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

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 (62) hide show
  1. package/dist/cli/runtime.cjs +7 -1
  2. package/dist/css/css.js +30 -6
  3. package/dist/driver/compile.js +1 -0
  4. package/dist/driver/paths.js +7 -0
  5. package/dist/kotlin/access.js +1 -1
  6. package/dist/kotlin/conversion.js +17 -5
  7. package/dist/kotlin/expressions.js +8 -3
  8. package/dist/kotlin/literals.js +7 -9
  9. package/dist/kotlin/native/calls.js +84 -3
  10. package/dist/kotlin/overrides.js +7 -5
  11. package/dist/kotlin/placement.js +3 -1
  12. package/dist/kotlin/static-calls.js +6 -4
  13. package/dist/kotlin/translator.js +31 -11
  14. package/dist/kotlin/type-facts.js +10 -2
  15. package/dist/plugins/native-android.js +30 -2
  16. package/dist/program/program.js +35 -26
  17. package/dist/semantics/facts.js +28 -1
  18. package/dist/semantics/shapes.js +21 -1
  19. package/dist/swift/conversion.js +1 -1
  20. package/dist/swift/from-any.js +2 -2
  21. package/dist/swift/literals.js +4 -4
  22. package/dist/swift/modules.js +1 -1
  23. package/dist/swift/placement.js +2 -3
  24. package/dist/swift/static-calls.js +5 -3
  25. package/dist/targets/android/build.js +5 -3
  26. package/kit-android/generated/kotlin/org/nativescript/kit/application_application.kt +4 -4
  27. package/kit-android/generated/kotlin/org/nativescript/kit/image_source_index.kt +1 -1
  28. package/kit-android/generated/kotlin/org/nativescript/kit/ui_animation_animation_common.kt +7 -3
  29. package/kit-android/generated/kotlin/org/nativescript/kit/ui_animation_index.kt +3 -1
  30. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_view_base_index.kt +2 -4
  31. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_view_index.kt +5 -6
  32. package/kit-android/generated/kotlin/org/nativescript/kit/ui_dialogs_index.kt +11 -6
  33. package/kit-android/generated/kotlin/org/nativescript/kit/ui_frame_fragment_transitions.kt +1 -1
  34. package/kit-android/generated/kotlin/org/nativescript/kit/ui_frame_frame_common.kt +1 -1
  35. package/kit-android/generated/kotlin/org/nativescript/kit/ui_frame_frame_helper_for_android.kt +7 -5
  36. package/kit-android/generated/kotlin/org/nativescript/kit/ui_frame_index.kt +6 -3
  37. package/kit-android/generated/kotlin/org/nativescript/kit/ui_gestures_touch_manager.kt +1 -1
  38. package/kit-android/generated/kotlin/org/nativescript/kit/ui_layouts_flexbox_layout_index.kt +1 -1
  39. package/kit-android/generated/kotlin/org/nativescript/kit/ui_search_bar_index.kt +4 -3
  40. package/kit-android/generated/kotlin/org/nativescript/kit/ui_segmented_bar_index.kt +2 -2
  41. package/kit-android/generated/kotlin/org/nativescript/kit/ui_text_base_formatted_string.kt +1 -3
  42. package/kit-android/generated/kotlin/org/nativescript/kit/ui_text_base_index.kt +1 -1
  43. package/kit-android/generated/kotlin/org/nativescript/kit/ui_transition_fade_transition.kt +1 -1
  44. package/kit-android/generated/kotlin/org/nativescript/kit/ui_transition_flip_transition.kt +8 -8
  45. package/kit-android/generated/kotlin/org/nativescript/kit/utils_index.kt +1 -1
  46. package/kit-android/generated/source-lines.json +1 -1
  47. package/kit-android/gradlew.bat +94 -0
  48. package/kit-android/src/main/kotlin/org/nativescript/kit/Signals.kt +15 -2
  49. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity1.swift +2 -15
  50. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity2.swift +9 -3
  51. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity3Plus.swift +11 -7
  52. package/kit-apple/Sources/NativeScriptKit/Core/Object_callback_thisArg_once.swift +1 -1
  53. package/kit-apple/Sources/NativeScriptKit/Core/Object_eventName_object_index_section_view_ios_android.swift +7 -5
  54. package/kit-apple/Sources/NativeScriptKit/Core/Object_eventName_object_oldIndex_newIndex.swift +4 -2
  55. package/kit-apple/Sources/NativeScriptKit/Core/data.observable.index.swift +3 -3
  56. package/kit-apple/Sources/NativeScriptKit/Core/kit-index.json +6 -2
  57. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.weak-event-listener.index.swift +3 -3
  58. package/kit-apple/Sources/NativeScriptKit/Core/ui.gestures.index.ios.swift +2 -2
  59. package/kit-apple/Sources/NativeScriptKit/Core/ui.repeater.index.swift +6 -2
  60. package/kit-apple/Sources/NativeScriptKit/Core/ui.text-base.formatted-string.swift +2 -1
  61. package/kit-apple/Sources/NativeScriptKit/Signals.swift +20 -2
  62. package/package.json +2 -1
@@ -128,8 +128,14 @@ function copyArtifact(artifact, copyTo, projectDir) {
128
128
  return destination;
129
129
  }
