build-ts 13.1.0 → 13.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{readAndApplyEnvironmentVariables as e,yargsOptionsBuilderForEnv as o,removeNpmAndYarnEnvironmentVariables as n}from"@willbooster/shared-lib-node";import s from"yargs";import{hideBin as t}from"yargs/helpers";import i from"node:fs";import r from"node:path";import c from"chalk";import a from"date-time";import p from"pretty-ms";import{rollup as l,watch as d}from"rollup";import{onExit as m}from"signal-exit";import u from"node:url";import{babel as f}from"@rollup/plugin-babel";import y from"@rollup/plugin-commonjs";import g from"@rollup/plugin-json";import h from"@rollup/plugin-node-resolve";import b from"@rollup/plugin-replace";import j from"@rollup/plugin-terser";import v from"rollup-plugin-analyzer";import{keepImport as w}from"rollup-plugin-keep-import";import{nodeExternals as x}from"rollup-plugin-node-externals";import S from"rollup-plugin-preserve-directives";import{string as k}from"rollup-plugin-string";import E from"node:process";import $ from"typescript";import*as D from"node:child_process";let O;function T(o,n){return O||(O=e(o,n),o.verbose&&console.info("Loaded env vars:",Object.keys(O))),O}function _(e,o){const n={},s=new Set([...(e.inline??[]).flatMap((e=>e.toString().split(","))),...Object.keys(T(e,o))]);for(const e of s)void 0!==process.env[e]&&(n[`process.env.${e}`]=JSON.stringify(process.env[e]));return e.verbose&&console.info("Inline env vars:",Object.keys(n)),n}const N=["app","functions","lib"];async function F(e){const o=r.join(e,"package.json");try{const e=await i.promises.readFile(o,"utf8");return[JSON.parse(e),o]}catch{}return[void 0,o]}const R={...o,silent:{description:"Whether watch mode is enabled or not",type:"boolean",alias:"s"}},L={...R,input:{description:'Paths of source code files to be built. The first file is main. If no option is given, "src/index.{ts,tsx}" from package directory is targeted.',type:"array",alias:"i"},"core-js":{description:"Whether or not core-js is employed.",type:"boolean",default:!1},"core-js-proposals":{description:"Whether or not core-js with proposals support is employed.",type:"boolean",default:!1},minify:{description:"Whether or not minification is enabled.",type:"boolean",default:!0},sourcemap:{description:"Whether or not sourcemap is enabled.",type:"boolean",default:!0},external:{description:"Additional external dependencies.",type:"array"},inline:{description:"Environment variables to be inlined.",type:"array"},watch:{description:"Whether watch mode is enabled or not",type:"boolean",alias:"w"},keepImport:{description:"Identifiers to be kept as import statements.",type:"array"}},B={...L,moduleType:{description:"esm, cjs, or either (default).",type:"string",alias:"m"}},C={...B,onlyPackageJson:{description:"Whether to generate only package.json.",type:"boolean"}},A={...L,moduleType:{description:"esm, cjs, either, or both (default).",type:"string",alias:"m"},jsExtension:{description:"Whether to use .js in cjs and/or esm: either (default), both, or none.",type:"string",alias:"j"}};function I(e,o,n,s,t,c){const a=[...e.external??[]].map((e=>e.toString()));if(n.dependencies?.["@prisma/client"]&&a.push("prisma-client"),a.push(...Object.keys(n.dependencies??{}),...Object.keys(n.peerDependencies??{}),...Object.keys(n.optionalDependencies??{})),i.existsSync(r.join("..","..","package.json"))){const e=i.readdirSync(r.join(".."),{withFileTypes:!0});for(const o of e){if(!o.isDirectory())continue;const e=r.join("..",o.name,"package.json");if(!i.existsSync(e))continue;const s=JSON.parse(i.readFileSync(e,"utf8"));n.dependencies?.[s.name??""]&&a.push(...Object.keys(s.dependencies??{}),...Object.keys(s.peerDependencies??{}),...Object.keys(s.optionalDependencies??{}))}}const p=[".cjs",".mjs",".js",".jsx",".json",".cts",".mts",".ts",".tsx"],l=r.join(u.fileURLToPath(r.dirname(r.dirname(import.meta.url))),"babel.config.mjs"),d=[b({delimiters:["",""],preventAssignment:!0,values:_(e,t)}),g(),x({deps:!0,devDeps:!1,peerDeps:!0,optDeps:!0,include:a.map((e=>new RegExp(`^${e}(?:\\/.+)?`))),exclude:s&&new RegExp(`^@?${s}(?:\\/.+)?`)}),h({extensions:p}),y(),w({moduleNames:e.keepImport?.map((e=>e.toString()))??[]})],m="app-node"===o||"functions"===o||!a.includes("@babel/runtime");return process.env.BUILDTS_USE_BABLE_RUNTIME=m?"":"1",d.push(f({configFile:l,extensions:p,babelHelpers:m?"bundled":"runtime",exclude:/^(.+\/)?node_modules\/.+$/}),...c.some((e=>e.preserveModules))?[S()]:[],k({include:["**/*.csv","**/*.txt"]})),e.minify&&d.push(j({compress:{directives:!1}})),d.push(v({summaryOnly:!0})),d}async function W(e){const o=$.findConfigFile(e,$.sys.fileExists);if(!o)throw new Error(`Failed to find tsconfig.json in ${e}.`);const n=[];let s=r.join("dist",r.basename(e),"src");if(i.existsSync(s)){const o=await i.promises.readdir(r.dirname(e),{withFileTypes:!0});e=r.resolve(e);for(const s of o){if(!s.isDirectory())continue;const o=r.resolve(s.path,s.name);if(o===e)continue;const t=$.findConfigFile(o,$.sys.fileExists),c=r.join("dist",s.name,"src");t&&i.existsSync(c)&&n.push([o,t,c])}}else s="dist";n.push([e,o,s]);let t=!0;for(const[o,s,i]of n)t&&=P(o,s,r.join(e,i));return t}function P(e,o,n){const{config:s}=$.readConfigFile(o,$.sys.readFile);s.compilerOptions={...s.compilerOptions,declaration:!0,emitDeclarationOnly:!0,noEmit:!1,noEmitOnError:!0,outDir:n},s.include=["src/**/*"];const{errors:t,fileNames:i,options:r}=$.parseJsonConfigFileContent(s,$.sys,e),c=$.createProgram({options:r,rootNames:i,configFileParsingDiagnostics:t}),{diagnostics:a,emitSkipped:p}=c.emit(),l=[...$.getPreEmitDiagnostics(c),...a,...t];if(l.length>0){const e={getCanonicalFileName:e=>e,getCurrentDirectory:$.sys.getCurrentDirectory,getNewLine:()=>$.sys.newLine},o=$.formatDiagnostics(l,e);console.warn(o)}return!p}const U={command:"app [package]",describe:"Build an app",builder:B,handler:async e=>M(e,"app")},J={command:"functions [package]",describe:"Build a GCP/Firebase functions app",builder:C,async handler(e){if(!e.onlyPackageJson)return M(e,"functions");{const o=r.resolve(e.package?.toString()??"."),[n,s]=await F(o);n||(console.error(`Failed to parse package.json (${s}).`),process.exit(1)),await H(o,n,e.moduleType)}}},G={command:"lib [package]",describe:"Build a Node.js / React library",builder:A,handler:async e=>M(e,"lib")};async function M(e,o){process.env.NODE_ENV||="production";const n=!e.silent&&e.verbose,s=process.cwd(),t=r.resolve(e.package?.toString()??"."),[u,f]=await F(t);u||(console.error(`Failed to parse package.json (${f}).`),process.exit(1)),T(e,t);const y=function(e,o,n){if(e.input&&e.input.length>0)return e.input.map((e=>r.join(o,e.toString())));const s=r.join(n,"src");for(const e of["ts","tsx","cts","mts"]){const o=r.join(s,`index.${e}`);if(i.existsSync(o))return[o]}console.error("Failed to detect input file."),process.exit(1)}(e,s,t),g=function(e,o){switch(e){case"app":return"app-node";case"functions":return"functions";case"lib":return o.some((e=>e.endsWith(".tsx")))?"lib-react":"lib";default:console.error("target option must be one of: "+N.join(", ")),process.exit(1)}}(o,y);n&&console.info("Target (Category):",`${g} (${o})`);const[h]=function(e){const o=e.name?.toString()||"",n=/@([^/]+)\/(.+)/.exec(o),[,s,t]=n||[];return[s,t]}(u),b="module"===u.type;e["core-js"]?process.env.BUILD_TS_COREJS="1":e["core-js-proposals"]&&(process.env.BUILD_TS_COREJS_WITH_PROPOSALS="1"),n&&(process.env.BUILD_TS_VERBOSE="1"),process.env.BUILD_TS_TARGET_CATEGORY=o,process.env.BUILD_TS_TARGET_DETAIL=g;const j=function(e,o,n,s){const t=r.join(n,"dist");if("app-node"===o||"functions"===o)return[{dir:t,format:V(s,e.moduleType)?"module":"commonjs",sourcemap:e.sourcemap}];const i=[],c=e.moduleType||"both",a=e.jsExtension||"either";("cjs"===c||"both"===c||"either"===c&&!s)&&i.push({dir:t,entryFileNames:"both"===a||"either"===a&&!s?"[name].js":"[name].cjs",format:"commonjs",preserveModules:!0,sourcemap:e.sourcemap});("esm"===c||"both"===c||"either"===c&&s)&&i.push({dir:t,entryFileNames:"both"===a||"either"===a&&s?"[name].js":"[name].mjs",format:"module",preserveModules:!0,sourcemap:e.sourcemap});return i}(e,g,t,b);n&&console.info("OutputOptions:",j),0===j.length&&(console.error("Failed to detect output files."),process.exit(1)),process.chdir(t),await i.promises.rm(r.join(t,"dist"),{recursive:!0,force:!0}),"functions"===g&&await H(t,u,e.moduleType);const v={input:"functions"===g?Object.fromEntries(y.map(((e,o)=>[0===o?"index":r.basename(e,r.extname(e)),e]))):y,plugins:I(e,g,u,h,t,j),watch:e.watch?{clearScreen:!1}:void 0},w=e=>(Array.isArray(e)?e:[e]).map((e=>r.relative(t,e)));if(e.watch)!function(e,o,n,s,t,i){const r=d({...s,output:t}),l=async e=>{process.removeListener("uncaughtException",l),process.stdin.removeListener("end",l),r&&await r.close(),e&&process.exit(e)};m(l),process.on("uncaughtException",l),process.stdin.isTTY||(process.stdin.on("end",l),process.stdin.resume());r.on("event",(async s=>{switch(s.code){case"ERROR":!function(e,o=!1){const n=e.name||e.cause?.name,s=n?`${n}: `:"",t=`${e.plugin?`(plugin ${e.plugin}) `:""}${s}${e.message}`,i=[c.bold(c.red(`[!] ${c.bold(t.toString())}`))];e.url&&i.push(c.cyan(e.url)),e.loc?i.push(`${e.loc.file||e.id} (${e.loc.line}:${e.loc.column})`):e.id&&i.push(e.id),e.frame&&i.push(c.dim(e.frame)),e.stack&&i.push(c.dim(e.stack?.replace(`${s}${e.message}\n`,""))),i.push("",""),console.error(i.join("\n")),o||E.exit(1)}(s.error,!0);break;case"BUNDLE_START":{if(e.silent)break;const o=s.input,t=[];"string"==typeof o?t.push(o):t.push(...Array.isArray(o)?o:Object.values(o)),console.info(c.cyan(`Bundles ${c.bold(i(t).join(", "))} → ${c.bold(i(s.output).join(", "))}\non ${n} ...`));break}case"BUNDLE_END":if(e.silent)break;console.info(c.green(`Created ${c.bold(i(s.output).join(", "))} in ${c.bold(p(s.duration))}`)),"app-node"!==o&&"functions"!==o&&await W(n);break;case"END":if(e.silent)break;console.info(`\n[${a()}] waiting for changes...`)}"result"in s&&s.result&&s.result.close()}))}(e,g,t,v,j,w);else{let o;e.silent||console.info(c.cyan(`Bundles ${c.bold(w(y).join(", "))} → ${c.bold(w(j.map((e=>e.file||e.dir||""))).join(", "))}\non ${t} ...`));let n=!1;try{const n=Date.now(),s=await l(v);o=s,await Promise.all(j.map((e=>s.write(e)))),e.silent||console.info(c.green(`Created ${w(j.map((e=>e.file||e.dir||""))).join(", ")} in ${c.bold(p(Date.now()-n))}`))}catch(e){n=!0,console.error("Failed to build due to:",e)}await(o?.close()),n&&process.exit(1),"app-node"===g||"functions"===g||await W(t)||process.exit(1)}}async function H(e,o,n){o.name+="-dist";const s="module"===o.type,t=V(s,n);o.main=s===t?"index.js":t?"index.mjs":"index.cjs",delete o.scripts,delete o.devDependencies,await i.promises.mkdir(r.join(e,"dist"),{recursive:!0}),await i.promises.writeFile(r.join(e,"dist","package.json"),JSON.stringify(o))}function V(e,o){return"esm"===o||(!o||"either"===o)&&e}const Y={command:"run <file>",describe:"Run script",builder:{...R,module:{description:"A module type: cjs or esm",type:"string",alias:"m"},watch:{description:"Whether watch mode is enabled or not",type:"boolean",alias:"w"}},async handler(e){T(e,process.cwd());const o=e.file?.toString()||"",n=[];e.watch&&n.push("--watch"),n.push("--import","tsx",o);const[,...s]=e._;e.verbose&&console.info(`Running 'node ${[...n,...s.map((e=>e.toString()))].join(" ")}'`);const t=D.spawnSync("node",[...n,...s.map((e=>e.toString()))],{stdio:"inherit",env:{...process.env,NODE_NO_WARNINGS:"1"}});process.exit(t.status??1)}};n(process.env),await s(t(process.argv)).scriptName("build-ts").options(R).command(U).command(J).command(G).command(Y).demandCommand().strict().help().argv;
1
+ import{readAndApplyEnvironmentVariables as e,yargsOptionsBuilderForEnv as o,removeNpmAndYarnEnvironmentVariables as n}from"@willbooster/shared-lib-node";import s from"yargs";import{hideBin as i}from"yargs/helpers";import t from"node:fs";import r from"node:path";import c from"chalk";import a from"date-time";import p from"pretty-ms";import{rollup as l,watch as d}from"rollup";import{onExit as m}from"signal-exit";import u from"node:url";import{babel as f}from"@rollup/plugin-babel";import y from"@rollup/plugin-commonjs";import g from"@rollup/plugin-json";import h from"@rollup/plugin-node-resolve";import b from"@rollup/plugin-replace";import j from"@rollup/plugin-terser";import v from"rollup-plugin-analyzer";import{keepImport as w}from"rollup-plugin-keep-import";import{nodeExternals as x}from"rollup-plugin-node-externals";import S from"rollup-plugin-preserve-directives";import{string as k}from"rollup-plugin-string";import E from"node:process";import $ from"typescript";import*as D from"node:child_process";let O;function T(o,n){return O||(O=e(o,n),o.verbose&&console.info("Loaded env vars:",Object.keys(O))),O}function _(e,o){const n={},s=new Set([...(e.inline??[]).flatMap((e=>e.toString().split(","))),...Object.keys(T(e,o))]);for(const e of s)void 0!==process.env[e]&&(n[`process.env.${e}`]=JSON.stringify(process.env[e]));return e.verbose&&console.info("Inline env vars:",Object.keys(n)),n}const N=["app","functions","lib"];async function F(e){const o=r.join(e,"package.json");try{const e=await t.promises.readFile(o,"utf8");return[JSON.parse(e),o]}catch{}return[void 0,o]}const R={...o,silent:{description:"Whether watch mode is enabled or not",type:"boolean",alias:"s"}},L={...R,input:{description:'Paths of source code files to be built. The first file is main. If no option is given, "src/index.{ts,tsx}" from package directory is targeted.',type:"array",alias:"i"},"core-js":{description:"Whether or not core-js is employed.",type:"boolean",default:!1},"core-js-proposals":{description:"Whether or not core-js with proposals support is employed.",type:"boolean",default:!1},minify:{description:"Whether or not minification is enabled.",type:"boolean",default:!0},sourcemap:{description:"Whether or not sourcemap is enabled.",type:"boolean",default:!0},external:{description:"Additional external dependencies.",type:"array"},inline:{description:"Environment variables to be inlined.",type:"array"},watch:{description:"Whether watch mode is enabled or not",type:"boolean",alias:"w"},keepImport:{description:"Identifiers to be kept as import statements.",type:"array"}},B={...L,moduleType:{description:"esm, cjs, or either (default).",type:"string",alias:"m"}},C={...B,onlyPackageJson:{description:"Whether to generate only package.json.",type:"boolean"}},A={...L,moduleType:{description:"esm, cjs, either, or both (default).",type:"string",alias:"m"},jsExtension:{description:"Whether to use .js in cjs and/or esm: either (default), both, or none.",type:"string",alias:"j"}};function I(e,o,n,s,i,c){const a=[...e.external??[]].map((e=>e.toString()));if(n.dependencies?.["@prisma/client"]&&a.push("prisma-client"),a.push(...Object.keys(n.dependencies??{}),...Object.keys(n.peerDependencies??{}),...Object.keys(n.optionalDependencies??{})),t.existsSync(r.join("..","..","package.json"))){const e=t.readdirSync(r.join(".."),{withFileTypes:!0});for(const o of e){if(!o.isDirectory())continue;const e=r.join("..",o.name,"package.json");if(!t.existsSync(e))continue;const s=JSON.parse(t.readFileSync(e,"utf8"));n.dependencies?.[s.name??""]&&a.push(...Object.keys(s.dependencies??{}),...Object.keys(s.peerDependencies??{}),...Object.keys(s.optionalDependencies??{}))}}const p=[".cjs",".mjs",".js",".jsx",".json",".cts",".mts",".ts",".tsx"],l=r.join(u.fileURLToPath(r.dirname(r.dirname(import.meta.url))),"babel.config.mjs"),d=[b({delimiters:["",""],preventAssignment:!0,values:_(e,i)}),g(),x({deps:!0,devDeps:!1,peerDeps:!0,optDeps:!0,include:a.map((e=>new RegExp(`^${e}(?:\\/.+)?`))),exclude:s&&new RegExp(`^@?${s}(?:\\/.+)?`)}),h({extensions:p}),y(),w({moduleNames:e.keepImport?.map((e=>e.toString()))??[]})],m="app-node"===o||"functions"===o||!a.includes("@babel/runtime");return process.env.BUILDTS_USE_BABLE_RUNTIME=m?"":"1",d.push(f({configFile:l,extensions:p,babelHelpers:m?"bundled":"runtime",exclude:/^(.+\/)?node_modules\/.+$/}),...c.some((e=>e.preserveModules))?[S()]:[],k({include:["**/*.csv","**/*.txt"]})),e.minify&&d.push(j({compress:{directives:!1}})),d.push(v({summaryOnly:!0})),d}async function W(e){const o=$.findConfigFile(e,$.sys.fileExists);if(!o)throw new Error(`Failed to find tsconfig.json in ${e}.`);const n=[];let s=r.join("dist",r.basename(e),"src");if(t.existsSync(s)){const o=await t.promises.readdir(r.dirname(e),{withFileTypes:!0});e=r.resolve(e);for(const s of o){if(!s.isDirectory())continue;const o=r.resolve(s.path,s.name);if(o===e)continue;const i=$.findConfigFile(o,$.sys.fileExists),c=r.join("dist",s.name,"src");i&&t.existsSync(c)&&n.push([o,i,c])}}else s="dist";n.push([e,o,s]);let i=!0;for(const[o,s,t]of n)i&&=P(o,s,r.join(e,t));return i}function P(e,o,n){const{config:s}=$.readConfigFile(o,$.sys.readFile);s.compilerOptions={...s.compilerOptions,declaration:!0,emitDeclarationOnly:!0,noEmit:!1,noEmitOnError:!0,outDir:n},s.include=["src/**/*"];const{errors:i,fileNames:t,options:r}=$.parseJsonConfigFileContent(s,$.sys,e),c=$.createProgram({options:r,rootNames:t,configFileParsingDiagnostics:i}),{diagnostics:a,emitSkipped:p}=c.emit(),l=[...$.getPreEmitDiagnostics(c),...a,...i];if(l.length>0){const e={getCanonicalFileName:e=>e,getCurrentDirectory:$.sys.getCurrentDirectory,getNewLine:()=>$.sys.newLine},o=$.formatDiagnostics(l,e);console.warn(o)}return!p}const U={command:"app [package]",describe:"Build an app",builder:B,handler:async e=>M(e,"app")},J={command:"functions [package]",describe:"Build a GCP/Firebase functions app",builder:C,async handler(e){if(!e.onlyPackageJson)return M(e,"functions");{const o=r.resolve(e.package?.toString()??"."),[n,s]=await F(o);n||(console.error(`Failed to parse package.json (${s}).`),process.exit(1)),await H(o,n,e.moduleType)}}},G={command:"lib [package]",describe:"Build a Node.js / React library",builder:A,handler:async e=>M(e,"lib")};async function M(e,o){process.env.NODE_ENV||="production";const n=!e.silent&&e.verbose,s=process.cwd(),i=r.resolve(e.package?.toString()??"."),[u,f]=await F(i);u||(console.error(`Failed to parse package.json (${f}).`),process.exit(1)),T(e,i);const y=function(e,o,n){if(e.input&&e.input.length>0)return e.input.map((e=>r.join(o,e.toString())));const s=r.join(n,"src");for(const e of["ts","tsx","cts","mts"]){const o=r.join(s,`index.${e}`);if(t.existsSync(o))return[o]}console.error("Failed to detect input file."),process.exit(1)}(e,s,i),g=function(e,o){switch(e){case"app":return"app-node";case"functions":return"functions";case"lib":return o.some((e=>e.endsWith(".tsx")))?"lib-react":"lib";default:console.error("target option must be one of: "+N.join(", ")),process.exit(1)}}(o,y);n&&console.info("Target (Category):",`${g} (${o})`);const[h]=function(e){const o=e.name?.toString()||"",n=/@([^/]+)\/(.+)/.exec(o),[,s,i]=n||[];return[s,i]}(u),b="module"===u.type;e["core-js"]?process.env.BUILD_TS_COREJS="1":e["core-js-proposals"]&&(process.env.BUILD_TS_COREJS_WITH_PROPOSALS="1"),n&&(process.env.BUILD_TS_VERBOSE="1"),process.env.BUILD_TS_TARGET_CATEGORY=o,process.env.BUILD_TS_TARGET_DETAIL=g;const j=function(e,o,n,s){const i=r.join(n,"dist");if("app-node"===o||"functions"===o)return[{dir:i,format:V(s,e.moduleType)?"module":"commonjs",sourcemap:e.sourcemap}];const t=[],c=e.moduleType||"both",a=e.jsExtension||"either";("cjs"===c||"both"===c||"either"===c&&!s)&&t.push({dir:i,entryFileNames:"both"===a||"either"===a&&!s?"[name].js":"[name].cjs",format:"commonjs",preserveModules:!0,sourcemap:e.sourcemap});("esm"===c||"both"===c||"either"===c&&s)&&t.push({dir:i,entryFileNames:"both"===a||"either"===a&&s?"[name].js":"[name].mjs",format:"module",preserveModules:!0,sourcemap:e.sourcemap});return t}(e,g,i,b);n&&console.info("OutputOptions:",j),0===j.length&&(console.error("Failed to detect output files."),process.exit(1)),process.chdir(i),await t.promises.rm(r.join(i,"dist"),{recursive:!0,force:!0}),"functions"===g&&await H(i,u,e.moduleType);const v={input:"functions"===g?Object.fromEntries(y.map(((e,o)=>[0===o?"index":r.basename(e,r.extname(e)),e]))):y,plugins:I(e,g,u,h,i,j),watch:e.watch?{clearScreen:!1}:void 0},w=e=>(Array.isArray(e)?e:[e]).map((e=>r.relative(i,e)));if(e.watch)!function(e,o,n,s,i,t){const r=d({...s,output:i}),l=async e=>{process.removeListener("uncaughtException",l),process.stdin.removeListener("end",l),r&&await r.close(),e&&process.exit(e)};m(l),process.on("uncaughtException",l),process.stdin.isTTY||(process.stdin.on("end",l),process.stdin.resume());r.on("event",(async s=>{switch(s.code){case"ERROR":!function(e,o=!1){const n=e.name||e.cause?.name,s=n?`${n}: `:"",i=`${e.plugin?`(plugin ${e.plugin}) `:""}${s}${e.message}`,t=[c.bold(c.red(`[!] ${c.bold(i.toString())}`))];e.url&&t.push(c.cyan(e.url)),e.loc?t.push(`${e.loc.file||e.id} (${e.loc.line}:${e.loc.column})`):e.id&&t.push(e.id),e.frame&&t.push(c.dim(e.frame)),e.stack&&t.push(c.dim(e.stack?.replace(`${s}${e.message}\n`,""))),t.push("",""),console.error(t.join("\n")),o||E.exit(1)}(s.error,!0);break;case"BUNDLE_START":{if(e.silent)break;const o=s.input,i=[];"string"==typeof o?i.push(o):i.push(...Array.isArray(o)?o:Object.values(o)),console.info(c.cyan(`Bundles ${c.bold(t(i).join(", "))} → ${c.bold(t(s.output).join(", "))}\non ${n} ...`));break}case"BUNDLE_END":if(e.silent)break;console.info(c.green(`Created ${c.bold(t(s.output).join(", "))} in ${c.bold(p(s.duration))}`)),"app-node"!==o&&"functions"!==o&&await W(n);break;case"END":if(e.silent)break;console.info(`\n[${a()}] waiting for changes...`)}"result"in s&&s.result&&s.result.close()}))}(e,g,i,v,j,w);else{let o;e.silent||console.info(c.cyan(`Bundles ${c.bold(w(y).join(", "))} → ${c.bold(w(j.map((e=>e.file||e.dir||""))).join(", "))}\non ${i} ...`));let n=!1;try{const n=Date.now(),s=await l(v);o=s,await Promise.all(j.map((e=>s.write(e)))),e.silent||console.info(c.green(`Created ${w(j.map((e=>e.file||e.dir||""))).join(", ")} in ${c.bold(p(Date.now()-n))}`))}catch(e){n=!0,console.error("Failed to build due to:",e)}await(o?.close()),n&&process.exit(1),"app-node"===g||"functions"===g||await W(i)||process.exit(1)}}async function H(e,o,n){o.name+="-dist";const s="module"===o.type,i=V(s,n);o.main=s===i?"index.js":i?"index.mjs":"index.cjs",delete o.scripts,delete o.devDependencies,await t.promises.mkdir(r.join(e,"dist"),{recursive:!0}),await t.promises.writeFile(r.join(e,"dist","package.json"),JSON.stringify(o))}function V(e,o){return"esm"===o||(!o||"either"===o)&&e}const Y={command:"run <file>",describe:"Run script",builder:{...R,module:{description:"A module type: cjs or esm",type:"string",alias:"m"},watch:{description:"Whether watch mode is enabled or not",type:"boolean",alias:"w"}},async handler(e){T(e,process.cwd());const o=["--no-warnings","--import","tsx",e.file?.toString()||""];e.watch&&o.push("--watch");const[,...n]=e._;e.verbose&&console.info(`Running 'node ${[...o,...n.map((e=>e.toString()))].join(" ")}'`);const s=D.spawnSync("node",[...o,...n.map((e=>e.toString()))],{stdio:"inherit",env:{...process.env,NODE_NO_WARNINGS:"1"}});process.exit(s.status??1)}};n(process.env),await s(i(process.argv)).scriptName("build-ts").options(R).command(U).command(J).command(G).command(Y).demandCommand().strict().help().argv;
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/env.ts","../src/types.ts","../src/utils.ts","../src/sharedOptionsBuilder.ts","../src/commands/build/builder.ts","../src/commands/build/plugin.ts","../src/commands/build/typeScript.ts","../src/commands/build/build.ts","../src/commands/build/rollupLogger.ts","../src/commands/run.ts","../src/index.ts"],"sourcesContent":["import { readAndApplyEnvironmentVariables } from '@willbooster/shared-lib-node';\n\nimport type { builder } from './commands/build/builder.js';\nimport type { sharedOptionsBuilder } from './sharedOptionsBuilder.js';\nimport type { ArgumentsType } from './types.js';\n\nlet envVars: Record<string, string | undefined> | undefined;\n\n/**\n * This function loads environment variables from `.env` files.\n * */\nexport function loadEnvironmentVariablesWithCache(\n argv: ArgumentsType<typeof sharedOptionsBuilder>,\n cwd: string\n): Record<string, string | undefined> {\n if (!envVars) {\n envVars = readAndApplyEnvironmentVariables(argv, cwd);\n if (argv.verbose) {\n console.info('Loaded env vars:', Object.keys(envVars));\n }\n }\n return envVars;\n}\n\n/**\n * This function creates a definition of environment variables that will be injected into the build.\n * */\nexport function createEnvironmentVariablesDefinition(\n argv: ArgumentsType<typeof builder>,\n cwd: string\n): Record<string, string> {\n const envVarsDef: Record<string, string> = {};\n const names = new Set([\n ...(argv.inline ?? []).flatMap((e) => e.toString().split(',')),\n ...Object.keys(loadEnvironmentVariablesWithCache(argv, cwd)),\n ]);\n for (const name of names) {\n if (process.env[name] === undefined) continue;\n\n envVarsDef[`process.env.${name}`] = JSON.stringify(process.env[name]);\n }\n if (argv.verbose) {\n console.info('Inline env vars:', Object.keys(envVarsDef));\n }\n return envVarsDef;\n}\n","import type { ArgumentsCamelCase, InferredOptionTypes, Options } from 'yargs';\n\nexport const allTargetCategories = ['app', 'functions', 'lib'] as const;\n\nexport type TargetCategory = (typeof allTargetCategories)[number];\n\nexport const allTargetDetails = ['app-node', 'functions', 'lib', 'lib-react'] as const;\n\nexport type TargetDetail = (typeof allTargetDetails)[number];\n\nexport type ArgumentsType<T extends { [key: string]: Options }> = ArgumentsCamelCase<InferredOptionTypes<T>>;\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport url from 'node:url';\n\nimport type { PackageJson } from 'type-fest';\n\nexport async function readPackageJson(dirPath: string): Promise<[PackageJson | undefined, string]> {\n const packageJsonPath = path.join(dirPath, 'package.json');\n try {\n const packageJsonText = await fs.promises.readFile(packageJsonPath, 'utf8');\n return [JSON.parse(packageJsonText) as PackageJson, packageJsonPath];\n } catch {\n // do nothing\n }\n return [undefined, packageJsonPath];\n}\n\nexport function getBuildTsRootPath(): string {\n return url.fileURLToPath(path.dirname(path.dirname(import.meta.url)));\n}\n\nexport function getNamespaceAndName(packageJson: PackageJson): [string | undefined, string | undefined] {\n const packageName = packageJson.name?.toString() || '';\n const match = /@([^/]+)\\/(.+)/.exec(packageName);\n const [, namespace, name] = match || [];\n return [namespace, name];\n}\n","import { yargsOptionsBuilderForEnv } from '@willbooster/shared-lib-node';\n\nexport const sharedOptionsBuilder = {\n ...yargsOptionsBuilderForEnv,\n silent: {\n description: 'Whether watch mode is enabled or not',\n type: 'boolean',\n alias: 's',\n },\n} as const;\n","import { sharedOptionsBuilder } from '../../sharedOptionsBuilder.js';\n\nexport const builder = {\n ...sharedOptionsBuilder,\n input: {\n description:\n 'Paths of source code files to be built. The first file is main. If no option is given, \"src/index.{ts,tsx}\" from package directory is targeted.',\n type: 'array',\n alias: 'i',\n },\n 'core-js': {\n description: 'Whether or not core-js is employed.',\n type: 'boolean',\n default: false,\n },\n 'core-js-proposals': {\n description: 'Whether or not core-js with proposals support is employed.',\n type: 'boolean',\n default: false,\n },\n minify: {\n description: 'Whether or not minification is enabled.',\n type: 'boolean',\n default: true,\n },\n sourcemap: {\n description: 'Whether or not sourcemap is enabled.',\n type: 'boolean',\n default: true,\n },\n external: {\n description: 'Additional external dependencies.',\n type: 'array',\n },\n inline: {\n description: 'Environment variables to be inlined.',\n type: 'array',\n },\n watch: {\n description: 'Whether watch mode is enabled or not',\n type: 'boolean',\n alias: 'w',\n },\n keepImport: {\n description: 'Identifiers to be kept as import statements.',\n type: 'array',\n },\n} as const;\n\nexport const appBuilder = {\n ...builder,\n moduleType: {\n description: 'esm, cjs, or either (default).',\n type: 'string',\n alias: 'm',\n },\n} as const;\n\nexport const functionsBuilder = {\n ...appBuilder,\n onlyPackageJson: {\n description: 'Whether to generate only package.json.',\n type: 'boolean',\n },\n} as const;\n\nexport const libBuilder = {\n ...builder,\n moduleType: {\n description: 'esm, cjs, either, or both (default).',\n type: 'string',\n alias: 'm',\n },\n // .js files in a package with `\"type\": \"module\"` are treated as esm.\n // However, we want to treat them as cjs in the case where a cjs project imports an esm package.\n // To deal with the case, we use .cjs and .mjs extensions instead of .js extension.\n jsExtension: {\n description: 'Whether to use .js in cjs and/or esm: either (default), both, or none.',\n type: 'string',\n alias: 'j',\n },\n} as const;\n\nexport type AnyBuilderType = typeof appBuilder | typeof functionsBuilder | typeof libBuilder;\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { babel } from '@rollup/plugin-babel';\nimport commonjs from '@rollup/plugin-commonjs';\nimport json from '@rollup/plugin-json';\nimport resolve from '@rollup/plugin-node-resolve';\nimport replace from '@rollup/plugin-replace';\nimport terser from '@rollup/plugin-terser';\nimport type { OutputOptions, Plugin } from 'rollup';\nimport analyze from 'rollup-plugin-analyzer';\nimport { keepImport } from 'rollup-plugin-keep-import';\nimport { nodeExternals } from 'rollup-plugin-node-externals';\nimport preserveDirectives from 'rollup-plugin-preserve-directives';\nimport { string } from 'rollup-plugin-string';\nimport type { PackageJson } from 'type-fest';\n\nimport { createEnvironmentVariablesDefinition } from '../../env.js';\nimport type { ArgumentsType, TargetDetail } from '../../types.js';\nimport { getBuildTsRootPath } from '../../utils.js';\n\nimport type { builder } from './builder.js';\n\nexport function setupPlugins(\n argv: ArgumentsType<typeof builder>,\n targetDetail: TargetDetail,\n packageJson: PackageJson,\n namespace: string | undefined,\n packageDirPath: string,\n outputOptionsList: OutputOptions[]\n): Plugin[] {\n const externalDeps = [...(argv.external ?? [])].map((item) => item.toString());\n if (packageJson.dependencies?.['@prisma/client']) {\n externalDeps.push('prisma-client');\n }\n // Since `deps: true` does not work for `import chunk from 'lodash.chunk/index.js';`\n externalDeps.push(\n ...Object.keys(packageJson.dependencies ?? {}),\n ...Object.keys(packageJson.peerDependencies ?? {}),\n ...Object.keys(packageJson.optionalDependencies ?? {})\n );\n // Add external dependencies from sibling packages\n if (fs.existsSync(path.join('..', '..', 'package.json'))) {\n const packageDirs = fs.readdirSync(path.join('..'), { withFileTypes: true });\n for (const packageDir of packageDirs) {\n if (!packageDir.isDirectory()) continue;\n\n const packageJsonPath = path.join('..', packageDir.name, 'package.json');\n if (!fs.existsSync(packageJsonPath)) continue;\n\n const otherPackageJson: PackageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));\n if (packageJson.dependencies?.[otherPackageJson.name ?? '']) {\n externalDeps.push(\n ...Object.keys(otherPackageJson.dependencies ?? {}),\n ...Object.keys(otherPackageJson.peerDependencies ?? {}),\n ...Object.keys(otherPackageJson.optionalDependencies ?? {})\n );\n }\n }\n }\n\n const extensions = ['.cjs', '.mjs', '.js', '.jsx', '.json', '.cts', '.mts', '.ts', '.tsx'];\n const babelConfigPath = path.join(getBuildTsRootPath(), 'babel.config.mjs');\n const plugins: Plugin[] = [\n replace({\n delimiters: ['', ''],\n preventAssignment: true,\n values: createEnvironmentVariablesDefinition(argv, packageDirPath),\n }),\n json(),\n nodeExternals({\n deps: true,\n devDeps: false,\n peerDeps: true,\n optDeps: true,\n include: externalDeps.map((name) => new RegExp(`^${name}(?:\\\\/.+)?`)),\n exclude: namespace && new RegExp(`^@?${namespace}(?:\\\\/.+)?`),\n }),\n resolve({ extensions }),\n commonjs(),\n keepImport({ moduleNames: argv.keepImport?.map((item) => item.toString()) ?? [] }),\n ];\n const isBabelHelpersBundled =\n targetDetail === 'app-node' || targetDetail === 'functions' || !externalDeps.includes('@babel/runtime');\n process.env.BUILDTS_USE_BABLE_RUNTIME = isBabelHelpersBundled ? '' : '1';\n plugins.push(\n babel({\n configFile: babelConfigPath,\n extensions,\n // We need `runtime since `bundled` may break directory structure by creating _virtual directory.\n babelHelpers: isBabelHelpersBundled ? 'bundled' : 'runtime',\n exclude: /^(.+\\/)?node_modules\\/.+$/,\n }),\n ...(outputOptionsList.some((opts) => opts.preserveModules) ? [preserveDirectives()] : []),\n string({ include: ['**/*.csv', '**/*.txt'] })\n );\n if (argv.minify) {\n plugins.push(terser({ compress: { directives: false } }));\n }\n plugins.push(analyze({ summaryOnly: true }));\n return plugins;\n}\n","/* eslint-disable import/no-named-as-default-member */\n\n// We cannot use named imports from 'typescript' because of build errors.\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport ts from 'typescript';\n\nexport async function generateDeclarationFiles(coreProjectDirPath: string): Promise<boolean> {\n const coreConfigFile = ts.findConfigFile(coreProjectDirPath, ts.sys.fileExists);\n if (!coreConfigFile) throw new Error(`Failed to find tsconfig.json in ${coreProjectDirPath}.`);\n\n const projects: [string, string, string][] = [];\n let outDir = path.join('dist', path.basename(coreProjectDirPath), 'src');\n if (fs.existsSync(outDir)) {\n const dirents = await fs.promises.readdir(path.dirname(coreProjectDirPath), { withFileTypes: true });\n coreProjectDirPath = path.resolve(coreProjectDirPath);\n for (const dirent of dirents) {\n if (!dirent.isDirectory()) continue;\n\n const projectDirPath = path.resolve(dirent.path, dirent.name);\n if (projectDirPath === coreProjectDirPath) continue;\n\n const configFile = ts.findConfigFile(projectDirPath, ts.sys.fileExists);\n const outDir = path.join('dist', dirent.name, 'src');\n if (configFile && fs.existsSync(outDir)) {\n projects.push([projectDirPath, configFile, outDir]);\n }\n }\n } else {\n outDir = 'dist';\n }\n projects.push([coreProjectDirPath, coreConfigFile, outDir]);\n\n let allSucceeded = true;\n for (const [projectDirPath, configFile, outDir] of projects) {\n allSucceeded &&= runTypeScriptCompiler(projectDirPath, configFile, path.join(coreProjectDirPath, outDir));\n }\n return allSucceeded;\n}\n\nfunction runTypeScriptCompiler(projectDirPath: string, configFile: string, outDir: string): boolean {\n const { config } = ts.readConfigFile(configFile, ts.sys.readFile);\n config.compilerOptions = {\n ...config.compilerOptions,\n declaration: true,\n emitDeclarationOnly: true,\n noEmit: false,\n noEmitOnError: true,\n outDir,\n };\n config.include = ['src/**/*'];\n const { errors, fileNames, options } = ts.parseJsonConfigFileContent(config, ts.sys, projectDirPath);\n\n const program = ts.createProgram({ options, rootNames: fileNames, configFileParsingDiagnostics: errors });\n const { diagnostics, emitSkipped } = program.emit();\n\n const allDiagnostics = [...ts.getPreEmitDiagnostics(program), ...diagnostics, ...errors];\n if (allDiagnostics.length > 0) {\n const formatHost: ts.FormatDiagnosticsHost = {\n getCanonicalFileName: (path) => path,\n getCurrentDirectory: ts.sys.getCurrentDirectory,\n getNewLine: () => ts.sys.newLine,\n };\n const message = ts.formatDiagnostics(allDiagnostics, formatHost);\n console.warn(message);\n }\n return !emitSkipped;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nimport chalk from 'chalk';\nimport dateTime from 'date-time';\nimport ms from 'pretty-ms';\nimport type { OutputOptions, RollupBuild, RollupOptions } from 'rollup';\nimport { rollup, watch } from 'rollup';\nimport type { Handler } from 'signal-exit';\nimport { onExit } from 'signal-exit';\nimport type { PackageJson } from 'type-fest';\nimport type { CommandModule } from 'yargs';\n\nimport { loadEnvironmentVariablesWithCache } from '../../env.js';\nimport type { ArgumentsType, TargetCategory, TargetDetail } from '../../types.js';\nimport { allTargetCategories } from '../../types.js';\nimport { getNamespaceAndName, readPackageJson } from '../../utils.js';\n\nimport type { AnyBuilderType, builder } from './builder.js';\nimport { appBuilder, functionsBuilder, libBuilder } from './builder.js';\nimport { setupPlugins } from './plugin.js';\nimport { handleError } from './rollupLogger.js';\nimport { generateDeclarationFiles } from './typeScript.js';\n\nexport const app: CommandModule<unknown, ArgumentsType<typeof appBuilder>> = {\n command: 'app [package]',\n describe: 'Build an app',\n builder: appBuilder,\n async handler(argv) {\n return build(argv, 'app');\n },\n};\n\nexport const functions: CommandModule<unknown, ArgumentsType<typeof functionsBuilder>> = {\n command: 'functions [package]',\n describe: 'Build a GCP/Firebase functions app',\n builder: functionsBuilder,\n async handler(argv) {\n if (argv.onlyPackageJson) {\n const packageDirPath = path.resolve(argv.package?.toString() ?? '.');\n const [packageJson, packageJsonPath] = await readPackageJson(packageDirPath);\n if (!packageJson) {\n console.error(`Failed to parse package.json (${packageJsonPath}).`);\n process.exit(1);\n }\n await generatePackageJsonForFunctions(packageDirPath, packageJson, argv.moduleType);\n } else {\n return build(argv, 'functions');\n }\n },\n};\n\nexport const lib: CommandModule<unknown, ArgumentsType<typeof libBuilder>> = {\n command: 'lib [package]',\n describe: 'Build a Node.js / React library',\n builder: libBuilder,\n async handler(argv) {\n return build(argv, 'lib');\n },\n};\n\nexport async function build(argv: ArgumentsType<AnyBuilderType>, targetCategory: TargetCategory): Promise<void> {\n process.env.NODE_ENV ||= 'production';\n\n // `silent` is stronger than `verbose`.\n const verbose = !argv.silent && argv.verbose;\n const cwd = process.cwd();\n\n const packageDirPath = path.resolve(argv.package?.toString() ?? '.');\n const [packageJson, packageJsonPath] = await readPackageJson(packageDirPath);\n if (!packageJson) {\n console.error(`Failed to parse package.json (${packageJsonPath}).`);\n process.exit(1);\n }\n\n loadEnvironmentVariablesWithCache(argv, packageDirPath);\n\n const inputs = verifyInput(argv, cwd, packageDirPath);\n const targetDetail = detectTargetDetail(targetCategory, inputs);\n\n if (verbose) {\n console.info('Target (Category):', `${targetDetail} (${targetCategory})`);\n }\n\n const [namespace] = getNamespaceAndName(packageJson);\n const isEsmPackage = packageJson.type === 'module';\n\n if (argv['core-js']) {\n process.env.BUILD_TS_COREJS = '1';\n } else if (argv['core-js-proposals']) {\n process.env.BUILD_TS_COREJS_WITH_PROPOSALS = '1';\n }\n\n if (verbose) {\n process.env.BUILD_TS_VERBOSE = '1';\n }\n process.env.BUILD_TS_TARGET_CATEGORY = targetCategory;\n process.env.BUILD_TS_TARGET_DETAIL = targetDetail;\n\n const outputOptionsList = getOutputOptionsList(argv, targetDetail, packageDirPath, isEsmPackage);\n if (verbose) {\n console.info('OutputOptions:', outputOptionsList);\n }\n if (outputOptionsList.length === 0) {\n console.error('Failed to detect output files.');\n process.exit(1);\n }\n\n process.chdir(packageDirPath);\n await fs.promises.rm(path.join(packageDirPath, 'dist'), { recursive: true, force: true });\n if (targetDetail === 'functions') {\n await generatePackageJsonForFunctions(packageDirPath, packageJson, argv.moduleType);\n }\n\n const options: RollupOptions = {\n input:\n targetDetail === 'functions'\n ? Object.fromEntries(\n inputs.map((input, index) => [index === 0 ? 'index' : path.basename(input, path.extname(input)), input])\n )\n : inputs,\n plugins: setupPlugins(argv, targetDetail, packageJson, namespace, packageDirPath, outputOptionsList),\n watch: argv.watch ? { clearScreen: false } : undefined,\n };\n\n const pathToRelativePath = (paths: string | Readonly<string[]>): string[] =>\n (Array.isArray(paths) ? paths : [paths]).map((p) => path.relative(packageDirPath, p));\n if (argv.watch) {\n watchRollup(argv, targetDetail, packageDirPath, options, outputOptionsList, pathToRelativePath);\n } else {\n if (!argv.silent) {\n console.info(\n chalk.cyan(\n `Bundles ${chalk.bold(pathToRelativePath(inputs).join(', '))} → ${chalk.bold(\n pathToRelativePath(outputOptionsList.map((opts) => opts.file || opts.dir || '')).join(', ')\n )}\\non ${packageDirPath} ...`\n )\n );\n }\n\n let bundle: RollupBuild | undefined;\n let buildFailed = false;\n try {\n const startTime = Date.now();\n const _bundle = await rollup(options);\n bundle = _bundle;\n await Promise.all(outputOptionsList.map((opts) => _bundle.write(opts)));\n\n if (!argv.silent) {\n console.info(\n chalk.green(\n `Created ${pathToRelativePath(outputOptionsList.map((opts) => opts.file || opts.dir || '')).join(\n ', '\n )} in ${chalk.bold(ms(Date.now() - startTime))}`\n )\n );\n }\n } catch (error) {\n buildFailed = true;\n console.error('Failed to build due to:', error);\n }\n await bundle?.close();\n if (buildFailed) process.exit(1);\n\n if (\n targetDetail !== 'app-node' &&\n targetDetail !== 'functions' &&\n !(await generateDeclarationFiles(packageDirPath))\n ) {\n process.exit(1);\n }\n }\n}\n\nfunction watchRollup(\n argv: ArgumentsType<AnyBuilderType>,\n targetDetail: string,\n packageDirPath: string,\n options: RollupOptions,\n outputOptionsList: OutputOptions[],\n pathToRelativePath: (paths: string | Readonly<string[]>) => string[]\n): void {\n const watcher = watch({ ...options, output: outputOptionsList });\n\n const close = async (code: number | null | undefined): Promise<void> => {\n process.removeListener('uncaughtException', close);\n process.stdin.removeListener('end', close);\n if (watcher) await watcher.close();\n if (code) process.exit(code);\n };\n onExit(close as unknown as Handler);\n process.on('uncaughtException', close);\n if (!process.stdin.isTTY) {\n process.stdin.on('end', close);\n process.stdin.resume();\n }\n\n watcher.on('event', async (event) => {\n switch (event.code) {\n case 'ERROR': {\n handleError(event.error, true);\n break;\n }\n case 'BUNDLE_START': {\n if (argv.silent) break;\n\n const eventInput = event.input;\n const inputFiles: string[] = [];\n if (typeof eventInput === 'string') {\n inputFiles.push(eventInput);\n } else {\n inputFiles.push(\n ...(Array.isArray(eventInput) ? eventInput : Object.values(eventInput as Record<string, string>))\n );\n }\n console.info(\n chalk.cyan(\n `Bundles ${chalk.bold(pathToRelativePath(inputFiles).join(', '))} → ${chalk.bold(\n pathToRelativePath(event.output).join(', ')\n )}\\non ${packageDirPath} ...`\n )\n );\n break;\n }\n case 'BUNDLE_END': {\n if (argv.silent) break;\n\n console.info(\n chalk.green(\n `Created ${chalk.bold(pathToRelativePath(event.output).join(', '))} in ${chalk.bold(ms(event.duration))}`\n )\n );\n\n if (targetDetail !== 'app-node' && targetDetail !== 'functions') {\n await generateDeclarationFiles(packageDirPath);\n }\n break;\n }\n case 'END': {\n if (argv.silent) break;\n\n console.info(`\\n[${dateTime()}] waiting for changes...`);\n break;\n }\n }\n\n if ('result' in event && event.result) {\n void event.result.close();\n }\n });\n}\n\nfunction verifyInput(argv: ArgumentsType<typeof builder>, cwd: string, packageDirPath: string): string[] {\n if (argv.input && argv.input.length > 0) return argv.input.map((p) => path.join(cwd, p.toString()));\n\n const srcDirPath = path.join(packageDirPath, 'src');\n for (const ext of ['ts', 'tsx', 'cts', 'mts']) {\n const input = path.join(srcDirPath, `index.${ext}`);\n if (fs.existsSync(input)) return [input];\n }\n\n console.error('Failed to detect input file.');\n process.exit(1);\n}\n\nfunction detectTargetDetail(targetCategory: string, inputs: string[]): TargetDetail {\n switch (targetCategory) {\n case 'app': {\n return 'app-node';\n }\n case 'functions': {\n return 'functions';\n }\n case 'lib': {\n if (inputs.some((input) => input.endsWith('.tsx'))) {\n return 'lib-react';\n }\n return 'lib';\n }\n default: {\n console.error('target option must be one of: ' + allTargetCategories.join(', '));\n process.exit(1);\n }\n }\n}\n\nasync function generatePackageJsonForFunctions(\n packageDirPath: string,\n packageJson: PackageJson,\n moduleType: string | undefined\n): Promise<void> {\n packageJson.name += '-dist';\n const esmPackage = packageJson.type === 'module';\n const esmOutput = isEsmOutput(esmPackage, moduleType);\n packageJson.main = esmPackage === esmOutput ? 'index.js' : esmOutput ? 'index.mjs' : 'index.cjs';\n\n // Prevent Firebase Functions from running `build` script since we are building code before deploying.\n delete packageJson.scripts;\n // devDependencies are not required since we are building code before deploying.\n delete packageJson.devDependencies;\n\n await fs.promises.mkdir(path.join(packageDirPath, 'dist'), { recursive: true });\n await fs.promises.writeFile(path.join(packageDirPath, 'dist', 'package.json'), JSON.stringify(packageJson));\n}\n\nfunction getOutputOptionsList(\n argv: ArgumentsType<AnyBuilderType>,\n targetDetail: string,\n packageDirPath: string,\n isEsmPackage: boolean\n): OutputOptions[] {\n const outDirPath = path.join(packageDirPath, 'dist');\n if (targetDetail === 'app-node' || targetDetail === 'functions') {\n return [\n {\n dir: outDirPath,\n format: isEsmOutput(isEsmPackage, argv.moduleType) ? 'module' : 'commonjs',\n sourcemap: argv.sourcemap,\n },\n ];\n }\n\n // The following import statement in an esm module causes the following error:\n // Statement:\n // import { usePrevious } from 'react-use';\n // Error:\n // Named export 'usePrevious' not found. The requested module 'react-use' is a CommonJS module,\n // which may not support all module.exports as named exports.\n // We need cjs modules for web apps to avoid the error.\n // Also, splitting a library is useful in both modules, so preserveModules should be true.\n const outputOptionsList: OutputOptions[] = [];\n const moduleType = argv.moduleType || 'both';\n const jsExt = argv.jsExtension || 'either';\n if (moduleType === 'cjs' || moduleType === 'both' || (moduleType === 'either' && !isEsmPackage)) {\n outputOptionsList.push({\n dir: outDirPath,\n entryFileNames: jsExt === 'both' || (jsExt === 'either' && !isEsmPackage) ? '[name].js' : '[name].cjs',\n format: 'commonjs',\n preserveModules: true,\n sourcemap: argv.sourcemap,\n });\n }\n if (moduleType === 'esm' || moduleType === 'both' || (moduleType === 'either' && isEsmPackage)) {\n outputOptionsList.push({\n dir: outDirPath,\n entryFileNames: jsExt === 'both' || (jsExt === 'either' && isEsmPackage) ? '[name].js' : '[name].mjs',\n format: 'module',\n preserveModules: true,\n sourcemap: argv.sourcemap,\n });\n }\n return outputOptionsList;\n}\n\nfunction isEsmOutput(isEsmPackage: boolean, moduleType: string | undefined): boolean {\n return moduleType === 'esm' || ((!moduleType || moduleType === 'either') && isEsmPackage);\n}\n","import process from 'node:process';\n\nimport chalk from 'chalk';\nimport type { RollupError } from 'rollup';\n\nexport function handleError(error: RollupError, recover = false): void {\n const name = error.name || (error.cause as Error)?.name;\n const nameSection = name ? `${name}: ` : '';\n const pluginSection = error.plugin ? `(plugin ${error.plugin}) ` : '';\n const message = `${pluginSection}${nameSection}${error.message}`;\n\n const outputLines = [chalk.bold(chalk.red(`[!] ${chalk.bold(message.toString())}`))];\n\n if (error.url) {\n outputLines.push(chalk.cyan(error.url));\n }\n\n if (error.loc) {\n outputLines.push(`${error.loc.file || error.id} (${error.loc.line}:${error.loc.column})`);\n } else if (error.id) {\n outputLines.push(error.id);\n }\n\n if (error.frame) {\n outputLines.push(chalk.dim(error.frame));\n }\n\n if (error.stack) {\n outputLines.push(chalk.dim(error.stack?.replace(`${nameSection}${error.message}\\n`, '')));\n }\n\n outputLines.push('', '');\n console.error(outputLines.join('\\n'));\n\n if (!recover) process.exit(1);\n}\n","import * as child_process from 'node:child_process';\n\nimport type { CommandModule, InferredOptionTypes } from 'yargs';\n\nimport { loadEnvironmentVariablesWithCache } from '../env.js';\nimport { sharedOptionsBuilder } from '../sharedOptionsBuilder.js';\n\nconst builder = {\n ...sharedOptionsBuilder,\n module: {\n description: 'A module type: cjs or esm',\n type: 'string',\n alias: 'm',\n },\n watch: {\n description: 'Whether watch mode is enabled or not',\n type: 'boolean',\n alias: 'w',\n },\n} as const;\n\nexport const run: CommandModule<unknown, InferredOptionTypes<typeof builder>> = {\n command: 'run <file>',\n describe: 'Run script',\n builder,\n async handler(argv) {\n loadEnvironmentVariablesWithCache(argv, process.cwd());\n\n const file = argv.file?.toString() || '';\n\n const args: string[] = [];\n if (argv.watch) {\n args.push('--watch');\n }\n args.push('--import', 'tsx', file);\n const [, ...additionalArguments] = argv._;\n if (argv.verbose) {\n console.info(`Running 'node ${[...args, ...additionalArguments.map((arg) => arg.toString())].join(' ')}'`);\n }\n const ret = child_process.spawnSync('node', [...args, ...additionalArguments.map((arg) => arg.toString())], {\n stdio: 'inherit',\n env: { ...process.env, NODE_NO_WARNINGS: '1' },\n });\n process.exit(ret.status ?? 1);\n },\n};\n","import { removeNpmAndYarnEnvironmentVariables } from '@willbooster/shared-lib-node';\nimport yargs from 'yargs';\nimport { hideBin } from 'yargs/helpers';\n\nimport { app, functions, lib } from './commands/build/build.js';\nimport { run } from './commands/run.js';\nimport { sharedOptionsBuilder } from './sharedOptionsBuilder.js';\n\nremoveNpmAndYarnEnvironmentVariables(process.env);\n\nawait yargs(hideBin(process.argv))\n .scriptName('build-ts')\n .options(sharedOptionsBuilder)\n .command(app)\n .command(functions)\n .command(lib)\n .command(run)\n .demandCommand()\n .strict()\n .help().argv;\n"],"names":["envVars","loadEnvironmentVariablesWithCache","argv","cwd","readAndApplyEnvironmentVariables","verbose","console","info","Object","keys","createEnvironmentVariablesDefinition","envVarsDef","names","Set","inline","flatMap","e","toString","split","name","undefined","process","env","JSON","stringify","allTargetCategories","async","readPackageJson","dirPath","packageJsonPath","path","join","packageJsonText","fs","promises","readFile","parse","sharedOptionsBuilder","yargsOptionsBuilderForEnv","silent","description","type","alias","builder","input","default","minify","sourcemap","external","watch","keepImport","appBuilder","moduleType","functionsBuilder","onlyPackageJson","libBuilder","jsExtension","setupPlugins","targetDetail","packageJson","namespace","packageDirPath","outputOptionsList","externalDeps","map","item","dependencies","push","peerDependencies","optionalDependencies","existsSync","packageDirs","readdirSync","withFileTypes","packageDir","isDirectory","otherPackageJson","readFileSync","extensions","babelConfigPath","url","fileURLToPath","dirname","plugins","replace","delimiters","preventAssignment","values","json","nodeExternals","deps","devDeps","peerDeps","optDeps","include","RegExp","exclude","resolve","commonjs","moduleNames","isBabelHelpersBundled","includes","BUILDTS_USE_BABLE_RUNTIME","babel","configFile","babelHelpers","some","opts","preserveModules","preserveDirectives","string","terser","compress","directives","analyze","summaryOnly","generateDeclarationFiles","coreProjectDirPath","coreConfigFile","ts","findConfigFile","sys","fileExists","Error","projects","outDir","basename","dirents","readdir","dirent","projectDirPath","allSucceeded","runTypeScriptCompiler","config","readConfigFile","compilerOptions","declaration","emitDeclarationOnly","noEmit","noEmitOnError","errors","fileNames","options","parseJsonConfigFileContent","program","createProgram","rootNames","configFileParsingDiagnostics","diagnostics","emitSkipped","emit","allDiagnostics","getPreEmitDiagnostics","length","formatHost","getCanonicalFileName","getCurrentDirectory","getNewLine","newLine","message","formatDiagnostics","warn","app","command","describe","handler","build","functions","package","error","exit","generatePackageJsonForFunctions","lib","targetCategory","NODE_ENV","inputs","p","srcDirPath","ext","verifyInput","endsWith","detectTargetDetail","packageName","match","exec","getNamespaceAndName","isEsmPackage","BUILD_TS_COREJS","BUILD_TS_COREJS_WITH_PROPOSALS","BUILD_TS_VERBOSE","BUILD_TS_TARGET_CATEGORY","BUILD_TS_TARGET_DETAIL","outDirPath","dir","format","isEsmOutput","jsExt","entryFileNames","getOutputOptionsList","chdir","rm","recursive","force","fromEntries","index","extname","clearScreen","pathToRelativePath","paths","Array","isArray","relative","watcher","output","close","removeListener","stdin","code","onExit","on","isTTY","resume","event","recover","cause","nameSection","plugin","outputLines","chalk","bold","red","cyan","loc","file","id","line","column","frame","dim","stack","handleError","eventInput","inputFiles","green","ms","duration","dateTime","result","watchRollup","bundle","buildFailed","startTime","Date","now","_bundle","rollup","Promise","all","write","esmPackage","esmOutput","main","scripts","devDependencies","mkdir","writeFile","run","module","args","additionalArguments","_","arg","ret","child_process","spawnSync","stdio","NODE_NO_WARNINGS","status","removeNpmAndYarnEnvironmentVariables","yargs","hideBin","scriptName","demandCommand","strict","help"],"mappings":"s/BAMA,IAAIA,EAKG,SAASC,EACdC,EACAC,GAQA,OANKH,IACHA,EAAUI,EAAiCF,EAAMC,GAC7CD,EAAKG,SACPC,QAAQC,KAAK,mBAAoBC,OAAOC,KAAKT,KAG1CA,CACT,CAKO,SAASU,EACdR,EACAC,GAEA,MAAMQ,EAAqC,CAAA,EACrCC,EAAQ,IAAIC,IAAI,KAChBX,EAAKY,QAAU,IAAIC,SAASC,GAAMA,EAAEC,WAAWC,MAAM,UACtDV,OAAOC,KAAKR,EAAkCC,EAAMC,MAEzD,IAAK,MAAMgB,KAAQP,OACSQ,IAAtBC,QAAQC,IAAIH,KAEhBR,EAAY,eA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,OAAQ,IAAIN,KAASC,EAAoB7M,KAAK+M,GAAQA,EAAI9P,cAAc,CAC1GkQ,MAAO,UACP7P,IAAK,IAAKD,QAAQC,IAAK8P,iBAAkB,OAE3C/P,QAAQqJ,KAAKsG,EAAIK,QAAU,EAC7B,GCpCFC,EAAqCjQ,QAAQC,WAEvCiQ,EAAMC,EAAQnQ,QAAQnB,OACzBuR,WAAW,YACX3I,QAAQzG,GACR8H,QAAQD,GACRC,QAAQI,GACRJ,QAAQS,GACRT,QAAQuG,GACRgB,gBACAC,SACAC,OAAO1R"}
1
+ {"version":3,"file":"index.js","sources":["../src/env.ts","../src/types.ts","../src/utils.ts","../src/sharedOptionsBuilder.ts","../src/commands/build/builder.ts","../src/commands/build/plugin.ts","../src/commands/build/typeScript.ts","../src/commands/build/build.ts","../src/commands/build/rollupLogger.ts","../src/commands/run.ts","../src/index.ts"],"sourcesContent":["import { readAndApplyEnvironmentVariables } from '@willbooster/shared-lib-node';\n\nimport type { builder } from './commands/build/builder.js';\nimport type { sharedOptionsBuilder } from './sharedOptionsBuilder.js';\nimport type { ArgumentsType } from './types.js';\n\nlet envVars: Record<string, string | undefined> | undefined;\n\n/**\n * This function loads environment variables from `.env` files.\n * */\nexport function loadEnvironmentVariablesWithCache(\n argv: ArgumentsType<typeof sharedOptionsBuilder>,\n cwd: string\n): Record<string, string | undefined> {\n if (!envVars) {\n envVars = readAndApplyEnvironmentVariables(argv, cwd);\n if (argv.verbose) {\n console.info('Loaded env vars:', Object.keys(envVars));\n }\n }\n return envVars;\n}\n\n/**\n * This function creates a definition of environment variables that will be injected into the build.\n * */\nexport function createEnvironmentVariablesDefinition(\n argv: ArgumentsType<typeof builder>,\n cwd: string\n): Record<string, string> {\n const envVarsDef: Record<string, string> = {};\n const names = new Set([\n ...(argv.inline ?? []).flatMap((e) => e.toString().split(',')),\n ...Object.keys(loadEnvironmentVariablesWithCache(argv, cwd)),\n ]);\n for (const name of names) {\n if (process.env[name] === undefined) continue;\n\n envVarsDef[`process.env.${name}`] = JSON.stringify(process.env[name]);\n }\n if (argv.verbose) {\n console.info('Inline env vars:', Object.keys(envVarsDef));\n }\n return envVarsDef;\n}\n","import type { ArgumentsCamelCase, InferredOptionTypes, Options } from 'yargs';\n\nexport const allTargetCategories = ['app', 'functions', 'lib'] as const;\n\nexport type TargetCategory = (typeof allTargetCategories)[number];\n\nexport const allTargetDetails = ['app-node', 'functions', 'lib', 'lib-react'] as const;\n\nexport type TargetDetail = (typeof allTargetDetails)[number];\n\nexport type ArgumentsType<T extends { [key: string]: Options }> = ArgumentsCamelCase<InferredOptionTypes<T>>;\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport url from 'node:url';\n\nimport type { PackageJson } from 'type-fest';\n\nexport async function readPackageJson(dirPath: string): Promise<[PackageJson | undefined, string]> {\n const packageJsonPath = path.join(dirPath, 'package.json');\n try {\n const packageJsonText = await fs.promises.readFile(packageJsonPath, 'utf8');\n return [JSON.parse(packageJsonText) as PackageJson, packageJsonPath];\n } catch {\n // do nothing\n }\n return [undefined, packageJsonPath];\n}\n\nexport function getBuildTsRootPath(): string {\n return url.fileURLToPath(path.dirname(path.dirname(import.meta.url)));\n}\n\nexport function getNamespaceAndName(packageJson: PackageJson): [string | undefined, string | undefined] {\n const packageName = packageJson.name?.toString() || '';\n const match = /@([^/]+)\\/(.+)/.exec(packageName);\n const [, namespace, name] = match || [];\n return [namespace, name];\n}\n","import { yargsOptionsBuilderForEnv } from '@willbooster/shared-lib-node';\n\nexport const sharedOptionsBuilder = {\n ...yargsOptionsBuilderForEnv,\n silent: {\n description: 'Whether watch mode is enabled or not',\n type: 'boolean',\n alias: 's',\n },\n} as const;\n","import { sharedOptionsBuilder } from '../../sharedOptionsBuilder.js';\n\nexport const builder = {\n ...sharedOptionsBuilder,\n input: {\n description:\n 'Paths of source code files to be built. The first file is main. If no option is given, \"src/index.{ts,tsx}\" from package directory is targeted.',\n type: 'array',\n alias: 'i',\n },\n 'core-js': {\n description: 'Whether or not core-js is employed.',\n type: 'boolean',\n default: false,\n },\n 'core-js-proposals': {\n description: 'Whether or not core-js with proposals support is employed.',\n type: 'boolean',\n default: false,\n },\n minify: {\n description: 'Whether or not minification is enabled.',\n type: 'boolean',\n default: true,\n },\n sourcemap: {\n description: 'Whether or not sourcemap is enabled.',\n type: 'boolean',\n default: true,\n },\n external: {\n description: 'Additional external dependencies.',\n type: 'array',\n },\n inline: {\n description: 'Environment variables to be inlined.',\n type: 'array',\n },\n watch: {\n description: 'Whether watch mode is enabled or not',\n type: 'boolean',\n alias: 'w',\n },\n keepImport: {\n description: 'Identifiers to be kept as import statements.',\n type: 'array',\n },\n} as const;\n\nexport const appBuilder = {\n ...builder,\n moduleType: {\n description: 'esm, cjs, or either (default).',\n type: 'string',\n alias: 'm',\n },\n} as const;\n\nexport const functionsBuilder = {\n ...appBuilder,\n onlyPackageJson: {\n description: 'Whether to generate only package.json.',\n type: 'boolean',\n },\n} as const;\n\nexport const libBuilder = {\n ...builder,\n moduleType: {\n description: 'esm, cjs, either, or both (default).',\n type: 'string',\n alias: 'm',\n },\n // .js files in a package with `\"type\": \"module\"` are treated as esm.\n // However, we want to treat them as cjs in the case where a cjs project imports an esm package.\n // To deal with the case, we use .cjs and .mjs extensions instead of .js extension.\n jsExtension: {\n description: 'Whether to use .js in cjs and/or esm: either (default), both, or none.',\n type: 'string',\n alias: 'j',\n },\n} as const;\n\nexport type AnyBuilderType = typeof appBuilder | typeof functionsBuilder | typeof libBuilder;\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { babel } from '@rollup/plugin-babel';\nimport commonjs from '@rollup/plugin-commonjs';\nimport json from '@rollup/plugin-json';\nimport resolve from '@rollup/plugin-node-resolve';\nimport replace from '@rollup/plugin-replace';\nimport terser from '@rollup/plugin-terser';\nimport type { OutputOptions, Plugin } from 'rollup';\nimport analyze from 'rollup-plugin-analyzer';\nimport { keepImport } from 'rollup-plugin-keep-import';\nimport { nodeExternals } from 'rollup-plugin-node-externals';\nimport preserveDirectives from 'rollup-plugin-preserve-directives';\nimport { string } from 'rollup-plugin-string';\nimport type { PackageJson } from 'type-fest';\n\nimport { createEnvironmentVariablesDefinition } from '../../env.js';\nimport type { ArgumentsType, TargetDetail } from '../../types.js';\nimport { getBuildTsRootPath } from '../../utils.js';\n\nimport type { builder } from './builder.js';\n\nexport function setupPlugins(\n argv: ArgumentsType<typeof builder>,\n targetDetail: TargetDetail,\n packageJson: PackageJson,\n namespace: string | undefined,\n packageDirPath: string,\n outputOptionsList: OutputOptions[]\n): Plugin[] {\n const externalDeps = [...(argv.external ?? [])].map((item) => item.toString());\n if (packageJson.dependencies?.['@prisma/client']) {\n externalDeps.push('prisma-client');\n }\n // Since `deps: true` does not work for `import chunk from 'lodash.chunk/index.js';`\n externalDeps.push(\n ...Object.keys(packageJson.dependencies ?? {}),\n ...Object.keys(packageJson.peerDependencies ?? {}),\n ...Object.keys(packageJson.optionalDependencies ?? {})\n );\n // Add external dependencies from sibling packages\n if (fs.existsSync(path.join('..', '..', 'package.json'))) {\n const packageDirs = fs.readdirSync(path.join('..'), { withFileTypes: true });\n for (const packageDir of packageDirs) {\n if (!packageDir.isDirectory()) continue;\n\n const packageJsonPath = path.join('..', packageDir.name, 'package.json');\n if (!fs.existsSync(packageJsonPath)) continue;\n\n const otherPackageJson: PackageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));\n if (packageJson.dependencies?.[otherPackageJson.name ?? '']) {\n externalDeps.push(\n ...Object.keys(otherPackageJson.dependencies ?? {}),\n ...Object.keys(otherPackageJson.peerDependencies ?? {}),\n ...Object.keys(otherPackageJson.optionalDependencies ?? {})\n );\n }\n }\n }\n\n const extensions = ['.cjs', '.mjs', '.js', '.jsx', '.json', '.cts', '.mts', '.ts', '.tsx'];\n const babelConfigPath = path.join(getBuildTsRootPath(), 'babel.config.mjs');\n const plugins: Plugin[] = [\n replace({\n delimiters: ['', ''],\n preventAssignment: true,\n values: createEnvironmentVariablesDefinition(argv, packageDirPath),\n }),\n json(),\n nodeExternals({\n deps: true,\n devDeps: false,\n peerDeps: true,\n optDeps: true,\n include: externalDeps.map((name) => new RegExp(`^${name}(?:\\\\/.+)?`)),\n exclude: namespace && new RegExp(`^@?${namespace}(?:\\\\/.+)?`),\n }),\n resolve({ extensions }),\n commonjs(),\n keepImport({ moduleNames: argv.keepImport?.map((item) => item.toString()) ?? [] }),\n ];\n const isBabelHelpersBundled =\n targetDetail === 'app-node' || targetDetail === 'functions' || !externalDeps.includes('@babel/runtime');\n process.env.BUILDTS_USE_BABLE_RUNTIME = isBabelHelpersBundled ? '' : '1';\n plugins.push(\n babel({\n configFile: babelConfigPath,\n extensions,\n // We need `runtime since `bundled` may break directory structure by creating _virtual directory.\n babelHelpers: isBabelHelpersBundled ? 'bundled' : 'runtime',\n exclude: /^(.+\\/)?node_modules\\/.+$/,\n }),\n ...(outputOptionsList.some((opts) => opts.preserveModules) ? [preserveDirectives()] : []),\n string({ include: ['**/*.csv', '**/*.txt'] })\n );\n if (argv.minify) {\n plugins.push(terser({ compress: { directives: false } }));\n }\n plugins.push(analyze({ summaryOnly: true }));\n return plugins;\n}\n","/* eslint-disable import/no-named-as-default-member */\n\n// We cannot use named imports from 'typescript' because of build errors.\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport ts from 'typescript';\n\nexport async function generateDeclarationFiles(coreProjectDirPath: string): Promise<boolean> {\n const coreConfigFile = ts.findConfigFile(coreProjectDirPath, ts.sys.fileExists);\n if (!coreConfigFile) throw new Error(`Failed to find tsconfig.json in ${coreProjectDirPath}.`);\n\n const projects: [string, string, string][] = [];\n let outDir = path.join('dist', path.basename(coreProjectDirPath), 'src');\n if (fs.existsSync(outDir)) {\n const dirents = await fs.promises.readdir(path.dirname(coreProjectDirPath), { withFileTypes: true });\n coreProjectDirPath = path.resolve(coreProjectDirPath);\n for (const dirent of dirents) {\n if (!dirent.isDirectory()) continue;\n\n const projectDirPath = path.resolve(dirent.path, dirent.name);\n if (projectDirPath === coreProjectDirPath) continue;\n\n const configFile = ts.findConfigFile(projectDirPath, ts.sys.fileExists);\n const outDir = path.join('dist', dirent.name, 'src');\n if (configFile && fs.existsSync(outDir)) {\n projects.push([projectDirPath, configFile, outDir]);\n }\n }\n } else {\n outDir = 'dist';\n }\n projects.push([coreProjectDirPath, coreConfigFile, outDir]);\n\n let allSucceeded = true;\n for (const [projectDirPath, configFile, outDir] of projects) {\n allSucceeded &&= runTypeScriptCompiler(projectDirPath, configFile, path.join(coreProjectDirPath, outDir));\n }\n return allSucceeded;\n}\n\nfunction runTypeScriptCompiler(projectDirPath: string, configFile: string, outDir: string): boolean {\n const { config } = ts.readConfigFile(configFile, ts.sys.readFile);\n config.compilerOptions = {\n ...config.compilerOptions,\n declaration: true,\n emitDeclarationOnly: true,\n noEmit: false,\n noEmitOnError: true,\n outDir,\n };\n config.include = ['src/**/*'];\n const { errors, fileNames, options } = ts.parseJsonConfigFileContent(config, ts.sys, projectDirPath);\n\n const program = ts.createProgram({ options, rootNames: fileNames, configFileParsingDiagnostics: errors });\n const { diagnostics, emitSkipped } = program.emit();\n\n const allDiagnostics = [...ts.getPreEmitDiagnostics(program), ...diagnostics, ...errors];\n if (allDiagnostics.length > 0) {\n const formatHost: ts.FormatDiagnosticsHost = {\n getCanonicalFileName: (path) => path,\n getCurrentDirectory: ts.sys.getCurrentDirectory,\n getNewLine: () => ts.sys.newLine,\n };\n const message = ts.formatDiagnostics(allDiagnostics, formatHost);\n console.warn(message);\n }\n return !emitSkipped;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nimport chalk from 'chalk';\nimport dateTime from 'date-time';\nimport ms from 'pretty-ms';\nimport type { OutputOptions, RollupBuild, RollupOptions } from 'rollup';\nimport { rollup, watch } from 'rollup';\nimport type { Handler } from 'signal-exit';\nimport { onExit } from 'signal-exit';\nimport type { PackageJson } from 'type-fest';\nimport type { CommandModule } from 'yargs';\n\nimport { loadEnvironmentVariablesWithCache } from '../../env.js';\nimport type { ArgumentsType, TargetCategory, TargetDetail } from '../../types.js';\nimport { allTargetCategories } from '../../types.js';\nimport { getNamespaceAndName, readPackageJson } from '../../utils.js';\n\nimport type { AnyBuilderType, builder } from './builder.js';\nimport { appBuilder, functionsBuilder, libBuilder } from './builder.js';\nimport { setupPlugins } from './plugin.js';\nimport { handleError } from './rollupLogger.js';\nimport { generateDeclarationFiles } from './typeScript.js';\n\nexport const app: CommandModule<unknown, ArgumentsType<typeof appBuilder>> = {\n command: 'app [package]',\n describe: 'Build an app',\n builder: appBuilder,\n async handler(argv) {\n return build(argv, 'app');\n },\n};\n\nexport const functions: CommandModule<unknown, ArgumentsType<typeof functionsBuilder>> = {\n command: 'functions [package]',\n describe: 'Build a GCP/Firebase functions app',\n builder: functionsBuilder,\n async handler(argv) {\n if (argv.onlyPackageJson) {\n const packageDirPath = path.resolve(argv.package?.toString() ?? '.');\n const [packageJson, packageJsonPath] = await readPackageJson(packageDirPath);\n if (!packageJson) {\n console.error(`Failed to parse package.json (${packageJsonPath}).`);\n process.exit(1);\n }\n await generatePackageJsonForFunctions(packageDirPath, packageJson, argv.moduleType);\n } else {\n return build(argv, 'functions');\n }\n },\n};\n\nexport const lib: CommandModule<unknown, ArgumentsType<typeof libBuilder>> = {\n command: 'lib [package]',\n describe: 'Build a Node.js / React library',\n builder: libBuilder,\n async handler(argv) {\n return build(argv, 'lib');\n },\n};\n\nexport async function build(argv: ArgumentsType<AnyBuilderType>, targetCategory: TargetCategory): Promise<void> {\n process.env.NODE_ENV ||= 'production';\n\n // `silent` is stronger than `verbose`.\n const verbose = !argv.silent && argv.verbose;\n const cwd = process.cwd();\n\n const packageDirPath = path.resolve(argv.package?.toString() ?? '.');\n const [packageJson, packageJsonPath] = await readPackageJson(packageDirPath);\n if (!packageJson) {\n console.error(`Failed to parse package.json (${packageJsonPath}).`);\n process.exit(1);\n }\n\n loadEnvironmentVariablesWithCache(argv, packageDirPath);\n\n const inputs = verifyInput(argv, cwd, packageDirPath);\n const targetDetail = detectTargetDetail(targetCategory, inputs);\n\n if (verbose) {\n console.info('Target (Category):', `${targetDetail} (${targetCategory})`);\n }\n\n const [namespace] = getNamespaceAndName(packageJson);\n const isEsmPackage = packageJson.type === 'module';\n\n if (argv['core-js']) {\n process.env.BUILD_TS_COREJS = '1';\n } else if (argv['core-js-proposals']) {\n process.env.BUILD_TS_COREJS_WITH_PROPOSALS = '1';\n }\n\n if (verbose) {\n process.env.BUILD_TS_VERBOSE = '1';\n }\n process.env.BUILD_TS_TARGET_CATEGORY = targetCategory;\n process.env.BUILD_TS_TARGET_DETAIL = targetDetail;\n\n const outputOptionsList = getOutputOptionsList(argv, targetDetail, packageDirPath, isEsmPackage);\n if (verbose) {\n console.info('OutputOptions:', outputOptionsList);\n }\n if (outputOptionsList.length === 0) {\n console.error('Failed to detect output files.');\n process.exit(1);\n }\n\n process.chdir(packageDirPath);\n await fs.promises.rm(path.join(packageDirPath, 'dist'), { recursive: true, force: true });\n if (targetDetail === 'functions') {\n await generatePackageJsonForFunctions(packageDirPath, packageJson, argv.moduleType);\n }\n\n const options: RollupOptions = {\n input:\n targetDetail === 'functions'\n ? Object.fromEntries(\n inputs.map((input, index) => [index === 0 ? 'index' : path.basename(input, path.extname(input)), input])\n )\n : inputs,\n plugins: setupPlugins(argv, targetDetail, packageJson, namespace, packageDirPath, outputOptionsList),\n watch: argv.watch ? { clearScreen: false } : undefined,\n };\n\n const pathToRelativePath = (paths: string | Readonly<string[]>): string[] =>\n (Array.isArray(paths) ? paths : [paths]).map((p) => path.relative(packageDirPath, p));\n if (argv.watch) {\n watchRollup(argv, targetDetail, packageDirPath, options, outputOptionsList, pathToRelativePath);\n } else {\n if (!argv.silent) {\n console.info(\n chalk.cyan(\n `Bundles ${chalk.bold(pathToRelativePath(inputs).join(', '))} → ${chalk.bold(\n pathToRelativePath(outputOptionsList.map((opts) => opts.file || opts.dir || '')).join(', ')\n )}\\non ${packageDirPath} ...`\n )\n );\n }\n\n let bundle: RollupBuild | undefined;\n let buildFailed = false;\n try {\n const startTime = Date.now();\n const _bundle = await rollup(options);\n bundle = _bundle;\n await Promise.all(outputOptionsList.map((opts) => _bundle.write(opts)));\n\n if (!argv.silent) {\n console.info(\n chalk.green(\n `Created ${pathToRelativePath(outputOptionsList.map((opts) => opts.file || opts.dir || '')).join(\n ', '\n )} in ${chalk.bold(ms(Date.now() - startTime))}`\n )\n );\n }\n } catch (error) {\n buildFailed = true;\n console.error('Failed to build due to:', error);\n }\n await bundle?.close();\n if (buildFailed) process.exit(1);\n\n if (\n targetDetail !== 'app-node' &&\n targetDetail !== 'functions' &&\n !(await generateDeclarationFiles(packageDirPath))\n ) {\n process.exit(1);\n }\n }\n}\n\nfunction watchRollup(\n argv: ArgumentsType<AnyBuilderType>,\n targetDetail: string,\n packageDirPath: string,\n options: RollupOptions,\n outputOptionsList: OutputOptions[],\n pathToRelativePath: (paths: string | Readonly<string[]>) => string[]\n): void {\n const watcher = watch({ ...options, output: outputOptionsList });\n\n const close = async (code: number | null | undefined): Promise<void> => {\n process.removeListener('uncaughtException', close);\n process.stdin.removeListener('end', close);\n if (watcher) await watcher.close();\n if (code) process.exit(code);\n };\n onExit(close as unknown as Handler);\n process.on('uncaughtException', close);\n if (!process.stdin.isTTY) {\n process.stdin.on('end', close);\n process.stdin.resume();\n }\n\n watcher.on('event', async (event) => {\n switch (event.code) {\n case 'ERROR': {\n handleError(event.error, true);\n break;\n }\n case 'BUNDLE_START': {\n if (argv.silent) break;\n\n const eventInput = event.input;\n const inputFiles: string[] = [];\n if (typeof eventInput === 'string') {\n inputFiles.push(eventInput);\n } else {\n inputFiles.push(\n ...(Array.isArray(eventInput) ? eventInput : Object.values(eventInput as Record<string, string>))\n );\n }\n console.info(\n chalk.cyan(\n `Bundles ${chalk.bold(pathToRelativePath(inputFiles).join(', '))} → ${chalk.bold(\n pathToRelativePath(event.output).join(', ')\n )}\\non ${packageDirPath} ...`\n )\n );\n break;\n }\n case 'BUNDLE_END': {\n if (argv.silent) break;\n\n console.info(\n chalk.green(\n `Created ${chalk.bold(pathToRelativePath(event.output).join(', '))} in ${chalk.bold(ms(event.duration))}`\n )\n );\n\n if (targetDetail !== 'app-node' && targetDetail !== 'functions') {\n await generateDeclarationFiles(packageDirPath);\n }\n break;\n }\n case 'END': {\n if (argv.silent) break;\n\n console.info(`\\n[${dateTime()}] waiting for changes...`);\n break;\n }\n }\n\n if ('result' in event && event.result) {\n void event.result.close();\n }\n });\n}\n\nfunction verifyInput(argv: ArgumentsType<typeof builder>, cwd: string, packageDirPath: string): string[] {\n if (argv.input && argv.input.length > 0) return argv.input.map((p) => path.join(cwd, p.toString()));\n\n const srcDirPath = path.join(packageDirPath, 'src');\n for (const ext of ['ts', 'tsx', 'cts', 'mts']) {\n const input = path.join(srcDirPath, `index.${ext}`);\n if (fs.existsSync(input)) return [input];\n }\n\n console.error('Failed to detect input file.');\n process.exit(1);\n}\n\nfunction detectTargetDetail(targetCategory: string, inputs: string[]): TargetDetail {\n switch (targetCategory) {\n case 'app': {\n return 'app-node';\n }\n case 'functions': {\n return 'functions';\n }\n case 'lib': {\n if (inputs.some((input) => input.endsWith('.tsx'))) {\n return 'lib-react';\n }\n return 'lib';\n }\n default: {\n console.error('target option must be one of: ' + allTargetCategories.join(', '));\n process.exit(1);\n }\n }\n}\n\nasync function generatePackageJsonForFunctions(\n packageDirPath: string,\n packageJson: PackageJson,\n moduleType: string | undefined\n): Promise<void> {\n packageJson.name += '-dist';\n const esmPackage = packageJson.type === 'module';\n const esmOutput = isEsmOutput(esmPackage, moduleType);\n packageJson.main = esmPackage === esmOutput ? 'index.js' : esmOutput ? 'index.mjs' : 'index.cjs';\n\n // Prevent Firebase Functions from running `build` script since we are building code before deploying.\n delete packageJson.scripts;\n // devDependencies are not required since we are building code before deploying.\n delete packageJson.devDependencies;\n\n await fs.promises.mkdir(path.join(packageDirPath, 'dist'), { recursive: true });\n await fs.promises.writeFile(path.join(packageDirPath, 'dist', 'package.json'), JSON.stringify(packageJson));\n}\n\nfunction getOutputOptionsList(\n argv: ArgumentsType<AnyBuilderType>,\n targetDetail: string,\n packageDirPath: string,\n isEsmPackage: boolean\n): OutputOptions[] {\n const outDirPath = path.join(packageDirPath, 'dist');\n if (targetDetail === 'app-node' || targetDetail === 'functions') {\n return [\n {\n dir: outDirPath,\n format: isEsmOutput(isEsmPackage, argv.moduleType) ? 'module' : 'commonjs',\n sourcemap: argv.sourcemap,\n },\n ];\n }\n\n // The following import statement in an esm module causes the following error:\n // Statement:\n // import { usePrevious } from 'react-use';\n // Error:\n // Named export 'usePrevious' not found. The requested module 'react-use' is a CommonJS module,\n // which may not support all module.exports as named exports.\n // We need cjs modules for web apps to avoid the error.\n // Also, splitting a library is useful in both modules, so preserveModules should be true.\n const outputOptionsList: OutputOptions[] = [];\n const moduleType = argv.moduleType || 'both';\n const jsExt = argv.jsExtension || 'either';\n if (moduleType === 'cjs' || moduleType === 'both' || (moduleType === 'either' && !isEsmPackage)) {\n outputOptionsList.push({\n dir: outDirPath,\n entryFileNames: jsExt === 'both' || (jsExt === 'either' && !isEsmPackage) ? '[name].js' : '[name].cjs',\n format: 'commonjs',\n preserveModules: true,\n sourcemap: argv.sourcemap,\n });\n }\n if (moduleType === 'esm' || moduleType === 'both' || (moduleType === 'either' && isEsmPackage)) {\n outputOptionsList.push({\n dir: outDirPath,\n entryFileNames: jsExt === 'both' || (jsExt === 'either' && isEsmPackage) ? '[name].js' : '[name].mjs',\n format: 'module',\n preserveModules: true,\n sourcemap: argv.sourcemap,\n });\n }\n return outputOptionsList;\n}\n\nfunction isEsmOutput(isEsmPackage: boolean, moduleType: string | undefined): boolean {\n return moduleType === 'esm' || ((!moduleType || moduleType === 'either') && isEsmPackage);\n}\n","import process from 'node:process';\n\nimport chalk from 'chalk';\nimport type { RollupError } from 'rollup';\n\nexport function handleError(error: RollupError, recover = false): void {\n const name = error.name || (error.cause as Error)?.name;\n const nameSection = name ? `${name}: ` : '';\n const pluginSection = error.plugin ? `(plugin ${error.plugin}) ` : '';\n const message = `${pluginSection}${nameSection}${error.message}`;\n\n const outputLines = [chalk.bold(chalk.red(`[!] ${chalk.bold(message.toString())}`))];\n\n if (error.url) {\n outputLines.push(chalk.cyan(error.url));\n }\n\n if (error.loc) {\n outputLines.push(`${error.loc.file || error.id} (${error.loc.line}:${error.loc.column})`);\n } else if (error.id) {\n outputLines.push(error.id);\n }\n\n if (error.frame) {\n outputLines.push(chalk.dim(error.frame));\n }\n\n if (error.stack) {\n outputLines.push(chalk.dim(error.stack?.replace(`${nameSection}${error.message}\\n`, '')));\n }\n\n outputLines.push('', '');\n console.error(outputLines.join('\\n'));\n\n if (!recover) process.exit(1);\n}\n","import * as child_process from 'node:child_process';\n\nimport type { CommandModule, InferredOptionTypes } from 'yargs';\n\nimport { loadEnvironmentVariablesWithCache } from '../env.js';\nimport { sharedOptionsBuilder } from '../sharedOptionsBuilder.js';\n\nconst builder = {\n ...sharedOptionsBuilder,\n module: {\n description: 'A module type: cjs or esm',\n type: 'string',\n alias: 'm',\n },\n watch: {\n description: 'Whether watch mode is enabled or not',\n type: 'boolean',\n alias: 'w',\n },\n} as const;\n\nexport const run: CommandModule<unknown, InferredOptionTypes<typeof builder>> = {\n command: 'run <file>',\n describe: 'Run script',\n builder,\n async handler(argv) {\n loadEnvironmentVariablesWithCache(argv, process.cwd());\n\n const file = argv.file?.toString() || '';\n\n const args = ['--no-warnings', '--import', 'tsx', file];\n if (argv.watch) {\n args.push('--watch');\n }\n const [, ...additionalArguments] = argv._;\n if (argv.verbose) {\n console.info(`Running 'node ${[...args, ...additionalArguments.map((arg) => arg.toString())].join(' ')}'`);\n }\n const ret = child_process.spawnSync('node', [...args, ...additionalArguments.map((arg) => arg.toString())], {\n stdio: 'inherit',\n env: { ...process.env, NODE_NO_WARNINGS: '1' },\n });\n process.exit(ret.status ?? 1);\n },\n};\n","import { removeNpmAndYarnEnvironmentVariables } from '@willbooster/shared-lib-node';\nimport yargs from 'yargs';\nimport { hideBin } from 'yargs/helpers';\n\nimport { app, functions, lib } from './commands/build/build.js';\nimport { run } from './commands/run.js';\nimport { sharedOptionsBuilder } from './sharedOptionsBuilder.js';\n\nremoveNpmAndYarnEnvironmentVariables(process.env);\n\nawait yargs(hideBin(process.argv))\n .scriptName('build-ts')\n .options(sharedOptionsBuilder)\n .command(app)\n .command(functions)\n .command(lib)\n .command(run)\n .demandCommand()\n .strict()\n .help().argv;\n"],"names":["envVars","loadEnvironmentVariablesWithCache","argv","cwd","readAndApplyEnvironmentVariables","verbose","console","info","Object","keys","createEnvironmentVariablesDefinition","envVarsDef","names","Set","inline","flatMap","e","toString","split","name","undefined","process","env","JSON","stringify","allTargetCategories","async","readPackageJson","dirPath","packageJsonPath","path","join","packageJsonText","fs","promises","readFile","parse","sharedOptionsBuilder","yargsOptionsBuilderForEnv","silent","description","type","alias","builder","input","default","minify","sourcemap","external","watch","keepImport","appBuilder","moduleType","functionsBuilder","onlyPackageJson","libBuilder","jsExtension","setupPlugins","targetDetail","packageJson","namespace","packageDirPath","outputOptionsList","externalDeps","map","item","dependencies","push","peerDependencies","optionalDependencies","existsSync","packageDirs","readdirSync","withFileTypes","packageDir","isDirectory","otherPackageJson","readFileSync","extensions","babelConfigPath","url","fileURLToPath","dirname","plugins","replace","delimiters","preventAssignment","values","json","nodeExternals","deps","devDeps","peerDeps","optDeps","include","RegExp","exclude","resolve","commonjs","moduleNames","isBabelHelpersBundled","includes","BUILDTS_USE_BABLE_RUNTIME","babel","configFile","babelHelpers","some","opts","preserveModules","preserveDirectives","string","terser","compress","directives","analyze","summaryOnly","generateDeclarationFiles","coreProjectDirPath","coreConfigFile","ts","findConfigFile","sys","fileExists","Error","projects","outDir","basename","dirents","readdir","dirent","projectDirPath","allSucceeded","runTypeScriptCompiler","config","readConfigFile","compilerOptions","declaration","emitDeclarationOnly","noEmit","noEmitOnError","errors","fileNames","options","parseJsonConfigFileContent","program","createProgram","rootNames","configFileParsingDiagnostics","diagnostics","emitSkipped","emit","allDiagnostics","getPreEmitDiagnostics","length","formatHost","getCanonicalFileName","getCurrentDirectory","getNewLine","newLine","message","formatDiagnostics","warn","app","command","describe","handler","build","functions","package","error","exit","generatePackageJsonForFunctions","lib","targetCategory","NODE_ENV","inputs","p","srcDirPath","ext","verifyInput","endsWith","detectTargetDetail","packageName","match","exec","getNamespaceAndName","isEsmPackage","BUILD_TS_COREJS","BUILD_TS_COREJS_WITH_PROPOSALS","BUILD_TS_VERBOSE","BUILD_TS_TARGET_CATEGORY","BUILD_TS_TARGET_DETAIL","outDirPath","dir","format","isEsmOutput","jsExt","entryFileNames","getOutputOptionsList","chdir","rm","recursive","force","fromEntries","index","extname","clearScreen","pathToRelativePath","paths","Array","isArray","relative","watcher","output","close","removeListener","stdin","code","onExit","on","isTTY","resume","event","recover","cause","nameSection","plugin","outputLines","chalk","bold","red","cyan","loc","file","id","line","column","frame","dim","stack","handleError","eventInput","inputFiles","green","ms","duration","dateTime","result","watchRollup","bundle","buildFailed","startTime","Date","now","_bundle","rollup","Promise","all","write","esmPackage","esmOutput","main","scripts","devDependencies","mkdir","writeFile","run","module","args","additionalArguments","_","arg","ret","child_process","spawnSync","stdio","NODE_NO_WARNINGS","status","removeNpmAndYarnEnvironmentVariables","yargs","hideBin","scriptName","demandCommand","strict","help"],"mappings":"s/BAMA,IAAIA,EAKG,SAASC,EACdC,EACAC,GAQA,OANKH,IACHA,EAAUI,EAAiCF,EAAMC,GAC7CD,EAAKG,SACPC,QAAQC,KAAK,mBAAoBC,OAAOC,KAAKT,KAG1CA,CACT,CAKO,SAASU,EACdR,EACAC,GAEA,MAAMQ,EAAqC,CAAA,EACrCC,EAAQ,IAAIC,IAAI,KAChBX,EAAKY,QAAU,IAAIC,SAASC,GAAMA,EAAEC,WAAWC,MAAM,UACtDV,OAAOC,KAAKR,EAAkCC,EAAMC,MAEzD,IAAK,MAAMgB,KAAQP,OACSQ,IAAtBC,QAAQC,IAAIH,KAEhBR,EAAY,eAAcQ,KAAUI,KAAKC,UAAUH,QAAQC,IAAIH,KAKjE,OAHIjB,EAAKG,SACPC,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D,QAAQC,IAAK8P,iBAAkB,OAE3C/P,QAAQqJ,KAAKsG,EAAIK,QAAU,EAC7B,GCnCFC,EAAqCjQ,QAAQC,WAEvCiQ,EAAMC,EAAQnQ,QAAQnB,OACzBuR,WAAW,YACX3I,QAAQzG,GACR8H,QAAQD,GACRC,QAAQI,GACRJ,QAAQS,GACRT,QAAQuG,GACRgB,gBACAC,SACAC,OAAO1R"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "build-ts",
3
- "version": "13.1.0",
3
+ "version": "13.1.2",
4
4
  "repository": "github:WillBooster/build-ts",
5
5
  "license": "UNLICENSED",
6
6
  "author": "WillBooster Inc.",