@krate/runtime 0.5.0-beta.2 → 0.5.0-rc.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.
@@ -522,26 +522,38 @@ class KrateDev {
522
522
  }
523
523
  }
524
524
  captureRuntimeErrors() {
525
- window.addEventListener('error', (e) => {
526
- const stack = e.error?.stack || '';
527
- const message = e.message || 'Unknown error';
528
- this.report({
529
- message,
530
- stack,
531
- url: e.filename,
532
- line: e.lineno,
533
- col: e.colno,
534
- kind: 'error',
535
- });
536
- this.addRuntime('Runtime Error', message, stack);
537
- });
538
- window.addEventListener('unhandledrejection', (e) => {
539
- const reason = e.reason;
540
- const message = reason instanceof Error ? reason.message : String(reason);
541
- const stack = reason instanceof Error ? reason.stack : '';
542
- this.report({ message, stack, url: location.href, kind: 'unhandledrejection' });
543
- this.addRuntime('Unhandled Promise Rejection', message, stack);
525
+ window.addEventListener('error', (e) => this.onError(e));
526
+ window.addEventListener('unhandledrejection', (e) => this.onRejection(e));
527
+ // This bundle loads after the page script, so the page's first render ran
528
+ // before these listeners existed. The head buffers what happened until now.
529
+ const early = window.__KRATE_EARLY_ERRORS__;
530
+ window.__KRATE_EARLY_ERRORS__ = undefined;
531
+ for (const e of early ?? []) {
532
+ if (e.type === 'error')
533
+ this.onError(e);
534
+ else
535
+ this.onRejection(e);
536
+ }
537
+ }
538
+ onError(e) {
539
+ const stack = e.error?.stack || '';
540
+ const message = e.message || 'Unknown error';
541
+ this.report({
542
+ message,
543
+ stack,
544
+ url: e.filename,
545
+ line: e.lineno,
546
+ col: e.colno,
547
+ kind: 'error',
544
548
  });
549
+ this.addRuntime('Runtime Error', message, stack);
550
+ }
551
+ onRejection(e) {
552
+ const reason = e.reason;
553
+ const message = reason instanceof Error ? reason.message : String(reason);
554
+ const stack = reason instanceof Error ? reason.stack : '';
555
+ this.report({ message, stack, url: location.href, kind: 'unhandledrejection' });
556
+ this.addRuntime('Unhandled Promise Rejection', message, stack);
545
557
  }
546
558
  report(payload) {
547
559
  const key = payload.message + '|' + (payload.stack || '');
@@ -16,12 +16,20 @@ class FakeEventSource {
16
16
  }
17
17
  FakeEventSource.last = null;
18
18
  let overlay;
19
+ const beacons = [];
19
20
  // File-level setup: globals must exist BEFORE the overlay module auto-inits on
20
21
  // import, and the export is captured from the same module instance.
21
22
  beforeAll(async () => {
22
23
  globalThis.EventSource = FakeEventSource;
23
24
  // Error reports must not reach the (absent) dev server from the test.
24
- navigator.sendBeacon = () => true;
25
+ navigator.sendBeacon = (_url, body) => {
26
+ beacons.push(body);
27
+ return true;
28
+ };
29
+ // What the inline head script buffers before this bundle loads.
30
+ window.__KRATE_EARLY_ERRORS__ = [
31
+ new ErrorEvent('error', { message: 'thrown during first render', error: new Error('thrown during first render') }),
32
+ ];
25
33
  window.__KRATE_DEV__ = {
26
34
  sse: '/__krate/hotreload',
27
35
  errors: '/__krate/client-error',
@@ -36,6 +44,11 @@ function devRoot() {
36
44
  return host ? host.shadowRoot : null;
37
45
  }
38
46
  describe('dev-overlay', () => {
47
+ it('reports errors thrown before the bundle loaded', async () => {
48
+ const sent = await Promise.all(beacons.map((b) => b.text()));
49
+ expect(sent.some((t) => t.includes('thrown during first render'))).toBe(true);
50
+ expect(window.__KRATE_EARLY_ERRORS__).toBeUndefined();
51
+ });
39
52
  it('mounts a shadow-root host with a toolbar', () => {
40
53
  const shadow = devRoot();
41
54
  expect(shadow).toBeTruthy();
package/dist/dom.d.ts CHANGED
@@ -68,6 +68,10 @@ export interface KrateVNode {
68
68
  tag: string;
69
69
  props: Record<string, unknown> | null;
70
70
  children: unknown[];
71
+ /** Effect owner current when h() ran: the component the element belongs to. */
72
+ o?: unknown;
73
+ /** Components this element is the root of; unmounted with the element. */
74
+ u?: unknown[];
71
75
  }
72
76
  /** A value that knows how to mount itself or adopt server-rendered DOM. */
73
77
  export interface KrateAdoptable {
package/dist/dom.js CHANGED
@@ -1,4 +1,4 @@
1
- import { createEffect, onCleanup } from './signal.js';
1
+ import { createEffect, onCleanup, krateGetOwner, krateSetOwner } from './signal.js';
2
2
  import { krateWithOwner, krateUnmount } from './effects.js';
3
3
  import { krateSanitizeAttr } from './slots.js';
4
4
  import { krateOn, krateControl, krateSetControl } from './events.js';
@@ -37,6 +37,16 @@ function trackOwner(value, owner) {
37
37
  for (const v of value)
38
38
  trackOwner(v, owner);
39
39
  }
40
+ else if (isVNode(value)) {
41
+ // Not mounted yet: the unmount is registered on the element it becomes.
42
+ (value.u || (value.u = [])).push(owner);
43
+ }
44
+ }
45
+ // Registers the unmounts of the components a vnode is the root of.
46
+ function trackVNodeOwners(v, el) {
47
+ if (v.u)
48
+ for (const o of v.u)
49
+ trackEffect(el, () => krateUnmount(o));
40
50
  }
41
51
  /**
42
52
  * Binds the ref returned by `get` to `el` (hydration `ref={...}`). The ref is
@@ -126,7 +136,7 @@ export function insert(parent, value, startMarker) {
126
136
  function insertBefore(parent, value, before) {
127
137
  if (value == null || value === false || value === true)
128
138
  return;
129
- if (typeof value === 'string' || typeof value === 'number') {
139
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'bigint') {
130
140
  parent.insertBefore(document.createTextNode(String(value)), before);
131
141
  }
132
142
  else if (value instanceof Node) {
@@ -265,7 +275,9 @@ function setAttr(el, key, value) {
265
275
  // aria-* and data-* stringify booleans (aria-selected={false} renders
266
276
  // "false"), as in React.
267
277
  const stringly = /^(aria|data)-/.test(name);
268
- if (value === null || value === undefined || (value === false && !stringly)) {
278
+ // A function (or symbol) is not an attribute value: React drops it rather
279
+ // than writing its source, e.g. a signal getter inside a spread object.
280
+ if (value === null || value === undefined || typeof value === 'function' || typeof value === 'symbol' || (value === false && !stringly)) {
269
281
  if (el.hasAttribute(name))
270
282
  el.removeAttribute(name);
271
283
  }
@@ -327,6 +339,20 @@ export function krateSpread(el, get) {
327
339
  spreadKeys.set(el, next);
328
340
  }));
329
341
  }
342
+ // Runs fn with the vnode's component as the current effect owner, so the
343
+ // effects and components created when the vnode is adopted or materialized
344
+ // (later, outside the component's own call) are its children.
345
+ function withOwner(owner, fn) {
346
+ if (owner === undefined)
347
+ return fn();
348
+ const prev = krateSetOwner(owner);
349
+ try {
350
+ return fn();
351
+ }
352
+ finally {
353
+ krateSetOwner(prev);
354
+ }
355
+ }
330
356
  let vnodeDepth = 0;
331
357
  /** Evaluate `fn` with h() producing virtual nodes (see KrateVNode). */
332
358
  export function withVNodes(fn) {
@@ -402,7 +428,9 @@ function buildElement(tag, props, children) {
402
428
  return el;
403
429
  }
404
430
  function materialize(v) {
405
- return withDOM(() => buildElement(v.tag, v.props, v.children));
431
+ const el = withOwner(v.o, () => withDOM(() => buildElement(v.tag, v.props, v.children)));
432
+ trackVNodeOwners(v, el);
433
+ return el;
406
434
  }
407
435
  function isTextLike(v) {
408
436
  return v == null || typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || typeof v === 'bigint';
@@ -558,14 +586,17 @@ function adoptElement(v, c) {
558
586
  if (n && n.nodeType === 1 && n.localName.toLowerCase() === v.tag.toLowerCase()) {
559
587
  c.next = n.nextSibling;
560
588
  const el = n;
561
- if (v.props)
562
- applyProps(el, v.props);
563
- if (!v.props || !v.props.dangerouslySetInnerHTML) {
564
- const inner = { parent: el, next: el.firstChild };
565
- for (const child of v.children)
566
- adoptValue(child, inner);
567
- removeRest(inner, null);
568
- }
589
+ trackVNodeOwners(v, el);
590
+ withOwner(v.o, () => {
591
+ if (v.props)
592
+ applyProps(el, v.props);
593
+ if (!v.props || !v.props.dangerouslySetInnerHTML) {
594
+ const inner = { parent: el, next: el.firstChild };
595
+ for (const child of v.children)
596
+ adoptValue(child, inner);
597
+ removeRest(inner, null);
598
+ }
599
+ });
569
600
  return;
570
601
  }
571
602
  insertAt(c, materialize(v));
@@ -633,7 +664,7 @@ export function h(tag, props, ...children) {
633
664
  return value;
634
665
  }
635
666
  if (vnodeDepth > 0) {
636
- return { __kv: 1, tag, props, children };
667
+ return { __kv: 1, tag, props, children, o: krateGetOwner() };
637
668
  }
638
669
  return buildElement(tag, props, children);
639
670
  }
package/dist/dom.test.js CHANGED
@@ -28,4 +28,12 @@ describe('insert', () => {
28
28
  expect(parent.textContent).toBe('new');
29
29
  expect(parent.textContent.includes('old')).toBe(false);
30
30
  });
31
+ it('inserts a bigint as text', () => {
32
+ const parent = document.createElement('div');
33
+ const start = document.createComment('k');
34
+ const end = document.createComment('k');
35
+ parent.append(start, document.createTextNode('old'), end);
36
+ insert(parent, [1n, 'a', 20n], start);
37
+ expect(parent.textContent).toBe('1a20');
38
+ });
31
39
  });
@@ -1,5 +1,5 @@
1
1
  import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
2
- import { createSignal, createEffect, disposeAll, krateFlushSync, krateOnSettle, setOwnerHooks, } from './signal';
2
+ import { createSignal, createEffect, onCleanup, disposeAll, krateFlushSync, krateOnSettle, setOwnerHooks, } from './signal';
3
3
  // Settle hooks cannot be unregistered; this one counts flushes for the whole file.
4
4
  let settleRuns = 0;
5
5
  let settleThrows = false;
@@ -161,3 +161,39 @@ describe('a throwing effect does not strand the others', () => {
161
161
  expect(seen).toEqual([0, 5]);
162
162
  });
163
163
  });
164
+ describe('a throwing cleanup does not strand the others', () => {
165
+ beforeEach(() => disposeAll());
166
+ afterEach(() => vi.restoreAllMocks());
167
+ it('runs the remaining cleanups of an effect that re-runs', () => {
168
+ const [a, setA] = createSignal(0);
169
+ const log = [];
170
+ createEffect(() => {
171
+ a();
172
+ onCleanup(() => {
173
+ log.push('first');
174
+ throw new Error('cleanup boom');
175
+ });
176
+ onCleanup(() => log.push('second'));
177
+ });
178
+ setA(1);
179
+ expect(() => krateFlushSync()).toThrow('cleanup boom');
180
+ expect(log).toEqual(['first', 'second']);
181
+ });
182
+ it('keeps tearing down the page when a cleanup throws', () => {
183
+ const logged = vi.spyOn(console, 'error').mockImplementation(() => { });
184
+ const log = [];
185
+ createEffect(() => {
186
+ onCleanup(() => {
187
+ log.push('a');
188
+ throw new Error('teardown boom');
189
+ });
190
+ onCleanup(() => log.push('a2'));
191
+ });
192
+ createEffect(() => {
193
+ onCleanup(() => log.push('b'));
194
+ });
195
+ expect(() => disposeAll()).not.toThrow();
196
+ expect(log).toEqual(['a', 'a2', 'b']);
197
+ expect(logged).toHaveBeenCalledTimes(1);
198
+ });
199
+ });
package/dist/effects.js CHANGED
@@ -169,7 +169,7 @@ function disposeTree(owner, active, passive) {
169
169
  continue;
170
170
  }
171
171
  if (hook.phase === 'passive') {
172
- const c = takeCleanup(hook);
172
+ const c = takePassiveCleanup(hook);
173
173
  if (c)
174
174
  passive.push(c);
175
175
  }
@@ -320,7 +320,7 @@ function hideTree(owner, passive) {
320
320
  for (const hook of owner.hooks) {
321
321
  dirty.delete(hook);
322
322
  if (hook.phase === 'passive') {
323
- const c = takeCleanup(hook);
323
+ const c = takePassiveCleanup(hook);
324
324
  if (c)
325
325
  passive.push(c);
326
326
  }
@@ -485,6 +485,12 @@ function runCleanup(hook) {
485
485
  if (c)
486
486
  runGuarded(c, hook.owner);
487
487
  }
488
+ // A passive cleanup detached for the passive phase; its errors go to the
489
+ // owner's error boundary like a layout cleanup's.
490
+ function takePassiveCleanup(hook) {
491
+ const c = takeCleanup(hook);
492
+ return c ? () => runGuarded(c, hook.owner) : null;
493
+ }
488
494
  function pruneSnapshots() {
489
495
  let min = krateEpoch();
490
496
  for (const e of liveEpochs.keys())
@@ -571,7 +577,7 @@ function commit() {
571
577
  for (const h of hooks) {
572
578
  if (h.phase !== 'passive')
573
579
  continue;
574
- const c = takeCleanup(h);
580
+ const c = takePassiveCleanup(h);
575
581
  if (c)
576
582
  passiveCleanups.push(c);
577
583
  passiveSetups.push([h, at]);
@@ -600,6 +606,17 @@ export function flushPassive() {
600
606
  clearTimeout(passiveTimer);
601
607
  passiveTimer = null;
602
608
  }
609
+ let failed = false;
610
+ let first;
611
+ const remember = (err) => {
612
+ if (!failed) {
613
+ failed = true;
614
+ first = err;
615
+ }
616
+ else if (typeof console !== 'undefined') {
617
+ console.error(err);
618
+ }
619
+ };
603
620
  // Loop: a passive cleanup or setup may unmount components, queueing more.
604
621
  while (passiveCleanups.length || passiveSetups.length) {
605
622
  const cleanups = passiveCleanups;
@@ -607,18 +624,34 @@ export function flushPassive() {
607
624
  passiveCleanups = [];
608
625
  passiveSetups = [];
609
626
  krateCommitting(true);
627
+ // An error with no boundary to take it must not drop the cleanups and
628
+ // setups queued behind it: run them all, then rethrow the first.
610
629
  try {
611
- for (const c of cleanups)
612
- c();
630
+ for (const c of cleanups) {
631
+ try {
632
+ c();
633
+ }
634
+ catch (err) {
635
+ remember(err);
636
+ }
637
+ }
613
638
  for (const [h, at] of setups) {
614
- if (isActive(h.owner))
639
+ if (!isActive(h.owner))
640
+ continue;
641
+ try {
615
642
  runSetup(h, at);
643
+ }
644
+ catch (err) {
645
+ remember(err);
646
+ }
616
647
  }
617
648
  }
618
649
  finally {
619
650
  krateCommitting(false);
620
651
  }
621
652
  }
653
+ if (failed)
654
+ throw first;
622
655
  }
623
656
  /**
624
657
  * React's useMemo with a dependency array: the getter recomputes
@@ -712,7 +745,7 @@ function unmountExcept(gone) {
712
745
  hook.stop();
713
746
  dirty.delete(hook);
714
747
  if (hook.phase === 'passive') {
715
- const c = takeCleanup(hook);
748
+ const c = takePassiveCleanup(hook);
716
749
  if (c)
717
750
  passive.push(c);
718
751
  }
@@ -764,7 +797,7 @@ function unmountAll(gone) {
764
797
  for (const hook of root.hooks) {
765
798
  hook.stop();
766
799
  if (hook.phase === 'passive') {
767
- const c = takeCleanup(hook);
800
+ const c = takePassiveCleanup(hook);
768
801
  if (c)
769
802
  passive.push(c);
770
803
  }
package/dist/events.d.ts CHANGED
@@ -26,6 +26,8 @@ export declare function krateSynthetic<E extends Event>(native: E, type?: string
26
26
  * to on it.
27
27
  */
28
28
  export declare function krateEventRoot(node: Node): void;
29
+ /** Runs fn with delegated and direct handlers silenced (internal). */
30
+ export declare function krateMuteEvents<T>(fn: () => T): T;
29
31
  /** Splits a React prop (`onClickCapture`) into its event name and phase. */
30
32
  export declare function krateEventName(prop: string): [name: string, capture: boolean];
31
33
  /**
package/dist/events.js CHANGED
@@ -187,7 +187,23 @@ function onRootCapture(native) {
187
187
  function onRootBubble(native) {
188
188
  dispatchRoot(native, false);
189
189
  }
190
+ // React turns its event system off while it commits: the blur and focus a
191
+ // browser fires when a focused node is moved or removed must not reach
192
+ // handlers. Keyed list updates run their DOM moves inside this.
193
+ let muted = 0;
194
+ /** Runs fn with delegated and direct handlers silenced (internal). */
195
+ export function krateMuteEvents(fn) {
196
+ muted++;
197
+ try {
198
+ return fn();
199
+ }
200
+ finally {
201
+ muted--;
202
+ }
203
+ }
190
204
  function dispatchRoot(native, capture) {
205
+ if (muted > 0)
206
+ return;
191
207
  // Several roots can be on the path (a portal inside the root); the first
192
208
  // listener to see the event handles the whole path.
193
209
  const flag = capture ? '__kdc' : '__kdb';
@@ -219,6 +235,8 @@ function onDirectCapture(native) {
219
235
  directDispatch(this, native, true);
220
236
  }
221
237
  function directDispatch(el, native, capture) {
238
+ if (muted > 0)
239
+ return;
222
240
  const m = el.__kh;
223
241
  const h = m && m[native.type + (capture ? '$' : '')];
224
242
  if (!h)