@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]);
@@ -257,7 +267,7 @@ function isJSONSafe(value) {
257
267
  const t = typeof v;
258
268
  if (t === "string" || t === "boolean") continue;
259
269
  if (t === "number") {
260
- if (!Number.isFinite(v)) return false;
270
+ if (!Number.isFinite(v) || Object.is(v, -0)) return false;
261
271
  continue;
262
272
  }
263
273
  if (t !== "object") return false;
@@ -343,31 +353,30 @@ function getHeadersAndBody(body) {
343
353
  async function extractBody(source, codecOptions) {
344
354
  const contentType = source.headers.get("content-type");
345
355
  const format = source.headers.get(BODY_FORMAT_HEADER);
346
- const clone = source.clone();
347
356
  switch (true) {
348
357
  case format === BodyFormat.Serialized:
349
- return await deserializeStream(clone, codecOptions);
358
+ return await deserializeStream(source, codecOptions);
350
359
  case format === BodyFormat.Json:
351
- return JSON.parse(await clone.text());
360
+ return JSON.parse(await source.text());
352
361
  case format === BodyFormat.String:
353
- return await clone.text();
362
+ return await source.text();
354
363
  case format === BodyFormat.File:
355
364
  {
356
- const formData = await clone.formData();
365
+ const formData = await source.formData();
357
366
  return formData.get(FILE_FORM_KEY);
358
367
  }
359
368
  case format === BodyFormat.FormData:
360
369
  case contentType && contentType.startsWith("multipart/form-data"):
361
- return await clone.formData();
370
+ return await source.formData();
362
371
  case format === BodyFormat.URLSearchParams:
363
372
  case contentType && contentType.startsWith("application/x-www-form-urlencoded"):
364
- return new URLSearchParams(await clone.text());
373
+ return new URLSearchParams(await source.text());
365
374
  case format === BodyFormat.Blob:
366
- return await clone.blob();
375
+ return await source.blob();
367
376
  case format === BodyFormat.ArrayBuffer:
368
- return await clone.arrayBuffer();
377
+ return await source.arrayBuffer();
369
378
  case format === BodyFormat.Uint8Array:
370
- return new Uint8Array(await clone.arrayBuffer());
379
+ return new Uint8Array(await source.arrayBuffer());
371
380
  }
372
381
  return undefined;
373
382
  }
@@ -503,7 +512,7 @@ async function deserializeString(text, codecOptions) {
503
512
  }
504
513
  async function decodeResponse(response, codecOptions) {
505
514
  if (!response.body) return undefined;
506
- return await extractBody(response, codecOptions === undefined ? codecConfig.codec : codecOptions);
515
+ return await extractBody(response.clone(), codecOptions === undefined ? codecConfig.codec : codecOptions);
507
516
  }
508
517
  async function decodeResponsePayload(response, codecOptions) {
509
518
  const decoded = await decodeResponse(response, codecOptions);
@@ -554,7 +563,8 @@ function copyInitHeaders(init) {
554
563
  for (const cookie of init.getSetCookie()) headers.append("Set-Cookie", cookie);
555
564
  return headers;
556
565
  }
557
- 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()));
566
+ const STUB_GAP_FILL_EXCLUDED = /*#__PURE__*/new Set([ERROR_HEADER, BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, REVALIDATE_HEADER, REDIRECT_HEADER, "Location",
567
+ ...COMPOSED_BODY_FRAMING].map(header => header.toLowerCase()));
558
568
  function fillsStubGap(key, headers, response) {
559
569
  if (key === "set-cookie" || STUB_GAP_FILL_EXCLUDED.has(key)) return false;
560
570
  if (response.body === null && (key === "content-type" || key === "content-length")) return false;
@@ -582,6 +592,68 @@ function commitEventResponse(response, event = getRequestEvent()) {
582
592
  });
583
593
  }
584
594
 
