@native-sdk/cli 0.4.4 → 0.5.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 (83) hide show
  1. package/build/app.zig +187 -6
  2. package/build/ts_run.mjs +63 -0
  3. package/build.zig +213 -1
  4. package/build.zig.zon +1 -0
  5. package/package.json +15 -10
  6. package/packages/core/package-lock.json +43 -0
  7. package/packages/core/package.json +37 -0
  8. package/packages/core/rt/rt.zig +1579 -0
  9. package/packages/core/sdk/bytes_text_methods.d.ts +88 -0
  10. package/packages/core/sdk/core.ts +694 -0
  11. package/packages/core/sdk/events.ts +137 -0
  12. package/packages/core/sdk/text.ts +519 -0
  13. package/packages/core/src/checker.ts +1869 -0
  14. package/packages/core/src/cli.ts +68 -0
  15. package/packages/core/src/devhost.ts +291 -0
  16. package/packages/core/src/devhost_resolver.mjs +22 -0
  17. package/packages/core/src/diagnostics.ts +417 -0
  18. package/packages/core/src/emitter.ts +8815 -0
  19. package/packages/core/src/infer.ts +1515 -0
  20. package/packages/core/src/modules.ts +173 -0
  21. package/packages/core/src/ownership.ts +740 -0
  22. package/packages/core/src/text_polyfill.ts +337 -0
  23. package/packages/core/src/text_tables.ts +408 -0
  24. package/packages/core/src/transpile.ts +146 -0
  25. package/packages/core/src/typed_ast.ts +536 -0
  26. package/packages/core/src/types.ts +815 -0
  27. package/skill-data/native-ui/SKILL.md +14 -0
  28. package/skill-data/ts-core/SKILL.md +493 -0
  29. package/skill-data/zig/SKILL.md +10 -0
  30. package/src/app_runner/root.zig +24 -0
  31. package/src/app_runner/ts_core_main.zig +231 -0
  32. package/src/primitives/app_manifest/comptime_scene.zig +341 -0
  33. package/src/primitives/app_manifest/root.zig +5 -0
  34. package/src/primitives/canvas/commands.zig +14 -7
  35. package/src/primitives/canvas/lazy_tls.zig +73 -0
  36. package/src/primitives/canvas/render_generic_resources.zig +22 -15
  37. package/src/primitives/canvas/root.zig +6 -0
  38. package/src/primitives/canvas/tests.zig +1 -0
  39. package/src/primitives/canvas/text_atlas.zig +40 -32
  40. package/src/primitives/canvas/text_layout_cache.zig +29 -22
  41. package/src/primitives/canvas/text_measure_cache.zig +56 -41
  42. package/src/primitives/canvas/text_spans.zig +39 -26
  43. package/src/primitives/canvas/tokens.zig +54 -0
  44. package/src/primitives/canvas/ui.zig +125 -0
  45. package/src/primitives/canvas/ui_markup.zig +22 -3
  46. package/src/primitives/canvas/ui_markup_compiled.zig +97 -7
  47. package/src/primitives/canvas/ui_markup_compiled_tests.zig +275 -0
  48. package/src/primitives/canvas/ui_markup_contract.zig +68 -14
  49. package/src/primitives/canvas/ui_markup_contract_tests.zig +257 -2
  50. package/src/primitives/canvas/ui_markup_reflect.zig +214 -0
  51. package/src/primitives/canvas/ui_markup_view.zig +105 -1
  52. package/src/primitives/canvas/ui_markup_view_tests.zig +336 -0
  53. package/src/primitives/canvas/ui_schema.zig +8 -0
  54. package/src/primitives/canvas/ui_schema_tests.zig +5 -4
  55. package/src/primitives/canvas/widget_invalidation.zig +14 -7
  56. package/src/primitives/canvas/widget_render.zig +25 -15
  57. package/src/primitives/canvas/widget_render_controls.zig +15 -9
  58. package/src/primitives/canvas/widget_runtime_tests.zig +44 -0
  59. package/src/root.zig +7 -0
  60. package/src/runtime/canvas_frame.zig +57 -36
  61. package/src/runtime/canvas_images.zig +9 -3
  62. package/src/runtime/canvas_widget_control_tests.zig +5 -6
  63. package/src/runtime/canvas_widget_runtime.zig +7 -4
  64. package/src/runtime/effects.zig +490 -2
  65. package/src/runtime/effects_host_tests.zig +594 -0
  66. package/src/runtime/root.zig +18 -0
  67. package/src/runtime/session_replay.zig +7 -1
  68. package/src/runtime/tests.zig +2 -0
  69. package/src/runtime/ts_core_host.zig +1505 -0
  70. package/src/runtime/ts_core_host_tests.zig +1408 -0
  71. package/src/runtime/ts_ui_app.zig +469 -0
  72. package/src/runtime/ui_app.zig +58 -0
  73. package/src/runtime/view_canvas.zig +24 -17
  74. package/src/runtime/view_widget_tree.zig +2 -2
  75. package/src/tooling/codesign.zig +212 -105
  76. package/src/tooling/doctor.zig +78 -0
  77. package/src/tooling/manifest.zig +47 -0
  78. package/src/tooling/package.zig +124 -12
  79. package/src/tooling/raw_manifest.zig +15 -0
  80. package/src/tooling/root.zig +1 -0
  81. package/src/tooling/templates.zig +683 -28
  82. package/src/tooling/ts_core.zig +486 -0
  83. package/src/tooling/verbs.zig +17 -0
