@askrjs/askr 0.0.4 → 0.0.6

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 (80) hide show
  1. package/dist/{index.d.cts → component-BBGWJdqJ.d.ts} +42 -33
  2. package/dist/foundations/index.d.ts +32 -0
  3. package/dist/{chunk-WTFWRSHB.js → foundations/index.js} +76 -28
  4. package/dist/foundations/index.js.map +1 -0
  5. package/dist/fx/index.js +295 -77
  6. package/dist/fx/index.js.map +1 -1
  7. package/dist/index.d.ts +4 -134
  8. package/dist/index.js +3709 -42
  9. package/dist/index.js.map +1 -1
  10. package/dist/{jsx/jsx-dev-runtime.d.ts → jsx-dev-runtime.d.ts} +3 -3
  11. package/dist/jsx-dev-runtime.js +17 -0
  12. package/dist/jsx-dev-runtime.js.map +1 -0
  13. package/dist/jsx-runtime.d.ts +14 -0
  14. package/dist/{chunk-SALJX5PZ.js → jsx-runtime.js} +6 -9
  15. package/dist/jsx-runtime.js.map +1 -0
  16. package/dist/layout-D5MqtW_q.d.ts +14 -0
  17. package/dist/resources/index.d.ts +3 -0
  18. package/dist/resources/index.js +753 -239
  19. package/dist/resources/index.js.map +1 -1
  20. package/dist/router/index.d.ts +2 -14
  21. package/dist/router/index.js +3115 -19
  22. package/dist/router/index.js.map +1 -1
  23. package/dist/ssr/index.js +3363 -103
  24. package/dist/ssr/index.js.map +1 -1
  25. package/dist/{types-CZHOAiC1.d.ts → types-uOPfcrdz.d.ts} +3 -1
  26. package/dist/vite/index.d.ts +17 -0
  27. package/dist/vite/index.js +2306 -0
  28. package/dist/vite/index.js.map +1 -0
  29. package/package.json +21 -23
  30. package/dist/chunk-64C7W2AE.js +0 -43
  31. package/dist/chunk-64C7W2AE.js.map +0 -1
  32. package/dist/chunk-6FLMH4EL.js +0 -124
  33. package/dist/chunk-6FLMH4EL.js.map +0 -1
  34. package/dist/chunk-FJUXFA72.js +0 -16
  35. package/dist/chunk-FJUXFA72.js.map +0 -1
  36. package/dist/chunk-SALJX5PZ.js.map +0 -1
  37. package/dist/chunk-VRAEBIJ3.js +0 -82
  38. package/dist/chunk-VRAEBIJ3.js.map +0 -1
  39. package/dist/chunk-WTFWRSHB.js.map +0 -1
  40. package/dist/chunk-XHKZGJE3.js +0 -2907
  41. package/dist/chunk-XHKZGJE3.js.map +0 -1
  42. package/dist/chunk-Z5ZSTLYF.js +0 -420
  43. package/dist/chunk-Z5ZSTLYF.js.map +0 -1
  44. package/dist/fx/index.cjs +0 -1193
  45. package/dist/fx/index.cjs.map +0 -1
  46. package/dist/fx/index.d.cts +0 -186
  47. package/dist/index.cjs +0 -4035
  48. package/dist/index.cjs.map +0 -1
  49. package/dist/jsx/jsx-dev-runtime.cjs +0 -46
  50. package/dist/jsx/jsx-dev-runtime.cjs.map +0 -1
  51. package/dist/jsx/jsx-dev-runtime.d.cts +0 -12
  52. package/dist/jsx/jsx-dev-runtime.js +0 -19
  53. package/dist/jsx/jsx-dev-runtime.js.map +0 -1
  54. package/dist/jsx/jsx-runtime.cjs +0 -54
  55. package/dist/jsx/jsx-runtime.cjs.map +0 -1
  56. package/dist/jsx/jsx-runtime.d.cts +0 -21
  57. package/dist/jsx/jsx-runtime.d.ts +0 -21
  58. package/dist/jsx/jsx-runtime.js +0 -16
  59. package/dist/jsx/jsx-runtime.js.map +0 -1
  60. package/dist/jsx-AzPM8gMS.d.cts +0 -35
  61. package/dist/navigate-LUVYHYZZ.js +0 -17
  62. package/dist/navigate-LUVYHYZZ.js.map +0 -1
  63. package/dist/resources/index.cjs +0 -1200
  64. package/dist/resources/index.cjs.map +0 -1
  65. package/dist/resources/index.d.cts +0 -21
  66. package/dist/route-BCND6MPK.js +0 -32
  67. package/dist/route-BCND6MPK.js.map +0 -1
  68. package/dist/router/index.cjs +0 -3247
  69. package/dist/router/index.cjs.map +0 -1
  70. package/dist/router/index.d.cts +0 -64
  71. package/dist/router-DaGtH1Sq.d.cts +0 -36
  72. package/dist/ssr/index.cjs +0 -4059
  73. package/dist/ssr/index.cjs.map +0 -1
  74. package/dist/ssr/index.d.cts +0 -123
  75. package/dist/types-CZ5sWur5.d.cts +0 -23
  76. package/src/jsx/index.ts +0 -4
  77. package/src/jsx/jsx-dev-runtime.ts +0 -23
  78. package/src/jsx/jsx-runtime.ts +0 -48
  79. package/src/jsx/types.ts +0 -33
  80. package/src/jsx/utils.ts +0 -19
