@native-sdk/cli 0.8.3 → 0.9.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 (188) hide show
  1. package/build/app.zig +905 -61
  2. package/build.zig +674 -373
  3. package/build.zig.zon +1 -0
  4. package/native-sdk.d.ts +6 -0
  5. package/package.json +12 -11
  6. package/packages/core/compile-surface/core.ts +455 -3
  7. package/packages/core/package-lock.json +11 -11
  8. package/packages/core/package.json +2 -2
  9. package/packages/core/scripts/compiler_typecheck.mjs +116 -15
  10. package/packages/core/scripts/gen_service_surface.mjs +268 -0
  11. package/packages/core/scripts/npm_static_spike.mjs +64 -0
  12. package/packages/core/scripts/run_external_core_compiler.mjs +77 -6
  13. package/packages/core/scripts/run_external_service_compiler.mjs +240 -0
  14. package/packages/core/scripts/stage_external_core.mjs +9 -1
  15. package/packages/core/scripts/stage_external_services.mjs +172 -0
  16. package/packages/core/scripts/surface_manifest_diff.mjs +253 -0
  17. package/packages/core/scripts/vendor_service_packages.mjs +189 -0
  18. package/packages/core/sdk/core.d.ts +214 -2
  19. package/packages/core/sdk/core.ts +715 -42
  20. package/packages/core/sdk/events.d.ts +50 -0
  21. package/packages/core/sdk/events.ts +75 -0
  22. package/packages/core/src/checker.ts +528 -15
  23. package/packages/core/src/cli.ts +143 -3
  24. package/packages/core/src/contract.ts +26 -5
  25. package/packages/core/src/devhost.ts +1849 -18
  26. package/packages/core/src/devhost_journal.mjs +181 -0
  27. package/packages/core/src/devhost_resolver.mjs +17 -1
  28. package/packages/core/src/devhost_service_worker.mjs +90 -0
  29. package/packages/core/src/diagnostics.ts +84 -18
  30. package/packages/core/src/frontend.ts +204 -34
  31. package/packages/core/src/modules.ts +129 -80
  32. package/packages/core/src/service_contract.ts +597 -0
  33. package/packages/core/src/sqlite_cli.ts +93 -0
  34. package/packages/core/src/sqlite_codegen.ts +806 -0
  35. package/packages/core/src/sqlite_runtime_policy.ts +364 -0
  36. package/packages/core/src/typed_ast.ts +36 -8
  37. package/skill-data/core/SKILL.md +4 -2
  38. package/skill-data/core/references/project-anatomy.md +3 -2
  39. package/skill-data/core/references/web-engines-packaging-debugging.md +3 -1
  40. package/skill-data/native-ui/SKILL.md +55 -8
  41. package/skill-data/ts-core/SKILL.md +92 -40
  42. package/skill-data/ts-services/SKILL.md +126 -0
  43. package/skill-data/ts-services/references/service-surface.md +603 -0
  44. package/skill-data/zig/SKILL.md +1 -1
  45. package/skills/native-sdk/SKILL.md +1 -1
  46. package/src/app_runner/no_migrations.zig +3 -0
  47. package/src/app_runner/no_services.zig +20 -0
  48. package/src/app_runner/root.zig +104 -4
  49. package/src/app_runner/ts_core_main.zig +268 -4
  50. package/src/automation/snapshot.zig +23 -5
  51. package/src/embed/app_exports.zig +11 -1
  52. package/src/embed/c_api.zig +48 -2
  53. package/src/embed/conversions.zig +4 -5
  54. package/src/embed/host.zig +115 -1
  55. package/src/embed/root.zig +7 -0
  56. package/src/embed/tests.zig +213 -0
  57. package/src/embed/types.zig +51 -0
  58. package/src/embed/ui_host.zig +121 -5
  59. package/src/platform/android/NativeSdkActivity.java +131 -0
  60. package/src/platform/android/android_host.c +182 -1
  61. package/src/platform/android/native_sdk_app.h +17 -0
  62. package/src/platform/ios/native_sdk_app.h +17 -0
  63. package/src/platform/ios/uikit_host.m +115 -0
  64. package/src/platform/linux/cef_host.cpp +1 -1
  65. package/src/platform/linux/gtk_host.c +89 -17
  66. package/src/platform/linux/gtk_host.h +3 -0
  67. package/src/platform/linux/root.zig +41 -18
  68. package/src/platform/macos/appkit_host.h +26 -3
  69. package/src/platform/macos/appkit_host.m +1051 -129
  70. package/src/platform/macos/capture_info_plist.c +25 -0
  71. package/src/platform/macos/cef_host.mm +270 -36
  72. package/src/platform/macos/root.zig +312 -34
  73. package/src/platform/null_platform.zig +281 -19
  74. package/src/platform/null_platform_tests.zig +74 -0
  75. package/src/platform/root.zig +16 -0
  76. package/src/platform/types.zig +279 -15
  77. package/src/platform/windows/root.zig +243 -21
  78. package/src/platform/windows/webview2_host.cpp +464 -46
  79. package/src/primitives/app_manifest/comptime_scene.zig +2 -0
  80. package/src/primitives/app_manifest/root.zig +4 -0
  81. package/src/primitives/app_manifest/tests.zig +3 -0
  82. package/src/primitives/app_manifest/types.zig +34 -0
  83. package/src/primitives/app_manifest/validation.zig +19 -1
  84. package/src/primitives/canvas/code_tests.zig +9 -9
  85. package/src/primitives/canvas/events.zig +12 -11
  86. package/src/primitives/canvas/frame.zig +44 -9
  87. package/src/primitives/canvas/icons/mic.svg +1 -0
  88. package/src/primitives/canvas/icons.zig +2 -0
  89. package/src/primitives/canvas/root.zig +8 -0
  90. package/src/primitives/canvas/text_span_tests.zig +39 -0
  91. package/src/primitives/canvas/ui.zig +23 -4
  92. package/src/primitives/canvas/ui_markup.zig +15 -0
  93. package/src/primitives/canvas/ui_markup_compiled.zig +9 -0
  94. package/src/primitives/canvas/ui_markup_compiled_tests.zig +1 -1
  95. package/src/primitives/canvas/ui_markup_tests.zig +5 -0
  96. package/src/primitives/canvas/ui_markup_view.zig +9 -0
  97. package/src/primitives/canvas/ui_markup_view_tests.zig +9 -6
  98. package/src/primitives/canvas/ui_schema.zig +19 -10
  99. package/src/primitives/canvas/ui_schema_tests.zig +5 -3
  100. package/src/primitives/canvas/ui_tests.zig +18 -4
  101. package/src/primitives/canvas/widget_invalidation.zig +9 -2
  102. package/src/primitives/canvas/widget_render.zig +296 -114
  103. package/src/primitives/canvas/widget_runtime_tests.zig +133 -0
  104. package/src/primitives/canvas/widget_text_input.zig +10 -10
  105. package/src/primitives/canvas/widget_tree.zig +1 -1
  106. package/src/primitives/canvas/widgets.zig +29 -5
  107. package/src/root.zig +56 -0
  108. package/src/runtime/api.zig +11 -0
  109. package/src/runtime/automation_snapshot.zig +4 -0
  110. package/src/runtime/automation_widget_dispatch.zig +1 -0
  111. package/src/runtime/bridge_payload.zig +2 -0
  112. package/src/runtime/bridge_permission_tests.zig +23 -2
  113. package/src/runtime/bridge_responses.zig +3 -1
  114. package/src/runtime/canvas_frame.zig +31 -13
  115. package/src/runtime/canvas_frame_animation_tests.zig +4 -0
  116. package/src/runtime/canvas_frame_invalidation_tests.zig +35 -10
  117. package/src/runtime/canvas_widget_anchored_tests.zig +83 -0
  118. package/src/runtime/canvas_widget_events.zig +69 -24
  119. package/src/runtime/canvas_widget_runtime.zig +101 -6
  120. package/src/runtime/canvas_widget_scroll_driver_tests.zig +47 -4
  121. package/src/runtime/canvas_widget_scroll_drivers.zig +3 -3
  122. package/src/runtime/canvas_widget_semantics_tests.zig +2 -0
  123. package/src/runtime/canvas_widget_split_tree_tests.zig +228 -0
  124. package/src/runtime/canvas_widget_state.zig +6 -1
  125. package/src/runtime/canvas_widget_text_tests.zig +112 -3
  126. package/src/runtime/clock.zig +13 -1
  127. package/src/runtime/core.zig +133 -1
  128. package/src/runtime/credentials_store.zig +115 -0
  129. package/src/runtime/effects.zig +2568 -75
  130. package/src/runtime/effects_audio_capture_tests.zig +251 -0
  131. package/src/runtime/effects_credentials_tests.zig +332 -0
  132. package/src/runtime/effects_host_tests.zig +208 -1
  133. package/src/runtime/effects_relational_tests.zig +314 -0
  134. package/src/runtime/effects_store_tests.zig +211 -0
  135. package/src/runtime/flow.zig +14 -1
  136. package/src/runtime/gpu_surface_events.zig +6 -1
  137. package/src/runtime/native_command_event_tests.zig +42 -0
  138. package/src/runtime/persist_store.zig +666 -0
  139. package/src/runtime/record_store.zig +788 -0
  140. package/src/runtime/relational_store.zig +854 -0
  141. package/src/runtime/root.zig +52 -0
  142. package/src/runtime/runtime_event_tests.zig +70 -0
  143. package/src/runtime/service_host.zig +711 -0
  144. package/src/runtime/service_pool.zig +1314 -0
  145. package/src/runtime/session_blobs.zig +1 -1
  146. package/src/runtime/session_journal.zig +102 -0
  147. package/src/runtime/session_record.zig +177 -0
  148. package/src/runtime/session_replay.zig +109 -4
  149. package/src/runtime/shell_layout.zig +1 -0
  150. package/src/runtime/shell_layout_tests.zig +120 -0
  151. package/src/runtime/sqlite_engine.zig +474 -0
  152. package/src/runtime/state.zig +6 -0
  153. package/src/runtime/system_services.zig +49 -10
  154. package/src/runtime/tests.zig +5 -0
  155. package/src/runtime/ts_core_host.zig +1189 -118
  156. package/src/runtime/ts_core_host_tests.zig +638 -11
  157. package/src/runtime/ts_ui_app.zig +537 -1
  158. package/src/runtime/ui_app.zig +160 -19
  159. package/src/runtime/ui_app_tests.zig +203 -5
  160. package/src/runtime/validation.zig +22 -0
  161. package/src/runtime/view.zig +11 -0
  162. package/src/runtime/view_widget_scroll.zig +56 -5
  163. package/src/runtime/view_widget_text.zig +24 -5
  164. package/src/runtime/view_widget_tree.zig +1 -1
  165. package/src/runtime/window_storage.zig +1 -0
  166. package/src/runtime/window_view_runtime.zig +2 -3
  167. package/src/runtime/window_views.zig +19 -0
  168. package/src/tooling/android.zig +21 -16
  169. package/src/tooling/db.zig +160 -0
  170. package/src/tooling/ios.zig +7 -1
  171. package/src/tooling/manifest.zig +1248 -2
  172. package/src/tooling/package.zig +953 -6
  173. package/src/tooling/raw_manifest.zig +65 -0
  174. package/src/tooling/root.zig +1 -0
  175. package/src/tooling/templates.zig +216 -4
  176. package/src/tooling/ts_core.zig +283 -17
  177. package/src/tooling/verbs.zig +7 -0
  178. package/third_party/sqlite/README.md +13 -0
  179. package/third_party/sqlite/sqlite3.c +269649 -0
  180. package/third_party/sqlite/sqlite3.h +14349 -0
  181. package/tools/corewire/core_abi.zig +14 -2
  182. package/tools/corewire/emit.zig +98 -29
  183. package/tools/corewire/emit_facade.zig +414 -23
  184. package/tools/corewire/emit_profile.zig +6 -2
  185. package/tools/corewire/emit_service.zig +924 -0
  186. package/tools/corewire/main.zig +122 -0
  187. package/tools/corewire/service_contract.zig +250 -0
  188. package/tools/corewire/sidecar.zig +26 -15
