@nstudio/nativescript-compiler 9.2.0-alpha.10 → 9.2.0-alpha.11

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 (135) hide show
  1. package/dist/api/ir.js +7 -1
  2. package/dist/driver/cli.js +2 -0
  3. package/dist/driver/compile.js +22 -10
  4. package/dist/driver/unimplemented.js +15 -0
  5. package/dist/kotlin/access.js +22 -4
  6. package/dist/kotlin/arguments.js +5 -0
  7. package/dist/kotlin/builtins.js +0 -4
  8. package/dist/kotlin/calls.js +6 -2
  9. package/dist/kotlin/class-methods.js +9 -3
  10. package/dist/kotlin/components.js +13 -8
  11. package/dist/kotlin/core-api.js +2 -13
  12. package/dist/kotlin/declarations.js +2 -0
  13. package/dist/kotlin/expression-statements.js +5 -4
  14. package/dist/kotlin/functions.js +13 -4
  15. package/dist/kotlin/global-calls.js +11 -0
  16. package/dist/kotlin/literals.js +51 -5
  17. package/dist/kotlin/names.js +2 -2
  18. package/dist/kotlin/native/api.js +9 -1
  19. package/dist/kotlin/native/subclasses.js +4 -3
  20. package/dist/kotlin/native/types.js +8 -5
  21. package/dist/kotlin/operators.js +4 -1
  22. package/dist/kotlin/prototype-calls.js +5 -0
  23. package/dist/kotlin/render.js +62 -0
  24. package/dist/kotlin/statements.js +9 -0
  25. package/dist/kotlin/static-calls.js +4 -3
  26. package/dist/kotlin/types.js +6 -6
  27. package/dist/plugins/native-android.js +7 -3
  28. package/dist/plugins/native-ios.js +2 -0
  29. package/dist/plugins/source.js +73 -23
  30. package/dist/program/app-modules.js +91 -16
  31. package/dist/program/app-paths.js +80 -12
  32. package/dist/program/class-mixins.js +463 -0
  33. package/dist/program/core-facts.js +7 -0
  34. package/dist/program/glob.js +274 -0
  35. package/dist/program/platform.js +32 -4
  36. package/dist/program/program.js +212 -20
  37. package/dist/program/source-lines.js +4 -1
  38. package/dist/program/vite-plugins.js +144 -0
  39. package/dist/semantics/apis/globals.js +2 -2
  40. package/dist/semantics/apis/object.js +1 -0
  41. package/dist/semantics/apis/statics.js +6 -0
  42. package/dist/semantics/ast.js +20 -2
  43. package/dist/semantics/classes.js +36 -1
  44. package/dist/semantics/globals.js +3 -0
  45. package/dist/semantics/lang.js +13 -1
  46. package/dist/semantics/nullish.js +29 -11
  47. package/dist/semantics/refuse-receivers.js +3 -3
  48. package/dist/semantics/refuse-scope.js +2 -7
  49. package/dist/semantics/runtime.js +1 -0
  50. package/dist/semantics/states/value-states.js +1 -1
  51. package/dist/semantics/throws.js +1 -0
  52. package/dist/semantics/translator-methods.js +1 -1
  53. package/dist/semantics/types.js +21 -1
  54. package/dist/swift/access.js +25 -10
  55. package/dist/swift/arguments.js +10 -2
  56. package/dist/swift/assignment.js +12 -1
  57. package/dist/swift/builtins.js +0 -4
  58. package/dist/swift/calls.js +6 -2
  59. package/dist/swift/class-methods.js +3 -3
  60. package/dist/swift/components.js +28 -8
  61. package/dist/swift/construction.js +4 -0
  62. package/dist/swift/core-api.js +9 -12
  63. package/dist/swift/functions.js +13 -2
  64. package/dist/swift/generics.js +5 -1
  65. package/dist/swift/global-calls.js +2 -0
  66. package/dist/swift/literals.js +53 -6
  67. package/dist/swift/names.js +1 -1
  68. package/dist/swift/native/sdk-tables.js +52 -4
  69. package/dist/swift/native/sdk.js +9 -1
  70. package/dist/swift/operators.js +4 -1
  71. package/dist/swift/parameters.js +5 -2
  72. package/dist/swift/placement.js +42 -1
  73. package/dist/swift/prototype-calls.js +17 -2
  74. package/dist/swift/render.js +64 -0
  75. package/dist/swift/results.js +1 -1
  76. package/dist/swift/statements.js +9 -0
  77. package/dist/swift/static-calls.js +8 -3
  78. package/dist/swift/types.js +9 -9
  79. package/dist/targets/android/build.js +13 -9
  80. package/dist/targets/ios/build.js +11 -10
  81. package/dist/targets/ios/dependencies.js +12 -0
  82. package/dist/targets/resources.js +15 -1
  83. package/dist/template/plan.js +105 -8
  84. package/dist/types/adapter-api.d.ts +13 -0
  85. package/dist/types/ir.d.ts +47 -0
  86. package/kit-android/generated/kotlin/org/nativescript/kit/__Objects.kt +102 -7485
  87. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_view_view_common.kt +1 -3
  88. package/kit-android/generated/source-lines.json +1 -1
  89. package/kit-android/src/fromcore/kotlin/org/nativescript/kit/CoreBridge.kt +67 -1
  90. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Prototypes.kt +26 -0
  91. package/kit-apple/Overlays/xml-free/Core/ui.core.bindable.index.swift +4 -4
  92. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity1.swift +24 -146
  93. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity2.swift +0 -281
  94. package/kit-apple/Sources/NativeScriptKit/Core/{Object_iterator_prototype_for_keyFor_hasInstance_isConcatSpreadable_and_19_more_91b5f3.swift → Object_iterator_prototype_for_keyFor_hasInstance_isConcatSpreadable_and_19_more_fa18e1.swift} +28 -103
  95. package/kit-apple/Sources/NativeScriptKit/Core/__Namespace.Utils.swift +17 -15
  96. package/kit-apple/Sources/NativeScriptKit/Core/application-settings.index.ios.swift +8 -8
  97. package/kit-apple/Sources/NativeScriptKit/Core/application.application-common.swift +4 -4
  98. package/kit-apple/Sources/NativeScriptKit/Core/color.color-common.swift +7 -7
  99. package/kit-apple/Sources/NativeScriptKit/Core/http.http-request-internal.index.ios.swift +2 -1
  100. package/kit-apple/Sources/NativeScriptKit/Core/image-source.index.ios.swift +1 -1
  101. package/kit-apple/Sources/NativeScriptKit/Core/kit-index.json +34 -244
  102. package/kit-apple/Sources/NativeScriptKit/Core/manifest.json +1 -2
  103. package/kit-apple/Sources/NativeScriptKit/Core/ui.action-bar.index.ios.swift +3 -3
  104. package/kit-apple/Sources/NativeScriptKit/Core/ui.button.index.ios.swift +4 -4
  105. package/kit-apple/Sources/NativeScriptKit/Core/ui.content-view.index.swift +8 -8
  106. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.bindable.index.swift +4 -4
  107. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.view.index.ios.swift +8 -8
  108. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.view.view-common.swift +1 -3
  109. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.view.view-helper.view-helper-common.swift +7 -7
  110. package/kit-apple/Sources/NativeScriptKit/Core/ui.frame.index.ios.swift +4 -4
  111. package/kit-apple/Sources/NativeScriptKit/Core/ui.html-view.index.ios.swift +4 -4
  112. package/kit-apple/Sources/NativeScriptKit/Core/ui.image.image-common.swift +2 -2
  113. package/kit-apple/Sources/NativeScriptKit/Core/ui.image.index.ios.swift +4 -4
  114. package/kit-apple/Sources/NativeScriptKit/Core/ui.label.index.ios.swift +4 -4
  115. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.absolute-layout.index.ios.swift +4 -4
  116. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.dock-layout.index.ios.swift +4 -4
  117. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.flexbox-layout.index.ios.swift +3 -3
  118. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.grid-layout.index.ios.swift +4 -4
  119. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.stack-layout.index.ios.swift +4 -4
  120. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.wrap-layout.index.ios.swift +4 -4
  121. package/kit-apple/Sources/NativeScriptKit/Core/ui.list-view.index.ios.swift +3 -3
  122. package/kit-apple/Sources/NativeScriptKit/Core/ui.page.index.ios.swift +4 -4
  123. package/kit-apple/Sources/NativeScriptKit/Core/ui.repeater.index.swift +4 -4
  124. package/kit-apple/Sources/NativeScriptKit/Core/ui.scroll-view.index.ios.swift +4 -4
  125. package/kit-apple/Sources/NativeScriptKit/Core/ui.split-view.index.ios.swift +4 -4
  126. package/kit-apple/Sources/NativeScriptKit/Core/ui.styling.background.ios.swift +1 -1
  127. package/kit-apple/Sources/NativeScriptKit/Core/ui.tab-view.index.ios.swift +4 -4
  128. package/kit-apple/Sources/NativeScriptKit/Core/utils.common.swift +9 -9
  129. package/kit-apple/Sources/NativeScriptKit/Core/utils.layout-helper.index.ios.swift +10 -10
  130. package/kit-apple/Sources/NativeScriptKit/CoreBridge.swift +67 -1
  131. package/kit-apple/Sources/NativeScriptKit/Runtime/Lowering.swift +4 -0
  132. package/kit-apple/Sources/NativeScriptKit/Runtime/Prototypes.swift +25 -0
  133. package/kit-apple/Sources/NativeScriptKit/Runtime/RegExp.swift +6 -0
  134. package/package.json +1 -1
  135. package/kit-apple/Sources/NativeScriptKit/Core/Object_toString_charAt_charCodeAt_concat_indexOf_lastIndexOf_and_44_more_fc25df.swift +0 -481
