@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.
@@ -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;
@@ -1325,6 +1326,45 @@ function namesRefusedType(payload) {
1325
1326
  for (const tag of REFUSED_TAGS) if (payload.includes(`"c":"${tag}"`)) return true;
1326
1327
  return false;
1327
1328
  }
1329
+ function withArgumentPlugins(argumentCodec, extra) {
1330
+ return {
1331
+ ...argumentCodec,
1332
+ [RESOLVED_PLUGINS]: [...extra, ...argumentCodec[RESOLVED_PLUGINS]]
1333
+ };
1334
+ }
1335
+
1336
+ const UPLOAD_ARGS_PART = "args";
1337
+ const UPLOAD_FILE_PART = "file";
1338
+ const UPLOAD_TAG = "solid/server-function-upload";
1339
+ function isBlob(value) {
1340
+ if (typeof Blob !== "undefined" && value instanceof Blob) return true;
1341
+ return typeof value === "object" && value !== null && typeof value.size === "number" && typeof value.type === "string" && typeof value.arrayBuffer === "function" && typeof value.slice === "function";
1342
+ }
1343
+ function malformed() {
1344
+ return new TypeError("Malformed server function upload");
1345
+ }
1346
+ function createUploadDeserializer(form) {
1347
+ const refuse = () => {
1348
+ throw malformed();
1349
+ };
1350
+ return {
1351
+ tag: UPLOAD_TAG,
1352
+ test: () => false,
1353
+ parse: {
1354
+ sync: refuse,
1355
+ async: refuse,
1356
+ stream: refuse
1357
+ },
1358
+ serialize: refuse,
1359
+ deserialize: (node, ctx) => {
1360
+ const index = ctx.deserialize(node.i);
1361
+ if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0) refuse();
1362
+ const part = form.get(UPLOAD_FILE_PART + index);
1363
+ if (!isBlob(part)) refuse();
1364
+ return part;
1365
+ }
1366
+ };
1367
+ }
1328
1368
 