@@ -12,6 +12,7 @@
12
12
  // printed verbatim, are the teaching. Exit 2: toolchain missing/broken.
13
13
  import { spawnSync } from "node:child_process";
14
14
  import fs from "node:fs";
15
+ import os from "node:os";
15
16
  import path from "node:path";
16
17
  import { createRequire } from "node:module";
17
18
  import { fileURLToPath } from "node:url";
@@ -21,6 +22,10 @@ if (!entry) {
21
22
  console.error("usage: compiler_typecheck.mjs <entry.ts>");
22
23
  process.exit(2);
23
24
  }
25
+ let generatedCore = null;
26
+ for (let i = 3; i < process.argv.length; i++) {
27
+ if (process.argv[i] === "--sdk-core") generatedCore = process.argv[++i] ?? null;
28
+ }
24
29
  const here = path.dirname(fileURLToPath(import.meta.url));
25
30
  const coreRoot = path.resolve(here, "..");
26
31
  let compilerJs;
@@ -39,20 +44,116 @@ for (const [specifier, file] of [
39
44
  ["@native-sdk/core/text", "sdk/text.d.ts"],
40
45
  ["@native-sdk/core/events", "sdk/events.d.ts"],
41
46
  ]) {
42
- const p = path.join(coreRoot, file);
47
+ const p = specifier === "@native-sdk/core" && generatedCore !== null
48
+ ? path.resolve(generatedCore)
49
+ : path.join(coreRoot, file);
43
50
  if (fs.existsSync(p)) maps.push("--external-types", `${specifier}=${p}`);
44
51
  }
