@krate/runtime 0.5.0-beta.3 → 0.5.0-rc.2

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 (43) hide show
  1. package/dist/actions.js +2 -5
  2. package/dist/base-path.d.ts +7 -0
  3. package/dist/base-path.js +19 -0
  4. package/dist/base-path.test.d.ts +1 -0
  5. package/dist/base-path.test.js +88 -0
  6. package/dist/dev-overlay.js +31 -19
  7. package/dist/dev-overlay.test.js +14 -1
  8. package/dist/dom.d.ts +4 -0
  9. package/dist/dom.js +59 -15
  10. package/dist/dom.test.js +8 -0
  11. package/dist/effect-errors.test.js +37 -1
  12. package/dist/effects.js +41 -8
  13. package/dist/events.d.ts +2 -0
  14. package/dist/events.js +18 -0
  15. package/dist/index.d.ts +5 -0
  16. package/dist/krate-core.js +1 -1
  17. package/dist/krate-dev.js +27 -19
  18. package/dist/krate-f-actions.js +1 -1
  19. package/dist/krate-f-list.js +1 -1
  20. package/dist/krate-f-router-lite.js +1 -1
  21. package/dist/krate-f-router.js +1 -1
  22. package/dist/krate-features.json +1 -0
  23. package/dist/krate-hydrate-lite.js +5 -5
  24. package/dist/krate-hydrate.js +5 -5
  25. package/dist/krate-runtime.js +5 -5
  26. package/dist/krate-suspense.js +1 -1
  27. package/dist/list.js +26 -18
  28. package/dist/list.test.js +91 -0
  29. package/dist/metadata.js +3 -0
  30. package/dist/patterns.test.js +27 -0
  31. package/dist/react-effects.test.js +37 -0
  32. package/dist/router-lite.js +3 -9
  33. package/dist/router-nav.test.js +95 -0
  34. package/dist/router.js +59 -19
  35. package/dist/server-handler.d.ts +1 -0
  36. package/dist/server-handler.js +39 -5
  37. package/dist/server-handler.test.js +46 -0
  38. package/dist/server.js +2 -1
  39. package/dist/signal.js +47 -14
  40. package/dist/slots.test.js +18 -0
  41. package/dist/suspense.js +34 -2
  42. package/dist/suspense.test.js +39 -1
  43. package/package.json +1 -1
@@ -24,6 +24,7 @@ export interface HandlerConfig {
24
24
  source: string;
25
25
  destination: string;
26
26
  permanent?: boolean;
27
+ basePath?: boolean;
27
28
  }>;
