@solidjs/web 2.0.0-rc.17 → 2.0.0-rc.19

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.
@@ -1,4 +1,4 @@
1
- import { isStream, fromCrossJSON, Feature, createStream, OpaqueReference as OpaqueReference$1, createPlugin as createPlugin$1, toCrossJSONStream, Serializer, getCrossReferenceHeader } from 'seroval';
1
+ import { isStream, fromCrossJSON, Feature, createStream, OpaqueReference as OpaqueReference$1, createPlugin as createPlugin$1, Serializer, getCrossReferenceHeader, toCrossJSONStream, crossSerializeStream } from 'seroval';
2
2
  import { AbortSignalPlugin, CustomEventPlugin, DOMExceptionPlugin, EventPlugin, FormDataPlugin, HeadersPlugin, ReadableStreamPlugin, RequestPlugin, ResponsePlugin, URLSearchParamsPlugin, URLPlugin } from 'seroval-plugins/web';
3
3
 
4
4
  const STATE = Symbol.for("solid.container-trace-state");
@@ -132,11 +132,16 @@ function createJSONDeserializer(options) {
132
132
  const close = () => {
133
133
  alive = false;
134
134
  };
135
- const off = stream.on({
136
- next() {},
137
- throw: close,
138
- return: close
139
- });
135
+ let off;
136
+ try {
137
+ off = stream.on({
138
+ next() {},
139
+ throw: close,
140
+ return: close
141
+ });
142
+ } catch {
143
+ return stream.alive !== false;
144
+ }
140
145
  if (typeof off === "function") off();
141
146
  return alive;
142
147
  }
@@ -233,6 +238,90 @@ function createSerializer(options) {
233
238
  disabledFeatures: (options.disabledFeatures === undefined ? defaultDisabledFeatures() : options.disabledFeatures) | serializeOnlyDisabledFeatures(options.serializeErrorStacks)
234
239
  });
235
240
  }