45
- const probe = spawnSync(process.execPath, [compilerJs, "coverage", entry, ...maps], { encoding: "utf8" });
46
- const out = `${probe.stdout ?? ""}${probe.stderr ?? ""}`;
47
- if (probe.status === 0) process.exit(0);
48
- // Analyzer refusals for TYPE errors carry the compiler's own diagnostics;
49
- // pass them through untouched and fail the check.
50
- if (/TypeScript error/.test(out) || /error SC0001/.test(out)) {
51
- process.stderr.write(out);
52
- process.exit(1);
53
- }
54
- // Any other nonzero outcome (analyzer internal trouble) must not wedge
55
- // `native check`: the compile stage will judge for real.
56
- process.stderr.write(out);
57
- console.error("native check: the external compiler's analyzer could not run to a verdict here; the build will judge for real");
58
- process.exit(0);
52
+ const servicesClient = path.resolve(path.dirname(entry), "..", "node_modules", "@native-sdk", "services", "index.d.ts");
53
+ if (fs.existsSync(servicesClient)) maps.push("--external-types", `@native-sdk/services=${servicesClient}`);
54
+ const sourceRoot = path.dirname(entry);
55
+ const serviceVendor = path.join(sourceRoot, "services", "vendor");
56
+ function vendorPackageDirs(root) {
57
+ if (!fs.existsSync(root)) return [];
58
+ const dirs = [];
59
+ for (const item of fs.readdirSync(root, { withFileTypes: true })) {
60
+ if (!item.isDirectory()) continue;
61
+ const candidate = path.join(root, item.name);
62
+ if (item.name.startsWith("@")) {
63
+ for (const child of fs.readdirSync(candidate, { withFileTypes: true })) {
64
+ if (child.isDirectory()) dirs.push(path.join(candidate, child.name));
65
+ }
66
+ } else dirs.push(candidate);
67
+ }
68
+ return dirs;
69
+ }
70
+ const vendoredPackages = [];
71
+ for (const packageDir of vendorPackageDirs(serviceVendor)) {
72
+ const manifestPath = path.join(packageDir, "package.json");
73
+ if (!fs.existsSync(manifestPath)) continue;
74
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
75
+ const types = manifest.types ?? manifest.typings ?? "index.d.ts";
76
+ const declaration = typeof types === "string" ? path.resolve(packageDir, types) : "";
77
+ if (typeof manifest.name === "string" && fs.existsSync(declaration)) {
78
+ // Do not map vendored packages as external host modules: service coverage
79
+ // must follow --npm-static into their shipped JS, exactly like the build.
80
+ // The declaration check here is only the eligibility/source-identity gate.
81
+ vendoredPackages.push({ name: manifest.name, directory: packageDir });
82
+ }
83
+ }
84
+ function serviceEntries(root) {
85
+ const found = [];
86
+ if (!fs.existsSync(root)) return found;
87
+ for (const item of fs.readdirSync(root, { withFileTypes: true })) {
88
+ if (item.isDirectory() && item.name === "vendor") continue;
89
+ const candidate = path.join(root, item.name);
90
+ if (item.isDirectory()) found.push(...serviceEntries(candidate));
91
+ else if (item.isFile() && item.name.endsWith(".ts") && !item.name.endsWith(".d.ts")) found.push(candidate);
92
+ }
93
+ return found.sort();
94
+ }
95
+
96
+ function packagePath(root, name) {
97
+ return path.join(root, ...name.split("/"));
98
+ }
99
+
100
+ function isNpmStaticRefusal(output) {
101
+ const percent = output.match(/compile statically\s+\d+\s+\((\d+)%\)/i);
102
+ return (percent !== null && Number(percent[1]) < 100)
103
+ || /SC-NPM-STATIC|\bSC2013\b|\bSC4020\b|island fallback|cannot compile statically|static coverage[^\n]*dynamic/i.test(output);
104
+ }
105
+
106
+ let checkFailure = false;
107
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), "native-service-coverage-"));
108
+ try {
109
+ const stagedRoot = path.join(scratch, "src");
110
+ if (vendoredPackages.length > 0) {
111
+ fs.cpSync(sourceRoot, stagedRoot, { recursive: true });
112
+ for (const pkg of vendoredPackages) {
113
+ const destination = packagePath(path.join(stagedRoot, "node_modules"), pkg.name);
114
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
115
+ fs.cpSync(pkg.directory, destination, { recursive: true });
116
+ }
117
+ }
118
+ const authoredCandidates = [entry, ...serviceEntries(path.join(sourceRoot, "services"))];
119
+ for (const authoredCandidate of authoredCandidates) {
120
+ const isService = authoredCandidate !== entry;
121
+ const candidate = isService && vendoredPackages.length > 0
122
+ ? path.join(stagedRoot, path.relative(sourceRoot, authoredCandidate))
123
+ : authoredCandidate;
124
+ const npmArgs = isService && vendoredPackages.length > 0
125
+ ? ["--npm-static", vendoredPackages.map((pkg) => pkg.name).join(",")]
126
+ : [];
127
+ const probe = spawnSync(process.execPath, [compilerJs, "coverage", candidate, ...npmArgs, ...maps], { encoding: "utf8" });
128
+ const out = `${probe.stdout ?? ""}${probe.stderr ?? ""}`;
129
+ // Coverage deliberately reports per-package fallback as a note even
130
+ // when the rest of the source graph is analyzable. Native SDK's policy
131
+ // upgrades that note to a refusal: service builds have no island tier.
132
+ if (isService && isNpmStaticRefusal(out)) {
133
+ process.stderr.write(out);
134
+ console.error(
135
+ "native check: this service package does not clear scriptc's static tier. " +
136
+ "Choose another exact vendored package, port/vendor a static-compatible implementation, or wait for compiler support; " +
137
+ "Native SDK never enables npm auto-fallback or --dynamic.",
138
+ );
139
+ checkFailure = true;
140
+ continue;
141
+ }
142
+ if (probe.status === 0) continue;
143
+ // Analyzer refusals for TYPE errors carry the compiler's own diagnostics;
144
+ // pass them through untouched and fail the check. Service files receive
145
+ // this verdict independently because the core is forbidden to import them.
146
+ if (/TypeScript error/.test(out) || /error SC0001/.test(out)) {
147
+ process.stderr.write(out);
148
+ checkFailure = true;
149
+ continue;
150
+ }
151
+ // Any other nonzero outcome (analyzer internal trouble) must not wedge
152
+ // `native check`: the compile stage will judge for real.
153
+ process.stderr.write(out);
154
+ console.error(`native check: the external compiler's analyzer could not reach a verdict for ${authoredCandidate}; the build will judge for real`);
155
+ }
156
+ } finally {
157
+ fs.rmSync(scratch, { recursive: true, force: true });
158
+ }
159
+ process.exit(checkFailure ? 1 : 0);
@@ -0,0 +1,268 @@
1
+ #!/usr/bin/env node
2
+ // Generate the author-facing service compile-surface reference from the
3
+ // PINNED compiler's own surface manifest, and gate hand-written
4
+ // capability claims against it. Compiler capability facts (what
5
+ // services can use, which SC code refuses what) drift into folklore
6
+ // when they are hand-maintained prose; here they are byte-derived from
7
+ // packages/core/node_modules/@scriptc/compiler/surface-manifest.json,
8
+ // so a pin move regenerates them and a stale claim fails a check
9
+ // instead of surviving on memory.
10
+ //
11
+ // node gen_service_surface.mjs # (re)write the reference
12
+ // node gen_service_surface.mjs --check # verify, changing nothing
13
+ //
14
+ // Output: skill-data/ts-services/references/service-surface.md
15
+ //
16
+ // --check fails (exit 1) when:
17
+ // - the checked-in reference is missing or not byte-identical to a
18
+ // regeneration from the installed manifest (pin moved without
19
+ // regenerating, or the file was hand-edited);
20
+ // - the manifest's compilerVersion disagrees with the scriptc pin in
21
+ // packages/core/package.json (stale install — run
22
+ // `npm ci --include=dev` in packages/core);
23
+ // - an SC diagnostic code (SC0000..SC9999) appears in docs/, skills/,
24
+ // or skill-data/ outside the generated reference — compiler
25
+ // capability claims live in the generated table, never in prose;
26
+ // - a scriptc version literal (0.0.N) in those same trees names a
27
+ // version other than the pin — the calibration/spike sentences the
28
+ // docs carry must move with the pin.
29
+ //
30
+ // Exit 2: the compiler manifest is not installed or unreadable.
31
+
32
+ import fs from "node:fs";
33
+ import path from "node:path";
34
+ import { fileURLToPath } from "node:url";
35
+
36
+ const KNOWN_SCHEMA_VERSION = 1;
37
+ const coreRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
38
+ const repoRoot = path.resolve(coreRoot, "..", "..");
39
+ const manifestPath = path.join(coreRoot, "node_modules", "@scriptc", "compiler", "surface-manifest.json");
40
+ const outputRel = "skill-data/ts-services/references/service-surface.md";
41
+ const outputPath = path.join(repoRoot, outputRel);
42
+
43
+ const check = process.argv.includes("--check");
44
+
45
+ if (!fs.existsSync(manifestPath)) {
46
+ console.error("gen_service_surface: the pinned compiler is not installed — run `npm ci --include=dev` in the SDK's packages/core");
47
+ process.exit(2);
48
+ }
49
+ let manifest;
50
+ try {
51
+ manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
52
+ } catch (error) {
53
+ console.error(`gen_service_surface: cannot read ${manifestPath}: ${error.message}`);
54
+ process.exit(2);
55
+ }
56
+ if (manifest.schemaVersion !== KNOWN_SCHEMA_VERSION) {
57
+ console.error(`gen_service_surface: manifest schemaVersion ${manifest.schemaVersion} is unknown (this tool knows ${KNOWN_SCHEMA_VERSION}) — update the tool before regenerating`);
58
+ process.exit(2);
59
+ }
60
+
61
+ // ---- render ---------------------------------------------------------------
62
+
63
+ const cell = (text) =>
64
+ text === undefined ? "" : String(text)
65
+ .replaceAll("&", "&amp;")
66
+ .replaceAll("<", "&lt;")
67
+ .replaceAll(">", "&gt;")
68
+ .replaceAll("|", "\\|")
69
+ .replaceAll(/\r?\n/g, " ");
70
+ const byId = (a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
71
+
72
+ function table(entries, { withCode = true } = {}) {
73
+ const lines = [];
74
+ lines.push(withCode ? "| Entry id | Surface | Status | Refusal code | Notes |" : "| Entry id | Surface | Status | Notes |");
75
+ lines.push(withCode ? "|---|---|---|---|---|" : "|---|---|---|---|");
76
+ for (const e of [...entries].sort(byId)) {
77
+ const cols = [`\`${e.id}\``, cell(e.name), e.status];
78
+ if (withCode) cols.push(e.code ? `\`${e.code}\`` : "");
79
+ cols.push(cell(e.note));
80
+ lines.push(`| ${cols.join(" | ")} |`);
81
+ }
82
+ return lines.join("\n");
83
+ }
84
+
85
+ const kinds = { syntax: [], "diagnostic-fence": [], "node-builtin": [], stdlib: [] };
86
+ const unknownKinds = new Set();
87
+ for (const e of manifest.entries) {
88
+ (kinds[e.kind] ?? (unknownKinds.add(e.kind), (kinds[e.kind] = []))).push(e);
89
+ }
90
+ const counts = { static: 0, "dynamic-only": 0, unsupported: 0 };
91
+ for (const e of manifest.entries) counts[e.status] = (counts[e.status] ?? 0) + 1;
92
+
93
+ const isBuiltinModule = (entry) => !entry.name.includes(".");
94
+ const builtinModules = kinds["node-builtin"].filter(isBuiltinModule);
95
+ const builtinMembers = kinds["node-builtin"].filter((entry) => !isBuiltinModule(entry));
96
+ const missingLoweringFence = kinds["diagnostic-fence"].find((entry) =>
97
+ entry.name === "standard-library or @types/node surface with no lowering");
98
+ const constrainedCallRefusal = missingLoweringFence?.code
99
+ ? `outside the lowered set are refused per site with \`${missingLoweringFence.code}\`.`
100
+ : "outside the lowered set are refused with the applicable diagnostic fence listed below.";
101
+
102
+ const sections = [];
103
+ sections.push(`<!-- GENERATED FILE — do not edit by hand.
104
+ Derived byte-for-byte from the pinned compiler's surface manifest:
105
+ packages/core/node_modules/@scriptc/compiler/surface-manifest.json
106
+ Regenerate after any compiler pin move:
107
+ node packages/core/scripts/gen_service_surface.mjs
108
+ Verify without writing:
109
+ node packages/core/scripts/gen_service_surface.mjs --check -->
110
+
111
+ # Service compile surface — scriptc ${manifest.compilerVersion}
112
+
113
+ What TypeScript under \`src/services/\` can use, as stated by the pinned
114
+ compiler itself (surface manifest schema ${manifest.schemaVersion}, ${manifest.entries.length} entries:
115
+ ${counts.static} static, ${counts["dynamic-only"]} dynamic-only, ${counts.unsupported} unsupported).
116
+
117
+ How to read the tables:
118
+
119
+ - **static** — compiles in the engine-free static tier services use.
120
+ - **dynamic-only** — needs the embedded dynamic engine (\`--dynamic\`),
121
+ which Native SDK builds never pass, so for services this means
122
+ **unavailable** until the entry goes static.
123
+ - **unsupported** — refused with the listed SC code. A status describes
124
+ where the named code is *raised*: forms outside the supported subset
125
+ refuse with that code, while supported forms appear as their own
126
+ static entries.
127
+ - Absence from the manifest means "not projected by the compiler's
128
+ decision tables yet", never "unsupported".
129
+ - Standard-library and node-builtin rows name surface whose lowered
130
+ call forms are constrained (arity, argument shapes); call forms
131
+ ${constrainedCallRefusal}`);
132
+
133
+ sections.push(`## Syntax
134
+
135
+ ${table(kinds.syntax)}`);
136
+
137
+ sections.push(`## Diagnostic fences
138
+
139
+ The SC codes an author can hit at the module/program level, and what
140
+ each one refuses.
141
+
142
+ ${table(kinds["diagnostic-fence"])}`);
143
+
144
+ sections.push(`## Node built-in modules
145
+
146
+ Recognized modules and their accepted specifier forms, as stated by each
147
+ manifest row in the Notes column:
148
+
149
+ ${table(builtinModules, { withCode: false })}
150
+
151
+ ### Module member surface
152
+
153
+ ${table(builtinMembers)}`);
154
+
155
+ sections.push(`## Standard library
156
+
157
+ ${table(kinds.stdlib)}`);
158
+
159
+ if (unknownKinds.size > 0) {
160
+ const otherTables = [...unknownKinds].sort().map((kind) => `### \`${kind}\`
161
+
162
+ ${table(kinds[kind])}`).join("\n\n");
163
+ sections.push(`## Other entries
164
+
165
+ Entry kinds this generator does not know yet. Their manifest rows are
166
+ preserved here; update the generator when a dedicated section would make
167
+ the reference clearer.
168
+
169
+ ${otherTables}`);
170
+ }
171
+
172
+ sections.push(`## Compiler coverage statement
173
+
174
+ The manifest's own description of how it is projected and what its
175
+ statuses promise, verbatim:
176
+
177
+ ${(manifest.coverage ?? []).map((c) => `- ${c}`).join("\n")}`);
178
+
179
+ const rendered = sections.join("\n\n") + "\n";
180
+
181
+ // ---- write mode -----------------------------------------------------------
182
+
183
+ if (!check) {
184
+ fs.mkdirSync(path.dirname(outputPath), { recursive: true });
185
+ fs.writeFileSync(outputPath, rendered);
186
+ console.log(`wrote ${outputRel} (compiler ${manifest.compilerVersion}, ${manifest.entries.length} entries)`);
187
+ process.exit(0);
188
+ }
189
+
190
+ // ---- check mode -----------------------------------------------------------
191
+
192
+ const problems = [];
193
+
194
+ // 1. Reference file freshness: byte-identical to regeneration.
195
+ const existing = fs.existsSync(outputPath) ? fs.readFileSync(outputPath, "utf8") : null;
196
+ if (existing === null) {
197
+ problems.push(`${outputRel} is missing — generate it: node packages/core/scripts/gen_service_surface.mjs`);
198
+ } else if (existing !== rendered) {
199
+ problems.push(`${outputRel} does not match the installed compiler manifest (pin moved without regenerating, or the file was hand-edited) — regenerate: node packages/core/scripts/gen_service_surface.mjs`);
200
+ }
201
+
202
+ // 2. Pin sanity: the installed manifest is the pinned compiler's.
203
+ const pkg = JSON.parse(fs.readFileSync(path.join(coreRoot, "package.json"), "utf8"));
204
+ const pin = pkg.dependencies?.scriptc;
205
+ if (manifest.compilerVersion !== pin) {
206
+ problems.push(`installed compiler manifest is ${manifest.compilerVersion} but packages/core/package.json pins scriptc ${pin} — run \`npm ci --include=dev\` in packages/core`);
207
+ }
208
+
209
+ // 3+4. Claim scan: SC codes and scriptc version literals in prose.
210
+ function proseFiles() {
211
+ const roots = ["docs", "skills", "skill-data"];
212
+ const files = [];
213
+ const walk = (dir) => {
214
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
215
+ const full = path.join(dir, entry.name);
216
+ if (entry.isDirectory()) {
217
+ if (entry.name === "node_modules" || entry.name.startsWith(".next")) continue;
218
+ walk(full);
219
+ } else if (/\.(md|mdx)$/.test(entry.name)) {
220
+ files.push(full);
221
+ }
222
+ }
223
+ };
224
+ for (const root of roots) {
225
+ const full = path.join(repoRoot, root);
226
+ if (fs.existsSync(full)) walk(full);
227
+ }
228
+ return files.filter((f) => path.resolve(f) !== outputPath);
229
+ }
230
+
231
+ // Only semver literals in explicit compiler context are scriptc claims.
232
+ // Package examples such as `some-package@0.0.1` are unrelated and must
233
+ // remain legal in authoring docs.
234
+ const semver = String.raw`\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?`;
235
+ const markdownWrapper = "(?:`{1,3}|\\*{1,3}|_{1,3})?";
236
+ const scriptcContext = String.raw`scriptc(?:\s+compiler)?(?:'s)?(?:\s+(?:version|pin))?`;
237
+ const versionJoin = String.raw`(?:\s+(?:(?:is|at)\s*)?[:=]?\s*|[:=]\s*)`;
238
+ const versionClaim = new RegExp(
239
+ String.raw`\b${scriptcContext}${versionJoin}${markdownWrapper}(?<![\d.])(?<version>${semver})(?!\d|\.\d)${markdownWrapper}`,
240
+ "gi",
241
+ );
242
+ const scClaim = /\bSC\d{4}\b/g;
243
+ const lineNumberAt = (text, offset) =>
244
+ 1 + (text.slice(0, offset).match(/\n/g)?.length ?? 0);
245
+
246
+ for (const file of proseFiles()) {
247
+ const rel = path.relative(repoRoot, file);
248
+ const text = fs.readFileSync(file, "utf8");
249
+ for (const match of text.matchAll(scClaim)) {
250
+ const line = lineNumberAt(text, match.index);
251
+ problems.push(`${rel}:${line}: hand-written compiler capability claim \`${match[0]}\` — SC codes live only in the generated ${outputRel}; state the fact there (regenerate) and link or describe it here without the code`);
252
+ }
253
+ for (const match of text.matchAll(versionClaim)) {
254
+ const claimedVersion = match.groups.version;
255
+ if (claimedVersion !== pin) {
256
+ const versionOffset = match.index + match[0].indexOf(claimedVersion);
257
+ const line = lineNumberAt(text, versionOffset);
258
+ problems.push(`${rel}:${line}: names compiler version ${claimedVersion} but the pin is ${pin} — refresh the sentence (calibration/spike claims move with the pin)`);
259
+ }
260
+ }
261
+ }
262
+
263
+ if (problems.length > 0) {
264
+ console.error(`service surface check: ${problems.length} problem(s)\n`);
265
+ for (const p of problems) console.error(` - ${p}`);
266
+ process.exit(1);
267
+ }
268
+ console.log(`service surface check: ${outputRel} matches compiler ${manifest.compilerVersion}; no hand-written SC-code or stale version claims in docs/, skills/, skill-data/`);
@@ -0,0 +1,64 @@
1
+ #!/usr/bin/env node
2
+ // Empirical service-package probe for the compiler pin carried by this SDK.
3
+ // These are deliberately small, common data/text utilities already locked in
4
+ // the docs workspace, so the spike needs no network and judges exact bytes.
5
+
6
+ import { spawnSync } from "node:child_process";
7
+ import fs from "node:fs";
8
+ import os from "node:os";
9
+ import path from "node:path";
10
+ import { createRequire } from "node:module";
11
+ import { fileURLToPath } from "node:url";
12
+
13
+ const here = path.dirname(fileURLToPath(import.meta.url));
14
+ const coreRoot = path.resolve(here, "..");
15
+ const repoRoot = path.resolve(coreRoot, "..", "..");
16
+ const compilerJs = createRequire(path.join(coreRoot, "package.json")).resolve("scriptc/dist/main.js");
17
+ const compilerVersion = JSON.parse(fs.readFileSync(path.join(coreRoot, "package.json"), "utf8")).dependencies.scriptc;
18
+
19
+ const candidates = [
20
+ { name: "escape-string-regexp", version: "5.0.0", source: 'import escape from "escape-string-regexp";\nconsole.log(escape("a.b"));\n' },
21
+ { name: "comma-separated-tokens", version: "2.0.3", source: 'import { parse } from "comma-separated-tokens";\nconsole.log(parse("a,b").length);\n' },
22
+ { name: "space-separated-tokens", version: "2.0.2", source: 'import { parse } from "space-separated-tokens";\nconsole.log(parse("a b").length);\n' },
23
+ { name: "nanoid", version: "3.3.15", source: 'import { nanoid } from "nanoid";\nconsole.log(nanoid(4));\n' },
24
+ { name: "micromark", version: "4.0.2", source: 'import { micromark } from "micromark";\nconsole.log(micromark("# hi"));\n' },
25
+ ];
26
+
27
+ function pnpmNodeModules(candidate) {
28
+ const spelling = `${candidate.name.replaceAll("/", "+")}@${candidate.version}`;
29
+ const exact = path.join(repoRoot, "docs", "node_modules", ".pnpm", spelling, "node_modules");
30
+ if (fs.statSync(exact, { throwIfNoEntry: false })?.isDirectory()) return exact;
31
+ throw new Error(`locked spike source is missing: ${exact}; run pnpm --dir docs install`);
32
+ }
33
+
34
+ const results = [];
35
+ for (const candidate of candidates) {
36
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), "native-npm-static-spike-"));
37
+ try {
38
+ fs.symlinkSync(pnpmNodeModules(candidate), path.join(scratch, "node_modules"), "dir");
39
+ const entry = path.join(scratch, "probe.ts");
40
+ fs.writeFileSync(entry, candidate.source);
41
+ const probe = spawnSync(process.execPath, [compilerJs, "coverage", entry, "--npm-static", candidate.name], { encoding: "utf8" });
42
+ const output = `${probe.stdout ?? ""}${probe.stderr ?? ""}`;
43
+ if (process.env.NATIVE_NPM_STATIC_SPIKE_VERBOSE === "1") {
44
+ process.stderr.write(`\n===== ${candidate.name}@${candidate.version} =====\n${output}\n`);
45
+ }
46
+ const fallback = /island fallback/i.test(output);
47
+ const staticPercent = Number(output.match(/compile statically\s+\d+\s+\((\d+)%\)/i)?.[1] ?? "-1");
48
+ const reason = output.match(/island fallback\s*\(([^\n)]+(?:\)[^\n)]*)?)/i)?.[1]
49
+ ?? output.match(/error\s+(SC\d+)[^\n]*/i)?.[0]
50
+ ?? (staticPercent >= 0 && staticPercent < 100 ? `only ${staticPercent}% of analyzed statements compile statically` : null)
51
+ ?? (probe.status === 0 ? "static coverage accepted" : "coverage command failed without a diagnostic");
52
+ results.push({
53
+ package: candidate.name,
54
+ version: candidate.version,
55
+ verdict: probe.status === 0 && !fallback && staticPercent === 100 ? "static" : "refused",
56
+ static_percent: staticPercent,
57
+ reason: reason.trim(),
58
+ });
59
+ } finally {
60
+ fs.rmSync(scratch, { recursive: true, force: true });
61
+ }
62
+ }
63
+
64
+ process.stdout.write(JSON.stringify({ compiler: `scriptc ${compilerVersion}`, policy: "explicit --npm-static; no auto or dynamic fallback", candidates: results }, null, 2) + "\n");
@@ -9,8 +9,11 @@
9
9
  // the same rule).
