@native-sdk/cli 0.7.2 → 0.8.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 (41) hide show
  1. package/build/app.zig +265 -65
  2. package/build/ts_run.mjs +6 -8
  3. package/build.zig +292 -349
  4. package/package.json +13 -11
  5. package/packages/core/compile-surface/core.ts +559 -0
  6. package/packages/core/package-lock.json +375 -12
  7. package/packages/core/package.json +9 -6
  8. package/packages/core/scripts/compiler_typecheck.mjs +58 -0
  9. package/packages/core/scripts/gen_case_tables.mjs +130 -0
  10. package/packages/core/scripts/gen_declarations.mjs +97 -0
  11. package/packages/core/scripts/run_external_core_compiler.mjs +108 -0
  12. package/packages/core/scripts/stage_external_core.mjs +148 -0
  13. package/packages/core/sdk/core.d.ts +363 -0
  14. package/packages/core/sdk/events.d.ts +65 -0
  15. package/packages/core/sdk/text.d.ts +51 -0
  16. package/packages/core/src/checker.ts +3 -3
  17. package/packages/core/src/cli.ts +40 -38
  18. package/packages/core/src/contract.ts +749 -0
  19. package/packages/core/src/devhost.ts +4 -3
  20. package/packages/core/src/diagnostics.ts +5 -7
  21. package/packages/core/src/{transpile.ts → frontend.ts} +38 -50
  22. package/packages/core/src/infer.ts +1 -1
  23. package/packages/core/src/typed_ast.ts +16 -15
  24. package/packages/core/src/wyhash.ts +79 -0
  25. package/skill-data/ts-core/SKILL.md +29 -29
  26. package/src/runtime/ts_core_host.zig +38 -38
  27. package/src/runtime/ts_ui_app.zig +12 -12
  28. package/src/tooling/manifest.zig +32 -0
  29. package/src/tooling/raw_manifest.zig +4 -0
  30. package/src/tooling/templates.zig +25 -20
  31. package/src/tooling/ts_core.zig +55 -34
  32. package/src/tooling/verbs.zig +1 -1
  33. package/tools/corewire/core_abi.zig +169 -0
  34. package/tools/corewire/emit.zig +2418 -0
  35. package/tools/corewire/emit_facade.zig +3984 -0
  36. package/tools/corewire/emit_profile.zig +501 -0
  37. package/tools/corewire/main.zig +561 -0
  38. package/tools/corewire/shim_rt.zig +632 -0
  39. package/tools/corewire/sidecar.zig +2507 -0
  40. package/packages/core/rt/rt.zig +0 -1986
  41. package/packages/core/src/emitter.ts +0 -11898
