@native-sdk/cli 0.4.4 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/build/app.zig +371 -5
  2. package/build/ts_run.mjs +102 -0
  3. package/build.zig +255 -1
  4. package/build.zig.zon +1 -0
  5. package/package.json +19 -10
  6. package/packages/core/package-lock.json +44 -0
  7. package/packages/core/package.json +38 -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 +546 -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/platform/windows/webview2_host.cpp +24 -0
  33. package/src/primitives/app_manifest/comptime_scene.zig +341 -0
  34. package/src/primitives/app_manifest/root.zig +5 -0
  35. package/src/primitives/canvas/commands.zig +14 -7
  36. package/src/primitives/canvas/layout_audit.zig +5 -5
  37. package/src/primitives/canvas/lazy_tls.zig +73 -0
  38. package/src/primitives/canvas/render_generic_resources.zig +22 -15
  39. package/src/primitives/canvas/root.zig +11 -0
  40. package/src/primitives/canvas/tests.zig +1 -0
  41. package/src/primitives/canvas/text_atlas.zig +40 -32
  42. package/src/primitives/canvas/text_layout_cache.zig +29 -22
  43. package/src/primitives/canvas/text_measure_cache.zig +56 -41
  44. package/src/primitives/canvas/text_spans.zig +39 -26
  45. package/src/primitives/canvas/tokens.zig +69 -0
  46. package/src/primitives/canvas/ui.zig +125 -0
  47. package/src/primitives/canvas/ui_markup.zig +22 -3
  48. package/src/primitives/canvas/ui_markup_compiled.zig +97 -7
  49. package/src/primitives/canvas/ui_markup_compiled_tests.zig +275 -0
  50. package/src/primitives/canvas/ui_markup_contract.zig +68 -14
  51. package/src/primitives/canvas/ui_markup_contract_tests.zig +257 -2
  52. package/src/primitives/canvas/ui_markup_reflect.zig +214 -0
  53. package/src/primitives/canvas/ui_markup_view.zig +105 -1
  54. package/src/primitives/canvas/ui_markup_view_tests.zig +336 -0
  55. package/src/primitives/canvas/ui_schema.zig +8 -0
  56. package/src/primitives/canvas/ui_schema_tests.zig +5 -4
  57. package/src/primitives/canvas/widget_builtin_tests.zig +309 -5
  58. package/src/primitives/canvas/widget_invalidation.zig +14 -7
  59. package/src/primitives/canvas/widget_layout.zig +138 -2
  60. package/src/primitives/canvas/widget_metrics.zig +16 -8
  61. package/src/primitives/canvas/widget_render.zig +25 -15
  62. package/src/primitives/canvas/widget_render_controls.zig +15 -9
  63. package/src/primitives/canvas/widget_runtime_tests.zig +44 -0
  64. package/src/root.zig +7 -0
  65. package/src/runtime/canvas_frame.zig +57 -36
  66. package/src/runtime/canvas_images.zig +9 -3
  67. package/src/runtime/canvas_widget_control_tests.zig +5 -6
  68. package/src/runtime/canvas_widget_runtime.zig +7 -4
  69. package/src/runtime/core.zig +16 -0
  70. package/src/runtime/effects.zig +1525 -133
  71. package/src/runtime/effects_fetch_tests.zig +42 -0
  72. package/src/runtime/effects_file_tests.zig +220 -0
  73. package/src/runtime/effects_host_tests.zig +594 -0
  74. package/src/runtime/effects_tests.zig +287 -0
  75. package/src/runtime/root.zig +18 -0
  76. package/src/runtime/session_replay.zig +7 -1
  77. package/src/runtime/tests.zig +2 -0
  78. package/src/runtime/ts_core_host.zig +1505 -0
  79. package/src/runtime/ts_core_host_tests.zig +1408 -0
  80. package/src/runtime/ts_ui_app.zig +469 -0
  81. package/src/runtime/ui_app.zig +189 -38
  82. package/src/runtime/ui_app_tests.zig +221 -0
  83. package/src/runtime/ui_app_window_tests.zig +182 -0
  84. package/src/runtime/view_canvas.zig +24 -17
  85. package/src/runtime/view_widget_tree.zig +2 -2
  86. package/src/tooling/codesign.zig +212 -105
  87. package/src/tooling/doctor.zig +78 -0
  88. package/src/tooling/manifest.zig +47 -0
  89. package/src/tooling/package.zig +435 -20
  90. package/src/tooling/raw_manifest.zig +15 -0
  91. package/src/tooling/root.zig +1 -0
  92. package/src/tooling/templates.zig +777 -34
  93. package/src/tooling/ts_core.zig +1099 -0
  94. package/src/tooling/verbs.zig +105 -2
