@nstudio/nativescript-compiler 9.2.0-alpha.13 → 9.2.0-alpha.14

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 (30) hide show
  1. package/dist/css/worker.js +2 -2
  2. package/dist/kotlin/arguments.js +5 -2
  3. package/dist/kotlin/assignment.js +3 -0
  4. package/dist/kotlin/builtins.js +1 -1
  5. package/dist/kotlin/conversion.js +3 -0
  6. package/dist/kotlin/core-api.js +17 -0
  7. package/dist/kotlin/declarations.js +7 -2
  8. package/dist/kotlin/library.js +2 -2
  9. package/dist/kotlin/modules.js +2 -1
  10. package/dist/kotlin/narrowing.js +2 -1
  11. package/dist/kotlin/static-calls.js +17 -5
  12. package/dist/kotlin/translator.js +15 -0
  13. package/dist/kotlin/type-facts.js +3 -2
  14. package/dist/kotlin/types.js +4 -2
  15. package/dist/swift/builtins.js +12 -2
  16. package/dist/swift/library.js +1 -1
  17. package/dist/swift/modules.js +2 -1
  18. package/dist/swift/type-facts.js +2 -0
  19. package/dist/swift/types.js +3 -3
  20. package/dist/targets/android/build.js +9 -7
  21. package/dist/targets/ios/build.js +1 -1
  22. package/kit-android/generated/kotlin/org/nativescript/kit/file_system_file_system_access.kt +1 -1
  23. package/kit-android/generated/kotlin/org/nativescript/kit/http_http_request_internal_index.kt +1 -1
  24. package/kit-android/generated/kotlin/org/nativescript/kit/ui_text_base_formatted_string.kt +2 -2
  25. package/kit-android/generated/kotlin/org/nativescript/kit/ui_text_base_text_base_common.kt +2 -2
  26. package/kit-android/gradlew.bat +2 -2
  27. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Iterators.kt +1 -0
  28. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Promise.kt +4 -3
  29. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Workers.kt +39 -11
  30. package/package.json +1 -1
@@ -19,7 +19,7 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
19
19
  // rewrite, Vite's preprocessCSS, rework-css's parse).
20
20
  import fs, { readFileSync, writeFileSync } from 'node:fs';
21
21
  import { createRequire } from 'node:module';
22
- import { dirname, join, relative } from 'node:path';
22
+ import { dirname, isAbsolute, join, relative } from 'node:path';
23
23
  import { pathToFileURL } from 'node:url';
24
24
  const [outFile, cliLib, platform, ...stylesheets] = process.argv.slice(2);
25
25
  /** Components' stylesheets, by path: they have no file of their own. */
