@pithyjs/core 0.1.0-beta.19 → 0.1.0-beta.20

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 (65) hide show
  1. package/README.md +13 -1
  2. package/dist/compile/binds/bindAfterProjection.d.ts.map +1 -1
  3. package/dist/compile/binds/bindAfterProjection.js +2 -0
  4. package/dist/compile/binds/bindAfterProjection.js.map +1 -1
  5. package/dist/compile/binds/bindClassDirectives.d.ts.map +1 -1
  6. package/dist/compile/binds/bindClassDirectives.js +2 -1
  7. package/dist/compile/binds/bindClassDirectives.js.map +1 -1
  8. package/dist/compile/binds/bindComponentsTags.d.ts.map +1 -1
  9. package/dist/compile/binds/bindComponentsTags.js +36 -21
  10. package/dist/compile/binds/bindComponentsTags.js.map +1 -1
  11. package/dist/compile/binds/bindErrorBoundary.d.ts +31 -0
  12. package/dist/compile/binds/bindErrorBoundary.d.ts.map +1 -1
  13. package/dist/compile/binds/bindErrorBoundary.js +110 -13
  14. package/dist/compile/binds/bindErrorBoundary.js.map +1 -1
  15. package/dist/compile/binds/bindTextInterpolations.d.ts.map +1 -1
  16. package/dist/compile/binds/bindTextInterpolations.js +7 -5
  17. package/dist/compile/binds/bindTextInterpolations.js.map +1 -1
  18. package/dist/compile/compileNodes.d.ts.map +1 -1
  19. package/dist/compile/compileNodes.js +8 -4
  20. package/dist/compile/compileNodes.js.map +1 -1
  21. package/dist/compile/compileTemplate.d.ts.map +1 -1
  22. package/dist/compile/compileTemplate.js +12 -8
  23. package/dist/compile/compileTemplate.js.map +1 -1
  24. package/dist/compile/contentProjection.d.ts +2 -2
  25. package/dist/compile/contentProjection.d.ts.map +1 -1
  26. package/dist/compile/contentProjection.js +22 -8
  27. package/dist/compile/contentProjection.js.map +1 -1
  28. package/dist/compile/evalDiagnostics.d.ts +7 -0
  29. package/dist/compile/evalDiagnostics.d.ts.map +1 -0
  30. package/dist/compile/evalDiagnostics.js +8 -0
  31. package/dist/compile/evalDiagnostics.js.map +1 -0
  32. package/dist/compile/forLoops/createLoopManager.d.ts.map +1 -1
  33. package/dist/compile/forLoops/createLoopManager.js +5 -0
  34. package/dist/compile/forLoops/createLoopManager.js.map +1 -1
  35. package/dist/compile/nodeExpando.d.ts +2 -0
  36. package/dist/compile/nodeExpando.d.ts.map +1 -1
  37. package/dist/compile/nodeExpando.js.map +1 -1
  38. package/dist/compile/renderBranch.d.ts.map +1 -1
  39. package/dist/compile/renderBranch.js +7 -2
  40. package/dist/compile/renderBranch.js.map +1 -1
  41. package/dist/compile/ssrCrashes.d.ts +64 -36
  42. package/dist/compile/ssrCrashes.d.ts.map +1 -1
  43. package/dist/compile/ssrCrashes.js +342 -37
  44. package/dist/compile/ssrCrashes.js.map +1 -1
  45. package/dist/runtime/applyBindings.d.ts.map +1 -1
  46. package/dist/runtime/applyBindings.js +13 -3
  47. package/dist/runtime/applyBindings.js.map +1 -1
  48. package/dist/runtime/bindings/applyComponent.d.ts.map +1 -1
  49. package/dist/runtime/bindings/applyComponent.js +19 -17
  50. package/dist/runtime/bindings/applyComponent.js.map +1 -1
  51. package/dist/runtime/bindings/applySimple.d.ts +7 -0
  52. package/dist/runtime/bindings/applySimple.d.ts.map +1 -1
  53. package/dist/runtime/bindings/applySimple.js +22 -10
  54. package/dist/runtime/bindings/applySimple.js.map +1 -1
  55. package/dist/runtime/bindings/applyStructural.d.ts.map +1 -1
  56. package/dist/runtime/bindings/applyStructural.js +115 -105
  57. package/dist/runtime/bindings/applyStructural.js.map +1 -1
  58. package/dist/runtime/bindings/index.d.ts +1 -1
  59. package/dist/runtime/bindings/index.d.ts.map +1 -1
  60. package/dist/runtime/bindings/index.js +1 -1
  61. package/dist/runtime/bindings/index.js.map +1 -1
  62. package/dist/types/globals.d.ts +6 -0
  63. package/dist/types/globals.d.ts.map +1 -1
  64. package/dist/types/globals.js.map +1 -1
  65. package/package.json +2 -2
@@ -6,9 +6,10 @@
6
6
  "risk": "high"
7
7
  }
8
8
  */
9
+ import { untrack } from '@pithyjs/signals';
9
10
  import { pithyGlobals } from '../types/globals.js';
10
11
  import { isSSRMode } from './ssrMode.js';
11
- import { setBoundaryError } from './binds/bindErrorBoundary.js';
12
+ import { boundaryContext, findParentBoundary, isInHiddenContent, registeredClosest, setBoundaryError, slotOwnerOf, } from './binds/bindErrorBoundary.js';
12
13
  /**
13
14
  * Crashes recorded during the current server render, keyed by the placeholder
14
15
  * element so a later binding pass over the same element can retract its own
@@ -49,26 +50,8 @@ function crashRegistry() {
49
50
  * `bindComponentTags`, `fragment.contains(el)` in `applyBindings`). It can
50
51
  * no longer contribute to the output, so any record for it is stale.
51
52
  *
52
- * Retraction matters because the JIT `@if` path really does attempt the same tag
53
- * twice, measured by counting component invocations:
54
- *
55
- * 1. `bindStructuralDirectives` runs first and `handleConditionalChain` binds
56
- * the chosen branch while it is still DETACHED, so `el.closest('[data-error]')`
57
- * finds nothing and the crash is recorded.
58
- * 2. The branch is inserted, and `bindTemplateDirectives` then reaches the
59
- * still-raw tag on the assembled tree, where the boundary is visible and
60
- * accepts — retracting via case 1 above.
61
- *
62
- * Case 3 exists because accepting is synchronous: it immediately hides the
63
- * boundary's content, so a SECOND crashing component in that branch is detached
64
- * before it can be retried, and its detached-pass record would otherwise stand
65
- * and fail a route whose fallback rendered correctly.
66
- *
67
53
  * Every one of these is mutation-tested; removing any of them turns a correct
68
54
  * render into a failed route, or a broken one into a silent success.
69
- *
70
- * AOT invokes `applyComponent` once per `pid` and never retries, which is why
71
- * the equivalent AOT boundary case behaves differently — see BUG-023.
72
55
  */
73
56
  /** @codexApi {"parent":"pithy.runtime.ssr-crashes","name":"clearSSRRenderCrash","stability":"internal","signature":"(el: Element) => void"} */
