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