@solidnative-dev/renderer 0.0.0-stage → 0.1.0-alpha.0

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.
@@ -0,0 +1,2159 @@
1
+ import { HOST_CAUSAL_OPERATION_ID_MAX_LENGTH, } from "@solidnative-dev/host-contract";
2
+ import { TREE_DEBUG_SNAPSHOT_MAX_CHILDREN, TREE_DEBUG_SNAPSHOT_MAX_DEPTH, TREE_DEBUG_SNAPSHOT_MAX_EVENT_NAMES, TREE_DEBUG_SNAPSHOT_MAX_NAME_LENGTH, TREE_DEBUG_SNAPSHOT_MAX_NODES, TREE_DEBUG_SNAPSHOT_MAX_PROP_NAMES, createTreeDebugSnapshot, normalizeTreeDebugAccessibilityRole, telemetryErrorAttributes, } from "@solidnative-dev/observability";
3
+ import { flush as flushSolid } from "solid-js";
4
+ import { normalizeCommandArgs, normalizeHostProperty, normalizeStaticProps, parseEventProperty, } from "./values.js";
5
+ const NATIVE_CAUSAL_RETAINED_RESULT = Symbol("solid-native.causal-retained-result");
6
+ /** @internal */
7
+ export function createNativeCausalRetainedResult(result, retain) {
8
+ if (typeof retain !== "function") {
9
+ throw new TypeError("Native causal event retention must be a function.");
10
+ }
11
+ return Object.freeze({
12
+ [NATIVE_CAUSAL_RETAINED_RESULT]: true,
13
+ result,
14
+ retain,
15
+ });
16
+ }
17
+ function isNativeCausalRetainedResult(value) {
18
+ return (value !== null &&
19
+ typeof value === "object" &&
20
+ NATIVE_CAUSAL_RETAINED_RESULT in value &&
21
+ value[NATIVE_CAUSAL_RETAINED_RESULT] === true);
22
+ }
23
+ function reportIsolatedRootError(handler, error) {
24
+ try {
25
+ const reported = handler?.(error);
26
+ void Promise.resolve(reported).catch(() => undefined);
27
+ }
28
+ catch {
29
+ // A diagnostic observer cannot replace a renderer or telemetry failure.
30
+ }
31
+ }
32
+ const NODE_STATES = new WeakMap();
33
+ const PRIORITY_RANK = {
34
+ background: 0,
35
+ normal: 1,
36
+ "user-blocking": 2,
37
+ immediate: 3,
38
+ };
39
+ const MAX_PENDING_MOUNT_OPERATIONS = 256;
40
+ const CAUSAL_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_.:-]{0,127}$/u;
41
+ /** @internal */
42
+ export function assertNativeCausalName(kind, name) {
43
+ if (!CAUSAL_NAME_PATTERN.test(name)) {
44
+ throw new TypeError(`Native causal ${kind} names must be 1-128 character identifiers.`);
45
+ }
46
+ }
47
+ function lifecycleKey(event) {
48
+ return `${event.surface}:${event.sequence}:${event.hostRevision}`;
49
+ }
50
+ function stateOf(node) {
51
+ const state = NODE_STATES.get(node);
52
+ if (state === undefined)
53
+ throw new Error("Unknown native node.");
54
+ return state;
55
+ }
56
+ function requireHandle(node) {
57
+ const handle = stateOf(node).handle;
58
+ if (handle === undefined) {
59
+ throw new Error("Sentinel nodes do not have host handles.");
60
+ }
61
+ return handle;
62
+ }
63
+ function isPromiseLike(value) {
64
+ return (value !== null &&
65
+ (typeof value === "object" || typeof value === "function") &&
66
+ "then" in value &&
67
+ typeof value.then === "function");
68
+ }
69
+ function distinctCausalOperations(...candidates) {
70
+ return candidates.filter((cause, index) => cause !== undefined && candidates.indexOf(cause) === index);
71
+ }
72
+ function commitTelemetryAttributes(transaction) {
73
+ const attributes = {
74
+ "commit.mutation_count": transaction.mutations.length,
75
+ "commit.priority": transaction.priority,
76
+ "commit.sequence": transaction.sequence,
77
+ "surface.id": transaction.surface,
78
+ };
79
+ for (const mutation of transaction.mutations) {
80
+ const key = `commit.mutation.${mutation.type}`;
81
+ const count = attributes[key];
82
+ attributes[key] = typeof count === "number" ? count + 1 : 1;
83
+ }
84
+ return attributes;
85
+ }
86
+ export class NativeNode {
87
+ constructor() { }
88
+ get kind() {
89
+ return stateOf(this).kind;
90
+ }
91
+ get componentName() {
92
+ return stateOf(this).component;
93
+ }
94
+ get parentNode() {
95
+ return stateOf(this).parent;
96
+ }
97
+ get firstChild() {
98
+ return stateOf(this).firstChild;
99
+ }
100
+ get nextSibling() {
101
+ return stateOf(this).nextSibling;
102
+ }
103
+ measure() {
104
+ return nativeNodeRoot(this).measure(this);
105
+ }
106
+ dispatchCommand(command, ...args) {
107
+ return nativeNodeRoot(this).dispatchCommand(this, command, args);
108
+ }
109
+ focus() {
110
+ return this.dispatchCommand("focus");
111
+ }
112
+ blur() {
113
+ return this.dispatchCommand("blur");
114
+ }
115
+ /** Moves platform accessibility focus to this mounted native element. */
116
+ focusAccessibility() {
117
+ return this.dispatchCommand("accessibilityFocus");
118
+ }
119
+ }
120
+ class NativeRootDisposedError extends Error {
121
+ constructor() {
122
+ super("Native root has been disposed.");
123
+ this.name = "NativeRootDisposedError";
124
+ }
125
+ }
126
+ class NativeRootInitializationError extends Error {
127
+ initializationError;
128
+ cleanup;
129
+ constructor(initializationError, cleanup) {
130
+ super("Native root initialization failed after acquiring its surface.", {
131
+ cause: initializationError,
132
+ });
133
+ this.initializationError = initializationError;
134
+ this.cleanup = cleanup;
135
+ this.name = "NativeRootInitializationError";
136
+ }
137
+ }
138
+ function createNode(state) {
139
+ const node = new NativeNode();
140
+ NODE_STATES.set(node, state);
141
+ return node;
142
+ }
143
+ function unlinkChild(parentState, node, nodeState) {
144
+ const previous = nodeState.previousSibling;
145
+ const next = nodeState.nextSibling;
146
+ if (previous !== undefined)
147
+ stateOf(previous).nextSibling = next;
148
+ else if (parentState.firstChild === node)
149
+ parentState.firstChild = next;
150
+ if (next !== undefined)
151
+ stateOf(next).previousSibling = previous;
152
+ else if (parentState.lastChild === node)
153
+ parentState.lastChild = previous;
154
+ nodeState.previousSibling = undefined;
155
+ nodeState.nextSibling = undefined;
156
+ nodeState.parent = undefined;
157
+ }
158
+ function linkChild(parent, parentState, node, nodeState, anchor) {
159
+ const anchorState = anchor === undefined ? undefined : stateOf(anchor);
160
+ const previous = anchorState === undefined
161
+ ? parentState.lastChild
162
+ : anchorState.previousSibling;
163
+ nodeState.parent = parent;
164
+ nodeState.previousSibling = previous;
165
+ nodeState.nextSibling = anchor;
166
+ if (previous !== undefined)
167
+ stateOf(previous).nextSibling = node;
168
+ else
169
+ parentState.firstChild = node;
170
+ if (anchorState !== undefined)
171
+ anchorState.previousSibling = node;
172
+ else
173
+ parentState.lastChild = node;
174
+ }
175
+ /** @internal Runs a host mutation with the causal annotations of a node. */
176
+ export function runWithNativeNodeCausalContext(node, fallback, callback) {
177
+ const nodeComputation = stateOf(node).causalComputation;
178
+ const fallbackComputation = fallback === undefined ? undefined : stateOf(fallback).causalComputation;
179
+ // Solid disposes a component owner before its reconciler removes the
180
+ // component's native children. The closed boundary truthfully describes no
181
+ // further output; fall back to an active parent boundary instead of trying
182
+ // to revive it for teardown mutations.
183
+ const computation = nodeComputation?.state === "active"
184
+ ? nodeComputation
185
+ : fallbackComputation?.state === "active"
186
+ ? fallbackComputation
187
+ : undefined;
188
+ const owner = stateOf(node).causalOwner ??
189
+ (fallback === undefined ? undefined : stateOf(fallback).causalOwner);
190
+ const run = () => computation === undefined ? callback() : computation.run(callback);
191
+ return owner === undefined ? run() : owner.run(run);
192
+ }
193
+ /** @internal */
194
+ export function createDetachedNativeText(value) {
195
+ return createNode({
196
+ kind: "text",
197
+ text: value,
198
+ props: new Map(),
199
+ events: new Map(),
200
+ captureEvents: new Map(),
201
+ });
202
+ }
203
+ /** @internal */
204
+ export function createDetachedNativeSentinel() {
205
+ return createNode({
206
+ kind: "sentinel",
207
+ props: new Map(),
208
+ events: new Map(),
209
+ captureEvents: new Map(),
210
+ });
211
+ }
212
+ export class NativeRoot {
213
+ host;
214
+ surfaceId;
215
+ container;
216
+ #autoCommit;
217
+ #onCommitError;
218
+ #telemetry;
219
+ #onTelemetryError;
220
+ #surfaceOperation;
221
+ #nodes = new Set();
222
+ #nodesByHandle = new Map();
223
+ #pending = [];
224
+ #pendingCreates = new Map();
225
+ #pendingTextCreates = new Map();
226
+ #pendingProps = new Map();
227
+ #pendingText = new Map();
228
+ #pendingEventListeners = new Map();
229
+ #pendingDetached = new Set();
230
+ #pendingCauses = new Map();
231
+ #pendingComputations = new Map();
232
+ #causalScopes = new Set();
233
+ #mountOperations = new Map();
234
+ #mountedLifecycleKeys = new Set();
235
+ #mountWaiters = new Map();
236
+ #pendingMeasurements = new Set();
237
+ #unsubscribe = () => { };
238
+ #unsubscribeLifecycle = () => { };
239
+ #supportsMountLifecycle = false;
240
+ #commitTail = Promise.resolve();
241
+ #commandTail = Promise.resolve();
242
+ #nextSequence = 1;
243
+ #lastCommittedSequence = 0;
244
+ #pendingPriority = "background";
245
+ #scopedPriority = "normal";
246
+ #mutationGeneration = 0;
247
+ #flushScheduled = false;
248
+ #disposed = false;
249
+ #disposal;
250
+ #commitError;
251
+ #activeCause;
252
+ constructor(host, options) {
253
+ this.host = host;
254
+ this.#autoCommit = options.autoCommit ?? true;
255
+ this.#onCommitError = options.onCommitError;
256
+ this.#telemetry = options.telemetry;
257
+ this.#onTelemetryError = options.onTelemetryError;
258
+ const component = options.rootComponent ?? "RootView";
259
+ if (host.getComponentDescriptor(component) === undefined) {
260
+ throw new Error(`The host does not provide root component ${component}.`);
261
+ }
262
+ this.surfaceId = host.createSurface(options.surface);
263
+ try {
264
+ this.#surfaceOperation =
265
+ this.#telemetry === undefined
266
+ ? undefined
267
+ : this.#startOperation("solid-native.surface", {
268
+ "surface.id": this.surfaceId,
269
+ "surface.name": options.surface.name,
270
+ "surface.root_component": component,
271
+ });
272
+ const handle = host.allocateNode(this.surfaceId);
273
+ this.container = createNode({
274
+ root: this,
275
+ kind: "element",
276
+ handle,
277
+ component,
278
+ props: new Map(),
279
+ events: new Map(),
280
+ captureEvents: new Map(),
281
+ });
282
+ this.#nodes.add(this.container);
283
+ this.#nodesByHandle.set(handle, this.container);
284
+ const previousCause = this.#activeCause;
285
+ this.#activeCause = this.#surfaceOperation;
286
+ try {
287
+ this.#queueCreateElement(handle, component, normalizeStaticProps(options.surface.initialProps));
288
+ }
289
+ finally {
290
+ this.#activeCause = previousCause;
291
+ }
292
+ this.#unsubscribe = host.subscribe((event) => this.#handleEvent(event));
293
+ this.#supportsMountLifecycle =
294
+ host.capabilities.commitMountEvents &&
295
+ host.subscribeLifecycle !== undefined;
296
+ this.#unsubscribeLifecycle =
297
+ this.#telemetry !== undefined && this.#supportsMountLifecycle
298
+ ? host.subscribeLifecycle((event) => this.#handleLifecycle(event))
299
+ : () => { };
300
+ }
301
+ catch (initializationError) {
302
+ const cleanup = this.#rollbackFailedInitialization(initializationError);
303
+ // A direct constructor caller cannot await rollback. Observe its
304
+ // rejection here; NativeRoot.createAsync still awaits the original
305
+ // promise and retains any rollback failure for production startup.
306
+ void cleanup.catch(() => undefined);
307
+ throw new NativeRootInitializationError(initializationError, cleanup);
308
+ }
309
+ }
310
+ async #rollbackFailedInitialization(initializationError) {
311
+ this.#disposed = true;
312
+ const cleanupErrors = [];
313
+ for (const unsubscribe of [this.#unsubscribeLifecycle, this.#unsubscribe]) {
314
+ try {
315
+ unsubscribe();
316
+ }
317
+ catch (error) {
318
+ cleanupErrors.push(error);
319
+ }
320
+ }
321
+ try {
322
+ await this.host.destroySurface(this.surfaceId);
323
+ }
324
+ catch (error) {
325
+ cleanupErrors.push(error);
326
+ }
327
+ finally {
328
+ this.#finishOperation(this.#surfaceOperation, "error", telemetryErrorAttributes(initializationError));
329
+ this.#pending.length = 0;
330
+ this.#pendingCreates.clear();
331
+ this.#pendingTextCreates.clear();
332
+ this.#pendingProps.clear();
333
+ this.#pendingText.clear();
334
+ this.#pendingEventListeners.clear();
335
+ this.#pendingDetached.clear();
336
+ this.#pendingCauses.clear();
337
+ this.#pendingComputations.clear();
338
+ this.#nodes.clear();
339
+ this.#nodesByHandle.clear();
340
+ }
341
+ if (cleanupErrors.length === 1)
342
+ throw cleanupErrors[0];
343
+ if (cleanupErrors.length > 1) {
344
+ throw new AggregateError(cleanupErrors, "Multiple native root initialization rollback steps failed.");
345
+ }
346
+ }
347
+ get lastCommittedSequence() {
348
+ return this.#lastCommittedSequence;
349
+ }
350
+ get disposed() {
351
+ return this.#disposed;
352
+ }
353
+ /**
354
+ * Captures a bounded, value-free snapshot of the mounted logical UI tree.
355
+ * Excludes rendered text content, prop values, labels, and user input.
356
+ */
357
+ snapshotTree(options = {}) {
358
+ this.#assertActive();
359
+ if (options === null || typeof options !== "object") {
360
+ throw new TypeError("Native root tree snapshot options must be an object.");
361
+ }
362
+ const maxNodes = options.maxNodes ?? TREE_DEBUG_SNAPSHOT_MAX_NODES;
363
+ if (!Number.isSafeInteger(maxNodes) ||
364
+ maxNodes < 1 ||
365
+ maxNodes > TREE_DEBUG_SNAPSHOT_MAX_NODES) {
366
+ throw new TypeError(`Native root tree snapshot maxNodes must be a safe integer from 1 through ${String(TREE_DEBUG_SNAPSHOT_MAX_NODES)}.`);
367
+ }
368
+ const maxDepth = options.maxDepth ?? TREE_DEBUG_SNAPSHOT_MAX_DEPTH;
369
+ if (!Number.isSafeInteger(maxDepth) ||
370
+ maxDepth < 0 ||
371
+ maxDepth > TREE_DEBUG_SNAPSHOT_MAX_DEPTH) {
372
+ throw new TypeError(`Native root tree snapshot maxDepth must be a safe integer from 0 through ${String(TREE_DEBUG_SNAPSHOT_MAX_DEPTH)}.`);
373
+ }
374
+ const maxChildren = options.maxChildren ?? TREE_DEBUG_SNAPSHOT_MAX_CHILDREN;
375
+ if (!Number.isSafeInteger(maxChildren) ||
376
+ maxChildren < 0 ||
377
+ maxChildren > TREE_DEBUG_SNAPSHOT_MAX_CHILDREN) {
378
+ throw new TypeError(`Native root tree snapshot maxChildren must be a safe integer from 0 through ${String(TREE_DEBUG_SNAPSHOT_MAX_CHILDREN)}.`);
379
+ }
380
+ let includedNodes = 0;
381
+ let elementCount = 0;
382
+ let textCount = 0;
383
+ let sentinelCount = 0;
384
+ let totalOmittedChildCount = 0;
385
+ let observedMaxDepth = 0;
386
+ let truncated = false;
387
+ const clipNameList = (names, maximum) => {
388
+ const normalized = new Set();
389
+ for (const raw of names) {
390
+ if (raw.length === 0 || /\p{Cc}/u.test(raw)) {
391
+ truncated = true;
392
+ continue;
393
+ }
394
+ if (raw.length > TREE_DEBUG_SNAPSHOT_MAX_NAME_LENGTH) {
395
+ truncated = true;
396
+ normalized.add(raw.slice(0, TREE_DEBUG_SNAPSHOT_MAX_NAME_LENGTH));
397
+ }
398
+ else {
399
+ normalized.add(raw);
400
+ }
401
+ }
402
+ const sorted = [...normalized].sort();
403
+ if (sorted.length > maximum) {
404
+ truncated = true;
405
+ return sorted.slice(0, maximum);
406
+ }
407
+ return sorted;
408
+ };
409
+ const visitElement = (node, depth) => {
410
+ const state = stateOf(node);
411
+ includedNodes += 1;
412
+ elementCount += 1;
413
+ if (depth > observedMaxDepth)
414
+ observedMaxDepth = depth;
415
+ const children = [];
416
+ let omittedChildCount = 0;
417
+ for (let child = state.firstChild; child !== undefined; child = stateOf(child).nextSibling) {
418
+ const childState = stateOf(child);
419
+ if (childState.kind === "sentinel") {
420
+ sentinelCount += 1;
421
+ continue;
422
+ }
423
+ if (depth >= maxDepth ||
424
+ children.length >= maxChildren ||
425
+ includedNodes >= maxNodes) {
426
+ omittedChildCount += 1;
427
+ totalOmittedChildCount += 1;
428
+ truncated = true;
429
+ continue;
430
+ }
431
+ if (childState.kind === "text") {
432
+ includedNodes += 1;
433
+ textCount += 1;
434
+ if (depth + 1 > observedMaxDepth)
435
+ observedMaxDepth = depth + 1;
436
+ const causalOwner = childState.causalOwner?.name;
437
+ const causalComputation = childState.causalComputation?.name;
438
+ children.push({
439
+ kind: "text",
440
+ handle: requireHandle(child),
441
+ textLength: (childState.text ?? "").length,
442
+ ...(causalOwner === undefined ? {} : { causalOwner }),
443
+ ...(causalComputation === undefined ? {} : { causalComputation }),
444
+ });
445
+ continue;
446
+ }
447
+ children.push(visitElement(child, depth + 1));
448
+ }
449
+ const role = normalizeTreeDebugAccessibilityRole(state.props.get("accessibilityRole"));
450
+ const causalOwner = state.causalOwner?.name;
451
+ const causalComputation = state.causalComputation?.name;
452
+ const componentName = state.component ?? "RootView";
453
+ const component = componentName.length > TREE_DEBUG_SNAPSHOT_MAX_NAME_LENGTH
454
+ ? ((truncated = true),
455
+ componentName.slice(0, TREE_DEBUG_SNAPSHOT_MAX_NAME_LENGTH))
456
+ : componentName;
457
+ return {
458
+ kind: "element",
459
+ handle: requireHandle(node),
460
+ component,
461
+ propNames: clipNameList(state.props.keys(), TREE_DEBUG_SNAPSHOT_MAX_PROP_NAMES),
462
+ eventNames: clipNameList([...state.events.keys(), ...state.captureEvents.keys()], TREE_DEBUG_SNAPSHOT_MAX_EVENT_NAMES),
463
+ ...(role === undefined ? {} : { role }),
464
+ ...(causalOwner === undefined ? {} : { causalOwner }),
465
+ ...(causalComputation === undefined ? {} : { causalComputation }),
466
+ ...(omittedChildCount === 0 ? {} : { omittedChildCount }),
467
+ children,
468
+ };
469
+ };
470
+ const root = visitElement(this.container, 0);
471
+ return createTreeDebugSnapshot({
472
+ ...(options.capturedAt === undefined
473
+ ? {}
474
+ : { capturedAt: options.capturedAt }),
475
+ platform: this.host.platform,
476
+ surfaceId: this.surfaceId,
477
+ committedSequence: this.#lastCommittedSequence,
478
+ pendingMutationCount: this.#pending.length,
479
+ truncated,
480
+ nodeCount: includedNodes,
481
+ elementCount,
482
+ textCount,
483
+ sentinelCount,
484
+ omittedChildCount: totalOmittedChildCount,
485
+ maxDepth: observedMaxDepth,
486
+ root,
487
+ });
488
+ }
489
+ createCausalScope(name) {
490
+ this.#assertActive();
491
+ assertNativeCausalName("scope", name);
492
+ const parentCause = this.#activeCause ?? this.#surfaceOperation;
493
+ const operation = this.#startOperation("solid-native.task", { "task.name": name }, parentCause === undefined ? [] : [parentCause]);
494
+ let state = "active";
495
+ let controller;
496
+ const complete = (nextState, error) => {
497
+ if (state !== "active")
498
+ return;
499
+ state = nextState;
500
+ this.#causalScopes.delete(controller);
501
+ this.#finishOperation(operation, nextState === "finished"
502
+ ? "ok"
503
+ : nextState === "failed"
504
+ ? "error"
505
+ : "cancelled", nextState === "failed" ? telemetryErrorAttributes(error) : {});
506
+ };
507
+ controller = { cancel: () => complete("cancelled") };
508
+ this.#causalScopes.add(controller);
509
+ return Object.freeze({
510
+ name,
511
+ get state() {
512
+ return state;
513
+ },
514
+ run: (callback) => {
515
+ if (state !== "active") {
516
+ throw new Error(`Native causal scope ${name} is no longer active.`);
517
+ }
518
+ this.#assertActive();
519
+ if (typeof callback !== "function") {
520
+ throw new TypeError("Native causal scope callback must be a function.");
521
+ }
522
+ const previousCause = this.#activeCause;
523
+ this.#activeCause = operation;
524
+ try {
525
+ const result = callback();
526
+ flushSolid();
527
+ return result;
528
+ }
529
+ finally {
530
+ this.#activeCause = previousCause;
531
+ }
532
+ },
533
+ finish: () => complete("finished"),
534
+ fail: (error) => complete("failed", error),
535
+ cancel: controller.cancel,
536
+ });
537
+ }
538
+ /** @internal Runs one non-Fabric native callback as a causal input event. */
539
+ runCausalPlatformEvent(name, options, callback) {
540
+ this.#assertActive();
541
+ assertNativeCausalName("event", name);
542
+ if (typeof callback !== "function") {
543
+ throw new TypeError("Native causal event callback must be a function.");
544
+ }
545
+ const priority = options.priority ?? "default";
546
+ if (priority !== "default" &&
547
+ priority !== "continuous" &&
548
+ priority !== "discrete") {
549
+ throw new TypeError("Native causal event priority must be default, continuous, or discrete.");
550
+ }
551
+ const coalescible = options.coalescible ?? false;
552
+ if (typeof coalescible !== "boolean") {
553
+ throw new TypeError("Native causal event coalescible must be a boolean.");
554
+ }
555
+ const previousCause = this.#activeCause;
556
+ const parentCause = previousCause ?? this.#surfaceOperation;
557
+ const operation = this.#startOperation("solid-native.event", {
558
+ "event.bubbles": false,
559
+ "event.coalescible": coalescible,
560
+ "event.name": name,
561
+ "event.priority": priority,
562
+ "event.source": "platform",
563
+ "surface.id": this.surfaceId,
564
+ }, parentCause === undefined ? [] : [parentCause]);
565
+ const previousPriority = this.#scopedPriority;
566
+ let operationFinished = false;
567
+ const finishEvent = (status, attributes) => {
568
+ if (operationFinished)
569
+ return;
570
+ operationFinished = true;
571
+ this.#finishOperation(operation, status, attributes);
572
+ };
573
+ this.#activeCause = operation ?? previousCause;
574
+ this.#scopedPriority = priority === "discrete" ? "user-blocking" : "normal";
575
+ try {
576
+ const result = callback();
577
+ flushSolid();
578
+ if (isNativeCausalRetainedResult(result)) {
579
+ let state = "active";
580
+ let controller;
581
+ const complete = (nextState, error) => {
582
+ if (state !== "active")
583
+ return;
584
+ state = nextState;
585
+ this.#causalScopes.delete(controller);
586
+ finishEvent(nextState === "finished"
587
+ ? "ok"
588
+ : nextState === "failed"
589
+ ? "error"
590
+ : "cancelled", {
591
+ "event.handler_count": 1,
592
+ "event.propagation_stopped": false,
593
+ ...(nextState === "failed"
594
+ ? telemetryErrorAttributes(error)
595
+ : {}),
596
+ });
597
+ };
598
+ controller = Object.freeze({
599
+ get state() {
600
+ return state;
601
+ },
602
+ run: (settle) => {
603
+ if (state !== "active") {
604
+ throw new Error("Native causal event retention is no longer active.");
605
+ }
606
+ this.#assertActive();
607
+ if (typeof settle !== "function") {
608
+ throw new TypeError("Native causal event settlement must be a function.");
609
+ }
610
+ const retainedCause = this.#activeCause;
611
+ const retainedPriority = this.#scopedPriority;
612
+ this.#activeCause = operation ?? retainedCause;
613
+ this.#scopedPriority =
614
+ priority === "discrete" ? "user-blocking" : "normal";
615
+ try {
616
+ const settled = settle();
617
+ flushSolid();
618
+ return settled;
619
+ }
620
+ finally {
621
+ this.#scopedPriority = retainedPriority;
622
+ this.#activeCause = retainedCause;
623
+ }
624
+ },
625
+ finish: () => complete("finished"),
626
+ fail: (error) => complete("failed", error),
627
+ cancel: () => complete("cancelled"),
628
+ });
629
+ this.#causalScopes.add(controller);
630
+ try {
631
+ result.retain(controller);
632
+ }
633
+ catch (error) {
634
+ controller.fail(error);
635
+ throw error;
636
+ }
637
+ return result.result;
638
+ }
639
+ finishEvent("ok", {
640
+ "event.handler_count": 1,
641
+ "event.propagation_stopped": false,
642
+ });
643
+ if (isPromiseLike(result)) {
644
+ void Promise.resolve(result).finally(() => {
645
+ if (!this.#disposed)
646
+ this.#linkPendingCause(operation);
647
+ });
648
+ }
649
+ return result;
650
+ }
651
+ catch (error) {
652
+ finishEvent("error", {
653
+ "event.handler_count": 1,
654
+ ...telemetryErrorAttributes(error),
655
+ });
656
+ throw error;
657
+ }
658
+ finally {
659
+ this.#scopedPriority = previousPriority;
660
+ this.#activeCause = previousCause;
661
+ }
662
+ }
663
+ createCausalOwner(name) {
664
+ this.#assertActive();
665
+ assertNativeCausalName("owner", name);
666
+ const parentCause = this.#activeCause ?? this.#surfaceOperation;
667
+ const operation = this.#startOperation("solid-native.owner", { "owner.name": name }, parentCause === undefined ? [] : [parentCause]);
668
+ let state = "active";
669
+ let controller;
670
+ const complete = (nextState) => {
671
+ if (state !== "active")
672
+ return;
673
+ state = nextState;
674
+ this.#causalScopes.delete(controller);
675
+ this.#finishOperation(operation, nextState === "finished" ? "ok" : "cancelled");
676
+ };
677
+ controller = { cancel: () => complete("cancelled") };
678
+ this.#causalScopes.add(controller);
679
+ return Object.freeze({
680
+ name,
681
+ get state() {
682
+ return state;
683
+ },
684
+ run: (callback) => {
685
+ this.#assertActive();
686
+ if (typeof callback !== "function") {
687
+ throw new TypeError("Native causal owner callback must be a function.");
688
+ }
689
+ const previousCause = this.#activeCause;
690
+ const previousMutationGeneration = this.#mutationGeneration;
691
+ this.#activeCause = operation;
692
+ try {
693
+ return callback();
694
+ }
695
+ finally {
696
+ if (this.#mutationGeneration !== previousMutationGeneration) {
697
+ this.#linkPendingCause(previousCause);
698
+ }
699
+ this.#activeCause = previousCause;
700
+ }
701
+ },
702
+ finish: () => complete("finished"),
703
+ });
704
+ }
705
+ /** @internal Creates one opt-in annotation for selected reactive output. */
706
+ createCausalComputation(name, parent) {
707
+ this.#assertActive();
708
+ assertNativeCausalName("computation", name);
709
+ let state = "active";
710
+ let controller;
711
+ const complete = (nextState) => {
712
+ if (state !== "active")
713
+ return;
714
+ state = nextState;
715
+ this.#causalScopes.delete(controller);
716
+ const operation = this.#pendingComputations.get(controller);
717
+ this.#pendingComputations.delete(controller);
718
+ this.#finishOperation(operation, nextState === "finished" ? "ok" : "cancelled");
719
+ };
720
+ controller = {
721
+ name,
722
+ parent,
723
+ cancel: () => complete("cancelled"),
724
+ };
725
+ this.#causalScopes.add(controller);
726
+ const runCurrent = (callback) => {
727
+ if (state !== "active") {
728
+ throw new Error(`Native causal computation ${name} is no longer active.`);
729
+ }
730
+ this.#assertActive();
731
+ if (typeof callback !== "function") {
732
+ throw new TypeError("Native causal computation callback must be a function.");
733
+ }
734
+ if (this.#telemetry === undefined)
735
+ return callback();
736
+ const previousCause = this.#activeCause;
737
+ const existingOperation = this.#pendingComputations.get(controller);
738
+ const parentCause = previousCause ?? this.#surfaceOperation;
739
+ const operation = existingOperation ??
740
+ this.#startOperation("solid-native.computation", {
741
+ "computation.kind": "native-output",
742
+ "computation.name": name,
743
+ }, parentCause === undefined ? [] : [parentCause]);
744
+ if (operation === undefined)
745
+ return callback();
746
+ const previousMutationGeneration = this.#mutationGeneration;
747
+ let failed = false;
748
+ let failure;
749
+ this.#activeCause = operation;
750
+ try {
751
+ return callback();
752
+ }
753
+ catch (caught) {
754
+ failed = true;
755
+ failure = caught;
756
+ throw caught;
757
+ }
758
+ finally {
759
+ const mutated = this.#mutationGeneration !== previousMutationGeneration;
760
+ if (mutated)
761
+ this.#linkPendingCause(previousCause);
762
+ this.#activeCause = previousCause;
763
+ if (failed) {
764
+ this.#pendingComputations.delete(controller);
765
+ this.#finishOperation(operation, "error", {
766
+ ...telemetryErrorAttributes(failure),
767
+ });
768
+ }
769
+ else if (mutated) {
770
+ this.#pendingComputations.set(controller, operation);
771
+ }
772
+ else if (existingOperation === undefined) {
773
+ this.#finishOperation(operation);
774
+ }
775
+ }
776
+ };
777
+ return Object.freeze({
778
+ name,
779
+ get state() {
780
+ return state;
781
+ },
782
+ run: (callback) => parent === undefined
783
+ ? runCurrent(callback)
784
+ : parent.run(() => runCurrent(callback)),
785
+ finish: () => complete("finished"),
786
+ });
787
+ }
788
+ /** @internal */
789
+ createElement(component, staticProps, causalOwner, causalComputation) {
790
+ this.#assertActive();
791
+ let resolvedComponent = component;
792
+ if (this.host.getComponentDescriptor(resolvedComponent) === undefined) {
793
+ const capitalized = `${component[0]?.toUpperCase() ?? ""}${component.slice(1)}`;
794
+ if (this.host.getComponentDescriptor(capitalized) !== undefined) {
795
+ resolvedComponent = capitalized;
796
+ }
797
+ else {
798
+ throw new Error(`Unknown native component: ${component}.`);
799
+ }
800
+ }
801
+ const handle = this.host.allocateNode(this.surfaceId);
802
+ const props = normalizeStaticProps(staticProps);
803
+ const node = createNode({
804
+ root: this,
805
+ ...(causalComputation === undefined ? {} : { causalComputation }),
806
+ ...(causalOwner === undefined ? {} : { causalOwner }),
807
+ kind: "element",
808
+ handle,
809
+ component: resolvedComponent,
810
+ props: new Map(Object.entries(props)),
811
+ events: new Map(),
812
+ captureEvents: new Map(),
813
+ });
814
+ this.#nodes.add(node);
815
+ this.#nodesByHandle.set(handle, node);
816
+ this.#queueCreateElement(handle, resolvedComponent, props);
817
+ for (const [name, value] of Object.entries(staticProps ?? {})) {
818
+ if (parseEventProperty(name) !== undefined) {
819
+ this.setProperty(node, name, value);
820
+ }
821
+ }
822
+ return node;
823
+ }
824
+ /** @internal */
825
+ createText(value) {
826
+ this.#assertActive();
827
+ const node = createDetachedNativeText(value);
828
+ this.#materializeNode(node);
829
+ return node;
830
+ }
831
+ /** @internal */
832
+ createSentinel() {
833
+ this.#assertActive();
834
+ const node = createDetachedNativeSentinel();
835
+ this.#materializeNode(node);
836
+ return node;
837
+ }
838
+ /** @internal */
839
+ replaceText(node, value) {
840
+ const state = this.#requireOwnedNode(node);
841
+ if (state.kind !== "text") {
842
+ throw new Error("Only text nodes can receive text updates.");
843
+ }
844
+ if (state.text === value)
845
+ return;
846
+ state.text = value;
847
+ if (!this.#nodes.has(node))
848
+ return;
849
+ const handle = requireHandle(node);
850
+ const create = this.#pendingTextCreates.get(handle);
851
+ if (create !== undefined) {
852
+ create.text = value;
853
+ }
854
+ else {
855
+ const existing = this.#pendingText.get(handle);
856
+ if (existing !== undefined) {
857
+ existing.text = value;
858
+ }
859
+ else {
860
+ const entry = {
861
+ kind: "update-text",
862
+ node: handle,
863
+ text: value,
864
+ };
865
+ this.#pending.push(entry);
866
+ this.#pendingText.set(handle, entry);
867
+ }
868
+ }
869
+ this.#scheduleCommit();
870
+ }
871
+ /** @internal */
872
+ setProperty(node, name, value) {
873
+ const state = this.#requireOwnedNode(node);
874
+ if (state.kind !== "element") {
875
+ throw new Error(`Cannot set property ${name} on a ${state.kind} node.`);
876
+ }
877
+ const event = parseEventProperty(name);
878
+ if (event !== undefined) {
879
+ const registry = event.capture ? state.captureEvents : state.events;
880
+ const observedBefore = state.events.has(event.name) || state.captureEvents.has(event.name);
881
+ if (value === undefined || value === null) {
882
+ registry.delete(event.name);
883
+ }
884
+ else if (typeof value === "function") {
885
+ registry.set(event.name, {
886
+ handler: value,
887
+ });
888
+ }
889
+ else {
890
+ throw new TypeError(`Event property ${name} must be a function.`);
891
+ }
892
+ const observedAfter = state.events.has(event.name) || state.captureEvents.has(event.name);
893
+ if (observedBefore !== observedAfter && this.#nodes.has(node)) {
894
+ this.#queueEventListeners(requireHandle(node), state);
895
+ }
896
+ return;
897
+ }
898
+ if (name === "children" || name === "ref")
899
+ return;
900
+ const normalized = normalizeHostProperty(name, value);
901
+ if (!this.#nodes.has(node)) {
902
+ if (normalized === undefined) {
903
+ state.props.delete(name);
904
+ }
905
+ else {
906
+ state.props.set(name, normalized);
907
+ }
908
+ return;
909
+ }
910
+ const handle = requireHandle(node);
911
+ const create = this.#pendingCreates.get(handle);
912
+ if (normalized === undefined) {
913
+ state.props.delete(name);
914
+ if (create !== undefined) {
915
+ delete create.props[name];
916
+ }
917
+ else {
918
+ const update = this.#getPendingProps(handle);
919
+ delete update.props[name];
920
+ update.removedProps.add(name);
921
+ }
922
+ }
923
+ else {
924
+ state.props.set(name, normalized);
925
+ if (create !== undefined) {
926
+ create.props[name] = normalized;
927
+ }
928
+ else {
929
+ const update = this.#getPendingProps(handle);
930
+ update.props[name] = normalized;
931
+ update.removedProps.delete(name);
932
+ }
933
+ }
934
+ this.#scheduleCommit();
935
+ }
936
+ /** @internal */
937
+ insertNode(parent, node, anchor) {
938
+ const parentState = this.#requireOwnedNode(parent);
939
+ const detachedState = stateOf(node);
940
+ if (detachedState.causalOwner === undefined &&
941
+ parentState.causalOwner !== undefined) {
942
+ detachedState.causalOwner = parentState.causalOwner;
943
+ }
944
+ if (detachedState.causalComputation === undefined &&
945
+ parentState.causalComputation !== undefined) {
946
+ detachedState.causalComputation = parentState.causalComputation;
947
+ }
948
+ if (parentState.kind !== "element") {
949
+ throw new Error("Native children can only be inserted into elements.");
950
+ }
951
+ if (parent === node)
952
+ throw new Error("A node cannot be its own parent.");
953
+ if (anchor !== undefined && stateOf(anchor).parent !== parent) {
954
+ throw new Error("The insertion anchor is not a child of the parent.");
955
+ }
956
+ for (let ancestor = parent; ancestor !== undefined;) {
957
+ if (ancestor === node)
958
+ throw new Error("The insertion would create a cycle.");
959
+ ancestor = stateOf(ancestor).parent;
960
+ }
961
+ if (!this.#nodes.has(parent)) {
962
+ if (detachedState.root !== undefined && detachedState.root !== this) {
963
+ throw new Error("Node belongs to another native root.");
964
+ }
965
+ if (detachedState.root === undefined) {
966
+ if (detachedState.kind === "element") {
967
+ throw new Error("Detached element nodes are not supported.");
968
+ }
969
+ detachedState.root = this;
970
+ }
971
+ if (anchor === node)
972
+ return;
973
+ if (detachedState.parent !== undefined) {
974
+ const previousParent = detachedState.parent;
975
+ unlinkChild(stateOf(previousParent), node, detachedState);
976
+ if (this.#nodes.has(node) &&
977
+ this.#nodes.has(previousParent) &&
978
+ detachedState.kind !== "sentinel") {
979
+ this.#queueMutation({
980
+ type: "remove-child",
981
+ parent: requireHandle(previousParent),
982
+ child: requireHandle(node),
983
+ });
984
+ }
985
+ }
986
+ if (this.#nodes.has(node)) {
987
+ this.#dematerializeSubtree(node, true);
988
+ }
989
+ linkChild(parent, parentState, node, detachedState, anchor);
990
+ this.#pendingDetached.delete(node);
991
+ return;
992
+ }
993
+ const nodeState = this.#materializeNode(node);
994
+ if (anchor === node)
995
+ return;
996
+ if (nodeState.parent !== undefined) {
997
+ unlinkChild(stateOf(nodeState.parent), node, nodeState);
998
+ }
999
+ linkChild(parent, parentState, node, nodeState, anchor);
1000
+ this.#pendingDetached.delete(node);
1001
+ if (nodeState.kind !== "sentinel") {
1002
+ let before;
1003
+ for (let next = nodeState.nextSibling; next !== undefined; next = stateOf(next).nextSibling) {
1004
+ const candidate = stateOf(next).handle;
1005
+ if (candidate !== undefined) {
1006
+ before = candidate;
1007
+ break;
1008
+ }
1009
+ }
1010
+ this.#queueMutation({
1011
+ type: "insert-child",
1012
+ parent: requireHandle(parent),
1013
+ child: requireHandle(node),
1014
+ ...(before === undefined ? {} : { before }),
1015
+ });
1016
+ }
1017
+ }
1018
+ /** @internal */
1019
+ removeNode(parent, node) {
1020
+ const parentState = this.#requireOwnedNode(parent);
1021
+ const nodeState = this.#requireOwnedNode(node);
1022
+ if (nodeState.parent !== parent)
1023
+ return;
1024
+ unlinkChild(parentState, node, nodeState);
1025
+ if (!this.#nodes.has(node))
1026
+ return;
1027
+ this.#pendingDetached.add(node);
1028
+ if (nodeState.kind !== "sentinel" && this.#nodes.has(parent)) {
1029
+ this.#queueMutation({
1030
+ type: "remove-child",
1031
+ parent: requireHandle(parent),
1032
+ child: requireHandle(node),
1033
+ });
1034
+ }
1035
+ }
1036
+ /** @internal Releases a component-owned tree that is deliberately detached. */
1037
+ releaseDetachedNode(node) {
1038
+ const state = this.#requireOwnedNode(node);
1039
+ if (state.parent !== undefined) {
1040
+ throw new Error("Only a detached native node can be released.");
1041
+ }
1042
+ if (!this.#nodes.has(node))
1043
+ return;
1044
+ this.#pendingDetached.add(node);
1045
+ this.#scheduleCommit();
1046
+ }
1047
+ /** @internal Reclaims an element whose owning Solid scope disposed while detached. */
1048
+ reclaimDetachedElementOnOwnerCleanup(node) {
1049
+ if (this.#disposed ||
1050
+ this.#commitError !== undefined ||
1051
+ !this.#nodes.has(node)) {
1052
+ return;
1053
+ }
1054
+ if (stateOf(node).parent !== undefined)
1055
+ return;
1056
+ this.#pendingDetached.add(node);
1057
+ this.#scheduleCommit();
1058
+ }
1059
+ async flush() {
1060
+ let result = await this.#flushPending(true);
1061
+ while (true) {
1062
+ const commands = this.#commandTail;
1063
+ await commands;
1064
+ const trailingResult = await this.#flushPending(true);
1065
+ if (trailingResult !== undefined)
1066
+ result = trailingResult;
1067
+ if (commands === this.#commandTail)
1068
+ return result;
1069
+ }
1070
+ }
1071
+ /** @internal */
1072
+ async flushMounted() {
1073
+ const unsubscribe = this.#telemetry === undefined && this.#supportsMountLifecycle
1074
+ ? this.host.subscribeLifecycle((event) => this.#handleLifecycle(event))
1075
+ : undefined;
1076
+ try {
1077
+ const result = await this.flush();
1078
+ if (result?.hostRevision !== undefined && this.#supportsMountLifecycle) {
1079
+ await this.#waitForMount(result.sequence, result.hostRevision);
1080
+ }
1081
+ return result;
1082
+ }
1083
+ finally {
1084
+ unsubscribe?.();
1085
+ }
1086
+ }
1087
+ async #flushPending(flushReactiveWork) {
1088
+ this.#flushScheduled = false;
1089
+ if (this.#commitError !== undefined)
1090
+ throw this.#commitError;
1091
+ if (flushReactiveWork)
1092
+ flushSolid();
1093
+ if (!this.#disposed)
1094
+ this.#reclaimDetachedNodes();
1095
+ this.#finishPendingComputations();
1096
+ const causes = this.#telemetry === undefined
1097
+ ? undefined
1098
+ : [...this.#pendingCauses.values()];
1099
+ this.#pendingCauses.clear();
1100
+ const mutations = this.#drainPending();
1101
+ if (mutations.length === 0) {
1102
+ await this.#commitTail;
1103
+ if (this.#commitError !== undefined)
1104
+ throw this.#commitError;
1105
+ return undefined;
1106
+ }
1107
+ const sequence = this.#nextSequence++;
1108
+ const priority = this.#pendingPriority;
1109
+ this.#pendingPriority = "background";
1110
+ const baseTransaction = {
1111
+ surface: this.surfaceId,
1112
+ sequence,
1113
+ priority,
1114
+ mutations,
1115
+ };
1116
+ let operation;
1117
+ if (this.#telemetry !== undefined) {
1118
+ operation = this.#startOperation("solid-native.commit", commitTelemetryAttributes(baseTransaction), causes ?? []);
1119
+ }
1120
+ let causalContext;
1121
+ if (operation !== undefined) {
1122
+ if (typeof operation.id === "string" &&
1123
+ operation.id.length > 0 &&
1124
+ operation.id.length <= HOST_CAUSAL_OPERATION_ID_MAX_LENGTH &&
1125
+ !operation.id.includes("\0")) {
1126
+ causalContext = { operationId: operation.id };
1127
+ }
1128
+ else {
1129
+ this.#reportTelemetryError(new RangeError(`Telemetry operation IDs crossing the host boundary must contain 1-${HOST_CAUSAL_OPERATION_ID_MAX_LENGTH} characters without null bytes.`));
1130
+ }
1131
+ }
1132
+ const transaction = {
1133
+ ...baseTransaction,
1134
+ ...(causalContext === undefined ? {} : { causalContext }),
1135
+ };
1136
+ let resolveResult;
1137
+ let rejectResult;
1138
+ const resultPromise = new Promise((resolve, reject) => {
1139
+ resolveResult = resolve;
1140
+ rejectResult = reject;
1141
+ });
1142
+ this.#commitTail = this.#commitTail.then(async () => {
1143
+ try {
1144
+ if (this.#commitError !== undefined)
1145
+ throw this.#commitError;
1146
+ const pendingResult = this.host.commit(transaction);
1147
+ const result = isPromiseLike(pendingResult)
1148
+ ? await pendingResult
1149
+ : pendingResult;
1150
+ if (result.surface !== this.surfaceId ||
1151
+ result.sequence !== sequence ||
1152
+ !result.mounted) {
1153
+ throw new Error(`Host returned an invalid result for commit ${sequence} on surface ${this.surfaceId}.`);
1154
+ }
1155
+ this.#lastCommittedSequence = sequence;
1156
+ this.#finishOperation(operation, "ok", {
1157
+ "commit.mounted": result.mounted,
1158
+ ...(result.hostRevision === undefined
1159
+ ? {}
1160
+ : { "commit.host_revision": result.hostRevision }),
1161
+ });
1162
+ resolveResult(result);
1163
+ }
1164
+ catch (error) {
1165
+ this.#commitError = error;
1166
+ this.#finishOperation(operation, "error", {
1167
+ ...telemetryErrorAttributes(error),
1168
+ });
1169
+ reportIsolatedRootError(this.#onCommitError, error);
1170
+ rejectResult(error);
1171
+ }
1172
+ });
1173
+ await this.#commitTail;
1174
+ return resultPromise;
1175
+ }
1176
+ measure(node) {
1177
+ const callsiteCause = this.#activeCause;
1178
+ return runWithNativeNodeCausalContext(node, undefined, () => {
1179
+ const causes = distinctCausalOperations(callsiteCause, this.#activeCause);
1180
+ const pending = this.#measure(node, causes);
1181
+ this.#pendingMeasurements.add(pending);
1182
+ const release = () => {
1183
+ this.#pendingMeasurements.delete(pending);
1184
+ };
1185
+ void pending.then(release, release);
1186
+ return pending;
1187
+ });
1188
+ }
1189
+ /**
1190
+ * Measures a mounted element node by handle for development UI-tree
1191
+ * inspection without recording a causal measure operation. Returns
1192
+ * `undefined` when the root is inactive or when the handle is unknown,
1193
+ * non-element, unmounted, or unmeasurable.
1194
+ */
1195
+ measureNodeByHandle(handle) {
1196
+ if (!Number.isSafeInteger(handle) || handle <= 0) {
1197
+ throw new TypeError("Native node handle must be a positive safe integer.");
1198
+ }
1199
+ const pending = this.#measureNodeByHandle(handle);
1200
+ this.#pendingMeasurements.add(pending);
1201
+ const release = () => {
1202
+ this.#pendingMeasurements.delete(pending);
1203
+ };
1204
+ void pending.then(release, release);
1205
+ return pending;
1206
+ }
1207
+ async #measureNodeByHandle(handle) {
1208
+ if (this.#disposed || this.#commitError !== undefined)
1209
+ return undefined;
1210
+ const isMountedElement = (candidate) => {
1211
+ if (candidate === undefined || !this.#nodes.has(candidate))
1212
+ return false;
1213
+ const candidateState = stateOf(candidate);
1214
+ if (candidateState.kind !== "element")
1215
+ return false;
1216
+ let cursor = candidate;
1217
+ while (cursor !== undefined) {
1218
+ if (cursor === this.container)
1219
+ return true;
1220
+ cursor = stateOf(cursor).parent;
1221
+ }
1222
+ return false;
1223
+ };
1224
+ const node = this.#nodesByHandle.get(handle);
1225
+ if (!isMountedElement(node))
1226
+ return undefined;
1227
+ try {
1228
+ await this.flush();
1229
+ if (this.#disposed || this.#commitError !== undefined)
1230
+ return undefined;
1231
+ if (this.#nodesByHandle.get(handle) !== node || !isMountedElement(node)) {
1232
+ return undefined;
1233
+ }
1234
+ const afterSequence = this.#lastCommittedSequence;
1235
+ const measurement = await this.host.measure(this.surfaceId, handle, afterSequence);
1236
+ if (this.#disposed || this.#commitError !== undefined)
1237
+ return undefined;
1238
+ return measurement;
1239
+ }
1240
+ catch {
1241
+ return undefined;
1242
+ }
1243
+ }
1244
+ async #measure(node, causes) {
1245
+ this.#requireHostNode(node);
1246
+ const target = requireHandle(node);
1247
+ const operation = this.#telemetry === undefined
1248
+ ? undefined
1249
+ : this.#startOperation("solid-native.measure", {
1250
+ "surface.id": this.surfaceId,
1251
+ "target.node": target,
1252
+ }, causes);
1253
+ this.#linkPendingCause(operation);
1254
+ try {
1255
+ await this.flush();
1256
+ this.#assertActive();
1257
+ const afterSequence = this.#lastCommittedSequence;
1258
+ const measurement = await this.host.measure(this.surfaceId, target, afterSequence);
1259
+ this.#assertActive();
1260
+ this.#finishOperation(operation, "ok", {
1261
+ "measurement.after_sequence": afterSequence,
1262
+ "measurement.observed_sequence": measurement.observedSequence,
1263
+ });
1264
+ return measurement;
1265
+ }
1266
+ catch (error) {
1267
+ this.#finishOperation(operation, "error", {
1268
+ ...telemetryErrorAttributes(error),
1269
+ });
1270
+ throw error;
1271
+ }
1272
+ }
1273
+ dispatchCommand(node, command, args) {
1274
+ const target = requireHandle(node);
1275
+ const callsiteCause = this.#activeCause;
1276
+ const priority = this.#scopedPriority;
1277
+ return runWithNativeNodeCausalContext(node, undefined, () => {
1278
+ const annotatedCause = this.#activeCause;
1279
+ const causes = distinctCausalOperations(callsiteCause, annotatedCause);
1280
+ // Capture the caller's synchronous event plus the node's selected
1281
+ // owner/computation before the command crosses its required microtask
1282
+ // boundary. Neither context should erase the other.
1283
+ const operation = this.#telemetry === undefined
1284
+ ? undefined
1285
+ : this.#startOperation("solid-native.command", {
1286
+ "command.name": command,
1287
+ "surface.id": this.surfaceId,
1288
+ "target.node": target,
1289
+ }, causes);
1290
+ // Framework components may request an imperative correction from an
1291
+ // effect's apply phase. Start native work after that reactive drain has
1292
+ // completed so its structural barrier does not re-enter Solid's flush.
1293
+ const pending = Promise.resolve().then(() => this.#dispatchCommand(node, command, args, operation, priority));
1294
+ const previousCommands = this.#commandTail;
1295
+ this.#commandTail = Promise.all([previousCommands, pending]).then(() => undefined);
1296
+ // A framework-owned command may be scheduled from a reactive effect
1297
+ // where there is no call site that can await it. Keep the rejection
1298
+ // observed; the next root flush still receives it through #commandTail.
1299
+ void this.#commandTail.catch(() => undefined);
1300
+ return pending;
1301
+ });
1302
+ }
1303
+ async #dispatchCommand(node, command, args, operation, priority) {
1304
+ this.#requireHostNode(node);
1305
+ const target = requireHandle(node);
1306
+ // Commands are observable side effects and cannot participate in the
1307
+ // rollback semantics of a structural transaction. Commit any pending tree
1308
+ // work first, then send exactly one command in its own sequence.
1309
+ try {
1310
+ await this.#flushPending(true);
1311
+ // A native event can enqueue reactive work while the preceding commit is
1312
+ // crossing an asynchronous host boundary. Drain all such structural work
1313
+ // before reserving the command transaction. Once JavaScript observes an
1314
+ // empty queue, queue and drain the command synchronously without another
1315
+ // Solid flush so no reactive mutation can join it.
1316
+ while (this.#pending.length > 0)
1317
+ await this.#flushPending(true);
1318
+ // Disposal can begin while an earlier structural commit is crossing an
1319
+ // asynchronous host boundary. Revalidate immediately before emitting
1320
+ // the observable command so a retired handle never receives it.
1321
+ this.#assertActive();
1322
+ const previousCause = this.#activeCause;
1323
+ const previousPriority = this.#scopedPriority;
1324
+ this.#activeCause = operation;
1325
+ this.#scopedPriority = priority;
1326
+ try {
1327
+ this.#queueMutation({
1328
+ type: "command",
1329
+ node: target,
1330
+ command,
1331
+ args: normalizeCommandArgs(args),
1332
+ });
1333
+ }
1334
+ finally {
1335
+ this.#scopedPriority = previousPriority;
1336
+ this.#activeCause = previousCause;
1337
+ }
1338
+ await this.#flushPending(false);
1339
+ this.#finishOperation(operation);
1340
+ }
1341
+ catch (error) {
1342
+ this.#finishOperation(operation, "error", {
1343
+ ...telemetryErrorAttributes(error),
1344
+ });
1345
+ throw error;
1346
+ }
1347
+ }
1348
+ dispose() {
1349
+ this.#disposal ??= this.#dispose();
1350
+ return this.#disposal;
1351
+ }
1352
+ async #dispose() {
1353
+ this.#disposed = true;
1354
+ for (const scope of [...this.#causalScopes])
1355
+ scope.cancel();
1356
+ const failures = [];
1357
+ const retainFailure = (error) => {
1358
+ if (!failures.includes(error))
1359
+ failures.push(error);
1360
+ };
1361
+ // A host is allowed to implement measurement asynchronously. Let any read
1362
+ // that already crossed into the host settle before deleting its target or
1363
+ // destroying the surface; the post-read active check still rejects stale
1364
+ // geometry to the caller.
1365
+ await Promise.allSettled([...this.#pendingMeasurements]);
1366
+ const previousCause = this.#activeCause;
1367
+ this.#activeCause = this.#surfaceOperation;
1368
+ let teardownQueued = false;
1369
+ try {
1370
+ for (const node of this.#nodes) {
1371
+ const state = stateOf(node);
1372
+ if (state.kind !== "sentinel" &&
1373
+ state.parent !== undefined &&
1374
+ stateOf(state.parent).kind !== "sentinel") {
1375
+ this.#queueMutation({
1376
+ type: "remove-child",
1377
+ parent: requireHandle(state.parent),
1378
+ child: requireHandle(node),
1379
+ });
1380
+ }
1381
+ state.parent = undefined;
1382
+ state.firstChild = undefined;
1383
+ state.lastChild = undefined;
1384
+ state.previousSibling = undefined;
1385
+ state.nextSibling = undefined;
1386
+ }
1387
+ this.#pendingDetached.clear();
1388
+ for (const node of this.#nodes) {
1389
+ if (stateOf(node).kind !== "sentinel") {
1390
+ this.#queueMutation({
1391
+ type: "delete-node",
1392
+ node: requireHandle(node),
1393
+ });
1394
+ }
1395
+ }
1396
+ teardownQueued = true;
1397
+ }
1398
+ catch (error) {
1399
+ retainFailure(error);
1400
+ }
1401
+ finally {
1402
+ this.#activeCause = previousCause;
1403
+ }
1404
+ if (teardownQueued) {
1405
+ try {
1406
+ await this.flush();
1407
+ }
1408
+ catch (error) {
1409
+ if (!(error instanceof NativeRootDisposedError))
1410
+ retainFailure(error);
1411
+ }
1412
+ }
1413
+ for (const unsubscribe of [this.#unsubscribeLifecycle, this.#unsubscribe]) {
1414
+ try {
1415
+ unsubscribe();
1416
+ }
1417
+ catch (error) {
1418
+ retainFailure(error);
1419
+ }
1420
+ }
1421
+ const disposedError = new Error("The native root was disposed before its pending mount barrier completed.");
1422
+ for (const waiters of this.#mountWaiters.values()) {
1423
+ for (const waiter of waiters)
1424
+ waiter.reject(disposedError);
1425
+ }
1426
+ this.#mountWaiters.clear();
1427
+ try {
1428
+ await this.host.destroySurface(this.surfaceId);
1429
+ }
1430
+ catch (error) {
1431
+ retainFailure(error);
1432
+ }
1433
+ const failure = failures.length === 0
1434
+ ? undefined
1435
+ : failures.length === 1
1436
+ ? failures[0]
1437
+ : new AggregateError(failures, "Native root disposal failed in multiple lifecycle steps.");
1438
+ this.#finishOperation(this.#surfaceOperation, failure === undefined ? "ok" : "error", failure === undefined ? {} : telemetryErrorAttributes(failure));
1439
+ this.#pending.length = 0;
1440
+ this.#pendingCreates.clear();
1441
+ this.#pendingTextCreates.clear();
1442
+ this.#pendingProps.clear();
1443
+ this.#pendingText.clear();
1444
+ this.#pendingEventListeners.clear();
1445
+ this.#pendingDetached.clear();
1446
+ this.#pendingCauses.clear();
1447
+ this.#pendingComputations.clear();
1448
+ this.#nodes.clear();
1449
+ this.#nodesByHandle.clear();
1450
+ this.#pendingMeasurements.clear();
1451
+ this.#mountOperations.clear();
1452
+ this.#mountedLifecycleKeys.clear();
1453
+ this.#causalScopes.clear();
1454
+ if (failure !== undefined)
1455
+ throw failure;
1456
+ }
1457
+ #assertActive() {
1458
+ if (this.#disposed)
1459
+ throw new NativeRootDisposedError();
1460
+ if (this.#commitError !== undefined)
1461
+ throw this.#commitError;
1462
+ }
1463
+ #materializeNode(node) {
1464
+ const state = stateOf(node);
1465
+ if (state.root !== undefined) {
1466
+ if (state.root !== this) {
1467
+ throw new Error("Node belongs to another native root.");
1468
+ }
1469
+ if (this.#nodes.has(node))
1470
+ return state;
1471
+ this.#rematerializeRetainedSubtree(node);
1472
+ return state;
1473
+ }
1474
+ if (state.kind === "element") {
1475
+ throw new Error("Detached element nodes are not supported.");
1476
+ }
1477
+ this.#assertActive();
1478
+ state.root = this;
1479
+ this.#rematerializeRetainedSubtree(node);
1480
+ return state;
1481
+ }
1482
+ #rematerializeRetainedSubtree(node) {
1483
+ const state = stateOf(node);
1484
+ if (state.root !== this) {
1485
+ throw new Error("Retained native subtree belongs to another root.");
1486
+ }
1487
+ if (this.#nodes.has(node))
1488
+ return;
1489
+ this.#assertActive();
1490
+ this.#nodes.add(node);
1491
+ this.#pendingDetached.delete(node);
1492
+ if (state.kind === "element") {
1493
+ if (state.component === undefined) {
1494
+ throw new Error("Retained native element has no component identity.");
1495
+ }
1496
+ const handle = this.host.allocateNode(this.surfaceId);
1497
+ state.handle = handle;
1498
+ this.#nodesByHandle.set(handle, node);
1499
+ this.#queueCreateElement(handle, state.component, Object.fromEntries(state.props));
1500
+ if (state.events.size > 0 || state.captureEvents.size > 0) {
1501
+ this.#queueEventListeners(handle, state);
1502
+ }
1503
+ }
1504
+ else if (state.kind === "text") {
1505
+ const handle = this.host.allocateNode(this.surfaceId);
1506
+ state.handle = handle;
1507
+ this.#nodesByHandle.set(handle, node);
1508
+ const entry = {
1509
+ kind: "create-text",
1510
+ node: handle,
1511
+ text: state.text ?? "",
1512
+ };
1513
+ this.#pending.push(entry);
1514
+ this.#pendingTextCreates.set(handle, entry);
1515
+ this.#scheduleCommit();
1516
+ }
1517
+ for (let child = state.firstChild; child !== undefined; child = stateOf(child).nextSibling) {
1518
+ const childState = stateOf(child);
1519
+ if (childState.parent !== node) {
1520
+ throw new Error("Retained native subtree has an invalid child link.");
1521
+ }
1522
+ this.#rematerializeRetainedSubtree(child);
1523
+ if (state.kind !== "element" || childState.kind === "sentinel")
1524
+ continue;
1525
+ this.#queueMutation({
1526
+ type: "insert-child",
1527
+ parent: requireHandle(node),
1528
+ child: requireHandle(child),
1529
+ });
1530
+ }
1531
+ }
1532
+ #dematerializeSubtree(node, scheduleCommit) {
1533
+ if (!this.#nodes.has(node))
1534
+ return;
1535
+ const state = stateOf(node);
1536
+ for (let child = state.firstChild; child !== undefined; child = stateOf(child).nextSibling) {
1537
+ const childState = stateOf(child);
1538
+ if (childState.kind !== "sentinel") {
1539
+ this.#pending.push({
1540
+ kind: "mutation",
1541
+ mutation: {
1542
+ type: "remove-child",
1543
+ parent: requireHandle(node),
1544
+ child: requireHandle(child),
1545
+ },
1546
+ });
1547
+ }
1548
+ this.#dematerializeSubtree(child, false);
1549
+ }
1550
+ if (state.kind !== "sentinel") {
1551
+ const handle = requireHandle(node);
1552
+ this.#pending.push({
1553
+ kind: "mutation",
1554
+ mutation: { type: "delete-node", node: handle },
1555
+ });
1556
+ this.#nodesByHandle.delete(handle);
1557
+ this.#pendingCreates.delete(handle);
1558
+ this.#pendingTextCreates.delete(handle);
1559
+ this.#pendingProps.delete(handle);
1560
+ this.#pendingText.delete(handle);
1561
+ this.#pendingEventListeners.delete(handle);
1562
+ }
1563
+ this.#nodes.delete(node);
1564
+ this.#pendingDetached.delete(node);
1565
+ if (scheduleCommit) {
1566
+ this.#scheduleCommit();
1567
+ }
1568
+ }
1569
+ #reclaimDetachedNodes() {
1570
+ for (const node of [...this.#pendingDetached]) {
1571
+ if (stateOf(node).parent === undefined) {
1572
+ this.#dematerializeSubtree(node, false);
1573
+ }
1574
+ }
1575
+ }
1576
+ #requireOwnedNode(node) {
1577
+ this.#assertActive();
1578
+ const state = stateOf(node);
1579
+ if (state.root !== this) {
1580
+ throw new Error("Node belongs to another native root.");
1581
+ }
1582
+ return state;
1583
+ }
1584
+ #requireNode(node) {
1585
+ const state = this.#requireOwnedNode(node);
1586
+ if (!this.#nodes.has(node)) {
1587
+ throw new Error("Node belongs to another native root.");
1588
+ }
1589
+ return state;
1590
+ }
1591
+ #requireHostNode(node) {
1592
+ const state = this.#requireNode(node);
1593
+ if (state.kind === "sentinel") {
1594
+ throw new Error("Sentinel nodes cannot receive host operations.");
1595
+ }
1596
+ return state;
1597
+ }
1598
+ #queueCreateElement(node, component, props) {
1599
+ const entry = {
1600
+ kind: "create-element",
1601
+ node,
1602
+ component,
1603
+ props: { ...props },
1604
+ };
1605
+ this.#pending.push(entry);
1606
+ this.#pendingCreates.set(node, entry);
1607
+ this.#scheduleCommit();
1608
+ }
1609
+ #getPendingProps(node) {
1610
+ const existing = this.#pendingProps.get(node);
1611
+ if (existing !== undefined)
1612
+ return existing;
1613
+ const entry = {
1614
+ kind: "update-props",
1615
+ node,
1616
+ props: {},
1617
+ removedProps: new Set(),
1618
+ };
1619
+ this.#pending.push(entry);
1620
+ this.#pendingProps.set(node, entry);
1621
+ return entry;
1622
+ }
1623
+ #queueMutation(mutation) {
1624
+ this.#pending.push({ kind: "mutation", mutation });
1625
+ this.#scheduleCommit();
1626
+ }
1627
+ #queueEventListeners(node, state) {
1628
+ const events = [
1629
+ ...new Set([...state.events.keys(), ...state.captureEvents.keys()]),
1630
+ ].sort();
1631
+ const existing = this.#pendingEventListeners.get(node);
1632
+ if (existing !== undefined) {
1633
+ existing.events = events;
1634
+ }
1635
+ else {
1636
+ const entry = {
1637
+ kind: "update-event-listeners",
1638
+ node,
1639
+ events,
1640
+ };
1641
+ this.#pending.push(entry);
1642
+ this.#pendingEventListeners.set(node, entry);
1643
+ }
1644
+ this.#scheduleCommit();
1645
+ }
1646
+ #scheduleCommit(priority = this.#scopedPriority) {
1647
+ this.#mutationGeneration =
1648
+ this.#mutationGeneration === Number.MAX_SAFE_INTEGER
1649
+ ? 0
1650
+ : this.#mutationGeneration + 1;
1651
+ if (PRIORITY_RANK[priority] > PRIORITY_RANK[this.#pendingPriority]) {
1652
+ this.#pendingPriority = priority;
1653
+ }
1654
+ if (this.#telemetry !== undefined) {
1655
+ this.#linkPendingCause(this.#activeCause);
1656
+ }
1657
+ if (!this.#autoCommit || this.#flushScheduled)
1658
+ return;
1659
+ this.#flushScheduled = true;
1660
+ void Promise.resolve().then(async () => {
1661
+ try {
1662
+ await this.flush();
1663
+ }
1664
+ catch {
1665
+ // The error is retained and reported through onCommitError/flush.
1666
+ }
1667
+ });
1668
+ }
1669
+ #drainPending() {
1670
+ const entries = this.#pending.splice(0);
1671
+ this.#pendingCreates.clear();
1672
+ this.#pendingTextCreates.clear();
1673
+ this.#pendingProps.clear();
1674
+ this.#pendingText.clear();
1675
+ this.#pendingEventListeners.clear();
1676
+ return entries.flatMap((entry) => {
1677
+ switch (entry.kind) {
1678
+ case "create-element":
1679
+ return [
1680
+ {
1681
+ type: "create-element",
1682
+ node: entry.node,
1683
+ component: entry.component,
1684
+ props: entry.props,
1685
+ },
1686
+ ];
1687
+ case "create-text":
1688
+ return [{ type: "create-text", node: entry.node, text: entry.text }];
1689
+ case "update-props":
1690
+ if (Object.keys(entry.props).length === 0 &&
1691
+ entry.removedProps.size === 0) {
1692
+ return [];
1693
+ }
1694
+ return [
1695
+ {
1696
+ type: "update-props",
1697
+ node: entry.node,
1698
+ props: entry.props,
1699
+ removedProps: [...entry.removedProps],
1700
+ },
1701
+ ];
1702
+ case "update-text":
1703
+ return [{ type: "update-text", node: entry.node, text: entry.text }];
1704
+ case "update-event-listeners":
1705
+ return [
1706
+ {
1707
+ type: "update-event-listeners",
1708
+ node: entry.node,
1709
+ events: entry.events,
1710
+ },
1711
+ ];
1712
+ case "mutation":
1713
+ return [entry.mutation];
1714
+ }
1715
+ });
1716
+ }
1717
+ #handleEvent(event) {
1718
+ if (event.surface !== this.surfaceId || this.#disposed)
1719
+ return;
1720
+ const target = this.#nodesByHandle.get(event.target);
1721
+ if (target === undefined) {
1722
+ this.#recordDroppedEvent(event, "unknown-target");
1723
+ return;
1724
+ }
1725
+ const targetState = stateOf(target);
1726
+ if (target !== this.container && targetState.parent === undefined) {
1727
+ this.#recordDroppedEvent(event, "detached-target");
1728
+ return;
1729
+ }
1730
+ const path = [];
1731
+ for (let node = target; node !== undefined;) {
1732
+ path.push(node);
1733
+ node = stateOf(node).parent;
1734
+ }
1735
+ const operation = this.#telemetry === undefined
1736
+ ? undefined
1737
+ : this.#startOperation("solid-native.event", {
1738
+ "event.bubbles": event.bubbles,
1739
+ "event.coalescible": event.coalescible,
1740
+ "event.name": event.name,
1741
+ "event.native_timestamp": event.timestamp,
1742
+ "event.observed_sequence": event.observedSequence,
1743
+ "event.priority": event.priority,
1744
+ "surface.id": event.surface,
1745
+ "target.node": event.target,
1746
+ });
1747
+ const previousCause = this.#activeCause;
1748
+ this.#activeCause = operation;
1749
+ let handlerCount = 0;
1750
+ let stopped = false;
1751
+ let dispatchComplete = false;
1752
+ let retainedCount = 0;
1753
+ let retainedStatus = "ok";
1754
+ let retainedError;
1755
+ let operationFinished = false;
1756
+ const asyncHandlers = [];
1757
+ const activeRetentions = new Set();
1758
+ const finishEvent = (status, attributes) => {
1759
+ if (operationFinished)
1760
+ return;
1761
+ operationFinished = true;
1762
+ this.#finishOperation(operation, status, attributes);
1763
+ };
1764
+ const finishDispatchIfSettled = () => {
1765
+ if (!dispatchComplete || retainedCount !== 0 || operationFinished)
1766
+ return;
1767
+ const status = handlerCount === 0
1768
+ ? "cancelled"
1769
+ : retainedStatus === "error"
1770
+ ? "error"
1771
+ : retainedStatus === "cancelled"
1772
+ ? "cancelled"
1773
+ : "ok";
1774
+ finishEvent(status, {
1775
+ "event.handler_count": handlerCount,
1776
+ "event.propagation_stopped": stopped,
1777
+ ...(handlerCount === 0 ? { "event.drop_reason": "no-handler" } : {}),
1778
+ ...(status === "error" ? telemetryErrorAttributes(retainedError) : {}),
1779
+ });
1780
+ };
1781
+ const retainEvent = (retained) => {
1782
+ retainedCount++;
1783
+ let state = "active";
1784
+ let controller;
1785
+ const complete = (nextState, error) => {
1786
+ if (state !== "active")
1787
+ return;
1788
+ state = nextState;
1789
+ activeRetentions.delete(controller);
1790
+ this.#causalScopes.delete(controller);
1791
+ retainedCount--;
1792
+ if (nextState === "failed") {
1793
+ retainedStatus = "error";
1794
+ retainedError ??= error;
1795
+ }
1796
+ else if (nextState === "cancelled" && retainedStatus === "ok") {
1797
+ retainedStatus = "cancelled";
1798
+ }
1799
+ finishDispatchIfSettled();
1800
+ };
1801
+ controller = Object.freeze({
1802
+ get state() {
1803
+ return state;
1804
+ },
1805
+ run: (settle) => {
1806
+ if (state !== "active") {
1807
+ throw new Error("Native causal event retention is no longer active.");
1808
+ }
1809
+ this.#assertActive();
1810
+ if (typeof settle !== "function") {
1811
+ throw new TypeError("Native causal event settlement must be a function.");
1812
+ }
1813
+ const retainedCause = this.#activeCause;
1814
+ const retainedPriority = this.#scopedPriority;
1815
+ this.#activeCause = operation ?? retainedCause;
1816
+ this.#scopedPriority =
1817
+ event.priority === "discrete" ? "user-blocking" : "normal";
1818
+ try {
1819
+ const settled = settle();
1820
+ flushSolid();
1821
+ return settled;
1822
+ }
1823
+ finally {
1824
+ this.#scopedPriority = retainedPriority;
1825
+ this.#activeCause = retainedCause;
1826
+ }
1827
+ },
1828
+ finish: () => complete("finished"),
1829
+ fail: (error) => complete("failed", error),
1830
+ cancel: () => complete("cancelled"),
1831
+ });
1832
+ activeRetentions.add(controller);
1833
+ this.#causalScopes.add(controller);
1834
+ try {
1835
+ retained.retain(controller);
1836
+ }
1837
+ catch (error) {
1838
+ controller.fail(error);
1839
+ throw error;
1840
+ }
1841
+ };
1842
+ const invoke = (node, capture) => {
1843
+ if (stopped)
1844
+ return;
1845
+ const state = stateOf(node);
1846
+ const registration = (capture ? state.captureEvents : state.events).get(event.name);
1847
+ if (registration === undefined)
1848
+ return;
1849
+ handlerCount++;
1850
+ const synthetic = {
1851
+ name: event.name,
1852
+ target,
1853
+ currentTarget: node,
1854
+ observedSequence: event.observedSequence,
1855
+ timestamp: event.timestamp,
1856
+ priority: event.priority,
1857
+ bubbles: event.bubbles,
1858
+ coalescible: event.coalescible,
1859
+ payload: event.payload,
1860
+ stopPropagation() {
1861
+ stopped = true;
1862
+ },
1863
+ };
1864
+ const previous = this.#scopedPriority;
1865
+ this.#scopedPriority =
1866
+ event.priority === "discrete" ? "user-blocking" : "normal";
1867
+ let result;
1868
+ try {
1869
+ // Solid 2 event callbacks are deliberately unowned. Re-entering the
1870
+ // component owner here turns ordinary signal setters into illegal
1871
+ // writes from an owned computation scope in development builds.
1872
+ result = registration.handler(synthetic);
1873
+ flushSolid();
1874
+ }
1875
+ finally {
1876
+ this.#scopedPriority = previous;
1877
+ }
1878
+ if (isNativeCausalRetainedResult(result))
1879
+ retainEvent(result);
1880
+ else if (isPromiseLike(result))
1881
+ asyncHandlers.push(result);
1882
+ };
1883
+ try {
1884
+ if (event.bubbles) {
1885
+ for (let index = path.length - 1; index >= 0; index--) {
1886
+ invoke(path[index], true);
1887
+ }
1888
+ }
1889
+ else {
1890
+ invoke(target, true);
1891
+ }
1892
+ const bubblePath = event.bubbles ? path : [target];
1893
+ for (const node of bubblePath)
1894
+ invoke(node, false);
1895
+ dispatchComplete = true;
1896
+ finishDispatchIfSettled();
1897
+ for (const result of asyncHandlers) {
1898
+ void Promise.resolve(result).finally(() => {
1899
+ if (!this.#disposed)
1900
+ this.#linkPendingCause(operation);
1901
+ });
1902
+ }
1903
+ }
1904
+ catch (error) {
1905
+ for (const retention of [...activeRetentions])
1906
+ retention.cancel();
1907
+ finishEvent("error", {
1908
+ "event.handler_count": handlerCount,
1909
+ ...telemetryErrorAttributes(error),
1910
+ });
1911
+ throw error;
1912
+ }
1913
+ finally {
1914
+ this.#activeCause = previousCause;
1915
+ }
1916
+ }
1917
+ #recordDroppedEvent(event, reason) {
1918
+ if (this.#telemetry === undefined)
1919
+ return;
1920
+ const operation = this.#startOperation("solid-native.event", {
1921
+ "event.name": event.name,
1922
+ "event.observed_sequence": event.observedSequence,
1923
+ "event.priority": event.priority,
1924
+ "surface.id": event.surface,
1925
+ "target.node": event.target,
1926
+ });
1927
+ this.#finishOperation(operation, "cancelled", {
1928
+ "event.drop_reason": reason,
1929
+ "event.handler_count": 0,
1930
+ });
1931
+ }
1932
+ #handleLifecycle(event) {
1933
+ if (event.surface !== this.surfaceId)
1934
+ return;
1935
+ if (event.type === "commit-mounted") {
1936
+ const key = lifecycleKey(event);
1937
+ this.#mountedLifecycleKeys.add(key);
1938
+ if (this.#mountedLifecycleKeys.size > MAX_PENDING_MOUNT_OPERATIONS) {
1939
+ const oldest = this.#mountedLifecycleKeys.values().next().value;
1940
+ if (oldest !== undefined)
1941
+ this.#mountedLifecycleKeys.delete(oldest);
1942
+ }
1943
+ const waiters = this.#mountWaiters.get(key);
1944
+ this.#mountWaiters.delete(key);
1945
+ if (waiters !== undefined) {
1946
+ for (const waiter of waiters)
1947
+ waiter.resolve();
1948
+ }
1949
+ }
1950
+ if (this.#telemetry === undefined)
1951
+ return;
1952
+ const commitCause = event.causalContext === undefined
1953
+ ? []
1954
+ : [{ id: event.causalContext.operationId }];
1955
+ const key = lifecycleKey(event);
1956
+ if (event.type === "commit-mounted") {
1957
+ const operation = this.#startOperation("solid-native.mount", {
1958
+ "commit.sequence": event.sequence,
1959
+ "mount.host_revision": event.hostRevision,
1960
+ "surface.id": event.surface,
1961
+ }, commitCause, event.commitStartedAt);
1962
+ this.#finishOperation(operation, "ok", { "mount.completed": true }, { timestamp: event.mountedAt, duration: event.mountLatency });
1963
+ if (operation !== undefined) {
1964
+ if (this.#mountOperations.size >= MAX_PENDING_MOUNT_OPERATIONS) {
1965
+ const oldest = this.#mountOperations.keys().next().value;
1966
+ if (oldest !== undefined)
1967
+ this.#mountOperations.delete(oldest);
1968
+ }
1969
+ this.#mountOperations.set(key, operation);
1970
+ }
1971
+ return;
1972
+ }
1973
+ const mountOperation = this.#mountOperations.get(key);
1974
+ this.#mountOperations.delete(key);
1975
+ const operation = this.#startOperation("solid-native.frame", {
1976
+ "commit.sequence": event.sequence,
1977
+ "frame.commit_latency": event.frameLatency,
1978
+ "frame.host_revision": event.hostRevision,
1979
+ "frame.observation": "next-vsync-after-mount",
1980
+ "surface.id": event.surface,
1981
+ }, mountOperation === undefined ? commitCause : [mountOperation], event.mountedAt);
1982
+ this.#finishOperation(operation, "ok", { "frame.started": true }, {
1983
+ timestamp: event.frameStartedAt,
1984
+ duration: event.mountToFrameLatency,
1985
+ });
1986
+ }
1987
+ #waitForMount(sequence, hostRevision) {
1988
+ const key = `${this.surfaceId}:${sequence}:${hostRevision}`;
1989
+ if (this.#mountedLifecycleKeys.has(key))
1990
+ return Promise.resolve();
1991
+ return new Promise((resolve, reject) => {
1992
+ const waiters = this.#mountWaiters.get(key);
1993
+ const waiter = { resolve, reject };
1994
+ if (waiters === undefined)
1995
+ this.#mountWaiters.set(key, [waiter]);
1996
+ else
1997
+ waiters.push(waiter);
1998
+ });
1999
+ }
2000
+ #linkPendingCause(operation) {
2001
+ if (operation !== undefined && this.#pending.length > 0) {
2002
+ this.#pendingCauses.set(operation.id, operation);
2003
+ }
2004
+ }
2005
+ #finishPendingComputations() {
2006
+ for (const operation of this.#pendingComputations.values()) {
2007
+ this.#finishOperation(operation);
2008
+ }
2009
+ this.#pendingComputations.clear();
2010
+ }
2011
+ #startOperation(name, attributes, causes = [], timestamp) {
2012
+ if (this.#telemetry === undefined)
2013
+ return undefined;
2014
+ try {
2015
+ return this.#telemetry.startOperation(name, {
2016
+ attributes,
2017
+ causes,
2018
+ ...(timestamp === undefined ? {} : { timestamp }),
2019
+ });
2020
+ }
2021
+ catch (error) {
2022
+ this.#reportTelemetryError(error);
2023
+ return undefined;
2024
+ }
2025
+ }
2026
+ #finishOperation(operation, status = "ok", attributes = {}, timing = {}) {
2027
+ if (operation === undefined || this.#telemetry === undefined)
2028
+ return;
2029
+ try {
2030
+ this.#telemetry.finishOperation(operation, {
2031
+ status,
2032
+ attributes,
2033
+ ...(timing.timestamp === undefined
2034
+ ? {}
2035
+ : { timestamp: timing.timestamp }),
2036
+ ...(timing.duration === undefined ? {} : { duration: timing.duration }),
2037
+ });
2038
+ }
2039
+ catch (error) {
2040
+ this.#reportTelemetryError(error);
2041
+ }
2042
+ }
2043
+ #reportTelemetryError(error) {
2044
+ reportIsolatedRootError(this.#onTelemetryError, error);
2045
+ }
2046
+ }
2047
+ /** @internal Preserves the synchronous mount API while starting rollback. */
2048
+ export function createNativeRoot(host, options) {
2049
+ try {
2050
+ return new NativeRoot(host, options);
2051
+ }
2052
+ catch (error) {
2053
+ if (!(error instanceof NativeRootInitializationError))
2054
+ throw error;
2055
+ throw error.initializationError;
2056
+ }
2057
+ }
2058
+ /** @internal Awaits surface rollback before rejecting native startup. */
2059
+ export async function createNativeRootAsync(host, options) {
2060
+ try {
2061
+ return new NativeRoot(host, options);
2062
+ }
2063
+ catch (error) {
2064
+ if (!(error instanceof NativeRootInitializationError))
2065
+ throw error;
2066
+ try {
2067
+ await error.cleanup;
2068
+ }
2069
+ catch (cleanupError) {
2070
+ throw new AggregateError([error.initializationError, cleanupError], "Native root initialization and surface rollback both failed.");
2071
+ }
2072
+ throw error.initializationError;
2073
+ }
2074
+ }
2075
+ /** @internal */
2076
+ export function nativeNodeRoot(node) {
2077
+ const root = stateOf(node).root;
2078
+ if (root === undefined) {
2079
+ throw new Error("Native node is not attached to a root.");
2080
+ }
2081
+ return root;
2082
+ }
2083
+ /** @internal Native execution adapters use this opaque logical identity. */
2084
+ export function nativeNodeHandle(node) {
2085
+ nativeNodeRoot(node);
2086
+ return requireHandle(node);
2087
+ }
2088
+ /** @internal */
2089
+ export function nativeNodeParent(node) {
2090
+ return stateOf(node).parent;
2091
+ }
2092
+ /** @internal */
2093
+ export function nativeNodeFirstChild(node) {
2094
+ return stateOf(node).firstChild;
2095
+ }
2096
+ /** @internal */
2097
+ export function nativeNodeNextSibling(node) {
2098
+ return stateOf(node).nextSibling;
2099
+ }
2100
+ /** @internal Component facades use this for current logical tree ordering. */
2101
+ export function compareNativeNodeOrder(left, right) {
2102
+ if (left === right)
2103
+ return 0;
2104
+ if (stateOf(left).root !== stateOf(right).root) {
2105
+ throw new Error("Cannot compare native nodes from different roots.");
2106
+ }
2107
+ const path = (node) => {
2108
+ const ancestors = [];
2109
+ let current = node;
2110
+ while (current !== undefined) {
2111
+ ancestors.push(current);
2112
+ current = stateOf(current).parent;
2113
+ }
2114
+ return ancestors.reverse();
2115
+ };
2116
+ const leftPath = path(left);
2117
+ const rightPath = path(right);
2118
+ let sharedLength = 0;
2119
+ while (sharedLength < leftPath.length &&
2120
+ sharedLength < rightPath.length &&
2121
+ leftPath[sharedLength] === rightPath[sharedLength]) {
2122
+ sharedLength++;
2123
+ }
2124
+ if (sharedLength === 0) {
2125
+ throw new Error("Cannot compare detached native node subtrees.");
2126
+ }
2127
+ if (sharedLength === leftPath.length)
2128
+ return -1;
2129
+ if (sharedLength === rightPath.length)
2130
+ return 1;
2131
+ const parent = leftPath[sharedLength - 1];
2132
+ const leftChild = leftPath[sharedLength];
2133
+ const rightChild = rightPath[sharedLength];
2134
+ if (parent === undefined ||
2135
+ leftChild === undefined ||
2136
+ rightChild === undefined) {
2137
+ throw new Error("Cannot compare incomplete native node paths.");
2138
+ }
2139
+ let leftIndex = -1;
2140
+ let rightIndex = -1;
2141
+ let index = 0;
2142
+ for (let child = stateOf(parent).firstChild; child !== undefined; child = stateOf(child).nextSibling, index++) {
2143
+ if (child === leftChild) {
2144
+ leftIndex = index;
2145
+ if (rightIndex >= 0)
2146
+ break;
2147
+ }
2148
+ else if (child === rightChild) {
2149
+ rightIndex = index;
2150
+ if (leftIndex >= 0)
2151
+ break;
2152
+ }
2153
+ }
2154
+ if (leftIndex < 0 || rightIndex < 0) {
2155
+ throw new Error("Cannot compare native nodes outside their parent tree.");
2156
+ }
2157
+ return leftIndex - rightIndex;
2158
+ }
2159
+ //# sourceMappingURL=native-root.js.map