@solidjs/web 2.0.0-rc.6 → 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 (50) hide show
  1. package/dist/server.cjs +105 -35
  2. package/dist/server.dev.cjs +3794 -0
  3. package/dist/server.dev.js +3627 -0
  4. package/dist/server.js +106 -36
  5. package/dist/web.cjs +39 -385
  6. package/dist/{dev.cjs → web.dev.cjs} +91 -396
  7. package/dist/{dev.js → web.dev.js} +93 -393
  8. package/dist/web.js +41 -382
  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 +234 -32
  14. package/frames/dist/server.dev.cjs +4584 -0
  15. package/frames/dist/server.dev.js +4571 -0
  16. package/frames/dist/server.js +234 -32
  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 +13 -14
  24. package/server-functions/dist/client.js +13 -14
  25. package/server-functions/dist/server.cjs +331 -83
  26. package/server-functions/dist/server.dev.cjs +338 -82
  27. package/server-functions/dist/server.dev.js +338 -82
  28. package/server-functions/dist/server.js +331 -83
  29. package/types/client.d.ts +0 -3
  30. package/types/frames/frame-client.d.ts +1 -1
  31. package/types/head.d.ts +3 -0
  32. package/types/index.d.ts +18 -7
  33. package/types/index.server.d.ts +31 -9
  34. package/types/render.d.ts +3 -1
  35. package/types/server-functions/flash.d.ts +12 -3
  36. package/types/server-functions/server.d.ts +27 -3
  37. package/types/server-mock.d.ts +43 -7
  38. package/types/server.d.ts +47 -5
  39. package/types-cjs/client.d.cts +0 -3
  40. package/types-cjs/frames/frame-client.d.cts +1 -1
  41. package/types-cjs/head.d.cts +3 -0
  42. package/types-cjs/index.d.cts +18 -7
  43. package/types-cjs/index.server.d.cts +31 -9
  44. package/types-cjs/render.d.cts +3 -1
  45. package/types-cjs/server-functions/flash.d.cts +12 -3
  46. package/types-cjs/server-functions/server.d.cts +27 -3
  47. package/types-cjs/server-mock.d.cts +43 -7
  48. package/types-cjs/server.d.cts +47 -5
  49. package/types/patch-driver.d.ts +0 -3
  50. package/types-cjs/patch-driver.d.cts +0 -3
@@ -269,7 +269,7 @@ function isJSONSafe(value) {
269
269
  const t = typeof v;
270
270
  if (t === "string" || t === "boolean") continue;
271
271
  if (t === "number") {
272
- if (!Number.isFinite(v)) return false;
272
+ if (!Number.isFinite(v) || Object.is(v, -0)) return false;
273
273
  continue;
274
274
  }
275
275
  if (t !== "object") return false;
@@ -355,31 +355,30 @@ function getHeadersAndBody(body) {
355
355
  async function extractBody(source, codecOptions) {
356
356
  const contentType = source.headers.get("content-type");
357
357
  const format = source.headers.get(BODY_FORMAT_HEADER);
358
- const clone = source.clone();
359
358
  switch (true) {
360
359
  case format === BodyFormat.Serialized:
361
- return await deserializeStream(clone, codecOptions);
360
+ return await deserializeStream(source, codecOptions);
362
361
  case format === BodyFormat.Json:
363
- return JSON.parse(await clone.text());
362
+ return JSON.parse(await source.text());
364
363
  case format === BodyFormat.String:
365
- return await clone.text();
364
+ return await source.text();
366
365
  case format === BodyFormat.File:
367
366
  {
368
- const formData = await clone.formData();
367
+ const formData = await source.formData();
369
368
  return formData.get(FILE_FORM_KEY);
370
369
  }
371
370
  case format === BodyFormat.FormData:
372
371
  case contentType && contentType.startsWith("multipart/form-data"):
373
- return await clone.formData();
372
+ return await source.formData();
374
373
  case format === BodyFormat.URLSearchParams:
375
374
  case contentType && contentType.startsWith("application/x-www-form-urlencoded"):
376
- return new URLSearchParams(await clone.text());
375
+ return new URLSearchParams(await source.text());
377
376
  case format === BodyFormat.Blob:
378
- return await clone.blob();
377
+ return await source.blob();
379
378
  case format === BodyFormat.ArrayBuffer:
380
- return await clone.arrayBuffer();
379
+ return await source.arrayBuffer();
381
380
  case format === BodyFormat.Uint8Array:
382
- return new Uint8Array(await clone.arrayBuffer());
381
+ return new Uint8Array(await source.arrayBuffer());
383
382
  }
384
383
  return undefined;
385
384
  }
@@ -515,7 +514,7 @@ async function deserializeString(text, codecOptions) {
515
514
  }
516
515
  async function decodeResponse(response, codecOptions) {
517
516
  if (!response.body) return undefined;
518
- return await extractBody(response, codecOptions === undefined ? codecConfig.codec : codecOptions);
517
+ return await extractBody(response.clone(), codecOptions === undefined ? codecConfig.codec : codecOptions);
519
518
  }
520
519
  async function decodeResponsePayload(response, codecOptions) {
521
520
  const decoded = await decodeResponse(response, codecOptions);
@@ -595,6 +594,68 @@ function commitEventResponse(response, event = getRequestEvent()) {
595
594
  });
596
595
  }
597
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
+ }
598
659
  function encodeInputValue(value) {
599
660
  if (value instanceof FormData) return {
600
661
  $f: [...value.entries()].filter(([, v]) => typeof v === "string")
@@ -615,7 +676,12 @@ function decodeInputValue(value) {
615
676
  }
616
677
  return value;
617
678
  }
618
- 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
+ }
619
685
  const isError = result instanceof Error;
