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

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 (90) hide show
  1. package/dist/driver/compile.js +4 -3
  2. package/dist/kotlin/arguments.js +2 -1
  3. package/dist/kotlin/builtins.js +14 -3
  4. package/dist/kotlin/class-accessors.js +1 -1
  5. package/dist/kotlin/class-constructor.js +3 -1
  6. package/dist/kotlin/class-declaration.js +3 -2
  7. package/dist/kotlin/class-methods.js +29 -12
  8. package/dist/kotlin/components.js +39 -14
  9. package/dist/kotlin/construction.js +4 -5
  10. package/dist/kotlin/conversion.js +16 -3
  11. package/dist/kotlin/core-api.js +14 -7
  12. package/dist/kotlin/declarations.js +1 -1
  13. package/dist/kotlin/expressions.js +10 -5
  14. package/dist/kotlin/modules.js +7 -3
  15. package/dist/kotlin/names.js +5 -2
  16. package/dist/kotlin/optional-chains.js +24 -5
  17. package/dist/kotlin/overrides.js +7 -2
  18. package/dist/kotlin/placement.js +5 -4
  19. package/dist/kotlin/translator.js +0 -39
  20. package/dist/kotlin/types.js +4 -5
  21. package/dist/kotlin/untyped-values.js +7 -1
  22. package/dist/program/program.js +3 -3
  23. package/dist/semantics/apis/array.js +11 -0
  24. package/dist/semantics/classes.js +24 -0
  25. package/dist/semantics/config.js +2 -0
  26. package/dist/semantics/forms/by-name.js +45 -19
  27. package/dist/semantics/globals.js +8 -2
  28. package/dist/semantics/lang.js +21 -1
  29. package/dist/semantics/ledger.js +0 -24
  30. package/dist/semantics/platform-globals.js +0 -16
  31. package/dist/semantics/refusals.js +1 -1
  32. package/dist/semantics/runtime.js +2 -0
  33. package/dist/semantics/throws.js +7 -0
  34. package/dist/semantics/worker-state.js +41 -1
  35. package/dist/swift/assignment.js +3 -0
  36. package/dist/swift/builtins.js +8 -10
  37. package/dist/swift/class-accessors.js +1 -1
  38. package/dist/swift/class-declaration.js +3 -2
  39. package/dist/swift/class-methods.js +19 -2
  40. package/dist/swift/construction.js +5 -1
  41. package/dist/swift/conversion.js +1 -1
  42. package/dist/swift/expressions.js +2 -4
  43. package/dist/swift/from-any.js +5 -0
  44. package/dist/swift/global-calls.js +8 -1
  45. package/dist/swift/object-classes.js +2 -1
  46. package/dist/swift/placement.js +6 -0
  47. package/dist/swift/protocols.js +30 -20
  48. package/dist/swift/types.js +4 -3
  49. package/dist/targets/ios/build.js +22 -7
  50. package/docs/cli/compile-ios.md +1 -1
  51. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_properties_index.kt +6 -6
  52. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_view_view_common.kt +1 -1
  53. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Collections.kt +15 -6
  54. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Promise.kt +1 -1
  55. package/kit-apple/Overlays/xml-free/Core/ui.core.bindable.index.swift +13 -2
  56. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity1.swift +0 -12
  57. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity2.swift +0 -39
  58. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity3Plus.swift +0 -44
  59. package/kit-apple/Sources/NativeScriptKit/Core/application.application-common.swift +19 -2
  60. package/kit-apple/Sources/NativeScriptKit/Core/color.color-common.swift +17 -0
  61. package/kit-apple/Sources/NativeScriptKit/Core/color.index.ios.swift +60 -0
  62. package/kit-apple/Sources/NativeScriptKit/Core/kit-index.json +90 -25
  63. package/kit-apple/Sources/NativeScriptKit/Core/text.text-common.swift +9 -1
  64. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.bindable.index.swift +13 -2
  65. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.view-base.index.swift +26 -2
  66. package/kit-apple/Sources/NativeScriptKit/Core/ui.gestures.gestures-common.swift +2 -0
  67. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.liquid-glass-container.index.ios.swift +12 -2
  68. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.root-layout.root-layout-common.swift +46 -6
  69. package/kit-apple/Sources/NativeScriptKit/Core/ui.list-view.index.ios.swift +37 -3
  70. package/kit-apple/Sources/NativeScriptKit/Core/ui.split-view.split-view-common.swift +12 -1
  71. package/kit-apple/Sources/NativeScriptKit/Core/ui.styling.css-selector.swift +50 -6
  72. package/kit-apple/Sources/NativeScriptKit/Core/ui.text-base.text-base-common.swift +13 -1
  73. package/kit-apple/Sources/NativeScriptKit/Runtime/Collections.swift +5 -1
  74. package/kit-apple/Sources/NativeScriptKit/Runtime/Dynamic.swift +13 -2
  75. package/kit-apple/Sources/NativeScriptKit/Runtime/Errors.swift +10 -2
  76. package/kit-apple/Sources/NativeScriptKit/Runtime/Functions.swift +57 -12
  77. package/kit-apple/Sources/NativeScriptKit/Runtime/Lowering.swift +12 -3
  78. package/kit-apple/Sources/NativeScriptKit/Runtime/Promise.swift +56 -29
  79. package/kit-apple/Sources/NativeScriptKit/Runtime/Realm.swift +92 -0
  80. package/kit-apple/Sources/NativeScriptKit/Runtime/Record.swift +25 -5
  81. package/kit-apple/Sources/NativeScriptKit/Runtime/RegExp.swift +13 -4
  82. package/kit-apple/Sources/NativeScriptKit/Runtime/RegExpEngine.swift +14 -5
  83. package/kit-apple/Sources/NativeScriptKit/Runtime/Symbol.swift +28 -6
  84. package/kit-apple/Sources/NativeScriptKit/Runtime/Threads.swift +2 -2
  85. package/kit-apple/Sources/NativeScriptKit/Runtime/Timers.swift +93 -47
  86. package/kit-apple/Sources/NativeScriptKit/Runtime/TypedArrays.swift +37 -9
  87. package/kit-apple/Sources/NativeScriptKit/Runtime/Values.swift +6 -4
  88. package/kit-apple/Sources/NativeScriptKit/Runtime/Views.swift +11 -2
  89. package/kit-apple/Sources/NativeScriptKit/Runtime/Workers.swift +680 -0
  90. package/package.json +1 -1
@@ -3,7 +3,7 @@ import { heldLoss } from "../semantics/losses.js";
3
3
  import ts from 'typescript';
4
4
  import { MATH, MATH_OF_SPREAD, isTypedArrayType } from "./library.js";
5
5
  import { mathFunction } from "../semantics/apis/math.js";
6
- import { arrayMember } from "../semantics/apis/array.js";
6
+ import { arrayMember, typedFlatPlan } from "../semantics/apis/array.js";
7
7
  import { collectionMember } from "../semantics/apis/mapset.js";
8
8
  import { argumentRunsConversion, numberMember } from "../semantics/apis/number.js";
