@sanity/pkg-utils 3.2.5 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/dist/_chunks/{build-x5i4O8IV.cjs → build-7mn5THX6.cjs} +4 -4
  2. package/dist/_chunks/{build-x5i4O8IV.cjs.map → build-7mn5THX6.cjs.map} +1 -1
  3. package/dist/_chunks/{buildAction-2LUsWSI8.cjs → buildAction-fRHTIDmx.cjs} +2 -2
  4. package/dist/_chunks/{buildAction-2LUsWSI8.cjs.map → buildAction-fRHTIDmx.cjs.map} +1 -1
  5. package/dist/_chunks/{check-K-76aP0H.cjs → check-pxYRC97N.cjs} +3 -3
  6. package/dist/_chunks/{check-K-76aP0H.cjs.map → check-pxYRC97N.cjs.map} +1 -1
  7. package/dist/_chunks/{checkAction-ovZpdoTW.cjs → checkAction-0xA1q64g.cjs} +2 -2
  8. package/dist/_chunks/{checkAction-ovZpdoTW.cjs.map → checkAction-0xA1q64g.cjs.map} +1 -1
  9. package/dist/_chunks/{consoleSpy-Njnvw7-i.cjs → consoleSpy-g4ZadSyB.cjs} +2 -2
  10. package/dist/_chunks/{consoleSpy-Njnvw7-i.cjs.map → consoleSpy-g4ZadSyB.cjs.map} +1 -1
  11. package/dist/_chunks/{index-yeO2SQtJ.cjs → index-1Mfz_QDA.cjs} +6 -6
  12. package/dist/_chunks/{index-yeO2SQtJ.cjs.map → index-1Mfz_QDA.cjs.map} +1 -1
  13. package/dist/_chunks/{init-JUK_GqHH.cjs → init-U-HiL7BD.cjs} +2 -2
  14. package/dist/_chunks/{init-JUK_GqHH.cjs.map → init-U-HiL7BD.cjs.map} +1 -1
  15. package/dist/_chunks/{initAction-Xi2rF6yS.cjs → initAction-QVQEhQh6.cjs} +2 -2
  16. package/dist/_chunks/{initAction-Xi2rF6yS.cjs.map → initAction-QVQEhQh6.cjs.map} +1 -1
  17. package/dist/_chunks/{logger-_q9DVAFj.cjs → logger-iA0nC-kL.cjs} +1 -2
  18. package/dist/_chunks/{logger-_q9DVAFj.cjs.map → logger-iA0nC-kL.cjs.map} +1 -1
  19. package/dist/_chunks/{watch-DsNunIr0.cjs → watch-6xc8QXJF.cjs} +4 -4
  20. package/dist/_chunks/{watch-DsNunIr0.cjs.map → watch-6xc8QXJF.cjs.map} +1 -1
  21. package/dist/_chunks/{watchAction-Qy9mrpk5.cjs → watchAction-JfAFOHP0.cjs} +2 -2
  22. package/dist/_chunks/{watchAction-Qy9mrpk5.cjs.map → watchAction-JfAFOHP0.cjs.map} +1 -1
  23. package/dist/cli.cjs +5 -5
  24. package/dist/index.cjs +7 -7
  25. package/dist/index.d.ts +2 -0
  26. package/dist/index.js +4 -4
  27. package/dist/index.js.map +1 -1
  28. package/package.json +8 -8
  29. package/src/node/core/config/types.ts +2 -1
  30. package/src/node/tasks/rollup/resolveRollupConfig.ts +1 -0
