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

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 (99) hide show
  1. package/dist/css/worker.js +2 -2
  2. package/dist/driver/compile.js +4 -3
  3. package/dist/kotlin/arguments.js +7 -3
  4. package/dist/kotlin/assignment.js +3 -0
  5. package/dist/kotlin/builtins.js +15 -4
  6. package/dist/kotlin/class-constructor.js +3 -1
  7. package/dist/kotlin/class-methods.js +9 -2
  8. package/dist/kotlin/components.js +39 -14
  9. package/dist/kotlin/construction.js +4 -5
  10. package/dist/kotlin/conversion.js +19 -3
  11. package/dist/kotlin/core-api.js +31 -7
  12. package/dist/kotlin/declarations.js +8 -3
  13. package/dist/kotlin/expressions.js +10 -5
  14. package/dist/kotlin/library.js +2 -2
  15. package/dist/kotlin/modules.js +9 -4
  16. package/dist/kotlin/names.js +5 -2
  17. package/dist/kotlin/narrowing.js +2 -1
  18. package/dist/kotlin/optional-chains.js +24 -5
  19. package/dist/kotlin/overrides.js +7 -2
  20. package/dist/kotlin/placement.js +5 -4
  21. package/dist/kotlin/static-calls.js +17 -5
  22. package/dist/kotlin/translator.js +15 -39
  23. package/dist/kotlin/type-facts.js +3 -2
  24. package/dist/kotlin/types.js +6 -5
  25. package/dist/kotlin/untyped-values.js +7 -1
  26. package/dist/program/program.js +3 -3
  27. package/dist/semantics/apis/array.js +11 -0
  28. package/dist/semantics/classes.js +24 -0
  29. package/dist/semantics/config.js +2 -0
  30. package/dist/semantics/forms/by-name.js +30 -18
  31. package/dist/semantics/globals.js +8 -2
  32. package/dist/semantics/lang.js +4 -0
  33. package/dist/semantics/ledger.js +0 -24
  34. package/dist/semantics/platform-globals.js +0 -16
  35. package/dist/semantics/refusals.js +1 -1
  36. package/dist/semantics/runtime.js +2 -0
  37. package/dist/semantics/throws.js +7 -0
  38. package/dist/semantics/worker-state.js +41 -1
  39. package/dist/swift/assignment.js +3 -0
  40. package/dist/swift/builtins.js +20 -12
  41. package/dist/swift/class-methods.js +3 -1
  42. package/dist/swift/construction.js +5 -1
  43. package/dist/swift/conversion.js +1 -1
  44. package/dist/swift/expressions.js +2 -4
  45. package/dist/swift/from-any.js +5 -0
  46. package/dist/swift/global-calls.js +8 -1
  47. package/dist/swift/library.js +1 -1
  48. package/dist/swift/modules.js +2 -1
  49. package/dist/swift/object-classes.js +2 -1
  50. package/dist/swift/protocols.js +5 -16
  51. package/dist/swift/type-facts.js +2 -0
  52. package/dist/swift/types.js +7 -6
  53. package/dist/targets/android/build.js +9 -7
  54. package/dist/targets/ios/build.js +23 -8
  55. package/docs/cli/compile-ios.md +1 -1
  56. package/kit-android/generated/kotlin/org/nativescript/kit/file_system_file_system_access.kt +1 -1
  57. package/kit-android/generated/kotlin/org/nativescript/kit/http_http_request_internal_index.kt +1 -1
  58. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_properties_index.kt +6 -6
  59. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_view_view_common.kt +1 -1
  60. package/kit-android/generated/kotlin/org/nativescript/kit/ui_text_base_formatted_string.kt +2 -2
  61. package/kit-android/generated/kotlin/org/nativescript/kit/ui_text_base_text_base_common.kt +2 -2
  62. package/kit-android/gradlew.bat +2 -2
  63. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Collections.kt +15 -6
  64. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Iterators.kt +1 -0
  65. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Promise.kt +5 -4
  66. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Workers.kt +39 -11
  67. package/kit-apple/Overlays/xml-free/Core/ui.core.bindable.index.swift +13 -2
  68. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity1.swift +0 -12
  69. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity2.swift +0 -39
  70. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity3Plus.swift +0 -44
  71. package/kit-apple/Sources/NativeScriptKit/Core/application.application-common.swift +19 -2
  72. package/kit-apple/Sources/NativeScriptKit/Core/kit-index.json +87 -22
  73. package/kit-apple/Sources/NativeScriptKit/Core/text.text-common.swift +9 -1
  74. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.bindable.index.swift +13 -2
  75. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.view-base.index.swift +26 -2
  76. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.liquid-glass-container.index.ios.swift +12 -2
  77. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.root-layout.root-layout-common.swift +46 -6
  78. package/kit-apple/Sources/NativeScriptKit/Core/ui.list-view.index.ios.swift +37 -3
  79. package/kit-apple/Sources/NativeScriptKit/Core/ui.split-view.split-view-common.swift +12 -1
  80. package/kit-apple/Sources/NativeScriptKit/Core/ui.styling.css-selector.swift +50 -6
  81. package/kit-apple/Sources/NativeScriptKit/Core/ui.text-base.text-base-common.swift +13 -1
  82. package/kit-apple/Sources/NativeScriptKit/Runtime/Collections.swift +5 -1
  83. package/kit-apple/Sources/NativeScriptKit/Runtime/Dynamic.swift +13 -2
  84. package/kit-apple/Sources/NativeScriptKit/Runtime/Errors.swift +10 -2
  85. package/kit-apple/Sources/NativeScriptKit/Runtime/Functions.swift +57 -12
  86. package/kit-apple/Sources/NativeScriptKit/Runtime/Lowering.swift +12 -3
  87. package/kit-apple/Sources/NativeScriptKit/Runtime/Promise.swift +56 -29
  88. package/kit-apple/Sources/NativeScriptKit/Runtime/Realm.swift +92 -0
  89. package/kit-apple/Sources/NativeScriptKit/Runtime/Record.swift +25 -5
  90. package/kit-apple/Sources/NativeScriptKit/Runtime/RegExp.swift +13 -4
  91. package/kit-apple/Sources/NativeScriptKit/Runtime/RegExpEngine.swift +14 -5
  92. package/kit-apple/Sources/NativeScriptKit/Runtime/Symbol.swift +28 -6
  93. package/kit-apple/Sources/NativeScriptKit/Runtime/Threads.swift +2 -2
  94. package/kit-apple/Sources/NativeScriptKit/Runtime/Timers.swift +93 -47
  95. package/kit-apple/Sources/NativeScriptKit/Runtime/TypedArrays.swift +37 -9
  96. package/kit-apple/Sources/NativeScriptKit/Runtime/Values.swift +6 -4
  97. package/kit-apple/Sources/NativeScriptKit/Runtime/Views.swift +11 -2
  98. package/kit-apple/Sources/NativeScriptKit/Runtime/Workers.swift +680 -0
  99. package/package.json +1 -1