9
9
  import { promiseMember } from "../semantics/apis/promise.js";
@@ -235,18 +235,16 @@ export const builtinMethods = {
235
235
  case 'values':
236
236
  return `${t}.${name}()`;
237
237
  case 'flat': {
238
- const [depth] = e.arguments;
239
- if (!depth)
238
+ const plan = typedFlatPlan(e, el, isUntyped(spelledType(el)));
239
+ if (plan.kind === 'default')
240
240
  return `${t}.flat()`;
241
- if (isUntyped(spelledType(el)))
242
- return `${t}.flat(${this.coerce(depth, 'Double')})`;
243
- // A typed array flattens one level per `flat()`, as deep as its type nests.
244
- const levels = Math.min(Number(ts.isNumericLiteral(depth) ? depth.text : NaN), /^(JSArray<)*/.exec(el)[0].length / 8);
245
- if (levels >= 1)
246
- return t + '.flat()'.repeat(levels);
241
+ if (plan.kind === 'chain')
242
+ return t + plan.suffix;
243
+ if (plan.untyped)
244
+ return `${t}.flat(${this.coerce(plan.arg, 'Double')})`;
247
245
  if (q)
248
246
  throw this.error(e, 'flat with a depth on an optional array');
249
- return this.convert(`JSArray<Any?>(${t}.jsAnyElements).flat(${this.coerce(depth, 'Double')})`, 'JSArray<Any?>', this.typeOf(e));
247
+ return this.convert(`JSArray<Any?>(${t}.jsAnyElements).flat(${this.coerce(plan.arg, 'Double')})`, 'JSArray<Any?>', this.typeOf(e));
250
248
  }
251
249
  case 'toLocaleString':
252
250
  if (!e.arguments.length)
@@ -80,7 +80,7 @@ export const classAccessorsMethods = {
80
80
  this.declare(n, { kind: 'var', mods, type: declared, throws: !!a.get && !reported && this.throwsInfo.fn(a.get) });
81
81
  // A plugin's objects are read untyped too (`navigator.gpu.native`): their accessors by name.
82
82
  const own = (a.get ?? a.set);
83
- if (this.byNameAccessor(cls, own) && !ts.isPrivateIdentifier(own.name)) {
83
+ if ((this.byNameAccessor(cls, own) || k.droppedProtocolMembers.has(n)) && !ts.isPrivateIdentifier(own.name)) {
84
84
  const getThrows = !!a.get && this.throwsInfo.fn(a.get) && !reported;
85
85
  const read = getThrows ? this.marks.orNil(`${RT.jsReported} { try self.${ident(n)} }`) : `self.${ident(n)}`;
86
86
  const stored = () => (declared.endsWith('!') ? this.fromAny('newValue', declared.replace(/!$/, '?')) : isKit(spelledType(declared), 'JSNullish') ? `(${RT.jsConverted}(newValue, to: ${declared}.self) ?? nil)` : this.fromAnyCode('newValue', declared, true));
@@ -5,7 +5,7 @@ import { atLossSite, HELD_LOSS } from "../semantics/losses.js";
5
5
  import { ERRORS } from "../semantics/globals.js";
6
6
  import { NONISOLATED_DEINIT, ident, swiftString, RT } from "./syntax.js";
7
7
  import { UNKEYED, memberPlanOf, notesNull, nullNames, definedNamesOf } from "../semantics/shapes.js";
8
- import { initializedNull } from "../semantics/lang.js";
8
+ import { droppedProtocolMemberNames, initializedNull } from "../semantics/lang.js";
9
9
  import { isStatic } from "../semantics/throws.js";
10
10
  import { isCoreDeclaration, isShimDeclaration } from "../program/core-facts.js";
11
11
  import { classExprCaptures, classExprScriptName, programBase } from "../semantics/classes.js";
@@ -111,6 +111,7 @@ export const classDeclMethods = {
111
111
  // The library's interfaces (`Iterable<T>`, `Iterator<T>`) are protocols of the kit's, conformed to below.
112
112
  const witnesses = [];
113
113
  const { named, met, implemented } = this.implementedProtocols(cls, kitRoot, witnesses);
114
+ const droppedProtocolMembers = droppedProtocolMemberNames(c, cls, this.protocols, implemented, (i) => this.heritageName(i), (_, t, n) => this.uncompiledType(t) || (t.getSymbol()?.declarations ?? []).every((d) => d.getSourceFile().isDeclarationFile && (this.library || !isCoreDeclaration(d) || !this.core.has(n))) || this.conformsToProtocol(cls, n));
114
115
  // What a protocol requires the class reads without throwing: a getter that throws reports instead.
115
116
  const required = new Set([...named, ...met].filter((i) => implemented.includes(i.name)).flatMap((i) => i.type.getProperties().map((p) => p.name)));
116
117
  const conformances = [...(base ? [base] : []), ...(collection && !appBase && !implemented.length ? ['JSDynamic'] : []), ...implemented];
@@ -130,7 +131,7 @@ export const classDeclMethods = {
130
131
  conformances.push('JSToJSONConvertible');
131
132
  implicitlyCalled.add('toJSON');
132
133
  }
133
- return { cls, name, layout, heritage, appBase, base, kitRoot, collection, isError, expando, isView, implemented, witnesses, required, conformances, implicitlyCalled, lines: [''], fieldInits: [], fields: [], paramPropValues: new Map(), symbolFields: [], symbolMethods: [], keyInits: [], symKeyCount: 0, dynAccessors: [], dynMethods: [] };
134
+ return { cls, name, layout, heritage, appBase, base, kitRoot, collection, isError, expando, isView, implemented, droppedProtocolMembers, witnesses, required, conformances, implicitlyCalled, lines: [''], fieldInits: [], fields: [], paramPropValues: new Map(), symbolFields: [], symbolMethods: [], keyInits: [], symKeyCount: 0, dynAccessors: [], dynMethods: [] };
134
135
  },
135
136
  conversionMembers(k) {
136
137
  const { cls, layout, lines } = k;
@@ -160,6 +160,21 @@ export const classMethodsMethods = {
160
160
  methodMembers(k) {
161
161
  for (const m of k.cls.members)
162
162
  this.methodMember(k, m);
163
+ for (const n of k.droppedProtocolMembers) {
164
+ if (k.dynMethods.some((d) => d.name === n))
165
+ continue;
166
+ const inh = this.inheritedMethod(k.cls, n);
167
+ if (!inh || !inh.body || isStatic(inh) || ts.isPrivateIdentifier(inh.name))
168
+ continue;
169
+ const restAt = inh.parameters.findIndex((p) => p.dotDotDotToken);
170
+ const generic = !this.library && !this.erasesGenerics(inh) && !!inh.typeParameters?.some((p) => !this.erasesTypeParameter(p));
171
+ if ((restAt >= 0 && restAt !== inh.parameters.length - 1) || generic)
172
+ continue;
173
+ const sig = this.emittedSignature(inh);
174
+ const plain = (t) => t.replace(/^\((any .*)\)!$/, '$1?').replace(/!$/, '?');
175
+ const params = this.readsArguments(inh) ? ['JSRest<Any?>'] : sig.params.map((p, idx) => (idx === restAt ? `JSRest<${/^JSArray<(.*)>$/.exec(plain(p.type))?.[1] ?? 'Any?'}>` : isFunctionType(p.type) ? `@escaping ${p.type}` : plain(p.type)));
176
+ k.dynMethods.push({ name: n, type: `(${params.join(', ')}) throws -> ${plain(sig.ret)}`, available: this.gatedFunctions.get(inh), length: scriptLength(inh) });
177
+ }
163
178
  },
164
179
  methodMember(k, m) {
165
180
  const { cls, kitRoot, lines } = k;
@@ -222,13 +237,15 @@ export const classMethodsMethods = {
222
237
  lines.push(' ' + this.memberFunc(m, ident(nonVirtualName(n, cls.name?.text ?? k.name)), 'final '));
223
238
  // A plugin's objects are read untyped too (`handler.attachToView(view)` on an `any`): their methods by name.
224
239
  const restAt = m.parameters.findIndex((p) => p.dotDotDotToken);
225
- if ((((this.pluginFiles.has(cls.getSourceFile().fileName) || this.appMembersByName || this.states.downcastClass(cls) || this.states.byNameClass(cls)) && this.states.byNameMember(cls, n)) || this.states.viewedMember(cls, n)) && !isStatic(m) && !ts.isPrivateIdentifier(m.name) && (restAt < 0 || restAt === m.parameters.length - 1) && !extra.length && !generic) {
240
+ if ((((this.pluginFiles.has(cls.getSourceFile().fileName) || this.appMembersByName || this.states.downcastClass(cls) || this.states.byNameClass(cls)) && this.states.byNameMember(cls, n)) || this.states.viewedMember(cls, n) || k.droppedProtocolMembers.has(n)) && !isStatic(m) && !ts.isPrivateIdentifier(m.name) && (restAt < 0 || restAt === m.parameters.length - 1) && !extra.length && !generic) {
226
241
  // The signature Swift has for the method: an override's is its root's.
227
242
  const sig = this.emittedSignature(m);
228
243
  const plain = (t) => t.replace(/^\((any .*)\)!$/, '$1?').replace(/!$/, '?');
229
244
  // A method reading `arguments` takes the call's arguments as one list; a rest parameter (`fill(...args)`) the arguments from its place.
230
245
  const params = this.readsArguments(m) ? ['JSRest<Any?>'] : sig.params.map((p, k) => (k === restAt ? `JSRest<${/^JSArray<(.*)>$/.exec(plain(p.type))?.[1] ?? 'Any?'}>` : isFunctionType(p.type) ? `@escaping ${p.type}` : plain(p.type)));
231
- k.dynMethods.push({ name: n, type: `(${params.join(', ')}) throws -> ${plain(sig.ret)}`, available: this.gatedFunctions.get(m), length: scriptLength(m) });
246
+ const defFrom = !overridden && !this.readsArguments(m) && restAt < 0 ? m.parameters.findIndex((p) => p.initializer) : -1;
247
+ const trailingFrom = defFrom >= 0 && !m.typeParameters?.length && m.parameters.slice(defFrom).every((p) => p.initializer && !p.dotDotDotToken) && splitTopLevel(this.params(m, false)).every((p) => p.trim().startsWith('_ ')) ? defFrom : undefined;
248
+ k.dynMethods.push({ name: n, type: `(${params.join(', ')}) throws -> ${plain(sig.ret)}`, available: this.gatedFunctions.get(m), length: scriptLength(m), trailingFrom });
232
249
  }
233
250
  },
234
251
  abstractMethod(k, m) {
@@ -2,12 +2,13 @@
2
2
  import ts from 'typescript';
3
3
  import { isTypedArrayType } from "./library.js";
4
4
  import { ERRORS, TYPED_ARRAYS, errorArguments, isWebClass, isLibGlobal } from "../semantics/globals.js";
5
- import { ident, isOptional, splitTopLevel, RT } from "./syntax.js";
5
+ import { ident, isOptional, splitTopLevel, swiftString, RT } from "./syntax.js";
6
6
  import { intlConstructor } from "../semantics/lang.js";
7
7
  import { isArrayLengthLiteral, isAsync } from "../semantics/throws.js";
8
8
  import { isLibDeclaration } from "../semantics/ast.js";
9
9
  import { isKit, isUntyped, spelledType } from "../semantics/types.js";
10
10
  import { constClassExpr, constructorOf } from "../semantics/classes.js";
11
+ import { resolveWorkerScript } from "../semantics/worker-state.js";
11
12
  export const constructionMethods = {
12
13
  /** The library error a class is under whose constructors, its own and its program bases', are none; null for another class. */
13
14
  libErrorConstructed(cls) {
@@ -250,6 +251,9 @@ export const constructionMethods = {
250
251
  if (this.native.isStructType(t) && !args.length)
251
252
  return `${t}()`;
252
253
  // A web class the runtime has (`new TextEncoder()`), declared by the DOM's library for core's own code: the runtime's class.
254
+ const workerScript = resolveWorkerScript(name, args, this.workerScripts, this.resolveAlias, 'ios');
255
+ if (workerScript)
256
+ return `JSWorker(${this.coerce(args[0], 'Any?')}, ${swiftString(workerScript)})`;
253
257
  if (ts.isIdentifier(callee) && isWebClass(this.ledger, name) && t === `JS${name}` && !!this.resolve(callee)?.declarations?.[0]?.getSourceFile().isDeclarationFile)
254
258
  return `${t}(${this.args(e).join(', ')})`;
255
259
  this.refuseFunctionNew(e);
@@ -359,7 +359,7 @@ export const conversionMethods = {
359
359
  // An untyped promise is read as the same promise, its reactions in the ticks they would have in JavaScript.
360
360
  if (isUntyped(spelledType(pf)) && !this.lenient && !isOptional(from))
361
361
  return `${RT.jsPromiseOf}(${code}) { ${pt === 'Void' ? '_ in ()' : this.presentFromAny('$0', pt)} }`;
362
- const value = pt === 'Void' ? '' : `return ${isUntyped(spelledType(pf)) ? this.presentFromAny('__v', pt) : this.convert('__v', pf, pt)}`;
362
+ const value = pt === 'Void' ? '' : `return ${pf === 'Void' ? 'nil' : isUntyped(spelledType(pf)) ? this.presentFromAny('__v', pt) : this.convert('__v', pf, pt)}`;
363
363
  // Lenient code's promise (or a plugin's, held optional) may be missing: then nothing is chained.
364
364
  return `${this.lenient || isOptional(from) ? `(${code} as JSPromise<${pf}>?)?` : code}.then({ (__v: ${pf}) throws -> ${pt} in ${value} })`;
365
365
  }
@@ -9,7 +9,6 @@ import { notedField } from "../semantics/shapes.js";
9
9
  import { isWriteTarget } from "../semantics/ast.js";
10
10
  import { convertedRead } from "../semantics/states/predicates.js";
11
11
  import { isStatic } from "../semantics/throws.js";
12
- import { iosRefusedGlobal } from "../semantics/platform-globals.js";
13
12
  import { optionalContext } from "../semantics/spelled.js";
14
13
  import { isKit, isUntyped, spelledType } from "../semantics/types.js";
15
14
  import { atLossSite, HELD_LOSS } from "../semantics/losses.js";
@@ -91,9 +90,6 @@ export const expressionsMethods = {
91
90
  return this.subst.get(e);
92
91
  if (globalProxyUse(e, this.checker))
93
92
  throw this.limit(e, 'proxy', '`Proxy`');
94
- const refused = iosRefusedGlobal(e, this.checker);
95
- if (refused)
96
- throw this.error(e, `\`${refused.name}\` in an iOS build`, refused.id);
97
93
  const narrowed = this.narrowedHeld(e);
98
94
  if (narrowed) {
99
95
  this.rawHeld.add(e);
@@ -307,6 +303,8 @@ export const expressionsMethods = {
307
303
  const made = this.madeClass(e.expression);
308
304
  if (made && sameClass(made, to))
309
305
  return this.expr(e.expression);
306
+ if (isOptional(to))
307
+ return this.marks.castCode(this.expr(e.expression), to.slice(0, -1), 'as?');
310
308
  return this.castThrows(e) ? this.marks.ownTried(`${RT.jsChecked}(${this.expr(e.expression)}, ${metatype(to)})`) : this.marks.castCode(this.expr(e.expression), to, 'as!');
311
309
  }
312
310
  // A non-strict app's assertion of a value that may be missing (`<UITableViewCell>table.cellForRow(…)`): unwrapped where used.
@@ -197,6 +197,11 @@ export const fromAnyMethods = {
197
197
  // An Error held untyped (a caught or rejected value): the error, or a view of what was thrown instead.
198
198
  if (type === 'JSError' && !this.lenient)
199
199
  return `${RT.jsErrorOf}(${code})`;
200
+ // `globalThis as unknown as Worker`: wraps a worker realm's global object as a JSWorker.
201
+ if (type === 'JSWorker')
202
+ return this.marks.ownTried(`JSWorker.fromAny(${code})`);
203
+ if (type === 'JSWorker?' || type === 'JSWorker!')
204
+ return `JSWorker.fromAnyOrNil(${code})`;
200
205
  // An implicitly unwrapped class (`tabView: TabView!`): the value as it, missing where it is none.
201
206
  if (/^[A-Z][\w.]*!$/.test(type) && !this.native.isStructType(type.slice(0, -1)) && !['Double', 'String', 'Bool'].includes(type.slice(0, -1)))
202
207
  return this.libraryClassCast(input, type.slice(0, -1), false, checked || throwing, placed) ?? this.marks.castCode(code, type.slice(0, -1), 'as?');
@@ -33,10 +33,17 @@ export const globalCallsMethods = {
33
33
  const mixed = this.patterns.isMixinCall(e);
34
34
  if (mixed)
35
35
  return mixed.map((c) => `__install_${c.name.text}()`).join('; ');
36
+ const decl = this.resolve(callee)?.declarations?.[0];
37
+ // Worker globals (`postMessage`, `close`): checked before `native.call` so Darwin's C `close(_:)` does not shadow `close()`.
38
+ if ((callee.text === 'postMessage' || callee.text === 'close') && decl && (decl.getSourceFile().fileName === '/__shims__/globals.d.ts' || isLibDeclaration(decl))) {
39
+ if (callee.text === 'close')
40
+ return `${RT.jsClose}()`;
41
+ const args = e.arguments;
42
+ return `${RT.jsPostMessage}(${args[0] ? this.coerce(args[0], 'Any?') : 'nil'}${args[1] ? `, ${this.coerce(args[1], 'Any?')}` : ''})`;
43
+ }
36
44
  const native = this.native.call(e);
37
45
  if (native)
38
46
  return native;
39
- const decl = this.resolve(callee)?.declarations?.[0];
40
47
  // A core function imported under another name (`timer.setTimeout`, read as `__timer_setTimeout`): by its own.
41
48
  const name = decl && isCoreDeclaration(decl) && ts.isFunctionDeclaration(decl) && decl.name ? decl.name.text : callee.text;
42
49
  const arg = (k) => e.arguments[k];
@@ -319,7 +319,8 @@ export const objectClassesMethods = {
319
319
  .filter((m) => !fields.some((f) => f.name === m.name))
320
320
  .map((m) => {
321
321
  // An app class's method sees the object it is called on as `this` when that is one of the class's (`obj[k].call(other)`).
322
- const value = byName ? `${RT.jsMethodValue}(self) { (__s: ${byName.receiver}) in ${this.boxFunction(`__s.${ident(m.name)}`, m.type, -1, m.name, m.length, undefined, false)} }` : this.boxFunction(`self.${ident(m.name)}`, m.type, -1, m.name, m.length, undefined, false);
322
+ const trailing = m.trailingFrom !== undefined ? { ref: `${byName ? '__s' : 'self'}.${ident(m.name)}`, from: m.trailingFrom } : undefined;
323
+ const value = byName ? `${RT.jsMethodValue}(self) { (__s: ${byName.receiver}) in ${this.boxFunction(`__s.${ident(m.name)}`, m.type, -1, m.name, m.length, trailing, false)} }` : this.boxFunction(`self.${ident(m.name)}`, m.type, -1, m.name, m.length, trailing, false);
323
324
  // A value the instance holds in the method's place (`obj.step = …`) is what reading it gives.
324
325
  const own = byName && ownNames.has(m.name) ? `if let __own = ${RT.jsOwnProperty}(self, ${swiftString(m.name)}) { return __own }; ` : '';
325
326
  return { name: m.name, code: m.available ? `${own}if #available(iOS ${m.available}, *) { return ${value} } else { return nil }` : `${own}return ${value}` };
@@ -694,6 +694,12 @@ export const placementMethods = {
694
694
  const viewedFrom = this.classNamed(source.replace(/[?!]$/, ''));
695
695
  if (viewedFrom && this.states.viewedClass(viewedFrom) && source.replace(/[?!]$/, '') !== target.replace(/[?!]$/, '') && this.isObjectShape(target.replace(/[?!]$/, '')))
696
696
  return this.convert(this.expr(e), source, target);
697
+ // A class whose declared protocol was dropped by `protocolWitnesses`: wrap through `IFaceObject(jsObject:)`.
698
+ const targetProto = target.replace(/[?!]$/, '');
699
+ if (!this.library && viewedFrom && source.replace(/[?!]$/, '') !== targetProto && this.protocols.has(targetProto) && this.facts.hasInterface(this, this.interfaces, (d, s) => this.topName(d, s), targetProto) && !this.conformsToProtocol(viewedFrom, targetProto)) {
700
+ const wrapped = `${targetProto}Object(jsObject: ${this.expr(e)})`;
701
+ return isOptional(source) || source.endsWith('!') ? this.marks.unwrappedIf(`(${this.expr(e)}).map { ${targetProto}Object(jsObject: $0) }`, !(isOptional(target) || target.endsWith('!'))) : wrapped;
702
+ }
697
703
  const viewedStatics = /^(\w+)\.Type$/.exec(source)?.[1];
698
704
  if (viewedStatics && this.classNamed(viewedStatics) && this.states.viewedStatics(this.classNamed(viewedStatics)) && /^\w+$/.test(target) && this.isObjectShape(target))
699
705
  return this.viewOf(target, this.expr(e));
@@ -1,12 +1,12 @@
1
1
  // Protocol conformance as Swift: the protocols a class implements and their witnesses.
2
2
  import ts from 'typescript';
3
3
  import { ident, isOptional, metatype, optionalType, RT } from "./syntax.js";
4
- import { implementedInterfaces } from "../semantics/lang.js";
4
+ import { implementedInterfaces, isEmittedInterface } from "../semantics/lang.js";
5
5
  import { UNKEYED } from "../semantics/shapes.js";
6
6
  import { hasModifier, isLibDeclaration } from "../semantics/ast.js";
7
7
  import { isCoreDeclaration } from "../program/core-facts.js";
8
8
  import { isNamed, isUntyped, spelledType } from "../semantics/types.js";
9
- import { programBase } from "../semantics/classes.js";
9
+ import { ownClassMember, programBase, redeclaredMember } from "../semantics/classes.js";
10
10
  export const protocolsMethods = {
11
11
  /** Whether a class's source base class (or one above it) implements an interface. */
12
12
  baseImplements(cls, iface) {
@@ -35,7 +35,7 @@ export const protocolsMethods = {
35
35
  const named = implementedInterfaces(this.checker, cls).map((i) => ({ name: this.heritageName(i), type: this.checker.getTypeAtLocation(i) }));
36
36
  const met = [...(this.structural.get(cls) ?? [])].map((d) => ({ name: this.topName(d, d.name.text), type: this.checker.getTypeAtLocation(d.name) }));
37
37
  const implemented = [...named, ...met.filter((m) => !named.some((n) => n.name === m.name))]
38
- .filter((i) => !isLibDeclaration(i.type.getSymbol()?.declarations?.[0]) && !this.uncompiledType(i.type))
38
+ .filter((i) => isEmittedInterface(i.type) && !isLibDeclaration(i.type.getSymbol()?.declarations?.[0]) && !this.uncompiledType(i.type))
39
39
  // An interface only a declaration file has is no Swift protocol (a plugin's `IHttpsResponseLegacy` in its `.d.ts`), unless core's
40
40
  // that the kit has; nor is one the program has no declaration of (a plugin's `import { IOptions } from '.'`, which the platform
41
41
  // suffix resolves to the importing file itself).
@@ -49,6 +49,24 @@ export const protocolsMethods = {
49
49
  this.used.add(i);
50
50
  return { named, met, implemented };
51
51
  },
52
+ /** Whether `cls` (or an app base class) conforms natively to protocol `name` in Swift. */
53
+ conformsToProtocol(cls, name) {
54
+ for (let c = cls; c; c = this.sourceBase(c)) {
55
+ const kitRoot = this.kitRootOf(c);
56
+ const named = implementedInterfaces(this.checker, c).map((i) => ({ name: this.heritageName(i), type: this.checker.getTypeAtLocation(i) }));
57
+ const met = [...(this.structural.get(c) ?? [])].map((d) => ({ name: this.topName(d, d.name.text), type: this.checker.getTypeAtLocation(d.name) }));
58
+ const hit = [...named, ...met].find((i) => i.name === name);
59
+ if (!hit || !isEmittedInterface(hit.type) || isLibDeclaration(hit.type.getSymbol()?.declarations?.[0]) || this.uncompiledType(hit.type))
60
+ continue;
61
+ if ((hit.type.getSymbol()?.declarations ?? []).every((d) => d.getSourceFile().isDeclarationFile && (this.library || !isCoreDeclaration(d) || !this.core.has(hit.name))))
62
+ continue;
63
+ if (kitRoot && hit.type.getProperties().some((p) => !!this.core.kitMember(kitRoot, p.name)))
64
+ continue;
65
+ if (this.protocolWitnesses(c, hit.name, hit.type, [], false))
66
+ return true;
67
+ }
68
+ return false;
69
+ },
52
70
  /**
53
71
  * A component class's conformance to the app interfaces it implements, as an extension of it. Every app protocol
54
72
  * refines JSDynamic, which here reads and writes the interfaces' fields only.
@@ -96,21 +114,10 @@ export const protocolsMethods = {
96
114
  * `handlerError(error: Error)`) conforms through a witness of the protocol's
97
115
  * signature that calls it; any other difference leaves the protocol out.
98
116
  */
99
- protocolWitnesses(cls, name, type, out) {
117
+ protocolWitnesses(cls, name, type, out, record = true) {
100
118
  const decl = type.getSymbol()?.declarations?.find(ts.isInterfaceDeclaration);
101
119
  if (!decl || !this.protocols.has(name))
102
120
  return true;
103
- const own = (name) => {
104
- for (let c = cls; c; c = this.sourceBase(c)) {
105
- const m = c.members.find((x) => x.name?.getText() === name);
106
- if (m)
107
- return m;
108
- const param = c.members.find(ts.isConstructorDeclaration)?.parameters.find((p) => ts.isIdentifier(p.name) && p.name.text === name && ts.canHaveModifiers(p) && !!ts.getModifiers(p)?.length);
109
- if (param)
110
- return param;
111
- }
112
- return undefined;
113
- };
114
121
  const added = [];
115
122
  // The protocol refines its interface's bases: their members are required too.
116
123
  const inherited = type
@@ -123,13 +130,13 @@ export const protocolsMethods = {
123
130
  continue;
124
131
  if (this.fieldByOwnParameter(cls, req))
125
132
  return false;
126
- const m = own(name);
133
+ const m = ownClassMember(cls, name, this.checker);
127
134
  // A parameter property or an inherited member the class does not declare: Swift checks it.
128
135
  if (!m)
129
136
  continue;
130
137
  if (ts.isPropertySignature(req)) {
131
138
  const want = req.questionToken ? optionalType(this.typeOf(req)) : this.typeOf(req);
132
- const root = ts.isPropertyDeclaration(m) || ts.isParameter(m) ? this.redeclaredField(m) : null;
139
+ const root = redeclaredMember(m, this.checker);
133
140
  const fieldType = ts.isPropertyDeclaration(m) ? this.typeOf(m.name) : ts.isParameter(m) ? (!!m.questionToken && !isOptional(this.typeOf(m.name)) && !isUntyped(spelledType(this.typeOf(m.name))) ? optionalType(this.typeOf(m.name)) : this.typeOf(m.name)) : null;
134
141
  const have = ts.isGetAccessorDeclaration(m) ? (this.narrowedFrom(m) ?? this.returnTypeOf(m)) : root ? this.redeclaredType(root) : fieldType;
135
142
  if (have !== want)
@@ -155,10 +162,13 @@ export const protocolsMethods = {
155
162
  const args = want.map((_, k) => `__p${k}`);
156
163
  const call = this.marks.tryCode(`self.${ident(name)}(${args.map((a, k) => (have[k] === want[k] ? a : erased(have[k], k) ? this.marks.ownTried(`${RT.jsChecked}(${a}, ${metatype(have[k])})`) : `${a} as Any?`)).join(', ')})`);
157
164
  const body = ret === 'Void' ? call : ownRet === 'Void' ? `${call}; return nil` : byResult ? `let __r: ${ownRet} = ${call}; return __r` : `return ${call}`;
158
- added.push(` func ${ident(name)}(${want.map((t, k) => `_ ${args[k]}: ${t}`).join(', ')}) throws${ret === 'Void' ? '' : ` -> ${ret}`} { ${body} }`);
159
- this.declare(name, { kind: 'func', params: want.map((t, k) => `_ ${args[k]}: ${t}`).join(', '), throws: true, type: ret });
165
+ if (record) {
166
+ added.push(` func ${ident(name)}(${want.map((t, k) => `_ ${args[k]}: ${t}`).join(', ')}) throws${ret === 'Void' ? '' : ` -> ${ret}`} { ${body} }`);
167
+ this.declare(name, { kind: 'func', params: want.map((t, k) => `_ ${args[k]}: ${t}`).join(', '), throws: true, type: ret });
168
+ }
160
169
  }
161
- out.push(...added);
170
+ if (record)
171
+ out.push(...added);
162
172
  return true;
163
173
  },
164
174
  };
@@ -1,7 +1,7 @@
1
1
  // TypeScript types as Swift types: representations, held and optional forms, shapes.
2
2
  import ts from 'typescript';
3
3
  import { DESCRIPTORS } from "./library.js";
4
- import { WEB_DICTIONARIES, isWebClass } from "../semantics/globals.js";
4
+ import { WEB_DICTIONARIES, webClassName } from "../semantics/globals.js";
5
5
  import { SPELLING, spell, functionParts, heldType, isFunctionLiteral, isFunctionType, isMethodValue, isOptional, nullishType, optionalElementsType, optionalType, returningAny, swiftString, RT } from "./syntax.js";
6
6
  import { literalOverArray, membersOverTypeParameter, readByKey, definedField, untypedResultBinding, untypedResultField } from "../semantics/shapes.js";
7
7
  import { ambientAddedMemberOf, ambientBase, augmentedPropertyRead, evolvingArrayRead, evolvingArrayType, isAmbientClass, isRegExpProtocol, mergedInterfaceMemberOf, statementLevel, tokenClassBase, undeclaredMemberOf, isArguments, nullableTypeNode } from "../semantics/lang.js";
@@ -176,8 +176,9 @@ export const typesMethods = {
176
176
  };
177
177
  // Core's own code and apps using DOM/core global typings: web classes declared in .d.ts map to the runtime's.
178
178
  if (name && sym?.declarations?.length && sym.declarations.every((d) => d.getSourceFile().isDeclarationFile)) {
179
- if (isWebClass(this.ledger, name))
180
- return `JS${name}`;
179
+ const web = webClassName(this.ledger, name);
180
+ if (web)
181
+ return web;
181
182
  if (WEB_DICTIONARIES.includes(name) && (sym.declarations[0].getSourceFile().fileName === '/__shims__/globals.d.ts' || isLibDeclaration(sym.declarations[0])))
182
183
  return 'Any?';
183
184
  }
@@ -28,6 +28,7 @@ import { mirror, writeIfChanged } from "../../driver/mirror.js";
28
28
  import { KIT_APPLE, PACKAGE } from "../../driver/paths.js";
29
29
  import { compiledEnv } from "../../program/env.js";
30
30
  import { programClassName } from "../../semantics/top-names.js";
31
+ import { sharedWorkerState, sharedWorkerStateError } from "../../semantics/worker-state.js";
31
32
  /** The app as an Xcode project in `b.out`, built where `b.build` says. */
32
33
  export async function writeIos(b) {
33
34
  const { context, app, appDir, out, name, framework, adapter, behaviour, components, modules, program, checker, files: sourceFiles, infos, elementClasses, root, mounted, xml, pageSheets, sheets, xmlRunTimeFree, xmlMemberKeys, lines: sourceLines, shownSource, plugins, bindings: pluginBindings, pluginFiles, compiledPlugins, reach, properties, resolved, lenient: lenientApp, assignFields: assignsFields, allowUnapplied, unapplied, say, started } = b;
@@ -74,6 +75,12 @@ export async function writeIos(b) {
74
75
  for (const [js, c] of Object.entries(nativeTable(m).classes))
75
76
  if (c.kind === 'class' && !c.extension && c.module === m)
76
77
  pluginNativeClasses.set(js, c.swift);
78
+ const allModuleFiles = [...new Set([...modules, ...components.map((c) => c.file), ...compiledPlugins])];
79
+ if (b.workers?.length) {
80
+ const writes = sharedWorkerState(program, b.workers.map((f) => f.replace(/\\/g, '/')), new Set(allModuleFiles.map((f) => f.replace(/\\/g, '/'))), resolved);
81
+ if (writes.length)
82
+ throw sharedWorkerStateError(writes, app);
83
+ }
77
84
  const translator = new Translator(checker, infos, sourceFiles, {
78
85
  ...context.translation(),
79
86
  pluginFiles,
@@ -95,6 +102,8 @@ export async function writeIos(b) {
95
102
  appNativeClasses: Object.keys(appNative).filter((c) => !appNative[c].extension && appNative[c].kind === 'class'),
96
103
  pluginNativeClasses,
97
104
  pluginModules: native.modules,
105
+ workerScripts: new Map((b.workers ?? []).map((f) => [f.replace(/\\/g, '/'), relative(app, f).replace(/\\/g, '/')])),
106
+ resolveAlias: b.aliased ?? null,
98
107
  allowUnapplied,
99
108
  errors: b.allErrors ? (allowUnapplied ? [] : [...unapplied]) : null,
100
109
  });
@@ -164,9 +173,14 @@ export async function writeIos(b) {
164
173
  const shapes = SourceLines.strip((translator.interfacesOutside(new Set(translated.map((m) => m.file))) + translator.shapesCode()).trim());
165
174
  if (shapes)
166
175
  writeFileSync(join(sourcesDir, '__Objects.swift'), `// Compiled by ns-compiled: the app's object literals without a declared type.\nimport Foundation\nimport NativeScriptKit\n${native.modules.length || /\bUI[A-Z]/.test(shapes) ? `import UIKit\n${native.modules.map((m) => `import ${m}\n`).join('')}` : ''}${SDK_IMPORTS}\n${shapes}\n`);
167
- const activeInits = translated.filter((m) => m.init);
176
+ const isWorker = (file) => !!translator.workerScripts?.has(file.replace(/\\/g, '/'));
177
+ const workerRegs = translated
178
+ .filter((m) => isWorker(m.file))
179
+ .map((m) => ` JSWorker.register(${swiftString(translator.workerScripts.get(m.file.replace(/\\/g, '/')))}) { ${m.init ? `${m.initThrows ? 'try ' : ''}${m.init}()` : ''} }\n`)
180
+ .join('');
181
+ const activeInits = translated.filter((m) => m.init && !isWorker(m.file));
168
182
  const anyInitThrows = activeInits.some((m) => m.initThrows);
169
- const inits = activeInits.length ? (anyInitThrows ? ` ${RT.jsReport} {\n${activeInits.map((m) => ` ${m.initThrows ? 'try ' : ''}${m.init}()\n`).join('')} }\n` : activeInits.map((m) => ` ${m.init}()\n`).join('')) : '';
183
+ const inits = workerRegs + (activeInits.length ? (anyInitThrows ? ` ${RT.jsReport} {\n${activeInits.map((m) => ` ${m.initThrows ? 'try ' : ''}${m.init}()\n`).join('')} }\n` : activeInits.map((m) => ` ${m.init}()\n`).join('')) : '');
170
184
  // The app's CSS as its NativeScript build ships it: the AST core applies.
171
185
  const css = kitAst(sheets);
172
186
  const corePatchRefusal = corePatchRefused(app, nodeModules(app), 'ios');
@@ -325,11 +339,12 @@ export async function writeIos(b) {
325
339
  removePods(out, name);
326
340
  const resources = iosProjectResources({ app, appDir, out, name, pods: !!pods, say, stubbed: context.stubbedPlugins });
327
341
  const extensions = iosExtensions({ app, out, bundle, packages, signing, team: resources.team, say });
328
- // Script is single-threaded: the kit and the app's code are isolated to the main actor, checked in Swift 6 mode. Plugins'
329
- // own Swift targets keep their language mode.
330
- const swiftMode = { SWIFT_VERSION: '"6"', SWIFT_DEFAULT_ACTOR_ISOLATION: 'MainActor' };
331
- // Release only: Debug keeps Swift 6's run-time isolation checks, so an isolation mistake traps during development.
332
- const swiftModeRelease = (...flags) => ` configs:\n Release:\n OTHER_SWIFT_FLAGS: "${['$(inherited)', '-Xfrontend', '-disable-dynamic-actor-isolation', ...flags].join(' ')}"\n`;
342
+ // Script is single-threaded unless the app starts workers (each in its own isolated JSRealm on a worker thread).
343
+ // When workers are present, disable dynamic MainActor assertions in Debug too so worker threads can run realm-isolated code.
344
+ const hasWorkers = !!(b.workers && b.workers.length);
345
+ const swiftMode = { SWIFT_VERSION: '"6"', SWIFT_DEFAULT_ACTOR_ISOLATION: 'MainActor', ...(hasWorkers ? { OTHER_SWIFT_FLAGS: '"$(inherited) -Xfrontend -disable-dynamic-actor-isolation"' } : {}) };
346
+ // Release only: Debug keeps Swift 6's run-time isolation checks when no workers are present.
347
+ const swiftModeRelease = (...flags) => ` configs:\n Release:\n OTHER_SWIFT_FLAGS: "${['$(inherited)', ...(hasWorkers ? [] : ['-Xfrontend', '-disable-dynamic-actor-isolation']), ...flags].join(' ')}"\n`;
333
348
  // The app's own Swift (App_Resources/iOS/src), compiled in the app's target, was written for Swift 5: the target keeps that mode,
334
349
  // with the Swift 6 features the generated code relies on (a default argument evaluated in its function's isolation).
335
350
  const appMode = native.appSwift ? { ...swiftMode, SWIFT_VERSION: '"5"', SWIFT_UPCOMING_FEATURE_ISOLATED_DEFAULT_VALUES: 'YES', SWIFT_UPCOMING_FEATURE_REGION_BASED_ISOLATION: 'YES', SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES: 'YES', SWIFT_UPCOMING_FEATURE_GLOBAL_ACTOR_ISOLATED_TYPES_USABILITY: 'YES' } : swiftMode;
@@ -31,4 +31,4 @@ General | `$ ns compile ios [--for-device] [--team-id <Team>] [--provision <Prof
31
31
 
32
32
  ### Platform Notes
33
33
 
34
- * `new Worker(...)` background threads are currently supported in compiled Android builds (`ns compile android`) and refused at compile time on iOS (`worker` refusal); guard worker usage behind `if (__ANDROID__)` or use async/Promise concurrency for cross-platform builds.
34
+ * `new Worker(...)` background threads are supported in compiled iOS builds (`ns compile ios`) with per-worker realms, structured cloning, `ArrayBuffer` transfer, timers, and microtasks, matching Android (`ns compile android`).
@@ -1403,15 +1403,15 @@ open class CssProperty : JSExpando, JSKeysMade {
1403
1403
  jsObjectOf(
1404
1404
  "enumerable" to true,
1405
1405
  "configurable" to true,
1406
- "get" to JSMethod { __self, _ -> get(__self) },
1407
- "set" to JSMethod { __self, __a -> setCssValue(__self, __a.getOrNull(0)) },
1406
+ "get" to JSMethod(0) { __self, _ -> get(__self) },
1407
+ "set" to JSMethod(1) { __self, __a -> setCssValue(__self, __a.getOrNull(0)) },
1408
1408
  )
1409
1409
  this.localValueDescriptor =
1410
1410
  jsObjectOf(
1411
1411
  "enumerable" to true,
1412
1412
  "configurable" to true,
1413
- "get" to JSMethod { __self, _ -> get(__self) },
1414
- "set" to JSMethod { __self, __a -> setLocalValue(__self, __a.getOrNull(0)) },
1413
+ "get" to JSMethod(0) { __self, _ -> get(__self) },
1414
+ "set" to JSMethod(1) { __self, __a -> setLocalValue(__self, __a.getOrNull(0)) },
1415
1415
  )
1416
1416
  jsSet(Core_ui_core_properties_index.cssSymbolPropertyMap, key.key, this)
1417
1417
  }
@@ -2592,7 +2592,7 @@ open class ShorthandProperty : JSExpando, JSKeysMade {
2592
2592
  "configurable" to true,
2593
2593
  "get" to jsGet(options, "getter"),
2594
2594
  "set" to
2595
- JSMethod { __self, __a ->
2595
+ JSMethod(1) { __self, __a ->
2596
2596
  setCssValue(__self, jsConvertedStringOrNull(__a.getOrNull(0)))
2597
2597
  },
2598
2598
  )
@@ -2601,7 +2601,7 @@ open class ShorthandProperty : JSExpando, JSKeysMade {
2601
2601
  "enumerable" to true,
2602
2602
  "configurable" to true,
2603
2603
  "get" to jsGet(options, "getter"),
2604
- "set" to JSMethod { __self, __a -> setLocalValue(__self, __a.getOrNull(0)) },
2604
+ "set" to JSMethod(1) { __self, __a -> setLocalValue(__self, __a.getOrNull(0)) },
2605
2605
  )
2606
2606
  jsSet(Core_ui_core_properties_index.cssSymbolPropertyMap, key.key, this)
2607
2607
  }
@@ -3257,7 +3257,7 @@ object Core_ui_core_view_view_common {
3257
3257
  jsSet(
3258
3258
  target,
3259
3259
  eventName,
3260
- JSMethod { __self, __a ->
3260
+ JSMethod(1) { __self, __a ->
3261
3261
  onSubscribe(__self, jsConvertedBooleanOrFalse(__a.getOrNull(0)))
3262
3262
  },
3263
3263
  )
@@ -376,6 +376,8 @@ open class JSSet<T>() : Iterable<T>, JSReactiveConvertible {
376
376
  * key order (integer-like keys ascending, then insertion order) and reference semantics.
377
377
  */
378
378
  class JSRecord<V>(val obj: JSObject) : JSDynamic, JSReactiveConvertible {
379
+ internal var backing: JSDynamic? = null
380
+
379
381
  constructor() : this(JSObject())
380
382
 
381
383
  constructor(entries: List<Pair<String, V>>) : this() {
@@ -383,9 +385,12 @@ class JSRecord<V>(val obj: JSObject) : JSDynamic, JSReactiveConvertible {
383
385
  }
384
386
 
385
387
  @Suppress("UNCHECKED_CAST")
386
- operator fun get(key: String): V? = obj[key] as V?
388
+ operator fun get(key: String): V? = if (obj.has(key)) obj[key] as V? else backing?.jsGet(key) as V?
387
389
 
388
- operator fun set(key: String, value: V?) { obj[key] = value }
390
+ operator fun set(key: String, value: V?) {
391
+ obj[key] = value
392
+ backing?.jsSet(key, value)
393
+ }
389
394
 
390
395
  fun delete(key: String): Boolean = obj.delete(key)
391
396
  fun has(key: String): Boolean = obj.has(key)
@@ -396,8 +401,11 @@ class JSRecord<V>(val obj: JSObject) : JSDynamic, JSReactiveConvertible {
396
401
  @Suppress("UNCHECKED_CAST")
397
402
  val entries: JSArray<Pair<String, V>> get() = JSArray(obj.jsKeys.map { Pair(it, obj[it] as V) })
398
403
 
399
- override fun jsGet(key: String): Any? = obj.jsGet(key)
400
- override fun jsSet(key: String, value: Any?) = obj.jsSet(key, value)
404
+ override fun jsGet(key: String): Any? = if (obj.has(key)) obj.jsGet(key) else backing?.jsGet(key)
405
+ override fun jsSet(key: String, value: Any?) {
406
+ obj.jsSet(key, value)
407
+ backing?.jsSet(key, value)
408
+ }
401
409
  override val jsKeys: List<String> get() = obj.jsKeys
402
410
  override val jsClassName: String? get() = null
403
411
 
@@ -408,14 +416,15 @@ class JSRecord<V>(val obj: JSObject) : JSDynamic, JSReactiveConvertible {
408
416
 
409
417
  /**
410
418
  * An untyped value read as a dictionary (`Record<string, V>`): a plain object is
411
- * shared, so writes through either show in both; another object's own keys are copied.
419
+ * shared, so writes through either show in both; another object's own keys are copied
420
+ * and its dynamic lookup (methods, getters) stays reachable as a fallback.
412
421
  */
413
422
  @Suppress("UNCHECKED_CAST")
414
423
  fun <V> jsRecordOrNull(value: Any?): JSRecord<V>? = when (value) {
415
424
  null, JSNull -> null
416
425
  is JSRecord<*> -> value as JSRecord<V>
417
426
  is JSObject -> JSRecord(value)
418
- is JSDynamic -> JSRecord<V>().also { r -> for (k in value.jsKeys) r.obj[k] = value.jsGet(k) }
427
+ is JSDynamic -> JSRecord<V>().also { r -> r.backing = value; for (k in value.jsKeys) r.obj[k] = value.jsGet(k) }
419
428
  else -> throw JSException(JSTypeError("${jsTypeof(value)} is not an object"))
420
429
  }
421
430
 
@@ -315,7 +315,7 @@ class JSPromise<T> internal constructor() : JSThenable, JSDynamic {
315
315
  viewed?.let { source ->
316
316
  val read = viewRead!!
317
317
  source.performThen({ v ->
318
- val typed = try { read(v) } catch (e: Throwable) { onRejected(jsCaught(e)); return@performThen }
318
+ val typed = try { read(jsBox(v)) } catch (e: Throwable) { onRejected(jsCaught(e)); return@performThen }
319
319
  onFulfilled(typed)
320
320
  }, onRejected)
321
321
  return
@@ -1202,8 +1202,19 @@ open class Binding: JSDynamic, JSExpando, JSKeysMade, JSStaticKeyed {
1202
1202
  return FunctionCell_AnyOpt_JSArray_String_Opt_to_JSArray_AnyOpt_Opt.script(
1203
1203
  "resolveObjectsAndProperties", 2, self.resolveObjectsAndProperties)
1204
1204
  case "prepareContextForExpression":
1205
- return FunctionCell_AnyOpt_AnyOpt_String_JSArray_AnyOpt_Opt_to_Bool.script(
1206
- "prepareContextForExpression", 3, self.prepareContextForExpression)
1205
+ return { (__f: @escaping (Any?, Any?, String, JSArray<Any?>?) throws -> Bool) -> JSFunctionObject in
1206
+ jsBoxedFunction(FunctionCell_AnyOpt_AnyOpt_String_JSArray_AnyOpt_Opt_to_Bool(f: __f)) {
1207
+ jsFunction("prepareContextForExpression", 3) { (__a: [Any?]) throws -> Any? in
1208
+ if __a.count <= 3 {
1209
+ return try self.prepareContextForExpression(
1210
+ jsArg(__a, 0), jsArg(__a, 1), (try jsConvertedString(jsArg(__a, 2))))
1211
+ }
1212
+ return try __f(
1213
+ jsArg(__a, 0), jsArg(__a, 1), (try jsConvertedString(jsArg(__a, 2))),
1214
+ jsArrayOrNil(jsArg(__a, 3), as: JSArray<Any?>.self, { $0 }))
1215
+ }
1216
+ }
1217
+ }(self.prepareContextForExpression)
1207
1218
  default: break
1208
1219
  }
1209
1220
  case 30:
@@ -1505,18 +1505,6 @@ public struct FunctionCell_String_to_JSUint8ArrayOpt {
1505
1505
  guard let value else { throw jsNoObject() }
1506
1506
  return value
1507
1507
  }
1508
- public static func script(_ name: String, _ length: Int, _ __f: @escaping (String) throws -> JSUint8Array?)
1509
- -> JSFunctionObject
1510
- {
1511
- jsBoxedFunction(Self(f: __f)) {
1512
- jsFunction(name, length) { (__a: [Any?]) throws -> Any? in
1513
- return try __f((try jsConvertedString(jsArg(__a, 0))))
1514
- }
1515
- }
1516
- }
1517
- public static func scriptOrNil(_ name: String, _ length: Int, _ __f: ((String) throws -> JSUint8Array?)?)
1518
- -> JSFunctionObject?
1519
- { if let __f { return script(name, length, __f) } else { return nil } }
1520
1508
  }
1521
1509
 
1522
1510
  public struct FunctionCell_NSData_to_Void {