@solidjs/web 2.0.0-rc.5 → 2.0.0-rc.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/server.cjs +122 -38
  2. package/dist/server.dev.cjs +3794 -0
  3. package/dist/server.dev.js +3627 -0
  4. package/dist/server.js +123 -39
  5. package/dist/web.cjs +102 -366
  6. package/dist/{dev.cjs → web.dev.cjs} +153 -376
  7. package/dist/{dev.js → web.dev.js} +155 -374
  8. package/dist/web.js +104 -364
  9. package/frames/dist/client.cjs +11 -3
  10. package/frames/dist/client.dev.cjs +11 -3
  11. package/frames/dist/client.dev.js +11 -3
  12. package/frames/dist/client.js +11 -3
  13. package/frames/dist/server.cjs +320 -53
  14. package/frames/dist/server.dev.cjs +4584 -0
  15. package/frames/dist/server.dev.js +4571 -0
  16. package/frames/dist/server.js +320 -53
  17. package/frames/package.json +10 -0
  18. package/package.json +78 -8
  19. package/serialization/dist/decode.cjs +18 -4
  20. package/serialization/dist/decode.js +18 -4
  21. package/serialization/dist/serialization.cjs +18 -4
  22. package/serialization/dist/serialization.js +18 -4
  23. package/server-functions/dist/client.cjs +27 -16
  24. package/server-functions/dist/client.js +27 -16
  25. package/server-functions/dist/server.cjs +529 -131
  26. package/server-functions/dist/server.dev.cjs +536 -130
  27. package/server-functions/dist/server.dev.js +536 -130
  28. package/server-functions/dist/server.js +529 -131
  29. package/types/client.d.ts +1 -3
  30. package/types/constants.d.ts +3 -1
  31. package/types/frames/frame-client.d.ts +1 -1
  32. package/types/head.d.ts +3 -0
  33. package/types/index.d.ts +18 -7
  34. package/types/index.server.d.ts +31 -9
  35. package/types/render.d.ts +3 -1
  36. package/types/server-functions/flash.d.ts +12 -3
  37. package/types/server-functions/server.d.ts +100 -5
  38. package/types/server-mock.d.ts +43 -7
  39. package/types/server.d.ts +47 -5
  40. package/types-cjs/client.d.cts +1 -3
  41. package/types-cjs/constants.d.cts +3 -1
  42. package/types-cjs/frames/frame-client.d.cts +1 -1
  43. package/types-cjs/head.d.cts +3 -0
  44. package/types-cjs/index.d.cts +18 -7
  45. package/types-cjs/index.server.d.cts +31 -9
  46. package/types-cjs/render.d.cts +3 -1
  47. package/types-cjs/server-functions/flash.d.cts +12 -3
  48. package/types-cjs/server-functions/server.d.cts +100 -5
  49. package/types-cjs/server-mock.d.cts +43 -7
  50. package/types-cjs/server.d.cts +47 -5
  51. package/types/patch-driver.d.ts +0 -3
  52. package/types-cjs/patch-driver.d.cts +0 -3
@@ -1,5 +1,15 @@
1
1
  import { sharedConfig } from 'solid-js';
2
2
 
3
+ const COMPOSED_BODY_FRAMING = /*#__PURE__*/new Set(["content-length", "content-encoding", "transfer-encoding"]);
4
+ function isHttpNavigationTarget(target) {
5
+ try {
6
+ const protocol = new URL(target, "http://base.invalid").protocol;
7
+ return protocol === "http:" || protocol === "https:";
8
+ } catch {
9
+ return false;
10
+ }
11
+ }
12
+
3
13
  const ENVELOPE = Symbol.for("solid.ResponseEnvelope");
