@deepseek-ai/dsh-cordis-client-runner 0.2.2-alpha.3 → 0.2.2-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 (34) hide show
  1. package/lib/client.js +2411 -7959
  2. package/lib/client.js.map +1 -0
  3. package/lib/types/client/api-catalog.d.ts.map +1 -0
  4. package/lib/types/client/api-catalog.js.map +1 -0
  5. package/lib/types/client/evaluator.d.ts.map +1 -0
  6. package/lib/types/client/evaluator.js.map +1 -0
  7. package/lib/types/client/guard.d.ts.map +1 -0
  8. package/lib/types/client/guard.js.map +1 -0
  9. package/lib/types/client/index.d.ts.map +1 -0
  10. package/lib/types/client/index.js.map +1 -0
  11. package/lib/types/client/inspect-registry.d.ts.map +1 -0
  12. package/lib/types/client/inspect-registry.js.map +1 -0
  13. package/lib/types/client/orchestrator.d.ts.map +1 -0
  14. package/lib/types/client/orchestrator.js.map +1 -0
  15. package/lib/types/client/providers.d.ts.map +1 -0
  16. package/lib/types/client/providers.js.map +1 -0
  17. package/lib/types/client/runtime.d.ts.map +1 -0
  18. package/lib/types/client/runtime.js.map +1 -0
  19. package/lib/types/client/slot-catalog.d.ts +6 -2
  20. package/lib/types/client/slot-catalog.d.ts.map +1 -0
  21. package/lib/types/client/slot-catalog.js.map +1 -0
  22. package/lib/types/index.d.ts.map +1 -0
  23. package/lib/types/index.js.map +1 -0
  24. package/package.json +14 -11
  25. package/src/client/api-catalog.ts +1208 -0
  26. package/src/client/evaluator.ts +222 -0
  27. package/src/client/guard.ts +245 -0
  28. package/src/client/index.ts +308 -0
  29. package/src/client/inspect-registry.ts +150 -0
  30. package/src/client/orchestrator.ts +458 -0
  31. package/src/client/providers.ts +263 -0
  32. package/src/client/runtime.ts +512 -0
  33. package/src/client/slot-catalog.ts +5782 -0
  34. package/src/index.ts +9 -0
