@sanity/pkg-utils 3.2.0 → 3.2.1

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.
Files changed (33) hide show
  1. package/dist/_chunks/{build-zIodsGMj.cjs → build-5-t0rNQ5.cjs} +3 -3
  2. package/dist/_chunks/{build-zIodsGMj.cjs.map → build-5-t0rNQ5.cjs.map} +1 -1
  3. package/dist/_chunks/{buildAction-F25hbZcX.cjs → buildAction-XzgSYD6h.cjs} +2 -2
  4. package/dist/_chunks/{buildAction-F25hbZcX.cjs.map → buildAction-XzgSYD6h.cjs.map} +1 -1
  5. package/dist/_chunks/{check-X8xKPDnl.cjs → check-K-76aP0H.cjs} +2 -2
  6. package/dist/_chunks/{check-X8xKPDnl.cjs.map → check-K-76aP0H.cjs.map} +1 -1
  7. package/dist/_chunks/{checkAction-uQWLDlBA.cjs → checkAction-ovZpdoTW.cjs} +2 -2
  8. package/dist/_chunks/{checkAction-uQWLDlBA.cjs.map → checkAction-ovZpdoTW.cjs.map} +1 -1
  9. package/dist/_chunks/{consoleSpy--ReK-_gE.cjs → consoleSpy-Njnvw7-i.cjs} +4 -4
  10. package/dist/_chunks/consoleSpy-Njnvw7-i.cjs.map +1 -0
  11. package/dist/_chunks/{index-qV4Iq6pv.cjs → index-jKQCY5H6.cjs} +3 -3
  12. package/dist/_chunks/{index-qV4Iq6pv.cjs.map → index-jKQCY5H6.cjs.map} +1 -1
  13. package/dist/_chunks/{init-gkPbG69g.cjs → init-F_vsNarH.cjs} +78 -49
  14. package/dist/_chunks/init-F_vsNarH.cjs.map +1 -0
  15. package/dist/_chunks/{initAction-bz-ok0LO.cjs → initAction-dKWPRJL7.cjs} +2 -2
  16. package/dist/_chunks/{initAction-bz-ok0LO.cjs.map → initAction-dKWPRJL7.cjs.map} +1 -1
  17. package/dist/_chunks/{watch-4Yq69TUG.cjs → watch-8dkaWImB.cjs} +3 -3
  18. package/dist/_chunks/{watch-4Yq69TUG.cjs.map → watch-8dkaWImB.cjs.map} +1 -1
  19. package/dist/_chunks/{watchAction-HseKdhoO.cjs → watchAction-MPezXdut.cjs} +2 -2
  20. package/dist/_chunks/{watchAction-HseKdhoO.cjs.map → watchAction-MPezXdut.cjs.map} +1 -1
  21. package/dist/cli.cjs +5 -5
  22. package/dist/index.cjs +6 -6
  23. package/dist/index.d.ts +5 -5
  24. package/dist/index.js +4 -3
  25. package/dist/index.js.map +1 -1
  26. package/package.json +20 -55
  27. package/src/node/core/pkg/types.ts +4 -4
  28. package/src/node/core/ts/loadTSConfig.ts +2 -2
  29. package/src/node/resolveBuildContext.ts +2 -2
  30. package/src/node/tasks/dts/getExtractMessagesConfig.ts +2 -2
  31. package/src/node/templates/default/template.ts +139 -92
  32. package/dist/_chunks/consoleSpy--ReK-_gE.cjs.map +0 -1
  33. package/dist/_chunks/init-gkPbG69g.cjs.map +0 -1
package/dist/index.js CHANGED
@@ -1,6 +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{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')),
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){return void 0;}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')),
4
4
  // publicTrimmedFilePath: path.resolve(distPath, filePath.replace('.d.ts', '-public.d.ts')),
