@ape-egg/vibe 4.0.1 → 4.1.1

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.
@@ -27,60 +27,29 @@ import {
27
27
 
28
28
  export { activeOutgoingRoots, isComponentWrapper };
29
29
 
30
- // Deterministic component counter
31
- // Runtime-minted ids live in their own range, far above every build-tagged
32
- // id (SPA units get 1000 ids each — 1M covers a thousand pages). Without the
33
- // floor, a long session's runtime counter could grow into a not-yet-mounted
34
- // fragment's build range and claim its state. advanceComponentCounterPastIds
35
- // still bumps past anything larger it encounters in the document.
36
30
  let componentCounter = 1000000;
37
31
 
38
- /**
39
- * Generate unique component ID
40
- * Uses deterministic counter: _c0, _c1, _c2, etc.
41
- */
42
32
  export const generateComponentId = () => {
43
33
  return `_c${componentCounter++}`;
44
34
  };
45
35
 
46
- // Helper to escape regex special characters
47
36
  const escapeRegex = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
48
37
 
49
- // Kept as no-ops for API compatibility — path-based tracking was replaced by
50
- // DOM-scan cleanup in releaseOrphanedComponentState. Manifest paths don't
51
- // align 1:1 with component ownership across conditional remounts, so scanning
52
- // the DOM subtree about to be removed is simpler and waterproof.
53
38
  export const trackComponentOwnership = () => {};
54
39
 
55
- // Given an iterable of DOM nodes that are about to be (or have just been)
56
- // removed, find every `data-vibe-component-id` inside them and, for each id
57
- // whose DOM is fully gone from the live document, evict its state.
58
- //
59
- // Call this AFTER the nodes have been detached from the document so the
60
- // `document.querySelector` check sees the post-removal state.
61
40
  export const releaseOrphanedComponentState = (collectedIds) => {
62
41
  if (!collectedIds || collectedIds.size === 0) return;
63
42
  for (const id of collectedIds) {
64
43
  if (document.querySelector(`[data-vibe-component-id="${id}"]`)) continue;
65
44
  delete window.__vibe?.components?.[id];
66
- // CLEANUP OF CURRENT STATE
67
45
  delete window.$[id];
68
46
  runComponentCleanups(id);
69
47
  }
70
48
  };
71
49
 
72
- // Listener registry: maps componentId → array of unsubscribe callbacks
73
- // returned from `$.on(...)` calls inside the component's `<script>`.
74
- // Re-running a script for the same id (HMR remount with reused ids) or
75
- // unmounting the component fires the callbacks so the previous evaluation's
76
- // listeners don't accumulate alongside fresh registrations.
77
50
  export const runComponentCleanups = (componentId) => {
78
51
  const cleanups = window.__vibe?.cleanups?.[componentId];
79
52
  if (!cleanups) return;
80
- // Deregister BEFORE running: a throwing callback must neither re-throw on
81
- // every later cleanup of this id nor take the remaining callbacks down
82
- // with it — and never escape into the script chain, whose links have no
83
- // rejection path. User callbacks fail loudly, the engine keeps going.
84
53
  delete window.__vibe.cleanups[componentId];
85
54
  for (let i = 0; i < cleanups.length; i++) {
86
55
  try {
@@ -91,11 +60,6 @@ export const runComponentCleanups = (componentId) => {
91
60
  }
92
61
  };
93
62
 
94
- // Per-script `$` Proxy. Bare `$` references in a component's <script> resolve
95
- // to this Proxy (the function parameter shadows the global), so every
96
- // `$.on(...)` registration is automatically attributed to `componentId` via
97
- // the closure — no global flag, async-safe across `await` boundaries because
98
- // the closure binds the id, not a shared variable.
99
63
  const createScopedDollar = (componentId) => {
100
64
  const dollar = window.$;
101
65
  if (!dollar) return dollar;
@@ -103,14 +67,6 @@ const createScopedDollar = (componentId) => {
103
67
  get(target, prop, receiver) {
104
68
  if (prop === 'on') {
105
69
  return (event, callback) => {
106
- // 'unmount' is scope-resolved: in a component script it means THIS
107
- // component's unmount (conditional toggle, iteration removal,
108
- // reactive src swap — and before an HMR re-run of the same id).
109
- // The callback rides the same per-component cleanup registry the
110
- // global-event unsubscribes below ride, so a component owns
111
- // arbitrary side effects (intervals, listeners, sockets) without
112
- // leaking them past its lifetime. At page level the root's `on`
113
- // resolves the same event name to pagehide instead.
114
70
  if (event === 'unmount') {
115
71
  const cleanupsReg = ((window.__vibe ??= {}).cleanups ??= {});
116
72
  const slot = cleanupsReg[componentId] || (cleanupsReg[componentId] = []);
@@ -135,8 +91,6 @@ const createScopedDollar = (componentId) => {
135
91
  });
136
92
  };
137
93
 
138
- // Walk a node subtree (element or node list) and collect all
139
- // `data-vibe-component-id` values found on the node and its descendants.
140
94
  export const collectComponentIds = (node, into = new Set()) => {
141
95
  if (!node) return into;
142
96
  if (node.nodeType === 1) {
@@ -149,25 +103,15 @@ export const collectComponentIds = (node, into = new Set()) => {
149
103
  return into;
150
104
  };
151
105
 
152
- // Prepare a component <script> body for execution through the injected
153
- // component() path: strip the `import component from '...'` line (the
154
- // function is passed in as a parameter) and rewrite any remaining static
155
- // imports to awaited dynamic imports. Shared by the fetch path
156
- // (processSingle) and the compiled-page path (executeCompiledComponentScripts).
157
106
  const transformScriptContent = (rawContent) => {
158
- // Strip `import component from '...'` — Vibe injects the contextual
159
- // component() function as a parameter (it needs access to the temp DOM)
160
107
  let content = rawContent.replace(
161
108
  /import\s+component\s+from\s+['"][^'"]+['"];?\s*/g,
162
109
  ''
163
110
  );
164
111
 
165
- // Check for remaining imports that need rewriting
166
112
  const hasImports = /import\s/.test(content);
167
113
 
168
114
  if (hasImports) {
169
- // Rewrite remaining imports to dynamic await import()
170
- // Order matters: combined → default → named → namespace → side-effect (most specific first)
171
115
  content = content.replace(
172
116
  /import\s+(\w+)\s*,\s*\{([^}]+)\}\s+from\s+(['"][^'"]+['"])\s*;?/g,
173
117
  'const __m_$1 = await import($3); const $1 = __m_$1.default; const {$2} = __m_$1;'
@@ -193,24 +137,6 @@ const transformScriptContent = (rawContent) => {
193
137
  return { content, hasImports };
194
138
  };
195
139
 
196
- // Compiled pages inline `<component src>` content at build time, and the
197
- // compiler neuters each component script to type="vibe-module" so the browser
198
- // does NOT execute it as a native page module — native timing is wrong
199
- // (pre-boot: `$` is the placeholder, state registered after boot never merges
200
- // into the live proxy). This executes those scripts through the same
201
- // injected-component() path processSingle uses for fetched scripts: one
202
- // pipeline, identical semantics in both modes. Scripts stay in the DOM
203
- // (inert) so the manifest's childNodes indices keep matching the page.
204
- //
205
- // Returns a Promise when any script is async (has imports) — the caller
206
- // gates `ready` on it — or null when everything ran synchronously.
207
- //
208
- // Collection is span-aware, not a blind document query: manifest adoption has
209
- // already swapped every directive's stamped content back to its pre-stamp
210
- // template (declaration form), so at sweep time ALL content between
211
- // `<!-- if -->`/`<!-- each -->` markers is unrendered template. Those scripts
212
- // run when their branch/row mounts (mountBranch / renderIteration call back
213
- // into this pipeline); only directive-free scripts are the boot pass's own.
214
140
  export const executeCompiledComponentScripts = () => {
215
141
  const scripts = [];
216
142
  collectMountedModuleScripts(document.body ? [document.body] : [], scripts);
@@ -219,21 +145,6 @@ export const executeCompiledComponentScripts = () => {
219
145
  return runVibeModuleScripts(scripts);
220
146
  };
221
147
 
222
- // Same pipeline as the boot-time pass, but scoped to a freshly mounted subtree
223
- // (a conditional branch or iteration row) rather than the whole document. The
224
- // boot pass only sees component scripts that are in the page at boot; a branch
225
- // that mounts later — or RE-mounts after being unmounted — carries its own
226
- // inlined `vibe-module` scripts that must run each time so component-local state
227
- // (`component({...})` → `$._cN`) is re-registered. Without this, a re-opened
228
- // conditional restores its markup but its `<!-- each _cN.x -->` reads state that
229
- // was released on unmount (the AccountProgression overlay rendering blank on
230
- // second open).
231
- //
232
- // `silent` routes fresh-id registrations through $.register (no global flush)
233
- // — correct ONLY when the subtree's own hydration runs after these scripts
234
- // against live `$` (the fetched-mount path). Branch/row mounts render against
235
- // a flush snapshot that predates the registration, so they rely on the
236
- // registration's own flush to fill `_cN` bindings in — they must stay loud.
237
148
  export const executeCompiledComponentScriptsIn = (nodes, { silent = false } = {}) => {
238
149
  const scripts = [];
239
150
  collectMountedModuleScripts(nodes, scripts);
@@ -242,16 +153,6 @@ export const executeCompiledComponentScriptsIn = (nodes, { silent = false } = {}
242
153
  return runVibeModuleScripts(scripts, silent);
243
154
  };
244
155
 
245
- // Collect the vibe-module scripts a fresh mount actually OWNS. Content between
246
- // nested `<!-- if -->`/`<!-- each -->` markers in a just-cloned subtree is an
247
- // unrendered template — its scripts belong to the nested directive and run when
248
- // THAT directive mounts its branch/rows (mountBranch and renderIteration each
249
- // call back into this pass). Running them here would execute component copies
250
- // this mount never shows: the compiler inlines a slotted component once per
251
- // conditional branch, so a mount that owns both branch templates would register
252
- // ghost state buckets whose `$.on` hooks shadow the mounted copy's writes
253
- // forever. Directive spans are sibling-scoped, so each child list scans with
254
- // its own depth counter (same walk as reconcile's opaque-region skip).
255
156
  const collectMountedModuleScripts = (nodes, out) => {
256
157
  let depth = 0;
257
158
  for (const node of nodes) {
@@ -267,8 +168,6 @@ const collectMountedModuleScripts = (nodes, out) => {
267
168
  }
268
169
  };
269
170
 
270
- // Build-time tagging already assigned _cN ids to wrappers; advance the runtime
271
- // counter past them so freshly generated ids never collide.
272
171
  const advanceComponentCounterPastIds = (root) => {
273
172
  root.querySelectorAll('[data-vibe-component-id]').forEach((el) => {
274
173
  const m = el.getAttribute('data-vibe-component-id')?.match(/^_c(\d+)$/);
@@ -276,11 +175,6 @@ const advanceComponentCounterPastIds = (root) => {
276
175
  });
277
176
  };
278
177
 
279
- // Shared registration: the component registry always, plus the live `$` when
280
- // booted. `silent` prefers $.register — a fresh id lands without its own
281
- // global flush; the MOUNT commits all its registrations in one notifyChanged
282
- // batch when its scripts settle. Re-registrations (HMR) still flush
283
- // immediately, and pre-boot placeholders keep the plain reactive write.
284
178
  const registerComponentState = (componentId, state, silent) => {
285
179
  ((window.__vibe ??= {}).components ??= {})[componentId] = state;
286
180
  if (window.$) {
@@ -289,18 +183,6 @@ const registerComponentState = (componentId, state, silent) => {
289
183
  }
290
184
  };
291
185
 
292
- // Native `<script type="module">` semantics: module scripts evaluate strictly
293
- // in document order — script N+1 never starts before script N finished,
294
- // imports included. A sync script may therefore rely on globals an earlier
295
- // script's import produced (the game's Layout imports boot.js; chrome
296
- // components read its globals at their top level). Eval'd vibe-module scripts
297
- // lose that for free — an async function returns at its first `await`, so the
298
- // executor's loop would start every script "concurrently" and sync scripts
299
- // would run before earlier imports landed. One global chain restores the
300
- // contract across ALL execution sites (boot batch, mounted subtrees, fetched
301
- // components): while a script is pending, later scripts — sync ones too —
302
- // queue behind it. An idle chain runs sync scripts synchronously, so
303
- // boot timing is unchanged until the first async script appears.
304
186
  let scriptChain = null;
305
187
 
306
188
  const enqueueScriptExecution = (run) => {
@@ -321,10 +203,6 @@ const enqueueScriptExecution = (run) => {
321
203
  return result;
322
204
  };
323
205
 
324
- // Cleanups, scoping and evaluation for one script — the unit the chain
325
- // executes. Never throws and never rejects: a crashed script is warned and
326
- // released, later scripts still run (a failed native module doesn't stop
327
- // subsequent script elements either).
328
206
  const executeScriptUnit = (componentId, content, hasImports, scopedDollar, componentFn) => () => {
329
207
  runComponentCleanups(componentId);
330
208
  try {
@@ -340,13 +218,6 @@ const executeScriptUnit = (componentId, content, hasImports, scopedDollar, compo
340
218
  }
341
219
  };
342
220
 
343
- // The wrapper's own setup script: the first vibe-module script in the wrapper's
344
- // subtree not owned by a nested component wrapper. Only THIS script may claim
345
- // the wrapper's build-tagged id — the id the stamped bindings reference — and
346
- // the rule must be deterministic across batches, not "first in this batch": a
347
- // later partial batch (a nested branch mount re-running one auxiliary script)
348
- // claiming the component's id would tear down the component's live `$.on` hooks
349
- // through executeScriptUnit's pre-run cleanup and never re-register them.
350
221
  const wrapperSetupScript = (wrapper) => {
351
222
  for (const s of wrapper.querySelectorAll('script[type="vibe-module"]')) {
352
223
  if (s.closest('[data-vibe-component-id]') === wrapper) return s;
@@ -359,14 +230,8 @@ const runVibeModuleScripts = (scripts, silent = false) => {
359
230
  const registeredIds = [];
360
231
 
361
232
  for (const script of scripts) {
362
- // One script node, one execution — native `<script>` semantics. Remounts
363
- // clone fresh nodes from the restoration template (clones don't carry the
364
- // marker), so they run; the same DOM node reached by overlapping passes
365
- // (boot's document sweep after a pre-boot branch mount already ran it)
366
- // does not run twice.
367
233
  if (script.__vibeExecuted) continue;
368
234
 
369
- // Parity with the fetch path: dehydrated components never execute
370
235
  if (script.closest(`[${DEHYDRATE_CLASS_OR_ATTR}], .${DEHYDRATE_CLASS_OR_ATTR}`)) continue;
371
236
 
372
237
  const rawContent = script.textContent?.trim() || '';
@@ -393,8 +258,6 @@ const runVibeModuleScripts = (scripts, silent = false) => {
393
258
  if (task) asyncTasks.push(task);
394
259
  }
395
260
 
396
- // Silent mode: one grouped commit once every script has registered, so
397
- // whole-`$` observers see all fresh keys with a single flush.
398
261
  if (silent) {
399
262
  if (asyncTasks.length) {
400
263
  return Promise.all(asyncTasks).then(() => notifyChanged(registeredIds));
@@ -406,20 +269,12 @@ const runVibeModuleScripts = (scripts, silent = false) => {
406
269
  return asyncTasks.length ? Promise.all(asyncTasks) : null;
407
270
  };
408
271
 
409
- // Track pending fetches to cancel them if element is removed
410
- const pendingFetches = new WeakMap(); // element → AbortController
272
+ const pendingFetches = new WeakMap();
411
273
 
412
- // Component HTML is parsed (and prop/slot-transformed) while its @[...]
413
- // bindings are still literal text. Parsing in the live document lets the
414
- // browser act on those literals mid-parse — Chrome logs "The specified value
415
- // ... cannot be parsed" for a typed input's value="@[...]". An inert document
416
- // (no browsing context) parses identical DOM without a console to complain to;
417
- // nodes are auto-adopted into the live document on insertion.
418
274
  let inertDocument;
419
275
  const createDetached = (tagName) =>
420
276
  (inertDocument ??= document.implementation.createHTMLDocument('')).createElement(tagName);
421
277
 
422
- // Cancel a pending fetch for a component element
423
278
  export const abortComponentFetch = (element) => {
424
279
  const controller = pendingFetches.get(element);
425
280
  if (controller) {
@@ -428,73 +283,34 @@ export const abortComponentFetch = (element) => {
428
283
  }
429
284
  };
430
285
 
431
- // The live element a reactive src binding acts on. The manifest tree keeps the
432
- // ORIGINAL element, but every (re)mount replaces the wrapper — staging.js's
433
- // chain resolver is the one implementation.
434
286
  export const liveComponentWrapper = liveNode;
435
287
 
436
- // (Re)mount a component for a reactive src binding (`src="@[page.src]"`).
437
- // Three phases of a wrapper's life, one entry point:
438
- // - Unprocessed element (no fetch yet): write the resolved src — the pending
439
- // boot/observer processComponent pass fetches it.
440
- // - Fetch in flight: abort it and fetch the new src.
441
- // - Mounted wrapper (src consumed by finalize): re-fetch and re-mount; the
442
- // authored props + slot content re-apply via the remount context finalize
443
- // stashed on the wrapper, and the outgoing component's state is evicted by
444
- // the removal pass when replaceWith drops the old wrapper.
445
288
  export const remountComponent = (el, src, debug = false) => {
446
289
  const wasFetching = pendingFetches.has(el);
447
290
  const hadSrcAttr = el.hasAttribute('src');
448
- // Compare against the LATEST requested src: with a fetch in flight the src
449
- // attribute holds it (rapid navigation A→B→A must abort B, not no-op on A);
450
- // mounted and idle, the finalize-stashed value does.
451
291
  const current = wasFetching
452
292
  ? el.getAttribute('src')
453
293
  : (el._vibeMountedSrc ?? el.getAttribute('src'));
454
294
  if (src === current) return;
455
295
  abortComponentFetch(el);
456
296
  el.setAttribute('src', src);
457
- // Pre-fetch element awaiting its initial processing pass: that pass reads
458
- // the new value — nothing to redo. A declaration-form wrapper (bound src
459
- // that resolved to nothing, carried on data-vibe-src with no src
460
- // attribute) was invisible to that pass, so hydration owns its first
461
- // fetch too — the observer doesn't watch attributes.
462
297
  if (el._vibeMountedSrc === undefined && !wasFetching && hadSrcAttr) return;
463
- // The mounted content is now OUTGOING: it will be replaced wholesale when
464
- // the new src lands, so re-rendering it against post-navigation state is
465
- // pure waste — and is what made outgoing pages visually collapse the
466
- // moment route state flipped. Both engines skip beneath a flagged wrapper
467
- // (the wrapper's own src/key bindings stay live so a rapid next navigation
468
- // still re-triggers). The flag dies with the wrapper at swap.
469
298
  markOutgoing(el);
470
299
  processSingle(el, debug);
471
300
  };
472
301
 
473
- // Key-change remount (`key="@[page.path]"`): mount the CURRENT src fresh even
474
- // though it is unchanged. Only a mounted, idle wrapper has anything to redo —
475
- // with a fetch pending the incoming mount is already fresh (a src change in
476
- // the same flush started it), and an unmounted wrapper's first mount is owned
477
- // by the normal processing pass.
478
302
  export const forceRemount = (el, debug = false) => {
479
303
  if (pendingFetches.has(el) || el._vibeMountedSrc === undefined) return;
480
304
  el.setAttribute('src', el._vibeMountedSrc);
481
- // Same outgoing freeze as remountComponent — a keyed remount replaces the
482
- // mounted content just the same.
483
305
  markOutgoing(el);
484
306
  processSingle(el, debug);
485
307
  };
486
308
 
487
- // A src still carrying an @[…] binding is not a URL — it's source material
488
- // (an iteration or branch template the renderer hasn't consumed yet, or an
489
- // outlet whose scope owner hasn't resolved it). Fetching it verbatim is never
490
- // right: initializeBlock substitutes loop-scoped srcs, hydration remounts
491
- // reactive outlets, and this pass only mounts real URLs.
492
309
  const hasUnresolvedSrc = (el) => {
493
310
  BINDING_REGEX.lastIndex = 0;
494
311
  return BINDING_REGEX.test(el.getAttribute('src'));
495
312
  };
496
313
 
497
- // Check if an element is nested inside another unprocessed component[src]
498
314
  const isNestedInUnprocessedComponent = (el, rootElement) => {
499
315
  let parent = el.parentElement;
500
316
  while (parent && parent !== rootElement) {
@@ -509,17 +325,6 @@ const isNestedInUnprocessedComponent = (el, rootElement) => {
509
325
  return false;
510
326
  };
511
327
 
512
- // Rewrite `@[this.x...]` and `$.this.x...` inside element's text/attrs to use
513
- // componentId. Shared between script-execution path and pure-render path.
514
- //
515
- // Within `@[...]` bindings we rewrite every `this.X` reference (preserving
516
- // any trailing `.Y.Z` chain), so `@[this.user.name]` and `@[this.x + 1]` both
517
- // resolve correctly. Outside bindings — i.e. event handler attribute bodies
518
- // like `onclick="$.this.mode = 'edit'"` — only `$.this.X` writes are
519
- // rewritten; bare `this.X` in event handlers is handled later by parse.js,
520
- // which lowers it to `$this(this).X` — resolved at fire time by
521
- // this-scope.js (declared state keys hit the bucket, everything else stays
522
- // the native element).
523
328
  const rewriteBindingsInString = (str, componentId) =>
524
329
  str.replace(BINDING_REGEX, (match, expr) => {
525
330
  const rewritten = expr.replace(THIS_PROP_REGEX, `${componentId}.$1`);
@@ -547,20 +352,12 @@ const rewriteThisBindings = (element, componentId) => {
547
352
  });
548
353
  };
549
354
 
550
- // Tag siblings of a <script> with componentId and rewrite `this.` bindings.
551
- // Runs BEFORE script.remove() so nextElementSibling is valid. Shared by
552
- // processSingle (executing path) and renderComponentTemplate (pure path).
553
355
  const tagScriptSiblings = (script, componentId) => {
554
356
  let sibling = script.nextElementSibling;
555
357
  while (sibling) {
556
358
  if (sibling.tagName === 'SCRIPT' && sibling.getAttribute('type') === 'module') {
557
359
  break;
558
360
  }
559
- // A sibling already carrying an id is a build-tagged compiled wrapper
560
- // that owns its scope — its `this.` bindings were rewritten to that id
561
- // at compile time. Overwriting it re-scopes the wrapper to THIS script's
562
- // id and orphans every `@[_cN.x]` binding inside it (the game's
563
- // top-level create-teamplay modal losing its state).
564
361
  if (!sibling.hasAttribute('data-vibe-component-id')) {
565
362
  sibling.setAttribute('data-vibe-component-id', componentId);
566
363
  rewriteThisBindings(sibling, componentId);
@@ -569,21 +366,12 @@ const tagScriptSiblings = (script, componentId) => {
569
366
  }
570
367
  };
571
368
 
572
- // Substitute props + inline slot content into a pre-processed temp container.
573
- // Returns the final processed HTML string. Shared by processSingle.finalize()
574
- // (runtime mount) and renderComponentTemplate (surgical HMR).
575
369
  const renderPropsAndSlot = (temp, props, slotHtml) => {
576
370
  let transformedHtml = temp.innerHTML;
577
371
 
578
372
  const DIRECTIVE_COMMENT_REGEX = /<!--\s*(if|else if|each)\s+([^]*?)\s*-->/g;
579
373
  const EVENT_ATTR_REGEX = /\bon(\w+)="([^"]*)"/g;
580
374
 
581
- // HTML's parser lowercases attribute names, so a consumer-written
582
- // `<component dndDisabled>` arrives here with propName `dnddisabled` while
583
- // the component template author wrote `dndDisabled`. Match identifiers and
584
- // bindings case-insensitively so both sides line up. Word-boundary
585
- // lookbehind/lookahead still hold (they're case-agnostic), so
586
- // `dnddisabled` won't bleed into `dndDisabledAlt`.
587
375
  Object.entries(props).forEach(([propName, propValue]) => {
588
376
  const bindingMatch = propValue.match(/^@\[(.+)\]$/);
589
377
  const exactPattern = new RegExp(`@\\[${escapeRegex(propName)}\\]`, 'gi');
@@ -592,11 +380,6 @@ const renderPropsAndSlot = (temp, props, slotHtml) => {
592
380
  'gi'
593
381
  );
594
382
 
595
- // Rewrite the identifier only outside string literals. A prop/alias that also
596
- // appears inside a quoted string — e.g. the selector in `closest('brawler-slot')`
597
- // when the prop is `slot` — must be left intact. Split on string literals
598
- // (single/double/backtick, honouring escapes) and substitute only the code spans
599
- // between them. Template `${…}` interpolation counts as part of the literal here.
600
383
  const stringLiteral = /(['"`])(?:\\.|(?!\1)[^\\])*\1/g;
601
384
  const substituteInExpr = (expr, replacement) => {
602
385
  let out = '';
@@ -627,11 +410,6 @@ const renderPropsAndSlot = (temp, props, slotHtml) => {
627
410
  );
628
411
  const stateRegex = new RegExp(`\\$\\.${escapeRegex(propName)}(?![a-zA-Z0-9_$])`, 'gi');
629
412
  transformedHtml = transformedHtml.replace(EVENT_ATTR_REGEX, (match, evName, body) => {
630
- // Substitute the bare prop identifier too (not just the `$.prop` form),
631
- // mirroring the @[...] binding pass above — so `onclick="pick(item)"`
632
- // resolves the live prop, not a global that throws ReferenceError. A
633
- // loop-alias path (`row.sig`) becomes `(row.sig)` here; parse.js then
634
- // rewrites the alias to `$scope(this,'row')`.
635
413
  const rewritten = substituteInExpr(body.replace(stateRegex, `$.${path}`), `(${path})`);
636
414
  return rewritten === body ? match : `on${evName}="${rewritten}"`;
637
415
  });
@@ -658,8 +436,6 @@ const renderPropsAndSlot = (temp, props, slotHtml) => {
658
436
  );
659
437
  const stateRegex = new RegExp(`\\$\\.${escapeRegex(propName)}(?![a-zA-Z0-9_$])`, 'gi');
660
438
  transformedHtml = transformedHtml.replace(EVENT_ATTR_REGEX, (match, evName, body) => {
661
- // Same bare-identifier substitution for a literal prop: `onclick="set(limit)"`
662
- // with `limit="5"` becomes `set(5)`.
663
439
  const rewritten = substituteInExpr(body.replace(stateRegex, `$.${literal}`), literal);
664
440
  return rewritten === body ? match : `on${evName}="${rewritten}"`;
665
441
  });
@@ -681,12 +457,6 @@ const renderPropsAndSlot = (temp, props, slotHtml) => {
681
457
  return transformedHtml;
682
458
  };
683
459
 
684
- // Pure-render path for surgical HMR. Takes a component's raw template HTML
685
- // plus the live instance's props, slot, and existing componentIds. Returns
686
- // the processed HTML string that $.reconcile can diff against the live
687
- // wrapper's children. Scripts are NOT executed — callers are responsible
688
- // for deciding whether to preserve the existing state (reuse componentIds)
689
- // or trigger a full re-mount (new componentIds).
690
460
  export const renderComponentTemplate = (rawHtml, props = {}, slotHtml = '', options = {}) => {
691
461
  const { componentIds = [] } = options;
692
462
  const temp = createDetached('div');
@@ -703,31 +473,19 @@ export const renderComponentTemplate = (rawHtml, props = {}, slotHtml = '', opti
703
473
  return renderPropsAndSlot(temp, props, slotHtml);
704
474
  };
705
475
 
706
- // Process a single component element: fetch HTML, execute scripts, replace DOM
707
476
  const processSingle = (el, debug) => {
708
- // Skip dehydrated components
709
477
  if (el.hasAttribute(DEHYDRATE_CLASS_OR_ATTR) || el.classList.contains(DEHYDRATE_CLASS_OR_ATTR)) {
710
478
  return Promise.resolve();
711
479
  }
712
480
 
713
- // Skip if fetch already in flight for this element
714
481
  if (pendingFetches.has(el)) return Promise.resolve();
715
482
 
716
483
  const src = el.getAttribute('src');
717
484
 
718
- // Use pre-hydration slot content if available (saved by index.js before
719
- // hydration ran, or re-stashed by finalize for reactive-src re-mounts),
720
- // otherwise fall back to current innerHTML (e.g. runtime-only usage without
721
- // boot). Kept on the element — a re-mount consumes the same authored slot.
722
485
  const children = (el._vibeSlotContent !== undefined ? el._vibeSlotContent : el.innerHTML).trim();
723
- // A re-mounted wrapper carries no prop attributes (finalize stripped them) —
724
- // its authored props ride the remount context stashed at the previous mount.
725
486
  let props = el._vibeRemountProps;
726
487
  if (!props) {
727
488
  props = {};
728
- // `src` and `key` are the wrapper's own contract (what to mount / when to
729
- // remount), and data-vibe-* attributes are runtime transport — none of
730
- // them are authored props for the component.
731
489
  Array.from(el.attributes).forEach((attr) => {
732
490
  if (attr.name !== 'src' && attr.name !== 'key' && !attr.name.startsWith('data-vibe-')) {
733
491
  props[attr.name] = attr.value;
@@ -735,47 +493,24 @@ const processSingle = (el, debug) => {
735
493
  });
736
494
  }
737
495
 
738
- // Capture cache state before the fetch so the debug layer can tell a real
739
- // network fetch from a runtime-cache hit (the call below would make them
740
- // indistinguishable — both just resolve a promise).
741
496
  const fromCache = isComponentCached(src);
742
497
 
743
- // Create AbortController to cancel fetch if element is removed
744
498
  const controller = new AbortController();
745
499
  pendingFetches.set(el, controller);
746
500
 
747
501
  return fetchComponentTemplate(src, controller.signal)
748
502
  .then((html) => {
749
- // Superseded before the template arrived: the cache path resolves
750
- // regardless of the abort signal (aborting a cache hit is meaningless
751
- // network-wise), so the supersede check lives here. A newer remount
752
- // owns the wrapper — running this mount's scripts or finalize would
753
- // land the stale fragment and discard the new one.
754
503
  if (controller.signal.aborted) return;
755
504
 
756
- // Parse HTML in temporary container to process component scripts
757
505
  const temp = createDetached('div');
758
506
  temp.innerHTML = html;
759
507
 
760
- // Process any <script type="module"> elements
761
508
  const moduleScripts = temp.querySelectorAll('script[type="module"]');
762
509
 
763
- // Process each script — collect async tasks if any have imports
764
510
  const asyncTasks = [];
765
511
 
766
- // Track every componentId registered during this fetch. If the host
767
- // element is detached before finalize runs (e.g. a conditional unmounted
768
- // mid-fetch, or the user navigated away), we release these state
769
- // buckets — otherwise component({...}) leaks state to `$` for DOM that
770
- // never reaches the document.
771
512
  const registeredComponentIds = [];
772
513
 
773
- // First componentId encountered — applied to the wrapper itself so
774
- // directives living between top-level sibling roots (e.g. a comment
775
- // marker for `<!-- if this.X -->`) can resolve component scope via
776
- // closest('[data-vibe-component-id]'). Without this, multi-root
777
- // templates have scope-less wrappers and top-level `this.` references
778
- // fall through to global state.
779
514
  let firstComponentId = null;
780
515
 
781
516
  for (const script of moduleScripts) {
@@ -784,54 +519,29 @@ const processSingle = (el, debug) => {
784
519
 
785
520
  const { content: scriptContent, hasImports } = transformScriptContent(rawContent);
786
521
 
787
- // Reuse component ID from HMR if available, otherwise generate new
788
522
  const reuseIds = el._vibeReuseComponentIds;
789
523
  const componentId = reuseIds && reuseIds.length ? reuseIds.shift() : generateComponentId();
790
524
 
791
525
  if (firstComponentId === null) firstComponentId = componentId;
792
526
 
793
- // Provide a component() function that registers state for this component.
794
- // Sibling tagging is handled below (before script.remove()) so it works
795
- // for both sync and async scripts.
796
527
  const componentFn = (state) => {
797
- // Fetched-mount registration is silent: the fetched subtree's
798
- // hydration runs after replaceWith against live `$`, so a fresh id
799
- // needs no flush (see registerComponentState / $.register).
800
528
  registerComponentState(componentId, state, true);
801
529
  if (!registeredComponentIds.includes(componentId)) {
802
530
  registeredComponentIds.push(componentId);
803
531
  }
804
- // Return the id so consumers can reach their reactive state via
805
- // `$[id]` — matches the public component.js contract. Without this,
806
- // `const id = component(state)` is undefined for src-fetched
807
- // components and `$[id]` silently resolves to nothing.
808
532
  return componentId;
809
533
  };
810
534
 
811
- // Execute through the global script chain (see enqueueScriptExecution):
812
- // cleanups for a reused componentId (HMR remount) tear down the prior
813
- // evaluation's listeners right before the fresh run, the scoped `$`
814
- // tracks this script's `.on(...)` registrations, and document-order
815
- // execution holds even against scripts from other batches (a fetched
816
- // component's script never runs while the shell's boot import is
817
- // still in flight).
818
535
  const task = enqueueScriptExecution(
819
536
  executeScriptUnit(componentId, scriptContent, hasImports, createScopedDollar(componentId), componentFn),
820
537
  );
821
538
  if (task) asyncTasks.push(task);
822
539
 
823
- // Tag siblings + rewrite this. bindings using shared helper. Runs
824
- // BEFORE script.remove() so nextElementSibling is valid.
825
540
  tagScriptSiblings(script, componentId);
826
541
 
827
- // Remove script from temp (we executed it manually)
828
542
  script.remove();
829
543
  }
830
544
 
831
- // Evict everything this mount's scripts registered — state buckets AND
832
- // their $.on listeners/unmount side effects. The scripts already RAN
833
- // (execution precedes finalize), so skipping the cleanups here leaks
834
- // live global listeners for DOM that never mounts.
835
545
  const releaseRegisteredIds = () => {
836
546
  for (const id of registeredComponentIds) {
837
547
  delete window.__vibe?.components?.[id];
@@ -840,27 +550,17 @@ const processSingle = (el, debug) => {
840
550
  }
841
551
  };
842
552
 
843
- // Finalize: props, slots, DOM replacement
844
553
  const finalize = () => {
845
- // Superseded DURING script execution (an async import held this mount
846
- // while a newer remount aborted it): the newer fetch owns the wrapper.
847
554
  if (controller.signal.aborted) {
848
555
  releaseRegisteredIds();
849
556
  return;
850
557
  }
851
558
 
852
- // Delegate prop substitution + slot inlining to shared helper.
853
559
  const transformedHtml = renderPropsAndSlot(temp, props, children);
854
560
 
855
- // Clean up pending fetch tracker — only if this fetch still owns the
856
- // slot (a reactive-src re-mount may have aborted us and registered a
857
- // newer controller for the same element).
858
561
  if (pendingFetches.get(el) === controller) pendingFetches.delete(el);
859
562
 
860
- // Replace with clean component wrapper (no src, no props)
861
- // Check if element still has a parent (might have been removed during fetch)
862
563
  if (el.parentNode) {
863
- // Create clean wrapper element (preserve tag type: component or div.component)
864
564
  const newWrapper =
865
565
  el.tagName === 'DIV' ? createDetached('div') : createDetached('component');
866
566
 
@@ -869,127 +569,47 @@ const processSingle = (el, debug) => {
869
569
  }
870
570
 
871
571
  newWrapper.innerHTML = transformedHtml;
872
- // Park binding-valued src while the wrapper still lives in the inert
873
- // document — adoption into the live document is what starts image
874
- // loads, so this is the last moment a raw `@[...]` src is harmless.
875
572
  parkFetchableSrc(newWrapper);
876
573
  if (firstComponentId !== null) {
877
574
  newWrapper.setAttribute('data-vibe-component-id', firstComponentId);
878
575
  }
879
- // Stash the raw source so the HMR plugin can establish a baseline
880
- // script hash on the very first update — without this, the first
881
- // save after page load would always fall back to re-mount (since
882
- // the plugin would have nothing to compare against). Vibe itself
883
- // never reads this; it's purely for the plugin spy.
884
576
  newWrapper._vibeRawSource = html;
885
- // Remount context for reactive src bindings (src="@[page.src]"):
886
- // the mounted src (no-op detection), the authored props, and the
887
- // authored slot content. Each re-mount consumes these and finalize
888
- // stashes them onto the next wrapper — self-sustaining across
889
- // arbitrarily many navigations.
890
577
  newWrapper._vibeMountedSrc = src;
891
578
  newWrapper._vibeRemountProps = props;
892
579
  newWrapper._vibeSlotContent = children;
893
- // The authored binding travels ON the wrapper (data-vibe-src, same
894
- // transport idea as data-vibe-namebind): the original tree node is
895
- // pruned when this replaceWith's removal mutation is processed, and
896
- // the replacement's reparse recaptures the binding from this
897
- // attribute — the DOM alone carries the knowledge across swaps.
898
580
  const srcBinding = el._vibeSrcBinding ?? el.getAttribute('data-vibe-src');
899
581
  if (srcBinding) newWrapper.setAttribute('data-vibe-src', srcBinding);
900
- // The key binding and its last resolved value ride along the same
901
- // way, so a later key change still finds what to compare against
902
- // on the replacement wrapper.
903
582
  const keyBinding = el._vibeKeyBinding ?? el.getAttribute('data-vibe-key');
904
583
  if (keyBinding) newWrapper.setAttribute('data-vibe-key', keyBinding);
905
584
  if (el._vibeMountedKey !== undefined) newWrapper._vibeMountedKey = el._vibeMountedKey;
906
- // Transfer iteration-prop registry ownership from the soon-to-be-
907
- // detached `<component src>` to the new wrapper. The detached element
908
- // would otherwise trigger releaseOrphanedIterationProps and free the
909
- // registry slots that the inlined template's bindings still reference,
910
- // causing every `@[window.__vibe.iterProps._pN]` to resolve to undefined
911
- // on the next hydrate.
912
585
  if (el._vibeIterPropIds) {
913
586
  newWrapper._vibeIterPropIds = el._vibeIterPropIds;
914
587
  el._vibeIterPropIds = null;
915
588
  }
916
- // The discovery marker rides on the registry path (props with iteration
917
- // aliases) AND the global-only raw-binding path (no registry slot, just
918
- // `_vibeIterPropExprs = []`). Transfer it whenever present so affected.js's
919
- // walkInlinedComponentTrees can find the wrapper and re-hydrate its
920
- // bindings on a global-state change.
921
589
  if (el.hasAttribute('data-vibe-iter-prop')) {
922
590
  newWrapper.setAttribute('data-vibe-iter-prop', '');
923
591
  el.removeAttribute('data-vibe-iter-prop');
924
592
  bumpIterPropGeneration();
925
593
  }
926
- // Transfer the original prop expressions too, so the iteration's
927
- // update path can re-evaluate them against the row's new scope and
928
- // refresh the registry slots in place — letting the inlined
929
- // component's bindings react without rebuilding the row's DOM.
930
594
  if (el._vibeIterPropExprs) {
931
595
  newWrapper._vibeIterPropExprs = el._vibeIterPropExprs;
932
596
  el._vibeIterPropExprs = null;
933
597
  }
934
- // Back-pointer from the soon-to-be-detached `<component src>` to
935
- // the new wrapper. The iteration's `instance.clonedNodes` still
936
- // references the original element; follow this link to reach the
937
- // live wrapper when refreshing registry slots / re-hydrating.
938
- // The wrapper's `_vibeIterTree` (set later by processMutations after
939
- // renderAllConditionals/Iterations populated runtime data) is what
940
- // iterate.js's update path uses to re-evaluate inlined bindings on
941
- // each row update.
942
- // The observer hydrates the inserted subtree in its NEXT batch —
943
- // until then, selectors keyed on hydrated attributes (a name-bound
944
- // <page @[page.name]> → page[pvp] rules) don't match and the
945
- // content paints unstyled. Cover the gap with the same fouc
946
- // contract pages use: hidden at insertion, revealed by the batch
947
- // that parsed and hydrated this subtree.
948
598
  newWrapper.setAttribute('vibe-fouc', '');
949
599
  el._vibeReplacedBy = newWrapper;
950
600
  if (el._vibeOutgoing) {
951
- // REMOUNT (route/key change): stage, don't swap — staging.js owns
952
- // the transition (display:none sibling now, one-paint commit in
953
- // tryReveal below).
954
601
  stageIncoming(el, newWrapper);
955
602
  } else {
956
603
  el.replaceWith(newWrapper);
957
604
  }
958
605
  debugLog(fromCache ? PHASE_FETCH_CACHED : PHASE_FETCH, src, debug);
959
606
 
960
- // The mount's own script registrations commit as one batch — the
961
- // subtree hydrates via the observer against live `$`, so the only
962
- // consumers needing a flush are whole-`$` observers elsewhere.
963
607
  notifyChanged(registeredComponentIds);
964
608
 
965
- // Build-inlined child components (compiled SPA fragments) arrive
966
- // with tagged wrapper ids and vibe-module scripts — the compiled-
967
- // document form. A fetched mount is the fourth delivery mode after
968
- // boot, conditional branches, and iteration rows: run those
969
- // scripts now so each child's component({...}) state registers
970
- // under its build-tagged id and the _cN bindings hydrate. Silent:
971
- // their registrations commit as one grouped notify when the
972
- // scripts settle — per-script flushes would re-walk the page N
973
- // times (the 26-script game fragments spent ~150ms/navigation on
974
- // exactly that). The settle promise also gates the reveal below:
975
- // a slow module import delays registration, and until it lands the
976
- // subtree's `this.`-derived bindings hydrate to junk (NaN widths —
977
- // the game's "Making potion" bar painting full/empty mid-mount).
978
609
  const scriptsSettled = Promise.resolve(
979
610
  executeCompiledComponentScriptsIn([newWrapper], { silent: true }),
980
611
  );
981
612
 
982
- // MutationObserver handles parsing and hydrating the new content.
983
- // Branch nodes are registered in the manifest by mountBranch,
984
- // so the observer can find parents even inside conditional branches.
985
- // Hydration can span multiple batches (nested fetched components,
986
- // async scripts) with paints in between — reveal only when the
987
- // wrapper's scripts have settled AND the subtree carries no raw
988
- // bindings (same predicate the page-level ready uses). The grouped
989
- // registration notify queues its correction flush BEFORE the settle
990
- // callback runs, so the recheck sees post-correction DOM in the
991
- // same microtask drain — the first painted frame is the true one.
992
- // A wrapper unmounted mid-hydration releases the hook.
993
613
  let scriptsDone = false;
994
614
  const tryReveal = () => {
995
615
  if (!newWrapper.isConnected) {
@@ -999,10 +619,6 @@ const processSingle = (el, debug) => {
999
619
  return;
1000
620
  }
1001
621
  if (!scriptsDone || !shouldCleanup(newWrapper)) return;
1002
- // Atomic visual commit: old page out, parked styling-context
1003
- // bindings applied, new page revealed — one synchronous block,
1004
- // one paint. Until this moment the outgoing page was still the
1005
- // one on screen, fully styled.
1006
622
  commitStaged(newWrapper);
1007
623
  newWrapper.removeAttribute('vibe-fouc');
1008
624
  unfouc();
@@ -1013,31 +629,19 @@ const processSingle = (el, debug) => {
1013
629
  tryReveal();
1014
630
  });
1015
631
  } else {
1016
- // Element was detached before finalize ran (conditional unmounted
1017
- // during fetch, parent removed, etc). Release any state component()
1018
- // calls registered — otherwise it leaks on `$` forever.
1019
632
  releaseOutgoing(el);
1020
633
  releaseRegisteredIds();
1021
634
  }
1022
635
  };
1023
636
 
1024
- // If any scripts had async imports, wait for them before finalizing.
1025
- // Otherwise finalize synchronously (preserves original boot timing).
1026
637
  if (asyncTasks.length > 0) {
1027
638
  return Promise.all(asyncTasks).then(finalize);
1028
639
  }
1029
640
  finalize();
1030
641
  })
1031
642
  .catch((error) => {
1032
- // Clean up pending fetch tracker — ownership-guarded (see finalize)
1033
643
  if (pendingFetches.get(el) === controller) pendingFetches.delete(el);
1034
644
 
1035
- // Aborted fetch: a removal-abort (wrapper left the DOM mid-remount)
1036
- // has no commit left to release its outgoing freeze — free the root
1037
- // here or the detached page subtree stays pinned in
1038
- // activeOutgoingRoots for the session. A supersede-abort (newer
1039
- // remount on the same, still-connected wrapper) keeps it: the new
1040
- // fetch owns the freeze.
1041
645
  if (error.name === 'AbortError') {
1042
646
  if (!el.isConnected) releaseOutgoing(el);
1043
647
  return;
@@ -1060,10 +664,6 @@ export const processComponent = (rootElement, onComplete, config = {}) => {
1060
664
  return;
1061
665
  }
1062
666
 
1063
- // Only process top-level components with a fetchable src — skip unresolved
1064
- // binding srcs (never fetchable), and skip those nested inside other
1065
- // unprocessed component[src] elements (they're slot content that will
1066
- // be revealed when the parent component finalizes).
1067
667
  const topLevel = Array.from(allComponents).filter(
1068
668
  (el) => !hasUnresolvedSrc(el) && !isNestedInUnprocessedComponent(el, rootElement)
1069
669
  );
@@ -1073,10 +673,5 @@ export const processComponent = (rootElement, onComplete, config = {}) => {
1073
673
  return;
1074
674
  }
1075
675
 
1076
- // Fetch and process all top-level components in parallel.
1077
- // Nested components (inside finalized content) are discovered and
1078
- // processed by the MutationObserver → processComponent chain.
1079
- // onComplete is handled by checkCleanup (which fires when no
1080
- // component[src] elements remain).
1081
676
  topLevel.forEach((el) => processSingle(el, debug));
1082
677
  };