595
+ let configuredSecret;
596
+ function setFlashSecret(secret) {
597
+ configuredSecret = secret;
598
+ }
599
+ function resolveSecret() {
600
+ return configuredSecret !== undefined ? configuredSecret : globalThis.__SOLID_SECRET__;
601
+ }
602
+ const FLASH_KEY_DOMAIN = "solid.flash.v1\0";
603
+ let cachedSecret;
604
+ let cachedKey;
605
+ function resolveFlashKey() {
606
+ const secret = resolveSecret();
607
+ if (typeof secret !== "string" || secret.length === 0) return null;
608
+ if (secret !== cachedSecret) {
609
+ cachedSecret = secret;
610
+ cachedKey = crypto.subtle.digest("SHA-256", new TextEncoder().encode(FLASH_KEY_DOMAIN + secret)).then(digest => crypto.subtle.importKey("raw", digest, {
611
+ name: "AES-GCM"
612
+ }, false, ["encrypt", "decrypt"]));
613
+ }
614
+ return cachedKey;
615
+ }
616
+ let warnedMissingKey = false;
617
+ function warnMissingKey() {
618
+ if (warnedMissingKey) return;
619
+ warnedMissingKey = true;
620
+ console.warn("[solid] A no-JS form outcome was not flashed: the flash cookie is encrypted and no key " + "is configured. Set configureServerFunctionsServer({ secret }) — or build with the Solid " + "bundler plugin, which provides a per-deployment key automatically. The submission " + "committed and the redirect was served; only the outcome echo was withheld.");
621
+ }
622
+ const FLASH_FORMAT_VERSION = "1.";
623
+ const IV_BYTES = 12;
624
+ const GCM_TAG_BYTES = 16;
625
+ function toBase64url(bytes) {
626
+ let binary = "";
627
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
628
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
629
+ }
630
+ function fromBase64url(text) {
631
+ const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/"));
632
+ const bytes = new Uint8Array(binary.length);
633
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
634
+ return bytes;
635
+ }
636
+ async function encryptFlashValue(key, json) {
637
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
638
+ const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
639
+ name: "AES-GCM",
640
+ iv
641
+ }, key, new TextEncoder().encode(json)));
642
+ const packed = new Uint8Array(IV_BYTES + ciphertext.length);
643
+ packed.set(iv);
644
+ packed.set(ciphertext, IV_BYTES);
645
+ return FLASH_FORMAT_VERSION + toBase64url(packed);
646
+ }
647
+ async function decryptFlashValue(key, value) {
648
+ if (!value.startsWith(FLASH_FORMAT_VERSION)) return;
649
+ const packed = fromBase64url(value.slice(FLASH_FORMAT_VERSION.length));
650
+ if (packed.length <= IV_BYTES + GCM_TAG_BYTES) return;
651
+ const plain = await crypto.subtle.decrypt({
652
+ name: "AES-GCM",
653
+ iv: packed.subarray(0, IV_BYTES)
654
+ }, key, packed.subarray(IV_BYTES));
655
+ return new TextDecoder().decode(plain);
656
+ }
585
657
  function encodeInputValue(value) {
586
658
  if (value instanceof FormData) return {
587
659
  $f: [...value.entries()].filter(([, v]) => typeof v === "string")
@@ -602,7 +674,12 @@ function decodeInputValue(value) {
602
674
  }
603
675
  return value;
604
676
  }
605
- function encodeFlashCookie(url, result, input, thrown) {
677
+ async function encodeFlashCookie(url, result, input, thrown) {
678
+ const key = resolveFlashKey();
679
+ if (!key) {
680
+ warnMissingKey();
681
+ return null;
682
+ }
606
683
  const isError = result instanceof Error;
607
684
  const payload = {
608
685
  url,
@@ -611,7 +688,7 @@ function encodeFlashCookie(url, result, input, thrown) {
611
688
  thrown: !!thrown,
612
689
  input: input.map(encodeInputValue)
613
690
  };
614
- if (fitsCookie(payload)) return flashCookie(payload);
691
+ if (fitsCookie(payload)) return flashCookie(payload, await key);
615
692
  payload.truncated = true;
616
693
  payload.input = [];
617
694
  if (!fitsCookie(payload)) {
@@ -628,24 +705,35 @@ function encodeFlashCookie(url, result, input, thrown) {
628
705
  payload.result = true;
629
706
  }
630
707
  }
631
- return flashCookie(payload);
708
+ if (!fitsCookie(payload)) return null;
709
+ return flashCookie(payload, await key);
632
710
  }
633
- function flashCookie(payload) {
634
- return serializeCookie(FLASH_COOKIE, JSON.stringify(payload), {
711
+ const FLASH_MAX_AGE_SECONDS = 60;
712
+ async function flashCookie(payload, key) {
713
+ return serializeCookie(FLASH_COOKIE, await encryptFlashValue(key, JSON.stringify(payload)), {
635
714
  secure: true,
636
- httpOnly: true
715
+ httpOnly: true,
716
+ sameSite: "lax",
717
+ maxAge: FLASH_MAX_AGE_SECONDS
637
718
  });
638
719
  }
639
720
  const COOKIE_PAIR_BUDGET = 4000;
640
721
  function fitsCookie(payload) {
641
- return FLASH_COOKIE.length + 1 + encodeURIComponent(JSON.stringify(payload)).length <= COOKIE_PAIR_BUDGET;
722
+ const plaintextBytes = new TextEncoder().encode(JSON.stringify(payload)).length;
723
+ const packedBytes = IV_BYTES + plaintextBytes + GCM_TAG_BYTES;
724
+ const valueLength = FLASH_FORMAT_VERSION.length + Math.ceil(packedBytes * 4 / 3);
725
+ return FLASH_COOKIE.length + 1 + valueLength <= COOKIE_PAIR_BUDGET;
642
726
  }
643
- function decodeFlashCookie(cookieHeader) {
727
+ async function decodeFlashCookie(cookieHeader) {
644
728
  const match = parseCookieHeader(cookieHeader)[FLASH_COOKIE];
645
729
  if (!match) return;
646
730
  try {
647
- const payload = JSON.parse(match);
648
- if (!payload || !payload.result) return;
731
+ const key = resolveFlashKey();
732
+ if (!key) return;
733
+ const json = await decryptFlashValue(await key, match);
734
+ if (json === undefined) return;
735
+ const payload = JSON.parse(json);
736
+ if (!payload || typeof payload !== "object" || !("result" in payload)) return;
649
737
  const result = payload.error ? new Error(payload.result) : payload.result;
650
738
  const submission = {
651
739
  input: Array.isArray(payload.input) ? payload.input.map(decodeInputValue) : [],
@@ -685,7 +773,8 @@ function configureServerFunctionsServer({
685
773
  csrf,
686
774
  codec,
687
775
  bodySizeLimit,
688
- maxArguments
776
+ maxArguments,
777
+ secret
689
778
  } = {}) {
690
779
  if (provideEvent !== undefined) config.provideEvent = provideEvent;
691
780
  if (wrapInvocation !== undefined) config.wrapInvocation = wrapInvocation;
@@ -699,6 +788,7 @@ function configureServerFunctionsServer({
699
788
  if (codec !== undefined) configureServerFunctionsCodec(codec);
700
789
  if (bodySizeLimit !== undefined) config.bodySizeLimit = bodySizeLimit;
701
790
  if (maxArguments !== undefined) config.maxArguments = maxArguments;
791
+ if (secret !== undefined) setFlashSecret(secret);
702
792
  }
703
793
  const flightSources = new Map();
704
794
  function registerFlightDataSource(source, hook) {
@@ -708,14 +798,198 @@ function registerFlightDataSource(source, hook) {
708
798
  if (flightSources.get(source) === hook) flightSources.delete(source);
709
799
  };
710
800
  }
801
+ function resolveWrapInvocation(hook) {
802
+ if (hook === undefined || typeof hook === "function") return hook;
803
+ 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.`);
804
+ }
711
805
  function provideEvent(event, fn) {
712
806
  if (config.provideEvent) return config.provideEvent(event, fn);
713
807
  const ctx = globalThis[RequestContext];
714
808
  if (ctx) return ctx.run(event, fn);
715
809
  throw new Error("No request event provider. Configure one with configureServerFunctionsServer({ provideEvent }).");
716
810
  }
811
+ 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.";
812
+ 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.";
813
+ function provideEventOnce(provide, event, run) {
814
+ let invocations = 0;
815
+ const settle = () => {
816
+ if (invocations !== 1) throw new Error(invocations === 0 ? PROVIDE_EVENT_NEVER : PROVIDE_EVENT_TWICE);
817
+ };
818
+ const result = provide(event, () => {
819
+ if (++invocations > 1) throw new Error(PROVIDE_EVENT_TWICE);
820
+ return run();
821
+ });
822
+ const promised = nativePromise(result);
823
+ if (promised) {
824
+ return promised.then(value => {
825
+ settle();
826
+ return value;
827
+ });
828
+ }
829
+ settle();
830
+ return result;
831
+ }
832
+ function scopeDeferredResult(value, scope) {
833
+ const bound = bindDeferredBody(value, scope);
834
+ if (bound !== value || value === null || typeof value !== "object") return bound;
835
+ return scopeDeferredContents(value, scope);
836
+ }
837
+ class ScopeFrame {
838
+ constructor(value, next, keys, descriptors) {
839
+ this.value = value;
840
+ this.next = next;
841
+ this.keys = keys;
842
+ this.descriptors = descriptors;
843
+ this.i = 0;
844
+ this.changed = false;
845
+ }
846
+ }
847
+ function enterScopeCarrier(value, state) {
848
+ if (value === null || typeof value !== "object" && typeof value !== "function") return value;
849
+ if (state.seen.has(value)) {
850
+ state.cyclic.add(value);
851
+ return state.seen.get(value);
852
+ }
853
+ const bound = bindDeferredBody(value, state.scope);
854
+ if (bound !== value) {
855
+ state.seen.set(value, bound);
856
+ return bound;
857
+ }
858
+ if (typeof value !== "object") return value;
859
+ if (Array.isArray(value)) {
860
+ if (Object.isFrozen(value)) {
861
+ state.seen.set(value, value);
862
+ return value;
863
+ }
864
+ const next = value.slice();
865
+ state.seen.set(value, next);
866
+ return new ScopeFrame(value, next, null, null);
867
+ }
868
+ const prototype = Object.getPrototypeOf(value);
869
+ if (prototype !== Object.prototype && prototype !== null || Object.isFrozen(value)) {
870
+ state.seen.set(value, value);
871
+ return value;
872
+ }
873
+ const descriptors = Object.getOwnPropertyDescriptors(value);
874
+ const next = Object.create(prototype, descriptors);
875
+ state.seen.set(value, next);
876
+ return new ScopeFrame(value, next, Object.keys(value), descriptors);
877
+ }
878
+ function scopeDeferredContents(root, scope) {
879
+ const state = {
880
+ seen: new Map(),
881
+ cyclic: new Set(),
882
+ scope
883
+ };
884
+ const entered = enterScopeCarrier(root, state);
885
+ if (!(entered instanceof ScopeFrame)) return entered;
886
+ const stack = [entered];
887
+ let delivered = NOTHING;
888
+ for (;;) {
889
+ const top = stack[stack.length - 1];
890
+ const length = top.keys ? top.keys.length : top.value.length;
891
+ let pushed = null;
892
+ while (top.i < length) {
893
+ const i = top.i;
894
+ let original;
895
+ let writable = true;
896
+ if (top.keys) {
897
+ const descriptor = top.descriptors[top.keys[i]];
898
+ writable = "value" in descriptor && descriptor.writable === true;
899
+ original = writable ? descriptor.value : undefined;
900
+ } else {
901
+ original = top.value[i];
902
+ }
903
+ if (!writable) {
904
+ top.i++;
905
+ continue;
906
+ }
907
+ let bound;
908
+ if (delivered !== NOTHING) {
909
+ bound = delivered;
910
+ delivered = NOTHING;
911
+ } else {
912
+ bound = enterScopeCarrier(original, state);
913
+ if (bound instanceof ScopeFrame) {
914
+ pushed = bound;
915
+ break;
916
+ }
917
+ }
918
+ if (bound !== original) {
919
+ if (top.keys) top.next[top.keys[i]] = bound;else top.next[i] = bound;
920
+ top.changed = true;
921
+ }
922
+ top.i++;
923
+ }
924
+ if (pushed !== null) {
925
+ stack.push(pushed);
926
+ continue;
927
+ }
928
+ stack.pop();
929
+ let out;
930
+ if (top.changed || state.cyclic.has(top.value)) {
931
+ out = top.next;
932
+ } else {
933
+ state.seen.set(top.value, top.value);
934
+ out = top.value;
935
+ }
936
+ if (stack.length === 0) return out;
937
+ delivered = out;
938
+ }
939
+ }
940
+ function bindDeferredBody(value, scope) {
941
+ if (value === null || typeof value !== "object" && typeof value !== "function") return value;
942
+ const promised = scope(() => nativePromise(value));
943
+ if (promised) {
944
+ return promised.then(result => scope(() => scopeDeferredResult(result, scope)));
945
+ }
946
+ if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) {
947
+ let reader;
948
+ return new ReadableStream({
949
+ async pull(controller) {
950
+ try {
951
+ const step = await scope(() => {
952
+ if (!reader) reader = value.getReader();
953
+ return reader.read();
954
+ });
955
+ if (step.done) controller.close();else controller.enqueue(step.value);
956
+ } catch (error) {
957
+ controller.error(error);
958
+ }
959
+ },
960
+ cancel(reason) {
961
+ return scope(() => reader ? reader.cancel(reason) : value.cancel(reason));
962
+ }
963
+ }, {
964
+ highWaterMark: 0
965
+ });
966
+ }
967
+ const scopedIterator = symbol => ({
968
+ [symbol]() {
969
+ const iterator = scope(() => value[symbol]());
970
+ return new Proxy(iterator, {
971
+ get(target, property) {
972
+ const member = Reflect.get(target, property, target);
973
+ return typeof member === "function" && (property === "next" || property === "return" || property === "throw") ? (...args) => scope(() => member.apply(target, args)) : member;
974
+ }
975
+ });
976
+ }
977
+ });
978
+ if (typeof value[Symbol.asyncIterator] === "function") {
979
+ return scopedIterator(Symbol.asyncIterator);
980
+ }
981
+ if (typeof value[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value)) {
982
+ return scopedIterator(Symbol.iterator);
983
+ }
984
+ return value;
985
+ }
717
986
  const REGISTRATIONS = new Map();
718
987
  const METHODS = new Map();
988
+ const REFERENCE_BINDINGS = new WeakMap();
989
+ function declaresRead(id) {
990
+ const granted = METHODS.get(id);
991
+ return granted !== undefined && granted === REGISTRATIONS.get(id);
992
+ }
719
993
  const INVOCATIONS = new WeakMap();
720
994
  let rpcProvided = false;
721
995
  function provideRPC() {
@@ -811,40 +1085,72 @@ function createServerReference({
811
1085
  id
812
1086
  });
813
1087
  evt.serverOnly = true;
814
- const result = provideEvent(evt, () => {
1088
+ const scope = run => provideEvent(evt, run);
1089
+ const wrap = resolveWrapInvocation(config.wrapInvocation);
1090
+ let result = provideEventOnce(provideEvent, evt, () => {
815
1091
  const run = () => fn.apply(thisArg, args);
816
- return config.wrapInvocation ? config.wrapInvocation(run, {
1092
+ return wrap ? wrap(run, {
817
1093
  id,
818
1094
  args,
819
1095
  event: evt,
820
1096
  direct: true
821
1097
  }) : run();
822
1098
  });
1099
+ result = scopeDeferredResult(result, scope);
823
1100
  const transform = config.transformDirectResult;
824
1101
  if (transform && result && typeof result.then === "function") {
825
- return result.then(value => transform(value, {
1102
+ return result.then(value => scopeDeferredResult(transform(value, {
826
1103
  id,
827
1104
  args,
828
1105
  event: evt
829
- }));
1106
+ }), scope));
830
1107
  }
831
- return transform ? transform(result, {
1108
+ return transform ? scopeDeferredResult(transform(result, {
832
1109
  id,
833
1110
  args,
834
1111
  event: evt
835
- }) : result;
1112
+ }), scope) : result;
836
1113
  }
837
1114
  });
1115
+ REFERENCE_BINDINGS.set(proxy, fn);
838
1116
  return proxy;
839
1117
  }
840
1118
  function GET(fn) {
841
1119
  if (!isServerFunction(fn) || typeof fn.id !== "string") {
842
1120
  throw new Error("GET expects a server function reference");
843
1121
  }
844
- METHODS.set(fn.id, "GET");
845
- return withMeta(fn, {
1122
+ const id = fn.id;
1123
+ const binding = REFERENCE_BINDINGS.has(fn) ? REFERENCE_BINDINGS.get(fn) : REGISTRATIONS.get(id);
1124
+ const existing = METHODS.get(id);
1125
+ if (existing !== undefined && existing !== binding) {
1126
+ if (DEV) {
1127
+ 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.`);
1128
+ }
1129
+ METHODS.delete(id);
1130
+ return fn;
1131
+ }
1132
+ METHODS.set(id, binding);
1133
+ const reference = withMeta(fn, {
846
1134
  method: "GET"
847
1135
  });
1136
+ guardDeclaredMethod(getServerFunctionMetadata(reference), id);
1137
+ return reference;
1138
+ }
1139
+ function guardDeclaredMethod(metadata, id) {
1140
+ let declared = metadata.method;
1141
+ Object.defineProperty(metadata, "method", {
1142
+ configurable: true,
1143
+ enumerable: true,
1144
+ get: () => declared,
1145
+ set(next) {
1146
+ if (next === declared) return;
1147
+ if (DEV) {
1148
+ 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.`);
1149
+ }
1150
+ METHODS.delete(id);
1151
+ declared = next;
1152
+ }
1153
+ });
848
1154
  }
849
1155
  function live(fn) {
850
1156
  if (!isServerFunction(fn) || typeof fn.id !== "string") {
@@ -898,22 +1204,58 @@ function assertDecodeDepth(value) {
898
1204
  level = next;
899
1205
  }
900
1206
  }
1207
+ const UNSAFE_ARGUMENT_KEYS = ["__proto__", "constructor", "prototype"];
1208
+ function stripUnsafeArgumentKeys(value) {
1209
+ const stack = [value];
1210
+ const seen = new Set();
1211
+ while (stack.length) {
1212
+ const v = stack.pop();
1213
+ if (v === null || typeof v !== "object" || seen.has(v)) continue;
1214
+ seen.add(v);
1215
+ for (const key of UNSAFE_ARGUMENT_KEYS) {
1216
+ delete v[key];
1217
+ }
1218
+ for (const key of Object.keys(v)) stack.push(v[key]);
1219
+ if (v instanceof Map) {
1220
+ for (const [k, entry] of v) stack.push(k, entry);
1221
+ } else if (v instanceof Set) {
1222
+ for (const member of v) stack.push(member);
1223
+ }
1224
+ }
1225
+ return value;
1226
+ }
901
1227
  async function bufferBodyWithin(request, limit) {
902
- const reader = request.clone().body.getReader();
1228
+ const reader = request.body.getReader();
1229
+ const signal = request.signal;
903
1230
  const chunks = [];
904
1231
  let total = 0;
905
- for (;;) {
906
- const {
907
- done,
908
- value
909
- } = await reader.read();
910
- if (done) break;
911
- total += value.byteLength;
912
- if (total > limit) {
913
- reader.cancel().catch(() => {});
914
- return null;
1232
+ const onAbort = () => {
1233
+ reader.cancel(signal.reason).catch(() => {});
1234
+ };
1235
+ if (signal.aborted) onAbort();else signal.addEventListener("abort", onAbort, {
1236
+ once: true
1237
+ });
1238
+ try {
1239
+ for (;;) {
1240
+ const {
1241
+ done,
1242
+ value
1243
+ } = await reader.read();
1244
+ if (signal.aborted) throw signal.reason;
1245
+ if (done) break;
1246
+ total += value.byteLength;
1247
+ if (total > limit) {
1248
+ reader.cancel().catch(() => {});
1249
+ return null;
1250
+ }
1251
+ chunks.push(value);
915
1252
  }
916
- chunks.push(value);
1253
+ } catch (error) {
1254
+ reader.cancel(error).catch(() => {});
1255
+ throw error;
1256
+ } finally {
1257
+ signal.removeEventListener("abort", onAbort);
1258
+ reader.releaseLock();
917
1259
  }
918
1260
  const body = new Uint8Array(total);
919
1261
  let offset = 0;
@@ -925,6 +1267,13 @@ async function bufferBodyWithin(request, limit) {
925
1267
  body
926
1268
  });
927
1269
  }
1270
+ const KNOWN_BODY_FORMATS = new Set(Object.values(BodyFormat));
1271
+ const FORMAT_SKEW = Symbol("solid.serverFunction.formatSkew");
1272
+ function unknownFormatError(tag) {
1273
+ 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.");
1274
+ error[FORMAT_SKEW] = true;
1275
+ return error;
1276
+ }
928
1277
  async function parseArguments(request, url, scripted, codec) {
929
1278
  const parsed = [];
930
1279
  const bodyFormat = request.method === "POST" ? request.headers.get(BODY_FORMAT_HEADER) : null;
@@ -940,6 +1289,7 @@ async function parseArguments(request, url, scripted, codec) {
940
1289
  if (!Array.isArray(result)) {
941
1290
  throw new TypeError("Server function arguments must encode an array");
942
1291
  }
1292
+ stripUnsafeArgumentKeys(result);
943
1293
  for (const arg of result) {
944
1294
  parsed.push(arg);
945
1295
  }
@@ -947,15 +1297,22 @@ async function parseArguments(request, url, scripted, codec) {
947
1297
  parsed.push(url.searchParams);
948
1298
  }
949
1299
  if (request.method === "POST" && request.body !== null) {
950
- const decoded = await extractBody(request.clone(), codec);
1300
+ if (bodyFormat !== null && !KNOWN_BODY_FORMATS.has(bodyFormat)) {
1301
+ throw unknownFormatError(bodyFormat);
1302
+ }
1303
+ const body = request.clone();
1304
+ const decoded = await extractBody(body, codec);
951
1305
  if (bodyFormat === BodyFormat.Serialized || bodyFormat === BodyFormat.Json) {
952
1306
  if (bodyFormat === BodyFormat.Json) assertDecodeDepth(decoded);
953
1307
  if (!Array.isArray(decoded)) {
954
1308
  throw new TypeError("Server function arguments must encode an array");
955
1309
  }
956
- return decoded;
1310
+ return stripUnsafeArgumentKeys(decoded);
957
1311
  }
958
1312
  if (decoded === undefined) {
1313
+ if (bodyFormat === null && (await body.arrayBuffer()).byteLength === 0) {
1314
+ return parsed;
1315
+ }
959
1316
  throw new TypeError("Server function body carries no usable encoding");
960
1317
  }
961
1318
  parsed.push(decoded);
@@ -983,13 +1340,14 @@ async function foldFlightData(hooks, event, headers, outcome, context = {}) {
983
1340
  data
984
1341
  }, context);
985
1342
  if (transformed !== undefined) {
986
- for (const cookie of headers.getSetCookie()) transformed.headers.append("Set-Cookie", cookie);
1343
+ const owned = ownResponse(transformed);
1344
+ for (const cookie of headers.getSetCookie()) owned.headers.append("Set-Cookie", cookie);
987
1345
  headers.forEach((value, key) => {
988
- if (key !== "set-cookie" && !transformed.headers.has(key)) {
989
- transformed.headers.set(key, value);
1346
+ if (key !== "set-cookie" && !owned.headers.has(key)) {
1347
+ owned.headers.set(key, value);
990
1348
  }
991
1349
  });
992
- return transformed;
1350
+ return owned;
993
1351
  }
994
1352
  }
995
1353
  return outcome.value === undefined ? {
@@ -1056,7 +1414,7 @@ function foldSetCookies(headers, setCookies) {
1056
1414
  }
1057
1415
  function mergeResponseHeaders(target, source) {
1058
1416
  source.forEach((value, key) => {
1059
- if (key !== "set-cookie") target.append(key, value);
1417
+ if (key !== "set-cookie" && !COMPOSED_BODY_FRAMING.has(key)) target.append(key, value);
1060
1418
  });
1061
1419
  if (source.getSetCookie) {
1062
1420
  for (const cookie of source.getSetCookie()) target.append("Set-Cookie", cookie);
@@ -1073,10 +1431,6 @@ function maskRedirect(headers, response, requestUrl) {
1073
1431
  headers.delete("Location");
1074
1432
  }
1075
1433
  const BOUNDED_COMPOSED_HEADERS = [REDIRECT_HEADER, "Location", REVALIDATE_HEADER];
1076
- function refusedTargetScheme(target) {
1077
- const match = /^[a-zA-Z][a-zA-Z0-9+.-]*:/.exec(target);
1078
- return match !== null && !/^https?:$/i.test(match[0]);
1079
- }
1080
1434
  function enforceComposedHeaderInvariants(response) {
1081
1435
  for (const name of BOUNDED_COMPOSED_HEADERS) {
1082
1436
  const value = response.headers.get(name);
@@ -1086,7 +1440,7 @@ function enforceComposedHeaderInvariants(response) {
1086
1440
  }
1087
1441
  if (name === REVALIDATE_HEADER) continue;
1088
1442
  const target = name === REDIRECT_HEADER ? value.slice(value.indexOf(" ") + 1) : value;
1089
- if (refusedTargetScheme(target)) {
1443
+ if (!isHttpNavigationTarget(target)) {
1090
1444
  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);
1091
1445
  }
1092
1446
  }
@@ -1114,7 +1468,7 @@ function warnScripted304(functionId) {
1114
1468
  function createNoJSHandler({
1115
1469
  base = ""
1116
1470
  } = {}) {
1117
- return function handleNoJS(result, request, args, thrown) {
1471
+ return async function handleNoJS(result, request, args, thrown) {
1118
1472
  const url = new URL(request.url);
1119
1473
  let back = new URL(base || "/", url.origin).toString();
1120
1474
  try {
@@ -1139,8 +1493,9 @@ function createNoJSHandler({
1139
1493
  Location: back
1140
1494
  });
1141
1495
  }
1142
- if (result && !(result instanceof Response)) {
1143
- headers.append("Set-Cookie", encodeFlashCookie(url.pathname + url.search, result, args, thrown));
1496
+ if (result !== undefined && !(result instanceof Response)) {
1497
+ const flash = await encodeFlashCookie(url.pathname, result, args, thrown);
1498
+ if (flash !== null) headers.append("Set-Cookie", flash);
1144
1499
  }
1145
1500
  return new Response(null, {
1146
1501
  status,
@@ -1214,14 +1569,11 @@ function guardFailures(value, state) {
1214
1569
  top.next.add(guarded);
1215
1570
  if (guarded !== original) top.changed = true;
1216
1571
  } else if (guarded !== original || top.accessorRead === i) {
1217
- Object.defineProperty(top.next, items[i], top.accessorRead === i ? {
1218
- enumerable: true,
1219
- configurable: true,
1572
+ Object.defineProperty(top.next, items[i], {
1573
+ value: guarded,
1220
1574
  writable: true,
1221
- value: guarded
1222
- } : {
1223
- ...top.descriptors[items[i]],
1224
- value: guarded
1575
+ configurable: true,
1576
+ enumerable: top.descriptors[items[i]].enumerable
1225
1577
  });
1226
1578
  top.changed = true;
1227
1579
  }
@@ -1256,6 +1608,9 @@ class Frame {
1256
1608
  this.pendingKey = undefined;
1257
1609
  }
1258
1610
  }
1611
+ function guardOperation(state, run) {
1612
+ return state.scope ? state.scope(run) : run();
1613
+ }
1259
1614
  function enterGuard(value, state) {
1260
1615
  if (value === null || typeof value !== "object") return value;
1261
1616
  if (state.seen.has(value)) {
@@ -1270,7 +1625,7 @@ function enterGuard(value, state) {
1270
1625
  if (finished) return;
1271
1626
  finished = true;
1272
1627
  try {
1273
- const cancelled = reader ? reader.cancel() : value.cancel();
1628
+ const cancelled = guardOperation(state, () => reader ? reader.cancel() : value.cancel());
1274
1629
  if (cancelled && typeof cancelled.then === "function") cancelled.then(undefined, () => {});
1275
1630
  } catch {}
1276
1631
  };
@@ -1282,19 +1637,19 @@ function enterGuard(value, state) {
1282
1637
  controller.close();
1283
1638
  return;
1284
1639
  }
1285
- if (!reader) reader = value.getReader();
1640
+ if (!reader) reader = guardOperation(state, () => value.getReader());
1286
1641
  const {
1287
1642
  done,
1288
1643
  value: chunk
1289
- } = await reader.read();
1290
- done ? controller.close() : controller.enqueue(guardFailures(chunk, state));
1644
+ } = await guardOperation(state, () => reader.read());
1645
+ done ? controller.close() : controller.enqueue(guardOperation(state, () => guardFailures(chunk, state)));
1291
1646
  } catch (error) {
1292
- controller.error(sanitizeServerError(error));
1647
+ controller.error(guardOperation(state, () => sanitizeServerError(error)));
1293
1648
  }
1294
1649
  },
1295
1650
  cancel(reason) {
1296
1651
  finished = true;
1297
- return reader ? reader.cancel(reason) : value.cancel(reason);
1652
+ return guardOperation(state, () => reader ? reader.cancel(reason) : value.cancel(reason));
1298
1653
  }
1299
1654
  });
1300
1655
  if (gate) gate.onOpen(close);
@@ -1302,9 +1657,10 @@ function enterGuard(value, state) {
1302
1657
  return guardedStream;
1303
1658
  }
1304
1659
  if (typeof value.then === "function") {
1305
- const guardedPromise = Promise.resolve(value).then(resolved => guardFailures(resolved, state), error => {
1306
- throw sanitizeServerError(error);
1660
+ const guardedPromise = Promise.resolve(value).then(resolved => guardOperation(state, () => guardFailures(resolved, state)), error => {
1661
+ throw guardOperation(state, () => sanitizeServerError(error));
1307
1662
  });
1663
+ guardedPromise.catch(() => {});
1308
1664
  state.seen.set(value, guardedPromise);
1309
1665
  return guardedPromise;
1310
1666
  }
@@ -1313,13 +1669,13 @@ function enterGuard(value, state) {
1313
1669
  const gate = state.gate;
1314
1670
  const guardedIterable = {
1315
1671
  [Symbol.asyncIterator]() {
1316
- const iterator = source[Symbol.asyncIterator]();
1672
+ const iterator = guardOperation(state, () => source[Symbol.asyncIterator]());
1317
1673
  let finished = false;
1318
1674
  const close = () => {
1319
1675
  if (finished) return;
1320
1676
  finished = true;
1321
1677
  try {
1322
- const returned = iterator.return && iterator.return();
1678
+ const returned = iterator.return && guardOperation(state, () => iterator.return());
1323
1679
  if (returned && typeof returned.then === "function") returned.then(undefined, () => {});
1324
1680
  } catch {}
1325
1681
  };
@@ -1327,17 +1683,17 @@ function enterGuard(value, state) {
1327
1683
  const step = () => finished ? Promise.resolve({
1328
1684
  done: true,
1329
1685
  value: undefined
1330
- }) : iterator.next().then(step => {
1686
+ }) : guardOperation(state, () => iterator.next()).then(step => {
1331
1687
  if (step.done) {
1332
1688
  finished = true;
1333
1689
  return step;
1334
1690
  }
1335
1691
  return {
1336
1692
  done: false,
1337
- value: guardFailures(step.value, state)
1693
+ value: guardOperation(state, () => guardFailures(step.value, state))
1338
1694
  };
1339
1695
  }, error => {
1340
- throw sanitizeServerError(error);
1696
+ throw guardOperation(state, () => sanitizeServerError(error));
1341
1697
  });
1342
1698
  return {
1343
1699
  next: () => finished || !gate || gate.wantsMore() ? step() : gate.awaitDemand().then(step),
@@ -1354,6 +1710,11 @@ function enterGuard(value, state) {
1354
1710
  state.seen.set(value, guardedIterable);
1355
1711
  return guardedIterable;
1356
1712
  }
1713
+ if (state.scope && typeof value[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value)) {
1714
+ const scopedIterable = scopeDeferredResult(value, state.scope);
1715
+ state.seen.set(value, scopedIterable);
1716
+ return scopedIterable;
1717
+ }
1357
1718
  if (Array.isArray(value)) {
1358
1719
  const next = value.slice();
1359
1720
  state.seen.set(value, next);
@@ -1372,21 +1733,29 @@ function enterGuard(value, state) {
1372
1733
  return new Frame(SET, value, next, [...value], null);
1373
1734
  }
1374
1735
  const prototype = Object.getPrototypeOf(value);
1375
- if (prototype !== Object.prototype && prototype !== null) {
1736
+ if (prototype !== Object.prototype && prototype !== null && !(value instanceof Error)) {
1376
1737
  state.seen.set(value, value);
1377
1738
  return value;
1378
1739
  }
1379
1740
  const descriptors = Object.getOwnPropertyDescriptors(value);
1741
+ for (const key of Object.keys(descriptors)) {
1742
+ descriptors[key].configurable = true;
1743
+ if ("value" in descriptors[key]) descriptors[key].writable = true;
1744
+ }
1380
1745
  const next = Object.create(prototype, descriptors);
1381
1746
  state.seen.set(value, next);
1382
- return new Frame(OBJECT, value, next, Object.keys(descriptors), descriptors);
1747
+ const children = !(value instanceof Error) ? Object.keys(value) : Object.getOwnPropertyNames(value).filter(key => {
1748
+ const descriptor = descriptors[key];
1749
+ return descriptor.enumerable || "value" in descriptor;
1750
+ });
1751
+ return new Frame(OBJECT, value, next, children, descriptors);
1383
1752
  }
1384
1753
  function keepGuarded(value, next, changed, state) {
1385
1754
  if (changed || state.cyclic.has(value)) return next;
1386
1755
  state.seen.set(value, value);
1387
1756
  return value;
1388
1757
  }
1389
- function serializeResponseStream(value, codecOptions, signal) {
1758
+ function serializeResponseStream(value, codecOptions, signal, scope) {
1390
1759
  let closed = false;
1391
1760
  let streamController = null;
1392
1761
  let demandWaiters = null;
@@ -1405,11 +1774,13 @@ function serializeResponseStream(value, codecOptions, signal) {
1405
1774
  if (closed) close();else sourceClosers.add(close);
1406
1775
  }
1407
1776
  };
1408
- value = guardFailures(value, {
1777
+ const guardState = {
1409
1778
  seen: new WeakMap(),
1410
1779
  cyclic: new WeakSet(),
1411
- gate
1412
- });
1780
+ gate,
1781
+ scope
1782
+ };
1783
+ value = guardOperation(guardState, () => guardFailures(value, guardState));
1413
1784
  let cancelSerialize = null;
1414
1785
  let onAbort = null;
1415
1786
  const finishSource = () => {
@@ -1490,14 +1861,14 @@ function serializeResponseStream(value, codecOptions, signal) {
1490
1861
  }
1491
1862
  });
1492
1863
  }
1493
- function serializedResponse(value, headers, codec, signal) {
1864
+ function serializedResponse(value, headers, codec, signal, scope) {
1494
1865
  headers.set(BODY_FORMAT_HEADER, BodyFormat.Serialized);
1495
1866
  headers.set("Content-Type", "text/plain");
1496
- return new Response(serializeResponseStream(value, codec, signal), {
1867
+ return new Response(serializeResponseStream(value, codec, signal, scope), {
1497
1868
  headers
1498
1869
  });
1499
1870
  }
1500
- function encodeResult(value, headers, status, codec, signal) {
1871
+ function encodeResult(value, headers, status, codec, signal, scope) {
1501
1872
  if (NULL_BODY_STATUSES.has(status)) {
1502
1873
  if (value === undefined || value === null) {
1503
1874
  headers.set(BODY_FORMAT_HEADER, BodyFormat.Void);
@@ -1508,7 +1879,7 @@ function encodeResult(value, headers, status, codec, signal) {
1508
1879
  }
1509
1880
  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.`);
1510
1881
  headers.set(ERROR_HEADER, encodeErrorHeaderValue(error.message));
1511
- return encodeResult(error, headers, 500, codec, signal);
1882
+ return encodeResult(error, headers, 500, codec, signal, scope);
1512
1883
  }
1513
1884
  const direct = getHeadersAndBody(value);
1514
1885
  if (direct) {
@@ -1528,10 +1899,12 @@ function encodeResult(value, headers, status, codec, signal) {
1528
1899
  });
1529
1900
  }
1530
1901
  try {
1531
- if (isJSONSafe(value)) {
1902
+ const jsonSafe = scope ? scope(() => isJSONSafe(value)) : isJSONSafe(value);
1903
+ if (jsonSafe) {
1532
1904
  headers.set(BODY_FORMAT_HEADER, BodyFormat.Json);
1533
1905
  headers.set("Content-Type", "application/json");
1534
- return new Response(JSON.stringify(value), {
1906
+ const body = scope ? scope(() => JSON.stringify(value)) : JSON.stringify(value);
1907
+ return new Response(body, {
1535
1908
  status,
1536
1909
  headers
1537
1910
  });
@@ -1539,7 +1912,7 @@ function encodeResult(value, headers, status, codec, signal) {
1539
1912
  } catch {
1540
1913
  }
1541
1914
  try {
1542
- const response = serializedResponse(value, headers, codec, signal);
1915
+ const response = serializedResponse(value, headers, codec, signal, scope);
1543
1916
  return status === 200 ? response : new Response(response.body, {
1544
1917
  status,
1545
1918
  headers
@@ -1637,13 +2010,22 @@ function forbiddenResponse() {
1637
2010
  }
1638
2011
  }));
1639
2012
  }
2013
+ function nativePromise(value) {
2014
+ if (value instanceof Promise) return value;
2015
+ try {
2016
+ if (Object.prototype.toString.call(value) === "[object Promise]") return Promise.prototype.then.call(value, value => value);
2017
+ } catch {}
2018
+ }
1640
2019
  async function handleServerFunctionRequest(request, options = {}) {
1641
- const codec = options.codec !== undefined ? options.codec : getServerFunctionsCodec();
2020
+ const codec = {
2021
+ ...(options.codec !== undefined ? options.codec : getServerFunctionsCodec())
2022
+ };
2023
+ codec.serializeErrorStacks ??= DEV;
1642
2024
  const url = new URL(request.url);
1643
2025
  const method = request.method;
1644
2026
  const address = resolveAddress(url);
1645
2027
  const functionId = address && address.id;
1646
- const declaredRead = (method === "GET" || method === "HEAD") && functionId !== null && METHODS.get(functionId) === "GET";
2028
+ const declaredRead = (method === "GET" || method === "HEAD") && functionId !== null && declaresRead(functionId);
1647
2029
  const csrf = options.csrf !== undefined ? options.csrf : config.csrf;
1648
2030
  const protectsRequest = csrf !== false && (!declaredRead || typeof csrf === "object" && csrf.protectDeclaredReads === true);
1649
2031
  let serverFunction;
@@ -1674,7 +2056,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1674
2056
  const response = new Response(DEV ? `Method not allowed for server function: ${functionId}` : null, {
1675
2057
  status: 405,
1676
2058
  headers: {
1677
- Allow: METHODS.get(functionId) === "GET" ? "POST, GET, HEAD" : "POST"
2059
+ Allow: declaresRead(functionId) ? "POST, GET, HEAD" : "POST"
1678
2060
  }
1679
2061
  });
1680
2062
  return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
@@ -1696,30 +2078,50 @@ async function handleServerFunctionRequest(request, options = {}) {
1696
2078
  });
1697
2079
  return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1698
2080
  }
1699
- if (!(declared > 0)) {
1700
- const bounded = await bufferBodyWithin(request, bodySizeLimit);
1701
- if (bounded === null) {
1702
- const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
1703
- status: 413
1704
- });
1705
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1706
- }
1707
- request = bounded;
2081
+ let bounded;
2082
+ try {
2083
+ bounded = await bufferBodyWithin(request, bodySizeLimit);
2084
+ } catch {
2085
+ const response = new Response(DEV ? "Malformed server function arguments" : null, {
2086
+ status: 400
2087
+ });
2088
+ return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2089
+ }
2090
+ if (bounded === null) {
2091
+ const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
2092
+ status: 413
2093
+ });
2094
+ return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1708
2095
  }
2096
+ request = bounded;
2097
+ }
2098
+ let event;
2099
+ try {
2100
+ event = options.createEvent ? options.createEvent(request) : {
2101
+ request,
2102
+ locals: {}
2103
+ };
2104
+ const promised = nativePromise(event);
2105
+ if (promised) event = await promised;
2106
+ } catch (error) {
2107
+ const safe = sanitizeServerError(error);
2108
+ const message = safe instanceof Error ? safe.message : String(safe);
2109
+ const headers = new Headers();
2110
+ headers.set(ERROR_HEADER, boundedErrorHeaderValue(message));
2111
+ const response = scripted ? encodeResult(safe, headers, 500, codec, request.signal) : new Response(DEV ? message : null, {
2112
+ status: 500
2113
+ });
2114
+ return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1709
2115
  }
1710
- let event = options.createEvent ? options.createEvent(request) : {
1711
- request,
1712
- locals: {}
1713
- };
1714
- if (typeof event?.then === "function") event = await event;
1715
2116
  const refuseCommitted = raw => {
1716
2117
  const response = commitEventResponse(raw, event);
1717
2118
  return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1718
2119
  };
1719
2120
  const provide = options.provideEvent || provideEvent;
2121
+ const scope = run => provide(event, run);
1720
2122
  const flightHook = options.collectFlightData !== undefined ? options.collectFlightData : config.collectFlightData;
1721
2123
  const transformResult = options.transformResult !== undefined ? options.transformResult : config.transformResult;
1722
- const wrapInvocation = options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation;
2124
+ const wrapInvocation = resolveWrapInvocation(options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation);
1723
2125
  const transformFlightResult = options.transformFlightResult !== undefined ? options.transformFlightResult : config.transformFlightResult;
1724
2126
  let handleNoJS = options.handleNoJS !== undefined ? options.handleNoJS : config.handleNoJS;
1725
2127
  if (handleNoJS === undefined && !scripted && isFormPost(request)) {
@@ -1734,7 +2136,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1734
2136
  }
1735
2137
  }
1736
2138
  const flightHeader = scripted && method === "POST" ? request.headers.get(SINGLE_FLIGHT_HEADER) : null;
1737
- const flightHooks = flightHeader ? flightHeader.split(",").flatMap(source => {
2139
+ const flightHooks = flightHeader ? [...new Set(flightHeader.split(","))].flatMap(source => {
1738
2140
  const hook = source === "true" ? flightHook : flightSources.get(source);
1739
2141
  return hook ? [[source, hook]] : [];
1740
2142
  }) : [];
@@ -1742,8 +2144,9 @@ async function handleServerFunctionRequest(request, options = {}) {
1742
2144
  let parsed;
1743
2145
  try {
1744
2146
  parsed = await parseArguments(request, url, scripted, codec);
1745
- } catch {
1746
- const response = new Response(DEV ? "Malformed server function arguments" : null, {
2147
+ } catch (error) {
2148
+ const skewed = error !== null && typeof error === "object" && error[FORMAT_SKEW] === true;
2149
+ const response = new Response(DEV ? skewed ? error.message : "Malformed server function arguments" : null, {
1747
2150
  status: 400
1748
2151
  });
1749
2152
  return refuseCommitted(response);
@@ -1767,7 +2170,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1767
2170
  const headers = new Headers();
1768
2171
  const dispatch = async () => {
1769
2172
  try {
1770
- let result = await provide(event, async () => {
2173
+ const invokeOnce = async () => {
1771
2174
  INVOCATIONS.set(event, {
1772
2175
  id: functionId
1773
2176
  });
@@ -1779,7 +2182,8 @@ async function handleServerFunctionRequest(request, options = {}) {
1779
2182
  request,
1780
2183
  direct: false
1781
2184
  }) : run();
1782
- });
2185
+ };
2186
+ let result = await provideEventOnce(provide, event, invokeOnce);
1783
2187
  if (transformResult) {
1784
2188
  result = await transformResult(event, result, flightContext);
1785
2189
  }
@@ -1831,12 +2235,14 @@ async function handleServerFunctionRequest(request, options = {}) {
1831
2235
  if (result instanceof Response && result.headers.has("X-Content-Raw")) return result;
1832
2236
  }
1833
2237
  if (!scripted) {
1834
- if (handleNoJS) return handleNoJS(result ?? metadata, request, parsed);
2238
+ if (handleNoJS) {
2239
+ return handleNoJS(result == null && metadata !== undefined ? metadata : result, request, parsed);
2240
+ }
1835
2241
  if (result instanceof Response) return result;
1836
- return encodeResult(result, headers, status, codec, request.signal);
2242
+ return encodeResult(result, headers, status, codec, request.signal, scope);
1837
2243
  }
1838
2244
  if (status === 304) warnScripted304(functionId);
1839
- return encodeResult(result, headers, status, codec, request.signal);
2245
+ return encodeResult(result, headers, status, codec, request.signal, scope);
1840
2246
  } catch (x) {
1841
2247
  const respondThrown = value => {
1842
2248
  const safe = sanitizeServerError(value);
@@ -1849,19 +2255,19 @@ async function handleServerFunctionRequest(request, options = {}) {
1849
2255
  }
1850
2256
  const error = safe instanceof Error ? safe.message : typeof safe === "string" ? safe : "true";
1851
2257
  headers.set(ERROR_HEADER, boundedErrorHeaderValue(error));
1852
- return encodeResult(safe, headers, 500, codec, request.signal);
2258
+ return encodeResult(safe, headers, 500, codec, request.signal, scope);
1853
2259
  };
1854
- if (x instanceof Response || isResponseEnvelope(x)) {
1855
- if (transformResult) {
1856
- try {
1857
- x = await transformResult(event, x, {
1858
- ...flightContext,
1859
- thrown: true
1860
- });
1861
- } catch (hookError) {
1862
- return respondThrown(hookError);
1863
- }
2260
+ if (transformResult) {
2261
+ try {
2262
+ x = await transformResult(event, x, {
2263
+ ...flightContext,
2264
+ thrown: true
2265
+ });
2266
+ } catch (hookError) {
2267
+ return respondThrown(hookError);
1864
2268
  }
2269
+ }
2270
+ if (x instanceof Response || isResponseEnvelope(x)) {
1865
2271
  let status = 200;
1866
2272
  let metadata;
1867
2273
  if (isResponseEnvelope(x)) {
@@ -1913,7 +2319,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1913
2319
  if (x instanceof Response) return x;
1914
2320
  }
1915
2321
  if (scripted && status === 304) warnScripted304(functionId);
1916
- return encodeResult(x, headers, status, codec, request.signal);
2322
+ return encodeResult(x, headers, status, codec, request.signal, scope);
1917
2323
  }
1918
2324
  return respondThrown(x);
1919
2325
  }