620
686
  const payload = {
621
687
  url,
@@ -624,7 +690,7 @@ function encodeFlashCookie(url, result, input, thrown) {
624
690
  thrown: !!thrown,
625
691
  input: input.map(encodeInputValue)
626
692
  };
627
- if (fitsCookie(payload)) return flashCookie(payload);
693
+ if (fitsCookie(payload)) return flashCookie(payload, await key);
628
694
  payload.truncated = true;
629
695
  payload.input = [];
630
696
  if (!fitsCookie(payload)) {
@@ -641,24 +707,35 @@ function encodeFlashCookie(url, result, input, thrown) {
641
707
  payload.result = true;
642
708
  }
643
709
  }
644
- return flashCookie(payload);
710
+ if (!fitsCookie(payload)) return null;
711
+ return flashCookie(payload, await key);
645
712
  }
646
- function flashCookie(payload) {
647
- 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)), {
648
716
  secure: true,
649
- httpOnly: true
717
+ httpOnly: true,
718
+ sameSite: "lax",
719
+ maxAge: FLASH_MAX_AGE_SECONDS
650
720
  });
651
721
  }
652
722
  const COOKIE_PAIR_BUDGET = 4000;
653
723
  function fitsCookie(payload) {
654
- 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;
655
728
  }
656
- function decodeFlashCookie(cookieHeader) {
729
+ async function decodeFlashCookie(cookieHeader) {
657
730
  const match = parseCookieHeader(cookieHeader)[FLASH_COOKIE];
658
731
  if (!match) return;
659
732
  try {
660
- const payload = JSON.parse(match);
661
- 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;
662
739
  const result = payload.error ? new Error(payload.result) : payload.result;
663
740
  const submission = {
664
741
  input: Array.isArray(payload.input) ? payload.input.map(decodeInputValue) : [],
@@ -698,7 +775,8 @@ function configureServerFunctionsServer({
698
775
  csrf,
699
776
  codec,
700
777
  bodySizeLimit,
701
- maxArguments
778
+ maxArguments,
779
+ secret
702
780
  } = {}) {
703
781
  if (provideEvent !== undefined) config.provideEvent = provideEvent;
704
782
  if (wrapInvocation !== undefined) config.wrapInvocation = wrapInvocation;
@@ -712,6 +790,7 @@ function configureServerFunctionsServer({
712
790
  if (codec !== undefined) configureServerFunctionsCodec(codec);
713
791
  if (bodySizeLimit !== undefined) config.bodySizeLimit = bodySizeLimit;
714
792
  if (maxArguments !== undefined) config.maxArguments = maxArguments;
793
+ if (secret !== undefined) setFlashSecret(secret);
715
794
  }
716
795
  const flightSources = new Map();
717
796
  function registerFlightDataSource(source, hook) {
@@ -721,13 +800,146 @@ function registerFlightDataSource(source, hook) {
721
800
  if (flightSources.get(source) === hook) flightSources.delete(source);
722
801
  };
723
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
+ }
724
807
  function provideEvent(event, fn) {
725
808
  if (config.provideEvent) return config.provideEvent(event, fn);
726
809
  const ctx = globalThis[RequestContext];
727
810
  if (ctx) return ctx.run(event, fn);
728
811
  throw new Error("No request event provider. Configure one with configureServerFunctionsServer({ provideEvent }).");
729
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
+ }
730
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) {
731
943
  if (value === null || typeof value !== "object" && typeof value !== "function") return value;
732
944
  const promised = scope(() => nativePromise(value));
733
945
  if (promised) {
@@ -775,6 +987,11 @@ function scopeDeferredResult(value, scope) {
775
987
  }
776
988
  const REGISTRATIONS = new Map();
777
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
+ }
778
995
  const INVOCATIONS = new WeakMap();
779
996
  let rpcProvided = false;
780
997
  function provideRPC() {
@@ -871,9 +1088,10 @@ function createServerReference({
871
1088
  });
872
1089
  evt.serverOnly = true;
873
1090
  const scope = run => provideEvent(evt, run);
874
- let result = provideEvent(evt, () => {
1091
+ const wrap = resolveWrapInvocation(config.wrapInvocation);
1092
+ let result = provideEventOnce(provideEvent, evt, () => {
875
1093
  const run = () => fn.apply(thisArg, args);
876
- return config.wrapInvocation ? config.wrapInvocation(run, {
1094
+ return wrap ? wrap(run, {
877
1095
  id,
878
1096
  args,
879
1097
  event: evt,
@@ -896,16 +1114,45 @@ function createServerReference({
896
1114
  }), scope) : result;
897
1115
  }
898
1116
  });
1117
+ REFERENCE_BINDINGS.set(proxy, fn);
899
1118
  return proxy;
900
1119
  }
901
1120
  function GET(fn) {
902
1121
  if (!isServerFunction(fn) || typeof fn.id !== "string") {
903
1122
  throw new Error("GET expects a server function reference");
904
1123
  }
905
- METHODS.set(fn.id, "GET");
906
- 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, {
907
1136
  method: "GET"
908
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
+ });
909
1156
  }
910
1157
  function live(fn) {
911
1158
  if (!isServerFunction(fn) || typeof fn.id !== "string") {
@@ -1022,6 +1269,13 @@ async function bufferBodyWithin(request, limit) {
1022
1269
  body
1023
1270
  });
1024
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
+ }
1025
1279
  async function parseArguments(request, url, scripted, codec) {
1026
1280
  const parsed = [];
1027
1281
  const bodyFormat = request.method === "POST" ? request.headers.get(BODY_FORMAT_HEADER) : null;
@@ -1045,7 +1299,11 @@ async function parseArguments(request, url, scripted, codec) {
1045
1299
  parsed.push(url.searchParams);
1046
1300
  }
1047
1301
  if (request.method === "POST" && request.body !== null) {
1048
- 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);
1049
1307
  if (bodyFormat === BodyFormat.Serialized || bodyFormat === BodyFormat.Json) {
1050
1308
  if (bodyFormat === BodyFormat.Json) assertDecodeDepth(decoded);
1051
1309
  if (!Array.isArray(decoded)) {
@@ -1054,7 +1312,7 @@ async function parseArguments(request, url, scripted, codec) {
1054
1312
  return stripUnsafeArgumentKeys(decoded);
1055
1313
  }
1056
1314
  if (decoded === undefined) {
1057
- if (bodyFormat === null && (await request.clone().arrayBuffer()).byteLength === 0) {
1315
+ if (bodyFormat === null && (await body.arrayBuffer()).byteLength === 0) {
1058
1316
  return parsed;
1059
1317
  }
1060
1318
  throw new TypeError("Server function body carries no usable encoding");
@@ -1084,13 +1342,14 @@ async function foldFlightData(hooks, event, headers, outcome, context = {}) {
1084
1342
  data
1085
1343
  }, context);
1086
1344
  if (transformed !== undefined) {
1087
- 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);
1088
1347
  headers.forEach((value, key) => {
1089
- if (key !== "set-cookie" && !transformed.headers.has(key)) {
1090
- transformed.headers.set(key, value);
1348
+ if (key !== "set-cookie" && !owned.headers.has(key)) {
1349
+ owned.headers.set(key, value);
1091
1350
  }
1092
1351
  });
1093
- return transformed;
1352
+ return owned;
1094
1353
  }
1095
1354
  }
1096
1355
  return outcome.value === undefined ? {
@@ -1211,7 +1470,7 @@ function warnScripted304(functionId) {
1211
1470
  function createNoJSHandler({
1212
1471
  base = ""
1213
1472
  } = {}) {
1214
- return function handleNoJS(result, request, args, thrown) {
1473
+ return async function handleNoJS(result, request, args, thrown) {
1215
1474
  const url = new URL(request.url);
1216
1475
  let back = new URL(base || "/", url.origin).toString();
1217
1476
  try {
@@ -1236,8 +1495,9 @@ function createNoJSHandler({
1236
1495
  Location: back
1237
1496
  });
1238
1497
  }
1239
- if (result && !(result instanceof Response)) {
1240
- 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);
1241
1501
  }
1242
1502
  return new Response(null, {
1243
1503
  status,
@@ -1475,7 +1735,7 @@ function enterGuard(value, state) {
1475
1735
  return new Frame(SET, value, next, [...value], null);
1476
1736
  }
1477
1737
  const prototype = Object.getPrototypeOf(value);
1478
- if (prototype !== Object.prototype && prototype !== null) {
1738
+ if (prototype !== Object.prototype && prototype !== null && !(value instanceof Error)) {
1479
1739
  state.seen.set(value, value);
1480
1740
  return value;
1481
1741
  }
@@ -1486,7 +1746,11 @@ function enterGuard(value, state) {
1486
1746
  }
1487
1747
  const next = Object.create(prototype, descriptors);
1488
1748
  state.seen.set(value, next);
1489
- return new Frame(OBJECT, value, next, Object.keys(value), 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);
1490
1754
  }
1491
1755
  function keepGuarded(value, next, changed, state) {
1492
1756
  if (changed || state.cyclic.has(value)) return next;
@@ -1763,7 +2027,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1763
2027
  const method = request.method;
1764
2028
  const address = resolveAddress(url);
1765
2029
  const functionId = address && address.id;
1766
- const declaredRead = (method === "GET" || method === "HEAD") && functionId !== null && METHODS.get(functionId) === "GET";
2030
+ const declaredRead = (method === "GET" || method === "HEAD") && functionId !== null && declaresRead(functionId);
1767
2031
  const csrf = options.csrf !== undefined ? options.csrf : config.csrf;
1768
2032
  const protectsRequest = csrf !== false && (!declaredRead || typeof csrf === "object" && csrf.protectDeclaredReads === true);
1769
2033
  let serverFunction;
@@ -1794,7 +2058,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1794
2058
  const response = new Response(DEV ? `Method not allowed for server function: ${functionId}` : null, {
1795
2059
  status: 405,
1796
2060
  headers: {
1797
- Allow: METHODS.get(functionId) === "GET" ? "POST, GET, HEAD" : "POST"
2061
+ Allow: declaresRead(functionId) ? "POST, GET, HEAD" : "POST"
1798
2062
  }
1799
2063
  });
1800
2064
  return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
@@ -1816,24 +2080,22 @@ async function handleServerFunctionRequest(request, options = {}) {
1816
2080
  });
1817
2081
  return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1818
2082
  }
1819
- if (!(declared > 0)) {
1820
- let bounded;
1821
- try {
1822
- bounded = await bufferBodyWithin(request, bodySizeLimit);
1823
- } catch {
1824
- const response = new Response(DEV ? "Malformed server function arguments" : null, {
1825
- status: 400
1826
- });
1827
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1828
- }
1829
- if (bounded === null) {
1830
- const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
1831
- status: 413
1832
- });
1833
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1834
- }
1835
- 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);
1836
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);
2097
+ }
2098
+ request = bounded;
1837
2099
  }
1838
2100
  let event;
1839
2101
  try {
@@ -1861,7 +2123,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1861
2123
  const scope = run => provide(event, run);
1862
2124
  const flightHook = options.collectFlightData !== undefined ? options.collectFlightData : config.collectFlightData;
1863
2125
  const transformResult = options.transformResult !== undefined ? options.transformResult : config.transformResult;
1864
- const wrapInvocation = options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation;
2126
+ const wrapInvocation = resolveWrapInvocation(options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation);
1865
2127
  const transformFlightResult = options.transformFlightResult !== undefined ? options.transformFlightResult : config.transformFlightResult;
1866
2128
  let handleNoJS = options.handleNoJS !== undefined ? options.handleNoJS : config.handleNoJS;
1867
2129
  if (handleNoJS === undefined && !scripted && isFormPost(request)) {
@@ -1876,7 +2138,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1876
2138
  }
1877
2139
  }
1878
2140
  const flightHeader = scripted && method === "POST" ? request.headers.get(SINGLE_FLIGHT_HEADER) : null;
1879
- const flightHooks = flightHeader ? flightHeader.split(",").flatMap(source => {
2141
+ const flightHooks = flightHeader ? [...new Set(flightHeader.split(","))].flatMap(source => {
1880
2142
  const hook = source === "true" ? flightHook : flightSources.get(source);
1881
2143
  return hook ? [[source, hook]] : [];
1882
2144
  }) : [];
@@ -1884,8 +2146,9 @@ async function handleServerFunctionRequest(request, options = {}) {
1884
2146
  let parsed;
1885
2147
  try {
1886
2148
  parsed = await parseArguments(request, url, scripted, codec);
1887
- } catch {
1888
- 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, {
1889
2152
  status: 400
1890
2153
  });
1891
2154
  return refuseCommitted(response);
@@ -1909,7 +2172,6 @@ async function handleServerFunctionRequest(request, options = {}) {
1909
2172
  const headers = new Headers();
1910
2173
  const dispatch = async () => {
1911
2174
  try {
1912
- let invocations = 0;
1913
2175
  const invokeOnce = async () => {
1914
2176
  INVOCATIONS.set(event, {
1915
2177
  id: functionId
@@ -1923,15 +2185,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1923
2185
  direct: false
1924
2186
  }) : run();
1925
2187
  };
1926
- let result = await provide(event, () => {
1927
- if (++invocations > 1) {
1928
- throw new Error("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.");
1929
- }
1930
- return invokeOnce();
1931
- });
1932
- if (invocations !== 1) {
1933
- throw new Error(invocations === 0 ? "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." : "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.");
1934
- }
2188
+ let result = await provideEventOnce(provide, event, invokeOnce);
1935
2189
  if (transformResult) {
1936
2190
  result = await transformResult(event, result, flightContext);
1937
2191
  }
@@ -1983,7 +2237,9 @@ async function handleServerFunctionRequest(request, options = {}) {
1983
2237
  if (result instanceof Response && result.headers.has("X-Content-Raw")) return result;
1984
2238
  }
1985
2239
  if (!scripted) {
1986
- if (handleNoJS) return handleNoJS(result ?? metadata, request, parsed);
2240
+ if (handleNoJS) {
2241
+ return handleNoJS(result == null && metadata !== undefined ? metadata : result, request, parsed);
2242
+ }
1987
2243
  if (result instanceof Response) return result;
1988
2244
  return encodeResult(result, headers, status, codec, request.signal, scope);
1989
2245
  }
@@ -2003,17 +2259,17 @@ async function handleServerFunctionRequest(request, options = {}) {
2003
2259
  headers.set(ERROR_HEADER, boundedErrorHeaderValue(error));
2004
2260
  return encodeResult(safe, headers, 500, codec, request.signal, scope);
2005
2261
  };
2006
- if (x instanceof Response || isResponseEnvelope(x)) {
2007
- if (transformResult) {
2008
- try {
2009
- x = await transformResult(event, x, {
2010
- ...flightContext,
2011
- thrown: true
2012
- });
2013
- } catch (hookError) {
2014
- return respondThrown(hookError);
2015
- }
2262
+ if (transformResult) {
2263
+ try {
2264
+ x = await transformResult(event, x, {
2265
+ ...flightContext,
2266
+ thrown: true
2267
+ });
2268
+ } catch (hookError) {
2269
+ return respondThrown(hookError);
2016
2270
  }
2271
+ }
2272
+ if (x instanceof Response || isResponseEnvelope(x)) {
2017
2273
  let status = 200;
2018
2274
  let metadata;
2019
2275
  if (isResponseEnvelope(x)) {