10
10
  //
11
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>)
12
+ // --manifest <packages/core/package.json> --frontend-sidecar <file>
13
+ // --out-archive <file>
14
+ // --out-sidecar <file>
15
+ // [--host-platform <arch-os-abi> --target-platform <arch-os-abi>
16
+ // --zig-exe <path>] (--compiler <cmd> | --compiler-js <main.js>)
14
17
 
15
18
  import { spawnSync } from "node:child_process";
16
19
  import fs from "node:fs";
@@ -23,12 +26,12 @@ function parseArgs(argv) {
23
26
  const key = argv[i];
24
27
  const value = argv[i + 1];
25
28
  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>)");
29
+ console.error("usage: run_external_core_compiler.mjs --stage <dir> --name <n> --manifest <package.json> --frontend-sidecar <file> --out-archive <file> --out-sidecar <file> [--host-platform <arch-os-abi> --target-platform <arch-os-abi> --zig-exe <path>] (--compiler <cmd> | --compiler-js <main.js>)");
27
30
  process.exit(2);
28
31
  }
29
32
  args[key.slice(2)] = value;
30
33
  }
31
- for (const required of ["stage", "name", "manifest", "out-archive", "out-sidecar"]) {
34
+ for (const required of ["stage", "name", "manifest", "frontend-sidecar", "out-archive", "out-sidecar"]) {
32
35
  if (!(required in args)) {
33
36
  console.error(`run_external_core_compiler.mjs: missing --${required}`);
34
37
  process.exit(2);
@@ -38,13 +41,17 @@ function parseArgs(argv) {
38
41
  console.error("run_external_core_compiler.mjs: supply --compiler <cmd> or --compiler-js <main.js>");
39
42
  process.exit(2);
40
43
  }
44
+ if (Boolean(args["host-platform"]) !== Boolean(args["target-platform"])) {
45
+ console.error("run_external_core_compiler.mjs: supply --host-platform and --target-platform together");
46
+ process.exit(2);
47
+ }
41
48
  return args;
42
49
  }
43
50
 
44
51
  const args = parseArgs(process.argv);
45
52
  // Every path argument resolves against the INVOCATION's cwd up front:
46
53
  // the compile itself runs from a scratch directory.
47
- for (const key of ["stage", "manifest", "out-archive", "out-sidecar", "compiler-js"]) {
54
+ for (const key of ["stage", "manifest", "frontend-sidecar", "out-archive", "out-sidecar", "compiler-js", "zig-exe"]) {
48
55
  if (key in args) args[key] = path.resolve(args[key]);
49
56
  }
50
57
  // --compiler is a COMMAND: a bare executable path (possibly containing
@@ -54,6 +61,57 @@ const argv0 = args.compiler
54
61
  ? (fs.existsSync(args.compiler) ? [args.compiler] : args.compiler.split(/\s+/))
55
62
  : [process.execPath, args["compiler-js"]];
56
63
 
64
+ // App and fixture build graphs state the host and target explicitly. A
65
+ // differing target must compile the core archive through the same ScriptC
66
+ // zig-cc lane as the service archive that links beside it; otherwise a cross
67
+ // build mixes a host-format core archive with target-format Zig and service
68
+ // objects. Standalone host-only callers may omit both platform arguments.
69
+ // The pairing matrix is the pinned compiler's build matrix, shared with
70
+ // run_external_service_compiler.mjs: same-triple compiles run the native
71
+ // lane; Linux and Windows GNU targets cross-compile from any desktop host;
72
+ // macOS targets need a macOS build host.
73
+ const hostParts = args["host-platform"]?.split("-") ?? [];
74
+ const targetParts = args["target-platform"]?.split("-") ?? [];
75
+ const hostArch = hostParts[0] ?? "";
76
+ const hostOs = (hostParts[1] ?? "").split(".")[0];
77
+ const hostAbi = (hostParts[2] ?? "").split(".")[0];
78
+ const targetArch = targetParts[0] ?? "";
79
+ const targetOs = (targetParts[1] ?? "").split(".")[0];
80
+ const targetAbi = (targetParts[2] ?? "").split(".")[0];
81
+ // A Windows host's Zig triple defaults to GNU, but an explicit same-arch MSVC
82
+ // target still compiles through native clang and the installed Windows SDK.
83
+ const nativeWindows = hostOs === "windows" && targetOs === "windows" && hostArch === targetArch &&
84
+ (targetAbi === hostAbi || targetAbi === "msvc");
85
+ const cross = args["host-platform"] !== undefined &&
86
+ args["target-platform"] !== args["host-platform"] && !nativeWindows;
87
+ if (cross) {
88
+ const desktopHost = ["macos", "linux", "windows"].includes(hostOs);
89
+ const admitted = desktopHost &&
90
+ (targetOs === "linux" ||
91
+ (targetOs === "windows" && targetAbi === "gnu") ||
92
+ (targetOs === "macos" && hostOs === "macos"));
93
+ if (!admitted) {
94
+ console.error(
95
+ targetOs === "windows" && targetAbi !== "gnu"
96
+ ? `TypeScript cores for a cross-target Windows build (${args["target-platform"]}) require the GNU ABI: Zig supplies that target's CRT and system libraries, while an MSVC target needs a native Windows toolchain. Build ${targetArch}-windows-msvc on a matching Windows host, or cross-compile as "${targetArch}-windows-gnu".`
97
+ : targetOs === "macos"
98
+ ? `TypeScript cores for a macOS target (${args["target-platform"]}) compile on a macOS build host only — Apple linking needs the host toolchain's SDK — but this build host is ${args["host-platform"]}. Build macOS apps on a Mac.`
99
+ : `TypeScript cores compile for desktop targets the pinned compiler covers — Linux and Windows GNU from a macOS/Linux/Windows build host, macOS from a macOS host — but this build pairs host ${args["host-platform"]} with target ${args["target-platform"]}.`,
100
+ );
101
+ process.exit(2);
102
+ }
103
+ }
104
+ const compileEnv = cross
105
+ ? {
106
+ ...process.env,
107
+ SCRIPTC_CC: "zigcc",
108
+ SCRIPTC_TARGET: args["target-platform"],
109
+ ...(args["zig-exe"]
110
+ ? { PATH: `${path.dirname(args["zig-exe"])}${path.delimiter}${process.env.PATH ?? ""}` }
111
+ : {}),
112
+ }
113
+ : process.env;
114
+
57
115
  // The profile's determinism-fence table is RELEASE-PINNED DATA (see
58
116
  // tools/corewire/emit_profile.zig): its ids resolve against one
59
117
  // toolchain release's surface manifest, so the supplied command must BE
@@ -84,6 +142,7 @@ try {
84
142
  const build = spawnSync(argv0[0], [...argv0.slice(1), "build", "--lib", "--profile", "profile.json", "-o", args.name], {
85
143
  cwd: work,
86
144
  stdio: "inherit",
145
+ env: compileEnv,
87
146
  });
88
147
  if (build.status !== 0) process.exit(build.status ?? 1);
89
148
 
@@ -102,7 +161,19 @@ try {
102
161
  fs.mkdirSync(path.dirname(args["out-archive"]), { recursive: true });
103
162
  fs.mkdirSync(path.dirname(args["out-sidecar"]), { recursive: true });
104
163
  fs.copyFileSync(path.join(work, produced), args["out-archive"]);
105
- fs.copyFileSync(sidecar, args["out-sidecar"]);
164
+
165
+ // The pinned compiler owns the archive contract (including its build id),
166
+ // while the SDK frontend owns facts the compiler release predates. Carry
167
+ // exactly those checked persistence facts across the compile boundary.
168
+ const compiledContract = JSON.parse(fs.readFileSync(sidecar, "utf8"));
169
+ const frontendContract = JSON.parse(fs.readFileSync(args["frontend-sidecar"], "utf8"));
170
+ if (!/^[0-9a-f]{16}$/.test(frontendContract.model_fingerprint ?? "") || typeof frontendContract.has_migrate !== "boolean") {
171
+ console.error("the frontend contract is missing its checked persistence metadata — the SDK frontend and build driver are out of sync");
172
+ process.exit(1);
173
+ }
174
+ compiledContract.model_fingerprint = frontendContract.model_fingerprint;
175
+ compiledContract.has_migrate = frontendContract.has_migrate;
176
+ fs.writeFileSync(args["out-sidecar"], `${JSON.stringify(compiledContract, null, 2)}\n`);
106
177
  } finally {
107
178
  fs.rmSync(work, { recursive: true, force: true });
108
179
  }