@solidjs/web 2.0.0-rc.16 → 2.0.0-rc.18

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.
@@ -520,6 +520,7 @@ function decodeErrorHeaderValue(value) {
520
520
  const BODY_FORMAT_HEADER = "X-Server-Function-Format";
521
521
  const LAST_EVENT_ID_HEADER = "Last-Event-ID";
522
522
  const UNKNOWN_HEADER = "X-Server-Function-Unknown";
523
+ const BUILD_HEADER = "X-Server-Function-Build";
523
524
  const REDIRECT_HEADER = "X-Server-Function-Redirect";
524
525
  function decodeRedirectHeaderValue(value) {
525
526
  if (typeof value !== "string") return undefined;
@@ -1243,6 +1244,45 @@ function namesRefusedType(payload) {
1243
1244
  for (const tag of REFUSED_TAGS) if (payload.includes(`"c":"${tag}"`)) return true;
1244
1245
  return false;
1245
1246
  }
1247
+ function withArgumentPlugins(argumentCodec, extra) {
1248
+ return {
1249
+ ...argumentCodec,
1250
+ [RESOLVED_PLUGINS]: [...extra, ...argumentCodec[RESOLVED_PLUGINS]]
1251
+ };
1252
+ }
1253
+
1254
+ const UPLOAD_ARGS_PART = "args";
1255
+ const UPLOAD_FILE_PART = "file";
1256
+ const UPLOAD_TAG = "solid/server-function-upload";
1257
+ function isBlob(value) {
1258
+ if (typeof Blob !== "undefined" && value instanceof Blob) return true;
1259
+ return typeof value === "object" && value !== null && typeof value.size === "number" && typeof value.type === "string" && typeof value.arrayBuffer === "function" && typeof value.slice === "function";
1260
+ }
1261
+ function malformed() {
1262
+ return new TypeError("Malformed server function upload");
1263
+ }
1264
+ function createUploadDeserializer(form) {
1265
+ const refuse = () => {
1266
+ throw malformed();
1267
+ };
1268
+ return {
1269
+ tag: UPLOAD_TAG,
1270
+ test: () => false,
1271
+ parse: {
1272
+ sync: refuse,
1273
+ async: refuse,
1274
+ stream: refuse
1275
+ },
1276
+ serialize: refuse,
1277
+ deserialize: (node, ctx) => {
1278
+ const index = ctx.deserialize(node.i);
1279
+ if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0) refuse();
1280
+ const part = form.get(UPLOAD_FILE_PART + index);
1281
+ if (!isBlob(part)) refuse();
1282
+ return part;
1283
+ }
1284
+ };
1285
+ }
1246
1286
 
1247
1287
  const config = {
1248
1288
  provideEvent: undefined,
@@ -1256,7 +1296,8 @@ const config = {
1256
1296
  csrf: true,
1257
1297
  bodySizeLimit: 1_048_576,
1258
1298
  maxArguments: 1000,
1259
- chaosReconnectEvery: 0
1299
+ chaosReconnectEvery: 0,
1300
+ buildId: undefined
1260
1301
  };
1261
1302
  function configureServerFunctionsServer({
1262
1303
  provideEvent,
@@ -1272,7 +1313,8 @@ function configureServerFunctionsServer({
1272
1313
  bodySizeLimit,
1273
1314
  maxArguments,
1274
1315
  secret,
1275
- chaosReconnectEvery
1316
+ chaosReconnectEvery,
1317
+ buildId
1276
1318
  } = {}) {
1277
1319
  if (provideEvent !== undefined) config.provideEvent = provideEvent;
1278
1320
  if (wrapInvocation !== undefined) config.wrapInvocation = wrapInvocation;
@@ -1288,6 +1330,7 @@ function configureServerFunctionsServer({
1288
1330
  if (maxArguments !== undefined) config.maxArguments = maxArguments;
1289
1331
  if (secret !== undefined) setFlashSecret(secret);
1290
1332
  if (chaosReconnectEvery !== undefined) config.chaosReconnectEvery = chaosReconnectEvery;
1333
+ if (buildId !== undefined) config.buildId = buildId;
1291
1334
  }
1292
1335
  const flightSources = new Map();
1293
1336
  function registerFlightDataSource(source, hook) {
@@ -1685,6 +1728,7 @@ function live(fn) {
1685
1728
  if (!isServerFunction(fn) || typeof fn.id !== "string") {
1686
1729
  throw new Error("live expects a server function reference");
1687
1730
  }
1731
+ if (getServerFunctionMetadata(fn)?.method !== "GET") fn = GET(fn);
1688
1732
  const metadata = {
1689
1733
  ...getServerFunctionMetadata(fn),
1690
1734
  live: true
@@ -1699,6 +1743,18 @@ function live(fn) {
1699
1743
  });
1700
1744
  return wrapped;
1701
1745
  }
1746
+ function broadcast(fn) {
1747
+ const ref = live(fn);
1748
+ ref[SERVER_FUNCTION_METADATA].broadcast = true;
1749
+ BROADCASTS.add(fn.id);
1750
+ return ref;
1751
+ }
1752
+ function encodedArguments(request, argsEncoding, argumentBytes) {
1753
+ if (request.method !== "POST") return argsEncoding || "";
1754
+ if (!argumentBytes) return undefined;
1755
+ return (request.headers.get("content-type") || "") + "\0" + (argsEncoding || "") + "\0" + new TextDecoder("latin1").decode(argumentBytes);
1756
+ }
1757
+ const BROADCASTS = new Set();
1702
1758
  function brandLive(answer) {
1703
1759
  if (typeof answer === "function" || answer !== null && typeof answer === "object" && answer[Symbol.asyncIterator]) {
1704
1760
  answer[LIVE_SOURCE] = true;
@@ -1875,7 +1931,17 @@ async function parseArguments(request, url, scripted, codec, buffered) {
1875
1931
  if (bodyFormat === BodyFormat.Serialized) {
1876
1932
  let argumentCodec = argumentCodecFor(codec);
1877
1933
  if (argumentCodec instanceof Promise) argumentCodec = await argumentCodec;
1878
- decoded = await decodeArguments(wire => extractBody(body, argumentCodec, wire), buffered);
1934
+ if ((request.headers.get("content-type") || "").startsWith("multipart/form-data")) {
1935
+ const form = await body.formData();
1936
+ const encoded = form.get(UPLOAD_ARGS_PART);
1937
+ if (typeof encoded !== "string") {
1938
+ throw new TypeError("Malformed server function upload");
1939
+ }
1940
+ const uploadCodec = withArgumentPlugins(argumentCodec, [createUploadDeserializer(form)]);
1941
+ decoded = await decodeArguments(wire => deserializeStream(new Response(encoded), uploadCodec, wire), encoded);
1942
+ } else {
1943
+ decoded = await decodeArguments(wire => extractBody(body, argumentCodec, wire), buffered);
1944
+ }
1879
1945
  } else {
1880
1946
  decoded = await extractBody(body, codec);
1881
1947
  }
@@ -2389,7 +2455,7 @@ function serializeResponseStream(value, codecOptions, signal, scope, live) {
2389
2455
  return new ReadableStream({
2390
2456
  async start(controller) {
2391
2457
  streamController = controller;
2392
- if (live) stopLive = armLiveBody(controller, teardown);
2458
+ if (live && !live.nodes) stopLive = armLiveBody(controller, teardown);
2393
2459
  if (signal) {
2394
2460
  if (signal.aborted) {
2395
2461
  teardown();
@@ -2419,7 +2485,10 @@ function serializeResponseStream(value, codecOptions, signal, scope, live) {
2419
2485
  cancelSerialize = serializeJSON(value, {
2420
2486
  ...codecOptions,
2421
2487
  onParse(node) {
2422
- if (!closed) controller.enqueue(frame(JSON.stringify(node)));
2488
+ if (closed) return;
2489
+ const chunk = frame(JSON.stringify(node));
2490
+ if (live && live.nodes) live.nodes.set(chunk, node);
2491
+ controller.enqueue(chunk);
2423
2492
  },
2424
2493
  onDone() {
2425
2494
  if (closed) return;
@@ -2490,7 +2559,7 @@ function armLiveBody(controller, teardown) {
2490
2559
  if (chaos !== null) clearTimeout(chaos);
2491
2560
  };
2492
2561
  }
2493
- function liveSource(value, lastEventId, position, scope) {
2562
+ function liveSource(value, lastEventId, position, scope, refs) {
2494
2563
  const digestOf = v => scope ? scope(() => positionDigest(v)) : positionDigest(v);
2495
2564
  if (value === null || typeof value !== "object" || typeof value[Symbol.asyncIterator] !== "function") {
2496
2565
  const digest = digestOf(value);
@@ -2505,7 +2574,12 @@ function liveSource(value, lastEventId, position, scope) {
2505
2574
  let first = true;
2506
2575
  const step = () => iterator.next().then(result => {
2507
2576
  if (result.done) return result;
2577
+ if (refs) refs.turn();
2508
2578
  const digest = digestOf(result.value);
2579
+ if (refs) position.yields.push({
2580
+ value: result.value,
2581
+ digest
2582
+ });
2509
2583
  if (first) {
2510
2584
  first = false;
2511
2585
  if (digest !== undefined && digest === lastEventId) return step();
@@ -2524,10 +2598,14 @@ function liveSource(value, lastEventId, position, scope) {
2524
2598
  }
2525
2599
  };
2526
2600
  }
2527
- function encodeLiveResult(value, headers, status, codec, request, scope) {
2601
+ function encodeLiveResult(value, headers, status, codec, request, scope, shareKey) {
2528
2602
  if (NULL_BODY_STATUSES.has(status) || value === undefined || getHeadersAndBody(value)) {
2529
2603
  return encodeResult(value, headers, status, codec, request.signal, scope);
2530
2604
  }
2605
+ if (shareKey !== undefined && value !== null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function") {
2606
+ const shared = sharedSourceResponse(shareKey, value, headers, status, codec, request);
2607
+ if (shared) return shared;
2608
+ }
2531
2609
  const position = {
2532
2610
  pending: undefined
2533
2611
  };
@@ -2545,6 +2623,213 @@ function encodeLiveResult(value, headers, status, codec, request, scope) {
2545
2623
  throw DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error;
2546
2624
  }
2547
2625
  }
2626
+ const SHARED_SOURCES = new Map();
2627
+ class GenerationalRefs extends Map {
2628
+ count = 0;
2629
+ touched = new Set();
2630
+ get size() {
2631
+ return this.count;
2632
+ }
2633
+ get(key) {
2634
+ const id = super.get(key);
2635
+ if (id !== undefined) this.touched.add(key);
2636
+ return id;
2637
+ }
2638
+ set(key, value) {
2639
+ if (!super.has(key)) this.count++;
2640
+ this.touched.add(key);
2641
+ return super.set(key, value);
2642
+ }
2643
+ turn() {
2644
+ for (const key of [...super.keys()]) if (!this.touched.has(key)) super.delete(key);
2645
+ this.touched = new Set();
2646
+ }
2647
+ idOf(key) {
2648
+ return super.get(key);
2649
+ }
2650
+ reserve() {
2651
+ return this.count++;
2652
+ }
2653
+ }
2654
+ function sharedSourceResponse(key, value, headers, status, codec, request) {
2655
+ let shared = SHARED_SOURCES.get(key);
2656
+ let snapshot;
2657
+ if (shared && !shared.ended) {
2658
+ snapshot = sharedSnapshot(shared);
2659
+ if (snapshot === null) return undefined;
2660
+ if (value !== shared.source) closeUnread(value);
2661
+ } else shared = startSharedSource(key, value, codec);
2662
+ return tapSharedSource(shared, request, headers, status, snapshot);
2663
+ }
2664
+ function closeUnread(value) {
2665
+ try {
2666
+ const closing = typeof value.return === "function" ? value.return() : typeof value.cancel === "function" ? value.cancel() : undefined;
2667
+ if (closing && typeof closing.then === "function") closing.then(undefined, () => {});
2668
+ } catch {}
2669
+ }
2670
+ function startSharedSource(key, value, codec) {
2671
+ const refs = new GenerationalRefs();
2672
+ const shared = {
2673
+ key,
2674
+ codec,
2675
+ refs,
2676
+ encode: null,
2677
+ head: null,
2678
+ node: null,
2679
+ value: undefined,
2680
+ position: undefined,
2681
+ stream: undefined,
2682
+ source: value,
2683
+ taps: new Set(),
2684
+ ended: false,
2685
+ teardown: new AbortController()
2686
+ };
2687
+ SHARED_SOURCES.set(key, shared);
2688
+ const event = broadcastEvent();
2689
+ const store = globalThis[RequestContext];
2690
+ const scope = run => store ? store.run(event, run) : run();
2691
+ const live = {
2692
+ pending: undefined,
2693
+ yields: [],
2694
+ nodes: new WeakMap()
2695
+ };
2696
+ const body = serializeResponseStream(liveSource(value, undefined, live, scope, refs), {
2697
+ ...codec,
2698
+ refs
2699
+ }, shared.teardown.signal, scope, live);
2700
+ pumpSharedSource(shared, body.getReader(), live);
2701
+ return shared;
2702
+ }
2703
+ async function pumpSharedSource(shared, reader, {
2704
+ nodes,
2705
+ yields
2706
+ }) {
2707
+ try {
2708
+ shared.encode = (await import('@solidjs/web/serialization')).serializeJSON;
2709
+ while (true) {
2710
+ const {
2711
+ done,
2712
+ value: chunk
2713
+ } = await reader.read();
2714
+ if (done) break;
2715
+ const node = nodes.get(chunk);
2716
+ if (shared.head === null) shared.head = chunk;else if (node && node.t === 32 && (shared.stream ??= node.i) === node.i) {
2717
+ const {
2718
+ value,
2719
+ digest
2720
+ } = yields.shift();
2721
+ shared.node = node;
2722
+ shared.value = value;
2723
+ shared.position = digest;
2724
+ }
2725
+ for (const tap of shared.taps) tap.write(chunk);
2726
+ }
2727
+ } catch {}
2728
+ shared.ended = true;
2729
+ if (SHARED_SOURCES.get(shared.key) === shared) SHARED_SOURCES.delete(shared.key);
2730
+ for (const tap of [...shared.taps]) tap.end();
2731
+ }
2732
+ function sharedSnapshot(shared) {
2733
+ if (shared.node === null) return undefined;
2734
+ const own = new Map();
2735
+ let root;
2736
+ let done = false;
2737
+ const cancel = shared.encode(shared.value, {
2738
+ ...shared.codec,
2739
+ refs: own,
2740
+ onParse(node) {
2741
+ root ??= node;
2742
+ },
2743
+ onDone() {
2744
+ done = true;
2745
+ },
2746
+ onError() {}
2747
+ });
2748
+ if (!done || root === undefined) {
2749
+ cancel();
2750
+ return null;
2751
+ }
2752
+ const ids = new Map();
2753
+ for (const [value, id] of own) ids.set(id, shared.refs.idOf(value) ?? shared.refs.reserve());
2754
+ return createEventChunk(JSON.stringify({
2755
+ ...shared.node,
2756
+ f: renumberNode(root, ids)
2757
+ }), shared.position);
2758
+ }
2759
+ function renumberNode(node, ids) {
2760
+ if (Array.isArray(node)) return node.map(item => renumberNode(item, ids));
2761
+ if (node === null || typeof node !== "object") return node;
2762
+ const out = {};
2763
+ for (const key in node) out[key] = key === "i" && typeof node[key] === "number" ? ids.get(node[key]) ?? node[key] : renumberNode(node[key], ids);
2764
+ return out;
2765
+ }
2766
+ function tapSharedSource(shared, request, headers, status, snapshot) {
2767
+ headers.set(BODY_FORMAT_HEADER, BodyFormat.Serialized);
2768
+ headers.set("Content-Type", "text/event-stream");
2769
+ headers.set("Cache-Control", "no-store");
2770
+ headers.set("X-Accel-Buffering", "no");
2771
+ const signal = request.signal;
2772
+ let closed = false;
2773
+ let stopLive = null;
2774
+ let tap = null;
2775
+ const leave = () => {
2776
+ if (closed) return;
2777
+ closed = true;
2778
+ if (stopLive) stopLive();
2779
+ if (signal) signal.removeEventListener("abort", leave);
2780
+ shared.taps.delete(tap);
2781
+ if (!shared.taps.size && !shared.ended) {
2782
+ shared.ended = true;
2783
+ if (SHARED_SOURCES.get(shared.key) === shared) SHARED_SOURCES.delete(shared.key);
2784
+ shared.teardown.abort();
2785
+ }
2786
+ };
2787
+ const body = new ReadableStream({
2788
+ start(controller) {
2789
+ tap = {
2790
+ write(chunk) {
2791
+ if (closed) return;
2792
+ try {
2793
+ controller.enqueue(chunk);
2794
+ } catch {
2795
+ leave();
2796
+ }
2797
+ },
2798
+ end() {
2799
+ leave();
2800
+ try {
2801
+ controller.close();
2802
+ } catch {}
2803
+ }
2804
+ };
2805
+ stopLive = armLiveBody(controller, leave);
2806
+ if (shared.head) controller.enqueue(shared.head);
2807
+ if (snapshot) controller.enqueue(snapshot);
2808
+ if (shared.ended || signal && signal.aborted) return tap.end();
2809
+ shared.taps.add(tap);
2810
+ if (signal) signal.addEventListener("abort", leave);
2811
+ },
2812
+ cancel() {
2813
+ leave();
2814
+ }
2815
+ });
2816
+ return new Response(body, {
2817
+ status,
2818
+ headers
2819
+ });
2820
+ }
2821
+ function broadcastEvent() {
2822
+ const event = {
2823
+ broadcast: true
2824
+ };
2825
+ for (const name of ["request", "locals", "clientAddress", "nativeEvent"]) Object.defineProperty(event, name, {
2826
+ get() {
2827
+ 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.");
2828
+ return undefined;
2829
+ }
2830
+ });
2831
+ return event;
2832
+ }
2548
2833
  function encodeResult(value, headers, status, codec, signal, scope) {
2549
2834
  if (NULL_BODY_STATUSES.has(status)) {
2550
2835
  if (value === undefined || value === null) {
@@ -2738,7 +3023,7 @@ function withHeaders(response, write) {
2738
3023
  function withCSRFVary(response) {
2739
3024
  return withHeaders(response, headers => appendVary(headers, CSRF_VARY));
2740
3025
  }
2741
- const TRANSPORT_REQUEST_HEADERS = ["Content-Type", BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER].join(", ");
3026
+ const TRANSPORT_REQUEST_HEADERS = ["Content-Type", BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, BUILD_HEADER].join(", ");
2742
3027
  const PREFLIGHT_MAX_AGE = "600";
2743
3028
  const CORS_SAFELISTED_RESPONSE_HEADERS = new Set(["cache-control", "content-language", "content-length", "content-type", "expires", "last-modified", "pragma"]);
2744
3029
  function withCORS(response, cors) {
@@ -2840,6 +3125,17 @@ async function handleServerFunctionRequest(request, options = {}) {
2840
3125
  });
2841
3126
  return finish(protectsRequest ? withCSRFVary(response) : response);
2842
3127
  }
3128
+ const callerBuild = request.headers.get(BUILD_HEADER);
3129
+ if (config.buildId && callerBuild !== null && callerBuild !== config.buildId) {
3130
+ return finish(new Response(DEV ? `Server function call from build "${callerBuild}" refused by build "${config.buildId}"` : null, {
3131
+ status: 409,
3132
+ headers: {
3133
+ [UNKNOWN_HEADER]: "true",
3134
+ [BUILD_HEADER]: config.buildId,
3135
+ "Cache-Control": "no-store"
3136
+ }
3137
+ }));
3138
+ }
2843
3139
  const scripted = address.data || address.live;
2844
3140
  const live = address.live;
2845
3141
  if (method !== "POST" && !declaredRead) {
@@ -2969,9 +3265,12 @@ async function handleServerFunctionRequest(request, options = {}) {
2969
3265
  const dispatch = async () => {
2970
3266
  try {
2971
3267
  const invokeOnce = async () => {
3268
+ const shared = !!live && BROADCASTS.has(functionId);
2972
3269
  INVOCATIONS.set(event, {
2973
3270
  id: functionId,
2974
- live: !!live
3271
+ live: !!live,
3272
+ broadcast: shared || undefined,
3273
+ shareKey: shared ? encodedArguments(request, argsEncoding, argumentBytes) : undefined
2975
3274
  });
2976
3275
  const run = () => serverFunction(...parsed);
2977
3276
  return observeInvocation({
@@ -3047,7 +3346,10 @@ async function handleServerFunctionRequest(request, options = {}) {
3047
3346
  return encodeResult(result, headers, status, codec, request.signal, scope);
3048
3347
  }
3049
3348
  if (status === 304) warnScripted304(functionId);
3050
- if (live) return encodeLiveResult(result, headers, status, codec, request, scope);
3349
+ if (live) {
3350
+ const invocation = INVOCATIONS.get(event);
3351
+ return encodeLiveResult(result, headers, status, codec, request, scope, invocation && invocation.broadcast && invocation.shareKey !== undefined ? invocation.id + "\0" + invocation.shareKey : undefined);
3352
+ }
3051
3353
  return encodeResult(result, headers, status, codec, request.signal, scope);
3052
3354
  } catch (x) {
3053
3355
  const respondThrown = value => {
@@ -3221,4 +3523,4 @@ function finalizeTransportResponse(response, method) {
3221
3523
  return response;
3222
3524
  }
3223
3525
 
3224
- export { ChunkReader, ERROR_HEADER, FLASH_COOKIE, GENERIC_SERVER_ERROR_MESSAGE, GET, REDIRECT_HEADER, SERVER_FUNCTION_INVOKE, SINGLE_FLIGHT_HEADER, UNKNOWN_HEADER, armLiveBody, clearFlashCookie, configureServerFunctionsServer, createChunk, createEventChunk, createNoJSHandler, createServerReference, decodeErrorHeaderValue, decodeFlashCookie, decodeRedirectHeaderValue, decodeResponse, decodeResponsePayload, encodeErrorHeaderValue, encodeFlashCookie, foldSetCookies, frameAddress, getEventServerFunctionInvocation, getServerFunction, getServerFunctionInvocation, getServerFunctionMetadata, guardFailures, handleServerFunctionRequest, hasFlashCookie, invoke, isServerFunction, live, parseServerFunctionActionUrl, registerFlightDataSource, registerServerFunction, registerServerReference, sanitizeServerError, serializeResponseStream, serializeStream, serverFunctionActionUrl, serverFunctionUrl, setServerFunctionsDev, subscribeFlightData, textDigest, withMeta };
3526
+ export { ChunkReader, ERROR_HEADER, FLASH_COOKIE, GENERIC_SERVER_ERROR_MESSAGE, GET, REDIRECT_HEADER, SERVER_FUNCTION_INVOKE, SINGLE_FLIGHT_HEADER, UNKNOWN_HEADER, armLiveBody, broadcast, clearFlashCookie, configureServerFunctionsServer, createChunk, createEventChunk, createNoJSHandler, createServerReference, decodeErrorHeaderValue, decodeFlashCookie, decodeRedirectHeaderValue, decodeResponse, decodeResponsePayload, encodeErrorHeaderValue, encodeFlashCookie, foldSetCookies, frameAddress, getEventServerFunctionInvocation, getServerFunction, getServerFunctionInvocation, getServerFunctionMetadata, guardFailures, handleServerFunctionRequest, hasFlashCookie, invoke, isServerFunction, live, parseServerFunctionActionUrl, registerFlightDataSource, registerServerFunction, registerServerReference, sanitizeServerError, serializeResponseStream, serializeStream, serverFunctionActionUrl, serverFunctionUrl, setServerFunctionsDev, subscribeFlightData, textDigest, withMeta };