130
130
  async function runNodeBin(scriptPath, args, cwd) {
131
+ const env = { ...process.env };
132
+ if (!env.NS_CLI_LIB && process.argv[1]) {
133
+ const candidate = (0, node_path_1.resolve)((0, node_path_1.dirname)(process.argv[1]), '..', 'lib', 'nativescript-cli-lib.js');
134
+ if ((0, node_fs_1.existsSync)(candidate))
135
+ env.NS_CLI_LIB = candidate;
136
+ }
131
137
  return new Promise((resolveCode, reject) => {
132
- const child = (0, node_child_process_1.spawn)(process.execPath, [scriptPath, ...args], { cwd, stdio: 'inherit' });
138
+ const child = (0, node_child_process_1.spawn)(process.execPath, [scriptPath, ...args], { cwd, stdio: 'inherit', env });
133
139
  child.on('error', reject);
134
140
  child.on('close', (code) => resolveCode(code ?? 1));
135
141
  });
package/dist/css/css.js CHANGED
@@ -10,17 +10,41 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
10
10
  import { BIN } from "../driver/paths.js";
11
11
  /** The NativeScript CLI's library, which the bundlers read nativescript.config.ts through. */
12
12
  function cliLibrary(app) {
13
+ const fromEnv = process.env.NS_CLI_LIB;
14
+ if (fromEnv && existsSync(fromEnv))
15
+ return fromEnv;
13
16
  const local = join(app, 'node_modules', 'nativescript', 'lib', 'nativescript-cli-lib.js');
14
17
  if (existsSync(local))
15
18
  return local;
19
+ const probeDir = (dir) => {
20
+ if (!dir)
21
+ return null;
22
+ const beside = join(dir, 'node_modules', 'nativescript', 'lib', 'nativescript-cli-lib.js');
23
+ if (existsSync(beside))
24
+ return beside;
25
+ for (const bin of process.platform === 'win32' ? ['ns.cmd', 'ns'] : ['ns']) {
26
+ const ns = join(dir, bin);
27
+ if (!existsSync(ns))
28
+ continue;
29
+ try {
30
+ const real = dirname(realpathSync(ns));
31
+ for (const candidate of [join(real, '..', 'lib', 'nativescript-cli-lib.js'), join(real, 'node_modules', 'nativescript', 'lib', 'nativescript-cli-lib.js')]) {
32
+ if (existsSync(candidate))
33
+ return candidate;
34
+ }
35
+ }
36
+ catch { }
37
+ }
38
+ return null;
39
+ };
16
40
  for (const dir of (process.env.PATH ?? '').split(delimiter)) {
17
- const ns = join(dir, 'ns');
18
- if (!existsSync(ns))
19
- continue;
20
- const lib = join(dirname(realpathSync(ns)), '..', 'lib', 'nativescript-cli-lib.js');
21
- if (existsSync(lib))
22
- return lib;
41
+ const found = probeDir(dir);
42
+ if (found)
43
+ return found;
23
44
  }
45
+ const besideNode = probeDir(dirname(process.execPath));
46
+ if (besideNode)
47
+ return besideNode;
24
48
  throw new Error("the NativeScript CLI (ns) is needed: its library reads nativescript.config.ts for the app's bundler");
25
49
  }
26
50
  /**
@@ -480,6 +480,7 @@ export async function compile(o, build = new BuildContext()) {
480
480
  resolved,
481
481
  mounted,
482
482
  workers: [...workerScripts],
483
+ aliased,
483
484
  allowUnapplied,
484
485
  allErrors: !!o.allErrors,
485
486
  lenient: lenientApp,
@@ -9,6 +9,13 @@ export const KIT_APPLE_SOURCES = join(KIT_APPLE, 'Sources', 'NativeScriptKit');
9
9
  /** NativeScriptKit for Android: a Gradle project. */
10
10
  export const KIT_ANDROID = join(PACKAGE, 'kit-android');
11
11
  export const BIN = join(PACKAGE, 'bin');
12
+ /** Command and arguments to invoke the bundled Gradle wrapper on the current OS. */
13
+ export function gradleWrapper(args, kit = KIT_ANDROID) {
14
+ if (process.platform === 'win32') {
15
+ return { command: process.env.ComSpec || 'cmd.exe', args: ['/d', '/c', join(kit, 'gradlew.bat'), ...args] };
16
+ }
17
+ return { command: join(kit, 'gradlew'), args };
18
+ }
12
19
  /**
13
20
  * Where the compiler keeps what it fetches and derives once per machine (plugins' sources, their Android libraries,
14
21
  * tools it downloads), outside the installed package: $NS_COMPILED_CACHE, else `nativescript/compiled` in
@@ -363,7 +363,7 @@ export const accessMethods = {
363
363
  if (!ts.isMethodSignature(d))
364
364
  return false;
365
365
  const owner = ts.isInterfaceDeclaration(d.parent) ? this.topName(d.parent, d.parent.name.text) : ts.isTypeLiteralNode(d.parent) && ts.isTypeAliasDeclaration(d.parent.parent) ? this.topName(d.parent.parent, d.parent.parent.name.text) : null;
366
- return !!owner && this.interfaces.has(owner) && !this.protocols.has(owner);
366
+ return !!owner && this.facts.hasInterface(this, this.interfaces, (d, s) => this.topName(d, s), owner) && !this.protocols.has(owner);
367
367
  }));
368
368
  },
369
369
  /** A key as its message names it. */
@@ -52,7 +52,12 @@ export const conversionMethods = {
52
52
  const set = tracked.has(f.name) ? `jsKeySet(field, value, ${kotlinString(f.name)})` : 'value';
53
53
  // A view is made with no fields given: a number or boolean field's backing value unboxes.
54
54
  const unboxed = { Double: '0.0', Boolean: 'false', Int: '0', Long: '0L', Float: '0f' };
55
- lines.push(` ${overrides?.has(f.name) ? 'override ' : ''}var ${ident(memberOf(f))}: ${f.type} = ${unboxed[f.type] ? `${ident(memberOf(f))} ?: ${unboxed[f.type]}` : `${RT.jsUnchecked}(${ident(memberOf(f))})`}`, ` get() { val __r = jsRoot ?: return field; return ${field(f, '__r')} }`, ` set(value) { val __r = jsRoot; if (__r != null) { __r.jsSet(${kotlinString(f.name)}, ${RT.jsBox}(value)); return }; field = ${set}${writes(f)} }`);
55
+ // A view over an untyped object must not fabricate an empty JSArray for a missing or non-array property (`Array.isArray((v as T).arr)`).
56
+ const arrayField = !this.library ? /^JSArray<(.+)>(\??)$/.exec(f.type) : null;
57
+ const viewRead = arrayField
58
+ ? `${RT.jsField}(__r, ${f.key ?? kotlinString(f.name)}).let { __v -> if (__v is JSArray<*> || (__v != null && __v.javaClass.isArray)) ${RT.jsArrayFrom}(__v) { ${this.fromAny('it', arrayField[1])} } else ${arrayField[2] ? 'null' : `${RT.jsUnchecked}<${f.type}>(null)`} }`
59
+ : field(f, '__r');
60
+ lines.push(` ${overrides?.has(f.name) ? 'override ' : ''}var ${ident(memberOf(f))}: ${f.type} = ${unboxed[f.type] ? `${ident(memberOf(f))} ?: ${unboxed[f.type]}` : `${RT.jsUnchecked}(${ident(memberOf(f))})`}`, ` get() { val __r = jsRoot ?: return field; return ${viewRead} }`, ` set(value) { val __r = jsRoot; if (__r != null) { __r.jsSet(${kotlinString(f.name)}, ${RT.jsBox}(value)); return }; field = ${set}${writes(f)} }`);
56
61
  }
57
62
  }