241
+ function createKeyedSerializer(serialize, onError, onDone) {
242
+ const cancels = new Set();
243
+ let pendingWrites = 0;
244
+ let flushed = false;
245
+ let done = false;
246
+ let closed = false;
247
+ const maybeDone = () => {
248
+ if (flushed && pendingWrites === 0 && !done) {
249
+ done = true;
250
+ onDone && onDone();
251
+ }
252
+ };
253
+ return {
254
+ write(key, value) {
255
+ if (flushed) return;
256
+ pendingWrites++;
257
+ let settled = false;
258
+ let failed = false;
259
+ let started = false;
260
+ let cancel = null;
261
+ const settle = () => {
262
+ if (settled) return;
263
+ settled = true;
264
+ if (cancel) cancels.delete(cancel);
265
+ pendingWrites--;
266
+ maybeDone();
267
+ };
268
+ let stream;
269
+ try {
270
+ stream = serialize(key, value, {
271
+ onError: onError && (err => {
272
+ failed = true;
273
+ onError(err);
274
+ if (cancel) {
275
+ cancel();
276
+ settle();
277
+ }
278
+ }),
279
+ onDone: settle
280
+ }, initial => {
281
+ if (initial) started = true;
282
+ return !closed;
283
+ });
284
+ } catch (err) {
285
+ settle();
286
+ throw err;
287
+ }
288
+ if (settled) return;
289
+ if (closed || failed) {
290
+ stream();
291
+ settle();
292
+ return;
293
+ }
294
+ cancel = stream;
295
+ cancels.add(cancel);
296
+ },
297
+ flush() {
298
+ flushed = true;
299
+ maybeDone();
300
+ },
301
+ close() {
302
+ closed = flushed = true;
303
+ for (const cancel of cancels) cancel();
304
+ cancels.clear();
305
+ if (!done) {
306
+ done = true;
307
+ onDone && onDone();
308
+ }
309
+ }
310
+ };
311
+ }
312
+ const KEY_ESCAPES = {
313
+ '"': '\\"',
314
+ "\\": "\\\\",
315
+ "\n": "\\n",
316
+ "\r": "\\r",
317
+ "\b": "\\b",
318
+ "\t": "\\t",
319
+ "\f": "\\f",
320
+ "<": "\\x3C",
321
+ "\u2028": "\\u2028",
322
+ "\u2029": "\\u2029"
323
+ };
324
+ const serializeKey = key => ("" + key).replace(/["\\\n\r\b\t\f<\u2028\u2029]/g, c => KEY_ESCAPES[c]);
236
325
  function createHydrationSerializer({
237
326
  onData,
238
327
  onDone,
@@ -240,14 +329,20 @@ function createHydrationSerializer({
240
329
  onError,
241
330
  plugins
242
331
  }) {
243
- return createSerializer({
332
+ const resolvedPlugins = resolveSerializerPlugins(plugins);
333
+ const disabledFeatures = defaultDisabledFeatures() | serializeOnlyDisabledFeatures();
334
+ const refs = new Map();
335
+ return createKeyedSerializer((key, value, callbacks, live) => crossSerializeStream(value, {
244
336
  scopeId,
245
- plugins,
246
- globalIdentifier: HYDRATION_GLOBAL,
247
- onData,
248
- onDone,
249
- onError
250
- });
337
+ refs,
338
+ plugins: resolvedPlugins,
339
+ disabledFeatures,
340
+ onSerialize(data, initial) {
341
+ if (!live(initial)) return;
342
+ onData(initial ? HYDRATION_GLOBAL + '["' + serializeKey(key) + '"]=' + data : data);
343
+ },
344
+ ...callbacks
345
+ }), onError, onDone);
251
346
  }
252
347
  function getLocalHeaderScript(id) {
253
348
  return getCrossReferenceHeader(id) + ";";
@@ -256,6 +351,7 @@ function serializeJSON(value, {
256
351
  onParse,
257
352
  onDone,
258
353
  onError,
354
+ refs,
259
355
  ...codecOptions
260
356
  }) {
261
357
  const resolved = resolveCodecOptions(codecOptions);
@@ -263,6 +359,7 @@ function serializeJSON(value, {
263
359
  onParse,
264
360
  onDone,
265
361
  onError,
362
+ refs,
266
363
  ...resolved,
267
364
  disabledFeatures: resolved.disabledFeatures | serializeOnlyDisabledFeatures(resolved.serializeErrorStacks)
268
365
  });
@@ -283,56 +380,19 @@ function createJSONSerializer({
283
380
  serializeErrorStacks
284
381
  });
285
382
  const refs = new Map();
286
- const cancels = new Set();
287
- let pendingWrites = 0;
288
- let flushed = false;
289
- let done = false;
290
- const maybeDone = () => {
291
- if (flushed && pendingWrites === 0 && !done) {
292
- done = true;
293
- onDone && onDone();
294
- }
295
- };
296
- return {
297
- write(key, value) {
298
- if (flushed) return;
299
- pendingWrites++;
300
- let settled = false;
301
- let cancel = null;
302
- const stream = toCrossJSONStream(value, {
303
- refs,
304
- plugins: resolved.plugins,
305
- disabledFeatures: resolved.disabledFeatures | serializeOnlyDisabledFeatures(resolved.serializeErrorStacks),
306
- onParse(node, initial) {
307
- onData({
308
- key,
309
- node,
310
- initial
311
- });
312
- },
313
- onError,
314
- onDone() {
315
- settled = true;
316
- if (cancel) cancels.delete(cancel);
317
- pendingWrites--;
318
- maybeDone();
319
- }
383
+ return createKeyedSerializer((key, value, callbacks, live) => toCrossJSONStream(value, {
384
+ refs,
385
+ plugins: resolved.plugins,
386
+ disabledFeatures: resolved.disabledFeatures | serializeOnlyDisabledFeatures(resolved.serializeErrorStacks),
387
+ onParse(node, initial) {
388
+ if (live(initial)) onData({
389
+ key,
390
+ node,
391
+ initial
320
392
  });
321
- if (!settled) {
322
- cancel = stream;
323
- cancels.add(cancel);
324
- }
325
393
  },
326
- flush() {
327
- flushed = true;
328
- maybeDone();
329
- },
330
- close() {
331
- flushed = true;
332
- for (const cancel of cancels) cancel();
333
- cancels.clear();
334
- }
335
- };
394
+ ...callbacks
395
+ }), onError, onDone);
336
396
  }
337
397
 
338
398
  export { DEFAULT_WEB_PLUGINS, OpaqueReference, createHydrationSerializer, createJSONDataTable, createJSONDeserializer, createJSONSerializer, createPlugin, createSerializer, getLocalHeaderScript, resolveSerializerPlugins, serializeJSON };
@@ -36,10 +36,11 @@ export interface WebSerializerOptions {
36
36
  }
37
37
  /**
38
38
  * Options for `createHydrationSerializer` — `WebSerializerOptions` minus
39
- * the knobs hydration pins (`globalIdentifier`, `disabledFeatures`).
39
+ * the knobs hydration pins (`globalIdentifier`, `disabledFeatures`,
40
+ * `serializeErrorStacks`: its stacks follow `NODE_ENV`).
40
41
  * @internal
41
42
  */
42
- export type HydrationSerializerOptions = Omit<WebSerializerOptions, "globalIdentifier" | "disabledFeatures">;
43
+ export type HydrationSerializerOptions = Omit<WebSerializerOptions, "globalIdentifier" | "disabledFeatures" | "serializeErrorStacks">;
43
44
  /**
44
45
  * Options for `serializeJSON`.
45
46
  *
@@ -69,7 +70,10 @@ export interface JSONSerializerOptions extends JSONCodecOptions {
69
70
  initial: boolean;
70
71
  }) => void;
71
72
  onError?: (error: unknown) => void;
72
- /** Fires once `flush()` has been called and every pending value settled. */
73
+ /**
74
+ * Fires once `flush()` has been called and every pending value settled, or
75
+ * once `close()` runs.
76
+ */
73
77
  onDone?: () => void;
74
78
  }
75
79
  export declare const createPlugin: <Value, Info extends PluginInfo>(plugin: SerializerPlugin<Value, Info>) => SerializerPlugin<Value, Info>;
@@ -91,7 +95,11 @@ export declare const OpaqueReference: {
91
95
  * Integration-facing; may change (see the entry banner).
92
96
  */
93
97
  export declare function createSerializer(options: WebSerializerOptions): Serializer;
94
- export declare function createHydrationSerializer(options: HydrationSerializerOptions): Serializer;
98
+ export declare function createHydrationSerializer(options: HydrationSerializerOptions): {
99
+ write(key: string, value: unknown): void;
100
+ flush(): void;
101
+ close(): void;
102
+ };
95
103
  export declare function getLocalHeaderScript(id?: string): string;
96
104
  export declare function serializeJSON(value: unknown, options: JSONSerializeOptions): () => void;
97
105
  export declare function createJSONSerializer(options: JSONSerializerOptions): {
@@ -36,10 +36,11 @@ export interface WebSerializerOptions {
36
36
  }
37
37
  /**
38
38
  * Options for `createHydrationSerializer` — `WebSerializerOptions` minus
39
- * the knobs hydration pins (`globalIdentifier`, `disabledFeatures`).
39
+ * the knobs hydration pins (`globalIdentifier`, `disabledFeatures`,
40
+ * `serializeErrorStacks`: its stacks follow `NODE_ENV`).
40
41
  * @internal
41
42
  */
42
- export type HydrationSerializerOptions = Omit<WebSerializerOptions, "globalIdentifier" | "disabledFeatures">;
43
+ export type HydrationSerializerOptions = Omit<WebSerializerOptions, "globalIdentifier" | "disabledFeatures" | "serializeErrorStacks">;
43
44
  /**
44
45
  * Options for `serializeJSON`.
45
46
  *
@@ -69,7 +70,10 @@ export interface JSONSerializerOptions extends JSONCodecOptions {
69
70
  initial: boolean;
70
71
  }) => void;
71
72
  onError?: (error: unknown) => void;
72
- /** Fires once `flush()` has been called and every pending value settled. */
73
+ /**
74
+ * Fires once `flush()` has been called and every pending value settled, or
75
+ * once `close()` runs.
76
+ */
73
77
  onDone?: () => void;
74
78
  }
75
79
  export declare const createPlugin: <Value, Info extends PluginInfo>(plugin: SerializerPlugin<Value, Info>) => SerializerPlugin<Value, Info>;
@@ -91,7 +95,11 @@ export declare const OpaqueReference: {
91
95
  * Integration-facing; may change (see the entry banner).
92
96
  */
93
97
  export declare function createSerializer(options: WebSerializerOptions): Serializer;
94
- export declare function createHydrationSerializer(options: HydrationSerializerOptions): Serializer;
98
+ export declare function createHydrationSerializer(options: HydrationSerializerOptions): {
99
+ write(key: string, value: unknown): void;
100
+ flush(): void;
101
+ close(): void;
102
+ };
95
103
  export declare function getLocalHeaderScript(id?: string): string;
96
104
  export declare function serializeJSON(value: unknown, options: JSONSerializeOptions): () => void;
97
105
  export declare function createJSONSerializer(options: JSONSerializerOptions): {
@@ -571,6 +571,7 @@ function decodeErrorHeaderValue(value) {
571
571
  const BODY_FORMAT_HEADER = "X-Server-Function-Format";
572
572
  const LAST_EVENT_ID_HEADER = "Last-Event-ID";
573
573
  const UNKNOWN_HEADER = "X-Server-Function-Unknown";
574
+ const BUILD_HEADER = "X-Server-Function-Build";
574
575
  const REDIRECT_HEADER = "X-Server-Function-Redirect";
575
576
  function decodeRedirectHeaderValue(value) {
576
577
  if (typeof value !== "string") return undefined;
@@ -1377,7 +1378,8 @@ const config = {
1377
1378
  csrf: true,
1378
1379
  bodySizeLimit: 1_048_576,
1379
1380
  maxArguments: 1000,
1380
- chaosReconnectEvery: 0
1381
+ chaosReconnectEvery: 0,
1382
+ buildId: undefined
1381
1383
  };
1382
1384
  function configureServerFunctionsServer({
1383
1385
  provideEvent,
@@ -1393,7 +1395,8 @@ function configureServerFunctionsServer({
1393
1395
  bodySizeLimit,
1394
1396
  maxArguments,
1395
1397
  secret,
1396
- chaosReconnectEvery
1398
+ chaosReconnectEvery,
1399
+ buildId
1397
1400
  } = {}) {
1398
1401
  if (provideEvent !== undefined) config.provideEvent = provideEvent;
1399
1402
  if (wrapInvocation !== undefined) config.wrapInvocation = wrapInvocation;
@@ -1409,6 +1412,7 @@ function configureServerFunctionsServer({
1409
1412
  if (maxArguments !== undefined) config.maxArguments = maxArguments;
1410
1413
  if (secret !== undefined) setFlashSecret(secret);
1411
1414
  if (chaosReconnectEvery !== undefined) config.chaosReconnectEvery = chaosReconnectEvery;
1415
+ if (buildId !== undefined) config.buildId = buildId;
1412
1416
  }
1413
1417
  const flightSources = new Map();
1414
1418
  function registerFlightDataSource(source, hook) {
@@ -2533,7 +2537,7 @@ function serializeResponseStream(value, codecOptions, signal, scope, live) {
2533
2537
  return new ReadableStream({
2534
2538
  async start(controller) {
2535
2539
  streamController = controller;
2536
- if (live) stopLive = armLiveBody(controller, teardown);
2540
+ if (live && !live.nodes) stopLive = armLiveBody(controller, teardown);
2537
2541
  if (signal) {
2538
2542
  if (signal.aborted) {
2539
2543
  teardown();
@@ -2563,7 +2567,10 @@ function serializeResponseStream(value, codecOptions, signal, scope, live) {
2563
2567
  cancelSerialize = serializeJSON(value, {
2564
2568
  ...codecOptions,
2565
2569
  onParse(node) {
2566
- if (!closed) controller.enqueue(frame(JSON.stringify(node)));
2570
+ if (closed) return;
2571
+ const chunk = frame(JSON.stringify(node));
2572
+ if (live && live.nodes) live.nodes.set(chunk, node);
2573
+ controller.enqueue(chunk);
2567
2574
  },
2568
2575
  onDone() {
2569
2576
  if (closed) return;
@@ -2634,7 +2641,7 @@ function armLiveBody(controller, teardown) {
2634
2641
  if (chaos !== null) clearTimeout(chaos);
2635
2642
  };
2636
2643
  }
2637
- function liveSource(value, lastEventId, position, scope) {
2644
+ function liveSource(value, lastEventId, position, scope, refs) {
2638
2645
  const digestOf = v => scope ? scope(() => positionDigest(v)) : positionDigest(v);
2639
2646
  if (value === null || typeof value !== "object" || typeof value[Symbol.asyncIterator] !== "function") {
2640
2647
  const digest = digestOf(value);
@@ -2649,7 +2656,12 @@ function liveSource(value, lastEventId, position, scope) {
2649
2656
  let first = true;
2650
2657
  const step = () => iterator.next().then(result => {
2651
2658
  if (result.done) return result;
2659
+ if (refs) refs.turn();
2652
2660
  const digest = digestOf(result.value);
2661
+ if (refs) position.yields.push({
2662
+ value: result.value,
2663
+ digest
2664
+ });
2653
2665
  if (first) {
2654
2666
  first = false;
2655
2667
  if (digest !== undefined && digest === lastEventId) return step();
@@ -2668,10 +2680,14 @@ function liveSource(value, lastEventId, position, scope) {
2668
2680
  }
2669
2681
  };
2670
2682
  }
2671
- function encodeLiveResult(value, headers, status, codec, request, scope) {
2683
+ function encodeLiveResult(value, headers, status, codec, request, scope, shareKey) {
2672
2684
  if (NULL_BODY_STATUSES.has(status) || value === undefined || getHeadersAndBody(value)) {
2673
2685
  return encodeResult(value, headers, status, codec, request.signal, scope);
2674
2686
  }
2687
+ if (shareKey !== undefined && value !== null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function") {
2688
+ const shared = sharedSourceResponse(shareKey, value, headers, status, codec, request);
2689
+ if (shared) return shared;
2690
+ }
2675
2691
  const position = {
2676
2692
  pending: undefined
2677
2693
  };
@@ -2689,6 +2705,213 @@ function encodeLiveResult(value, headers, status, codec, request, scope) {
2689
2705
  throw DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error;
2690
2706
  }
2691
2707
  }
2708
+ const SHARED_SOURCES = new Map();
2709
+ class GenerationalRefs extends Map {
2710
+ count = 0;
2711
+ touched = new Set();
2712
+ get size() {
2713
+ return this.count;
2714
+ }
2715
+ get(key) {
2716
+ const id = super.get(key);
2717
+ if (id !== undefined) this.touched.add(key);
2718
+ return id;
2719
+ }
2720
+ set(key, value) {
2721
+ if (!super.has(key)) this.count++;
2722
+ this.touched.add(key);
2723
+ return super.set(key, value);
2724
+ }
2725
+ turn() {
2726
+ for (const key of [...super.keys()]) if (!this.touched.has(key)) super.delete(key);
2727
+ this.touched = new Set();
2728
+ }
2729
+ idOf(key) {
2730
+ return super.get(key);
2731
+ }
2732
+ reserve() {
2733
+ return this.count++;
2734
+ }
2735
+ }
2736
+ function sharedSourceResponse(key, value, headers, status, codec, request) {
2737
+ let shared = SHARED_SOURCES.get(key);
2738
+ let snapshot;
2739
+ if (shared && !shared.ended) {
2740
+ snapshot = sharedSnapshot(shared);
2741
+ if (snapshot === null) return undefined;
2742
+ if (value !== shared.source) closeUnread(value);
2743
+ } else shared = startSharedSource(key, value, codec);
2744
+ return tapSharedSource(shared, request, headers, status, snapshot);
2745
+ }
2746
+ function closeUnread(value) {
2747
+ try {
2748
+ const closing = typeof value.return === "function" ? value.return() : typeof value.cancel === "function" ? value.cancel() : undefined;
2749
+ if (closing && typeof closing.then === "function") closing.then(undefined, () => {});
2750
+ } catch {}
2751
+ }
2752
+ function startSharedSource(key, value, codec) {
2753
+ const refs = new GenerationalRefs();
2754
+ const shared = {
2755
+ key,
2756
+ codec,
2757
+ refs,
2758
+ encode: null,
2759
+ head: null,
2760
+ node: null,
2761
+ value: undefined,
2762
+ position: undefined,
2763
+ stream: undefined,
2764
+ source: value,
2765
+ taps: new Set(),
2766
+ ended: false,
2767
+ teardown: new AbortController()
2768
+ };
2769
+ SHARED_SOURCES.set(key, shared);
2770
+ const event = broadcastEvent();
2771
+ const store = globalThis[RequestContext];
2772
+ const scope = run => store ? store.run(event, run) : run();
2773
+ const live = {
2774
+ pending: undefined,
2775
+ yields: [],
2776
+ nodes: new WeakMap()
2777
+ };
2778
+ const body = serializeResponseStream(liveSource(value, undefined, live, scope, refs), {
2779
+ ...codec,
2780
+ refs
2781
+ }, shared.teardown.signal, scope, live);
2782
+ pumpSharedSource(shared, body.getReader(), live);
2783
+ return shared;
2784
+ }
2785
+ async function pumpSharedSource(shared, reader, {
2786
+ nodes,
2787
+ yields
2788
+ }) {
2789
+ try {
2790
+ shared.encode = (await import('@solidjs/web/serialization')).serializeJSON;
2791
+ while (true) {
2792
+ const {
2793
+ done,
2794
+ value: chunk
2795
+ } = await reader.read();
2796
+ if (done) break;
2797
+ const node = nodes.get(chunk);
2798
+ if (shared.head === null) shared.head = chunk;else if (node && node.t === 32 && (shared.stream ??= node.i) === node.i) {
2799
+ const {
2800
+ value,
2801
+ digest
2802
+ } = yields.shift();
2803
+ shared.node = node;
2804
+ shared.value = value;
2805
+ shared.position = digest;
2806
+ }
2807
+ for (const tap of shared.taps) tap.write(chunk);
2808
+ }
2809
+ } catch {}
2810
+ shared.ended = true;
2811
+ if (SHARED_SOURCES.get(shared.key) === shared) SHARED_SOURCES.delete(shared.key);
2812
+ for (const tap of [...shared.taps]) tap.end();
2813
+ }
2814
+ function sharedSnapshot(shared) {
2815
+ if (shared.node === null) return undefined;
2816
+ const own = new Map();
2817
+ let root;
2818
+ let done = false;
2819
+ const cancel = shared.encode(shared.value, {
2820
+ ...shared.codec,
2821
+ refs: own,
2822
+ onParse(node) {
2823
+ root ??= node;
2824
+ },
2825
+ onDone() {
2826
+ done = true;
2827
+ },
2828
+ onError() {}
2829
+ });
2830
+ if (!done || root === undefined) {
2831
+ cancel();
2832
+ return null;
2833
+ }
2834
+ const ids = new Map();
2835
+ for (const [value, id] of own) ids.set(id, shared.refs.idOf(value) ?? shared.refs.reserve());
2836
+ return createEventChunk(JSON.stringify({
2837
+ ...shared.node,
2838
+ f: renumberNode(root, ids)
2839
+ }), shared.position);
2840
+ }
2841
+ function renumberNode(node, ids) {
2842
+ if (Array.isArray(node)) return node.map(item => renumberNode(item, ids));
2843
+ if (node === null || typeof node !== "object") return node;
2844
+ const out = {};
2845
+ for (const key in node) out[key] = key === "i" && typeof node[key] === "number" ? ids.get(node[key]) ?? node[key] : renumberNode(node[key], ids);
2846
+ return out;
2847
+ }
2848
+ function tapSharedSource(shared, request, headers, status, snapshot) {
2849
+ headers.set(BODY_FORMAT_HEADER, BodyFormat.Serialized);
2850
+ headers.set("Content-Type", "text/event-stream");
2851
+ headers.set("Cache-Control", "no-store");
2852
+ headers.set("X-Accel-Buffering", "no");
2853
+ const signal = request.signal;
2854
+ let closed = false;
2855
+ let stopLive = null;
2856
+ let tap = null;
2857
+ const leave = () => {
2858
+ if (closed) return;
2859
+ closed = true;
2860
+ if (stopLive) stopLive();
2861
+ if (signal) signal.removeEventListener("abort", leave);
2862
+ shared.taps.delete(tap);
2863
+ if (!shared.taps.size && !shared.ended) {
2864
+ shared.ended = true;
2865
+ if (SHARED_SOURCES.get(shared.key) === shared) SHARED_SOURCES.delete(shared.key);
2866
+ shared.teardown.abort();
2867
+ }
2868
+ };
2869
+ const body = new ReadableStream({
2870
+ start(controller) {
2871
+ tap = {
2872
+ write(chunk) {
2873
+ if (closed) return;
2874
+ try {
2875
+ controller.enqueue(chunk);
2876
+ } catch {
2877
+ leave();
2878
+ }
2879
+ },
2880
+ end() {
2881
+ leave();
2882
+ try {
2883
+ controller.close();
2884
+ } catch {}
2885
+ }
2886
+ };
2887
+ stopLive = armLiveBody(controller, leave);
2888
+ if (shared.head) controller.enqueue(shared.head);
2889
+ if (snapshot) controller.enqueue(snapshot);
2890
+ if (shared.ended || signal && signal.aborted) return tap.end();
2891
+ shared.taps.add(tap);
2892
+ if (signal) signal.addEventListener("abort", leave);
2893
+ },
2894
+ cancel() {
2895
+ leave();
2896
+ }
2897
+ });
2898
+ return new Response(body, {
2899
+ status,
2900
+ headers
2901
+ });
2902
+ }
2903
+ function broadcastEvent() {
2904
+ const event = {
2905
+ broadcast: true
2906
+ };
2907
+ for (const name of ["request", "locals", "clientAddress", "nativeEvent"]) Object.defineProperty(event, name, {
2908
+ get() {
2909
+ if (DEV) console.warn(`A broadcast server function read the request (\`event.${name}\`) while producing ` + "its answer, which every viewer shares; read per-viewer state before returning it.");
2910
+ return undefined;
2911
+ }
2912
+ });
2913
+ return event;
2914
+ }
2692
2915
  function encodeResult(value, headers, status, codec, signal, scope) {
2693
2916
  if (NULL_BODY_STATUSES.has(status)) {
2694
2917
  if (value === undefined || value === null) {
@@ -2893,7 +3116,7 @@ function withHeaders(response, write) {
2893
3116
  function withCSRFVary(response) {
2894
3117
  return withHeaders(response, headers => appendVary(headers, CSRF_VARY));
2895
3118
  }
2896
- const TRANSPORT_REQUEST_HEADERS = ["Content-Type", BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER].join(", ");
3119
+ const TRANSPORT_REQUEST_HEADERS = ["Content-Type", BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, BUILD_HEADER].join(", ");
2897
3120
  const PREFLIGHT_MAX_AGE = "600";
2898
3121
  const CORS_SAFELISTED_RESPONSE_HEADERS = new Set(["cache-control", "content-language", "content-length", "content-type", "expires", "last-modified", "pragma"]);
2899
3122
  function withCORS(response, cors) {
@@ -2995,6 +3218,17 @@ async function handleServerFunctionRequest(request, options = {}) {
2995
3218
  });
2996
3219
  return finish(protectsRequest ? withCSRFVary(response) : response);
2997
3220
  }
3221
+ const callerBuild = request.headers.get(BUILD_HEADER);
3222
+ if (config.buildId && callerBuild !== null && callerBuild !== config.buildId) {
3223
+ return finish(new Response(DEV ? `Server function call from build "${callerBuild}" refused by build "${config.buildId}"` : null, {
3224
+ status: 409,
3225
+ headers: {
3226
+ [UNKNOWN_HEADER]: "true",
3227
+ [BUILD_HEADER]: config.buildId,
3228
+ "Cache-Control": "no-store"
3229
+ }
3230
+ }));
3231
+ }
2998
3232
  const scripted = address.data || address.live;
2999
3233
  const live = address.live;
3000
3234
  if (method !== "POST" && !declaredRead) {
@@ -3205,7 +3439,10 @@ async function handleServerFunctionRequest(request, options = {}) {
3205
3439
  return encodeResult(result, headers, status, codec, request.signal, scope);
3206
3440
  }
3207
3441
  if (status === 304) warnScripted304(functionId);
3208
- if (live) return encodeLiveResult(result, headers, status, codec, request, scope);
3442
+ if (live) {
3443
+ const invocation = INVOCATIONS.get(event);
3444
+ return encodeLiveResult(result, headers, status, codec, request, scope, invocation && invocation.broadcast && invocation.shareKey !== undefined ? invocation.id + "\0" + invocation.shareKey : undefined);
3445
+ }
3209
3446
  return encodeResult(result, headers, status, codec, request.signal, scope);
3210
3447
  } catch (x) {
3211
3448
  const respondThrown = value => {