{
  "version": 3,
  "sources": ["../../../src/plugins/dts/plugin.ts"],
  "sourceRoot": "file://",
  "sourcesContent": ["/**\n * @file Plugins - dts\n * @module mkbuild/plugins/dts\n */\n\nimport {\n  EXT_DTS_REGEX,\n  EXT_JS_REGEX,\n  EXT_TS_REGEX\n} from '@flex-development/ext-regex'\nimport pathe from '@flex-development/pathe'\nimport * as tscu from '@flex-development/tsconfig-utils'\nimport {\n  DOT,\n  cast,\n  constant,\n  defaults,\n  define,\n  get,\n  includes,\n  keys,\n  shake\n} from '@flex-development/tutils'\nimport type {\n  BuildOptions,\n  BuildResult,\n  OnResolveArgs,\n  OutputFile,\n  Plugin,\n  PluginBuild\n} from 'esbuild'\nimport util from 'node:util'\nimport type {\n  CompilerHost,\n  CompilerOptions,\n  WriteFileCallback\n} from 'typescript'\n\n/**\n * Plugin-specific build options.\n *\n * @internal\n */\ntype SpecificOptions = { metafile: true; write: false }\n\n/**\n * Returns a TypeScript declaration plugin.\n *\n * @return {Plugin} TypeScript declaration plugin\n */\nconst plugin = (): Plugin => {\n  /**\n   * Generates TypeScript declarations.\n   *\n   * @todo handle diagnostics\n   * @todo bundle declarations\n   *\n   * [1]: https://esbuild.github.io/plugins\n   * [2]: https://esbuild.github.io/api/#build-api\n   *\n   * @async\n   *\n   * @param {PluginBuild} build - [esbuild plugin api][1]\n   * @param {BuildOptions} build.initialOptions - [esbuild build api][2] options\n   * @param {PluginBuild['onEnd']} build.onEnd - Build end cb\n   * @param {PluginBuild['onResolve']} build.onResolve - Path resolution cb\n   * @return {Promise<void>} Nothing when complete\n   * @throws {Error}\n   */\n  const setup = async ({\n    initialOptions,\n    onEnd,\n    onResolve\n  }: PluginBuild): Promise<void> => {\n    const {\n      absWorkingDir = process.cwd(),\n      bundle,\n      color = true,\n      format,\n      metafile,\n      outExtension: { '.js': ext = '.js' } = {},\n      outbase = '',\n      outdir = DOT,\n      preserveSymlinks = false,\n      tsconfig = 'tsconfig.json',\n      write\n    } = initialOptions\n\n    // not bundling declarations yet\n    if (bundle) return void bundle\n\n    // esbuild write must be disabled to access result.outputFiles\n    if (write) throw new Error('write must be disabled')\n\n    // metafile required to get output metadata\n    if (!metafile) throw new Error('metafile required')\n\n    /**\n     * TypeScript module.\n     *\n     * @const {typeof import('typescript')} ts\n     */\n    const ts: typeof import('typescript') = (await import('typescript')).default\n\n    /**\n     * Absolute paths to source files.\n     *\n     * @const {string[]} sourcefiles\n     */\n    const sourcefiles: string[] = []\n\n    /**\n     * Source file filter.\n     *\n     * @const {RegExp} filter\n     */\n    const filter: RegExp = new RegExp(\n      (\n        `(?:(?:${EXT_JS_REGEX.source.slice(0, -8)})` +\n        `|(?:${EXT_TS_REGEX.source.slice(0, -8)}))$`\n      ).replace(/\\?<.+?>/g, '?:')\n    )\n\n    // get source files as entry points are resolved\n    onResolve({ filter }, (args: OnResolveArgs): undefined => {\n      return void sourcefiles.push(pathe.resolve(args.resolveDir, args.path))\n    })\n\n    return void onEnd((result: BuildResult<SpecificOptions>): void => {\n      /**\n       * TypeScript compiler options.\n       *\n       * @var {CompilerOptions | tscu.CompilerOptions} compilerOptions\n       */\n      let compilerOptions: CompilerOptions | tscu.CompilerOptions =\n        // dprint-ignore-next\n        tscu.loadCompilerOptions(pathe.resolve(absWorkingDir, tsconfig))\n\n      // normalize compiler options\n      compilerOptions = tscu.normalizeCompilerOptions(compilerOptions)\n\n      // remove forbidden compiler options\n      delete compilerOptions.declarationDir\n      delete compilerOptions.out\n      delete compilerOptions.outFile\n      delete compilerOptions.rootDirs\n      delete compilerOptions.sourceMap\n      delete compilerOptions.sourceRoot\n\n      // remove overridden compiler options\n      delete compilerOptions.declaration\n      delete compilerOptions.emitDeclarationOnly\n      delete compilerOptions.noEmit\n      delete compilerOptions.noErrorTruncation\n      delete compilerOptions.outDir\n      delete compilerOptions.rootDir\n\n      // remove unsupported compiler options\n      delete compilerOptions.declarationMap\n      delete compilerOptions.noEmitOnError\n\n      // merge compiler options with defaults\n      compilerOptions = defaults(\n        compilerOptions,\n        shake({\n          allowJs: true,\n          allowUmdGlobalAccess: format === 'iife',\n          allowUnreachableCode: false,\n          baseUrl: absWorkingDir,\n          checkJs: false,\n          declaration: true,\n          declarationMap: false,\n          emitDeclarationOnly: true,\n          esModuleInterop: true,\n          forceConsistentCasingInFileNames: true,\n          isolatedModules: true,\n          module: ts.ModuleKind.ESNext,\n          moduleResolution: tscu.normalizeModuleResolution(\n            tscu.ModuleResolutionKind.NodeJs\n          ),\n          noEmit: false,\n          noEmitOnError: false,\n          noErrorTruncation: true,\n          noImplicitAny: true,\n          noImplicitOverride: true,\n          noImplicitReturns: true,\n          outDir: pathe.resolve(absWorkingDir, outdir),\n          preserveConstEnums: true,\n          preserveSymlinks,\n          pretty: color,\n          resolveJsonModule: true,\n          rootDir: pathe.resolve(absWorkingDir, outbase),\n          skipLibCheck: true,\n          target: ts.ScriptTarget.ESNext\n        })\n      )\n\n      /**\n       * TypeScript compiler host.\n       *\n       * @const {CompilerHost} host\n       */\n      const host: CompilerHost = ts.createCompilerHost(compilerOptions)\n\n      /**\n       * Virtual file system for declaration files.\n       *\n       * @const {Record<string, string>} vfs\n       */\n      const vfs: Record<string, string> = {}\n\n      // first letter before \"js\" or \"ts\" in output file extension\n      const [, cm = ''] = /\\.(c|m)?[jt]sx?$/.exec(ext)!\n\n      /**\n       * Writes a declaration file to {@linkcode vfs}.\n       *\n       * @param {string} filename - Name of file to write\n       * @param {string} contents - Content to write\n       * @return {void} Nothing when complete\n       */\n      const writeFile: WriteFileCallback = (\n        filename: string,\n        contents: string\n      ): void => {\n        filename = filename.replace(EXT_DTS_REGEX, `.d.${cm}ts`)\n        return void (vfs[filename] = contents)\n      }\n\n      // override write file function\n      host.writeFile = writeFile\n\n      // emit declarations to virtual file system\n      ts.createProgram(\n        sourcefiles.filter(sourcefile => !EXT_DTS_REGEX.test(sourcefile)),\n        compilerOptions,\n        host\n      ).emit()\n\n      // remap output files to insert declaration file outputs\n      return void (result.outputFiles = result.outputFiles.flatMap(output => {\n        /**\n         * Absolute path to declaration file for {@linkcode output}.\n         *\n         * @const {string} dtspath\n         */\n        const path: string = EXT_JS_REGEX.test(output.path)\n          ? output.path.replace(EXT_JS_REGEX, '.d.$1ts')\n          : EXT_TS_REGEX.test(output.path) && !EXT_DTS_REGEX.test(output.path)\n          ? output.path.replace(EXT_TS_REGEX, '.d.$2ts')\n          : ''\n\n        // do nothing if missing declaration file\n        if (!includes(keys(vfs), path)) return [output]\n\n        /**\n         * Declaration file output.\n         *\n         * @const {OutputFile} dts\n         */\n        const dts: OutputFile = cast({\n          contents: new util.TextEncoder().encode(vfs[path]),\n          path\n        })\n\n        // redefine output text\n        define(dts, 'text', { get: constant(vfs[path]) })\n\n        /**\n         * Relative path to declaration output file.\n         *\n         * **Note**: Relative to {@linkcode absWorkingDir}.\n         *\n         * @const {string} dtsoutfile\n         */\n        const outfile: string = path\n          .replace(absWorkingDir, '')\n          .replace(/^\\//, '')\n\n        // update metafile\n        result.metafile.outputs[outfile] = {\n          ...get(\n            result.metafile.outputs,\n            output.path.replace(absWorkingDir, '').replace(/^\\//, '')\n          ),\n          bytes: Buffer.byteLength(dts.contents)\n        }\n\n        return [output, dts]\n      }))\n    })\n  }\n\n  return { name: 'dts', setup }\n}\n\nexport default plugin\n"],
  "mappings": ";;AAKA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,OAAO,WAAW;AAClB,YAAY,UAAU;AACtB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AASP,OAAO,UAAU;AAmBjB,MAAM,SAAS,8BAmPN,EAAE,MAAM,OAAO,OAhOR,8BAAO;AAAA,EACnB;AAAA,EACA;AAAA,EACA;AACF,MAAkC;AAChC,QAAM;AAAA,IACJ,gBAAgB,QAAQ,IAAI;AAAA,IAC5B;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA,cAAc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