@zuke-build/cli 0.0.0-stage → 2.6.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 (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +343 -2
  3. package/mod.d.ts +99 -0
  4. package/mod.js +893 -0
  5. package/package.json +35 -4
  6. package/src/binary_launcher.d.ts +49 -0
  7. package/src/binary_launcher.js +327 -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 +65 -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 +220 -0
  23. package/src/dispatch.js +538 -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 +464 -0
  36. package/src/mcp_config.d.ts +63 -0
  37. package/src/mcp_config.js +86 -0
  38. package/src/output.d.ts +38 -0
  39. package/src/output.js +43 -0
  40. package/src/paint.d.ts +42 -0
  41. package/src/paint.js +38 -0
  42. package/src/project.d.ts +69 -0
  43. package/src/project.js +132 -0
  44. package/src/pyproject.d.ts +30 -0
  45. package/src/pyproject.js +156 -0
  46. package/src/python_build.d.ts +27 -0
  47. package/src/python_build.js +197 -0
  48. package/src/records.d.ts +9 -0
  49. package/src/records.js +13 -0
  50. package/src/relock.d.ts +11 -0
  51. package/src/relock.js +182 -0
  52. package/src/setup.d.ts +251 -0
  53. package/src/setup.js +601 -0
  54. package/src/star.d.ts +44 -0
  55. package/src/star.js +100 -0
  56. package/src/starter.d.ts +55 -0
  57. package/src/starter.js +126 -0
  58. package/src/toml.d.ts +32 -0
  59. package/src/toml.js +354 -0
  60. package/src/translate.d.ts +69 -0
  61. package/src/translate.js +198 -0
  62. package/src/upgrade.d.ts +113 -0
  63. package/src/upgrade.js +344 -0
  64. package/src/version.d.ts +11 -0
  65. package/src/version.js +13 -0
  66. package/src/version_report.d.ts +55 -0
  67. package/src/version_report.js +187 -0
  68. package/zuke.js +8 -0
package/src/star.js ADDED
@@ -0,0 +1,100 @@
1
+ // Copyright (c) 2026 the Zuke contributors
2
+ // SPDX-License-Identifier: MIT
3
+ /**
4
+ * The end-of-`setup` "star the repo" prompt: ask once, then help with the
5
+ * answer — star directly through an authenticated `gh`, fall back to opening
6
+ * the repository page in the browser, and fall back again to printing the URL.
7
+ * Every side effect sits behind {@link StarActions} so the flow is testable
8
+ * without a network, a `gh` install, or a browser.
9
+ *
10
+ * @module
11
+ */
12
+ import { BrowserTasks } from "@zuke/core";
13
+ import { GhTasks } from "@zuke/gh";
14
+ /** The Zuke repository's home page. */
15
+ export const ZUKE_REPO_URL = "https://github.com/zuke-build/zuke";
16
+ /** The `gh api` endpoint that stars the Zuke repository for the caller. */
17
+ const STAR_ENDPOINT = "user/starred/zuke-build/zuke";
18
+ /**
19
+ * Build the real {@link StarActions} over the given task functions. The
20
+ * parameters exist as seams — production uses the defaults ({@link GhTasks}
21
+ * and {@link BrowserTasks}); tests substitute fakes so no process is spawned.
22
+ */
23
+ export function realStarActions(runGh = GhTasks.run, apiGh = GhTasks.api, openUrl = BrowserTasks.open) {
24
+ return {
25
+ async ghAuthenticated() {
26
+ try {
27
+ const output = await runGh((s) => s.command("auth", "status").quiet().noThrow());
28
+ return output.code === 0;
29
+ }
30
+ catch {
31
+ return false; // gh not installed (ToolNotFoundError) — use the browser.
32
+ }
33
+ },
34
+ async starWithGh() {
35
+ await apiGh(STAR_ENDPOINT, (s) => s.method("PUT").silent().quiet());
36
+ },
37
+ async openBrowser(url) {
38
+ try {
39
+ const output = await openUrl(url, (s) => s.quiet().noThrow());
40
+ return output.code === 0;
41
+ }
42
+ catch {
43
+ return false; // no opener on this system — fall back to the URL.
44
+ }
45
+ },
46
+ };
47
+ }
48
+ /** The real {@link StarActions}, backed by `GhTasks` and `BrowserTasks`. */
49
+ export const defaultStarActions = realStarActions();
50
+ /** Star through `gh`, reporting success; `false` sends the caller onward. */
51
+ async function starViaGh(host, actions) {
52
+ try {
53
+ await actions.starWithGh();
54
+ }
55
+ catch {
56
+ return false; // gh was there but the call failed (network, scope).
57
+ }
58
+ host.log("★ Starred zuke-build/zuke — thank you!");
59
+ return true;
60
+ }
61
+ /** Open the repo page, reporting success; `false` sends the caller onward. */
62
+ async function openRepoPage(host, actions) {
63
+ try {
64
+ if (!(await actions.openBrowser(ZUKE_REPO_URL)))
65
+ return false;
66
+ }
67
+ catch {
68
+ return false; // no opener on this system — fall back to the URL.
69
+ }
70
+ host.log(`Opened ${ZUKE_REPO_URL} — click “☆ Star”. Thank you!`);
71
+ return true;
72
+ }
73
+ /**
74
+ * Ask the user to star the Zuke repository and help with a yes. The `gh` login
75
+ * is probed *before* asking, so the question says what a yes will do: with an
76
+ * authenticated `gh`, that the star is placed on their behalf through it;
77
+ * without one, that the repository page opens in the browser (falling back to
78
+ * printing its URL). A "no" is respected silently, and no failure here ever
79
+ * fails the setup that just succeeded.
80
+ */
81
+ export async function promptStar(host, prompter, actions) {
82
+ let authed = false;
83
+ try {
84
+ authed = await actions.ghAuthenticated();
85
+ }
86
+ catch {
87
+ // A probe failure only means the browser path — never a failed setup.
88
+ }
89
+ const how = authed
90
+ ? "uses your gh login to star on your behalf"
91
+ : "opens the repo page in your browser";
92
+ if (!prompter.confirm(`Enjoying Zuke? Star zuke-build/zuke on GitHub? (${how})`)) {
93
+ return;
94
+ }
95
+ if (authed && (await starViaGh(host, actions)))
96
+ return;
97
+ if (await openRepoPage(host, actions))
98
+ return;
99
+ host.log(`Star Zuke at ${ZUKE_REPO_URL} — thank you!`);
100
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * The `jsr:` dependency a scaffolded `deno.json` maps `@zuke/<name>` to.
3
+ *
4
+ * The caret major is what gets pinned: every Zuke package is 1.x on full
5
+ * semver, so `@^1` takes minors and patches and stops a future major from
6
+ * landing in a scaffolded build unannounced. One definition, so the starter
7
+ * build and `zuke import`'s generated one cannot drift apart on it.
8
+ */
9
+ export declare function zukeDependency(name: string): string;
10
+ /**
11
+ * The `deno.json` import map entries the starter build resolves through.
12
+ *
13
+ * The build imports `@zuke/core` by its **bare** specifier rather than writing
14
+ * `jsr:@zuke/core@^1` inline, because Deno's default lint set (the one that
15
+ * applies to a `deno.json` that does not configure `lint.rules`, which is
16
+ * exactly what `setup` writes) rejects an inline `jsr:` specifier under
17
+ * `no-import-prefix` — so a scaffold that inlined it failed `deno lint` on its
18
+ * own first file. The pin moves to the map instead; it is not lost.
19
+ */
20
+ export declare const STARTER_IMPORTS: Readonly<Record<string, string>>;
21
+ /** The starter `zuke.ts`, with the build class named `name`. */
22
+ export declare function starterBuild(name: string): string;
23
+ /**
24
+ * The starter `zuke.json` config. Its presence at the repository root is what
25
+ * `@zuke/core`'s `repoRoot()` walks up to find; the recorded `name` is the
26
+ * build class for reference, and `build` names the build file when it is not
27
+ * the default `zuke.ts`.
28
+ */
29
+ export declare function starterConfig(name: string, buildFile: string): string;
30
+ /** The build file `zuke setup --sdk python` writes, which `sdk.command` runs. */
31
+ export declare const PYTHON_BUILD_FILE = "build.py";
32
+ /**
33
+ * The `sdk.command` a Python scaffold's `zuke.json` names: `uv run` reads the
34
+ * inline script metadata atop {@link starterPythonBuild} and provides the
35
+ * `zuke` package, so the build runs with no project file of its own.
36
+ */
37
+ export declare const PYTHON_SDK_COMMAND: readonly string[];
38
+ /**
39
+ * The inline script metadata (PEP 723) every scaffolded `build.py` opens with,
40
+ * which makes `uv run build.py` install the `zuke` SDK by itself. Shared by
41
+ * {@link starterPythonBuild} and `zuke import`'s generated build.
42
+ */
43
+ export declare const PYTHON_SCRIPT_METADATA = "# /// script\n# requires-python = \">=3.12\"\n# dependencies = [\"zuke\"]\n# ///\n";
44
+ /**
45
+ * The starter `build.py`, the Python SDK's shape of {@link starterBuild}: the
46
+ * build class named `name`, a sample target and a `default`. The script
47
+ * metadata block makes `uv run build.py` install the SDK by itself.
48
+ */
49
+ export declare function starterPythonBuild(name: string): string;
50
+ /**
51
+ * The `zuke.json` of a build another SDK hosts: {@link starterConfig}'s
52
+ * `name`, the `sdk.command` that starts the worker, and the exact
53
+ * `@zuke/engine` release the launchers and the `zuke` command run it on.
54
+ */
55
+ export declare function starterSdkConfig(name: string, engine: string): string;
package/src/starter.js ADDED
@@ -0,0 +1,126 @@
1
+ // Copyright (c) 2026 the Zuke contributors
2
+ // SPDX-License-Identifier: MIT
3
+ /**
4
+ * The files `zuke setup` scaffolds from a template: the starter build and the
5
+ * repository-root marker. Kept apart from the scaffolder because the build
6
+ * template is source code for the user's project — its `console.log` runs in
7
+ * their build, not in this process — and the suite's check that nothing in
8
+ * this package writes to the console except its sink names this module as the
9
+ * one file that may look as if it does.
10
+ *
11
+ * @module
12
+ */
13
+ import { BUILD_FIELD, BUILD_FILE } from "./build_file.js";
14
+ /**
15
+ * The `jsr:` dependency a scaffolded `deno.json` maps `@zuke/<name>` to.
16
+ *
17
+ * The caret major is what gets pinned: every Zuke package is 1.x on full
18
+ * semver, so `@^1` takes minors and patches and stops a future major from
19
+ * landing in a scaffolded build unannounced. One definition, so the starter
20
+ * build and `zuke import`'s generated one cannot drift apart on it.
21
+ */
22
+ export function zukeDependency(name) {
23
+ return `jsr:@zuke/${name}@^1`;
24
+ }
25
+ /**
26
+ * The `deno.json` import map entries the starter build resolves through.
27
+ *
28
+ * The build imports `@zuke/core` by its **bare** specifier rather than writing
29
+ * `jsr:@zuke/core@^1` inline, because Deno's default lint set (the one that
30
+ * applies to a `deno.json` that does not configure `lint.rules`, which is
31
+ * exactly what `setup` writes) rejects an inline `jsr:` specifier under
32
+ * `no-import-prefix` — so a scaffold that inlined it failed `deno lint` on its
33
+ * own first file. The pin moves to the map instead; it is not lost.
34
+ */
35
+ export const STARTER_IMPORTS = {
36
+ "@zuke/core": zukeDependency("core"),
37
+ };
38
+ /** The starter `zuke.ts`, with the build class named `name`. */
39
+ export function starterBuild(name) {
40
+ return `import { Build, run, target } from "@zuke/core";
41
+
42
+ /** Your project's build. Run a target with \`./zuke <target>\`. */
43
+ class ${name} extends Build {
44
+ hello = target()
45
+ .description("A sample target — replace me with real work")
46
+ .executes(() => {
47
+ console.log("Hello from Zuke!");
48
+ });
49
+
50
+ // Convention: \`default\` runs when no target is named.
51
+ default = target()
52
+ .description("Default target")
53
+ .dependsOn(this.hello)
54
+ .executes(() => {});
55
+ }
56
+
57
+ await run(${name});
58
+ `;
59
+ }
60
+ /**
61
+ * The starter `zuke.json` config. Its presence at the repository root is what
62
+ * `@zuke/core`'s `repoRoot()` walks up to find; the recorded `name` is the
63
+ * build class for reference, and `build` names the build file when it is not
64
+ * the default `zuke.ts`.
65
+ */
66
+ export function starterConfig(name, buildFile) {
67
+ const build = buildFile === BUILD_FILE ? {} : { [BUILD_FIELD]: buildFile };
68
+ return `${JSON.stringify({ name, ...build }, null, 2)}\n`;
69
+ }
70
+ /** The build file `zuke setup --sdk python` writes, which `sdk.command` runs. */
71
+ export const PYTHON_BUILD_FILE = "build.py";
72
+ /**
73
+ * The `sdk.command` a Python scaffold's `zuke.json` names: `uv run` reads the
74
+ * inline script metadata atop {@link starterPythonBuild} and provides the
75
+ * `zuke` package, so the build runs with no project file of its own.
76
+ */
77
+ export const PYTHON_SDK_COMMAND = [
78
+ "uv",
79
+ "run",
80
+ PYTHON_BUILD_FILE,
81
+ ];
82
+ /**
83
+ * The inline script metadata (PEP 723) every scaffolded `build.py` opens with,
84
+ * which makes `uv run build.py` install the `zuke` SDK by itself. Shared by
85
+ * {@link starterPythonBuild} and `zuke import`'s generated build.
86
+ */
87
+ export const PYTHON_SCRIPT_METADATA = `# /// script
88
+ # requires-python = ">=3.12"
89
+ # dependencies = ["zuke"]
90
+ # ///
91
+ `;
92
+ /**
93
+ * The starter `build.py`, the Python SDK's shape of {@link starterBuild}: the
94
+ * build class named `name`, a sample target and a `default`. The script
95
+ * metadata block makes `uv run build.py` install the SDK by itself.
96
+ */
97
+ export function starterPythonBuild(name) {
98
+ return `${PYTHON_SCRIPT_METADATA}"""Your project's build. Run a target with ./zuke <target>."""
99
+
100
+ from zuke import Build, run, target
101
+
102
+
103
+ class ${name}(Build):
104
+ """The targets of this project."""
105
+
106
+ hello = (
107
+ target()
108
+ .description("A sample target, replace me with real work")
109
+ .executes(lambda ctx: ctx.log("Hello from Zuke!"))
110
+ )
111
+
112
+ # Convention: default runs when no target is named.
113
+ default = target().description("Default target").depends_on(hello)
114
+
115
+
116
+ run(${name})
117
+ `;
118
+ }
119
+ /**
120
+ * The `zuke.json` of a build another SDK hosts: {@link starterConfig}'s
121
+ * `name`, the `sdk.command` that starts the worker, and the exact
122
+ * `@zuke/engine` release the launchers and the `zuke` command run it on.
123
+ */
124
+ export function starterSdkConfig(name, engine) {
125
+ return `${JSON.stringify({ name, sdk: { command: PYTHON_SDK_COMMAND }, engine }, null, 2)}\n`;
126
+ }
package/src/toml.d.ts ADDED
@@ -0,0 +1,32 @@
1
+ /**
2
+ * A strict reader for the subset of TOML that `zuke import` needs from a
3
+ * `pyproject.toml`, so the package stays dependency-free.
4
+ *
5
+ * Read: comments; `[table]` headers with bare, quoted and dotted keys
6
+ * (`[tool.hatch.envs."default".scripts]`); key/value pairs with bare, quoted
7
+ * and dotted keys; basic and literal strings, single- and multi-line
8
+ * (`"""`/`'''`, with the basic form's escapes and line-ending backslash);
9
+ * decimal integers and floats; booleans; arrays (multi-line, comments inside,
10
+ * trailing comma); and inline tables (newlines and a trailing comma tolerated,
11
+ * as TOML 1.1 allows).
12
+ *
13
+ * `[[array.of.tables]]` headers are parsed and their contents validated, but
14
+ * discarded: no task table is an array of tables, and skipping them keeps
15
+ * every `pyproject.toml` that carries a `[[tool.mypy.overrides]]` readable.
16
+ *
17
+ * Rejected, naming the line: dates and times, hexadecimal/octal/binary
18
+ * integers, `inf`/`nan`, a duplicate key, a table defined twice, a control
19
+ * character in a string, and anything else malformed.
20
+ *
21
+ * @module
22
+ */
23
+ /** A parsed TOML table: plain data, to be narrowed by the caller. */
24
+ type Table = Record<string, unknown>;
25
+ /**
26
+ * Parse `text` as TOML into plain data: tables are objects, arrays are arrays,
27
+ * strings, numbers and booleans are themselves.
28
+ *
29
+ * @throws {SyntaxError} naming the line of the first construct it cannot read.
30
+ */
31
+ export declare function parseToml(text: string): Table;
32
+ export {};
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
+ }