1329
1369
  const config = {
1330
1370
  provideEvent: undefined,
@@ -1338,7 +1378,8 @@ const config = {
1338
1378
  csrf: true,
1339
1379
  bodySizeLimit: 1_048_576,
1340
1380
  maxArguments: 1000,
1341
- chaosReconnectEvery: 0
1381
+ chaosReconnectEvery: 0,
1382
+ buildId: undefined
1342
1383
  };
1343
1384
  function configureServerFunctionsServer({
1344
1385
  provideEvent,
@@ -1354,7 +1395,8 @@ function configureServerFunctionsServer({
1354
1395
  bodySizeLimit,
1355
1396
  maxArguments,
1356
1397
  secret,
1357
- chaosReconnectEvery
1398
+ chaosReconnectEvery,
1399
+ buildId
1358
1400
  } = {}) {
1359
1401
  if (provideEvent !== undefined) config.provideEvent = provideEvent;
1360
1402
  if (wrapInvocation !== undefined) config.wrapInvocation = wrapInvocation;
@@ -1370,6 +1412,7 @@ function configureServerFunctionsServer({
1370
1412
  if (maxArguments !== undefined) config.maxArguments = maxArguments;
1371
1413
  if (secret !== undefined) setFlashSecret(secret);
1372
1414
  if (chaosReconnectEvery !== undefined) config.chaosReconnectEvery = chaosReconnectEvery;
1415
+ if (buildId !== undefined) config.buildId = buildId;
1373
1416
  }
1374
1417
  const flightSources = new Map();
1375
1418
  function registerFlightDataSource(source, hook) {
@@ -1767,6 +1810,7 @@ function live(fn) {
1767
1810
  if (!isServerFunction(fn) || typeof fn.id !== "string") {
1768
1811
  throw new Error("live expects a server function reference");
1769
1812
  }
1813
+ if (getServerFunctionMetadata(fn)?.method !== "GET") fn = GET(fn);
1770
1814
  const metadata = {
1771
1815
  ...getServerFunctionMetadata(fn),
1772
1816
  live: true
@@ -1781,6 +1825,18 @@ function live(fn) {
1781
1825
  });
1782
1826
  return wrapped;
1783
1827
  }
1828
+ function broadcast(fn) {
1829
+ const ref = live(fn);
1830
+ ref[SERVER_FUNCTION_METADATA].broadcast = true;
1831
+ BROADCASTS.add(fn.id);
1832
+ return ref;
1833
+ }
1834
+ function encodedArguments(request, argsEncoding, argumentBytes) {
1835
+ if (request.method !== "POST") return argsEncoding || "";
1836
+ if (!argumentBytes) return undefined;
1837
+ return (request.headers.get("content-type") || "") + "\0" + (argsEncoding || "") + "\0" + new TextDecoder("latin1").decode(argumentBytes);
1838
+ }
1839
+ const BROADCASTS = new Set();
1784
1840
  function brandLive(answer) {
1785
1841
  if (typeof answer === "function" || answer !== null && typeof answer === "object" && answer[Symbol.asyncIterator]) {
1786
1842
  answer[LIVE_SOURCE] = true;
@@ -1957,7 +2013,17 @@ async function parseArguments(request, url, scripted, codec, buffered) {
1957
2013
  if (bodyFormat === BodyFormat.Serialized) {
1958
2014
  let argumentCodec = argumentCodecFor(codec);
1959
2015
  if (argumentCodec instanceof Promise) argumentCodec = await argumentCodec;
1960
- decoded = await decodeArguments(wire => extractBody(body, argumentCodec, wire), buffered);
2016
+ if ((request.headers.get("content-type") || "").startsWith("multipart/form-data")) {
2017
+ const form = await body.formData();
2018
+ const encoded = form.get(UPLOAD_ARGS_PART);
2019
+ if (typeof encoded !== "string") {
2020
+ throw new TypeError("Malformed server function upload");
2021
+ }
2022
+ const uploadCodec = withArgumentPlugins(argumentCodec, [createUploadDeserializer(form)]);
2023
+ decoded = await decodeArguments(wire => deserializeStream(new Response(encoded), uploadCodec, wire), encoded);
2024
+ } else {
2025
+ decoded = await decodeArguments(wire => extractBody(body, argumentCodec, wire), buffered);
2026
+ }
1961
2027
  } else {
1962
2028
  decoded = await extractBody(body, codec);
1963
2029
  }
@@ -2471,7 +2537,7 @@ function serializeResponseStream(value, codecOptions, signal, scope, live) {
2471
2537
  return new ReadableStream({
2472
2538
  async start(controller) {
2473
2539
  streamController = controller;
2474
- if (live) stopLive = armLiveBody(controller, teardown);
2540
+ if (live && !live.nodes) stopLive = armLiveBody(controller, teardown);
2475
2541
  if (signal) {
2476
2542
  if (signal.aborted) {
2477
2543
  teardown();
@@ -2501,7 +2567,10 @@ function serializeResponseStream(value, codecOptions, signal, scope, live) {
2501
2567
  cancelSerialize = serializeJSON(value, {
2502
2568
  ...codecOptions,
2503
2569
  onParse(node) {
2504
- 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);
2505
2574
  },
2506
2575
  onDone() {
2507
2576
  if (closed) return;
@@ -2572,7 +2641,7 @@ function armLiveBody(controller, teardown) {
2572
2641
  if (chaos !== null) clearTimeout(chaos);
2573
2642
  };
2574
2643
  }
2575
- function liveSource(value, lastEventId, position, scope) {
2644
+ function liveSource(value, lastEventId, position, scope, refs) {
2576
2645
  const digestOf = v => scope ? scope(() => positionDigest(v)) : positionDigest(v);
2577
2646
  if (value === null || typeof value !== "object" || typeof value[Symbol.asyncIterator] !== "function") {
2578
2647
  const digest = digestOf(value);
@@ -2587,7 +2656,12 @@ function liveSource(value, lastEventId, position, scope) {
2587
2656
  let first = true;
2588
2657
  const step = () => iterator.next().then(result => {
2589
2658
  if (result.done) return result;
2659
+ if (refs) refs.turn();
2590
2660
  const digest = digestOf(result.value);
2661
+ if (refs) position.yields.push({
2662
+ value: result.value,
2663
+ digest
2664
+ });
2591
2665
  if (first) {
2592
2666
  first = false;
2593
2667
  if (digest !== undefined && digest === lastEventId) return step();
@@ -2606,10 +2680,14 @@ function liveSource(value, lastEventId, position, scope) {
2606
2680
  }
2607
2681
  };
2608
2682
  }
2609
- function encodeLiveResult(value, headers, status, codec, request, scope) {
2683
+ function encodeLiveResult(value, headers, status, codec, request, scope, shareKey) {
2610
2684
  if (NULL_BODY_STATUSES.has(status) || value === undefined || getHeadersAndBody(value)) {
2611
2685
  return encodeResult(value, headers, status, codec, request.signal, scope);
2612
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
+ }
2613
2691
  const position = {
2614
2692
  pending: undefined
2615
2693
  };
@@ -2627,6 +2705,213 @@ function encodeLiveResult(value, headers, status, codec, request, scope) {
2627
2705
  throw DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error;
2628
2706
  }
2629
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
+ }
2630
2915
  function encodeResult(value, headers, status, codec, signal, scope) {
2631
2916
  if (NULL_BODY_STATUSES.has(status)) {
2632
2917
  if (value === undefined || value === null) {
@@ -2831,7 +3116,7 @@ function withHeaders(response, write) {
2831
3116
  function withCSRFVary(response) {
2832
3117
  return withHeaders(response, headers => appendVary(headers, CSRF_VARY));
2833
3118
  }
2834
- 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(", ");
2835
3120
  const PREFLIGHT_MAX_AGE = "600";
2836
3121
  const CORS_SAFELISTED_RESPONSE_HEADERS = new Set(["cache-control", "content-language", "content-length", "content-type", "expires", "last-modified", "pragma"]);
2837
3122
  function withCORS(response, cors) {
@@ -2933,6 +3218,17 @@ async function handleServerFunctionRequest(request, options = {}) {
2933
3218
  });
2934
3219
  return finish(protectsRequest ? withCSRFVary(response) : response);
2935
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
+ }
2936
3232
  const scripted = address.data || address.live;
2937
3233
  const live = address.live;
2938
3234
  if (method !== "POST" && !declaredRead) {
@@ -3062,9 +3358,12 @@ async function handleServerFunctionRequest(request, options = {}) {
3062
3358
  const dispatch = async () => {
3063
3359
  try {
3064
3360
  const invokeOnce = async () => {
3361
+ const shared = !!live && BROADCASTS.has(functionId);
3065
3362
  INVOCATIONS.set(event, {
3066
3363
  id: functionId,
3067
- live: !!live
3364
+ live: !!live,
3365
+ broadcast: shared || undefined,
3366
+ shareKey: shared ? encodedArguments(request, argsEncoding, argumentBytes) : undefined
3068
3367
  });
3069
3368
  const run = () => serverFunction(...parsed);
3070
3369
  return observeInvocation({
@@ -3140,7 +3439,10 @@ async function handleServerFunctionRequest(request, options = {}) {
3140
3439
  return encodeResult(result, headers, status, codec, request.signal, scope);
3141
3440
  }
3142
3441
  if (status === 304) warnScripted304(functionId);
3143
- 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
+ }
3144
3446
  return encodeResult(result, headers, status, codec, request.signal, scope);
3145
3447
  } catch (x) {
3146
3448
  const respondThrown = value => {
@@ -3314,4 +3616,4 @@ function finalizeTransportResponse(response, method) {
3314
3616
  return response;
3315
3617
  }
3316
3618
 
3317
- 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 };
3619
+ 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 };