@native-sdk/cli 0.8.4 → 0.9.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.
Files changed (161) hide show
  1. package/build/app.zig +1178 -74
  2. package/build.zig +715 -17
  3. package/build.zig.zon +1 -0
  4. package/native-sdk.d.ts +10 -0
  5. package/package.json +12 -11
  6. package/packages/core/compile-surface/core.ts +435 -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/merge_static_archives.mjs +78 -0
  12. package/packages/core/scripts/npm_static_spike.mjs +64 -0
  13. package/packages/core/scripts/run_external_core_compiler.mjs +122 -6
  14. package/packages/core/scripts/run_external_service_compiler.mjs +280 -0
  15. package/packages/core/scripts/stage_external_core.mjs +9 -1
  16. package/packages/core/scripts/stage_external_services.mjs +172 -0
  17. package/packages/core/scripts/surface_manifest_diff.mjs +253 -0
  18. package/packages/core/scripts/vendor_service_packages.mjs +189 -0
  19. package/packages/core/sdk/core.d.ts +224 -0
  20. package/packages/core/sdk/core.ts +694 -22
  21. package/packages/core/sdk/events.d.ts +89 -0
  22. package/packages/core/sdk/events.ts +128 -0
  23. package/packages/core/src/checker.ts +936 -15
  24. package/packages/core/src/cli.ts +156 -3
  25. package/packages/core/src/contract.ts +28 -5
  26. package/packages/core/src/devhost.ts +1876 -16
  27. package/packages/core/src/devhost_journal.mjs +183 -0
  28. package/packages/core/src/devhost_resolver.mjs +17 -1
  29. package/packages/core/src/devhost_service_worker.mjs +90 -0
  30. package/packages/core/src/diagnostics.ts +179 -22
  31. package/packages/core/src/frontend.ts +210 -34
  32. package/packages/core/src/infer.ts +24 -0
  33. package/packages/core/src/modules.ts +129 -80
  34. package/packages/core/src/service_contract.ts +597 -0
  35. package/packages/core/src/sqlite_cli.ts +93 -0
  36. package/packages/core/src/sqlite_codegen.ts +806 -0
  37. package/packages/core/src/sqlite_runtime_policy.ts +364 -0
  38. package/packages/core/src/typed_ast.ts +36 -8
  39. package/skill-data/automation/SKILL.md +1 -1
  40. package/skill-data/core/references/project-anatomy.md +1 -1
  41. package/skill-data/native-ui/SKILL.md +58 -5
  42. package/skill-data/ts-core/SKILL.md +123 -41
  43. package/skill-data/ts-services/SKILL.md +126 -0
  44. package/skill-data/ts-services/references/service-surface.md +604 -0
  45. package/skill-data/zig/SKILL.md +1 -1
  46. package/skills/native-sdk/SKILL.md +1 -1
  47. package/src/app_runner/no_migrations.zig +3 -0
  48. package/src/app_runner/no_services.zig +20 -0
  49. package/src/app_runner/root.zig +133 -4
  50. package/src/app_runner/ts_core_main.zig +254 -8
  51. package/src/app_runner/ts_core_mobile.zig +241 -0
  52. package/src/automation/protocol.zig +5 -1
  53. package/src/automation/snapshot.zig +31 -11
  54. package/src/embed/app_exports.zig +12 -1
  55. package/src/embed/c_api.zig +48 -2
  56. package/src/embed/conversions.zig +4 -5
  57. package/src/embed/host.zig +109 -1
  58. package/src/embed/root.zig +8 -0
  59. package/src/embed/tests.zig +241 -0
  60. package/src/embed/types.zig +51 -0
  61. package/src/embed/ui_host.zig +185 -5
  62. package/src/platform/android/NativeSdkActivity.java +131 -0
  63. package/src/platform/android/android_host.c +182 -1
  64. package/src/platform/android/native_sdk_app.h +17 -0
  65. package/src/platform/ios/native_sdk_app.h +17 -0
  66. package/src/platform/ios/uikit_host.m +115 -0
  67. package/src/platform/linux/cef_host.cpp +8 -2
  68. package/src/platform/linux/gtk_host.c +289 -22
  69. package/src/platform/linux/gtk_host.h +5 -1
  70. package/src/platform/linux/root.zig +109 -22
  71. package/src/platform/macos/appkit_host.h +24 -7
  72. package/src/platform/macos/appkit_host.m +686 -64
  73. package/src/platform/macos/cef_host.mm +400 -66
  74. package/src/platform/macos/root.zig +304 -47
  75. package/src/platform/null_platform.zig +435 -48
  76. package/src/platform/null_platform_tests.zig +113 -0
  77. package/src/platform/root.zig +19 -0
  78. package/src/platform/types.zig +281 -28
  79. package/src/platform/windows/root.zig +207 -27
  80. package/src/platform/windows/webview2_host.cpp +334 -51
  81. package/src/primitives/app_manifest/comptime_scene.zig +2 -0
  82. package/src/primitives/app_manifest/root.zig +4 -0
  83. package/src/primitives/app_manifest/tests.zig +3 -0
  84. package/src/primitives/app_manifest/types.zig +32 -0
  85. package/src/primitives/app_manifest/validation.zig +19 -1
  86. package/src/root.zig +53 -0
  87. package/src/runtime/api.zig +19 -0
  88. package/src/runtime/automation_commands.zig +35 -2
  89. package/src/runtime/automation_snapshot.zig +32 -20
  90. package/src/runtime/bridge_permission_tests.zig +58 -3
  91. package/src/runtime/bridge_responses.zig +4 -2
  92. package/src/runtime/builtin_bridge.zig +11 -1
  93. package/src/runtime/canvas_frame.zig +18 -11
  94. package/src/runtime/canvas_frame_animation_tests.zig +4 -0
  95. package/src/runtime/clock.zig +13 -1
  96. package/src/runtime/core.zig +145 -7
  97. package/src/runtime/credentials_store.zig +115 -0
  98. package/src/runtime/effects.zig +3701 -231
  99. package/src/runtime/effects_credentials_tests.zig +332 -0
  100. package/src/runtime/effects_file_tests.zig +587 -0
  101. package/src/runtime/effects_host_tests.zig +208 -1
  102. package/src/runtime/effects_notification_tests.zig +11 -0
  103. package/src/runtime/effects_relational_tests.zig +314 -0
  104. package/src/runtime/effects_store_tests.zig +211 -0
  105. package/src/runtime/file_access.zig +400 -0
  106. package/src/runtime/file_effect_crash_helper.zig +28 -0
  107. package/src/runtime/file_effect_crash_tests.zig +37 -0
  108. package/src/runtime/flow.zig +35 -10
  109. package/src/runtime/gpu_surface_events.zig +6 -1
  110. package/src/runtime/native_command_event_tests.zig +86 -2
  111. package/src/runtime/persist_store.zig +666 -0
  112. package/src/runtime/pty.zig +5 -2
  113. package/src/runtime/record_store.zig +788 -0
  114. package/src/runtime/relational_store.zig +854 -0
  115. package/src/runtime/root.zig +54 -0
  116. package/src/runtime/runtime_event_tests.zig +70 -0
  117. package/src/runtime/service_host.zig +711 -0
  118. package/src/runtime/service_pool.zig +1314 -0
  119. package/src/runtime/session_blobs.zig +4 -1
  120. package/src/runtime/session_journal.zig +158 -5
  121. package/src/runtime/session_record.zig +215 -0
  122. package/src/runtime/session_replay.zig +206 -11
  123. package/src/runtime/session_tests.zig +81 -0
  124. package/src/runtime/shell_layout.zig +1 -0
  125. package/src/runtime/shell_layout_tests.zig +120 -0
  126. package/src/runtime/sqlite_engine.zig +474 -0
  127. package/src/runtime/state.zig +16 -0
  128. package/src/runtime/system_services.zig +170 -38
  129. package/src/runtime/tests.zig +4 -0
  130. package/src/runtime/ts_core_host.zig +1067 -95
  131. package/src/runtime/ts_core_host_tests.zig +325 -11
  132. package/src/runtime/ts_ui_app.zig +953 -2
  133. package/src/runtime/ui_app.zig +434 -96
  134. package/src/runtime/ui_app_tests.zig +287 -11
  135. package/src/runtime/ui_app_window_tests.zig +61 -7
  136. package/src/runtime/validation.zig +42 -0
  137. package/src/runtime/view.zig +9 -0
  138. package/src/runtime/window_storage.zig +1 -0
  139. package/src/runtime/window_view_runtime.zig +2 -3
  140. package/src/runtime/window_views.zig +19 -0
  141. package/src/tooling/android.zig +21 -16
  142. package/src/tooling/db.zig +160 -0
  143. package/src/tooling/ios.zig +7 -1
  144. package/src/tooling/manifest.zig +214 -2
  145. package/src/tooling/package.zig +116 -0
  146. package/src/tooling/raw_manifest.zig +30 -0
  147. package/src/tooling/root.zig +1 -0
  148. package/src/tooling/templates.zig +189 -4
  149. package/src/tooling/ts_core.zig +366 -17
  150. package/src/tooling/verbs.zig +7 -0
  151. package/third_party/sqlite/README.md +13 -0
  152. package/third_party/sqlite/sqlite3.c +269649 -0
  153. package/third_party/sqlite/sqlite3.h +14349 -0
  154. package/tools/corewire/core_abi.zig +14 -2
  155. package/tools/corewire/emit.zig +98 -29
  156. package/tools/corewire/emit_facade.zig +442 -27
  157. package/tools/corewire/emit_profile.zig +6 -2
  158. package/tools/corewire/emit_service.zig +924 -0
  159. package/tools/corewire/main.zig +122 -0
  160. package/tools/corewire/service_contract.zig +250 -0
  161. package/tools/corewire/sidecar.zig +26 -15
