@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
@@ -0,0 +1,680 @@
1
+ import Foundation
2
+
3
+ // Web workers, URL and structured clone, matching Android's `Workers.kt`.
4
+
5
+ /// `URL`: an absolute URL, resolved against an optional base.
6
+ public final class JSURL: JSDynamic, JSStringConvertible, JSHostObject {
7
+ nonisolated deinit {}
8
+ public let href: String
9
+
10
+ public init(_ url: Any?, _ base: Any? = nil) throws {
11
+ let text = jsToString(url)
12
+ let resolved: URL?
13
+ if jsIsNullish(base) {
14
+ if let u = URL(string: text), u.scheme != nil { resolved = u } else { resolved = nil }
15
+ } else {
16
+ let baseText = jsToString(base)
17
+ if let b = URL(string: baseText), b.scheme != nil, let u = URL(string: text, relativeTo: b)?.absoluteURL {
18
+ resolved = u
19
+ } else {
20
+ resolved = nil
21
+ }
22
+ }
23
+ guard let finalURL = resolved else {
24
+ throw JSException(JSTypeError("Invalid URL: \(text)"))
25
+ }
26
+ self.href = finalURL.absoluteString
27
+ }
28
+
29
+ public func toString() -> String { href }
30
+
31
+ public subscript(jsKey key: String) -> Any? {
32
+ get {
33
+ switch key {
34
+ case "href": return href
35
+ case "toString": return { _, _ in self.href } as JSMethod
36
+ default: return nil
37
+ }
38
+ }
39
+ set {}
40
+ }
41
+
42
+ public var jsKeys: [String] { [] }
43
+ public var jsClassName: String? { "URL" }
44
+ public func jsInvoke(_ key: String, _ arguments: [Any?]) throws -> Any?? {
45
+ key == "toString" ? .some(href) : nil
46
+ }
47
+ }
48
+
49
+ /// `MessageEvent`: what a worker's message handler receives.
50
+ public final class JSMessageEvent: JSDynamic, JSHostObject {
51
+ nonisolated deinit {}
52
+ public let data: Any?
53
+
54
+ public init(_ data: Any?) { self.data = data }
55
+
56
+ public subscript(jsKey key: String) -> Any? {
57
+ get { key == "data" ? data : nil }
58
+ set {}
59
+ }
60
+
61
+ public var jsKeys: [String] { ["data"] }
62
+ public var jsClassName: String? { "MessageEvent" }
63
+ public func jsInvoke(_ key: String, _ arguments: [Any?]) throws -> Any?? { nil }
64
+ }
65
+
66
+ /// `ErrorEvent`: what a worker's error handler receives.
67
+ public final class JSErrorEvent: JSDynamic, JSHostObject {
68
+ nonisolated deinit {}
69
+ public let message: String
70
+
71
+ public init(_ message: String) { self.message = message }
72
+
73
+ public subscript(jsKey key: String) -> Any? {
74
+ get { key == "message" ? message : nil }
75
+ set {}
76
+ }
77
+
78
+ public var jsKeys: [String] { ["message"] }
79
+ public var jsClassName: String? { "ErrorEvent" }
80
+ public func jsInvoke(_ key: String, _ arguments: [Any?]) throws -> Any?? { nil }
81
+ }
82
+
83
+ /// Thread-safe registry of compiled worker scripts and currently running workers.
84
+ private nonisolated final class JSWorkerRegistry: @unchecked Sendable {
85
+ let lock = NSLock()
86
+ var scripts: [String: @Sendable () throws -> Void] = [:]
87
+ var running: [String: JSWorker] = [:]
88
+ var activeCount = 0
89
+ }
90
+
91
+ private nonisolated let workerRegistry = JSWorkerRegistry()
92
+
93
+ /// `Worker`: a compiled worker script on its own OS thread, in its own `JSRealm` (global object,
94
+ /// timers, microtasks). Messages pass between threads as structured clones (`jsStructuredClone`).
95
+ /// Also wraps a worker realm's global object via `JSWorker.fromAny(jsGlobalThis)` for `globalThis as Worker`.
96
+ public final class JSWorker: JSDynamic, JSHostObject, @unchecked Sendable {
97
+ nonisolated deinit {}
98
+
99
+ private var _onmessage: ((JSMessageEvent) throws -> Any?)?
100
+ private var _onerror: ((JSErrorEvent) throws -> Any?)?
101
+
102
+ public var onmessage: ((JSMessageEvent) throws -> Any?)? {
103
+ get {
104
+ if let scope {
105
+ guard let fn = jsFlat(scope[jsKey: "onmessage"]), jsIsFunction(fn) else { return nil }
106
+ return { event in try jsCall(fn, event) }
107
+ }
108
+ return _onmessage
109
+ }
110
+ set {
111
+ if let scope {
112
+ if let fn = newValue {
113
+ scope[jsKey: "onmessage"] = { (args: [Any?]) throws -> Any? in
114
+ let raw = jsArg(args, 0)
115
+ let ev = (jsFlat(raw) as? JSMessageEvent) ?? JSMessageEvent(jsField(raw, "data"))
116
+ return try fn(ev)
117
+ } as JSFunction
118
+ } else {
119
+ scope[jsKey: "onmessage"] = nil
120
+ }
121
+ } else {
122
+ _onmessage = newValue
123
+ }
124
+ }
125
+ }
126
+
127
+ public var onerror: ((JSErrorEvent) throws -> Any?)? {
128
+ get {
129
+ if let scope {
130
+ guard let fn = jsFlat(scope[jsKey: "onerror"]), jsIsFunction(fn) else { return nil }
131
+ return { event in try jsCall(fn, event) }
132
+ }
133
+ return _onerror
134
+ }
135
+ set {
136
+ if let scope {
137
+ if let fn = newValue {
138
+ scope[jsKey: "onerror"] = { (args: [Any?]) throws -> Any? in
139
+ let raw = jsArg(args, 0)
140
+ let ev = (jsFlat(raw) as? JSErrorEvent) ?? JSErrorEvent(jsToString(jsField(raw, "message")))
141
+ return try fn(ev)
142
+ } as JSFunction
143
+ } else {
144
+ scope[jsKey: "onerror"] = nil
145
+ }
146
+ } else {
147
+ _onerror = newValue
148
+ }
149
+ }
150
+ }
151
+
152
+ private let scope: JSObject?
153
+ private let owner: JSRealm
154
+ private let realm: JSRealm
155
+ private let key: String
156
+ private nonisolated let condition = NSCondition()
157
+ private nonisolated(unsafe) var inbox: [@Sendable () throws -> Void] = []
158
+ private nonisolated(unsafe) var terminated = false
159
+ private nonisolated(unsafe) var closing = false
160
+ private nonisolated(unsafe) var finished = false
161
+ private nonisolated(unsafe) var wake: UInt64?
162
+
163
+ private nonisolated var isLive: Bool { !terminated && !closing }
164
+
165
+ /// Scope-backed worker wrapper (`globalThis as unknown as Worker` inside a worker script).
166
+ private init(scope: JSObject) {
167
+ self.scope = scope
168
+ self.owner = JSRealm.current()
169
+ self.realm = self.owner
170
+ self.key = ""
171
+ self.finished = true
172
+ }
173
+
174
+ /// Starts a compiled worker script on its own thread.
175
+ public init(_ scriptURL: Any?, _ script: String? = nil) throws {
176
+ guard let script, let entry = JSWorker.lookupScript(script) else {
177
+ throw JSException(JSError("Worker script \(jsToString(scriptURL)) was not compiled with the app"))
178
+ }
179
+ let ownerRealm = JSRealm.current()
180
+ guard ownerRealm.post != nil else {
181
+ throw JSException(JSError("Worker: the creating thread has no event loop to receive messages"))
182
+ }
183
+ self.scope = nil
184
+ self.owner = ownerRealm
185
+ self.realm = JSRealm(isMain: false)
186
+ self.key = script
187
+
188
+ var previous: JSWorker?
189
+ workerRegistry.lock.lock()
190
+ if let current = workerRegistry.running[script], current.isLive {
191
+ workerRegistry.lock.unlock()
192
+ throw JSException(JSError("Worker script \(script) already runs in a worker. Its module state is shared, so one worker runs it at a time: terminate() the first, or close() it from inside, before starting another"))
193
+ }
194
+ previous = workerRegistry.running[script]
195
+ workerRegistry.running[script] = self
196
+ workerRegistry.activeCount += 1
197
+ workerRegistry.lock.unlock()
198
+
199
+ let selfRef = self
200
+ realm.global["postMessage"] = { _, a in
201
+ try selfRef.fromWorker(jsArg(a, 0), jsArg(a, 1))
202
+ return nil
203
+ } as JSMethod
204
+ realm.global["close"] = { _, _ in
205
+ selfRef.markClosing()
206
+ return nil
207
+ } as JSMethod
208
+ realm.global["self"] = realm.global
209
+ realm.global["global"] = realm.global
210
+ realm.uncaught = { error in selfRef.toOwner(error) }
211
+ realm.post = { job in selfRef.enqueue(job) }
212
+ realm.loop.host = { delay in
213
+ if let delay {
214
+ let ns = UInt64(max(0.0, Foundation.ceil(delay)) * 1_000_000.0)
215
+ selfRef.wake = DispatchTime.now().uptimeNanoseconds &+ ns
216
+ } else {
217
+ selfRef.wake = nil
218
+ }
219
+ }
220
+ realm.microtasks.onEnqueue = {
221
+ selfRef.enqueue {
222
+ jsRunInWorker { selfRef.realm.microtasks.checkpoint() }
223
+ }
224
+ }
225
+
226
+ let prev = previous
227
+ let thread = Thread {
228
+ selfRef.runLoop(entry: entry, previous: prev)
229
+ }
230
+ thread.name = "JSWorker \(script)"
231
+ thread.start()
232
+ }
233
+
234
+ private nonisolated static func lookupScript(_ script: String) -> (@Sendable () throws -> Void)? {
235
+ workerRegistry.lock.lock()
236
+ defer { workerRegistry.lock.unlock() }
237
+ return workerRegistry.scripts[script]
238
+ }
239
+
240
+ /// Whether any worker thread is currently active (used by `JSEventLoop.runUntilIdle`).
241
+ public nonisolated static var hasActiveWorkers: Bool {
242
+ workerRegistry.lock.lock()
243
+ defer { workerRegistry.lock.unlock() }
244
+ return workerRegistry.activeCount > 0
245
+ }
246
+
247
+ /// Waits for this worker's OS thread to exit.
248
+ public nonisolated func join() {
249
+ condition.lock()
250
+ while !finished { condition.wait() }
251
+ condition.unlock()
252
+ }
253
+
254
+ private nonisolated func enqueue(_ job: @escaping @Sendable () throws -> Void) {
255
+ condition.lock()
256
+ if !terminated {
257
+ inbox.append(job)
258
+ condition.signal()
259
+ }
260
+ condition.unlock()
261
+ }
262
+
263
+ private nonisolated func markClosing() {
264
+ condition.lock()
265
+ closing = true
266
+ condition.signal()
267
+ condition.unlock()
268
+ }
269
+
270
+ private nonisolated func runLoop(entry: @escaping @Sendable () throws -> Void, previous: JSWorker?) {
271
+ previous?.join()
272
+ JSRealm.enter(realm)
273
+ defer {
274
+ JSRealm.leave()
275
+ condition.lock()
276
+ inbox.removeAll()
277
+ finished = true
278
+ condition.broadcast()
279
+ condition.unlock()
280
+ workerRegistry.lock.lock()
281
+ if workerRegistry.running[key] === self { workerRegistry.running.removeValue(forKey: key) }
282
+ workerRegistry.activeCount -= 1
283
+ workerRegistry.lock.unlock()
284
+ JSPosted.arrived.signal()
285
+ }
286
+
287
+ if isLive {
288
+ runTask { try entry() }
289
+ }
290
+
291
+ while true {
292
+ condition.lock()
293
+ if !isLive {
294
+ condition.unlock()
295
+ break
296
+ }
297
+ if !inbox.isEmpty {
298
+ let job = inbox.removeFirst()
299
+ condition.unlock()
300
+ runTask { try job() }
301
+ continue
302
+ }
303
+ if let due = wake {
304
+ let now = DispatchTime.now().uptimeNanoseconds
305
+ if now >= due {
306
+ wake = nil
307
+ condition.unlock()
308
+ runTask { self.realm.loop.processTimers() }
309
+ continue
310
+ }
311
+ let remaining = Double(due - now) / 1_000_000_000.0
312
+ condition.wait(until: Date(timeIntervalSinceNow: remaining))
313
+ condition.unlock()
314
+ } else {
315
+ condition.wait()
316
+ condition.unlock()
317
+ }
318
+ }
319
+ }
320
+
321
+ private nonisolated func runTask(_ body: @escaping @MainActor () throws -> Void) {
322
+ jsRunInWorker {
323
+ do {
324
+ try body()
325
+ } catch {
326
+ self.toOwner(jsCaught(error))
327
+ }
328
+ if self.terminated { return }
329
+ self.realm.microtasks.taskRan()
330
+ self.realm.microtasks.checkpoint()
331
+ }
332
+ }
333
+
334
+ /// `worker.postMessage(message, transfer)`: clones `message` (moving transferred buffers) onto the worker thread.
335
+ public func postMessage(_ message: Any?, _ transfer: Any? = nil) throws {
336
+ if let scope {
337
+ if jsIsNullish(transfer) {
338
+ _ = try jsCallMethod(scope, "postMessage", message)
339
+ } else {
340
+ _ = try jsCallMethod(scope, "postMessage", message, transfer)
341
+ }
342
+ return
343
+ }
344
+ guard isLive else { return }
345
+ var seen = try jsTransferred(transfer)
346
+ let cloned = try jsStructuredClone(message, seen: &seen)
347
+ let carried = JSCarried(cloned)
348
+ enqueue {
349
+ try jsRunInWorker {
350
+ let handler = self.realm.global["onmessage"]
351
+ if !jsIsNullish(handler) {
352
+ _ = try jsCall(handler, JSMessageEvent(carried.value))
353
+ }
354
+ }
355
+ }
356
+ }
357
+
358
+ private func fromWorker(_ message: Any?, _ transfer: Any?) throws {
359
+ var seen = try jsTransferred(transfer)
360
+ let cloned = try jsStructuredClone(message, seen: &seen)
361
+ guard isLive else { return }
362
+ let carried = JSCarried(cloned)
363
+ if let post = owner.post {
364
+ post {
365
+ jsRunInWorker {
366
+ if !self.terminated {
367
+ self.ownerTask { _ = try self.onmessage?(JSMessageEvent(carried.value)) }
368
+ }
369
+ }
370
+ }
371
+ }
372
+ }
373
+
374
+ private func toOwner(_ error: Any?) {
375
+ guard isLive else { return }
376
+ let message = "Uncaught \(jsToString(error))"
377
+ let reported: Any?
378
+ do {
379
+ var seen: [ObjectIdentifier: Any?] = [:]
380
+ reported = try jsStructuredClone(error, seen: &seen)
381
+ } catch {
382
+ reported = message
383
+ }
384
+ let carried = JSCarried(reported)
385
+ if let post = owner.post {
386
+ post {
387
+ jsRunInWorker {
388
+ if !self.terminated {
389
+ self.ownerTask {
390
+ let handled = try self.onerror?(JSErrorEvent(message))
391
+ if (handled as? Bool) != true {
392
+ self.reportUncaught(carried.value)
393
+ }
394
+ }
395
+ }
396
+ }
397
+ }
398
+ }
399
+ }
400
+
401
+ private func ownerTask(_ body: () throws -> Void) {
402
+ do {
403
+ try body()
404
+ } catch {
405
+ reportUncaught(jsCaught(error))
406
+ }
407
+ Microtasks.taskRan()
408
+ Microtasks.checkpoint()
409
+ }
410
+
411
+ private func reportUncaught(_ error: Any?) {
412
+ jsReportUncaught(error)
413
+ }
414
+
415
+ /// `terminate()`: stops the worker and drops queued messages and timers.
416
+ public func terminate() {
417
+ if let scope {
418
+ _ = try? jsCallMethod(scope, "close")
419
+ return
420
+ }
421
+ condition.lock()
422
+ if terminated {
423
+ condition.unlock()
424
+ return
425
+ }
426
+ terminated = true
427
+ inbox.removeAll()
428
+ condition.broadcast()
429
+ condition.unlock()
430
+ }
431
+
432
+ /// `close()`: on a worker global scope, stops the worker after the current task.
433
+ public func close() {
434
+ if let scope {
435
+ _ = try? jsCallMethod(scope, "close")
436
+ } else {
437
+ terminate()
438
+ }
439
+ }
440
+
441
+ public subscript(jsKey key: String) -> Any? {
442
+ get {
443
+ if let scope { return scope[jsKey: key] }
444
+ switch key {
445
+ case "postMessage":
446
+ return { _, a in try self.postMessage(jsArg(a, 0), jsArg(a, 1)); return nil } as JSMethod
447
+ case "terminate":
448
+ return { _, _ in self.terminate(); return nil } as JSMethod
449
+ case "onmessage":
450
+ return onmessage
451
+ case "onerror":
452
+ return onerror
453
+ default:
454
+ return nil
455
+ }
456
+ }
457
+ set {
458
+ if let scope {
459
+ scope[jsKey: key] = newValue
460
+ return
461
+ }
462
+ let flat = jsFlat(newValue)
463
+ switch key {
464
+ case "onmessage":
465
+ if let flat, jsIsFunction(flat) {
466
+ onmessage = { event in try jsCall(flat, event) }
467
+ } else {
468
+ onmessage = nil
469
+ }
470
+ case "onerror":
471
+ if let flat, jsIsFunction(flat) {
472
+ onerror = { event in try jsCall(flat, event) }
473
+ } else {
474
+ onerror = nil
475
+ }
476
+ default:
477
+ break
478
+ }
479
+ }
480
+ }
481
+
482
+ public var jsKeys: [String] { scope?.jsKeys ?? [] }
483
+ public var jsClassName: String? { "Worker" }
484
+ public func jsInvoke(_ key: String, _ arguments: [Any?]) throws -> Any?? {
485
+ if scope != nil { return nil }
486
+ switch key {
487
+ case "postMessage":
488
+ try postMessage(jsArg(arguments, 0), jsArg(arguments, 1))
489
+ return .some(nil)
490
+ case "terminate":
491
+ terminate()
492
+ return .some(nil)
493
+ case "close":
494
+ close()
495
+ return .some(nil)
496
+ default:
497
+ return nil
498
+ }
499
+ }
500
+
501
+ /// Registers a compiled worker script's module initializer by its app-relative path.
502
+ public static func register(_ script: String, _ entry: @escaping () throws -> Void) {
503
+ let carried = JSCarried(entry)
504
+ workerRegistry.lock.lock()
505
+ workerRegistry.scripts[script] = { try jsRunInWorker { try carried.value() } }
506
+ workerRegistry.lock.unlock()
507
+ }
508
+
509
+ /// `globalThis as Worker` inside a worker script: wraps the worker realm's global object as a `JSWorker`.
510
+ public static func fromAny(_ value: Any?) throws -> JSWorker {
511
+ if let worker = fromAnyOrNil(value) { return worker }
512
+ throw JSException(JSTypeError("\(jsTypeof(value)) is not a JSWorker"))
513
+ }
514
+
515
+ /// Non-throwing `JSWorker` conversion for optional/shape fields.
516
+ public static func fromAnyOrNil(_ value: Any?) -> JSWorker? {
517
+ let flat = jsFlat(value)
518
+ if let w = flat as? JSWorker { return w }
519
+ if let obj = flat as? JSObject { return JSWorker(scope: obj) }
520
+ return nil
521
+ }
522
+ }
523
+
524
+ /// HTML StructuredSerialize/Deserialize in one step: deep-copies plain data, buffers, typed arrays,
525
+ /// Date, RegExp, Array, Map, Set, and standard Errors, preserving cycles and shared buffer views;
526
+ /// refuses functions, symbols, and host objects with `DataCloneError`.
527
+ public func jsStructuredClone(_ value: Any?) throws -> Any? {
528
+ var seen: [ObjectIdentifier: Any?] = [:]
529
+ return try jsStructuredClone(value, seen: &seen)
530
+ }
531
+
532
+ func jsStructuredClone(_ value: Any?, seen: inout [ObjectIdentifier: Any?]) throws -> Any? {
533
+ let flat = jsFlat(value)
534
+ guard let v = flat else { return nil }
535
+ if v is JSNull || v is String || v is Double || v is Bool || v is JSBigInt { return v }
536
+ if let n = jsNumeric(v) { return n }
537
+
538
+ let fail: () throws -> Never = {
539
+ throw JSException(JSDOMException("\(type(of: v)) could not be cloned.", "DataCloneError"))
540
+ }
541
+ if jsIsFunction(v) { try fail() }
542
+
543
+ if let obj = v as AnyObject? {
544
+ let id = ObjectIdentifier(obj)
545
+ if let existing = seen[id] { return existing }
546
+ }
547
+
548
+ if let buf = v as? JSArrayBuffer {
549
+ if buf.detached {
550
+ throw JSException(JSDOMException("An ArrayBuffer is detached and could not be cloned.", "DataCloneError"))
551
+ }
552
+ let copy = buf.slice()
553
+ seen[ObjectIdentifier(buf)] = copy
554
+ return copy
555
+ }
556
+ if let ta = v as? JSTypedArrayProtocol {
557
+ guard let clonedBuf = try jsStructuredClone(ta.buffer, seen: &seen) as? JSArrayBuffer else {
558
+ try fail()
559
+ }
560
+ let copy = ta.jsClone(buffer: clonedBuf)
561
+ seen[ObjectIdentifier(ta)] = copy
562
+ return copy
563
+ }
564
+ if let dv = v as? JSDataView {
565
+ guard let clonedBuf = try jsStructuredClone(dv.buffer, seen: &seen) as? JSArrayBuffer else {
566
+ try fail()
567
+ }
568
+ let copy = try JSDataView(buffer: clonedBuf, dv.byteOffset, dv.byteLength)
569
+ seen[ObjectIdentifier(dv)] = copy
570
+ return copy
571
+ }
572
+ if let d = v as? JSDate {
573
+ let copy = JSDate(d.time)
574
+ seen[ObjectIdentifier(d)] = copy
575
+ return copy
576
+ }
577
+ if let re = v as? JSRegExp {
578
+ let copy = try JSRegExp(re.source, re.flags)
579
+ seen[ObjectIdentifier(re)] = copy
580
+ return copy
581
+ }
582
+ if let arr = v as? JSArrayProtocol {
583
+ let copy = JSArray<Any?>()
584
+ seen[ObjectIdentifier(arr)] = copy
585
+ for e in arr.jsAnyElements {
586
+ copy.storage.append(try jsStructuredClone(e, seen: &seen))
587
+ }
588
+ return copy
589
+ }
590
+ if let map = v as? JSMapProtocol {
591
+ let copy = JSMap<Any?, Any?>()
592
+ seen[ObjectIdentifier(map)] = copy
593
+ for (k, val) in map.jsAnyEntries {
594
+ _ = copy.set(try jsStructuredClone(k, seen: &seen), try jsStructuredClone(val, seen: &seen))
595
+ }
596
+ return copy
597
+ }
598
+ if let set = v as? JSSetProtocol {
599
+ let copy = JSSet<Any?>()
600
+ seen[ObjectIdentifier(set)] = copy
601
+ for e in set.jsAnyValues {
602
+ _ = copy.add(try jsStructuredClone(e, seen: &seen))
603
+ }
604
+ return copy
605
+ }
606
+ if let err = v as? JSError {
607
+ let copy: JSError
608
+ if let dom = err as? JSDOMException {
609
+ copy = JSDOMException(dom.message, dom.name)
610
+ } else {
611
+ switch err.name {
612
+ case "TypeError": copy = JSTypeError(err.message)
613
+ case "RangeError": copy = JSRangeError(err.message)
614
+ case "SyntaxError": copy = JSSyntaxError(err.message)
615
+ case "ReferenceError": copy = JSReferenceError(err.message)
616
+ default: copy = JSError(err.message)
617
+ }
618
+ }
619
+ copy.stack = err.stack
620
+ seen[ObjectIdentifier(err)] = copy
621
+ return copy
622
+ }
623
+ if v is JSSymbol || v is JSHostObject {
624
+ try fail()
625
+ }
626
+ if let dyn = v as? JSDynamic {
627
+ let copy = JSObject()
628
+ seen[ObjectIdentifier(dyn)] = copy
629
+ for k in dyn.jsKeys {
630
+ copy[k] = try jsStructuredClone(dyn[jsKey: k], seen: &seen)
631
+ }
632
+ return copy
633
+ }
634
+ try fail()
635
+ }
636
+
637
+ /// Prepares the transfer map for `postMessage(message, transfer)`.
638
+ func jsTransferred(_ transfer: Any?) throws -> [ObjectIdentifier: Any?] {
639
+ var seen: [ObjectIdentifier: Any?] = [:]
640
+ let flat = jsFlat(transfer)
641
+ let listObj: Any?
642
+ if flat is JSArrayProtocol || flat == nil || flat is JSNull {
643
+ listObj = flat
644
+ } else {
645
+ listObj = jsField(flat, "transfer")
646
+ }
647
+ guard let arr = listObj as? JSArrayProtocol else { return seen }
648
+ let items = arr.jsAnyElements.map { jsFlat($0) }
649
+ var buffers: [JSArrayBuffer] = []
650
+ for (idx, item) in items.enumerated() {
651
+ guard let buf = item as? JSArrayBuffer else {
652
+ throw JSException(JSDOMException("Value at index \(idx) does not have a transferable type.", "DataCloneError"))
653
+ }
654
+ let id = ObjectIdentifier(buf)
655
+ if seen.keys.contains(id) {
656
+ throw JSException(JSDOMException("ArrayBuffer at index \(idx) is a duplicate of an earlier ArrayBuffer.", "DataCloneError"))
657
+ }
658
+ seen[id] = nil
659
+ buffers.append(buf)
660
+ }
661
+ for buf in buffers {
662
+ seen[ObjectIdentifier(buf)] = try buf.transfer()
663
+ }
664
+ return seen
665
+ }
666
+
667
+ /// A worker script's own `postMessage(message, transfer)`.
668
+ public func jsPostMessage(_ message: Any?, _ transfer: Any? = nil) throws {
669
+ let fn = jsGlobalThis["postMessage"]
670
+ if jsIsNullish(transfer) {
671
+ _ = try jsCall(fn, message)
672
+ } else {
673
+ _ = try jsCall(fn, message, transfer)
674
+ }
675
+ }
676
+
677
+ /// A worker script's own `close()`.
678
+ public func jsClose() throws {
679
+ _ = try jsCall(jsGlobalThis["close"])
680
+ }
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.15",
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": [