74
57
  export function clearSSRRenderCrash(el) {
@@ -106,6 +89,25 @@ function recordSSRRenderCrash(el, tag, error) {
106
89
  /** @codexApi {"parent":"pithy.runtime.ssr-crashes","name":"resetSSRRenderCrashes","stability":"stable","signature":"() => void"} */
107
90
  export function resetSSRRenderCrashes() {
108
91
  crashRegistry().clear();
92
+ const g = pithyGlobals();
93
+ g.__pithyAttributedCrashes = [];
94
+ g.__pithyRenderDepth = 0;
95
+ }
96
+ /**
97
+ * An element that left the tree being bound contributes nothing to the output:
98
+ * its recorded crash is stale, and an attributed one is only logged.
99
+ */
100
+ /** @codexApi {"parent":"pithy.runtime.ssr-crashes","name":"forgetCrash","stability":"internal","signature":"(el: Element) => void"} */
101
+ export function forgetCrash(el) {
102
+ clearSSRRenderCrash(el);
103
+ const crash = takeAttributedCrash(el);
104
+ if (crash)
105
+ logCrash(crash);
106
+ }
107
+ function takeAttributedCrash(el) {
108
+ const list = heldCrashes();
109
+ const at = list?.findIndex(crash => crash.el === el) ?? -1;
110
+ return at >= 0 ? list?.splice(at, 1)[0] : undefined;
109
111
  }
110
112
  /**
111
113
  * Return the crashes still recorded once the render has finished, and empty
@@ -118,26 +120,19 @@ export function resetSSRRenderCrashes() {
118
120
  * An earlier draft re-resolved each record's boundary here, dropping any crash
119
121
  * whose element had ended up inside an `@error-boundary`. That is unsound,
120
122
  * because a boundary *existing* above an element is not the same as that
121
- * boundary having *handled* the crash:
123
+ * boundary having *handled* the crash. A crash that a boundary rejected, or
124
+ * that ran where no boundary resolved, is placed under one afterwards just the
125
+ * same. Re-resolution dropped such a record: the boundary signal stayed null,
126
+ * its fallback never activated, the raw component tag shipped, and the build
127
+ * went green — the exact BUG-018 symptom, reintroduced by its own fix.
122
128
  *
123
- * - JIT never needed it. It does record a crash from the detached first
124
- * attempt, but the retry after insertion is caught by the boundary and
125
- * retracts that record itself (see `clearSSRRenderCrash`). By collect time
126
- * there is nothing left to re-resolve.
127
- * - AOT was actively broken by it. A branch factory binds its subtree while
128
- * detached, so `applyComponent`'s `el.closest('[data-error]')` finds
129
- * nothing and the boundary never receives the error — but the nodes are
130
- * then inserted *under* that boundary, so re-resolution saw one and
131
- * dropped the record. The boundary signal stayed null, its fallback never
132
- * activated, the raw component tag shipped, and the build went green: the
133
- * exact BUG-018 symptom, reintroduced by its own fix.
134
- *
135
- * That AOT boundary gap is real but predates this collector and is tracked
136
- * separately as BUG-023. Until it is fixed, such a crash fails its route, which
137
- * is the safe direction: a loud failure rather than silently truncated HTML.
129
+ * A crash in a branch, slot or component built detached is attributed to its
130
+ * boundary instead (`deferCrash`); whatever is still attributed here is
131
+ * recorded.
138
132
  */
139
133
  /** @codexApi {"parent":"pithy.runtime.ssr-crashes","name":"collectUnhandledSSRRenderCrashes","stability":"stable","signature":"() => SSRRenderCrash[]"} */
140
134
  export function collectUnhandledSSRRenderCrashes() {
135
+ resolveAttributedCrashes('collect');
141
136
  const registry = crashRegistry();
142
137
  const unhandled = [...registry.values()];
143
138
  registry.clear();
@@ -155,10 +150,19 @@ export function collectUnhandledSSRRenderCrashes() {
155
150
  * the boundary signal null, rendered no fallback, and failed the route, even
156
151
  * though the code called it "the same content loss as a crash".
157
152
  *
153
+ * With no `boundary`, a failure in a branch, slot or component built detached
154
+ * is attributed to the boundary its render sits under (`deferCrash`) and counts
155
+ * as handled here; `attribution` says how it is logged if no boundary takes it.
156
+ *
158
157
  * Callers still do their own logging, since the wording differs per failure.
159
158
  */
160
- /** @codexApi {"parent":"pithy.runtime.ssr-crashes","name":"reportComponentFailure","stability":"internal","signature":"(el: Element, tag: string, error: Error, boundary: BoundaryInfo | null) => boolean"} */
161
- export function reportComponentFailure(el, tag, error, boundary) {
159
+ /** @codexApi {"parent":"pithy.runtime.ssr-crashes","name":"reportComponentFailure","stability":"internal","signature":"(el: Element, tag: string, error: Error, boundary: BoundaryInfo | null, attribution?: Attribution) => boolean"} */
160
+ export function reportComponentFailure(el, tag, error, boundary, attribution = {}) {
161
+ if (!boundary && deferCrash(el, tag, error, attribution))
162
+ return true;
163
+ return settleFailure(el, tag, error, boundary);
164
+ }
165
+ function settleFailure(el, tag, error, boundary) {
162
166
  // A boundary in scope is not a boundary that accepted: an already-active one
163
167
  // with no free ancestor rejects, and that is as unhandled as having none.
164
168
  const accepted = boundary ? setBoundaryError(boundary, error) : false;
@@ -170,4 +174,305 @@ export function reportComponentFailure(el, tag, error, boundary) {
170
174
  }
171
175
  return accepted;
172
176
  }
177
+ const ops = {
178
+ locate: registeredClosest,
179
+ owner: slotOwnerOf,
180
+ hidden: isInHiddenContent,
181
+ parent: findParentBoundary,
182
+ settle: settleFailure,
183
+ };
184
+ let taskEndQueued = false;
185
+ // A crash that is neither in place nor hidden when a render ends may belong to
186
+ // content its caller inserts right after (a slot rendered from an effect): it
187
+ // waits once, to the end of the task, before it is reported.
188
+ function resolveAtTaskEnd() {
189
+ if (taskEndQueued)
190
+ return;
191
+ taskEndQueued = true;
192
+ queueMicrotask(() => {
193
+ taskEndQueued = false;
194
+ resolveAttributedCrashes('task');
195
+ });
196
+ }
197
+ // Shared on `globalThis` for the reason the registry is: a second copy of core
198
+ // must neither miss these nor resolve them in the middle of a render.
199
+ function heldCrashes() {
200
+ return pithyGlobals().__pithyAttributedCrashes;
201
+ }
202
+ function renderDepth(change = 0) {
203
+ const g = pithyGlobals();
204
+ return (g.__pithyRenderDepth = (g.__pithyRenderDepth ?? 0) + change);
205
+ }
206
+ function currentRender() {
207
+ return renderDepth() > 0 ? (pithyGlobals().__pithyRenderId ?? 0) : 0;
208
+ }
209
+ function crashedElements() {
210
+ const g = pithyGlobals();
211
+ return (g.__pithyCrashedElements ?? (g.__pithyCrashedElements = new WeakSet()));
212
+ }
213
+ /** Whether `el` crashed and was attributed; a retry would run its setup twice, which a build never does. */
214
+ /** @codexApi {"parent":"pithy.runtime.ssr-crashes","name":"hasCrashed","stability":"internal","signature":"(el: Element) => boolean"} */
215
+ export function hasCrashed(el) {
216
+ return crashedElements().has(el);
217
+ }
218
+ /**
219
+ * Brackets a render transaction: a template bind, or one structural update
220
+ * that builds a branch and inserts it. Attributed crashes are resolved when the
221
+ * outermost one ends, so a boundary hides its content only once everything in
222
+ * it is bound and in place.
223
+ */
224
+ /** @codexApi {"parent":"pithy.runtime.ssr-crashes","name":"withinRender","stability":"internal","signature":"<T>(fn: () => T) => T"} */
225
+ export function withinRender(fn) {
226
+ const g = pithyGlobals();
227
+ if (renderDepth() === 0)
228
+ g.__pithyRenderId = (g.__pithyRenderId ?? 0) + 1;
229
+ const render = g.__pithyRenderId ?? 0;
230
+ renderDepth(1);
231
+ let failed = false;
232
+ try {
233
+ return fn();
234
+ }
235
+ catch (err) {
236
+ failed = true;
237
+ throw err;
238
+ }
239
+ finally {
240
+ renderDepth(-1);
241
+ // Never throws, so a failed render keeps its own error. Its caller disposes
242
+ // what it bound, boundaries included, so its own crashes are only reported.
243
+ if (failed && renderDepth() === 0)
244
+ reportCrashesOf(render);
245
+ else
246
+ resolveAttributedCrashes();
247
+ }
248
+ }
249
+ /**
250
+ * Attributes a crash that reached no boundary through the DOM to the boundary
251
+ * its render sits under (`boundaryContext`): a branch, slot or component built
252
+ * detached. Returns `false` with no such context, so the caller handles the
253
+ * crash as before.
254
+ */
255
+ /** @codexApi {"parent":"pithy.runtime.ssr-crashes","name":"deferCrash","stability":"internal","signature":"(el: Element, tag: string, error: Error, attribution?: Attribution) => boolean"} */
256
+ export function deferCrash(el, tag, error, { message = null, onCaptured } = {}) {
257
+ var _a;
258
+ const boundaryEl = boundaryContext();
259
+ if (!boundaryEl)
260
+ return false;
261
+ crashedElements().add(el);
262
+ takeAttributedCrash(el);
263
+ ((_a = pithyGlobals()).__pithyAttributedCrashes ?? (_a.__pithyAttributedCrashes = [])).push({
264
+ el,
265
+ tag,
266
+ error,
267
+ boundaryEl,
268
+ message,
269
+ onCaptured,
270
+ ops,
271
+ render: currentRender(),
272
+ });
273
+ if (renderDepth() === 0)
274
+ resolveAtTaskEnd();
275
+ return true;
276
+ }
277
+ function reportCrashesOf(render) {
278
+ const list = heldCrashes();
279
+ if (!list?.length)
280
+ return;
281
+ for (const crash of list.splice(0)) {
282
+ if (crash.render !== render)
283
+ list.push(crash);
284
+ else
285
+ try {
286
+ unhandled(crash);
287
+ }
288
+ catch (err) {
289
+ reportResolveFailure([crash], err);
290
+ }
291
+ }
292
+ }
293
+ function logCrash(crash) {
294
+ if (crash.message)
295
+ console.error(crash.message, crash.error);
296
+ }
297
+ function unhandled(crash) {
298
+ crash.ops.settle(crash.el, crash.tag, crash.error, null);
299
+ logCrash(crash);
300
+ }
301
+ /**
302
+ * Resolves attributed crashes once they are in place. Each goes to the nearest
303
+ * registered boundary at its final position, exactly as a crash placed there
304
+ * would, and within one resolution a boundary takes at most one error. In the
305
+ * browser this waits for the
306
+ * outermost render to end. A static render binds text once, so there the
307
+ * component pass of the template that owns a boundary resolves its crashes
308
+ * (`scope`), before that template's text is bound and after its components
309
+ * ran. `task` runs at the end of the task; `collect` after the HTML is
310
+ * serialized, and only records.
311
+ */
312
+ /** @codexApi {"parent":"pithy.runtime.ssr-crashes","name":"resolveAttributedCrashes","stability":"internal","signature":"(mode?: 'render' | 'task' | 'collect', scope?: ParentNode) => void"} */
313
+ export function resolveAttributedCrashes(mode = 'render', scope) {
314
+ const list = heldCrashes();
315
+ if (!list?.length)
316
+ return;
317
+ const midRender = mode === 'render' && renderDepth() > 0;
318
+ if (midRender && (!scope || !isSSRMode()))
319
+ return;
320
+ const groups = new Map();
321
+ const into = (boundary, crash) => {
322
+ const group = groups.get(boundary);
323
+ if (group)
324
+ group.push(crash);
325
+ else
326
+ groups.set(boundary, [crash]);
327
+ };
328
+ let waiting = false;
329
+ for (const crash of list.splice(0)) {
330
+ try {
331
+ if (mode === 'collect') {
332
+ unhandled(crash);
333
+ continue;
334
+ }
335
+ if (midRender && !scope?.contains(crash.boundaryEl)) {
336
+ list.push(crash);
337
+ continue;
338
+ }
339
+ const target = placedAt(crash);
340
+ if (partOfShown(crash, target)) {
341
+ logCrash(crash);
342
+ continue;
343
+ }
344
+ if (target)
345
+ into(target, crash);
346
+ // In its boundary with no registered one around it, or out of time.
347
+ else if (mode === 'task' ||
348
+ (!midRender && crash.boundaryEl.contains(crash.el)))
349
+ unhandled(crash);
350
+ else {
351
+ // Not inserted yet: its caller may insert it right after.
352
+ list.push(crash);
353
+ waiting || (waiting = !midRender);
354
+ }
355
+ }
356
+ catch (err) {
357
+ reportResolveFailure([crash], err);
358
+ }
359
+ }
360
+ if (waiting)
361
+ resolveAtTaskEnd();
362
+ const innermostFirst = [...groups.entries()]
363
+ .map(entry => ({ entry, depth: depthOf(entry[0].element) }))
364
+ .sort((a, b) => b.depth - a.depth)
365
+ .map(({ entry }) => entry);
366
+ const handled = new Set();
367
+ for (const [boundary, group] of innermostFirst) {
368
+ try {
369
+ resolveGroup(boundary, group, handled);
370
+ }
371
+ catch (err) {
372
+ reportResolveFailure(group, err);
373
+ }
374
+ }
375
+ }
376
+ function reportResolveFailure(crashes, err) {
377
+ for (const crash of crashes)
378
+ if (isSSRMode())
379
+ recordSSRRenderCrash(crash.el, crash.tag, crash.error);
380
+ console.error('❌ Resolving a component crash failed:', err);
381
+ }
382
+ function depthOf(node) {
383
+ let depth = 0;
384
+ for (let at = node.parentNode; at; at = at.parentNode)
385
+ depth++;
386
+ return depth;
387
+ }
388
+ /**
389
+ * One boundary's crashes, content before fallback, so the outcome does not
390
+ * depend on the order they happened in. Each is handled as a crash placed there
391
+ * directly: a content crash goes to the boundary, a fallback crash too unless
392
+ * the boundary already shows its fallback, in which case it goes further out.
393
+ */
394
+ function resolveGroup(boundary, group, handled) {
395
+ const inFallback = (crash) => !!boundary.fallbackElement?.contains(crash.el);
396
+ for (const crash of group.filter(crash => !inFallback(crash)))
397
+ if (partOfShown(crash, boundary))
398
+ logCrash(crash);
399
+ else
400
+ deliver(crash, boundary, handled);
401
+ for (const crash of group.filter(inFallback)) {
402
+ if (partOfShown(crash, boundary))
403
+ logCrash(crash);
404
+ else
405
+ deliver(crash, showsError(boundary) ? crash.ops.parent(boundary) : boundary, handled);
406
+ }
407
+ }
408
+ // Slot content a portal moves out of its boundary goes to that boundary, as a
409
+ // component crash in it does through the slot frame. Only the nodes a slot
410
+ // rendered carry an owner: a root a component mounts during setup has none.
411
+ function placedAt(crash) {
412
+ const { el, ops } = crash;
413
+ const at = ops.locate(el);
414
+ if (at || !el.isConnected)
415
+ return at;
416
+ const owner = ops.owner(el);
417
+ return owner && !owner.contains(el) ? ops.locate(owner) : null;
418
+ }
419
+ // A delivery earlier in the resolution can hide it. A nearest boundary still
420
+ // free takes it, though an ancestor hides both, as it would a crash placed there.
421
+ function partOfShown(crash, nearest) {
422
+ return crash.ops.hidden(crash.el) && (!nearest || showsError(nearest));
423
+ }
424
+ // As `setBoundaryError` decides: by the signal, which a `batch()` sets before
425
+ // the boundary's effect updates `isActive`.
426
+ function showsError(boundary) {
427
+ return untrack(() => boundary.errorSignal()) !== null;
428
+ }
429
+ /**
430
+ * Hands a crash to the first boundary from `from` outward that is not already
431
+ * showing an error, as `setBoundaryError` escalates a crash placed there. One
432
+ * that reaches a boundary showing an error from this resolution is part of it.
433
+ */
434
+ function deliver(crash, from, handled) {
435
+ for (let at = from; at; at = crash.ops.parent(at)) {
436
+ if (handled.has(at)) {
437
+ logCrash(crash);
438
+ return;
439
+ }
440
+ if (showsError(at))
441
+ continue;
442
+ let accepted = false;
443
+ try {
444
+ accepted = crash.ops.settle(crash.el, crash.tag, crash.error, at);
445
+ }
446
+ catch (err) {
447
+ // An effect of the boundary threw; the crash is settled only if it took it.
448
+ if (!showsError(at))
449
+ reportResolveFailure([crash], err);
450
+ else
451
+ console.error('❌ Resolving a component crash failed:', err);
452
+ handled.add(at);
453
+ return;
454
+ }
455
+ if (accepted) {
456
+ handled.add(at);
457
+ crash.onCaptured?.();
458
+ }
459
+ else
460
+ logCrash(crash);
461
+ return;
462
+ }
463
+ unhandled(crash);
464
+ }
465
+ /**
466
+ * Before a component inside a boundary's fallback renders in a static render,
467
+ * that boundary takes its crashes, so content the component renders from the
468
+ * error (text is bound once there) has it.
469
+ */
470
+ /** @codexApi {"parent":"pithy.runtime.ssr-crashes","name":"resolveBeforeFallback","stability":"internal","signature":"(el: Element) => void"} */
471
+ export function resolveBeforeFallback(el) {
472
+ if (!isSSRMode() || !heldCrashes()?.length)
473
+ return;
474
+ const owner = el.closest('[data-fallback]')?.closest('[data-error]');
475
+ if (owner)
476
+ resolveAttributedCrashes('render', owner);
477
+ }
173
478
  //# sourceMappingURL=ssrCrashes.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ssrCrashes.js","sourceRoot":"","sources":["../../src/compile/ssrCrashes.ts"],"names":[],"mappings":"AAAA;;;;;;;EAOE;AAEF,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,gBAAgB,EAAqB,MAAM,2BAA2B,CAAC;AAchF;;;;;;;;;;;;;;;;GAgBG;AACH,SAAS,aAAa;IACpB,MAAM,CAAC,GAAG,YAAY,EAAE,CAAC;IACzB,OAAO,CAAC,CAAC,CAAC,iBAAiB,KAAnB,CAAC,CAAC,iBAAiB,GAAK,IAAI,GAAG,EAAE,EAAiC,CAAC;AAC7E,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,+IAA+I;AAC/I,MAAM,UAAU,mBAAmB,CAAC,EAAW;IAC7C,aAAa,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;AAC7B,CAAC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,SAAS,oBAAoB,CAAC,EAAW,EAAE,GAAW,EAAE,KAAc;IACpE,aAAa,EAAE,CAAC,GAAG,CAAC,EAAE,EAAE;QACtB,EAAE;QACF,GAAG;QACH,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;KACjE,CAAC,CAAC;AACL,CAAC;AAED;;;GAGG;AACH,oIAAoI;AACpI,MAAM,UAAU,qBAAqB;IACnC,aAAa,EAAE,CAAC,KAAK,EAAE,CAAC;AAC1B,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,2JAA2J;AAC3J,MAAM,UAAU,gCAAgC;IAC9C,MAAM,QAAQ,GAAG,aAAa,EAAE,CAAC;IACjC,MAAM,SAAS,GAAG,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;IACzC,QAAQ,CAAC,KAAK,EAAE,CAAC;IACjB,OAAO,SAAS,CAAC;AACnB,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,+MAA+M;AAC/M,MAAM,UAAU,sBAAsB,CACpC,EAAW,EACX,GAAW,EACX,KAAY,EACZ,QAA6B;IAE7B,6EAA6E;IAC7E,0EAA0E;IAC1E,MAAM,QAAQ,GAAG,QAAQ,CAAC,CAAC,CAAC,gBAAgB,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IAEtE,IAAI,SAAS,EAAE,EAAE,CAAC;QAChB,IAAI,QAAQ;YAAE,mBAAmB,CAAC,EAAE,CAAC,CAAC;;YACjC,oBAAoB,CAAC,EAAE,EAAE,GAAG,EAAE,KAAK,CAAC,CAAC;IAC5C,CAAC;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.runtime.ssr-crashes\",\n \"title\": \"SSR Unhandled Component Crash Collector\",\n \"category\": \"runtime\",\n \"risk\": \"high\"\n}\n*/\n\nimport { pithyGlobals } from '../types/globals';\nimport { isSSRMode } from './ssrMode';\nimport { setBoundaryError, type BoundaryInfo } from './binds/bindErrorBoundary';\n\n/**\n * A component render crash recorded during a static/server render.\n */\nexport interface SSRRenderCrash {\n /** The custom-element placeholder the crashed component was to replace. */\n el: Element;\n /** Authored tag name, for the failure message. */\n tag: string;\n /** The error the component threw. */\n error: Error;\n}\n\n/**\n * Crashes recorded during the current server render, keyed by the placeholder\n * element so a later binding pass over the same element can retract its own\n * earlier record (see `clearSSRRenderCrash`).\n *\n * Held on `globalThis`, not in this module. `@pithyjs/ssr` depends on\n * `@pithyjs/core` as a regular dependency, so an app and the SSR package can\n * resolve two physical copies: `html()` would record into the app's copy while\n * `renderToString()` collected and reset the SSR package's, reintroducing\n * BUG-018 *and* leaking the app copy's DOM records for the life of the process.\n * The same reasoning already puts `__PITHY_SSR__` and `__getComponentContext`\n * on this bridge.\n *\n * A `Map` (not a `WeakMap`) because the collector must be enumerable at flush\n * time. `resetSSRRenderCrashes()` is what keeps it from retaining DOM across\n * renders — the SSR renderer calls it in a `finally`.\n */\nfunction crashRegistry(): Map<Element, SSRRenderCrash> {\n const g = pithyGlobals();\n return (g.__pithySSRCrashes ??= new Map()) as Map<Element, SSRRenderCrash>;\n}\n\n/**\n * Forget any crash previously recorded for `el`.\n *\n * Called only at points where the record is provably no longer the outcome, and\n * NEVER before invoking a component. Retracting eagerly at the top of an attempt\n * hides a failed retry: a component that throws detached and then returns\n * something unusable would have its only record erased, shipping a page with a\n * missing subtree and a green build. The three call sites are:\n *\n * 1. A boundary ACCEPTING the error (`setBoundaryError()` returning `true`).\n * A boundary merely being in scope is not enough — an already-active one\n * with no free ancestor rejects the error, and that is as unhandled as\n * having no boundary at all.\n * 2. A component returning a usable node that then successfully reaches the\n * document, i.e. after `replaceWith` has not thrown.\n * 3. An element that has left the tree being bound (`scope.contains(el)` in\n * `bindComponentTags`, `fragment.contains(el)` in `applyBindings`). It can\n * no longer contribute to the output, so any record for it is stale.\n *\n * Retraction matters because the JIT `@if` path really does attempt the same tag\n * twice, measured by counting component invocations:\n *\n * 1. `bindStructuralDirectives` runs first and `handleConditionalChain` binds\n * the chosen branch while it is still DETACHED, so `el.closest('[data-error]')`\n * finds nothing and the crash is recorded.\n * 2. The branch is inserted, and `bindTemplateDirectives` then reaches the\n * still-raw tag on the assembled tree, where the boundary is visible and\n * accepts — retracting via case 1 above.\n *\n * Case 3 exists because accepting is synchronous: it immediately hides the\n * boundary's content, so a SECOND crashing component in that branch is detached\n * before it can be retried, and its detached-pass record would otherwise stand\n * and fail a route whose fallback rendered correctly.\n *\n * Every one of these is mutation-tested; removing any of them turns a correct\n * render into a failed route, or a broken one into a silent success.\n *\n * AOT invokes `applyComponent` once per `pid` and never retries, which is why\n * the equivalent AOT boundary case behaves differently — see BUG-023.\n */\n/** @codexApi {\"parent\":\"pithy.runtime.ssr-crashes\",\"name\":\"clearSSRRenderCrash\",\"stability\":\"internal\",\"signature\":\"(el: Element) => void\"} */\nexport function clearSSRRenderCrash(el: Element): void {\n crashRegistry().delete(el);\n}\n\n/**\n * Record a component failure that no error boundary took ownership of.\n *\n * The precondition is **not** \"no boundary was in scope\". It is that no boundary\n * ACCEPTED the error, which is a strictly weaker thing: `setBoundaryError()`\n * rejects an error when the nearest boundary is already showing one and no\n * ancestor is free, and both binders call this on that path with a boundary\n * very much present. Getting the two confused is what this whole module exists\n * to prevent.\n *\n * Nor is \"crash\" limited to a thrown error. The binders also record a component\n * that returned an unusable result, and one whose rendered node failed to reach\n * the document — both leave the raw tag exactly where a throw would, which is\n * the same content loss from the page's point of view.\n *\n * Callers must have established `isSSRMode()` themselves; this does not\n * re-check.\n */\nfunction recordSSRRenderCrash(el: Element, tag: string, error: unknown): void {\n crashRegistry().set(el, {\n el,\n tag,\n error: error instanceof Error ? error : new Error(String(error)),\n });\n}\n\n/**\n * Drop every recorded crash. Called by the SSR renderer before a render starts\n * and again in its `finally`, so one route's crash can never fail the next.\n */\n/** @codexApi {\"parent\":\"pithy.runtime.ssr-crashes\",\"name\":\"resetSSRRenderCrashes\",\"stability\":\"stable\",\"signature\":\"() => void\"} */\nexport function resetSSRRenderCrashes(): void {\n crashRegistry().clear();\n}\n\n/**\n * Return the crashes still recorded once the render has finished, and empty\n * the collector.\n *\n * Every surviving record is a failure. A record is only ever retracted by\n * `clearSSRRenderCrash`, i.e. by a genuine re-attempt at the same element that\n * then went better — never by inspecting the finished tree.\n *\n * An earlier draft re-resolved each record's boundary here, dropping any crash\n * whose element had ended up inside an `@error-boundary`. That is unsound,\n * because a boundary *existing* above an element is not the same as that\n * boundary having *handled* the crash:\n *\n * - JIT never needed it. It does record a crash from the detached first\n * attempt, but the retry after insertion is caught by the boundary and\n * retracts that record itself (see `clearSSRRenderCrash`). By collect time\n * there is nothing left to re-resolve.\n * - AOT was actively broken by it. A branch factory binds its subtree while\n * detached, so `applyComponent`'s `el.closest('[data-error]')` finds\n * nothing and the boundary never receives the error — but the nodes are\n * then inserted *under* that boundary, so re-resolution saw one and\n * dropped the record. The boundary signal stayed null, its fallback never\n * activated, the raw component tag shipped, and the build went green: the\n * exact BUG-018 symptom, reintroduced by its own fix.\n *\n * That AOT boundary gap is real but predates this collector and is tracked\n * separately as BUG-023. Until it is fixed, such a crash fails its route, which\n * is the safe direction: a loud failure rather than silently truncated HTML.\n */\n/** @codexApi {\"parent\":\"pithy.runtime.ssr-crashes\",\"name\":\"collectUnhandledSSRRenderCrashes\",\"stability\":\"stable\",\"signature\":\"() => SSRRenderCrash[]\"} */\nexport function collectUnhandledSSRRenderCrashes(): SSRRenderCrash[] {\n const registry = crashRegistry();\n const unhandled = [...registry.values()];\n registry.clear();\n return unhandled;\n}\n\n/**\n * Hand a component failure to its `@error-boundary`, or record it if none takes\n * it. Returns whether a boundary accepted ownership.\n *\n * The single funnel for every way a component can fail to produce content: a\n * thrown error, an unusable return value, and a rendered node that never reached\n * the document. They were handled in five separate places and drifted — the\n * throw paths consulted the boundary while the malformed paths recorded\n * directly, so a component under `@error-boundary` that returned garbage left\n * the boundary signal null, rendered no fallback, and failed the route, even\n * though the code called it \"the same content loss as a crash\".\n *\n * Callers still do their own logging, since the wording differs per failure.\n */\n/** @codexApi {\"parent\":\"pithy.runtime.ssr-crashes\",\"name\":\"reportComponentFailure\",\"stability\":\"internal\",\"signature\":\"(el: Element, tag: string, error: Error, boundary: BoundaryInfo | null) => boolean\"} */\nexport function reportComponentFailure(\n el: Element,\n tag: string,\n error: Error,\n boundary: BoundaryInfo | null\n): boolean {\n // A boundary in scope is not a boundary that accepted: an already-active one\n // with no free ancestor rejects, and that is as unhandled as having none.\n const accepted = boundary ? setBoundaryError(boundary, error) : false;\n\n if (isSSRMode()) {\n if (accepted) clearSSRRenderCrash(el);\n else recordSSRRenderCrash(el, tag, error);\n }\n\n return accepted;\n}\n"]}
1
+ {"version":3,"file":"ssrCrashes.js","sourceRoot":"","sources":["../../src/compile/ssrCrashes.ts"],"names":[],"mappings":"AAAA;;;;;;;EAOE;AAEF,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EACL,eAAe,EACf,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,EACjB,gBAAgB,EAChB,WAAW,GAEZ,MAAM,2BAA2B,CAAC;AAcnC;;;;;;;;;;;;;;;;GAgBG;AACH,SAAS,aAAa;IACpB,MAAM,CAAC,GAAG,YAAY,EAAE,CAAC;IACzB,OAAO,CAAC,CAAC,CAAC,iBAAiB,KAAnB,CAAC,CAAC,iBAAiB,GAAK,IAAI,GAAG,EAAE,EAAiC,CAAC;AAC7E,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,+IAA+I;AAC/I,MAAM,UAAU,mBAAmB,CAAC,EAAW;IAC7C,aAAa,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;AAC7B,CAAC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,SAAS,oBAAoB,CAAC,EAAW,EAAE,GAAW,EAAE,KAAc;IACpE,aAAa,EAAE,CAAC,GAAG,CAAC,EAAE,EAAE;QACtB,EAAE;QACF,GAAG;QACH,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;KACjE,CAAC,CAAC;AACL,CAAC;AAED;;;GAGG;AACH,oIAAoI;AACpI,MAAM,UAAU,qBAAqB;IACnC,aAAa,E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EAAE,EAAE,CAAC;QACvB,CAAC;;YAAM,QAAQ,CAAC,KAAK,CAAC,CAAC;QACvB,OAAO;IACT,CAAC;IACD,SAAS,CAAC,KAAK,CAAC,CAAC;AACnB,CAAC;AAED;;;;GAIG;AACH,iJAAiJ;AACjJ,MAAM,UAAU,qBAAqB,CAAC,EAAW;IAC/C,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,WAAW,EAAE,EAAE,MAAM;QAAE,OAAO;IACnD,MAAM,KAAK,GAAG,EAAE,CAAC,OAAO,CAAC,iBAAiB,CAAC,EAAE,OAAO,CAAC,cAAc,CAAC,CAAC;IACrE,IAAI,KAAK;QAAE,wBAAwB,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;AACvD,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.runtime.ssr-crashes\",\n \"title\": \"SSR Unhandled Component Crash Collector\",\n \"category\": \"runtime\",\n \"risk\": \"high\"\n}\n*/\n\nimport { untrack } from '@pithyjs/signals';\nimport { pithyGlobals } from '../types/globals';\nimport { isSSRMode } from './ssrMode';\nimport {\n boundaryContext,\n findParentBoundary,\n isInHiddenContent,\n registeredClosest,\n setBoundaryError,\n slotOwnerOf,\n type BoundaryInfo,\n} from './binds/bindErrorBoundary';\n\n/**\n * A component render crash recorded during a static/server render.\n */\nexport interface SSRRenderCrash {\n /** The custom-element placeholder the crashed component was to replace. */\n el: Element;\n /** Authored tag name, for the failure message. */\n tag: string;\n /** The error the component threw. */\n error: Error;\n}\n\n/**\n * Crashes recorded during the current server render, keyed by the placeholder\n * element so a later binding pass over the same element can retract its own\n * earlier record (see `clearSSRRenderCrash`).\n *\n * Held on `globalThis`, not in this module. `@pithyjs/ssr` depends on\n * `@pithyjs/core` as a regular dependency, so an app and the SSR package can\n * resolve two physical copies: `html()` would record into the app's copy while\n * `renderToString()` collected and reset the SSR package's, reintroducing\n * BUG-018 *and* leaking the app copy's DOM records for the life of the process.\n * The same reasoning already puts `__PITHY_SSR__` and `__getComponentContext`\n * on this bridge.\n *\n * A `Map` (not a `WeakMap`) because the collector must be enumerable at flush\n * time. `resetSSRRenderCrashes()` is what keeps it from retaining DOM across\n * renders — the SSR renderer calls it in a `finally`.\n */\nfunction crashRegistry(): Map<Element, SSRRenderCrash> {\n const g = pithyGlobals();\n return (g.__pithySSRCrashes ??= new Map()) as Map<Element, SSRRenderCrash>;\n}\n\n/**\n * Forget any crash previously recorded for `el`.\n *\n * Called only at points where the record is provably no longer the outcome, and\n * NEVER before invoking a component. Retracting eagerly at the top of an attempt\n * hides a failed retry: a component that throws detached and then returns\n * something unusable would have its only record erased, shipping a page with a\n * missing subtree and a green build. The three call sites are:\n *\n * 1. A boundary ACCEPTING the error (`setBoundaryError()` returning `true`).\n * A boundary merely being in scope is not enough — an already-active one\n * with no free ancestor rejects the error, and that is as unhandled as\n * having no boundary at all.\n * 2. A component returning a usable node that then successfully reaches the\n * document, i.e. after `replaceWith` has not thrown.\n * 3. An element that has left the tree being bound (`scope.contains(el)` in\n * `bindComponentTags`, `fragment.contains(el)` in `applyBindings`). It can\n * no longer contribute to the output, so any record for it is stale.\n *\n * Every one of these is mutation-tested; removing any of them turns a correct\n * render into a failed route, or a broken one into a silent success.\n */\n/** @codexApi {\"parent\":\"pithy.runtime.ssr-crashes\",\"name\":\"clearSSRRenderCrash\",\"stability\":\"internal\",\"signature\":\"(el: Element) => void\"} */\nexport function clearSSRRenderCrash(el: Element): void {\n crashRegistry().delete(el);\n}\n\n/**\n * Record a component failure that no error boundary took ownership of.\n *\n * The precondition is **not** \"no boundary was in scope\". It is that no boundary\n * ACCEPTED the error, which is a strictly weaker thing: `setBoundaryError()`\n * rejects an error when the nearest boundary is already showing one and no\n * ancestor is free, and both binders call this on that path with a boundary\n * very much present. Getting the two confused is what this whole module exists\n * to prevent.\n *\n * Nor is \"crash\" limited to a thrown error. The binders also record a component\n * that returned an unusable result, and one whose rendered node failed to reach\n * the document — both leave the raw tag exactly where a throw would, which is\n * the same content loss from the page's point of view.\n *\n * Callers must have established `isSSRMode()` themselves; this does not\n * re-check.\n */\nfunction recordSSRRenderCrash(el: Element, tag: string, error: unknown): void {\n crashRegistry().set(el, {\n el,\n tag,\n error: error instanceof Error ? error : new Error(String(error)),\n });\n}\n\n/**\n * Drop every recorded crash. Called by the SSR renderer before a render starts\n * and again in its `finally`, so one route's crash can never fail the next.\n */\n/** @codexApi {\"parent\":\"pithy.runtime.ssr-crashes\",\"name\":\"resetSSRRenderCrashes\",\"stability\":\"stable\",\"signature\":\"() => void\"} */\nexport function resetSSRRenderCrashes(): void {\n crashRegistry().clear();\n const g = pithyGlobals();\n g.__pithyAttributedCrashes = [];\n g.__pithyRenderDepth = 0;\n}\n\n/**\n * An element that left the tree being bound contributes nothing to the output:\n * its recorded crash is stale, and an attributed one is only logged.\n */\n/** @codexApi {\"parent\":\"pithy.runtime.ssr-crashes\",\"name\":\"forgetCrash\",\"stability\":\"internal\",\"signature\":\"(el: Element) => void\"} */\nexport function forgetCrash(el: Element): void {\n clearSSRRenderCrash(el);\n const crash = takeAttributedCrash(el);\n if (crash) logCrash(crash);\n}\n\nfunction takeAttributedCrash(el: Element): AttributedCrash | undefined {\n const list = heldCrashes();\n const at = list?.findIndex(crash => crash.el === el) ?? -1;\n return at >= 0 ? list?.splice(at, 1)[0] : undefined;\n}\n\n/**\n * Return the crashes still recorded once the render has finished, and empty\n * the collector.\n *\n * Every surviving record is a failure. A record is only ever retracted by\n * `clearSSRRenderCrash`, i.e. by a genuine re-attempt at the same element that\n * then went better — never by inspecting the finished tree.\n *\n * An earlier draft re-resolved each record's boundary here, dropping any crash\n * whose element had ended up inside an `@error-boundary`. That is unsound,\n * because a boundary *existing* above an element is not the same as that\n * boundary having *handled* the crash. A crash that a boundary rejected, or\n * that ran where no boundary resolved, is placed under one afterwards just the\n * same. Re-resolution dropped such a record: the boundary signal stayed null,\n * its fallback never activated, the raw component tag shipped, and the build\n * went green — the exact BUG-018 symptom, reintroduced by its own fix.\n *\n * A crash in a branch, slot or component built detached is attributed to its\n * boundary instead (`deferCrash`); whatever is still attributed here is\n * recorded.\n */\n/** @codexApi {\"parent\":\"pithy.runtime.ssr-crashes\",\"name\":\"collectUnhandledSSRRenderCrashes\",\"stability\":\"stable\",\"signature\":\"() => SSRRenderCrash[]\"} */\nexport function collectUnhandledSSRRenderCrashes(): SSRRenderCrash[] {\n resolveAttributedCrashes('collect');\n const registry = crashRegistry();\n const unhandled = [...registry.values()];\n registry.clear();\n return unhandled;\n}\n\n/**\n * Hand a component failure to its `@error-boundary`, or record it if none takes\n * it. Returns whether a boundary accepted ownership.\n *\n * The single funnel for every way a component can fail to produce content: a\n * thrown error, an unusable return value, and a rendered node that never reached\n * the document. They were handled in five separate places and drifted — the\n * throw paths consulted the boundary while the malformed paths recorded\n * directly, so a component under `@error-boundary` that returned garbage left\n * the boundary signal null, rendered no fallback, and failed the route, even\n * though the code called it \"the same content loss as a crash\".\n *\n * With no `boundary`, a failure in a branch, slot or component built detached\n * is attributed to the boundary its render sits under (`deferCrash`) and counts\n * as handled here; `attribution` says how it is logged if no boundary takes it.\n *\n * Callers still do their own logging, since the wording differs per failure.\n */\n/** @codexApi {\"parent\":\"pithy.runtime.ssr-crashes\",\"name\":\"reportComponentFailure\",\"stability\":\"internal\",\"signature\":\"(el: Element, tag: string, error: Error, boundary: BoundaryInfo | null, attribution?: Attribution) => boolean\"} */\nexport function reportComponentFailure(\n el: Element,\n tag: string,\n error: Error,\n boundary: BoundaryInfo | null,\n attribution: Attribution = {}\n): boolean {\n if (!boundary && deferCrash(el, tag, error, attribution)) return true;\n return settleFailure(el, tag, error, boundary);\n}\n\n/** How an attributed crash is logged: `message` if no boundary takes it, `onCaptured` if one does. */\nexport interface Attribution {\n message?: string | null;\n onCaptured?: () => void;\n}\n\nfunction settleFailure(\n el: Element,\n tag: string,\n error: Error,\n boundary: BoundaryInfo | null\n): boolean {\n // A boundary in scope is not a boundary that accepted: an already-active one\n // with no free ancestor rejects, and that is as unhandled as having none.\n const accepted = boundary ? setBoundaryError(boundary, error) : false;\n\n if (isSSRMode()) {\n if (accepted) clearSSRRenderCrash(el);\n else recordSSRRenderCrash(el, tag, error);\n }\n\n return accepted;\n}\n\n/** A crash raised where no boundary was reachable, owned by the boundary its render sat under. */\ninterface AttributedCrash extends SSRRenderCrash {\n /** The boundary the branch, slot or component was built for: the crash waits until it is inside. */\n boundaryEl: Element;\n message: string | null;\n onCaptured?: () => void;\n ops: CrashOps;\n /** The outermost render it was attributed in; `0` outside any. */\n render: number;\n}\n\n/** The copy of core that attributed a crash answers these, against its own boundaries. */\ninterface CrashOps {\n locate: (el: Element) => BoundaryInfo | null;\n owner: (node: Node) => Element | null;\n hidden: (node: Node) => boolean;\n parent: (boundary: BoundaryInfo) => BoundaryInfo | null;\n settle: typeof settleFailure;\n}\n\nconst ops: CrashOps = {\n locate: registeredClosest,\n owner: slotOwnerOf,\n hidden: isInHiddenContent,\n parent: findParentBoundary,\n settle: settleFailure,\n};\n\nlet taskEndQueued = false;\n\n// A crash that is neither in place nor hidden when a render ends may belong to\n// content its caller inserts right after (a slot rendered from an effect): it\n// waits once, to the end of the task, before it is reported.\nfunction resolveAtTaskEnd(): void {\n if (taskEndQueued) return;\n taskEndQueued = true;\n queueMicrotask(() => {\n taskEndQueued = false;\n resolveAttributedCrashes('task');\n });\n}\n\n// Shared on `globalThis` for the reason the registry is: a second copy of core\n// must neither miss these nor resolve them in the middle of a render.\n\nfunction heldCrashes(): AttributedCrash[] | undefined {\n return pithyGlobals().__pithyAttributedCrashes as\n | AttributedCrash[]\n | undefined;\n}\n\nfunction renderDepth(change = 0): number {\n const g = pithyGlobals();\n return (g.__pithyRenderDepth = (g.__pithyRenderDepth ?? 0) + change);\n}\n\nfunction currentRender(): number {\n return renderDepth() > 0 ? (pithyGlobals().__pithyRenderId ?? 0) : 0;\n}\n\nfunction crashedElements(): WeakSet<Element> {\n const g = pithyGlobals();\n return (g.__pithyCrashedElements ??= new WeakSet()) as WeakSet<Element>;\n}\n\n/** Whether `el` crashed and was attributed; a retry would run its setup twice, which a build never does. */\n/** @codexApi {\"parent\":\"pithy.runtime.ssr-crashes\",\"name\":\"hasCrashed\",\"stability\":\"internal\",\"signature\":\"(el: Element) => boolean\"} */\nexport function hasCrashed(el: Element): boolean {\n return crashedElements().has(el);\n}\n\n/**\n * Brackets a render transaction: a template bind, or one structural update\n * that builds a branch and inserts it. Attributed crashes are resolved when the\n * outermost one ends, so a boundary hides its content only once everything in\n * it is bound and in place.\n */\n/** @codexApi {\"parent\":\"pithy.runtime.ssr-crashes\",\"name\":\"withinRender\",\"stability\":\"internal\",\"signature\":\"<T>(fn: () => T) => T\"} */\nexport function withinRender<T>(fn: () => T): T {\n const g = pithyGlobals();\n if (renderDepth() === 0) g.__pithyRenderId = (g.__pithyRenderId ?? 0) + 1;\n const render = g.__pithyRenderId ?? 0;\n renderDepth(1);\n let failed = false;\n try {\n return fn();\n } catch (err) {\n failed = true;\n throw err;\n } finally {\n renderDepth(-1);\n // Never throws, so a failed render keeps its own error. Its caller disposes\n // what it bound, boundaries included, so its own crashes are only reported.\n if (failed && renderDepth() === 0) reportCrashesOf(render);\n else resolveAttributedCrashes();\n }\n}\n\n/**\n * Attributes a crash that reached no boundary through the DOM to the boundary\n * its render sits under (`boundaryContext`): a branch, slot or component built\n * detached. Returns `false` with no such context, so the caller handles the\n * crash as before.\n */\n/** @codexApi {\"parent\":\"pithy.runtime.ssr-crashes\",\"name\":\"deferCrash\",\"stability\":\"internal\",\"signature\":\"(el: Element, tag: string, error: Error, attribution?: Attribution) => boolean\"} */\nexport function deferCrash(\n el: Element,\n tag: string,\n error: Error,\n { message = null, onCaptured }: Attribution = {}\n): boolean {\n const boundaryEl = boundaryContext();\n if (!boundaryEl) return false;\n crashedElements().add(el);\n takeAttributedCrash(el);\n (pithyGlobals().__pithyAttributedCrashes ??= []).push({\n el,\n tag,\n error,\n boundaryEl,\n message,\n onCaptured,\n ops,\n render: currentRender(),\n });\n if (renderDepth() === 0) resolveAtTaskEnd();\n return true;\n}\n\nfunction reportCrashesOf(render: number): void {\n const list = heldCrashes();\n if (!list?.length) return;\n for (const crash of list.splice(0)) {\n if (crash.render !== render) list.push(crash);\n else\n try {\n unhandled(crash);\n } catch (err) {\n reportResolveFailure([crash], err);\n }\n }\n}\n\nfunction logCrash(crash: AttributedCrash): void {\n if (crash.message) console.error(crash.message, crash.error);\n}\n\nfunction unhandled(crash: AttributedCrash): void {\n crash.ops.settle(crash.el, crash.tag, crash.error, null);\n logCrash(crash);\n}\n\n/**\n * Resolves attributed crashes once they are in place. Each goes to the nearest\n * registered boundary at its final position, exactly as a crash placed there\n * would, and within one resolution a boundary takes at most one error. In the\n * browser this waits for the\n * outermost render to end. A static render binds text once, so there the\n * component pass of the template that owns a boundary resolves its crashes\n * (`scope`), before that template's text is bound and after its components\n * ran. `task` runs at the end of the task; `collect` after the HTML is\n * serialized, and only records.\n */\n/** @codexApi {\"parent\":\"pithy.runtime.ssr-crashes\",\"name\":\"resolveAttributedCrashes\",\"stability\":\"internal\",\"signature\":\"(mode?: 'render' | 'task' | 'collect', scope?: ParentNode) => void\"} */\nexport function resolveAttributedCrashes(\n mode: 'render' | 'task' | 'collect' = 'render',\n scope?: ParentNode\n): void {\n const list = heldCrashes();\n if (!list?.length) return;\n const midRender = mode === 'render' && renderDepth() > 0;\n if (midRender && (!scope || !isSSRMode())) return;\n const groups = new Map<BoundaryInfo, AttributedCrash[]>();\n const into = (boundary: BoundaryInfo, crash: AttributedCrash) => {\n const group = groups.get(boundary);\n if (group) group.push(crash);\n else groups.set(boundary, [crash]);\n };\n let waiting = false;\n for (const crash of list.splice(0)) {\n try {\n if (mode === 'collect') {\n unhandled(crash);\n continue;\n }\n if (midRender && !scope?.contains(crash.boundaryEl)) {\n list.push(crash);\n continue;\n }\n const target = placedAt(crash);\n if (partOfShown(crash, target)) {\n logCrash(crash);\n continue;\n }\n if (target) into(target, crash);\n // In its boundary with no registered one around it, or out of time.\n else if (\n mode === 'task' ||\n (!midRender && crash.boundaryEl.contains(crash.el))\n )\n unhandled(crash);\n else {\n // Not inserted yet: its caller may insert it right after.\n list.push(crash);\n waiting ||= !midRender;\n }\n } catch (err) {\n reportResolveFailure([crash], err);\n }\n }\n if (waiting) resolveAtTaskEnd();\n const innermostFirst = [...groups.entries()]\n .map(entry => ({ entry, depth: depthOf(entry[0].element) }))\n .sort((a, b) => b.depth - a.depth)\n .map(({ entry }) => entry);\n const handled = new Set<BoundaryInfo>();\n for (const [boundary, group] of innermostFirst) {\n try {\n resolveGroup(boundary, group, handled);\n } catch (err) {\n reportResolveFailure(group, err);\n }\n }\n}\n\nfunction reportResolveFailure(crashes: AttributedCrash[], err: unknown): void {\n for (const crash of crashes)\n if (isSSRMode()) recordSSRRenderCrash(crash.el, crash.tag, crash.error);\n console.error('❌ Resolving a component crash failed:', err);\n}\n\nfunction depthOf(node: Node): number {\n let depth = 0;\n for (let at = node.parentNode; at; at = at.parentNode) depth++;\n return depth;\n}\n\n/**\n * One boundary's crashes, content before fallback, so the outcome does not\n * depend on the order they happened in. Each is handled as a crash placed there\n * directly: a content crash goes to the boundary, a fallback crash too unless\n * the boundary already shows its fallback, in which case it goes further out.\n */\nfunction resolveGroup(\n boundary: BoundaryInfo,\n group: AttributedCrash[],\n handled: Set<BoundaryInfo>\n): void {\n const inFallback = (crash: AttributedCrash) =>\n !!boundary.fallbackElement?.contains(crash.el);\n for (const crash of group.filter(crash => !inFallback(crash)))\n if (partOfShown(crash, boundary)) logCrash(crash);\n else deliver(crash, boundary, handled);\n for (const crash of group.filter(inFallback)) {\n if (partOfShown(crash, boundary)) logCrash(crash);\n else\n deliver(\n crash,\n showsError(boundary) ? crash.ops.parent(boundary) : boundary,\n handled\n );\n }\n}\n\n// Slot content a portal moves out of its boundary goes to that boundary, as a\n// component crash in it does through the slot frame. Only the nodes a slot\n// rendered carry an owner: a root a component mounts during setup has none.\nfunction placedAt(crash: AttributedCrash): BoundaryInfo | null {\n const { el, ops } = crash;\n const at = ops.locate(el);\n if (at || !el.isConnected) return at;\n const owner = ops.owner(el);\n return owner && !owner.contains(el) ? ops.locate(owner) : null;\n}\n\n// A delivery earlier in the resolution can hide it. A nearest boundary still\n// free takes it, though an ancestor hides both, as it would a crash placed there.\nfunction partOfShown(\n crash: AttributedCrash,\n nearest: BoundaryInfo | null\n): boolean {\n return crash.ops.hidden(crash.el) && (!nearest || showsError(nearest));\n}\n\n// As `setBoundaryError` decides: by the signal, which a `batch()` sets before\n// the boundary's effect updates `isActive`.\nfunction showsError(boundary: BoundaryInfo): boolean {\n return untrack(() => boundary.errorSignal()) !== null;\n}\n\n/**\n * Hands a crash to the first boundary from `from` outward that is not already\n * showing an error, as `setBoundaryError` escalates a crash placed there. One\n * that reaches a boundary showing an error from this resolution is part of it.\n */\nfunction deliver(\n crash: AttributedCrash,\n from: BoundaryInfo | null,\n handled: Set<BoundaryInfo>\n): void {\n for (let at = from; at; at = crash.ops.parent(at)) {\n if (handled.has(at)) {\n logCrash(crash);\n return;\n }\n if (showsError(at)) continue;\n let accepted = false;\n try {\n accepted = crash.ops.settle(crash.el, crash.tag, crash.error, at);\n } catch (err) {\n // An effect of the boundary threw; the crash is settled only if it took it.\n if (!showsError(at)) reportResolveFailure([crash], err);\n else console.error('❌ Resolving a component crash failed:', err);\n handled.add(at);\n return;\n }\n if (accepted) {\n handled.add(at);\n crash.onCaptured?.();\n } else logCrash(crash);\n return;\n }\n unhandled(crash);\n}\n\n/**\n * Before a component inside a boundary's fallback renders in a static render,\n * that boundary takes its crashes, so content the component renders from the\n * error (text is bound once there) has it.\n */\n/** @codexApi {\"parent\":\"pithy.runtime.ssr-crashes\",\"name\":\"resolveBeforeFallback\",\"stability\":\"internal\",\"signature\":\"(el: Element) => void\"} */\nexport function resolveBeforeFallback(el: Element): void {\n if (!isSSRMode() || !heldCrashes()?.length) return;\n const owner = el.closest('[data-fallback]')?.closest('[data-error]');\n if (owner) resolveAttributedCrashes('render', owner);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"applyBindings.d.ts","sourceRoot":"","sources":["../../src/runtime/applyBindings.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAOF,OAAO,EAqBL,KAAK,IAAI,EACT,KAAK,SAAS,EACd,KAAK,UAAU,EACf,KAAK,SAAS,EACd,KAAK,WAAW,EAChB,KAAK,SAAS,EACd,KAAK,SAAS,EACd,KAAK,OAAO,EACZ,KAAK,QAAQ,EACb,KAAK,QAAQ,EACb,KAAK,SAAS,EACd,KAAK,SAAS,EACd,KAAK,QAAQ,EACb,KAAK,MAAM,EACX,KAAK,OAAO,EACZ,KAAK,UAAU,EAChB,MAAM,YAAY,CAAC;AAGpB,YAAY,EACV,IAAI,EACJ,SAAS,EACT,UAAU,EACV,SAAS,EACT,WAAW,EACX,SAAS,EACT,SAAS,EACT,OAAO,EACP,QAAQ,EACR,QAAQ,EACR,SAAS,EACT,SAAS,EACT,QAAQ,EACR,MAAM,EACN,OAAO,EACP,UAAU,GACX,CAAC;AAIF;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,8RAA8R;AAC9R,wBAAgB,eAAe,CAC7B,QAAQ,EAAE,gBAAgB,EAC1B,QAAQ,EAAE,IAAI,EAAE,EAChB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,oBAAoB,UAAO,GAC1B;IAAE,EAAE,EAAE,gBAAgB,CAAC;IAAC,OAAO,EAAE,MAAM,IAAI,CAAA;CAAE,CA4L/C"}
1
+ {"version":3,"file":"applyBindings.d.ts","sourceRoot":"","sources":["../../src/runtime/applyBindings.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAWF,OAAO,EAsBL,KAAK,IAAI,EACT,KAAK,SAAS,EACd,KAAK,UAAU,EACf,KAAK,SAAS,EACd,KAAK,WAAW,EAChB,KAAK,SAAS,EACd,KAAK,SAAS,EACd,KAAK,OAAO,EACZ,KAAK,QAAQ,EACb,KAAK,QAAQ,EACb,KAAK,SAAS,EACd,KAAK,SAAS,EACd,KAAK,QAAQ,EACb,KAAK,MAAM,EACX,KAAK,OAAO,EACZ,KAAK,UAAU,EAChB,MAAM,YAAY,CAAC;AAGpB,YAAY,EACV,IAAI,EACJ,SAAS,EACT,UAAU,EACV,SAAS,EACT,WAAW,EACX,SAAS,EACT,SAAS,EACT,OAAO,EACP,QAAQ,EACR,QAAQ,EACR,SAAS,EACT,SAAS,EACT,QAAQ,EACR,MAAM,EACN,OAAO,EACP,UAAU,GACX,CAAC;AAIF;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,8RAA8R;AAC9R,wBAAgB,eAAe,CAC7B,QAAQ,EAAE,gBAAgB,EAC1B,QAAQ,EAAE,IAAI,EAAE,EAChB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChC,oBAAoB,UAAO,GAC1B;IAAE,EAAE,EAAE,gBAAgB,CAAC;IAAC,OAAO,EAAE,MAAM,IAAI,CAAA;CAAE,CAI/C"}
@@ -6,11 +6,11 @@
6
6
  }
7
7
  */
8
8
  import { drainDestroyCallbacks } from './onDestroy.js';
9
- import { clearSSRRenderCrash } from '../compile/ssrCrashes.js';
9
+ import { forgetCrash, resolveAttributedCrashes, withinRender, } from '../compile/ssrCrashes.js';
10
10
  import { nodeExpando } from '../compile/nodeExpando.js';
11
11
  import { orderByDocument } from '../compile/disposeOrder.js';
12
12
  import { executeCustomDirectiveBinders } from '../compile/binds/directiveRegistry.js';
13
- import { buildPidMap, buildCommentMap, mergeContexts, nearestCtx, applyRef, applyError, applyProjection, applyComponent, applyBind, applyInterpolation, markSkeletonText, applyEvent, applyClass, applyClasses, applyStyle, applyBound, applyIf, applyFor, applySwitch, applyDefer, } from './bindings/index.js';
13
+ import { buildPidMap, buildCommentMap, mergeContexts, nearestCtx, applyRef, applyError, markBoundary, applyProjection, applyComponent, applyBind, applyInterpolation, markSkeletonText, applyEvent, applyClass, applyClasses, applyStyle, applyBound, applyIf, applyFor, applySwitch, applyDefer, } from './bindings/index.js';
14
14
  // ─── Main entry point ─────────────────────────────────────────────────────────
15
15
  /**
16
16
  * Applies pre-extracted binding descriptors to an AOT-generated DOM fragment.
@@ -39,6 +39,9 @@ import { buildPidMap, buildCommentMap, mergeContexts, nearestCtx, applyRef, appl
39
39
  */
40
40
  /** @codexApi {"parent":"pithy.runtime.apply-bindings","name":"__applyBindings","stability":"experimental","signature":"(fragment: DocumentFragment, bindings: Desc[], context: Record<string, unknown>, ownsDestroyCallbacks?: boolean) => { el: DocumentFragment; destroy: () => void }"} */
41
41
  export function __applyBindings(fragment, bindings, context, ownsDestroyCallbacks = true) {
42
+ return withinRender(() => applyBindings(fragment, bindings, context, ownsDestroyCallbacks));
43
+ }
44
+ function applyBindings(fragment, bindings, context, ownsDestroyCallbacks) {
42
45
  // Drain onDestroy() callbacks BEFORE processing bindings — child components
43
46
  // instantiated during binding will drain their own callbacks independently.
44
47
  const destroyCallbacks = ownsDestroyCallbacks ? drainDestroyCallbacks() : [];
@@ -72,6 +75,12 @@ export function __applyBindings(fragment, bindings, context, ownsDestroyCallback
72
75
  try {
73
76
  // ─── Phase 1: Structural directives (shape-changing) ─────────────────
74
77
  // Order: switch → if → for (matches bindStructuralDirectives)
78
+ // Marked, not registered: a branch built below must `closest()` its boundary.
79
+ for (const d of (byType.get('error') ?? [])) {
80
+ const el = pidMap.get(d.pid);
81
+ if (el)
82
+ markBoundary(d, el);
83
+ }
75
84
  for (const d of (byType.get('switch') ?? [])) {
76
85
  applySwitch(d, pidMap, ctx, disposers);
77
86
  }
@@ -174,9 +183,10 @@ export function __applyBindings(fragment, bindings, context, ownsDestroyCallback
174
183
  // Left the tree, so it contributes nothing to the output — and any crash
175
184
  // recorded for it on an earlier detached pass is stale. Same reasoning
176
185
  // as the `scope.contains(el)` skip in `bindComponentTags`.
177
- clearSSRRenderCrash(el);
186
+ forgetCrash(el);
178
187
  }
179
188
  }
189
+ resolveAttributedCrashes('render', fragment);
180
190
  for (const d of (byType.get('bind') ?? [])) {
181
191
  const el = pidMap.get(d.pid);
182
192
  if (el)