@@ -1,8 +1,12 @@
1
1
  import ts from 'typescript';
2
+ import { createHash } from 'node:crypto';
2
3
  import { existsSync, readFileSync } from 'node:fs';
3
4
  import { basename, dirname, isAbsolute, resolve, sep } from 'node:path';
4
5
  import { foldPlatform } from "./platform.js";
5
6
  import { desugarConstructorFactories } from "./constructor-factories.js";
7
+ import { desugarClassMixins } from "./class-mixins.js";
8
+ import { expandImportMetaGlob } from "./glob.js";
9
+ import { NO_VITE_PLUGINS } from "./vite-plugins.js";
6
10
  import { NATIVE_CONTROLLERS, NATIVE_VIEWS, nativeViewOf } from "./core-facts.js";
7
11
  import { packageOf, runtimeFile } from "../plugins/resolve.js";
8
12
  import { localFilePackages } from "../targets/resources.js";
@@ -21,9 +25,9 @@ const SHIMS = {
21
25
  /** Deeply reactive: arrays and objects it holds notify on mutation. */
22
26
  export interface DeepRef<T> { value: T }
23
27
  export declare function $ref<T>(value: T): DeepRef<T>;
24
- import type { ItemEventData, PanGestureEventData, PinchGestureEventData, RotationGestureEventData, SwipeGestureEventData, TouchGestureEventData, Pointer as CorePointer } from '@nativescript/core';
28
+ import type { ItemEventData, PanGestureEventData, PinchGestureEventData, PropertyChangeData, RotationGestureEventData, SwipeGestureEventData, TouchGestureEventData, Pointer as CorePointer } from '@nativescript/core';
25
29
  /** A template handler's \$event: whichever of core's event types the handler declares. */
26
- export type EventData = ItemEventData & PanGestureEventData & PinchGestureEventData & RotationGestureEventData & SwipeGestureEventData & TouchGestureEventData & { value: any; item: any };
30
+ export type EventData = ItemEventData & PanGestureEventData & PinchGestureEventData & PropertyChangeData & RotationGestureEventData & SwipeGestureEventData & TouchGestureEventData & { value: any; item: any; target?: any; currentTarget?: any; preventDefault?(): void; stopPropagation?(): void };
27
31
  export type Pointer = CorePointer;
28
32
  export declare function $navigate(page: () => any): void;
29
33
  export interface WritableSignal<T> { (): T; set(value: T): void; update(fn: (value: T) => T): void; $write(value: T | ((previous: T) => T)): void }
@@ -140,6 +144,22 @@ const WORKER_GLOBALS = `
140
144
  declare function postMessage(message: any, transfer?: any[]): void;
141
145
  declare function close(): void;
142
146
  `;
147
+ /** Minimal non-DOM globals added when the app's tsconfig includes `lib: ["dom"]` (which already declares console, URL, Worker, crypto, etc.). */
148
+ const DOM_COMPAT_GLOBALS = `
149
+ declare function setTimeout(callback: (...args: any[]) => void): number;
150
+ declare function setInterval(callback: (...args: any[]) => void): number;
151
+ declare namespace NodeJS { type Timeout = number; type Timer = number; type Immediate = number }
152
+ declare var global: typeof globalThis;
153
+ declare function cancelAnimationFrame(id: number | undefined): void;
154
+ declare function __nsRegisterAppModules(modules: any): void;
155
+ declare function __nsClass(make: () => any): any;
156
+ declare function __nsRegisterCompiledBinding(key: string, binding: any): void;
157
+ declare function __nsRegisterPage(file: string, factory: ((exports: any, moduleName: string, xmlModule: string) => any) | undefined, codeModule?: string, codeExports?: any): void;
158
+ interface SymbolConstructor {
159
+ readonly dispose: unique symbol;
160
+ readonly asyncDispose: unique symbol;
161
+ }
162
+ `;
143
163
  /** The platform's native API typings, as an app's `references.d.ts` includes them. */
144
164
  const PLATFORM_TYPES = { ios: '@nativescript/types-ios/index.d.ts', android: '@nativescript/types-android/index.d.ts' };
145
165
  /** The nearest `node_modules` above `from` that has @nativescript/core. */
@@ -156,6 +176,41 @@ export function nodeModules(from) {
156
176
  * the framework's are its adapter's, and the rest are typings or tooling.
157
177
  */
158
178
  const NOT_PLUGINS = /^(@nativescript\/(core|types|types-ios|types-android|types-minimal|webpack|vite|tailwind|android|ios)|tslib|typescript|vite)$/;
179
+ /**
180
+ * Rewrites ES `export default <expr>;` (`ts.ExportAssignment`) into `export { <id> as default };` (introducing
181
+ * `const __nsDefault = <expr>;` when `<expr>` is not already a plain identifier) so TypeScript's `getAliasedSymbol`
182
+ * resolves default and namespace imports directly to a real declaration in both Swift and Kotlin backends.
183
+ */
184
+ function desugarDefaultExport(code, name) {
185
+ // Desugar standard UMD `if (typeof module !== 'undefined' && module.exports) { module.exports = X; }` to an ES default export.
186
+ if (/\.m?js$/.test(name) && code.includes('module.exports') && !/\brequire\s*\(/.test(code)) {
187
+ code = code.replace(/if\s*\(\s*typeof\s+module\s*!==?\s*['"]undefined['"]\s*&&\s*module\.exports\s*\)\s*(?:\{\s*module\.exports\s*=\s*([^;{}]+?);?\s*\}|module\.exports\s*=\s*([^;]+?);?)/g, (_, a, b) => {
188
+ const rhs = (a ?? b ?? '').trim();
189
+ return /^[A-Za-z_$][\w$]*$/.test(rhs) ? `export { ${rhs} as default };` : `const __nsDefault = ${rhs}; export { __nsDefault as default };`;
190
+ });
191
+ }
192
+ if (!code.includes('export default'))
193
+ return code;
194
+ const sf = ts.createSourceFile(name, code, ts.ScriptTarget.Latest, true);
195
+ const edits = [];
196
+ for (const st of sf.statements) {
197
+ if (!ts.isExportAssignment(st) || st.isExportEquals)
198
+ continue;
199
+ const exprText = code.slice(st.expression.getStart(sf), st.expression.getEnd());
200
+ if (ts.isIdentifier(st.expression)) {
201
+ edits.push({ start: st.getStart(sf), end: st.getEnd(), text: `export { ${exprText} as default };` });
202
+ }
203
+ else {
204
+ edits.push({ start: st.getStart(sf), end: st.getEnd(), text: `const __nsDefault = ${exprText}; export { __nsDefault as default };` });
205
+ }
206
+ }
207
+ if (!edits.length)
208
+ return code;
209
+ let out = code;
210
+ for (const e of edits.sort((a, b) => b.start - a.start))
211
+ out = out.slice(0, e.start) + e.text + out.slice(e.end);
212
+ return out;
213
+ }
159
214
  /**
160
215
  * A program over the app's modules and the components' virtual classes,
161
216
  * typed by the real ES2022 library, @nativescript/core's own declarations
@@ -163,7 +218,7 @@ const NOT_PLUGINS = /^(@nativescript\/(core|types|types-ios|types-android|types-
163
218
  * own configuration is non-strict where no tsconfig.json of its says (a test's). `build`: the framework adapter's module
164
219
  * rules, the plugins built as stand-ins and the bundler's defines it is read with (by default, none).
165
220
  */
166
- export function createProgram(roots, virtual, platform = 'ios', modulesDir, plugins, declarations = [], replacements = {}, overrides = {}, aliased = () => undefined, appLenient, build = new BuildContext()) {
221
+ export function createProgram(roots, virtual, platform = 'ios', modulesDir, plugins, declarations = [], replacements = {}, overrides = {}, aliased = () => undefined, appLenient, build = new BuildContext(), vitePlugins = NO_VITE_PLUGINS) {
167
222
  const shimPath = (m) => `/__shims__/${m.replace(/[@/]/g, '_')}.d.ts`;
168
223
  const rules = build.adapter.rules;
169
224
  const notPlugin = (pkg) => NOT_PLUGINS.test(pkg) || build.adapter.isFrameworkPackage(pkg) || build.stubbedPlugins.has(pkg);
@@ -173,7 +228,8 @@ export function createProgram(roots, virtual, platform = 'ios', modulesDir, plug
173
228
  const files = new Map(virtual);
174
229
  for (const [m, text] of Object.entries(shims))
175
230
  files.set(shimPath(m), text);
176
- files.set('/__shims__/globals.d.ts', GLOBALS + WORKER_GLOBALS);
231
+ const hasDom = appIncludesDomLib(roots[0] ?? [...virtual.keys()][0]);
232
+ files.set('/__shims__/globals.d.ts', hasDom ? DOM_COMPAT_GLOBALS : GLOBALS + WORKER_GLOBALS);
177
233
  const modules = modulesDir ?? nodeModules(dirname([...roots, ...virtual.keys()][0]));
178
234
  const platformTypes = resolve(modules, PLATFORM_TYPES[platform]);
179
235
  if (!existsSync(platformTypes))
@@ -184,7 +240,7 @@ export function createProgram(roots, virtual, platform = 'ios', modulesDir, plug
184
240
  moduleResolution: ts.ModuleResolutionKind.Bundler,
185
241
  // Of ES2024, only what both runtimes implement (groupBy, withResolvers): the rest would type-check and then not translate.
186
242
  strict: true,
187
- lib: ['lib.es2023.d.ts', 'lib.es2024.object.d.ts', 'lib.es2024.collection.d.ts', 'lib.es2024.promise.d.ts'],
243
+ lib: ['lib.es2023.d.ts', 'lib.es2024.object.d.ts', 'lib.es2024.collection.d.ts', 'lib.es2024.promise.d.ts', ...(hasDom ? ['lib.dom.d.ts', 'lib.dom.iterable.d.ts'] : [])],
188
244
  types: [],
189
245
  skipLibCheck: true,
190
246
  experimentalDecorators: true,
@@ -223,18 +279,24 @@ export function createProgram(roots, virtual, platform = 'ios', modulesDir, plug
223
279
  pluginFiles.add(resolve(dirname(name), ref));
224
280
  return pluginDeclaredExports(code, name, platform);
225
281
  };
282
+ const appRoot = plugins?.options?.app ? resolve(plugins.options.app) : null;
283
+ const rootSet = new Set(roots);
226
284
  host.getSourceFile = (name, version, onError) => {
227
285
  const text = files.get(name) ?? (isSource(name) && existsSync(name) ? readFileSync(name, 'utf8') : appTypings.has(name) ? nativeReferences(readFileSync(name, 'utf8'), name) : undefined);
228
286
  if (text === undefined) {
229
287
  // A package's own TypeScript (or pure-JS ESM) source.
230
288
  if (!/\.(tsx?|m?js)$/.test(name) || name.endsWith('.d.ts') || !existsSync(name))
231
289
  return readLib(name, version, onError);
232
- const raw = readFileSync(name, 'utf8');
233
- if (/\.m?js$/.test(name))
234
- return ts.createSourceFile(name, raw, version, true, ts.ScriptKind.JS);
235
- return ts.createSourceFile(name, desugarConstructorFactories(declaredExports(name, raw), name), version, true);
290
+ const raw = desugarDefaultExport(expandImportMetaGlob(readFileSync(name, 'utf8'), name, appRoot), name);
291
+ if (/\.m?js$/.test(name)) {
292
+ const typedefs = pluginJsTypedefs(name, plugins);
293
+ return ts.createSourceFile(name, typedefs ? `${raw}\n${typedefs}\n` : raw, version, true, ts.ScriptKind.JS);
294
+ }
295
+ return ts.createSourceFile(name, desugarClassMixins(desugarConstructorFactories(declaredExports(name, raw), name), name), version, true);
236
296
  }
237
- const code = /\.tsx?$/.test(name) && !name.endsWith('.d.ts') ? desugarConstructorFactories(declaredExports(name, text), name) : text;
297
+ const transformed = !name.startsWith('/__shims__/') && !name.startsWith('/__raw__/') && !name.startsWith('/__vite__/') && !name.endsWith('.d.ts') ? vitePlugins.transform(text, name) : text;
298
+ const expanded = !name.startsWith('/__shims__/') && !name.endsWith('.d.ts') ? desugarDefaultExport(expandImportMetaGlob(transformed, name, appRoot), name) : transformed;
299
+ const code = /\.tsx?$/.test(name) && !name.endsWith('.d.ts') ? desugarClassMixins(desugarConstructorFactories(declaredExports(name, expanded), name), name) : expanded;
238
300
  return ts.createSourceFile(name, isSource(name) ? foldPlatform(code, name, platform, modules, build.defines) : code, version, true);
239
301
  };
240
302
  const fileExists = host.fileExists.bind(host);
@@ -258,12 +320,65 @@ export function createProgram(roots, virtual, platform = 'ios', modulesDir, plug
258
320
  resolutions.set(`${containing}\0${lit.text}`, r.resolvedModule.resolvedFileName);
259
321
  return r;
260
322
  });
261
- const appRoot = plugins?.options?.app ? resolve(plugins.options.app) : null;
262
323
  const localPackages = appRoot ? localFilePackages(appRoot) : new Map();
263
324
  const resolveLiteral = (lit, containing) => {
264
325
  {
265
- // The app's own tsconfig `paths` (`~/app/x`), as its bundler resolves them: plugins' sources have their own.
266
- const aliasTarget = isApp(containing) ? aliased(lit.text) : undefined;
326
+ // Vite `?raw` asset import (`import css from 'pkg/file.css?raw'` or `'./example.ts?raw'`): inline file contents as default export.
327
+ if (lit.text.endsWith('?raw')) {
328
+ const rawSpec = lit.text.slice(0, -4);
329
+ const aliasedRaw = isSource(containing) ? aliased(rawSpec, containing) : undefined;
330
+ const candidate = aliasedRaw ?? (rawSpec.startsWith('.') || isAbsolute(rawSpec) ? resolve(dirname(containing), rawSpec) : resolve(modules, rawSpec));
331
+ if (existsSync(candidate)) {
332
+ const hash = createHash('sha256').update(candidate).digest('hex').slice(0, 16);
333
+ const rawPath = `/__raw__/${hash}.ts`;
334
+ if (!files.has(rawPath))
335
+ files.set(rawPath, `const __nsRaw_${hash}: string = ${JSON.stringify(readFileSync(candidate, 'utf8'))};\nexport { __nsRaw_${hash} as default };\n`);
336
+ pluginFiles.add(rawPath);
337
+ return { resolvedModule: { resolvedFileName: rawPath, extension: ts.Extension.Ts } };
338
+ }
339
+ }
340
+ // JSON module import (`import data from 'pkg/data.json'` or `'./data.json'`): parse at runtime via JSON.parse so large data maps don't explode into native struct definitions.
341
+ if (lit.text.endsWith('.json') && !containing.startsWith('/__shims__/')) {
342
+ const aliasedJson = isSource(containing) ? aliased(lit.text, containing) : undefined;
343
+ let candidate = aliasedJson ?? (lit.text.startsWith('.') || isAbsolute(lit.text) ? resolve(dirname(containing), lit.text) : resolve(modules, lit.text));
344
+ if (!existsSync(candidate) && !lit.text.startsWith('.') && !isAbsolute(lit.text)) {
345
+ for (let dir = dirname(containing);; dir = dirname(dir)) {
346
+ const probe = resolve(dir, 'node_modules', lit.text);
347
+ if (existsSync(probe)) {
348
+ candidate = probe;
349
+ break;
350
+ }
351
+ if (dirname(dir) === dir)
352
+ break;
353
+ }
354
+ }
355
+ if (existsSync(candidate)) {
356
+ const hash = createHash('sha256').update(candidate).digest('hex').slice(0, 16);
357
+ const jsonPath = `/__json__/${hash}.ts`;
358
+ if (!files.has(jsonPath))
359
+ files.set(jsonPath, `const __nsJson_${hash}: any = JSON.parse(${JSON.stringify(readFileSync(candidate, 'utf8'))});\nexport { __nsJson_${hash} as default };\n`);
360
+ pluginFiles.add(jsonPath);
361
+ return { resolvedModule: { resolvedFileName: jsonPath, extension: ts.Extension.Ts } };
362
+ }
363
+ }
364
+ // Custom Vite plugin `load(id)` hook for query-suffixed virtual modules (e.g. `.md?ns-analog-content`).
365
+ const qIdx = lit.text.indexOf('?');
366
+ if (qIdx > 0) {
367
+ const baseSpec = lit.text.slice(0, qIdx);
368
+ const query = lit.text.slice(qIdx);
369
+ const resolvedBase = baseSpec.startsWith('.') || isAbsolute(baseSpec) ? resolve(dirname(containing), baseSpec) : (isSource(containing) ? aliased(baseSpec, containing) : undefined) ?? resolve(modules, baseSpec);
370
+ const loaded = vitePlugins.load(resolvedBase + query);
371
+ if (loaded !== undefined) {
372
+ const hash = createHash('sha256').update(resolvedBase + query).digest('hex').slice(0, 16);
373
+ const vPath = `/__vite__/${hash}.ts`;
374
+ if (!files.has(vPath))
375
+ files.set(vPath, desugarDefaultExport(loaded, vPath));
376
+ pluginFiles.add(vPath);
377
+ return { resolvedModule: { resolvedFileName: vPath, extension: ts.Extension.Ts } };
378
+ }
379
+ }
380
+ // The app's own tsconfig `paths` / Vite aliases (`~/app/x`), as its bundler resolves them: workspace sources outside node_modules share them.
381
+ const aliasTarget = isSource(containing) ? aliased(lit.text, containing) : undefined;
267
382
  const m = aliasTarget ?? lit.text;
268
383
  const substitution = rules.substitutions && Object.hasOwn(rules.substitutions, m) && !replacements[m] ? rules.substitutions[m] : undefined;
269
384
  if (substitution && (plugins || !substitution.sourcesOnly)) {
@@ -295,9 +410,14 @@ export function createProgram(roots, virtual, platform = 'ios', modulesDir, plug
295
410
  if (files.has(candidate) || existsSync(candidate)) {
296
411
  if (candidate.endsWith('.d.ts'))
297
412
  return { resolvedModule: { resolvedFileName: candidate, extension: ts.Extension.Dts } };
413
+ // A component file replaced by a compiled `.release.ts` virtual file must resolve to the virtual file everywhere so classes with private members stay nominally identical.
414
+ const released = candidate.endsWith('.ts') && !candidate.endsWith('.release.ts') ? candidate.replace(/\.ts$/, '.release.ts') : undefined;
415
+ if (released && virtual.has(released) && containing !== released)
416
+ return { resolvedModule: { resolvedFileName: released, extension: ts.Extension.Ts } };
298
417
  // A plugin's own modules, a substitution's file, or a monorepo workspace library outside the app folder
299
- // are compiled through closed-world reachability so only reached declarations emit native code.
300
- if (pluginFiles.has(containing) || substituted.has(candidate) || (aliasTarget && appRoot && !candidate.startsWith(appRoot + sep)))
418
+ // (not already compiled as an app/component root) are compiled through closed-world reachability.
419
+ const isCompiledRoot = rootSet.has(candidate) || virtual.has(candidate) || virtual.has(candidate.replace(/\.ts$/, '.release.ts'));
420
+ if (!isCompiledRoot && (pluginFiles.has(containing) || substituted.has(candidate) || (aliasTarget && appRoot && !candidate.startsWith(appRoot + sep))))
301
421
  pluginFiles.add(candidate);
302
422
  const extension = candidate.endsWith('.tsx') ? ts.Extension.Tsx : candidate.endsWith('.mjs') ? ts.Extension.Mjs : candidate.endsWith('.js') ? ts.Extension.Js : ts.Extension.Ts;
303
423
  return { resolvedModule: { resolvedFileName: candidate, extension } };
@@ -315,7 +435,9 @@ export function createProgram(roots, virtual, platform = 'ios', modulesDir, plug
315
435
  const typeOnly = !containing.startsWith('/__shims__/') && ts.isImportDeclaration(lit.parent) && !!lit.parent.importClause?.isTypeOnly && !(lit.parent.parent && ts.isSourceFile(lit.parent.parent) && lit.parent.parent.statements.some(valueImport));
316
436
  // A plugin's augmentation of another's module augments the module the program compiles: that package's source.
317
437
  const augments = ts.isModuleDeclaration(lit.parent) && lit.parent.name === lit && !!plugins?.all().some((p) => containing.startsWith(p.root + '/'));
318
- if (plugins && (isSource(containing) || pluginFiles.has(containing) || augments || containing.startsWith('/__shims__/')) && !m.startsWith('.') && !m.startsWith('/') && !notPlugin(packageOf(m)) && !typeOnly) {
438
+ // Every import of `rxjs` (including `import type` and `.d.ts` files like `@angular/cdk`) must resolve to the same compiled `rxjs` source so Observable/OperatorFunction types match across the whole program.
439
+ const sharedRxjs = m === 'rxjs' || m.startsWith('rxjs/');
440
+ if (plugins && (isSource(containing) || pluginFiles.has(containing) || augments || containing.startsWith('/__shims__/') || (containing.endsWith('.d.ts') && sharedRxjs)) && !m.startsWith('.') && !m.startsWith('/') && !notPlugin(packageOf(m)) && (!typeOnly || sharedRxjs)) {
319
441
  const js = runtimeFile(m, modules, platform, localPackages);
320
442
  if (js) {
321
443
  plugins.get(js.packageDir);
@@ -649,6 +771,19 @@ function appDefinesFields(from) {
649
771
  }
650
772
  return undefined;
651
773
  }
774
+ /** Whether the app's tsconfig.json (its `extends` followed) includes the DOM library (`"dom"`). */
775
+ function appIncludesDomLib(from) {
776
+ if (!from)
777
+ return false;
778
+ for (let dir = dirname(from); dirname(dir) !== dir; dir = dirname(dir)) {
779
+ const file = resolve(dir, 'tsconfig.json');
780
+ if (!existsSync(file))
781
+ continue;
782
+ const libs = parseTsConfig(file)?.options?.lib ?? [];
783
+ return libs.some((l) => /^lib\.dom(\.|$)/i.test(l) || /^dom$/i.test(l));
784
+ }
785
+ return false;
786
+ }
652
787
  /** Whether the app's tsconfig.json (its `extends` followed) leaves strict checking off. */
653
788
  function appStrictness(from) {
654
789
  if (!from)
@@ -662,6 +797,41 @@ function appStrictness(from) {
662
797
  }
663
798
  return false;
664
799
  }
800
+ /**
801
+ * For a pure-JS plugin compiled from `.js`/`.mjs` (e.g. `clsx`), exposes type/interface names declared in its
802
+ * package `.d.ts` as JSDoc `@typedef` so `import { clsx, type ClassValue } from 'clsx'` type-checks.
803
+ */
804
+ function pluginJsTypedefs(file, plugins) {
805
+ const owner = plugins?.all().find((p) => file.startsWith(p.root + sep) || file.startsWith(p.dir + sep));
806
+ if (!owner)
807
+ return '';
808
+ const pkgPath = resolve(owner.dir, 'package.json');
809
+ if (!existsSync(pkgPath))
810
+ return '';
811
+ let typesRel;
812
+ try {
813
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
814
+ typesRel = typeof pkg.types === 'string' ? pkg.types : typeof pkg.typings === 'string' ? pkg.typings : undefined;
815
+ }
816
+ catch {
817
+ return '';
818
+ }
819
+ if (!typesRel)
820
+ return '';
821
+ const dtsPath = resolve(owner.dir, typesRel);
822
+ if (!existsSync(dtsPath))
823
+ return '';
824
+ const dts = ts.createSourceFile(dtsPath, readFileSync(dtsPath, 'utf8'), ts.ScriptTarget.Latest, false);
825
+ const names = new Set();
826
+ const scan = (st) => {
827
+ if ((ts.isTypeAliasDeclaration(st) || ts.isInterfaceDeclaration(st)) && st.name)
828
+ names.add(st.name.text);
829
+ else if (ts.isModuleDeclaration(st) && st.body && ts.isModuleBlock(st.body))
830
+ st.body.statements.forEach(scan);
831
+ };
832
+ dts.statements.forEach(scan);
833
+ return [...names].map((n) => `/** @typedef {any} ${n} */`).join('\n');
834
+ }
665
835
  /**
666
836
  * A plugin's platform file (`index.ios.ts`) with the exports of the declarations beside it (`index.d.ts`) that it
667
837
  * lacks: an app is written against those declarations, and the build compiles the platform file in their place. A
@@ -705,8 +875,30 @@ export function pluginDeclaredExports(code, file, platform) {
705
875
  }
706
876
  return { exported, local, stars, from };
707
877
  };
708
- const own = exportsOf(ts.createSourceFile(file, code, ts.ScriptTarget.Latest, false));
709
- const declared = exportsOf(ts.createSourceFile(`${stem}.d.ts`, readFileSync(`${stem}.d.ts`, 'utf8'), ts.ScriptTarget.Latest, false));
878
+ const ownSf = ts.createSourceFile(file, code, ts.ScriptTarget.Latest, true);
879
+ const declaredSf = ts.createSourceFile(`${stem}.d.ts`, readFileSync(`${stem}.d.ts`, 'utf8'), ts.ScriptTarget.Latest, false);
880
+ const own = exportsOf(ownSf);
881
+ const declared = exportsOf(declaredSf);
882
+ // Give unannotated exported functions in a plugin's platform file their sibling `.d.ts` return type so callers see the published contract.
883
+ const dtsFnReturn = new Map();
884
+ for (const st of declaredSf.statements) {
885
+ if (!ts.isFunctionDeclaration(st) || !st.name || !st.type || st.typeParameters?.length)
886
+ continue;
887
+ dtsFnReturn.set(st.name.text, (dtsFnReturn.get(st.name.text) ?? 0) + 1);
888
+ }
889
+ const fnEdits = [];
890
+ const relBase = `./${basename(stem)}`;
891
+ for (const st of ownSf.statements) {
892
+ if (!ts.isFunctionDeclaration(st) || !st.name || st.type || !st.body || st.typeParameters?.length)
893
+ continue;
894
+ const isExported = !!ts.getModifiers(st)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword);
895
+ if (!isExported || dtsFnReturn.get(st.name.text) !== 1)
896
+ continue;
897
+ fnEdits.push({ at: st.body.getStart(ownSf), text: `: ReturnType<typeof import(${JSON.stringify(relBase)}).${st.name.text}> ` });
898
+ }
899
+ let patched = code;
900
+ for (const e of fnEdits.sort((a, b) => b.at - a.at))
901
+ patched = patched.slice(0, e.at) + e.text + patched.slice(e.at);
710
902
  const lines = [];
711
903
  for (const name of declared.exported) {
712
904
  if (own.exported.has(name))
@@ -717,10 +909,10 @@ export function pluginDeclaredExports(code, file, platform) {
717
909
  else if (spec)
718
910
  lines.push(`export { ${name} } from ${JSON.stringify(spec)};`);
719
911
  else if (declared.local.get(name) === 'type')
720
- lines.push(`export type { ${name} } from ${JSON.stringify(`./${basename(stem)}`)};`);
912
+ lines.push(`export type { ${name} } from ${JSON.stringify(relBase)};`);
721
913
  }
722
914
  for (const spec of declared.stars)
723
915
  if (!own.stars.has(spec))
724
916
  lines.push(`export * from ${JSON.stringify(spec)};`);
725
- return lines.length ? `${code}\n${lines.join('\n')}\n` : code;
917
+ return lines.length ? `${patched}\n${lines.join('\n')}\n` : patched;
726
918
  }
@@ -40,7 +40,10 @@ export class SourceLines {
40
40
  /** Lines of a virtual file whose source is known exactly (a template binding's), which no matching then guesses. */
41
41
  pinned = new Map();
42
42
  pin(virtualFile, file, lines) {
43
- this.pinned.set(virtualFile, new Map(lines.map(([v, line]) => [v, { file, line }])));
43
+ const map = this.pinned.get(virtualFile) ?? new Map();
44
+ for (const [v, line] of lines)
45
+ map.set(v, { file, line });
46
+ this.pinned.set(virtualFile, map);
44
47
  }
45
48
  /** The marker for the statement `s`; one that ends the current region when its source line is unknown. */
46
49
  mark(s) {
@@ -0,0 +1,144 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ // Loads app-authored Vite plugins from an app's `vite.config.*` so ahead-of-time compilation honors
10
+ // custom `resolveId`, `transform`, and `load` hooks (e.g. monorepo component shims, virtual markdown modules).
11
+ import { existsSync } from 'node:fs';
12
+ import { createRequire } from 'node:module';
13
+ import { resolve } from 'node:path';
14
+ import { pathToFileURL } from 'node:url';
15
+ export const NO_VITE_PLUGINS = {
16
+ resolveId: () => undefined,
17
+ transform: (code) => code,
18
+ load: () => undefined,
19
+ };
20
+ /** Built-in Vite, @nativescript/vite, and framework bundler plugins skipped when running app-level hooks. */
21
+ const BUILTIN_PLUGIN_PREFIX = /^(vite:|builtin:|native:|ns-|nsvite-|@analogjs\/|vite-plugin-static-copy)/;
22
+ const BUILTIN_PLUGIN_NAMES = new Set([
23
+ 'alias',
24
+ 'replace',
25
+ 'main-entry',
26
+ 'source-map-js-compat',
27
+ 'html-entities-compat',
28
+ 'fast-xml-parser-compat',
29
+ 'angular-template-deps',
30
+ 'nativescript-package-resolver',
31
+ 'nativescript-worker-loader-stub',
32
+ 'nativescript-angular-worker-url-preserve',
33
+ 'nativescript-app-components',
34
+ 'nativescript-worker-url-transform',
35
+ 'nativescript-dynamic-import-fix',
36
+ 'nativescript-cli-integration',
37
+ ]);
38
+ function hookFn(hook) {
39
+ if (typeof hook === 'function')
40
+ return hook;
41
+ if (hook && typeof hook.handler === 'function')
42
+ return hook.handler;
43
+ return undefined;
44
+ }
45
+ const cache = new Map();
46
+ /** Resolves the app's `vite.config.*` (if any) and returns a synchronous bridge to its custom app plugins. */
47
+ export async function loadViteAppPlugins(root) {
48
+ const absRoot = resolve(root);
49
+ const cached = cache.get(absRoot);
50
+ if (cached)
51
+ return cached;
52
+ const configFile = ['vite.config.mts', 'vite.config.ts', 'vite.config.mjs', 'vite.config.js'].map((f) => resolve(absRoot, f)).find(existsSync);
53
+ if (!configFile || !existsSync(resolve(absRoot, 'package.json'))) {
54
+ cache.set(absRoot, NO_VITE_PLUGINS);
55
+ return NO_VITE_PLUGINS;
56
+ }
57
+ const prevCwd = process.cwd();
58
+ const prevIgnore = process.env.VITE_CONFIG_NATIVE_IGNORE_WARNING;
59
+ let plugins = [];
60
+ try {
61
+ process.env.VITE_CONFIG_NATIVE_IGNORE_WARNING = 'true';
62
+ process.chdir(absRoot);
63
+ const req = createRequire(resolve(absRoot, 'package.json'));
64
+ const vite = await import(__rewriteRelativeImportExtension(pathToFileURL(req.resolve('vite')).href, true));
65
+ const cfg = await vite.resolveConfig({ configFile, root: absRoot, mode: 'production' }, 'build', 'production', 'production');
66
+ plugins = (cfg.plugins ?? []).filter((p) => {
67
+ const name = p?.name ?? '';
68
+ return !!name && !BUILTIN_PLUGIN_PREFIX.test(name) && !BUILTIN_PLUGIN_NAMES.has(name);
69
+ });
70
+ }
71
+ catch {
72
+ plugins = [];
73
+ }
74
+ finally {
75
+ process.chdir(prevCwd);
76
+ if (prevIgnore === undefined)
77
+ delete process.env.VITE_CONFIG_NATIVE_IGNORE_WARNING;
78
+ else
79
+ process.env.VITE_CONFIG_NATIVE_IGNORE_WARNING = prevIgnore;
80
+ }
81
+ if (!plugins.length) {
82
+ cache.set(absRoot, NO_VITE_PLUGINS);
83
+ return NO_VITE_PLUGINS;
84
+ }
85
+ const resolvers = plugins.map((p) => hookFn(p.resolveId)).filter((fn) => !!fn);
86
+ const transformers = plugins.map((p) => hookFn(p.transform)).filter((fn) => !!fn);
87
+ const loaders = plugins.map((p) => hookFn(p.load)).filter((fn) => !!fn);
88
+ const ctx = { warn: () => { }, error: (e) => { throw new Error(String(e)); } };
89
+ const bridge = {
90
+ resolveId(specifier, importer) {
91
+ for (const fn of resolvers) {
92
+ try {
93
+ const out = fn.call(ctx, specifier, importer, {});
94
+ if (out && typeof out.then === 'function')
95
+ continue;
96
+ const id = typeof out === 'string' ? out : out && typeof out.id === 'string' ? out.id : undefined;
97
+ if (id && !id.startsWith('\0'))
98
+ return id;
99
+ }
100
+ catch {
101
+ // Ignore plugins that rely on full Rollup context for unrelated specifiers.
102
+ }
103
+ }
104
+ return undefined;
105
+ },
106
+ transform(code, id) {
107
+ let cur = code;
108
+ for (const fn of transformers) {
109
+ try {
110
+ const out = fn.call(ctx, cur, id);
111
+ if (out && typeof out.then === 'function')
112
+ continue;
113
+ if (typeof out === 'string')
114
+ cur = out;
115
+ else if (out && typeof out.code === 'string')
116
+ cur = out.code;
117
+ }
118
+ catch {
119
+ // Ignore plugins that cannot transform this file synchronously.
120
+ }
121
+ }
122
+ return cur;
123
+ },
124
+ load(id) {
125
+ for (const fn of loaders) {
126
+ try {
127
+ const out = fn.call(ctx, id);
128
+ if (out && typeof out.then === 'function')
129
+ continue;
130
+ if (typeof out === 'string')
131
+ return out;
132
+ if (out && typeof out.code === 'string')
133
+ return out.code;
134
+ }
135
+ catch {
136
+ // Ignore plugins that do not handle this id.
137
+ }
138
+ }
139
+ return undefined;
140
+ },
141
+ };
142
+ cache.set(absRoot, bridge);
143
+ return bridge;
144
+ }
@@ -13,8 +13,8 @@ const FACTS = {
13
13
  clearTimeout: { arity: 0, result: 'undefined', runtime: 'jsClearTimeout', host: true },
14
14
  clearInterval: { arity: 0, result: 'undefined', runtime: 'jsClearInterval', host: true },
15
15
  queueMicrotask: { arity: 1, result: 'undefined', runtime: 'jsQueueMicrotask', args: ['callback'] },
16
- requestAnimationFrame: { arity: 1, result: 'number', host: true, declaredBy: 'android' },
17
- cancelAnimationFrame: { arity: 1, result: 'undefined', host: true, declaredBy: 'android' },
16
+ requestAnimationFrame: { arity: 1, result: 'number', host: true },
17
+ cancelAnimationFrame: { arity: 1, result: 'undefined', host: true },
18
18
  unescape: { arity: 1, result: 'string', runtime: 'jsUnescape', args: ['string'] },
19
19
  atob: { arity: 1, result: 'string', throws: true, runtime: 'jsAtob', args: ['string'] },
20
20
  btoa: { arity: 1, result: 'string', throws: true, runtime: 'jsBtoa', args: ['string'] },
@@ -21,5 +21,6 @@ export const OBJECT_STATICS = apiTable('static', {
21
21
  keys: { arity: 1, result: 'object' },
22
22
  preventExtensions: { arity: 1, result: 'object' },
23
23
  seal: { arity: 1, result: 'object' },
24
+ setPrototypeOf: { arity: 2, result: 'object', throws: true, runtime: 'jsSetPrototypeOf', args: ['any', 'any'] },
24
25
  values: { arity: 1, result: 'object' },
25
26
  });
@@ -51,6 +51,12 @@ export function libFunctionValueKind(owner, name) {
51
51
  return 'console';
52
52
  if (owner === 'String' && name === 'fromCharCode')
53
53
  return 'fromCharCode';
54
+ if (owner === 'String' && name === 'fromCodePoint')
55
+ return 'fromCodePoint';
56
+ if (owner === 'Math' && name === 'random')
57
+ return 'mathRandom';
58
+ if (owner === 'Math' && (name === 'min' || name === 'max'))
59
+ return 'mathVariadic';
54
60
  if (TYPED_ARRAYS.includes(owner) && name === 'from')
55
61
  return 'typedArrayFrom';
56
62
  if (owner === 'Array' && name === 'isArray')
@@ -1,5 +1,13 @@
1
1
  // Syntax-tree questions both backends ask, answered the same way for each.
2
2
  import ts from 'typescript';
3
+ /** A constructor body's statements excluding any bare `super(...)` call expression statement. */
4
+ export function nonSuperStatements(ctor) {
5
+ return (ctor?.body?.statements ?? []).filter((s) => !(ts.isExpressionStatement(s) && ts.isCallExpression(s.expression) && s.expression.expression.kind === ts.SyntaxKind.SuperKeyword));
6
+ }
7
+ /** The `extends` heritage entry of a class, if any. */
8
+ export function extendsHeritage(cls) {
9
+ return cls.heritageClauses?.find((h) => h.token === ts.SyntaxKind.ExtendsKeyword)?.types[0];
10
+ }
3
11
  /**
4
12
  * `o.k = (o = other)`, `o.k += (o = other).k`: an assignment to a member of the variable `o` whose value assigns `o`.
5
13
  * Script evaluates the target's object before the value, so the member is written on the object `o` held first.
@@ -267,9 +275,9 @@ export function declaresThis(fn) {
267
275
  const first = fn.parameters[0];
268
276
  return !!first && ts.isIdentifier(first.name) && first.name.text === 'this' && first.type?.kind !== ts.SyntaxKind.VoidKeyword;
269
277
  }
270
- /** A function type or function expression declaring its `this` with a type other than void. */
278
+ /** A function type, function expression or method signature declaring its `this` with a type other than void. */
271
279
  export function takesOwnThis(d) {
272
- return !!d && (ts.isFunctionTypeNode(d) || ts.isFunctionExpression(d)) && d.parameters.some((q) => ts.isIdentifier(q.name) && q.name.text === 'this' && !!q.type && q.type.kind !== ts.SyntaxKind.VoidKeyword);
280
+ return !!d && (ts.isFunctionTypeNode(d) || ts.isFunctionExpression(d) || ts.isMethodSignature(d)) && d.parameters.some((q) => ts.isIdentifier(q.name) && q.name.text === 'this' && !!q.type && q.type.kind !== ts.SyntaxKind.VoidKeyword);
273
281
  }
274
282
  /** Whether `this` appears in `e` outside nested functions, methods and classes, which bind their own. */
275
283
  export function refersToThis(e) {
@@ -313,3 +321,13 @@ export function notIterable(e) {
313
321
  const x = ts.skipOuterExpressions(e);
314
322
  return ts.isCallExpression(x) ? `${v8Text(x.expression)} is not a function or its return value is not iterable` : `${v8Text(x)} is not iterable`;
315
323
  }
324
+ /** The `length` property's value expression in `Array.from({ length }, fn)` / `Array.from({ length: n }, fn)`, if present. */
325
+ export function arrayFromLengthInit(obj) {
326
+ const length = obj.properties.find((p) => p.name?.getText() === 'length');
327
+ return length && (ts.isPropertyAssignment(length) ? length.initializer : ts.isShorthandPropertyAssignment(length) ? length.name : undefined);
328
+ }
329
+ /** The element types of a spread expression `...x` when `x` is a fixed tuple type; null otherwise. */
330
+ export function tupleSpreadTypes(x, checker) {
331
+ const st = checker.getNonNullableType(checker.getTypeAtLocation(x.expression));
332
+ return checker.isTupleType(st) ? checker.getTypeArguments(st) : null;
333
+ }
@@ -1,9 +1,44 @@
1
1
  // A class's place in its hierarchy, as the checker gives it: its program base, the constructor it runs, what it inherits.
2
2
  import ts from 'typescript';
3
- import { ERRORS } from "./globals.js";
3
+ import { ERRORS, isLibGlobal } from "./globals.js";
4
4
  import { isStatic } from "./throws.js";
5
5
  import { hasModifier, isLibDeclaration, isWriteTarget } from "./ast.js";
6
6
  import { literalKey, optionalBodilessMethod } from "./lang.js";
7
+ /** The program class declaring `static [Symbol.hasInstance]`, if `e` names one. */
8
+ export function hasInstanceClass(e, checker) {
9
+ if (!ts.isIdentifier(e) && !ts.isPropertyAccessExpression(e))
10
+ return null;
11
+ let sym = checker.getSymbolAtLocation(ts.isPropertyAccessExpression(e) ? e.name : e);
12
+ if (sym && sym.flags & ts.SymbolFlags.Alias)
13
+ sym = checker.getAliasedSymbol(sym);
14
+ const decl = sym?.valueDeclaration;
15
+ if (!decl || !ts.isClassDeclaration(decl) || decl.getSourceFile().isDeclarationFile)
16
+ return null;
17
+ for (let c = decl; c; c = programBase(c, checker)) {
18
+ if (c.members.some((m) => ts.isMethodDeclaration(m) &&
19
+ !!m.body &&
20
+ isStatic(m) &&
21
+ ts.isComputedPropertyName(m.name) &&
22
+ ts.isPropertyAccessExpression(m.name.expression) &&
23
+ ts.isIdentifier(m.name.expression.expression) &&
24
+ m.name.expression.expression.text === 'Symbol' &&
25
+ m.name.expression.name.text === 'hasInstance'))
26
+ return decl;
27
+ }
28
+ return null;
29
+ }
30
+ /** A member declared on a class applied as a mixin: the extension it becomes has it by name. */
31
+ export function isMixinOwnMember(name, checker, mixinOf) {
32
+ const decl = checker.getSymbolAtLocation(name)?.valueDeclaration;
33
+ return !!decl && ts.isClassDeclaration(decl.parent) && !!mixinOf(checker.getSymbolAtLocation(decl.parent.name));
34
+ }
35
+ /** The class symbol whose `.prototype` is read (`Cls.prototype`), excluding ES lib globals. */
36
+ export function prototypeClassSymbol(target, name, b) {
37
+ if (name !== 'prototype' || (ts.isIdentifier(target) && isLibGlobal(b, target)))
38
+ return null;
39
+ const sym = b.resolve(target);
40
+ return sym && sym.flags & ts.SymbolFlags.Class ? sym : null;
41
+ }
7
42
  /** The class `cls` extends where the program's own source declares it; undefined for a library's class or none. */
8
43
  export function programBase(cls, checker) {
9
44
  const h = cls.heritageClauses?.find((x) => x.token === ts.SyntaxKind.ExtendsKeyword)?.types[0];