@@ -1,32 +1,32 @@
1
1
  {
2
2
  "name": "@native-sdk/core",
3
- "version": "0.8.4",
3
+ "version": "0.9.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@native-sdk/core",
9
- "version": "0.8.4",
9
+ "version": "0.9.1",
10
10
  "dependencies": {
11
- "scriptc": "0.0.22"
11
+ "scriptc": "0.0.31"
12
12
  },
13
13
  "devDependencies": {
14
14
  "@typescript/old": "npm:typescript@6.0.3"
15
15
  }
16
16
  },
17
17
  "node_modules/@scriptc/compiler": {
18
- "version": "0.0.22",
19
- "integrity": "sha512-cZil7ZgK64yRpSk1X3BSq1Q2DBru53KfC4X0i/qa0vHNk/rvk3teDzykSP5l3nb5wY2ckh0Es3fojfD0kUp/gA==",
18
+ "version": "0.0.31",
19
+ "integrity": "sha512-mx0GZXQdYR19jwahXQeo8dgZffi38v2F43n2zvofRsNozjPkh4cJ8qM7ir5xgc1otEfXKHIVMTBh0x/uKq6gbQ==",
20
20
  "license": "Apache-2.0",
21
21
  "dependencies": {
22
- "@scriptc/runtime": "0.0.22",
22
+ "@scriptc/runtime": "0.0.31",
23
23
  "typescript": "7.0.2",
24
24
  "typescript5": "npm:typescript@5.9.3"
25
25
  }
26
26
  },
