@rzl-zone/build-tools 0.0.5

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 (70) hide show
  1. package/LICENSE +21 -0
  2. package/dist/.references/index.d.cts +18 -0
  3. package/dist/.references/index.d.ts +18 -0
  4. package/dist/bundler/rolldown.cjs +32 -0
  5. package/dist/bundler/rolldown.cjs.map +1 -0
  6. package/dist/bundler/rolldown.d.cts +162 -0
  7. package/dist/bundler/rolldown.d.ts +162 -0
  8. package/dist/bundler/rolldown.js +25 -0
  9. package/dist/bundler/rolldown.js.map +1 -0
  10. package/dist/bundler/tsdown.cjs +132 -0
  11. package/dist/bundler/tsdown.cjs.map +1 -0
  12. package/dist/bundler/tsdown.d.cts +1165 -0
  13. package/dist/bundler/tsdown.d.ts +1165 -0
  14. package/dist/bundler/tsdown.js +124 -0
  15. package/dist/bundler/tsdown.js.map +1 -0
  16. package/dist/bundler/utils.cjs +24 -0
  17. package/dist/bundler/utils.cjs.map +1 -0
  18. package/dist/bundler/utils.d.cts +40 -0
  19. package/dist/bundler/utils.d.ts +40 -0
  20. package/dist/bundler/utils.js +21 -0
  21. package/dist/bundler/utils.js.map +1 -0
  22. package/dist/client-XhkdKJ4d.js +160 -0
  23. package/dist/client-XhkdKJ4d.js.map +1 -0
  24. package/dist/client-u8yLSxEI.cjs +221 -0
  25. package/dist/client-u8yLSxEI.cjs.map +1 -0
  26. package/dist/commander-kit/index.cjs +569 -0
  27. package/dist/commander-kit/index.cjs.map +1 -0
  28. package/dist/commander-kit/index.d.cts +1383 -0
  29. package/dist/commander-kit/index.d.ts +1383 -0
  30. package/dist/commander-kit/index.js +550 -0
  31. package/dist/commander-kit/index.js.map +1 -0
  32. package/dist/extra-CVuXMpEw.d.ts +994 -0
  33. package/dist/extra-CxDwtQEy.d.cts +994 -0
  34. package/dist/fast-globe-options-6r2aj6UC.d.ts +126 -0
  35. package/dist/fast-globe-options-BFt__e__.d.cts +126 -0
  36. package/dist/helper-BdjaR8Yv.js +215 -0
  37. package/dist/helper-BdjaR8Yv.js.map +1 -0
  38. package/dist/helper-DorgNsB9.cjs +377 -0
  39. package/dist/helper-DorgNsB9.cjs.map +1 -0
  40. package/dist/identity-BJ0QX7AJ.js +88 -0
  41. package/dist/identity-BJ0QX7AJ.js.map +1 -0
  42. package/dist/identity-CxR9DRMh.cjs +100 -0
  43. package/dist/identity-CxR9DRMh.cjs.map +1 -0
  44. package/dist/index-B-NeF7PU.d.cts +670 -0
  45. package/dist/index-CzxZta4Z.d.ts +356 -0
  46. package/dist/index-Idak1iwg.d.cts +356 -0
  47. package/dist/index-PXsb85LI.d.ts +670 -0
  48. package/dist/index.cjs +1689 -0
  49. package/dist/index.cjs.map +1 -0
  50. package/dist/index.d.cts +2193 -0
  51. package/dist/index.d.ts +2193 -0
  52. package/dist/index.js +1641 -0
  53. package/dist/index.js.map +1 -0
  54. package/dist/package-banner-6RzEf-mV.cjs +54 -0
  55. package/dist/package-banner-6RzEf-mV.cjs.map +1 -0
  56. package/dist/package-banner-BzheZbxy.js +41 -0
  57. package/dist/package-banner-BzheZbxy.js.map +1 -0
  58. package/dist/server-B2hBoGDR.cjs +181 -0
  59. package/dist/server-B2hBoGDR.cjs.map +1 -0
  60. package/dist/server-CWrDd29Y.js +142 -0
  61. package/dist/server-CWrDd29Y.js.map +1 -0
  62. package/dist/utils/client.cjs +23 -0
  63. package/dist/utils/client.d.cts +887 -0
  64. package/dist/utils/client.d.ts +887 -0
  65. package/dist/utils/client.js +12 -0
  66. package/dist/utils/server.cjs +17 -0
  67. package/dist/utils/server.d.cts +124 -0
  68. package/dist/utils/server.d.ts +124 -0
  69. package/dist/utils/server.js +12 -0
  70. package/package.json +151 -0