@@ -0,0 +1,417 @@
1
+ // Teaching diagnostics for the app-core subset checker.
2
+ //
3
+ // Every rule speaks in three parts, in order: the rule, the fix, the reason.
4
+ // No diagnostic may say only "not allowed in the subset" — if a rule cannot
5
+ // explain itself in one sentence it does not ship.
6
+
7
+ export interface SubsetDiagnostic {
8
+ readonly id: string;
9
+ readonly title: string;
10
+ readonly message: string;
11
+ readonly file: string;
12
+ readonly line: number; // 1-based
13
+ readonly column: number; // 1-based
14
+ }
15
+
16
+ export interface RuleCopy {
17
+ readonly id: string;
18
+ readonly title: string;
19
+ /// `fix` and `why` are joined after the site-specific lead-in.
20
+ readonly fix: string;
21
+ readonly why: string;
22
+ }
23
+
24
+ export const rules = {
25
+ NS1001: {
26
+ id: "NS1001",
27
+ title: "shared data is immutable; your own scratch is yours",
28
+ fix: "Build the next value instead (`{ ...model, tasks: [...model.tasks, task] }`), or take a copy you own first (`const copy = xs.slice();`) — arrays this function creates itself (literals, `.slice()`/`.map()`/`.filter()`/`.concat()`/`.toSorted()` copies) mutate freely until they escape, `xs[xs.length] = v` appends like `.push`, a `let` whose EVERY assignment is a fresh construction stays owned, and passing to a `readonly T[]` parameter of a reading helper keeps ownership.",
29
+ why: "The previous model stays live for rendering and undo, and a caller's array outlives the call; native builds share unchanged parts without copying, so the immutable style is not slower — while a locally-created array has exactly one holder, which is what makes mutating it deterministic and safe.",
30
+ },
31
+ NS1002: {
32
+ id: "NS1002",
33
+ title: "updates are synchronous",
34
+ fix: "Return the work as a command: `[model, Cmd.host(\"fetch_profile\", userId)]`.",
35
+ why: "The runtime performs the effect after commit and dispatches your message with the result.",
36
+ },
37
+ NS1003: {
38
+ id: "NS1003",
39
+ title: "models hold data, not functions",
40
+ fix: "Name the behavior as a message (`{ kind: \"tick\" }`) and handle it in update.",
41
+ why: "The model is data; commit walkers cannot (and should not) copy closures.",
42
+ },
43
+ NS1004: {
44
+ id: "NS1004",
45
+ title: "text is not indexable",
46
+ fix: "Store text as `Uint8Array` bytes and index those; turn literals and templates into bytes with the `asciiBytes` intrinsic from \"@native-sdk/core\".",
47
+ why: "Code-unit reads behave differently in JS (UTF-16) and native (UTF-8); with them gone the encodings are indistinguishable.",
48
+ },
49
+ NS1005: {
50
+ id: "NS1005",
51
+ title: "update is deterministic",
52
+ fix: "Take the value as input instead: time via `[model, Cmd.now(\"tick\")]`; randomness rides in as a Msg payload from the host.",
53
+ why: "Ambient time, randomness, and I/O make replay and testing lie.",
54
+ },
55
+ NS1006: {
56
+ id: "NS1006",
57
+ title: "classes are data classes, declared at module level",
58
+ fix: "Declare the class at module level — annotated fields, one constructor, plain methods (`class Task { title: Uint8Array; constructor(...) {...} rename(...) {...} }`) — and construct it with `new Task(...)`; everything else stays records and functions.",
59
+ why: "A data class emits as a plain struct plus module-level functions; a class expression, a `this` outside a member body, or `new` of an arbitrary expression would need runtime prototypes and object identity the fixed native layout does not carry.",
60
+ },
61
+ NS1007: {
62
+ id: "NS1007",
63
+ title: "implicit builtin throws stay out",
64
+ fix: "Give the operation its explicit form (`.reduce(f, init)` — the starting accumulator makes the empty array well-defined); your own `throw` of a subset value is supported, deterministic control flow.",
65
+ why: "JS builtins throw engine TypeError objects mid-operation; a user `throw` carries a subset value the native payload slot can hold, but a builtin's implicit throw has no such value and no native mapping.",
66
+ },
67
+ NS1008: {
68
+ id: "NS1008",
69
+ title: "only erasable TypeScript syntax compiles",
70
+ fix: "Replace `enum` with a string-literal union; drop namespaces, decorators, and parameter properties.",
71
+ why: "The same file must run unmodified under node (`erasableSyntaxOnly`); these constructs generate code.",
72
+ },
73
+ NS1009: {
74
+ id: "NS1009",
75
+ title: "for/in does not compile",
76
+ fix: "Model the data as an array and walk it with a classic `for (let i = 0; ...)` loop.",
77
+ why: "`for`/`in` walks the prototype chain; the subset has fixed shapes and no prototypes.",
78
+ },
79
+ NS1010: {
80
+ id: "NS1010",
81
+ title: "module state lives in the Model",
82
+ fix: "Move the mutable value into the Model and update it through messages; module-level `const` is fine.",
83
+ why: "Mutable globals escape the dispatch/commit lifecycle and break replay.",
84
+ },
85
+ NS1011: {
86
+ id: "NS1011",
87
+ title: "Map and Set are not part of v1",
88
+ fix: "Model the data as an id-keyed array of records (`readonly Item[]` with a `readonly id: number` field) and look items up with a loop or `.filter`.",
89
+ why: "Hashed containers need identity and hashing machinery the commit walkers do not carry in v1; id-keyed arrays give the same access pattern with plain data.",
90
+ },
91
+ NS1012: {
92
+ id: "NS1012",
93
+ title: "object shapes are fixed",
94
+ fix: "Model optional data with `T | null` fields; build new objects instead of deleting fields.",
95
+ why: "Sparse arrays, `delete`, getters/setters, `Proxy`, and `Symbol` break the fixed native layouts the compiler emits.",
96
+ },
97
+ NS1013: {
98
+ id: "NS1013",
99
+ title: "app cores are a closed world",
100
+ fix: "Remove `eval` / `new Function` / dynamic `import()`; express the logic as ordinary functions.",
101
+ why: "No JS engine ships in the binary, so code cannot be created at runtime.",
102
+ },
103
+ NS1014: {
104
+ id: "NS1014",
105
+ title: "the core's entry points live in core.ts",
106
+ fix: "Move this export into src/core.ts (imported modules may hold the helpers it calls and the types it uses).",
107
+ why: "The build wires `update`, `initialModel`, `subscriptions`, the host-event channels, and `viewUnbound` from the entry module only, so an entry export in an imported file would be silently ignored.",
108
+ },
109
+ NS1015: {
110
+ id: "NS1015",
111
+ title: "exhaustive switch required on message unions",
112
+ fix: "Add a case for every `kind` (no `default` needed once all arms are present).",
113
+ why: "Exhaustiveness is what lets the compiler emit a closed native switch with no fallback path.",
114
+ },
115
+ NS1016: {
116
+ id: "NS1016",
117
+ title: "integer and fractional values cannot share a number slot",
118
+ fix: "Split the value into two fields, or keep every value on this path whole (no fractional literals or fractional math flowing into it).",
119
+ why: "Native code gives each `number` slot one machine type; this slot must be an integer where it is used, but a fractional value also flows in, and an integer type cannot hold both.",
120
+ },
121
+ NS1017: {
122
+ id: "NS1017",
123
+ title: "commands are issued in update's return, not stored",
124
+ fix: "Construct the Cmd inline in update's return: `return [next, Cmd.persist()]` (several at once via `Cmd.batch([...])`).",
125
+ why: "A Cmd describes effects for the runtime to perform after this dispatch commits; a command that lives in the model, a message, a local, or a helper escapes the dispatch cycle and breaks replay.",
126
+ },
127
+ NS1018: {
128
+ id: "NS1018",
129
+ title: "text builds with templates and bytes, not +",
130
+ fix: "Build the text as bytes: `asciiBytes(`${count} items`)` from \"@native-sdk/core\", or stitch byte buffers with `new Uint8Array(n)` + `.set`.",
131
+ why: "Runtime string concatenation would need a JS string heap the native binary does not carry; bytes in the frame arena are the one dynamic-text representation.",
132
+ },
133
+ NS1019: {
134
+ id: "NS1019",
135
+ title: "functions have fixed arity",
136
+ fix: "Pass every argument explicitly at every call site: drop parameter defaults (`= value`), rest parameters (`...xs`), `arguments`, and call spreads (`f(...xs)`) — take and pass an array instead.",
137
+ why: "Emitted native functions have exact signatures; a dynamic argument list would be materialized invisibly at each call site, and a missed site diverges from node instead of failing loudly.",
138
+ },
139
+ NS1020: {
140
+ id: "NS1020",
141
+ title: "host command arguments are numbers or one bytes payload",
142
+ fix: "Pass numbers (`Cmd.host(\"beep\", model.count)`), or exactly one payload — a `Uint8Array` or a flat record of number/boolean/`Uint8Array` fields (`Cmd.host(\"save\", model.draft)`).",
143
+ why: "The Cmd wire format encodes f64 scalars or one bytes payload per record; a value smuggled past the type with `as` has no encoding and would corrupt the effect stream.",
144
+ },
145
+ NS1021: {
146
+ id: "NS1021",
147
+ title: "optional chains end in ?? or a value use, not a null test",
148
+ fix: "Normalize with `??` (`model.sel?.tag ?? null`) or guard the base first (`model.sel !== null && model.sel.tag === null`).",
149
+ why: "A short-circuiting `?.` yields JS `undefined` while the field's own empty value is `null`; native folds both into one null, so a null test on the chain would disagree with node.",
150
+ },
151
+ NS1022: {
152
+ id: "NS1022",
153
+ title: "shared arrays sort by copy, not in place",
154
+ fix: "Sort a copy you own — `const copy = xs.slice(); copy.sort((a, b) => a - b);` — or inline with `.toSorted((a, b) => a - b)` and use the returned copy.",
155
+ why: "`.sort()` mutates the array it is called on; model data stays live for rendering and undo, so an in-place sort would corrupt the previous model. A local `.slice()` copy is yours, and sorting it in place is legal.",
156
+ },
157
+ NS1023: {
158
+ id: "NS1023",
159
+ title: "sort comparators return a sign, not a boolean",
160
+ fix: "Return a number whose sign orders the pair: `(a, b) => a - b` for ascending numbers, or explicit -1/0/1 branches.",
161
+ why: "JS reads the comparator numerically — `true` coerces to 1 but `false` coerces to 0, which claims the pair is already ordered, so a boolean comparator leaves data unsorted under node too.",
162
+ },
163
+ NS1024: {
164
+ id: "NS1024",
165
+ title: "model text is bytes",
166
+ fix: "Type the field `Uint8Array` and build its values with the `asciiBytes` intrinsic from \"@native-sdk/core\" (literals and templates fold at compile time), or use a string-literal union (`\"low\" | \"high\"`) when the field holds one of a closed set of tags.",
167
+ why: "A `string` model field would need a JS string heap at every commit; bytes have exactly one representation under node and native, and literal-union tags compile to a native enum.",
168
+ },
169
+ NS1025: {
170
+ id: "NS1025",
171
+ title: "subscriptions are declared in subscriptions' return, not stored",
172
+ fix: "Derive the descriptors from the model and return them from `subscriptions`: `return model.running ? Sub.timer(\"tick\", 1000, \"tick\") : Sub.none;`.",
173
+ why: "A Sub describes recurring effects the host reconciles against the committed model after every dispatch; a descriptor stored in the model, a message, a local, or a helper escapes that reconciliation and breaks replay.",
174
+ },
175
+ NS1026: {
176
+ id: "NS1026",
177
+ title: "host payloads are bytes or a flat scalar record",
178
+ fix: "Pass one `Uint8Array` (build text with `asciiBytes`), or one inline record whose fields are numbers, booleans, or `Uint8Array` values — nothing nested, no extra arguments alongside a payload.",
179
+ why: "A host command carries exactly one bytes payload on the wire; only these field types have a byte encoding that is identical under node and native.",
180
+ },
181
+ NS1027: {
182
+ id: "NS1027",
183
+ title: "effect results route to Msg arms by name",
184
+ fix: "Spell the routing as data — string-literal arm names, optionally keyed: `{ key: \"load\", ok: \"loaded\", err: \"load_failed\" }` — where each named arm carries exactly the payload the effect produces (one `Uint8Array` field for host results; one number field for timer fires).",
185
+ why: "The runtime builds the result Msg itself from the arm's declared shape, so the decoding derives from your types at build time; a callback would run outside the dispatch cycle and could capture state replay cannot see.",
186
+ },
187
+ NS1028: {
188
+ id: "NS1028",
189
+ title: "Cmd.persist is not yet host-backed",
190
+ fix: "Persist app state yourself with `Cmd.writeFile(path, bytes, { ok, err })` and load it back at boot with `Cmd.readFile` from `initialModel`'s command.",
191
+ why: "No shipping host implements the persist verb yet, so the record is performed by nobody — a writeFile you control (own path, own format, a load path) is the persistence real apps use. The op still compiles and stays on the wire for hosts that add the service.",
192
+ },
193
+ NS1029: {
194
+ id: "NS1029",
195
+ title: "effect op arguments have a fixed shape",
196
+ fix: "Spell the op exactly: paths/URLs/bodies are `Uint8Array` (asciiBytes for literals), `method` is one of the closed verb literals, `timeoutMs` is a number literal, and `headers` is an inline flat record whose names are compile-time ASCII and whose values are string literals or `Uint8Array` bytes (`{ accept: \"application/json\", authorization: token }`).",
197
+ why: "Named effect ops encode to a fixed wire record shape at build time — a closed verb set, literal header names, and bytes-typed dynamic fields (URL, body, header values) are what encodes identically under node and native.",
198
+ },
199
+ NS1030: {
200
+ id: "NS1030",
201
+ title: "effect arguments respect the engine's limits",
202
+ fix: "Keep the value inside the engine bound this diagnostic names (shorter path/URL/header block, fewer headers, a delay between 1ms and one year).",
203
+ why: "The host effect engine enforces fixed capacities and would reject the op at runtime through the err arm; a bound that is knowable at compile time should stop the build instead of shipping a guaranteed rejection.",
204
+ },
205
+ NS1031: {
206
+ id: "NS1031",
207
+ title: "exported model helpers join the model's binding surface",
208
+ fix: "Rename the helper or the colliding member so their emitted names differ.",
209
+ why: "An exported helper taking exactly one Model parameter also emits as a Model declaration markup binds by the helper's own name (`doneCount` binds as `{doneCount}`); two members with one emitted name would be ambiguous to every binding engine.",
210
+ },
211
+ NS1032: {
212
+ id: "NS1032",
213
+ title: "viewUnbound names update-only model state",
214
+ fix: "Export a const array of string literals naming Model fields, exported model helpers, or Msg kinds: `export const viewUnbound = [\"nextId\", \"tick\"] as const;`.",
215
+ why: "The list emits as the `view_unbound` opt-out `native check` reads, keeping the unbound-state lint honest for state only update logic touches; a name outside the model surface would silence nothing and hide a typo.",
216
+ },
217
+ NS1033: {
218
+ id: "NS1033",
219
+ title: "wiring channel exports match their host event shapes",
220
+ fix: "Declare the channel exactly: `commandMsg(name: string)` / `keyMsg(key: KeyEvent)` / `frameMsg(model: Model, frame: FrameEvent)` returning `Msg | null`; `export const appearanceMsg = \"<arm>\"` / `chromeMsg = \"<arm>\"` naming a Msg arm with that channel's record shape; `export const envMsgs = [{ env: \"NAME\", msg: \"<arm>\" }] as const` with one-`Uint8Array`-field arms.",
221
+ why: "The generated wiring builds these host events structurally from your declarations at build time (the effects-routing rule applied to the app shell); a wrong shape would otherwise surface as a Zig compile error inside generated code instead of a teaching diagnostic here.",
222
+ },
223
+ NS1034: {
224
+ id: "NS1034",
225
+ title: "core imports stay inside src/",
226
+ fix: "Move the module under the app's src/ directory and import it relatively (`./parsers.ts`, `./util/bytes.ts`).",
227
+ why: "The entry module's directory is the core's whole world — the build ships exactly that tree, so a file above it (`../`) or at an absolute path would exist on your machine but not in the app the build compiles.",
228
+ },
229
+ NS1035: {
230
+ id: "NS1035",
231
+ title: "npm packages do not run inside a core",
232
+ fix: "Vendor the logic as a module under src/ and import it relatively, or make the import type-only (`import type`); only \"@native-sdk/core\" modules carry runtime meaning.",
233
+ why: "No JS engine ships in the binary — an npm package's code has nowhere to run natively, while types erase and cost nothing.",
234
+ },
235
+ NS1036: {
236
+ id: "NS1036",
237
+ title: "core modules do not import in a cycle",
238
+ fix: "Hoist the shared declarations into a module both sides import, or make the back-edge type-only (`import type { Model } from \"./core.ts\"` is fine).",
239
+ why: "A runtime import cycle only works through JS's live-binding indirection, which the emitted native module (and plain reading order) cannot represent; type-only edges erase and are exempt.",
240
+ },
241
+ NS1037: {
242
+ id: "NS1037",
243
+ title: "an import names a real module file",
244
+ fix: "Point the specifier at an existing .ts file, spelled with its extension (`./parsers.ts` — node's module loader resolves real filenames, not bare stems).",
245
+ why: "The import graph is the build's whole input: a specifier that resolves to nothing would fail under node and silently vanish natively.",
246
+ },
247
+ NS1038: {
248
+ id: "NS1038",
249
+ title: "module-scope names are unique across a core's files",
250
+ fix: "Rename one side, or declare the shared thing once and import it where it is used.",
251
+ why: "The core emits as one native module with one namespace: two types (or two exported values) with one name would collide there, and which one markup or a caller meant would be ambiguous.",
252
+ },
253
+ NS1039: {
254
+ id: "NS1039",
255
+ title: "a namespace import is a compile-time alias",
256
+ fix: "Reference members through the alias (`ns.helper(x)`, `ns.Config`) or import them by name; the SDK intrinsics are always named imports — `import { Cmd, Sub, asciiBytes } from \"@native-sdk/core\"`.",
257
+ why: "The core emits as one flat namespace, so `ns` is dot-syntax that erases at build time — it is not an object value that can be stored or passed — and the effect purity rules recognize the SDK factories by their imported names.",
258
+ },
259
+ NS1040: {
260
+ id: "NS1040",
261
+ title: "regular expressions are not part of v1",
262
+ fix: "Scan the bytes with the byte-text methods (`.includes`/`.indexOf`/`.startsWith`/`.split` on `Uint8Array`), a loop, or the SDK text helpers (`containsIgnoreCase` from \"@native-sdk/core/text\").",
263
+ why: "A regex is a runtime engine (backtracking, unicode tables) the native binary does not carry, and it reads text as UTF-16 code units where the core's text is bytes.",
264
+ },
265
+ NS1041: {
266
+ id: "NS1041",
267
+ title: "types are static: no runtime type or shape tests",
268
+ fix: "Model alternatives as a discriminated union and switch on its `kind`; optional data is `T | null` tested against null; walk arrays, not object keys.",
269
+ why: "Emitted values are fixed native layouts with no runtime tags to inspect (a union's `kind` is the one tag that exists), so `typeof`/`in`/`instanceof`/`Object.keys` have nothing to read.",
270
+ },
271
+ NS1042: {
272
+ id: "NS1042",
273
+ title: "generators are not part of v1",
274
+ fix: "Build the sequence as an array — the push-builder (`const out: T[] = []` + `out.push(x)`) or `.map`/`.filter` — and return it whole.",
275
+ why: "A generator is a resumable stack frame with hidden state; the subset's collections are materialized arrays built by pure code, which replay and the commit walkers can see.",
276
+ },
277
+ NS1043: {
278
+ id: "NS1043",
279
+ title: "statements stay statements",
280
+ fix: "Write each step as its own statement. A classic for-loop may step several counters (`i++, j--`), and a number `++`/`--`/assignment may sit in a value position when it is the variable's only mention in the statement and JS cannot skip it (`arr[i++]`, `const n = ++count`); everywhere else a comma hides a statement and `void` manufactures a JS undefined (spell the empty `null`).",
281
+ why: "Comma, `void`, and the mixed read-write forms exist to squeeze statements into expression position; the emitted native code splits them back into statements, which is only JS-order-exact in the pinned positions.",
282
+ },
283
+ NS1044: {
284
+ id: "NS1044",
285
+ title: "BigInt and Symbol are not part of v1",
286
+ fix: "Keep integer math in `number` (exact to 2^53, and integer-classed slots emit as native i64); model identities as number ids.",
287
+ why: "A core's numbers are IEEE f64 slots; arbitrary-precision integers and engine-allocated symbol identities have no native representation.",
288
+ },
289
+ NS1045: {
290
+ id: "NS1045",
291
+ title: "destructuring binds record fields into const locals",
292
+ fix: "Destructure records only: `const { total, done } = stats;` (rename with `{ done: doneCount }`). Bind array elements by index (`const first = xs[0];`), parameters by name, and drop defaults/rest.",
293
+ why: "A record field is always present, so the binding is a compile-time alias; array positions, rest, and defaults can be silently absent in JS (`undefined`), which a bounds-checked native read cannot mean.",
294
+ },
295
+ NS1046: {
296
+ id: "NS1046",
297
+ title: "functions live at module level",
298
+ fix: "Move the function to module scope (or bind it once: `const helper = (x: number): number => ...` — a capture-free const helper hoists) and pass what it captured as parameters; inline arrow callbacks stay where they are — as call arguments (`xs.map((x) => x * 2)`).",
299
+ why: "A nested declaration, a non-const function value, or a `?.()` call treats a function as a runtime value closing over the enclosing frame; emitted native functions are plain module-level code with explicit inputs, so the capture has no representation.",
300
+ },
301
+ NS1047: {
302
+ id: "NS1047",
303
+ title: "modules export their declarations by name",
304
+ fix: "Export by name: `export` on the declaration, an export list (`export { doneCount, helper as visible }`), or a named value re-export (`export { parsePs } from \"./parsers.ts\"`); what stays out is `export default`, `export =`, `export * from`, and bindings over things with no single emitted value (renamed generics/classes, wiring config, names from outside the core).",
305
+ why: "Every consumer — markup bindings, the generated wiring, imports across the core's modules — resolves the flat emitted namespace by NAME: an export list binds real names over real declarations (NS1038 keeps them unique), while a default has no name and a star re-export names nothing.",
306
+ },
307
+ NS1048: {
308
+ id: "NS1048",
309
+ title: "equality is strict",
310
+ fix: "Compare with `===` / `!==`.",
311
+ why: "`==` applies JS's coercion table (\"1\" == 1 is true); the subset's typed values never coerce, so the loose forms are either identical to `===` or depend on string/number coercions that do not exist natively.",
312
+ },
313
+ NS1049: {
314
+ id: "NS1049",
315
+ title: "locals declare with const and let",
316
+ fix: "Replace `var` with `const` (or `let` where the local is reassigned).",
317
+ why: "`var` hoists to function scope and reads as `undefined` before its line — behavior the emitted block-scoped native locals cannot have, so the subset keeps the two forms whose semantics map exactly.",
318
+ },
319
+ NS1050: {
320
+ id: "NS1050",
321
+ title: "generics live on module-level declarations",
322
+ fix: "Make the generic a module-level `function`, `interface`, or `type` (those monomorphize per concrete use — `pick<Task>` emits `pick__Task`); the dispatch entry points (update/initialModel/subscriptions) and function values stay concrete.",
323
+ why: "A monomorphized generic needs a declaration the emitter can instantiate per call site; an entry point has one host-facing ABI signature, and a function value hoists as one concrete fn, so neither can vary by type parameter.",
324
+ },
325
+ NS1051: {
326
+ id: "NS1051",
327
+ title: "a local array is yours until it escapes",
328
+ fix: "Finish mutating before the value escapes: move the mutation above the return/store/call, pass the array only after the last mutation, or mutate inside the callee instead — a call whose parameter is `readonly T[]` and only READS it (no return, no store, no onward pass into a mutable position) is a borrow, not an escape.",
329
+ why: "Once an array is returned, stored, passed where the callee could retain or mutate it, or aliased, other code can hold the same reference; JS would show it your later mutations through that reference, while the native value was shared structurally at the escape — so ownership (and with it mutability) ends there.",
330
+ },
331
+ NS1052: {
332
+ id: "NS1052",
333
+ title: "spread array locals declare their array type",
334
+ fix: "Annotate the local with its array type: `const turns: readonly Turn[] = [...model.turns, next];`.",
335
+ why: "An array literal lowers against a declared slice target (the element type sizes the copy the spread allocates); an un-annotated spread local leaves that type unknown, so the emitter has nothing to lower against.",
336
+ },
337
+ NS1053: {
338
+ id: "NS1053",
339
+ title: "generics instantiate per concrete call site",
340
+ fix: "Give the call site concrete types the emitter can name — resolved records, unions, arrays, optionals, numbers, booleans, or bytes (`pick<Task>(tasks)` or plain inference from typed arguments); a call whose type argument stays abstract (an empty `[]`, an `any`/`unknown`/`never`, an unnamed literal union) needs an annotation or a named alias.",
341
+ why: "A generic helper emits one monomorphic Zig function per distinct instantiation (`pick__Task`, `pick__f64`) from tsc's resolved type arguments; a type argument with no concrete native name has nothing to instantiate against.",
342
+ },
343
+ NS1054: {
344
+ id: "NS1054",
345
+ title: "function values stay local helpers",
346
+ fix: "Bind the function once (`const helper = (x: number): number => x * 2;`), spell its full signature, take everything it needs as parameters (module constants are fine), and use it only by calling it directly or passing it where an inline callback is legal (`xs.map(helper)`).",
347
+ why: "A const-bound, capture-free, fully-annotated function value hoists to an ordinary module-level native function; captures, reassignment, storing or returning the value, and function-typed fields would make it a runtime closure, which has no native representation.",
348
+ },
349
+ NS1055: {
350
+ id: "NS1055",
351
+ title: "classes hold data, not hierarchies",
352
+ fix: "Drop `extends`/`super`/`abstract`: compose (a field holding the other record or class), or model the variants as a `kind`-discriminated union and switch on it.",
353
+ why: "Emitted classes are flat structs with static dispatch; a subclass would need vtables, prototype chains, and layout subtyping that neither the native mapping nor the commit walkers carry.",
354
+ },
355
+ NS1056: {
356
+ id: "NS1056",
357
+ title: "class members are annotated fields, one constructor, and plain methods",
358
+ fix: "Spell state as annotated fields (`count: number = 0`) and behavior as ordinary methods — `static` methods, `static readonly` consts, and erased `private`/`protected` keywords included; replace getters/setters with methods, `#`-privates with `private` (or module boundaries), and use `this` only to reach instance fields and methods (`this.count`, `this.step()` — statics go by the class name: `Task.LIMIT`).",
359
+ why: "A data class emits as a struct plus module-level functions (statics under the class's mangled names); accessors, runtime `#` privacy brands, and a `this` that escapes as a value are prototype/closure machinery with no struct representation — and a record-shaped instance must stay exactly its fields.",
360
+ },
361
+ NS1057: {
362
+ id: "NS1057",
363
+ title: "thrown values are kind-tagged subset shapes",
364
+ fix: "Throw kind-discriminated record values (`throw { kind: \"parse\", at: i } as ParseError;` — several distinct shapes may throw; the checker collects them into the core's thrown union) and read the catch binding in place: test `e.kind` to narrow, read the arm's fields, rethrow bare (`throw e;`), or narrow a single-shape core once with `const err = e as YourError;`.",
365
+ why: "Every `throw` unwinds through one native payload slot typed as the union of the core's thrown shapes, and the `kind` tags are what let a catch narrow that slot exactly — so a thrown value with no subset shape, two shapes sharing one tag, or an error value smuggled out untyped has no sound reading.",
366
+ },
367
+ NS1058: {
368
+ id: "NS1058",
369
+ title: "finally never redirects control flow",
370
+ fix: "Keep `finally` to cleanup statements; move `return`/`break`/`continue`/`throw` decisions into the `try` or `catch` blocks.",
371
+ why: "A `finally` that exits overrides the pending return or exception (JS's own no-unsafe-finally lint rule exists because that is almost always a bug); the native lowering runs finally on every path through a scoped defer, which cannot carry control flow out.",
372
+ },
373
+ NS1059: {
374
+ id: "NS1059",
375
+ title: "arrays build from literals, spreads, and loops",
376
+ fix: "Spell the construction directly: `Array.of(a, b)` is the literal `[a, b]`, `Array.from(xs)` is the spread copy `[...xs]`, and `Array.from({ length: n }, f)` is a classic loop pushing `f(i)` into `const out: T[] = []`.",
377
+ why: "The `Array` statics consume iterables and array-like objects — runtime protocols (`Symbol.iterator`, dynamic `length` probing) the fixed native layouts do not carry — while the literal, spread, and push-builder forms construct the same arrays from data the emitter can see.",
378
+ },
379
+ NS1060: {
380
+ id: "NS1060",
381
+ title: "byte text speaks the byte-honest method set",
382
+ fix: "Use the byte surface: case with `.toUpperCase()`/`.toLowerCase()` (Unicode simple case mapping, locale-free), search with `.includes`/`.indexOf`/`.lastIndexOf`/`.startsWith`/`.endsWith` (bytes needles), measure and pad in bytes (`.length`, `.padStart`), read bytes with `b[i]`/`.at(i)`, and rebuild text with `.split`, slices, and a push-builder.",
383
+ why: "Core text is UTF-8 bytes with exactly one representation under node and native; UTF-16 code-unit reads and Unicode normalization would reintroduce the encoding seam the bytes model exists to close, so their spellings teach the byte-honest form instead.",
384
+ },
385
+ // NS9xxx: internal emit-time verification. A checker gap becomes a loud
386
+ // internal error naming the construct, never silent misbehavior.
387
+ NS9001: {
388
+ id: "NS9001",
389
+ title: "construct not covered by the v1 emitter",
390
+ fix: "Rewrite with the constructs in the subset table, or report this file so the mapping gains a rule.",
391
+ why: "The emitter re-derives every subset rule during emission; anything it cannot prove a mapping for must stop the build.",
392
+ },
393
+ } as const satisfies Record<string, RuleCopy>;
394
+
395
+ export type RuleId = keyof typeof rules;
396
+
397
+ export function formatDiagnostic(d: SubsetDiagnostic, severity: "error" | "warning" = "error"): string {
398
+ return `${d.file}:${d.line}:${d.column} ${severity} ${d.id} ${d.title}\n ${d.message}`;
399
+ }
400
+
401
+ export function makeDiagnostic(
402
+ id: RuleId,
403
+ site: string,
404
+ file: string,
405
+ line: number,
406
+ column: number,
407
+ ): SubsetDiagnostic {
408
+ const rule = rules[id];
409
+ return {
410
+ id: rule.id,
411
+ title: rule.title,
412
+ message: `${site} ${rule.fix} ${rule.why}`,
413
+ file,
414
+ line,
415
+ column,
416
+ };
417
+ }