@sanity/pkg-utils 3.1.0 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_chunks/{build-ttL1gCQE.cjs → build-zIodsGMj.cjs} +2 -2
- package/dist/_chunks/{build-ttL1gCQE.cjs.map → build-zIodsGMj.cjs.map} +1 -1
- package/dist/_chunks/{buildAction-2FuCIzEr.cjs → buildAction-F25hbZcX.cjs} +2 -2
- package/dist/_chunks/{buildAction-2FuCIzEr.cjs.map → buildAction-F25hbZcX.cjs.map} +1 -1
- package/dist/_chunks/{index-jC5AhNHb.cjs → index-qV4Iq6pv.cjs} +4 -5
- package/dist/_chunks/index-qV4Iq6pv.cjs.map +1 -0
- package/dist/_chunks/{watch-UrB-haEA.cjs → watch-4Yq69TUG.cjs} +2 -2
- package/dist/_chunks/{watch-UrB-haEA.cjs.map → watch-4Yq69TUG.cjs.map} +1 -1
- package/dist/_chunks/{watchAction-1U3Gh9UD.cjs → watchAction-HseKdhoO.cjs} +2 -2
- package/dist/_chunks/{watchAction-1U3Gh9UD.cjs.map → watchAction-HseKdhoO.cjs.map} +1 -1
- package/dist/cli.cjs +3 -3
- package/dist/index.cjs +3 -3
- package/dist/index.d.ts +1 -0
- package/dist/index.js +3 -4
- package/dist/index.js.map +1 -1
- package/package.json +44 -38
- package/src/node/core/config/types.ts +1 -0
- package/src/node/tasks/dts/createApiExtractorConfig.ts +3 -1
- package/src/node/tasks/dts/doExtract.ts +2 -0
- package/src/node/tasks/dts/extractTypes.ts +3 -0
- package/dist/_chunks/index-jC5AhNHb.cjs.map +0 -1
|
@@ -10,7 +10,7 @@ require('mkdirp');
|
|
|
10
10
|
require('prompts');
|
|
11
11
|
require('typescript');
|
|
12
12
|
var fs = require('fs');
|
|
13
|
-
var index = require('./index-
|
|
13
|
+
var index = require('./index-qV4Iq6pv.cjs');
|
|
14
14
|
var operators = require('rxjs/operators');
|
|
15
15
|
var globby = require('globby');
|
|
16
16
|
var chokidar = require('chokidar');
|
|
@@ -230,4 +230,4 @@ async function watch(options) {
|
|
|
230
230
|
});
|
|
231
231
|
}
|
|
232
232
|
exports.watch = watch;
|
|
233
|
-
//# sourceMappingURL=watch-
|
|
233
|
+
//# sourceMappingURL=watch-4Yq69TUG.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"watch-UrB-haEA.cjs","sources":["../../src/node/resolveWatchTasks.ts","../../src/node/globFiles.ts","../../src/node/watchFiles.ts","../../src/node/watchConfigFiles.ts","../../src/node/watch.ts"],"sourcesContent":["import fs from 'fs'\nimport path from 'path'\n\nimport {BuildContext, PkgExport, PkgFormat, PkgRuntime} from './core'\nimport {DtsWatchTask, RollupTaskEntry, RollupWatchTask, WatchTask} from './tasks'\n\n/** @internal */\nexport function resolveWatchTasks(ctx: BuildContext): WatchTask[] {\n const {config, cwd, pkg, target} = ctx\n const tasks: WatchTask[] = []\n\n const exports = Object.entries(ctx.exports || {}).map(\n ([_path, exp]) => ({_path, ...exp}) as PkgExport & {_path: string},\n )\n\n const dtsTask: DtsWatchTask = {\n type: 'watch:dts',\n entries: [],\n }\n\n const rollupTasks: Record<string, RollupWatchTask> = {}\n\n function addRollupTaskEntry(format: PkgFormat, runtime: PkgRuntime, entry: RollupTaskEntry) {\n const buildId = `${format}:${runtime}`\n\n if (rollupTasks[buildId]) {\n rollupTasks[buildId].entries.push(entry)\n } else {\n rollupTasks[buildId] = {\n type: 'watch:js',\n buildId,\n entries: [entry],\n runtime,\n format,\n target: target[runtime],\n }\n }\n }\n\n // Parse `dts` tasks\n for (const exp of exports) {\n const importId = path.join(pkg.name, exp._path)\n\n if (exp.types) {\n dtsTask.entries.push({\n importId,\n exportPath: exp._path,\n sourcePath: exp.source,\n targetPath: exp.types,\n })\n }\n }\n\n // Parse rollup:commonjs:* tasks\n for (const exp of exports) {\n const output = exp.require\n\n if (!output) continue\n\n addRollupTaskEntry('commonjs', ctx.runtime, {\n path: exp._path,\n source: exp.source,\n output,\n })\n }\n\n // Parse rollup:commonjs:browser tasks\n for (const exp of exports) {\n const output = exp.browser?.require\n\n if (!output) continue\n\n addRollupTaskEntry('commonjs', 'browser', {\n path: exp._path,\n source: exp.browser?.source || exp.source,\n output,\n })\n }\n\n // Parse rollup:esm:* tasks\n for (const exp of exports) {\n const output = exp.import\n\n if (!output) continue\n\n addRollupTaskEntry('esm', ctx.runtime, {\n path: exp._path,\n source: exp.source,\n output,\n })\n }\n\n // Parse rollup:esm:browser tasks\n for (const exp of exports) {\n const output = exp.browser?.import\n\n if (!output) continue\n\n addRollupTaskEntry('esm', 'browser', {\n path: exp._path,\n source: exp.browser?.source || exp.source,\n output,\n })\n }\n\n if (dtsTask.entries.length) {\n tasks.push(dtsTask)\n }\n\n tasks.push(...Object.values(rollupTasks))\n\n // Write legacy exports files\n if (config?.legacyExports) {\n for (const exp of exports) {\n if (exp._exported && exp._path !== '.') {\n const relativeTargetPath = (exp.browser?.import || exp.import || '').replace(\n /\\.[^/.]+$/,\n '',\n )\n\n if (relativeTargetPath) {\n fs.writeFileSync(\n path.resolve(cwd, `${exp._path}.js`),\n [`// AUTO-GENERATED – DO NOT EDIT`, `export * from '${relativeTargetPath}'`, ``].join(\n '\\n',\n ),\n )\n }\n }\n }\n }\n\n return tasks\n}\n","import globby from 'globby'\nimport path from 'path'\n\nexport function globFiles(patterns: string[]): Promise<string[]> {\n return globby(patterns.map((pattern) => pattern.split(path.sep).join(path.posix.sep)))\n}\n","import chokidar from 'chokidar'\nimport {Observable} from 'rxjs'\n\nexport interface FileEvent {\n type: 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir'\n file: string\n}\n\nexport function watchFiles(patterns: string[]): Observable<FileEvent> {\n return new Observable((observer) => {\n const watcher = chokidar.watch(patterns, {\n ignoreInitial: true,\n })\n\n function handleFileEvent(\n type: 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir',\n file: string,\n ) {\n observer.next({type, file})\n }\n\n watcher.on('all', handleFileEvent)\n\n return () => {\n watcher.off('all', handleFileEvent)\n watcher.close()\n }\n })\n}\n","import path from 'path'\nimport {Observable} from 'rxjs'\nimport {distinctUntilChanged, scan, startWith} from 'rxjs/operators'\n\nimport {globFiles} from './globFiles'\nimport {Logger} from './logger'\nimport {watchFiles} from './watchFiles'\n\nexport async function watchConfigFiles(options: {\n cwd: string\n logger: Logger\n}): Promise<Observable<string[]>> {\n const {cwd, logger} = options\n\n const initialFiles = await globFiles([\n path.resolve(cwd, 'package.json'),\n path.resolve(cwd, 'package.config.cjs'),\n path.resolve(cwd, 'package.config.js'),\n path.resolve(cwd, 'package.config.ts'),\n ])\n\n const fileEvent$ = watchFiles([\n path.resolve(cwd, 'package.json'),\n path.resolve(cwd, 'package.config.cjs'),\n path.resolve(cwd, 'package.config.js'),\n path.resolve(cwd, 'package.config.ts'),\n ])\n\n return fileEvent$.pipe(\n scan((files, fileEvent) => {\n if (fileEvent.type === 'add') {\n return files.concat(fileEvent.file)\n }\n\n if (fileEvent.type === 'unlink') {\n return files.filter((f) => f !== fileEvent.file)\n }\n\n if (fileEvent.type === 'change') {\n logger.log(\n '--------------------------------------------------------------------------------',\n )\n logger.info(path.relative(cwd, fileEvent.file), 'changed')\n logger.log('')\n\n return files.slice(0) // trigger update\n }\n\n return files\n }, initialFiles),\n startWith(initialFiles),\n distinctUntilChanged(),\n )\n}\n","import path from 'path'\nimport {switchMap} from 'rxjs'\n\nimport {getPkgExtMap, loadConfig, loadPkgWithReporting} from './core'\nimport {createLogger} from './logger'\nimport {resolveBuildContext} from './resolveBuildContext'\nimport {resolveWatchTasks} from './resolveWatchTasks'\nimport {TaskHandler, WatchTask, watchTaskHandlers} from './tasks'\nimport {watchConfigFiles} from './watchConfigFiles'\n\n/** @public */\nexport async function watch(options: {\n cwd: string\n strict?: boolean\n tsconfig?: string\n}): Promise<void> {\n const {cwd, strict = false, tsconfig: tsconfigOption} = options\n\n const logger = createLogger()\n\n const configFiles$ = await watchConfigFiles({cwd, logger})\n\n const ctx$ = configFiles$.pipe(\n switchMap(async (configFiles) => {\n const files = configFiles.map((f) => path.relative(cwd, f))\n\n const packageJsonPath = files.find((f) => f === 'package.json')\n\n if (!packageJsonPath) {\n throw new Error('missing package.json')\n }\n\n const pkg = await loadPkgWithReporting({cwd, logger})\n const config = await loadConfig({cwd})\n const extMap = getPkgExtMap({legacyExports: config?.legacyExports ?? false})\n const tsconfig = tsconfigOption || config?.tsconfig || 'tsconfig.json'\n\n return resolveBuildContext({config, cwd, extMap, logger, pkg, strict, tsconfig})\n }),\n )\n\n ctx$.subscribe(async (ctx) => {\n const watchTasks = resolveWatchTasks(ctx)\n\n for (const task of watchTasks) {\n const handler = watchTaskHandlers[task.type] as TaskHandler<WatchTask, unknown>\n const result$ = handler.exec(ctx, task)\n\n result$.subscribe({\n error: (err) => {\n ctx.logger.error(err)\n ctx.logger.log()\n\n process.exit(1)\n },\n next: (result) => {\n handler.complete(ctx, task, result)\n },\n complete: () => {\n ctx.logger.success(handler.name(ctx, task))\n ctx.logger.log()\n },\n })\n }\n })\n}\n"],"names":["resolveWatchTasks","ctx","config","cwd","pkg","target","tasks","exports","Object","entries","map","_ref","_path","exp","dtsTask","type","rollupTasks","addRollupTaskEntry","format","runtime","entry","buildId","concat","push","importId","path","join","name","types","exportPath","sourcePath","source","targetPath","output","require","_exp$browser","_exp$browser2","browser","import","_exp$browser3","_exp$browser4","length","values","legacyExports","_exported","_exp$browser5","relativeTargetPath","replace","fs","writeFileSync","resolve","globFiles","patterns","globby","pattern","split","default","sep","posix","watchFiles","Observable","observer","watcher","chokidar","watch","ignoreInitial","handleFileEvent","file","next","on","off","close","watchConfigFiles","options","logger","initialFiles","fileEvent$","pipe","scan","files","fileEvent","filter","f","log","info","relative","slice","startWith","distinctUntilChanged","strict","tsconfig","tsconfigOption","createLogger","configFiles$","ctx$","switchMap","configFiles","_config$legacyExports","packageJsonPath","find","Error","loadPkgWithReporting","loadConfig","extMap","getPkgExtMap","resolveBuildContext","subscribe","watchTasks","task","handler","watchTaskHandlers","result$","exec","error","err","process","exit","result","complete","success"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAOO,SAASA,kBAAkBC,GAAgC,EAAA;EAChE,MAAM;IAACC,MAAA;IAAQC,GAAK;IAAAC,GAAA;IAAKC;GAAU,GAAAJ,GAAA;EACnC,MAAMK,QAAqB,EAAC;EAE5B,MAAMC,UAAUC,MAAO,CAAAC,OAAA,CAAQR,IAAIM,OAAW,IAAA,CAAE,CAAA,CAAE,CAAAG,GAAA,CAChDC,IAAA;IAAA,IAAC,CAACC,KAAO,EAAAC,GAAG;WAAO;MAACD,KAAA;MAAO,GAAGC;KAAG;EAAA,CAAA,CACnC;EAEA,MAAMC,OAAwB,GAAA;IAC5BC,IAAM,EAAA,WAAA;IACNN,SAAS;EAAC,CACZ;EAEA,MAAMO,cAA+C,CAAA,CAAC;EAE7C,SAAAC,kBAAAA,CAAmBC,MAAmB,EAAAC,OAAA,EAAqBC,KAAwB,EAAA;IAC1F,MAAMC,OAAU,MAAAC,MAAA,CAAGJ,MAAM,OAAAI,MAAA,CAAIH,OAAO,CAAA;IAEhC,IAAAH,WAAA,CAAYK,OAAO,CAAG,EAAA;MACxBL,WAAA,CAAYK,OAAO,CAAA,CAAEZ,OAAQ,CAAAc,IAAA,CAAKH,KAAK,CAAA;IAAA,CAClC,MAAA;MACLJ,WAAA,CAAYK,OAAO,CAAI,GAAA;QACrBN,IAAM,EAAA,UAAA;QACNM,OAAA;QACAZ,OAAA,EAAS,CAACW,KAAK,CAAA;QACfD,OAAA;QACAD,MAAA;QACAb,MAAA,EAAQA,OAAOc,OAAO;MAAA,CACxB;IACF;EACF;EAGA,KAAA,MAAWN,OAAON,OAAS,EAAA;IACzB,MAAMiB,WAAWC,aAAAA,CAAAA,OAAK,CAAAC,IAAA,CAAKtB,GAAI,CAAAuB,IAAA,EAAMd,IAAID,KAAK,CAAA;IAE9C,IAAIC,IAAIe,KAAO,EAAA;MACbd,OAAA,CAAQL,Q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,EAAA;MACvB,MAAAE,OAAA,GAAUC,KAAAA,CAAAA,iBAAkB,CAAAF,IAAA,CAAK7F,IAAI,CAAA;MAC3C,MAAMgG,OAAU,GAAAF,OAAA,CAAQG,IAAK,CAAA/G,GAAA,EAAK2G,IAAI,CAAA;MAEtCG,OAAA,CAAQL,SAAU,CAAA;QAChBO,KAAA,EAAQC,GAAQ,IAAA;UACVjH,GAAA,CAAAyE,MAAA,CAAOuC,MAAMC,GAAG,CAAA;UACpBjH,GAAA,CAAIyE,OAAOS,GAAI,EAAA;UAEfgC,OAAA,CAAQC,KAAK,CAAC,CAAA;QAChB,CAAA;QACAhD,IAAA,EAAOiD,MAAW,IAAA;UACRR,OAAA,CAAAS,QAAA,CAASrH,GAAK,EAAA2G,IAAA,EAAMS,MAAM,CAAA;QACpC,CAAA;QACAC,UAAUA,CAAA,KAAM;UACdrH,GAAA,CAAIyE,OAAO6C,OAAQ,CAAAV,OAAA,CAAQlF,IAAK,CAAA1B,GAAA,EAAK2G,IAAI,CAAC,CAAA;UAC1C3G,GAAA,CAAIyE,OAAOS,GAAI,EAAA;QACjB;MAAA,CACD,CAAA;IACH;EAAA,CACD,CAAA;AACH;"}
|
|
1
|
+
{"version":3,"file":"watch-4Yq69TUG.cjs","sources":["../../src/node/resolveWatchTasks.ts","../../src/node/globFiles.ts","../../src/node/watchFiles.ts","../../src/node/watchConfigFiles.ts","../../src/node/watch.ts"],"sourcesContent":["import fs from 'fs'\nimport path from 'path'\n\nimport {BuildContext, PkgExport, PkgFormat, PkgRuntime} from './core'\nimport {DtsWatchTask, RollupTaskEntry, RollupWatchTask, WatchTask} from './tasks'\n\n/** @internal */\nexport function resolveWatchTasks(ctx: BuildContext): WatchTask[] {\n const {config, cwd, pkg, target} = ctx\n const tasks: WatchTask[] = []\n\n const exports = Object.entries(ctx.exports || {}).map(\n ([_path, exp]) => ({_path, ...exp}) as PkgExport & {_path: string},\n )\n\n const dtsTask: DtsWatchTask = {\n type: 'watch:dts',\n entries: [],\n }\n\n const rollupTasks: Record<string, RollupWatchTask> = {}\n\n function addRollupTaskEntry(format: PkgFormat, runtime: PkgRuntime, entry: RollupTaskEntry) {\n const buildId = `${format}:${runtime}`\n\n if (rollupTasks[buildId]) {\n rollupTasks[buildId].entries.push(entry)\n } else {\n rollupTasks[buildId] = {\n type: 'watch:js',\n buildId,\n entries: [entry],\n runtime,\n format,\n target: target[runtime],\n }\n }\n }\n\n // Parse `dts` tasks\n for (const exp of exports) {\n const importId = path.join(pkg.name, exp._path)\n\n if (exp.types) {\n dtsTask.entries.push({\n importId,\n exportPath: exp._path,\n sourcePath: exp.source,\n targetPath: exp.types,\n })\n }\n }\n\n // Parse rollup:commonjs:* tasks\n for (const exp of exports) {\n const output = exp.require\n\n if (!output) continue\n\n addRollupTaskEntry('commonjs', ctx.runtime, {\n path: exp._path,\n source: exp.source,\n output,\n })\n }\n\n // Parse rollup:commonjs:browser tasks\n for (const exp of exports) {\n const output = exp.browser?.require\n\n if (!output) continue\n\n addRollupTaskEntry('commonjs', 'browser', {\n path: exp._path,\n source: exp.browser?.source || exp.source,\n output,\n })\n }\n\n // Parse rollup:esm:* tasks\n for (const exp of exports) {\n const output = exp.import\n\n if (!output) continue\n\n addRollupTaskEntry('esm', ctx.runtime, {\n path: exp._path,\n source: exp.source,\n output,\n })\n }\n\n // Parse rollup:esm:browser tasks\n for (const exp of exports) {\n const output = exp.browser?.import\n\n if (!output) continue\n\n addRollupTaskEntry('esm', 'browser', {\n path: exp._path,\n source: exp.browser?.source || exp.source,\n output,\n })\n }\n\n if (dtsTask.entries.length) {\n tasks.push(dtsTask)\n }\n\n tasks.push(...Object.values(rollupTasks))\n\n // Write legacy exports files\n if (config?.legacyExports) {\n for (const exp of exports) {\n if (exp._exported && exp._path !== '.') {\n const relativeTargetPath = (exp.browser?.import || exp.import || '').replace(\n /\\.[^/.]+$/,\n '',\n )\n\n if (relativeTargetPath) {\n fs.writeFileSync(\n path.resolve(cwd, `${exp._path}.js`),\n [`// AUTO-GENERATED – DO NOT EDIT`, `export * from '${relativeTargetPath}'`, ``].join(\n '\\n',\n ),\n )\n }\n }\n }\n }\n\n return tasks\n}\n","import globby from 'globby'\nimport path from 'path'\n\nexport function globFiles(patterns: string[]): Promise<string[]> {\n return globby(patterns.map((pattern) => pattern.split(path.sep).join(path.posix.sep)))\n}\n","import chokidar from 'chokidar'\nimport {Observable} from 'rxjs'\n\nexport interface FileEvent {\n type: 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir'\n file: string\n}\n\nexport function watchFiles(patterns: string[]): Observable<FileEvent> {\n return new Observable((observer) => {\n const watcher = chokidar.watch(patterns, {\n ignoreInitial: true,\n })\n\n function handleFileEvent(\n type: 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir',\n file: string,\n ) {\n observer.next({type, file})\n }\n\n watcher.on('all', handleFileEvent)\n\n return () => {\n watcher.off('all', handleFileEvent)\n watcher.close()\n }\n })\n}\n","import path from 'path'\nimport {Observable} from 'rxjs'\nimport {distinctUntilChanged, scan, startWith} from 'rxjs/operators'\n\nimport {globFiles} from './globFiles'\nimport {Logger} from './logger'\nimport {watchFiles} from './watchFiles'\n\nexport async function watchConfigFiles(options: {\n cwd: string\n logger: Logger\n}): Promise<Observable<string[]>> {\n const {cwd, logger} = options\n\n const initialFiles = await globFiles([\n path.resolve(cwd, 'package.json'),\n path.resolve(cwd, 'package.config.cjs'),\n path.resolve(cwd, 'package.config.js'),\n path.resolve(cwd, 'package.config.ts'),\n ])\n\n const fileEvent$ = watchFiles([\n path.resolve(cwd, 'package.json'),\n path.resolve(cwd, 'package.config.cjs'),\n path.resolve(cwd, 'package.config.js'),\n path.resolve(cwd, 'package.config.ts'),\n ])\n\n return fileEvent$.pipe(\n scan((files, fileEvent) => {\n if (fileEvent.type === 'add') {\n return files.concat(fileEvent.file)\n }\n\n if (fileEvent.type === 'unlink') {\n return files.filter((f) => f !== fileEvent.file)\n }\n\n if (fileEvent.type === 'change') {\n logger.log(\n '--------------------------------------------------------------------------------',\n )\n logger.info(path.relative(cwd, fileEvent.file), 'changed')\n logger.log('')\n\n return files.slice(0) // trigger update\n }\n\n return files\n }, initialFiles),\n startWith(initialFiles),\n distinctUntilChanged(),\n )\n}\n","import path from 'path'\nimport {switchMap} from 'rxjs'\n\nimport {getPkgExtMap, loadConfig, loadPkgWithReporting} from './core'\nimport {createLogger} from './logger'\nimport {resolveBuildContext} from './resolveBuildContext'\nimport {resolveWatchTasks} from './resolveWatchTasks'\nimport {TaskHandler, WatchTask, watchTaskHandlers} from './tasks'\nimport {watchConfigFiles} from './watchConfigFiles'\n\n/** @public */\nexport async function watch(options: {\n cwd: string\n strict?: boolean\n tsconfig?: string\n}): Promise<void> {\n const {cwd, strict = false, tsconfig: tsconfigOption} = options\n\n const logger = createLogger()\n\n const configFiles$ = await watchConfigFiles({cwd, logger})\n\n const ctx$ = configFiles$.pipe(\n switchMap(async (configFiles) => {\n const files = configFiles.map((f) => path.relative(cwd, f))\n\n const packageJsonPath = files.find((f) => f === 'package.json')\n\n if (!packageJsonPath) {\n throw new Error('missing package.json')\n }\n\n const pkg = await loadPkgWithReporting({cwd, logger})\n const config = await loadConfig({cwd})\n const extMap = getPkgExtMap({legacyExports: config?.legacyExports ?? false})\n const tsconfig = tsconfigOption || config?.tsconfig || 'tsconfig.json'\n\n return resolveBuildContext({config, cwd, extMap, logger, pkg, strict, tsconfig})\n }),\n )\n\n ctx$.subscribe(async (ctx) => {\n const watchTasks = resolveWatchTasks(ctx)\n\n for (const task of watchTasks) {\n const handler = watchTaskHandlers[task.type] as TaskHandler<WatchTask, unknown>\n const result$ = handler.exec(ctx, task)\n\n result$.subscribe({\n error: (err) => {\n ctx.logger.error(err)\n ctx.logger.log()\n\n process.exit(1)\n },\n next: (result) => {\n handler.complete(ctx, task, result)\n },\n complete: () => {\n ctx.logger.success(handler.name(ctx, task))\n ctx.logger.log()\n },\n })\n }\n })\n}\n"],"names":["resolveWatchTasks","ctx","config","cwd","pkg","target","tasks","exports","Object","entries","map","_ref","_path","exp","dtsTask","type","rollupTasks","addRollupTaskEntry","format","runtime","entry","buildId","concat","push","importId","path","join","name","types","exportPath","sourcePath","source","targetPath","output","require","_exp$browser","_exp$browser2","browser","import","_exp$browser3","_exp$browser4","length","values","legacyExports","_exported","_exp$browser5","relativeTargetPath","replace","fs","writeFileSync","resolve","globFiles","patterns","globby","pattern","split","default","sep","posix","watchFiles","Observable","observer","watcher","chokidar","watch","ignoreInitial","handleFileEvent","file","next","on","off","close","watchConfigFiles","options","logger","initialFiles","fileEvent$","pipe","scan","files","fileEvent","filter","f","log","info","relative","slice","startWith","distinctUntilChanged","strict","tsconfig","tsconfigOption","createLogger","configFiles$","ctx$","switchMap","configFiles","_config$legacyExports","packageJsonPath","find","Error","loadPkgWithReporting","loadConfig","extMap","getPkgExtMap","resolveBuildContext","subscribe","watchTasks","task","handler","watchTaskHandlers","result$","exec","error","err","process","exit","result","complete","success"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAOO,SAASA,kBAAkBC,GAAgC,EAAA;EAChE,MAAM;IAACC,MAAA;IAAQC,GAAK;IAAAC,GAAA;IAAKC;GAAU,GAAAJ,GAAA;EACnC,MAAMK,QAAqB,EAAC;EAE5B,MAAMC,UAAUC,MAAO,CAAAC,OAAA,CAAQR,IAAIM,OAAW,IAAA,CAAE,CAAA,CAAE,CAAAG,GAAA,CAChDC,IAAA;IAAA,IAAC,CAACC,KAAO,EAAAC,GAAG;WAAO;MAACD,KAAA;MAAO,GAAGC;KAAG;EAAA,CAAA,CACnC;EAEA,MAAMC,OAAwB,GAAA;IAC5BC,IAAM,EAAA,WAAA;IACNN,SAAS;EAAC,CACZ;EAEA,MAAMO,cAA+C,CAAA,CAAC;EAE7C,SAAAC,kBAAAA,CAAmBC,MAAmB,EAAAC,OAAA,EAAqBC,KAAwB,EAAA;IAC1F,MAAMC,OAAU,MAAAC,MAAA,CAAGJ,MAAM,OAAAI,MAAA,CAAIH,OAAO,CAAA;IAEhC,IAAA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H;EAAA,CACD,CAAA;AACH;"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var watch = require('./watch-
|
|
3
|
+
var watch = require('./watch-4Yq69TUG.cjs');
|
|
4
4
|
var handleError = require('./handleError-esTdSrHu.cjs');
|
|
5
5
|
async function watchAction(options) {
|
|
6
6
|
try {
|
|
@@ -14,4 +14,4 @@ async function watchAction(options) {
|
|
|
14
14
|
}
|
|
15
15
|
}
|
|
16
16
|
exports.watchAction = watchAction;
|
|
17
|
-
//# sourceMappingURL=watchAction-
|
|
17
|
+
//# sourceMappingURL=watchAction-HseKdhoO.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"watchAction-
|
|
1
|
+
{"version":3,"file":"watchAction-HseKdhoO.cjs","sources":["../../src/cli/watchAction.ts"],"sourcesContent":["import {watch} from '../node/watch'\nimport {handleError} from './handleError'\n\nexport async function watchAction(options: {strict?: boolean; tsconfig?: string}): Promise<void> {\n try {\n await watch({\n cwd: process.cwd(),\n strict: options.strict,\n tsconfig: options.tsconfig,\n })\n } catch (err) {\n handleError(err)\n }\n}\n"],"names":["watchAction","options","watch","cwd","process","strict","tsconfig","err","handleError"],"mappings":";;;;AAGA,eAAsBA,YAAYC,OAA+D,EAAA;EAC3F,IAAA;IACF,MAAMC,WAAM,CAAA;MACVC,GAAA,EAAKC,QAAQD,GAAI,CAAA,CAAA;MACjBE,QAAQJ,OAAQ,CAAAI,MAAA;MAChBC,UAAUL,OAAQ,CAAAK;IAAA,CACnB,CAAA;WACMC,GAAK,EAAA;IACZC,WAAA,CAAAA,WAAA,CAAYD,GAAG,CAAA;EACjB;AACF;"}
|
package/dist/cli.cjs
CHANGED
|
@@ -7,7 +7,7 @@ function _interopDefaultCompat(e) {
|
|
|
7
7
|
};
|
|
8
8
|
}
|
|
9
9
|
var cac__default = /*#__PURE__*/_interopDefaultCompat(cac);
|
|
10
|
-
var version = "3.
|
|
10
|
+
var version = "3.2.0";
|
|
11
11
|
const cli = cac__default.default();
|
|
12
12
|
cli.command("", "Check").alias("check").option("--strict", "Strict mode").option("--tsconfig [tsconfig]", "[string] tsconfig.json").action(async options => {
|
|
13
13
|
const {
|
|
@@ -21,7 +21,7 @@ cli.command("build", "Build package").option("--emitDeclarationOnly", "Emit d.ts
|
|
|
21
21
|
const {
|
|
22
22
|
buildAction
|
|
23
23
|
} = await Promise.resolve().then(function () {
|
|
24
|
-
return require('./_chunks/buildAction-
|
|
24
|
+
return require('./_chunks/buildAction-F25hbZcX.cjs');
|
|
25
25
|
});
|
|
26
26
|
return buildAction(options);
|
|
27
27
|
});
|
|
@@ -39,7 +39,7 @@ cli.command("watch", "Watch package").option("--strict", "Strict mode").option("
|
|
|
39
39
|
const {
|
|
40
40
|
watchAction
|
|
41
41
|
} = await Promise.resolve().then(function () {
|
|
42
|
-
return require('./_chunks/watchAction-
|
|
42
|
+
return require('./_chunks/watchAction-HseKdhoO.cjs');
|
|
43
43
|
});
|
|
44
44
|
return watchAction(options);
|
|
45
45
|
});
|
package/dist/index.cjs
CHANGED
|
@@ -3,13 +3,13 @@
|
|
|
3
3
|
Object.defineProperty(exports, '__esModule', {
|
|
4
4
|
value: true
|
|
5
5
|
});
|
|
6
|
-
var build = require('./_chunks/build-
|
|
6
|
+
var build = require('./_chunks/build-zIodsGMj.cjs');
|
|
7
7
|
var check = require('./_chunks/check-X8xKPDnl.cjs');
|
|
8
8
|
var consoleSpy = require('./_chunks/consoleSpy--ReK-_gE.cjs');
|
|
9
9
|
var logger = require('./_chunks/logger-_q9DVAFj.cjs');
|
|
10
10
|
var init = require('./_chunks/init-gkPbG69g.cjs');
|
|
11
|
-
var index = require('./_chunks/index-
|
|
12
|
-
var watch = require('./_chunks/watch-
|
|
11
|
+
var index = require('./_chunks/index-qV4Iq6pv.cjs');
|
|
12
|
+
var watch = require('./_chunks/watch-4Yq69TUG.cjs');
|
|
13
13
|
function defineConfig(configOptions) {
|
|
14
14
|
return configOptions;
|
|
15
15
|
}
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
var _templateObject,_templateObject2,_templateObject3,_templateObject4,_templateObject5,_templateObject6,_templateObject7,_templateObject8,_templateObject9,_templateObject10,_templateObject11,_templateObject12,_templateObject13,_templateObject14,_templateObject15,_templateObject16,_templateObject17;function _taggedTemplateLiteral(strings,raw){if(!raw){raw=strings.slice(0);}return Object.freeze(Object.defineProperties(strings,{raw:{value:Object.freeze(raw)}}));}import{register}from'esbuild-register/dist/node';import path$1,{relative,resolve,dirname}from'path';import pkgUp from'pkg-up';import findConfig from'find-config';import fs$1,{statSync}from'fs';import fs,{writeFile,readFile,readdir,lstat}from'fs/promises';import{z,ZodError}from'zod';import chalk from'chalk';import{mkdirp}from'mkdirp';import prompts from'prompts';import ts from'typescript';import browserslist from'browserslist';import{Observable,from,switchMap}from'rxjs';import rimraf from'rimraf';import{ExtractorConfig,Extractor}from'@microsoft/api-extractor';import prettier from'prettier';import{TSDocConfigFile}from'@microsoft/tsdoc-config';import{parse as parse$1}from'jsonc-parser';import require$$1 from'assert';import require$$4 from'os';import{rollup,watch as watch$1}from'rollup';import alias from'@rollup/plugin-alias';import{getBabelOutputPlugin}from'@rollup/plugin-babel';import commonjs from'@rollup/plugin-commonjs';import json from'@rollup/plugin-json';import{nodeResolve}from'@rollup/plugin-node-resolve';import replace from'@rollup/plugin-replace';import terser from'@rollup/plugin-terser';import esbuild from'rollup-plugin-esbuild';import esbuild$1 from'esbuild';import treeify from'treeify';import prettyBytes from'pretty-bytes';import getLatestVersion from'get-latest-version';import gitUrlParse from'git-url-parse';import{outdent}from'outdent';import parseGitConfig from'parse-git-config';import{scan,startWith,distinctUntilChanged}from'rxjs/operators';import globby from'globby';import chokidar from'chokidar';function defineConfig(configOptions){return configOptions;}function fileExists(filePath){try{statSync(filePath);return true;}catch(_){return false;}}const CONFIG_FILE_NAMES=["package.config.ts","package.config.js","package.config.cjs","package.config.mjs"];function findConfigFile(cwd){const pkgJsonPath=findConfig("package.json",{cwd});if(!pkgJsonPath)return void 0;const pkgPath=path$1.dirname(pkgJsonPath);for(const fileName of CONFIG_FILE_NAMES){const configPath=path$1.resolve(pkgPath,fileName);const exists=fileExists(configPath);if(exists){return configPath;}}return void 0;}async function loadConfig(options){const{cwd}=options;const pkgPath=await pkgUp({cwd});if(!pkgPath)return void 0;const root=path$1.dirname(pkgPath);const configFile=await findConfigFile(root);if(!configFile){return void 0;}if(!configFile.startsWith(cwd)){return void 0;}const esbuildOptions={extensions:[".js",".mjs",".ts"]};const{unregister}=globalThis.__DEV__?{unregister:()=>void 0}:register(esbuildOptions);const mod=require(configFile);unregister();return(mod===null||mod===void 0?void 0:mod.default)||mod||void 0;}function resolveConfigProperty(prop,initialValue){if(!prop)return initialValue;if(typeof prop==="function"){return prop(initialValue);}return prop;}const DEFAULT_BROWSERSLIST_QUERY=["> 0.2% and supports es6-module and supports es6-module-dynamic-import","not dead","not IE 11","maintained node versions"];function isRecord(value){return Boolean(value)&&!Array.isArray(value)&&typeof value==="object";}const pkgSchema=z.object({type:z.optional(z.enum(["commonjs","module"])),name:z.string(),version:z.string(),license:z.string(),bin:z.optional(z.record(z.string())),dependencies:z.optional(z.record(z.string())),devDependencies:z.optional(z.record(z.string())),peerDependencies:z.optional(z.record(z.string())),source:z.optional(z.string()),main:z.optional(z.string()),browser:z.optional(z.record(z.string())),module:z.optional(z.string()),types:z.optional(z.string()),exports:z.optional(z.record(z.union([z.custom(val=>/^\.\/.*\.json$/.test(val)),z.object({types:z.optional(z.string()),source:z.string(),browser:z.optional(z.object({source:z.string(),import:z.optional(z.string()),require:z.optional(z.string())})),node:z.optional(z.object({source:z.optional(z.string()),module:z.optional(z.string()),import:z.optional(z.string()),require:z.optional(z.string())})),module:z.optional(z.string()),import:z.optional(z.string()),require:z.optional(z.string()),default:z.string()})]))),browserslist:z.optional(z.array(z.string()))});function validatePkg(input){return pkgSchema.parse(input);}async function loadPkg(options){const{cwd}=options;const pkgPath=await pkgUp({cwd});if(!pkgPath)throw new Error("no package.json found");const buf=await fs.readFile(pkgPath);const raw=JSON.parse(buf.toString());validatePkg(raw);return raw;}function assertFirst(a,arr){const aIdx=arr.indexOf(a);if(aIdx===-1){return true;}return aIdx===0;}function assertLast(a,arr){const aIdx=arr.indexOf(a);if(aIdx===-1){return true;}return aIdx===arr.length-1;}function assertOrder(a,b,arr){const aIdx=arr.indexOf(a);const bIdx=arr.indexOf(b);if(aIdx===-1||bIdx===-1){return true;}return aIdx<bIdx;}async function loadPkgWithReporting(options){const{cwd,logger}=options;try{const pkg=await loadPkg({cwd});let shouldError=false;if(pkg.exports){const _exports=Object.entries(pkg.exports);for(const[expPath,exp]of _exports){if(typeof exp==="string"){continue;}const keys=Object.keys(exp);if(!assertFirst("types",keys)){shouldError=true;logger.error("exports[\"".concat(expPath,"\"]: the `types` property should be the first property"));}if(exp.node){const nodeKeys=Object.keys(exp.node);if(!assertOrder("module","import",nodeKeys)){shouldError=true;logger.error("exports[\"".concat(expPath,"\"]: the `node.module` property should come before the `node.import` property"));}if(!assertOrder("import","require",nodeKeys)){logger.warn("exports[\"".concat(expPath,"\"]: the `node.import` property should come before the `node.require` property"));}if(!assertOrder("module","require",nodeKeys)){logger.warn("exports[\"".concat(expPath,"\"]: the `node.module` property should come before `node.require` property"));}if(exp.import&&exp.node.import&&!assertOrder("node","import",keys)){shouldError=true;logger.error("exports[\"".concat(expPath,"\"]: the `node` property should come before the `import` property"));}if(exp.module&&exp.node.module&&!assertOrder("node","module",keys)){shouldError=true;logger.error("exports[\"".concat(expPath,"\"]: the `node` property should come before the `module` property"));}if(exp.node.import&&!exp.node.require&&exp.node.module&&exp.import&&exp.node.module!==exp.import){shouldError=true;logger.error("exports[\"".concat(expPath,"\"]: the `node.module` property should match `import`"));}if(exp.require&&exp.node.require&&exp.require===exp.node.require){shouldError=true;logger.error("exports[\"".concat(expPath,"\"]: the `node.require` property isn't necessary as it's identical to `require`"));}else if(exp.require&&exp.node.require&&!assertOrder("node","require",keys)){shouldError=true;logger.error("exports[\"".concat(expPath,"\"]: the `node` property should come before the `require` property"));}}else{if(!assertOrder("import","require",keys)){logger.warn("exports[\"".concat(expPath,"\"]: the `import` property should come before the `require` property"));}if(!assertOrder("module","import",keys)){logger.warn("exports[\"".concat(expPath,"\"]: the `module` property should come before `import` property"));}}if(!assertLast("default",keys)){shouldError=true;logger.error("exports[\"".concat(expPath,"\"]: the `default` property should be the last property"));}}}if(shouldError){process.exit(1);}return pkg;}catch(err){if(err instanceof ZodError){for(const issue of err.issues){if(issue.code==="invalid_type"){logger.error(["`".concat(formatPath(issue.path),"` "),"in `./package.json` must be of type ".concat(chalk.magenta(issue.expected)," "),"(received ".concat(chalk.magenta(issue.received),")")].join(""));continue;}logger.error(issue);}}else{logger.error(err);}process.exit(1);}}function formatPath(segments){return segments.map((s,idx)=>{if(idx===0)return s;if(typeof s==="number"){return"[".concat(s,"]");}if(s.startsWith(".")){return"[\"".concat(s,"\"]");}return".".concat(s);}).join("");}function validateExports(_exports,options){const{extMap,pkg}=options;const ext=extMap[pkg.type||"commonjs"];const errors=[];for(const exp of _exports){if(exp.require&&!exp.require.endsWith(ext.commonjs)){errors.push("package.json with `type: \"".concat(pkg.type,"\"` - `exports[\"").concat(exp._path,"\"].require` must end with \"").concat(ext.commonjs,"\""));}if(exp.import&&!exp.import.endsWith(ext.esm)){errors.push("package.json with `type: \"".concat(pkg.type,"\"` - `exports[\"").concat(exp._path,"\"].import` must end with \"").concat(ext.esm,"\""));}}return errors;}function parseExports(options){const{extMap,pkg,strict}=options;const rootExport={_exported:true,_path:".",types:pkg.types,source:pkg.source||"",browser:pkg.browser&&{source:pkg.source||"",require:pkg.main&&pkg.browser[pkg.main],import:pkg.module&&pkg.browser[pkg.module]},require:pkg.main,import:pkg.module,default:pkg.module||pkg.main||""};const extraExports=[];const errors=[];if(pkg.exports){if(strict&&!pkg.exports["./package.json"]){errors.push('package.json: `exports["./package.json"] must be declared.');}for(const[exportPath,exportEntry]of Object.entries(pkg.exports)){if(exportPath.endsWith(".json")){if(exportPath==="./package.json"){if(exportEntry!=="./package.json"){errors.push('package.json: `exports["./package.json"] must be "./package.json".');}}}else if(isRecord(exportEntry)){if(exportPath==="."){if(exportEntry.require&&rootExport.require&&exportEntry.require!==rootExport.require){errors.push('package.json: mismatch between "main" and "exports.require". These must be equal.');}if(exportEntry.import&&rootExport.import&&exportEntry.import!==rootExport.import){errors.push('package.json: mismatch between "module" and "exports.import" These must be equal.');}if(exportEntry.types&&rootExport.types&&exportEntry.types!==rootExport.types){errors.push('package.json: mismatch between "types" and "exports.types". These must be equal.');}if(exportEntry.source&&rootExport.source&&exportEntry.source!==rootExport.source){errors.push('package.json: mismatch between "source" and "exports.source". These must be equal.');}Object.assign(rootExport,exportEntry);}else{const extraExport={_exported:true,_path:exportPath,...exportEntry};extraExports.push(extraExport);}}else{errors.push("package.json: exports must be an object");}}}const _exports=[rootExport,...extraExports];errors.push(...validateExports(_exports,{extMap,pkg}));if(errors.length){throw new Error("\n- "+errors.join("\n- "));}return _exports;}const DEFAULT_PKG_EXT_MAP={// pkg.type: "commonjs"
|
|
2
2
|
commonjs:{commonjs:".js",esm:".mjs"},// pkg.type: "module"
|
|
3
|
-
module:{commonjs:".cjs",esm:".js"}};function getPkgExtMap(options){const{legacyExports}=options;const ret={...DEFAULT_PKG_EXT_MAP};if(legacyExports){ret["commonjs"]={commonjs:".js",esm:".esm.js"};}return ret;}const promptsTypes={string:"text"};async function createFromTemplate(options){const{cwd,logger,packagePath,template:templateOrResolver}=options;const template=typeof templateOrResolver==="function"?await templateOrResolver({cwd,logger,packagePath}):templateOrResolver;logger.log("create new package at",relative(cwd,packagePath));const templateOptions={};for(const templateOption of template.options){const templateValidate=templateOption.validate;const res=await prompts({type:promptsTypes[templateOption.type],name:templateOption.name,message:templateOption.description,validate:templateValidate?prev=>templateValidate(prev):void 0,initial:typeof templateOption.initial==="function"?templateOption.initial(templateOptions):templateOption.initial},{onCancel:()=>process.exit(0)});templateOptions[templateOption.name]=templateOption.parse?templateOption.parse(res[templateOption.name]):res[templateOption.name];}const features={};for(const templateFeature of template.features){const res=templateFeature.optional?await prompts({type:"confirm",name:"confirm",message:"use ".concat(templateFeature.name,"?"),initial:templateFeature.initial},{onCancel:()=>process.exit(0)}):void 0;features[templateFeature.name]=(res===null||res===void 0?void 0:res.confirm)||!templateFeature.optional;}const files=await template.getFiles(templateOptions,features);files.sort((a,b)=>{return a.name.localeCompare(b.name);});for(const file of files){const filePath=resolve(packagePath,file.name);await mkdirp(dirname(filePath));await writeFile(filePath,file.contents.trim()+"\n");logger.success("wrote ".concat(relative(cwd,filePath)));}}function defineTemplateOption(option){return option;}async function loadTSConfig(options){const{cwd,tsconfigPath}=options;const configPath=ts.findConfigFile(cwd,ts.sys.fileExists,tsconfigPath);if(!configPath){throw new Error("could not find a valid '".concat(tsconfigPath,"'"));}const configFile=ts.readConfigFile(configPath,ts.sys.readFile);return ts.parseJsonConfigFileContent(configFile.config,ts.sys,cwd);}function createLogger(){return{/* eslint-disable no-console */log:function(){console.log(...arguments);},info:function(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}console.log(chalk.blue("[info]"),...args);},warn:function(){for(var _len2=arguments.length,args=new Array(_len2),_key2=0;_key2<_len2;_key2++){args[_key2]=arguments[_key2];}console.log(chalk.yellow("[warning]"),...args);},error:function(){for(var _len3=arguments.length,args=new Array(_len3),_key3=0;_key3<_len3;_key3++){args[_key3]=arguments[_key3];}console.log(chalk.red("[error]"),...args);},success:function(){for(var _len4=arguments.length,args=new Array(_len4),_key4=0;_key4<_len4;_key4++){args[_key4]=arguments[_key4];}console.log(chalk.green("[success]"),...args);}/* eslint-enable no-console */};}function pathContains(containerPath,itemPath){return!path$1.relative(containerPath,itemPath).startsWith("..");}function findCommonDirPath(filePaths){let ret=void 0;for(const filePath of filePaths){let dirPath=path$1.dirname(filePath);if(!ret){ret=dirPath;continue;}while(dirPath!==ret){dirPath=path$1.dirname(dirPath);if(dirPath===ret){break;}if(pathContains(dirPath,ret)){ret=dirPath;break;}if(dirPath===".")return void 0;}}return ret;}function sortAsNumber(a,b){const aVersion=Number(a);const bVersion=Number(b);return aVersion-bVersion;}function resolveBrowserslistVersions(query){const result=browserslist(query);const entries=result.map(key=>{const[name,version]=key.split(" ");return{name,version:version.split("-")[0].split(".")[0]};});const andChr=entries.filter(b=>b.name==="and_chr");const andFf=entries.filter(b=>b.name==="and_ff");const chrome=entries.filter(b=>b.name==="chrome");const edge=entries.filter(b=>b.name==="edge");const ff=entries.filter(b=>b.name==="firefox");const iosSaf=entries.filter(b=>b.name==="ios_saf");const saf=entries.filter(b=>b.name==="safari");const opera=entries.filter(b=>b.name==="opera");const node=entries.filter(b=>b.name==="node");const versions={chrome:andChr.concat(chrome).map(b=>b.version),ff:andFf.concat(ff).map(b=>b.version),edge:edge.map(b=>b.version),iosSaf:iosSaf.map(b=>b.version),saf:saf.map(b=>b.version),opera:opera.map(b=>b.version),node:node.map(b=>b.version)};versions.chrome.sort(sortAsNumber);versions.ff.sort(sortAsNumber);versions.edge.sort(sortAsNumber);versions.iosSaf.sort(sortAsNumber);versions.saf.sort(sortAsNumber);versions.opera.sort(sortAsNumber);versions.node.sort(sortAsNumber);return versions;}function resolveBrowserTarget(versions){const target=[];if(versions.chrome.length){target.push("chrome".concat(versions.chrome[0]));}if(versions.ff.length){target.push("firefox".concat(versions.ff[0]));}if(versions.edge.length){target.push("edge".concat(versions.edge[0]));}if(versions.iosSaf.length){target.push("ios".concat(versions.iosSaf[0]));}if(versions.saf.length){target.push("safari".concat(versions.saf[0]));}if(versions.opera.length){target.push("opera".concat(versions.opera[0]));}if(target.length===0){return void 0;}return target;}function resolveNodeTarget(versions){const target=[];if(versions.node.length){target.push("node".concat(versions.node[0]));}if(target.length===0){return void 0;}return target;}async function resolveBuildContext(options){var _config$runtime;const{config,cwd,emitDeclarationOnly=false,extMap,logger,pkg,strict,tsconfig:tsconfigPath}=options;const tsconfig=await loadTSConfig({cwd,tsconfigPath});const targetVersions=resolveBrowserslistVersions(pkg.browserslist||DEFAULT_BROWSERSLIST_QUERY);const nodeTarget=resolveNodeTarget(targetVersions);const webTarget=resolveBrowserTarget(targetVersions);if(!nodeTarget){throw new Error("no matching `node` target");}if(!webTarget){throw new Error("no matching `web` target");}const target={"*":webTarget.concat(nodeTarget),browser:webTarget,node:nodeTarget};const parsedExports=parseExports({extMap,pkg,strict}).reduce((acc,x)=>{const{_path:exportPath,...exportEntry}=x;return{...acc,[exportPath]:exportEntry};},{});const exports=resolveConfigProperty(config===null||config===void 0?void 0:config.exports,parsedExports);const parsedExternal=[...(pkg.dependencies?Object.keys(pkg.dependencies):[]),...(pkg.peerDependencies?Object.keys(pkg.peerDependencies):[])];const external=config&&Array.isArray(config.external)?[...parsedExternal,...config.external]:resolveConfigProperty(config===null||config===void 0?void 0:config.external,parsedExternal);const outputPaths=Object.values(exports).flatMap(exportEntry=>{var _exportEntry$browser,_exportEntry$browser2,_exportEntry$node,_exportEntry$node2;return[exportEntry.import,exportEntry.require,(_exportEntry$browser=exportEntry.browser)===null||_exportEntry$browser===void 0?void 0:_exportEntry$browser.import,(_exportEntry$browser2=exportEntry.browser)===null||_exportEntry$browser2===void 0?void 0:_exportEntry$browser2.require,((_exportEntry$node=exportEntry.node)===null||_exportEntry$node===void 0?void 0:_exportEntry$node.source)&&exportEntry.node.import,((_exportEntry$node2=exportEntry.node)===null||_exportEntry$node2===void 0?void 0:_exportEntry$node2.source)&&exportEntry.node.require].filter(Boolean);}).map(p=>path$1.resolve(cwd,p));const commonDistPath=findCommonDirPath(outputPaths);if(commonDistPath===cwd){throw new Error("all output files must share a common parent directory which is not the root package directory");}if(commonDistPath&&!pathContains(cwd,commonDistPath)){throw new Error("all output files must be located within the package");}const configDistPath=config!==null&&config!==void 0&&config.dist?path$1.resolve(cwd,config.dist):void 0;if(configDistPath&&commonDistPath&&configDistPath!==commonDistPath&&!pathContains(configDistPath,commonDistPath)){logger.log("did you mean to configure `dist: './".concat(path$1.relative(cwd,commonDistPath),"'`?"));throw new Error("all output files must be located with the configured `dist` path");}const distPath=configDistPath||commonDistPath;if(!distPath){throw new Error("could not detect `dist` path");}const ctx={config,cwd,distPath,emitDeclarationOnly,exports,external,extMap,files:[],logger,pkg,runtime:(_config$runtime=config===null||config===void 0?void 0:config.runtime)!==null&&_config$runtime!==void 0?_config$runtime:"*",strict,target,ts:{config:tsconfig,configPath:tsconfigPath}};return ctx;}function resolveBuildTasks(ctx){const{config,cwd,pkg,target}=ctx;const bundles=(config===null||config===void 0?void 0:config.bundles)||[];const tasks=[];const exports=Object.entries(ctx.exports||{}).map(_ref3=>{let[_path,exp]=_ref3;return{_path,...exp};});const dtsTask={type:"build:dts",entries:[]};const rollupTasks={};function addRollupTaskEntry(format,runtime,entry){const buildId="".concat(format,":").concat(runtime);if(rollupTasks[buildId]){rollupTasks[buildId].entries.push(entry);}else{rollupTasks[buildId]={type:"build:js",buildId,entries:[entry],runtime,format,target:target[runtime]};}}for(const exp of exports){const importId=path$1.join(pkg.name,exp._path);if(exp.types){dtsTask.entries.push({importId,exportPath:exp._path,sourcePath:exp.source,targetPath:exp.types});}}if(dtsTask.entries.length){tasks.push(dtsTask);}if(!ctx.emitDeclarationOnly){for(const exp of exports){const output=exp.require;if(!output)continue;addRollupTaskEntry("commonjs",ctx.runtime,{path:exp._path,source:exp.source,output});}for(const exp of exports){const output=exp.import;if(!output)continue;addRollupTaskEntry("esm",ctx.runtime,{path:exp._path,source:exp.source,output});}for(const exp of exports){var _exp$browser,_exp$browser2;const output=(_exp$browser=exp.browser)===null||_exp$browser===void 0?void 0:_exp$browser.require;if(!output)continue;addRollupTaskEntry("commonjs","browser",{path:exp._path,source:((_exp$browser2=exp.browser)===null||_exp$browser2===void 0?void 0:_exp$browser2.source)||exp.source,output});}for(const exp of exports){var _exp$browser3,_exp$browser4;const output=(_exp$browser3=exp.browser)===null||_exp$browser3===void 0?void 0:_exp$browser3.import;if(!output)continue;addRollupTaskEntry("esm","browser",{path:exp._path,source:((_exp$browser4=exp.browser)===null||_exp$browser4===void 0?void 0:_exp$browser4.source)||exp.source,output});}for(const bundle of bundles){const idx=bundles.indexOf(bundle);if(bundle.require){addRollupTaskEntry("commonjs",bundle.runtime||ctx.runtime,{path:"__$$bundle_cjs_".concat(idx,"$$__"),source:bundle.source,output:bundle.require});}if(bundle.import){addRollupTaskEntry("esm",bundle.runtime||ctx.runtime,{path:"__$$bundle_esm_".concat(idx,"$$__"),source:bundle.source,output:bundle.import});}}tasks.push(...Object.values(rollupTasks));if(config!==null&&config!==void 0&&config.legacyExports){for(const exp of exports){if(exp._exported&&exp._path!=="."){var _exp$browser5;const relativeTargetPath=(((_exp$browser5=exp.browser)===null||_exp$browser5===void 0?void 0:_exp$browser5.import)||exp.import||"").replace(/\.[^/.]+$/,"");if(relativeTargetPath){fs$1.writeFileSync(path$1.resolve(cwd,"".concat(exp._path,".js")),["// AUTO-GENERATED \u2013 DO NOT EDIT","export * from '".concat(relativeTargetPath,"'"),""].join("\n"));}}}}}const nodeReexportCjsEntries=[];for(const exp of exports){if(exp.node&&!exp.node.source&&exp.node.import&&(exp.node.require||exp.require)&&(exp.node.import.endsWith(".cjs.js")||exp.node.import.endsWith(".cjs.mjs"))){const importId=path$1.join(pkg.name,exp._path);nodeReexportCjsEntries.push({importId,import:exp.node.import,require:exp.node.require||exp.require});}}if(nodeReexportCjsEntries.length){tasks.push({type:"node:reexport-cjs",entries:nodeReexportCjsEntries});}return tasks;}function createSpinner(msg){const startTime=Date.now();console.log(msg);return{complete:()=>{console.log("".concat(chalk.green("[success]")," ").concat(chalk.gray("".concat(Date.now()-startTime,"ms"))));},error:()=>{console.log("".concat(chalk.red("[error]")," ").concat(chalk.gray("".concat(Date.now()-startTime,"ms"))));}};}function printExtractMessages(ctx,messages){const{cwd,logger}=ctx;const warnings=messages.filter(msg=>msg.logLevel==="warning");if(warnings.length){logger.log();}for(const msg of warnings){const sourceFilePath=msg.sourceFilePath&&path$1.relative(cwd,msg.sourceFilePath);if(msg.messageId==="TS6307"){continue;}logger.log(["".concat(chalk.cyan(sourceFilePath||"?")),":".concat(chalk.yellow(msg.sourceFileLine),":").concat(chalk.yellow(msg.sourceFileColumn))," - ".concat(chalk.yellow("warning")," ").concat(chalk.gray(msg.messageId),"\n"),msg.text,"\n"].join(""));}const errors=messages.filter(msg=>msg.logLevel==="error");if(!warnings.length&&errors.length){logger.log("");}for(const msg of errors){const sourceFilePath=msg.sourceFilePath&&path$1.relative(cwd,msg.sourceFilePath);logger.log(["".concat(chalk.cyan(sourceFilePath||"?")),":".concat(chalk.yellow(msg.sourceFileLine),":").concat(chalk.yellow(msg.sourceFileColumn))," - ".concat(chalk.red("error")," ").concat(chalk.gray(msg.messageId),"\n"),msg.text,"\n"].join(""));}if(errors.length){process.exit(1);}}function printDiagnostic(options){const{cwd,logger,diagnostic}=options;if(diagnostic.file&&diagnostic.start){const{line,character}=ts.getLineAndCharacterOfPosition(diagnostic.file,diagnostic.start);const message=ts.flattenDiagnosticMessageText(diagnostic.messageText,"\n");const file=path$1.relative(cwd,diagnostic.file.fileName);const output=["".concat(chalk.yellow(file),":").concat(chalk.blue(line+1),":").concat(chalk.blue(character+1)," - "),"".concat(chalk.gray("TS".concat(diagnostic.code,":"))," ").concat(message)].join("");if(diagnostic.category===ts.DiagnosticCategory.Error){logger.error(output);}if(diagnostic.category===ts.DiagnosticCategory.Warning){logger.warn(output);}if(diagnostic.category===ts.DiagnosticCategory.Message){logger.log(output);}if(diagnostic.category===ts.DiagnosticCategory.Suggestion){logger.log(output);}}else{logger.log(ts.flattenDiagnosticMessageText(diagnostic.messageText,"\n"));}}async function buildTypes(options){const{cwd,logger,outDir,tsconfig,strict=false}=options;const compilerOptions={...tsconfig.options,declaration:true,declarationDir:outDir,emitDeclarationOnly:true,noEmit:false,outDir};const program=ts.createProgram(tsconfig.fileNames,compilerOptions);const emitResult=program.emit();const allDiagnostics=ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);for(const diagnostic of allDiagnostics){printDiagnostic({cwd,logger,diagnostic});}if(emitResult.emitSkipped){const errors=allDiagnostics.filter(diag=>diag.category===ts.DiagnosticCategory.Error);if(errors.length){if(strict){throw new Error("failed to compile TypeScript definitions");}}}}class DtsError extends Error{constructor(message,messages){super(message);this.messages=messages;}}function createApiExtractorConfig(options){const{distPath,exportPath,filePath,messages,projectFolder,mainEntryPointFilePath,tsconfigPath}=options;return{apiReport:{enabled:false,reportFileName:"<unscopedPackageName>.api.md"},// bundledPackages: [],
|
|
4
|
-
compiler:{tsconfigFilePath:tsconfigPath},docModel:{enabled:false,apiJsonFilePath:path$1.resolve(distPath,"".concat(exportPath,".api.json"))},dtsRollup:{enabled:true,untrimmedFilePath:path$1.resolve(distPath,filePath)// betaTrimmedFilePath: path.resolve(distPath, filePath.replace('.d.ts', '-beta.d.ts')),
|
|
3
|
+
module:{commonjs:".cjs",esm:".js"}};function getPkgExtMap(options){const{legacyExports}=options;const ret={...DEFAULT_PKG_EXT_MAP};if(legacyExports){ret["commonjs"]={commonjs:".js",esm:".esm.js"};}return ret;}const promptsTypes={string:"text"};async function createFromTemplate(options){const{cwd,logger,packagePath,template:templateOrResolver}=options;const template=typeof templateOrResolver==="function"?await templateOrResolver({cwd,logger,packagePath}):templateOrResolver;logger.log("create new package at",relative(cwd,packagePath));const templateOptions={};for(const templateOption of template.options){const templateValidate=templateOption.validate;const res=await prompts({type:promptsTypes[templateOption.type],name:templateOption.name,message:templateOption.description,validate:templateValidate?prev=>templateValidate(prev):void 0,initial:typeof templateOption.initial==="function"?templateOption.initial(templateOptions):templateOption.initial},{onCancel:()=>process.exit(0)});templateOptions[templateOption.name]=templateOption.parse?templateOption.parse(res[templateOption.name]):res[templateOption.name];}const features={};for(const templateFeature of template.features){const res=templateFeature.optional?await prompts({type:"confirm",name:"confirm",message:"use ".concat(templateFeature.name,"?"),initial:templateFeature.initial},{onCancel:()=>process.exit(0)}):void 0;features[templateFeature.name]=(res===null||res===void 0?void 0:res.confirm)||!templateFeature.optional;}const files=await template.getFiles(templateOptions,features);files.sort((a,b)=>{return a.name.localeCompare(b.name);});for(const file of files){const filePath=resolve(packagePath,file.name);await mkdirp(dirname(filePath));await writeFile(filePath,file.contents.trim()+"\n");logger.success("wrote ".concat(relative(cwd,filePath)));}}function defineTemplateOption(option){return option;}async function loadTSConfig(options){const{cwd,tsconfigPath}=options;const configPath=ts.findConfigFile(cwd,ts.sys.fileExists,tsconfigPath);if(!configPath){throw new Error("could not find a valid '".concat(tsconfigPath,"'"));}const configFile=ts.readConfigFile(configPath,ts.sys.readFile);return ts.parseJsonConfigFileContent(configFile.config,ts.sys,cwd);}function createLogger(){return{/* eslint-disable no-console */log:function(){console.log(...arguments);},info:function(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}console.log(chalk.blue("[info]"),...args);},warn:function(){for(var _len2=arguments.length,args=new Array(_len2),_key2=0;_key2<_len2;_key2++){args[_key2]=arguments[_key2];}console.log(chalk.yellow("[warning]"),...args);},error:function(){for(var _len3=arguments.length,args=new Array(_len3),_key3=0;_key3<_len3;_key3++){args[_key3]=arguments[_key3];}console.log(chalk.red("[error]"),...args);},success:function(){for(var _len4=arguments.length,args=new Array(_len4),_key4=0;_key4<_len4;_key4++){args[_key4]=arguments[_key4];}console.log(chalk.green("[success]"),...args);}/* eslint-enable no-console */};}function pathContains(containerPath,itemPath){return!path$1.relative(containerPath,itemPath).startsWith("..");}function findCommonDirPath(filePaths){let ret=void 0;for(const filePath of filePaths){let dirPath=path$1.dirname(filePath);if(!ret){ret=dirPath;continue;}while(dirPath!==ret){dirPath=path$1.dirname(dirPath);if(dirPath===ret){break;}if(pathContains(dirPath,ret)){ret=dirPath;break;}if(dirPath===".")return void 0;}}return ret;}function sortAsNumber(a,b){const aVersion=Number(a);const bVersion=Number(b);return aVersion-bVersion;}function resolveBrowserslistVersions(query){const result=browserslist(query);const entries=result.map(key=>{const[name,version]=key.split(" ");return{name,version:version.split("-")[0].split(".")[0]};});const andChr=entries.filter(b=>b.name==="and_chr");const andFf=entries.filter(b=>b.name==="and_ff");const chrome=entries.filter(b=>b.name==="chrome");const edge=entries.filter(b=>b.name==="edge");const ff=entries.filter(b=>b.name==="firefox");const iosSaf=entries.filter(b=>b.name==="ios_saf");const saf=entries.filter(b=>b.name==="safari");const opera=entries.filter(b=>b.name==="opera");const node=entries.filter(b=>b.name==="node");const versions={chrome:andChr.concat(chrome).map(b=>b.version),ff:andFf.concat(ff).map(b=>b.version),edge:edge.map(b=>b.version),iosSaf:iosSaf.map(b=>b.version),saf:saf.map(b=>b.version),opera:opera.map(b=>b.version),node:node.map(b=>b.version)};versions.chrome.sort(sortAsNumber);versions.ff.sort(sortAsNumber);versions.edge.sort(sortAsNumber);versions.iosSaf.sort(sortAsNumber);versions.saf.sort(sortAsNumber);versions.opera.sort(sortAsNumber);versions.node.sort(sortAsNumber);return versions;}function resolveBrowserTarget(versions){const target=[];if(versions.chrome.length){target.push("chrome".concat(versions.chrome[0]));}if(versions.ff.length){target.push("firefox".concat(versions.ff[0]));}if(versions.edge.length){target.push("edge".concat(versions.edge[0]));}if(versions.iosSaf.length){target.push("ios".concat(versions.iosSaf[0]));}if(versions.saf.length){target.push("safari".concat(versions.saf[0]));}if(versions.opera.length){target.push("opera".concat(versions.opera[0]));}if(target.length===0){return void 0;}return target;}function resolveNodeTarget(versions){const target=[];if(versions.node.length){target.push("node".concat(versions.node[0]));}if(target.length===0){return void 0;}return target;}async function resolveBuildContext(options){var _config$runtime;const{config,cwd,emitDeclarationOnly=false,extMap,logger,pkg,strict,tsconfig:tsconfigPath}=options;const tsconfig=await loadTSConfig({cwd,tsconfigPath});const targetVersions=resolveBrowserslistVersions(pkg.browserslist||DEFAULT_BROWSERSLIST_QUERY);const nodeTarget=resolveNodeTarget(targetVersions);const webTarget=resolveBrowserTarget(targetVersions);if(!nodeTarget){throw new Error("no matching `node` target");}if(!webTarget){throw new Error("no matching `web` target");}const target={"*":webTarget.concat(nodeTarget),browser:webTarget,node:nodeTarget};const parsedExports=parseExports({extMap,pkg,strict}).reduce((acc,x)=>{const{_path:exportPath,...exportEntry}=x;return{...acc,[exportPath]:exportEntry};},{});const exports=resolveConfigProperty(config===null||config===void 0?void 0:config.exports,parsedExports);const parsedExternal=[...(pkg.dependencies?Object.keys(pkg.dependencies):[]),...(pkg.peerDependencies?Object.keys(pkg.peerDependencies):[])];const external=config&&Array.isArray(config.external)?[...parsedExternal,...config.external]:resolveConfigProperty(config===null||config===void 0?void 0:config.external,parsedExternal);const outputPaths=Object.values(exports).flatMap(exportEntry=>{var _exportEntry$browser,_exportEntry$browser2,_exportEntry$node,_exportEntry$node2;return[exportEntry.import,exportEntry.require,(_exportEntry$browser=exportEntry.browser)===null||_exportEntry$browser===void 0?void 0:_exportEntry$browser.import,(_exportEntry$browser2=exportEntry.browser)===null||_exportEntry$browser2===void 0?void 0:_exportEntry$browser2.require,((_exportEntry$node=exportEntry.node)===null||_exportEntry$node===void 0?void 0:_exportEntry$node.source)&&exportEntry.node.import,((_exportEntry$node2=exportEntry.node)===null||_exportEntry$node2===void 0?void 0:_exportEntry$node2.source)&&exportEntry.node.require].filter(Boolean);}).map(p=>path$1.resolve(cwd,p));const commonDistPath=findCommonDirPath(outputPaths);if(commonDistPath===cwd){throw new Error("all output files must share a common parent directory which is not the root package directory");}if(commonDistPath&&!pathContains(cwd,commonDistPath)){throw new Error("all output files must be located within the package");}const configDistPath=config!==null&&config!==void 0&&config.dist?path$1.resolve(cwd,config.dist):void 0;if(configDistPath&&commonDistPath&&configDistPath!==commonDistPath&&!pathContains(configDistPath,commonDistPath)){logger.log("did you mean to configure `dist: './".concat(path$1.relative(cwd,commonDistPath),"'`?"));throw new Error("all output files must be located with the configured `dist` path");}const distPath=configDistPath||commonDistPath;if(!distPath){throw new Error("could not detect `dist` path");}const ctx={config,cwd,distPath,emitDeclarationOnly,exports,external,extMap,files:[],logger,pkg,runtime:(_config$runtime=config===null||config===void 0?void 0:config.runtime)!==null&&_config$runtime!==void 0?_config$runtime:"*",strict,target,ts:{config:tsconfig,configPath:tsconfigPath}};return ctx;}function resolveBuildTasks(ctx){const{config,cwd,pkg,target}=ctx;const bundles=(config===null||config===void 0?void 0:config.bundles)||[];const tasks=[];const exports=Object.entries(ctx.exports||{}).map(_ref3=>{let[_path,exp]=_ref3;return{_path,...exp};});const dtsTask={type:"build:dts",entries:[]};const rollupTasks={};function addRollupTaskEntry(format,runtime,entry){const buildId="".concat(format,":").concat(runtime);if(rollupTasks[buildId]){rollupTasks[buildId].entries.push(entry);}else{rollupTasks[buildId]={type:"build:js",buildId,entries:[entry],runtime,format,target:target[runtime]};}}for(const exp of exports){const importId=path$1.join(pkg.name,exp._path);if(exp.types){dtsTask.entries.push({importId,exportPath:exp._path,sourcePath:exp.source,targetPath:exp.types});}}if(dtsTask.entries.length){tasks.push(dtsTask);}if(!ctx.emitDeclarationOnly){for(const exp of exports){const output=exp.require;if(!output)continue;addRollupTaskEntry("commonjs",ctx.runtime,{path:exp._path,source:exp.source,output});}for(const exp of exports){const output=exp.import;if(!output)continue;addRollupTaskEntry("esm",ctx.runtime,{path:exp._path,source:exp.source,output});}for(const exp of exports){var _exp$browser,_exp$browser2;const output=(_exp$browser=exp.browser)===null||_exp$browser===void 0?void 0:_exp$browser.require;if(!output)continue;addRollupTaskEntry("commonjs","browser",{path:exp._path,source:((_exp$browser2=exp.browser)===null||_exp$browser2===void 0?void 0:_exp$browser2.source)||exp.source,output});}for(const exp of exports){var _exp$browser3,_exp$browser4;const output=(_exp$browser3=exp.browser)===null||_exp$browser3===void 0?void 0:_exp$browser3.import;if(!output)continue;addRollupTaskEntry("esm","browser",{path:exp._path,source:((_exp$browser4=exp.browser)===null||_exp$browser4===void 0?void 0:_exp$browser4.source)||exp.source,output});}for(const bundle of bundles){const idx=bundles.indexOf(bundle);if(bundle.require){addRollupTaskEntry("commonjs",bundle.runtime||ctx.runtime,{path:"__$$bundle_cjs_".concat(idx,"$$__"),source:bundle.source,output:bundle.require});}if(bundle.import){addRollupTaskEntry("esm",bundle.runtime||ctx.runtime,{path:"__$$bundle_esm_".concat(idx,"$$__"),source:bundle.source,output:bundle.import});}}tasks.push(...Object.values(rollupTasks));if(config!==null&&config!==void 0&&config.legacyExports){for(const exp of exports){if(exp._exported&&exp._path!=="."){var _exp$browser5;const relativeTargetPath=(((_exp$browser5=exp.browser)===null||_exp$browser5===void 0?void 0:_exp$browser5.import)||exp.import||"").replace(/\.[^/.]+$/,"");if(relativeTargetPath){fs$1.writeFileSync(path$1.resolve(cwd,"".concat(exp._path,".js")),["// AUTO-GENERATED \u2013 DO NOT EDIT","export * from '".concat(relativeTargetPath,"'"),""].join("\n"));}}}}}const nodeReexportCjsEntries=[];for(const exp of exports){if(exp.node&&!exp.node.source&&exp.node.import&&(exp.node.require||exp.require)&&(exp.node.import.endsWith(".cjs.js")||exp.node.import.endsWith(".cjs.mjs"))){const importId=path$1.join(pkg.name,exp._path);nodeReexportCjsEntries.push({importId,import:exp.node.import,require:exp.node.require||exp.require});}}if(nodeReexportCjsEntries.length){tasks.push({type:"node:reexport-cjs",entries:nodeReexportCjsEntries});}return tasks;}function createSpinner(msg){const startTime=Date.now();console.log(msg);return{complete:()=>{console.log("".concat(chalk.green("[success]")," ").concat(chalk.gray("".concat(Date.now()-startTime,"ms"))));},error:()=>{console.log("".concat(chalk.red("[error]")," ").concat(chalk.gray("".concat(Date.now()-startTime,"ms"))));}};}function printExtractMessages(ctx,messages){const{cwd,logger}=ctx;const warnings=messages.filter(msg=>msg.logLevel==="warning");if(warnings.length){logger.log();}for(const msg of warnings){const sourceFilePath=msg.sourceFilePath&&path$1.relative(cwd,msg.sourceFilePath);if(msg.messageId==="TS6307"){continue;}logger.log(["".concat(chalk.cyan(sourceFilePath||"?")),":".concat(chalk.yellow(msg.sourceFileLine),":").concat(chalk.yellow(msg.sourceFileColumn))," - ".concat(chalk.yellow("warning")," ").concat(chalk.gray(msg.messageId),"\n"),msg.text,"\n"].join(""));}const errors=messages.filter(msg=>msg.logLevel==="error");if(!warnings.length&&errors.length){logger.log("");}for(const msg of errors){const sourceFilePath=msg.sourceFilePath&&path$1.relative(cwd,msg.sourceFilePath);logger.log(["".concat(chalk.cyan(sourceFilePath||"?")),":".concat(chalk.yellow(msg.sourceFileLine),":").concat(chalk.yellow(msg.sourceFileColumn))," - ".concat(chalk.red("error")," ").concat(chalk.gray(msg.messageId),"\n"),msg.text,"\n"].join(""));}if(errors.length){process.exit(1);}}function printDiagnostic(options){const{cwd,logger,diagnostic}=options;if(diagnostic.file&&diagnostic.start){const{line,character}=ts.getLineAndCharacterOfPosition(diagnostic.file,diagnostic.start);const message=ts.flattenDiagnosticMessageText(diagnostic.messageText,"\n");const file=path$1.relative(cwd,diagnostic.file.fileName);const output=["".concat(chalk.yellow(file),":").concat(chalk.blue(line+1),":").concat(chalk.blue(character+1)," - "),"".concat(chalk.gray("TS".concat(diagnostic.code,":"))," ").concat(message)].join("");if(diagnostic.category===ts.DiagnosticCategory.Error){logger.error(output);}if(diagnostic.category===ts.DiagnosticCategory.Warning){logger.warn(output);}if(diagnostic.category===ts.DiagnosticCategory.Message){logger.log(output);}if(diagnostic.category===ts.DiagnosticCategory.Suggestion){logger.log(output);}}else{logger.log(ts.flattenDiagnosticMessageText(diagnostic.messageText,"\n"));}}async function buildTypes(options){const{cwd,logger,outDir,tsconfig,strict=false}=options;const compilerOptions={...tsconfig.options,declaration:true,declarationDir:outDir,emitDeclarationOnly:true,noEmit:false,outDir};const program=ts.createProgram(tsconfig.fileNames,compilerOptions);const emitResult=program.emit();const allDiagnostics=ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);for(const diagnostic of allDiagnostics){printDiagnostic({cwd,logger,diagnostic});}if(emitResult.emitSkipped){const errors=allDiagnostics.filter(diag=>diag.category===ts.DiagnosticCategory.Error);if(errors.length){if(strict){throw new Error("failed to compile TypeScript definitions");}}}}class DtsError extends Error{constructor(message,messages){super(message);this.messages=messages;}}function createApiExtractorConfig(options){const{bundledPackages,distPath,exportPath,filePath,messages,projectFolder,mainEntryPointFilePath,tsconfigPath}=options;return{apiReport:{enabled:false,reportFileName:"<unscopedPackageName>.api.md"},bundledPackages,compiler:{tsconfigFilePath:tsconfigPath},docModel:{enabled:false,apiJsonFilePath:path$1.resolve(distPath,"".concat(exportPath,".api.json"))},dtsRollup:{enabled:true,untrimmedFilePath:path$1.resolve(distPath,filePath)// betaTrimmedFilePath: path.resolve(distPath, filePath.replace('.d.ts', '-beta.d.ts')),
|
|
5
4
|
// publicTrimmedFilePath: path.resolve(distPath, filePath.replace('.d.ts', '-public.d.ts')),
|
|
6
5
|
},tsdocMetadata:{enabled:false},messages,mainEntryPointFilePath,projectFolder};}async function createTSDocConfig(opts){const{customTags}=opts;if(customTags.length===0){return void 0;}const tsDocBaseBuf=await readFile(require.resolve("@microsoft/api-extractor/extends/tsdoc-base.json"));const tsDocBaseConfig=parse$1(tsDocBaseBuf.toString());const tagDefinitions=(tsDocBaseConfig.tagDefinitions||[]).concat(customTags.map(t=>({tagName:"@".concat(t.name),syntaxKind:t.syntaxKind,allowMultiple:t.allowMultiple})));const supportForTags={...tsDocBaseConfig.supportForTags};for(const customTag of customTags){supportForTags["@".concat(customTag.name)]=true;}return TSDocConfigFile.loadFromObject({...tsDocBaseConfig,noStandardTags:false,tagDefinitions,supportForTags});}var commonjsGlobal=typeof globalThis!=='undefined'?globalThis:typeof window!=='undefined'?window:typeof global!=='undefined'?global:typeof self!=='undefined'?self:{};function getAugmentedNamespace(n){if(n.__esModule)return n;var f=n.default;if(typeof f=="function"){var a=function a(){if(this instanceof a){return Reflect.construct(f,arguments,this.constructor);}return f.apply(this,arguments);};a.prototype=f.prototype;}else a={};Object.defineProperty(a,'__esModule',{value:true});Object.keys(n).forEach(function(k){var d=Object.getOwnPropertyDescriptor(n,k);Object.defineProperty(a,k,d.get?d:{enumerable:true,get:function(){return n[k];}});});return a;}var main$1={};/******************************************************************************
|
|
7
6
|
Copyright (c) Microsoft Corporation.
|
|
@@ -2152,10 +2151,10 @@ function parse(source,options){var babelOptions=(0,_babel_options_1.default)(opt
|
|
|
2152
2151
|
// parser: require("recast/parsers/typescript")
|
|
2153
2152
|
// });
|
|
2154
2153
|
//
|
|
2155
|
-
function parse(source,options){var babelOptions=(0,_babel_options_1.default)(options);babelOptions.plugins.push("typescript");return babel_1.parser.parse(source,babelOptions);}typescript.parse=parse;async function extractModuleBlocksFromTypes(_ref90){let{tsOutDir,extractResult}=_ref90;const program=extractResult.compilerState.program;const moduleBlocks=[];const allProgramFiles=[...program.getSourceFiles()];const sourceFiles=allProgramFiles.filter(sourceFile=>sourceFile.fileName.includes(tsOutDir));for(const sourceFile of sourceFiles){if(sourceFile.text.includes("declare module")){moduleBlocks.push(...extractModuleBlocks(sourceFile.text));}}return moduleBlocks;}function extractModuleBlocks(fileContent){const ast=main$1.parse(fileContent,{parser:typescript});return ast.program.body.filter(node=>node.type==="TSModuleDeclaration").map(node=>main$1.print(node).code);}const LOG_LEVELS={error:"error",info:"info",off:"none",warn:"warning"};function getExtractMessagesConfig(options){const{rules}=options;function ruleToLogLevel(key,defaultLevel){const r=rules===null||rules===void 0?void 0:rules[key];return r?LOG_LEVELS[r]:defaultLevel||"warning";}return{compilerMessageReporting:{default:{logLevel:"warning"}},extractorMessageReporting:{default:{logLevel:"warning",addToApiReportFile:false},"ae-forgotten-export":{logLevel:ruleToLogLevel("ae-forgotten-export","error"),addToApiReportFile:false},"ae-incompatible-release-tags":{logLevel:ruleToLogLevel("ae-incompatible-release-tags","error"),addToApiReportFile:false},"ae-internal-missing-underscore":{logLevel:ruleToLogLevel("ae-internal-missing-underscore"),addToApiReportFile:false},"ae-missing-release-tag":{logLevel:ruleToLogLevel("ae-missing-release-tag","error"),addToApiReportFile:false},"ae-wrong-input-file-type":{logLevel:"none",addToApiReportFile:false}},tsdocMessageReporting:{default:{logLevel:"warning",addToApiReportFile:false},"tsdoc-link-tag-unescaped-text":{logLevel:ruleToLogLevel("tsdoc-link-tag-unescaped-text","warning"),addToApiReportFile:false},"tsdoc-undefined-tag":{logLevel:ruleToLogLevel("tsdoc-undefined-tag","error"),addToApiReportFile:false},"tsdoc-unsupported-tag":{logLevel:ruleToLogLevel("tsdoc-unsupported-tag","none"),addToApiReportFile:false}}};}async function extractTypes(options){const{customTags,distPath,exportPath,files,filePath,projectPath,rules,sourceTypesPath,tmpPath,tsconfigPath}=options;const tsdocConfigFile=await createTSDocConfig({customTags:customTags||[]});const extractorConfig=ExtractorConfig.prepare({configObject:createApiExtractorConfig({distPath,exportPath,filePath,messages:getExtractMessagesConfig({rules}),projectFolder:projectPath,mainEntryPointFilePath:sourceTypesPath,tsconfigPath}),configObjectFullPath:void 0,tsdocConfigFile,packageJsonFullPath:path$1.resolve(projectPath,"package.json")});const messages=[];const extractorResult=Extractor.invoke(extractorConfig,{// Equivalent to the "--local" command-line parameter
|
|
2154
|
+
function parse(source,options){var babelOptions=(0,_babel_options_1.default)(options);babelOptions.plugins.push("typescript");return babel_1.parser.parse(source,babelOptions);}typescript.parse=parse;async function extractModuleBlocksFromTypes(_ref90){let{tsOutDir,extractResult}=_ref90;const program=extractResult.compilerState.program;const moduleBlocks=[];const allProgramFiles=[...program.getSourceFiles()];const sourceFiles=allProgramFiles.filter(sourceFile=>sourceFile.fileName.includes(tsOutDir));for(const sourceFile of sourceFiles){if(sourceFile.text.includes("declare module")){moduleBlocks.push(...extractModuleBlocks(sourceFile.text));}}return moduleBlocks;}function extractModuleBlocks(fileContent){const ast=main$1.parse(fileContent,{parser:typescript});return ast.program.body.filter(node=>node.type==="TSModuleDeclaration").map(node=>main$1.print(node).code);}const LOG_LEVELS={error:"error",info:"info",off:"none",warn:"warning"};function getExtractMessagesConfig(options){const{rules}=options;function ruleToLogLevel(key,defaultLevel){const r=rules===null||rules===void 0?void 0:rules[key];return r?LOG_LEVELS[r]:defaultLevel||"warning";}return{compilerMessageReporting:{default:{logLevel:"warning"}},extractorMessageReporting:{default:{logLevel:"warning",addToApiReportFile:false},"ae-forgotten-export":{logLevel:ruleToLogLevel("ae-forgotten-export","error"),addToApiReportFile:false},"ae-incompatible-release-tags":{logLevel:ruleToLogLevel("ae-incompatible-release-tags","error"),addToApiReportFile:false},"ae-internal-missing-underscore":{logLevel:ruleToLogLevel("ae-internal-missing-underscore"),addToApiReportFile:false},"ae-missing-release-tag":{logLevel:ruleToLogLevel("ae-missing-release-tag","error"),addToApiReportFile:false},"ae-wrong-input-file-type":{logLevel:"none",addToApiReportFile:false}},tsdocMessageReporting:{default:{logLevel:"warning",addToApiReportFile:false},"tsdoc-link-tag-unescaped-text":{logLevel:ruleToLogLevel("tsdoc-link-tag-unescaped-text","warning"),addToApiReportFile:false},"tsdoc-undefined-tag":{logLevel:ruleToLogLevel("tsdoc-undefined-tag","error"),addToApiReportFile:false},"tsdoc-unsupported-tag":{logLevel:ruleToLogLevel("tsdoc-unsupported-tag","none"),addToApiReportFile:false}}};}async function extractTypes(options){const{bundledPackages,customTags,distPath,exportPath,files,filePath,projectPath,rules,sourceTypesPath,tmpPath,tsconfigPath}=options;const tsdocConfigFile=await createTSDocConfig({customTags:customTags||[]});const extractorConfig=ExtractorConfig.prepare({configObject:createApiExtractorConfig({bundledPackages,distPath,exportPath,filePath,messages:getExtractMessagesConfig({rules}),projectFolder:projectPath,mainEntryPointFilePath:sourceTypesPath,tsconfigPath}),configObjectFullPath:void 0,tsdocConfigFile,packageJsonFullPath:path$1.resolve(projectPath,"package.json")});const messages=[];const extractorResult=Extractor.invoke(extractorConfig,{// Equivalent to the "--local" command-line parameter
|
|
2156
2155
|
localBuild:true,// Equivalent to the "--verbose" command-line parameter
|
|
2157
2156
|
showVerboseMessages:true,// handle messages
|
|
2158
|
-
messageCallback(message){messages.push(message);message.handled=true;}});const typesPath=path$1.resolve(distPath,filePath);const typesBuf=await fs.readFile(typesPath);const prettierConfig=await prettier.resolveConfig(typesPath);await mkdirp(path$1.dirname(typesPath));const moduleBlocks=await extractModuleBlocksFromTypes({extractResult:extractorResult,tsOutDir:tmpPath});const code=[typesBuf.toString(),...moduleBlocks].join("\n\n");await fs.writeFile(typesPath,await prettier.format(code,{...prettierConfig,filepath:typesPath}));files.push({type:"types",path:typesPath});return{extractorResult,messages};}async function doExtract(ctx,task){const{config,cwd,files,logger,strict,ts}=ctx;if(!ts.config||!ts.configPath){return{type:"dts",messages:[],results:[]};}const{outDir,rootDir=cwd}=ts.config.options;if(!outDir){throw new Error("tsconfig.json is missing `compilerOptions.outDir`");}const tmpPath=path$1.resolve(outDir,"__tmp__");await buildTypes({cwd,logger,outDir:tmpPath,strict,tsconfig:ts.config});const messages=[];const results=[];for(const entry of task.entries){var _config$extract,_config$extract2;const exportPath=entry.exportPath==="."?"./index":entry.exportPath;const sourceTypesPath=path$1.resolve(tmpPath,path$1.relative(rootDir,path$1.resolve(cwd,entry.sourcePath)).replace(/\.ts$/,".d.ts"));const targetPath=path$1.resolve(cwd,entry.targetPath);const filePath=path$1.relative(outDir,targetPath);const result=await extractTypes({
|
|
2157
|
+
messageCallback(message){messages.push(message);message.handled=true;}});const typesPath=path$1.resolve(distPath,filePath);const typesBuf=await fs.readFile(typesPath);const prettierConfig=await prettier.resolveConfig(typesPath);await mkdirp(path$1.dirname(typesPath));const moduleBlocks=await extractModuleBlocksFromTypes({extractResult:extractorResult,tsOutDir:tmpPath});const code=[typesBuf.toString(),...moduleBlocks].join("\n\n");await fs.writeFile(typesPath,await prettier.format(code,{...prettierConfig,filepath:typesPath}));files.push({type:"types",path:typesPath});return{extractorResult,messages};}async function doExtract(ctx,task){const{config,cwd,files,logger,strict,ts}=ctx;if(!ts.config||!ts.configPath){return{type:"dts",messages:[],results:[]};}const{outDir,rootDir=cwd}=ts.config.options;if(!outDir){throw new Error("tsconfig.json is missing `compilerOptions.outDir`");}const tmpPath=path$1.resolve(outDir,"__tmp__");await buildTypes({cwd,logger,outDir:tmpPath,strict,tsconfig:ts.config});const messages=[];const results=[];for(const entry of task.entries){var _config$extract,_config$extract2,_config$extract3;const exportPath=entry.exportPath==="."?"./index":entry.exportPath;const sourceTypesPath=path$1.resolve(tmpPath,path$1.relative(rootDir,path$1.resolve(cwd,entry.sourcePath)).replace(/\.ts$/,".d.ts"));const targetPath=path$1.resolve(cwd,entry.targetPath);const filePath=path$1.relative(outDir,targetPath);const result=await extractTypes({bundledPackages:(config===null||config===void 0||(_config$extract=config.extract)===null||_config$extract===void 0?void 0:_config$extract.bundledPackages)||[],customTags:config===null||config===void 0||(_config$extract2=config.extract)===null||_config$extract2===void 0?void 0:_config$extract2.customTags,cwd,distPath:outDir,exportPath,files,filePath,projectPath:cwd,rules:config===null||config===void 0||(_config$extract3=config.extract)===null||_config$extract3===void 0?void 0:_config$extract3.rules,sourceTypesPath,tmpPath,tsconfigPath:path$1.resolve(cwd,ts.configPath||"tsconfig.json")});messages.push(...result.messages);const errors=result.messages.filter(msg=>msg.logLevel==="error");if(errors.length>0){await rimraf(tmpPath);throw new DtsError("encountered ".concat(errors.length," errors when extracting types"),errors);}results.push({sourcePath:path$1.resolve(cwd,entry.sourcePath),filePath:targetPath});}await rimraf(tmpPath);return{type:"dts",messages,results};}const dtsTask={name:(_ctx,task)=>["Build type definitions..."," entries:",...task.entries.map(entry=>[" - ".concat(chalk.cyan(entry.importId),": "),"".concat(chalk.yellow(entry.sourcePath)," ").concat(chalk.gray("\u2192")," ").concat(chalk.yellow(entry.targetPath))].join(""))].join("\n"),exec:(ctx,task)=>{return new Observable(observer=>{doExtract(ctx,task).then(result=>{observer.next(result);observer.complete();}).catch(err=>{observer.error(err);});});},complete:(ctx,_task,result)=>{printExtractMessages(ctx,result.messages);},error:(ctx,_task,err)=>{const{logger}=ctx;if(err instanceof DtsError){printExtractMessages(ctx,err.messages);}else if(err instanceof Error){logger.error(err);}}};const dtsWatchTask={name:(_ctx,task)=>["build type definitions",...task.entries.map(entry=>" ".concat(chalk.blue(entry.importId),": ").concat(entry.sourcePath," -> ").concat(entry.targetPath))].join("\n"),exec:(ctx,task)=>{return new Observable(observer=>{doExtract(ctx,task).then(result=>{observer.next(result);observer.complete();}).catch(err=>observer.error(err));});},complete:(ctx,_task,result)=>{const{logger}=ctx;printExtractMessages(ctx,result.messages);logger.warn("watching typescript definitions is currently not supported");logger.log();},error:(ctx,_task,err)=>{const{logger}=ctx;if(err instanceof DtsError){printExtractMessages(ctx,err.messages);}else if(err instanceof Error){logger.error(err);}}};const nodeReexportCjsTask={name:(_ctx,task)=>["Re-export CommonJS module in ESM wrapper\u2026"," entries:",...task.entries.map(entry=>[" - ".concat(chalk.cyan(entry.importId),": "),"".concat(chalk.yellow(entry.require)," ").concat(chalk.gray("\u2192")," ").concat(chalk.yellow(entry.import))].join(""))].join("\n"),exec:(ctx,task)=>{return from(exec(ctx,task));},complete:()=>{},error:(_ctx,_task,err)=>{console.error(err);}};async function exec(ctx,task){const{cwd}=ctx;for(const entry of task.entries){const sourcePath=path$1.resolve(cwd,entry.require);const targetPath=path$1.resolve(cwd,entry.import);const targetDir=path$1.dirname(targetPath);await mkdirp(targetDir);const mod=require(sourcePath);let relativeImport="./".concat(path$1.relative(targetDir,sourcePath));if(relativeImport.startsWith("./.")){relativeImport=relativeImport.slice(2);}const code=compileESMWrapper(mod,relativeImport);await writeFile(targetPath,code,"utf8");}}function compileESMWrapper(mod,relativeImport){const keys=Object.keys(mod).filter(k=>k!=="__esModule");let code="import cjs from '".concat(relativeImport,"';\n");if(keys.length){code+="\n";code+=keys.filter(k=>mod.__esModule?k!=="default":true).map(k=>"export const ".concat(k," = cjs.").concat(k,";\n")).join("");}code+="\n";if(mod.__esModule){if("default"in mod){code+="export default cjs.default;\n";}}else{code+="export default cjs;\n";}return code;}function createConsoleSpy(options){const{onRestored}=options||{};const original={log:console.log,warn:console.warn,error:console.error};const messages=[];console.log=function(){for(var _len5=arguments.length,args=new Array(_len5),_key5=0;_key5<_len5;_key5++){args[_key5]=arguments[_key5];}return messages.push({type:"log",args});};console.warn=function(){for(var _len6=arguments.length,args=new Array(_len6),_key6=0;_key6<_len6;_key6++){args[_key6]=arguments[_key6];}return messages.push({type:"warn",args});};console.error=function(){for(var _len7=arguments.length,args=new Array(_len7),_key7=0;_key7<_len7;_key7++){args[_key7]=arguments[_key7];}return messages.push({type:"error",args});};return{messages,restore:()=>{console.log=original.log;console.warn=original.warn;console.error=original.error;onRestored===null||onRestored===void 0||onRestored(messages);}};}function resolveRollupConfig(ctx,buildTask){var _config$minify,_ts$config,_config$jsx,_config$jsxFactory,_config$jsxFragment,_config$jsxImportSour,_config$babel,_config$rollup,_config$rollup2,_config$sourcemap;const{format,runtime,target}=buildTask;const{config,cwd,exports:_exports,extMap,external,distPath,logger,pkg,ts}=ctx;const outputExt=extMap[pkg.type||"commonjs"][format];const minify=(_config$minify=config===null||config===void 0?void 0:config.minify)!==null&&_config$minify!==void 0?_config$minify:false;const outDir=path$1.relative(cwd,distPath);const pathAliases=Object.fromEntries(Object.entries(((_ts$config=ts.config)===null||_ts$config===void 0?void 0:_ts$config.options.paths)||{}).map(_ref91=>{var _ts$config2;let[key,val]=_ref91;return[key,path$1.resolve(cwd,((_ts$config2=ts.config)===null||_ts$config2===void 0?void 0:_ts$config2.options.baseUrl)||".",val[0])];}));const entries=buildTask.entries.map(entry=>{return{...entry,name:path$1.relative(outDir,entry.output).replace(/\.[^/.]+$/,"")};},{});const exportIds=_exports&&Object.keys(_exports).map(exportPath=>path$1.join(pkg.name,exportPath));const sourcePaths=_exports&&Object.values(_exports).map(e=>path$1.resolve(cwd,e.source));const replacements=Object.fromEntries(Object.entries((config===null||config===void 0?void 0:config.define)||{}).map(_ref92=>{let[key,val]=_ref92;return[key,JSON.stringify(val)];}));const defaultPlugins=[replace({preventAssignment:true,values:{...(pkg.name==="@sanity/pkg-utils"?{...replacements}:{"process.env.PKG_FILE_PATH":arg=>{const sourcePath="./"+path$1.relative(cwd,arg);const entry=entries.find(e=>e.source===sourcePath);if(!entry){console.error("could not find source entry: ".concat(sourcePath));return"null";}return JSON.stringify(path$1.relative(cwd,path$1.resolve(outDir,entry.name+outputExt)));},"process.env.PKG_FORMAT":JSON.stringify(format),"process.env.PKG_RUNTIME":JSON.stringify(runtime),"process.env.PKG_VERSION":JSON.stringify(process.env.PKG_VERSION||pkg.version),...replacements})}}),alias({entries:{...pathAliases}}),nodeResolve({// mainFields: ['module', 'jsnext', 'main'],
|
|
2159
2158
|
browser:runtime==="browser",// exportConditions: [runtime === 'node' ? 'node' : 'browser'],
|
|
2160
2159
|
extensions:[".cjs",".mjs",".js",".jsx",".json",".node"],preferBuiltins:true// runtime === 'node',
|
|
2161
2160
|
}),commonjs(),json(),esbuild({jsx:(_config$jsx=config===null||config===void 0?void 0:config.jsx)!==null&&_config$jsx!==void 0?_config$jsx:"automatic",jsxFactory:(_config$jsxFactory=config===null||config===void 0?void 0:config.jsxFactory)!==null&&_config$jsxFactory!==void 0?_config$jsxFactory:"createElement",jsxFragment:(_config$jsxFragment=config===null||config===void 0?void 0:config.jsxFragment)!==null&&_config$jsxFragment!==void 0?_config$jsxFragment:"Fragment",jsxImportSource:(_config$jsxImportSour=config===null||config===void 0?void 0:config.jsxImportSource)!==null&&_config$jsxImportSour!==void 0?_config$jsxImportSour:"react",target,tsconfig:ctx.ts.configPath||"tsconfig.json"}),getBabelOutputPlugin({babelrc:false,plugins:config===null||config===void 0||(_config$babel=config.babel)===null||_config$babel===void 0?void 0:_config$babel.plugins,presets:[["@babel/preset-env",{targets:pkg.browserslist||DEFAULT_BROWSERSLIST_QUERY,modules:false}]]}),minify&&terser({compress:true,output:{comments:(_node,comment)=>{const text=comment.value;const type=comment.type;if(type=="comment2"){return /@preserve|@license|@cc_on/i.test(text);}return false;}}})].filter(Boolean);const userPlugins=config===null||config===void 0||(_config$rollup=config.rollup)===null||_config$rollup===void 0?void 0:_config$rollup.plugins;const plugins=Array.isArray(userPlugins)?defaultPlugins.concat(userPlugins):resolveConfigProperty(config===null||config===void 0||(_config$rollup2=config.rollup)===null||_config$rollup2===void 0?void 0:_config$rollup2.plugins,defaultPlugins);return{inputOptions:{context:cwd,external:(id,importer)=>{if(exportIds!==null&&exportIds!==void 0&&exportIds.includes(id)){return true;}if(importer&&(id.startsWith(".")||id.startsWith("/"))){const idPath=path$1.resolve(path$1.dirname(importer),id);if(sourcePaths!==null&&sourcePaths!==void 0&&sourcePaths.includes(idPath)){logger.warn("detected self-referencing import \u2013 treating as external: ".concat(path$1.relative(cwd,idPath)));return true;}}const idParts=id.split("/");const name=idParts[0].startsWith("@")?"".concat(idParts[0],"/").concat(idParts[1]):idParts[0];if(name&&external.includes(name)){return true;}return false;},input:entries.reduce((acc,entry)=>{return{...acc,[entry.name]:entry.source};},{}),watch:{chokidar:{usePolling:true}},plugins,treeshake:{propertyReadSideEffects:false}},outputOptions:{chunkFileNames:()=>{const parts=outputExt.split(".");if(parts.length===3){return"_chunks/[name]-[hash].".concat(parts[2]);}return"_chunks/[name]-[hash]".concat(outputExt);},compact:minify,dir:outDir,entryFileNames:()=>{const parts=outputExt.split(".");if(parts.length===3){return"[name].".concat(parts[2]);}return"[name]".concat(outputExt);},esModule:true,format,interop:"compat",minifyInternalExports:minify,sourcemap:(_config$sourcemap=config===null||config===void 0?void 0:config.sourcemap)!==null&&_config$sourcemap!==void 0?_config$sourcemap:true,hoistTransitiveImports:false}};}const rollupTask={name:(ctx,task)=>{const bundleEntries=task.entries.filter(e=>e.path.includes("__$$bundle_"));const entries=task.entries.filter(e=>!e.path.includes("__$$bundle_"));const targetLines=task.target.length?[" target:",...task.target.map(t=>" - ".concat(chalk.yellow(t)))]:[];const bundlesLines=bundleEntries.length?[" bundles:",...bundleEntries.map(e=>[" - ","".concat(chalk.yellow(e.source)," ").concat(chalk.gray("\u2192")," ").concat(chalk.yellow(e.output))].join(""))]:[];const entriesLines=entries.length?[" entries:",...entries.map(e=>[" - ","".concat(chalk.cyan(path$1.join(ctx.pkg.name,e.path)),": "),"".concat(chalk.yellow(e.source)," ").concat(chalk.gray("\u2192")," ").concat(chalk.yellow(e.output))].join(""))]:[];return["Build javascript files..."," format: ".concat(chalk.yellow(task.format)),...targetLines,...bundlesLines,...entriesLines].join("\n");},exec:(ctx,task)=>{return new Observable(observer=>{execPromise(ctx,task).then(result=>{observer.next(result);observer.complete();}).catch(err=>observer.error(err));});},complete:()=>{},error:(_ctx,_task,err)=>{console.error(err);}};async function execPromise(ctx,task){const{distPath,files,logger}=ctx;const outDir=path$1.relative(ctx.cwd,distPath);const consoleSpy=createConsoleSpy({onRestored:messages=>{for(const msg of messages){const text=String(msg.args[0]);if(msg.code==="CIRCULAR_DEPENDENCY"){continue;}if(text.startsWith("Dynamic import can only")){continue;}if(text.startsWith("Sourcemap is likely to be incorrect")){continue;}if(msg.type==="log"){logger.info(...msg.args);}if(msg.type==="warn"){logger.warn(...msg.args);}if(msg.type==="error"){logger.error(...msg.args);}}}});try{const{inputOptions,outputOptions}=resolveRollupConfig(ctx,task);const bundle=await rollup({...inputOptions,onwarn(warning){consoleSpy.messages.push({type:"warn",code:warning.code,args:[warning.message]});}});const{output}=await bundle.generate(outputOptions);for(const chunkOrAsset of output){if(chunkOrAsset.type==="asset"){files.push({type:"asset",path:path$1.resolve(outDir,chunkOrAsset.fileName)});}else{files.push({type:"chunk",path:path$1.resolve(outDir,chunkOrAsset.fileName)});}}await bundle.write(outputOptions);await bundle.close();consoleSpy.restore();}catch(err){consoleSpy.restore();throw err;}}const rollupWatchTask={name:(ctx,task)=>"build javascript files (target ".concat(task.target.join(" + "),", format ").concat(task.format,")\n ").concat(task.entries.map(e=>"".concat(chalk.blue(path$1.join(ctx.pkg.name,e.path)),": ").concat(e.source," -> ").concat(e.output)).join("\n ")),exec:(ctx,task)=>{const{inputOptions,outputOptions}=resolveRollupConfig(ctx,task);return new Observable(observer=>{const watchOptions={...inputOptions,output:outputOptions};const watcher=watch$1(watchOptions);watcher.on("event",event=>{observer.next(event);});return()=>{watcher.close();};});},complete:(ctx,task,event)=>{const{logger}=ctx;if(event.code==="BUNDLE_END"){logger.success("build javascript files (target ".concat(task.target.join(" + "),", format ").concat(task.format,")\n ").concat(task.entries.map(e=>"".concat(chalk.blue(path$1.join(ctx.pkg.name,e.path)),": ").concat(e.source," -> ").concat(e.output)).join("\n ")));logger.log("");return;}if(event.code==="BUNDLE_START"){return;}if(event.code==="END"){return;}if(event.code==="ERROR"){logger.error(event.code,event);return;}if(event.code==="START"){return;}},error:(ctx,_task,err)=>{const{logger}=ctx;if(err instanceof Error){logger.log(err);}}};const buildTaskHandlers={"build:dts":dtsTask,"build:js":rollupTask,"node:reexport-cjs":nodeReexportCjsTask};const watchTaskHandlers={"watch:dts":dtsWatchTask,"watch:js":rollupWatchTask};async function build(options){var _config$legacyExports;const{cwd,emitDeclarationOnly,strict=false,tsconfig:tsconfigOption}=options;const logger=createLogger();const pkg=await loadPkgWithReporting({cwd,logger});const config=await loadConfig({cwd});const extMap=getPkgExtMap({legacyExports:(_config$legacyExports=config===null||config===void 0?void 0:config.legacyExports)!==null&&_config$legacyExports!==void 0?_config$legacyExports:false});const tsconfig=tsconfigOption||(config===null||config===void 0?void 0:config.tsconfig)||"tsconfig.json";const ctx=await resolveBuildContext({config,cwd,emitDeclarationOnly,extMap,logger,pkg,strict,tsconfig});const buildTasks=resolveBuildTasks(ctx);for(const task of buildTasks){const handler=buildTaskHandlers[task.type];const taskName=handler.name(ctx,task);const spinner=createSpinner(taskName);try{const result=await handler.exec(ctx,task).toPromise();spinner.complete();ctx.logger.log();handler.complete(ctx,task,result);}catch(err){spinner.error();if(err instanceof Error){const RE_CWD=new RegExp("".concat(cwd),"g");ctx.logger.error(err.message.replace(RE_CWD,"."));ctx.logger.log();}handler.error(ctx,task,err);process.exit(1);}}}function getFilesize(file){const stats=statSync(file);return prettyBytes(stats.size);}function getFileInfo(cwd,filePath){const p=path$1.resolve(cwd,filePath);const exists=fileExists(p);const size=exists?getFilesize(p):void 0;return{exists,size};}function printPackageTree(ctx){const{cwd,exports,logger,pkg}=ctx;if(!exports)return;logger.log("".concat(chalk.blue(pkg.name),"@").concat(chalk.green(pkg.version)));const tree={};if(pkg.type){tree.type=chalk.yellow(pkg.type);}if(pkg.bin){tree.bin=Object.fromEntries(Object.entries(pkg.bin).map(_ref93=>{let[name,file]=_ref93;return[chalk.cyan(name),fileInfo(file)];}));}function fileInfo(file){const info=getFileInfo(cwd,file);if(!info.size){return"".concat(chalk.gray(file)," ").concat(chalk.red("does not exist"));}return"".concat(chalk.yellow(file)," ").concat(chalk.gray(info.size));}tree.exports=Object.fromEntries(Object.entries(exports).filter(_ref94=>{let[,entry]=_ref94;return entry._exported;}).map(_ref95=>{let[exportPath,entry]=_ref95;const exp={types:void 0,source:fileInfo(entry.source),browser:void 0,require:void 0,node:void 0,import:void 0,default:fileInfo(entry.default)};if(entry.types){exp.types=fileInfo(entry.types);}else{delete exp.types;}if(entry.browser){exp.browser={source:fileInfo(entry.browser.source)};if(entry.browser.import)exp.browser.import=fileInfo(entry.browser.import);if(entry.browser.require)exp.browser.require=fileInfo(entry.browser.require);}else{delete exp.browser;}if(entry.require){exp.require=fileInfo(entry.require);}else{delete exp.require;}if(entry.node){exp.node={};if(entry.node.source)exp.node.source=fileInfo(entry.node.source);if(entry.node.import)exp.node.import=fileInfo(entry.node.import);if(entry.node.require)exp.node.require=fileInfo(entry.node.require);}else{delete exp.node;}if(entry.import){exp.import=fileInfo(entry.import);}else{delete exp.import;}return[chalk.cyan(path$1.join(pkg.name,exportPath)),exp];}));logger.log(treeify.asTree(tree,true,true));}async function check(options){var _config$legacyExports2;const{cwd,strict=false,tsconfig:tsconfigOption}=options;const logger=createLogger();const pkg=await loadPkgWithReporting({cwd,logger});const config=await loadConfig({cwd});const extMap=getPkgExtMap({legacyExports:(_config$legacyExports2=config===null||config===void 0?void 0:config.legacyExports)!==null&&_config$legacyExports2!==void 0?_config$legacyExports2:false});const tsconfig=tsconfigOption||(config===null||config===void 0?void 0:config.tsconfig)||"tsconfig.json";const ctx=await resolveBuildContext({config,cwd,extMap,logger,pkg,strict,tsconfig});printPackageTree(ctx);if(strict){const missingFiles=[];for(const[,exp]of Object.entries(ctx.exports||{})){if(exp.source&&!fileExists(path$1.resolve(cwd,exp.source))){missingFiles.push(exp.source);}if(exp.require&&!fileExists(path$1.resolve(cwd,exp.require))){missingFiles.push(exp.require);}if(exp.import&&!fileExists(path$1.resolve(cwd,exp.import))){missingFiles.push(exp.import);}if(exp.types&&!fileExists(path$1.resolve(cwd,exp.types))){missingFiles.push(exp.types);}}if(missingFiles.length){logger.error("missing files");process.exit(1);}const exportPaths={require:[],import:[]};for(const exp of Object.values(ctx.exports||{})){if(!exp._exported)continue;if(exp.require)exportPaths.require.push(exp.require);if(exp.import)exportPaths.import.push(exp.import);}const external=[...Object.keys(pkg.dependencies||{}),...Object.keys(pkg.devDependencies||{})];const consoleSpy=createConsoleSpy();if(exportPaths.import.length){checkExports(exportPaths.import,{cwd,external,format:"esm",logger});}if(exportPaths.require.length){checkExports(exportPaths.require,{cwd,external,format:"cjs",logger});}consoleSpy.restore();}}async function checkExports(exportPaths,options){const{cwd,external,format,logger}=options;const code=exportPaths.map(id=>format?"import('".concat(id,"');"):"require('".concat(id,"');")).join("\n");try{const esbuildResult=await esbuild$1.build({bundle:true,external,format,logLevel:"silent",// otherwise output maps to stdout as we're using stdin
|