@@ -473,7 +473,19 @@ open class TextBaseCommon: View {
473
473
  }
474
474
  case 14:
475
475
  switch key {
476
- case "_setNativeText": return FunctionCell_Bool_to_Void.script("_setNativeText", 0, self._setNativeText)
476
+ case "_setNativeText":
477
+ return { (__f: @escaping (Bool) throws -> Void) -> JSFunctionObject in
478
+ jsBoxedFunction(FunctionCell_Bool_to_Void(f: __f)) {
479
+ jsFunction("_setNativeText", 0) { (__a: [Any?]) throws -> Any? in
480
+ if __a.count <= 0 {
481
+ try self._setNativeText()
482
+ return nil
483
+ }
484
+ try __f((try jsConvertedBool(jsArg(__a, 0))))
485
+ return nil
486
+ }
487
+ }
488
+ }(self._setNativeText)
477
489
  default: break
478
490
  }
479
491
  case 20:
@@ -38,6 +38,7 @@ enum JSCollectionKey: Equatable {
38
38
  case unique(Int)
39
39
 
40
40
  private static var uniqueCounter = 0
41
+ private static let uniqueLock = JSUnfairLock()
41
42
 
42
43
  @inlinable static func number(_ d: Double) -> JSCollectionKey {
43
44
  .number(d.isNaN ? Double.nan.bitPattern : (d == 0 ? 0 : d.bitPattern))
@@ -63,8 +64,11 @@ enum JSCollectionKey: Equatable {
63
64
  case let v?:
64
65
  if let n = jsNumeric(v) { return number(n) }
65
66
  if jsIsObject(v) { return .object(ObjectIdentifier(jsIdentity(v)! as AnyObject)) }
67
+ uniqueLock.lock()
66
68
  uniqueCounter += 1
67
- return .unique(uniqueCounter)
69
+ let id = uniqueCounter
70
+ uniqueLock.unlock()
71
+ return .unique(id)
68
72
  }
69
73
  }
70
74
 
@@ -319,6 +319,7 @@ public func jsOwnPropertyNames(_ value: Any?) -> JSArray<String> {
319
319
  }
320
320
 
321
321
  private var jsRestricted: [ObjectIdentifier: JSRestriction] = [:]
322
+ private let jsRestrictedLock = JSUnfairLock()
322
323
 
323
324
  /// How far `Object.preventExtensions`, `seal` or `freeze` closed an object other than a plain one.
324
325
  private final class JSRestriction {
@@ -330,6 +331,8 @@ private final class JSRestriction {
330
331
 
331
332
  /// 0: open; 1: not extensible; 2: sealed; 3: frozen.
332
333
  func jsRestriction(_ object: AnyObject) -> Int {
334
+ jsRestrictedLock.lock()
335
+ defer { jsRestrictedLock.unlock() }
333
336
  guard !jsRestricted.isEmpty, let r = jsRestricted[ObjectIdentifier(object)], r.object === object else { return 0 }
334
337
  return r.level
335
338
  }
@@ -339,7 +342,10 @@ private func jsRestrict(object v: Any?, level: Int) {
339
342
  case let o as JSObject: o.restrict(sealed: level >= 2, frozen: level >= 3)
340
343
  case let v? where jsIsObject(v) && !(v is JSNull):
341
344
  let object = v as AnyObject
342
- jsRestricted[ObjectIdentifier(object)] = JSRestriction(object, max(level, jsRestriction(object)))
345
+ jsRestrictedLock.lock()
346
+ let current = (jsRestricted[ObjectIdentifier(object)].flatMap { $0.object === object ? $0.level : nil }) ?? 0
347
+ jsRestricted[ObjectIdentifier(object)] = JSRestriction(object, max(level, current))
348
+ jsRestrictedLock.unlock()
343
349
  default: break
344
350
  }
345
351
  }
@@ -454,15 +460,20 @@ public func jsIn(_ key: String, _ object: Any?) -> Bool {
454
460
  /// A tagged template's strings array; translated code makes one per call site.
455
461
  public func jsTemplateObject(_ cooked: [String], raw: [String]) -> JSArray<String> {
456
462
  let strings = JSArray(cooked)
463
+ jsTemplateRawsLock.lock()
457
464
  jsTemplateRaws[ObjectIdentifier(strings)] = JSArray(raw)
465
+ jsTemplateRawsLock.unlock()
458
466
  return strings
459
467
  }
460
468
 
461
469
  /// `strings.raw`.
462
470
  public func jsTemplateRaw(_ strings: JSArray<String>) -> JSArray<String> {
463
- jsTemplateRaws[ObjectIdentifier(strings)] ?? strings
471
+ jsTemplateRawsLock.lock()
472
+ defer { jsTemplateRawsLock.unlock() }
473
+ return jsTemplateRaws[ObjectIdentifier(strings)] ?? strings
464
474
  }
465
475
  private var jsTemplateRaws: [ObjectIdentifier: JSArray<String>] = [:]
476
+ private let jsTemplateRawsLock = JSUnfairLock()
466
477
 
467
478
  /// The key order of an object literal with spreads (`{ ...a, b: 1 }`): each spread source's keys as it holds
468
479
  /// them, then the literal's own, a key keeping its first position; integer keys first; only the `fields` it has.
@@ -6,7 +6,12 @@ public struct JSException: Error, @unchecked Sendable, CustomStringConvertible {
6
6
  public let value: Any?
7
7
  public init(_ value: Any?) { self.value = value }
8
8
  public init(value: Any?) { self.value = value }
9
- public var description: String { MainActor.assumeIsolated { "Uncaught " + jsToString(value) } }
9
+ public var description: String {
10
+ if pthread_main_np() != 0 {
11
+ return MainActor.assumeIsolated { "Uncaught " + jsToString(value) }
12
+ }
13
+ return jsRunInWorker { "Uncaught " + jsToString(self.value) }
14
+ }
10
15
  }
11
16
 
12
17
  /// JavaScript `Error`. TypeScript classes extending `Error` subclass it and set `name` in their initializer.
@@ -297,7 +302,10 @@ public final class JSThrownValue: JSError {
297
302
  }
298
303
 
299
304
  /// A dynamic write (`obj[key] = v`, a binding's set) a typed field refused, or a defined field's setter threw: what `jsSet` throws after the write.
300
- var jsRefusedWrite: JSException?
305
+ var jsRefusedWrite: JSException? {
306
+ get { JSRealm.current().refusedWrite }
307
+ set { JSRealm.current().refusedWrite = newValue }
308
+ }
301
309
 
302
310
  /// A dynamic write whose value converting throws (an array holding undefined where its elements are objects): refused, the TypeError `jsSet` throws.
303
311
  public func jsStoring(_ body: () throws -> Void) {
@@ -60,7 +60,11 @@ public final class JSFunctionObject: JSDynamic, CustomStringConvertible {
60
60
  if let own { return own }
61
61
  let made = JSObject()
62
62
  own = made
63
- if let identityKey { JSFunctionIdentity.table[identityKey]?.kept = self }
63
+ if let identityKey {
64
+ JSFunctionIdentity.lock.lock()
65
+ JSFunctionIdentity.table[identityKey]?.kept = self
66
+ JSFunctionIdentity.lock.unlock()
67
+ }
64
68
  return made
65
69
  }
66
70
 
@@ -221,15 +225,18 @@ enum JSFunctionIdentity {
221
225
  }
222
226
  }
223
227
 
228
+ static let lock = JSUnfairLock()
224
229
  static var table: [JSFunctionKey: Slot] = [:]
225
230
 
226
231
  static func forget(_ key: JSFunctionKey) {
232
+ lock.lock()
227
233
  if let slot = table[key], slot.alias == nil, slot.box == nil { table[key] = nil }
234
+ lock.unlock()
228
235
  }
229
236
 
230
237
  /// The function a closure key stands for: an object (a function object, or a class's method), or
231
- /// the key itself for a closure made from nothing else.
232
- static func root(_ key: JSFunctionKey) -> Root {
238
+ /// the key itself for a closure made from nothing else. Caller must hold `lock`.
239
+ static func rootLocked(_ key: JSFunctionKey) -> Root {
233
240
  var k = key
234
241
  while let slot = table[k] {
235
242
  if let alias = slot.alias {
@@ -244,20 +251,38 @@ enum JSFunctionIdentity {
244
251
  }
245
252
  return .key(k)
246
253
  }
254
+
255
+ static func root(_ key: JSFunctionKey) -> Root {
256
+ lock.lock()
257
+ defer { lock.unlock() }
258
+ return rootLocked(key)
259
+ }
247
260
  }
248
261
 
249
262
  /// A typed closure given to script untyped: one function object per function, so that the same
250
263
  /// closure boxed twice (or a closure made from a function object) is the same value to `===`.
251
264
  public func jsBoxedFunction<Cell>(_ cell: Cell, _ make: () -> JSFunctionObject) -> JSFunctionObject {
252
265
  let key = jsFunctionKey(cell)
253
- if let box = JSFunctionIdentity.table[key]?.box { return box }
254
- let root = JSFunctionIdentity.root(key)
266
+ JSFunctionIdentity.lock.lock()
267
+ if let box = JSFunctionIdentity.table[key]?.box {
268
+ JSFunctionIdentity.lock.unlock()
269
+ return box
270
+ }
271
+ let root = JSFunctionIdentity.rootLocked(key)
255
272
  if case .object(let o) = root {
256
- if let box = o as? JSFunctionObject { return box }
257
- if let box = (o as? JSFunctionDeclaration)?.box { return box }
273
+ if let box = o as? JSFunctionObject {
274
+ JSFunctionIdentity.lock.unlock()
275
+ return box
276
+ }
277
+ if let box = (o as? JSFunctionDeclaration)?.box {
278
+ JSFunctionIdentity.lock.unlock()
279
+ return box
280
+ }
258
281
  }
282
+ JSFunctionIdentity.lock.unlock()
259
283
  let box = make()
260
284
  // Kept under the key the closure stands for (an adapter's, the function it adapts), which the box keeps alive through it.
285
+ JSFunctionIdentity.lock.lock()
261
286
  let at: JSFunctionKey
262
287
  switch root {
263
288
  case .key(let k): at = k
@@ -265,6 +290,7 @@ public func jsBoxedFunction<Cell>(_ cell: Cell, _ make: () -> JSFunctionObject)
265
290
  }
266
291
  box.identityKey = at
267
292
  JSFunctionIdentity.table[at, default: .init()].box = box
293
+ JSFunctionIdentity.lock.unlock()
268
294
  return box
269
295
  }
270
296
 
@@ -274,7 +300,9 @@ public func jsIdentified<Cell>(_ cell: Cell, _ alias: JSFunctionAlias) -> Cell {
274
300
  if case .none = alias.target { return cell }
275
301
  let key = jsFunctionKey(cell)
276
302
  alias.key = key
303
+ JSFunctionIdentity.lock.lock()
277
304
  JSFunctionIdentity.table[key] = .init(alias: alias)
305
+ JSFunctionIdentity.lock.unlock()
278
306
  return cell
279
307
  }
280
308
 
@@ -291,12 +319,18 @@ public final class JSFunctionDeclaration {
291
319
  /// A module's or namespace's function declaration as a value: the first closure read of it, kept for
292
320
  /// good as the function itself is, so that every read is the same closure. `id` names the declaration.
293
321
  public func jsDeclaredFunction<Cell>(_ id: String, _ cell: Cell) -> Cell {
294
- if let found = JSDeclaredFunctions.table[id] as? Cell { return found }
322
+ JSDeclaredFunctions.lock.lock()
323
+ if let found = JSDeclaredFunctions.table[id] as? Cell {
324
+ JSDeclaredFunctions.lock.unlock()
325
+ return found
326
+ }
295
327
  JSDeclaredFunctions.table[id] = cell
328
+ JSDeclaredFunctions.lock.unlock()
296
329
  return cell
297
330
  }
298
331
 
299
332
  enum JSDeclaredFunctions {
333
+ static let lock = JSUnfairLock()
300
334
  static var table: [String: Any] = [:]
301
335
  }
302
336
 
@@ -313,7 +347,12 @@ public func jsSameFunction<A, B>(_ a: A?, _ b: B?) -> Bool {
313
347
  /// storing it on the receiver or in this cache keeps nothing alive. `make` captures the alias it is given.
314
348
  public func jsMethodValue<Receiver: AnyObject, Cell>(_ receiver: Receiver, _ name: String, _ make: (Receiver, JSFunctionAlias) -> Cell) -> Cell {
315
349
  let key = JSMethodValues.Key(receiver: ObjectIdentifier(receiver), name: name, cell: ObjectIdentifier(Cell.self))
316
- if let entry = JSMethodValues.table[key], entry.receiver === receiver, let cell = entry.cell as? Cell { return cell }
350
+ JSMethodValues.lock.lock()
351
+ if let entry = JSMethodValues.table[key], entry.receiver === receiver, let cell = entry.cell as? Cell {
352
+ JSMethodValues.lock.unlock()
353
+ return cell
354
+ }
355
+ JSMethodValues.lock.unlock()
317
356
  let alias = JSFunctionAlias(method: JSMethodValues.identity(type(of: receiver), name))
318
357
  let cell = jsIdentified(make(receiver, alias), alias)
319
358
  JSMethodValues.store(key, .init(receiver: receiver, cell: cell))
@@ -344,6 +383,7 @@ enum JSMethodValues {
344
383
  weak var receiver: AnyObject?
345
384
  let cell: Any
346
385
  }
386
+ static let lock = JSUnfairLock()
347
387
  static var table: [Key: Entry] = [:]
348
388
  private static var pruneAt = 64
349
389
 
@@ -357,6 +397,8 @@ enum JSMethodValues {
357
397
 
358
398
  static func identity(_ type: AnyClass, _ name: String) -> Identity {
359
399
  let key = IdentityKey(type: ObjectIdentifier(type), name: name)
400
+ lock.lock()
401
+ defer { lock.unlock() }
360
402
  if let found = identities[key] { return found }
361
403
  let made = Identity()
362
404
  identities[key] = made
@@ -364,9 +406,12 @@ enum JSMethodValues {
364
406
  }
365
407
 
366
408
  static func store(_ key: Key, _ entry: Entry) {
409
+ lock.lock()
367
410
  table[key] = entry
368
- guard table.count >= pruneAt else { return }
369
- table = table.filter { $0.value.receiver != nil }
370
- pruneAt = max(64, table.count * 2)
411
+ if table.count >= pruneAt {
412
+ table = table.filter { $0.value.receiver != nil }
413
+ pruneAt = max(64, table.count * 2)
414
+ }
415
+ lock.unlock()
371
416
  }
372
417
  }
@@ -50,7 +50,13 @@ func jsReportedToScript(_ value: Any?) -> Bool {
50
50
  return true
51
51
  }
52
52
 
53
- public func jsReportUncaught(_ value: Any?) { jsUncaughtHandler(value) }
53
+ public func jsReportUncaught(_ value: Any?) {
54
+ if let handler = JSRealm.current().uncaught {
55
+ handler(value)
56
+ return
57
+ }
58
+ jsUncaughtHandler(value)
59
+ }
54
60
 
55
61
  /// A framework's own handling of what no script code caught, which hears it before the app's (`UncaughtErrors`): true
56
62
  /// when it took it.
@@ -452,11 +458,14 @@ public func jsIsSafeInteger(_ x: Double) -> Bool { jsIsInteger(x) && abs(x) <= 9
452
458
  /// `n.toString(radix)`; nil radix is 10.
453
459
  public func jsNumberToString(_ x: Double, radix: Double?) throws -> String { try radix.map { try jsNumberToRadixString(x, $0) } ?? jsNumberToString(x) }
454
460
 
455
- /// An untyped value read as a dictionary-typed object: a record already, or a record of an object's keys.
461
+ /// An untyped value read as a dictionary-typed object: a record already, or a record of an object's keys
462
+ /// (keeping a class instance's dynamic lookup as a fallback for methods and getters).
456
463
  public func jsRecordOf<T>(_ value: Any?, _ element: (Any?) throws -> T) rethrows -> JSRecord<T> {
457
464
  if let record = jsFlat(value) as? JSRecord<T> { return record }
458
465
  guard let object = jsFlat(value) as? JSDynamic else { return JSRecord<T>() }
459
- return JSRecord(try object.jsKeys.map { ($0, try element(object[jsKey: $0])) })
466
+ let record = JSRecord(try object.jsKeys.map { ($0, try element(object[jsKey: $0])) })
467
+ if !(object is JSObject) { record.backing = object }
468
+ return record
460
469
  }
461
470
 
462
471
  /// The RegExp match, matchAll and search make of a pattern that is not one.
@@ -3,37 +3,27 @@ import Foundation
3
3
  // Promises and the microtask queue, following ECMA-262 §27.2 job for job so that the
4
4
  // interleaving of callbacks matches V8's exactly.
5
5
 
6
- /// The microtask queue (HTML "perform a microtask checkpoint", Node's `runMicrotasks`).
7
- public enum Microtasks {
8
- private static var queue: [(() -> Void)?] = []
9
- private static var head = 0
10
- private static var draining = false
11
- static var pendingRejections: [JSRejection] = []
6
+ /// Per-realm microtask queue state.
7
+ final class JSMicrotasks {
8
+ nonisolated deinit {}
9
+ private var queue: [(() -> Void)?] = []
10
+ private var head = 0
11
+ private var draining = false
12
+ var pendingRejections: [JSRejection] = []
13
+ var kept: [AnyObject] = []
14
+ private var turned = false
15
+ /// Notifies a worker host when work enters an idle queue so its loop can wake and drain.
16
+ var onEnqueue: (() -> Void)?
12
17
 
13
- /// Receives the reason of every promise still rejected without a handler when a checkpoint
14
- /// ends, as Node's `unhandledRejection` event does. The default prints
15
- /// `Uncaught (in promise) <reason>` to standard error, or gives it to `globalThis.__onUncaughtError` as
16
- /// `jsUncaughtHandler` does, and carries on (Node would exit).
17
- public static var onUnhandledRejection: (Any?) -> Void = { reason in
18
- if !jsReportedToScript(reason) { jsWriteStandardError("Uncaught (in promise) \(jsToString(reason))\n") }
18
+ func enqueue(_ job: @escaping () -> Void) {
19
+ let wasEmpty = head >= queue.count
20
+ queue.append(job)
21
+ if wasEmpty && !draining { onEnqueue?() }
19
22
  }
20
23
 
21
- public static func enqueue(_ job: @escaping () -> Void) { queue.append(job) }
22
-
23
- /// The targets of WeakRefs made in the current job, held until the checkpoint after it ends (ECMA-262 KeepDuringJob):
24
- /// under ARC a target nothing else holds would otherwise be gone before the next statement.
25
- static var kept: [AnyObject] = []
24
+ func taskRan() { turned = true }
26
25
 
27
- /// Called when a checkpoint ends after a task (`taskRan`) or a job ran: the app turning stable.
28
- public static var onStable: (() -> Void)?
29
- private static var turned = false
30
-
31
- /// A JavaScript task (an event handler, a timer callback) ran.
32
- public static func taskRan() { turned = true }
33
-
34
- /// Runs queued jobs FIFO, including jobs they queue, then reports unhandled rejections
35
- /// (and drains again if reporting queued more). A call made while draining does nothing.
36
- public static func checkpoint() {
26
+ func checkpoint() {
37
27
  guard !draining else { return }
38
28
  draining = true
39
29
  defer {
@@ -55,7 +45,7 @@ public enum Microtasks {
55
45
  queue.removeAll(keepingCapacity: true)
56
46
  head = 0
57
47
  if pendingRejections.isEmpty {
58
- guard turned, let onStable else { return }
48
+ guard turned, self === JSRealm.main.microtasks, let onStable = Microtasks.onStable else { return }
59
49
  turned = false
60
50
  onStable()
61
51
  continue
@@ -63,12 +53,49 @@ public enum Microtasks {
63
53
  let pending = pendingRejections
64
54
  pendingRejections = []
65
55
  for rejection in pending where !rejection.handled {
66
- onUnhandledRejection(rejection.reason)
56
+ Microtasks.onUnhandledRejection(rejection.reason)
67
57
  }
68
58
  }
69
59
  }
70
60
  }
71
61
 
62
+ /// The microtask queue (HTML "perform a microtask checkpoint", Node's `runMicrotasks`).
63
+ public enum Microtasks {
64
+ private static var current: JSMicrotasks { JSRealm.current().microtasks }
65
+
66
+ static var pendingRejections: [JSRejection] {
67
+ get { current.pendingRejections }
68
+ set { current.pendingRejections = newValue }
69
+ }
70
+
71
+ /// Receives the reason of every promise still rejected without a handler when a checkpoint
72
+ /// ends, as Node's `unhandledRejection` event does. The default prints
73
+ /// `Uncaught (in promise) <reason>` to standard error, or gives it to `globalThis.__onUncaughtError` as
74
+ /// `jsUncaughtHandler` does, and carries on (Node would exit).
75
+ public static var onUnhandledRejection: (Any?) -> Void = { reason in
76
+ if !jsReportedToScript(reason) { jsWriteStandardError("Uncaught (in promise) \(jsToString(reason))\n") }
77
+ }
78
+
79
+ public static func enqueue(_ job: @escaping () -> Void) { current.enqueue(job) }
80
+
81
+ /// The targets of WeakRefs made in the current job, held until the checkpoint after it ends (ECMA-262 KeepDuringJob):
82
+ /// under ARC a target nothing else holds would otherwise be gone before the next statement.
83
+ static var kept: [AnyObject] {
84
+ get { current.kept }
85
+ set { current.kept = newValue }
86
+ }
87
+
88
+ /// Called when a checkpoint ends after a task (`taskRan`) or a job ran: the app turning stable.
89
+ public static var onStable: (() -> Void)?
90
+
91
+ /// A JavaScript task (an event handler, a timer callback) ran.
92
+ public static func taskRan() { current.taskRan() }
93
+
94
+ /// Runs queued jobs FIFO, including jobs they queue, then reports unhandled rejections
95
+ /// (and drains again if reporting queued more). A call made while draining does nothing.
96
+ public static func checkpoint() { current.checkpoint() }
97
+ }
98
+
72
99
  /// A rejection HostPromiseRejectionTracker saw without a handler.
73
100
  final class JSRejection {
74
101
  nonisolated deinit {}
@@ -0,0 +1,92 @@
1
+ import Foundation
2
+
3
+ // A realm's per-thread state: its global object, timers, microtask queue and per-thread runtime scratch state.
4
+ // A worker's thread enters its own realm; every other thread runs in the app's (`main`), as all code did before workers.
5
+
6
+ /// Runs a `@MainActor` closure on a worker thread where the worker owns its own isolated `JSRealm`.
7
+ @usableFromInline nonisolated func jsRunInWorker(_ body: @escaping @MainActor () throws -> Void) throws {
8
+ let fn = unsafeBitCast(body, to: (() throws -> Void).self)
9
+ try fn()
10
+ }
11
+
12
+ /// Runs a non-throwing `@MainActor` closure on a worker thread.
13
+ @usableFromInline nonisolated func jsRunInWorker(_ body: @escaping @MainActor () -> Void) {
14
+ let fn = unsafeBitCast(body, to: (() -> Void).self)
15
+ fn()
16
+ }
17
+
18
+ /// Runs a value-returning `@MainActor` closure on a worker thread.
19
+ @usableFromInline nonisolated func jsRunInWorker<T>(_ body: @escaping @MainActor () -> T) -> T {
20
+ let fn = unsafeBitCast(body, to: (() -> T).self)
21
+ return fn()
22
+ }
23
+
24
+ /// Thread-local pointer to the current thread's `JSRealm` (nil on threads using `JSRealm.main`).
25
+ private nonisolated final class JSRealmTLS: @unchecked Sendable {
26
+ let key: pthread_key_t
27
+ init() {
28
+ var k: pthread_key_t = 0
29
+ pthread_key_create(&k, nil)
30
+ key = k
31
+ }
32
+ }
33
+
34
+ private nonisolated let jsRealmTLS = JSRealmTLS()
35
+
36
+ /// Per-realm script state: global object, event loop, microtask queue, and thread-confined scratch fields.
37
+ public final class JSRealm: @unchecked Sendable {
38
+ nonisolated deinit {}
39
+
40
+ public let global: JSObject
41
+ let loop: JSEventLoopState
42
+ let microtasks: JSMicrotasks
43
+ /// Runs a job on this realm's thread from any thread: the host installs it for the app's realm.
44
+ public nonisolated(unsafe) var post: ((@Sendable @escaping () -> Void) -> Void)?
45
+ /// Where an uncaught error in this realm goes; nil reports it as the app's.
46
+ var uncaught: ((Any?) -> Void)?
47
+
48
+ /// Per-thread cycle guard for `Array.prototype.join`.
49
+ var joining: [ObjectIdentifier] = []
50
+ /// Per-thread refused dynamic write (`jsSet`).
51
+ var refusedWrite: JSException?
52
+ /// Per-thread last RegExp subject cache.
53
+ var lastRegExpSubject: JSRegExpSubject?
54
+ /// Per-thread RegExp VM (matching runs no script, so each realm owns its own VM without locking).
55
+ let regexVM = RegexVM()
56
+
57
+ init(isMain: Bool = false) {
58
+ self.global = JSObject([("DOMException", jsDOMExceptionConstructor), ("performance", jsDateBuiltin)])
59
+ self.loop = JSEventLoopState(isMain: isMain)
60
+ self.microtasks = JSMicrotasks()
61
+ if isMain {
62
+ self.post = { job in
63
+ JSPosted.post {
64
+ job()
65
+ }
66
+ }
67
+ }
68
+ }
69
+
70
+ /// The app's main-thread realm.
71
+ public nonisolated static let main: JSRealm = {
72
+ let make: @MainActor () -> JSRealm = { JSRealm(isMain: true) }
73
+ return unsafeBitCast(make, to: (() -> JSRealm).self)()
74
+ }()
75
+
76
+ /// The realm of the calling thread: a worker's own on a worker thread, else `main`.
77
+ @inline(__always)
78
+ public nonisolated static func current() -> JSRealm {
79
+ if let raw = pthread_getspecific(jsRealmTLS.key) {
80
+ return Unmanaged<JSRealm>.fromOpaque(raw).takeUnretainedValue()
81
+ }
82
+ return main
83
+ }
84
+
85
+ nonisolated static func enter(_ realm: JSRealm) {
86
+ pthread_setspecific(jsRealmTLS.key, Unmanaged.passUnretained(realm).toOpaque())
87
+ }
88
+
89
+ nonisolated static func leave() {
90
+ pthread_setspecific(jsRealmTLS.key, nil)
91
+ }
92
+ }
@@ -6,34 +6,51 @@ import Foundation
6
6
  public final class JSRecord<Value>: JSDynamic, JSReactiveConvertible, ExpressibleByDictionaryLiteral {
7
7
  nonisolated deinit {}
8
8
  public let object: JSObject
9
+ internal var backing: JSDynamic?
9
10
 
10
11
  public init(object: JSObject = JSObject()) {
11
12
  self.object = object
13
+ self.backing = nil
12
14
  }
13
15
 
14
16
  public init(dictionaryLiteral elements: (String, Value)...) {
15
17
  self.object = JSObject()
18
+ self.backing = nil
16
19
  for (key, value) in elements { object[key] = value }
17
20
  }
18
21
 
19
22
  public init(_ entries: [(String, Value)]) {
20
23
  self.object = JSObject()
24
+ self.backing = nil
21
25
  for (key, value) in entries { object[key] = value }
22
26
  }
23
27
 
24
28
  public init(_ dictionary: [String: Value]) {
25
29
  self.object = JSObject()
30
+ self.backing = nil
26
31
  for key in dictionary.keys.sorted() { object[key] = dictionary[key] }
27
32
  }
28
33
 
29
34
  public subscript(key: String) -> Value? {
30
- get { object[key] as? Value }
31
- set { if let newValue { object[key] = newValue } else { _ = object.delete(key) } }
35
+ get {
36
+ if object.has(key) { return object[key] as? Value }
37
+ return backing?[jsKey: key] as? Value
38
+ }
39
+ set {
40
+ if let newValue {
41
+ object[key] = newValue
42
+ backing?[jsKey: key] = newValue
43
+ } else {
44
+ _ = object.delete(key)
45
+ backing?[jsKey: key] = nil
46
+ }
47
+ }
32
48
  }
33
49
 
34
50
  /// The entry of a record whose values may be undefined: nil for a missing key and a stored undefined alike.
35
51
  public subscript<Wrapped>(entry key: String) -> Wrapped? where Value == Wrapped? {
36
- (object[key] as? Value) ?? nil
52
+ if object.has(key) { return (object[key] as? Value) ?? nil }
53
+ return (backing?[jsKey: key] as? Value) ?? nil
37
54
  }
38
55
 
39
56
  @discardableResult public func delete(_ key: String) -> Bool { object.delete(key) }
@@ -46,8 +63,11 @@ public final class JSRecord<Value>: JSDynamic, JSReactiveConvertible, Expressibl
46
63
  public var jsKeys: [String] { object.jsKeys }
47
64
  public var jsClassName: String? { nil }
48
65
  public subscript(jsKey key: String) -> Any? {
49
- get { object[jsKey: key] }
50
- set { object[jsKey: key] = newValue }
66
+ get { object.has(key) ? object[jsKey: key] : backing?[jsKey: key] }
67
+ set {
68
+ object[jsKey: key] = newValue
69
+ backing?[jsKey: key] = newValue
70
+ }
51
71
  }
52
72
 
53
73
  public var jsTracker: JSTracker? {
@@ -164,11 +164,12 @@ public final class JSRegExp: JSDynamic, JSStringConvertible {
164
164
 
165
165
  public func toString() -> String { "/\(source)/\(flags)" }
166
166
 
167
- /// The matcher for every expression: matching runs no script, so it is never re-entered.
168
- private static let machine = RegexVM()
167
+ /// The matcher for every expression: per-realm so worker threads match concurrently without locking.
168
+ private static var machine: RegexVM { JSRealm.current().regexVM }
169
169
 
170
170
  /// Compiled patterns by pattern and flags: a literal evaluated in a loop makes a new RegExp each time, as
171
171
  /// JavaScript's does, without parsing it again. Bounded by emptying it when full.
172
+ private nonisolated static let cacheLock = NSLock()
172
173
  private static var cache: [String: [String: RegexProgram]] = [:]
173
174
  private static var cached = 0
174
175
  private static let cacheLimit = 256
@@ -184,7 +185,10 @@ public final class JSRegExp: JSDynamic, JSStringConvertible {
184
185
  }
185
186
 
186
187
  private static func compile(_ pattern: String, _ flags: String) throws -> RegexProgram {
187
- if let known = cache[pattern]?[flags] { return known }
188
+ cacheLock.lock()
189
+ let known = cache[pattern]?[flags]
190
+ cacheLock.unlock()
191
+ if let known { return known }
188
192
  let unicodeSets = flags.contains("v")
189
193
  let program: RegexProgram
190
194
  do {
@@ -193,12 +197,14 @@ public final class JSRegExp: JSDynamic, JSStringConvertible {
193
197
  } catch let e as RegexSyntaxError {
194
198
  throw JSException(value: JSSyntaxError("Invalid regular expression: /\(pattern)/\(flags): \(e.message)"))
195
199
  }
200
+ cacheLock.lock()
196
201
  if cached >= cacheLimit {
197
202
  cache.removeAll(keepingCapacity: true)
198
203
  cached = 0
199
204
  }
200
205
  cache[pattern, default: [:]][flags] = program
201
206
  cached += 1
207
+ cacheLock.unlock()
202
208
  return program
203
209
  }
204
210
 
@@ -329,7 +335,10 @@ final class JSRegExpSubject {
329
335
  units = Array(string.utf16)
330
336
  }
331
337
 
332
- private static var last: JSRegExpSubject?
338
+ private static var last: JSRegExpSubject? {
339
+ get { JSRealm.current().lastRegExpSubject }
340
+ set { JSRealm.current().lastRegExpSubject = newValue }
341
+ }
333
342
 
334
343
  static func of(_ s: String) -> JSRegExpSubject {
335
344
  if let last, jsSameText(last.string, s) { return last }