@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
@@ -267,7 +267,7 @@ function isJSONSafe(value) {
267
267
  const t = typeof v;
268
268
  if (t === "string" || t === "boolean") continue;
269
269
  if (t === "number") {
270
- if (!Number.isFinite(v)) return false;
270
+ if (!Number.isFinite(v) || Object.is(v, -0)) return false;
271
271
  continue;
272
272
  }
273
273
  if (t !== "object") return false;
@@ -353,31 +353,30 @@ function getHeadersAndBody(body) {
353
353
  async function extractBody(source, codecOptions) {
354
354
  const contentType = source.headers.get("content-type");
355
355
  const format = source.headers.get(BODY_FORMAT_HEADER);
356
- const clone = source.clone();
357
356
  switch (true) {
358
357
  case format === BodyFormat.Serialized:
359
- return await deserializeStream(clone, codecOptions);
358
+ return await deserializeStream(source, codecOptions);
360
359
  case format === BodyFormat.Json:
361
- return JSON.parse(await clone.text());
360
+ return JSON.parse(await source.text());
362
361
  case format === BodyFormat.String:
363
- return await clone.text();
362
+ return await source.text();
364
363
  case format === BodyFormat.File:
365
364
  {
366
- const formData = await clone.formData();
365
+ const formData = await source.formData();
367
366
  return formData.get(FILE_FORM_KEY);
368
367
  }
369
368
  case format === BodyFormat.FormData:
370
369
  case contentType && contentType.startsWith("multipart/form-data"):
371
- return await clone.formData();
370
+ return await source.formData();
372
371
  case format === BodyFormat.URLSearchParams:
373
372
  case contentType && contentType.startsWith("application/x-www-form-urlencoded"):
374
- return new URLSearchParams(await clone.text());
373
+ return new URLSearchParams(await source.text());
375
374
  case format === BodyFormat.Blob:
376
- return await clone.blob();
375
+ return await source.blob();
377
376
  case format === BodyFormat.ArrayBuffer:
378
- return await clone.arrayBuffer();
377
+ return await source.arrayBuffer();
379
378
  case format === BodyFormat.Uint8Array:
380
- return new Uint8Array(await clone.arrayBuffer());
379
+ return new Uint8Array(await source.arrayBuffer());
381
380
  }
382
381
  return undefined;
383
382
  }
@@ -513,7 +512,7 @@ async function deserializeString(text, codecOptions) {
513
512
  }
514
513
  async function decodeResponse(response, codecOptions) {
515
514
  if (!response.body) return undefined;
516
- return await extractBody(response, codecOptions === undefined ? codecConfig.codec : codecOptions);
515
+ return await extractBody(response.clone(), codecOptions === undefined ? codecConfig.codec : codecOptions);
517
516
  }
518
517
  async function decodeResponsePayload(response, codecOptions) {
519
518
  const decoded = await decodeResponse(response, codecOptions);
@@ -593,6 +592,68 @@ function commitEventResponse(response, event = getRequestEvent()) {
593
592
  });
594
593
  }
595
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
+ }
596
657
  function encodeInputValue(value) {
597
658
  if (value instanceof FormData) return {
598
659
  $f: [...value.entries()].filter(([, v]) => typeof v === "string")
@@ -613,7 +674,12 @@ function decodeInputValue(value) {
613
674
  }
614
675
  return value;
615
676
  }
616
- 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
+ }
617
683
  const isError = result instanceof Error;
618
684
  const payload = {
619
685
  url,
@@ -622,7 +688,7 @@ function encodeFlashCookie(url, result, input, thrown) {
622
688
  thrown: !!thrown,
623
689
  input: input.map(encodeInputValue)
624
690
  };
625
- if (fitsCookie(payload)) return flashCookie(payload);
691
+ if (fitsCookie(payload)) return flashCookie(payload, await key);
626
692
  payload.truncated = true;
627
693
  payload.input = [];
628
694
  if (!fitsCookie(payload)) {
@@ -639,24 +705,35 @@ function encodeFlashCookie(url, result, input, thrown) {
639
705
  payload.result = true;
640
706
  }
641
707
  }
642
- return flashCookie(payload);
708
+ if (!fitsCookie(payload)) return null;
709
+ return flashCookie(payload, await key);
643
710
  }
644
- function flashCookie(payload) {
645
- 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)), {
646
714
  secure: true,
647
- httpOnly: true
715
+ httpOnly: true,
716
+ sameSite: "lax",
717
+ maxAge: FLASH_MAX_AGE_SECONDS
648
718
  });
649
719
  }
650
720
  const COOKIE_PAIR_BUDGET = 4000;
651
721
  function fitsCookie(payload) {
652
- 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;
653
726
  }
