@zuke-build/cli 0.0.0-stage → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +353 -2
  3. package/mod.d.ts +102 -0
  4. package/mod.js +931 -0
  5. package/package.json +35 -4
  6. package/src/binary_launcher.d.ts +49 -0
  7. package/src/binary_launcher.js +325 -0
  8. package/src/binary_pin.d.ts +47 -0
  9. package/src/binary_pin.js +117 -0
  10. package/src/build_file.d.ts +25 -0
  11. package/src/build_file.js +58 -0
  12. package/src/cache.d.ts +23 -0
  13. package/src/cache.js +26 -0
  14. package/src/deno_isolated.d.ts +14 -0
  15. package/src/deno_isolated.js +70 -0
  16. package/src/deno_path.d.ts +115 -0
  17. package/src/deno_path.js +205 -0
  18. package/src/deno_pin.d.ts +37 -0
  19. package/src/deno_pin.js +32 -0
  20. package/src/dependencies.d.ts +48 -0
  21. package/src/dependencies.js +80 -0
  22. package/src/dispatch.d.ts +229 -0
  23. package/src/dispatch.js +549 -0
  24. package/src/embedded_engine.d.ts +28 -0
  25. package/src/embedded_engine.js +21 -0
  26. package/src/engine_pin.d.ts +56 -0
  27. package/src/engine_pin.js +196 -0
  28. package/src/fs.d.ts +14 -0
  29. package/src/fs.js +25 -0
  30. package/src/import.d.ts +132 -0
  31. package/src/import.js +289 -0
  32. package/src/install_source.d.ts +79 -0
  33. package/src/install_source.js +104 -0
  34. package/src/launcher.d.ts +37 -0
  35. package/src/launcher.js +405 -0
  36. package/src/launcher_shared.d.ts +25 -0
  37. package/src/launcher_shared.js +91 -0
  38. package/src/mcp_config.d.ts +71 -0
  39. package/src/mcp_config.js +96 -0
  40. package/src/node_launcher.d.ts +19 -0
  41. package/src/node_launcher.js +416 -0
  42. package/src/node_pin.d.ts +25 -0
  43. package/src/node_pin.js +30 -0
  44. package/src/output.d.ts +38 -0
  45. package/src/output.js +43 -0
  46. package/src/paint.d.ts +42 -0
  47. package/src/paint.js +38 -0
  48. package/src/project.d.ts +69 -0
  49. package/src/project.js +132 -0
  50. package/src/pyproject.d.ts +30 -0
  51. package/src/pyproject.js +156 -0
  52. package/src/python_build.d.ts +27 -0
  53. package/src/python_build.js +197 -0
  54. package/src/records.d.ts +18 -0
  55. package/src/records.js +31 -0
  56. package/src/relock.d.ts +11 -0
  57. package/src/relock.js +182 -0
  58. package/src/runtime_field.d.ts +15 -0
  59. package/src/runtime_field.js +29 -0
  60. package/src/setup.d.ts +259 -0
  61. package/src/setup.js +693 -0
  62. package/src/star.d.ts +44 -0
  63. package/src/star.js +100 -0
  64. package/src/starter.d.ts +64 -0
  65. package/src/starter.js +138 -0
  66. package/src/toml.d.ts +32 -0
  67. package/src/toml.js +354 -0
  68. package/src/translate.d.ts +69 -0
  69. package/src/translate.js +198 -0
  70. package/src/upgrade.d.ts +113 -0
  71. package/src/upgrade.js +344 -0
  72. package/src/version.d.ts +11 -0
  73. package/src/version.js +13 -0
  74. package/src/version_report.d.ts +55 -0
  75. package/src/version_report.js +187 -0
  76. package/zuke.js +8 -0