@@ -0,0 +1,546 @@
1
+ // The TypedAst seam — the ONLY file that imports the type-checker provider.
2
+ //
3
+ // The transpiler needs resolved types (union discrimination, literal types,
4
+ // readonly-ness, symbol resolution, contextual types) but must not couple to
5
+ // a particular checker API: today the provider is the `@typescript/typescript6`
6
+ // compat package (same checker semantics as the author-facing TS7 tsc by
7
+ // upstream design); when the stable Go-native programmatic API ships, only
8
+ // this adapter changes.
9
+ //
10
+ // Surface discipline:
11
+ // - Syntax (node kinds, tree walking) passes through as `ts` — syntax trees
12
+ // are structurally identical across the two providers by design.
13
+ // - Every TYPE question goes through the named queries on `TypedAst` below.
14
+ // Checker/emitter code never touches `program.getTypeChecker()` directly.
15
+
16
+ // The IMPORT deliberately bypasses the `@typescript/typescript6` wrapper
17
+ // (which stays the declared dependency — it is the provider named above,
18
+ // and its own dependency IS this alias): the wrapper's lib/typescript.js
19
+ // re-exports "@typescript/old" resolved from the WRAPPER's location, so a
20
+ // consumer tree already carrying a conflicting hoisted @typescript/old
21
+ // would win node's nearest-wins walk there while our exactly pinned copy
22
+ // sat nested and unused. Importing the alias directly resolves it from
23
+ // THIS file — inside our package, where our own nested/hoisted exact pin
24
+ // is always the nearest — and the CLI's resolution gate additionally
25
+ // verifies the resolved version against the pin.
26
+ import tsImpl from "@typescript/old";
27
+ import path from "node:path";
28
+ import { fileURLToPath } from "node:url";
29
+
30
+ export const ts = tsImpl;
31
+
32
+ /// Absolute path of the SDK directory this package ships (sdk/core.ts and
33
+ /// the transpiled library modules beside it).
34
+ export const sdkModuleDir = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "sdk");
35
+
36
+ /// Absolute path of the SDK module the subset program maps the
37
+ /// "@native-sdk/core" specifier onto (the `Cmd` surface authors import).
38
+ /// This module is INTRINSIC: the transpiler lowers references to it onto
39
+ /// the rt kernel and never emits its code.
40
+ export const sdkCoreModulePath = path.join(sdkModuleDir, "core.ts");
41
+
42
+ /// The SDK LIBRARY modules an app core may import by published name. Unlike
43
+ /// sdk/core.ts these are ordinary subset TypeScript, transpiled into the
44
+ /// emitted core when (and only when) imported — the module-granular
45
+ /// tree-shake. Validated once in this package's CI and re-checked at app
46
+ /// build time (the re-check is cheap: tsc already parses the file for the
47
+ /// program, and a diagnostic pointing into the SDK is an SDK bug by
48
+ /// definition).
49
+ export const sdkLibraryModules: ReadonlyMap<string, string> = new Map([
50
+ ["@native-sdk/core/text", path.join(sdkModuleDir, "text.ts")],
51
+ ["@native-sdk/core/events", path.join(sdkModuleDir, "events.ts")],
52
+ ]);
53
+
54
+ /// The ambient byte-text method surface (declaration merging into
55
+ /// lib.esnext's Uint8Array): part of every core's PROGRAM (an extra root
56
+ /// file, never an importable module), so `draft.toUpperCase()` typechecks
57
+ /// in core compilation exactly as the emitted rt helpers and the devhost
58
+ /// polyfill run it. Outside a core program the methods do not exist —
59
+ /// the surface is core-only by construction.
60
+ export const bytesTextMethodsDts = path.join(sdkModuleDir, "bytes_text_methods.d.ts");
61
+ export type Node = tsImpl.Node;
62
+ export type SourceFile = tsImpl.SourceFile;
63
+ export type Symbol = tsImpl.Symbol;
64
+ export type Type = tsImpl.Type;
65
+ export type Declaration = tsImpl.Declaration;
66
+
67
+ /// The compiler options every app core is checked with (the shipped tsconfig,
68
+ /// spec section 6). Stricter than or equal to TS7's hardened defaults —
69
+ /// except `useUnknownInCatchVariables` (see below), where the subset checker
70
+ /// itself is the stricter authority — so the 6-to-7 provider swap changes no
71
+ /// acceptance decision.
72
+ export function subsetCompilerOptions(): tsImpl.CompilerOptions {
73
+ return {
74
+ strict: true,
75
+ // The one strict-family knob turned OFF: the subset's own checker types
76
+ // a `catch (e)` binding as the core's thrown union (collected from the
77
+ // actual `throw` sites) and validates every use against it, so kind
78
+ // tests narrow with no `as` ceremony — `unknown` would demand the
79
+ // ceremony back while teaching nothing the thrown-shape rules don't.
80
+ useUnknownInCatchVariables: false,
81
+ target: tsImpl.ScriptTarget.ESNext,
82
+ module: tsImpl.ModuleKind.ESNext,
83
+ moduleResolution: tsImpl.ModuleResolutionKind.Bundler,
84
+ lib: ["lib.esnext.d.ts"],
85
+ types: [],
86
+ // The SDK modules ship inside this package; app cores import them by
87
+ // their published names. Absolute mappings so entry files anywhere
88
+ // (tmp dirs, workspaces) resolve the same modules.
89
+ paths: {
90
+ "@native-sdk/core": [sdkCoreModulePath.replace(/\.ts$/, "")],
91
+ ...Object.fromEntries(
92
+ [...sdkLibraryModules].map(([name, p]) => [name, [p.replace(/\.ts$/, "")]]),
93
+ ),
94
+ },
95
+ // Relative imports inside src/ are spelled with their real filename
96
+ // ("./parsers.ts") because the same core runs unmodified under node,
97
+ // whose loader resolves real files, never bare stems.
98
+ allowImportingTsExtensions: true,
99
+ verbatimModuleSyntax: true,
100
+ exactOptionalPropertyTypes: true,
101
+ noFallthroughCasesInSwitch: true,
102
+ isolatedModules: true,
103
+ noEmit: true,
104
+ skipLibCheck: true,
105
+ };
106
+ }
107
+
108
+ export interface UnionMemberInfo {
109
+ /// Discriminant literal of this member for the given tag property, e.g.
110
+ /// "insert_text" for { kind: "insert_text", ... }.
111
+ readonly tag: string;
112
+ /// Non-tag properties, in declaration order.
113
+ readonly fields: readonly PropInfo[];
114
+ readonly declaration: tsImpl.TypeNode;
115
+ }
116
+
117
+ export interface PropInfo {
118
+ readonly name: string;
119
+ readonly optional: boolean;
120
+ readonly readonly: boolean;
121
+ readonly typeNode: tsImpl.TypeNode | undefined;
122
+ readonly declaration: tsImpl.Declaration;
123
+ }
124
+
125
+ export class TypedAst {
126
+ readonly program: tsImpl.Program;
127
+ private readonly checker: tsImpl.TypeChecker;
128
+
129
+ constructor(program: tsImpl.Program) {
130
+ this.program = program;
131
+ this.checker = program.getTypeChecker();
132
+ }
133
+
134
+ /// Author-facing acceptance: the provider's full diagnostics for a file.
135
+ fileDiagnostics(file: SourceFile): readonly tsImpl.Diagnostic[] {
136
+ return tsImpl.getPreEmitDiagnostics(this.program, file);
137
+ }
138
+
139
+ /// Symbol resolution: which declaration an identifier means.
140
+ symbolOf(node: Node): Symbol | undefined {
141
+ return this.checker.getSymbolAtLocation(node);
142
+ }
143
+
144
+ /// The canonical declaration of an identifier/expression's symbol, with
145
+ /// alias (import) indirection resolved.
146
+ declarationOf(node: Node): Declaration | undefined {
147
+ let sym = this.checker.getSymbolAtLocation(node);
148
+ if (!sym) return undefined;
149
+ if (sym.flags & tsImpl.SymbolFlags.Alias) sym = this.checker.getAliasedSymbol(sym);
150
+ return sym.declarations?.[0];
151
+ }
152
+
153
+ /// The underlying declaration an export specifier binds (`export { a }`,
154
+ /// `export { a as b }`, `export { x } from "./m.ts"` alike), with alias
155
+ /// indirection resolved to the real declaration — the flat-namespace
156
+ /// target the exported name binds over.
157
+ exportSpecifierTarget(spec: tsImpl.ExportSpecifier): Declaration | undefined {
158
+ let sym = this.checker.getSymbolAtLocation(spec.propertyName ?? spec.name);
159
+ if (!sym) return undefined;
160
+ if (sym.flags & tsImpl.SymbolFlags.Alias) sym = this.checker.getAliasedSymbol(sym);
161
+ return (sym.valueDeclaration as Declaration | undefined) ?? sym.declarations?.[0];
162
+ }
163
+
164
+ /// Resolved type of an expression position.
165
+ typeOf(node: Node): Type {
166
+ return this.checker.getTypeAtLocation(node);
167
+ }
168
+
169
+ /// The VALUE side of a shorthand property (`{ x }` reads the local/param
170
+ /// `x`): getSymbolAtLocation on the name yields the property symbol, so
171
+ /// the value symbol needs its own query.
172
+ shorthandValueDeclaration(node: tsImpl.ShorthandPropertyAssignment): Declaration | undefined {
173
+ const sym = this.checker.getShorthandAssignmentValueSymbol(node);
174
+ return sym?.declarations?.[0];
175
+ }
176
+
177
+ /// Resolved (contextual) type of an expression — the type the surrounding
178
+ /// position expects, e.g. the annotated interface for an object literal.
179
+ contextualTypeOf(expr: tsImpl.Expression): Type | undefined {
180
+ return this.checker.getContextualType(expr);
181
+ }
182
+
183
+ typeToString(type: Type): string {
184
+ return this.checker.typeToString(type);
185
+ }
186
+
187
+ /// True when the type contains `null` or `undefined` as a union member.
188
+ isNullable(type: Type): boolean {
189
+ if (!type.isUnion()) return (type.flags & (tsImpl.TypeFlags.Null | tsImpl.TypeFlags.Undefined)) !== 0;
190
+ return type.types.some((t) => (t.flags & (tsImpl.TypeFlags.Null | tsImpl.TypeFlags.Undefined)) !== 0);
191
+ }
192
+
193
+ /// Which JS empties (null / undefined) the expression's resolved type
194
+ /// carries. The native optional folds both into one empty, so an empty
195
+ /// TEST (`=== null`, `=== undefined`) is only emittable when the value
196
+ /// carries exactly the tested empty — the emitter's R7c check.
197
+ emptiesOf(node: Node): { null: boolean; undefined: boolean } {
198
+ const t = this.checker.getTypeAtLocation(node);
199
+ const members = t.isUnion() ? t.types : [t];
200
+ return {
201
+ null: members.some((m) => (m.flags & tsImpl.TypeFlags.Null) !== 0),
202
+ undefined: members.some((m) => (m.flags & tsImpl.TypeFlags.Undefined) !== 0),
203
+ };
204
+ }
205
+
206
+ /// True when a callback's resolved return type is boolean-only (every
207
+ /// union member boolean-like). The NS1023 comparator check: a boolean
208
+ /// where JS expects a sign is wrong under node too, so it is taught.
209
+ arrowReturnsBoolean(fn: tsImpl.ArrowFunction | tsImpl.FunctionExpression | tsImpl.FunctionDeclaration): boolean {
210
+ const t = this.checker.getTypeAtLocation(fn);
211
+ const sigs = t.getCallSignatures();
212
+ if (sigs.length === 0) return false;
213
+ const booleanLike = tsImpl.TypeFlags.Boolean | tsImpl.TypeFlags.BooleanLiteral;
214
+ return sigs.every((s) => {
215
+ const ret = s.getReturnType();
216
+ const members = ret.isUnion() ? ret.types : [ret];
217
+ return members.every((m) => (m.flags & booleanLike) !== 0);
218
+ });
219
+ }
220
+
221
+ /// True when the expression's resolved type is Uint8Array (through
222
+ /// aliases like `type Bytes = Uint8Array`).
223
+ isBytesTyped(expr: tsImpl.Expression): boolean {
224
+ const t = this.checker.getTypeAtLocation(expr);
225
+ return t.symbol?.name === "Uint8Array";
226
+ }
227
+
228
+ /// Literal value at a type position (string/number literal types), else null.
229
+ literalValue(type: Type): string | number | null {
230
+ if (type.isStringLiteral()) return type.value;
231
+ if (type.isNumberLiteral()) return type.value;
232
+ return null;
233
+ }
234
+
235
+ /// Union members of a discriminated union type node, with the discriminant
236
+ /// literal of each member for the given tag property. Returns null when the
237
+ /// node is not a union of object types each carrying a literal tag.
238
+ discriminatedUnionMembers(node: tsImpl.TypeNode, tagName: string): UnionMemberInfo[] | null {
239
+ if (!tsImpl.isUnionTypeNode(node)) return null;
240
+ const members: UnionMemberInfo[] = [];
241
+ for (const member of node.types) {
242
+ if (!tsImpl.isTypeLiteralNode(member)) return null;
243
+ let tag: string | null = null;
244
+ const fields: PropInfo[] = [];
245
+ for (const prop of member.members) {
246
+ if (!tsImpl.isPropertySignature(prop) || !prop.name || !tsImpl.isIdentifier(prop.name)) return null;
247
+ const name = prop.name.text;
248
+ if (name === tagName) {
249
+ if (!prop.type) return null;
250
+ const t = this.checker.getTypeFromTypeNode(prop.type);
251
+ const value = this.literalValue(t);
252
+ if (typeof value !== "string") return null;
253
+ tag = value;
254
+ continue;
255
+ }
256
+ fields.push({
257
+ name,
258
+ optional: prop.questionToken !== undefined,
259
+ readonly: hasReadonlyModifier(prop),
260
+ typeNode: prop.type,
261
+ declaration: prop,
262
+ });
263
+ }
264
+ if (tag === null) return null;
265
+ members.push({ tag, fields, declaration: member });
266
+ }
267
+ return members;
268
+ }
269
+
270
+ /// String-literal union members of a type alias node (e.g. Filter), in
271
+ /// declaration order; null when the node is not a pure string-literal union.
272
+ stringLiteralUnionMembers(node: tsImpl.TypeNode): string[] | null {
273
+ if (!tsImpl.isUnionTypeNode(node)) return null;
274
+ const out: string[] = [];
275
+ for (const member of node.types) {
276
+ if (!tsImpl.isLiteralTypeNode(member) || !tsImpl.isStringLiteral(member.literal)) return null;
277
+ out.push(member.literal.text);
278
+ }
279
+ return out;
280
+ }
281
+
282
+ /// Number-literal union members (e.g. 0 | 1 | 2), else null.
283
+ numberLiteralUnionMembers(node: tsImpl.TypeNode): number[] | null {
284
+ if (!tsImpl.isUnionTypeNode(node)) return null;
285
+ const out: number[] = [];
286
+ for (const member of node.types) {
287
+ if (!tsImpl.isLiteralTypeNode(member) || !tsImpl.isNumericLiteral(member.literal)) return null;
288
+ out.push(Number(member.literal.text));
289
+ }
290
+ return out;
291
+ }
292
+
293
+ /// Properties of an interface declaration, in declaration order.
294
+ propsOfInterface(decl: tsImpl.InterfaceDeclaration): PropInfo[] {
295
+ const out: PropInfo[] = [];
296
+ for (const member of decl.members) {
297
+ if (!tsImpl.isPropertySignature(member) || !member.name || !tsImpl.isIdentifier(member.name)) continue;
298
+ out.push({
299
+ name: member.name.text,
300
+ optional: member.questionToken !== undefined,
301
+ readonly: hasReadonlyModifier(member),
302
+ typeNode: member.type,
303
+ declaration: member,
304
+ });
305
+ }
306
+ return out;
307
+ }
308
+
309
+ /// tsc's own assignability relation — thrown values checked against the
310
+ /// core's declared error shape (the catch assertion's type node).
311
+ isAssignableToNode(expr: tsImpl.Expression, typeNode: tsImpl.TypeNode): boolean {
312
+ const src = this.checker.getTypeAtLocation(expr);
313
+ const dst = this.checker.getTypeFromTypeNode(typeNode);
314
+ return this.checker.isTypeAssignableTo(src, dst);
315
+ }
316
+
317
+ /// Fields of a data-class declaration (annotated property declarations),
318
+ /// in declaration order — the struct layout `new` constructs.
319
+ propsOfClass(decl: tsImpl.ClassDeclaration): PropInfo[] {
320
+ const out: PropInfo[] = [];
321
+ for (const member of decl.members) {
322
+ if (!tsImpl.isPropertyDeclaration(member) || !member.name || !tsImpl.isIdentifier(member.name)) continue;
323
+ // `static` fields are per-class module consts, never instance layout.
324
+ if ((tsImpl.getModifiers(member) ?? []).some((m) => m.kind === tsImpl.SyntaxKind.StaticKeyword)) continue;
325
+ out.push({
326
+ name: member.name.text,
327
+ optional: member.questionToken !== undefined,
328
+ readonly: hasReadonlyModifier(member),
329
+ typeNode: member.type,
330
+ declaration: member,
331
+ });
332
+ }
333
+ return out;
334
+ }
335
+
336
+ /// Const-evaluability: fold an expression of literals and module constants
337
+ /// to a number, else null. This is the transpiler's comptime surface for
338
+ /// numeric module constants.
339
+ constEvalNumber(expr: tsImpl.Expression): number | null {
340
+ if (tsImpl.isNumericLiteral(expr)) return Number(expr.text);
341
+ if (tsImpl.isParenthesizedExpression(expr)) return this.constEvalNumber(expr.expression);
342
+ if (tsImpl.isPrefixUnaryExpression(expr) && expr.operator === tsImpl.SyntaxKind.MinusToken) {
343
+ const inner = this.constEvalNumber(expr.operand);
344
+ return inner === null ? null : -inner;
345
+ }
346
+ if (tsImpl.isBinaryExpression(expr)) {
347
+ const l = this.constEvalNumber(expr.left);
348
+ const r = this.constEvalNumber(expr.right);
349
+ if (l === null || r === null) return null;
350
+ switch (expr.operatorToken.kind) {
351
+ case tsImpl.SyntaxKind.PlusToken: return l + r;
352
+ case tsImpl.SyntaxKind.MinusToken: return l - r;
353
+ case tsImpl.SyntaxKind.AsteriskToken: return l * r;
354
+ case tsImpl.SyntaxKind.SlashToken: return l / r;
355
+ case tsImpl.SyntaxKind.PercentToken: return l % r;
356
+ // The host IS a JS engine, so these fold to their exact JS values
357
+ // (`**` right-associates with the JS pow corners; shifts apply
358
+ // ToInt32/ToUint32 with the count masked & 31).
359
+ case tsImpl.SyntaxKind.AsteriskAsteriskToken: return l ** r;
360
+ case tsImpl.SyntaxKind.LessThanLessThanToken: return l << r;
361
+ case tsImpl.SyntaxKind.GreaterThanGreaterThanToken: return l >> r;
362
+ case tsImpl.SyntaxKind.GreaterThanGreaterThanGreaterThanToken: return l >>> r;
363
+ default: return null;
364
+ }
365
+ }
366
+ // Math.<fn>(consts) folds through the host JS Math — by definition the
367
+ // JS value, NaN/Infinity/-0 corners included.
368
+ if (
369
+ tsImpl.isCallExpression(expr) &&
370
+ tsImpl.isPropertyAccessExpression(expr.expression) &&
371
+ tsImpl.isIdentifier(expr.expression.expression) &&
372
+ expr.expression.expression.text === "Math"
373
+ ) {
374
+ const fn = comptimeMathFns.get(expr.expression.name.text);
375
+ if (!fn) return null;
376
+ const args: number[] = [];
377
+ for (const a of expr.arguments) {
378
+ const v = this.constEvalNumber(a);
379
+ if (v === null) return null;
380
+ args.push(v);
381
+ }
382
+ return fn(...args);
383
+ }
384
+ if (tsImpl.isIdentifier(expr)) {
385
+ // The NaN/Infinity globals (a shadowing declaration in the module
386
+ // itself does not count — same rule as the emitter's `undefined`).
387
+ if (expr.text === "NaN" || expr.text === "Infinity") {
388
+ const decl = this.declarationOf(expr);
389
+ if (!decl || decl.getSourceFile() !== expr.getSourceFile()) {
390
+ return expr.text === "NaN" ? NaN : Infinity;
391
+ }
392
+ }
393
+ const decl = this.declarationOf(expr);
394
+ if (decl && tsImpl.isVariableDeclaration(decl) && decl.initializer &&
395
+ (tsImpl.getCombinedNodeFlags(decl) & tsImpl.NodeFlags.Const) !== 0) {
396
+ return this.constEvalNumber(decl.initializer);
397
+ }
398
+ }
399
+ return null;
400
+ }
401
+
402
+ /// Declaration of the property a literal's member assigns to, resolved via
403
+ /// the contextual (expected) type of the enclosing object literal.
404
+ contextualPropDecl(prop: tsImpl.PropertyAssignment): Declaration | undefined {
405
+ const objLit = prop.parent;
406
+ if (!tsImpl.isObjectLiteralExpression(objLit)) return undefined;
407
+ let contextual = this.checker.getContextualType(objLit);
408
+ if (!contextual || !prop.name || !tsImpl.isIdentifier(prop.name)) return undefined;
409
+ // `T | null` contexts: the property lives on the non-null constituent.
410
+ contextual = this.checker.getNonNullableType(contextual);
411
+ // Union contexts (e.g. `Model | [Model, Cmd<Msg>]` return positions):
412
+ // the property lives on whichever constituent carries it.
413
+ if (contextual.isUnion()) {
414
+ for (const member of contextual.types) {
415
+ const sym = member.getProperty(prop.name.text);
416
+ if (sym?.declarations?.[0]) return sym.declarations[0];
417
+ }
418
+ return undefined;
419
+ }
420
+ const sym = contextual.getProperty(prop.name.text);
421
+ return sym?.declarations?.[0];
422
+ }
423
+
424
+ /// Generic instantiation sites for a declaration — the monomorphization
425
+ /// worklist. v1 supports non-generic app cores; the query exists so the
426
+ /// seam is complete, and returns the empty list until generics land.
427
+ genericInstantiations(_decl: Declaration): readonly Type[] {
428
+ return [];
429
+ }
430
+
431
+ /// The resolved type of a TYPE NODE position (`typeof CONST` queries and
432
+ /// generic-argument type nodes resolve through the checker, never by
433
+ /// re-implementing its inference).
434
+ typeFromTypeNode(node: tsImpl.TypeNode): Type {
435
+ return this.checker.getTypeFromTypeNode(node);
436
+ }
437
+
438
+ /// The RESOLVED type arguments of a call to a generic function — tsc's
439
+ /// own signature resolution (explicit arguments and inferred ones alike),
440
+ /// aligned with the callee's type-parameter list. Undefined when the call
441
+ /// does not resolve or resolves without instantiation.
442
+ resolvedCallTypeArguments(call: tsImpl.CallExpression): readonly Type[] | undefined {
443
+ const sig = this.checker.getResolvedSignature(call);
444
+ if (!sig) return undefined;
445
+ return this.checker.getTypeArgumentsForResolvedSignature(sig);
446
+ }
447
+
448
+ /// Type arguments of a resolved reference type (e.g. `readonly T[]`'s
449
+ /// element, a generic interface instantiation's arguments).
450
+ typeArgumentsOf(type: Type): readonly Type[] {
451
+ if ((type.flags & tsImpl.TypeFlags.Object) === 0) return [];
452
+ if (((type as tsImpl.ObjectType).objectFlags & tsImpl.ObjectFlags.Reference) === 0) return [];
453
+ return this.checker.getTypeArguments(type as tsImpl.TypeReference);
454
+ }
455
+
456
+ isArrayLikeType(type: Type): boolean {
457
+ return this.checker.isArrayType(type);
458
+ }
459
+ }
460
+
461
+ /// The Math functions the transpiler folds at compile time (the emitter's
462
+ /// v1 Math surface; Math.random is banned by NS1005 and never reaches here).
463
+ const comptimeMathFns = new Map<string, (...args: number[]) => number>([
464
+ ["floor", Math.floor],
465
+ ["ceil", Math.ceil],
466
+ ["trunc", Math.trunc],
467
+ ["abs", Math.abs],
468
+ ["sign", Math.sign],
469
+ ["sqrt", Math.sqrt],
470
+ ["round", Math.round],
471
+ ["min", Math.min],
472
+ ["max", Math.max],
473
+ ]);
474
+
475
+ export function hasReadonlyModifier(node: tsImpl.PropertySignature | tsImpl.PropertyDeclaration): boolean {
476
+ return node.modifiers?.some((m) => m.kind === tsImpl.SyntaxKind.ReadonlyKeyword) ?? false;
477
+ }
478
+
479
+ export function hasExportModifier(node: tsImpl.Node): boolean {
480
+ const mods = (node as { modifiers?: readonly tsImpl.ModifierLike[] }).modifiers;
481
+ return mods?.some((m) => m.kind === tsImpl.SyntaxKind.ExportKeyword) ?? false;
482
+ }
483
+
484
+ /// One VALUE binding an export list creates: `export { a }` binds `a`,
485
+ /// `export { a as b }` binds `b`, and `export { x } from "./m.ts"` binds `x`
486
+ /// over another module's declaration. Type-only statements and specifiers
487
+ /// (`export type { T }`, `export { type T }`) never appear here — they erase.
488
+ export interface ExportListBinding {
489
+ /// The name the binding is exported under (`b` in `export { a as b }`).
490
+ readonly exportedName: string;
491
+ /// The exported-name node, for diagnostics.
492
+ readonly nameNode: tsImpl.ModuleExportName;
493
+ readonly spec: tsImpl.ExportSpecifier;
494
+ /// Whether the exported name differs from the target declaration's own
495
+ /// name (a renamed export binds a NEW name over the declaration).
496
+ readonly renamed: boolean;
497
+ /// Whether the list re-exports from another module (`export ... from`).
498
+ readonly reExport: boolean;
499
+ /// The resolved underlying declaration, alias indirection included; the
500
+ /// checker teaches when this is missing or outside the core's modules.
501
+ readonly target: Declaration | undefined;
502
+ }
503
+
504
+ /// The value bindings of every export list in a file, in source order.
505
+ export function exportListBindings(tast: TypedAst, file: SourceFile): ExportListBinding[] {
506
+ const out: ExportListBinding[] = [];
507
+ for (const stmt of file.statements) {
508
+ if (!tsImpl.isExportDeclaration(stmt) || stmt.isTypeOnly) continue;
509
+ if (!stmt.exportClause || !tsImpl.isNamedExports(stmt.exportClause)) continue;
510
+ for (const spec of stmt.exportClause.elements) {
511
+ if (spec.isTypeOnly) continue;
512
+ const target = tast.exportSpecifierTarget(spec);
513
+ const targetName =
514
+ target && tsImpl.isFunctionDeclaration(target)
515
+ ? target.name?.text
516
+ : target && (tsImpl.isVariableDeclaration(target) || tsImpl.isClassDeclaration(target)) && target.name && tsImpl.isIdentifier(target.name)
517
+ ? target.name.text
518
+ : target && (tsImpl.isInterfaceDeclaration(target) || tsImpl.isTypeAliasDeclaration(target))
519
+ ? target.name.text
520
+ : undefined;
521
+ const exportedName = spec.name.text;
522
+ out.push({
523
+ exportedName,
524
+ nameNode: spec.name,
525
+ spec,
526
+ renamed: targetName !== undefined && targetName !== exportedName,
527
+ reExport: stmt.moduleSpecifier !== undefined,
528
+ target,
529
+ });
530
+ }
531
+ }
532
+ return out;
533
+ }
534
+
535
+ export function lineColumn(file: SourceFile, pos: number): { line: number; column: number } {
536
+ const lc = file.getLineAndCharacterOfPosition(pos);
537
+ return { line: lc.line + 1, column: lc.character + 1 };
538
+ }
539
+
540
+ /// Build a checked program rooted at the app-core entry file. tsc resolves
541
+ /// the whole import graph from it (relative modules under src/, the SDK
542
+ /// modules by their published names), so a multi-file core needs no extra
543
+ /// root names; modules.ts validates the graph's boundaries first.
544
+ export function createSubsetProgram(entry: string): tsImpl.Program {
545
+ return tsImpl.createProgram([entry, bytesTextMethodsDts], subsetCompilerOptions());
546
+ }