@moku-labs/web 1.15.1 → 1.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -9156,6 +9156,18 @@ function createApi(ctx) {
9156
9156
  */
9157
9157
  current() {
9158
9158
  return ctx.state.currentUrl;
9159
+ },
9160
+ /**
9161
+ * Resolve a registered island's api by name (the cross-island seam). Returns
9162
+ * `undefined` when no provider with that name is currently registered.
9163
+ *
9164
+ * @param name - The provider island's component name.
9165
+ * @returns The provider's api, or `undefined`.
9166
+ * @example
9167
+ * app.spa.component("lightbox");
9168
+ */
9169
+ component(name) {
9170
+ return ctx.state.componentApis.get(name);
9159
9171
  }
9160
9172
  };
9161
9173
  }
@@ -9196,6 +9208,15 @@ const COMPONENT_HOOK_NAMES = [
9196
9208
  const ERROR_PREFIX$2 = "[web]";
9197
9209
  /** The set of legal hook names, frozen for O(1) membership checks. */
9198
9210
  const HOOK_NAME_SET = new Set(COMPONENT_HOOK_NAMES);
9211
+ /** The spec-only keys that select the plugin-mirror form of {@link createComponent}. */
9212
+ const SPEC_KEYS = new Set([
9213
+ "state",
9214
+ "render",
9215
+ "events",
9216
+ "api"
9217
+ ]);
9218
+ /** Synchronous re-entrancy cap for the render scheduler (a render that calls `ctx.flush`). */
9219
+ const MAX_RENDER_DEPTH = 25;
9199
9220
  /**
9200
9221
  * No-op link builder for the {@link EMPTY_ROUTE} slice (used when no route matched).
9201
9222
  *
@@ -9214,40 +9235,346 @@ const EMPTY_ROUTE = {
9214
9235
  url: noUrl
9215
9236
  };
9216
9237
  /**
9238
+ * No-op placeholder for an instance's `flush` slot until the real one is bound at mount.
9239
+ *
9240
+ * @example
9241
+ * const instance = { flush: noop };
9242
+ */
9243
+ function noop() {}
9244
+ /** Cached promise for the lazy `./render` chunk (loaded at most once per module). */
9245
+ let renderChunk;
9246
+ /** The resolved VNode committer once the chunk loads (undefined until then). */
9247
+ let commitVNodeFunction;
9248
+ /**
9249
+ * Load the lazy `./render` chunk (once) and cache its `commitVNode` for synchronous
9250
+ * use by later renders. Awaited by a component's `mountPromise` so the test harness's
9251
+ * `settle()` can deterministically flush a VNode render.
9252
+ *
9253
+ * @returns A promise that resolves once `commitVNode` is available.
9254
+ * @example
9255
+ * await loadRenderChunk();
9256
+ */
9257
+ async function loadRenderChunk() {
9258
+ renderChunk ??= Promise.resolve().then(() => require("./render-KdufA3_b.cjs"));
9259
+ commitVNodeFunction = (await renderChunk).commitVNode;
9260
+ }
9261
+ /**
9262
+ * Commit a {@link RenderResult} into a host: `string` → `innerHTML`, `Node` →
9263
+ * `replaceChildren`, `void`/`undefined` → no-op (the render mutated the DOM itself), and
9264
+ * a Preact `VNode` → committed through the lazy gate (loading it on demand if needed).
9265
+ *
9266
+ * @param host - The island host element to render into.
9267
+ * @param result - The value returned by the component's `render`.
9268
+ * @example
9269
+ * commitResult(host, h(View, { items }));
9270
+ */
9271
+ function commitResult(host, result) {
9272
+ if (result === void 0) return;
9273
+ if (typeof result === "string") {
9274
+ host.innerHTML = result;
9275
+ return;
9276
+ }
9277
+ if (result instanceof Node) {
9278
+ host.replaceChildren(result);
9279
+ return;
9280
+ }
9281
+ const vnode = result;
9282
+ if (commitVNodeFunction) {
9283
+ commitVNodeFunction(vnode, host);
9284
+ return;
9285
+ }
9286
+ loadRenderChunk().then(() => commitVNodeFunction?.(vnode, host)).catch(() => {});
9287
+ }
9288
+ /**
9289
+ * Run a component's `render(state, ctx)` and commit the result now. Guards against
9290
+ * synchronous re-entrancy (a render that calls `ctx.flush`) with a depth cap.
9291
+ *
9292
+ * @param instance - The instance to render.
9293
+ * @throws {Error} When the synchronous render depth exceeds {@link MAX_RENDER_DEPTH}.
9294
+ * @example
9295
+ * runRender(instance);
9296
+ */
9297
+ function runRender(instance) {
9298
+ const render = instance.def.spec?.render;
9299
+ if (!render) return;
9300
+ if (instance.renderDepth > MAX_RENDER_DEPTH) throw new Error(`${ERROR_PREFIX$2} component "${instance.def.name}" render re-entered ${MAX_RENDER_DEPTH}+ times\n → a render must not synchronously trigger its own render (avoid ctx.flush() inside render)`);
9301
+ instance.renderDepth += 1;
9302
+ try {
9303
+ commitResult(instance.el, render(instance.state ?? {}, instance.ctx));
9304
+ } finally {
9305
+ instance.renderDepth -= 1;
9306
+ }
9307
+ }
9308
+ /**
9309
+ * Schedule a microtask-batched render for an instance (no-op when it has no `render`).
9310
+ * Multiple `ctx.set` calls in the same tick coalesce into a single render.
9311
+ *
9312
+ * @param instance - The instance to schedule a render for.
9313
+ * @example
9314
+ * scheduleRender(instance);
9315
+ */
9316
+ function scheduleRender(instance) {
9317
+ if (!instance.def.spec?.render || instance.renderScheduled) return;
9318
+ instance.renderScheduled = true;
9319
+ queueMicrotask(() => {
9320
+ if (!instance.renderScheduled) return;
9321
+ instance.renderScheduled = false;
9322
+ runRender(instance);
9323
+ });
9324
+ }
9325
+ /**
9326
+ * Build the single per-instance {@link ComponentContext} reused by every hook, event
9327
+ * handler, and render. Route fields (`params`/`meta`/`locale`/`url`) and `data` read
9328
+ * through the instance so a navigation update is reflected without rebuilding the ctx;
9329
+ * `state`/`set`/`flush`/`cleanup`/`component` are bound to the instance + plugin state.
9330
+ *
9331
+ * @param state - The plugin state (for the cross-island `component` resolver).
9332
+ * @param instance - The instance the context is bound to.
9333
+ * @returns The instance-bound context.
9334
+ * @example
9335
+ * instance.ctx = buildContext(state, instance);
9336
+ */
9337
+ function buildContext(state, instance) {
9338
+ return {
9339
+ el: instance.el,
9340
+ /**
9341
+ * The current page data payload (live; updated across navigations).
9342
+ *
9343
+ * @returns The page data.
9344
+ * @example
9345
+ * ctx.data;
9346
+ */
9347
+ get data() {
9348
+ return instance.data;
9349
+ },
9350
+ /**
9351
+ * The matched route's path params (live; updated across navigations).
9352
+ *
9353
+ * @returns The route params.
9354
+ * @example
9355
+ * ctx.params.id;
9356
+ */
9357
+ get params() {
9358
+ return instance.route.params;
9359
+ },
9360
+ /**
9361
+ * The matched route's `.meta()` bag (live; updated across navigations).
9362
+ *
9363
+ * @returns The route meta.
9364
+ * @example
9365
+ * ctx.meta.focus;
9366
+ */
9367
+ get meta() {
9368
+ return instance.route.meta;
9369
+ },
9370
+ /**
9371
+ * The active locale for the current route (live; updated across navigations).
9372
+ *
9373
+ * @returns The locale code.
9374
+ * @example
9375
+ * ctx.locale;
9376
+ */
9377
+ get locale() {
9378
+ return instance.route.locale;
9379
+ },
9380
+ /**
9381
+ * The named-route link builder for the current route.
9382
+ *
9383
+ * @returns The link builder.
9384
+ * @example
9385
+ * ctx.url("board", { id });
9386
+ */
9387
+ get url() {
9388
+ return instance.route.url;
9389
+ },
9390
+ /**
9391
+ * The live per-instance state (`undefined` for legacy hooks-only islands).
9392
+ *
9393
+ * @returns The current state.
9394
+ * @example
9395
+ * ctx.state.count;
9396
+ */
9397
+ get state() {
9398
+ return instance.state;
9399
+ },
9400
+ /**
9401
+ * Merge a patch into the per-instance state and schedule one batched render.
9402
+ *
9403
+ * @param patch - A partial state object, or an updater `(prev) => partial`.
9404
+ * @example
9405
+ * ctx.set(prev => ({ count: prev.count + 1 }));
9406
+ */
9407
+ set(patch) {
9408
+ const previous = instance.state ?? {};
9409
+ const next = typeof patch === "function" ? patch(previous) : patch;
9410
+ instance.state = Object.assign({}, previous, next);
9411
+ scheduleRender(instance);
9412
+ },
9413
+ /**
9414
+ * Force a synchronous render now (drains any pending scheduled render).
9415
+ *
9416
+ * @example
9417
+ * ctx.flush();
9418
+ */
9419
+ flush() {
9420
+ instance.flush();
9421
+ },
9422
+ /**
9423
+ * Register a disposer run on destroy (subscriptions, timers, manual listeners).
9424
+ *
9425
+ * @param dispose - The teardown function.
9426
+ * @example
9427
+ * ctx.cleanup(off);
9428
+ */
9429
+ cleanup(dispose) {
9430
+ instance.cleanups.push(dispose);
9431
+ },
9432
+ /**
9433
+ * Resolve another island's registered api by name (`undefined` when absent).
9434
+ *
9435
+ * @param name - The provider island's component name.
9436
+ * @returns The provider's api, or `undefined`.
9437
+ * @example
9438
+ * ctx.component("lightbox");
9439
+ */
9440
+ component(name) {
9441
+ return state.componentApis.get(name);
9442
+ }
9443
+ };
9444
+ }
9445
+ /**
9446
+ * Resolve the element a delegated handler should receive for an event: the host for a
9447
+ * host-level binding (empty selector), else the nearest ancestor of `event.target`
9448
+ * matching the selector that is still inside the host.
9449
+ *
9450
+ * @param host - The island host element.
9451
+ * @param event - The dispatched DOM event.
9452
+ * @param selector - The key's selector (empty string → host-level).
9453
+ * @returns The matched element, or `undefined` when nothing matches inside the host.
9454
+ * @example
9455
+ * const target = matchTarget(host, event, "[data-action]");
9456
+ */
9457
+ function matchTarget(host, event, selector) {
9458
+ if (selector === "") return host;
9459
+ const target = event.target;
9460
+ if (!(target instanceof Element)) return void 0;
9461
+ const matched = target.closest(selector);
9462
+ return matched && host.contains(matched) ? matched : void 0;
9463
+ }
9464
+ /**
9465
+ * Attach a component's declarative `events` map: one real listener per event TYPE on
9466
+ * the host (dispatch walks `closest(selector)` for each registered selector), each
9467
+ * removed via the instance's cleanup registry on destroy.
9468
+ *
9469
+ * @param instance - The instance whose host the listeners attach to.
9470
+ * @param events - The declarative `{ "<type> <selector>": handler }` map.
9471
+ * @throws {Error} When a key has no event type.
9472
+ * @example
9473
+ * attachEvents(instance, { "click [data-action]": (ctx, e, el) => {} });
9474
+ */
9475
+ function attachEvents(instance, events) {
9476
+ const host = instance.el;
9477
+ const byType = /* @__PURE__ */ new Map();
9478
+ for (const [key, handler] of Object.entries(events)) {
9479
+ const space = key.indexOf(" ");
9480
+ const type = (space === -1 ? key : key.slice(0, space)).trim();
9481
+ const selector = space === -1 ? "" : key.slice(space + 1).trim();
9482
+ if (type === "") throw new Error(`${ERROR_PREFIX$2} component "${instance.def.name}" event key must start with an event type: "${key}"\n → use "<type>" or "<type> <selector>" (e.g. "click [data-action]")`);
9483
+ const list = byType.get(type) ?? [];
9484
+ list.push({
9485
+ selector,
9486
+ handler
9487
+ });
9488
+ byType.set(type, list);
9489
+ }
9490
+ for (const [type, handlers] of byType) {
9491
+ const listener = (event) => {
9492
+ for (const { selector, handler } of handlers) {
9493
+ const target = matchTarget(host, event, selector);
9494
+ if (target) handler(instance.ctx, event, target);
9495
+ }
9496
+ };
9497
+ host.addEventListener(type, listener);
9498
+ instance.cleanups.push(() => host.removeEventListener(type, listener));
9499
+ }
9500
+ }
9501
+ /**
9217
9502
  * Validate a single hook entry: its key must be a known hook name and its value
9218
9503
  * must be a function. Throws fail-fast on the first violation.
9219
9504
  *
9220
9505
  * @param componentName - The owning component name (for error messages).
9221
- * @param hooks - The hooks object being validated.
9506
+ * @param source - The raw authoring object being validated.
9222
9507
  * @param key - The hook key to validate.
9223
9508
  * @throws {Error} If `key` is not in `COMPONENT_HOOK_NAMES`.
9224
9509
  * @throws {TypeError} If the hook value is not a function.
9225
9510
  * @example
9226
- * validateHookEntry("counter", hooks, "onMount");
9511
+ * validateHookEntry("counter", source, "onMount");
9227
9512
  */
9228
- function validateHookEntry(componentName, hooks, key) {
9229
- if (!HOOK_NAME_SET.has(key)) throw new Error(`${ERROR_PREFIX$2} unknown component hook "${key}" on "${componentName}"\n → valid hooks: ${COMPONENT_HOOK_NAMES.join(", ")}`);
9230
- if (typeof hooks[key] !== "function") throw new TypeError(`${ERROR_PREFIX$2} component hook "${key}" on "${componentName}" must be a function\n → provide a function or omit the hook`);
9513
+ function validateHookEntry(componentName, source, key) {
9514
+ if (!HOOK_NAME_SET.has(key)) throw new Error(`${ERROR_PREFIX$2} unknown component hook "${key}" on "${componentName}"\n → valid hooks: ${COMPONENT_HOOK_NAMES.join(", ")}\n → spec keys: state, render, events, api`);
9515
+ if (typeof source[key] !== "function") throw new TypeError(`${ERROR_PREFIX$2} component hook "${key}" on "${componentName}" must be a function\n → provide a function or omit the hook`);
9516
+ }
9517
+ /**
9518
+ * Validate the spec extras (`state`/`render`/`api` must be functions; `events` must be
9519
+ * a plain object of functions). Throws fail-fast on the first violation.
9520
+ *
9521
+ * @param componentName - The owning component name (for error messages).
9522
+ * @param extras - The partitioned spec extras to validate.
9523
+ * @throws {TypeError} If a present extra has the wrong shape.
9524
+ * @example
9525
+ * validateSpecExtras("board", { state: () => ({}) });
9526
+ */
9527
+ function validateSpecExtras(componentName, extras) {
9528
+ for (const key of [
9529
+ "state",
9530
+ "render",
9531
+ "api"
9532
+ ]) if (extras[key] !== void 0 && typeof extras[key] !== "function") throw new TypeError(`${ERROR_PREFIX$2} component "${key}" on "${componentName}" must be a function\n → provide a function or omit it`);
9533
+ if (extras.events !== void 0) {
9534
+ const events = extras.events;
9535
+ if (!(typeof events === "object")) throw new TypeError(`${ERROR_PREFIX$2} component "events" on "${componentName}" must be an object of handlers`);
9536
+ for (const [key, handler] of Object.entries(events)) if (typeof handler !== "function") throw new TypeError(`${ERROR_PREFIX$2} component event "${key}" on "${componentName}" must be a function`);
9537
+ }
9231
9538
  }
9232
9539
  /**
9233
- * Create a validated component definition. Validates hook names at registration
9234
- * for fail-fast typo detection (e.g. `onMout` throws immediately) and asserts
9235
- * each provided hook is a function.
9540
+ * Create a validated component definition. Accepts either the legacy hooks-only form
9541
+ * (`createComponent("counter", { onMount() {} })`) or the plugin-mirror spec form
9542
+ * (`createComponent("board", { state, render, events, api, ...hooks })`). Spec-only
9543
+ * keys (`state`/`render`/`events`/`api`) are partitioned out before hook-name
9544
+ * validation, so a real typo (e.g. `onMout`) still throws immediately while the spec
9545
+ * keys are accepted.
9236
9546
  *
9237
9547
  * @param name - Unique component name.
9238
- * @param hooks - Lifecycle hook implementations.
9548
+ * @param spec - Lifecycle hooks, or the `{ state, render, events, api, ...hooks }` spec.
9239
9549
  * @returns A `ComponentDef` ready to `register`.
9240
- * @throws {Error} If `name` is empty, any hook key is not in
9241
- * `COMPONENT_HOOK_NAMES`, or any provided hook value is not a function.
9550
+ * @throws {Error} If `name` is empty, a hook key is unknown, or an extra/hook value has the wrong shape.
9551
+ * @example
9552
+ * const counter = createComponent("counter", { onMount({ el }) { el.textContent = "0"; } });
9242
9553
  * @example
9243
- * const counter = createComponent("counter", {
9244
- * onMount({ el }) { el.textContent = "0"; }
9554
+ * const list = createComponent<{ items: string[] }>("list", {
9555
+ * state: () => ({ items: [] }),
9556
+ * render: (s) => h(List, { items: s.items })
9245
9557
  * });
9246
9558
  */
9247
- function createComponent(name, hooks) {
9559
+ function createComponent(name, spec) {
9248
9560
  if (name.trim() === "") throw new Error(`${ERROR_PREFIX$2} component name must be a non-empty string\n → pass a unique name to createComponent("name", hooks)`);
9249
- for (const key of Object.keys(hooks)) validateHookEntry(name, hooks, key);
9250
- return {
9561
+ const source = spec;
9562
+ const hooks = {};
9563
+ const extras = {};
9564
+ for (const key of Object.keys(source)) {
9565
+ if (SPEC_KEYS.has(key)) {
9566
+ extras[key] = source[key];
9567
+ continue;
9568
+ }
9569
+ validateHookEntry(name, source, key);
9570
+ hooks[key] = source[key];
9571
+ }
9572
+ validateSpecExtras(name, extras);
9573
+ return Object.keys(extras).length > 0 ? {
9574
+ name,
9575
+ hooks,
9576
+ spec: extras
9577
+ } : {
9251
9578
  name,
9252
9579
  hooks
9253
9580
  };
@@ -9271,64 +9598,53 @@ function extractPageData(doc) {
9271
9598
  }
9272
9599
  }
9273
9600
  /**
9274
- * Builds a live component instance bound to an element.
9601
+ * Read the current page data, or `{}` in a headless (non-browser) context.
9275
9602
  *
9276
- * @param definition - The component definition.
9277
- * @param element - The element the instance binds to.
9278
- * @param persistent - Whether the instance survives navigation.
9279
- * @returns The constructed (not-yet-mounted) instance.
9603
+ * @returns The current page data payload.
9280
9604
  * @example
9281
- * const inst = createInstance(definition, element, false);
9605
+ * const data = currentPageData();
9282
9606
  */
9283
- function createInstance(definition, element, persistent) {
9284
- return {
9285
- def: definition,
9286
- el: element,
9287
- persistent
9288
- };
9607
+ function currentPageData() {
9608
+ return typeof document === "undefined" ? {} : extractPageData(document);
9289
9609
  }
9290
9610
  /**
9291
- * Invokes a single lifecycle hook on an instance with its component context.
9292
- * Missing hooks are skipped silently.
9611
+ * Invokes a single lifecycle hook on an instance with its bound context. Missing
9612
+ * hooks are skipped silently.
9293
9613
  *
9294
9614
  * @param instance - The instance whose hook to run.
9295
9615
  * @param hook - The hook name to invoke.
9296
- * @param ctx - The component context passed to the hook.
9297
9616
  * @example
9298
- * runHook(instance, "onMount", ctx);
9617
+ * runHook(instance, "onDestroy");
9299
9618
  */
9300
- function runHook(instance, hook, ctx) {
9301
- instance.def.hooks[hook]?.(ctx);
9619
+ function runHook(instance, hook) {
9620
+ instance.def.hooks[hook]?.(instance.ctx);
9302
9621
  }
9303
9622
  /**
9304
- * Builds the component context handed to a hook: the bound element + page data, merged
9305
- * with the matched route's slice (params/meta/locale/url). Defaults to {@link EMPTY_ROUTE}
9306
- * when no route is supplied (headless, tests, public `scan()`).
9623
+ * Run an instance's registered cleanup disposers (LIFO) and unregister its api. Each
9624
+ * disposer runs in isolation so a throwing one never strands the others during teardown.
9307
9625
  *
9308
- * @param element - The element the instance is bound to.
9309
- * @param data - The current page data payload.
9310
- * @param route - The matched-route slice for the current URL.
9311
- * @returns The hook context.
9626
+ * @param state - The plugin state (for the api registry).
9627
+ * @param instance - The instance being disposed.
9312
9628
  * @example
9313
- * const ctx = makeContext(element, data, route);
9629
+ * disposeInstance(state, instance);
9314
9630
  */
9315
- function makeContext(element, data, route = EMPTY_ROUTE) {
9316
- return {
9317
- el: element,
9318
- data,
9319
- params: route.params,
9320
- meta: route.meta,
9321
- locale: route.locale,
9322
- url: route.url
9323
- };
9631
+ function disposeInstance(state, instance) {
9632
+ for (let index = instance.cleanups.length - 1; index >= 0; index -= 1) try {
9633
+ instance.cleanups[index]?.();
9634
+ } catch {}
9635
+ instance.cleanups.length = 0;
9636
+ instance.renderScheduled = false;
9637
+ if (instance.api !== void 0 && state.componentApis.get(instance.def.name) === instance.api) state.componentApis.delete(instance.def.name);
9324
9638
  }
9325
9639
  /**
9326
- * Mounts a single `data-component` element: classifies persistent vs
9327
- * page-specific, builds the instance, fires `onCreate` then `onMount`, records
9328
- * it in state, and emits `spa:component-mount`. No-ops if the element is already
9640
+ * Mounts a single `data-component` element: classifies persistent vs page-specific,
9641
+ * builds the instance + its bound context, initializes per-instance `state`, registers
9642
+ * its `api`, attaches declarative `events`, fires `onCreate` then `onMount` (capturing
9643
+ * an async `onMount` + render-chunk load as `mountPromise`), schedules the initial
9644
+ * render, records it, and emits `spa:component-mount`. No-ops if the element is already
9329
9645
  * mounted, has no component name, or names an unregistered component.
9330
9646
  *
9331
- * @param state - The plugin state (registeredComponents + instances).
9647
+ * @param state - The plugin state (registeredComponents + instances + componentApis).
9332
9648
  * @param emit - The event emitter for spa:component-mount.
9333
9649
  * @param swapArea - The swap-region element, or null when none was found.
9334
9650
  * @param data - The current page data payload.
@@ -9343,10 +9659,40 @@ function mountElement(state, emit, swapArea, data, element, route = EMPTY_ROUTE)
9343
9659
  if (!name) return;
9344
9660
  const definition = state.registeredComponents.get(name);
9345
9661
  if (!definition) return;
9346
- const instance = createInstance(definition, element, swapArea ? !swapArea.contains(element) : true);
9347
- const ctx = makeContext(element, data, route);
9348
- runHook(instance, "onCreate", ctx);
9349
- runHook(instance, "onMount", ctx);
9662
+ const instance = {
9663
+ def: definition,
9664
+ el: element,
9665
+ persistent: swapArea ? !swapArea.contains(element) : true,
9666
+ ctx: void 0,
9667
+ state: void 0,
9668
+ api: void 0,
9669
+ route,
9670
+ data,
9671
+ cleanups: [],
9672
+ flush: noop,
9673
+ renderScheduled: false,
9674
+ renderDepth: 0,
9675
+ mountPromise: void 0
9676
+ };
9677
+ instance.ctx = buildContext(state, instance);
9678
+ instance.flush = () => {
9679
+ instance.renderScheduled = false;
9680
+ runRender(instance);
9681
+ };
9682
+ const spec = definition.spec;
9683
+ if (spec?.state) instance.state = spec.state(instance.ctx);
9684
+ if (spec?.api) {
9685
+ instance.api = spec.api(instance.ctx);
9686
+ state.componentApis.set(definition.name, instance.api);
9687
+ }
9688
+ if (spec?.events) attachEvents(instance, spec.events);
9689
+ runHook(instance, "onCreate");
9690
+ const onMountResult = definition.hooks.onMount?.(instance.ctx);
9691
+ if (spec?.render) scheduleRender(instance);
9692
+ const pending = [];
9693
+ if (spec?.render) pending.push(loadRenderChunk());
9694
+ if (onMountResult && typeof onMountResult.then === "function") pending.push(onMountResult);
9695
+ instance.mountPromise = pending.length > 0 ? Promise.all(pending).then(() => {}) : void 0;
9350
9696
  state.instances.set(element, instance);
9351
9697
  emit("spa:component-mount", {
9352
9698
  name: definition.name,
@@ -9354,12 +9700,12 @@ function mountElement(state, emit, swapArea, data, element, route = EMPTY_ROUTE)
9354
9700
  });
9355
9701
  }
9356
9702
  /**
9357
- * Scans the swap region, mounts components for matching `data-component`
9358
- * elements, classifies persistent (outside swap area) vs page-specific (inside),
9359
- * fires `onCreate` then `onMount`, and emits `spa:component-mount` per instance.
9703
+ * Scans the swap region, mounts components for matching `data-component` elements,
9704
+ * classifies persistent (outside swap area) vs page-specific (inside), runs
9705
+ * `onCreate`/`onMount` + initial render, and emits `spa:component-mount` per instance.
9360
9706
  * Already-mounted elements are skipped.
9361
9707
  *
9362
- * @param state - The plugin state (registeredComponents + instances).
9708
+ * @param state - The plugin state (registeredComponents + instances + componentApis).
9363
9709
  * @param emit - The event emitter for spa:component-mount.
9364
9710
  * @param swapSelector - CSS selector bounding page-specific components.
9365
9711
  * @param route - The matched-route slice for the current URL (params/meta/locale/url).
@@ -9373,9 +9719,10 @@ function scanAndMount(state, emit, swapSelector, route = EMPTY_ROUTE) {
9373
9719
  for (const element of document.querySelectorAll("[data-component]")) mountElement(state, emit, swapArea, data, element, route);
9374
9720
  }
9375
9721
  /**
9376
- * Unmounts page-specific instances inside the swap region (runs `onUnMount`
9377
- * then `onDestroy`), removes them from state, and emits `spa:component-unmount`.
9378
- * Persistent instances (outside the swap area) are left in place.
9722
+ * Unmounts page-specific instances inside the swap region (runs `onUnMount` then
9723
+ * `onDestroy`, then their cleanup disposers + api unregister), removes them from state,
9724
+ * and emits `spa:component-unmount`. Persistent instances (outside the swap area) are
9725
+ * left in place.
9379
9726
  *
9380
9727
  * @param state - The plugin state holding live instances.
9381
9728
  * @param emit - The event emitter for spa:component-unmount.
@@ -9383,12 +9730,13 @@ function scanAndMount(state, emit, swapSelector, route = EMPTY_ROUTE) {
9383
9730
  * unmountPageSpecific(state, emit);
9384
9731
  */
9385
9732
  function unmountPageSpecific(state, emit) {
9386
- const data = typeof document === "undefined" ? {} : extractPageData(document);
9733
+ const data = currentPageData();
9387
9734
  for (const [element, instance] of state.instances) {
9388
9735
  if (instance.persistent) continue;
9389
- const ctx = makeContext(element, data);
9390
- runHook(instance, "onUnMount", ctx);
9391
- runHook(instance, "onDestroy", ctx);
9736
+ instance.data = data;
9737
+ runHook(instance, "onUnMount");
9738
+ runHook(instance, "onDestroy");
9739
+ disposeInstance(state, instance);
9392
9740
  state.instances.delete(element);
9393
9741
  emit("spa:component-unmount", {
9394
9742
  name: instance.def.name,
@@ -9397,9 +9745,10 @@ function unmountPageSpecific(state, emit) {
9397
9745
  }
9398
9746
  }
9399
9747
  /**
9400
- * Disposes ALL live instances (persistent and page-specific) on teardown:
9401
- * runs `onUnMount` then `onDestroy`, emits `spa:component-unmount`, and clears
9402
- * the instance map. Used by the kernel's `dispose` on plugin stop.
9748
+ * Disposes ALL live instances (persistent and page-specific) on teardown: runs
9749
+ * `onUnMount` then `onDestroy`, then their cleanup disposers + api unregister, emits
9750
+ * `spa:component-unmount`, and clears the instance + api maps. Used by the kernel's
9751
+ * `dispose` on plugin stop.
9403
9752
  *
9404
9753
  * @param state - The plugin state holding live instances.
9405
9754
  * @param emit - The event emitter for spa:component-unmount.
@@ -9407,17 +9756,19 @@ function unmountPageSpecific(state, emit) {
9407
9756
  * unmountAll(state, emit);
9408
9757
  */
9409
9758
  function unmountAll(state, emit) {
9410
- const data = typeof document === "undefined" ? {} : extractPageData(document);
9759
+ const data = currentPageData();
9411
9760
  for (const [element, instance] of state.instances) {
9412
- const ctx = makeContext(element, data);
9413
- runHook(instance, "onUnMount", ctx);
9414
- runHook(instance, "onDestroy", ctx);
9761
+ instance.data = data;
9762
+ runHook(instance, "onUnMount");
9763
+ runHook(instance, "onDestroy");
9764
+ disposeInstance(state, instance);
9415
9765
  emit("spa:component-unmount", {
9416
9766
  name: instance.def.name,
9417
9767
  el: element
9418
9768
  });
9419
9769
  }
9420
9770
  state.instances.clear();
9771
+ state.componentApis.clear();
9421
9772
  }
9422
9773
  /**
9423
9774
  * Fires `onNavStart` on every currently-mounted instance (persistent instances
@@ -9428,12 +9779,16 @@ function unmountAll(state, emit) {
9428
9779
  * notifyNavStart(state);
9429
9780
  */
9430
9781
  function notifyNavStart(state) {
9431
- const data = typeof document === "undefined" ? {} : extractPageData(document);
9432
- for (const [element, instance] of state.instances) runHook(instance, "onNavStart", makeContext(element, data));
9782
+ const data = currentPageData();
9783
+ for (const instance of state.instances.values()) {
9784
+ instance.data = data;
9785
+ runHook(instance, "onNavStart");
9786
+ }
9433
9787
  }
9434
9788
  /**
9435
9789
  * Fires `onNavEnd` on persistent instances that survived the swap (page-specific
9436
- * instances were already destroyed and re-created by the swap).
9790
+ * instances were already destroyed and re-created by the swap), updating their route
9791
+ * slice to the destination first.
9437
9792
  *
9438
9793
  * @param state - The plugin state holding live instances.
9439
9794
  * @param route - The matched-route slice for the destination URL (params/meta/locale/url).
@@ -9441,8 +9796,13 @@ function notifyNavStart(state) {
9441
9796
  * notifyNavEnd(state, route);
9442
9797
  */
9443
9798
  function notifyNavEnd(state, route = EMPTY_ROUTE) {
9444
- const data = typeof document === "undefined" ? {} : extractPageData(document);
9445
- for (const [element, instance] of state.instances) if (instance.persistent) runHook(instance, "onNavEnd", makeContext(element, data, route));
9799
+ const data = currentPageData();
9800
+ for (const instance of state.instances.values()) {
9801
+ if (!instance.persistent) continue;
9802
+ instance.data = data;
9803
+ instance.route = route;
9804
+ runHook(instance, "onNavEnd");
9805
+ }
9446
9806
  }
9447
9807
  //#endregion
9448
9808
  //#region src/plugins/spa/head.ts
@@ -9983,6 +10343,7 @@ function createState(_ctx) {
9983
10343
  return {
9984
10344
  registeredComponents: /* @__PURE__ */ new Map(),
9985
10345
  instances: /* @__PURE__ */ new Map(),
10346
+ componentApis: /* @__PURE__ */ new Map(),
9986
10347
  currentUrl: "",
9987
10348
  destroyRouter: null,
9988
10349
  started: false,
@@ -10221,7 +10582,7 @@ function createSpaKernel(state, config, emit, deps) {
10221
10582
  const commitDataRender = async (pathname, resolvedRender, signal) => {
10222
10583
  if (signal?.aborted) return;
10223
10584
  const { route, vnode, routeContext, region } = resolvedRender;
10224
- const { renderVNode } = await Promise.resolve().then(() => require("./render-DLZEOe4M.cjs"));
10585
+ const { renderVNode } = await Promise.resolve().then(() => require("./render-KdufA3_b.cjs"));
10225
10586
  if (signal?.aborted) return;
10226
10587
  syncDataHead(deps.head, route, routeContext);
10227
10588
  unmountPageSpecific(state, emit);
@@ -10290,7 +10651,7 @@ function createSpaKernel(state, config, emit, deps) {
10290
10651
  return;
10291
10652
  }
10292
10653
  const { vnode, region } = resolvedRender;
10293
- const { renderVNode } = await Promise.resolve().then(() => require("./render-DLZEOe4M.cjs"));
10654
+ const { renderVNode } = await Promise.resolve().then(() => require("./render-KdufA3_b.cjs"));
10294
10655
  renderVNode(vnode, region);
10295
10656
  scanAndMount(state, emit, resolved.swapSelector, routeSlice);
10296
10657
  };