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