58
63
  else
@@ -406,7 +411,7 @@ export const conversionMethods = {
406
411
  const record = unbox.composite === 'record' ? /^JSRecord<(.*)>(\??)$/.exec(type) : null;
407
412
  // App code: of objects it types as its own classes, which a package's copies (`{ ...entity }`) are not: each read as one.
408
413
  const entry = record?.[1].replace(/\?$/, '');
409
- if (record && !this.library && entry && (this.interfaces.has(entry) || this.isShapeType(entry))) {
414
+ if (record && !this.library && entry && this.isShapeType(entry)) {
410
415
  const read = (x) => `${RT.jsRecordOf}(${x}) { ${this.fromAny('it', record[1])} }`;
411
416
  if (!record[2])
412
417
  return read(code);
@@ -445,9 +450,16 @@ export const conversionMethods = {
445
450
  // A promise its type promises may be any thenable: adopted, as awaiting it or `Promise.resolve` would.
446
451
  const promised = unbox.composite === 'promise' ? /^JSPromise<(.*)>$/.exec(base) : null;
447
452
  if (promised) {
448
- // Kotlin cannot tell a promise's element type: objects read into classes are read as each value arrives.
449
- const read = this.readsIntoClass(promised[1]) ? ` { ${this.fromAny('it', promised[1])} }` : '';
450
- const of = (x) => `${RT.jsPromiseOf}<${promised[1]}>(${x})${read}`;
453
+ // Kotlin cannot tell a promise's element type: convert resolved values as each arrives (including Unit and shapes).
454
+ const inner = promised[1];
455
+ const innerBase = inner.replace(/\?$/, '');
456
+ const converted = inner === 'Unit'
457
+ ? 'Unit'
458
+ : this.readsIntoClass(inner) || (!this.library && !isUntyped(spelledType(inner)) && !this.isTypeParameterName(innerBase))
459
+ ? this.fromAny(this.marks.pureCode('it'), inner)
460
+ : 'it';
461
+ const read = converted !== 'it' ? ` { ${converted} }` : '';
462
+ const of = (x) => `${RT.jsPromiseOf}<${inner}>(${x})${read}`;
451
463
  return type.endsWith('?') ? `${RT.jsUnlessNullish}(${code}) { ${of('it')} }` : of(code);
452
464
  }
453
465
  // Library mode: JavaScript's null where an object goes (`cond ? entry.fragment : null`) is Kotlin's.
@@ -256,14 +256,19 @@ export const expressionsMethods = {
256
256
  // An object of one shape asserted another's (`cur as ICalEvent` of a `Partial<ICalEvent> & {…}`): Kotlin's classes are apart, so
257
257
  // the object is read as the asserted interface's, by its keys.
258
258
  const [fromName, toName] = [from.replace(/\?$/, ''), to.replace(/\?$/, '')];
259
- const fieldClass = (n) => (this.interfaces.has(n) && !this.protocols.has(n)) || !!this.shapes.named(n);
260
- if (!this.library && fromName !== toName && fieldClass(fromName) && this.interfaces.has(toName) && !this.protocols.has(toName)) {
259
+ const fieldClass = (n) => (this.facts.hasInterface(this, this.interfaces, (d, s) => this.topName(d, s), n) && !this.protocols.has(n)) || !!this.shapes.named(n);
260
+ if (!this.library && fromName !== toName && fieldClass(fromName) && this.facts.hasInterface(this, this.interfaces, (d, s) => this.topName(d, s), toName) && !this.protocols.has(toName)) {
261
261
  return from.endsWith('?') ? `${this.expr(e.expression)}?.let { ${this.viewOf(toName, 'it')} }` : this.viewOf(toName, this.expr(e.expression));
262
262
  }
263
263
  if (from !== to && from.replace(/\?$/, '') !== to.replace(/\?$/, '') && this.isObjectRef(e) && this.isObjectRef(e.expression)) {
264
- // Library mode: a script assertion never fails, so a value of another class (a TabViewItem walked up to as a parent) reads as null where null fits.
264
+ // Library mode: a script assertion never fails, so a value of another class (a TabViewItem walked up to as a parent)
265
+ // or a null Java result (`dlg.findViewById(id) as TextView`) reads as null instead of throwing ClassCastException/NPE.
265
266
  if (this.library && this.isClassDowncast(e) && (isNullable(to) || this.functionLiteralArgument(e)))
266
267
  return safeCast(this.expr(e.expression), to.replace(/\?$/, ''));
268
+ if (this.library && this.native?.type(this.checker.getNonNullableType(this.checker.getTypeAtLocation(e))) && this.native?.type(this.checker.getNonNullableType(this.checker.getTypeAtLocation(e.expression)))) {
269
+ const safe = safeCast(this.expr(e.expression), to.replace(/\?$/, ''));
270
+ return isNullable(to) || this.nullOk.has(e) ? safe : this.unchecked(to, safe);
271
+ }
267
272
  return this.classCast(this.expr(e.expression), from, to);
268
273
  }
269
274
  if (from.endsWith('?') && !to.endsWith('?') && from.replace(/\?$/, '') === to)
@@ -2,7 +2,7 @@
2
2
  import ts from 'typescript';
3
3
  import { cast, destructuringSource, ident, isNullable, jsObjectCode, kotlinString, optionalType, splitTopLevel, spell, RT } from "./syntax.js";
4
4
  import { assertedOperand, evolvingElementContext, intersectionAliasMembers, isTypeParameterType, literalKey, openSpreadType, spreadOperand, unquoted, wellKnownMember } from "../semantics/lang.js";
5
- import { holdsNil, literalNotes, signatureField, shapePlanOfLiteral, spelledOptional, resultShapeNamed } from "../semantics/shapes.js";
5
+ import { holdsNil, literalNotes, signatureField, shapePlanOfLiteral, spelledOptional, spreadElementNeedsMap, resultShapeNamed } from "../semantics/shapes.js";
6
6
  import { structural } from "../semantics/conversion.js";
7
7
  import { heldOf, isKit, isUntyped, parseNativeType, spelledType } from "../semantics/types.js";
8
8
  import { boxStep, unboxStep } from "../semantics/type-step.js";
@@ -104,8 +104,7 @@ export const literalsMethods = {
104
104
  run = [];
105
105
  }
106
106
  const items = `(${this.iterable(x.expression)}).toList()`;
107
- // Library mode: an array of untyped values (`const cssClasses = []`) spread where the literal's elements are typed.
108
- parts.push(this.library && !isUntyped(spelledType(el)) && isUntyped(spelledType(this.elementTypeOf(x.expression))) ? `${items}.map { ${this.fromAny('it', el)} }` : items);
107
+ parts.push(spreadElementNeedsMap(this.elementTypeOf(x.expression), el, (n) => this.isShapeType(n), !!this.library) ? `${items}.map { ${this.fromAny('it', el)} }` : items);
109
108
  }
110
109
  else if (ts.isOmittedExpression(x))
111
110
  throw this.error(x, 'an array hole', 'array-hole');
@@ -507,7 +506,7 @@ export const literalsMethods = {
507
506
  },
508
507
  /** An interface's or object shape's Kotlin class. */
509
508
  isShapeType(name) {
510
- return this.interfaces.has(name) || !!this.shapes.named(name) || (!this.library && !!this.core?.viewable?.(name));
509
+ return this.facts.hasInterface(this, this.interfaces, (d, s) => this.topName(d, s), name) || !!this.shapes.named(name) || (!this.library && !!this.core?.viewable?.(name));
511
510
  },
512
511
  /**
513
512
  * A value of one of the app's object types where another goes (`DuoFold` passed as a `StageFold`): TypeScript's
@@ -521,16 +520,15 @@ export const literalsMethods = {
521
520
  return null;
522
521
  const contextual = this.checker.getContextualType(e);
523
522
  const props = contextual ? this.checker.getNonNullableType(contextual).getProperties() : [];
524
- if (!props.length)
525
- return null;
526
523
  // A literal is made as its contextual type already; a copy would lose the keys it notes.
527
- if (ts.isObjectLiteralExpression(ts.skipOuterExpressions(e)) && this.shapes.question(() => this.type(this.checker.getNonNullableType(contextual)).replace(/\?$/, '') === to))
524
+ if (props.length && ts.isObjectLiteralExpression(ts.skipOuterExpressions(e)) && this.shapes.question(() => this.type(this.checker.getNonNullableType(contextual)).replace(/\?$/, '') === to))
528
525
  return this.expr(e);
529
526
  const code = this.expr(e);
530
527
  if (this.constructs(code, to))
531
528
  return code;
532
- const view = this.viewOf(to, '__s');
533
- if (view === `${to}.jsView(__s)`)
529
+ const reader = this.protocols.has(to) ? `${to}Object` : to;
530
+ const view = this.viewOf(reader, '__s');
531
+ if (!props.length || view === `${reader}.jsView(__s)`)
534
532
  return `(${code})${holdsNil(heldOf(spelledType(source))) ? '?' : ''}.let { __s -> ${view} }`;
535
533
  const fields = props
536
534
  .map((p) => programSymbolKey(p, this.checker)?.member ?? wellKnownMember(p.name) ?? p.name)
@@ -94,8 +94,8 @@ export const nativeCallsMethods = {
94
94
  // An optional chain (`?.`) TypeScript types as present: the value, as the code reads it.
95
95
  if (raw.optional && !ts.isPropertyAccessExpression(e.parent) && !ts.isCallExpression(e.parent) && !ts.isElementAccessExpression(e.parent))
96
96
  return this.t.asserted(raw.code);
97
- // Tested or passed on as it is (`intent.getAction() && …`): null is the test's to see.
98
- if (raw.nullable && this.t.library && raw.desc.startsWith('L') && raw.desc !== 'Ljava/lang/CharSequence;' && this.t.nullTolerant(e))
97
+ // Discarded results (`context.registerReceiver(...)`) or null-tolerant uses (`intent.getParcelableExtra(...) as UsbDevice | null`) never dereference null.
98
+ if (raw.nullable && raw.desc.startsWith('L') && raw.desc !== 'Ljava/lang/CharSequence;' && this.t.nullTolerant(e))
99
99
  return raw.code;
100
100
  // `@RecentlyNullable` (android.jar): null passes on as Kotlin's platform types let it, except into a member read or an array's elements.
101
101
  if (raw.recentlyNullable && !raw.optional && ((ts.isPropertyAccessExpression(e.parent) && e.parent.expression === e) || raw.desc.startsWith('[')))
@@ -263,10 +263,91 @@ export const nativeCallsMethods = {
263
263
  if (property)
264
264
  return { code: e.arguments.length ? `run { ${target}.${ident(property)} = ${args} }` : `${target}.${ident(property)}`, desc: e.arguments.length ? 'V' : chosen.ret, optional: target.endsWith('?'), nullable: chosen.m.nullable, recentlyNullable: chosen.m.recentlyNullable };
265
265
  const mapped = r.isStatic ? null : this.mapped(classes, name, chosen.m.descriptor);
266
+ // A generic Java method whose return type parameter is unconstrained by its arguments (e.g. `Intent.getParcelableExtra`,
267
+ // `View.findViewById`) would otherwise infer `Nothing` (`java.lang.Void`) under an unsafe `as` cast.
268
+ const typeArgs = mapped ? '' : this.unconstrainedMethodTypeArgs(chosen.m, e);
266
269
  // Kotlin's own member keeps a function's call parentheses (`toInt()`, `get(i)`) and drops a property's.
267
- const call = mapped ? (/^\.(get|to\w+)$/.test(mapped) ? `${mapped}(${args})` : mapped) : `.${ident(name)}(${args})`;
270
+ const call = mapped ? (/^\.(get|to\w+)$/.test(mapped) ? `${mapped}(${args})` : mapped) : `.${ident(name)}${typeArgs}(${args})`;
268
271
  return { code: `${target}${call}`, desc: chosen.ret, optional: target.endsWith('?'), nullable: chosen.m.nullable, recentlyNullable: chosen.m.recentlyNullable };
269
272
  },
273
+ /**
274
+ * Explicit Kotlin type arguments for a generic Java method when any of its type parameters is not referenced in its
275
+ * parameter list (e.g. `<T::Landroid/os/Parcelable;>(Ljava/lang/String;)TT;`), preventing Kotlin from inferring `Nothing` (`Void`).
276
+ */
277
+ unconstrainedMethodTypeArgs(m, e) {
278
+ const sig = m.signature;
279
+ if (!sig || !sig.startsWith('<'))
280
+ return '';
281
+ // Parse `<Name:ClassBound:InterfaceBound...>` respecting nested generic arguments.
282
+ let depth = 0;
283
+ let headerEnd = -1;
284
+ for (let i = 0; i < sig.length; i++) {
285
+ if (sig[i] === '<')
286
+ depth++;
287
+ else if (sig[i] === '>' && --depth === 0) {
288
+ headerEnd = i;
289
+ break;
290
+ }
291
+ }
292
+ if (headerEnd < 0 || sig[headerEnd + 1] !== '(')
293
+ return '';
294
+ const paramsEnd = sig.indexOf(')', headerEnd + 2);
295
+ if (paramsEnd < 0)
296
+ return '';
297
+ const paramsSig = sig.slice(headerEnd + 2, paramsEnd);
298
+ const header = sig.slice(1, headerEnd);
299
+ const typeParams = [];
300
+ let i = 0;
301
+ while (i < header.length) {
302
+ const colon = header.indexOf(':', i);
303
+ if (colon < 0)
304
+ break;
305
+ const name = header.slice(i, colon);
306
+ i = colon;
307
+ let bound = null;
308
+ while (i < header.length && header[i] === ':') {
309
+ i++;
310
+ if (i >= header.length || header[i] === ':')
311
+ continue;
312
+ const start = i;
313
+ let d = 0;
314
+ while (i < header.length) {
315
+ const ch = header[i];
316
+ if (ch === '<')
317
+ d++;
318
+ else if (ch === '>')
319
+ d--;
320
+ else if (ch === ';' && d === 0) {
321
+ i++;
322
+ break;
323
+ }
324
+ i++;
325
+ }
326
+ const raw = header.slice(start, i);
327
+ if (!bound && raw.startsWith('L')) {
328
+ const internal = raw.slice(1, -1).replace(/<.*$/, '');
329
+ if (internal !== 'java/lang/Object')
330
+ bound = internal;
331
+ }
332
+ }
333
+ typeParams.push({ name, bound });
334
+ }
335
+ if (!typeParams.length || typeParams.every((tp) => paramsSig.includes(`T${tp.name};`)))
336
+ return '';
337
+ const resolved = typeParams.map((tp, k) => {
338
+ const tsArg = e.typeArguments?.[k];
339
+ if (tsArg) {
340
+ const kt = this.t.type(this.t.checker.getTypeFromTypeNode(tsArg), e).replace(/\?$/, '');
341
+ if (kt && kt !== 'Any' && kt !== 'Nothing' && kt !== 'Unit' && !this.t.isTypeParameterName(kt) && (!tp.bound || this.classpath.distance(kt.replace(/\./g, '/'), tp.bound) !== null))
342
+ return kt;
343
+ }
344
+ if (!tp.bound)
345
+ return 'Any?';
346
+ const cls = this.classpath.get(tp.bound);
347
+ return cls && this.typeParamCount(cls) ? this.classRef(cls, undefined, '*', e) : this.kotlinTypeName(tp.bound);
348
+ });
349
+ return `<${resolved.join(', ')}>`;
350
+ },
270
351
  /** `const AccessibilityDelegate = android.view.View['AccessibilityDelegate']`: the nested Java class the alias names. */
271
352
  nestedAlias(e) {
272
353
  const d = ts.isIdentifier(e) ? this.t.resolve(e)?.valueDeclaration : undefined;
@@ -153,9 +153,11 @@ export const overridesMethods = {
153
153
  return this.fromAny(code, to);
154
154
  if (to === optionalType(from))
155
155
  return code;
156
- // An array of one element type where another is declared (`string[]` given as `any[]`): the same array, as script shares it.
157
- if (/^JSArray<.*>$/.test(from.replace(/\?$/, '')) && /^JSArray<.*>$/.test(to.replace(/\?$/, '')) && from.replace(/\?$/, '') !== to.replace(/\?$/, ''))
158
- return this.unchecked(to, code);
156
+ // An array of one element type where another is declared (`string[]` given as `any[]`): convert structural elements, else share the array.
157
+ if (/^JSArray<.*>$/.test(from.replace(/\?$/, '')) && /^JSArray<.*>$/.test(to.replace(/\?$/, '')) && from.replace(/\?$/, '') !== to.replace(/\?$/, '')) {
158
+ const el = !this.library ? this.elementwise(from, to) : null;
159
+ return el ? el(code) : this.unchecked(to, code);
160
+ }
159
161
  // A tuple where an array is declared: its elements.
160
162
  const tuple = /^(Pair|Triple)<.*>$/.exec(from), array = /^JSArray<(.*)>\??$/.exec(to);
161
163
  if (tuple && array)
@@ -168,13 +170,13 @@ export const overridesMethods = {
168
170
  // An object of a known shape where a dictionary is wanted: a dictionary of its entries.
169
171
  const record = /^JSRecord<(.+)>$/.exec(to.replace(/\?$/, ''));
170
172
  const fromShape = from.replace(/\?$/, '');
171
- if (record && (this.interfaces.has(fromShape) || !!this.shapes.named(fromShape))) {
173
+ if (record && this.isShapeType(fromShape)) {
172
174
  const entries = `JSRecord<${record[1]}>(__s.jsKeys.map { __k -> Pair(__k, ${this.fromAny('__s.jsGet(__k)', record[1])}) })`;
173
175
  return from.endsWith('?') ? `${code}?.let { __s -> ${entries} }` : `${code}.let { __s -> ${entries} }`;
174
176
  }
175
177
  // One object shape where another is declared (a wider shape an override returns): not a subclass, read by its keys.
176
178
  const shape = to.replace(/\?$/, '');
177
- if (from.replace(/\?$/, '') !== shape && (this.interfaces.has(shape) || !!this.shapes.named(shape)))
179
+ if (from.replace(/\?$/, '') !== shape && this.isShapeType(shape))
178
180
  return this.fromAny(code, to);
179
181
  if (this.isObjectType(from) && this.isObjectType(to) && from.replace(/\?$/, '') !== to.replace(/\?$/, ''))
180
182
  return this.classCast(code, from, to);
@@ -567,6 +567,8 @@ export const placementMethods = {
567
567
  return elements(code);
568
568
  }
569
569
  }
570
+ if (!this.library && sb === 'JSPromise<Any?>' && /^JSPromise<(.+)>$/.test(tb))
571
+ return this.fromAny(this.functionValue(e), target);
570
572
  if (head(sb) && head(sb) === head(tb) && sb !== tb)
571
573
  return cast(this.functionValue(e), target);
572
574
  if (sb !== tb && anyArguments(sb, tb))
@@ -574,7 +576,7 @@ export const placementMethods = {
574
576
  // An object given where an object type of the program's is declared, which it meets without naming it (`btn` as a `MeasuredView`): read through it by name.
575
577
  const wanted = this.checker.getContextualType(e)?.getSymbol();
576
578
  const programInterface = !!wanted && !!(wanted.flags & ts.SymbolFlags.Interface) && !(wanted.flags & ts.SymbolFlags.Class) && !!wanted.declarations?.every((d) => !d.getSourceFile().isDeclarationFile) && wanted.name === tb;
577
- if (!this.library && sb !== tb && this.isObjectType(sb) && (programInterface || this.interfaces.has(tb) || !!this.shapes.named(tb)) && !this.declaresInterface(this.checker.getTypeAtLocation(e), tb)) {
579
+ if (!this.library && sb !== tb && this.isObjectType(sb) && (programInterface || this.facts.hasInterface(this, this.interfaces, (d, s) => this.topName(d, s), tb) || !!this.shapes.named(tb)) && !this.declaresInterface(this.checker.getTypeAtLocation(e), tb)) {
578
580
  const reader = this.protocols.has(tb) ? `${tb}Object` : tb;
579
581
  return isNullable(target) ? `${this.expr(e)}?.let { ${this.viewOf(reader, 'it')} }` : this.viewOf(reader, this.expr(e));
580
582
  }
@@ -2,10 +2,10 @@
2
2
  import { heldLoss } from "../semantics/losses.js";
3
3
  import ts from 'typescript';
4
4
  import { TYPED_ARRAYS } from "../semantics/globals.js";
5
- import { ident, isThisParameter, optionalType, RT } from "./syntax.js";
5
+ import { ident, isThisParameter, kotlinString, optionalType, RT } from "./syntax.js";
6
6
  import { undefinedLiteral } from "../semantics/lang.js";
7
7
  import { arrayFromLengthInit } from "../semantics/ast.js";
8
- import { assignsArrayIntoObject } from "../semantics/shapes.js";
8
+ import { assignsArrayIntoObject, shapeArrayGuardAccess } from "../semantics/shapes.js";
9
9
  import { CONSOLE } from "../semantics/apis/console.js";
10
10
  import { staticFunction } from "../semantics/apis/statics.js";
11
11
  import { runtimeCall } from "../semantics/apis/api.js";
@@ -121,8 +121,10 @@ export const staticCallsMethods = {
121
121
  if (native)
122
122
  return native;
123
123
  }
124
- if (method === 'isArray')
125
- return `JSArray.isArray(${this.restArgument(e, arg(0), 'Any?')})`;
124
+ if (method === 'isArray') {
125
+ const guard = !this.library ? shapeArrayGuardAccess(arg(0), (t) => this.isShapeType(t), (x) => this.typeOf(x)) : null;
126
+ return guard ? `JSArray.isArray(${this.expr(guard.prop.expression)}${guard.optional ? '?' : ''}.jsGet(${kotlinString(guard.prop.name.text)}))` : `JSArray.isArray(${this.restArgument(e, arg(0), 'Any?')})`;
127
+ }
126
128
  if (method === 'from' && e.arguments.length === 1)
127
129
  return `JSArray(${this.iterable(arg(0))}.toList())`;
128
130
  if (method === 'from' && (e.arguments.length === 2 || e.arguments.length === 3) && ts.isObjectLiteralExpression(arg(0))) {
@@ -89,6 +89,7 @@ export class Translator {
89
89
  translating;
90
90
  /** Android: the worker scripts compiled with the app, by file, and the name the entry registers each under. */
91
91
  workerScripts;
92
+ resolveAlias;
92
93
  /** The generated kit: a module's name for `AppModules.runImport`, set where modules `await import(…)` reaches run when imported. */
93
94
  moduleKey;
94
95
  /** The program's whole-program answers, shared with any translator of the same checker and files. */
@@ -148,6 +149,7 @@ export class Translator {
148
149
  this.checker = checker;
149
150
  this.lenient = c.lenient ?? false;
150
151
  this.workerScripts = c.workerScripts ?? null;
152
+ this.resolveAlias = c.resolveAlias ?? null;
151
153
  this.moduleThread = c.moduleThread ?? null;
152
154
  this.moduleKey = c.moduleKey;
153
155
  this.components = components;
@@ -691,7 +693,7 @@ export class Translator {
691
693
  if (at === 'JSArrayBuffer')
692
694
  return `${t}(${[this.expr(a), ...numbers].join(', ')})`;
693
695
  if (name === 'DataView')
694
- return `${t}((${this.coerce(a, 'Any?')} as JSArrayBufferView).buffer, ${numbers.join(', ')})`;
696
+ return `${t}.from(${[this.coerce(a, 'Any?'), ...numbers].join(', ')})`;
695
697
  if (at === 'Double')
696
698
  return `${t}(${this.expr(a)})`;
697
699
  if (isKit(spelledType(at), 'JSArray'))
@@ -714,18 +716,36 @@ export class Translator {
714
716
  });
715
717
  return `object : ${this.className(base)}() {\n${members.join('\n')}\n}`;
716
718
  }
717
- /** `new URL('./x.worker', import.meta.url)`: the worker script it names, when the app compiled it. */
719
+ /** `new Worker('~/x')`, `new Worker('./x')`, or `new Worker(new URL('./x', import.meta.url))`: the worker script it names, when the app compiled it. */
718
720
  workerScript(e) {
719
- if (!ts.isNewExpression(e) || !ts.isIdentifier(e.expression) || e.expression.text !== 'URL')
720
- return null;
721
- const [spec, base] = e.arguments ?? [];
722
- if (!spec || !ts.isStringLiteralLike(spec) || !base || base.getText() !== 'import.meta.url')
721
+ let spec = null;
722
+ if (ts.isStringLiteralLike(e)) {
723
+ spec = e.text;
724
+ }
725
+ else if (ts.isNewExpression(e) && ts.isIdentifier(e.expression) && e.expression.text === 'URL') {
726
+ const [s, base] = e.arguments ?? [];
727
+ if (s && ts.isStringLiteralLike(s) && base && base.getText() === 'import.meta.url')
728
+ spec = s.text;
729
+ }
730
+ if (!spec || !this.workerScripts?.size)
723
731
  return null;
724
- const stem = pathResolve(pathDirname(e.getSourceFile().fileName), spec.text).replace(/\.(ts|js)$/, '');
725
- for (const f of [stem + '.ts', stem + '.android.ts', stem + '/index.ts']) {
726
- const script = this.workerScripts?.get(f);
727
- if (script)
728
- return script;
732
+ const file = e.getSourceFile().fileName;
733
+ const target = spec.startsWith('.') ? pathResolve(pathDirname(file), spec) : this.resolveAlias?.(spec, file);
734
+ if (target) {
735
+ const stem = target.replace(/\\/g, '/').replace(/\.(tsx?|m?js)$/, '');
736
+ for (const f of [stem + '.ts', stem + '.android.ts', stem + '.tsx', stem + '/index.ts', stem + '/index.android.ts']) {
737
+ const script = this.workerScripts.get(f);
738
+ if (script)
739
+ return script;
740
+ }
741
+ }
742
+ if (spec.startsWith('~/') || spec.startsWith('@/')) {
743
+ const rel = spec.slice(2).replace(/\\/g, '/').replace(/\.(tsx?|m?js)$/, '');
744
+ for (const [key, script] of this.workerScripts) {
745
+ const norm = key.replace(/\\/g, '/');
746
+ if ([`/${rel}.ts`, `/${rel}.android.ts`, `/${rel}.tsx`, `/${rel}/index.ts`, `/${rel}/index.android.ts`].some((s) => norm.endsWith(s)))
747
+ return script;
748
+ }
729
749
  }
730
750
  return null;
731
751
  }
@@ -86,12 +86,20 @@ export const typeFactsMethods = {
86
86
  /** Whether a read of `e` only tests or passes on its value, so a nullable declaration needs no unwrap there. */
87
87
  nullTolerant(e) {
88
88
  let n = e;
89
- while (ts.isParenthesizedExpression(n.parent))
89
+ while (ts.isParenthesizedExpression(n.parent) ||
90
+ ((ts.isAsExpression(n.parent) || ts.isTypeAssertionExpression(n.parent)) &&
91
+ (() => {
92
+ const pt = this.typeOf(n.parent);
93
+ return isUntyped(spelledType(pt)) || isNullable(pt) || this.isTypeParameterName(pt);
94
+ })()))
90
95
  n = n.parent;
91
96
  if (this.nullOk.has(n) || this.nullOk.has(e) || this.states.observedAsIs(e))
92
97
  return true;
93
98
  const p = n.parent;
94
99
  const K = ts.SyntaxKind;
100
+ // A discarded expression (`context.registerReceiver(...)`, `void expr`) never dereferences its result.
101
+ if (ts.isExpressionStatement(p) || ts.isVoidExpression(p))
102
+ return true;
95
103
  // A branch of a conditional, or `a ?? b`'s `b`, where the whole goes where missing is taken; or a result a function gives as nullable.
96
104
  if (ts.isConditionalExpression(p) && (p.whenTrue === n || p.whenFalse === n))
97
105
  return this.nullTolerant(p);
@@ -101,7 +109,7 @@ export const typeFactsMethods = {
101
109
  const fn = ts.isArrowFunction(p) ? p : ts.findAncestor(p, ts.isFunctionLike);
102
110
  if (fn && (ts.isMethodDeclaration(fn) || ts.isFunctionDeclaration(fn) || ts.isGetAccessorDeclaration(fn))) {
103
111
  const rt = this.returnTypeOf(fn);
104
- if (isNullable(rt) || isUntyped(spelledType(rt)))
112
+ if (isNullable(rt) || isUntyped(spelledType(rt)) || (this.library && this.isTypeParameterName(rt)))
105
113
  return true;
106
114
  }
107
115
  }
@@ -4,7 +4,7 @@ import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync,
4
4
  import { homedir } from 'node:os';
5
5
  import { dirname, join, relative, resolve } from 'node:path';
6
6
  import { archiveClasses } from "../kotlin/native/classfiles.js";
7
- import { cacheDir, KIT_ANDROID } from "../driver/paths.js";
7
+ import { cacheDir, gradleWrapper, KIT_ANDROID } from "../driver/paths.js";
8
8
  import { byName, compareText } from "../program/order.js";
9
9
  /** What the plugin libraries are built with: the generated app's (targets/android/build.ts). */
10
10
  const AGP = '8.12.1', KOTLIN = '2.2.20', COMPILE_SDK = 36, KIT_MIN_SDK = 24;
@@ -193,7 +193,8 @@ ${l.include?.libraryBlocks.join('\n\n') ?? ''}
193
193
  });
194
194
  options.say?.(`building the Android code of ${libraries.map((l) => `${l.source.name}@${l.source.version}`).join(', ')}`);
195
195
  try {
196
- execFileSync(join(kit, 'gradlew'), ['-p', root, 'assembleRelease', '-PtempBuild=true', '--quiet'], { stdio: 'inherit' });
196
+ const gw = gradleWrapper(['-p', root, 'assembleRelease', '-PtempBuild=true', '--quiet'], kit);
197
+ execFileSync(gw.command, gw.args, { stdio: 'inherit' });
197
198
  }
198
199
  catch {
199
200
  throw new Error(`the Android code of ${libraries.map((l, i) => `${l.source.name} (:p${i})`).join(', ')} did not build (Gradle's output is above)`);
@@ -415,6 +416,33 @@ export function parseIncludeGradle(text) {
415
416
  });
416
417
  return;
417
418
  }
419
+ if (blockOf('compileOptions')) {
420
+ i++;
421
+ statements((c) => {
422
+ if (!is(c, 'id', 'sourceCompatibility') && !is(c, 'id', 'targetCompatibility') && !is(c, 'id', 'encoding'))
423
+ unsupported(c);
424
+ i++;
425
+ if (is(peek(), 'punct', '='))
426
+ i++;
427
+ if (is(peek(), 'str') || is(peek(), 'num')) {
428
+ i++;
429
+ return;
430
+ }
431
+ // `JavaVersion.VERSION_1_8` or `JavaVersion.toVersion(...)`.
432
+ expect('id');
433
+ while (is(peek(), 'punct', '.')) {
434
+ i++;
435
+ expect('id');
436
+ }
437
+ if (is(peek(), 'punct', '(')) {
438
+ i++;
439
+ while (!is(peek(), 'punct', ')') && !is(peek(), 'end'))
440
+ i++;
441
+ expect('punct', ')');
442
+ }
443
+ });
444
+ return;
445
+ }
418
446
  if (!is(s, 'id', 'defaultConfig'))
419
447
  unsupported(s);
420
448
  i++;