27
27
  "node_modules/@scriptc/runtime": {
28
- "version": "0.0.22",
29
- "integrity": "sha512-UytlS/6vxWXYIpIO2lQYVh4xTzMoybX0Uz1wKA41ezq62sMeuhHT6JVappUG55DgVNAWGgMI/WAHun2TeRutNg==",
28
+ "version": "0.0.31",
29
+ "integrity": "sha512-NS37+H6blyQGmv24BN11vXmqOZ9igudWOqlkcL1MWvslOemy4vLWqxAe77Ca/51DJCfAu1xui2a3MPq8rQLfcQ==",
30
30
  "license": "Apache-2.0"
31
31
  },
32
32
  "node_modules/@typescript/old": {
@@ -344,11 +344,11 @@
344
344
  }
345
345
  },
346
346
  "node_modules/scriptc": {
347
- "version": "0.0.22",
348
- "integrity": "sha512-gJQ5Johx477Al1EqZOTeXOPsPgwzSOvVljIc9l1S0BqhaffyZtxXa1Mm3YFKZaCV3u4YNAEMsbO9EBgvW1awDg==",
347
+ "version": "0.0.31",
348
+ "integrity": "sha512-V7cR6080/mqm1PlHeIIlGDHID4aL/Poq+w4U/03935nK0stIJkHaKGtmKZEk5GrOXrejqVEtMNCGjZvYk/ClUQ==",
349
349
  "license": "Apache-2.0",
350
350
  "dependencies": {
351
- "@scriptc/compiler": "0.0.22"
351
+ "@scriptc/compiler": "0.0.31"
352
352
  },
353
353
  "bin": {
354
354
  "scriptc": "dist/main.js"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@native-sdk/core",
3
- "version": "0.8.4",
3
+ "version": "0.9.1",
4
4
  "description": "The TypeScript authoring tier: the app-core subset, its checker and contract frontend, the exact-pinned core compiler dependency, and the SDK module cores import",
5
5
  "repository": {
6
6
  "type": "git",
@@ -36,6 +36,6 @@
36
36
  "@typescript/old": "npm:typescript@6.0.3"
37
37
  },
38
38
  "dependencies": {
39
- "scriptc": "0.0.22"
39
+ "scriptc": "0.0.31"
40
40
  }
41
41
  }
@@ -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,78 @@
1
+ #!/usr/bin/env node
2
+ // Flatten a static archive whose members include nested archives into one
3
+ // plain object archive.
4
+ //
5
+ // Zig's ELF static-library emission stores `.a` link inputs as archive
6
+ // MEMBERS instead of merging their objects (Mach-O emission merges), so an
7
+ // Android embed library carrying compiled TypeScript core/service archives
8
+ // would hand the NDK linker nested blobs it skips with a warning. This
9
+ // driver extracts every member with the supplied zig's llvm-ar (GNU
10
+ // long-name members included — the reason system `ar` on macOS is not an
11
+ // option), recurses into nested archives, and re-archives the objects with
12
+ // a fresh symbol index.
13
+ //
14
+ // node merge_static_archives.mjs --zig <zig-exe> --format <gnu|darwin>
15
+ // --out <file.a> --in <file.a> [--in <file.a> ...]
16
+
17
+ import { spawnSync } from "node:child_process";
18
+ import fs from "node:fs";
19
+ import os from "node:os";
20
+ import path from "node:path";
21
+
22
+ const args = { in: [] };
23
+ for (let i = 2; i < process.argv.length; i += 2) {
24
+ const key = process.argv[i];
25
+ const value = process.argv[i + 1];
26
+ if (!key?.startsWith("--") || value === undefined) {
27
+ console.error("usage: merge_static_archives.mjs --zig <zig-exe> --format <gnu|darwin> --out <file.a> --in <file.a> [--in ...]");
28
+ process.exit(2);
29
+ }
30
+ if (key === "--in") args.in.push(path.resolve(value));
31
+ else args[key.slice(2)] = value;
32
+ }
33
+ for (const required of ["zig", "format", "out"]) {
34
+ if (!args[required]) {
35
+ console.error(`merge_static_archives.mjs: missing --${required}`);
36
+ process.exit(2);
37
+ }
38
+ }
39
+ if (args.in.length === 0) {
40
+ console.error("merge_static_archives.mjs: supply at least one --in archive");
41
+ process.exit(2);
42
+ }
43
+ args.out = path.resolve(args.out);
44
+
45
+ function ar(arArgs) {
46
+ const result = spawnSync(args.zig, ["ar", ...arArgs], { encoding: "utf8" });
47
+ if (result.status !== 0) {
48
+ console.error(`merge_static_archives.mjs: zig ar ${arArgs[0]} failed:\n${result.stderr ?? ""}`);
49
+ process.exit(result.status ?? 1);
50
+ }
51
+ }
52
+
53
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), "native-merge-archives-"));
54
+ try {
55
+ const objects = [];
56
+ let extraction = 0;
57
+ const extract = (archive) => {
58
+ const dir = path.join(work, String(extraction));
59
+ extraction += 1;
60
+ fs.mkdirSync(dir);
61
+ ar(["x", `--output=${dir}`, archive]);
62
+ for (const name of fs.readdirSync(dir)) {
63
+ const member = path.join(dir, name);
64
+ if (name.endsWith(".a")) extract(member);
65
+ else objects.push(member);
66
+ }
67
+ };
68
+ for (const input of args.in) extract(input);
69
+ if (objects.length === 0) {
70
+ console.error("merge_static_archives.mjs: the input archives contain no objects");
71
+ process.exit(1);
72
+ }
73
+ fs.mkdirSync(path.dirname(args.out), { recursive: true });
74
+ fs.rmSync(args.out, { force: true });
75
+ ar(["rcs", `--format=${args.format}`, args.out, ...objects]);
76
+ } finally {
77
+ fs.rmSync(work, { recursive: true, force: true });
78
+ }
@@ -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");