28
29
  rewrites: Array<{
29
30
  source: string;
@@ -186,6 +186,9 @@ export function createKrateHandler(options) {
186
186
  const trustProxy = options.trustProxy !== undefined ? options.trustProxy : cfg.trustProxy === undefined ? null : cfg.trustProxy;
187
187
  const platform = PLATFORMS[target];
188
188
  const basePath = cfg.basePath || "";
189
+ // Server-rendered <Link>s read the base path from here, as in the browser.
190
+ if (basePath)
191
+ globalThis.__KRATE_CFG__ = { basePath };
189
192
  const hashed = new Set(data.hashedAssets);
190
193
  const staticOnly = new Set(data.staticOnlyRoutes.map(normalizeRoutePattern));
191
194
  const sha256Hex = options.sha256Hex || portableSha256Hex;
@@ -881,14 +884,33 @@ export function createKrateHandler(options) {
881
884
  return new Response(body, { status: 200, headers: rs.res });
882
885
  }
883
886
  // Redirects and rewrites
884
- async function redirectRewriteHandler(rs) {
885
- const p = rs.path;
886
- for (const rd of cfg.redirects) {
887
+ // Under a base path, basePath: false rules match the full path before the
888
+ // base is stripped (see handle) and stay out of this list.
889
+ const insideRedirects = basePath ? cfg.redirects.filter((rd) => rd.basePath !== false) : cfg.redirects;
890
+ const outsideRedirects = basePath ? cfg.redirects.filter((rd) => rd.basePath === false) : [];
891
+ function configRedirect(rs, p, rules) {
892
+ for (const rd of rules) {
887
893
  if (matchRedirect(p, rd.source)) {
888
894
  const dest = rewriteDestination(p, rd.source, rd.destination);
889
895
  return goRedirect(dest, p, rs.method, rd.permanent ? 301 : 302, rs.res);
890
896
  }
891
897
  }
898
+ return null;
899
+ }
900
+ /** Prefixes a root-relative Location from inside the base path. */
901
+ function withBaseLocation(res) {
902
+ const loc = res.headers.get("location");
903
+ if (!loc || !loc.startsWith("/") || loc.startsWith("//"))
904
+ return res;
905
+ const headers = new Headers(res.headers);
906
+ headers.set("location", basePath + loc);
907
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
908
+ }
909
+ async function redirectRewriteHandler(rs) {
910
+ const p = rs.path;
911
+ const redirected = configRedirect(rs, p, insideRedirects);
912
+ if (redirected)
913
+ return redirected;
892
914
  for (const rw of cfg.rewrites) {
893
915
  if (matchRedirect(p, rw.source)) {
894
916
  const rewritten = rewriteDestination(p, rw.source, rw.destination);
@@ -1797,9 +1819,17 @@ export function createKrateHandler(options) {
1797
1819
  };
1798
1820
  try {
1799
1821
  // Mount under the base path: requests outside it redirect (GET/HEAD) or 404.
1822
+ // The app then sees base-less paths, so a root-relative Location it
1823
+ // answers with gets the base on the way out.
1824
+ let mounted = false;
1800
1825
  if (basePath) {
1801
1826
  const p = rs.path;
1802
1827
  if (!(p.startsWith("/__krate/") || p === "/healthz" || p === "/readyz")) {
1828
+ const outside = configRedirect(rs, p, outsideRedirects);
1829
+ if (outside) {
1830
+ applySecurityAndHeaders(rs);
1831
+ return outside;
1832
+ }
1803
1833
  if (p === basePath || p === basePath + "/")
1804
1834
  rs.path = "/";
1805
1835
  else if (p.startsWith(basePath + "/"))
@@ -1810,14 +1840,18 @@ export function createKrateHandler(options) {
1810
1840
  return goRedirect(basePath + (p.startsWith("/") ? p : "/" + p), p, rs.method, 307, rs.res);
1811
1841
  return notFoundText(rs);
1812
1842
  }
1843
+ mounted = true;
1844
+ if (rs.rawPath.startsWith(basePath))
1845
+ rs.rawPath = rs.rawPath.slice(basePath.length) || "/";
1813
1846
  }
1814
1847
  }
1815
1848
  applySecurityAndHeaders(rs);
1816
1849
  const preflight = applyCORS(rs);
1817
1850
  if (preflight)
1818
- return preflight;
1851
+ return mounted ? withBaseLocation(preflight) : preflight;
1819
1852
  await sleepMicrotask();
1820
- return await mux(rs);
1853
+ const res = await mux(rs);
1854
+ return mounted ? withBaseLocation(res) : res;
1821
1855
  }
1822
1856
  catch (err) {
1823
1857
  console.error(`[krate] panic recovered: ${rs.method} ${rs.path}: ${(err && err.stack) || err}`);
@@ -533,3 +533,49 @@ describe("middleware exports", () => {
533
533
  error.mockRestore();
534
534
  });
535
535
  });
536
+ describe("redirects under a base path", () => {
537
+ const based = {
538
+ ...config,
539
+ basePath: "/docs",
540
+ redirects: [
541
+ { source: "/old", destination: "/new", permanent: true },
542
+ { source: "/outside", destination: "/elsewhere", basePath: false },
543
+ { source: "/docs/gone", destination: "https://other.example/", basePath: false },
544
+ ],
545
+ };
546
+ const handler = createKrateHandler({
547
+ target: "node",
548
+ data: data({ config: based, apiRoutes: ["hello", "items/[id]", "go"] }),
549
+ modules: {
550
+ ...modules,
551
+ api: { ...modules.api, go: { GET: () => new Response(null, { status: 302, headers: { location: "/login?next=1" } }) } },
552
+ },
553
+ });
554
+ const get = (path) => handler(new Request("http://localhost" + path, { redirect: "manual" }));
555
+ it("puts config redirect source and destination under the base", async () => {
556
+ const r = await get("/docs/old");
557
+ expect(r.status).toBe(301);
558
+ expect(r.headers.get("location")).toBe("/docs/new");
559
+ });
560
+ it("adds the base to a root-relative Location from a route handler", async () => {
561
+ const r = await get("/docs/api/go");
562
+ expect(r.status).toBe(302);
563
+ expect(r.headers.get("location")).toBe("/docs/login?next=1");
564
+ });
565
+ it("matches basePath: false rules on the full path and sends them as written", async () => {
566
+ const out = await get("/outside");
567
+ expect(out.status).toBe(302);
568
+ expect(out.headers.get("location")).toBe("/elsewhere");
569
+ const gone = await get("/docs/gone");
570
+ expect(gone.headers.get("location")).toBe("https://other.example/");
571
+ });
572
+ it("does not double the base on the path-cleaning redirect", async () => {
573
+ const r = await get("/docs//new");
574
+ expect(r.headers.get("location")).toBe("/docs/new");
575
+ });
576
+ it("keeps the canonical slash redirect relative", async () => {
577
+ const r = await get("/docs/live");
578
+ expect(r.status).toBe(301);
579
+ expect(r.headers.get("location")).toBe("./live/");
580
+ });
581
+ });
package/dist/server.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // @krate/runtime/server - Server-side rendering runtime
2
2
  // Provides the same API as the client runtime but renders to HTML strings.
3
3
  import { ATTR_ALIASES } from './htmlspec-attributes.js';
4
+ import { withBase } from './base-path.js';
4
5
  import { highlight as highlightCode, trimSpace } from './highlight.js';
5
6
  export { getActionContext, headers, cookies, redirect } from './action-context.js';
6
7
  export { revalidatePath, revalidateTag, unstable_cache, unstable_noStore } from './cache.js';
@@ -488,7 +489,7 @@ export function Link(props) {
488
489
  const { href = "", prefetch, replace, scroll, children, ...rest } = props;
489
490
  const attrs = [];
490
491
  if (href)
491
- attrs.push(`href="${escapeHTML(href)}"`);
492
+ attrs.push(`href="${escapeHTML(withBase(href))}"`);
492
493
  const external = /^(https?:|mailto:|tel:|#|javascript:)/.test(href) ||
493
494
  href.startsWith("//") ||
494
495
  rest.target === "_blank" ||
package/dist/signal.js CHANGED
@@ -106,7 +106,7 @@ export function krateDisposeOwner(owner) {
106
106
  ownerEffects.delete(owner);
107
107
  if (effects) {
108
108
  for (const effect of effects) {
109
- disposeEffect(effect);
109
+ disposeEffectQuietly(effect);
110
110
  allEffects.delete(effect);
111
111
  }
112
112
  }
@@ -341,6 +341,31 @@ function drainAfterQueue() {
341
341
  export function sameValue(a, b) {
342
342
  return Object.is(a, b);
343
343
  }
344
+ /**
345
+ * Runs every cleanup in order even when one throws, so a failing cleanup
346
+ * cannot strand the listeners and timers registered after it; the first error
347
+ * is rethrown once all have run, the others are logged.
348
+ */
349
+ function runCleanups(list) {
350
+ let failed = false;
351
+ let first;
352
+ for (const cleanup of list.splice(0)) {
353
+ try {
354
+ cleanup();
355
+ }
356
+ catch (err) {
357
+ if (!failed) {
358
+ failed = true;
359
+ first = err;
360
+ }
361
+ else if (typeof console !== 'undefined') {
362
+ console.error(err);
363
+ }
364
+ }
365
+ }
366
+ if (failed)
367
+ throw first;
368
+ }
344
369
  function disposeEffect(effect) {
345
370
  if (!effect.disposed) {
346
371
  effect.disposed = true;
@@ -352,10 +377,17 @@ function disposeEffect(effect) {
352
377
  set.delete(effect);
353
378
  }
354
379
  effect.sources.clear();
355
- for (const cleanup of effect.cleanups) {
356
- cleanup();
357
- }
358
- effect.cleanups.length = 0;
380
+ runCleanups(effect.cleanups);
381
+ }
382
+ }
383
+ /** Teardown disposal: a failing cleanup is logged and never stops the sweep. */
384
+ function disposeEffectQuietly(effect) {
385
+ try {
386
+ disposeEffect(effect);
387
+ }
388
+ catch (err) {
389
+ if (typeof console !== 'undefined')
390
+ console.error(err);
359
391
  }
360
392
  }
361
393
  /**
@@ -393,13 +425,15 @@ function disposeMatching(gone, pageTeardown) {
393
425
  try {
394
426
  hook(gone);
395
427
  }
396
- catch {
428
+ catch (err) {
397
429
  // Unmount errors must not prevent the rest of the teardown.
430
+ if (typeof console !== 'undefined')
431
+ console.error(err);
398
432
  }
399
433
  }
400
434
  for (const effect of Array.from(allEffects)) {
401
435
  if (gone(effect.scope)) {
402
- disposeEffect(effect);
436
+ disposeEffectQuietly(effect);
403
437
  allEffects.delete(effect);
404
438
  }
405
439
  }
@@ -447,12 +481,14 @@ export function disposeAll() {
447
481
  try {
448
482
  hook(null);
449
483
  }
450
- catch {
484
+ catch (err) {
451
485
  // Unmount errors must not prevent the rest of the teardown.
486
+ if (typeof console !== 'undefined')
487
+ console.error(err);
452
488
  }
453
489
  }
454
490
  for (const effect of allEffects) {
455
- disposeEffect(effect);
491
+ disposeEffectQuietly(effect);
456
492
  }
457
493
  allEffects.clear();
458
494
  for (const cleanup of rootCleanups) {
@@ -1053,9 +1089,7 @@ function runEffect(effect) {
1053
1089
  snapshotEpoch = null;
1054
1090
  try {
1055
1091
  // Run cleanups from previous execution
1056
- for (const cleanup of effect.cleanups.splice(0)) {
1057
- cleanup();
1058
- }
1092
+ runCleanups(effect.cleanups);
1059
1093
  // Re-track from scratch so a dependency the last run did not read stops
1060
1094
  // re-running the effect.
1061
1095
  for (const set of effect.sources) {
@@ -1234,8 +1268,7 @@ export function createMemo(fn) {
1234
1268
  const node = newEffectState(() => { });
1235
1269
  allEffects.add(node);
1236
1270
  const recompute = () => {
1237
- for (const cleanup of node.cleanups.splice(0))
1238
- cleanup();
1271
+ runCleanups(node.cleanups);
1239
1272
  for (const source of node.sources)
1240
1273
  source.delete(node);
1241
1274
  node.sources.clear();
@@ -140,6 +140,24 @@ describe('hydration bootstrap', () => {
140
140
  await tick();
141
141
  expect(tbody.textContent).toBe('off7');
142
142
  });
143
+ it('renders bigint, and primitives inside arrays, as text in a content slot', async () => {
144
+ document.body.innerHTML = '<div id="root"><p><!--k:v-->0<!--/k:v--></p></div>';
145
+ new Function(loadBootstrap())();
146
+ const w = window;
147
+ const [val, setVal] = createSignal(5n / 2n);
148
+ w.kbindContent('v', () => val());
149
+ const p = document.querySelector('p');
150
+ expect(w.__krateErrs).toEqual([]);
151
+ await tick();
152
+ expect(p.textContent).toBe('2');
153
+ setVal(['a', 3, 7n, null, false]);
154
+ await tick();
155
+ expect(w.__krateErrs).toEqual([]);
156
+ expect(p.textContent).toBe('a37');
157
+ setVal(12345678901234567890n);
158
+ await tick();
159
+ expect(p.textContent).toBe('12345678901234567890');
160
+ });
143
161
  it('finds nodes of a branch swapped out before its binding ran', async () => {
144
162
  document.body.innerHTML =
145
163
  '<div id="root"><p><!--k:c--><button data-k="k:b">ssr</button><!--/k:c--></p>' +
package/dist/suspense.js CHANGED
@@ -23,7 +23,7 @@
23
23
  * content keeps showing it when a transition update suspends it, and the
24
24
  * transition stays pending until that work and any async action settle.
25
25
  */
26
- import { createSignal, createEffect, onCleanup, krateGetOwner, krateSetOwner } from './signal.js';
26
+ import { createSignal, createEffect, onCleanup, krateGetOwner, krateSetOwner, krateOnDispose, krateCurrentScope } from './signal.js';
27
27
  const tracked = new WeakSet();
28
28
  export function isThenable(value) {
29
29
  return (value != null &&
@@ -369,6 +369,9 @@ class BoundaryController {
369
369
  this.pending = new Set();
370
370
  this.holds = 0;
371
371
  this.scheduled = false;
372
+ /** Route scope the boundary belongs to, and whether its page is gone. */
373
+ this.route = krateCurrentScope();
374
+ this.dead = false;
372
375
  this.throttle = null;
373
376
  this.id = id;
374
377
  this.anchor = anchor;
@@ -420,6 +423,10 @@ class BoundaryController {
420
423
  });
421
424
  }
422
425
  update() {
426
+ // A boundary of a page that was navigated away from must not touch the DOM
427
+ // or the slot state of the page that replaced it.
428
+ if (this.dead)
429
+ return;
423
430
  const want = this.pending.size === 0 && this.holds === 0;
424
431
  if (want === this.content)
425
432
  return;
@@ -609,6 +616,23 @@ export function registerBoundary(boundary) {
609
616
  export function resetBoundaries() {
610
617
  boundaries.clear();
611
618
  }
619
+ // Suspended component runs and compiled boundaries are retried when their
620
+ // promise settles, which can be after the user left the page: a retry would
621
+ // mount the effects of a page that is gone. A page teardown (soft navigation)
622
+ // marks the ones it removed dead.
623
+ const liveRuns = new Set();
624
+ krateOnDispose((gone) => {
625
+ for (const run of liveRuns) {
626
+ if (gone === null || gone(run.route))
627
+ run.dead = true;
628
+ }
629
+ for (const [id, b] of Array.from(boundaries)) {
630
+ if (b instanceof BoundaryController && (gone === null || gone(b.route))) {
631
+ b.dead = true;
632
+ boundaries.delete(id);
633
+ }
634
+ }
635
+ });
612
636
  /**
613
637
  * Suspends `boundary` on `t`. Inside a transition an already revealed
614
638
  * boundary keeps its content and the transition waits instead; with no
@@ -634,10 +658,15 @@ export function currentBoundary() {
634
658
  */
635
659
  export function __krateBoundary(id, fn) {
636
660
  const boundary = id ? getBoundary(id) : null;
637
- const state = { boundary, scope: { list: [], i: 0 }, disposers: [] };
661
+ const state = { boundary, scope: { list: [], i: 0 }, disposers: [], route: krateCurrentScope(), dead: false };
638
662
  const errOwner = errorOwner();
639
663
  boundary?.hold();
640
664
  const attempt = () => {
665
+ // The page was left while the promise was pending: do not mount it now.
666
+ if (state.dead) {
667
+ liveRuns.delete(state);
668
+ return;
669
+ }
641
670
  state.scope.i = 0;
642
671
  const prev = currentRun;
643
672
  currentRun = state;
@@ -649,6 +678,7 @@ export function __krateBoundary(id, fn) {
649
678
  withReadScope(state.scope, fn);
650
679
  currentRun = prev;
651
680
  krateSetOwner(owner);
681
+ liveRuns.delete(state);
652
682
  boundary?.release();
653
683
  }
654
684
  catch (error) {
@@ -657,9 +687,11 @@ export function __krateBoundary(id, fn) {
657
687
  for (const dispose of state.disposers.splice(0))
658
688
  dispose();
659
689
  if (isSuspenseSignal(error)) {
690
+ liveRuns.add(state);
660
691
  error.thenable.then(attempt, attempt);
661
692
  return;
662
693
  }
694
+ liveRuns.delete(state);
663
695
  boundary?.release();
664
696
  reportSuspenseError(error, boundary, errOwner);
665
697
  }
@@ -1,5 +1,5 @@
1
1
  import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
- import { createSignal, createEffect } from './signal.js';
2
+ import { createSignal, createEffect, disposeAll, krateDisposeExcept, krateEnterScope, krateLeaveScope } from './signal.js';
3
3
  import { createContext } from './context.js';
4
4
  import { createResource } from './resource.js';
5
5
  import { __krateBoundary, __krateLazy, __krateLazyPayload, __krateRead, __krateTransitionStarter, __krateUse, createBoundary, createDeferredValue, createExternalStore, getBoundary, isInTransition, readValue, registerBoundary, resetBoundaries, runAsyncTransition, setFallbackThrottle, setLazyChunkImporter, setSuspenseErrorHandler, startTransition, trackThenable, isSuspenseSignal, } from './suspense.js';
@@ -516,3 +516,41 @@ function installFindSlot(html) {
516
516
  return null;
517
517
  };
518
518
  }
519
+ describe('a page left while a boundary is suspended', () => {
520
+ it('does not retry the suspended component when its promise settles', async () => {
521
+ const { b, shown } = testBoundary('gone', false);
522
+ const d = deferred();
523
+ let runs = 0;
524
+ let effects = 0;
525
+ runIn(b, () => {
526
+ runs++;
527
+ __krateUse(() => __krateRead(d.promise));
528
+ createEffect(() => void effects++);
529
+ });
530
+ expect(runs).toBe(1);
531
+ disposeAll();
532
+ d.resolve('late');
533
+ await flush();
534
+ // Neither the component body (with its effects) nor the reveal ran.
535
+ expect(runs).toBe(1);
536
+ expect(effects).toBe(0);
537
+ expect(shown).toEqual([]);
538
+ });
539
+ it('still retries after a soft navigation that kept the layout owning the run', async () => {
540
+ krateEnterScope('_lkeep_');
541
+ const { b, shown } = testBoundary('kept', false);
542
+ const d = deferred();
543
+ let runs = 0;
544
+ runIn(b, () => {
545
+ runs++;
546
+ __krateUse(() => __krateRead(d.promise));
547
+ });
548
+ krateLeaveScope();
549
+ krateDisposeExcept(['_lkeep_']);
550
+ d.resolve('ok');
551
+ await flush();
552
+ expect(runs).toBe(2);
553
+ expect(shown).toEqual(['content']);
554
+ disposeAll();
555
+ });
556
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@krate/runtime",
3
- "version": "0.5.0-beta.3",
3
+ "version": "0.5.0-rc.2",
4
4
  "description": "Client-side runtime for Krate - signals, hydration, SPA router, resources, and context.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",