@@ -0,0 +1,97 @@
1
+ #!/usr/bin/env node
2
+ // Generate the SDK's shipped declaration files (sdk/*.d.ts) from the
3
+ // author-visible modules with the real tsc — never hand-written. The
4
+ // npm package ships TS sources as its editor type surface (the exports
5
+ // map's `types` condition), and these generated declarations beside
6
+ // them so external tooling that consumes declaration files can resolve
7
+ // `@native-sdk/core` types without compiling the sources.
8
+ //
9
+ // The global Uint8Array augmentation (sdk/bytes_text_methods.d.ts) is
10
+ // deliberately NOT part of this program: the generated declarations
11
+ // must stay clean of ambient augmentations, which collide with other
12
+ // toolchains' own lib typings.
13
+ //
14
+ // node scripts/gen_declarations.mjs # (re)write sdk/*.d.ts
15
+ // node scripts/gen_declarations.mjs --check # verify freshness, no writes
16
+
17
+ import ts from "@typescript/old";
18
+ import fs from "node:fs";
19
+ import path from "node:path";
20
+ import { fileURLToPath } from "node:url";
21
+
22
+ const pkg = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
23
+ const sdkDir = path.join(pkg, "sdk");
24
+
25
+ /// The author-visible modules, in exports-map order.
26
+ export const declarationSources = ["core.ts", "text.ts", "events.ts"];
27
+
28
+ /// Generate declaration text per output file name (relative to sdk/),
29
+ /// entirely in memory.
30
+ export function generateDeclarations() {
31
+ const roots = declarationSources.map((f) => path.join(sdkDir, f));
32
+ const options = {
33
+ // The checker's own environment (typed_ast.ts subsetCompilerOptions),
34
+ // minus the app-side plumbing: strict, modern lib, TS-extension
35
+ // imports rewritten so the emitted declarations resolve as files.
36
+ strict: true,
37
+ exactOptionalPropertyTypes: true,
38
+ target: ts.ScriptTarget.ESNext,
39
+ module: ts.ModuleKind.ESNext,
40
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
41
+ lib: ["lib.esnext.d.ts"],
42
+ types: [],
43
+ allowImportingTsExtensions: true,
44
+ rewriteRelativeImportExtensions: true,
45
+ declaration: true,
46
+ emitDeclarationOnly: true,
47
+ skipLibCheck: false,
48
+ };
49
+ const program = ts.createProgram(roots, options);
50
+ const diagnostics = ts.getPreEmitDiagnostics(program).filter((d) => d.category === ts.DiagnosticCategory.Error);
51
+ if (diagnostics.length > 0) {
52
+ const text = diagnostics
53
+ .map((d) => `TS${d.code} ${ts.flattenDiagnosticMessageText(d.messageText, "\n")}`)
54
+ .join("\n");
55
+ throw new Error(`the SDK sources do not typecheck for declaration emit:\n${text}`);
56
+ }
57
+ const outputs = new Map();
58
+ const result = program.emit(undefined, (fileName, text) => {
59
+ // Declaration emit preserves the sources' `.ts` relative specifiers;
60
+ // spell them `.js` (the declaration ecosystem's convention — tsc
61
+ // resolves `./text.js` to the shipped `./text.d.ts`), so consumers
62
+ // that read declarations never fall through to the sources.
63
+ const rewritten = text.replace(/(from\s+")(\.\.?\/[^"]+)\.ts(")/g, "$1$2.js$3");
64
+ outputs.set(path.basename(fileName), rewritten);
65
+ });
66
+ if (result.emitSkipped) throw new Error("declaration emit was skipped");
67
+ for (const source of declarationSources) {
68
+ const name = source.replace(/\.ts$/, ".d.ts");
69
+ if (!outputs.has(name)) throw new Error(`declaration emit produced no ${name}`);
70
+ if (/declare\s+global|interface\s+Uint8Array/.test(outputs.get(name))) {
71
+ throw new Error(`${name} carries a global augmentation — the generated declarations must stay ambient-clean`);
72
+ }
73
+ }
74
+ return outputs;
75
+ }
76
+
77
+ function main(check) {
78
+ const outputs = generateDeclarations();
79
+ let stale = false;
80
+ for (const [name, text] of outputs) {
81
+ const outPath = path.join(sdkDir, name);
82
+ const current = fs.existsSync(outPath) ? fs.readFileSync(outPath, "utf8") : null;
83
+ if (current === text) continue;
84
+ if (check) {
85
+ stale = true;
86
+ console.error(`${path.relative(pkg, outPath)} is stale — run \`node scripts/gen_declarations.mjs\``);
87
+ } else {
88
+ fs.writeFileSync(outPath, text);
89
+ console.error(`wrote ${path.relative(pkg, outPath)}`);
90
+ }
91
+ }
92
+ process.exit(stale ? 1 : 0);
93
+ }
94
+
95
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
96
+ main(process.argv.includes("--check"));
97
+ }
@@ -0,0 +1,108 @@
1
+ #!/usr/bin/env node
2
+ // Drive one external core compile — the lane every TypeScript core
3
+ // builds through: verify the toolchain release against the SDK's exact
4
+ // pin, run a library-mode build over the staged tree, and normalize
5
+ // the outputs to the paths the build graph declared. The compile itself co-emits the archive's
6
+ // OWN contract sidecar — the document the mirror module generates from,
7
+ // so the boot identity fence always pairs an archive with its own
8
+ // compile (the fixture driver, tests/compiled-core/build_core.sh, holds
9
+ // the same rule).
10
+ //
11
+ // node run_external_core_compiler.mjs --stage <dir> --name <symbol name>
12
+ // --manifest <packages/core/package.json> --out-archive <file>
13
+ // --out-sidecar <file> (--compiler <cmd> | --compiler-js <main.js>)
14
+
15
+ import { spawnSync } from "node:child_process";
16
+ import fs from "node:fs";
17
+ import os from "node:os";
18
+ import path from "node:path";
19
+
20
+ function parseArgs(argv) {
21
+ const args = {};
22
+ for (let i = 2; i < argv.length; i += 2) {
23
+ const key = argv[i];
24
+ const value = argv[i + 1];
25
+ if (!key.startsWith("--") || value === undefined) {
26
+ console.error("usage: run_external_core_compiler.mjs --stage <dir> --name <n> --manifest <package.json> --out-archive <file> --out-sidecar <file> (--compiler <cmd> | --compiler-js <main.js>)");
27
+ process.exit(2);
28
+ }
29
+ args[key.slice(2)] = value;
30
+ }
31
+ for (const required of ["stage", "name", "manifest", "out-archive", "out-sidecar"]) {
32
+ if (!(required in args)) {
33
+ console.error(`run_external_core_compiler.mjs: missing --${required}`);
34
+ process.exit(2);
35
+ }
36
+ }
37
+ if (!args.compiler && !args["compiler-js"]) {
38
+ console.error("run_external_core_compiler.mjs: supply --compiler <cmd> or --compiler-js <main.js>");
39
+ process.exit(2);
40
+ }
41
+ return args;
42
+ }
43
+
44
+ const args = parseArgs(process.argv);
45
+ // Every path argument resolves against the INVOCATION's cwd up front:
46
+ // the compile itself runs from a scratch directory.
47
+ for (const key of ["stage", "manifest", "out-archive", "out-sidecar", "compiler-js"]) {
48
+ if (key in args) args[key] = path.resolve(args[key]);
49
+ }
50
+ // --compiler is a COMMAND: a bare executable path (possibly containing
51
+ // spaces) or an interpreter plus script ("node .../main.js"). A path
52
+ // that exists is taken whole; anything else splits on whitespace.
53
+ const argv0 = args.compiler
54
+ ? (fs.existsSync(args.compiler) ? [args.compiler] : args.compiler.split(/\s+/))
55
+ : [process.execPath, args["compiler-js"]];
56
+
57
+ // The profile's determinism-fence table is RELEASE-PINNED DATA (see
58
+ // tools/corewire/emit_profile.zig): its ids resolve against one
59
+ // toolchain release's surface manifest, so the supplied command must BE
60
+ // the release the SDK pins — the exact-pinned dependency of
61
+ // packages/core (the ONE place the pin lives).
62
+ const manifest = JSON.parse(fs.readFileSync(args.manifest, "utf8"));
63
+ const pin = manifest.dependencies?.scriptc;
64
+ if (typeof pin !== "string" || !/^\d+\.\d+\.\d+$/.test(pin)) {
65
+ console.error("the SDK's packages/core/package.json carries no exact external core compiler pin — the SDK tree is broken; reinstall or re-clone it");
66
+ process.exit(2);
67
+ }
68
+ const versionProbe = spawnSync(argv0[0], [...argv0.slice(1), "-v"], { encoding: "utf8" });
69
+ const reported = (versionProbe.stdout ?? "").trim();
70
+ if (versionProbe.status !== 0 || reported.length === 0) {
71
+ console.error(`the external core compiler did not report a version (${argv0.join(" ")} -v failed) — run \`npm ci --prefix <sdk>/packages/core\` to install the pinned release, or point NATIVE_SDK_CORE_COMPILER at a working command`);
72
+ process.exit(2);
73
+ }
74
+ if (reported !== pin) {
75
+ console.error(`external core toolchain reports version ${reported}, but the profile's fence table is pinned to ${pin} — supply that release (npm ci --prefix <sdk>/packages/core installs it), or bump the pin when the fence table has been re-verified against the new release's surface manifest`);
76
+ process.exit(2);
77
+ }
78
+
79
+ // The compile runs in its own scratch copy: the staged tree is a build
80
+ // output another step owns, and the toolchain writes beside its entry.
81
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), "native-external-core-"));
82
+ try {
83
+ fs.cpSync(args.stage, work, { recursive: true });
84
+ const build = spawnSync(argv0[0], [...argv0.slice(1), "build", "--lib", "--profile", "profile.json", "-o", args.name], {
85
+ cwd: work,
86
+ stdio: "inherit",
87
+ });
88
+ if (build.status !== 0) process.exit(build.status ?? 1);
89
+
90
+ // The toolchain writes the ar archive at the bare -o name (some
91
+ // releases add .lib.a); the link input needs a recognized extension.
92
+ const produced = [`${args.name}.lib.a`, args.name].find((name) => fs.existsSync(path.join(work, name)));
93
+ if (!produced) {
94
+ console.error(`the external core compile produced no archive (expected ${args.name}.lib.a or ${args.name})`);
95
+ process.exit(1);
96
+ }
97
+ const sidecar = path.join(work, "core.contract.json");
98
+ if (!fs.existsSync(sidecar)) {
99
+ console.error("the external core compile emitted no core.contract.json beside the archive — the co-emitted sidecar is the mirror's contract; the compile is incomplete");
100
+ process.exit(1);
101
+ }
102
+ fs.mkdirSync(path.dirname(args["out-archive"]), { recursive: true });
103
+ fs.mkdirSync(path.dirname(args["out-sidecar"]), { recursive: true });
104
+ fs.copyFileSync(path.join(work, produced), args["out-archive"]);
105
+ fs.copyFileSync(sidecar, args["out-sidecar"]);
106
+ } finally {
107
+ fs.rmSync(work, { recursive: true, force: true });
108
+ }
@@ -0,0 +1,148 @@
1
+ #!/usr/bin/env node
2
+ // Stage a ts-core app for an external core compile: one scratch tree
3
+ // carrying the AUTHOR'S sources verbatim except for mechanical,
4
+ // behavior-preserving transforms, the SDK modules they import, the
5
+ // static @native-sdk/core restatement, and the generated compile entry
6
+ // + profile beside them. The product-lane twin of the fixture driver's
7
+ // staging (tests/compiled-core/build_core.sh) — the transforms are the
8
+ // same five, ported spelling for spelling, and the paired compiled-core
9
+ // batteries hold their output byte-identical to the transpiler lane:
10
+ //
11
+ // 1. bare-specifier resolution — "@native-sdk/core*" rewrites to the
12
+ // staged ./sdk/ copies (the toolchain compiles from files, not
13
+ // package resolution), relative to each staged file's own depth;
14
+ // 2. readonly-array erasure — `readonly T[]` sits outside the
15
+ // toolchain's sidecar type vocabulary today (type-level only);
16
+ // 3. Bytes-alias folding — a tabled scalar alias refuses, so staged
17
+ // copies spell Uint8Array directly and drop the alias;
18
+ // 4. duplicate-alias dedupe — the static SDK surface drops any alias
19
+ // another staged file declares, so one declaration site survives;
20
+ // 5. event-record storage — the staged SDK text/events modules spell
21
+ // their records as object-literal aliases (value storage), the
22
+ // form the host-constructed channel arms need.
23
+ //
24
+ // node stage_external_core.mjs --src <app src dir> --sdk <sdk dir>
25
+ // --static <compile-surface core.ts> --facade <core_facade.ts>
26
+ // --profile <core_profile.json> --out <stage dir>
27
+
28
+ import fs from "node:fs";
29
+ import path from "node:path";
30
+
31
+ function parseArgs(argv) {
32
+ const args = {};
33
+ for (let i = 2; i < argv.length; i += 2) {
34
+ const key = argv[i];
35
+ const value = argv[i + 1];
36
+ if (!key.startsWith("--") || value === undefined) {
37
+ console.error("usage: stage_external_core.mjs --src <dir> --sdk <dir> --static <file> --facade <file> --profile <file> --out <dir>");
38
+ process.exit(2);
39
+ }
40
+ args[key.slice(2)] = value;
41
+ }
42
+ for (const required of ["src", "sdk", "static", "facade", "profile", "out"]) {
43
+ if (!(required in args)) {
44
+ console.error(`stage_external_core.mjs: missing --${required}`);
45
+ process.exit(2);
46
+ }
47
+ }
48
+ return args;
49
+ }
50
+
51
+ /// Every .ts file under `dir`, as POSIX-relative paths.
52
+ function tsFilesUnder(dir) {
53
+ const out = [];
54
+ const walk = (sub) => {
55
+ for (const entry of fs.readdirSync(path.join(dir, sub), { withFileTypes: true })) {
56
+ const rel = sub === "" ? entry.name : `${sub}/${entry.name}`;
57
+ if (entry.isDirectory()) walk(rel);
58
+ else if (entry.isFile() && rel.endsWith(".ts") && !rel.endsWith(".d.ts")) out.push(rel);
59
+ }
60
+ };
61
+ walk("");
62
+ return out.sort();
63
+ }
64
+
65
+ /// Transform 1-3 on one author source, `rel` staged-relative (the SDK
66
+ /// specifiers resolve relative to the file's own directory).
67
+ function resolveSpecifiers(text, rel) {
68
+ const toSdk = (name) => {
69
+ const spelled = path.posix.relative(path.posix.dirname(rel), `sdk/${name}`);
70
+ return spelled.startsWith(".") ? spelled : `./${spelled}`;
71
+ };
72
+ return text
73
+ .replaceAll('"@native-sdk/core/text"', `"${toSdk("text.ts")}"`)
74
+ .replaceAll('"@native-sdk/core/events"', `"${toSdk("events.ts")}"`)
75
+ .replaceAll('"@native-sdk/core"', `"${toSdk("core.ts")}"`)
76
+ .replace(/readonly ([A-Za-z_][A-Za-z0-9_]*(?:<[A-Za-z_, ]*>)?)\[\]/g, "$1[]")
77
+ .replace(/(?<![A-Za-z0-9_])Bytes(?![A-Za-z0-9_])/g, "Uint8Array")
78
+ .split("\n")
79
+ .filter((line) => line !== "export type Uint8Array = Uint8Array;" && !/^ *type Uint8Array,$/.test(line))
80
+ .map((line) => line.replaceAll("type Uint8Array, ", "").replace(/, type Uint8Array([,}])/g, "$1"))
81
+ .join("\n");
82
+ }
83
+
84
+ /// The names of `export type X = ...` declarations in a staged file
85
+ /// (the dedupe set for the static SDK surface).
86
+ function exportedAliasNames(text) {
87
+ const names = [];
88
+ for (const line of text.split("\n")) {
89
+ const match = /^export type ([A-Za-z0-9_]+) =/.exec(line);
90
+ if (match) names.push(match[1]);
91
+ }
92
+ return names;
93
+ }
94
+
95
+ /// Transform 4: drop the static surface's copy of any alias another
96
+ /// staged file declares (single-line aliases and multi-line ones,
97
+ /// through the terminating `;`).
98
+ function dedupeAliases(text, dropNames) {
99
+ const drop = new Set(dropNames);
100
+ const out = [];
101
+ let skipping = false;
102
+ for (const line of text.split("\n")) {
103
+ if (skipping) {
104
+ if (/;[ \t]*$/.test(line)) skipping = false;
105
+ continue;
106
+ }
107
+ const match = /^export type ([A-Za-z0-9_]+) =/.exec(line);
108
+ if (match && drop.has(match[1])) {
109
+ if (!/;[ \t]*$/.test(line)) skipping = true;
110
+ continue;
111
+ }
112
+ out.push(line);
113
+ }
114
+ return out.join("\n");
115
+ }
116
+
117
+ const args = parseArgs(process.argv);
118
+ fs.rmSync(args.out, { recursive: true, force: true });
119
+ fs.mkdirSync(path.join(args.out, "sdk"), { recursive: true });
120
+
121
+ // Author sources, at their entry-relative (src-relative) paths.
122
+ const authorFiles = tsFilesUnder(args.src);
123
+ const aliasNames = [];
124
+ for (const rel of authorFiles) {
125
+ const staged = resolveSpecifiers(fs.readFileSync(path.join(args.src, rel), "utf8"), rel);
126
+ fs.mkdirSync(path.dirname(path.join(args.out, rel)), { recursive: true });
127
+ fs.writeFileSync(path.join(args.out, rel), staged);
128
+ aliasNames.push(...exportedAliasNames(staged));
129
+ }
130
+
131
+ // Transform 5: the staged SDK library modules spell their exported
132
+ // records as object-literal aliases (value storage).
133
+ for (const sdkFile of ["text.ts", "events.ts"]) {
134
+ const staged = fs
135
+ .readFileSync(path.join(args.sdk, sdkFile), "utf8")
136
+ .replace(/^export interface ([A-Za-z0-9_]+) \{/gm, "export type $1 = {");
137
+ fs.writeFileSync(path.join(args.out, "sdk", sdkFile), staged);
138
+ aliasNames.push(...exportedAliasNames(staged));
139
+ }
140
+
141
+ // The static @native-sdk/core restatement, deduped against every alias
142
+ // another staged file declares.
143
+ fs.writeFileSync(path.join(args.out, "sdk", "core.ts"), dedupeAliases(fs.readFileSync(args.static, "utf8"), aliasNames));
144
+
145
+ // The generated compile entry and its profile, staged under the names
146
+ // the profile's entry spelling expects.
147
+ fs.copyFileSync(args.facade, path.join(args.out, "core_facade.ts"));
148
+ fs.copyFileSync(args.profile, path.join(args.out, "profile.json"));