5
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={};/******************************************************************************
6
6
  Copyright (c) Microsoft Corporation.
@@ -2151,12 +2151,13 @@ function parse(source,options){var babelOptions=(0,_babel_options_1.default)(opt
2151
2151
  // parser: require("recast/parsers/typescript")
2152
2152
  // });
2153
2153
  //
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
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
2155
2155
  localBuild:true,// Equivalent to the "--verbose" command-line parameter
2156
2156
  showVerboseMessages:true,// handle messages
2157
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'],
2158
2158
  browser:runtime==="browser",// exportConditions: [runtime === 'node' ? 'node' : 'browser'],
2159
2159
  extensions:[".cjs",".mjs",".js",".jsx",".json",".node"],preferBuiltins:true// runtime === 'node',
2160
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
2161
- outfile:"/dev/null",platform:"node",stdin:{contents:code,loader:"js",resolveDir:cwd}});if(esbuildResult.errors.length>0){for(const msg of esbuildResult.errors){printEsbuildMessage(logger.warn,msg);logger.log();}process.exit(1);}const esbuildWarnings=esbuildResult.warnings.filter(msg=>{!(msg.detail||msg.text).includes("does not affect esbuild's own target setting");});for(const msg of esbuildWarnings){printEsbuildMessage(logger.warn,msg);logger.log();}}catch(err){const{errors}=err;for(const msg of errors){printEsbuildMessage(logger.error,msg);logger.log();}process.exit(1);}}function printEsbuildMessage(log,msg){if(msg.location){log(["".concat(msg.detail||msg.text,"\n"),"".concat(msg.location.line," | ").concat(msg.location.lineText,"\n"),"in ./".concat(msg.location.file,":").concat(msg.location.line,":").concat(msg.location.column)].join(""));}else{log(msg.detail||msg.text);}}async function isEmptyDirectory(dirPath){return(await readdir(dirPath)).length===0;}const RE_NAME=/^(?:@(?:[a-z0-9-*~][a-z0-9-*._~]*)\/)?[a-z0-9-~][a-z0-9-._~]*$/i;const defaultTemplate=async _ref96=>{var _gitConfig$user,_gitConfig$user2;let{cwd,logger,packagePath}=_ref96;const gitConfig=await parseGitConfig({cwd,type:"global"});return{options:[defineTemplateOption({name:"repo",type:"string",description:"git url",validate:v=>{if(!v)return true;try{gitUrlParse(v);return true;}catch(err){return"invalid git url";}},parse:v=>{if(!v)return null;const result=gitUrlParse(v);return{source:result.source,owner:result.owner,name:result.name};}}),defineTemplateOption({name:"pkgName",type:"string",description:"package name",initial:options=>{var _options$repo;return((_options$repo=options.repo)===null||_options$repo===void 0?void 0:_options$repo.name)||void 0;},validate:v=>{if(!v)return"package name is required";const match=RE_NAME.exec(v);if(!match){return"invalid package name";}return true;},parse:v=>{if(!v){throw new Error("package name is required");}const match=RE_NAME.exec(v);if(!match){throw new Error("invalid package name");}const[scope,name]=v.split("/");return{scope,name,fullName:v};}}),defineTemplateOption({name:"description",type:"string",description:"package description"}),defineTemplateOption({name:"authorName",type:"string",description:"package author name",initial:gitConfig===null||gitConfig===void 0||(_gitConfig$user=gitConfig.user)===null||_gitConfig$user===void 0?void 0:_gitConfig$user.name}),defineTemplateOption({name:"authorEmail",type:"string",description:"package author email",initial:gitConfig===null||gitConfig===void 0||(_gitConfig$user2=gitConfig.user)===null||_gitConfig$user2===void 0?void 0:_gitConfig$user2.email}),defineTemplateOption({name:"license",type:"string",description:"package license",initial:"MIT",validate:v=>{if(!v)return"license is required";return true;}})],features:[{name:"eslint",optional:true,initial:true},{name:"typescript",optional:true,initial:true}],async getFiles(options,features){var _filter$join,_options$description;const{pkgName,repo}=options;const{fullName:name}=pkgName;const author=(_filter$join=[options.authorName,options.authorEmail&&"<".concat(options.authorEmail,">")].filter(Boolean).join(" "))!==null&&_filter$join!==void 0?_filter$join:void 0;const prettierConfig={bracketSpacing:false,printWidth:100,semi:false,singleQuote:true,tabWidth:2,plugins:["prettier-plugin-packagejson"],overrides:[{files:["*.yml"],options:{singleQuote:false}}]};const pkgJson={name,version:"0.0.0",description:(_options$description=options.description)!==null&&_options$description!==void 0?_options$description:void 0,keywords:[],license:options.license,author,type:"module",exports:{".":{types:void 0,source:features.typescript?"./src/index.ts":"./src/index.js",require:"./dist/index.cjs",import:"./dist/index.js",default:"./dist/index.js"},"./package.json":"./package.json"},main:"./dist/index.cjs",module:"./dist/index.js",source:features.typescript?"./src/index.ts":"./src/index.js",files:["dist","src"],scripts:{build:"run-s clean pkg:build pkg:check",clean:"rimraf dist",format:"prettier --write --cache --ignore-unknown .","pkg:build":"pkg build --strict","pkg:check":"pkg check --strict"},prettier:prettierConfig,"lint-staged":{"*":["prettier --write --cache --ignore-unknown"]},dependencies:{},devDependencies:{"@sanity/pkg-utils":"*","lint-staged":"*","npm-run-all":"*",prettier:"*","prettier-plugin-packagejson":"*",rimraf:"*"},engines:{node:">=18.0.0"}};const files=[];files.push({name:".editorconfig",contents:outdent(_templateObject6||(_templateObject6=_taggedTemplateLiteral(["\n root = true\n\n [*]\n charset = utf-8\n indent_style = space\n indent_size = 2\n end_of_line = lf\n insert_final_newline = true\n trim_trailing_whitespace = true\n "])))});files.push({name:".gitignore",contents:outdent(_templateObject7||(_templateObject7=_taggedTemplateLiteral(["\n *.local\n *.log\n\n .DS_Store\n etc\n dist\n node_modules\n "])))});files.push({name:".prettierignore",contents:outdent(_templateObject8||(_templateObject8=_taggedTemplateLiteral(["\n /dist\n /pnpm-lock.yaml\n "])))});if(repo){pkgJson.repository={type:"git",url:"git+ssh://git@".concat(repo.source,"/").concat(repo.owner,"/").concat(repo.name,".git")};pkgJson.bugs={url:"https://".concat(repo.source,"/").concat(repo.owner,"/").concat(repo.name,"/issues")};pkgJson.homepage="https://".concat(repo.source,"/").concat(repo.owner,"/").concat(repo.name,"#readme");}if(features.typescript){var _pkgJson$exports;pkgJson.types="./dist/index.d.ts";const mainExport=(_pkgJson$exports=pkgJson.exports)===null||_pkgJson$exports===void 0?void 0:_pkgJson$exports["."];if(isRecord(mainExport)){mainExport.types="./dist/index.d.ts";}pkgJson.scripts={...pkgJson.scripts,["type:check"]:"tsc --build"};const devDependencies=pkgJson.devDependencies;if(isRecord(devDependencies)){devDependencies["typescript"]="*";}}if(features.eslint){const eslintConfig={root:true,env:{browser:true,es6:true,node:true},extends:["eslint:recommended","plugin:prettier/recommended"],parserOptions:{ecmaVersion:2020,sourceType:"module"},plugins:["import","prettier"],rules:{"no-console":"error","no-shadow":"error","no-warning-comments":["warn",{location:"start",terms:["todo","fixme"]}]}};files.push({name:".eslintignore",contents:outdent(_templateObject9||(_templateObject9=_taggedTemplateLiteral(["\n /dist\n "])))});pkgJson.scripts={...pkgJson.scripts,lint:features.typescript?"eslint . --ext .cjs,.js,.ts,.tsx":"eslint . --ext .cjs,.js"};pkgJson.devDependencies={...pkgJson.devDependencies,eslint:"*","eslint-config-prettier":"*","eslint-plugin-import":"*","eslint-plugin-prettier":"*"};if(features.typescript){pkgJson.devDependencies={...pkgJson.devDependencies,"@typescript-eslint/eslint-plugin":"*","@typescript-eslint/parser":"*"};const eslintConfigOverride={files:["**/*.ts","**/*.tsx"],parser:"@typescript-eslint/parser",parserOptions:{project:["./tsconfig.json"]},extends:["eslint:recommended","plugin:prettier/recommended","plugin:@typescript-eslint/eslint-recommended","plugin:@typescript-eslint/recommended"].filter(Boolean),plugins:["import","@typescript-eslint","prettier"].filter(Boolean),rules:{"@typescript-eslint/explicit-module-boundary-types":"error","@typescript-eslint/interface-name-prefix":"off","@typescript-eslint/member-delimiter-style":"off","@typescript-eslint/no-empty-interface":"off"}};eslintConfig.overrides=[eslintConfigOverride];}files.push({name:".eslintrc.cjs",contents:await format(resolve(packagePath,".eslintrc.cjs"),outdent(_templateObject10||(_templateObject10=_taggedTemplateLiteral(["\n 'use strict'\n\n /** @type import('eslint').Linter.Config */\n module.exports = ","\n "])),JSON.stringify(eslintConfig,null,2)),prettierConfig)});}if(features.typescript){files.push({name:"tsconfig.settings.json",contents:await format(resolve(packagePath,"tsconfig.settings.json"),outdent(_templateObject11||(_templateObject11=_taggedTemplateLiteral(["\n {\n \"compilerOptions\": {\n \"module\": \"ES2020\",\n \"target\": \"ES2020\",\n \"declaration\": true,\n \"declarationMap\": true,\n \"sourceMap\": true,\n\n // Strict type-checking\n \"strict\": true,\n \"noImplicitAny\": true,\n \"strictNullChecks\": true,\n \"strictFunctionTypes\": true,\n \"strictPropertyInitialization\": true,\n \"noImplicitThis\": true,\n \"alwaysStrict\": true,\n\n // Additional checks\n \"noUnusedLocals\": true,\n \"noUnusedParameters\": true,\n \"noImplicitReturns\": true,\n \"noFallthroughCasesInSwitch\": true,\n \"skipLibCheck\": true,\n\n // Module resolution\n \"moduleResolution\": \"node\",\n \"allowSyntheticDefaultImports\": true,\n \"esModuleInterop\": true\n }\n }\n "]))),prettierConfig)});files.push({name:"tsconfig.dist.json",contents:await format(resolve(packagePath,"tsconfig.dist.json"),outdent(_templateObject12||(_templateObject12=_taggedTemplateLiteral(["\n {\n \"extends\": \"./tsconfig.settings\",\n \"include\": [\"./src\"],\n \"compilerOptions\": {\n \"rootDir\": \".\",\n \"outDir\": \"./dist\",\n \"emitDeclarationOnly\": true,\n \"resolveJsonModule\": true\n }\n }\n "]))),prettierConfig)});files.push({name:"tsconfig.json",contents:await format(resolve(packagePath,"tsconfig.json"),outdent(_templateObject13||(_templateObject13=_taggedTemplateLiteral(["\n {\n \"extends\": \"./tsconfig.settings\",\n \"include\": [\"./*.cjs\", \"./*.ts\", \"./package.config.ts\", \"./src\"],\n \"compilerOptions\": {\n \"rootDir\": \".\",\n \"outDir\": \"./dist\",\n \"noEmit\": true,\n \"allowJs\": true,\n \"resolveJsonModule\": true,\n }\n }\n "]))),prettierConfig)});}if(features.typescript){files.push({name:"package.config.ts",contents:await format(resolve(packagePath,"package.config.ts"),outdent(_templateObject14||(_templateObject14=_taggedTemplateLiteral(["\n import {defineConfig} from '@sanity/pkg-utils'\n\n export default defineConfig({\n extract: {\n rules: {\n // do not require internal members to be prefixed with `_`\n 'ae-internal-missing-underscore': 'off',\n },\n },\n\n // the path to the tsconfig file for distributed builds\n tsconfig: 'tsconfig.dist.json',\n })\n "],["\n import {defineConfig} from '@sanity/pkg-utils'\n\n export default defineConfig({\n extract: {\n rules: {\n // do not require internal members to be prefixed with \\`_\\`\n 'ae-internal-missing-underscore': 'off',\n },\n },\n\n // the path to the tsconfig file for distributed builds\n tsconfig: 'tsconfig.dist.json',\n })\n "]))),prettierConfig)});files.push({name:"src/index.ts",contents:await format(resolve(packagePath,"src/index.ts"),outdent(_templateObject15||(_templateObject15=_taggedTemplateLiteral(["\n /** @public */\n export function main(): void {\n //\n }\n "]))),prettierConfig)});}else{files.push({name:"package.config.js",contents:await format(resolve(packagePath,"package.config.js"),outdent(_templateObject16||(_templateObject16=_taggedTemplateLiteral(["\n import {defineConfig} from '@sanity/pkg-utils'\n\n export default defineConfig({\n extract: {\n rules: {\n // do not require internal members to be prefixed with `_`\n 'ae-internal-missing-underscore': 'off',\n },\n },\n })\n "],["\n import {defineConfig} from '@sanity/pkg-utils'\n\n export default defineConfig({\n extract: {\n rules: {\n // do not require internal members to be prefixed with \\`_\\`\n 'ae-internal-missing-underscore': 'off',\n },\n },\n })\n "]))),prettierConfig)});files.push({name:"src/index.js",contents:await format(resolve(packagePath,"src/index.js"),outdent(_templateObject17||(_templateObject17=_taggedTemplateLiteral(["\n /** @public */\n export function main() {\n //\n }\n "]))),prettierConfig)});}try{var _pkgJson$dependencies;pkgJson.dependencies=await resolveLatestDeps((_pkgJson$dependencies=pkgJson.dependencies)!==null&&_pkgJson$dependencies!==void 0?_pkgJson$dependencies:{});}catch(error){logger.warn(error instanceof Error?error.message:error);}try{var _pkgJson$devDependenc;pkgJson.devDependencies=await resolveLatestDeps((_pkgJson$devDependenc=pkgJson.devDependencies)!==null&&_pkgJson$devDependenc!==void 0?_pkgJson$devDependenc:{});}catch(error){logger.warn(error instanceof Error?error.message:error);}files.push({name:"package.json",contents:await format(resolve(packagePath,"package.json"),JSON.stringify(pkgJson,null,2),prettierConfig)});return files;}};};function format(filepath,input,prettierOptions){return prettier.format(input,{...prettierOptions,filepath});}async function resolveLatestDeps(deps){const depsEntries=Object.entries(deps);const latestDeps={};for(const entry of depsEntries){const[name,version]=entry;const latestVersion=await getLatestVersion(name,version);latestDeps[name]=latestVersion?"^".concat(latestVersion):version;}return latestDeps;}async function init(options){if(!options.cwd){throw new Error("Missing required option: cwd");}if(!options.path){throw new Error("Missing required option: path");}const logger=createLogger();const packagePath=resolve(options.cwd,options.path);await ensurePackagePath(packagePath);await createFromTemplate({cwd:options.cwd,logger,template:defaultTemplate,packagePath});}async function ensurePackagePath(packagePath){const exists=fileExists(packagePath);if(!exists){await mkdirp(packagePath);return;}const dir=(await lstat(packagePath)).isDirectory();if(!dir){throw new Error("the package path is a file, not a directory");}const empty=await isEmptyDirectory(packagePath);if(!empty){throw new Error("the package directory is not empty");}}function resolveWatchTasks(ctx){const{config,cwd,pkg,target}=ctx;const tasks=[];const exports=Object.entries(ctx.exports||{}).map(_ref97=>{let[_path,exp]=_ref97;return{_path,...exp};});const dtsTask={type:"watch: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:"watch: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});}}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){var _exp$browser6,_exp$browser7;const output=(_exp$browser6=exp.browser)===null||_exp$browser6===void 0?void 0:_exp$browser6.require;if(!output)continue;addRollupTaskEntry("commonjs","browser",{path:exp._path,source:((_exp$browser7=exp.browser)===null||_exp$browser7===void 0?void 0:_exp$browser7.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$browser8,_exp$browser9;const output=(_exp$browser8=exp.browser)===null||_exp$browser8===void 0?void 0:_exp$browser8.import;if(!output)continue;addRollupTaskEntry("esm","browser",{path:exp._path,source:((_exp$browser9=exp.browser)===null||_exp$browser9===void 0?void 0:_exp$browser9.source)||exp.source,output});}if(dtsTask.entries.length){tasks.push(dtsTask);}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$browser10;const relativeTargetPath=(((_exp$browser10=exp.browser)===null||_exp$browser10===void 0?void 0:_exp$browser10.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"));}}}}return tasks;}function globFiles(patterns){return globby(patterns.map(pattern=>pattern.split(path$1.sep).join(path$1.posix.sep)));}function watchFiles(patterns){return new Observable(observer=>{const watcher=chokidar.watch(patterns,{ignoreInitial:true});function handleFileEvent(type,file){observer.next({type,file});}watcher.on("all",handleFileEvent);return()=>{watcher.off("all",handleFileEvent);watcher.close();};});}async function watchConfigFiles(options){const{cwd,logger}=options;const initialFiles=await globFiles([path$1.resolve(cwd,"package.json"),path$1.resolve(cwd,"package.config.cjs"),path$1.resolve(cwd,"package.config.js"),path$1.resolve(cwd,"package.config.ts")]);const fileEvent$=watchFiles([path$1.resolve(cwd,"package.json"),path$1.resolve(cwd,"package.config.cjs"),path$1.resolve(cwd,"package.config.js"),path$1.resolve(cwd,"package.config.ts")]);return fileEvent$.pipe(scan((files,fileEvent)=>{if(fileEvent.type==="add"){return files.concat(fileEvent.file);}if(fileEvent.type==="unlink"){return files.filter(f=>f!==fileEvent.file);}if(fileEvent.type==="change"){logger.log("--------------------------------------------------------------------------------");logger.info(path$1.relative(cwd,fileEvent.file),"changed");logger.log("");return files.slice(0);}return files;},initialFiles),startWith(initialFiles),distinctUntilChanged());}async function watch(options){const{cwd,strict=false,tsconfig:tsconfigOption}=options;const logger=createLogger();const configFiles$=await watchConfigFiles({cwd,logger});const ctx$=configFiles$.pipe(switchMap(async configFiles=>{var _config$legacyExports3;const files=configFiles.map(f=>path$1.relative(cwd,f));const packageJsonPath=files.find(f=>f==="package.json");if(!packageJsonPath){throw new Error("missing package.json");}const pkg=await loadPkgWithReporting({cwd,logger});const config=await loadConfig({cwd});const extMap=getPkgExtMap({legacyExports:(_config$legacyExports3=config===null||config===void 0?void 0:config.legacyExports)!==null&&_config$legacyExports3!==void 0?_config$legacyExports3:false});const tsconfig=tsconfigOption||(config===null||config===void 0?void 0:config.tsconfig)||"tsconfig.json";return resolveBuildContext({config,cwd,extMap,logger,pkg,strict,tsconfig});}));ctx$.subscribe(async ctx=>{const watchTasks=resolveWatchTasks(ctx);for(const task of watchTasks){const handler=watchTaskHandlers[task.type];const result$=handler.exec(ctx,task);result$.subscribe({error:err=>{ctx.logger.error(err);ctx.logger.log();process.exit(1);},next:result=>{handler.complete(ctx,task,result);},complete:()=>{ctx.logger.success(handler.name(ctx,task));ctx.logger.log();}});}});}export{DEFAULT_BROWSERSLIST_QUERY,DEFAULT_PKG_EXT_MAP,build,buildTaskHandlers,check,createFromTemplate,createLogger,defineConfig,defineTemplateOption,dtsTask,dtsWatchTask,getExtractMessagesConfig,getPkgExtMap,init,isRecord,loadConfig,loadPkg,loadPkgWithReporting,loadTSConfig,parseExports,resolveBuildTasks,resolveConfigProperty,rollupTask,rollupWatchTask,watch,watchTaskHandlers};
2161
+ outfile:"/dev/null",platform:"node",stdin:{contents:code,loader:"js",resolveDir:cwd}});if(esbuildResult.errors.length>0){for(const msg of esbuildResult.errors){printEsbuildMessage(logger.warn,msg);logger.log();}process.exit(1);}const esbuildWarnings=esbuildResult.warnings.filter(msg=>{!(msg.detail||msg.text).includes("does not affect esbuild's own target setting");});for(const msg of esbuildWarnings){printEsbuildMessage(logger.warn,msg);logger.log();}}catch(err){const{errors}=err;for(const msg of errors){printEsbuildMessage(logger.error,msg);logger.log();}process.exit(1);}}function printEsbuildMessage(log,msg){if(msg.location){log(["".concat(msg.detail||msg.text,"\n"),"".concat(msg.location.line," | ").concat(msg.location.lineText,"\n"),"in ./".concat(msg.location.file,":").concat(msg.location.line,":").concat(msg.location.column)].join(""));}else{log(msg.detail||msg.text);}}async function isEmptyDirectory(dirPath){return(await readdir(dirPath)).length===0;}const RE_NAME=/^(?:@(?:[a-z0-9-*~][a-z0-9-*._~]*)\/)?[a-z0-9-~][a-z0-9-._~]*$/i;const defaultTemplate=async _ref96=>{var _gitConfig$user,_gitConfig$user2;let{cwd,logger,packagePath}=_ref96;const gitConfig=await parseGitConfig({cwd,type:"global"});return{options:[defineTemplateOption({name:"repo",type:"string",description:"git url",validate:v=>{if(!v)return true;try{gitUrlParse(v);return true;}catch(err){return"invalid git url";}},parse:v=>{if(!v)return null;const result=gitUrlParse(v);return{source:result.source,owner:result.owner,name:result.name};}}),defineTemplateOption({name:"pkgName",type:"string",description:"package name",initial:options=>{var _options$repo;return((_options$repo=options.repo)===null||_options$repo===void 0?void 0:_options$repo.name)||void 0;},validate:v=>{if(!v)return"package name is required";const match=RE_NAME.exec(v);if(!match){return"invalid package name";}return true;},parse:v=>{if(!v){throw new Error("package name is required");}const match=RE_NAME.exec(v);if(!match){throw new Error("invalid package name");}const[scope,name]=v.split("/");return{scope,name,fullName:v};}}),defineTemplateOption({name:"description",type:"string",description:"package description"}),defineTemplateOption({name:"authorName",type:"string",description:"package author name",initial:gitConfig===null||gitConfig===void 0||(_gitConfig$user=gitConfig.user)===null||_gitConfig$user===void 0?void 0:_gitConfig$user.name}),defineTemplateOption({name:"authorEmail",type:"string",description:"package author email",initial:gitConfig===null||gitConfig===void 0||(_gitConfig$user2=gitConfig.user)===null||_gitConfig$user2===void 0?void 0:_gitConfig$user2.email}),defineTemplateOption({name:"license",type:"string",description:"package license",initial:"MIT",validate:v=>{if(!v)return"license is required";return true;}})],features:[{name:"eslint",optional:true,initial:true},{name:"prettier",optional:true,initial:true},{name:"typescript",optional:true,initial:true}],async getFiles(options,features){var _filter$join,_options$description;const{pkgName,repo}=options;const{fullName:name}=pkgName;const author=(_filter$join=[options.authorName,options.authorEmail&&"<".concat(options.authorEmail,">")].filter(Boolean).join(" "))!==null&&_filter$join!==void 0?_filter$join:void 0;const prettierConfig=features.prettier?{bracketSpacing:false,plugins:["prettier-plugin-packagejson"],printWidth:100,quoteProps:"consistent",semi:false,singleQuote:true,tabWidth:2,overrides:[{files:["*.yml"],options:{singleQuote:false}}]}:void 0;const pkgJson={name,"version":"0.0.0","description":(_options$description=options.description)!==null&&_options$description!==void 0?_options$description:void 0,"keywords":[],"homepage":void 0,"bugs":void 0,"repository":void 0,"license":options.license,author,"type":"module","exports":{".":{types:void 0,source:features.typescript?"./src/index.ts":"./src/index.js",import:"./dist/index.js",require:"./dist/index.cjs",default:"./dist/index.js"},"./package.json":"./package.json"},"main":"./dist/index.cjs","module":"./dist/index.js","source":features.typescript?"./src/index.ts":"./src/index.js","types":void 0,"files":["dist","src"],"scripts":{"build":"run-s clean pkg:build pkg:check","clean":"rimraf dist","format":features.prettier?"prettier --write --cache --ignore-unknown .":void 0,"pkg:build":"pkg build --strict","pkg:check":"pkg check --strict"},"lint-staged":features.prettier?{"*":["prettier --write --cache --ignore-unknown"]}:void 0,// prettier: prettierConfig,
2162
+ "dependencies":{},"devDependencies":{"@sanity/pkg-utils":"*","@typescript-eslint/eslint-plugin":void 0,"@typescript-eslint/parser":void 0,"eslint":void 0,"eslint-config-prettier":void 0,"eslint-plugin-import":void 0,"eslint-plugin-prettier":void 0,"eslint-plugin-simple-import-sort":void 0,"lint-staged":"*","npm-run-all":"*","prettier":features.prettier?"*":void 0,"prettier-plugin-packagejson":features.prettier?"*":void 0,"rimraf":"*","typescript":void 0},"engines":{node:">=18.0.0"}};const files=[];files.push({name:".editorconfig",contents:outdent(_templateObject6||(_templateObject6=_taggedTemplateLiteral(["\n root = true\n\n [*]\n charset = utf-8\n indent_style = space\n indent_size = 2\n end_of_line = lf\n insert_final_newline = true\n trim_trailing_whitespace = true\n "])))});files.push({name:".gitignore",contents:outdent(_templateObject7||(_templateObject7=_taggedTemplateLiteral(["\n *.local\n *.log\n *.tgz\n\n .DS_Store\n dist\n etc\n node_modules\n "])))});if(features.prettier){files.push({name:".prettierignore",contents:outdent(_templateObject8||(_templateObject8=_taggedTemplateLiteral(["\n dist\n pnpm-lock.yaml\n "])))});files.push({name:".prettierrc",contents:await format(resolve(packagePath,".prettierrc.json"),JSON.stringify(prettierConfig,null,2)+"\n",prettierConfig)});}if(repo){pkgJson.repository={type:"git",url:"git+ssh://git@".concat(repo.source,"/").concat(repo.owner,"/").concat(repo.name,".git")};pkgJson.bugs={url:"https://".concat(repo.source,"/").concat(repo.owner,"/").concat(repo.name,"/issues")};pkgJson.homepage="https://".concat(repo.source,"/").concat(repo.owner,"/").concat(repo.name,"#readme");}if(features.typescript){var _pkgJson$exports;pkgJson.types="./dist/index.d.ts";const mainExport=(_pkgJson$exports=pkgJson.exports)===null||_pkgJson$exports===void 0?void 0:_pkgJson$exports["."];if(isRecord(mainExport)){mainExport.types="./dist/index.d.ts";}pkgJson.scripts={...pkgJson.scripts,["ts:check"]:"tsc --build"};const devDependencies=pkgJson.devDependencies;if(isRecord(devDependencies)){devDependencies["typescript"]="*";}}if(features.eslint){const eslintConfig={root:true,env:{browser:true,es6:true,node:true},extends:["eslint:recommended",features.prettier?"plugin:prettier/recommended":void 0].filter(Boolean),parserOptions:{ecmaVersion:2020,sourceType:"module"},plugins:["import","simple-import-sort",features.prettier?"prettier":void 0].filter(Boolean),rules:{"no-console":"error","no-shadow":"error","no-warning-comments":["warn",{location:"start",terms:["todo","fixme"]}],"quote-props":["warn","consistent-as-needed"],"strict":["warn","global"]}};files.push({name:".eslintignore",contents:outdent(_templateObject9||(_templateObject9=_taggedTemplateLiteral(["\n dist\n "])))});pkgJson.scripts={...pkgJson.scripts,lint:features.typescript?"eslint . --ext .cjs,.js,.ts,.tsx":"eslint . --ext .cjs,.js"};pkgJson.devDependencies={...pkgJson.devDependencies,"eslint":"*","eslint-config-prettier":features.prettier?"*":void 0,"eslint-plugin-simple-import-sort":"*","eslint-plugin-import":"*","eslint-plugin-prettier":features.prettier?"*":void 0};if(features.typescript){pkgJson.devDependencies={...pkgJson.devDependencies,"@typescript-eslint/eslint-plugin":"*","@typescript-eslint/parser":"*"};const eslintConfigOverride={files:["**/*.ts","**/*.tsx"],parser:"@typescript-eslint/parser",parserOptions:{project:["./tsconfig.json"]},extends:["eslint:recommended",features.prettier?"plugin:prettier/recommended":void 0,"plugin:@typescript-eslint/eslint-recommended","plugin:@typescript-eslint/recommended"].filter(Boolean),plugins:["import","@typescript-eslint","simple-import-sort",features.prettier?"prettier":void 0].filter(Boolean),rules:{"@typescript-eslint/explicit-module-boundary-types":"error","@typescript-eslint/interface-name-prefix":"off","@typescript-eslint/member-delimiter-style":"off","@typescript-eslint/no-empty-interface":"off"}};eslintConfig.overrides=[eslintConfigOverride];}files.push({name:".eslintrc.cjs",contents:await format(resolve(packagePath,".eslintrc.cjs"),outdent(_templateObject10||(_templateObject10=_taggedTemplateLiteral(["\n 'use strict'\n\n /** @type import('eslint').Linter.Config */\n module.exports = ","\n "])),JSON.stringify(eslintConfig,null,2)),prettierConfig)});}if(features.typescript){files.push({name:"tsconfig.settings.json",contents:await format(resolve(packagePath,"tsconfig.settings.json"),outdent(_templateObject11||(_templateObject11=_taggedTemplateLiteral(["\n {\n \"compilerOptions\": {\n // Completeness\n \"skipLibCheck\": true,\n\n // Interop constraints\n \"allowSyntheticDefaultImports\": true,\n \"esModuleInterop\": true,\n\n // Language and environment\n \"target\": \"ES2020\",\n\n // Modules\n \"module\": \"ES2020\",\n \"moduleResolution\": \"Node\",\n\n // Type checking\n \"alwaysStrict\": true,\n \"noFallthroughCasesInSwitch\": true,\n \"noImplicitAny\": true,\n \"noImplicitReturns\": true,\n \"noImplicitThis\": true,\n \"noUnusedLocals\": true,\n \"noUnusedParameters\": true,\n \"strict\": true,\n \"strictFunctionTypes\": true,\n \"strictNullChecks\": true,\n \"strictPropertyInitialization\": true\n }\n }\n "]))),prettierConfig)});files.push({name:"tsconfig.dist.json",contents:await format(resolve(packagePath,"tsconfig.dist.json"),outdent(_templateObject12||(_templateObject12=_taggedTemplateLiteral(["\n {\n \"extends\": \"./tsconfig.settings\",\n \"include\": [\"./src\"],\n \"exclude\": [\"./src/**/*.test.ts\"],\n \"compilerOptions\": {\n \"rootDir\": \".\",\n \"outDir\": \"./dist\",\n \"resolveJsonModule\": true\n }\n }\n "]))),prettierConfig)});files.push({name:"tsconfig.json",contents:await format(resolve(packagePath,"tsconfig.json"),outdent(_templateObject13||(_templateObject13=_taggedTemplateLiteral(["\n {\n \"extends\": \"./tsconfig.settings\",\n \"include\": [\"./**/*.cjs\", \"./**/*.ts\", \"./**/*.tsx\"],\n \"exclude\": [\"./node_modules\"],\n \"compilerOptions\": {\n \"rootDir\": \".\",\n \"outDir\": \"./dist\",\n \"noEmit\": true,\n \"allowJs\": true,\n \"resolveJsonModule\": true,\n }\n }\n "]))),prettierConfig)});}if(features.typescript){files.push({name:"package.config.ts",contents:await format(resolve(packagePath,"package.config.ts"),outdent(_templateObject14||(_templateObject14=_taggedTemplateLiteral(["\n import {defineConfig} from '@sanity/pkg-utils'\n\n // https://github.com/sanity-io/pkg-utils#configuration\n export default defineConfig({\n // the path to the tsconfig file for distributed builds\n tsconfig: 'tsconfig.dist.json',\n })\n "]))),prettierConfig)});files.push({name:"src/index.ts",contents:await format(resolve(packagePath,"src/index.ts"),outdent(_templateObject15||(_templateObject15=_taggedTemplateLiteral(["\n /** @public */\n export function main(): void {\n //\n }\n "]))),prettierConfig)});}else{files.push({name:"package.config.js",contents:await format(resolve(packagePath,"package.config.js"),outdent(_templateObject16||(_templateObject16=_taggedTemplateLiteral(["\n import {defineConfig} from '@sanity/pkg-utils'\n\n export default defineConfig({\n extract: {\n rules: {\n // do not require internal members to be prefixed with `_`\n 'ae-internal-missing-underscore': 'off',\n },\n },\n })\n "],["\n import {defineConfig} from '@sanity/pkg-utils'\n\n export default defineConfig({\n extract: {\n rules: {\n // do not require internal members to be prefixed with \\`_\\`\n 'ae-internal-missing-underscore': 'off',\n },\n },\n })\n "]))),prettierConfig)});files.push({name:"src/index.js",contents:await format(resolve(packagePath,"src/index.js"),outdent(_templateObject17||(_templateObject17=_taggedTemplateLiteral(["\n /** @public */\n export function main() {\n //\n }\n "]))),prettierConfig)});}try{var _pkgJson$dependencies;pkgJson.dependencies=await resolveLatestDeps((_pkgJson$dependencies=pkgJson.dependencies)!==null&&_pkgJson$dependencies!==void 0?_pkgJson$dependencies:{});}catch(error){logger.warn(error instanceof Error?error.message:error);}try{var _pkgJson$devDependenc;pkgJson.devDependencies=await resolveLatestDeps((_pkgJson$devDependenc=pkgJson.devDependencies)!==null&&_pkgJson$devDependenc!==void 0?_pkgJson$devDependenc:{});}catch(error){logger.warn(error instanceof Error?error.message:error);}files.push({name:"package.json",contents:await format(resolve(packagePath,"package.json"),JSON.stringify(pkgJson,null,2),prettierConfig)});return files;}};};function format(filepath,input,prettierOptions){return prettier.format(input,{...prettierOptions,plugins:[],filepath});}async function resolveLatestDeps(deps){const depsEntries=Object.entries(deps);const latestDeps={};for(const entry of depsEntries){const[name,version]=entry;if(version){const latestVersion=await getLatestVersion(name,version);latestDeps[name]=latestVersion?"^".concat(latestVersion):version;}}return latestDeps;}async function init(options){if(!options.cwd){throw new Error("Missing required option: cwd");}if(!options.path){throw new Error("Missing required option: path");}const logger=createLogger();const packagePath=resolve(options.cwd,options.path);await ensurePackagePath(packagePath);await createFromTemplate({cwd:options.cwd,logger,template:defaultTemplate,packagePath});}async function ensurePackagePath(packagePath){const exists=fileExists(packagePath);if(!exists){await mkdirp(packagePath);return;}const dir=(await lstat(packagePath)).isDirectory();if(!dir){throw new Error("the package path is a file, not a directory");}const empty=await isEmptyDirectory(packagePath);if(!empty){throw new Error("the package directory is not empty");}}function resolveWatchTasks(ctx){const{config,cwd,pkg,target}=ctx;const tasks=[];const exports=Object.entries(ctx.exports||{}).map(_ref97=>{let[_path,exp]=_ref97;return{_path,...exp};});const dtsTask={type:"watch: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:"watch: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});}}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){var _exp$browser6,_exp$browser7;const output=(_exp$browser6=exp.browser)===null||_exp$browser6===void 0?void 0:_exp$browser6.require;if(!output)continue;addRollupTaskEntry("commonjs","browser",{path:exp._path,source:((_exp$browser7=exp.browser)===null||_exp$browser7===void 0?void 0:_exp$browser7.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$browser8,_exp$browser9;const output=(_exp$browser8=exp.browser)===null||_exp$browser8===void 0?void 0:_exp$browser8.import;if(!output)continue;addRollupTaskEntry("esm","browser",{path:exp._path,source:((_exp$browser9=exp.browser)===null||_exp$browser9===void 0?void 0:_exp$browser9.source)||exp.source,output});}if(dtsTask.entries.length){tasks.push(dtsTask);}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$browser10;const relativeTargetPath=(((_exp$browser10=exp.browser)===null||_exp$browser10===void 0?void 0:_exp$browser10.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"));}}}}return tasks;}function globFiles(patterns){return globby(patterns.map(pattern=>pattern.split(path$1.sep).join(path$1.posix.sep)));}function watchFiles(patterns){return new Observable(observer=>{const watcher=chokidar.watch(patterns,{ignoreInitial:true});function handleFileEvent(type,file){observer.next({type,file});}watcher.on("all",handleFileEvent);return()=>{watcher.off("all",handleFileEvent);watcher.close();};});}async function watchConfigFiles(options){const{cwd,logger}=options;const initialFiles=await globFiles([path$1.resolve(cwd,"package.json"),path$1.resolve(cwd,"package.config.cjs"),path$1.resolve(cwd,"package.config.js"),path$1.resolve(cwd,"package.config.ts")]);const fileEvent$=watchFiles([path$1.resolve(cwd,"package.json"),path$1.resolve(cwd,"package.config.cjs"),path$1.resolve(cwd,"package.config.js"),path$1.resolve(cwd,"package.config.ts")]);return fileEvent$.pipe(scan((files,fileEvent)=>{if(fileEvent.type==="add"){return files.concat(fileEvent.file);}if(fileEvent.type==="unlink"){return files.filter(f=>f!==fileEvent.file);}if(fileEvent.type==="change"){logger.log("--------------------------------------------------------------------------------");logger.info(path$1.relative(cwd,fileEvent.file),"changed");logger.log("");return files.slice(0);}return files;},initialFiles),startWith(initialFiles),distinctUntilChanged());}async function watch(options){const{cwd,strict=false,tsconfig:tsconfigOption}=options;const logger=createLogger();const configFiles$=await watchConfigFiles({cwd,logger});const ctx$=configFiles$.pipe(switchMap(async configFiles=>{var _config$legacyExports3;const files=configFiles.map(f=>path$1.relative(cwd,f));const packageJsonPath=files.find(f=>f==="package.json");if(!packageJsonPath){throw new Error("missing package.json");}const pkg=await loadPkgWithReporting({cwd,logger});const config=await loadConfig({cwd});const extMap=getPkgExtMap({legacyExports:(_config$legacyExports3=config===null||config===void 0?void 0:config.legacyExports)!==null&&_config$legacyExports3!==void 0?_config$legacyExports3:false});const tsconfig=tsconfigOption||(config===null||config===void 0?void 0:config.tsconfig)||"tsconfig.json";return resolveBuildContext({config,cwd,extMap,logger,pkg,strict,tsconfig});}));ctx$.subscribe(async ctx=>{const watchTasks=resolveWatchTasks(ctx);for(const task of watchTasks){const handler=watchTaskHandlers[task.type];const result$=handler.exec(ctx,task);result$.subscribe({error:err=>{ctx.logger.error(err);ctx.logger.log();process.exit(1);},next:result=>{handler.complete(ctx,task,result);},complete:()=>{ctx.logger.success(handler.name(ctx,task));ctx.logger.log();}});}});}export{DEFAULT_BROWSERSLIST_QUERY,DEFAULT_PKG_EXT_MAP,build,buildTaskHandlers,check,createFromTemplate,createLogger,defineConfig,defineTemplateOption,dtsTask,dtsWatchTask,getExtractMessagesConfig,getPkgExtMap,init,isRecord,loadConfig,loadPkg,loadPkgWithReporting,loadTSConfig,parseExports,resolveBuildTasks,resolveConfigProperty,rollupTask,rollupWatchTask,watch,watchTaskHandlers};
2162
2163
  //# sourceMappingURL=index.js.map