@bgub/fig-server 0.1.0-alpha.1 → 0.1.0-alpha.3

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.
@@ -0,0 +1,602 @@
1
+ import { a as componentStack, c as errorMessage, d as streamHighWaterMark, f as withContextValue, i as cloneContextValues, n as suppressesImagePreloads, o as createStaticDispatcher, s as deferred, t as imagePreloadFromHostProps, u as streamFlowBlocked } from "./image-preloads-D3OBEaWp.js";
2
+ import { Fragment, isValidElement } from "@bgub/fig";
3
+ import { assetResourceDestination, assetResourceKey, checkpointPayloadGraph, clientOnlyHostBehavior, clientReferenceAssets, createPayloadGraphEncodeContext, createRendererDataStore, definePayloadGraphElement, describeInvalidChild, encodePayloadDataEntries, encodePayloadValueWithGraph, isActivity, isAssets, isClientReference, isContext, isErrorBoundary, isFigAssetResource, isPlainPayloadValue, isPortal, isSuspense, isThenable, isViewTransition, jsonPayloadCodec, readThenable, rollbackPayloadGraph, serializePayloadArray, serializePayloadMap, serializePayloadPlainObject, serializePayloadSet, setCurrentDataStore, setCurrentDispatcher } from "@bgub/fig/internal";
4
+ //#region src/payload.ts
5
+ var PayloadRequestCancelledError = class extends Error {
6
+ constructor() {
7
+ super("Payload request cancelled.");
8
+ this.name = "PayloadRequestCancelledError";
9
+ }
10
+ };
11
+ const errorStacks = /* @__PURE__ */ new WeakMap();
12
+ const childrenTreeProps = /* @__PURE__ */ new Set(["children"]);
13
+ const emptyTreeProps = /* @__PURE__ */ new Set();
14
+ const suspenseTreeProps = /* @__PURE__ */ new Set(["children", "fallback"]);
15
+ function renderToPayloadStream(node, options = {}) {
16
+ const { request, stream } = createPayloadRequest(node, options);
17
+ return {
18
+ allReady: request.allReady.promise,
19
+ contentType: jsonPayloadCodec.contentType,
20
+ stream
21
+ };
22
+ }
23
+ function createPayloadRequest(node, options) {
24
+ throwIfAborted(options.signal);
25
+ const pendingDataSnapshots = /* @__PURE__ */ new Map();
26
+ const request = {
27
+ allReady: deferred(),
28
+ cleanupAbortListener: () => void 0,
29
+ clientReferenceRows: /* @__PURE__ */ new Map(),
30
+ clientReferenceAssets: options.clientReferenceAssets,
31
+ componentAssets: options.componentAssets,
32
+ controller: null,
33
+ dataStore: createRendererDataStore({
34
+ getLane: () => null,
35
+ onEntryChange: (entry) => {
36
+ pendingDataSnapshots.set(entry.canonicalKey, entry);
37
+ },
38
+ partition: options.dataPartition,
39
+ schedule: () => void 0
40
+ }),
41
+ emittedAssetKeys: /* @__PURE__ */ new Set(),
42
+ emittedDataKeys: /* @__PURE__ */ new Set(),
43
+ graph: createPayloadGraphEncodeContext(),
44
+ nextRowId: 1,
45
+ nextUseId: 0,
46
+ onError: options.onError,
47
+ pendingDataSnapshots,
48
+ pendingTasks: 0,
49
+ pingedTasks: [],
50
+ queuedRows: [],
51
+ flushingRows: false,
52
+ status: "open",
53
+ workScheduled: false
54
+ };
55
+ request.allReady.promise.catch(() => void 0);
56
+ request.pingedTasks.push(createTask(request, 0, {
57
+ kind: "node",
58
+ value: node
59
+ }, /* @__PURE__ */ new Map(), false, null));
60
+ const stream = new ReadableStream({
61
+ start(controller) {
62
+ request.controller = controller;
63
+ flushRows(request);
64
+ },
65
+ pull() {
66
+ flushRows(request);
67
+ },
68
+ cancel(reason) {
69
+ abortPayloadRequest(request, reason);
70
+ }
71
+ }, new ByteLengthQueuingStrategy({ highWaterMark: streamHighWaterMark(options.highWaterMark) }));
72
+ const signal = options.signal;
73
+ if (signal !== void 0) {
74
+ const abortListener = () => abortPayloadRequest(request, signal.reason);
75
+ signal.addEventListener("abort", abortListener, { once: true });
76
+ request.cleanupAbortListener = () => {
77
+ signal.removeEventListener("abort", abortListener);
78
+ request.cleanupAbortListener = () => void 0;
79
+ };
80
+ }
81
+ scheduleWork(request);
82
+ return {
83
+ request,
84
+ stream
85
+ };
86
+ }
87
+ function createTask(request, id, value, contextValues, imagePreloadsSuppressed, stack) {
88
+ request.pendingTasks += 1;
89
+ return {
90
+ contextValues,
91
+ id,
92
+ imagePreloadsSuppressed,
93
+ stack,
94
+ ...value
95
+ };
96
+ }
97
+ function performWork(request) {
98
+ if (request.status === "closed") return;
99
+ const tasks = request.pingedTasks;
100
+ request.pingedTasks = [];
101
+ for (const task of tasks) retryTask(request, task);
102
+ flushRows(request);
103
+ }
104
+ function retryTask(request, task) {
105
+ const frame = {
106
+ contextValues: cloneContextValues(task.contextValues),
107
+ dispatcher: null,
108
+ pendingAssets: [],
109
+ request,
110
+ imagePreloadsSuppressed: task.imagePreloadsSuppressed,
111
+ stack: task.stack
112
+ };
113
+ try {
114
+ let value;
115
+ switch (task.kind) {
116
+ case "node":
117
+ value = serializeNode(task.value, frame);
118
+ break;
119
+ case "node-promise":
120
+ value = serializeNode(readThenable(task.value), frame);
121
+ break;
122
+ case "promise":
123
+ value = serializeValue(readThenable(task.value), frame);
124
+ break;
125
+ }
126
+ flushFrameAssets(frame, task.id);
127
+ emitDataRows(request);
128
+ emitRow(request, {
129
+ id: task.id,
130
+ tag: "model",
131
+ value
132
+ });
133
+ finishTask(request);
134
+ } catch (error) {
135
+ if (isThenable(error)) {
136
+ flushFrameAssets(frame, task.id);
137
+ error.then(() => pingTask(request, task), () => pingTask(request, task));
138
+ return;
139
+ }
140
+ flushFrameAssets(frame, task.id);
141
+ emitRow(request, {
142
+ id: task.id,
143
+ tag: "error",
144
+ value: errorRowPayload(request, error, task.stack)
145
+ });
146
+ finishTask(request);
147
+ }
148
+ }
149
+ function finishTask(request) {
150
+ request.pendingTasks -= 1;
151
+ if (request.pendingTasks === 0) request.allReady.resolve(void 0);
152
+ }
153
+ function emitDataRows(request) {
154
+ const entries = [];
155
+ for (const snapshot of request.pendingDataSnapshots.values()) {
156
+ if (!snapshot.hasValue || snapshot.status === "refreshing") continue;
157
+ const key = snapshot.canonicalKey;
158
+ if (request.emittedDataKeys.has(key)) {
159
+ request.pendingDataSnapshots.delete(snapshot.canonicalKey);
160
+ continue;
161
+ }
162
+ request.emittedDataKeys.add(key);
163
+ request.pendingDataSnapshots.delete(snapshot.canonicalKey);
164
+ entries.push({
165
+ key: snapshot.key,
166
+ value: snapshot.value
167
+ });
168
+ }
169
+ if (entries.length > 0) emitRow(request, {
170
+ tag: "data",
171
+ value: encodePayloadDataEntries(entries)
172
+ });
173
+ }
174
+ function flushFrameAssets(frame, rowId) {
175
+ if (frame.pendingAssets.length === 0) return;
176
+ const value = frame.pendingAssets.splice(0);
177
+ emitRow(frame.request, {
178
+ for: rowId,
179
+ tag: "assets",
180
+ value
181
+ });
182
+ }
183
+ function createPayloadDispatcher(frame) {
184
+ const dispatcher = createStaticDispatcher({
185
+ contextValues: frame.contextValues,
186
+ externalStoreError: "useSyncExternalStore requires getServerSnapshot during payload render.",
187
+ readPromise: readThenable,
188
+ readData(resource, args) {
189
+ return frame.request.dataStore.readData(resource, args, frame);
190
+ },
191
+ preloadData(resource, args) {
192
+ frame.request.dataStore.preloadData(resource, ...args);
193
+ },
194
+ useId() {
195
+ const id = `fig-pl-${frame.request.nextUseId.toString(32)}`;
196
+ frame.request.nextUseId += 1;
197
+ return id;
198
+ },
199
+ updateError: "State updates are not allowed during payload render."
200
+ });
201
+ {
202
+ const throwClientApi = (hook) => () => {
203
+ throw new Error(`${hook} cannot be used during payload render: serialized components are render-only. Move state, effects, and interactivity into a client reference.`);
204
+ };
205
+ dispatcher.useState = throwClientApi("useState");
206
+ dispatcher.useActionState = throwClientApi("useActionState");
207
+ dispatcher.useTransition = throwClientApi("useTransition");
208
+ dispatcher.useStableEvent = throwClientApi("useStableEvent");
209
+ dispatcher.useReactive = throwClientApi("useReactive");
210
+ dispatcher.useBeforePaint = throwClientApi("useBeforePaint");
211
+ dispatcher.useBeforeLayout = throwClientApi("useBeforeLayout");
212
+ }
213
+ return dispatcher;
214
+ }
215
+ function serializeNode(node, frame) {
216
+ if (Array.isArray(node)) return flattenChildArrays(node).map((child) => serializeNodeOrLazy(child, frame));
217
+ if (node === null || node === void 0 || typeof node === "boolean") return node === void 0 ? { $fig: "undefined" } : node;
218
+ if (typeof node === "string" || typeof node === "number") return node;
219
+ if (isPortal(node)) return null;
220
+ if (isValidElement(node)) return serializeElement(node, frame, false);
221
+ if (isThenable(node)) return outlineTask(frame, {
222
+ kind: "node-promise",
223
+ value: node
224
+ }, "promise", node);
225
+ throw invalidChildError$1(node);
226
+ }
227
+ function serializeNodeOrLazy(node, frame, preserveElementIdentity = false) {
228
+ const graphCheckpoint = checkpointPayloadGraph(frame.request.graph);
229
+ const assetCheckpoint = frame.pendingAssets.length;
230
+ try {
231
+ if (!isValidElement(node)) return serializeNode(node, frame);
232
+ return serializeElement(node, frame, preserveElementIdentity);
233
+ } catch (error) {
234
+ rollbackPayloadGraph(frame.request.graph, graphCheckpoint);
235
+ const scopedAssets = frame.pendingAssets.splice(assetCheckpoint);
236
+ if (isThenable(error)) return outlineTask(frame, {
237
+ kind: "node",
238
+ value: node
239
+ }, "lazy", error, scopedAssets);
240
+ return outlineError(frame, error, "lazy", scopedAssets);
241
+ }
242
+ }
243
+ function serializeElement(element, frame, preserveIdentity) {
244
+ const type = element.type;
245
+ if (typeof type === "string") return serializeHostElement(element, type, frame, preserveIdentity);
246
+ if (type === Fragment) return serializeElementModel(element, { $fig: "fragment" }, frame, preserveIdentity, childrenTreeProps);
247
+ if (isClientReference(type)) return serializeElementModel(element, {
248
+ $fig: "client",
249
+ id: emitClientReference(frame.request, type)
250
+ }, frame, preserveIdentity);
251
+ if (isContext(type)) return serializeContextProvider(type, element.props, frame);
252
+ if (isAssets(type)) return serializeAssets(element.props, frame);
253
+ if (isSuspense(type)) return serializeElementModel(element, { $fig: "suspense" }, frame, preserveIdentity, suspenseTreeProps);
254
+ if (isErrorBoundary(type)) return serializeNode(element.props.children, frame);
255
+ if (isActivity(type)) return serializeNode(element.props.children, frame);
256
+ if (isViewTransition(type)) return serializeElementModel(element, { $fig: "view-transition" }, frame, preserveIdentity, childrenTreeProps);
257
+ if (typeof type === "function") return serializeFunctionComponent(type, element.props, frame);
258
+ throw new Error("Unsupported Fig element type during payload render.");
259
+ }
260
+ function serializeHostElement(element, type, frame, preserveIdentity) {
261
+ const preload = imagePreloadFromHostProps(type, element.props, frame.imagePreloadsSuppressed);
262
+ if (preload !== null) frame.pendingAssets.push(...serializeAssetResources(frame.request, preload));
263
+ const previousImagePreloadsSuppressed = frame.imagePreloadsSuppressed;
264
+ frame.imagePreloadsSuppressed = previousImagePreloadsSuppressed || suppressesImagePreloads(type);
265
+ try {
266
+ return serializeElementModel(element, type, frame, preserveIdentity, childrenTreeProps);
267
+ } finally {
268
+ frame.imagePreloadsSuppressed = previousImagePreloadsSuppressed;
269
+ }
270
+ }
271
+ function serializeElementModel(element, type, frame, preserveIdentity, treeProps = emptyTreeProps) {
272
+ const id = preserveIdentity ? definePayloadGraphElement(frame.request.graph, element) : void 0;
273
+ if (typeof id === "object") return id;
274
+ const model = {
275
+ $fig: "element",
276
+ key: element.key,
277
+ props: serializeProps(element.props, frame, treeProps, typeof type === "string"),
278
+ type
279
+ };
280
+ if (id !== void 0) model.id = id;
281
+ return model;
282
+ }
283
+ function serializeFunctionComponent(type, props, frame) {
284
+ const assetCheckpoint = frame.pendingAssets.length;
285
+ frame.pendingAssets.push(...serializeAssetResources(frame.request, frame.request.componentAssets?.(type)));
286
+ frame.dispatcher ??= createPayloadDispatcher(frame);
287
+ const previousDispatcher = setCurrentDispatcher(frame.dispatcher);
288
+ const previousDataStore = setCurrentDataStore(frame.request.dataStore);
289
+ const previousStack = frame.stack;
290
+ frame.stack = {
291
+ name: type.name || "Anonymous",
292
+ parent: previousStack
293
+ };
294
+ try {
295
+ if ("$$typeof" in type && type.$$typeof === Symbol.for("fig.data-resource")) throw new Error("Payload components cannot be rendered inside Payload. Render the underlying server component directly, or mount separate Payload components from the client tree.");
296
+ const result = type(props);
297
+ if (isThenable(result)) {
298
+ const scopedAssets = frame.pendingAssets.splice(assetCheckpoint);
299
+ return outlineTask(frame, {
300
+ kind: "node-promise",
301
+ value: result
302
+ }, "promise", result, scopedAssets);
303
+ }
304
+ return serializeNode(result, frame);
305
+ } catch (error) {
306
+ recordErrorStack(error, frame.stack);
307
+ throw error;
308
+ } finally {
309
+ frame.stack = previousStack;
310
+ setCurrentDataStore(previousDataStore);
311
+ setCurrentDispatcher(previousDispatcher);
312
+ }
313
+ }
314
+ function serializeContextProvider(context, props, frame) {
315
+ return withContextValue(frame.contextValues, context, props.value, () => serializeNode(props.children, frame));
316
+ }
317
+ function serializeAssets(props, frame) {
318
+ frame.pendingAssets.push(...serializeAssetResources(frame.request, props.assets));
319
+ return serializeNode(props.children, frame);
320
+ }
321
+ function serializeProps(props, frame, treeProps, hostElement = false) {
322
+ const clientOnlyBehavior = hostElement ? clientOnlyHostBehavior(props) : void 0;
323
+ if (clientOnlyBehavior !== void 0) throw new Error(`Client-only host behavior from ${clientOnlyBehavior} cannot be serialized in a payload; move it into a client reference.`);
324
+ const value = {};
325
+ for (const name of Object.keys(props)) {
326
+ if (hostElement && name === "mix") continue;
327
+ const child = props[name];
328
+ value[name] = treeProps.has(name) ? serializeTreeProp(child, frame) : serializeValue(child, frame);
329
+ }
330
+ return {
331
+ $fig: "object",
332
+ value
333
+ };
334
+ }
335
+ function serializeTreeProp(value, frame) {
336
+ if (Array.isArray(value)) return flattenChildArrays(value).map((child) => serializeNodeOrLazy(child, frame));
337
+ return serializeNodeOrLazy(value, frame);
338
+ }
339
+ function serializeValue(value, frame) {
340
+ if (isPlainPayloadValue(value)) return encodePayloadValueWithGraph(value, frame.request.graph);
341
+ if (isClientReference(value)) return {
342
+ $fig: "client",
343
+ id: emitClientReference(frame.request, value)
344
+ };
345
+ if (isValidElement(value)) return serializeNodeOrLazy(value, frame, true);
346
+ if (isPortal(value)) return null;
347
+ if (isThenable(value)) return outlineTask(frame, {
348
+ kind: "promise",
349
+ value
350
+ }, "promise", value);
351
+ if (typeof value === "function") throw new Error("Functions cannot be passed to client references.");
352
+ if (typeof value === "object" && value !== null) {
353
+ if (value instanceof Date) return encodePayloadValueWithGraph(value, frame.request.graph);
354
+ if (value instanceof Map) return serializePayloadMap(value, frame.request.graph, ([key, item]) => [serializeValue(key, frame), serializeValue(item, frame)]);
355
+ if (value instanceof Set) return serializePayloadSet(value, frame.request.graph, (item) => serializeValue(item, frame));
356
+ if (Array.isArray(value)) return serializePayloadArray(value, frame.request.graph, () => value, (item) => serializeValue(item, frame));
357
+ return serializePayloadPlainObject(value, frame.request.graph, (child) => serializeValue(child, frame));
358
+ }
359
+ throw new Error(`Cannot serialize ${typeof value} into the payload.`);
360
+ }
361
+ function outlineTask(frame, value, referenceKind, wakeable, scopedAssets = []) {
362
+ const request = frame.request;
363
+ const id = request.nextRowId++;
364
+ if (scopedAssets.length > 0) emitRow(request, {
365
+ for: id,
366
+ tag: "assets",
367
+ value: scopedAssets
368
+ });
369
+ const task = createTask(request, id, value, cloneContextValues(frame.contextValues), frame.imagePreloadsSuppressed, stackForError(wakeable, frame.stack));
370
+ wakeable.then(() => pingTask(request, task), () => pingTask(request, task));
371
+ return {
372
+ $fig: referenceKind,
373
+ id
374
+ };
375
+ }
376
+ function outlineError(frame, error, referenceKind, scopedAssets) {
377
+ const request = frame.request;
378
+ const id = request.nextRowId++;
379
+ if (scopedAssets.length > 0) emitRow(request, {
380
+ for: id,
381
+ tag: "assets",
382
+ value: scopedAssets
383
+ });
384
+ emitRow(request, {
385
+ id,
386
+ tag: "error",
387
+ value: errorRowPayload(request, error, frame.stack)
388
+ });
389
+ return {
390
+ $fig: referenceKind,
391
+ id
392
+ };
393
+ }
394
+ function errorRowPayload(request, error, stack) {
395
+ const info = { componentStack: componentStack(stackForError(error, stack)) };
396
+ if (request.onError === void 0) return { message: errorMessage(error) };
397
+ try {
398
+ return request.onError(error, info) ?? {};
399
+ } catch {
400
+ return {};
401
+ }
402
+ }
403
+ function recordErrorStack(error, stack) {
404
+ if (stack === null) return;
405
+ if (typeof error !== "object" || error === null) return;
406
+ if (!errorStacks.has(error)) errorStacks.set(error, stack);
407
+ }
408
+ function stackForError(error, fallback) {
409
+ if (typeof error !== "object" || error === null) return fallback;
410
+ return errorStacks.get(error) ?? fallback;
411
+ }
412
+ function clientReferenceExportName(id) {
413
+ const hashIndex = id.lastIndexOf("#");
414
+ if (hashIndex === -1) return void 0;
415
+ return id.slice(hashIndex + 1) || void 0;
416
+ }
417
+ function emitClientReference(request, reference) {
418
+ const existing = request.clientReferenceRows.get(reference.id);
419
+ if (existing !== void 0) return existing;
420
+ const assets = serializeAssetResources(request, collectClientReferenceAssets(request, reference));
421
+ const value = { id: reference.id };
422
+ if (assets.length > 0) value.assets = assets;
423
+ const exportName = clientReferenceExportName(reference.id);
424
+ if (exportName !== void 0) value.exportName = exportName;
425
+ if (reference.ssr !== void 0) value.ssr = true;
426
+ const id = request.nextRowId++;
427
+ request.clientReferenceRows.set(reference.id, id);
428
+ emitRow(request, {
429
+ id,
430
+ tag: "client",
431
+ value
432
+ });
433
+ return id;
434
+ }
435
+ function serializeAssetResources(request, value) {
436
+ const input = isFigAssetResource(value) ? [value] : Array.isArray(value) ? value : [];
437
+ const resources = [];
438
+ for (const resource of input) {
439
+ if (!isFigAssetResource(resource)) continue;
440
+ if (assetResourceDestination(resource) === "stream") {
441
+ const key = assetResourceKey(resource);
442
+ if (request.emittedAssetKeys.has(key)) continue;
443
+ request.emittedAssetKeys.add(key);
444
+ }
445
+ resources.push(serializeAssetResource(resource));
446
+ }
447
+ return resources;
448
+ }
449
+ function collectClientReferenceAssets(request, reference) {
450
+ const resources = [...clientReferenceAssets(reference)];
451
+ const resolved = request.clientReferenceAssets?.({ id: reference.id });
452
+ if (resolved === void 0) return resources;
453
+ if (isFigAssetResource(resolved)) return [...resources, resolved];
454
+ return Array.isArray(resolved) ? [...resources, ...resolved] : resources;
455
+ }
456
+ function serializeAssetResource(resource) {
457
+ switch (resource.kind) {
458
+ case "stylesheet": {
459
+ const model = {
460
+ href: resource.href,
461
+ kind: resource.kind
462
+ };
463
+ if (resource.crossorigin !== void 0) model.crossorigin = resource.crossorigin;
464
+ if (resource.media !== void 0) model.media = resource.media;
465
+ if (resource.precedence !== void 0) model.precedence = resource.precedence;
466
+ return model;
467
+ }
468
+ case "preload": {
469
+ const model = {
470
+ as: resource.as,
471
+ kind: resource.kind
472
+ };
473
+ if (resource.crossorigin !== void 0) model.crossorigin = resource.crossorigin;
474
+ if (resource.fetchpriority !== void 0) model.fetchpriority = resource.fetchpriority;
475
+ if (resource.href !== void 0) model.href = resource.href;
476
+ if (resource.imagesizes !== void 0) model.imagesizes = resource.imagesizes;
477
+ if (resource.imagesrcset !== void 0) model.imagesrcset = resource.imagesrcset;
478
+ if (resource.referrerpolicy !== void 0) model.referrerpolicy = resource.referrerpolicy;
479
+ if (resource.type !== void 0) model.type = resource.type;
480
+ return model;
481
+ }
482
+ case "modulepreload": {
483
+ const model = {
484
+ href: resource.href,
485
+ kind: resource.kind
486
+ };
487
+ if (resource.crossorigin !== void 0) model.crossorigin = resource.crossorigin;
488
+ if (resource.fetchpriority !== void 0) model.fetchpriority = resource.fetchpriority;
489
+ return model;
490
+ }
491
+ case "script": {
492
+ const model = {
493
+ kind: resource.kind,
494
+ src: resource.src
495
+ };
496
+ if (resource.async !== void 0) model.async = resource.async;
497
+ if (resource.crossorigin !== void 0) model.crossorigin = resource.crossorigin;
498
+ if (resource.defer !== void 0) model.defer = resource.defer;
499
+ if (resource.module !== void 0) model.module = resource.module;
500
+ return model;
501
+ }
502
+ case "font": {
503
+ const model = {
504
+ href: resource.href,
505
+ kind: resource.kind,
506
+ type: resource.type
507
+ };
508
+ if (resource.crossorigin !== void 0) model.crossorigin = resource.crossorigin;
509
+ if (resource.fetchpriority !== void 0) model.fetchpriority = resource.fetchpriority;
510
+ return model;
511
+ }
512
+ case "preconnect": {
513
+ const model = {
514
+ href: resource.href,
515
+ kind: resource.kind
516
+ };
517
+ if (resource.crossorigin !== void 0) model.crossorigin = resource.crossorigin;
518
+ return model;
519
+ }
520
+ case "title": return {
521
+ kind: resource.kind,
522
+ value: resource.value
523
+ };
524
+ case "meta": {
525
+ const model = { kind: resource.kind };
526
+ if (resource.charset !== void 0) model.charset = resource.charset;
527
+ if (resource.content !== void 0) model.content = resource.content;
528
+ if (resource["http-equiv"] !== void 0) model["http-equiv"] = resource["http-equiv"];
529
+ if (resource.key !== void 0) model.key = resource.key;
530
+ if (resource.name !== void 0) model.name = resource.name;
531
+ if (resource.property !== void 0) model.property = resource.property;
532
+ return model;
533
+ }
534
+ }
535
+ }
536
+ function emitRow(request, row) {
537
+ request.queuedRows.push(jsonPayloadCodec.encodeRow(row));
538
+ flushRows(request);
539
+ }
540
+ function pingTask(request, task) {
541
+ if (request.status === "closed") return;
542
+ request.pingedTasks.push(task);
543
+ scheduleWork(request);
544
+ }
545
+ function scheduleWork(request) {
546
+ if (request.workScheduled) return;
547
+ request.workScheduled = true;
548
+ queueMicrotask(() => {
549
+ request.workScheduled = false;
550
+ performWork(request);
551
+ });
552
+ }
553
+ function flushRows(request) {
554
+ if (request.controller === null || request.status === "closed") return;
555
+ if (request.flushingRows) return;
556
+ request.flushingRows = true;
557
+ try {
558
+ let flushed = 0;
559
+ while (flushed < request.queuedRows.length && !streamFlowBlocked(request.controller)) {
560
+ request.controller.enqueue(request.queuedRows[flushed]);
561
+ flushed += 1;
562
+ }
563
+ if (flushed === request.queuedRows.length) request.queuedRows.length = 0;
564
+ else if (flushed > 0) request.queuedRows = request.queuedRows.slice(flushed);
565
+ } finally {
566
+ request.flushingRows = false;
567
+ }
568
+ if (request.pendingTasks === 0 && request.queuedRows.length === 0) {
569
+ request.status = "closed";
570
+ request.cleanupAbortListener();
571
+ request.dataStore.dispose();
572
+ request.controller.close();
573
+ }
574
+ }
575
+ function closeWithError(request, error) {
576
+ if (request.status === "closed") return;
577
+ request.cleanupAbortListener();
578
+ request.status = "closed";
579
+ request.dataStore.dispose();
580
+ request.allReady.reject(error);
581
+ request.controller?.error(error);
582
+ }
583
+ function abortPayloadRequest(request, reason) {
584
+ closeWithError(request, reason ?? new PayloadRequestCancelledError());
585
+ }
586
+ function flattenChildArrays(children) {
587
+ if (!children.some(Array.isArray)) return children;
588
+ const collected = [];
589
+ for (const child of children) if (Array.isArray(child)) for (const nested of flattenChildArrays(child)) collected.push(nested);
590
+ else collected.push(child);
591
+ return collected;
592
+ }
593
+ function invalidChildError$1(value) {
594
+ return /* @__PURE__ */ new Error(`Invalid Fig child in payload render: ${describeInvalidChild(value)}.`);
595
+ }
596
+ function throwIfAborted(signal) {
597
+ if (signal?.aborted) throw new PayloadRequestCancelledError();
598
+ }
599
+ //#endregion
600
+ export { renderToPayloadStream };
601
+
602
+ //# sourceMappingURL=payload.js.map