package/src/toml.js ADDED
@@ -0,0 +1,354 @@
1
+ // Copyright (c) 2026 the Zuke contributors
2
+ // SPDX-License-Identifier: MIT
3
+ /** Bare key characters. */
4
+ const BARE_KEY = /[A-Za-z0-9_-]+/y;
5
+ /** A decimal integer or float, underscores between digits allowed. */
6
+ const NUMBER = /[+-]?(?:0|[1-9](?:_?[0-9])*)(?:\.[0-9](?:_?[0-9])*)?(?:[eE][+-]?[0-9](?:_?[0-9])*)?/y;
7
+ /** The single-character escapes of a basic string. */
8
+ const ESCAPES = {
9
+ b: "\b",
10
+ t: "\t",
11
+ n: "\n",
12
+ f: "\f",
13
+ r: "\r",
14
+ '"': '"',
15
+ "\\": "\\",
16
+ };
17
+ /**
18
+ * Parse `text` as TOML into plain data: tables are objects, arrays are arrays,
19
+ * strings, numbers and booleans are themselves.
20
+ *
21
+ * @throws {SyntaxError} naming the line of the first construct it cannot read.
22
+ */
23
+ export function parseToml(text) {
24
+ return new Reader(text).document();
25
+ }
26
+ /** Read a value at `key` only when it is the table's own (never a prototype's). */
27
+ function own(table, key) {
28
+ return Object.hasOwn(table, key) ? table[key] : undefined;
29
+ }
30
+ /** Whether `value` is a parsed table. */
31
+ function isTable(value) {
32
+ return typeof value === "object" && value !== null && !Array.isArray(value);
33
+ }
34
+ /** The cursor over one document. */
35
+ class Reader {
36
+ pos = 0;
37
+ /** Tables a `[header]` has defined, so a second definition is refused. */
38
+ defined = new Set();
39
+ text;
40
+ constructor(text) {
41
+ this.text = text;
42
+ }
43
+ document() {
44
+ const root = {};
45
+ let current = root;
46
+ for (;;) {
47
+ this.skipBlank();
48
+ if (this.pos >= this.text.length)
49
+ return root;
50
+ if (this.text.startsWith("[[", this.pos)) {
51
+ this.pos += 2;
52
+ this.keyPath();
53
+ this.expect("]]");
54
+ current = {}; // validated, then discarded (see the module doc)
55
+ }
56
+ else if (this.text[this.pos] === "[") {
57
+ this.pos++;
58
+ const path = this.keyPath();
59
+ this.expect("]");
60
+ current = this.header(root, path);
61
+ }
62
+ else {
63
+ this.keyValue(current);
64
+ }
65
+ this.endOfLine();
66
+ }
67
+ }
68
+ /** The table a `[a.b.c]` header names, created on first use. */
69
+ header(root, path) {
70
+ const table = this.descend(root, path);
71
+ if (this.defined.has(table)) {
72
+ this.fail(`table [${path.join(".")}] is defined twice`);
73
+ }
74
+ this.defined.add(table);
75
+ return table;
76
+ }
77
+ /** Walk (and create) the tables along `path` from `from`. */
78
+ descend(from, path) {
79
+ let table = from;
80
+ for (const key of path) {
81
+ const next = own(table, key);
82
+ if (next === undefined) {
83
+ const created = {};
84
+ define(table, key, created);
85
+ table = created;
86
+ }
87
+ else if (isTable(next)) {
88
+ table = next;
89
+ }
90
+ else {
91
+ this.fail(`key "${key}" is already a value, not a table`);
92
+ }
93
+ }
94
+ return table;
95
+ }
96
+ /** `key = value`, assigned into `table` (a dotted key into its nested tables). */
97
+ keyValue(table) {
98
+ const path = this.keyPath();
99
+ this.expect("=");
100
+ this.skipSpaces();
101
+ const value = this.value();
102
+ const last = path[path.length - 1];
103
+ const target = this.descend(table, path.slice(0, -1));
104
+ if (Object.hasOwn(target, last))
105
+ this.fail(`duplicate key "${last}"`);
106
+ define(target, last, value);
107
+ }
108
+ /** One or more keys joined by dots, with spaces around each. */
109
+ keyPath() {
110
+ const path = [this.key()];
111
+ for (;;) {
112
+ this.skipSpaces();
113
+ if (this.text[this.pos] !== ".")
114
+ return path;
115
+ this.pos++;
116
+ path.push(this.key());
117
+ }
118
+ }
119
+ key() {
120
+ this.skipSpaces();
121
+ const ch = this.text[this.pos];
122
+ if (ch === '"')
123
+ return this.basicString();
124
+ if (ch === "'")
125
+ return this.literalString();
126
+ BARE_KEY.lastIndex = this.pos;
127
+ const bare = BARE_KEY.exec(this.text);
128
+ if (bare === null)
129
+ this.fail("expected a key");
130
+ this.pos += bare[0].length;
131
+ return bare[0];
132
+ }
133
+ value() {
134
+ const rest = this.text.slice(this.pos, this.pos + 3);
135
+ if (rest === '"""')
136
+ return this.multilineString('"');
137
+ if (rest === "'''")
138
+ return this.multilineString("'");
139
+ const ch = this.text[this.pos];
140
+ if (ch === '"')
141
+ return this.basicString();
142
+ if (ch === "'")
143
+ return this.literalString();
144
+ if (ch === "[")
145
+ return this.array();
146
+ if (ch === "{")
147
+ return this.inlineTable();
148
+ for (const word of ["true", "false"]) {
149
+ if (this.text.startsWith(word, this.pos) && this.delimited(word.length)) {
150
+ this.pos += word.length;
151
+ return word === "true";
152
+ }
153
+ }
154
+ NUMBER.lastIndex = this.pos;
155
+ const number = NUMBER.exec(this.text);
156
+ if (number !== null && this.delimited(number[0].length)) {
157
+ this.pos += number[0].length;
158
+ return Number(number[0].replaceAll("_", ""));
159
+ }
160
+ this.fail("expected a value (a string, number, boolean, array or inline table; " +
161
+ "dates and hex/octal/binary numbers are not read)");
162
+ }
163
+ /** Whether the `length` characters at the cursor end a value. */
164
+ delimited(length) {
165
+ const next = this.text[this.pos + length];
166
+ return next === undefined || /[\s,\]}#]/.test(next);
167
+ }
168
+ basicString() {
169
+ this.pos++;
170
+ let out = "";
171
+ for (;;) {
172
+ const ch = this.text[this.pos];
173
+ if (ch === undefined || ch === "\n")
174
+ this.fail("unterminated string");
175
+ this.pos++;
176
+ if (ch === '"')
177
+ return out;
178
+ out += ch === "\\" ? this.escape() : this.plain(ch);
179
+ }
180
+ }
181
+ literalString() {
182
+ this.pos++;
183
+ const end = this.text.indexOf("'", this.pos);
184
+ const newline = this.text.indexOf("\n", this.pos);
185
+ if (end === -1 || (newline !== -1 && newline < end)) {
186
+ this.fail("unterminated string");
187
+ }
188
+ const body = this.text.slice(this.pos, end);
189
+ for (const ch of body)
190
+ this.plain(ch);
191
+ this.pos = end + 1;
192
+ return body;
193
+ }
194
+ /** A `"""` or `'''` string, `quote` naming which. */
195
+ multilineString(quote) {
196
+ this.pos += 3;
197
+ // A newline straight after the opening delimiter is trimmed.
198
+ if (this.text.startsWith("\r\n", this.pos))
199
+ this.pos += 2;
200
+ else if (this.text[this.pos] === "\n")
201
+ this.pos++;
202
+ let out = "";
203
+ for (;;) {
204
+ const ch = this.text[this.pos];
205
+ if (ch === undefined)
206
+ this.fail("unterminated multi-line string");
207
+ if (ch === quote && this.text.startsWith(quote.repeat(3), this.pos)) {
208
+ // Up to two quotes may sit right before the closing delimiter.
209
+ let run = 3;
210
+ while (this.text[this.pos + run] === quote)
211
+ run++;
212
+ if (run > 5)
213
+ this.fail("too many quotes closing a multi-line string");
214
+ this.pos += run;
215
+ return out + quote.repeat(run - 3);
216
+ }
217
+ this.pos++;
218
+ if (ch === "\\" && quote === '"') {
219
+ const continuation = /[ \t]*\r?\n[\s]*/y;
220
+ continuation.lastIndex = this.pos;
221
+ const skip = continuation.exec(this.text);
222
+ if (skip !== null)
223
+ this.pos += skip[0].length;
224
+ else
225
+ out += this.escape();
226
+ }
227
+ else {
228
+ out += ch === "\n" || ch === "\r" ? ch : this.plain(ch);
229
+ }
230
+ }
231
+ }
232
+ /** The character a `\` escape (cursor just past the backslash) stands for. */
233
+ escape() {
234
+ const ch = this.text[this.pos];
235
+ if (ch !== undefined && Object.hasOwn(ESCAPES, ch)) {
236
+ this.pos++;
237
+ return ESCAPES[ch];
238
+ }
239
+ const width = ch === "u" ? 4 : ch === "U" ? 8 : 0;
240
+ const hex = this.text.slice(this.pos + 1, this.pos + 1 + width);
241
+ const code = width > 0 && /^[0-9A-Fa-f]+$/.test(hex) && hex.length === width
242
+ ? parseInt(hex, 16)
243
+ : -1;
244
+ if (code < 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)) {
245
+ this.fail("invalid escape sequence in string");
246
+ }
247
+ this.pos += 1 + width;
248
+ return String.fromCodePoint(code);
249
+ }
250
+ /** `ch` unchanged, unless it is a control character TOML forbids in a string. */
251
+ plain(ch) {
252
+ // deno-lint-ignore no-control-regex -- matching control characters is the point
253
+ if (/[\x00-\x08\x0a-\x1f\x7f]/.test(ch)) {
254
+ this.fail("control character in string");
255
+ }
256
+ return ch;
257
+ }
258
+ array() {
259
+ this.pos++;
260
+ const items = [];
261
+ for (;;) {
262
+ this.skipBlank();
263
+ if (this.text[this.pos] === "]") {
264
+ this.pos++;
265
+ return items;
266
+ }
267
+ items.push(this.value());
268
+ this.skipBlank();
269
+ const ch = this.text[this.pos];
270
+ this.pos++;
271
+ if (ch === "]")
272
+ return items;
273
+ if (ch !== ",")
274
+ this.fail('expected "," or "]" in array');
275
+ }
276
+ }
277
+ inlineTable() {
278
+ this.pos++;
279
+ const table = {};
280
+ for (;;) {
281
+ this.skipBlank();
282
+ if (this.text[this.pos] === "}") {
283
+ this.pos++;
284
+ return table;
285
+ }
286
+ this.keyValue(table);
287
+ this.skipBlank();
288
+ const ch = this.text[this.pos];
289
+ this.pos++;
290
+ if (ch === "}")
291
+ return table;
292
+ if (ch !== ",")
293
+ this.fail('expected "," or "}" in inline table');
294
+ }
295
+ }
296
+ /** Expect the literal `token` (after optional spaces). */
297
+ expect(token) {
298
+ this.skipSpaces();
299
+ if (!this.text.startsWith(token, this.pos)) {
300
+ this.fail(`expected "${token}"`);
301
+ }
302
+ this.pos += token.length;
303
+ }
304
+ /** Only a comment may follow a statement on its line. */
305
+ endOfLine() {
306
+ this.skipSpaces();
307
+ if (this.text[this.pos] === "#")
308
+ this.skipComment();
309
+ if (this.text.startsWith("\r\n", this.pos))
310
+ this.pos += 2;
311
+ else if (this.text[this.pos] === "\n")
312
+ this.pos++;
313
+ else if (this.pos < this.text.length)
314
+ this.fail("expected a new line");
315
+ }
316
+ skipSpaces() {
317
+ while (this.text[this.pos] === " " || this.text[this.pos] === "\t") {
318
+ this.pos++;
319
+ }
320
+ }
321
+ /** Spaces, newlines and comments. */
322
+ skipBlank() {
323
+ for (;;) {
324
+ const ch = this.text[this.pos];
325
+ if (ch === " " || ch === "\t" || ch === "\n" || ch === "\r")
326
+ this.pos++;
327
+ else if (ch === "#")
328
+ this.skipComment();
329
+ else
330
+ return;
331
+ }
332
+ }
333
+ skipComment() {
334
+ const end = this.text.indexOf("\n", this.pos);
335
+ this.pos = end === -1 ? this.text.length : end;
336
+ }
337
+ fail(message) {
338
+ const line = this.text.slice(0, this.pos).split("\n").length;
339
+ throw new SyntaxError(`line ${line}: ${message}`);
340
+ }
341
+ }
342
+ /**
343
+ * Set `table[key]` as an own, enumerable property. `define` rather than
344
+ * assignment, so a key named `__proto__` is stored as data instead of
345
+ * replacing the object's prototype.
346
+ */
347
+ function define(table, key, value) {
348
+ Object.defineProperty(table, key, {
349
+ value,
350
+ enumerable: true,
351
+ writable: true,
352
+ configurable: true,
353
+ });
354
+ }
@@ -0,0 +1,69 @@
1
+ /** One `&&`-separated segment of a command: argv to run, or text to keep verbatim. */
2
+ export type Segment = {
3
+ readonly argv: readonly string[];
4
+ } | {
5
+ readonly raw: string;
6
+ };
7
+ /**
8
+ * Split a shell command into its `&&`-separated segments, each one argv
9
+ * (never empty: a segment is non-blank and holds no backslash), or the raw
10
+ * text when it is too shell-specific to translate (or its quoting does not
11
+ * balance). Blank segments are dropped.
12
+ */
13
+ export declare function segments(command: string): Segment[];
14
+ /** Split a command on top-level `&&`, ignoring `&&` inside quotes. */
15
+ export declare function splitChain(command: string): string[];
16
+ /**
17
+ * Split a command segment into argv with POSIX quoting rules, or `undefined`
18
+ * when the segment's quoting is unbalanced. An unterminated quote is not
19
+ * translatable, so the caller falls back to preserving the raw text — the
20
+ * scaffold must never silently drop half a command.
21
+ */
22
+ export declare function tokenize(segment: string): string[] | undefined;
23
+ /**
24
+ * A double-quoted string literal for `value`, valid as TypeScript and as
25
+ * Python alike — the one escaper every generated literal goes through.
26
+ *
27
+ * `JSON.stringify` escapes quotes, backslashes, and control characters (as
28
+ * `\n`, `\t`, `\uXXXX`, which both languages read the same way), but leaves
29
+ * U+2028/U+2029 raw — legal inside JSON strings, line terminators to a
30
+ * JavaScript parser — so those are escaped on top, keeping the generated
31
+ * literal on one line whatever the imported command contains.
32
+ */
33
+ export declare function literal(value: string): string;
34
+ /**
35
+ * `text` on one line, fit for a `//` or `#` comment: every run of whitespace
36
+ * or control characters collapses to a space, so an embedded newline cannot
37
+ * break the text out of its comment, and a NUL (which Python refuses in
38
+ * source) never reaches the file.
39
+ */
40
+ export declare function oneLine(text: string): string;
41
+ /** An imported task with a unique identifier and its dependencies remapped to identifiers. */
42
+ export interface Named<T> {
43
+ /** The identifier of the generated target field. */
44
+ readonly id: string;
45
+ /** The task as it was imported. */
46
+ readonly task: T;
47
+ /** The identifiers of the tasks it depends on (unknown names dropped). */
48
+ readonly deps: readonly string[];
49
+ }
50
+ /**
51
+ * Give each task a unique identifier — `toId` of its name, suffixed with `_`
52
+ * until it collides with neither another task's nor a `reserved` one — and
53
+ * remap its dependencies to those identifiers.
54
+ */
55
+ export declare function normalize<T extends {
56
+ name: string;
57
+ deps: readonly string[];
58
+ }>(tasks: readonly T[], toId: (name: string) => string, reserved: ReadonlySet<string>): Named<T>[];
59
+ /**
60
+ * Order tasks so every dependency is declared before its dependents (Zuke
61
+ * forbids forward references), dropping the edges that would close a cycle
62
+ * (a task naming itself included). Returns the order — each task's `deps`
63
+ * without its dropped edges, so every one names a task declared above it —
64
+ * plus, per task id, the dependency ids that were dropped.
65
+ */
66
+ export declare function order<T>(tasks: readonly Named<T>[]): {
67
+ ordered: Named<T>[];
68
+ dropped: Map<string, string[]>;
69
+ };
@@ -0,0 +1,198 @@
1
+ // Copyright (c) 2026 the Zuke contributors
2
+ // SPDX-License-Identifier: MIT
3
+ /**
4
+ * The language-neutral half of `zuke import`: splitting an imported shell
5
+ * command into argv (or flagging it as too shell-specific to translate),
6
+ * quoting a value into a generated source file, and giving imported tasks
7
+ * unique identifiers in a declaration order with no forward reference. The
8
+ * TypeScript (`zuke.ts`) and Python (`build.py`) generators both render from
9
+ * these, so the two can never disagree about what a command means.
10
+ *
11
+ * @module
12
+ */
13
+ import { splitShellArgs } from "@zuke/core/shell";
14
+ /** Shell features a single argv cannot faithfully express. */
15
+ function needsShell(segment) {
16
+ // pipe, redirect, subst, env expand, and a newline (a second command)
17
+ if (/[|<>;`$\n\r]/.test(segment))
18
+ return true;
19
+ if (/(^|\s)&(\s|$)/.test(segment))
20
+ return true; // background job
21
+ if (hasUnquotedBackslash(segment))
22
+ return true; // escape or Windows separator?
23
+ const first = segment.trim().split(/\s+/)[0] ?? "";
24
+ return /^[A-Za-z_][A-Za-z0-9_]*=/.test(first); // leading VAR=value assignment
25
+ }
26
+ /**
27
+ * Whether `segment` contains a backslash outside quotes, which is ambiguous and
28
+ * therefore not translatable: a POSIX shell reads it as an escape (`a\ b` is one
29
+ * argument), while a `package.json` script written on Windows — where npm runs
30
+ * scripts through `cmd.exe` — uses it as a path separator (`node scripts\b.js`).
31
+ * Picking either reading silently changes the command, so the segment is
32
+ * preserved verbatim for a human to resolve. A backslash inside quotes is
33
+ * unambiguous and stays translatable.
34
+ */
35
+ function hasUnquotedBackslash(segment) {
36
+ let quote;
37
+ for (let i = 0; i < segment.length; i++) {
38
+ const ch = segment[i];
39
+ if (quote !== undefined) {
40
+ // Inside double quotes a backslash escapes the next character, so skip it
41
+ // and keep tracking the quote state accurately.
42
+ if (quote === '"' && ch === "\\")
43
+ i++;
44
+ else if (ch === quote)
45
+ quote = undefined;
46
+ continue;
47
+ }
48
+ if (ch === '"' || ch === "'")
49
+ quote = ch;
50
+ else if (ch === "\\")
51
+ return true;
52
+ }
53
+ return false;
54
+ }
55
+ /**
56
+ * Split a shell command into its `&&`-separated segments, each one argv
57
+ * (never empty: a segment is non-blank and holds no backslash), or the raw
58
+ * text when it is too shell-specific to translate (or its quoting does not
59
+ * balance). Blank segments are dropped.
60
+ */
61
+ export function segments(command) {
62
+ const out = [];
63
+ for (const raw of splitChain(command)) {
64
+ const segment = raw.trim();
65
+ if (segment === "")
66
+ continue;
67
+ const argv = needsShell(segment) ? undefined : tokenize(segment);
68
+ out.push(argv === undefined ? { raw: segment } : { argv });
69
+ }
70
+ return out;
71
+ }
72
+ /** Split a command on top-level `&&`, ignoring `&&` inside quotes. */
73
+ export function splitChain(command) {
74
+ const parts = [];
75
+ let current = "";
76
+ let quote;
77
+ for (let i = 0; i < command.length; i++) {
78
+ const ch = command[i];
79
+ if (quote !== undefined) {
80
+ current += ch;
81
+ if (ch === quote)
82
+ quote = undefined;
83
+ continue;
84
+ }
85
+ if (ch === '"' || ch === "'") {
86
+ quote = ch;
87
+ current += ch;
88
+ continue;
89
+ }
90
+ if (ch === "&" && command[i + 1] === "&") {
91
+ parts.push(current);
92
+ current = "";
93
+ i++;
94
+ continue;
95
+ }
96
+ current += ch;
97
+ }
98
+ parts.push(current);
99
+ return parts;
100
+ }
101
+ /**
102
+ * Split a command segment into argv with POSIX quoting rules, or `undefined`
103
+ * when the segment's quoting is unbalanced. An unterminated quote is not
104
+ * translatable, so the caller falls back to preserving the raw text — the
105
+ * scaffold must never silently drop half a command.
106
+ */
107
+ export function tokenize(segment) {
108
+ try {
109
+ return splitShellArgs(segment);
110
+ }
111
+ catch {
112
+ return undefined; // Only ShellArgsError can escape splitShellArgs.
113
+ }
114
+ }
115
+ /**
116
+ * A double-quoted string literal for `value`, valid as TypeScript and as
117
+ * Python alike — the one escaper every generated literal goes through.
118
+ *
119
+ * `JSON.stringify` escapes quotes, backslashes, and control characters (as
120
+ * `\n`, `\t`, `\uXXXX`, which both languages read the same way), but leaves
121
+ * U+2028/U+2029 raw — legal inside JSON strings, line terminators to a
122
+ * JavaScript parser — so those are escaped on top, keeping the generated
123
+ * literal on one line whatever the imported command contains.
124
+ */
125
+ export function literal(value) {
126
+ return JSON.stringify(value)
127
+ .replace(/\u2028/g, "\\u2028")
128
+ .replace(/\u2029/g, "\\u2029");
129
+ }
130
+ /**
131
+ * `text` on one line, fit for a `//` or `#` comment: every run of whitespace
132
+ * or control characters collapses to a space, so an embedded newline cannot
133
+ * break the text out of its comment, and a NUL (which Python refuses in
134
+ * source) never reaches the file.
135
+ */
136
+ export function oneLine(text) {
137
+ // deno-lint-ignore no-control-regex -- matching control characters is the point
138
+ return text.replace(/[\s\x00-\x1f\x7f]+/g, " ").trim();
139
+ }
140
+ /**
141
+ * Give each task a unique identifier — `toId` of its name, suffixed with `_`
142
+ * until it collides with neither another task's nor a `reserved` one — and
143
+ * remap its dependencies to those identifiers.
144
+ */
145
+ export function normalize(tasks, toId, reserved) {
146
+ const idByName = new Map();
147
+ const used = new Set(reserved);
148
+ for (const task of tasks) {
149
+ let id = toId(task.name);
150
+ while (used.has(id))
151
+ id = `${id}_`;
152
+ used.add(id);
153
+ idByName.set(task.name, id);
154
+ }
155
+ return tasks.map((task) => ({
156
+ id: idByName.get(task.name) ?? toId(task.name),
157
+ task,
158
+ deps: task.deps
159
+ .map((d) => idByName.get(d))
160
+ .filter((d) => d !== undefined),
161
+ }));
162
+ }
163
+ /**
164
+ * Order tasks so every dependency is declared before its dependents (Zuke
165
+ * forbids forward references), dropping the edges that would close a cycle
166
+ * (a task naming itself included). Returns the order — each task's `deps`
167
+ * without its dropped edges, so every one names a task declared above it —
168
+ * plus, per task id, the dependency ids that were dropped.
169
+ */
170
+ export function order(tasks) {
171
+ const byId = new Map(tasks.map((t) => [t.id, t]));
172
+ const state = new Map();
173
+ const ordered = [];
174
+ const dropped = new Map();
175
+ const visit = (task) => {
176
+ state.set(task.id, "open");
177
+ for (const dep of task.deps) {
178
+ const target = byId.get(dep);
179
+ if (target === undefined)
180
+ continue;
181
+ const st = state.get(dep);
182
+ if (st === "open") {
183
+ dropped.set(task.id, [...(dropped.get(task.id) ?? []), dep]);
184
+ }
185
+ else if (st === undefined) {
186
+ visit(target);
187
+ }
188
+ }
189
+ state.set(task.id, "done");
190
+ const cut = dropped.get(task.id) ?? [];
191
+ ordered.push({ ...task, deps: task.deps.filter((d) => !cut.includes(d)) });
192
+ };
193
+ for (const task of tasks) {
194
+ if (state.get(task.id) === undefined)
195
+ visit(task);
196
+ }
197
+ return { ordered, dropped };
198
+ }