@@ -97,7 +97,7 @@ async function webpackSheets(configPath) {
97
97
  const resolveLoader = (name) => {
98
98
  for (const dir of loaderDirs) {
99
99
  try {
100
- return dir.startsWith('/') ? createRequire(join(dir, 'index.js')).resolve(join(dir, name)) : appRequire.resolve(name);
100
+ return isAbsolute(dir) ? createRequire(join(dir, 'index.js')).resolve(join(dir, name)) : appRequire.resolve(name);
101
101
  }
102
102
  catch { }
103
103
  }
@@ -123,9 +123,12 @@ export const argumentsMethods = {
123
123
  for (let k = 0; k < list.length; k++) {
124
124
  const a = list[k];
125
125
  if (restAt >= 0 && k >= restAt && appDeclared) {
126
- const calleeParam = ts.isCallExpression(e) ? functionTypeParts(this.typeOf(e.expression).replace(/^\((.*)\)\?$/, '$1'))?.params[restAt] : undefined;
126
+ const restDecl = params[restAt].valueDeclaration;
127
+ const erasedRest = this.library && !!restDecl && ts.isParameter(restDecl) && (!!restDecl.parent.typeParameters?.length || (ts.isClassLike(restDecl.parent.parent) && !!restDecl.parent.parent.typeParameters?.length));
128
+ const overloadedRest = !!impl && impl !== sig?.getDeclaration();
129
+ const calleeParam = ts.isCallExpression(e) && !erasedRest && !overloadedRest ? functionTypeParts(this.typeOf(e.expression).replace(/^\((.*)\)\?$/, '$1'))?.params[restAt] : undefined;
127
130
  const rest = calleeParam?.startsWith('JSArray<') && calleeParam.endsWith('>') ? calleeParam : this.restType(params[restAt]);
128
- out.push(this.packed(list.slice(k), rest, this.restSlot(e, rest.replace(/^JSArray<(.*)>$/, '$1'), params[restAt].valueDeclaration)));
131
+ out.push(this.packed(list.slice(k), rest, this.restSlot(e, rest.replace(/^JSArray<(.*)>$/, '$1'), restDecl)));
129
132
  break;
130
133
  }
131
134
  if (ts.isSpreadElement(a)) {
@@ -202,6 +202,9 @@ export const assignmentMethods = {
202
202
  isPromiseType(this.nativeOf(left.expression)));
203
203
  if (ts.isPropertyAccessExpression(left) && !this.library && this.isGlobalObject(left.expression))
204
204
  return `${RT.jsSet}(jsGlobalThis, ${kotlinString(left.name.text)}, ${this.untypedCallable(right)})`;
205
+ if (ts.isPropertyAccessExpression(left) && !this.library && this.typeOf(left.expression).replace(/\?$/, '') === 'JSWorker' && (left.name.text === 'onmessage' || left.name.text === 'onerror')) {
206
+ return `${RT.jsSet}(${this.expr(left.expression)}, ${kotlinString(left.name.text)}, ${this.untypedCallable(right)})`;
207
+ }
205
208
  // `record.key = v` of a `Record<string, T>`: its entry.
206
209
  const record = ts.isPropertyAccessExpression(left) ? /^JSRecord<(.*)>\??$/.exec(this.typeOf(left.expression)) : null;
207
210
  if (record && ts.isPropertyAccessExpression(left))
@@ -478,7 +478,7 @@ export const builtinMethods = {
478
478
  /** A rejection handler: it takes the reason untyped, whatever its parameter declares. */
479
479
  rejectionHandler(e, ret) {
480
480
  if (!(ts.isArrowFunction(e) || ts.isFunctionExpression(e)))
481
- return this.isAny(e) ? this.fn(e, `(Any?) -> ${ret ?? 'Any?'}`) : this.fn(e);
481
+ return this.fn(e, `(Any?) -> ${ret ?? 'Any?'}`);
482
482
  if (!e.parameters.length)
483
483
  return this.closure(e, `(Any?) -> ${ret ?? this.returnTypeOf(e)}`);
484
484
  const p = e.parameters[0];
@@ -433,6 +433,9 @@ export const conversionMethods = {
433
433
  return read(code);
434
434
  return this.marks.isPure(code) ? `(if (${RT.jsIsNullish}(${code})) null else ${read(code)})` : `${RT.jsUnlessNullish}(${code}) { ${read('it')} }`;
435
435
  }
436
+ if (!this.library && (type === 'JSWorker' || type === 'JSWorker?')) {
437
+ return type.endsWith('?') ? `${RT.jsUnlessNullish}(${code}) { JSWorker.fromAny(it) }` : `JSWorker.fromAny(${code})`;
438
+ }
436
439
  if (!this.library && /^[A-Z]\w*\??$/.test(type)) {
437
440
  const reified = this.reifiedRead(code, type);
438
441
  if (reified)
@@ -383,6 +383,23 @@ export class CoreKotlin extends KitTypes {
383
383
  const ps = Array.from({ length: arity }, (_, k) => `__s${k}`);
384
384
  return `{ ${ps.map((p) => `${p}: Any?`).join(', ')} -> ${recv}.${name}(${ps.join(', ')}) }`;
385
385
  }
386
+ // A kit method with non-null Kotlin default parameters (e.g. `flags: Double = 2.0`) where TS types the parameter optional (`Double?`):
387
+ // a method reference drops the default and keeps non-null `Double`, so wrap in a lambda that forwards the default.
388
+ const parsedParams = (m.params ?? '').trim()
389
+ ? splitTopLevel(m.params).map((p) => {
390
+ const hit = /^([^:]+):\s*(.+?)(?:\s*=\s*(.+))?$/.exec(p.trim());
391
+ return hit ? { type: hit[2].trim(), def: hit[3]?.trim() } : null;
392
+ })
393
+ : [];
394
+ const tsParts = functionTypeParts(t.typeOf(e).replace(/^\((.*)\)\?$/, '$1'));
395
+ if (tsParts && parsedParams.length === tsParts.params.length && parsedParams.every(Boolean) && parsedParams.some((p, k) => p.def && !p.type.endsWith('?') && tsParts.params[k].endsWith('?'))) {
396
+ const ps = tsParts.params.map((pt, k) => `__p${k}: ${pt}`);
397
+ const callArgs = parsedParams.map((p, k) => (p.def && !p.type.endsWith('?') && tsParts.params[k].endsWith('?') ? `(__p${k} ?: ${p.def})` : `__p${k}`));
398
+ const call = (r) => `{ ${ps.join(', ')} -> ${r}.${name}(${callArgs.join(', ')}) }`;
399
+ if (owner.isStatic)
400
+ return call(recv);
401
+ return recv.endsWith('?') ? `${recv.slice(0, -1)}?.let { __r -> ${call('__r')} }` : `(${recv}).let { __r -> ${call('__r')} }`;
402
+ }
386
403
  // A Kotlin object's own function is referenced on the object; a class's static, on its companion.
387
404
  if (owner.isStatic)
388
405
  return this.index.get(owner.name)?.object ? `${recv}::${name}` : `${recv}.Companion::${name}`;
@@ -455,8 +455,13 @@ export const declarationsMethods = {
455
455
  // A match reads its values as an array does.
456
456
  const js = ts.isArrayBindingPattern(name) && !/^JSMatch\??$/.test(this.typeOf(init)) ? this.patternIteration(init) : null;
457
457
  // A literal builds a shape class of its own, which the pattern's contextual shape need not be.
458
- if (!js)
459
- return ts.isObjectLiteralExpression(init) ? ` = ${this.expr(init)}` : `: ${this.typeOf(init)} = ${this.coerce(init, this.typeOf(init))}`;
458
+ if (!js) {
459
+ if (ts.isObjectLiteralExpression(init))
460
+ return ` = ${this.expr(init)}`;
461
+ const t = this.typeOf(init);
462
+ const target = isNullable(t) && !isUntyped(spelledType(t)) ? t.slice(0, -1) : t;
463
+ return `: ${target} = ${this.coerce(init, target)}`;
464
+ }
460
465
  const rest = name.elements.some((el) => ts.isBindingElement(el) && el.dotDotDotToken);
461
466
  return ` = JSArray(ArrayList(${js}.${rest ? 'jsCollect()' : `jsTake(${name.elements.length})`}))`;
462
467
  },
@@ -1,7 +1,7 @@
1
- import { SHARED_LIB_CONSTANTS } from "../semantics/globals.js";
1
+ import { BUFFER_TYPES, SHARED_LIB_CONSTANTS } from "../semantics/globals.js";
2
2
  import { RT } from "./syntax.js";
3
3
  // No prototype: a name like `toString` is no error class.
4
- export const BUILTIN_CLASSES = Object.assign(Object.create(null), { Promise: 'JSPromise<*>', Array: 'JSArray<*>', Map: 'JSMap<*, *>', Set: 'JSSet<*>', Date: 'JSDate' });
4
+ export const BUILTIN_CLASSES = Object.assign(Object.create(null), { Promise: 'JSPromise<*>', Array: 'JSArray<*>', Map: 'JSMap<*, *>', Set: 'JSSet<*>', Date: 'JSDate', RegExp: 'JSRegExp' }, Object.fromEntries([...BUFFER_TYPES].map((n) => [n, `JS${n}`])));
5
5
  /** Core classes kit-android implements under another name. */
6
6
  export const KIT_NAMES_ANDROID = { ViewBase: 'View', ViewCommon: 'View', EditableTextBase: 'TextBase', LayoutBaseCommon: 'LayoutBase' };
7
7
  /** `Math`'s functions, as Kotlin calls them. */
@@ -740,10 +740,11 @@ export const modulesMethods = {
740
740
  interfacesOf(file) {
741
741
  let out = '';
742
742
  const emitted = new Set();
743
+ const norm = file.replace(/\\/g, '/');
743
744
  for (let more = true; more;) {
744
745
  more = false;
745
746
  for (const [name, decl] of this.interfaces) {
746
- if (decl.file !== file || emitted.has(name) || !this.used.has(name))
747
+ if (decl.file.replace(/\\/g, '/') !== norm || emitted.has(name) || !this.used.has(name))
747
748
  continue;
748
749
  out = decl.code() + '\n\n' + out;
749
750
  emitted.add(name);
@@ -43,7 +43,8 @@ export const narrowingMethods = {
43
43
  const keyed = (actual === 'Double' || actual === 'String') && this.states.unsetNullField(e) ? this.states.nullableEntry(e, () => this.expr(e)) : null;
44
44
  if (keyed)
45
45
  return () => `${actual === 'Double' ? RT.jsToNumber : RT.jsToString}(${keyed})`;
46
- if (['String', 'Double', 'Boolean'].includes(actual) && this.states.nilIsNull(e))
46
+ const nullishDefault = !!sym?.valueDeclaration && ts.isParameter(sym.valueDeclaration) && !!sym.valueDeclaration.initializer && this.states.nullishHeld(sym.valueDeclaration);
47
+ if (['String', 'Double', 'Boolean'].includes(actual) && (this.states.nilIsNull(e) || nullishDefault))
47
48
  return (code) => nullAs(code, actual);
48
49
  if (this.lenient || ['String', 'Double', 'Boolean'].includes(actual))
49
50
  return (code) => this.undefinedAs(code, actual);
@@ -2,7 +2,7 @@
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, kotlinString, optionalType, RT } from "./syntax.js";
5
+ import { functionTypeParts, 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
8
  import { assignsArrayIntoObject, shapeArrayGuardAccess } from "../semantics/shapes.js";
@@ -125,8 +125,14 @@ export const staticCallsMethods = {
125
125
  const guard = !this.library ? shapeArrayGuardAccess(arg(0), (t) => this.isShapeType(t), (x) => this.typeOf(x)) : null;
126
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
127
  }
128
- if (method === 'from' && e.arguments.length === 1)
129
- return `JSArray(${this.iterable(arg(0))}.toList())`;
128
+ if (method === 'from' && e.arguments.length === 1) {
129
+ const seq = this.iterable(arg(0));
130
+ const el = T().replace(/^JSArray<(.*)>$/, '$1');
131
+ if (el !== T() && !isUntyped(spelledType(el)) && (this.isAny(arg(0)) || !!this.jsIteration(arg(0)) || /^(Pair|Triple)</.test(this.typeOf(arg(0)).replace(/\?$/, '')))) {
132
+ return `JSArray<${el}>(${seq}.map { ${this.fromAny('it', el)} })`;
133
+ }
134
+ return `JSArray(${seq}.toList())`;
135
+ }
130
136
  if (method === 'from' && (e.arguments.length === 2 || e.arguments.length === 3) && ts.isObjectLiteralExpression(arg(0))) {
131
137
  const lenExpr = arrayFromLengthInit(arg(0));
132
138
  const fn = arg(1);
@@ -141,8 +147,14 @@ export const staticCallsMethods = {
141
147
  return `JSArray.fromLength<${el}>(${this.toNumber(lenExpr)}, fun(${index}: Double): ${el} { ${value}${body.slice(1, -1)} })`;
142
148
  });
143
149
  }
144
- if (method === 'from' && (e.arguments.length === 2 || e.arguments.length === 3))
145
- return this.ignoringThisArg(e, arg(0), () => `JSArray(${this.iterable(arg(0))}.toList()).map(${this.fn(arg(1))})`);
150
+ if (method === 'from' && (e.arguments.length === 2 || e.arguments.length === 3)) {
151
+ return this.ignoringThisArg(e, arg(0), () => {
152
+ const seq = this.iterable(arg(0));
153
+ const p0 = functionTypeParts(this.typeOf(arg(1)).replace(/^\((.*)\)\?$/, '$1'))?.params[0];
154
+ const arr = p0 && !isUntyped(spelledType(p0)) && (this.isAny(arg(0)) || !!this.jsIteration(arg(0))) ? `JSArray<${p0}>(${seq}.map { ${this.fromAny('it', p0)} })` : `JSArray(${seq}.toList())`;
155
+ return `${arr}.map(${this.fn(arg(1))})`;
156
+ });
157
+ }
146
158
  if (method === 'of')
147
159
  return `${RT.jsArrayOf}<${T().replace(/^JSArray<(.*)>$/, '$1')}>(${a().join(', ')})`;
148
160
  // `Array.apply(thisArg, list)`: `Array(...list)`, a length when the list is one number.
@@ -194,6 +194,21 @@ export class Translator {
194
194
  };
195
195
  visit(f);
196
196
  }
197
+ // Mark unviewable interface object classes upfront before any module translates, so cross-file `fromAny` never emits `.jsView(...)` for one.
198
+ for (const f of this.sourceFiles) {
199
+ if (f.isDeclarationFile)
200
+ continue;
201
+ for (const st of f.statements) {
202
+ if (!ts.isInterfaceDeclaration(st))
203
+ continue;
204
+ const name = this.topName(st, st.name.text);
205
+ const all = this.withInherited(st, st.members);
206
+ if (this.protocols.has(name) && all.some(ts.isMethodSignature))
207
+ this.unviewable.add(`${name}Object`);
208
+ else if (!this.protocols.has(name) && all.some((m) => !!m.name && ts.isComputedPropertyName(m.name)))
209
+ this.unviewable.add(name);
210
+ }
211
+ }
197
212
  }
198
213
  /** A class whose methods and accessors are read by name: a substitution's, which untyped code reads as often as typed code does, or a `ValueStates.viewedClass`. */
199
214
  membersByName(cls) {
@@ -54,8 +54,9 @@ export const typeFactsMethods = {
54
54
  // Lenient code: an optional member's type does not say it may be missing.
55
55
  if (this.lenient && (ts.isPropertySignature(decl) || ts.isPropertyDeclaration(decl)) && decl.questionToken)
56
56
  t = optionalType(t);
57
- // A parameter with a default is nullable in its signature only; the body sees it filled in.
58
- if (ts.isParameter(decl) && decl.questionToken)
57
+ // A parameter with a default is nullable in its signature only; the body sees it filled in,
58
+ // except when held as `JSNullish<T>` (where `.optional` is nullable until narrowed/unwrapped).
59
+ if (ts.isParameter(decl) && (decl.questionToken || this.states.nullishHeld(decl)))
59
60
  t = optionalType(t);
60
61
  if ((this.nullableDecls.has(sym) || this.states.looseDeclaration(decl) || this.states.lenientNullField(decl) || (ts.isPropertyAccessExpression(e) && (['String', 'Double', 'Boolean'].includes(t) || this.states.unsetMember(decl)) && this.states.shapeFieldOptional(sym))) && !isUntyped(spelledType(t)))
61
62
  t = optionalType(t);
@@ -182,10 +182,12 @@ export const typesMethods = {
182
182
  const a = args()[k];
183
183
  return a ? this.type(a, where) : 'Any?';
184
184
  };
185
- if (name && sym?.declarations?.[0]?.getSourceFile().fileName === '/__shims__/globals.d.ts') {
185
+ if (name && sym?.declarations?.length && sym.declarations.every((d) => d.getSourceFile().isDeclarationFile)) {
186
186
  if (isWebClass(this.ledger, name))
187
187
  return `JS${name}`;
188
- if (WEB_DICTIONARIES.includes(name))
188
+ if (name === 'DedicatedWorkerGlobalScope' && this.ledger.workerGlobals)
189
+ return 'JSWorker';
190
+ if (WEB_DICTIONARIES.includes(name) && (sym.declarations[0].getSourceFile().fileName === '/__shims__/globals.d.ts' || isLibDeclaration(sym.declarations[0])))
189
191
  return 'Any?';
190
192
  }
191
193
  // Library mode: a Java class named as a library type (`java.util.Map`, `java.util.Iterator`) is the Java class.
@@ -653,6 +653,12 @@ export const builtinMethods = {
653
653
  const call = this.marks.tryCode(`${RT.jsCall}(${this.expr(e)}, __reason)`);
654
654
  return `{ (__reason: Any?) throws -> ${result} in ${result === 'Void' ? `_ = ${call}` : `return ${this.fromAnyCode(call, result, true)}`} }`;
655
655
  }
656
+ // A 0-arg function value (`run: () => Promise<T>`): wrap to ignore the rejection reason.
657
+ const parts = functionParts(this.typeOf(e).replace(/^\((.*)\)!$/, '$1'));
658
+ if (parts && !parts.params.length) {
659
+ const call = this.marks.tryCode(`(${this.fn(e)})()`);
660
+ return `{ (_: Any?) throws -> ${parts.result} in ${parts.result === 'Void' ? call : `return ${call}`} }`;
661
+ }
656
662
  return this.fn(e);
657
663
  }
658
664
  // A handler that only rethrows (`(error) => { …; throw error; }`) is typed as the promise's other handler.
@@ -688,8 +694,12 @@ export const builtinMethods = {
688
694
  let onFulfilled = nullFulfilled ? `{ (__v: ${value}) -> ${value} in ${value === 'Never' ? 'switch __v {}' : '__v'} }` : ignores ? this.closure(f, [`_ __unused: ${value}`]) : f && this.fn(f);
689
695
  // A function value taking its arguments as a rest (`then(log)` of a `log(...values)`), or any value where the promise's is
690
696
  // undefined (`then($DONE)`, which Swift would pass `()`): called with the one value, as it holds it.
691
- const own = f && !adopt && !ts.isArrowFunction(f) && !ts.isFunctionExpression(f) ? functionParts(this.typeOf(f).replace(/^\((.*)\)!$/, '$1')) : null;
692
- if (own && (own.rest >= 0 || (value === 'Void' && own.params.length && own.params[0] !== 'Void')))
697
+ const own = f && !nullFulfilled && !ts.isArrowFunction(f) && !ts.isFunctionExpression(f) ? functionParts(this.typeOf(f).replace(/^\((.*)\)!$/, '$1')) : null;
698
+ if (own && !own.params.length && value !== 'Void') {
699
+ const call = this.marks.tryCode(`(${this.fn(f)})()`);
700
+ onFulfilled = `{ (_: ${value}) throws -> ${own.result} in ${own.result === 'Void' ? call : `return ${call}`} }`;
701
+ }
702
+ else if (own && !adopt && (own.rest >= 0 || (value === 'Void' && own.params.length && own.params[0] !== 'Void')))
693
703
  onFulfilled = this.coerce(f, `(${value}) throws -> ${own.result}`);
694
704
  // A handler declaring the type of what an untyped promise settles with (`.then((r: Item) => …)` of a `Promise<any>`): it takes the value untyped, read as that type.
695
705
  const declared = f && !ignores && isUntyped(spelledType(value)) && (ts.isArrowFunction(f) || ts.isFunctionExpression(f)) && f.parameters.length ? this.closureParamType(f.parameters[0]) : undefined;
@@ -14,7 +14,7 @@ export const DESCRIPTORS = new Set(['PropertyDescriptor', 'TypedPropertyDescript
14
14
  export const ARRAY_CALLBACK_METHODS = new Set(['forEach', 'map', 'filter', 'some', 'every', 'find', 'findIndex', 'findLast', 'findLastIndex', 'flatMap']);
15
15
  export const isTypedArrayType = (t) => /^JS(Int8|Uint8|Uint8Clamped|Int16|Uint16|Int32|Uint32|Float32|Float64|BigInt64|BigUint64)Array$/.test(t);
16
16
  // No prototype: a name like `toString` is no error class.
17
- export const BUILTIN_CLASSES = Object.assign(Object.create(null), { Promise: 'JSThenable', Array: 'JSArrayProtocol', Map: 'JSMapProtocol', Set: 'JSSetProtocol', Date: 'JSDate' }, Object.fromEntries([...BUFFER_TYPES].map((n) => [n, `JS${n}`])));
17
+ export const BUILTIN_CLASSES = Object.assign(Object.create(null), { Promise: 'JSThenable', Array: 'JSArrayProtocol', Map: 'JSMapProtocol', Set: 'JSSetProtocol', Date: 'JSDate', RegExp: 'JSRegExp' }, Object.fromEntries([...BUFFER_TYPES].map((n) => [n, `JS${n}`])));
18
18
  /** Library functions read as values, with their Swift function types. */
19
19
  export const LIB_FUNCTION_VALUES = {
20
20
  clearTimeout: { code: `{ (__id: Any?) -> Void in ${RT.jsClearTimeout}(${RT.jsIsNullish}(__id) ? nil : ${RT.jsToNumber}(__id)) }`, type: '(Any?) throws -> Void' },
@@ -709,11 +709,12 @@ export const modulesMethods = {
709
709
  interfacesOf(file) {
710
710
  let out = '';
711
711
  const emitted = new Set();
712
+ const norm = file.replace(/\\/g, '/');
712
713
  // An interface's own fields can use another one.
713
714
  for (let more = true; more;) {
714
715
  more = false;
715
716
  for (const [name, decl] of this.interfaces) {
716
- if (decl.file !== file || emitted.has(name) || !this.used.has(name))
717
+ if (decl.file.replace(/\\/g, '/') !== norm || emitted.has(name) || !this.used.has(name))
717
718
  continue;
718
719
  out = decl.code() + '\n\n' + out;
719
720
  emitted.add(name);
@@ -326,6 +326,8 @@ export const typeFactsMethods = {
326
326
  return `${t}?`;
327
327
  if (isFunctionType(t) && this.widenedFunctionField(decl))
328
328
  return optionalType(t);
329
+ if (ts.isParameter(decl) && this.states.nullishHeld(decl))
330
+ return optionalType(t);
329
331
  return isWriteTarget(e) && (this.looseObjectDeclaration(decl, t) || (ts.isParameter(decl) && this.states.mayBeNull(decl))) ? optionalType(t) : t;
330
332
  },
331
333
  /**
@@ -174,11 +174,11 @@ export const typesMethods = {
174
174
  const a = args()[k];
175
175
  return a ? this.type(a, where) : 'Any?';
176
176
  };
177
- // Core's own code (library mode) is typed by the DOM's library, whose web classes are the runtime's too.
178
- if (name && (sym?.declarations?.[0]?.getSourceFile().fileName === '/__shims__/globals.d.ts' || (this.library && isLibDeclaration(sym?.declarations?.[0])))) {
177
+ // Core's own code and apps using DOM/core global typings: web classes declared in .d.ts map to the runtime's.
178
+ if (name && sym?.declarations?.length && sym.declarations.every((d) => d.getSourceFile().isDeclarationFile)) {
179
179
  if (isWebClass(this.ledger, name))
180
180
  return `JS${name}`;
181
- if (WEB_DICTIONARIES.includes(name))
181
+ if (WEB_DICTIONARIES.includes(name) && (sym.declarations[0].getSourceFile().fileName === '/__shims__/globals.d.ts' || isLibDeclaration(sym.declarations[0])))
182
182
  return 'Any?';
183
183
  }
184
184
  const kind = name === undefined ? undefined : this.framework.signalKind(name);
@@ -53,15 +53,17 @@ export async function writeAndroid(b) {
53
53
  bindingDefines.push(...prepared.defines);
54
54
  }
55
55
  const classPath = androidClassPath(widgets, native);
56
+ const slash = (p) => p.replace(/\\/g, '/');
56
57
  // The app's own typings of Java APIs no package types (`declare module androidx { … }` in a script .d.ts).
57
- const appDir = resolve(b.app) + '/';
58
- const appTypings = b.program.getSourceFiles().filter((sf) => sf.isDeclarationFile && sf.fileName.startsWith(appDir) && !sf.fileName.includes('/node_modules/') && !/^(import|export)\b/m.test(sf.text) && /^declare\s+(module|namespace)\s+(android|androidx|java|javax|com|org|kotlin|io)\b/m.test(sf.text));
58
+ const appDir = slash(resolve(b.app)) + '/';
59
+ const appTypings = b.program.getSourceFiles().filter((sf) => sf.isDeclarationFile && slash(sf.fileName).startsWith(appDir) && !slash(sf.fileName).includes('/node_modules/') && !/^(import|export)\b/m.test(sf.text) && /^declare\s+(module|namespace)\s+(android|androidx|java|javax|com|org|kotlin|io)\b/m.test(sf.text));
60
+ const allModuleFiles = [...b.modules, ...b.components.map((c) => c.file), ...(b.compiledPlugins ?? [])].map(slash);
59
61
  if (b.workers?.length) {
60
- const writes = sharedWorkerState(b.program, b.workers, new Set([...b.modules, ...b.components.map((c) => c.file), ...(b.compiledPlugins ?? [])]), b.resolved);
62
+ const writes = sharedWorkerState(b.program, b.workers.map(slash), new Set(allModuleFiles), b.resolved);
61
63
  if (writes.length)
62
64
  throw sharedWorkerStateError(writes, b.app);
63
65
  }
64
- const moduleFiles = [...new Set([...b.modules, ...b.components.map((c) => c.file), ...(b.compiledPlugins ?? [])])];
66
+ const moduleFiles = [...new Set(allModuleFiles)];
65
67
  // Which modules run on the main thread only; a worker's script reaching one stops the build with the import chain.
66
68
  const threads = moduleThreads({ program: b.program, modules: moduleFiles, workers: b.workers, resolved: b.resolved, coreModuleOf: (f) => /[\\/]@nativescript[\\/]core[\\/](.+)$/.exec(f)?.[1] ?? null });
67
69
  // A module only `await import(…)` reaches (and what only it imports) runs when it is imported, as the bundle evaluates
@@ -92,7 +94,7 @@ export async function writeAndroid(b) {
92
94
  errors: b.allErrors ? [] : null,
93
95
  plainFields: !!b.translatorHooks?.plainFields,
94
96
  appMembersByName: !!b.xml && !b.xmlMemberKeys,
95
- pluginRoots: (b.plugins ?? []).map((p) => p.root + '/'),
97
+ pluginRoots: (b.plugins ?? []).map((p) => slash(p.root) + '/'),
96
98
  workerScripts: new Map((b.workers ?? []).map((f) => [f.replace(/\\/g, '/'), relative(b.app, f).replace(/\\/g, '/')])),
97
99
  resolveAlias: b.aliased ?? null,
98
100
  moduleThread: (file) => threads.get(file),
@@ -354,8 +356,8 @@ project(":kit").projectDir = file(${kotlinString(kitProjectDir(b.out))})
354
356
  const adapterSources = [adapterKotlin, androidGenerated].filter((d) => !!d && existsSync(d));
355
357
  writeFileSync(join(b.out, 'gradle.properties'), `org.gradle.jvmargs=-Xmx4g -Dfile.encoding=UTF-8
356
358
  android.useAndroidX=true
357
- nativescriptWidgetsAar=${widgets}
358
- ${overlay ? `kitOverlay=${join(KIT_ANDROID, 'overlays', XML_FREE_OVERLAY)}\nkitOverlayReplaces=${overlay.replaces.join(',')}\n` : ''}${adapterSources.length ? `kitAdapterSources=${adapterSources.join(',')}\n` : ''}`);
359
+ nativescriptWidgetsAar=${slash(widgets)}
360
+ ${overlay ? `kitOverlay=${slash(join(KIT_ANDROID, 'overlays', XML_FREE_OVERLAY))}\nkitOverlayReplaces=${overlay.replaces.join(',')}\n` : ''}${adapterSources.length ? `kitAdapterSources=${adapterSources.map(slash).join(',')}\n` : ''}`);
359
361
  writeFileSync(join(b.out, 'build.gradle.kts'), `plugins {
360
362
  id("com.android.application") version "8.12.1"
361
363
  id("com.android.library") version "8.12.1" apply false
@@ -77,7 +77,7 @@ export async function writeIos(b) {
77
77
  const translator = new Translator(checker, infos, sourceFiles, {
78
78
  ...context.translation(),
79
79
  pluginFiles,
80
- pluginRoots: plugins.all().map((p) => p.root + '/'),
80
+ pluginRoots: plugins.all().map((p) => p.root.replace(/\\/g, '/') + '/'),
81
81
  lenientFiles,
82
82
  reach,
83
83
  properties,
@@ -2342,7 +2342,7 @@ open class FileSystemAccess : JSExpando {
2342
2342
 
2343
2343
  companion object {
2344
2344
  fun getBuffer(buffer: Any?): Any? {
2345
- if ((buffer is Any)) {
2345
+ if ((buffer is JSArrayBuffer)) {
2346
2346
  return jsOr(
2347
2347
  jsGet((jsCastCarried(buffer, JSArrayBuffer::class.java)), "nativeObject")
2348
2348
  ) {
@@ -161,7 +161,7 @@ object Core_http_http_request_internal_index {
161
161
  ?: jsObjectRequired())
162
162
  )
163
163
  javaOptions.content = nativeBuffer
164
- } else if ((jsGet(options, "content") is Any)) {
164
+ } else if ((jsGet(options, "content") is JSArrayBuffer)) {
165
165
  val typedArray: JSUint8Array =
166
166
  JSUint8Array(jsCastCarried(jsGet(options, "content"), JSArrayBuffer::class.java))
167
167
  val nativeBuffer: ByteBuffer? =
@@ -142,7 +142,7 @@ open class FormattedString : ViewBase {
142
142
  open fun _addArrayFromBuilder(name: String?, value: JSArray<Any?>?) {
143
143
  if (name == "spans") {
144
144
  (this.spans ?: jsCannotRead("push")).push(
145
- JSArray<Span>(((value ?: jsObjectRequired())).toList())
145
+ JSArray<Any?>(((value ?: jsObjectRequired())).toList())
146
146
  )
147
147
  }
148
148
  }
@@ -150,7 +150,7 @@ open class FormattedString : ViewBase {
150
150
  open fun _addChildFromBuilder(name: String?, value: Any?) {
151
151
  if ((value is Span)) {
152
152
  (this.spans ?: jsCannotRead("push")).push(
153
- JSArray<Span>(listOf<Span>(jsCastCarried(value, Span::class.java)))
153
+ JSArray<Any?>(listOf<Any?>(jsCastCarried(value, Span::class.java)))
154
154
  )
155
155
  }
156
156
  }
@@ -219,13 +219,13 @@ abstract class TextBaseCommon : View {
219
219
  if (!jsTruthy(this.formattedText)) {
220
220
  val formattedText: FormattedString = FormattedString()
221
221
  (formattedText.spans ?: jsCannotRead("push")).push(
222
- JSArray<Span>(listOf<Span>(jsCastCarried(value, Span::class.java)))
222
+ JSArray<Any?>(listOf<Any?>(value))
223
223
  )
224
224
  this.formattedText = formattedText
225
225
  } else {
226
226
  ((this.formattedText ?: jsCannotRead("spans")).spans
227
227
  ?: jsCannotRead("push"))
228
- .push(JSArray<Span>(listOf<Span>(jsCastCarried(value, Span::class.java))))
228
+ .push(JSArray<Any?>(listOf<Any?>(value)))
229
229
  }
230
230
  } else if (
231
231
  name == Core_ui_text_base_text_base_common.CHILD_FORMATTED_TEXT ||
@@ -70,11 +70,11 @@ goto fail
70
70
  :execute
71
71
  @rem Setup the command line
72
72
 
73
- set CLASSPATH=
73
+ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
74
74
 
75
75
 
76
76
  @rem Execute Gradle
77
- "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
77
+ "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
78
78
 
79
79
  :end
80
80
  @rem End local scope for the variables with windows NT shell
@@ -205,6 +205,7 @@ fun <T> jsAsyncIterable(value: JSAsyncIterableValue): JSAsyncIterable<T> = JSAsy
205
205
  /** GetIterator for an untyped value. */
206
206
  fun jsIteratorOf(value: Any?, message: String? = null): JSIterator<Any?> = when (val v = jsBox(value)) {
207
207
  is JSIterableValue -> JSIteratorAdapter(v.jsAnyIterator())
208
+ is JSTypedArray<*, *> -> { val values = v.jsAnyValues.iterator(); JSIterator { if (values.hasNext()) values.next() else JSIterator.END } }
208
209
  is JSArray<*> -> { var i = 0; JSIterator { if (i < v.storage.size) v.storage[i++] else JSIterator.END } }
209
210
  is String -> JSIteratorAdapter(jsIterator(v))
210
211
  is JSMatch -> jsIteratorOf(v.values)
@@ -259,14 +259,15 @@ class JSPromise<T> internal constructor() : JSThenable, JSDynamic {
259
259
  }
260
260
 
261
261
  /** Resolving with a native promise: NewPromiseResolveThenableJob, then that promise's `then`. */
262
- internal fun adopt(other: JSPromise<T>) {
262
+ @Suppress("UNCHECKED_CAST")
263
+ internal fun adopt(other: JSPromise<*>) {
263
264
  if (other === this) {
264
265
  settleRejected(JSTypeError("Chaining cycle detected for promise #<Promise>"))
265
266
  return
266
267
  }
267
268
  Microtasks.enqueue {
268
269
  val resolvers = JSResolvers(this)
269
- other.performThen({ resolvers.resolve(it) }, { resolvers.reject(it) })
270
+ other.performThen({ resolvers.resolve(it as T) }, { resolvers.reject(it) })
270
271
  }
271
272
  }
272
273
 
@@ -629,7 +630,7 @@ class JSAsync<T> {
629
630
  }
630
631
 
631
632
  /** `return promise`: adopted through a NewPromiseResolveThenableJob, two ticks later than `return await`. */
632
- fun returnPromise(other: JSPromise<T>) {
633
+ fun returnPromise(other: JSPromise<*>) {
633
634
  if (settled) return
634
635
  settled = true
635
636
  promise.adopt(other)
@@ -54,13 +54,13 @@ class JSErrorEvent(val message: String) : JSDynamic {
54
54
  * runs in one live worker at a time; a new one of a script whose worker is stopping starts once
55
55
  * that worker's thread has ended.
56
56
  */
57
- class JSWorker(scriptURL: Any?, script: String? = null) : JSDynamic {
57
+ class JSWorker private constructor(private val scope: JSObject?) : JSDynamic {
58
58
  var onmessage: ((JSMessageEvent) -> Any?)? = null
59
59
  var onerror: ((JSErrorEvent) -> Any?)? = null
60
60
 
61
61
  private val owner = JSRealm.current()
62
62
  private val realm = JSRealm()
63
- private val key: String
63
+ private var key: String = ""
64
64
  private val inbox = LinkedBlockingQueue<() -> Unit>()
65
65
  /** `terminate()`: nothing more runs in the worker, and nothing more reaches the creator. */
66
66
  @Volatile private var terminated = false
@@ -69,11 +69,11 @@ class JSWorker(scriptURL: Any?, script: String? = null) : JSDynamic {
69
69
  /** When the worker's next timer is due, in `System.nanoTime()`; only its thread reads and writes it. */
70
70
  private var wake: Long? = null
71
71
  /** The worker's thread; it ends once the worker is terminated or closed and its running task returns. */
72
- val thread: Thread
72
+ lateinit var thread: Thread
73
73
 
74
74
  private val live: Boolean get() = !terminated && !closing
75
75
 
76
- init {
76
+ constructor(scriptURL: Any?, script: String? = null) : this(null) {
77
77
  val entry = script?.let { scripts[it] }
78
78
  ?: throw JSException(JSError("Worker script ${jsToString(scriptURL)} was not compiled with the app"))
79
79
  if (owner.post == null) throw JSException(JSError("Worker: the creating thread has no event loop to receive messages"))
@@ -144,6 +144,11 @@ class JSWorker(scriptURL: Any?, script: String? = null) : JSDynamic {
144
144
 
145
145
  /** `worker.postMessage(message, transfer)`: the buffers listed move to the worker; a stopped worker drops it. */
146
146
  fun postMessage(message: Any?, transfer: Any? = null) {
147
+ if (scope != null) {
148
+ if (transfer == null) jsCallMethod(scope, "postMessage", message)
149
+ else jsCallMethod(scope, "postMessage", message, transfer)
150
+ return
151
+ }
147
152
  if (!live) return
148
153
  val data = jsStructuredClone(message, jsTransferred(transfer))
149
154
  inbox.put { jsGetOptional(realm.global, "onmessage")?.let { jsCall(it, JSMessageEvent(data)) } }
@@ -185,26 +190,42 @@ class JSWorker(scriptURL: Any?, script: String? = null) : JSDynamic {
185
190
 
186
191
  /** `terminate()`: queued messages and timers are dropped; a blocking call in progress finishes first. */
187
192
  fun terminate() {
193
+ if (scope != null) {
194
+ jsCallMethod(scope, "close")
195
+ return
196
+ }
188
197
  if (terminated) return
189
198
  terminated = true
190
199
  inbox.put {}
191
200
  }
192
201
 
193
- override fun jsGet(key: String): Any? = when (key) {
194
- "postMessage" -> JSMethod { _, a -> postMessage(a.getOrNull(0), a.getOrNull(1)); null }
195
- "terminate" -> JSMethod { _, _ -> terminate(); null }
196
- "onmessage" -> onmessage
197
- "onerror" -> onerror
198
- else -> null
202
+ /** `close()`: on a worker global scope, stops the worker after the current task. */
203
+ fun close() {
204
+ if (scope != null) jsCallMethod(scope, "close")
205
+ else terminate()
199
206
  }
207
+
208
+ override fun jsGet(key: String): Any? =
209
+ if (scope != null) scope.jsGet(key)
210
+ else when (key) {
211
+ "postMessage" -> JSMethod { _, a -> postMessage(a.getOrNull(0), a.getOrNull(1)); null }
212
+ "terminate" -> JSMethod { _, _ -> terminate(); null }
213
+ "onmessage" -> onmessage
214
+ "onerror" -> onerror
215
+ else -> null
216
+ }
200
217
  override fun jsSet(key: String, value: Any?) {
218
+ if (scope != null) {
219
+ scope.jsSet(key, value)
220
+ return
221
+ }
201
222
  val handler: ((Any?) -> Any?)? = if (jsIsFunction(value)) { event -> jsCall(value, event) } else null
202
223
  when (key) {
203
224
  "onmessage" -> onmessage = handler
204
225
  "onerror" -> onerror = handler
205
226
  }
206
227
  }
207
- override val jsKeys: List<String> get() = emptyList()
228
+ override val jsKeys: List<String> get() = scope?.jsKeys ?: emptyList()
208
229
  override val jsClassName: String? get() = "Worker"
209
230
 
210
231
  companion object {
@@ -213,6 +234,13 @@ class JSWorker(scriptURL: Any?, script: String? = null) : JSDynamic {
213
234
 
214
235
  /** A worker script the app compiled, by its path in the app: its module's top level, run on the worker's thread. */
215
236
  fun register(script: String, entry: () -> Unit) { scripts[script] = entry }
237
+
238
+ /** `globalThis as Worker` inside a worker script: wraps the worker realm's global object as a `JSWorker`. */
239
+ fun fromAny(value: Any?): JSWorker = when (value) {
240
+ is JSWorker -> value
241
+ is JSObject -> JSWorker(value)
242
+ else -> jsUnchecked(jsJavaArgument(value))
243
+ }
216
244
  }
217
245
  }
218
246
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nstudio/nativescript-compiler",
3
- "version": "9.2.0-alpha.13",
3
+ "version": "9.2.0-alpha.14",
4
4
  "description": "NativeScript CLI plugin (`ns compile`) and compiler turning a NativeScript app into native Swift (iOS) or Kotlin (Android) with no JavaScript runtime; framework adapters (`@nstudio/nativescript-compiler-<framework>`) compile each framework.",
5
5
  "type": "module",
6
6
  "keywords": [