@@ -0,0 +1,512 @@
1
+ /**
2
+ * Per-package browser lifecycle: evaluate the closure, wrap `apply` in the guard
3
+ * facade, seat a ready-made factory in the module table, and create a loader
4
+ * entry — so dynamic packages ride the exact machinery static plugins do
5
+ * (activation gating on inject, fiber-effect cleanup, status projection). Unload
6
+ * = loader entry removal (fiber disposal cascades slot entries and facade
7
+ * effects) + factory invalidation + style removal.
8
+ *
9
+ * The engine answers its caller: `load` resolves with what this page ended up
10
+ * with, which is what the run orchestration reports back to the host. Loads
11
+ * converge by Plugin Run ID against live state, not history: loading the exact
12
+ * activation this page already runs is a no-op that still answers, another run
13
+ * replaces it, and the same Package after a retract loads afresh. Per-Plugin
14
+ * serialization keeps a second request from interleaving with one in flight.
15
+ */
16
+
17
+ import type { Context } from '@deepseek-ai/cordis'
18
+ import type { Loader } from '@deepseek-ai/cordis-plugin-loader'
19
+ import type {
20
+ CordisDynamicPackageId, CordisDynamicPluginId, CordisDynamicPluginRunId, DynamicCordisPackage,
21
+ SessionId,
22
+ } from '@deepseek-ai/dsh-api-remotes/client'
23
+ import type { ClientModuleSystem } from '@deepseek-ai/dsh-client-modules/client'
24
+ import type { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client'
25
+ import { DynamicCordisStyles, evaluateClientHalf, DYNAMIC_CLIENT_REDIRECTS } from './evaluator.ts'
26
+ import type { DynamicCordisEvaluatedPlugin } from './evaluator.ts'
27
+ import { dynamicCordisContext } from './guard.ts'
28
+ import type { DynamicCordisSlotLedgerRow } from './guard.ts'
29
+
30
+ /**
31
+ * Snapshot source a surface can subscribe to (the render seam's observable
32
+ * shape). Lives here because both this engine and the run orchestration publish
33
+ * through it, and the orchestration already depends on this module.
34
+ */
35
+ export interface CordisObservable<T> {
36
+ /** Current value; the reference is stable between mutations. */
37
+ getSnapshot(): T
38
+ /**
39
+ * Observe mutations.
40
+ * @param fn - notified after each committed change.
41
+ * @returns unsubscribe.
42
+ */
43
+ subscribe(fn: () => void): () => void
44
+ }
45
+
46
+ /** Which stage of a load failed, as the page classified it. */
47
+ export type DynamicCordisLoadErrorCause = 'evaluate' | 'module-import' | 'activate'
48
+
49
+ /** Error fields retained by the page runner and Host transport. */
50
+ export interface CordisErrorDetails {
51
+ /** Original error message. */
52
+ message: string
53
+ /** Original stack when the thrown value supplied one. */
54
+ stack?: string
55
+ }
56
+
57
+ /** One package's browser half as the host handed it over. */
58
+ export interface DynamicCordisClientHalf {
59
+ /** Stable Plugin instance. */
60
+ pluginId: CordisDynamicPluginId
61
+ /** Immutable Package source version. */
62
+ packageId: CordisDynamicPackageId
63
+ /** Exact activation. */
64
+ pluginRunId: CordisDynamicPluginRunId
65
+ /** Session the run is carried out for; a later render failure is reported under it. */
66
+ agentId: SessionId
67
+ /** Label from the define call; also the plugin name. */
68
+ name: string
69
+ /** Browser-half source: an async function body returning a plugin. */
70
+ code: string
71
+ }
72
+
73
+ /**
74
+ * One render-time crash of a dynamic package's slot entry, as this page reports
75
+ * it. Post-settle diagnosis only: the run it belongs to was answered long before
76
+ * (a package that crashes while rendering loaded successfully), so this never
77
+ * reaches a run resolution.
78
+ */
79
+ export interface DynamicCordisRenderFailure {
80
+ /** Slot key the crashed entry rendered under. */
81
+ slot: string
82
+ /** What the author has to read to fix it: the crash text, plus a redirect when it names a withheld global. */
83
+ message: string
84
+ /** Original render failure stack when available. */
85
+ stack?: string
86
+ /** Whether the crash retired the entry from its cell — the package's UI is gone, not merely broken. */
87
+ abdicated: boolean
88
+ }
89
+
90
+ /**
91
+ * What this page ended up with. A parked package is a success — the browser half
92
+ * settled and waits on declared services this page has not got.
93
+ */
94
+ export type DynamicCordisLoadResult =
95
+ | { ok: true; pluginRunId: CordisDynamicPluginRunId; waitingFor?: string[] }
96
+ | ({ ok: false; cause: DynamicCordisLoadErrorCause; error?: unknown } & CordisErrorDetails)
97
+
98
+ /** The `window.__ModuleLoader__` registration sink (client-modules contract C6). */
99
+ interface ModuleLoaderSink {
100
+ __ModuleLoader__?: {
101
+ load(handoff: { id: string; factory: (require: (spec: string) => unknown) => unknown }): void
102
+ }
103
+ }
104
+
105
+ /** One live package's bookkeeping. */
106
+ interface LivePackage {
107
+ pkg: DynamicCordisPackage
108
+ entryId: string
109
+ styles: DynamicCordisStyles
110
+ ledger: DynamicCordisSlotLedgerRow[]
111
+ /** Services the browser half declared and this page has not got (parked, still a success). */
112
+ waitingFor: string[]
113
+ }
114
+
115
+ /** Runner dependencies, resolved by the plugin entry at activation. */
116
+ export interface DynamicCordisRunnerEnv {
117
+ /** The client root context (service reads and the guard's fiber owner). */
118
+ ctx: Context
119
+ /** Client cordis Loader: dynamic packages become entries under it. */
120
+ loader: Loader
121
+ /** Module table, for factory invalidation before every (re-)registration. */
122
+ modules: ClientModuleSystem
123
+ /** Slot registry, for the entry-crash supervision seam. */
124
+ slots: SlotRegistry
125
+ /** Route one `host.call` to the package's host half through the Remote namespace. */
126
+ invoke(
127
+ pluginId: CordisDynamicPluginId,
128
+ pluginRunId: CordisDynamicPluginRunId,
129
+ method: string,
130
+ args: unknown,
131
+ ): Promise<unknown>
132
+ /**
133
+ * Send one render-time crash back to the session that authored the package.
134
+ * Fire-and-forget by contract: the crash already happened, and a failed report
135
+ * must not become a second failure.
136
+ * @param agentId - session the crashed package was run for.
137
+ * @param id - the crashed package.
138
+ * @param failure - slot, teaching text, and whether the entry was retired.
139
+ */
140
+ reportRenderFailure(
141
+ agentId: SessionId,
142
+ pluginId: CordisDynamicPluginId,
143
+ pluginRunId: CordisDynamicPluginRunId,
144
+ failure: DynamicCordisRenderFailure,
145
+ ): void
146
+ /** Send one post-activation Client guard rejection to the owning Agent. */
147
+ reportGuardFailure(
148
+ agentId: SessionId,
149
+ pluginId: CordisDynamicPluginId,
150
+ pluginRunId: CordisDynamicPluginRunId,
151
+ failure: CordisErrorDetails,
152
+ ): void
153
+ }
154
+
155
+ /** Module-table id of one package (also its loader entry name and fiber name). */
156
+ function moduleIdOf(id: CordisDynamicPluginId): string {
157
+ return `dyn/${id}`
158
+ }
159
+
160
+ /** One live package's contribution summary in this page. */
161
+ export interface DynamicCordisLivePackage {
162
+ /** Stable Plugin instance. */
163
+ pluginId: CordisDynamicPluginId
164
+ /** Immutable Package source version. */
165
+ packageId: CordisDynamicPackageId
166
+ /** Exact activation loaded in this page. */
167
+ pluginRunId: CordisDynamicPluginRunId
168
+ /** Label from the define call. */
169
+ name: string
170
+ /** Slot names and `factory:<name>` definitions this package registered here. */
171
+ slots: string[]
172
+ /** Live injected-style tag count. */
173
+ styleCount: number
174
+ }
175
+
176
+ /** The browser-side load engine for dynamic packages. */
177
+ export class DynamicCordisPackageRunner {
178
+ private readonly live = new Map<CordisDynamicPluginId, LivePackage>()
179
+ /** Serializes load/unload per package id (a second request can outrun a slow load). */
180
+ private readonly queues = new Map<CordisDynamicPluginId, Promise<unknown>>()
181
+ private readonly changeListeners = new Set<() => void>()
182
+ /** Page-local shadowing rank. A later registration receives a lower priority. */
183
+ private nextPriority = 0
184
+ /**
185
+ * Which package seated which component, and for whom. Component identity is the
186
+ * only attribution key that holds:
187
+ * - the registry stores the component verbatim, so a crashed entry carries its
188
+ * own way back — no parallel entry ledger to keep in step;
189
+ * - `entry.registrant` is `options.registrant ?? fiber.name` and the facade does
190
+ * not strip a package-supplied one, so a package could name itself something
191
+ * else — attributing by it would let a package impersonate another;
192
+ * - the assigned shadowing priority is unique but absent on chain entries (their
193
+ * election is deliberately left alone), so it would miss chain crashes;
194
+ * - a package torn down between the crash and the report is still attributable,
195
+ * because this index does not depend on the live record.
196
+ *
197
+ * Two packages cannot collide here: each browser half is evaluated in its own
198
+ * closure, so no component object reaches two of them. A collision is only
199
+ * possible inside ONE package (the same component seated twice), where both
200
+ * entries map to the same id and the value is identical.
201
+ */
202
+ private readonly owners = new WeakMap<object, {
203
+ pluginId: CordisDynamicPluginId
204
+ pluginRunId: CordisDynamicPluginRunId
205
+ agentId: SessionId
206
+ }>()
207
+ /** This page's last render crash per package: what a run surface shows on the row. */
208
+ private readonly failures = new Map<CordisDynamicPluginId, DynamicCordisRenderFailure>()
209
+ private readonly unwatch: () => void
210
+ private snapshotCache: readonly DynamicCordisLivePackage[] | undefined
211
+ private failureCache: ReadonlyMap<CordisDynamicPluginId, DynamicCordisRenderFailure> | undefined
212
+
213
+ /** @param env - loader/module/slot wiring plus the two host verbs this engine uses. */
214
+ constructor(private readonly env: DynamicCordisRunnerEnv) {
215
+ // The supervision seam fires for EVERY entry crash on the page, factory UI
216
+ // included; only the ones this runner seated are ours to report.
217
+ this.unwatch = env.slots.onEntryError((slot, entry, error, info) => {
218
+ const component: unknown = (entry as { component?: unknown }).component
219
+ const owner = indexable(component) ? this.owners.get(component) : undefined
220
+ if (owner === undefined) return
221
+ const details = errorDetails(error)
222
+ const failure: DynamicCordisRenderFailure = {
223
+ slot,
224
+ message: renderFailureMessage(slot, details.message),
225
+ ...details.stack === undefined ? {} : { stack: details.stack },
226
+ abdicated: info.abdicated,
227
+ }
228
+ // One observation, two outlets with different owners and lifetimes: the host
229
+ // keeps the last crash ACROSS pages for the model, this map is what THIS page
230
+ // currently shows. Neither is derived from the other.
231
+ env.reportRenderFailure(owner.agentId, owner.pluginId, owner.pluginRunId, failure)
232
+ this.failures.set(owner.pluginId, failure)
233
+ this.notify()
234
+ })
235
+ }
236
+
237
+ /**
238
+ * Observe live-set changes (the run-state surface's re-render seam).
239
+ * @param fn - notified after every converged mutation.
240
+ * @returns unsubscribe.
241
+ */
242
+ subscribe(fn: () => void): () => void {
243
+ this.changeListeners.add(fn)
244
+ return () => { this.changeListeners.delete(fn) }
245
+ }
246
+
247
+ /**
248
+ * This page's last render crash per package, on the same notification channel as
249
+ * the live set — a surface that already subscribed learns about a crash without
250
+ * a second mechanism to wire.
251
+ */
252
+ readonly renderFailures: CordisObservable<ReadonlyMap<CordisDynamicPluginId, DynamicCordisRenderFailure>> = {
253
+ getSnapshot: () => this.failureCache ??= new Map(this.failures),
254
+ subscribe: fn => this.subscribe(fn),
255
+ }
256
+
257
+ /**
258
+ * What this page currently has loaded (stable reference between mutations, so
259
+ * it can back a snapshot selector).
260
+ * @returns one row per live package.
261
+ */
262
+ getSnapshot(): readonly DynamicCordisLivePackage[] {
263
+ return this.snapshotCache ??= [...this.live.values()].map(({ pkg, ledger, styles }) => ({
264
+ pluginId: pkg.pluginId,
265
+ packageId: pkg.packageId,
266
+ pluginRunId: pkg.pluginRunId,
267
+ name: pkg.name,
268
+ slots: [...new Set(ledger.map(row => row.slot))],
269
+ styleCount: styles.count,
270
+ }))
271
+ }
272
+
273
+ /**
274
+ * Whether this page has the browser half loaded — page-local truth, never the
275
+ * host's "it is running".
276
+ * @param pluginId - stable Plugin identity.
277
+ * @returns true while one activation of the Plugin is live here.
278
+ */
279
+ isLoaded(pluginId: CordisDynamicPluginId): boolean {
280
+ return this.live.has(pluginId)
281
+ }
282
+
283
+ /**
284
+ * Load one browser half into this page and answer what happened.
285
+ * @param half - source for one exact Host activation.
286
+ * @returns the outcome the run orchestration reports to the host.
287
+ */
288
+ load(half: DynamicCordisClientHalf): Promise<DynamicCordisLoadResult> {
289
+ return this.enqueue(half.pluginId, async () => {
290
+ const current = this.live.get(half.pluginId)
291
+ if (current !== undefined) {
292
+ // Already running this activation here: nothing to load, but the caller
293
+ // still needs an answer (a replayed run must not look unacknowledged).
294
+ if (current.pkg.pluginRunId === half.pluginRunId) return settled(current)
295
+ await this.teardown(current.pkg.pluginId, current.entryId, current.styles)
296
+ }
297
+ const result = await this.mount(half)
298
+ this.notify()
299
+ return result
300
+ })
301
+ }
302
+
303
+ /**
304
+ * Unload one package (`cordis/dynamic-retract`: a stop, or an undefine
305
+ * that stops first).
306
+ * @param pluginId - stable Plugin identity.
307
+ * @param pluginRunId - exact activation being retracted; a newer run survives.
308
+ */
309
+ retract(pluginId: CordisDynamicPluginId, pluginRunId: CordisDynamicPluginRunId): void {
310
+ void this.enqueue(pluginId, async () => {
311
+ const current = this.live.get(pluginId)
312
+ if (current === undefined || current.pkg.pluginRunId !== pluginRunId) return
313
+ await this.teardown(pluginId, current.entryId, current.styles)
314
+ this.notify()
315
+ })
316
+ }
317
+
318
+ /** Unload everything (plugin disposal path). */
319
+ async dispose(): Promise<void> {
320
+ this.unwatch()
321
+ for (const current of [...this.live.values()]) {
322
+ await this.teardown(current.pkg.pluginId, current.entryId, current.styles)
323
+ }
324
+ this.notify()
325
+ }
326
+
327
+ private notify(): void {
328
+ this.snapshotCache = undefined
329
+ this.failureCache = undefined
330
+ for (const fn of [...this.changeListeners]) fn()
331
+ }
332
+
333
+ /** Queue one package operation behind that package's previous ones. */
334
+ private enqueue<T>(id: CordisDynamicPluginId, op: () => Promise<T>): Promise<T> {
335
+ const previous = this.queues.get(id) ?? Promise.resolve()
336
+ const next = previous.then(op)
337
+ // The queue tail must survive this operation's failure, or one rejection
338
+ // would wedge every later operation on the same package.
339
+ this.queues.set(id, next.then(() => {}, () => {}))
340
+ return next
341
+ }
342
+
343
+ private async mount(half: DynamicCordisClientHalf): Promise<DynamicCordisLoadResult> {
344
+ const styles = new DynamicCordisStyles(half.pluginId)
345
+ const ledger: DynamicCordisSlotLedgerRow[] = []
346
+ let plugin: DynamicCordisEvaluatedPlugin | ((ctx: unknown) => unknown)
347
+ try {
348
+ plugin = await evaluateClientHalf(half.pluginId, half.code, {
349
+ invoke: (method, args) => this.env.invoke(half.pluginId, half.pluginRunId, method, args),
350
+ noteError: (message) => {
351
+ // A loaded package's own console.error: a page-local diagnostic with
352
+ // no wire carrier (the run round trip settled long before).
353
+ console.error(`[cordis-client-runner] ${half.pluginId} logged an error:`, message)
354
+ },
355
+ }, styles)
356
+ } catch (error) {
357
+ styles.dispose()
358
+ return { ok: false, cause: 'evaluate', ...errorDetails(error), error }
359
+ }
360
+
361
+ const pkg: DynamicCordisPackage = {
362
+ pluginId: half.pluginId,
363
+ packageId: half.packageId,
364
+ pluginRunId: half.pluginRunId,
365
+ name: half.name,
366
+ }
367
+ const surface = this.guardedSurface(pkg, half.agentId, plugin, ledger)
368
+ const moduleId = moduleIdOf(half.pluginId)
369
+ // Invalidate-then-register keeps re-loading legal: the module table throws
370
+ // loudly on a duplicate factory registration.
371
+ this.env.modules.invalidate(moduleId)
372
+ const sink = (globalThis as ModuleLoaderSink).__ModuleLoader__
373
+ if (sink === undefined) {
374
+ throw new Error('cordis-client-runner: window.__ModuleLoader__ is missing (booted outside the web shell?)')
375
+ }
376
+ sink.load({ id: moduleId, factory: () => surface })
377
+
378
+ const entryId = await this.env.loader.create({ name: moduleId })
379
+ const fiber = this.env.loader.resolve(entryId).fiber
380
+ if (fiber === undefined) {
381
+ await this.teardown(half.pluginId, entryId, styles)
382
+ return { ok: false, cause: 'module-import', message: 'module import failed (see the browser console)' }
383
+ }
384
+ try {
385
+ await fiber.await()
386
+ } catch (error) {
387
+ await this.teardown(half.pluginId, entryId, styles)
388
+ return { ok: false, cause: 'activate', ...errorDetails(error), error }
389
+ }
390
+ // Settled but not active = legal pending on an unsatisfied declaration. The
391
+ // record is seated only now, so an error mirrored during `apply` cannot
392
+ // claim the package is already live.
393
+ const waitingFor = Object.keys(fiber.inject).filter(name => this.env.ctx.get(name) === undefined)
394
+ const record: LivePackage = { pkg, entryId, styles, ledger, waitingFor }
395
+ this.live.set(half.pluginId, record)
396
+ // A fresh load answers for itself: whatever this page last showed as crashed
397
+ // is no longer true of what is mounted now.
398
+ this.failures.delete(half.pluginId)
399
+ return settled(record)
400
+ }
401
+
402
+ /**
403
+ * Wrap the evaluated plugin so `apply` sees the guard facade; the surface
404
+ * doubles as the module-table module. The plugin's OWN `inject` survives (the
405
+ * object form's declaration is the facade's service gate, mirroring the host
406
+ * sandbox reading `ctx.fiber.inject`); the function form has no declaration
407
+ * site and therefore reaches no service.
408
+ */
409
+ private guardedSurface(
410
+ pkg: DynamicCordisPackage,
411
+ agentId: SessionId,
412
+ plugin: DynamicCordisEvaluatedPlugin | ((ctx: unknown) => unknown),
413
+ ledger: DynamicCordisSlotLedgerRow[],
414
+ ): DynamicCordisEvaluatedPlugin {
415
+ const claim = (component: unknown): void => {
416
+ if (indexable(component)) {
417
+ this.owners.set(component, { pluginId: pkg.pluginId, pluginRunId: pkg.pluginRunId, agentId })
418
+ }
419
+ }
420
+ const guarded = (ctx: unknown): Context => dynamicCordisContext(ctx as Context, {
421
+ pkg,
422
+ ledger,
423
+ claim,
424
+ allocatePriority: () => --this.nextPriority,
425
+ reportFailure: (error) => {
426
+ this.env.reportGuardFailure(agentId, pkg.pluginId, pkg.pluginRunId, errorDetails(error))
427
+ },
428
+ })
429
+ if (typeof plugin === 'function') {
430
+ return { name: moduleIdOf(pkg.pluginId), apply: (ctx: unknown) => plugin(guarded(ctx)) }
431
+ }
432
+ return {
433
+ ...plugin,
434
+ name: moduleIdOf(pkg.pluginId),
435
+ apply: (ctx: unknown, config?: unknown) => plugin.apply(guarded(ctx), config),
436
+ }
437
+ }
438
+
439
+ /**
440
+ * Unload one package's contributions. Takes the pieces rather than the record
441
+ * because a load can fail before any record is seated.
442
+ */
443
+ private async teardown(
444
+ id: CordisDynamicPluginId,
445
+ entryId: string,
446
+ styles: DynamicCordisStyles,
447
+ ): Promise<void> {
448
+ this.live.delete(id)
449
+ // Nothing of this package renders here any more, so a crash row would outlive
450
+ // the thing it described.
451
+ this.failures.delete(id)
452
+ // Entry removal disposes the fiber (slot entries and facade effects
453
+ // cascade); the factory invalidation makes a later re-load legal.
454
+ const disposal = this.env.loader.resolve(entryId).fiber?.dispose()
455
+ this.env.loader.remove(entryId)
456
+ await disposal
457
+ this.env.modules.invalidate(moduleIdOf(id))
458
+ styles.dispose()
459
+ }
460
+ }
461
+
462
+ /** The success answer for a package that is live here, parked or active. */
463
+ function settled(record: { pkg: DynamicCordisPackage; waitingFor: string[] }): DynamicCordisLoadResult {
464
+ return {
465
+ ok: true,
466
+ pluginRunId: record.pkg.pluginRunId,
467
+ ...record.waitingFor.length > 0 ? { waitingFor: record.waitingFor } : {},
468
+ }
469
+ }
470
+
471
+ /**
472
+ * Whether a component can key the ownership index. Identity is the key, so only
473
+ * objects and functions qualify — a package may register anything, and what it
474
+ * registered is what a crash report carries back.
475
+ * @param component - whatever a package passed as its component.
476
+ * @returns true when the value can be indexed by identity.
477
+ */
478
+ function indexable(component: unknown): component is object {
479
+ return typeof component === 'object' && component !== null || typeof component === 'function'
480
+ }
481
+
482
+ /**
483
+ * Preserve error fields for a load result without fabricating a stack.
484
+ * @param error - original thrown value.
485
+ * @returns its message and original string stack, when present.
486
+ */
487
+ /* jscpd:ignore-start */
488
+ export function errorDetails(error: unknown): CordisErrorDetails {
489
+ if (typeof error !== 'object' || error === null) return { message: String(error) }
490
+ const message = 'message' in error && typeof error.message === 'string'
491
+ ? error.message
492
+ : Object.prototype.toString.call(error)
493
+ const stack = 'stack' in error && typeof error.stack === 'string' ? error.stack : undefined
494
+ return { message, ...stack === undefined ? {} : { stack } }
495
+ }
496
+ /* jscpd:ignore-end */
497
+
498
+ /**
499
+ * What the authoring session reads about one render crash. The slot says where it
500
+ * happened, the crash message says what broke, and a withheld global named in that
501
+ * text pulls in its redirect — a package that reached `window.setInterval` around
502
+ * the closure trap crashes with the engine's bare message, which teaches nothing.
503
+ */
504
+ function renderFailureMessage(slot: string, message: string): string {
505
+ const redirect = Object.entries(DYNAMIC_CLIENT_REDIRECTS)
506
+ .find(([name, text]) => message.includes(name) && !message.includes(text))?.[1]
507
+ const subject = slot.startsWith('factory:')
508
+ ? `your component in Factory "${slot.slice('factory:'.length)}"`
509
+ : `your entry in slot "${slot}"`
510
+ return `${subject} crashed while React rendered it: ${message}`
511
+ + (redirect === undefined ? '' : `\n${redirect}`)
512
+ }