package/dist/index.js ADDED
@@ -0,0 +1,1641 @@
1
+ /*!
2
+ * ========================================================================
3
+ * @rzl-zone/build-tools
4
+ * ------------------------------------------------------------------------
5
+ * Version: `0.0.5`
6
+ * Author: `Rizalvin Dwiky <rizalvindwiky1998@gmail.com>`
7
+ * Repository: `https://github.com/rzl-zone/rzl-zone/tree/main/packages/build-tools`
8
+ * ========================================================================
9
+ */
10
+
11
+ import { S as toStringSet, _ as isUndefined, a as isError, d as isNumber, g as isString, h as isSet, i as isBoolean, l as isNonEmptyString, m as isRegExp, n as flattenStrings, p as isPlainObject, r as isArray, v as normalizeSpaces, x as toObjectSet, y as safeStableStringify } from "./helper-BdjaR8Yv.js";
12
+ import { a as resolvePatternOptions, i as defaultPatternOptions, n as fsExtra, o as sourceOfPatternOptions, r as ICONS, t as fastGlob } from "./server-CWrDd29Y.js";
13
+ import { t as CommandIdentity } from "./identity-BJ0QX7AJ.js";
14
+ import { a as joinInline, i as formatOptionValue, l as picocolors, n as EOL, o as joinLines, s as joinLinesLoose, u as plural } from "./client-XhkdKJ4d.js";
15
+ import { n as getPackageJson, t as generatePackageBanner } from "./package-banner-BzheZbxy.js";
16
+ import "@rzl-zone/node-only";
17
+ import * as t from "@babel/types";
18
+ import { parse } from "@babel/parser";
19
+ import traverseImport from "@babel/traverse";
20
+ import path from "node:path";
21
+ import * as acorn from "acorn";
22
+ import { ChildProcess, spawn } from "node:child_process";
23
+ function isLogLevel(value) {
24
+ return typeof value === "string" && value in LOG_LEVEL_PRIORITY;
25
+ }
26
+ const DEFAULT_LOG_LEVEL = "info";
27
+ const VERBOSE_LOG = ["info", "debug"];
28
+ const LOG_LEVEL_PRIORITY = Object.freeze({
29
+ silent: 0,
30
+ error: 1,
31
+ info: 2,
32
+ debug: 3
33
+ });
34
+ function resolveLogVerbosity(options, fallback = DEFAULT_LOG_LEVEL) {
35
+ const input = options?.logLevel;
36
+ if (isLogLevel(input)) return input;
37
+ return isLogLevel(fallback) ? fallback : DEFAULT_LOG_LEVEL;
38
+ }
39
+ function canLog(current, target, fallbackIfInvalid = DEFAULT_LOG_LEVEL) {
40
+ const fallbackLog = isLogLevel(fallbackIfInvalid) ? fallbackIfInvalid : DEFAULT_LOG_LEVEL;
41
+ const resolvedCurrent = isLogLevel(current) ? current : fallbackLog;
42
+ return (isString(target) ? [target] : isArray(target) ? target : [fallbackLog]).some((level) => LOG_LEVEL_PRIORITY[resolvedCurrent] >= LOG_LEVEL_PRIORITY[level]);
43
+ }
44
+ const DEFAULT_CLEAN_PATTERN_POLICY = {
45
+ filesOnly: true,
46
+ forceUnique: true
47
+ };
48
+ const resolvedCleanPatternOption = resolvePatternOptions(defaultPatternOptions, DEFAULT_CLEAN_PATTERN_POLICY);
49
+ const DEFAULT_CLEAN_OPTION = {
50
+ removeSourceMap: false,
51
+ removeRegion: true,
52
+ removeAdjacentEmptyLines: false,
53
+ patternOptions: resolvedCleanPatternOption,
54
+ logLevel: DEFAULT_LOG_LEVEL
55
+ };
56
+ const USE_STRICT_RE = /^['"]use strict['"];?\s*$/gm;
57
+ const SHEBANG_RE = /^#![^\r\n]*\r?\n/;
58
+ const BANNER_RE = /^(?:\/\*![\s\S]*?\*\/\s*)+/;
59
+ const JS_OUTPUT_FILE_RE = /\.(?:js|mjs|cjs|esm\.js|module\.js)$/i;
60
+ const TS_DECLARATION_FILE_RE = /\.d\.(?:ts|mts|cts)$/i;
61
+ const REGION_RE = /^[ \t]*\/\/\s*#(?:end)?region\b.*$/i;
62
+ const SOURCE_PATH_RE = /^[ \t]*\/\/\s*(?:\.\.\/|\.\/)*[^ \n]*?(?:src|node_modules)\//;
63
+ const ESLINT_RE = /^[ \t]*\/\/\s*eslint/;
64
+ const SOURCE_MAP_RE = /^[ \t]*\/\/[#@]\s*sourceMappingURL=\S+\s*$/;
65
+ const IMPORTANT_COMMENT = /^!|@license|@preserve|@copyright|@cc_on|@__(PURE|INLINE|NOINLINE|NO_SIDE_EFFECTS)__/;
66
+ const EMPTY_LINE_RE = /^\s*$/;
67
+ function shouldRemoveDocRuntime(commentText) {
68
+ const text = commentText.trim();
69
+ const hasRemoveDocRuntime = /[@]removeDocRuntime\b/.test(text);
70
+ const hasKeepDocRuntime = /[@]keepDocRuntime\b/.test(text);
71
+ if (hasRemoveDocRuntime && hasKeepDocRuntime) return true;
72
+ if (hasKeepDocRuntime) return false;
73
+ if (hasRemoveDocRuntime) return true;
74
+ }
75
+ const NON_COMMENTABLE_FILE_RE = /(?:^|[\\/])(?:package-lock\.json|composer\.lock|bun\.lockb)$|\.(?:json|map|webmanifest|har|geojson|topojson|tsbuildinfo)$/i;
76
+ function hasExecutableCode(content) {
77
+ const { body } = extractAndHoistBanner(content.trim());
78
+ const { rest } = extractDirectives(body);
79
+ return isNonEmptyString(rest);
80
+ }
81
+ const defaultCommentOptions = {
82
+ removeRegion: true,
83
+ removeSourceMap: false
84
+ };
85
+ const isTargetComment = (line, options = defaultCommentOptions) => {
86
+ if (!isNonEmptyString(line)) return false;
87
+ if (SOURCE_PATH_RE.test(line)) return true;
88
+ if (ESLINT_RE.test(line)) return true;
89
+ if (options.removeRegion && REGION_RE.test(line)) return true;
90
+ if (options.removeSourceMap && SOURCE_MAP_RE.test(line)) return true;
91
+ return false;
92
+ };
93
+ const isAdjacentToTarget = (arr, index, options = defaultCommentOptions) => {
94
+ return isTargetComment(arr[index - 1], options) || isTargetComment(arr[index + 1], options);
95
+ };
96
+ function detectModuleKindFromContent(code) {
97
+ let hasImport = false;
98
+ let hasExport = false;
99
+ let hasModuleExports = false;
100
+ let hasExportsMutation = false;
101
+ let hasRequire = false;
102
+ let hasDefine = false;
103
+ let hasUMDEnvCheck = false;
104
+ let hasTopLevelIIFE = false;
105
+ const ast = parse(code, {
106
+ sourceType: "unambiguous",
107
+ plugins: ["typescript", "jsx"]
108
+ });
109
+ (traverseImport.default ?? traverseImport)(ast, {
110
+ Program(path) {
111
+ for (const node of path.node.body) {
112
+ if (t.isExpressionStatement(node) && t.isCallExpression(node.expression) && (t.isFunctionExpression(node.expression.callee) || t.isArrowFunctionExpression(node.expression.callee))) hasTopLevelIIFE = true;
113
+ if (t.isVariableDeclaration(node)) {
114
+ for (const decl of node.declarations) if (decl.init && t.isCallExpression(decl.init) && (t.isFunctionExpression(decl.init.callee) || t.isArrowFunctionExpression(decl.init.callee))) hasTopLevelIIFE = true;
115
+ }
116
+ }
117
+ },
118
+ ImportDeclaration() {
119
+ hasImport = true;
120
+ },
121
+ ExportNamedDeclaration() {
122
+ hasExport = true;
123
+ },
124
+ ExportDefaultDeclaration() {
125
+ hasExport = true;
126
+ },
127
+ AssignmentExpression(path) {
128
+ const left = path.node.left;
129
+ if (t.isMemberExpression(left)) {
130
+ if (t.isIdentifier(left.object) && t.isIdentifier(left.property)) {
131
+ if (left.object.name === "module" && left.property.name === "exports") hasModuleExports = true;
132
+ if (left.object.name === "exports") hasExportsMutation = true;
133
+ }
134
+ }
135
+ },
136
+ CallExpression(path) {
137
+ const { callee, arguments: args } = path.node;
138
+ if (args.length > 0 && t.isIdentifier(args[0]) && args[0].name === "exports") hasExportsMutation = true;
139
+ if (t.isIdentifier(callee)) {
140
+ if (callee.name === "require") hasRequire = true;
141
+ if (callee.name === "define") hasDefine = true;
142
+ }
143
+ },
144
+ UnaryExpression(path) {
145
+ if (path.node.operator === "typeof" && t.isIdentifier(path.node.argument) && (path.node.argument.name === "exports" || path.node.argument.name === "module")) hasUMDEnvCheck = true;
146
+ }
147
+ });
148
+ const isCJS = hasModuleExports || hasExportsMutation;
149
+ if (hasUMDEnvCheck && (hasDefine || isCJS)) return "umd";
150
+ if (isCJS) return "cjs";
151
+ if (hasExport || hasImport) return "esm";
152
+ if (hasTopLevelIIFE && !isCJS && !hasImport && !hasExport) return "iife";
153
+ if (hasRequire) return "cjs";
154
+ return "esm";
155
+ }
156
+ function extractAndHoistBanner(content) {
157
+ let rest = content;
158
+ let shebang = "";
159
+ let banner = "";
160
+ const shebangMatch = rest.match(SHEBANG_RE);
161
+ if (shebangMatch && shebangMatch.index === 0) {
162
+ shebang = shebangMatch[0];
163
+ rest = rest.slice(shebang.length);
164
+ }
165
+ const bannerMatch = rest.match(BANNER_RE);
166
+ if (bannerMatch && bannerMatch.index === 0) {
167
+ banner = bannerMatch[0];
168
+ rest = rest.slice(banner.length);
169
+ }
170
+ return {
171
+ shebang,
172
+ banner,
173
+ body: rest.replace(/^\s+/, "")
174
+ };
175
+ }
176
+ function extractDirectives(code) {
177
+ const match = code.match(/^((?:(?:"use\s+\w+"|'use\s+\w+');\s*)+)/);
178
+ return {
179
+ directives: match?.[1] ?? "",
180
+ rest: code.slice(match?.[1]?.length ?? 0)
181
+ };
182
+ }
183
+ function stripUseStrict(content, { trimStart = true, trimEnd = false } = {}) {
184
+ const result = content.replace(USE_STRICT_RE, "");
185
+ if (trimStart) result.trimStart();
186
+ if (trimEnd) result.trimEnd();
187
+ return result;
188
+ }
189
+ const sourceOf = (value, defaultValue) => {
190
+ return Object.is(value, defaultValue) ? "default" : "overridden";
191
+ };
192
+ const BUILD_LOGGER = {
193
+ SOURCE_OF: sourceOf,
194
+ OPTIONS(label, value, source, isRequired) {
195
+ const sourceLabel = !isRequired && source ? source === "default" ? picocolors.blueBright(` (${source})`) : picocolors.yellowBright(` (${source})`) : "";
196
+ console.log(picocolors.dim(" - ") + normalizeSpaces(picocolors.bold(label || "`⚠️ Label Unset!!!`") + picocolors.dim(": ") + formatOptionValue(value) + picocolors.italic(sourceLabel)));
197
+ },
198
+ SECTION(title, options = {}) {
199
+ const { icon = ICONS.config, indent = "" } = options;
200
+ console.log(picocolors.bold(`${indent}${picocolors.whiteBright(icon)} ${picocolors.underline(picocolors.cyanBright(title || "`⚠️ Unset Title!!!`"))}:`));
201
+ },
202
+ NEW_LINE(value = "") {
203
+ return console.log(value);
204
+ },
205
+ ON_STARTING: (options) => {
206
+ const { actionName, textDirectAction = "to" } = options;
207
+ console.log(picocolors.bold(`${picocolors.whiteBright(ICONS.start)} ${picocolors.cyanBright("Starting")} ${normalizeSpaces(`${textDirectAction} ${picocolors.underline(picocolors.blueBright(actionName))}`)}.`));
208
+ },
209
+ ON_FINISH: (options) => {
210
+ const { actionName, count, typeCount = "file", progress, textSuccess = "Success" } = options;
211
+ console.log(picocolors.bold(`${picocolors.greenBright(ICONS.success)} ${picocolors.greenBright(textSuccess)} ${normalizeSpaces(`${picocolors.underline(picocolors.blueBright(actionName))} (${picocolors.yellowBright(`${isNonEmptyString(progress) ? progress : count} ${typeCount}${count > 1 ? "(s)" : ""}`)}`)}).`));
212
+ },
213
+ ON_SKIPPING: (options) => {
214
+ const { actionName, reasonEndText, reasonSkipAction = "nothing left", reasonTitle = "because", reasonType = "files", textDirectAction = "to" } = options;
215
+ console.log(picocolors.bold(`${picocolors.yellowBright(ICONS.warn)} ${picocolors.yellowBright("Skipping")} ${normalizeSpaces(`${picocolors.underline(picocolors.blueBright(actionName))} ${picocolors.white(reasonTitle)} ${picocolors.redBright(reasonSkipAction)} ${reasonType} ${textDirectAction} ${picocolors.redBright(reasonEndText)}`)}.`));
216
+ },
217
+ ON_ERROR: (options) => {
218
+ const { actionName, textDirectAction = "to", error } = options;
219
+ const errorMsg = isError(error) ? error.message : "Something went wrong";
220
+ console.error(picocolors.bold(`${picocolors.redBright(ICONS.error)} ${picocolors.redBright("Error")} ${normalizeSpaces(`${textDirectAction} ${picocolors.underline(picocolors.blueBright(actionName))},`)} ${joinLines("because: ", "", ` ${picocolors.bold(picocolors.red(ICONS.arrowRight))} ${picocolors.inverse(picocolors.red(normalizeSpaces(errorMsg)))}`)}`));
221
+ },
222
+ ON_PROCESS: (options) => {
223
+ const { actionName, count, nameDirect, textDirectFolder = "in" } = options;
224
+ console.log(`${picocolors.bold(" " + picocolors.whiteBright(ICONS.bullet))} ${picocolors.italic(`${picocolors.white(count + ".")} ${normalizeSpaces(`${picocolors.white(actionName)} ${picocolors.magentaBright(textDirectFolder)} ${picocolors.bold(picocolors.underline(picocolors.blue(nameDirect)))}.`)}`)}`);
225
+ },
226
+ ON_PROCESS_COPY: (options) => {
227
+ const { actionName, count, copyTo, copyFrom, textFrom = "from", textArrow = "➔" } = options;
228
+ console.log(`${picocolors.bold(" " + picocolors.whiteBright(ICONS.bullet))} ${picocolors.italic(`${picocolors.white(count + ".")} ${normalizeSpaces(`${picocolors.white(actionName)} ${picocolors.yellow(textFrom)} '${picocolors.bold(picocolors.underline(picocolors.cyanBright(copyFrom)))}' ${picocolors.bold(picocolors.gray(textArrow))} '${picocolors.bold(picocolors.underline(picocolors.cyanBright(copyTo)))}'.`)}`)}`);
229
+ },
230
+ ON_PROCESS_COPY_ERROR: (options) => {
231
+ const { actionName, count, errorReason, copyFrom, index, indexKey, textFrom = "from", textReason = "because" } = options;
232
+ const errorReasonText = isError(errorReason) ? errorReason.message : String(errorReason);
233
+ const atIndexText = isNumber(index) ? picocolors.blueBright(` (at${isNonEmptyString(indexKey) ? ` '${indexKey}' ` : " "}index: ${picocolors.magentaBright(index)}) `) : " ";
234
+ console.log(`${picocolors.bold(" " + picocolors.whiteBright(ICONS.bullet))} ${picocolors.italic(`${picocolors.white(count + ".")} ${normalizeSpaces(`${picocolors.redBright(actionName)} ${picocolors.yellow(textFrom)} '${picocolors.bold(picocolors.underline(picocolors.cyanBright(copyFrom)))}'${atIndexText}${picocolors.bold(picocolors.gray(textReason))} ${picocolors.redBright(errorReasonText)}.`)}`)}`);
235
+ },
236
+ ON_PROCESS_REFERENCING: (options) => {
237
+ const { actionName, count, referenceTo, referenceFrom, textFrom = "from", textArrow = "➔" } = options;
238
+ console.log(`${picocolors.bold(" " + picocolors.whiteBright(ICONS.bullet))} ${picocolors.italic(`${picocolors.white(count + ".")} ${normalizeSpaces(`${picocolors.white(actionName)} ${picocolors.magentaBright(textFrom)} ${picocolors.bold(picocolors.underline(picocolors.cyanBright(referenceFrom)))} ${picocolors.bold(picocolors.gray(textArrow))} ${picocolors.bold(picocolors.underline(picocolors.blueBright(referenceTo)))}.`)}`)}`);
239
+ }
240
+ };
241
+ function stripLineArtifacts(line, options) {
242
+ let out = line.replace(/^[ \t]*\/\/\s*(?:\.\.\/|\.\/)*[^ \n]*?(?:src|node_modules)\/[^\n]*\n?/gm, "").replace(/\/\/\s*eslint[^\n]*/g, "");
243
+ if (options.removeSourceMap) out = out.replace(/^[ \t]*\/\/[#@]\s*sourceMappingURL\s*=\s*\S+/gm, "");
244
+ out = out.replace(/(^[ \t]*\/\/[#@]\s*sourceMappingURL\s*=\s*\S+)(?:\r?\n\1)+/gm, "$1");
245
+ return out;
246
+ }
247
+ function splitLines(content) {
248
+ return content.split(/\r\n|\n/);
249
+ }
250
+ function fileHasTarget(lines, options) {
251
+ return lines.some((line, i, arr) => {
252
+ if (isTargetComment(line, options)) return true;
253
+ if (options.removeAdjacentEmptyLines && EMPTY_LINE_RE.test(line) && isAdjacentToTarget(arr, i, options)) return true;
254
+ return false;
255
+ });
256
+ }
257
+ function cleanBuildArtifactsCore(lines, options) {
258
+ const seenSourceMap = /* @__PURE__ */ new Set();
259
+ return lines.filter((line, i, arr) => {
260
+ if (SOURCE_MAP_RE.test(line)) {
261
+ const key = line.trim();
262
+ if (seenSourceMap.has(key)) return false;
263
+ seenSourceMap.add(key);
264
+ if (options.removeSourceMap) return false;
265
+ return true;
266
+ }
267
+ if (options.removeRegion && REGION_RE.test(line)) return false;
268
+ if (isTargetComment(line, options)) return false;
269
+ if (options.removeAdjacentEmptyLines && EMPTY_LINE_RE.test(line) && isAdjacentToTarget(arr, i, options)) return false;
270
+ return true;
271
+ }).map((line) => stripLineArtifacts(line, options));
272
+ }
273
+ async function runCleanBuildArtifacts({ patterns: pattern, options, fileTest, logAction }) {
274
+ if (!isPlainObject(options)) options = DEFAULT_CLEAN_OPTION;
275
+ else options = {
276
+ ...DEFAULT_CLEAN_OPTION,
277
+ ...options
278
+ };
279
+ const { patternOptions, logLevel: loggerLevel, removeAdjacentEmptyLines, removeRegion, removeSourceMap } = options;
280
+ try {
281
+ if (canLog(loggerLevel, VERBOSE_LOG)) console.log(joinLinesLoose(logAction.title, ""));
282
+ const patterns = [...toStringSet(pattern)];
283
+ const cleanPatternOptions = resolvePatternOptions(patternOptions, DEFAULT_CLEAN_PATTERN_POLICY);
284
+ const files = (await fastGlob(patterns, cleanPatternOptions)).sort();
285
+ if (canLog(loggerLevel, VERBOSE_LOG)) {
286
+ BUILD_LOGGER.SECTION("Options", { icon: "⚙️ " });
287
+ BUILD_LOGGER.OPTIONS("pattern", patterns, BUILD_LOGGER.SOURCE_OF(patterns, void 0), true);
288
+ BUILD_LOGGER.OPTIONS("options.patternOptions", cleanPatternOptions, sourceOfPatternOptions(cleanPatternOptions, DEFAULT_CLEAN_OPTION.patternOptions));
289
+ BUILD_LOGGER.OPTIONS("options.removeSourceMap", removeSourceMap, BUILD_LOGGER.SOURCE_OF(removeSourceMap, DEFAULT_CLEAN_OPTION.removeSourceMap));
290
+ BUILD_LOGGER.OPTIONS("options.removeRegion", removeRegion, BUILD_LOGGER.SOURCE_OF(removeRegion, DEFAULT_CLEAN_OPTION.removeRegion));
291
+ BUILD_LOGGER.OPTIONS("options.removeAdjacentEmptyLines", removeAdjacentEmptyLines, BUILD_LOGGER.SOURCE_OF(removeAdjacentEmptyLines, DEFAULT_CLEAN_OPTION.removeAdjacentEmptyLines));
292
+ BUILD_LOGGER.OPTIONS("options.logLevel", loggerLevel, BUILD_LOGGER.SOURCE_OF(loggerLevel, DEFAULT_CLEAN_OPTION.logLevel));
293
+ BUILD_LOGGER.NEW_LINE();
294
+ BUILD_LOGGER.ON_STARTING({
295
+ ...logAction.onStart,
296
+ actionName: logAction.actionName
297
+ });
298
+ }
299
+ let count = 0;
300
+ for (const filePath of files) {
301
+ if (!new RegExp(fileTest).test(filePath)) continue;
302
+ let content;
303
+ try {
304
+ content = await fsExtra.promises.readFile(filePath, "utf8");
305
+ } catch (err) {
306
+ if (err.code === "ENOENT") continue;
307
+ throw err;
308
+ }
309
+ const lines = splitLines(content);
310
+ if (!fileHasTarget(lines, options)) continue;
311
+ const finalContent = cleanBuildArtifactsCore(lines, options).join(EOL);
312
+ if (finalContent === content) continue;
313
+ count++;
314
+ try {
315
+ await fsExtra.promises.writeFile(filePath, finalContent, "utf8");
316
+ } catch (err) {
317
+ if (err.code === "ENOENT") continue;
318
+ throw err;
319
+ }
320
+ if (canLog(loggerLevel, VERBOSE_LOG)) BUILD_LOGGER.ON_PROCESS({
321
+ ...logAction.onProcess,
322
+ actionName: logAction.actionName,
323
+ count,
324
+ nameDirect: filePath
325
+ });
326
+ }
327
+ if (canLog(loggerLevel, VERBOSE_LOG)) if (count > 0) BUILD_LOGGER.ON_FINISH({
328
+ actionName: logAction.actionName,
329
+ count
330
+ });
331
+ else BUILD_LOGGER.ON_SKIPPING({
332
+ ...logAction.onSkipping,
333
+ actionName: logAction.actionName,
334
+ reasonEndText: logAction.onSkipping?.reasonEndText ?? "cleaning"
335
+ });
336
+ } catch (error) {
337
+ if (loggerLevel !== "silent") BUILD_LOGGER.ON_ERROR({
338
+ ...logAction.onError,
339
+ actionName: logAction.actionName,
340
+ error
341
+ });
342
+ }
343
+ }
344
+ const commandCjbaIdentity = new CommandIdentity({ defaultCommandName: "clean-js-build-artifacts" });
345
+ const cleanJsBuildArtifacts = async (pattern, options = {}) => {
346
+ const logLevel = resolveLogVerbosity(options, DEFAULT_CLEAN_OPTION.logLevel);
347
+ return await runCleanBuildArtifacts({
348
+ patterns: pattern,
349
+ options: {
350
+ ...options,
351
+ logLevel
352
+ },
353
+ fileTest: JS_OUTPUT_FILE_RE,
354
+ logAction: {
355
+ actionName: "Cleaning JS Build Artifacts",
356
+ title: isNonEmptyString(options.__commandTitle) ? options.__commandTitle : commandCjbaIdentity.utility()
357
+ }
358
+ });
359
+ };
360
+ const commandCtbaIdentity = new CommandIdentity({ defaultCommandName: "clean-types-build-artifacts" });
361
+ const cleanTypesBuildArtifacts = async (pattern, options = {}) => {
362
+ const logLevel = resolveLogVerbosity(options, DEFAULT_CLEAN_OPTION.logLevel);
363
+ return await runCleanBuildArtifacts({
364
+ patterns: pattern,
365
+ options: {
366
+ ...options,
367
+ logLevel
368
+ },
369
+ fileTest: TS_DECLARATION_FILE_RE,
370
+ logAction: {
371
+ actionName: "Cleaning Types Build Artifacts",
372
+ title: isNonEmptyString(options.__commandTitle) ? options.__commandTitle : commandCtbaIdentity.utility()
373
+ }
374
+ });
375
+ };
376
+ const DEFAULT_CFTD_OPTIONS = {
377
+ fileName: void 0,
378
+ outputRoot: "dist",
379
+ absoluteTarget: false,
380
+ ignoreMissingSourceError: false
381
+ };
382
+ const validateItem = (item, index) => {
383
+ const indexText = isNumber(index) ? ` at index ${index}` : "";
384
+ if (!isPlainObject(item)) throw new TypeError(`Invalid item${indexText}: must be a 'plain object'!`);
385
+ if (!isNonEmptyString(item.source) && !isNonEmptyString(item.target)) throw new TypeError(`Invalid item${indexText}: 'source' and 'target' must be 'non-empty string'!`);
386
+ if (!isNonEmptyString(item.source)) throw new TypeError(`Invalid item${indexText}: 'source' must be 'non-empty string'!`);
387
+ if (!isNonEmptyString(item.target)) throw new TypeError(`Invalid item${indexText}: 'target' must be 'non-empty string'!`);
388
+ if (!isUndefined(item.fileName) && !isNonEmptyString(item.fileName)) throw new TypeError(`Invalid item${indexText}: 'fileName' must be 'non-empty string' if provided!`);
389
+ if (!isUndefined(item.outputRoot) && !isNonEmptyString(item.outputRoot)) throw new TypeError(`Invalid item${indexText}: 'outputRoot' must be 'non-empty string' if provided!`);
390
+ if (!isUndefined(item.absoluteTarget) && !isBoolean(item.absoluteTarget)) throw new TypeError(`Invalid item${indexText}: 'absoluteTarget' must be a 'boolean' if provided!`);
391
+ };
392
+ function buildCopySummary(successCount, errorCount, duplicateCount, label) {
393
+ return picocolors.bold(joinLinesLoose(joinInline(picocolors.yellowBright("⚠"), picocolors.blueBright(label) + picocolors.gray(" -"), picocolors.whiteBright(successCount > 0 ? "Some" : "All"), picocolors.whiteBright("files"), picocolors.redBright("failed to copy") + ":"), successCount < 1 ? false : ` ${picocolors.greenBright("✔")} ${picocolors.greenBright(successCount)} ${plural(successCount, "file")} copied.`, errorCount < 1 ? false : ` ${picocolors.redBright("✖")} ${picocolors.redBright(errorCount)} ${plural(errorCount, "file")} failed.`, duplicateCount < 1 ? false : ` ${picocolors.yellowBright("⚠")} ${picocolors.yellowBright(duplicateCount)} ${plural(duplicateCount, "duplicate operation")} skipped.`));
394
+ }
395
+ function buildOperationKey(item) {
396
+ return [
397
+ item.source,
398
+ item.target,
399
+ item.fileName ?? "",
400
+ item.outputRoot ?? DEFAULT_CFTD_OPTIONS.outputRoot,
401
+ item.absoluteTarget ? 1 : 0
402
+ ].join("|");
403
+ }
404
+ function createCopyFileToDestParameterSet(items) {
405
+ return new Set(isArray(items) ? items : [items]);
406
+ }
407
+ const commandCftdIdentity = new CommandIdentity({ defaultCommandName: "copy-file-to-dest" });
408
+ async function copyFileToDest(parameter, options = {}) {
409
+ const loggerLevel = resolveLogVerbosity(options);
410
+ try {
411
+ const { __commandTitle } = options;
412
+ if (canLog(loggerLevel, VERBOSE_LOG)) console.log(joinLinesLoose(isNonEmptyString(__commandTitle) ? __commandTitle : commandCftdIdentity.utility(), ""));
413
+ if (isArray(parameter) || isSet(parameter)) {
414
+ let i = 0;
415
+ for (const item of parameter) validateItem(item, i++);
416
+ } else if (isPlainObject(parameter)) validateItem(parameter);
417
+ else throw new TypeError("Parameter argument must be a 'plain object', 'array of plain objects' or an 'set of plain objects'!");
418
+ const list = [...toObjectSet(parameter)];
419
+ const uniqueLists = [];
420
+ const seenOperations = /* @__PURE__ */ new Set();
421
+ if (canLog(loggerLevel, VERBOSE_LOG)) {
422
+ BUILD_LOGGER.SECTION("Options", { icon: "⚙️ " });
423
+ list.forEach((item, i) => {
424
+ const { source, target, fileName = DEFAULT_CFTD_OPTIONS.fileName, outputRoot = DEFAULT_CFTD_OPTIONS.outputRoot, absoluteTarget = DEFAULT_CFTD_OPTIONS.absoluteTarget, ignoreMissingSourceError = DEFAULT_CFTD_OPTIONS.ignoreMissingSourceError } = item;
425
+ const defaultFileName = fileName ?? path.basename(source);
426
+ const indexText = list.length > 1 ? `[${i}]` : "";
427
+ BUILD_LOGGER.OPTIONS(`options.copy${indexText}.source`, source, "overridden", true);
428
+ BUILD_LOGGER.OPTIONS(`options.copy${indexText}.target`, target, "overridden", true);
429
+ BUILD_LOGGER.OPTIONS(`options.copy${indexText}.fileName`, fileName || defaultFileName, BUILD_LOGGER.SOURCE_OF(fileName, DEFAULT_CFTD_OPTIONS.fileName));
430
+ BUILD_LOGGER.OPTIONS(`options.copy${indexText}.outputRoot`, outputRoot, BUILD_LOGGER.SOURCE_OF(outputRoot, DEFAULT_CFTD_OPTIONS.outputRoot));
431
+ BUILD_LOGGER.OPTIONS(`options.copy${indexText}.absoluteTarget`, absoluteTarget, BUILD_LOGGER.SOURCE_OF(absoluteTarget, DEFAULT_CFTD_OPTIONS.absoluteTarget));
432
+ BUILD_LOGGER.OPTIONS(`options.copy${indexText}.ignoreMissingSourceError`, ignoreMissingSourceError, BUILD_LOGGER.SOURCE_OF(ignoreMissingSourceError, DEFAULT_CFTD_OPTIONS.ignoreMissingSourceError));
433
+ if (i < list.length - 1) console.log(picocolors.gray(" =========================================================================="));
434
+ });
435
+ BUILD_LOGGER.OPTIONS("options.logLevel", loggerLevel, BUILD_LOGGER.SOURCE_OF(loggerLevel, DEFAULT_LOG_LEVEL));
436
+ BUILD_LOGGER.NEW_LINE();
437
+ BUILD_LOGGER.ON_STARTING({
438
+ actionName: "Copy File",
439
+ textDirectAction: "action:"
440
+ });
441
+ }
442
+ let count = 0;
443
+ let errorCount = 0;
444
+ let duplicateCount = 0;
445
+ for (let index = 0; index < list.length; index++) {
446
+ const item = list[index];
447
+ const key = buildOperationKey(item);
448
+ if (seenOperations.has(key)) {
449
+ duplicateCount++;
450
+ if (canLog(loggerLevel, VERBOSE_LOG)) BUILD_LOGGER.ON_SKIPPING({
451
+ actionName: "Copy File",
452
+ reasonType: "",
453
+ textDirectAction: "at",
454
+ reasonSkipAction: "duplicate operation",
455
+ reasonEndText: item.source + " " + picocolors.blueBright(`('parameter' index: ${picocolors.magentaBright(index)})`)
456
+ });
457
+ continue;
458
+ }
459
+ seenOperations.add(key);
460
+ uniqueLists.push({
461
+ item,
462
+ index
463
+ });
464
+ }
465
+ const procCwd = process.cwd();
466
+ for (let i = 0; i < uniqueLists.length; i++) {
467
+ const uniqList = uniqueLists[i];
468
+ count++;
469
+ const { source, target, fileName = DEFAULT_CFTD_OPTIONS.fileName, outputRoot = DEFAULT_CFTD_OPTIONS.outputRoot, absoluteTarget = DEFAULT_CFTD_OPTIONS.absoluteTarget, ignoreMissingSourceError = DEFAULT_CFTD_OPTIONS.ignoreMissingSourceError } = uniqList.item;
470
+ const absSource = path.resolve(procCwd, source);
471
+ if (!await fsExtra.pathExists(absSource)) {
472
+ if (ignoreMissingSourceError) continue;
473
+ errorCount++;
474
+ if (loggerLevel !== "silent") BUILD_LOGGER.ON_PROCESS_COPY_ERROR({
475
+ copyFrom: source,
476
+ index: uniqList.index,
477
+ indexKey: "parameter",
478
+ count: loggerLevel === "error" ? errorCount : count,
479
+ actionName: "Failed to Copy File",
480
+ errorReason: "the source file was not found"
481
+ });
482
+ } else {
483
+ const absTargetDir = path.resolve(procCwd, absoluteTarget ? "" : outputRoot, target);
484
+ const absTargetFile = path.join(absTargetDir, fileName ?? path.basename(source));
485
+ await fsExtra.ensureDir(absTargetDir);
486
+ await fsExtra.copy(absSource, absTargetFile);
487
+ const relSrc = path.relative(procCwd, absSource).replace(/\\/g, "/");
488
+ const relDest = path.relative(procCwd, absTargetFile).replace(/\\/g, "/");
489
+ if (canLog(loggerLevel, VERBOSE_LOG)) BUILD_LOGGER.ON_PROCESS_COPY({
490
+ actionName: "File copied",
491
+ count,
492
+ copyFrom: relSrc,
493
+ copyTo: relDest
494
+ });
495
+ }
496
+ }
497
+ const successCount = count - errorCount;
498
+ if ((errorCount > 0 || duplicateCount > 0) && loggerLevel !== "silent" && !canLog(loggerLevel, VERBOSE_LOG)) console.log(buildCopySummary(successCount, errorCount, duplicateCount, "[Copy File to Dest]"));
499
+ if (canLog(loggerLevel, VERBOSE_LOG)) if (count > 0 && errorCount === 0 && duplicateCount === 0) BUILD_LOGGER.ON_FINISH({
500
+ textSuccess: "Successfully",
501
+ actionName: "copied",
502
+ count
503
+ });
504
+ else if (successCount > 0) console.log(buildCopySummary(successCount, errorCount, duplicateCount, "[Copy File to Dest]"));
505
+ else if (successCount === 0 && errorCount !== 0) BUILD_LOGGER.ON_SKIPPING({
506
+ actionName: "\"Copy File\"",
507
+ reasonSkipAction: "failed",
508
+ reasonEndText: `${count > 1 ? "all " : ""}files`,
509
+ reasonType: "to",
510
+ textDirectAction: "copy"
511
+ });
512
+ else BUILD_LOGGER.ON_SKIPPING({
513
+ actionName: "\"Copy File\"",
514
+ reasonSkipAction: errorCount > 0 ? "nothing found" : "nothing",
515
+ reasonEndText: "copy"
516
+ });
517
+ } catch (error) {
518
+ if (loggerLevel !== "silent") BUILD_LOGGER.ON_ERROR({
519
+ actionName: "Copying File",
520
+ error
521
+ });
522
+ }
523
+ }
524
+ const DEFAULT_ECI_PATTERN_POLICY = {
525
+ filesOnly: true,
526
+ forceUnique: true
527
+ };
528
+ const resolvedEciPatternOption = resolvePatternOptions(defaultPatternOptions, DEFAULT_ECI_PATTERN_POLICY);
529
+ const DEFAULT_ECI_OPTIONS = {
530
+ cssImportPath: [],
531
+ dedupe: true,
532
+ sort: false,
533
+ minify: false,
534
+ patternOptions: resolvedEciPatternOption,
535
+ logLevel: DEFAULT_LOG_LEVEL
536
+ };
537
+ function inlineCssImports(code) {
538
+ return code.replace(/((?:import\s+["'][^"']+\.css["'];\s*\n?|require\(["'][^"']+\.css["']\);\s*\n?){2,})/g, (block) => block.split(/\n+/).map((l) => l.trim()).join(""));
539
+ }
540
+ function createCssStatements(kind, cssImports) {
541
+ return cssImports.map((p) => kind === "cjs" ? `require("${p}");` : `import "${p}";`);
542
+ }
543
+ function getMissingCssStatements(body, cssImports, kind, dedupe) {
544
+ const cleanedBody = body;
545
+ const cssStatements = createCssStatements(kind, cssImports);
546
+ return {
547
+ missing: dedupe ? cssStatements.filter((stmt) => !cleanedBody.includes(stmt)) : cssStatements,
548
+ cleanedBody
549
+ };
550
+ }
551
+ function injectCssSmart({ shebang, banner, directives, rest, cssStatements, kind, minify }) {
552
+ let out = minify ? shebang.trim() + EOL : shebang;
553
+ out += minify ? banner.trim() + EOL : banner;
554
+ let finalDirectives = stripUseStrict(directives, {
555
+ trimEnd: minify,
556
+ trimStart: minify
557
+ });
558
+ if (kind === "cjs") finalDirectives = `"use strict";${EOL}` + finalDirectives.trimStart();
559
+ out += finalDirectives;
560
+ out += cssStatements.join(EOL) + (minify ? "" : EOL);
561
+ out += rest.replace(/^\n+/, minify ? "" : EOL);
562
+ return out.trimStart();
563
+ }
564
+ function normalizeCssImports(input) {
565
+ return flattenStrings(isArray(input) ? input : [input]).map((s) => s.trim()).filter(Boolean);
566
+ }
567
+ const commandEciIdentity = new CommandIdentity({ defaultCommandName: "ensure-css-import" });
568
+ const ensureCssImport = async (pattern, options) => {
569
+ const loggerLevel = resolveLogVerbosity(options, DEFAULT_ECI_OPTIONS.logLevel);
570
+ try {
571
+ const { patternOptions = DEFAULT_ECI_OPTIONS.patternOptions, cssImportPath, dedupe = DEFAULT_ECI_OPTIONS.dedupe, sort = DEFAULT_ECI_OPTIONS.sort, minify = DEFAULT_ECI_OPTIONS.minify, __commandTitle } = options;
572
+ if (canLog(loggerLevel, VERBOSE_LOG)) console.log(joinLinesLoose(isNonEmptyString(__commandTitle) ? __commandTitle : commandEciIdentity.utility(), ""));
573
+ const patterns = [...toStringSet(pattern)];
574
+ const cleanPatternOptions = resolvePatternOptions(patternOptions, DEFAULT_ECI_PATTERN_POLICY);
575
+ let cssImports = normalizeCssImports(cssImportPath);
576
+ if (cssImports.length === 0) throw new Error("`cssImportPath` option must not be empty.");
577
+ if (dedupe) cssImports = Array.from(new Set(cssImports));
578
+ if (sort) cssImports.sort();
579
+ if (canLog(loggerLevel, VERBOSE_LOG)) {
580
+ BUILD_LOGGER.SECTION("Options", { icon: "⚙️ " });
581
+ BUILD_LOGGER.OPTIONS("pattern", patterns, BUILD_LOGGER.SOURCE_OF(patterns, void 0), true);
582
+ BUILD_LOGGER.OPTIONS("options.patternOptions", cleanPatternOptions, sourceOfPatternOptions(cleanPatternOptions, DEFAULT_ECI_OPTIONS.patternOptions));
583
+ BUILD_LOGGER.OPTIONS("options.cssImportPath", cssImports, BUILD_LOGGER.SOURCE_OF(cssImports, DEFAULT_ECI_OPTIONS.cssImportPath), true);
584
+ BUILD_LOGGER.OPTIONS("options.dedupe", dedupe, BUILD_LOGGER.SOURCE_OF(dedupe, DEFAULT_ECI_OPTIONS.dedupe));
585
+ BUILD_LOGGER.OPTIONS("options.sort", sort, BUILD_LOGGER.SOURCE_OF(sort, DEFAULT_ECI_OPTIONS.sort));
586
+ BUILD_LOGGER.OPTIONS("options.minify", minify, BUILD_LOGGER.SOURCE_OF(minify, DEFAULT_ECI_OPTIONS.minify));
587
+ BUILD_LOGGER.OPTIONS("options.logLevel", loggerLevel, BUILD_LOGGER.SOURCE_OF(loggerLevel, DEFAULT_ECI_OPTIONS.logLevel));
588
+ BUILD_LOGGER.NEW_LINE();
589
+ BUILD_LOGGER.ON_STARTING({ actionName: "Ensuring CSS Import" });
590
+ }
591
+ const files = (await fastGlob(patterns, cleanPatternOptions)).sort();
592
+ let count = 0;
593
+ for (const filePath of files) {
594
+ if (!JS_OUTPUT_FILE_RE.test(filePath)) continue;
595
+ let content;
596
+ try {
597
+ content = await fsExtra.promises.readFile(filePath, "utf8");
598
+ } catch (err) {
599
+ if (err.code === "ENOENT") continue;
600
+ throw err;
601
+ }
602
+ const { banner, body, shebang } = extractAndHoistBanner(content);
603
+ const kind = detectModuleKindFromContent(content);
604
+ const { missing, cleanedBody } = getMissingCssStatements(body, cssImports, kind, dedupe);
605
+ if (missing.length === 0) continue;
606
+ const { directives, rest } = extractDirectives(cleanedBody);
607
+ let updated = injectCssSmart({
608
+ shebang,
609
+ banner,
610
+ directives,
611
+ rest,
612
+ kind,
613
+ minify: options.minify,
614
+ cssStatements: missing
615
+ });
616
+ if (options.minify) updated = inlineCssImports(updated);
617
+ if (updated !== content) {
618
+ try {
619
+ await fsExtra.promises.writeFile(filePath, updated, "utf8");
620
+ } catch (err) {
621
+ if (err.code === "ENOENT") continue;
622
+ throw err;
623
+ }
624
+ count++;
625
+ if (canLog(loggerLevel, VERBOSE_LOG)) BUILD_LOGGER.ON_PROCESS({
626
+ actionName: "CSS Import",
627
+ count,
628
+ nameDirect: filePath
629
+ });
630
+ }
631
+ }
632
+ if (canLog(loggerLevel, VERBOSE_LOG)) if (count > 0) BUILD_LOGGER.ON_FINISH({
633
+ actionName: "Ensuring CSS Import",
634
+ count
635
+ });
636
+ else BUILD_LOGGER.ON_SKIPPING({
637
+ actionName: "Ensuring CSS Import",
638
+ reasonType: "file",
639
+ reasonEndText: "check"
640
+ });
641
+ } catch (error) {
642
+ if (loggerLevel !== "silent") BUILD_LOGGER.ON_ERROR({
643
+ actionName: "Ensuring CSS Import",
644
+ error
645
+ });
646
+ }
647
+ };
648
+ const DEFAULT_EFN_PATTERN_POLICY = {
649
+ filesOnly: true,
650
+ forceUnique: true
651
+ };
652
+ const resolvedEfnPatternOption = resolvePatternOptions(defaultPatternOptions, DEFAULT_EFN_PATTERN_POLICY);
653
+ const DEFAULT_EFN_OPTIONS = {
654
+ patternOptions: resolvedEfnPatternOption,
655
+ logLevel: DEFAULT_LOG_LEVEL
656
+ };
657
+ const commandEfnIdentity = new CommandIdentity({ defaultCommandName: "ensure-final-newline" });
658
+ const ensureFinalNewline = async (pattern, options = {}) => {
659
+ const loggerLevel = resolveLogVerbosity(options, DEFAULT_EFN_OPTIONS.logLevel);
660
+ try {
661
+ const { __commandTitle, patternOptions = DEFAULT_EFN_OPTIONS.patternOptions } = options;
662
+ if (canLog(loggerLevel, VERBOSE_LOG)) console.log(joinLinesLoose(isNonEmptyString(__commandTitle) ? __commandTitle : commandEfnIdentity.utility(), ""));
663
+ const patterns = [...toStringSet(pattern)];
664
+ const cleanPatternOptions = resolvePatternOptions(patternOptions, DEFAULT_EFN_PATTERN_POLICY);
665
+ if (canLog(loggerLevel, VERBOSE_LOG)) {
666
+ BUILD_LOGGER.SECTION("Options", { icon: "⚙️ " });
667
+ BUILD_LOGGER.OPTIONS("pattern", patterns, BUILD_LOGGER.SOURCE_OF(patterns, void 0), true);
668
+ BUILD_LOGGER.OPTIONS("options.patternOptions", cleanPatternOptions, sourceOfPatternOptions(cleanPatternOptions, DEFAULT_EFN_OPTIONS.patternOptions));
669
+ BUILD_LOGGER.OPTIONS("options.logLevel", loggerLevel, BUILD_LOGGER.SOURCE_OF(loggerLevel, DEFAULT_EFN_OPTIONS.logLevel));
670
+ BUILD_LOGGER.NEW_LINE();
671
+ BUILD_LOGGER.ON_STARTING({ actionName: "Ensuring Final Newline" });
672
+ }
673
+ const files = (await fastGlob(patterns, cleanPatternOptions)).sort();
674
+ let count = 0;
675
+ for (const filePath of files) {
676
+ let content;
677
+ try {
678
+ content = await fsExtra.promises.readFile(filePath, "utf8");
679
+ } catch (err) {
680
+ if (err.code === "ENOENT") continue;
681
+ throw err;
682
+ }
683
+ const normalized = content.replace(/(\r?\n)*$/, EOL);
684
+ if (normalized === content) continue;
685
+ try {
686
+ await fsExtra.promises.writeFile(filePath, normalized, "utf8");
687
+ } catch (err) {
688
+ if (err.code === "ENOENT") continue;
689
+ throw err;
690
+ }
691
+ count++;
692
+ if (canLog(loggerLevel, VERBOSE_LOG)) BUILD_LOGGER.ON_PROCESS({
693
+ actionName: "Final Newline",
694
+ count,
695
+ nameDirect: filePath
696
+ });
697
+ }
698
+ if (canLog(loggerLevel, VERBOSE_LOG)) if (count > 0) BUILD_LOGGER.ON_FINISH({
699
+ actionName: "Ensuring Final Newline",
700
+ count
701
+ });
702
+ else if (files.length < 1) BUILD_LOGGER.ON_SKIPPING({
703
+ actionName: "Ensuring Final Newline",
704
+ reasonSkipAction: `no files found matching the pattern${picocolors.reset(",")}`,
705
+ reasonType: "",
706
+ textDirectAction: "no need to fix",
707
+ reasonEndText: "end of file (EOF)"
708
+ });
709
+ else BUILD_LOGGER.ON_SKIPPING({
710
+ actionName: "Ensuring Final Newline",
711
+ reasonSkipAction: `all files are valid${picocolors.reset(",")}`,
712
+ reasonType: "",
713
+ textDirectAction: "no need to fix",
714
+ reasonEndText: "end of file (EOF)"
715
+ });
716
+ } catch (error) {
717
+ if (loggerLevel !== "silent") BUILD_LOGGER.ON_ERROR({
718
+ actionName: "Ensuring Final Newline",
719
+ error
720
+ });
721
+ }
722
+ };
723
+ const DEFAULT_GRI_PATTERN_POLICY = {
724
+ filesOnly: true,
725
+ forceUnique: true
726
+ };
727
+ const resolvedGriPatternOption = resolvePatternOptions(defaultPatternOptions, DEFAULT_GRI_PATTERN_POLICY);
728
+ const DEFAULT_GRI_OPTIONS = {
729
+ outDir: "dist/.references",
730
+ outFileName: "index.d.ts",
731
+ inputDirReference: "dist",
732
+ withExportTypes: false,
733
+ banner: true,
734
+ onlyDeclarations: true,
735
+ patternOptions: resolvedGriPatternOption,
736
+ logLevel: DEFAULT_LOG_LEVEL
737
+ };
738
+ function normalizeRelative(from, to) {
739
+ return path.relative(from, to).replace(/\\/g, "/").replace(/^([^./])/, "./$1");
740
+ }
741
+ const resolveExportModulePath = (relativePath) => {
742
+ const parsed = path.parse(relativePath);
743
+ let baseName = parsed.name;
744
+ if (baseName.endsWith(".d")) baseName = baseName.slice(0, -2);
745
+ return path.join(parsed.dir, baseName).replace(/\\/g, "/");
746
+ };
747
+ const validateOut = ({ outDir, outFileName, inputDirReference }) => {
748
+ const normalizePath = (value) => {
749
+ const trimmed = value.trim();
750
+ return trimmed.endsWith("/") ? trimmed.slice(0, -1) : trimmed;
751
+ };
752
+ const normalizeFileName = (value) => {
753
+ const trimmed = value.trim();
754
+ if (trimmed.includes("/") || trimmed.includes("\\")) throw new Error(`Invalid outFileName: "${value}"`);
755
+ return trimmed;
756
+ };
757
+ return {
758
+ outDir: normalizePath(outDir),
759
+ inputDirReference: normalizePath(inputDirReference),
760
+ outFileName: normalizeFileName(outFileName)
761
+ };
762
+ };
763
+ const resolveBanner = async (banner) => {
764
+ if (banner === false) return "";
765
+ if (banner === true) return await generatePackageBanner() + EOL;
766
+ const resolved = await banner;
767
+ return isNonEmptyString(resolved) ? resolved : "";
768
+ };
769
+ const commandGriIdentity = new CommandIdentity({ defaultCommandName: "generate-reference-index" });
770
+ const generateReferenceIndex = async (pattern, options = {}) => {
771
+ let _withExportTypes = DEFAULT_GRI_OPTIONS.withExportTypes;
772
+ const loggerLevel = resolveLogVerbosity(options, DEFAULT_GRI_OPTIONS.logLevel);
773
+ try {
774
+ const { __commandTitle, patternOptions = DEFAULT_GRI_OPTIONS.patternOptions, outDir: _outDir = DEFAULT_GRI_OPTIONS.outDir, outFileName: _outFileName = DEFAULT_GRI_OPTIONS.outFileName, inputDirReference: _inputDirReference = DEFAULT_GRI_OPTIONS.inputDirReference, withExportTypes = DEFAULT_GRI_OPTIONS.withExportTypes, banner = DEFAULT_GRI_OPTIONS.banner, onlyDeclarations = DEFAULT_GRI_OPTIONS.onlyDeclarations } = options;
775
+ _withExportTypes = withExportTypes;
776
+ if (canLog(loggerLevel, VERBOSE_LOG)) console.log(joinLinesLoose(isNonEmptyString(__commandTitle) ? __commandTitle : commandGriIdentity.utility(), ""));
777
+ const patterns = [...toStringSet(pattern)];
778
+ const cleanPatternOptions = resolvePatternOptions(patternOptions, DEFAULT_GRI_PATTERN_POLICY);
779
+ if (canLog(loggerLevel, VERBOSE_LOG)) {
780
+ BUILD_LOGGER.SECTION("Options", { icon: "⚙️ " });
781
+ BUILD_LOGGER.OPTIONS("pattern", patterns, BUILD_LOGGER.SOURCE_OF(patterns, void 0), true);
782
+ BUILD_LOGGER.OPTIONS("outDir", _outDir, sourceOf(_outDir, DEFAULT_GRI_OPTIONS.outDir));
783
+ BUILD_LOGGER.OPTIONS("options.patternOptions", cleanPatternOptions, sourceOfPatternOptions(cleanPatternOptions, DEFAULT_GRI_OPTIONS.patternOptions));
784
+ BUILD_LOGGER.OPTIONS("options.outFileName", _outFileName, sourceOf(_outFileName, DEFAULT_GRI_OPTIONS.outFileName));
785
+ BUILD_LOGGER.OPTIONS("options.inputDirReference", _inputDirReference, sourceOf(_inputDirReference, DEFAULT_GRI_OPTIONS.inputDirReference));
786
+ BUILD_LOGGER.OPTIONS("options.withExportTypes", withExportTypes, sourceOf(withExportTypes, DEFAULT_GRI_OPTIONS.withExportTypes));
787
+ BUILD_LOGGER.OPTIONS("options.banner", banner, sourceOf(banner, DEFAULT_GRI_OPTIONS.banner));
788
+ BUILD_LOGGER.OPTIONS("options.logLevel", loggerLevel, BUILD_LOGGER.SOURCE_OF(loggerLevel, DEFAULT_GRI_OPTIONS.logLevel));
789
+ BUILD_LOGGER.NEW_LINE();
790
+ BUILD_LOGGER.ON_STARTING({ actionName: "Generating References" });
791
+ }
792
+ let files = (await fastGlob(patterns, cleanPatternOptions)).sort();
793
+ if (onlyDeclarations) files = files.filter((file) => TS_DECLARATION_FILE_RE.test(file));
794
+ const { inputDirReference, outDir, outFileName } = validateOut({
795
+ outDir: _outDir,
796
+ outFileName: _outFileName,
797
+ inputDirReference: _inputDirReference
798
+ });
799
+ const outDirAbs = path.resolve(outDir);
800
+ const outFileAbs = path.join(outDirAbs, outFileName);
801
+ const outFileNormalize = path.relative(process.cwd(), outFileAbs).replace(/\\/g, "/");
802
+ const lines = /* @__PURE__ */ new Set();
803
+ let referenceCount = 0;
804
+ const inputDirRefAbs = path.resolve(inputDirReference);
805
+ const reference = files.map((f, i) => {
806
+ const referencedAbs = path.resolve(f);
807
+ if (!referencedAbs.startsWith(inputDirRefAbs + path.sep) || referencedAbs === outFileAbs) return;
808
+ const referencePath = normalizeRelative(path.dirname(outFileAbs), referencedAbs);
809
+ const displayPath = `${inputDirReference}/${path.relative(inputDirRefAbs, referencedAbs).replace(/\\/g, "/")}`;
810
+ if (canLog(loggerLevel, VERBOSE_LOG)) BUILD_LOGGER.ON_PROCESS_REFERENCING({
811
+ actionName: "Generated Reference",
812
+ count: i + 1,
813
+ referenceFrom: displayPath,
814
+ referenceTo: outFileNormalize
815
+ });
816
+ referenceCount++;
817
+ return `/// <reference path="${referencePath}" />`;
818
+ }).filter(Boolean);
819
+ if (Array.isArray(reference) && reference.length > 0) {
820
+ lines.add("//! References Paths:");
821
+ lines.add(reference.join(EOL));
822
+ }
823
+ if (canLog(loggerLevel, VERBOSE_LOG)) if (referenceCount > 0) BUILD_LOGGER.ON_FINISH({
824
+ actionName: "Generating Reference",
825
+ count: files.length,
826
+ typeCount: "reference"
827
+ });
828
+ else BUILD_LOGGER.ON_SKIPPING({
829
+ actionName: "Generating References",
830
+ reasonEndText: "referencing",
831
+ reasonType: "references"
832
+ });
833
+ if (withExportTypes) {
834
+ if (canLog(loggerLevel, VERBOSE_LOG)) {
835
+ console.log(picocolors.bold(picocolors.magentaBright(`${EOL}=======================================================================================${EOL}`)));
836
+ BUILD_LOGGER.ON_STARTING({ actionName: "Adding Exported Types" });
837
+ }
838
+ const exportLines = /* @__PURE__ */ new Set();
839
+ let exportCount = 0;
840
+ files.forEach((f) => {
841
+ const referencedAbs = path.resolve(f);
842
+ if (!referencedAbs.startsWith(inputDirRefAbs + path.sep) || referencedAbs === outFileAbs) return;
843
+ const exportModulePath = resolveExportModulePath(path.relative(inputDirRefAbs, referencedAbs).replace(/\\/g, "/"));
844
+ const line = `export * from "${normalizeRelative(path.dirname(outFileAbs), path.resolve(inputDirReference, exportModulePath))}";`;
845
+ if (!exportLines.has(line)) {
846
+ exportCount++;
847
+ const displayPath = `${inputDirReference}/${path.relative(inputDirRefAbs, referencedAbs).replace(/\\/g, "/")}`;
848
+ if (canLog(loggerLevel, VERBOSE_LOG)) BUILD_LOGGER.ON_PROCESS_REFERENCING({
849
+ actionName: "Exported Type",
850
+ count: exportCount,
851
+ referenceFrom: displayPath,
852
+ referenceTo: outFileNormalize
853
+ });
854
+ exportLines.add(line);
855
+ }
856
+ });
857
+ if (exportLines.size > 0) {
858
+ if (referenceCount > 0) lines.add("");
859
+ lines.add("//! Exported Types:");
860
+ lines.add([...exportLines].join(EOL));
861
+ if (canLog(loggerLevel, VERBOSE_LOG)) BUILD_LOGGER.ON_FINISH({
862
+ actionName: "Adding Exported Types",
863
+ count: exportLines.size,
864
+ typeCount: "type"
865
+ });
866
+ } else if (canLog(loggerLevel, VERBOSE_LOG)) BUILD_LOGGER.ON_SKIPPING({
867
+ actionName: "Adding Exported Types",
868
+ reasonEndText: "exporting",
869
+ reasonType: "types"
870
+ });
871
+ }
872
+ await fsExtra.ensureDir(outDirAbs);
873
+ if (lines.size === 0) {
874
+ const action = withExportTypes ? "reference and type export" : "reference";
875
+ lines.add(`// No files matched the given patterns and input dir references, skipping ${action} generation.`);
876
+ }
877
+ await fsExtra.promises.writeFile(outFileAbs, await resolveBanner(banner) + [...lines].join(EOL) + EOL);
878
+ } catch (error) {
879
+ if (loggerLevel !== "silent") BUILD_LOGGER.ON_ERROR({
880
+ actionName: "Generating References" + (_withExportTypes ? " and Adding Exported Types" : ""),
881
+ error
882
+ });
883
+ }
884
+ };
885
+ const DEFAULT_IB_PATTERN_POLICY = {
886
+ filesOnly: true,
887
+ forceUnique: true
888
+ };
889
+ const resolvedIbPatternOption = resolvePatternOptions(defaultPatternOptions, DEFAULT_IB_PATTERN_POLICY);
890
+ const DEFAULT_IB_OPTIONS = {
891
+ replaceBanner: false,
892
+ removeDuplicate: true,
893
+ bannerPosition: "after-existing",
894
+ patternOptions: resolvedIbPatternOption,
895
+ logLevel: DEFAULT_LOG_LEVEL
896
+ };
897
+ const commandIbIdentity = new CommandIdentity({ defaultCommandName: "inject-banner" });
898
+ const injectBanner = async (pattern, bannerText, options = {}) => {
899
+ const loggerLevel = resolveLogVerbosity(options, DEFAULT_LOG_LEVEL);
900
+ try {
901
+ const { __commandTitle, removeDuplicate = DEFAULT_IB_OPTIONS.removeDuplicate, bannerPosition = DEFAULT_IB_OPTIONS.bannerPosition, replaceBanner = DEFAULT_IB_OPTIONS.replaceBanner, patternOptions = DEFAULT_IB_OPTIONS.patternOptions } = options;
902
+ if (canLog(loggerLevel, VERBOSE_LOG)) console.log(joinLinesLoose(isNonEmptyString(__commandTitle) ? __commandTitle : commandIbIdentity.utility(), ""));
903
+ const patterns = [...toStringSet(pattern)];
904
+ const banners = toStringSet(bannerText, { parameterKey: "bannerText" });
905
+ const cleanPatternOptions = resolvePatternOptions(patternOptions, DEFAULT_IB_PATTERN_POLICY);
906
+ if (canLog(loggerLevel, VERBOSE_LOG)) {
907
+ BUILD_LOGGER.SECTION("Options", { icon: "⚙️ " });
908
+ BUILD_LOGGER.OPTIONS("pattern", patterns, BUILD_LOGGER.SOURCE_OF(patterns, void 0), true);
909
+ BUILD_LOGGER.OPTIONS("options.patternOptions", cleanPatternOptions, sourceOfPatternOptions(cleanPatternOptions, DEFAULT_IB_OPTIONS.patternOptions));
910
+ BUILD_LOGGER.OPTIONS("options.removeDuplicate", removeDuplicate, BUILD_LOGGER.SOURCE_OF(removeDuplicate, DEFAULT_IB_OPTIONS.removeDuplicate));
911
+ BUILD_LOGGER.OPTIONS("options.replaceBanner", replaceBanner, BUILD_LOGGER.SOURCE_OF(replaceBanner, DEFAULT_IB_OPTIONS.replaceBanner));
912
+ BUILD_LOGGER.OPTIONS("options.bannerPosition", bannerPosition, BUILD_LOGGER.SOURCE_OF(bannerPosition, DEFAULT_IB_OPTIONS.bannerPosition));
913
+ BUILD_LOGGER.OPTIONS("options.logLevel", loggerLevel, BUILD_LOGGER.SOURCE_OF(loggerLevel, DEFAULT_IB_OPTIONS.logLevel));
914
+ BUILD_LOGGER.NEW_LINE();
915
+ BUILD_LOGGER.ON_STARTING({ actionName: "Injecting Banner" });
916
+ }
917
+ if (banners.size === 0) {
918
+ if (canLog(loggerLevel, VERBOSE_LOG)) BUILD_LOGGER.ON_SKIPPING({
919
+ actionName: "Inject Banner",
920
+ reasonSkipAction: "empty bannerText",
921
+ reasonType: "parameter",
922
+ reasonEndText: "injecting"
923
+ });
924
+ return;
925
+ }
926
+ const files = (await fastGlob(patterns, cleanPatternOptions)).sort();
927
+ let count = 0;
928
+ for (const filePath of files) {
929
+ if (NON_COMMENTABLE_FILE_RE.test(filePath)) continue;
930
+ let original;
931
+ try {
932
+ original = await fsExtra.promises.readFile(filePath, "utf8");
933
+ } catch (err) {
934
+ if (err.code === "ENOENT") continue;
935
+ throw err;
936
+ }
937
+ if (!isNonEmptyString(original)) continue;
938
+ if (!hasExecutableCode(original)) continue;
939
+ const { body, shebang, banner: existingBanner } = extractAndHoistBanner(original);
940
+ const bannerRegex = new RegExp(BANNER_RE.source, "g");
941
+ const newBlocks = [...banners];
942
+ if (newBlocks.length === 0) continue;
943
+ const existingBlocks = existingBanner ? [...existingBanner.matchAll(bannerRegex)].map((m) => m[0]) : [];
944
+ let finalBlocks = [];
945
+ if (replaceBanner) {
946
+ const replaceRegex = isRegExp(replaceBanner) ? replaceBanner : BANNER_RE;
947
+ if (existingBanner && new RegExp(replaceRegex.source, replaceRegex.flags.replace("g", "")).test(existingBanner)) finalBlocks = [...newBlocks];
948
+ else finalBlocks = bannerPosition === "top" ? [...newBlocks, ...existingBlocks] : [...existingBlocks, ...newBlocks];
949
+ } else finalBlocks = bannerPosition === "top" ? [...newBlocks, ...existingBlocks] : [...existingBlocks, ...newBlocks];
950
+ if (removeDuplicate) {
951
+ const seen = /* @__PURE__ */ new Set();
952
+ finalBlocks = finalBlocks.filter((block) => {
953
+ const normalized = block.trim();
954
+ if (seen.has(normalized)) return false;
955
+ seen.add(normalized);
956
+ return true;
957
+ });
958
+ }
959
+ let content = shebang + finalBlocks.map((text) => {
960
+ if (!text || !isNonEmptyString(text)) return "";
961
+ return text.replace(/\r\n/g, EOL).replace(/\n+$/, "") + EOL + EOL;
962
+ }).join("") + body;
963
+ try {
964
+ await fsExtra.promises.writeFile(filePath, content, "utf8");
965
+ } catch (err) {
966
+ if (err.code === "ENOENT") continue;
967
+ throw err;
968
+ }
969
+ count++;
970
+ if (canLog(loggerLevel, VERBOSE_LOG)) BUILD_LOGGER.ON_PROCESS({
971
+ actionName: "Banner Injected " + picocolors.cyanBright(replaceBanner ? "(replace mode)" : "(preserve mode)"),
972
+ count,
973
+ nameDirect: filePath
974
+ });
975
+ }
976
+ if (canLog(loggerLevel, VERBOSE_LOG)) if (count > 0) BUILD_LOGGER.ON_FINISH({
977
+ actionName: "Inject Banner",
978
+ count
979
+ });
980
+ else BUILD_LOGGER.ON_SKIPPING({
981
+ actionName: "Inject Banner",
982
+ reasonEndText: "injecting"
983
+ });
984
+ } catch (error) {
985
+ if (loggerLevel !== "silent") BUILD_LOGGER.ON_ERROR({
986
+ actionName: "Inject Banner",
987
+ error
988
+ });
989
+ }
990
+ };
991
+ const DEFAULT_ID_PATTERN_POLICY = {
992
+ filesOnly: true,
993
+ forceUnique: true
994
+ };
995
+ const resolvedIdPatternOption = resolvePatternOptions(defaultPatternOptions, DEFAULT_ID_PATTERN_POLICY);
996
+ const DEFAULT_ID_OPTIONS = {
997
+ patternOptions: resolvedIdPatternOption,
998
+ logLevel: DEFAULT_LOG_LEVEL
999
+ };
1000
+ const commandIdIdentity = new CommandIdentity({ defaultCommandName: "inject-directive" });
1001
+ const injectDirective = async (pattern, directive, options = {}) => {
1002
+ const loggerLevel = resolveLogVerbosity(options, DEFAULT_ID_OPTIONS.logLevel);
1003
+ try {
1004
+ const { __commandTitle, patternOptions = DEFAULT_ID_OPTIONS.patternOptions } = options;
1005
+ if (canLog(loggerLevel, VERBOSE_LOG)) console.log(joinLinesLoose(isNonEmptyString(__commandTitle) ? __commandTitle : commandIdIdentity.utility(), ""));
1006
+ const patterns = [...toStringSet(pattern)];
1007
+ const cleanPatternOptions = resolvePatternOptions(patternOptions, DEFAULT_ID_PATTERN_POLICY);
1008
+ if (canLog(loggerLevel, VERBOSE_LOG)) {
1009
+ BUILD_LOGGER.SECTION("Options", { icon: "⚙️ " });
1010
+ BUILD_LOGGER.OPTIONS("pattern", patterns, BUILD_LOGGER.SOURCE_OF(patterns, void 0), true);
1011
+ BUILD_LOGGER.OPTIONS("directive", directive, BUILD_LOGGER.SOURCE_OF(directive, void 0), true);
1012
+ BUILD_LOGGER.OPTIONS("options.patternOptions", cleanPatternOptions, sourceOfPatternOptions(cleanPatternOptions, DEFAULT_ID_OPTIONS.patternOptions));
1013
+ BUILD_LOGGER.OPTIONS("options.logLevel", loggerLevel, BUILD_LOGGER.SOURCE_OF(loggerLevel, DEFAULT_ID_OPTIONS.logLevel));
1014
+ BUILD_LOGGER.NEW_LINE();
1015
+ BUILD_LOGGER.ON_STARTING({ actionName: "Inject Directive" });
1016
+ }
1017
+ const directives = [...toStringSet(directive)];
1018
+ const files = (await fastGlob(patterns, cleanPatternOptions)).sort();
1019
+ let count = 0;
1020
+ for (const filePath of files) {
1021
+ if (!JS_OUTPUT_FILE_RE.test(filePath)) continue;
1022
+ let original;
1023
+ try {
1024
+ original = await fsExtra.promises.readFile(filePath, "utf8");
1025
+ } catch (err) {
1026
+ if (err.code === "ENOENT") continue;
1027
+ throw err;
1028
+ }
1029
+ if (!isNonEmptyString(original) || !hasExecutableCode(original)) continue;
1030
+ const { body, banner, shebang } = extractAndHoistBanner(original);
1031
+ const { directives: extractedDirectives, rest } = extractDirectives(body);
1032
+ const existing = new Set(extractedDirectives);
1033
+ let injectLines;
1034
+ if (detectModuleKindFromContent(rest) === "cjs") {
1035
+ injectLines ??= [];
1036
+ injectLines.push(`"use strict";`);
1037
+ }
1038
+ for (const d of directives) {
1039
+ const dTrim = d.trim();
1040
+ if (!dTrim || dTrim === "use strict") continue;
1041
+ const line = `"${dTrim}";`;
1042
+ if (!existing.has(line)) {
1043
+ injectLines ??= [];
1044
+ injectLines.push(line);
1045
+ }
1046
+ }
1047
+ if (!injectLines?.length) continue;
1048
+ const finalDirective = injectLines.join(EOL) + EOL + stripUseStrict(extractedDirectives);
1049
+ const content = shebang + banner + finalDirective + rest;
1050
+ try {
1051
+ await fsExtra.promises.writeFile(filePath, content, "utf8");
1052
+ } catch (err) {
1053
+ if (err.code === "ENOENT") continue;
1054
+ throw err;
1055
+ }
1056
+ count++;
1057
+ if (canLog(loggerLevel, VERBOSE_LOG)) BUILD_LOGGER.ON_PROCESS({
1058
+ actionName: "Directive Injected " + picocolors.cyanBright("(`" + injectLines.join("`, `") + "`)"),
1059
+ count,
1060
+ nameDirect: filePath
1061
+ });
1062
+ }
1063
+ if (canLog(loggerLevel, VERBOSE_LOG)) if (count > 0) BUILD_LOGGER.ON_FINISH({
1064
+ actionName: "Inject Directive",
1065
+ count
1066
+ });
1067
+ else BUILD_LOGGER.ON_SKIPPING({
1068
+ actionName: "Inject Directive",
1069
+ reasonEndText: "injecting"
1070
+ });
1071
+ } catch (error) {
1072
+ if (loggerLevel !== "silent") BUILD_LOGGER.ON_ERROR({
1073
+ actionName: "Inject Directive",
1074
+ error
1075
+ });
1076
+ }
1077
+ };
1078
+ const DEFAULT_NJBN_PATTERN_POLICY = {
1079
+ filesOnly: true,
1080
+ forceUnique: true
1081
+ };
1082
+ const resolvedNjbnPatternOption = resolvePatternOptions(defaultPatternOptions, DEFAULT_NJBN_PATTERN_POLICY);
1083
+ const DEFAULT_NJBN_OPTIONS = {
1084
+ patternOptions: resolvedNjbnPatternOption,
1085
+ logLevel: DEFAULT_LOG_LEVEL
1086
+ };
1087
+ const commandNjbnIdentity = new CommandIdentity({ defaultCommandName: "normalize-js-build-newlines" });
1088
+ const normalizeJsBuildNewlines = async (pattern, options = {}) => {
1089
+ const loggerLevel = resolveLogVerbosity(options, DEFAULT_NJBN_OPTIONS.logLevel);
1090
+ try {
1091
+ const { __commandTitle, patternOptions = DEFAULT_NJBN_OPTIONS.patternOptions } = options;
1092
+ if (canLog(loggerLevel, VERBOSE_LOG)) console.log(joinLinesLoose(isNonEmptyString(__commandTitle) ? __commandTitle : commandNjbnIdentity.utility(), ""));
1093
+ const patterns = [...toStringSet(pattern)];
1094
+ const cleanPatternOptions = resolvePatternOptions(patternOptions, DEFAULT_NJBN_PATTERN_POLICY);
1095
+ if (canLog(loggerLevel, VERBOSE_LOG)) {
1096
+ BUILD_LOGGER.SECTION("Options", { icon: "⚙️ " });
1097
+ BUILD_LOGGER.OPTIONS("pattern", patterns, BUILD_LOGGER.SOURCE_OF(patterns, void 0), true);
1098
+ BUILD_LOGGER.OPTIONS("options.patternOptions", cleanPatternOptions, sourceOfPatternOptions(cleanPatternOptions, DEFAULT_NJBN_OPTIONS.patternOptions));
1099
+ BUILD_LOGGER.OPTIONS("options.logLevel", loggerLevel, BUILD_LOGGER.SOURCE_OF(loggerLevel, DEFAULT_NJBN_OPTIONS.logLevel));
1100
+ BUILD_LOGGER.NEW_LINE();
1101
+ BUILD_LOGGER.ON_STARTING({ actionName: "Normalize New Lines" });
1102
+ }
1103
+ const files = (await fastGlob(patterns, cleanPatternOptions)).sort();
1104
+ const filesToClean = /* @__PURE__ */ new Set();
1105
+ for (const filePath of files) {
1106
+ if (!JS_OUTPUT_FILE_RE.test(filePath)) continue;
1107
+ let content;
1108
+ try {
1109
+ content = await fsExtra.promises.readFile(filePath, "utf8");
1110
+ } catch (err) {
1111
+ if (err.code === "ENOENT") continue;
1112
+ throw err;
1113
+ }
1114
+ if (!/(\r?\n){3,}/.test(content)) continue;
1115
+ filesToClean.add(filePath);
1116
+ }
1117
+ let count = 0;
1118
+ for (const [, filePath] of filesToClean.entries()) {
1119
+ count++;
1120
+ let content;
1121
+ try {
1122
+ content = await fsExtra.promises.readFile(filePath, "utf8");
1123
+ } catch (err) {
1124
+ if (err.code === "ENOENT") continue;
1125
+ throw err;
1126
+ }
1127
+ const finalContent = content.replace(/(\r?\n){3,}/g, EOL);
1128
+ if (finalContent !== content) {
1129
+ try {
1130
+ await fsExtra.promises.writeFile(filePath, finalContent, "utf8");
1131
+ } catch (err) {
1132
+ if (err.code === "ENOENT") continue;
1133
+ throw err;
1134
+ }
1135
+ if (canLog(loggerLevel, VERBOSE_LOG)) BUILD_LOGGER.ON_PROCESS({
1136
+ actionName: "New Line Normalized",
1137
+ count,
1138
+ nameDirect: filePath
1139
+ });
1140
+ }
1141
+ }
1142
+ if (canLog(loggerLevel, VERBOSE_LOG)) if (filesToClean.size > 0) BUILD_LOGGER.ON_FINISH({
1143
+ actionName: "Normalize New Lines",
1144
+ count
1145
+ });
1146
+ else BUILD_LOGGER.ON_SKIPPING({
1147
+ actionName: "Normalize New Lines",
1148
+ reasonEndText: "normalize"
1149
+ });
1150
+ } catch (error) {
1151
+ if (loggerLevel !== "silent") BUILD_LOGGER.ON_ERROR({
1152
+ actionName: "Normalize New Lines",
1153
+ error
1154
+ });
1155
+ }
1156
+ };
1157
+ const DEFAULT_SJC_PATTERN_POLICY = {
1158
+ filesOnly: true,
1159
+ forceUnique: true
1160
+ };
1161
+ const resolvedSjcPatternOption = resolvePatternOptions(defaultPatternOptions, DEFAULT_SJC_PATTERN_POLICY);
1162
+ const DEFAULT_SJC_OPTIONS = {
1163
+ removeSourceMap: false,
1164
+ sourceType: "module",
1165
+ removeRegion: true,
1166
+ ecmaVersion: "latest",
1167
+ patternOptions: resolvedSjcPatternOption,
1168
+ logLevel: DEFAULT_LOG_LEVEL
1169
+ };
1170
+ const VALID_SOURCE_TYPE = new Set([
1171
+ "module",
1172
+ "script",
1173
+ "commonjs"
1174
+ ]);
1175
+ const VALID_ECMA_VERSION = new Set([
1176
+ "latest",
1177
+ 3,
1178
+ 5,
1179
+ 6,
1180
+ 7,
1181
+ 8,
1182
+ 9,
1183
+ 10,
1184
+ 11,
1185
+ 12,
1186
+ 13,
1187
+ 14,
1188
+ 15,
1189
+ 16,
1190
+ 17,
1191
+ 2015,
1192
+ 2016,
1193
+ 2017,
1194
+ 2018,
1195
+ 2019,
1196
+ 2020,
1197
+ 2021,
1198
+ 2022,
1199
+ 2023,
1200
+ 2024,
1201
+ 2025,
1202
+ 2026
1203
+ ]);
1204
+ const REGION_COMMENT_RE = /^#(?:end)?region\b/i;
1205
+ const SOURCE_MAP_COMMENT_RE = /^[#@]\s*sourceMappingURL=/;
1206
+ function normalizeNewlines(code) {
1207
+ return code.replace(/[ \t]+\n/g, EOL).replace(/\n\s*\n+/g, EOL);
1208
+ }
1209
+ function stripComments(code, { removeRegion, removeSourceMap, sourceType, ecmaVersion }) {
1210
+ const comments = [];
1211
+ if (sourceType == null || !VALID_SOURCE_TYPE.has(sourceType)) sourceType = DEFAULT_SJC_OPTIONS.sourceType;
1212
+ if (ecmaVersion == null || !VALID_ECMA_VERSION.has(ecmaVersion)) ecmaVersion = DEFAULT_SJC_OPTIONS.ecmaVersion;
1213
+ try {
1214
+ acorn.parse(code, {
1215
+ sourceType,
1216
+ ecmaVersion,
1217
+ allowHashBang: true,
1218
+ onComment(block, text, start, end) {
1219
+ if (!block) {
1220
+ const value = text.trim();
1221
+ if (!REGION_COMMENT_RE.test(value) && !SOURCE_MAP_COMMENT_RE.test(value)) return;
1222
+ }
1223
+ const value = text.trim();
1224
+ const forceRemove = shouldRemoveDocRuntime(value);
1225
+ if (forceRemove === true) {
1226
+ comments.push([start, end]);
1227
+ return;
1228
+ }
1229
+ if (forceRemove === false) return;
1230
+ if (IMPORTANT_COMMENT.test(value)) return;
1231
+ if (SOURCE_MAP_COMMENT_RE.test(value)) {
1232
+ if (removeSourceMap) comments.push([start, end]);
1233
+ return;
1234
+ }
1235
+ if (REGION_COMMENT_RE.test(value)) {
1236
+ if (removeRegion) comments.push([start, end]);
1237
+ return;
1238
+ }
1239
+ if (block) comments.push([start, end]);
1240
+ }
1241
+ });
1242
+ } catch {
1243
+ return code;
1244
+ }
1245
+ if (!comments.length) return code;
1246
+ const parts = [];
1247
+ let last = 0;
1248
+ for (const [start, end] of comments) {
1249
+ parts.push(code.slice(last, start));
1250
+ last = end;
1251
+ }
1252
+ parts.push(code.slice(last));
1253
+ const lines = parts.join("").split(/\r?\n/);
1254
+ const seenSourceMap = /* @__PURE__ */ new Set();
1255
+ return lines.filter((line) => {
1256
+ if (SOURCE_MAP_RE.test(line)) {
1257
+ const key = line.trim();
1258
+ if (seenSourceMap.has(key)) return false;
1259
+ seenSourceMap.add(key);
1260
+ if (removeSourceMap) return false;
1261
+ return true;
1262
+ }
1263
+ if (removeRegion && REGION_RE.test(line)) return false;
1264
+ if (isTargetComment(line, {
1265
+ removeSourceMap,
1266
+ removeRegion
1267
+ })) return false;
1268
+ return true;
1269
+ }).map((line) => {
1270
+ let out = line.replace(/^[ \t]*\/\/\s*(?:\.\.\/|\.\/)*[^ \n]*?(?:src|node_modules)\/[^\n]*\n?/gm, "").replace(/\/\/\s*eslint[^\n]*/g, "");
1271
+ out = out.replace(/(\/\/[#@]\s*sourceMappingURL=[^\r\n]*)(?:\r?\n\1)+/g, "$1");
1272
+ return out;
1273
+ }).join(EOL);
1274
+ }
1275
+ const commandSjcIdentity = new CommandIdentity({ defaultCommandName: "strip-js-comments" });
1276
+ const stripJsComments = async (pattern, options = {}) => {
1277
+ const loggerLevel = resolveLogVerbosity(options, DEFAULT_SJC_OPTIONS.logLevel);
1278
+ try {
1279
+ const { patternOptions = DEFAULT_SJC_OPTIONS.patternOptions, removeSourceMap = DEFAULT_SJC_OPTIONS.removeSourceMap, removeRegion = DEFAULT_SJC_OPTIONS.removeRegion, sourceType = DEFAULT_SJC_OPTIONS.sourceType, ecmaVersion = DEFAULT_SJC_OPTIONS.ecmaVersion, __commandTitle } = options;
1280
+ if (canLog(loggerLevel, VERBOSE_LOG)) console.log(joinLinesLoose(isNonEmptyString(__commandTitle) ? __commandTitle : commandSjcIdentity.utility(), ""));
1281
+ const patterns = [...toStringSet(pattern)];
1282
+ const cleanPatternOptions = resolvePatternOptions(patternOptions, DEFAULT_SJC_PATTERN_POLICY);
1283
+ if (canLog(loggerLevel, VERBOSE_LOG)) {
1284
+ BUILD_LOGGER.SECTION("Options", { icon: "⚙️ " });
1285
+ BUILD_LOGGER.OPTIONS("pattern", patterns, BUILD_LOGGER.SOURCE_OF(patterns, void 0), true);
1286
+ BUILD_LOGGER.OPTIONS("options.patternOptions", cleanPatternOptions, sourceOfPatternOptions(cleanPatternOptions, DEFAULT_SJC_OPTIONS.patternOptions));
1287
+ BUILD_LOGGER.OPTIONS("options.removeSourceMap", removeSourceMap, BUILD_LOGGER.SOURCE_OF(removeSourceMap, DEFAULT_SJC_OPTIONS.removeSourceMap));
1288
+ BUILD_LOGGER.OPTIONS("options.removeRegion", removeRegion, BUILD_LOGGER.SOURCE_OF(removeRegion, DEFAULT_SJC_OPTIONS.removeRegion));
1289
+ BUILD_LOGGER.OPTIONS("options.sourceType", sourceType, BUILD_LOGGER.SOURCE_OF(sourceType, DEFAULT_SJC_OPTIONS.sourceType));
1290
+ BUILD_LOGGER.OPTIONS("options.ecmaVersion", ecmaVersion, BUILD_LOGGER.SOURCE_OF(ecmaVersion, DEFAULT_SJC_OPTIONS.ecmaVersion));
1291
+ BUILD_LOGGER.OPTIONS("options.logLevel", loggerLevel, BUILD_LOGGER.SOURCE_OF(loggerLevel, DEFAULT_SJC_OPTIONS.logLevel));
1292
+ BUILD_LOGGER.NEW_LINE();
1293
+ BUILD_LOGGER.ON_STARTING({ actionName: "Stripping JS Comments" });
1294
+ }
1295
+ const files = (await fastGlob(patterns, cleanPatternOptions)).sort();
1296
+ let count = 0;
1297
+ for (const filePath of files) {
1298
+ if (!JS_OUTPUT_FILE_RE.test(filePath)) continue;
1299
+ let content;
1300
+ try {
1301
+ content = await fsExtra.promises.readFile(filePath, "utf8");
1302
+ } catch (err) {
1303
+ if (err.code === "ENOENT") continue;
1304
+ throw err;
1305
+ }
1306
+ let output = content;
1307
+ if (!/\/[/*]/.test(content)) continue;
1308
+ output = stripComments(content, {
1309
+ removeRegion,
1310
+ removeSourceMap,
1311
+ sourceType,
1312
+ ecmaVersion
1313
+ });
1314
+ output = normalizeNewlines(output).trim() + EOL;
1315
+ if (output !== content) {
1316
+ try {
1317
+ await fsExtra.promises.writeFile(filePath, output, "utf8");
1318
+ } catch (err) {
1319
+ if (err.code === "ENOENT") continue;
1320
+ throw err;
1321
+ }
1322
+ count++;
1323
+ if (canLog(loggerLevel, VERBOSE_LOG)) BUILD_LOGGER.ON_PROCESS({
1324
+ actionName: "JS Comment Stripping",
1325
+ count,
1326
+ nameDirect: filePath
1327
+ });
1328
+ }
1329
+ }
1330
+ if (canLog(loggerLevel, VERBOSE_LOG)) if (count > 0) BUILD_LOGGER.ON_FINISH({
1331
+ actionName: "Stripping JS Comments",
1332
+ count
1333
+ });
1334
+ else BUILD_LOGGER.ON_SKIPPING({
1335
+ actionName: "Stripping JS Comments",
1336
+ reasonType: "file",
1337
+ reasonEndText: "processing"
1338
+ });
1339
+ } catch (error) {
1340
+ if (loggerLevel !== "silent") BUILD_LOGGER.ON_ERROR({
1341
+ actionName: "Stripping JS Comments",
1342
+ error
1343
+ });
1344
+ }
1345
+ };
1346
+ function runCommand(command, argsOrOptions = [], maybeOptions = {}) {
1347
+ assertValidCommand(command);
1348
+ let args;
1349
+ let options;
1350
+ if (Array.isArray(argsOrOptions)) {
1351
+ args = argsOrOptions;
1352
+ options = maybeOptions;
1353
+ } else {
1354
+ args = [];
1355
+ options = argsOrOptions;
1356
+ }
1357
+ return new Promise((resolve, reject) => {
1358
+ const { shell = true, stdio = "inherit", argv0: _argv0, useColors = true, ...restOption } = options;
1359
+ const { child, setupLifecycle, cmdStringPlain } = spawnWithLifecycle(command, args, {
1360
+ ...restOption,
1361
+ stdio,
1362
+ useColors,
1363
+ shell
1364
+ }, { rejectOnNonZero: true });
1365
+ setupLifecycle({
1366
+ onSuccess: (code) => {
1367
+ if (code === 0) resolve(child);
1368
+ else reject(/* @__PURE__ */ new Error(`${cmdStringPlain} exited with code ${code}`));
1369
+ },
1370
+ onError: reject
1371
+ });
1372
+ });
1373
+ }
1374
+ function normalizeChunk(chunk) {
1375
+ if (typeof chunk === "string") return chunk;
1376
+ if (Buffer.isBuffer(chunk)) return chunk.toString("utf8");
1377
+ return String(chunk);
1378
+ }
1379
+ function runCommandCapture(command, argsOrOptions = [], maybeOptions = {}) {
1380
+ assertValidCommand(command);
1381
+ let args;
1382
+ let options;
1383
+ if (Array.isArray(argsOrOptions)) {
1384
+ args = argsOrOptions;
1385
+ options = maybeOptions;
1386
+ } else {
1387
+ args = [];
1388
+ options = argsOrOptions;
1389
+ }
1390
+ const { shell = true, signal, timeout, forceKill, useColors = true, argv0: _argv0, ...restOption } = options;
1391
+ return new Promise((resolve, reject) => {
1392
+ const { child, setupLifecycle } = spawnWithLifecycle(command, args, {
1393
+ ...restOption,
1394
+ stdio: "pipe",
1395
+ shell,
1396
+ signal,
1397
+ timeout,
1398
+ forceKill,
1399
+ useColors
1400
+ }, { rejectOnNonZero: false });
1401
+ let stdout = "";
1402
+ let stderr = "";
1403
+ child.stdout?.on("data", (chunk) => {
1404
+ stdout += normalizeChunk(chunk);
1405
+ });
1406
+ child.stderr?.on("data", (chunk) => {
1407
+ stderr += normalizeChunk(chunk);
1408
+ });
1409
+ setupLifecycle({
1410
+ onSuccess: (code) => {
1411
+ resolve({
1412
+ stdout: stdout.trimEnd(),
1413
+ stderr: stderr.trimEnd(),
1414
+ exitCode: code,
1415
+ ok: code === 0
1416
+ });
1417
+ },
1418
+ onError: reject
1419
+ });
1420
+ });
1421
+ }
1422
+ function formatCommand(command, args, { useColors = true } = {}) {
1423
+ const hasArgs = args.length > 0;
1424
+ const argsString = hasArgs ? args.map((a) => safeStableStringify(a)).join(" ") : "";
1425
+ if (useColors) {
1426
+ const cmd = picocolors.cyanBright(command);
1427
+ return hasArgs ? `${cmd} ${picocolors.gray(argsString)}` : cmd;
1428
+ }
1429
+ return hasArgs ? `${command} ${argsString}` : command;
1430
+ }
1431
+ function assertValidCommand(command, { useColors = true } = {}) {
1432
+ if (typeof command !== "string") {
1433
+ const errorMsg = `Invalid command: expected a string, received ${safeStableStringify(command)}`;
1434
+ throw new TypeError(useColors ? picocolors.redBright(errorMsg) : errorMsg);
1435
+ }
1436
+ const trimmed = command.trim();
1437
+ if (trimmed.length === 0) {
1438
+ const errorMsg = "Invalid command: command cannot be empty";
1439
+ throw new Error(useColors ? picocolors.redBright(errorMsg) : errorMsg);
1440
+ }
1441
+ const hasSpace = trimmed.includes(" ");
1442
+ const hasQuotes = /['"`]/.test(trimmed);
1443
+ const hasShellOps = /[|&;<>(){}$]/.test(trimmed);
1444
+ if (hasSpace || hasQuotes || hasShellOps) {
1445
+ const [cmd, ...rest] = trimmed.split(/\s+/);
1446
+ const errorMsg = joinLinesLoose(`Invalid command: "${trimmed}"`, "Do not pass a full shell command.", `Use arguments instead: runCommand("${cmd}", ${safeStableStringify(rest)})`);
1447
+ throw new Error(useColors ? picocolors.redBright(errorMsg) : errorMsg);
1448
+ }
1449
+ }
1450
+ function stripInternalStack(lines) {
1451
+ const blacklist = [
1452
+ "at new Promise (<anonymous>)",
1453
+ "Timeout.",
1454
+ "ChildProcess.",
1455
+ "node:events:",
1456
+ "createProcessError",
1457
+ "formatError",
1458
+ "spawnWithLifecycle",
1459
+ "setupLifecycle",
1460
+ "node:internal"
1461
+ ];
1462
+ return lines.filter((line) => {
1463
+ if (blacklist.some((key) => line.includes(key))) return false;
1464
+ const isFileFrame = line.includes("/build-tools/dist/");
1465
+ const hasFunctionName = /\bat\s+\S+\s+\(/.test(line);
1466
+ if (isFileFrame && !hasFunctionName) return false;
1467
+ return true;
1468
+ });
1469
+ }
1470
+ function createProcessError(message, { reason, exitCode, signal, command }, baseStack) {
1471
+ const error = new CommandProcessError(message, {
1472
+ reason,
1473
+ exitCode,
1474
+ signal,
1475
+ command
1476
+ });
1477
+ const currentStack = error.stack?.split(EOL) ?? [];
1478
+ const base = baseStack?.split(EOL) ?? [];
1479
+ const [currentHead, ...currentRest] = currentStack;
1480
+ const [, ...baseRest] = base;
1481
+ const cleanedCurrent = stripInternalStack(currentRest);
1482
+ const cleanedBase = stripInternalStack(baseRest);
1483
+ command = command.trim();
1484
+ error.stack = [
1485
+ currentHead,
1486
+ ...cleanedCurrent,
1487
+ ...cleanedBase.length ? [...cleanedBase] : []
1488
+ ].join(EOL);
1489
+ Object.defineProperties(error, {
1490
+ reason: {
1491
+ value: reason,
1492
+ enumerable: false
1493
+ },
1494
+ exitCode: {
1495
+ value: exitCode,
1496
+ enumerable: false
1497
+ },
1498
+ signal: {
1499
+ value: signal,
1500
+ enumerable: false
1501
+ },
1502
+ command: {
1503
+ value: command,
1504
+ enumerable: false
1505
+ }
1506
+ });
1507
+ error.stack += joinLinesLoose("", "meta:", ` reason: ${formatOptionValue(reason)}`, ` exitCode: ${formatOptionValue(exitCode ?? null)}`, ` signal: ${formatOptionValue(signal ?? null)}`, ` command: ${formatOptionValue(command)}`);
1508
+ return error;
1509
+ }
1510
+ var CommandProcessError = class extends Error {
1511
+ reason;
1512
+ exitCode;
1513
+ signal;
1514
+ command;
1515
+ constructor(message, meta) {
1516
+ super(message);
1517
+ this.name = "CommandProcessError";
1518
+ this.reason = meta.reason;
1519
+ this.exitCode = meta.exitCode;
1520
+ this.signal = meta.signal;
1521
+ this.command = meta.command;
1522
+ }
1523
+ };
1524
+ function isCommandProcessError(err) {
1525
+ return err instanceof CommandProcessError;
1526
+ }
1527
+ function spawnWithLifecycle(command, args, options, config) {
1528
+ const { useColors = true, timeout, forceKill, signal: abortSignal, ...restOption } = options;
1529
+ const baseStack = (/* @__PURE__ */ new Error()).stack;
1530
+ const cmdString = formatCommand(command, args, { useColors });
1531
+ const cmdStringPlain = formatCommand(command, args, { useColors: false });
1532
+ const formatError = config?.formatError ?? ((msg, meta) => {
1533
+ const metaCommand = meta.command.trim();
1534
+ const argsString = meta.args.length > 0 ? meta.args.map((a) => safeStableStringify(a).trim()).join(" ") : "";
1535
+ if (meta.useColors) {
1536
+ const cmd = picocolors.magentaBright(metaCommand);
1537
+ const args = argsString ? picocolors.yellowBright(argsString) : "";
1538
+ return createProcessError(`${cmd}${args ? " " + args : ""} ${picocolors.redBright(msg)}`, {
1539
+ ...meta,
1540
+ command: `${metaCommand} ${argsString}`
1541
+ }, baseStack);
1542
+ }
1543
+ return createProcessError(`${metaCommand}${isNonEmptyString(argsString) ? " " + argsString : ""} ${msg}`, {
1544
+ ...meta,
1545
+ command: `${metaCommand} ${argsString}`
1546
+ }, baseStack);
1547
+ });
1548
+ const rejectOnNonZero = config?.rejectOnNonZero ?? false;
1549
+ const child = spawn(command, [...args], restOption);
1550
+ let finished = false;
1551
+ const kill = () => {
1552
+ try {
1553
+ if (process.platform === "win32") if (forceKill && child.pid) spawn("taskkill", [
1554
+ "/pid",
1555
+ String(child.pid),
1556
+ "/f",
1557
+ "/t"
1558
+ ]);
1559
+ else child.kill();
1560
+ else child.kill("SIGTERM");
1561
+ } catch {}
1562
+ };
1563
+ return {
1564
+ child,
1565
+ kill,
1566
+ cmdString,
1567
+ cmdStringPlain,
1568
+ setupLifecycle({ onSuccess, onError }) {
1569
+ const timeoutId = timeout != null ? setTimeout(() => {
1570
+ if (finished) return;
1571
+ kill();
1572
+ fail(formatError(`timed out after ${timeout}ms`, {
1573
+ reason: "timeout",
1574
+ command,
1575
+ args,
1576
+ useColors
1577
+ }));
1578
+ }, timeout) : null;
1579
+ const cleanup = () => {
1580
+ finished = true;
1581
+ if (abortSignal) abortSignal.removeEventListener("abort", onAbort);
1582
+ if (timeoutId) clearTimeout(timeoutId);
1583
+ };
1584
+ const fail = (err) => {
1585
+ if (finished) return;
1586
+ cleanup();
1587
+ onError(err);
1588
+ };
1589
+ const succeed = (code) => {
1590
+ if (finished) return;
1591
+ cleanup();
1592
+ onSuccess(code);
1593
+ };
1594
+ const onAbort = () => {
1595
+ if (finished) return;
1596
+ kill();
1597
+ fail(formatError("aborted by signal", {
1598
+ reason: "abort",
1599
+ command,
1600
+ args,
1601
+ useColors
1602
+ }));
1603
+ };
1604
+ if (abortSignal) {
1605
+ if (abortSignal.aborted) {
1606
+ onAbort();
1607
+ return;
1608
+ }
1609
+ abortSignal.addEventListener("abort", onAbort);
1610
+ }
1611
+ child.once("error", fail);
1612
+ child.once("close", (code, signal) => {
1613
+ if (signal) {
1614
+ fail(formatError(`terminated by ${signal}`, {
1615
+ reason: "signal",
1616
+ signal,
1617
+ exitCode: code ?? void 0,
1618
+ command,
1619
+ args,
1620
+ useColors
1621
+ }));
1622
+ return;
1623
+ }
1624
+ const exitCode = code ?? 0;
1625
+ if (rejectOnNonZero && exitCode !== 0) {
1626
+ fail(formatError(`exited with code ${exitCode}`, {
1627
+ reason: "non-zero exit code",
1628
+ exitCode,
1629
+ command,
1630
+ args,
1631
+ useColors
1632
+ }));
1633
+ return;
1634
+ }
1635
+ succeed(exitCode);
1636
+ });
1637
+ }
1638
+ };
1639
+ }
1640
+ export { CommandProcessError, DEFAULT_CLEAN_PATTERN_POLICY, DEFAULT_ECI_PATTERN_POLICY, DEFAULT_EFN_PATTERN_POLICY, DEFAULT_GRI_PATTERN_POLICY, DEFAULT_IB_PATTERN_POLICY, DEFAULT_ID_PATTERN_POLICY, DEFAULT_NJBN_PATTERN_POLICY, DEFAULT_SJC_PATTERN_POLICY, cleanJsBuildArtifacts, cleanTypesBuildArtifacts, commandCftdIdentity, commandCjbaIdentity, commandCtbaIdentity, commandEciIdentity, commandEfnIdentity, commandGriIdentity, commandIbIdentity, commandIdIdentity, commandNjbnIdentity, commandSjcIdentity, copyFileToDest, createCopyFileToDestParameterSet, ensureCssImport, ensureFinalNewline, generatePackageBanner, generateReferenceIndex, getPackageJson, injectBanner, injectDirective, isCommandProcessError, normalizeJsBuildNewlines, resolvedCleanPatternOption, resolvedEciPatternOption, resolvedEfnPatternOption, resolvedGriPatternOption, resolvedIbPatternOption, resolvedIdPatternOption, resolvedNjbnPatternOption, resolvedSjcPatternOption, runCommand, runCommandCapture, stripJsComments };
1641
+ //# sourceMappingURL=index.js.map