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