4
14
  function isResponseEnvelope(value) {
5
15
  return !!(value && typeof value === "object" && value[ENVELOPE]);
@@ -237,7 +247,7 @@ function isJSONSafe(value) {
237
247
  const t = typeof v;
238
248
  if (t === "string" || t === "boolean") continue;
239
249
  if (t === "number") {
240
- if (!Number.isFinite(v)) return false;
250
+ if (!Number.isFinite(v) || Object.is(v, -0)) return false;
241
251
  continue;
242
252
  }
243
253
  if (t !== "object") return false;
@@ -323,31 +333,30 @@ function getHeadersAndBody(body) {
323
333
  async function extractBody(source, codecOptions) {
324
334
  const contentType = source.headers.get("content-type");
325
335
  const format = source.headers.get(BODY_FORMAT_HEADER);
326
- const clone = source.clone();
327
336
  switch (true) {
328
337
  case format === BodyFormat.Serialized:
329
- return await deserializeStream(clone, codecOptions);
338
+ return await deserializeStream(source, codecOptions);
330
339
  case format === BodyFormat.Json:
331
- return JSON.parse(await clone.text());
340
+ return JSON.parse(await source.text());
332
341
  case format === BodyFormat.String:
333
- return await clone.text();
342
+ return await source.text();
334
343
  case format === BodyFormat.File:
335
344
  {
336
- const formData = await clone.formData();
345
+ const formData = await source.formData();
337
346
  return formData.get(FILE_FORM_KEY);
338
347
  }
339
348
  case format === BodyFormat.FormData:
340
349
  case contentType && contentType.startsWith("multipart/form-data"):
341
- return await clone.formData();
350
+ return await source.formData();
342
351
  case format === BodyFormat.URLSearchParams:
343
352
  case contentType && contentType.startsWith("application/x-www-form-urlencoded"):
344
- return new URLSearchParams(await clone.text());
353
+ return new URLSearchParams(await source.text());
345
354
  case format === BodyFormat.Blob:
346
- return await clone.blob();
355
+ return await source.blob();
347
356
  case format === BodyFormat.ArrayBuffer:
348
- return await clone.arrayBuffer();
357
+ return await source.arrayBuffer();
349
358
  case format === BodyFormat.Uint8Array:
350
- return new Uint8Array(await clone.arrayBuffer());
359
+ return new Uint8Array(await source.arrayBuffer());
351
360
  }
352
361
  return undefined;
353
362
  }
@@ -483,7 +492,7 @@ async function deserializeString(text, codecOptions) {
483
492
  }
484
493
  async function decodeResponse(response, codecOptions) {
485
494
  if (!response.body) return undefined;
486
- return await extractBody(response, codecOptions === undefined ? codecConfig.codec : codecOptions);
495
+ return await extractBody(response.clone(), codecOptions === undefined ? codecConfig.codec : codecOptions);
487
496
  }
488
497
  async function decodeResponsePayload(response, codecOptions) {
489
498
  const decoded = await decodeResponse(response, codecOptions);
@@ -534,7 +543,8 @@ function copyInitHeaders(init) {
534
543
  for (const cookie of init.getSetCookie()) headers.append("Set-Cookie", cookie);
535
544
  return headers;
536
545
  }
537
- const STUB_GAP_FILL_EXCLUDED = /*#__PURE__*/new Set([ERROR_HEADER, BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, REVALIDATE_HEADER, REDIRECT_HEADER, "Location"].map(header => header.toLowerCase()));
546
+ const STUB_GAP_FILL_EXCLUDED = /*#__PURE__*/new Set([ERROR_HEADER, BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, REVALIDATE_HEADER, REDIRECT_HEADER, "Location",
547
+ ...COMPOSED_BODY_FRAMING].map(header => header.toLowerCase()));
538
548
  function fillsStubGap(key, headers, response) {
539
549
  if (key === "set-cookie" || STUB_GAP_FILL_EXCLUDED.has(key)) return false;
540
550
  if (response.body === null && (key === "content-type" || key === "content-length")) return false;
@@ -562,6 +572,62 @@ function commitEventResponse(response, event = getRequestEvent()) {
562
572
  });
563
573
  }
564
574
 
575
+ let configuredSecret;
576
+ function setFlashSecret(secret) {
577
+ configuredSecret = secret;
578
+ }
579
+ function resolveSecret() {
580
+ return configuredSecret !== undefined ? configuredSecret : globalThis.__SOLID_SECRET__;
581
+ }
582
+ const FLASH_KEY_DOMAIN = "solid.flash.v1\0";
583
+ let cachedSecret;
584
+ let cachedKey;
585
+ function resolveFlashKey() {
586
+ const secret = resolveSecret();
587
+ if (typeof secret !== "string" || secret.length === 0) return null;
588
+ if (secret !== cachedSecret) {
589
+ cachedSecret = secret;
590
+ cachedKey = crypto.subtle.digest("SHA-256", new TextEncoder().encode(FLASH_KEY_DOMAIN + secret)).then(digest => crypto.subtle.importKey("raw", digest, {
591
+ name: "AES-GCM"
592
+ }, false, ["encrypt", "decrypt"]));
593
+ }
594
+ return cachedKey;
595
+ }
596
+ const FLASH_FORMAT_VERSION = "1.";
597
+ const IV_BYTES = 12;
598
+ const GCM_TAG_BYTES = 16;
599
+ function toBase64url(bytes) {
600
+ let binary = "";
601
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
602
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
603
+ }
604
+ function fromBase64url(text) {
605
+ const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/"));
606
+ const bytes = new Uint8Array(binary.length);
607
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
608
+ return bytes;
609
+ }
610
+ async function encryptFlashValue(key, json) {
611
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
612
+ const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
613
+ name: "AES-GCM",
614
+ iv
615
+ }, key, new TextEncoder().encode(json)));
616
+ const packed = new Uint8Array(IV_BYTES + ciphertext.length);
617
+ packed.set(iv);
618
+ packed.set(ciphertext, IV_BYTES);
619
+ return FLASH_FORMAT_VERSION + toBase64url(packed);
620
+ }
621
+ async function decryptFlashValue(key, value) {
622
+ if (!value.startsWith(FLASH_FORMAT_VERSION)) return;
623
+ const packed = fromBase64url(value.slice(FLASH_FORMAT_VERSION.length));
624
+ if (packed.length <= IV_BYTES + GCM_TAG_BYTES) return;
625
+ const plain = await crypto.subtle.decrypt({
626
+ name: "AES-GCM",
627
+ iv: packed.subarray(0, IV_BYTES)
628
+ }, key, packed.subarray(IV_BYTES));
629
+ return new TextDecoder().decode(plain);
630
+ }
565
631
  function encodeInputValue(value) {
566
632
  if (value instanceof FormData) return {
567
633
  $f: [...value.entries()].filter(([, v]) => typeof v === "string")
@@ -582,7 +648,11 @@ function decodeInputValue(value) {
582
648
  }
583
649
  return value;
584
650
  }
585
- function encodeFlashCookie(url, result, input, thrown) {
651
+ async function encodeFlashCookie(url, result, input, thrown) {
652
+ const key = resolveFlashKey();
653
+ if (!key) {
654
+ return null;
655
+ }
586
656
  const isError = result instanceof Error;
587
657
  const payload = {
588
658
  url,
@@ -591,7 +661,7 @@ function encodeFlashCookie(url, result, input, thrown) {
591
661
  thrown: !!thrown,
592
662
  input: input.map(encodeInputValue)
593
663
  };
594
- if (fitsCookie(payload)) return flashCookie(payload);
664
+ if (fitsCookie(payload)) return flashCookie(payload, await key);
595
665
  payload.truncated = true;
596
666
  payload.input = [];
597
667
  if (!fitsCookie(payload)) {
@@ -608,24 +678,35 @@ function encodeFlashCookie(url, result, input, thrown) {
608
678
  payload.result = true;
609
679
  }
610
680
  }
611
- return flashCookie(payload);
681
+ if (!fitsCookie(payload)) return null;
682
+ return flashCookie(payload, await key);
612
683
  }
613
- function flashCookie(payload) {
614
- return serializeCookie(FLASH_COOKIE, JSON.stringify(payload), {
684
+ const FLASH_MAX_AGE_SECONDS = 60;
685
+ async function flashCookie(payload, key) {
686
+ return serializeCookie(FLASH_COOKIE, await encryptFlashValue(key, JSON.stringify(payload)), {
615
687
  secure: true,
616
- httpOnly: true
688
+ httpOnly: true,
689
+ sameSite: "lax",
690
+ maxAge: FLASH_MAX_AGE_SECONDS
617
691
  });
618
692
  }
619
693
  const COOKIE_PAIR_BUDGET = 4000;
620
694
  function fitsCookie(payload) {
621
- return FLASH_COOKIE.length + 1 + encodeURIComponent(JSON.stringify(payload)).length <= COOKIE_PAIR_BUDGET;
695
+ const plaintextBytes = new TextEncoder().encode(JSON.stringify(payload)).length;
696
+ const packedBytes = IV_BYTES + plaintextBytes + GCM_TAG_BYTES;
697
+ const valueLength = FLASH_FORMAT_VERSION.length + Math.ceil(packedBytes * 4 / 3);
698
+ return FLASH_COOKIE.length + 1 + valueLength <= COOKIE_PAIR_BUDGET;
622
699
  }
623
- function decodeFlashCookie(cookieHeader) {
700
+ async function decodeFlashCookie(cookieHeader) {
624
701
  const match = parseCookieHeader(cookieHeader)[FLASH_COOKIE];
625
702
  if (!match) return;
626
703
  try {
627
- const payload = JSON.parse(match);
628
- if (!payload || !payload.result) return;
704
+ const key = resolveFlashKey();
705
+ if (!key) return;
706
+ const json = await decryptFlashValue(await key, match);
707
+ if (json === undefined) return;
708
+ const payload = JSON.parse(json);
709
+ if (!payload || typeof payload !== "object" || !("result" in payload)) return;
629
710
  const result = payload.error ? new Error(payload.result) : payload.result;
630
711
  const submission = {
631
712
  input: Array.isArray(payload.input) ? payload.input.map(decodeInputValue) : [],
@@ -636,7 +717,6 @@ function decodeFlashCookie(cookieHeader) {
636
717
  if (payload.truncated) submission.truncated = true;
637
718
  return submission;
638
719
  } catch (error) {
639
- console.error(error);
640
720
  }
641
721
  }
642
722
 
@@ -665,7 +745,8 @@ function configureServerFunctionsServer({
665
745
  csrf,
666
746
  codec,
667
747
  bodySizeLimit,
668
- maxArguments
748
+ maxArguments,
749
+ secret
669
750
  } = {}) {
670
751
  if (provideEvent !== undefined) config.provideEvent = provideEvent;
671
752
  if (wrapInvocation !== undefined) config.wrapInvocation = wrapInvocation;
@@ -679,6 +760,7 @@ function configureServerFunctionsServer({
679
760
  if (codec !== undefined) configureServerFunctionsCodec(codec);
680
761
  if (bodySizeLimit !== undefined) config.bodySizeLimit = bodySizeLimit;
681
762
  if (maxArguments !== undefined) config.maxArguments = maxArguments;
763
+ if (secret !== undefined) setFlashSecret(secret);
682
764
  }
683
765
  const flightSources = new Map();
684
766
  function registerFlightDataSource(source, hook) {
@@ -688,14 +770,198 @@ function registerFlightDataSource(source, hook) {
688
770
  if (flightSources.get(source) === hook) flightSources.delete(source);
689
771
  };
690
772
  }
773
+ function resolveWrapInvocation(hook) {
774
+ if (hook === undefined || typeof hook === "function") return hook;
775
+ throw new Error(`Invalid wrapInvocation: expected a function, received ${hook === null ? "null" : typeof hook}. A hook that is not callable cannot wrap the call - configure a function, or leave ` + `wrapInvocation undefined.`);
776
+ }
691
777
  function provideEvent(event, fn) {
692
778
  if (config.provideEvent) return config.provideEvent(event, fn);
693
779
  const ctx = globalThis[RequestContext];
694
780
  if (ctx) return ctx.run(event, fn);
695
781
  throw new Error("No request event provider. Configure one with configureServerFunctionsServer({ provideEvent }).");
696
782
  }
783
+ const PROVIDE_EVENT_TWICE = "provideEvent invoked the server function callback more than once: a second invocation " + "would commit the call's side effects twice. The hook must call fn exactly once and return " + "its result.";
784
+ const PROVIDE_EVENT_NEVER = "provideEvent returned without invoking the server function callback: the call would have " + "answered as a void success without running the function. The hook must call fn exactly once " + "and return its result.";
785
+ function provideEventOnce(provide, event, run) {
786
+ let invocations = 0;
787
+ const settle = () => {
788
+ if (invocations !== 1) throw new Error(invocations === 0 ? PROVIDE_EVENT_NEVER : PROVIDE_EVENT_TWICE);
789
+ };
790
+ const result = provide(event, () => {
791
+ if (++invocations > 1) throw new Error(PROVIDE_EVENT_TWICE);
792
+ return run();
793
+ });
794
+ const promised = nativePromise(result);
795
+ if (promised) {
796
+ return promised.then(value => {
797
+ settle();
798
+ return value;
799
+ });
800
+ }
801
+ settle();
802
+ return result;
803
+ }
804
+ function scopeDeferredResult(value, scope) {
805
+ const bound = bindDeferredBody(value, scope);
806
+ if (bound !== value || value === null || typeof value !== "object") return bound;
807
+ return scopeDeferredContents(value, scope);
808
+ }
809
+ class ScopeFrame {
810
+ constructor(value, next, keys, descriptors) {
811
+ this.value = value;
812
+ this.next = next;
813
+ this.keys = keys;
814
+ this.descriptors = descriptors;
815
+ this.i = 0;
816
+ this.changed = false;
817
+ }
818
+ }
819
+ function enterScopeCarrier(value, state) {
820
+ if (value === null || typeof value !== "object" && typeof value !== "function") return value;
821
+ if (state.seen.has(value)) {
822
+ state.cyclic.add(value);
823
+ return state.seen.get(value);
824
+ }
825
+ const bound = bindDeferredBody(value, state.scope);
826
+ if (bound !== value) {
827
+ state.seen.set(value, bound);
828
+ return bound;
829
+ }
830
+ if (typeof value !== "object") return value;
831
+ if (Array.isArray(value)) {
832
+ if (Object.isFrozen(value)) {
833
+ state.seen.set(value, value);
834
+ return value;
835
+ }
836
+ const next = value.slice();
837
+ state.seen.set(value, next);
838
+ return new ScopeFrame(value, next, null, null);
839
+ }
840
+ const prototype = Object.getPrototypeOf(value);
841
+ if (prototype !== Object.prototype && prototype !== null || Object.isFrozen(value)) {
842
+ state.seen.set(value, value);
843
+ return value;
844
+ }
845
+ const descriptors = Object.getOwnPropertyDescriptors(value);
846
+ const next = Object.create(prototype, descriptors);
847
+ state.seen.set(value, next);
848
+ return new ScopeFrame(value, next, Object.keys(value), descriptors);
849
+ }
850
+ function scopeDeferredContents(root, scope) {
851
+ const state = {
852
+ seen: new Map(),
853
+ cyclic: new Set(),
854
+ scope
855
+ };
856
+ const entered = enterScopeCarrier(root, state);
857
+ if (!(entered instanceof ScopeFrame)) return entered;
858
+ const stack = [entered];
859
+ let delivered = NOTHING;
860
+ for (;;) {
861
+ const top = stack[stack.length - 1];
862
+ const length = top.keys ? top.keys.length : top.value.length;
863
+ let pushed = null;
864
+ while (top.i < length) {
865
+ const i = top.i;
866
+ let original;
867
+ let writable = true;
868
+ if (top.keys) {
869
+ const descriptor = top.descriptors[top.keys[i]];
870
+ writable = "value" in descriptor && descriptor.writable === true;
871
+ original = writable ? descriptor.value : undefined;
872
+ } else {
873
+ original = top.value[i];
874
+ }
875
+ if (!writable) {
876
+ top.i++;
877
+ continue;
878
+ }
879
+ let bound;
880
+ if (delivered !== NOTHING) {
881
+ bound = delivered;
882
+ delivered = NOTHING;
883
+ } else {
884
+ bound = enterScopeCarrier(original, state);
885
+ if (bound instanceof ScopeFrame) {
886
+ pushed = bound;
887
+ break;
888
+ }
889
+ }
890
+ if (bound !== original) {
891
+ if (top.keys) top.next[top.keys[i]] = bound;else top.next[i] = bound;
892
+ top.changed = true;
893
+ }
894
+ top.i++;
895
+ }
896
+ if (pushed !== null) {
897
+ stack.push(pushed);
898
+ continue;
899
+ }
900
+ stack.pop();
901
+ let out;
902
+ if (top.changed || state.cyclic.has(top.value)) {
903
+ out = top.next;
904
+ } else {
905
+ state.seen.set(top.value, top.value);
906
+ out = top.value;
907
+ }
908
+ if (stack.length === 0) return out;
909
+ delivered = out;
910
+ }
911
+ }
912
+ function bindDeferredBody(value, scope) {
913
+ if (value === null || typeof value !== "object" && typeof value !== "function") return value;
914
+ const promised = scope(() => nativePromise(value));
915
+ if (promised) {
916
+ return promised.then(result => scope(() => scopeDeferredResult(result, scope)));
917
+ }
918
+ if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) {
919
+ let reader;
920
+ return new ReadableStream({
921
+ async pull(controller) {
922
+ try {
923
+ const step = await scope(() => {
924
+ if (!reader) reader = value.getReader();
925
+ return reader.read();
926
+ });
927
+ if (step.done) controller.close();else controller.enqueue(step.value);
928
+ } catch (error) {
929
+ controller.error(error);
930
+ }
931
+ },
932
+ cancel(reason) {
933
+ return scope(() => reader ? reader.cancel(reason) : value.cancel(reason));
934
+ }
935
+ }, {
936
+ highWaterMark: 0
937
+ });
938
+ }
939
+ const scopedIterator = symbol => ({
940
+ [symbol]() {
941
+ const iterator = scope(() => value[symbol]());
942
+ return new Proxy(iterator, {
943
+ get(target, property) {
944
+ const member = Reflect.get(target, property, target);
945
+ return typeof member === "function" && (property === "next" || property === "return" || property === "throw") ? (...args) => scope(() => member.apply(target, args)) : member;
946
+ }
947
+ });
948
+ }
949
+ });
950
+ if (typeof value[Symbol.asyncIterator] === "function") {
951
+ return scopedIterator(Symbol.asyncIterator);
952
+ }
953
+ if (typeof value[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value)) {
954
+ return scopedIterator(Symbol.iterator);
955
+ }
956
+ return value;
957
+ }
697
958
  const REGISTRATIONS = new Map();
698
959
  const METHODS = new Map();
960
+ const REFERENCE_BINDINGS = new WeakMap();
961
+ function declaresRead(id) {
962
+ const granted = METHODS.get(id);
963
+ return granted !== undefined && granted === REGISTRATIONS.get(id);
964
+ }
699
965
  const INVOCATIONS = new WeakMap();
700
966
  let rpcProvided = false;
701
967
  function provideRPC() {
@@ -791,40 +1057,72 @@ function createServerReference({
791
1057
  id
792
1058
  });
793
1059
  evt.serverOnly = true;
794
- const result = provideEvent(evt, () => {
1060
+ const scope = run => provideEvent(evt, run);
1061
+ const wrap = resolveWrapInvocation(config.wrapInvocation);
1062
+ let result = provideEventOnce(provideEvent, evt, () => {
795
1063
  const run = () => fn.apply(thisArg, args);
796
- return config.wrapInvocation ? config.wrapInvocation(run, {
1064
+ return wrap ? wrap(run, {
797
1065
  id,
798
1066
  args,
799
1067
  event: evt,
800
1068
  direct: true
801
1069
  }) : run();
802
1070
  });
1071
+ result = scopeDeferredResult(result, scope);
803
1072
  const transform = config.transformDirectResult;
804
1073
  if (transform && result && typeof result.then === "function") {
805
- return result.then(value => transform(value, {
1074
+ return result.then(value => scopeDeferredResult(transform(value, {
806
1075
  id,
807
1076
  args,
808
1077
  event: evt
809
- }));
1078
+ }), scope));
810
1079
  }
811
- return transform ? transform(result, {
1080
+ return transform ? scopeDeferredResult(transform(result, {
812
1081
  id,
813
1082
  args,
814
1083
  event: evt
815
- }) : result;
1084
+ }), scope) : result;
816
1085
  }
817
1086
  });
1087
+ REFERENCE_BINDINGS.set(proxy, fn);
818
1088
  return proxy;
819
1089
  }
820
1090
  function GET(fn) {
821
1091
  if (!isServerFunction(fn) || typeof fn.id !== "string") {
822
1092
  throw new Error("GET expects a server function reference");
823
1093
  }
824
- METHODS.set(fn.id, "GET");
825
- return withMeta(fn, {
1094
+ const id = fn.id;
1095
+ const binding = REFERENCE_BINDINGS.has(fn) ? REFERENCE_BINDINGS.get(fn) : REGISTRATIONS.get(id);
1096
+ const existing = METHODS.get(id);
1097
+ if (existing !== undefined && existing !== binding) {
1098
+ if (DEV) {
1099
+ throw new Error(`GET() would rebind the existing grant for server function "${id}" to a different ` + `function. A GET declaration is made about a function, not an id - two references ` + `sharing one id cannot both hold it. Give the functions distinct ids, or drop the ` + `stale declaration.`);
1100
+ }
1101
+ METHODS.delete(id);
1102
+ return fn;
1103
+ }
1104
+ METHODS.set(id, binding);
1105
+ const reference = withMeta(fn, {
826
1106
  method: "GET"
827
1107
  });
1108
+ guardDeclaredMethod(getServerFunctionMetadata(reference), id);
1109
+ return reference;
1110
+ }
1111
+ function guardDeclaredMethod(metadata, id) {
1112
+ let declared = metadata.method;
1113
+ Object.defineProperty(metadata, "method", {
1114
+ configurable: true,
1115
+ enumerable: true,
1116
+ get: () => declared,
1117
+ set(next) {
1118
+ if (next === declared) return;
1119
+ if (DEV) {
1120
+ throw new Error(`withMeta({ method }) cannot change the GET() declaration of server function ` + `"${id}". The method is declaration-scoped: it was granted about the function ` + `by GET(fn), and a metadata write cannot re-shape the wire grant.`);
1121
+ }
1122
+ METHODS.delete(id);
1123
+ declared = next;
1124
+ }
1125
+ });
828
1126
  }
829
1127
  function live(fn) {
830
1128
  if (!isServerFunction(fn) || typeof fn.id !== "string") {
@@ -878,22 +1176,58 @@ function assertDecodeDepth(value) {
878
1176
  level = next;
879
1177
  }
880
1178
  }
1179
+ const UNSAFE_ARGUMENT_KEYS = ["__proto__", "constructor", "prototype"];
1180
+ function stripUnsafeArgumentKeys(value) {
1181
+ const stack = [value];
1182
+ const seen = new Set();
1183
+ while (stack.length) {
1184
+ const v = stack.pop();
1185
+ if (v === null || typeof v !== "object" || seen.has(v)) continue;
1186
+ seen.add(v);
1187
+ for (const key of UNSAFE_ARGUMENT_KEYS) {
1188
+ delete v[key];
1189
+ }
1190
+ for (const key of Object.keys(v)) stack.push(v[key]);
1191
+ if (v instanceof Map) {
1192
+ for (const [k, entry] of v) stack.push(k, entry);
1193
+ } else if (v instanceof Set) {
1194
+ for (const member of v) stack.push(member);
1195
+ }
1196
+ }
1197
+ return value;
1198
+ }
881
1199
  async function bufferBodyWithin(request, limit) {
882
- const reader = request.clone().body.getReader();
1200
+ const reader = request.body.getReader();
1201
+ const signal = request.signal;
883
1202
  const chunks = [];
884
1203
  let total = 0;
885
- for (;;) {
886
- const {
887
- done,
888
- value
889
- } = await reader.read();
890
- if (done) break;
891
- total += value.byteLength;
892
- if (total > limit) {
893
- reader.cancel().catch(() => {});
894
- return null;
1204
+ const onAbort = () => {
1205
+ reader.cancel(signal.reason).catch(() => {});
1206
+ };
1207
+ if (signal.aborted) onAbort();else signal.addEventListener("abort", onAbort, {
1208
+ once: true
1209
+ });
1210
+ try {
1211
+ for (;;) {
1212
+ const {
1213
+ done,
1214
+ value
1215
+ } = await reader.read();
1216
+ if (signal.aborted) throw signal.reason;
1217
+ if (done) break;
1218
+ total += value.byteLength;
1219
+ if (total > limit) {
1220
+ reader.cancel().catch(() => {});
1221
+ return null;
1222
+ }
1223
+ chunks.push(value);
895
1224
  }
896
- chunks.push(value);
1225
+ } catch (error) {
1226
+ reader.cancel(error).catch(() => {});
1227
+ throw error;
1228
+ } finally {
1229
+ signal.removeEventListener("abort", onAbort);
1230
+ reader.releaseLock();
897
1231
  }
898
1232
  const body = new Uint8Array(total);
899
1233
  let offset = 0;
@@ -905,6 +1239,13 @@ async function bufferBodyWithin(request, limit) {
905
1239
  body
906
1240
  });
907
1241
  }
1242
+ const KNOWN_BODY_FORMATS = new Set(Object.values(BodyFormat));
1243
+ const FORMAT_SKEW = Symbol("solid.serverFunction.formatSkew");
1244
+ function unknownFormatError(tag) {
1245
+ const error = new TypeError(`Server function body carries an unrecognized ${BODY_FORMAT_HEADER} tag ("${tag}"): the ` + "caller encodes a newer wire format than this build can decode (version skew), or an " + "intermediary duplicated the header. The body was refused rather than reinterpreted.");
1246
+ error[FORMAT_SKEW] = true;
1247
+ return error;
1248
+ }
908
1249
  async function parseArguments(request, url, scripted, codec) {
909
1250
  const parsed = [];
910
1251
  const bodyFormat = request.method === "POST" ? request.headers.get(BODY_FORMAT_HEADER) : null;
@@ -920,6 +1261,7 @@ async function parseArguments(request, url, scripted, codec) {
920
1261
  if (!Array.isArray(result)) {
921
1262
  throw new TypeError("Server function arguments must encode an array");
922
1263
  }
1264
+ stripUnsafeArgumentKeys(result);
923
1265
  for (const arg of result) {
924
1266
  parsed.push(arg);
925
1267
  }
@@ -927,15 +1269,22 @@ async function parseArguments(request, url, scripted, codec) {
927
1269
  parsed.push(url.searchParams);
928
1270
  }
929
1271
  if (request.method === "POST" && request.body !== null) {
930
- const decoded = await extractBody(request.clone(), codec);
1272
+ if (bodyFormat !== null && !KNOWN_BODY_FORMATS.has(bodyFormat)) {
1273
+ throw unknownFormatError(bodyFormat);
1274
+ }
1275
+ const body = request.clone();
1276
+ const decoded = await extractBody(body, codec);
931
1277
  if (bodyFormat === BodyFormat.Serialized || bodyFormat === BodyFormat.Json) {
932
1278
  if (bodyFormat === BodyFormat.Json) assertDecodeDepth(decoded);
933
1279
  if (!Array.isArray(decoded)) {
934
1280
  throw new TypeError("Server function arguments must encode an array");
935
1281
  }
936
- return decoded;
1282
+ return stripUnsafeArgumentKeys(decoded);
937
1283
  }
938
1284
  if (decoded === undefined) {
1285
+ if (bodyFormat === null && (await body.arrayBuffer()).byteLength === 0) {
1286
+ return parsed;
1287
+ }
939
1288
  throw new TypeError("Server function body carries no usable encoding");
940
1289
  }
941
1290
  parsed.push(decoded);
@@ -963,13 +1312,14 @@ async function foldFlightData(hooks, event, headers, outcome, context = {}) {
963
1312
  data
964
1313
  }, context);
965
1314
  if (transformed !== undefined) {
966
- for (const cookie of headers.getSetCookie()) transformed.headers.append("Set-Cookie", cookie);
1315
+ const owned = ownResponse(transformed);
1316
+ for (const cookie of headers.getSetCookie()) owned.headers.append("Set-Cookie", cookie);
967
1317
  headers.forEach((value, key) => {
968
- if (key !== "set-cookie" && !transformed.headers.has(key)) {
969
- transformed.headers.set(key, value);
1318
+ if (key !== "set-cookie" && !owned.headers.has(key)) {
1319
+ owned.headers.set(key, value);
970
1320
  }
971
1321
  });
972
- return transformed;
1322
+ return owned;
973
1323
  }
974
1324
  }
975
1325
  return outcome.value === undefined ? {
@@ -1036,7 +1386,7 @@ function foldSetCookies(headers, setCookies) {
1036
1386
  }
1037
1387
  function mergeResponseHeaders(target, source) {
1038
1388
  source.forEach((value, key) => {
1039
- if (key !== "set-cookie") target.append(key, value);
1389
+ if (key !== "set-cookie" && !COMPOSED_BODY_FRAMING.has(key)) target.append(key, value);
1040
1390
  });
1041
1391
  if (source.getSetCookie) {
1042
1392
  for (const cookie of source.getSetCookie()) target.append("Set-Cookie", cookie);
@@ -1053,10 +1403,6 @@ function maskRedirect(headers, response, requestUrl) {
1053
1403
  headers.delete("Location");
1054
1404
  }
1055
1405
  const BOUNDED_COMPOSED_HEADERS = [REDIRECT_HEADER, "Location", REVALIDATE_HEADER];
1056
- function refusedTargetScheme(target) {
1057
- const match = /^[a-zA-Z][a-zA-Z0-9+.-]*:/.exec(target);
1058
- return match !== null && !/^https?:$/i.test(match[0]);
1059
- }
1060
1406
  function enforceComposedHeaderInvariants(response) {
1061
1407
  for (const name of BOUNDED_COMPOSED_HEADERS) {
1062
1408
  const value = response.headers.get(name);
@@ -1066,7 +1412,7 @@ function enforceComposedHeaderInvariants(response) {
1066
1412
  }
1067
1413
  if (name === REVALIDATE_HEADER) continue;
1068
1414
  const target = name === REDIRECT_HEADER ? value.slice(value.indexOf(" ") + 1) : value;
1069
- if (refusedTargetScheme(target)) {
1415
+ if (!isHttpNavigationTarget(target)) {
1070
1416
  return refuseComposedHeader(response, name, `${name} response header refused: non-http(s) navigation target`, DEV ? `The ${name} response header carries a navigation target with a non-http(s) ` + `scheme ("${target.slice(0, 64)}"). A javascript: target is same-origin script ` + `execution in any integration that navigates to it, so only http(s) and ` + `relative targets leave this transport. If the target came from request data ` + `(?next= and friends), validate it against your own origin before redirecting.` : null);
1071
1417
  }
1072
1418
  }
@@ -1094,7 +1440,7 @@ function warnScripted304(functionId) {
1094
1440
  function createNoJSHandler({
1095
1441
  base = ""
1096
1442
  } = {}) {
1097
- return function handleNoJS(result, request, args, thrown) {
1443
+ return async function handleNoJS(result, request, args, thrown) {
1098
1444
  const url = new URL(request.url);
1099
1445
  let back = new URL(base || "/", url.origin).toString();
1100
1446
  try {
@@ -1119,8 +1465,9 @@ function createNoJSHandler({
1119
1465
  Location: back
1120
1466
  });
1121
1467
  }
1122
- if (result && !(result instanceof Response)) {
1123
- headers.append("Set-Cookie", encodeFlashCookie(url.pathname + url.search, result, args, thrown));
1468
+ if (result !== undefined && !(result instanceof Response)) {
1469
+ const flash = await encodeFlashCookie(url.pathname, result, args, thrown);
1470
+ if (flash !== null) headers.append("Set-Cookie", flash);
1124
1471
  }
1125
1472
  return new Response(null, {
1126
1473
  status,
@@ -1194,14 +1541,11 @@ function guardFailures(value, state) {
1194
1541
  top.next.add(guarded);
1195
1542
  if (guarded !== original) top.changed = true;
1196
1543
  } else if (guarded !== original || top.accessorRead === i) {
1197
- Object.defineProperty(top.next, items[i], top.accessorRead === i ? {
1198
- enumerable: true,
1199
- configurable: true,
1544
+ Object.defineProperty(top.next, items[i], {
1545
+ value: guarded,
1200
1546
  writable: true,
1201
- value: guarded
1202
- } : {
1203
- ...top.descriptors[items[i]],
1204
- value: guarded
1547
+ configurable: true,
1548
+ enumerable: top.descriptors[items[i]].enumerable
1205
1549
  });
1206
1550
  top.changed = true;
1207
1551
  }
@@ -1236,6 +1580,9 @@ class Frame {
1236
1580
  this.pendingKey = undefined;
1237
1581
  }
1238
1582
  }
1583
+ function guardOperation(state, run) {
1584
+ return state.scope ? state.scope(run) : run();
1585
+ }
1239
1586
  function enterGuard(value, state) {
1240
1587
  if (value === null || typeof value !== "object") return value;
1241
1588
  if (state.seen.has(value)) {
@@ -1250,7 +1597,7 @@ function enterGuard(value, state) {
1250
1597
  if (finished) return;
1251
1598
  finished = true;
1252
1599
  try {
1253
- const cancelled = reader ? reader.cancel() : value.cancel();
1600
+ const cancelled = guardOperation(state, () => reader ? reader.cancel() : value.cancel());
1254
1601
  if (cancelled && typeof cancelled.then === "function") cancelled.then(undefined, () => {});
1255
1602
  } catch {}
1256
1603
  };
@@ -1262,19 +1609,19 @@ function enterGuard(value, state) {
1262
1609
  controller.close();
1263
1610
  return;
1264
1611
  }
1265
- if (!reader) reader = value.getReader();
1612
+ if (!reader) reader = guardOperation(state, () => value.getReader());
1266
1613
  const {
1267
1614
  done,
1268
1615
  value: chunk
1269
- } = await reader.read();
1270
- done ? controller.close() : controller.enqueue(guardFailures(chunk, state));
1616
+ } = await guardOperation(state, () => reader.read());
1617
+ done ? controller.close() : controller.enqueue(guardOperation(state, () => guardFailures(chunk, state)));
1271
1618
  } catch (error) {
1272
- controller.error(sanitizeServerError(error));
1619
+ controller.error(guardOperation(state, () => sanitizeServerError(error)));
1273
1620
  }
1274
1621
  },
1275
1622
  cancel(reason) {
1276
1623
  finished = true;
1277
- return reader ? reader.cancel(reason) : value.cancel(reason);
1624
+ return guardOperation(state, () => reader ? reader.cancel(reason) : value.cancel(reason));
1278
1625
  }
1279
1626
  });
1280
1627
  if (gate) gate.onOpen(close);
@@ -1282,9 +1629,10 @@ function enterGuard(value, state) {
1282
1629
  return guardedStream;
1283
1630
  }
1284
1631
  if (typeof value.then === "function") {
1285
- const guardedPromise = Promise.resolve(value).then(resolved => guardFailures(resolved, state), error => {
1286
- throw sanitizeServerError(error);
1632
+ const guardedPromise = Promise.resolve(value).then(resolved => guardOperation(state, () => guardFailures(resolved, state)), error => {
1633
+ throw guardOperation(state, () => sanitizeServerError(error));
1287
1634
  });
1635
+ guardedPromise.catch(() => {});
1288
1636
  state.seen.set(value, guardedPromise);
1289
1637
  return guardedPromise;
1290
1638
  }
@@ -1293,13 +1641,13 @@ function enterGuard(value, state) {
1293
1641
  const gate = state.gate;
1294
1642
  const guardedIterable = {
1295
1643
  [Symbol.asyncIterator]() {
1296
- const iterator = source[Symbol.asyncIterator]();
1644
+ const iterator = guardOperation(state, () => source[Symbol.asyncIterator]());
1297
1645
  let finished = false;
1298
1646
  const close = () => {
1299
1647
  if (finished) return;
1300
1648
  finished = true;
1301
1649
  try {
1302
- const returned = iterator.return && iterator.return();
1650
+ const returned = iterator.return && guardOperation(state, () => iterator.return());
1303
1651
  if (returned && typeof returned.then === "function") returned.then(undefined, () => {});
1304
1652
  } catch {}
1305
1653
  };
@@ -1307,17 +1655,17 @@ function enterGuard(value, state) {
1307
1655
  const step = () => finished ? Promise.resolve({
1308
1656
  done: true,
1309
1657
  value: undefined
1310
- }) : iterator.next().then(step => {
1658
+ }) : guardOperation(state, () => iterator.next()).then(step => {
1311
1659
  if (step.done) {
1312
1660
  finished = true;
1313
1661
  return step;
1314
1662
  }
1315
1663
  return {
1316
1664
  done: false,
1317
- value: guardFailures(step.value, state)
1665
+ value: guardOperation(state, () => guardFailures(step.value, state))
1318
1666
  };
1319
1667
  }, error => {
1320
- throw sanitizeServerError(error);
1668
+ throw guardOperation(state, () => sanitizeServerError(error));
1321
1669
  });
1322
1670
  return {
1323
1671
  next: () => finished || !gate || gate.wantsMore() ? step() : gate.awaitDemand().then(step),
@@ -1334,6 +1682,11 @@ function enterGuard(value, state) {
1334
1682
  state.seen.set(value, guardedIterable);
1335
1683
  return guardedIterable;
1336
1684
  }
1685
+ if (state.scope && typeof value[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value)) {
1686
+ const scopedIterable = scopeDeferredResult(value, state.scope);
1687
+ state.seen.set(value, scopedIterable);
1688
+ return scopedIterable;
1689
+ }
1337
1690
  if (Array.isArray(value)) {
1338
1691
  const next = value.slice();
1339
1692
  state.seen.set(value, next);
@@ -1352,21 +1705,29 @@ function enterGuard(value, state) {
1352
1705
  return new Frame(SET, value, next, [...value], null);
1353
1706
  }
1354
1707
  const prototype = Object.getPrototypeOf(value);
1355
- if (prototype !== Object.prototype && prototype !== null) {
1708
+ if (prototype !== Object.prototype && prototype !== null && !(value instanceof Error)) {
1356
1709
  state.seen.set(value, value);
1357
1710
  return value;
1358
1711
  }
1359
1712
  const descriptors = Object.getOwnPropertyDescriptors(value);
1713
+ for (const key of Object.keys(descriptors)) {
1714
+ descriptors[key].configurable = true;
1715
+ if ("value" in descriptors[key]) descriptors[key].writable = true;
1716
+ }
1360
1717
  const next = Object.create(prototype, descriptors);
1361
1718
  state.seen.set(value, next);
1362
- return new Frame(OBJECT, value, next, Object.keys(descriptors), descriptors);
1719
+ const children = !(value instanceof Error) ? Object.keys(value) : Object.getOwnPropertyNames(value).filter(key => {
1720
+ const descriptor = descriptors[key];
1721
+ return descriptor.enumerable || "value" in descriptor;
1722
+ });
1723
+ return new Frame(OBJECT, value, next, children, descriptors);
1363
1724
  }
1364
1725
  function keepGuarded(value, next, changed, state) {
1365
1726
  if (changed || state.cyclic.has(value)) return next;
1366
1727
  state.seen.set(value, value);
1367
1728
  return value;
1368
1729
  }
1369
- function serializeResponseStream(value, codecOptions, signal) {
1730
+ function serializeResponseStream(value, codecOptions, signal, scope) {
1370
1731
  let closed = false;
1371
1732
  let streamController = null;
1372
1733
  let demandWaiters = null;
@@ -1385,11 +1746,13 @@ function serializeResponseStream(value, codecOptions, signal) {
1385
1746
  if (closed) close();else sourceClosers.add(close);
1386
1747
  }
1387
1748
  };
1388
- value = guardFailures(value, {
1749
+ const guardState = {
1389
1750
  seen: new WeakMap(),
1390
1751
  cyclic: new WeakSet(),
1391
- gate
1392
- });
1752
+ gate,
1753
+ scope
1754
+ };
1755
+ value = guardOperation(guardState, () => guardFailures(value, guardState));
1393
1756
  let cancelSerialize = null;
1394
1757
  let onAbort = null;
1395
1758
  const finishSource = () => {
@@ -1470,14 +1833,14 @@ function serializeResponseStream(value, codecOptions, signal) {
1470
1833
  }
1471
1834
  });
1472
1835
  }
1473
- function serializedResponse(value, headers, codec, signal) {
1836
+ function serializedResponse(value, headers, codec, signal, scope) {
1474
1837
  headers.set(BODY_FORMAT_HEADER, BodyFormat.Serialized);
1475
1838
  headers.set("Content-Type", "text/plain");
1476
- return new Response(serializeResponseStream(value, codec, signal), {
1839
+ return new Response(serializeResponseStream(value, codec, signal, scope), {
1477
1840
  headers
1478
1841
  });
1479
1842
  }
1480
- function encodeResult(value, headers, status, codec, signal) {
1843
+ function encodeResult(value, headers, status, codec, signal, scope) {
1481
1844
  if (NULL_BODY_STATUSES.has(status)) {
1482
1845
  if (value === undefined || value === null) {
1483
1846
  headers.set(BODY_FORMAT_HEADER, BodyFormat.Void);
@@ -1488,7 +1851,7 @@ function encodeResult(value, headers, status, codec, signal) {
1488
1851
  }
1489
1852
  const error = new Error(`Server function answered status ${status}, which forbids a response body, with a value. ` + `Return respond(undefined, { status: ${status} }) for a bodiless answer, or drop the ` + `status to send the value.`);
1490
1853
  headers.set(ERROR_HEADER, encodeErrorHeaderValue(error.message));
1491
- return encodeResult(error, headers, 500, codec, signal);
1854
+ return encodeResult(error, headers, 500, codec, signal, scope);
1492
1855
  }
1493
1856
  const direct = getHeadersAndBody(value);
1494
1857
  if (direct) {
@@ -1508,10 +1871,12 @@ function encodeResult(value, headers, status, codec, signal) {
1508
1871
  });
1509
1872
  }
1510
1873
  try {
1511
- if (isJSONSafe(value)) {
1874
+ const jsonSafe = scope ? scope(() => isJSONSafe(value)) : isJSONSafe(value);
1875
+ if (jsonSafe) {
1512
1876
  headers.set(BODY_FORMAT_HEADER, BodyFormat.Json);
1513
1877
  headers.set("Content-Type", "application/json");
1514
- return new Response(JSON.stringify(value), {
1878
+ const body = scope ? scope(() => JSON.stringify(value)) : JSON.stringify(value);
1879
+ return new Response(body, {
1515
1880
  status,
1516
1881
  headers
1517
1882
  });
@@ -1519,7 +1884,7 @@ function encodeResult(value, headers, status, codec, signal) {
1519
1884
  } catch {
1520
1885
  }
1521
1886
  try {
1522
- const response = serializedResponse(value, headers, codec, signal);
1887
+ const response = serializedResponse(value, headers, codec, signal, scope);
1523
1888
  return status === 200 ? response : new Response(response.body, {
1524
1889
  status,
1525
1890
  headers
@@ -1617,13 +1982,22 @@ function forbiddenResponse() {
1617
1982
  }
1618
1983
  }));
1619
1984
  }
1985
+ function nativePromise(value) {
1986
+ if (value instanceof Promise) return value;
1987
+ try {
1988
+ if (Object.prototype.toString.call(value) === "[object Promise]") return Promise.prototype.then.call(value, value => value);
1989
+ } catch {}
1990
+ }
1620
1991
  async function handleServerFunctionRequest(request, options = {}) {
1621
- const codec = options.codec !== undefined ? options.codec : getServerFunctionsCodec();
1992
+ const codec = {
1993
+ ...(options.codec !== undefined ? options.codec : getServerFunctionsCodec())
1994
+ };
1995
+ codec.serializeErrorStacks ??= DEV;
1622
1996
  const url = new URL(request.url);
1623
1997
  const method = request.method;
1624
1998
  const address = resolveAddress(url);
1625
1999
  const functionId = address && address.id;
1626
- const declaredRead = (method === "GET" || method === "HEAD") && functionId !== null && METHODS.get(functionId) === "GET";
2000
+ const declaredRead = (method === "GET" || method === "HEAD") && functionId !== null && declaresRead(functionId);
1627
2001
  const csrf = options.csrf !== undefined ? options.csrf : config.csrf;
1628
2002
  const protectsRequest = csrf !== false && (!declaredRead || typeof csrf === "object" && csrf.protectDeclaredReads === true);
1629
2003
  let serverFunction;
@@ -1654,7 +2028,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1654
2028
  const response = new Response(DEV ? `Method not allowed for server function: ${functionId}` : null, {
1655
2029
  status: 405,
1656
2030
  headers: {
1657
- Allow: METHODS.get(functionId) === "GET" ? "POST, GET, HEAD" : "POST"
2031
+ Allow: declaresRead(functionId) ? "POST, GET, HEAD" : "POST"
1658
2032
  }
1659
2033
  });
1660
2034
  return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
@@ -1676,30 +2050,50 @@ async function handleServerFunctionRequest(request, options = {}) {
1676
2050
  });
1677
2051
  return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1678
2052
  }
1679
- if (!(declared > 0)) {
1680
- const bounded = await bufferBodyWithin(request, bodySizeLimit);
1681
- if (bounded === null) {
1682
- const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
1683
- status: 413
1684
- });
1685
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1686
- }
1687
- request = bounded;
2053
+ let bounded;
2054
+ try {
2055
+ bounded = await bufferBodyWithin(request, bodySizeLimit);
2056
+ } catch {
2057
+ const response = new Response(DEV ? "Malformed server function arguments" : null, {
2058
+ status: 400
2059
+ });
2060
+ return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2061
+ }
2062
+ if (bounded === null) {
2063
+ const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
2064
+ status: 413
2065
+ });
2066
+ return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1688
2067
  }
2068
+ request = bounded;
2069
+ }
2070
+ let event;
2071
+ try {
2072
+ event = options.createEvent ? options.createEvent(request) : {
2073
+ request,
2074
+ locals: {}
2075
+ };
2076
+ const promised = nativePromise(event);
2077
+ if (promised) event = await promised;
2078
+ } catch (error) {
2079
+ const safe = sanitizeServerError(error);
2080
+ const message = safe instanceof Error ? safe.message : String(safe);
2081
+ const headers = new Headers();
2082
+ headers.set(ERROR_HEADER, boundedErrorHeaderValue(message));
2083
+ const response = scripted ? encodeResult(safe, headers, 500, codec, request.signal) : new Response(DEV ? message : null, {
2084
+ status: 500
2085
+ });
2086
+ return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1689
2087
  }
1690
- let event = options.createEvent ? options.createEvent(request) : {
1691
- request,
1692
- locals: {}
1693
- };
1694
- if (typeof event?.then === "function") event = await event;
1695
2088
  const refuseCommitted = raw => {
1696
2089
  const response = commitEventResponse(raw, event);
1697
2090
  return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1698
2091
  };
1699
2092
  const provide = options.provideEvent || provideEvent;
2093
+ const scope = run => provide(event, run);
1700
2094
  const flightHook = options.collectFlightData !== undefined ? options.collectFlightData : config.collectFlightData;
1701
2095
  const transformResult = options.transformResult !== undefined ? options.transformResult : config.transformResult;
1702
- const wrapInvocation = options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation;
2096
+ const wrapInvocation = resolveWrapInvocation(options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation);
1703
2097
  const transformFlightResult = options.transformFlightResult !== undefined ? options.transformFlightResult : config.transformFlightResult;
1704
2098
  let handleNoJS = options.handleNoJS !== undefined ? options.handleNoJS : config.handleNoJS;
1705
2099
  if (handleNoJS === undefined && !scripted && isFormPost(request)) {
@@ -1714,7 +2108,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1714
2108
  }
1715
2109
  }
1716
2110
  const flightHeader = scripted && method === "POST" ? request.headers.get(SINGLE_FLIGHT_HEADER) : null;
1717
- const flightHooks = flightHeader ? flightHeader.split(",").flatMap(source => {
2111
+ const flightHooks = flightHeader ? [...new Set(flightHeader.split(","))].flatMap(source => {
1718
2112
  const hook = source === "true" ? flightHook : flightSources.get(source);
1719
2113
  return hook ? [[source, hook]] : [];
1720
2114
  }) : [];
@@ -1722,8 +2116,9 @@ async function handleServerFunctionRequest(request, options = {}) {
1722
2116
  let parsed;
1723
2117
  try {
1724
2118
  parsed = await parseArguments(request, url, scripted, codec);
1725
- } catch {
1726
- const response = new Response(DEV ? "Malformed server function arguments" : null, {
2119
+ } catch (error) {
2120
+ const skewed = error !== null && typeof error === "object" && error[FORMAT_SKEW] === true;
2121
+ const response = new Response(DEV ? skewed ? error.message : "Malformed server function arguments" : null, {
1727
2122
  status: 400
1728
2123
  });
1729
2124
  return refuseCommitted(response);
@@ -1747,7 +2142,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1747
2142
  const headers = new Headers();
1748
2143
  const dispatch = async () => {
1749
2144
  try {
1750
- let result = await provide(event, async () => {
2145
+ const invokeOnce = async () => {
1751
2146
  INVOCATIONS.set(event, {
1752
2147
  id: functionId
1753
2148
  });
@@ -1759,7 +2154,8 @@ async function handleServerFunctionRequest(request, options = {}) {
1759
2154
  request,
1760
2155
  direct: false
1761
2156
  }) : run();
1762
- });
2157
+ };
2158
+ let result = await provideEventOnce(provide, event, invokeOnce);
1763
2159
  if (transformResult) {
1764
2160
  result = await transformResult(event, result, flightContext);
1765
2161
  }
@@ -1811,12 +2207,14 @@ async function handleServerFunctionRequest(request, options = {}) {
1811
2207
  if (result instanceof Response && result.headers.has("X-Content-Raw")) return result;
1812
2208
  }
1813
2209
  if (!scripted) {
1814
- if (handleNoJS) return handleNoJS(result ?? metadata, request, parsed);
2210
+ if (handleNoJS) {
2211
+ return handleNoJS(result == null && metadata !== undefined ? metadata : result, request, parsed);
2212
+ }
1815
2213
  if (result instanceof Response) return result;
1816
- return encodeResult(result, headers, status, codec, request.signal);
2214
+ return encodeResult(result, headers, status, codec, request.signal, scope);
1817
2215
  }
1818
2216
  if (status === 304) warnScripted304(functionId);
1819
- return encodeResult(result, headers, status, codec, request.signal);
2217
+ return encodeResult(result, headers, status, codec, request.signal, scope);
1820
2218
  } catch (x) {
1821
2219
  const respondThrown = value => {
1822
2220
  const safe = sanitizeServerError(value);
@@ -1829,19 +2227,19 @@ async function handleServerFunctionRequest(request, options = {}) {
1829
2227
  }
1830
2228
  const error = safe instanceof Error ? safe.message : typeof safe === "string" ? safe : "true";
1831
2229
  headers.set(ERROR_HEADER, boundedErrorHeaderValue(error));
1832
- return encodeResult(safe, headers, 500, codec, request.signal);
2230
+ return encodeResult(safe, headers, 500, codec, request.signal, scope);
1833
2231
  };
1834
- if (x instanceof Response || isResponseEnvelope(x)) {
1835
- if (transformResult) {
1836
- try {
1837
- x = await transformResult(event, x, {
1838
- ...flightContext,
1839
- thrown: true
1840
- });
1841
- } catch (hookError) {
1842
- return respondThrown(hookError);
1843
- }
2232
+ if (transformResult) {
2233
+ try {
2234
+ x = await transformResult(event, x, {
2235
+ ...flightContext,
2236
+ thrown: true
2237
+ });
2238
+ } catch (hookError) {
2239
+ return respondThrown(hookError);
1844
2240
  }
2241
+ }
2242
+ if (x instanceof Response || isResponseEnvelope(x)) {
1845
2243
  let status = 200;
1846
2244
  let metadata;
1847
2245
  if (isResponseEnvelope(x)) {
@@ -1893,7 +2291,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1893
2291
  if (x instanceof Response) return x;
1894
2292
  }
1895
2293
  if (scripted && status === 304) warnScripted304(functionId);
1896
- return encodeResult(x, headers, status, codec, request.signal);
2294
+ return encodeResult(x, headers, status, codec, request.signal, scope);
1897
2295
  }
1898
2296
  return respondThrown(x);
1899
2297
  }