@native-sdk/cli 0.5.0 → 0.5.1

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.
@@ -22,6 +22,8 @@ pub const Error = error{
22
22
  MissingTsCore,
23
23
  MissingNode,
24
24
  MissingTranspiler,
25
+ BrokenToolchainInstall,
26
+ ToolchainVersionMismatch,
25
27
  CoreCheckFailed,
26
28
  DevHostFailed,
27
29
  };
@@ -68,7 +70,8 @@ fn nodeMissing() Error {
68
70
  std.debug.print(
69
71
  \\TypeScript app cores need node on PATH (the @native-sdk/core transpiler and the
70
72
  \\core dev-harness run under it; the binary you ship carries no JS runtime).
71
- \\Install Node.js 22+ - https://nodejs.org or `brew install node` - and re-run.
73
+ \\Install Node.js 22.15+ (on the 23 line: 23.5+) - https://nodejs.org or
74
+ \\`brew install node` - and re-run.
72
75
  \\
73
76
  , .{});
74
77
  return error.MissingNode;
@@ -99,18 +102,311 @@ fn tsRunnerPath(allocator: std.mem.Allocator, io: std.Io, framework_root: []cons
99
102
  return path;
100
103
  }
101
104
 
102
- fn requireInstalledTranspiler(allocator: std.mem.Allocator, io: std.Io, framework_root: []const u8) !void {
103
- const marker = try std.fs.path.join(allocator, &.{ framework_root, "packages", "core", "node_modules", "@typescript", "typescript6" });
104
- defer allocator.free(marker);
105
- const stat = std.Io.Dir.cwd().statFile(io, marker, .{}) catch {
106
- std.debug.print(
107
- \\the SDK's @native-sdk/core transpiler is missing its installed dependency.
108
- \\Fix with: cd {s}/packages/core && npm ci
109
- \\
110
- , .{framework_root});
111
- return error.MissingTranspiler;
105
+ /// The install command the repo-checkout teaching names. `--include=dev`
106
+ /// is correctness, not style: @typescript/typescript6 is packages/core's
107
+ /// devDependency, and a plain `npm ci` under ambient production npm config
108
+ /// (NODE_ENV=production, `omit=dev` in an npmrc) skips devDependencies
109
+ /// while exiting 0 — the named command would "succeed" and install
110
+ /// nothing.
111
+ pub const npm_ci_teaching_command = "npm ci --include=dev";
112
+
113
+ /// Whether the transpiler's TypeScript compiler (@typescript/old, the
114
+ /// exactly pinned npm alias of the real `typescript` package) RESOLVES
115
+ /// from the transpiler's own home — node's ancestor node_modules walk
116
+ /// from `<framework_root>/packages/core` upward — at the SDK's exactly
117
+ /// pinned VERSION.
118
+ ///
119
+ /// Validation tracks ONLY what runtime loads, from the same origin
120
+ /// runtime resolves from. Both runtime importers resolve the ALIAS from
121
+ /// inside packages/core: typed_ast.ts imports "@typescript/old" directly
122
+ /// (the one file that imports the checker provider), and
123
+ /// build/ts_run.mjs's load hook does `createRequire(targetPath)` against
124
+ /// a packages/core/src module. Node walking from
125
+ /// packages/core/src/<module>.ts would consult src's own node_modules
126
+ /// first, but src/ is our source directory and never carries one, so
127
+ /// packages/core is the walk origin that mirrors both — every layout
128
+ /// that works for node passes here and none that fails does:
129
+ /// - repo checkout: packages/core/node_modules (nearest, after `npm ci`)
130
+ /// - npm-installed CLI: the alias npm installed alongside the package
131
+ /// (nested under the CLI on global prefixes, hoisted to the project
132
+ /// root on local ones, pnpm's sibling node_modules)
133
+ ///
134
+ /// The @typescript/typescript6 wrapper is deliberately NOT probed:
135
+ /// nothing imports it at run time (typed_ast.ts bypasses its one-line
136
+ /// re-export on purpose — see the comment there), so holding the
137
+ /// wrapper's resolution — or the alias's version as seen FROM the
138
+ /// wrapper's origin — against the pin can only FALSE-REJECT healthy
139
+ /// trees. npm's own conflict shape hoists a consumer's conflicting
140
+ /// `@typescript/old` at the project root (where it wins the walk from a
141
+ /// hoisted wrapper) while our exact pin lands nested under the CLI — and
142
+ /// that nested copy is precisely what runtime loads from packages/core;
143
+ /// a consumer's own shadowing wrapper install must not sway the verdict
144
+ /// either. The wrapper stays a DECLARED dependency in both manifests
145
+ /// (continuity semantics, and it keeps npm shipping the package) — it is
146
+ /// just not what validation vouches for.
147
+ ///
148
+ /// Resolvable means the alias's manifest AND its entrypoint are present
149
+ /// and its installed version equals the pin — see
150
+ /// `aliasedCompilerVersion` for the probe details (node's error shape,
151
+ /// the mid-extraction slivers). The pin is read from the framework's own
152
+ /// packages/core/package.json (the `npm:typescript@X.Y.Z` alias suffix
153
+ /// in devDependencies — `parseAliasedCompilerPin`), never hardcoded, so
154
+ /// a version bump stays a one-file change; check-version-sync keeps that
155
+ /// manifest and the CLI's dependencies in lockstep. Kept in lockstep with
156
+ /// its deliberate twin for direct `zig build` runs,
157
+ /// build/app.zig's tsToolchainResolution.
158
+ pub const ToolchainResolution = union(enum) {
159
+ resolved,
160
+ unresolved,
161
+ /// The aliased compiler resolves, but at a version other than the
162
+ /// SDK's exact pin (a conflicting consumer-tree `@typescript/old`
163
+ /// shadowing ours). Both strings are allocator-owned.
164
+ version_mismatch: Mismatch,
165
+
166
+ pub const Mismatch = struct {
167
+ resolved: []const u8,
168
+ pinned: []const u8,
169
+
170
+ pub fn deinit(self: Mismatch, allocator: std.mem.Allocator) void {
171
+ allocator.free(self.resolved);
172
+ allocator.free(self.pinned);
173
+ }
174
+ };
175
+ };
176
+
177
+ fn transpilerResolution(allocator: std.mem.Allocator, io: std.Io, framework_root: []const u8) ToolchainResolution {
178
+ // The pin first: a framework tree whose packages/core/package.json is
179
+ // missing or pinless is not a tree this gate can vouch for (the file
180
+ // ships in every layout), so it concludes unresolved and the layout
181
+ // teachings act.
182
+ const pinned = pinnedCompilerVersion(allocator, io, framework_root) orelse return .unresolved;
183
+ const core_dir = std.fs.path.join(allocator, &.{ framework_root, "packages", "core" }) catch {
184
+ allocator.free(pinned);
185
+ return .unresolved;
112
186
  };
113
- _ = stat;
187
+ defer allocator.free(core_dir);
188
+ const resolved = aliasedCompilerVersion(allocator, io, core_dir) orelse {
189
+ allocator.free(pinned);
190
+ return .unresolved;
191
+ };
192
+ if (std.mem.eql(u8, resolved, pinned)) {
193
+ allocator.free(resolved);
194
+ allocator.free(pinned);
195
+ return .resolved;
196
+ }
197
+ return .{ .version_mismatch = .{ .resolved = resolved, .pinned = pinned } };
198
+ }
199
+
200
+ /// `transpilerResolution` folded to the yes/no most callers (and the
201
+ /// layout tests) want: a version mismatch is NOT a resolvable toolchain.
202
+ fn transpilerResolves(allocator: std.mem.Allocator, io: std.Io, framework_root: []const u8) bool {
203
+ switch (transpilerResolution(allocator, io, framework_root)) {
204
+ .resolved => return true,
205
+ .unresolved => return false,
206
+ .version_mismatch => |mismatch| {
207
+ mismatch.deinit(allocator);
208
+ return false;
209
+ },
210
+ }
211
+ }
212
+
213
+ /// How runtime's `import "@typescript/old"` resolves, by node's walk FROM
214
+ /// `origin_dir` upward: the nearest ancestor
215
+ /// `node_modules/@typescript/old` wins (skipping ancestors that are
216
+ /// themselves a node_modules directory, as node does). Callers pass
217
+ /// packages/core — the origin typed_ast.ts and ts_run.mjs resolve the
218
+ /// alias from (see `transpilerResolution`). The walk must be a real
219
+ /// ancestor walk, not a fixed-sibling probe: npm hoists the alias to the
220
+ /// install root on flat layouts (project-local installs) and nests it
221
+ /// under the CLI on version conflicts, and both are ancestor hits of
222
+ /// packages/core. Resolvable means the alias's manifest AND its
223
+ /// entrypoint — the alias is the real `typescript` package, whose
224
+ /// `"main"` is ./lib/typescript.js (no `"exports"`): node reads
225
+ /// `<candidate>/package.json` for the entrypoint and then loads that
226
+ /// file, so a bare directory — an interrupted `npm ci`, a pruned or
227
+ /// half-cleaned node_modules — is MODULE_NOT_FOUND at run time, and a
228
+ /// manifest WITHOUT its entrypoint is a real npm failure shape too
229
+ /// (extraction is not atomic; package.json rides first in the tarball,
230
+ /// so a mid-extraction crash lands exactly that sliver). Hardcoding
231
+ /// lib/typescript.js is safe: the alias is exactly pinned
232
+ /// (`npm:typescript@X.Y.Z` in both manifests plus the lockfile) and
233
+ /// drift-checked by check-version-sync, so the entrypoint cannot move
234
+ /// under us. The walk mirrors node's error shape: a candidate WITHOUT
235
+ /// package.json lets node keep walking upward, but a manifest whose
236
+ /// "main" fails to load THROWS rather than consulting a deeper ancestor,
237
+ /// so that candidate concludes unresolvable here too.
238
+ ///
239
+ /// Returns the resolved alias's installed VERSION (allocator-owned) so the
240
+ /// caller can hold it against the SDK's pin — resolving is not the whole
241
+ /// bar (see `transpilerResolution`). A resolvable-looking alias
242
+ /// whose manifest carries no version field returns null: every real npm
243
+ /// install writes one, so its absence is a hand-rolled or corrupt sliver,
244
+ /// not a compiler to vouch for.
245
+ fn aliasedCompilerVersion(allocator: std.mem.Allocator, io: std.Io, origin_dir: []const u8) ?[]const u8 {
246
+ var dir: []const u8 = origin_dir;
247
+ while (true) {
248
+ if (!std.mem.eql(u8, std.fs.path.basename(dir), "node_modules")) {
249
+ const manifest_path = std.fs.path.join(allocator, &.{ dir, "node_modules", "@typescript", "old", "package.json" }) catch return null;
250
+ defer allocator.free(manifest_path);
251
+ if (std.Io.Dir.cwd().statFile(io, manifest_path, .{})) |_| {
252
+ const entrypoint = std.fs.path.join(allocator, &.{ dir, "node_modules", "@typescript", "old", "lib", "typescript.js" }) catch return null;
253
+ defer allocator.free(entrypoint);
254
+ _ = std.Io.Dir.cwd().statFile(io, entrypoint, .{}) catch return null;
255
+ const manifest = std.Io.Dir.cwd().readFileAlloc(io, manifest_path, allocator, .limited(64 * 1024)) catch return null;
256
+ defer allocator.free(manifest);
257
+ const version = parsePackageVersion(manifest) orelse return null;
258
+ return allocator.dupe(u8, version) catch null;
259
+ } else |_| {}
260
+ }
261
+ dir = std.fs.path.dirname(dir) orelse return null;
262
+ }
263
+ }
264
+
265
+ /// Extract the exactly pinned compiler version from a packages/core
266
+ /// manifest: the `"@typescript/old": "npm:typescript@X.Y.Z"` devDependency
267
+ /// entry's version suffix. A targeted scan like `parsePackageVersion`, and
268
+ /// deliberately strict about the alias shape: anything but the exact
269
+ /// `npm:typescript@X.Y.Z` form is a manifest check-version-sync would
270
+ /// reject, so this parser vouches for nothing else.
271
+ pub fn parseAliasedCompilerPin(manifest_json: []const u8) ?[]const u8 {
272
+ const key = "\"@typescript/old\"";
273
+ const value_prefix = "npm:typescript@";
274
+ const key_at = std.mem.indexOf(u8, manifest_json, key) orelse return null;
275
+ var rest = manifest_json[key_at + key.len ..];
276
+ rest = std.mem.trimStart(u8, rest, " \t\r\n");
277
+ if (rest.len == 0 or rest[0] != ':') return null;
278
+ rest = std.mem.trimStart(u8, rest[1..], " \t\r\n");
279
+ if (rest.len == 0 or rest[0] != '"') return null;
280
+ rest = rest[1..];
281
+ const end = std.mem.indexOfScalar(u8, rest, '"') orelse return null;
282
+ const value = rest[0..end];
283
+ if (!std.mem.startsWith(u8, value, value_prefix)) return null;
284
+ const pin = value[value_prefix.len..];
285
+ // Exact X.Y.Z only, mirroring check-version-sync's pin-shape check: a
286
+ // range after the @ is not a pin, and comparing an installed version
287
+ // against one would "mismatch" every tree.
288
+ if (pin.len == 0) return null;
289
+ for (pin) |c| {
290
+ if (!std.ascii.isDigit(c) and c != '.') return null;
291
+ }
292
+ if (std.mem.count(u8, pin, ".") != 2) return null;
293
+ return pin;
294
+ }
295
+
296
+ /// The version the framework pins its aliased compiler to, read from its
297
+ /// own packages/core/package.json (allocator-owned), or null when the
298
+ /// manifest is missing or carries no exact alias pin.
299
+ fn pinnedCompilerVersion(allocator: std.mem.Allocator, io: std.Io, framework_root: []const u8) ?[]const u8 {
300
+ const path = std.fs.path.join(allocator, &.{ framework_root, "packages", "core", "package.json" }) catch return null;
301
+ defer allocator.free(path);
302
+ const manifest = std.Io.Dir.cwd().readFileAlloc(io, path, allocator, .limited(64 * 1024)) catch return null;
303
+ defer allocator.free(manifest);
304
+ const pin = parseAliasedCompilerPin(manifest) orelse return null;
305
+ return allocator.dupe(u8, pin) catch null;
306
+ }
307
+
308
+ /// The teaching for a REPO CHECKOUT whose toolchain resolves nowhere (a
309
+ /// clone whose `npm ci` hasn't happened yet, or whose node_modules was
310
+ /// deleted): name the one command, fail the verb cleanly. The gate never
311
+ /// runs npm itself — the tree stays exactly as the user left it.
312
+ /// Non-checkout layouts route to `toolchainInstallBroken` instead: naming
313
+ /// `npm ci` there would teach mutating an npm-owned tree.
314
+ fn transpilerDepsMissing(framework_root: []const u8) Error {
315
+ std.debug.print(
316
+ \\the @native-sdk/core transpiler's dependencies are not installed
317
+ \\(its TypeScript compiler, @typescript/old, resolves nowhere). Fix with:
318
+ \\ cd {s}/packages/core && {s}
319
+ \\
320
+ , .{ framework_root, npm_ci_teaching_command });
321
+ return error.MissingTranspiler;
322
+ }
323
+
324
+ /// The teaching for an npm-installed CLI whose toolchain resolves nowhere:
325
+ /// @typescript/old is a regular dependency of @native-sdk/cli, so npm
326
+ /// installs it in the same transaction as the package — its absence
327
+ /// means the install itself is broken (interrupted install, a pruned
328
+ /// node_modules, an overzealous cleaner). The fix is reinstalling the CLI,
329
+ /// never `npm ci` inside the installed package: that would silently mutate
330
+ /// npm-owned files and mask the breakage instead of curing it.
331
+ fn toolchainInstallBroken(framework_root: []const u8) Error {
332
+ std.debug.print(
333
+ \\the @native-sdk/cli install at
334
+ \\ {s}
335
+ \\is missing its TypeScript toolchain (@typescript/old). npm installs
336
+ \\that dependency in the same transaction as the CLI, so this install is
337
+ \\broken - reinstall @native-sdk/cli (e.g. re-run `npm install`, or
338
+ \\`npm install -g @native-sdk/cli` for a global install).
339
+ \\
340
+ , .{framework_root});
341
+ return error.BrokenToolchainInstall;
342
+ }
343
+
344
+ /// The teaching for a toolchain whose aliased compiler RESOLVES at the
345
+ /// wrong version: the walk from packages/core — runtime's own origin —
346
+ /// found an `@typescript/old` that is not the SDK's exact pin, so the
347
+ /// compiler the transpiler would actually load is one the SDK never
348
+ /// vouched for (a consumer's conflicting `@typescript/old` winning
349
+ /// nearest-wins over ours). Neither layout teaching fits (an install
350
+ /// command changes nothing), so this one names both versions and the
351
+ /// conflict instead.
352
+ fn compilerVersionMismatch(resolved: []const u8, pinned: []const u8) Error {
353
+ std.debug.print(
354
+ \\the transpiler's TypeScript compiler resolves at the wrong version:
355
+ \\@typescript/old resolves to typescript {s}, but the SDK pins npm:typescript@{s}.
356
+ \\Another package in this tree pins a conflicting @typescript/old - align it with
357
+ \\the SDK's pin (or remove it) and reinstall, so the SDK's exact pin is the copy
358
+ \\that resolves.
359
+ \\
360
+ , .{ resolved, pinned });
361
+ return error.ToolchainVersionMismatch;
362
+ }
363
+
364
+ fn dirExists(io: std.Io, path: []const u8) bool {
365
+ var cwd = std.Io.Dir.cwd();
366
+ var dir = cwd.openDir(io, path, .{}) catch return false;
367
+ dir.close(io);
368
+ return true;
369
+ }
370
+
371
+ /// The one gate every verb that reaches the transpiler runs (`native
372
+ /// check`, `native dev --core`, and the build-graph verbs before they
373
+ /// spawn `zig build`): the compiler must RESOLVE from packages/core — at
374
+ /// the exactly pinned version (see `transpilerResolution`). The
375
+ /// npm-installed CLI always resolves — @typescript/old is a regular
376
+ /// dependency installed in the same transaction — and a repo
377
+ /// checkout resolves after its one `npm ci --include=dev`. The gate NEVER
378
+ /// runs npm itself, on any layout: it only splits the teaching when
379
+ /// resolution fails. Which teaching is decided by `packages/core/test/`:
380
+ /// the published payload deliberately omits it (copy-framework.js stages
381
+ /// packages/core entry-by-entry without test/, and check-framework-sync.js
382
+ /// pins that exclusion; @native-sdk/core's own tarball is pinned to
383
+ /// `files: ["sdk"]` by test/package_manifest.test.ts) while every repo
384
+ /// checkout carries it. Checkouts are taught the install command;
385
+ /// non-checkout layouts are taught the reinstall — running `npm ci` there
386
+ /// would mutate an npm-owned tree.
387
+ pub fn ensureResolvedTranspiler(allocator: std.mem.Allocator, io: std.Io, framework_root: []const u8) !void {
388
+ switch (transpilerResolution(allocator, io, framework_root)) {
389
+ .resolved => return,
390
+ // The wrong-VERSION shape gets its own teaching on every layout:
391
+ // the layout split below prescribes installs, and no install fixes
392
+ // a conflicting consumer pin shadowing ours.
393
+ .version_mismatch => |mismatch| {
394
+ defer mismatch.deinit(allocator);
395
+ return compilerVersionMismatch(mismatch.resolved, mismatch.pinned);
396
+ },
397
+ .unresolved => {},
398
+ }
399
+ const test_dir = try std.fs.path.join(allocator, &.{ framework_root, "packages", "core", "test" });
400
+ defer allocator.free(test_dir);
401
+ if (!dirExists(io, test_dir)) return toolchainInstallBroken(framework_root);
402
+ // Teach the command against the RESOLVED absolute path: the checkout
403
+ // root may have been reached through a relative NATIVE_SDK_PATH or a
404
+ // symlinked binary, and the one command must paste-and-run from any
405
+ // cwd.
406
+ const resolved = std.Io.Dir.cwd().realPathFileAlloc(io, framework_root, allocator) catch
407
+ return transpilerDepsMissing(framework_root);
408
+ defer allocator.free(resolved);
409
+ return transpilerDepsMissing(resolved);
114
410
  }
115
411
 
116
412
  /// `native check` over a TypeScript core: run the transpiler (checker +
@@ -125,7 +421,7 @@ pub fn checkCore(allocator: std.mem.Allocator, io: std.Io, base_env: *std.proces
125
421
  defer allocator.free(cli_path);
126
422
  const runner_path = try tsRunnerPath(allocator, io, framework_root);
127
423
  defer allocator.free(runner_path);
128
- try requireInstalledTranspiler(allocator, io, framework_root);
424
+ try ensureResolvedTranspiler(allocator, io, framework_root);
129
425
  try std.Io.Dir.cwd().createDirPath(io, ".native/check");
130
426
 
131
427
  var child = std.process.spawn(io, .{
@@ -167,6 +463,9 @@ pub fn runDevHost(allocator: std.mem.Allocator, io: std.Io, framework_root: []co
167
463
  defer allocator.free(devhost_path);
168
464
  const runner_path = try tsRunnerPath(allocator, io, framework_root);
169
465
  defer allocator.free(runner_path);
466
+ // The harness runs the transpiler tier under node, so it needs the
467
+ // TypeScript toolchain to resolve exactly like check/build do.
468
+ try ensureResolvedTranspiler(allocator, io, framework_root);
170
469
 
171
470
  var argv: std.ArrayList([]const u8) = .empty;
172
471
  defer argv.deinit(allocator);
@@ -461,6 +760,320 @@ test "editor package: materialize, heal, and the npm-install handoff" {
461
760
  try std.testing.expect(buildgraph.fileExists(io, app ++ "/node_modules/@native-sdk/core/sdk/text.ts"));
462
761
  }
463
762
 
763
+ // --------------------------------------------- toolchain resolution
764
+ //
765
+ // The resolution gate never spawns anything — it is stats plus teachings —
766
+ // so the tests exercise it directly against fixture trees: the walk across
767
+ // every layout npm produces, each partial-extraction sliver the predicate
768
+ // must refuse, and the two teachings the layouts split into. "Nothing ran
769
+ // npm" is asserted structurally: the gate has no runner to inject, and the
770
+ // checkout fixtures prove their node_modules stayed exactly as staged.
771
+
772
+ test "the checkout teaching's npm command survives production npm config" {
773
+ // `--include=dev` must ride the named command: without it, ambient
774
+ // NODE_ENV=production (or omit=dev) makes `npm ci` skip the
775
+ // devDependency the install exists for — exit 0, nothing on disk.
776
+ try std.testing.expect(std.mem.indexOf(u8, npm_ci_teaching_command, "--include=dev") != null);
777
+ }
778
+
779
+ /// The minimal manifest of the @typescript/typescript6 WRAPPER a fake
780
+ /// COMPLETED install also lands (npm keeps installing it as a declared
781
+ /// dependency). The gate never probes it — validation tracks only the
782
+ /// aliased real compiler runtime loads — so tests land it exactly where
783
+ /// they model complete installs, to prove its presence or absence never
784
+ /// sways the verdict.
785
+ const fake_toolchain_manifest = "{ \"name\": \"@typescript/typescript6\", \"version\": \"0.0.2\", \"main\": \"./lib/typescript.js\" }";
786
+
787
+ /// The wrapper entrypoint bytes its manifest's "main" names.
788
+ const fake_toolchain_entrypoint = "// fake typescript.js";
789
+
790
+ /// The minimal manifest of the aliased REAL compiler (@typescript/old is
791
+ /// `npm:typescript@X.Y.Z`, so the installed manifest names `typescript`)
792
+ /// — the package the gate probes, because it is the one runtime imports.
793
+ /// The resolvability predicate (like node) requires BOTH the manifest and
794
+ /// its entrypoint; half-written trees — bare directories, manifests
795
+ /// without their entrypoint — are staged in the tests themselves. Its
796
+ /// version matches `fake_pin_manifest`'s exact pin, so a fully staged
797
+ /// fake compiler passes the version check too.
798
+ const fake_compiler_manifest = "{ \"name\": \"typescript\", \"version\": \"9.9.9\", \"main\": \"./lib/typescript.js\" }";
799
+
800
+ /// The same compiler at a version the fake SDK never pinned: the
801
+ /// conflicting-consumer-tree shape the version check exists to refuse.
802
+ const fake_conflicting_compiler_manifest = "{ \"name\": \"typescript\", \"version\": \"1.2.3\", \"main\": \"./lib/typescript.js\" }";
803
+
804
+ /// The aliased compiler's entrypoint bytes.
805
+ const fake_compiler_entrypoint = "// fake real typescript.js";
806
+
807
+ /// A fake framework's packages/core/package.json: the file the resolution
808
+ /// gate reads its exact compiler pin from (the `npm:typescript@X.Y.Z`
809
+ /// alias suffix), matching `fake_compiler_manifest`'s version.
810
+ const fake_pin_manifest = "{ \"name\": \"@native-sdk/core\", \"version\": \"0.0.9\", \"devDependencies\": { \"@typescript/old\": \"npm:typescript@9.9.9\" } }";
811
+
812
+ /// Land a fake framework root's own pin manifest (packages/core/package.json).
813
+ fn landFakePinManifest(io: std.Io, framework_root: []const u8) bool {
814
+ var buffer: [512]u8 = undefined;
815
+ const dir = std.fmt.bufPrint(&buffer, "{s}/packages/core", .{framework_root}) catch return false;
816
+ var cwd = std.Io.Dir.cwd();
817
+ cwd.createDirPath(io, dir) catch return false;
818
+ var manifest_buffer: [512]u8 = undefined;
819
+ const manifest = std.fmt.bufPrint(&manifest_buffer, "{s}/package.json", .{dir}) catch return false;
820
+ cwd.writeFile(io, .{ .sub_path = manifest, .data = fake_pin_manifest }) catch return false;
821
+ return true;
822
+ }
823
+
824
+ /// Land one fake-but-complete package (lib/ directory, manifest,
825
+ /// lib/typescript.js entrypoint) at `dir`'s
826
+ /// node_modules/@typescript/<package_name>.
827
+ fn landFakePackage(io: std.Io, dir: []const u8, comptime package_name: []const u8, manifest_data: []const u8, entrypoint_data: []const u8) bool {
828
+ var buffer: [512]u8 = undefined;
829
+ const package = std.fmt.bufPrint(&buffer, "{s}/node_modules/@typescript/" ++ package_name, .{dir}) catch return false;
830
+ var cwd = std.Io.Dir.cwd();
831
+ var lib_buffer: [512]u8 = undefined;
832
+ const lib = std.fmt.bufPrint(&lib_buffer, "{s}/lib", .{package}) catch return false;
833
+ cwd.createDirPath(io, lib) catch return false;
834
+ var manifest_buffer: [512]u8 = undefined;
835
+ const manifest = std.fmt.bufPrint(&manifest_buffer, "{s}/package.json", .{package}) catch return false;
836
+ cwd.writeFile(io, .{ .sub_path = manifest, .data = manifest_data }) catch return false;
837
+ var entry_buffer: [512]u8 = undefined;
838
+ const entrypoint = std.fmt.bufPrint(&entry_buffer, "{s}/typescript.js", .{lib}) catch return false;
839
+ cwd.writeFile(io, .{ .sub_path = entrypoint, .data = entrypoint_data }) catch return false;
840
+ return true;
841
+ }
842
+
843
+ /// Land a fake COMPLETE install under `dir`'s node_modules: the wrapper
844
+ /// (still a declared dependency, so npm always lands it) AND the aliased
845
+ /// real compiler, as npm's dedupe lands them — siblings under one
846
+ /// node_modules. Only the compiler decides resolution; the wrapper rides
847
+ /// along so complete-install fixtures stay shaped like real trees.
848
+ fn landFakeToolchain(io: std.Io, dir: []const u8) bool {
849
+ if (!landFakePackage(io, dir, "typescript6", fake_toolchain_manifest, fake_toolchain_entrypoint)) return false;
850
+ return landFakePackage(io, dir, "old", fake_compiler_manifest, fake_compiler_entrypoint);
851
+ }
852
+
853
+ test "toolchain resolution: the nested install (repo checkout) resolves, partial extractions do not" {
854
+ const allocator = std.testing.allocator;
855
+ const io = std.testing.io;
856
+ var cwd = std.Io.Dir.cwd();
857
+ const root = ".zig-cache/test-ts-toolchain-nested";
858
+ const sdk = root ++ "/sdk-checkout";
859
+ cwd.deleteTree(io, root) catch {};
860
+ defer cwd.deleteTree(io, root) catch {};
861
+
862
+ try cwd.createDirPath(io, sdk ++ "/packages/core");
863
+ try std.testing.expect(!transpilerResolves(allocator, io, sdk));
864
+ // The gate reads its exact compiler pin from the framework's own
865
+ // packages/core/package.json; every real layout ships it.
866
+ try std.testing.expect(landFakePinManifest(io, sdk));
867
+ try std.testing.expect(!transpilerResolves(allocator, io, sdk));
868
+ // The COMPLETE wrapper — manifest, entrypoint, the works — changes
869
+ // nothing: nothing imports @typescript/typescript6 at run time, so
870
+ // validation does not probe it. Only the aliased real compiler
871
+ // counts.
872
+ try std.testing.expect(landFakePackage(io, sdk ++ "/packages/core", "typescript6", fake_toolchain_manifest, fake_toolchain_entrypoint));
873
+ try std.testing.expect(!transpilerResolves(allocator, io, sdk));
874
+ // A bare compiler DIRECTORY (an interrupted extraction, a pruned
875
+ // install) is not resolvable: node needs the package's manifest.
876
+ try cwd.createDirPath(io, sdk ++ "/packages/core/node_modules/@typescript/old");
877
+ try std.testing.expect(!transpilerResolves(allocator, io, sdk));
878
+ // A manifest WITHOUT its entrypoint is the mid-extraction crash shape
879
+ // (package.json rides first in the tarball): still not resolvable —
880
+ // node would read "main" and fail loading it.
881
+ try cwd.writeFile(io, .{ .sub_path = sdk ++ "/packages/core/node_modules/@typescript/old/package.json", .data = fake_compiler_manifest });
882
+ try std.testing.expect(!transpilerResolves(allocator, io, sdk));
883
+ try cwd.createDirPath(io, sdk ++ "/packages/core/node_modules/@typescript/old/lib");
884
+ try cwd.writeFile(io, .{ .sub_path = sdk ++ "/packages/core/node_modules/@typescript/old/lib/typescript.js", .data = fake_compiler_entrypoint });
885
+ try std.testing.expect(transpilerResolves(allocator, io, sdk));
886
+ }
887
+
888
+ test "toolchain resolution: the hoisted install (npm project layout) resolves by ancestor walk" {
889
+ const allocator = std.testing.allocator;
890
+ const io = std.testing.io;
891
+ var cwd = std.Io.Dir.cwd();
892
+ const root = ".zig-cache/test-ts-toolchain-hoisted";
893
+ // The npm local-install shape: the CLI package and its dependencies
894
+ // are SIBLINGS under the project's node_modules — nothing sits inside
895
+ // the CLI package itself.
896
+ const sdk = root ++ "/proj/node_modules/@native-sdk/cli";
897
+ cwd.deleteTree(io, root) catch {};
898
+ defer cwd.deleteTree(io, root) catch {};
899
+
900
+ try cwd.createDirPath(io, sdk ++ "/packages/core");
901
+ try std.testing.expect(landFakePinManifest(io, sdk));
902
+ try std.testing.expect(!transpilerResolves(allocator, io, sdk));
903
+ // The hoisted wrapper — even complete — is not what validation
904
+ // tracks: nothing imports it at run time.
905
+ try std.testing.expect(landFakePackage(io, root ++ "/proj", "typescript6", fake_toolchain_manifest, fake_toolchain_entrypoint));
906
+ try std.testing.expect(!transpilerResolves(allocator, io, sdk));
907
+ // A bare compiler directory on the hoisted layout is a broken
908
+ // install, not a resolvable compiler — the manifest is the bar here
909
+ // too...
910
+ try cwd.createDirPath(io, root ++ "/proj/node_modules/@typescript/old");
911
+ try std.testing.expect(!transpilerResolves(allocator, io, sdk));
912
+ // ...and a manifest without its entrypoint (the mid-extraction crash
913
+ // shape) is still broken, not resolvable.
914
+ try cwd.writeFile(io, .{ .sub_path = root ++ "/proj/node_modules/@typescript/old/package.json", .data = fake_compiler_manifest });
915
+ try std.testing.expect(!transpilerResolves(allocator, io, sdk));
916
+ // npm hoists @typescript/old to the install root on flat layouts — an
917
+ // ANCESTOR of the CLI's packages/core, not a fixed sibling: the walk
918
+ // from the runtime origin must reach it.
919
+ try cwd.createDirPath(io, root ++ "/proj/node_modules/@typescript/old/lib");
920
+ try cwd.writeFile(io, .{ .sub_path = root ++ "/proj/node_modules/@typescript/old/lib/typescript.js", .data = fake_compiler_entrypoint });
921
+ try std.testing.expect(transpilerResolves(allocator, io, sdk));
922
+
923
+ // And the global-prefix shape: the compiler nested inside the CLI
924
+ // package's own node_modules (npm -g) resolves as a nearer ancestor
925
+ // of packages/core — with nothing hoisted at the install root at all.
926
+ cwd.deleteTree(io, root ++ "/proj/node_modules/@typescript/old") catch {};
927
+ try std.testing.expect(!transpilerResolves(allocator, io, sdk));
928
+ try std.testing.expect(landFakePackage(io, sdk, "old", fake_compiler_manifest, fake_compiler_entrypoint));
929
+ try std.testing.expect(transpilerResolves(allocator, io, sdk));
930
+ }
931
+
932
+ test "toolchain gate: a resolvable tree passes silently, a checkout teaches the one npm ci and runs nothing" {
933
+ const allocator = std.testing.allocator;
934
+ const io = std.testing.io;
935
+ var cwd = std.Io.Dir.cwd();
936
+ const root = ".zig-cache/test-ts-toolchain-gate";
937
+ const sdk = root ++ "/sdk-checkout";
938
+ cwd.deleteTree(io, root) catch {};
939
+ defer cwd.deleteTree(io, root) catch {};
940
+ // test/ marks the layout a repo checkout (the published payload
941
+ // deliberately omits it): the teaching names `npm ci --include=dev`.
942
+ try cwd.createDirPath(io, sdk ++ "/packages/core/test");
943
+ try std.testing.expect(landFakePinManifest(io, sdk));
944
+
945
+ // An uninstalled checkout: the teaching error — and NOTHING was
946
+ // spawned, structurally: the gate has no installer to call, and the
947
+ // tree it inspected stayed exactly as staged (no node_modules
948
+ // appeared).
949
+ try std.testing.expectError(error.MissingTranspiler, ensureResolvedTranspiler(allocator, io, sdk));
950
+ try std.testing.expect(!dirExists(io, sdk ++ "/packages/core/node_modules"));
951
+
952
+ // A partial extraction (the wrapper landed, the aliased compiler —
953
+ // the package runtime actually imports — did not) is taught the same
954
+ // way, and left byte-for-byte in place, never "repaired".
955
+ try std.testing.expect(landFakePackage(io, sdk ++ "/packages/core", "typescript6", fake_toolchain_manifest, fake_toolchain_entrypoint));
956
+ try std.testing.expectError(error.MissingTranspiler, ensureResolvedTranspiler(allocator, io, sdk));
957
+ try std.testing.expect(!dirExists(io, sdk ++ "/packages/core/node_modules/@typescript/old"));
958
+
959
+ // A complete install passes silently.
960
+ try std.testing.expect(landFakePackage(io, sdk ++ "/packages/core", "old", fake_compiler_manifest, fake_compiler_entrypoint));
961
+ try ensureResolvedTranspiler(allocator, io, sdk);
962
+ }
963
+
964
+ test "toolchain gate: an npm-payload layout teaches the reinstall, never npm ci" {
965
+ const allocator = std.testing.allocator;
966
+ const io = std.testing.io;
967
+ var cwd = std.Io.Dir.cwd();
968
+ const root = ".zig-cache/test-ts-toolchain-npm-payload";
969
+ // The npm-installed CLI's shape: packages/core carries the lockfile
970
+ // (the payload deliberately ships it) but NO test/ directory — the
971
+ // staging excludes it, and that absence is the layout signal.
972
+ const sdk = root ++ "/proj/node_modules/@native-sdk/cli";
973
+ cwd.deleteTree(io, root) catch {};
974
+ defer cwd.deleteTree(io, root) catch {};
975
+ try cwd.createDirPath(io, sdk ++ "/packages/core");
976
+ try std.testing.expect(landFakePinManifest(io, sdk));
977
+ try cwd.writeFile(io, .{ .sub_path = sdk ++ "/packages/core/package-lock.json", .data = "{ \"lockfileVersion\": 3 }" });
978
+
979
+ // A missing toolchain here is a broken install: the reinstall
980
+ // teaching, and the npm-owned tree untouched (no node_modules
981
+ // appeared anywhere the gate looked).
982
+ try std.testing.expectError(error.BrokenToolchainInstall, ensureResolvedTranspiler(allocator, io, sdk));
983
+ try std.testing.expect(!dirExists(io, sdk ++ "/packages/core/node_modules"));
984
+
985
+ // The same verdict for each partial-extraction sliver of the
986
+ // compiler: a hoisted bare directory, then its
987
+ // manifest-without-entrypoint completion — both broken installs to
988
+ // teach, never trees to repair.
989
+ try cwd.createDirPath(io, root ++ "/proj/node_modules/@typescript/old");
990
+ try std.testing.expectError(error.BrokenToolchainInstall, ensureResolvedTranspiler(allocator, io, sdk));
991
+ try cwd.writeFile(io, .{ .sub_path = root ++ "/proj/node_modules/@typescript/old/package.json", .data = fake_compiler_manifest });
992
+ try std.testing.expectError(error.BrokenToolchainInstall, ensureResolvedTranspiler(allocator, io, sdk));
993
+
994
+ // A complete hoisted install (compiler plus the wrapper npm still
995
+ // ships) passes silently.
996
+ try std.testing.expect(landFakeToolchain(io, root ++ "/proj"));
997
+ try ensureResolvedTranspiler(allocator, io, sdk);
998
+ }
999
+
1000
+ test "aliased compiler pin extraction is strict about the npm:typescript@X.Y.Z shape" {
1001
+ try std.testing.expectEqualStrings("9.9.9", parseAliasedCompilerPin(fake_pin_manifest).?);
1002
+ try std.testing.expectEqualStrings("6.0.3", parseAliasedCompilerPin(
1003
+ \\{
1004
+ \\ "devDependencies": {
1005
+ \\ "@typescript/old": "npm:typescript@6.0.3",
1006
+ \\ "@typescript/typescript6": "6.0.2"
1007
+ \\ }
1008
+ \\}
1009
+ ).?);
1010
+ // Ranges, bare versions, and empty pins are shapes check-version-sync
1011
+ // rejects; the gate must not vouch for them either.
1012
+ try std.testing.expect(parseAliasedCompilerPin("{ \"@typescript/old\": \"npm:typescript@^6\" }") == null);
1013
+ try std.testing.expect(parseAliasedCompilerPin("{ \"@typescript/old\": \"npm:typescript@6.0\" }") == null);
1014
+ try std.testing.expect(parseAliasedCompilerPin("{ \"@typescript/old\": \"6.0.3\" }") == null);
1015
+ try std.testing.expect(parseAliasedCompilerPin("{ \"@typescript/old\": \"npm:typescript@\" }") == null);
1016
+ try std.testing.expect(parseAliasedCompilerPin("{}") == null);
1017
+ }
1018
+
1019
+ test "toolchain version pin: a compiler resolved at the wrong version teaches the mismatch, on both layouts" {
1020
+ const allocator = std.testing.allocator;
1021
+ const io = std.testing.io;
1022
+ var cwd = std.Io.Dir.cwd();
1023
+ const root = ".zig-cache/test-ts-toolchain-version";
1024
+ cwd.deleteTree(io, root) catch {};
1025
+ defer cwd.deleteTree(io, root) catch {};
1026
+
1027
+ // Checkout layout: a complete nested install whose aliased compiler is
1028
+ // NOT the pinned version (pin 9.9.9, installed 1.2.3). Resolvability
1029
+ // alone would pass this tree; the version check must refuse it with
1030
+ // the mismatch teaching, not the npm-ci teaching — no install command
1031
+ // fixes a resolved-but-wrong compiler.
1032
+ const checkout = root ++ "/sdk-checkout";
1033
+ try cwd.createDirPath(io, checkout ++ "/packages/core/test");
1034
+ try std.testing.expect(landFakePinManifest(io, checkout));
1035
+ try std.testing.expect(landFakePackage(io, checkout ++ "/packages/core", "typescript6", fake_toolchain_manifest, fake_toolchain_entrypoint));
1036
+ try std.testing.expect(landFakePackage(io, checkout ++ "/packages/core", "old", fake_conflicting_compiler_manifest, fake_compiler_entrypoint));
1037
+ try std.testing.expect(!transpilerResolves(allocator, io, checkout));
1038
+ try std.testing.expectError(error.ToolchainVersionMismatch, ensureResolvedTranspiler(allocator, io, checkout));
1039
+
1040
+ // npm layout, the conflict shape npm itself produces: the consumer's
1041
+ // own conflicting @typescript/old hoisted at the project root, while
1042
+ // the SDK's exact pin lands nested under the CLI. Runtime resolves
1043
+ // the alias from packages/core and loads the NESTED exact pin — so
1044
+ // the gate, walking from the same origin, must PASS this healthy
1045
+ // tree. (Holding the hoisted wrapper's origin against the pin here
1046
+ // was the false rejection the walk origin exists to prevent.)
1047
+ const cli = root ++ "/proj/node_modules/@native-sdk/cli";
1048
+ try cwd.createDirPath(io, cli ++ "/packages/core");
1049
+ try std.testing.expect(landFakePinManifest(io, cli));
1050
+ try cwd.writeFile(io, .{ .sub_path = cli ++ "/packages/core/package-lock.json", .data = "{ \"lockfileVersion\": 3 }" });
1051
+ try std.testing.expect(landFakePackage(io, root ++ "/proj", "typescript6", fake_toolchain_manifest, fake_toolchain_entrypoint));
1052
+ try std.testing.expect(landFakePackage(io, root ++ "/proj", "old", fake_conflicting_compiler_manifest, fake_compiler_entrypoint));
1053
+ try std.testing.expect(landFakePackage(io, cli, "old", fake_compiler_manifest, fake_compiler_entrypoint));
1054
+ try std.testing.expect(transpilerResolves(allocator, io, cli));
1055
+ try ensureResolvedTranspiler(allocator, io, cli);
1056
+
1057
+ // A consumer's own shadowing WRAPPER changes nothing either way:
1058
+ // validation tracks only the compiler runtime loads, so the verdict
1059
+ // is identical with the hoisted wrapper deleted outright.
1060
+ try cwd.deleteTree(io, root ++ "/proj/node_modules/@typescript/typescript6");
1061
+ try ensureResolvedTranspiler(allocator, io, cli);
1062
+
1063
+ // A genuinely wrong compiler AT the packages/core origin still
1064
+ // teaches the mismatch: with the CLI's nested exact pin gone, the
1065
+ // conflicting hoisted copy is what the walk from packages/core — and
1066
+ // node at run time — resolves, and no install command fixes a
1067
+ // resolved-but-wrong compiler.
1068
+ try cwd.deleteTree(io, cli ++ "/node_modules/@typescript/old");
1069
+ try std.testing.expect(!transpilerResolves(allocator, io, cli));
1070
+ try std.testing.expectError(error.ToolchainVersionMismatch, ensureResolvedTranspiler(allocator, io, cli));
1071
+
1072
+ // Align the hoisted copy with the pin and the same tree passes.
1073
+ try cwd.writeFile(io, .{ .sub_path = root ++ "/proj/node_modules/@typescript/old/package.json", .data = fake_compiler_manifest });
1074
+ try ensureResolvedTranspiler(allocator, io, cli);
1075
+ }
1076
+
464
1077
  // The copy the CLI materializes IS the future published artifact: the
465
1078
  // bundled manifest must carry the exports/files shape editors resolve
466
1079
  // through (pinned in full by packages/core/test/package_manifest.test.ts;