package/dist/index.js CHANGED
@@ -1407,7 +1407,7 @@ node.expressions.forEach(function(expr,i){// Rewind from expr.loc.start over any
1407
1407
  var dollarCurlyPos=lines.skipSpaces(expr.loc.start,true,false);if(lines.prevPos(dollarCurlyPos)&&lines.charAt(dollarCurlyPos)==="{"&&lines.prevPos(dollarCurlyPos)&&lines.charAt(dollarCurlyPos)==="$"){var quasiBefore=node.quasis[i];if(comparePos(dollarCurlyPos,quasiBefore.loc.end)<0){quasiBefore.loc.end=dollarCurlyPos;}}// Likewise, some parsers accidentally include the } that follows
1408
1408
  // the expression in the .loc of the following quasi element.
1409
1409
  var rightCurlyPos=lines.skipSpaces(expr.loc.end,false,false);if(lines.charAt(rightCurlyPos)==="}"){assert_1.default.ok(lines.nextPos(rightCurlyPos));// Now rightCurlyPos is technically the position just after the }.
1410
- var quasiAfter=node.quasis[i+1];if(comparePos(quasiAfter.loc.start,rightCurlyPos)<0){quasiAfter.loc.start=rightCurlyPos;}}});}function isExportDeclaration(node){if(node)switch(node.type){case"ExportDeclaration":case"ExportDefaultDeclaration":case"ExportDefaultSpecifier":case"DeclareExportDeclaration":case"ExportNamedDeclaration":case"ExportAllDeclaration":return true;}return false;}util$1.isExportDeclaration=isExportDeclaration;function getParentExportDeclaration(path){var parentNode=path.getParentNode();if(path.getName()==="declaration"&&isExportDeclaration(parentNode)){return parentNode;}return null;}util$1.getParentExportDeclaration=getParentExportDeclaration;function isTrailingCommaEnabled(options,context){var trailingComma=options.trailingComma;if(typeof trailingComma==="object"){return!!trailingComma[context];}return!!trailingComma;}util$1.isTrailingCommaEnabled=isTrailingCommaEnabled;return util$1;}var esprima$1={};var esprima={exports:{}};var hasRequiredEsprima$1;function requireEsprima$1(){if(hasRequiredEsprima$1)return esprima.exports;hasRequiredEsprima$1=1;(function(module,exports){(function webpackUniversalModuleDefinition(root,factory){/* istanbul ignore next */module.exports=factory();})(commonjsGlobal,function(){return(/******/function(modules){// webpackBootstrap
1410
+ var quasiAfter=node.quasis[i+1];if(comparePos(quasiAfter.loc.start,rightCurlyPos)<0){quasiAfter.loc.start=rightCurlyPos;}}});}function isExportDeclaration(node){if(node)switch(node.type){case"ExportDeclaration":case"ExportDefaultDeclaration":case"ExportDefaultSpecifier":case"DeclareExportDeclaration":case"ExportNamedDeclaration":case"ExportAllDeclaration":return true;}return false;}util$1.isExportDeclaration=isExportDeclaration;function getParentExportDeclaration(path){var parentNode=path.getParentNode();if(path.getName()==="declaration"&&isExportDeclaration(parentNode)){return parentNode;}return null;}util$1.getParentExportDeclaration=getParentExportDeclaration;function isTrailingCommaEnabled(options,context){var trailingComma=options.trailingComma;if(typeof trailingComma==="object"){return!!trailingComma[context];}return!!trailingComma;}util$1.isTrailingCommaEnabled=isTrailingCommaEnabled;return util$1;}var esprima$1={};var esprima={exports:{}};var hasRequiredEsprima$1;function requireEsprima$1(){if(hasRequiredEsprima$1)return esprima.exports;hasRequiredEsprima$1=1;(function(module,exports){(function webpackUniversalModuleDefinition(root,factory){/* istanbul ignore next */module.exports=factory();})(commonjsGlobal,function(){return/******/function(modules){// webpackBootstrap
1411
1411
  /******/ // The module cache
1412
1412
  /******/var installedModules={};/******/ // The require function
1413
1413
  /******/function __webpack_require__(moduleId){/******/ // Check if module is in cache
@@ -1674,7 +1674,7 @@ Reader.prototype.isRegexStart=function(){var previous=this.values[this.values.le
1674
1674
  // but we have to check for that.
1675
1675
  regex=false;if(this.values[this.curly-3]==='function'){// Anonymous function, e.g. function(){} /42
1676
1676
  var check=this.values[this.curly-4];regex=check?!this.beforeFunctionExpression(check):false;}else if(this.values[this.curly-4]==='function'){// Named function, e.g. function f(){} /42/
1677
- var check=this.values[this.curly-5];regex=check?!this.beforeFunctionExpression(check):true;}break;}return regex;};Reader.prototype.push=function(token){if(token.type===7/* Punctuator */||token.type===4/* Keyword */){if(token.value==='{'){this.curly=this.values.length;}else if(token.value==='('){this.paren=this.values.length;}this.values.push(token.value);}else{this.values.push(null);}};return Reader;}();var Tokenizer=function(){function Tokenizer(code,config){this.errorHandler=new error_handler_1.ErrorHandler();this.errorHandler.tolerant=config?typeof config.tolerant==='boolean'&&config.tolerant:false;this.scanner=new scanner_1.Scanner(code,this.errorHandler);this.scanner.trackComment=config?typeof config.comment==='boolean'&&config.comment:false;this.trackRange=config?typeof config.range==='boolean'&&config.range:false;this.trackLoc=config?typeof config.loc==='boolean'&&config.loc:false;this.buffer=[];this.reader=new Reader();}Tokenizer.prototype.errors=function(){return this.errorHandler.errors;};Tokenizer.prototype.getNextToken=function(){if(this.buffer.length===0){var comments=this.scanner.scanComments();if(this.scanner.trackComment){for(var i=0;i<comments.length;++i){var e=comments[i];var value=this.scanner.source.slice(e.slice[0],e.slice[1]);var comment={type:e.multiLine?'BlockComment':'LineComment',value:value};if(this.trackRange){comment.range=e.range;}if(this.trackLoc){comment.loc=e.loc;}this.buffer.push(comment);}}if(!this.scanner.eof()){var loc=void 0;if(this.trackLoc){loc={start:{line:this.scanner.lineNumber,column:this.scanner.index-this.scanner.lineStart},end:{}};}var startRegex=this.scanner.source[this.scanner.index]==='/'&&this.reader.isRegexStart();var token=startRegex?this.scanner.scanRegExp():this.scanner.lex();this.reader.push(token);var entry={type:token_1.TokenName[token.type],value:this.scanner.source.slice(token.start,token.end)};if(this.trackRange){entry.range=[token.start,token.end];}if(this.trackLoc){loc.end={line:this.scanner.lineNumber,column:this.scanner.index-this.scanner.lineStart};entry.loc=loc;}if(token.type===9/* RegularExpression */){var pattern=token.pattern;var flags=token.flags;entry.regex={pattern:pattern,flags:flags};}this.buffer.push(entry);}}return this.buffer.shift();};return Tokenizer;}();exports.Tokenizer=Tokenizer;/***/}/******/]));});})(esprima);return esprima.exports;}var hasRequiredEsprima;function requireEsprima(){if(hasRequiredEsprima)return esprima$1;hasRequiredEsprima=1;Object.defineProperty(esprima$1,"__esModule",{value:true});esprima$1.parse=void 0;// This module is suitable for passing as options.parser when calling
1677
+ var check=this.values[this.curly-5];regex=check?!this.beforeFunctionExpression(check):true;}break;}return regex;};Reader.prototype.push=function(token){if(token.type===7/* Punctuator */||token.type===4/* Keyword */){if(token.value==='{'){this.curly=this.values.length;}else if(token.value==='('){this.paren=this.values.length;}this.values.push(token.value);}else{this.values.push(null);}};return Reader;}();var Tokenizer=function(){function Tokenizer(code,config){this.errorHandler=new error_handler_1.ErrorHandler();this.errorHandler.tolerant=config?typeof config.tolerant==='boolean'&&config.tolerant:false;this.scanner=new scanner_1.Scanner(code,this.errorHandler);this.scanner.trackComment=config?typeof config.comment==='boolean'&&config.comment:false;this.trackRange=config?typeof config.range==='boolean'&&config.range:false;this.trackLoc=config?typeof config.loc==='boolean'&&config.loc:false;this.buffer=[];this.reader=new Reader();}Tokenizer.prototype.errors=function(){return this.errorHandler.errors;};Tokenizer.prototype.getNextToken=function(){if(this.buffer.length===0){var comments=this.scanner.scanComments();if(this.scanner.trackComment){for(var i=0;i<comments.length;++i){var e=comments[i];var value=this.scanner.source.slice(e.slice[0],e.slice[1]);var comment={type:e.multiLine?'BlockComment':'LineComment',value:value};if(this.trackRange){comment.range=e.range;}if(this.trackLoc){comment.loc=e.loc;}this.buffer.push(comment);}}if(!this.scanner.eof()){var loc=void 0;if(this.trackLoc){loc={start:{line:this.scanner.lineNumber,column:this.scanner.index-this.scanner.lineStart},end:{}};}var startRegex=this.scanner.source[this.scanner.index]==='/'&&this.reader.isRegexStart();var token=startRegex?this.scanner.scanRegExp():this.scanner.lex();this.reader.push(token);var entry={type:token_1.TokenName[token.type],value:this.scanner.source.slice(token.start,token.end)};if(this.trackRange){entry.range=[token.start,token.end];}if(this.trackLoc){loc.end={line:this.scanner.lineNumber,column:this.scanner.index-this.scanner.lineStart};entry.loc=loc;}if(token.type===9/* RegularExpression */){var pattern=token.pattern;var flags=token.flags;entry.regex={pattern:pattern,flags:flags};}this.buffer.push(entry);}}return this.buffer.shift();};return Tokenizer;}();exports.Tokenizer=Tokenizer;/***/}/******/]);});})(esprima);return esprima.exports;}var hasRequiredEsprima;function requireEsprima(){if(hasRequiredEsprima)return esprima$1;hasRequiredEsprima=1;Object.defineProperty(esprima$1,"__esModule",{value:true});esprima$1.parse=void 0;// This module is suitable for passing as options.parser when calling
1678
1678
  // recast.parse to process ECMAScript code with Esprima:
1679
1679
  //
1680
1680
  // const ast = recast.parse(source, {
@@ -2154,10 +2154,10 @@ function parse(source,options){var babelOptions=(0,_babel_options_1.default)(opt
2154
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
- 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'],
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,_config$rollup3;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
- }),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
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,...(config===null||config===void 0||(_config$rollup3=config.rollup)===null||_config$rollup3===void 0?void 0:_config$rollup3.output)}};}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
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
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"],"simple-import-sort/exports":"warn","simple-import-sort/imports":"warn","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};
2163
2163
  //# sourceMappingURL=index.js.map