@@ -1,2907 +0,0 @@
1
- import {
2
- Fragment as Fragment2
3
- } from "./chunk-SALJX5PZ.js";
4
- import {
5
- Fragment
6
- } from "./chunk-FJUXFA72.js";
7
-
8
- // src/dev/logger.ts
9
- function callConsole(method, args) {
10
- const c = typeof console !== "undefined" ? console : void 0;
11
- if (!c) return;
12
- const fn = c[method];
13
- if (typeof fn === "function") {
14
- try {
15
- fn.apply(console, args);
16
- } catch {
17
- }
18
- }
19
- }
20
- var logger = {
21
- debug: (...args) => {
22
- if (process.env.NODE_ENV === "production") return;
23
- callConsole("debug", args);
24
- },
25
- info: (...args) => {
26
- if (process.env.NODE_ENV === "production") return;
27
- callConsole("info", args);
28
- },
29
- warn: (...args) => {
30
- if (process.env.NODE_ENV === "production") return;
31
- callConsole("warn", args);
32
- },
33
- error: (...args) => {
34
- callConsole("error", args);
35
- }
36
- };
37
-
38
- // src/dev/invariant.ts
39
- function invariant(condition, message, context) {
40
- if (!condition) {
41
- const contextStr = context ? "\n" + JSON.stringify(context, null, 2) : "";
42
- throw new Error(`[Askr Invariant] ${message}${contextStr}`);
43
- }
44
- }
45
- function assertSchedulingPrecondition(condition, violationMessage) {
46
- invariant(condition, `[Scheduler Precondition] ${violationMessage}`);
47
- }
48
-
49
- // src/runtime/scheduler.ts
50
- var MAX_FLUSH_DEPTH = 50;
51
- function isBulkCommitActive() {
52
- try {
53
- const fb = globalThis.__ASKR_FASTLANE;
54
- return typeof fb?.isBulkCommitActive === "function" ? !!fb.isBulkCommitActive() : false;
55
- } catch (e) {
56
- void e;
57
- return false;
58
- }
59
- }
60
- var Scheduler = class {
61
- constructor() {
62
- this.q = [];
63
- this.head = 0;
64
- this.running = false;
65
- this.inHandler = false;
66
- this.depth = 0;
67
- this.executionDepth = 0;
68
- // for compat with existing diagnostics
69
- // Monotonic flush version increments at end of each flush
70
- this.flushVersion = 0;
71
- // Best-effort microtask kick scheduling
72
- this.kickScheduled = false;
73
- // Escape hatch flag for runWithSyncProgress
74
- this.allowSyncProgress = false;
75
- // Waiters waiting for flushVersion >= target
76
- this.waiters = [];
77
- // Keep a lightweight taskCount for compatibility/diagnostics
78
- this.taskCount = 0;
79
- }
80
- enqueue(task) {
81
- assertSchedulingPrecondition(
82
- typeof task === "function",
83
- "enqueue() requires a function"
84
- );
85
- if (isBulkCommitActive() && !this.allowSyncProgress) {
86
- if (process.env.NODE_ENV !== "production") {
87
- throw new Error(
88
- "[Scheduler] enqueue() during bulk commit (not allowed)"
89
- );
90
- }
91
- return;
92
- }
93
- this.q.push(task);
94
- this.taskCount++;
95
- if (!this.running && !this.kickScheduled && !this.inHandler && !isBulkCommitActive()) {
96
- this.kickScheduled = true;
97
- queueMicrotask(() => {
98
- this.kickScheduled = false;
99
- if (this.running) return;
100
- if (isBulkCommitActive()) return;
101
- try {
102
- this.flush();
103
- } catch (err) {
104
- setTimeout(() => {
105
- throw err;
106
- });
107
- }
108
- });
109
- }
110
- }
111
- flush() {
112
- invariant(
113
- !this.running,
114
- "[Scheduler] flush() called while already running"
115
- );
116
- if (process.env.NODE_ENV !== "production") {
117
- if (isBulkCommitActive() && !this.allowSyncProgress) {
118
- throw new Error(
119
- "[Scheduler] flush() started during bulk commit (not allowed)"
120
- );
121
- }
122
- }
123
- this.running = true;
124
- this.depth = 0;
125
- let fatal = null;
126
- try {
127
- while (this.head < this.q.length) {
128
- this.depth++;
129
- if (process.env.NODE_ENV !== "production" && this.depth > MAX_FLUSH_DEPTH) {
130
- throw new Error(
131
- `[Scheduler] exceeded MAX_FLUSH_DEPTH (${MAX_FLUSH_DEPTH}). Likely infinite update loop.`
132
- );
133
- }
134
- const task = this.q[this.head++];
135
- try {
136
- this.executionDepth++;
137
- task();
138
- this.executionDepth--;
139
- } catch (err) {
140
- if (this.executionDepth > 0) this.executionDepth = 0;
141
- fatal = err;
142
- break;
143
- }
144
- if (this.taskCount > 0) this.taskCount--;
145
- }
146
- } finally {
147
- this.running = false;
148
- this.depth = 0;
149
- this.executionDepth = 0;
150
- if (this.head >= this.q.length) {
151
- this.q.length = 0;
152
- this.head = 0;
153
- } else if (this.head > 0) {
154
- const remaining = this.q.length - this.head;
155
- for (let i = 0; i < remaining; i++) {
156
- this.q[i] = this.q[this.head + i];
157
- }
158
- this.q.length = remaining;
159
- this.head = 0;
160
- }
161
- this.flushVersion++;
162
- this.resolveWaiters();
163
- }
164
- if (fatal) throw fatal;
165
- }
166
- runWithSyncProgress(fn) {
167
- const prev = this.allowSyncProgress;
168
- this.allowSyncProgress = true;
169
- const g = globalThis;
170
- const origQueueMicrotask = g.queueMicrotask;
171
- const origSetTimeout = g.setTimeout;
172
- if (process.env.NODE_ENV !== "production") {
173
- g.queueMicrotask = () => {
174
- throw new Error(
175
- "[Scheduler] queueMicrotask not allowed during runWithSyncProgress"
176
- );
177
- };
178
- g.setTimeout = () => {
179
- throw new Error(
180
- "[Scheduler] setTimeout not allowed during runWithSyncProgress"
181
- );
182
- };
183
- }
184
- const startVersion = this.flushVersion;
185
- try {
186
- const res = fn();
187
- if (!this.running && this.q.length - this.head > 0) {
188
- this.flush();
189
- }
190
- if (process.env.NODE_ENV !== "production") {
191
- if (this.q.length - this.head > 0) {
192
- throw new Error(
193
- "[Scheduler] tasks remain after runWithSyncProgress flush"
194
- );
195
- }
196
- }
197
- return res;
198
- } finally {
199
- if (process.env.NODE_ENV !== "production") {
200
- g.queueMicrotask = origQueueMicrotask;
201
- g.setTimeout = origSetTimeout;
202
- }
203
- try {
204
- if (this.flushVersion === startVersion) {
205
- this.flushVersion++;
206
- this.resolveWaiters();
207
- }
208
- } catch (e) {
209
- void e;
210
- }
211
- this.allowSyncProgress = prev;
212
- }
213
- }
214
- waitForFlush(targetVersion, timeoutMs = 2e3) {
215
- const target = typeof targetVersion === "number" ? targetVersion : this.flushVersion + 1;
216
- if (this.flushVersion >= target) return Promise.resolve();
217
- return new Promise((resolve, reject) => {
218
- const timer = setTimeout(() => {
219
- const ns = globalThis.__ASKR__ || {};
220
- const diag = {
221
- flushVersion: this.flushVersion,
222
- queueLen: this.q.length - this.head,
223
- running: this.running,
224
- inHandler: this.inHandler,
225
- bulk: isBulkCommitActive(),
226
- namespace: ns
227
- };
228
- reject(
229
- new Error(
230
- `waitForFlush timeout ${timeoutMs}ms: ${JSON.stringify(diag)}`
231
- )
232
- );
233
- }, timeoutMs);
234
- this.waiters.push({ target, resolve, reject, timer });
235
- });
236
- }
237
- getState() {
238
- return {
239
- queueLength: this.q.length - this.head,
240
- running: this.running,
241
- depth: this.depth,
242
- executionDepth: this.executionDepth,
243
- taskCount: this.taskCount,
244
- flushVersion: this.flushVersion,
245
- // New fields for optional inspection
246
- inHandler: this.inHandler,
247
- allowSyncProgress: this.allowSyncProgress
248
- };
249
- }
250
- setInHandler(v) {
251
- this.inHandler = v;
252
- }
253
- isInHandler() {
254
- return this.inHandler;
255
- }
256
- isExecuting() {
257
- return this.running || this.executionDepth > 0;
258
- }
259
- // Clear pending synchronous tasks (used by fastlane enter/exit)
260
- clearPendingSyncTasks() {
261
- const remaining = this.q.length - this.head;
262
- if (remaining <= 0) return 0;
263
- if (this.running) {
264
- this.q.length = this.head;
265
- this.taskCount = Math.max(0, this.taskCount - remaining);
266
- queueMicrotask(() => {
267
- try {
268
- this.flushVersion++;
269
- this.resolveWaiters();
270
- } catch (e) {
271
- void e;
272
- }
273
- });
274
- return remaining;
275
- }
276
- this.q.length = 0;
277
- this.head = 0;
278
- this.taskCount = Math.max(0, this.taskCount - remaining);
279
- this.flushVersion++;
280
- this.resolveWaiters();
281
- return remaining;
282
- }
283
- resolveWaiters() {
284
- if (this.waiters.length === 0) return;
285
- const ready = [];
286
- const remaining = [];
287
- for (const w of this.waiters) {
288
- if (this.flushVersion >= w.target) {
289
- if (w.timer) clearTimeout(w.timer);
290
- ready.push(w.resolve);
291
- } else {
292
- remaining.push(w);
293
- }
294
- }
295
- this.waiters = remaining;
296
- for (const r of ready) r();
297
- }
298
- };
299
- var globalScheduler = new Scheduler();
300
- function isSchedulerExecuting() {
301
- return globalScheduler.isExecuting();
302
- }
303
-
304
- // src/runtime/context.ts
305
- var CONTEXT_FRAME_SYMBOL = /* @__PURE__ */ Symbol("__tempoContextFrame__");
306
- var currentContextFrame = null;
307
- var currentAsyncResourceFrame = null;
308
- function withContext(frame, fn) {
309
- const oldFrame = currentContextFrame;
310
- currentContextFrame = frame;
311
- try {
312
- return fn();
313
- } finally {
314
- currentContextFrame = oldFrame;
315
- }
316
- }
317
- function withAsyncResourceContext(frame, fn) {
318
- const oldFrame = currentAsyncResourceFrame;
319
- currentAsyncResourceFrame = frame;
320
- try {
321
- return fn();
322
- } finally {
323
- currentAsyncResourceFrame = oldFrame;
324
- }
325
- }
326
- function getCurrentContextFrame() {
327
- return currentContextFrame;
328
- }
329
-
330
- // src/renderer/diag/index.ts
331
- function getDiagMap() {
332
- try {
333
- const root = globalThis;
334
- if (!root.__ASKR_DIAG) root.__ASKR_DIAG = {};
335
- return root.__ASKR_DIAG;
336
- } catch (e) {
337
- void e;
338
- return {};
339
- }
340
- }
341
- function __ASKR_set(key, value) {
342
- try {
343
- const g = getDiagMap();
344
- g[key] = value;
345
- try {
346
- const root = globalThis;
347
- try {
348
- const ns = root.__ASKR__ || (root.__ASKR__ = {});
349
- try {
350
- ns[key] = value;
351
- } catch (e) {
352
- void e;
353
- }
354
- } catch (e) {
355
- void e;
356
- }
357
- } catch (e) {
358
- void e;
359
- }
360
- } catch (e) {
361
- void e;
362
- }
363
- }
364
- function __ASKR_incCounter(key) {
365
- try {
366
- const g = getDiagMap();
367
- const prev = typeof g[key] === "number" ? g[key] : 0;
368
- const next = prev + 1;
369
- g[key] = next;
370
- try {
371
- const root = globalThis;
372
- const ns = root.__ASKR__ || (root.__ASKR__ = {});
373
- try {
374
- const nsPrev = typeof ns[key] === "number" ? ns[key] : 0;
375
- ns[key] = nsPrev + 1;
376
- } catch (e) {
377
- void e;
378
- }
379
- } catch (e) {
380
- void e;
381
- }
382
- } catch (e) {
383
- void e;
384
- }
385
- }
386
-
387
- // src/renderer/utils.ts
388
- function parseEventName(propName) {
389
- if (!propName.startsWith("on") || propName.length <= 2) return null;
390
- return propName.slice(2).charAt(0).toLowerCase() + propName.slice(3).toLowerCase();
391
- }
392
- function getPassiveOptions(eventName) {
393
- if (eventName === "wheel" || eventName === "scroll" || eventName.startsWith("touch")) {
394
- return { passive: true };
395
- }
396
- return void 0;
397
- }
398
- function createWrappedHandler(handler, flushAfter = false) {
399
- return (event) => {
400
- globalScheduler.setInHandler(true);
401
- try {
402
- handler(event);
403
- } catch (error) {
404
- logger.error("[Askr] Event handler error:", error);
405
- } finally {
406
- globalScheduler.setInHandler(false);
407
- if (flushAfter) {
408
- const state = globalScheduler.getState();
409
- if ((state.queueLength ?? 0) > 0 && !state.running) {
410
- queueMicrotask(() => {
411
- try {
412
- if (!globalScheduler.isExecuting()) globalScheduler.flush();
413
- } catch (err) {
414
- queueMicrotask(() => {
415
- throw err;
416
- });
417
- }
418
- });
419
- }
420
- }
421
- }
422
- };
423
- }
424
- function isSkippedProp(key) {
425
- return key === "children" || key === "key";
426
- }
427
- function isIgnoredForPropChanges(key) {
428
- if (key === "children" || key === "key") return true;
429
- if (key.startsWith("on") && key.length > 2) return true;
430
- if (key.startsWith("data-")) return true;
431
- return false;
432
- }
433
- function hasPropChanged(el, key, value) {
434
- try {
435
- if (key === "class" || key === "className") {
436
- return el.className !== String(value);
437
- }
438
- if (key === "value" || key === "checked") {
439
- return el[key] !== value;
440
- }
441
- const attr = el.getAttribute(key);
442
- if (value === void 0 || value === null || value === false) {
443
- return attr !== null;
444
- }
445
- return String(value) !== attr;
446
- } catch {
447
- return true;
448
- }
449
- }
450
- function hasNonTrivialProps(props) {
451
- for (const k of Object.keys(props)) {
452
- if (isIgnoredForPropChanges(k)) continue;
453
- return true;
454
- }
455
- return false;
456
- }
457
- function checkPropChanges(el, props) {
458
- for (const k of Object.keys(props)) {
459
- if (isIgnoredForPropChanges(k)) continue;
460
- if (hasPropChanged(el, k, props[k])) {
461
- return true;
462
- }
463
- }
464
- return false;
465
- }
466
- function extractKey(vnode) {
467
- if (typeof vnode !== "object" || vnode === null) return void 0;
468
- const obj = vnode;
469
- const rawKey = obj.key ?? obj.props?.key;
470
- if (rawKey === void 0) return void 0;
471
- return typeof rawKey === "symbol" ? String(rawKey) : rawKey;
472
- }
473
- function buildKeyMapFromChildren(parent) {
474
- const map = /* @__PURE__ */ new Map();
475
- for (let ch = parent.firstElementChild; ch; ch = ch.nextElementSibling) {
476
- const k = ch.getAttribute("data-key");
477
- if (k !== null) {
478
- map.set(k, ch);
479
- const n = Number(k);
480
- if (!Number.isNaN(n)) map.set(n, ch);
481
- }
482
- }
483
- return map;
484
- }
485
- function recordDOMReplace(source) {
486
- try {
487
- __ASKR_incCounter("__DOM_REPLACE_COUNT");
488
- __ASKR_set(`__LAST_DOM_REPLACE_STACK_${source}`, new Error().stack);
489
- } catch {
490
- }
491
- }
492
- function recordFastPathStats(stats, counterName) {
493
- try {
494
- __ASKR_set("__LAST_FASTPATH_STATS", stats);
495
- __ASKR_set("__LAST_FASTPATH_COMMIT_COUNT", 1);
496
- if (counterName) {
497
- __ASKR_incCounter(counterName);
498
- }
499
- } catch {
500
- }
501
- }
502
- function logFastPathDebug(message, indexOrData, data) {
503
- if (process.env.ASKR_FASTPATH_DEBUG === "1" || process.env.ASKR_FASTPATH_DEBUG === "true") {
504
- if (data !== void 0) {
505
- logger.warn(`[Askr][FASTPATH] ${message}`, indexOrData, data);
506
- } else if (indexOrData !== void 0) {
507
- logger.warn(`[Askr][FASTPATH] ${message}`, indexOrData);
508
- } else {
509
- logger.warn(`[Askr][FASTPATH] ${message}`);
510
- }
511
- }
512
- }
513
- function now() {
514
- return typeof performance !== "undefined" && performance.now ? performance.now() : Date.now();
515
- }
516
-
517
- // src/renderer/keyed.ts
518
- var keyedElements = /* @__PURE__ */ new WeakMap();
519
- function getKeyMapForElement(el) {
520
- return keyedElements.get(el);
521
- }
522
- function populateKeyMapForElement(parent) {
523
- try {
524
- if (keyedElements.has(parent)) return;
525
- let domMap = buildKeyMapFromChildren(parent);
526
- if (domMap.size === 0) {
527
- domMap = /* @__PURE__ */ new Map();
528
- const children = Array.from(parent.children);
529
- for (const ch of children) {
530
- const text = (ch.textContent || "").trim();
531
- if (text) {
532
- domMap.set(text, ch);
533
- const n = Number(text);
534
- if (!Number.isNaN(n)) domMap.set(n, ch);
535
- }
536
- }
537
- }
538
- if (domMap.size > 0) keyedElements.set(parent, domMap);
539
- } catch {
540
- }
541
- }
542
- var _reconcilerRecordedParents = /* @__PURE__ */ new WeakSet();
543
- function extractKeyedVnodes(newChildren) {
544
- const result = [];
545
- for (const child of newChildren) {
546
- const key = extractKey(child);
547
- if (key !== void 0) {
548
- result.push({ key, vnode: child });
549
- }
550
- }
551
- return result;
552
- }
553
- function computeLISLength(positions) {
554
- const tails = [];
555
- for (const pos of positions) {
556
- if (pos === -1) continue;
557
- let lo = 0;
558
- let hi = tails.length;
559
- while (lo < hi) {
560
- const mid = lo + hi >> 1;
561
- if (tails[mid] < pos) lo = mid + 1;
562
- else hi = mid;
563
- }
564
- if (lo === tails.length) tails.push(pos);
565
- else tails[lo] = pos;
566
- }
567
- return tails.length;
568
- }
569
- function checkVnodesHaveProps(keyedVnodes) {
570
- for (const { vnode } of keyedVnodes) {
571
- if (typeof vnode !== "object" || vnode === null) continue;
572
- const vnodeObj = vnode;
573
- if (vnodeObj.props && hasNonTrivialProps(vnodeObj.props)) {
574
- return true;
575
- }
576
- }
577
- return false;
578
- }
579
- function checkVnodePropChanges(keyedVnodes, oldKeyMap) {
580
- for (const { key, vnode } of keyedVnodes) {
581
- const el = oldKeyMap?.get(key);
582
- if (!el || typeof vnode !== "object" || vnode === null) continue;
583
- const vnodeObj = vnode;
584
- const props = vnodeObj.props || {};
585
- for (const k of Object.keys(props)) {
586
- if (isIgnoredForPropChanges(k)) continue;
587
- if (hasPropChanged(el, k, props[k])) {
588
- return true;
589
- }
590
- }
591
- }
592
- return false;
593
- }
594
- function isKeyedReorderFastPathEligible(parent, newChildren, oldKeyMap) {
595
- const keyedVnodes = extractKeyedVnodes(newChildren);
596
- const totalKeyed = keyedVnodes.length;
597
- const newKeyOrder = keyedVnodes.map((kv) => kv.key);
598
- const oldKeyOrder = oldKeyMap ? Array.from(oldKeyMap.keys()) : [];
599
- let moveCount = 0;
600
- for (let i = 0; i < newKeyOrder.length; i++) {
601
- const k = newKeyOrder[i];
602
- if (i >= oldKeyOrder.length || oldKeyOrder[i] !== k || !oldKeyMap?.has(k)) {
603
- moveCount++;
604
- }
605
- }
606
- const FAST_MOVE_THRESHOLD_ABS = 64;
607
- const FAST_MOVE_THRESHOLD_REL = 0.1;
608
- const cheapMoveTrigger = totalKeyed >= 128 && oldKeyOrder.length > 0 && moveCount > Math.max(
609
- FAST_MOVE_THRESHOLD_ABS,
610
- Math.floor(totalKeyed * FAST_MOVE_THRESHOLD_REL)
611
- );
612
- let lisTrigger = false;
613
- let lisLen = 0;
614
- if (totalKeyed >= 128) {
615
- const parentChildren = Array.from(parent.children);
616
- const positions = keyedVnodes.map(({ key }) => {
617
- const el = oldKeyMap?.get(key);
618
- return el?.parentElement === parent ? parentChildren.indexOf(el) : -1;
619
- });
620
- lisLen = computeLISLength(positions);
621
- lisTrigger = lisLen < Math.floor(totalKeyed * 0.5);
622
- }
623
- const hasPropsPresent = checkVnodesHaveProps(keyedVnodes);
624
- const hasPropChanges = checkVnodePropChanges(keyedVnodes, oldKeyMap);
625
- const useFastPath = (cheapMoveTrigger || lisTrigger) && !hasPropChanges && !hasPropsPresent;
626
- return {
627
- useFastPath,
628
- totalKeyed,
629
- moveCount,
630
- lisLen,
631
- hasPropChanges
632
- };
633
- }
634
-
635
- // src/runtime/dev-namespace.ts
636
- function getDevNamespace() {
637
- if (process.env.NODE_ENV === "production") return {};
638
- try {
639
- const g = globalThis;
640
- if (!g.__ASKR__) g.__ASKR__ = {};
641
- return g.__ASKR__;
642
- } catch {
643
- return {};
644
- }
645
- }
646
- function setDevValue(key, value) {
647
- if (process.env.NODE_ENV === "production") return;
648
- try {
649
- getDevNamespace()[key] = value;
650
- } catch {
651
- }
652
- }
653
- function getDevValue(key) {
654
- if (process.env.NODE_ENV === "production") return void 0;
655
- try {
656
- return getDevNamespace()[key];
657
- } catch {
658
- return void 0;
659
- }
660
- }
661
-
662
- // src/runtime/fastlane.ts
663
- var _bulkCommitActive = false;
664
- var _appliedParents = null;
665
- function enterBulkCommit() {
666
- _bulkCommitActive = true;
667
- _appliedParents = /* @__PURE__ */ new WeakSet();
668
- try {
669
- const cleared = globalScheduler.clearPendingSyncTasks?.() ?? 0;
670
- setDevValue("__ASKR_FASTLANE_CLEARED_TASKS", cleared);
671
- } catch (err) {
672
- if (process.env.NODE_ENV !== "production") throw err;
673
- }
674
- }
675
- function exitBulkCommit() {
676
- _bulkCommitActive = false;
677
- _appliedParents = null;
678
- }
679
- function isBulkCommitActive2() {
680
- return _bulkCommitActive;
681
- }
682
- function markFastPathApplied(parent) {
683
- if (!_appliedParents) return;
684
- try {
685
- _appliedParents.add(parent);
686
- } catch (e) {
687
- void e;
688
- }
689
- }
690
- function isFastPathApplied(parent) {
691
- return !!(_appliedParents && _appliedParents.has(parent));
692
- }
693
- function finalizeReadSubscriptions(instance) {
694
- const newSet = instance._pendingReadStates ?? /* @__PURE__ */ new Set();
695
- const oldSet = instance._lastReadStates ?? /* @__PURE__ */ new Set();
696
- const token = instance._currentRenderToken;
697
- if (token === void 0) return;
698
- for (const s of oldSet) {
699
- if (!newSet.has(s)) {
700
- const readers = s._readers;
701
- if (readers) readers.delete(instance);
702
- }
703
- }
704
- instance.lastRenderToken = token;
705
- for (const s of newSet) {
706
- let readers = s._readers;
707
- if (!readers) {
708
- readers = /* @__PURE__ */ new Map();
709
- s._readers = readers;
710
- }
711
- readers.set(instance, instance.lastRenderToken ?? 0);
712
- }
713
- instance._lastReadStates = newSet;
714
- instance._pendingReadStates = /* @__PURE__ */ new Set();
715
- instance._currentRenderToken = void 0;
716
- }
717
- function unwrapFragmentForFastPath(vnode) {
718
- if (!vnode || typeof vnode !== "object" || !("type" in vnode)) return vnode;
719
- const v = vnode;
720
- if (typeof v.type === "symbol" && (v.type === Fragment || String(v.type) === "Symbol(askr.fragment)")) {
721
- const children = v.children || v.props?.children;
722
- if (Array.isArray(children) && children.length > 0) {
723
- for (const child of children) {
724
- if (child && typeof child === "object" && "type" in child) {
725
- const c = child;
726
- if (typeof c.type === "string") {
727
- return child;
728
- }
729
- }
730
- }
731
- }
732
- }
733
- return vnode;
734
- }
735
- function classifyUpdate(instance, result) {
736
- const unwrappedResult = unwrapFragmentForFastPath(result);
737
- if (!unwrappedResult || typeof unwrappedResult !== "object" || !("type" in unwrappedResult))
738
- return { useFastPath: false, reason: "not-vnode" };
739
- const vnode = unwrappedResult;
740
- if (vnode == null || typeof vnode.type !== "string")
741
- return { useFastPath: false, reason: "not-intrinsic" };
742
- const parent = instance.target;
743
- if (!parent) return { useFastPath: false, reason: "no-root" };
744
- const firstChild = parent.children[0];
745
- if (!firstChild) return { useFastPath: false, reason: "no-first-child" };
746
- if (firstChild.tagName.toLowerCase() !== String(vnode.type).toLowerCase())
747
- return { useFastPath: false, reason: "root-tag-mismatch" };
748
- const children = vnode.children || vnode.props?.children;
749
- if (!Array.isArray(children))
750
- return { useFastPath: false, reason: "no-children-array" };
751
- for (const c of children) {
752
- if (typeof c === "object" && c !== null && "type" in c && typeof c.type === "function") {
753
- return { useFastPath: false, reason: "component-child-present" };
754
- }
755
- }
756
- if (instance.mountOperations.length > 0)
757
- return { useFastPath: false, reason: "pending-mounts" };
758
- try {
759
- populateKeyMapForElement(firstChild);
760
- } catch {
761
- }
762
- const oldKeyMap = getKeyMapForElement(firstChild);
763
- const decision = isKeyedReorderFastPathEligible(
764
- firstChild,
765
- children,
766
- oldKeyMap
767
- );
768
- if (!decision.useFastPath || decision.totalKeyed < 128)
769
- return { ...decision, useFastPath: false, reason: "renderer-declined" };
770
- return { ...decision, useFastPath: true };
771
- }
772
- function commitReorderOnly(instance, result) {
773
- const evaluate2 = globalThis.__ASKR_RENDERER?.evaluate;
774
- if (typeof evaluate2 !== "function") {
775
- logger.warn(
776
- "[Tempo][FASTPATH][DEV] renderer.evaluate not available; declining fast-lane"
777
- );
778
- return false;
779
- }
780
- const schedBefore = process.env.NODE_ENV !== "production" ? globalScheduler.getState() : null;
781
- enterBulkCommit();
782
- try {
783
- globalScheduler.runWithSyncProgress(() => {
784
- evaluate2(result, instance.target);
785
- try {
786
- finalizeReadSubscriptions(instance);
787
- } catch (e) {
788
- if (process.env.NODE_ENV !== "production") throw e;
789
- }
790
- });
791
- const clearedAfter = globalScheduler.clearPendingSyncTasks?.() ?? 0;
792
- setDevValue("__FASTLANE_CLEARED_AFTER", clearedAfter);
793
- if (process.env.NODE_ENV !== "production") {
794
- validateFastLaneInvariants(instance, schedBefore);
795
- }
796
- return true;
797
- } finally {
798
- exitBulkCommit();
799
- }
800
- if (process.env.NODE_ENV !== "production") {
801
- if (isBulkCommitActive2()) {
802
- throw new Error(
803
- "Fast-lane invariant violated: bulk commit flag still set after commit"
804
- );
805
- }
806
- }
807
- }
808
- function validateFastLaneInvariants(instance, schedBefore) {
809
- const commitCount = getDevValue("__LAST_FASTPATH_COMMIT_COUNT") ?? 0;
810
- const invariants = {
811
- commitCount,
812
- mountOps: instance.mountOperations.length,
813
- cleanupFns: instance.cleanupFns.length
814
- };
815
- setDevValue("__LAST_FASTLANE_INVARIANTS", invariants);
816
- if (commitCount !== 1) {
817
- console.error(
818
- "[FASTLANE][INV] commitCount",
819
- commitCount,
820
- "diag",
821
- globalThis.__ASKR_DIAG
822
- );
823
- throw new Error(
824
- "Fast-lane invariant violated: expected exactly one DOM commit during reorder-only commit"
825
- );
826
- }
827
- if (invariants.mountOps > 0) {
828
- throw new Error(
829
- "Fast-lane invariant violated: mount operations were registered during bulk commit"
830
- );
831
- }
832
- if (invariants.cleanupFns > 0) {
833
- throw new Error(
834
- "Fast-lane invariant violated: cleanup functions were added during bulk commit"
835
- );
836
- }
837
- const schedAfter = globalScheduler.getState();
838
- if (schedBefore && schedAfter && schedAfter.taskCount > schedBefore.taskCount) {
839
- console.error(
840
- "[FASTLANE] schedBefore, schedAfter",
841
- schedBefore,
842
- schedAfter
843
- );
844
- console.error("[FASTLANE] enqueue logs", getDevValue("__ENQUEUE_LOGS"));
845
- throw new Error(
846
- "Fast-lane invariant violated: scheduler enqueued leftover work during bulk commit"
847
- );
848
- }
849
- let finalState = globalScheduler.getState();
850
- const executing = globalScheduler.isExecuting();
851
- let outstandingAfter = Math.max(
852
- 0,
853
- finalState.taskCount - (executing ? 1 : 0)
854
- );
855
- if (outstandingAfter !== 0) {
856
- let attempts = 0;
857
- while (attempts < 5) {
858
- const cleared = globalScheduler.clearPendingSyncTasks?.() ?? 0;
859
- if (cleared === 0) break;
860
- attempts++;
861
- }
862
- finalState = globalScheduler.getState();
863
- outstandingAfter = Math.max(
864
- 0,
865
- finalState.taskCount - (globalScheduler.isExecuting() ? 1 : 0)
866
- );
867
- if (outstandingAfter !== 0) {
868
- console.error(
869
- "[FASTLANE] Post-commit enqueue logs:",
870
- getDevValue("__ENQUEUE_LOGS")
871
- );
872
- console.error(
873
- "[FASTLANE] Cleared counts:",
874
- getDevValue("__FASTLANE_CLEARED_TASKS"),
875
- getDevValue("__FASTLANE_CLEARED_AFTER")
876
- );
877
- throw new Error(
878
- `Fast-lane invariant violated: scheduler has ${finalState.taskCount} pending task(s) after commit`
879
- );
880
- }
881
- }
882
- }
883
- function tryRuntimeFastLaneSync(instance, result) {
884
- const cls = classifyUpdate(instance, result);
885
- if (!cls.useFastPath) {
886
- setDevValue("__LAST_FASTPATH_STATS", void 0);
887
- setDevValue("__LAST_FASTPATH_COMMIT_COUNT", 0);
888
- return false;
889
- }
890
- try {
891
- return commitReorderOnly(instance, result);
892
- } catch (err) {
893
- if (process.env.NODE_ENV !== "production") throw err;
894
- return false;
895
- }
896
- }
897
- if (typeof globalThis !== "undefined") {
898
- globalThis.__ASKR_FASTLANE = {
899
- isBulkCommitActive: isBulkCommitActive2,
900
- enterBulkCommit,
901
- exitBulkCommit,
902
- tryRuntimeFastLaneSync,
903
- markFastPathApplied,
904
- isFastPathApplied
905
- };
906
- }
907
-
908
- // src/common/vnode.ts
909
- function _isDOMElement(node) {
910
- return typeof node === "object" && node !== null && "type" in node;
911
- }
912
-
913
- // src/renderer/cleanup.ts
914
- function cleanupSingleInstance(node, errors, strict) {
915
- const inst = node.__ASKR_INSTANCE;
916
- if (!inst) return;
917
- try {
918
- cleanupComponent(inst);
919
- } catch (err) {
920
- if (strict) errors.push(err);
921
- else logger.warn("[Askr] cleanupComponent failed:", err);
922
- }
923
- try {
924
- delete node.__ASKR_INSTANCE;
925
- } catch (e) {
926
- if (strict) errors.push(e);
927
- }
928
- }
929
- function forEachDescendantElement(root, visit) {
930
- try {
931
- const doc = root.ownerDocument;
932
- const createTreeWalker = doc?.createTreeWalker;
933
- if (typeof createTreeWalker === "function") {
934
- const walker = createTreeWalker.call(doc, root, 1);
935
- let n = walker.firstChild();
936
- while (n) {
937
- visit(n);
938
- n = walker.nextNode();
939
- }
940
- return;
941
- }
942
- } catch {
943
- }
944
- const descendants = root.querySelectorAll("*");
945
- for (let i = 0; i < descendants.length; i++) {
946
- visit(descendants[i]);
947
- }
948
- }
949
- function cleanupInstanceIfPresent(node, opts) {
950
- if (!node || !(node instanceof Element)) return;
951
- const strict = opts?.strict ?? false;
952
- const errors = strict ? [] : null;
953
- try {
954
- cleanupSingleInstance(node, errors, strict);
955
- } catch (err) {
956
- if (strict) errors.push(err);
957
- else logger.warn("[Askr] cleanupInstanceIfPresent failed:", err);
958
- }
959
- try {
960
- forEachDescendantElement(node, (d) => {
961
- try {
962
- cleanupSingleInstance(d, errors, strict);
963
- } catch (err) {
964
- if (strict) errors.push(err);
965
- else
966
- logger.warn(
967
- "[Askr] cleanupInstanceIfPresent descendant cleanup failed:",
968
- err
969
- );
970
- }
971
- });
972
- } catch (err) {
973
- if (strict) errors.push(err);
974
- else
975
- logger.warn(
976
- "[Askr] cleanupInstanceIfPresent descendant query failed:",
977
- err
978
- );
979
- }
980
- if (errors && errors.length > 0) {
981
- throw new AggregateError(errors, "cleanupInstanceIfPresent failed");
982
- }
983
- }
984
- function cleanupInstancesUnder(node, opts) {
985
- cleanupInstanceIfPresent(node, opts);
986
- }
987
- var elementListeners = /* @__PURE__ */ new WeakMap();
988
- function removeElementListeners(element) {
989
- const map = elementListeners.get(element);
990
- if (map) {
991
- for (const [eventName, entry] of map) {
992
- if (entry.options !== void 0)
993
- element.removeEventListener(eventName, entry.handler, entry.options);
994
- else element.removeEventListener(eventName, entry.handler);
995
- }
996
- elementListeners.delete(element);
997
- }
998
- }
999
- function removeAllListeners(root) {
1000
- if (!root) return;
1001
- removeElementListeners(root);
1002
- forEachDescendantElement(root, removeElementListeners);
1003
- }
1004
-
1005
- // src/renderer/dom.ts
1006
- var IS_DOM_AVAILABLE = typeof document !== "undefined";
1007
- function addTrackedListener(el, eventName, handler) {
1008
- const wrappedHandler = createWrappedHandler(handler, true);
1009
- const options = getPassiveOptions(eventName);
1010
- if (options !== void 0) {
1011
- el.addEventListener(eventName, wrappedHandler, options);
1012
- } else {
1013
- el.addEventListener(eventName, wrappedHandler);
1014
- }
1015
- if (!elementListeners.has(el)) {
1016
- elementListeners.set(el, /* @__PURE__ */ new Map());
1017
- }
1018
- elementListeners.get(el).set(eventName, {
1019
- handler: wrappedHandler,
1020
- original: handler,
1021
- options
1022
- });
1023
- }
1024
- function applyPropsToElement(el, props, tagName) {
1025
- for (const key in props) {
1026
- const value = props[key];
1027
- if (isSkippedProp(key)) continue;
1028
- if (value === void 0 || value === null || value === false) continue;
1029
- const eventName = parseEventName(key);
1030
- if (eventName) {
1031
- addTrackedListener(el, eventName, value);
1032
- continue;
1033
- }
1034
- if (key === "class" || key === "className") {
1035
- el.className = String(value);
1036
- } else if (key === "value" || key === "checked") {
1037
- applyFormControlProp(el, key, value, tagName);
1038
- } else {
1039
- el.setAttribute(key, String(value));
1040
- }
1041
- }
1042
- }
1043
- function applyFormControlProp(el, key, value, tagName) {
1044
- if (key === "value") {
1045
- if (tagNamesEqualIgnoreCase(tagName, "input") || tagNamesEqualIgnoreCase(tagName, "textarea") || tagNamesEqualIgnoreCase(tagName, "select")) {
1046
- el.value = String(value);
1047
- el.setAttribute("value", String(value));
1048
- } else {
1049
- el.setAttribute("value", String(value));
1050
- }
1051
- } else if (key === "checked") {
1052
- if (tagNamesEqualIgnoreCase(tagName, "input")) {
1053
- el.checked = Boolean(value);
1054
- el.setAttribute("checked", String(Boolean(value)));
1055
- } else {
1056
- el.setAttribute("checked", String(Boolean(value)));
1057
- }
1058
- }
1059
- }
1060
- function materializeKey(el, vnode, props) {
1061
- const vnodeKey = vnode.key ?? props?.key;
1062
- if (vnodeKey !== void 0) {
1063
- el.setAttribute("data-key", String(vnodeKey));
1064
- }
1065
- }
1066
- function warnMissingKeys(children) {
1067
- if (process.env.NODE_ENV === "production") return;
1068
- let hasElements = false;
1069
- let hasKeys = false;
1070
- for (const item of children) {
1071
- if (typeof item === "object" && item !== null && "type" in item) {
1072
- hasElements = true;
1073
- const rawKey = item.key ?? item.props?.key;
1074
- if (rawKey !== void 0) {
1075
- hasKeys = true;
1076
- break;
1077
- }
1078
- }
1079
- }
1080
- if (hasElements && !hasKeys) {
1081
- try {
1082
- const inst = getCurrentInstance();
1083
- const name = inst?.fn?.name || "<anonymous>";
1084
- logger.warn(
1085
- `Missing keys on dynamic lists in ${name}. Each child in a list should have a unique "key" prop.`
1086
- );
1087
- } catch {
1088
- logger.warn(
1089
- 'Missing keys on dynamic lists. Each child in a list should have a unique "key" prop.'
1090
- );
1091
- }
1092
- }
1093
- }
1094
- function createDOMNode(node) {
1095
- if (!IS_DOM_AVAILABLE) {
1096
- if (process.env.NODE_ENV !== "production") {
1097
- try {
1098
- logger.warn("[Askr] createDOMNode called in non-DOM environment");
1099
- } catch {
1100
- }
1101
- }
1102
- return null;
1103
- }
1104
- if (typeof node === "string") {
1105
- return document.createTextNode(node);
1106
- }
1107
- if (typeof node === "number") {
1108
- return document.createTextNode(String(node));
1109
- }
1110
- if (!node) {
1111
- return null;
1112
- }
1113
- if (Array.isArray(node)) {
1114
- const fragment = document.createDocumentFragment();
1115
- for (const child of node) {
1116
- const dom = createDOMNode(child);
1117
- if (dom) fragment.appendChild(dom);
1118
- }
1119
- return fragment;
1120
- }
1121
- if (typeof node === "object" && node !== null && "type" in node) {
1122
- const type = node.type;
1123
- const props = node.props || {};
1124
- if (typeof type === "string") {
1125
- return createIntrinsicElement(node, type, props);
1126
- }
1127
- if (typeof type === "function") {
1128
- return createComponentElement(node, type, props);
1129
- }
1130
- if (typeof type === "symbol" && (type === Fragment2 || String(type) === "Symbol(Fragment)")) {
1131
- return createFragmentElement(node, props);
1132
- }
1133
- }
1134
- return null;
1135
- }
1136
- function createIntrinsicElement(node, type, props) {
1137
- const el = document.createElement(type);
1138
- materializeKey(el, node, props);
1139
- applyPropsToElement(el, props, type);
1140
- const children = props.children || node.children;
1141
- if (children) {
1142
- if (Array.isArray(children)) {
1143
- warnMissingKeys(children);
1144
- for (const child of children) {
1145
- const dom = createDOMNode(child);
1146
- if (dom) el.appendChild(dom);
1147
- }
1148
- } else {
1149
- const dom = createDOMNode(children);
1150
- if (dom) el.appendChild(dom);
1151
- }
1152
- }
1153
- return el;
1154
- }
1155
- function createComponentElement(node, type, props) {
1156
- const frame = node[CONTEXT_FRAME_SYMBOL];
1157
- const snapshot = frame || getCurrentContextFrame();
1158
- const componentFn = type;
1159
- const isAsync = componentFn.constructor.name === "AsyncFunction";
1160
- if (isAsync) {
1161
- throw new Error(
1162
- "Async components are not supported. Use resource() for async work."
1163
- );
1164
- }
1165
- let childInstance = node.__instance;
1166
- if (!childInstance) {
1167
- childInstance = createComponentInstance(
1168
- `comp-${Math.random().toString(36).slice(2, 7)}`,
1169
- componentFn,
1170
- props || {},
1171
- null
1172
- );
1173
- node.__instance = childInstance;
1174
- }
1175
- if (snapshot) {
1176
- childInstance.ownerFrame = snapshot;
1177
- }
1178
- const result = withContext(
1179
- snapshot,
1180
- () => renderComponentInline(childInstance)
1181
- );
1182
- if (result instanceof Promise) {
1183
- throw new Error(
1184
- "Async components are not supported. Components must return synchronously."
1185
- );
1186
- }
1187
- const dom = withContext(snapshot, () => createDOMNode(result));
1188
- if (dom instanceof Element) {
1189
- mountInstanceInline(childInstance, dom);
1190
- return dom;
1191
- }
1192
- if (!dom) {
1193
- const placeholder = document.createComment("");
1194
- childInstance._placeholder = placeholder;
1195
- childInstance.mounted = true;
1196
- childInstance.notifyUpdate = childInstance._enqueueRun;
1197
- return placeholder;
1198
- }
1199
- const host = document.createElement("div");
1200
- host.appendChild(dom);
1201
- mountInstanceInline(childInstance, host);
1202
- return host;
1203
- }
1204
- function createFragmentElement(node, props) {
1205
- const fragment = document.createDocumentFragment();
1206
- const children = props.children || node.children;
1207
- if (children) {
1208
- if (Array.isArray(children)) {
1209
- for (const child of children) {
1210
- const dom = createDOMNode(child);
1211
- if (dom) fragment.appendChild(dom);
1212
- }
1213
- } else {
1214
- const dom = createDOMNode(children);
1215
- if (dom) fragment.appendChild(dom);
1216
- }
1217
- }
1218
- return fragment;
1219
- }
1220
- function updateElementFromVnode(el, vnode, updateChildren = true) {
1221
- if (!_isDOMElement(vnode)) {
1222
- return;
1223
- }
1224
- const props = vnode.props || {};
1225
- materializeKey(el, vnode, props);
1226
- const existingListeners = elementListeners.get(el);
1227
- let desiredEventNames = null;
1228
- for (const key in props) {
1229
- const value = props[key];
1230
- if (isSkippedProp(key)) continue;
1231
- const eventName = parseEventName(key);
1232
- if (value === void 0 || value === null || value === false) {
1233
- if (key === "class" || key === "className") {
1234
- el.className = "";
1235
- } else if (eventName && existingListeners?.has(eventName)) {
1236
- const entry = existingListeners.get(eventName);
1237
- if (entry.options !== void 0) {
1238
- el.removeEventListener(eventName, entry.handler, entry.options);
1239
- } else {
1240
- el.removeEventListener(eventName, entry.handler);
1241
- }
1242
- existingListeners.delete(eventName);
1243
- } else {
1244
- el.removeAttribute(key);
1245
- }
1246
- continue;
1247
- }
1248
- if (key === "class" || key === "className") {
1249
- el.className = String(value);
1250
- } else if (key === "value" || key === "checked") {
1251
- el[key] = value;
1252
- } else if (eventName) {
1253
- if (existingListeners && existingListeners.size > 0) {
1254
- (desiredEventNames ??= /* @__PURE__ */ new Set()).add(eventName);
1255
- }
1256
- const existing = existingListeners?.get(eventName);
1257
- if (existing && existing.original === value) {
1258
- continue;
1259
- }
1260
- if (existing) {
1261
- if (existing.options !== void 0) {
1262
- el.removeEventListener(eventName, existing.handler, existing.options);
1263
- } else {
1264
- el.removeEventListener(eventName, existing.handler);
1265
- }
1266
- }
1267
- const wrappedHandler = createWrappedHandler(
1268
- value,
1269
- false
1270
- );
1271
- const options = getPassiveOptions(eventName);
1272
- if (options !== void 0) {
1273
- el.addEventListener(eventName, wrappedHandler, options);
1274
- } else {
1275
- el.addEventListener(eventName, wrappedHandler);
1276
- }
1277
- if (!elementListeners.has(el)) {
1278
- elementListeners.set(el, /* @__PURE__ */ new Map());
1279
- }
1280
- elementListeners.get(el).set(eventName, {
1281
- handler: wrappedHandler,
1282
- original: value,
1283
- options
1284
- });
1285
- } else {
1286
- el.setAttribute(key, String(value));
1287
- }
1288
- }
1289
- if (existingListeners && existingListeners.size > 0) {
1290
- if (desiredEventNames === null) {
1291
- for (const [eventName, entry] of existingListeners) {
1292
- if (entry.options !== void 0) {
1293
- el.removeEventListener(eventName, entry.handler, entry.options);
1294
- } else {
1295
- el.removeEventListener(eventName, entry.handler);
1296
- }
1297
- }
1298
- elementListeners.delete(el);
1299
- } else {
1300
- for (const [eventName, entry] of existingListeners) {
1301
- if (!desiredEventNames.has(eventName)) {
1302
- if (entry.options !== void 0) {
1303
- el.removeEventListener(eventName, entry.handler, entry.options);
1304
- } else {
1305
- el.removeEventListener(eventName, entry.handler);
1306
- }
1307
- existingListeners.delete(eventName);
1308
- }
1309
- }
1310
- if (existingListeners.size === 0) elementListeners.delete(el);
1311
- }
1312
- }
1313
- if (updateChildren) {
1314
- const children = vnode.children || props.children;
1315
- updateElementChildren(el, children);
1316
- }
1317
- }
1318
- function updateElementChildren(el, children) {
1319
- if (!children) {
1320
- el.textContent = "";
1321
- return;
1322
- }
1323
- if (!Array.isArray(children) && (typeof children === "string" || typeof children === "number")) {
1324
- if (el.childNodes.length === 1 && el.firstChild?.nodeType === 3) {
1325
- el.firstChild.data = String(children);
1326
- } else {
1327
- el.textContent = String(children);
1328
- }
1329
- return;
1330
- }
1331
- if (Array.isArray(children)) {
1332
- updateUnkeyedChildren(el, children);
1333
- return;
1334
- }
1335
- el.textContent = "";
1336
- const dom = createDOMNode(children);
1337
- if (dom) el.appendChild(dom);
1338
- }
1339
- function updateUnkeyedChildren(parent, newChildren) {
1340
- const existing = Array.from(parent.children);
1341
- if (newChildren.length === 1 && existing.length === 0 && parent.childNodes.length === 1) {
1342
- const firstNewChild = newChildren[0];
1343
- const firstExisting = parent.firstChild;
1344
- if ((typeof firstNewChild === "string" || typeof firstNewChild === "number") && firstExisting?.nodeType === 3) {
1345
- firstExisting.data = String(firstNewChild);
1346
- return;
1347
- }
1348
- }
1349
- if (existing.length === 0 && parent.childNodes.length > 0) {
1350
- parent.textContent = "";
1351
- }
1352
- const max = Math.max(existing.length, newChildren.length);
1353
- for (let i = 0; i < max; i++) {
1354
- const current = existing[i];
1355
- const next = newChildren[i];
1356
- if (next === void 0 && current) {
1357
- cleanupInstanceIfPresent(current);
1358
- current.remove();
1359
- continue;
1360
- }
1361
- if (!current && next !== void 0) {
1362
- const dom = createDOMNode(next);
1363
- if (dom) parent.appendChild(dom);
1364
- continue;
1365
- }
1366
- if (!current || next === void 0) continue;
1367
- if (typeof next === "string" || typeof next === "number") {
1368
- current.textContent = String(next);
1369
- } else if (_isDOMElement(next)) {
1370
- if (typeof next.type === "string") {
1371
- if (tagsEqualIgnoreCase(current.tagName, next.type)) {
1372
- updateElementFromVnode(current, next);
1373
- } else {
1374
- const dom = createDOMNode(next);
1375
- if (dom) {
1376
- if (current instanceof Element) removeAllListeners(current);
1377
- cleanupInstanceIfPresent(current);
1378
- parent.replaceChild(dom, current);
1379
- }
1380
- }
1381
- } else {
1382
- const dom = createDOMNode(next);
1383
- if (dom) {
1384
- if (current instanceof Element) removeAllListeners(current);
1385
- cleanupInstanceIfPresent(current);
1386
- parent.replaceChild(dom, current);
1387
- }
1388
- }
1389
- } else {
1390
- const dom = createDOMNode(next);
1391
- if (dom) {
1392
- if (current instanceof Element) removeAllListeners(current);
1393
- cleanupInstanceIfPresent(current);
1394
- parent.replaceChild(dom, current);
1395
- }
1396
- }
1397
- }
1398
- }
1399
- function performBulkPositionalKeyedTextUpdate(parent, keyedVnodes) {
1400
- const total = keyedVnodes.length;
1401
- let reused = 0;
1402
- let updatedKeys = 0;
1403
- const t0 = now();
1404
- const debugFastPath = process.env.ASKR_FASTPATH_DEBUG === "1" || process.env.ASKR_FASTPATH_DEBUG === "true";
1405
- for (let i = 0; i < total; i++) {
1406
- const { key, vnode } = keyedVnodes[i];
1407
- const ch = parent.children[i];
1408
- if (ch && _isDOMElement(vnode) && typeof vnode.type === "string") {
1409
- const vnodeType = vnode.type;
1410
- if (tagsEqualIgnoreCase(ch.tagName, vnodeType)) {
1411
- const children = vnode.children || vnode.props?.children;
1412
- if (debugFastPath) {
1413
- logFastPathDebug("positional idx", i, {
1414
- chTag: ch.tagName,
1415
- vnodeType,
1416
- chChildNodes: ch.childNodes.length,
1417
- childrenType: Array.isArray(children) ? "array" : typeof children
1418
- });
1419
- }
1420
- updateTextContent(ch, children, vnode);
1421
- setDataKey(ch, key, () => updatedKeys++);
1422
- reused++;
1423
- continue;
1424
- } else {
1425
- if (debugFastPath) {
1426
- logFastPathDebug("positional tag mismatch", i, {
1427
- chTag: ch.tagName,
1428
- vnodeType
1429
- });
1430
- }
1431
- }
1432
- } else {
1433
- if (debugFastPath) {
1434
- logFastPathDebug("positional missing or invalid", i, { ch: !!ch });
1435
- }
1436
- }
1437
- replaceNodeAtPosition(parent, i, vnode);
1438
- }
1439
- const t = now() - t0;
1440
- updateKeyedElementsMap(parent, keyedVnodes);
1441
- const stats = { n: total, reused, updatedKeys, t };
1442
- recordFastPathStats(stats, "bulkKeyedPositionalHits");
1443
- return stats;
1444
- }
1445
- function updateTextContent(el, children, vnode) {
1446
- if (typeof children === "string" || typeof children === "number") {
1447
- setTextNodeData(el, String(children));
1448
- } else if (Array.isArray(children) && children.length === 1 && (typeof children[0] === "string" || typeof children[0] === "number")) {
1449
- setTextNodeData(el, String(children[0]));
1450
- } else {
1451
- if (!tryUpdateTwoChildTextPattern(el, vnode)) {
1452
- updateElementFromVnode(el, vnode);
1453
- }
1454
- }
1455
- }
1456
- function tryUpdateTwoChildTextPattern(parentEl, vnode) {
1457
- const vnodeChildren = vnode.children || vnode.props?.children;
1458
- if (!Array.isArray(vnodeChildren) || vnodeChildren.length !== 2) return false;
1459
- const c0 = vnodeChildren[0];
1460
- const c1 = vnodeChildren[1];
1461
- if (!_isDOMElement(c0) || !_isDOMElement(c1)) return false;
1462
- if (typeof c0.type !== "string" || typeof c1.type !== "string") return false;
1463
- const el0 = parentEl.children[0];
1464
- const el1 = parentEl.children[1];
1465
- if (!el0 || !el1) return false;
1466
- if (!tagsEqualIgnoreCase(el0.tagName, c0.type)) return false;
1467
- if (!tagsEqualIgnoreCase(el1.tagName, c1.type)) return false;
1468
- const t0 = c0.children || c0.props?.children;
1469
- const t1 = c1.children || c1.props?.children;
1470
- if (typeof t0 === "string" || typeof t0 === "number") {
1471
- setTextNodeData(el0, String(t0));
1472
- } else if (Array.isArray(t0) && t0.length === 1 && (typeof t0[0] === "string" || typeof t0[0] === "number")) {
1473
- setTextNodeData(el0, String(t0[0]));
1474
- } else {
1475
- return false;
1476
- }
1477
- if (typeof t1 === "string" || typeof t1 === "number") {
1478
- setTextNodeData(el1, String(t1));
1479
- } else if (Array.isArray(t1) && t1.length === 1 && (typeof t1[0] === "string" || typeof t1[0] === "number")) {
1480
- setTextNodeData(el1, String(t1[0]));
1481
- } else {
1482
- return false;
1483
- }
1484
- return true;
1485
- }
1486
- function setTextNodeData(el, text) {
1487
- if (el.childNodes.length === 1 && el.firstChild?.nodeType === 3) {
1488
- el.firstChild.data = text;
1489
- } else {
1490
- el.textContent = text;
1491
- }
1492
- }
1493
- function setDataKey(el, key, onSet) {
1494
- try {
1495
- const next = String(key);
1496
- if (el.getAttribute("data-key") === next) return;
1497
- el.setAttribute("data-key", next);
1498
- onSet();
1499
- } catch {
1500
- }
1501
- }
1502
- function upperCommonTagName(tag) {
1503
- switch (tag) {
1504
- case "div":
1505
- return "DIV";
1506
- case "span":
1507
- return "SPAN";
1508
- case "p":
1509
- return "P";
1510
- case "a":
1511
- return "A";
1512
- case "button":
1513
- return "BUTTON";
1514
- case "input":
1515
- return "INPUT";
1516
- case "ul":
1517
- return "UL";
1518
- case "ol":
1519
- return "OL";
1520
- case "li":
1521
- return "LI";
1522
- default:
1523
- return null;
1524
- }
1525
- }
1526
- function tagNamesEqualIgnoreCase(a, b) {
1527
- if (a === b) return true;
1528
- const len = a.length;
1529
- if (len !== b.length) return false;
1530
- for (let i = 0; i < len; i++) {
1531
- const ac = a.charCodeAt(i);
1532
- const bc = b.charCodeAt(i);
1533
- if (ac === bc) continue;
1534
- const an = ac >= 65 && ac <= 90 ? ac + 32 : ac;
1535
- const bn = bc >= 65 && bc <= 90 ? bc + 32 : bc;
1536
- if (an !== bn) return false;
1537
- }
1538
- return true;
1539
- }
1540
- function tagsEqualIgnoreCase(elementTagName, vnodeType) {
1541
- const upperCommon = upperCommonTagName(vnodeType);
1542
- if (upperCommon !== null && elementTagName === upperCommon) return true;
1543
- return tagNamesEqualIgnoreCase(elementTagName, vnodeType);
1544
- }
1545
- function replaceNodeAtPosition(parent, index, vnode) {
1546
- const dom = createDOMNode(vnode);
1547
- if (dom) {
1548
- const existing = parent.children[index];
1549
- if (existing) {
1550
- cleanupInstanceIfPresent(existing);
1551
- parent.replaceChild(dom, existing);
1552
- } else {
1553
- parent.appendChild(dom);
1554
- }
1555
- }
1556
- }
1557
- function updateKeyedElementsMap(parent, keyedVnodes) {
1558
- try {
1559
- const existing = keyedElements.get(parent);
1560
- const newKeyMap = existing ? (existing.clear(), existing) : /* @__PURE__ */ new Map();
1561
- for (let i = 0; i < keyedVnodes.length; i++) {
1562
- const k = keyedVnodes[i].key;
1563
- const ch = parent.children[i];
1564
- if (ch) newKeyMap.set(k, ch);
1565
- }
1566
- keyedElements.set(parent, newKeyMap);
1567
- } catch {
1568
- }
1569
- }
1570
- function performBulkTextReplace(parent, newChildren) {
1571
- const t0 = now();
1572
- const existing = Array.from(parent.childNodes);
1573
- const finalNodes = [];
1574
- let reused = 0;
1575
- let created = 0;
1576
- for (let i = 0; i < newChildren.length; i++) {
1577
- const result = processChildNode(newChildren[i], existing[i], finalNodes);
1578
- if (result === "reused") reused++;
1579
- else if (result === "created") created++;
1580
- }
1581
- const tBuild = now() - t0;
1582
- const tCommit = commitBulkReplace(parent, finalNodes);
1583
- keyedElements.delete(parent);
1584
- const stats = {
1585
- n: newChildren.length,
1586
- reused,
1587
- created,
1588
- tBuild,
1589
- tCommit
1590
- };
1591
- recordBulkTextStats(stats);
1592
- return stats;
1593
- }
1594
- function processChildNode(vnode, existingNode, finalNodes) {
1595
- if (typeof vnode === "string" || typeof vnode === "number") {
1596
- return processTextVnode(String(vnode), existingNode, finalNodes);
1597
- }
1598
- if (typeof vnode === "object" && vnode !== null && "type" in vnode) {
1599
- return processElementVnode(vnode, existingNode, finalNodes);
1600
- }
1601
- return "skipped";
1602
- }
1603
- function processTextVnode(text, existingNode, finalNodes) {
1604
- if (existingNode && existingNode.nodeType === 3) {
1605
- existingNode.data = text;
1606
- finalNodes.push(existingNode);
1607
- return "reused";
1608
- }
1609
- finalNodes.push(document.createTextNode(text));
1610
- return "created";
1611
- }
1612
- function processElementVnode(vnode, existingNode, finalNodes) {
1613
- const vnodeObj = vnode;
1614
- if (typeof vnodeObj.type === "string") {
1615
- const tag = vnodeObj.type;
1616
- if (existingNode && existingNode.nodeType === 1 && tagsEqualIgnoreCase(existingNode.tagName, tag)) {
1617
- updateElementFromVnode(existingNode, vnode);
1618
- finalNodes.push(existingNode);
1619
- return "reused";
1620
- }
1621
- }
1622
- const dom = createDOMNode(vnode);
1623
- if (dom) {
1624
- finalNodes.push(dom);
1625
- return "created";
1626
- }
1627
- return "skipped";
1628
- }
1629
- function commitBulkReplace(parent, nodes) {
1630
- const fragStart = Date.now();
1631
- const fragment = document.createDocumentFragment();
1632
- for (let i = 0; i < nodes.length; i++) {
1633
- fragment.appendChild(nodes[i]);
1634
- }
1635
- try {
1636
- for (let n = parent.firstChild; n; ) {
1637
- const next = n.nextSibling;
1638
- if (n instanceof Element) removeAllListeners(n);
1639
- cleanupInstanceIfPresent(n);
1640
- n = next;
1641
- }
1642
- } catch {
1643
- }
1644
- recordDOMReplace("bulk-text-replace");
1645
- parent.replaceChildren(fragment);
1646
- return Date.now() - fragStart;
1647
- }
1648
- function recordBulkTextStats(stats) {
1649
- try {
1650
- __ASKR_set("__LAST_BULK_TEXT_FASTPATH_STATS", stats);
1651
- __ASKR_set("__LAST_FASTPATH_STATS", stats);
1652
- __ASKR_set("__LAST_FASTPATH_COMMIT_COUNT", 1);
1653
- __ASKR_incCounter("bulkTextFastpathHits");
1654
- } catch {
1655
- }
1656
- }
1657
- function isBulkTextFastPathEligible(parent, newChildren) {
1658
- const threshold = Number(process.env.ASKR_BULK_TEXT_THRESHOLD) || 1024;
1659
- const requiredFraction = 0.8;
1660
- const total = Array.isArray(newChildren) ? newChildren.length : 0;
1661
- if (total < threshold) {
1662
- recordBulkDiag({
1663
- phase: "bulk-unkeyed-eligible",
1664
- reason: "too-small",
1665
- total,
1666
- threshold
1667
- });
1668
- return false;
1669
- }
1670
- const result = countSimpleChildren(newChildren);
1671
- if (result.componentFound !== void 0) {
1672
- recordBulkDiag({
1673
- phase: "bulk-unkeyed-eligible",
1674
- reason: "component-child",
1675
- index: result.componentFound
1676
- });
1677
- return false;
1678
- }
1679
- const fraction = result.simple / total;
1680
- const eligible = fraction >= requiredFraction && parent.childNodes.length >= total;
1681
- recordBulkDiag({
1682
- phase: "bulk-unkeyed-eligible",
1683
- total,
1684
- simple: result.simple,
1685
- fraction,
1686
- requiredFraction,
1687
- eligible
1688
- });
1689
- return eligible;
1690
- }
1691
- function countSimpleChildren(children) {
1692
- let simple = 0;
1693
- for (let i = 0; i < children.length; i++) {
1694
- const c = children[i];
1695
- if (typeof c === "string" || typeof c === "number") {
1696
- simple++;
1697
- continue;
1698
- }
1699
- if (typeof c === "object" && c !== null && "type" in c) {
1700
- const dv = c;
1701
- if (typeof dv.type === "function") {
1702
- return { simple, componentFound: i };
1703
- }
1704
- if (typeof dv.type === "string" && isSimpleElement(dv)) {
1705
- simple++;
1706
- }
1707
- }
1708
- }
1709
- return { simple };
1710
- }
1711
- function isSimpleElement(dv) {
1712
- const children = dv.children || dv.props?.children;
1713
- if (!children) return true;
1714
- if (typeof children === "string" || typeof children === "number") {
1715
- return true;
1716
- }
1717
- if (Array.isArray(children) && children.length === 1 && (typeof children[0] === "string" || typeof children[0] === "number")) {
1718
- return true;
1719
- }
1720
- return false;
1721
- }
1722
- function recordBulkDiag(data) {
1723
- if (process.env.NODE_ENV !== "production" || process.env.ASKR_FASTPATH_DEBUG === "1") {
1724
- try {
1725
- __ASKR_set("__BULK_DIAG", data);
1726
- } catch {
1727
- }
1728
- }
1729
- }
1730
-
1731
- // src/renderer/fastpath.ts
1732
- function applyRendererFastPath(parent, keyedVnodes, oldKeyMap, unkeyedVnodes) {
1733
- if (typeof document === "undefined") return null;
1734
- const totalKeyed = keyedVnodes.length;
1735
- if (totalKeyed === 0 && (!unkeyedVnodes || unkeyedVnodes.length === 0))
1736
- return null;
1737
- if (!isSchedulerExecuting()) {
1738
- logger.warn(
1739
- "[Askr][FASTPATH][DEV] Fast-path reconciliation invoked outside scheduler execution"
1740
- );
1741
- }
1742
- let parentChildrenArr;
1743
- let localOldKeyMap;
1744
- if (totalKeyed <= 20) {
1745
- try {
1746
- const pc = parent.children;
1747
- parentChildrenArr = new Array(pc.length);
1748
- for (let i = 0; i < pc.length; i++)
1749
- parentChildrenArr[i] = pc[i];
1750
- } catch (e) {
1751
- parentChildrenArr = void 0;
1752
- void e;
1753
- }
1754
- } else {
1755
- localOldKeyMap = /* @__PURE__ */ new Map();
1756
- try {
1757
- for (let ch = parent.firstElementChild; ch; ch = ch.nextElementSibling) {
1758
- const k = ch.getAttribute("data-key");
1759
- if (k !== null) {
1760
- localOldKeyMap.set(k, ch);
1761
- const n = Number(k);
1762
- if (!Number.isNaN(n)) localOldKeyMap.set(n, ch);
1763
- }
1764
- }
1765
- } catch (e) {
1766
- localOldKeyMap = void 0;
1767
- void e;
1768
- }
1769
- }
1770
- const finalNodes = [];
1771
- let mapLookups = 0;
1772
- let createdNodes = 0;
1773
- let reusedCount = 0;
1774
- for (let i = 0; i < keyedVnodes.length; i++) {
1775
- const { key, vnode } = keyedVnodes[i];
1776
- mapLookups++;
1777
- let el;
1778
- if (totalKeyed <= 20 && parentChildrenArr) {
1779
- const ks = String(key);
1780
- for (let j = 0; j < parentChildrenArr.length; j++) {
1781
- const ch = parentChildrenArr[j];
1782
- const k = ch.getAttribute("data-key");
1783
- if (k !== null && (k === ks || Number(k) === key)) {
1784
- el = ch;
1785
- break;
1786
- }
1787
- }
1788
- if (!el) el = oldKeyMap?.get(key);
1789
- } else {
1790
- el = localOldKeyMap?.get(key) ?? oldKeyMap?.get(key);
1791
- }
1792
- if (el) {
1793
- finalNodes.push(el);
1794
- reusedCount++;
1795
- } else {
1796
- const newEl = createDOMNode(vnode);
1797
- if (newEl) {
1798
- finalNodes.push(newEl);
1799
- createdNodes++;
1800
- }
1801
- }
1802
- }
1803
- if (unkeyedVnodes && unkeyedVnodes.length) {
1804
- for (const vnode of unkeyedVnodes) {
1805
- const newEl = createDOMNode(vnode);
1806
- if (newEl) {
1807
- finalNodes.push(newEl);
1808
- createdNodes++;
1809
- }
1810
- }
1811
- }
1812
- try {
1813
- const tFragmentStart = Date.now();
1814
- const fragment = document.createDocumentFragment();
1815
- let fragmentAppendCount = 0;
1816
- for (let i = 0; i < finalNodes.length; i++) {
1817
- fragment.appendChild(finalNodes[i]);
1818
- fragmentAppendCount++;
1819
- }
1820
- try {
1821
- for (let n = parent.firstChild; n; ) {
1822
- const next = n.nextSibling;
1823
- if (n instanceof Element) removeAllListeners(n);
1824
- cleanupInstanceIfPresent(n);
1825
- n = next;
1826
- }
1827
- } catch (e) {
1828
- void e;
1829
- }
1830
- try {
1831
- __ASKR_incCounter("__DOM_REPLACE_COUNT");
1832
- __ASKR_set("__LAST_DOM_REPLACE_STACK_FASTPATH", new Error().stack);
1833
- } catch (e) {
1834
- void e;
1835
- }
1836
- parent.replaceChildren(fragment);
1837
- try {
1838
- __ASKR_set("__LAST_FASTPATH_COMMIT_COUNT", 1);
1839
- } catch (e) {
1840
- void e;
1841
- }
1842
- try {
1843
- if (isBulkCommitActive2()) markFastPathApplied(parent);
1844
- } catch (e) {
1845
- void e;
1846
- }
1847
- const newKeyMap = /* @__PURE__ */ new Map();
1848
- for (let i = 0; i < keyedVnodes.length; i++) {
1849
- const key = keyedVnodes[i].key;
1850
- const node = finalNodes[i];
1851
- if (node instanceof Element) newKeyMap.set(key, node);
1852
- }
1853
- try {
1854
- const stats = {
1855
- n: totalKeyed,
1856
- moves: 0,
1857
- lisLen: 0,
1858
- t_lookup: 0,
1859
- t_fragment: Date.now() - tFragmentStart,
1860
- t_commit: 0,
1861
- t_bookkeeping: 0,
1862
- fragmentAppendCount,
1863
- mapLookups,
1864
- createdNodes,
1865
- reusedCount
1866
- };
1867
- if (typeof globalThis !== "undefined") {
1868
- __ASKR_set("__LAST_FASTPATH_STATS", stats);
1869
- __ASKR_set("__LAST_FASTPATH_REUSED", reusedCount > 0);
1870
- __ASKR_incCounter("fastpathHistoryPush");
1871
- }
1872
- if (process.env.ASKR_FASTPATH_DEBUG === "1" || process.env.ASKR_FASTPATH_DEBUG === "true") {
1873
- logger.warn(
1874
- "[Askr][FASTPATH]",
1875
- JSON.stringify({ n: totalKeyed, createdNodes, reusedCount })
1876
- );
1877
- }
1878
- } catch (e) {
1879
- void e;
1880
- }
1881
- try {
1882
- _reconcilerRecordedParents.add(parent);
1883
- } catch (e) {
1884
- void e;
1885
- }
1886
- return newKeyMap;
1887
- } catch (e) {
1888
- void e;
1889
- return null;
1890
- }
1891
- }
1892
-
1893
- // src/renderer/reconcile.ts
1894
- function tagNamesEqualIgnoreCase2(a, b) {
1895
- if (a === b) return true;
1896
- if (a.length !== b.length) return false;
1897
- for (let i = 0; i < a.length; i++) {
1898
- const ca = a.charCodeAt(i);
1899
- const cb = b.charCodeAt(i);
1900
- if (ca === cb) continue;
1901
- const fa = ca >= 65 && ca <= 90 ? ca + 32 : ca;
1902
- const fb = cb >= 65 && cb <= 90 ? cb + 32 : cb;
1903
- if (fa !== fb) return false;
1904
- }
1905
- return true;
1906
- }
1907
- function reconcileKeyedChildren(parent, newChildren, oldKeyMap) {
1908
- const { keyedVnodes, unkeyedVnodes } = partitionChildren(newChildren);
1909
- const fastPathResult = tryFastPaths(
1910
- parent,
1911
- newChildren,
1912
- keyedVnodes,
1913
- unkeyedVnodes,
1914
- oldKeyMap
1915
- );
1916
- if (fastPathResult) return fastPathResult;
1917
- return performFullReconciliation(parent, newChildren, keyedVnodes, oldKeyMap);
1918
- }
1919
- function partitionChildren(newChildren) {
1920
- const keyedVnodes = [];
1921
- const unkeyedVnodes = [];
1922
- for (let i = 0; i < newChildren.length; i++) {
1923
- const child = newChildren[i];
1924
- const key = extractKey(child);
1925
- if (key !== void 0) {
1926
- keyedVnodes.push({ key, vnode: child });
1927
- } else {
1928
- unkeyedVnodes.push(child);
1929
- }
1930
- }
1931
- return { keyedVnodes, unkeyedVnodes };
1932
- }
1933
- function tryFastPaths(parent, newChildren, keyedVnodes, unkeyedVnodes, oldKeyMap) {
1934
- try {
1935
- const rendererResult = tryRendererFastPath(
1936
- parent,
1937
- newChildren,
1938
- keyedVnodes,
1939
- unkeyedVnodes,
1940
- oldKeyMap
1941
- );
1942
- if (rendererResult) return rendererResult;
1943
- const positionalResult = tryPositionalBulkUpdate(parent, keyedVnodes);
1944
- if (positionalResult) return positionalResult;
1945
- } catch {
1946
- }
1947
- return null;
1948
- }
1949
- function tryRendererFastPath(parent, newChildren, keyedVnodes, unkeyedVnodes, oldKeyMap) {
1950
- const decision = isKeyedReorderFastPathEligible(
1951
- parent,
1952
- newChildren,
1953
- oldKeyMap
1954
- );
1955
- if (decision.useFastPath && keyedVnodes.length >= 128 || isBulkCommitActive2()) {
1956
- try {
1957
- const map = applyRendererFastPath(
1958
- parent,
1959
- keyedVnodes,
1960
- oldKeyMap,
1961
- unkeyedVnodes
1962
- );
1963
- if (map) {
1964
- keyedElements.set(parent, map);
1965
- return map;
1966
- }
1967
- } catch {
1968
- }
1969
- }
1970
- return null;
1971
- }
1972
- function tryPositionalBulkUpdate(parent, keyedVnodes) {
1973
- const total = keyedVnodes.length;
1974
- if (total < 10) return null;
1975
- const matchCount = countPositionalMatches(parent, keyedVnodes);
1976
- if (matchCount / total < 0.9) return null;
1977
- if (hasPositionalPropChanges(parent, keyedVnodes)) return null;
1978
- try {
1979
- const stats = performBulkPositionalKeyedTextUpdate(parent, keyedVnodes);
1980
- recordFastPathStats(stats, "bulkKeyedPositionalHits");
1981
- rebuildKeyedMap(parent);
1982
- return keyedElements.get(parent);
1983
- } catch {
1984
- return null;
1985
- }
1986
- }
1987
- function countPositionalMatches(parent, keyedVnodes) {
1988
- let matchCount = 0;
1989
- try {
1990
- for (let i = 0; i < keyedVnodes.length; i++) {
1991
- const vnode = keyedVnodes[i].vnode;
1992
- if (!vnode || typeof vnode !== "object" || typeof vnode.type !== "string")
1993
- continue;
1994
- const el = parent.children[i];
1995
- if (!el) continue;
1996
- if (tagNamesEqualIgnoreCase2(el.tagName, vnode.type)) {
1997
- matchCount++;
1998
- }
1999
- }
2000
- } catch {
2001
- }
2002
- return matchCount;
2003
- }
2004
- function hasPositionalPropChanges(parent, keyedVnodes) {
2005
- try {
2006
- for (let i = 0; i < keyedVnodes.length; i++) {
2007
- const vnode = keyedVnodes[i].vnode;
2008
- const el = parent.children[i];
2009
- if (!el || !vnode || typeof vnode !== "object") continue;
2010
- if (checkPropChanges(el, vnode.props || {})) {
2011
- return true;
2012
- }
2013
- }
2014
- } catch {
2015
- return true;
2016
- }
2017
- return false;
2018
- }
2019
- function rebuildKeyedMap(parent) {
2020
- try {
2021
- const map = /* @__PURE__ */ new Map();
2022
- for (let el = parent.firstElementChild; el; el = el.nextElementSibling) {
2023
- const k = el.getAttribute("data-key");
2024
- if (k !== null) {
2025
- map.set(k, el);
2026
- const n = Number(k);
2027
- if (!Number.isNaN(n)) map.set(n, el);
2028
- }
2029
- }
2030
- keyedElements.set(parent, map);
2031
- } catch {
2032
- }
2033
- }
2034
- function performFullReconciliation(parent, newChildren, keyedVnodes, oldKeyMap) {
2035
- const newKeyMap = /* @__PURE__ */ new Map();
2036
- const finalNodes = [];
2037
- const usedOldEls = /* @__PURE__ */ new WeakSet();
2038
- const resolveOldElOnce = createOldElResolver(parent, oldKeyMap, usedOldEls);
2039
- for (let i = 0; i < newChildren.length; i++) {
2040
- const child = newChildren[i];
2041
- const node = reconcileSingleChild(
2042
- child,
2043
- i,
2044
- parent,
2045
- resolveOldElOnce,
2046
- usedOldEls,
2047
- newKeyMap
2048
- );
2049
- if (node) finalNodes.push(node);
2050
- }
2051
- if (typeof document === "undefined") return newKeyMap;
2052
- commitReconciliation(parent, finalNodes);
2053
- keyedElements.delete(parent);
2054
- return newKeyMap;
2055
- }
2056
- function createOldElResolver(parent, oldKeyMap, usedOldEls) {
2057
- return (k) => {
2058
- if (!oldKeyMap) return void 0;
2059
- const direct = oldKeyMap.get(k);
2060
- if (direct && !usedOldEls.has(direct)) {
2061
- usedOldEls.add(direct);
2062
- return direct;
2063
- }
2064
- const s = String(k);
2065
- const byString = oldKeyMap.get(s);
2066
- if (byString && !usedOldEls.has(byString)) {
2067
- usedOldEls.add(byString);
2068
- return byString;
2069
- }
2070
- const n = Number(s);
2071
- if (!Number.isNaN(n)) {
2072
- const byNum = oldKeyMap.get(n);
2073
- if (byNum && !usedOldEls.has(byNum)) {
2074
- usedOldEls.add(byNum);
2075
- return byNum;
2076
- }
2077
- }
2078
- return scanForElementByKey(parent, k, s, usedOldEls);
2079
- };
2080
- }
2081
- function scanForElementByKey(parent, k, keyStr, usedOldEls) {
2082
- try {
2083
- for (let ch = parent.firstElementChild; ch; ch = ch.nextElementSibling) {
2084
- if (usedOldEls.has(ch)) continue;
2085
- const attr = ch.getAttribute("data-key");
2086
- if (attr === keyStr) {
2087
- usedOldEls.add(ch);
2088
- return ch;
2089
- }
2090
- if (attr !== null) {
2091
- const numAttr = Number(attr);
2092
- if (!Number.isNaN(numAttr) && numAttr === k) {
2093
- usedOldEls.add(ch);
2094
- return ch;
2095
- }
2096
- }
2097
- }
2098
- } catch {
2099
- }
2100
- return void 0;
2101
- }
2102
- function reconcileSingleChild(child, index, parent, resolveOldElOnce, usedOldEls, newKeyMap) {
2103
- const key = extractKey(child);
2104
- if (key !== void 0) {
2105
- return reconcileKeyedChild(child, key, parent, resolveOldElOnce, newKeyMap);
2106
- }
2107
- return reconcileUnkeyedChild(child, index, parent, usedOldEls);
2108
- }
2109
- function reconcileKeyedChild(child, key, parent, resolveOldElOnce, newKeyMap) {
2110
- const el = resolveOldElOnce(key);
2111
- if (el && el.parentElement === parent) {
2112
- try {
2113
- const childObj = child;
2114
- if (childObj && typeof childObj === "object" && typeof childObj.type === "string") {
2115
- if (tagNamesEqualIgnoreCase2(el.tagName, childObj.type)) {
2116
- updateElementFromVnode(el, child);
2117
- newKeyMap.set(key, el);
2118
- return el;
2119
- }
2120
- }
2121
- } catch {
2122
- }
2123
- }
2124
- const dom = createDOMNode(child);
2125
- if (dom) {
2126
- if (dom instanceof Element) newKeyMap.set(key, dom);
2127
- return dom;
2128
- }
2129
- return null;
2130
- }
2131
- function reconcileUnkeyedChild(child, index, parent, usedOldEls) {
2132
- try {
2133
- const existing = parent.children[index];
2134
- if (existing && (typeof child === "string" || typeof child === "number") && existing.nodeType === 1) {
2135
- existing.textContent = String(child);
2136
- usedOldEls.add(existing);
2137
- return existing;
2138
- }
2139
- if (canReuseElement(existing, child)) {
2140
- updateElementFromVnode(existing, child);
2141
- usedOldEls.add(existing);
2142
- return existing;
2143
- }
2144
- const avail = findAvailableUnkeyedElement(parent, usedOldEls);
2145
- if (avail) {
2146
- const reuseResult = tryReuseElement(avail, child, usedOldEls);
2147
- if (reuseResult) return reuseResult;
2148
- }
2149
- } catch {
2150
- }
2151
- const dom = createDOMNode(child);
2152
- return dom;
2153
- }
2154
- function canReuseElement(existing, child) {
2155
- if (!existing) return false;
2156
- if (typeof child !== "object" || child === null || !("type" in child))
2157
- return false;
2158
- const childObj = child;
2159
- const existingKey = existing.getAttribute("data-key");
2160
- const hasNoKey = existingKey === null || existingKey === void 0;
2161
- return hasNoKey && typeof childObj.type === "string" && tagNamesEqualIgnoreCase2(existing.tagName, childObj.type);
2162
- }
2163
- function findAvailableUnkeyedElement(parent, usedOldEls) {
2164
- for (let ch = parent.firstElementChild; ch; ch = ch.nextElementSibling) {
2165
- if (usedOldEls.has(ch)) continue;
2166
- if (ch.getAttribute("data-key") === null) return ch;
2167
- }
2168
- return void 0;
2169
- }
2170
- function tryReuseElement(avail, child, usedOldEls) {
2171
- if (typeof child === "string" || typeof child === "number") {
2172
- avail.textContent = String(child);
2173
- usedOldEls.add(avail);
2174
- return avail;
2175
- }
2176
- if (typeof child === "object" && child !== null && "type" in child) {
2177
- const childObj = child;
2178
- if (typeof childObj.type === "string" && tagNamesEqualIgnoreCase2(avail.tagName, childObj.type)) {
2179
- updateElementFromVnode(avail, child);
2180
- usedOldEls.add(avail);
2181
- return avail;
2182
- }
2183
- }
2184
- return null;
2185
- }
2186
- function commitReconciliation(parent, finalNodes) {
2187
- const fragment = document.createDocumentFragment();
2188
- for (let i = 0; i < finalNodes.length; i++) {
2189
- fragment.appendChild(finalNodes[i]);
2190
- }
2191
- try {
2192
- for (let n = parent.firstChild; n; ) {
2193
- const next = n.nextSibling;
2194
- if (n instanceof Element) removeAllListeners(n);
2195
- cleanupInstanceIfPresent(n);
2196
- n = next;
2197
- }
2198
- } catch {
2199
- }
2200
- recordDOMReplace("reconcile");
2201
- parent.replaceChildren(fragment);
2202
- }
2203
-
2204
- // src/renderer/evaluate.ts
2205
- var domRanges = /* @__PURE__ */ new WeakMap();
2206
- function tagNamesEqualIgnoreCase3(a, b) {
2207
- if (a === b) return true;
2208
- if (a.length !== b.length) return false;
2209
- for (let i = 0; i < a.length; i++) {
2210
- const ca = a.charCodeAt(i);
2211
- const cb = b.charCodeAt(i);
2212
- if (ca === cb) continue;
2213
- const fa = ca >= 65 && ca <= 90 ? ca + 32 : ca;
2214
- const fb = cb >= 65 && cb <= 90 ? cb + 32 : cb;
2215
- if (fa !== fb) return false;
2216
- }
2217
- return true;
2218
- }
2219
- function checkSimpleText(vnodeChildren) {
2220
- if (!Array.isArray(vnodeChildren)) {
2221
- if (typeof vnodeChildren === "string" || typeof vnodeChildren === "number") {
2222
- return { isSimple: true, text: String(vnodeChildren) };
2223
- }
2224
- } else if (vnodeChildren.length === 1) {
2225
- const child = vnodeChildren[0];
2226
- if (typeof child === "string" || typeof child === "number") {
2227
- return { isSimple: true, text: String(child) };
2228
- }
2229
- }
2230
- return { isSimple: false };
2231
- }
2232
- function tryUpdateTextInPlace(element, text) {
2233
- if (element.childNodes.length === 1 && element.firstChild?.nodeType === 3) {
2234
- element.firstChild.data = text;
2235
- return true;
2236
- }
2237
- return false;
2238
- }
2239
- function buildKeyMapFromDOM(parent) {
2240
- const keyMap = /* @__PURE__ */ new Map();
2241
- for (let child = parent.firstElementChild; child; child = child.nextElementSibling) {
2242
- const k = child.getAttribute("data-key");
2243
- if (k !== null) {
2244
- keyMap.set(k, child);
2245
- const n = Number(k);
2246
- if (!Number.isNaN(n)) keyMap.set(n, child);
2247
- }
2248
- }
2249
- return keyMap;
2250
- }
2251
- function getOrBuildKeyMap(parent) {
2252
- let keyMap = keyedElements.get(parent);
2253
- if (!keyMap) {
2254
- keyMap = buildKeyMapFromDOM(parent);
2255
- if (keyMap.size > 0) {
2256
- keyedElements.set(parent, keyMap);
2257
- }
2258
- }
2259
- return keyMap.size > 0 ? keyMap : void 0;
2260
- }
2261
- function hasKeyedChildren(children) {
2262
- for (let i = 0; i < children.length; i++) {
2263
- if (extractKey(children[i]) !== void 0) return true;
2264
- }
2265
- return false;
2266
- }
2267
- function trackBulkTextStats(stats) {
2268
- if (process.env.NODE_ENV !== "production") {
2269
- try {
2270
- __ASKR_set("__LAST_BULK_TEXT_FASTPATH_STATS", stats);
2271
- __ASKR_incCounter("bulkTextHits");
2272
- } catch {
2273
- }
2274
- }
2275
- }
2276
- function trackBulkTextMiss() {
2277
- if (process.env.NODE_ENV !== "production") {
2278
- try {
2279
- __ASKR_incCounter("bulkTextMisses");
2280
- } catch {
2281
- }
2282
- }
2283
- }
2284
- function reconcileKeyed(parent, children, oldKeyMap) {
2285
- if (process.env.ASKR_FORCE_BULK_POSREUSE === "1") {
2286
- const result = tryForcedBulkKeyedPath(parent, children);
2287
- if (result) return;
2288
- }
2289
- const newKeyMap = reconcileKeyedChildren(parent, children, oldKeyMap);
2290
- keyedElements.set(parent, newKeyMap);
2291
- }
2292
- function tryForcedBulkKeyedPath(parent, children) {
2293
- try {
2294
- const keyedVnodes = [];
2295
- for (const child of children) {
2296
- if (_isDOMElement(child) && child.key !== void 0) {
2297
- keyedVnodes.push({
2298
- key: child.key,
2299
- vnode: child
2300
- });
2301
- }
2302
- }
2303
- if (keyedVnodes.length === 0 || keyedVnodes.length !== children.length) {
2304
- return false;
2305
- }
2306
- if (process.env.ASKR_FASTPATH_DEBUG === "1" || process.env.ASKR_FASTPATH_DEBUG === "true") {
2307
- logger.warn(
2308
- "[Askr][FASTPATH] forced positional bulk keyed reuse (evaluate-level)"
2309
- );
2310
- }
2311
- const stats = performBulkPositionalKeyedTextUpdate(parent, keyedVnodes);
2312
- if (process.env.NODE_ENV !== "production" || process.env.ASKR_FASTPATH_DEBUG === "1") {
2313
- try {
2314
- __ASKR_set("__LAST_FASTPATH_STATS", stats);
2315
- __ASKR_set("__LAST_FASTPATH_COMMIT_COUNT", 1);
2316
- __ASKR_incCounter("bulkKeyedPositionalForced");
2317
- } catch {
2318
- }
2319
- }
2320
- const newMap = buildKeyMapFromDOM(parent);
2321
- keyedElements.set(parent, newMap);
2322
- return true;
2323
- } catch (err) {
2324
- if (process.env.ASKR_FASTPATH_DEBUG === "1" || process.env.ASKR_FASTPATH_DEBUG === "true") {
2325
- logger.warn(
2326
- "[Askr][FASTPATH] forced bulk path failed, falling back",
2327
- err
2328
- );
2329
- }
2330
- return false;
2331
- }
2332
- }
2333
- function reconcileUnkeyed(parent, children) {
2334
- if (isBulkTextFastPathEligible(parent, children)) {
2335
- const stats = performBulkTextReplace(parent, children);
2336
- trackBulkTextStats(stats);
2337
- } else {
2338
- trackBulkTextMiss();
2339
- updateUnkeyedChildren(parent, children);
2340
- }
2341
- keyedElements.delete(parent);
2342
- }
2343
- function updateElementChildren2(element, vnodeChildren) {
2344
- if (!vnodeChildren) {
2345
- element.textContent = "";
2346
- keyedElements.delete(element);
2347
- return;
2348
- }
2349
- if (!Array.isArray(vnodeChildren)) {
2350
- element.textContent = "";
2351
- const dom = createDOMNode(vnodeChildren);
2352
- if (dom) element.appendChild(dom);
2353
- keyedElements.delete(element);
2354
- return;
2355
- }
2356
- if (hasKeyedChildren(vnodeChildren)) {
2357
- const oldKeyMap = getOrBuildKeyMap(element);
2358
- try {
2359
- reconcileKeyed(element, vnodeChildren, oldKeyMap);
2360
- } catch {
2361
- const newKeyMap = reconcileKeyedChildren(
2362
- element,
2363
- vnodeChildren,
2364
- oldKeyMap
2365
- );
2366
- keyedElements.set(element, newKeyMap);
2367
- }
2368
- } else {
2369
- reconcileUnkeyed(element, vnodeChildren);
2370
- }
2371
- }
2372
- function smartUpdateElement(element, vnode) {
2373
- const vnodeChildren = vnode.children || vnode.props?.children;
2374
- const textCheck = checkSimpleText(vnodeChildren);
2375
- if (textCheck.isSimple && tryUpdateTextInPlace(element, textCheck.text)) {
2376
- } else {
2377
- updateElementChildren2(element, vnodeChildren);
2378
- }
2379
- updateElementFromVnode(element, vnode, false);
2380
- }
2381
- function processFragmentChildren(target, childArray) {
2382
- let existingNode = target.firstElementChild;
2383
- for (let i = 0; i < childArray.length; i++) {
2384
- const childVnode = childArray[i];
2385
- const nextExisting = existingNode ? existingNode.nextElementSibling : null;
2386
- if (existingNode && _isDOMElement(childVnode) && typeof childVnode.type === "string" && tagNamesEqualIgnoreCase3(
2387
- existingNode.tagName,
2388
- childVnode.type
2389
- )) {
2390
- smartUpdateElement(existingNode, childVnode);
2391
- existingNode = nextExisting;
2392
- continue;
2393
- }
2394
- const newDom = createDOMNode(childVnode);
2395
- if (newDom) {
2396
- if (existingNode) {
2397
- target.replaceChild(newDom, existingNode);
2398
- } else {
2399
- target.appendChild(newDom);
2400
- }
2401
- }
2402
- existingNode = nextExisting;
2403
- }
2404
- while (existingNode) {
2405
- const next = existingNode.nextElementSibling;
2406
- target.removeChild(existingNode);
2407
- existingNode = next;
2408
- }
2409
- }
2410
- function applyPropsToElement2(el, props) {
2411
- for (const [key, value] of Object.entries(props)) {
2412
- if (key === "children" || key === "key") continue;
2413
- if (value === void 0 || value === null || value === false) continue;
2414
- const eventName = parseEventName(key);
2415
- if (eventName) {
2416
- const wrappedHandler = createWrappedHandler(
2417
- value,
2418
- false
2419
- );
2420
- const options = getPassiveOptions(eventName);
2421
- if (options !== void 0)
2422
- el.addEventListener(eventName, wrappedHandler, options);
2423
- else el.addEventListener(eventName, wrappedHandler);
2424
- if (!elementListeners.has(el)) elementListeners.set(el, /* @__PURE__ */ new Map());
2425
- elementListeners.get(el).set(eventName, {
2426
- handler: wrappedHandler,
2427
- original: value,
2428
- options
2429
- });
2430
- continue;
2431
- }
2432
- if (key === "class" || key === "className") {
2433
- el.className = String(value);
2434
- } else if (key === "value" || key === "checked") {
2435
- el[key] = value;
2436
- } else {
2437
- el.setAttribute(key, String(value));
2438
- }
2439
- }
2440
- }
2441
- function tryFirstRenderKeyedChildren(target, vnode) {
2442
- const children = vnode.children;
2443
- if (!Array.isArray(children) || !hasKeyedChildren(children)) {
2444
- return false;
2445
- }
2446
- const el = document.createElement(vnode.type);
2447
- target.appendChild(el);
2448
- applyPropsToElement2(el, vnode.props || {});
2449
- const newKeyMap = reconcileKeyedChildren(el, children, void 0);
2450
- keyedElements.set(el, newKeyMap);
2451
- return true;
2452
- }
2453
- function isFragment(vnode) {
2454
- return _isDOMElement(vnode) && typeof vnode.type === "symbol" && (vnode.type === Fragment || String(vnode.type) === "Symbol(askr.fragment)");
2455
- }
2456
- function getFragmentChildren(vnode) {
2457
- const fragmentChildren = vnode.props?.children || vnode.children || [];
2458
- return Array.isArray(fragmentChildren) ? fragmentChildren : [fragmentChildren];
2459
- }
2460
- function evaluate(node, target, context) {
2461
- if (!target) return;
2462
- if (typeof document === "undefined") {
2463
- if (process.env.NODE_ENV !== "production") {
2464
- try {
2465
- console.warn("[Askr] evaluate() called in non-DOM environment; no-op.");
2466
- } catch (e) {
2467
- void e;
2468
- }
2469
- }
2470
- return;
2471
- }
2472
- if (context && domRanges.has(context)) {
2473
- const range = domRanges.get(context);
2474
- let current = range.start.nextSibling;
2475
- while (current && current !== range.end) {
2476
- const next = current.nextSibling;
2477
- current.remove();
2478
- current = next;
2479
- }
2480
- const dom = createDOMNode(node);
2481
- if (dom) {
2482
- target.insertBefore(dom, range.end);
2483
- }
2484
- } else if (context) {
2485
- const start = document.createComment("component-start");
2486
- const end = document.createComment("component-end");
2487
- target.appendChild(start);
2488
- target.appendChild(end);
2489
- domRanges.set(context, { start, end });
2490
- const dom = createDOMNode(node);
2491
- if (dom) {
2492
- target.insertBefore(dom, end);
2493
- }
2494
- } else {
2495
- let vnode = node;
2496
- if (isFragment(vnode)) {
2497
- const childArray = getFragmentChildren(vnode);
2498
- if (childArray.length === 1 && _isDOMElement(childArray[0]) && typeof childArray[0].type === "string") {
2499
- vnode = childArray[0];
2500
- } else {
2501
- processFragmentChildren(target, childArray);
2502
- return;
2503
- }
2504
- }
2505
- const firstChild = target.children[0];
2506
- if (firstChild && _isDOMElement(vnode) && typeof vnode.type === "string" && tagNamesEqualIgnoreCase3(firstChild.tagName, vnode.type)) {
2507
- smartUpdateElement(firstChild, vnode);
2508
- } else {
2509
- target.textContent = "";
2510
- if (_isDOMElement(vnode) && typeof vnode.type === "string" && tryFirstRenderKeyedChildren(target, vnode)) {
2511
- return;
2512
- }
2513
- const dom = createDOMNode(vnode);
2514
- if (dom) {
2515
- target.appendChild(dom);
2516
- }
2517
- }
2518
- }
2519
- }
2520
-
2521
- // src/renderer/index.ts
2522
- if (typeof globalThis !== "undefined") {
2523
- const _g = globalThis;
2524
- _g.__ASKR_RENDERER = {
2525
- evaluate,
2526
- isKeyedReorderFastPathEligible,
2527
- getKeyMapForElement
2528
- };
2529
- }
2530
-
2531
- // src/runtime/component.ts
2532
- function createComponentInstance(id, fn, props, target) {
2533
- const instance = {
2534
- id,
2535
- fn,
2536
- props,
2537
- target,
2538
- mounted: false,
2539
- abortController: new AbortController(),
2540
- // Create per-component
2541
- stateValues: [],
2542
- evaluationGeneration: 0,
2543
- notifyUpdate: null,
2544
- // Prebound helpers (initialized below) to avoid per-update allocations
2545
- _pendingFlushTask: void 0,
2546
- _pendingRunTask: void 0,
2547
- _enqueueRun: void 0,
2548
- stateIndexCheck: -1,
2549
- expectedStateIndices: [],
2550
- firstRenderComplete: false,
2551
- mountOperations: [],
2552
- cleanupFns: [],
2553
- hasPendingUpdate: false,
2554
- ownerFrame: null,
2555
- // Will be set by renderer when vnode is marked
2556
- ssr: false,
2557
- cleanupStrict: false,
2558
- isRoot: false,
2559
- // Render-tracking (for precise state subscriptions)
2560
- _currentRenderToken: void 0,
2561
- lastRenderToken: 0,
2562
- _pendingReadStates: /* @__PURE__ */ new Set(),
2563
- _lastReadStates: /* @__PURE__ */ new Set()
2564
- };
2565
- instance._pendingRunTask = () => {
2566
- instance.hasPendingUpdate = false;
2567
- runComponent(instance);
2568
- };
2569
- instance._enqueueRun = () => {
2570
- if (!instance.hasPendingUpdate) {
2571
- instance.hasPendingUpdate = true;
2572
- globalScheduler.enqueue(instance._pendingRunTask);
2573
- }
2574
- };
2575
- instance._pendingFlushTask = () => {
2576
- instance.hasPendingUpdate = false;
2577
- instance._enqueueRun?.();
2578
- };
2579
- return instance;
2580
- }
2581
- var currentInstance = null;
2582
- var stateIndex = 0;
2583
- function getCurrentComponentInstance() {
2584
- return currentInstance;
2585
- }
2586
- function setCurrentComponentInstance(instance) {
2587
- currentInstance = instance;
2588
- }
2589
- function executeMountOperations(instance) {
2590
- if (!instance.isRoot) return;
2591
- for (const operation of instance.mountOperations) {
2592
- const result = operation();
2593
- if (result instanceof Promise) {
2594
- result.then((cleanup) => {
2595
- if (typeof cleanup === "function") {
2596
- instance.cleanupFns.push(cleanup);
2597
- }
2598
- });
2599
- } else if (typeof result === "function") {
2600
- instance.cleanupFns.push(result);
2601
- }
2602
- }
2603
- instance.mountOperations = [];
2604
- }
2605
- function mountInstanceInline(instance, target) {
2606
- instance.target = target;
2607
- try {
2608
- if (target instanceof Element)
2609
- target.__ASKR_INSTANCE = instance;
2610
- } catch (err) {
2611
- void err;
2612
- }
2613
- instance.notifyUpdate = instance._enqueueRun;
2614
- const wasFirstMount = !instance.mounted;
2615
- instance.mounted = true;
2616
- if (wasFirstMount && instance.mountOperations.length > 0) {
2617
- executeMountOperations(instance);
2618
- }
2619
- }
2620
- var _globalRenderCounter = 0;
2621
- function runComponent(instance) {
2622
- instance.notifyUpdate = instance._enqueueRun;
2623
- instance._currentRenderToken = ++_globalRenderCounter;
2624
- instance._pendingReadStates = /* @__PURE__ */ new Set();
2625
- const domSnapshot = instance.target ? instance.target.innerHTML : "";
2626
- const result = executeComponentSync(instance);
2627
- if (result instanceof Promise) {
2628
- throw new Error(
2629
- "Async components are not supported. Components must be synchronous."
2630
- );
2631
- } else {
2632
- const fastlaneBridge = globalThis.__ASKR_FASTLANE;
2633
- try {
2634
- const used = fastlaneBridge?.tryRuntimeFastLaneSync?.(instance, result);
2635
- if (used) return;
2636
- } catch (err) {
2637
- if (process.env.NODE_ENV !== "production") throw err;
2638
- }
2639
- globalScheduler.enqueue(() => {
2640
- if (!instance.target && instance._placeholder) {
2641
- if (result === null || result === void 0) {
2642
- finalizeReadSubscriptions2(instance);
2643
- return;
2644
- }
2645
- const placeholder = instance._placeholder;
2646
- const parent = placeholder.parentNode;
2647
- if (!parent) {
2648
- logger.warn(
2649
- "[Askr] placeholder no longer in DOM, cannot render component"
2650
- );
2651
- return;
2652
- }
2653
- const host = document.createElement("div");
2654
- const oldInstance = currentInstance;
2655
- currentInstance = instance;
2656
- try {
2657
- evaluate(result, host);
2658
- parent.replaceChild(host, placeholder);
2659
- instance.target = host;
2660
- instance._placeholder = void 0;
2661
- host.__ASKR_INSTANCE = instance;
2662
- finalizeReadSubscriptions2(instance);
2663
- } finally {
2664
- currentInstance = oldInstance;
2665
- }
2666
- return;
2667
- }
2668
- if (instance.target) {
2669
- let oldChildren = [];
2670
- try {
2671
- const wasFirstMount = !instance.mounted;
2672
- const oldInstance = currentInstance;
2673
- currentInstance = instance;
2674
- oldChildren = Array.from(instance.target.childNodes);
2675
- try {
2676
- evaluate(result, instance.target);
2677
- } catch (e) {
2678
- try {
2679
- const newChildren = Array.from(instance.target.childNodes);
2680
- for (const n of newChildren) {
2681
- try {
2682
- cleanupInstancesUnder(n);
2683
- } catch (err) {
2684
- logger.warn(
2685
- "[Askr] error cleaning up failed commit children:",
2686
- err
2687
- );
2688
- }
2689
- }
2690
- } catch (_err) {
2691
- void _err;
2692
- }
2693
- try {
2694
- __ASKR_incCounter("__DOM_REPLACE_COUNT");
2695
- __ASKR_set(
2696
- "__LAST_DOM_REPLACE_STACK_COMPONENT_RESTORE",
2697
- new Error().stack
2698
- );
2699
- } catch (e2) {
2700
- void e2;
2701
- }
2702
- instance.target.replaceChildren(...oldChildren);
2703
- throw e;
2704
- } finally {
2705
- currentInstance = oldInstance;
2706
- }
2707
- finalizeReadSubscriptions2(instance);
2708
- instance.mounted = true;
2709
- if (wasFirstMount && instance.mountOperations.length > 0) {
2710
- executeMountOperations(instance);
2711
- }
2712
- } catch (renderError) {
2713
- try {
2714
- const currentChildren = Array.from(instance.target.childNodes);
2715
- for (const n of currentChildren) {
2716
- try {
2717
- cleanupInstancesUnder(n);
2718
- } catch (err) {
2719
- logger.warn(
2720
- "[Askr] error cleaning up partial children during rollback:",
2721
- err
2722
- );
2723
- }
2724
- }
2725
- } catch (_err) {
2726
- void _err;
2727
- }
2728
- try {
2729
- try {
2730
- __ASKR_incCounter("__DOM_REPLACE_COUNT");
2731
- __ASKR_set(
2732
- "__LAST_DOM_REPLACE_STACK_COMPONENT_ROLLBACK",
2733
- new Error().stack
2734
- );
2735
- } catch (e) {
2736
- void e;
2737
- }
2738
- instance.target.replaceChildren(...oldChildren);
2739
- } catch {
2740
- instance.target.innerHTML = domSnapshot;
2741
- }
2742
- throw renderError;
2743
- }
2744
- }
2745
- });
2746
- }
2747
- }
2748
- function renderComponentInline(instance) {
2749
- const hadToken = instance._currentRenderToken !== void 0;
2750
- const prevToken = instance._currentRenderToken;
2751
- const prevPendingReads = instance._pendingReadStates;
2752
- if (!hadToken) {
2753
- instance._currentRenderToken = ++_globalRenderCounter;
2754
- instance._pendingReadStates = /* @__PURE__ */ new Set();
2755
- }
2756
- try {
2757
- const result = executeComponentSync(instance);
2758
- if (!hadToken) {
2759
- finalizeReadSubscriptions2(instance);
2760
- }
2761
- return result;
2762
- } finally {
2763
- instance._currentRenderToken = prevToken;
2764
- instance._pendingReadStates = prevPendingReads ?? /* @__PURE__ */ new Set();
2765
- }
2766
- }
2767
- function executeComponentSync(instance) {
2768
- instance.stateIndexCheck = -1;
2769
- for (const state of instance.stateValues) {
2770
- if (state) {
2771
- state._hasBeenRead = false;
2772
- }
2773
- }
2774
- instance._pendingReadStates = /* @__PURE__ */ new Set();
2775
- currentInstance = instance;
2776
- stateIndex = 0;
2777
- try {
2778
- const renderStartTime = process.env.NODE_ENV !== "production" ? Date.now() : 0;
2779
- const context = {
2780
- signal: instance.abortController.signal
2781
- };
2782
- const executionFrame = {
2783
- parent: instance.ownerFrame,
2784
- values: null
2785
- };
2786
- const result = withContext(
2787
- executionFrame,
2788
- () => instance.fn(instance.props, context)
2789
- );
2790
- const renderTime = Date.now() - renderStartTime;
2791
- if (renderTime > 5) {
2792
- logger.warn(
2793
- `[askr] Slow render detected: ${renderTime}ms. Consider optimizing component performance.`
2794
- );
2795
- }
2796
- if (!instance.firstRenderComplete) {
2797
- instance.firstRenderComplete = true;
2798
- }
2799
- for (let i = 0; i < instance.stateValues.length; i++) {
2800
- const state = instance.stateValues[i];
2801
- if (state && !state._hasBeenRead) {
2802
- try {
2803
- const name = instance.fn?.name || "<anonymous>";
2804
- logger.warn(
2805
- `[askr] Unused state variable detected in ${name} at index ${i}. State should be read during render or removed.`
2806
- );
2807
- } catch {
2808
- logger.warn(
2809
- `[askr] Unused state variable detected. State should be read during render or removed.`
2810
- );
2811
- }
2812
- }
2813
- }
2814
- return result;
2815
- } finally {
2816
- currentInstance = null;
2817
- }
2818
- }
2819
- function executeComponent(instance) {
2820
- instance.abortController = new AbortController();
2821
- instance.notifyUpdate = instance._enqueueRun;
2822
- globalScheduler.enqueue(() => runComponent(instance));
2823
- }
2824
- function getCurrentInstance() {
2825
- return currentInstance;
2826
- }
2827
- function finalizeReadSubscriptions2(instance) {
2828
- const newSet = instance._pendingReadStates ?? /* @__PURE__ */ new Set();
2829
- const oldSet = instance._lastReadStates ?? /* @__PURE__ */ new Set();
2830
- const token = instance._currentRenderToken;
2831
- if (token === void 0) return;
2832
- for (const s of oldSet) {
2833
- if (!newSet.has(s)) {
2834
- const readers = s._readers;
2835
- if (readers) readers.delete(instance);
2836
- }
2837
- }
2838
- instance.lastRenderToken = token;
2839
- for (const s of newSet) {
2840
- let readers = s._readers;
2841
- if (!readers) {
2842
- readers = /* @__PURE__ */ new Map();
2843
- s._readers = readers;
2844
- }
2845
- readers.set(instance, instance.lastRenderToken ?? 0);
2846
- }
2847
- instance._lastReadStates = newSet;
2848
- instance._pendingReadStates = /* @__PURE__ */ new Set();
2849
- instance._currentRenderToken = void 0;
2850
- }
2851
- function getNextStateIndex() {
2852
- return stateIndex++;
2853
- }
2854
- function mountComponent(instance) {
2855
- executeComponent(instance);
2856
- }
2857
- function cleanupComponent(instance) {
2858
- const cleanupErrors = [];
2859
- for (const cleanup of instance.cleanupFns) {
2860
- try {
2861
- cleanup();
2862
- } catch (err) {
2863
- if (instance.cleanupStrict) {
2864
- cleanupErrors.push(err);
2865
- } else {
2866
- if (process.env.NODE_ENV !== "production") {
2867
- logger.warn("[Askr] cleanup function threw:", err);
2868
- }
2869
- }
2870
- }
2871
- }
2872
- instance.cleanupFns = [];
2873
- if (cleanupErrors.length > 0) {
2874
- throw new AggregateError(
2875
- cleanupErrors,
2876
- `Cleanup failed for component ${instance.id}`
2877
- );
2878
- }
2879
- if (instance._lastReadStates) {
2880
- for (const s of instance._lastReadStates) {
2881
- const readers = s._readers;
2882
- if (readers) readers.delete(instance);
2883
- }
2884
- instance._lastReadStates = /* @__PURE__ */ new Set();
2885
- }
2886
- instance.abortController.abort();
2887
- instance.notifyUpdate = null;
2888
- instance.mounted = false;
2889
- }
2890
-
2891
- export {
2892
- invariant,
2893
- logger,
2894
- globalScheduler,
2895
- withAsyncResourceContext,
2896
- getCurrentContextFrame,
2897
- isBulkCommitActive2 as isBulkCommitActive,
2898
- removeAllListeners,
2899
- createComponentInstance,
2900
- getCurrentComponentInstance,
2901
- setCurrentComponentInstance,
2902
- getCurrentInstance,
2903
- getNextStateIndex,
2904
- mountComponent,
2905
- cleanupComponent
2906
- };
2907
- //# sourceMappingURL=chunk-XHKZGJE3.js.map