654
- function decodeFlashCookie(cookieHeader) {
727
+ async function decodeFlashCookie(cookieHeader) {
655
728
  const match = parseCookieHeader(cookieHeader)[FLASH_COOKIE];
656
729
  if (!match) return;
657
730
  try {
658
- const payload = JSON.parse(match);
659
- 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;
660
737
  const result = payload.error ? new Error(payload.result) : payload.result;
661
738
  const submission = {
662
739
  input: Array.isArray(payload.input) ? payload.input.map(decodeInputValue) : [],
@@ -696,7 +773,8 @@ function configureServerFunctionsServer({
696
773
  csrf,
697
774
  codec,
698
775
  bodySizeLimit,
699
- maxArguments
776
+ maxArguments,
777
+ secret
700
778
  } = {}) {
701
779
  if (provideEvent !== undefined) config.provideEvent = provideEvent;
702
780
  if (wrapInvocation !== undefined) config.wrapInvocation = wrapInvocation;
@@ -710,6 +788,7 @@ function configureServerFunctionsServer({
710
788
  if (codec !== undefined) configureServerFunctionsCodec(codec);
711
789
  if (bodySizeLimit !== undefined) config.bodySizeLimit = bodySizeLimit;
712
790
  if (maxArguments !== undefined) config.maxArguments = maxArguments;
791
+ if (secret !== undefined) setFlashSecret(secret);
713
792
  }
714
793
  const flightSources = new Map();
715
794
  function registerFlightDataSource(source, hook) {
@@ -719,13 +798,146 @@ function registerFlightDataSource(source, hook) {
719
798
  if (flightSources.get(source) === hook) flightSources.delete(source);
720
799
  };
721
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
+ }
722
805
  function provideEvent(event, fn) {
723
806
  if (config.provideEvent) return config.provideEvent(event, fn);
724
807
  const ctx = globalThis[RequestContext];
725
808
  if (ctx) return ctx.run(event, fn);
726
809
  throw new Error("No request event provider. Configure one with configureServerFunctionsServer({ provideEvent }).");
727
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
+ }
728
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) {
729
941
  if (value === null || typeof value !== "object" && typeof value !== "function") return value;
730
942
  const promised = scope(() => nativePromise(value));
731
943
  if (promised) {
@@ -773,6 +985,11 @@ function scopeDeferredResult(value, scope) {
773
985
  }
774
986
  const REGISTRATIONS = new Map();
775
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
+ }
776
993
  const INVOCATIONS = new WeakMap();
777
994
  let rpcProvided = false;
778
995
  function provideRPC() {
@@ -869,9 +1086,10 @@ function createServerReference({
869
1086
  });
870
1087
  evt.serverOnly = true;
871
1088
  const scope = run => provideEvent(evt, run);
872
- let result = provideEvent(evt, () => {
1089
+ const wrap = resolveWrapInvocation(config.wrapInvocation);
1090
+ let result = provideEventOnce(provideEvent, evt, () => {
873
1091
  const run = () => fn.apply(thisArg, args);
874
- return config.wrapInvocation ? config.wrapInvocation(run, {
1092
+ return wrap ? wrap(run, {
875
1093
  id,
876
1094
  args,
877
1095
  event: evt,
@@ -894,16 +1112,45 @@ function createServerReference({
894
1112
  }), scope) : result;
895
1113
  }
896
1114
  });
1115
+ REFERENCE_BINDINGS.set(proxy, fn);
897
1116
  return proxy;
898
1117
  }
899
1118
  function GET(fn) {
900
1119
  if (!isServerFunction(fn) || typeof fn.id !== "string") {
901
1120
  throw new Error("GET expects a server function reference");
902
1121
  }
903
- METHODS.set(fn.id, "GET");
904
- 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, {
905
1134
  method: "GET"
906
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
+ });
907
1154
  }
908
1155
  function live(fn) {
909
1156
  if (!isServerFunction(fn) || typeof fn.id !== "string") {
@@ -1020,6 +1267,13 @@ async function bufferBodyWithin(request, limit) {
1020
1267
  body
1021
1268
  });
1022
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
+ }
1023
1277
  async function parseArguments(request, url, scripted, codec) {
1024
1278
  const parsed = [];
1025
1279
  const bodyFormat = request.method === "POST" ? request.headers.get(BODY_FORMAT_HEADER) : null;
@@ -1043,7 +1297,11 @@ async function parseArguments(request, url, scripted, codec) {
1043
1297
  parsed.push(url.searchParams);
1044
1298
  }
1045
1299
  if (request.method === "POST" && request.body !== null) {
1046
- 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);
1047
1305
  if (bodyFormat === BodyFormat.Serialized || bodyFormat === BodyFormat.Json) {
1048
1306
  if (bodyFormat === BodyFormat.Json) assertDecodeDepth(decoded);
1049
1307
  if (!Array.isArray(decoded)) {
@@ -1052,7 +1310,7 @@ async function parseArguments(request, url, scripted, codec) {
1052
1310
  return stripUnsafeArgumentKeys(decoded);
1053
1311
  }
1054
1312
  if (decoded === undefined) {
1055
- if (bodyFormat === null && (await request.clone().arrayBuffer()).byteLength === 0) {
1313
+ if (bodyFormat === null && (await body.arrayBuffer()).byteLength === 0) {
1056
1314
  return parsed;
1057
1315
  }
1058
1316
  throw new TypeError("Server function body carries no usable encoding");
@@ -1082,13 +1340,14 @@ async function foldFlightData(hooks, event, headers, outcome, context = {}) {
1082
1340
  data
1083
1341
  }, context);
1084
1342
  if (transformed !== undefined) {
1085
- 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);
1086
1345
  headers.forEach((value, key) => {
1087
- if (key !== "set-cookie" && !transformed.headers.has(key)) {
1088
- transformed.headers.set(key, value);
1346
+ if (key !== "set-cookie" && !owned.headers.has(key)) {
1347
+ owned.headers.set(key, value);
1089
1348
  }
1090
1349
  });
1091
- return transformed;
1350
+ return owned;
1092
1351
  }
1093
1352
  }
1094
1353
  return outcome.value === undefined ? {
@@ -1209,7 +1468,7 @@ function warnScripted304(functionId) {
1209
1468
  function createNoJSHandler({
1210
1469
  base = ""
1211
1470
  } = {}) {
1212
- return function handleNoJS(result, request, args, thrown) {
1471
+ return async function handleNoJS(result, request, args, thrown) {
1213
1472
  const url = new URL(request.url);
1214
1473
  let back = new URL(base || "/", url.origin).toString();
1215
1474
  try {
@@ -1234,8 +1493,9 @@ function createNoJSHandler({
1234
1493
  Location: back
1235
1494
  });
1236
1495
  }
1237
- if (result && !(result instanceof Response)) {
1238
- 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);
1239
1499
  }
1240
1500
  return new Response(null, {
1241
1501
  status,
@@ -1473,7 +1733,7 @@ function enterGuard(value, state) {
1473
1733
  return new Frame(SET, value, next, [...value], null);
1474
1734
  }
1475
1735
  const prototype = Object.getPrototypeOf(value);
1476
- if (prototype !== Object.prototype && prototype !== null) {
1736
+ if (prototype !== Object.prototype && prototype !== null && !(value instanceof Error)) {
1477
1737
  state.seen.set(value, value);
1478
1738
  return value;
1479
1739
  }
@@ -1484,7 +1744,11 @@ function enterGuard(value, state) {
1484
1744
  }
1485
1745
  const next = Object.create(prototype, descriptors);
1486
1746
  state.seen.set(value, next);
1487
- return new Frame(OBJECT, value, next, Object.keys(value), 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);
1488
1752
  }
1489
1753
  function keepGuarded(value, next, changed, state) {
1490
1754
  if (changed || state.cyclic.has(value)) return next;
@@ -1761,7 +2025,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1761
2025
  const method = request.method;
1762
2026
  const address = resolveAddress(url);
1763
2027
  const functionId = address && address.id;
1764
- const declaredRead = (method === "GET" || method === "HEAD") && functionId !== null && METHODS.get(functionId) === "GET";
2028
+ const declaredRead = (method === "GET" || method === "HEAD") && functionId !== null && declaresRead(functionId);
1765
2029
  const csrf = options.csrf !== undefined ? options.csrf : config.csrf;
1766
2030
  const protectsRequest = csrf !== false && (!declaredRead || typeof csrf === "object" && csrf.protectDeclaredReads === true);
1767
2031
  let serverFunction;
@@ -1792,7 +2056,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1792
2056
  const response = new Response(DEV ? `Method not allowed for server function: ${functionId}` : null, {
1793
2057
  status: 405,
1794
2058
  headers: {
1795
- Allow: METHODS.get(functionId) === "GET" ? "POST, GET, HEAD" : "POST"
2059
+ Allow: declaresRead(functionId) ? "POST, GET, HEAD" : "POST"
1796
2060
  }
1797
2061
  });
1798
2062
  return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
@@ -1814,24 +2078,22 @@ async function handleServerFunctionRequest(request, options = {}) {
1814
2078
  });
1815
2079
  return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1816
2080
  }
1817
- if (!(declared > 0)) {
1818
- let bounded;
1819
- try {
1820
- bounded = await bufferBodyWithin(request, bodySizeLimit);
1821
- } catch {
1822
- const response = new Response(DEV ? "Malformed server function arguments" : null, {
1823
- status: 400
1824
- });
1825
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1826
- }
1827
- if (bounded === null) {
1828
- const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
1829
- status: 413
1830
- });
1831
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1832
- }
1833
- 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);
1834
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);
2095
+ }
2096
+ request = bounded;
1835
2097
  }
1836
2098
  let event;
1837
2099
  try {
@@ -1859,7 +2121,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1859
2121
  const scope = run => provide(event, run);
1860
2122
  const flightHook = options.collectFlightData !== undefined ? options.collectFlightData : config.collectFlightData;
1861
2123
  const transformResult = options.transformResult !== undefined ? options.transformResult : config.transformResult;
1862
- const wrapInvocation = options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation;
2124
+ const wrapInvocation = resolveWrapInvocation(options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation);
1863
2125
  const transformFlightResult = options.transformFlightResult !== undefined ? options.transformFlightResult : config.transformFlightResult;
1864
2126
  let handleNoJS = options.handleNoJS !== undefined ? options.handleNoJS : config.handleNoJS;
1865
2127
  if (handleNoJS === undefined && !scripted && isFormPost(request)) {
@@ -1874,7 +2136,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1874
2136
  }
1875
2137
  }
1876
2138
  const flightHeader = scripted && method === "POST" ? request.headers.get(SINGLE_FLIGHT_HEADER) : null;
1877
- const flightHooks = flightHeader ? flightHeader.split(",").flatMap(source => {
2139
+ const flightHooks = flightHeader ? [...new Set(flightHeader.split(","))].flatMap(source => {
1878
2140
  const hook = source === "true" ? flightHook : flightSources.get(source);
1879
2141
  return hook ? [[source, hook]] : [];
1880
2142
  }) : [];
@@ -1882,8 +2144,9 @@ async function handleServerFunctionRequest(request, options = {}) {
1882
2144
  let parsed;
1883
2145
  try {
1884
2146
  parsed = await parseArguments(request, url, scripted, codec);
1885
- } catch {
1886
- 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, {
1887
2150
  status: 400
1888
2151
  });
1889
2152
  return refuseCommitted(response);
@@ -1907,7 +2170,6 @@ async function handleServerFunctionRequest(request, options = {}) {
1907
2170
  const headers = new Headers();
1908
2171
  const dispatch = async () => {
1909
2172
  try {
1910
- let invocations = 0;
1911
2173
  const invokeOnce = async () => {
1912
2174
  INVOCATIONS.set(event, {
1913
2175
  id: functionId
@@ -1921,15 +2183,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1921
2183
  direct: false
1922
2184
  }) : run();
1923
2185
  };
1924
- let result = await provide(event, () => {
1925
- if (++invocations > 1) {
1926
- 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.");
1927
- }
1928
- return invokeOnce();
1929
- });
1930
- if (invocations !== 1) {
1931
- 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.");
1932
- }
2186
+ let result = await provideEventOnce(provide, event, invokeOnce);
1933
2187
  if (transformResult) {
1934
2188
  result = await transformResult(event, result, flightContext);
1935
2189
  }
@@ -1981,7 +2235,9 @@ async function handleServerFunctionRequest(request, options = {}) {
1981
2235
  if (result instanceof Response && result.headers.has("X-Content-Raw")) return result;
1982
2236
  }
1983
2237
  if (!scripted) {
1984
- if (handleNoJS) return handleNoJS(result ?? metadata, request, parsed);
2238
+ if (handleNoJS) {
2239
+ return handleNoJS(result == null && metadata !== undefined ? metadata : result, request, parsed);
2240
+ }
1985
2241
  if (result instanceof Response) return result;
1986
2242
  return encodeResult(result, headers, status, codec, request.signal, scope);
1987
2243
  }
@@ -2001,17 +2257,17 @@ async function handleServerFunctionRequest(request, options = {}) {
2001
2257
  headers.set(ERROR_HEADER, boundedErrorHeaderValue(error));
2002
2258
  return encodeResult(safe, headers, 500, codec, request.signal, scope);
2003
2259
  };
2004
- if (x instanceof Response || isResponseEnvelope(x)) {
2005
- if (transformResult) {
2006
- try {
2007
- x = await transformResult(event, x, {
2008
- ...flightContext,
2009
- thrown: true
2010
- });
2011
- } catch (hookError) {
2012
- return respondThrown(hookError);
2013
- }
2260
+ if (transformResult) {
2261
+ try {
2262
+ x = await transformResult(event, x, {
2263
+ ...flightContext,
2264
+ thrown: true
2265
+ });
2266
+ } catch (hookError) {
2267
+ return respondThrown(hookError);
2014
2268
  }
2269
+ }
2270
+ if (x instanceof Response || isResponseEnvelope(x)) {
2015
2271
  let status = 200;
2016
2272
  let metadata;
2017
2273
  if (isResponseEnvelope(x)) {