@solidjs/web 2.0.0-rc.6 → 2.0.0-rc.8

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 (82) hide show
  1. package/dist/{server.cjs → server.dev.js} +274 -272
  2. package/dist/server.js +119 -36
  3. package/dist/{dev.js → web.dev.js} +131 -399
  4. package/dist/web.js +78 -388
  5. package/dist/{web.cjs → web.observe.js} +174 -622
  6. package/frames/dist/client.dev.js +11 -3
  7. package/frames/dist/client.js +11 -3
  8. package/frames/dist/{server.cjs → server.dev.js} +375 -125
  9. package/frames/dist/server.js +253 -32
  10. package/frames/package.json +7 -15
  11. package/package.json +88 -251
  12. package/serialization/decode/package.json +3 -9
  13. package/serialization/dist/decode.js +18 -4
  14. package/serialization/dist/serialization.js +18 -4
  15. package/serialization/package.json +3 -9
  16. package/serialization/types/serializer-decode.d.ts +49 -2
  17. package/server-functions/dist/client.js +13 -14
  18. package/server-functions/dist/server.dev.js +359 -85
  19. package/server-functions/dist/server.js +352 -86
  20. package/server-functions/package.json +6 -24
  21. package/server-functions/rich-args/package.json +3 -9
  22. package/storage/package.json +3 -9
  23. package/types/client.d.ts +17 -3
  24. package/types/frames/frame-client.d.ts +1 -1
  25. package/types/frames/serializer-decode.d.ts +49 -2
  26. package/types/head.d.ts +3 -0
  27. package/types/index.d.ts +18 -7
  28. package/types/index.server.d.ts +31 -9
  29. package/types/render.d.ts +3 -1
  30. package/types/serializer-decode.d.ts +49 -2
  31. package/types/server-functions/flash.d.ts +12 -3
  32. package/types/server-functions/server.d.ts +50 -3
  33. package/types/server-mock.d.ts +43 -7
  34. package/types/server.d.ts +48 -6
  35. package/dist/dev.cjs +0 -2590
  36. package/frames/dist/client.cjs +0 -2035
  37. package/frames/dist/client.dev.cjs +0 -2055
  38. package/serialization/dist/decode.cjs +0 -141
  39. package/serialization/dist/serialization.cjs +0 -261
  40. package/serialization/types-cjs/index.d.cts +0 -101
  41. package/serialization/types-cjs/package.json +0 -3
  42. package/serialization/types-cjs/serializer-decode.d.cts +0 -172
  43. package/serialization/types-cjs/serializer.d.cts +0 -101
  44. package/server-functions/dist/client.cjs +0 -1070
  45. package/server-functions/dist/rich-args.cjs +0 -11
  46. package/server-functions/dist/server.cjs +0 -2133
  47. package/server-functions/dist/server.dev.cjs +0 -2153
  48. package/storage/dist/storage.cjs +0 -12
  49. package/storage/types-cjs/index.d.cts +0 -28
  50. package/storage/types-cjs/package.json +0 -3
  51. package/types/patch-driver.d.ts +0 -3
  52. package/types-cjs/client.d.cts +0 -200
  53. package/types-cjs/constants.d.cts +0 -20
  54. package/types-cjs/cookies.d.cts +0 -41
  55. package/types-cjs/frames/client.d.cts +0 -36
  56. package/types-cjs/frames/frame-client.d.cts +0 -370
  57. package/types-cjs/frames/frame-container-plugin.d.cts +0 -71
  58. package/types-cjs/frames/frame-sink.d.cts +0 -92
  59. package/types-cjs/frames/frame-transport.d.cts +0 -189
  60. package/types-cjs/frames/serializer-decode.d.cts +0 -172
  61. package/types-cjs/frames/serializer.d.cts +0 -101
  62. package/types-cjs/frames/server.d.cts +0 -52
  63. package/types-cjs/head.d.cts +0 -16
  64. package/types-cjs/index.d.cts +0 -180
  65. package/types-cjs/index.server.d.cts +0 -125
  66. package/types-cjs/jsx-properties.d.cts +0 -93
  67. package/types-cjs/jsx.d.cts +0 -4146
  68. package/types-cjs/package.json +0 -3
  69. package/types-cjs/patch-driver.d.cts +0 -3
  70. package/types-cjs/reconcile.d.cts +0 -1
  71. package/types-cjs/render.d.cts +0 -4
  72. package/types-cjs/response.d.cts +0 -81
  73. package/types-cjs/serializer-decode.d.cts +0 -172
  74. package/types-cjs/serializer.d.cts +0 -101
  75. package/types-cjs/server-functions/client.d.cts +0 -184
  76. package/types-cjs/server-functions/flash.d.cts +0 -27
  77. package/types-cjs/server-functions/registry.d.cts +0 -100
  78. package/types-cjs/server-functions/rich-args.d.cts +0 -1
  79. package/types-cjs/server-functions/server.d.cts +0 -522
  80. package/types-cjs/server-functions/shared.d.cts +0 -283
  81. package/types-cjs/server-mock.d.cts +0 -301
  82. package/types-cjs/server.d.cts +0 -366
@@ -247,7 +247,7 @@ function isJSONSafe(value) {
247
247
  const t = typeof v;
248
248
  if (t === "string" || t === "boolean") continue;
249
249
  if (t === "number") {
250
- if (!Number.isFinite(v)) return false;
250
+ if (!Number.isFinite(v) || Object.is(v, -0)) return false;
251
251
  continue;
252
252
  }
253
253
  if (t !== "object") return false;
@@ -333,31 +333,30 @@ function getHeadersAndBody(body) {
333
333
  async function extractBody(source, codecOptions) {
334
334
  const contentType = source.headers.get("content-type");
335
335
  const format = source.headers.get(BODY_FORMAT_HEADER);
336
- const clone = source.clone();
337
336
  switch (true) {
338
337
  case format === BodyFormat.Serialized:
339
- return await deserializeStream(clone, codecOptions);
338
+ return await deserializeStream(source, codecOptions);
340
339
  case format === BodyFormat.Json:
341
- return JSON.parse(await clone.text());
340
+ return JSON.parse(await source.text());
342
341
  case format === BodyFormat.String:
343
- return await clone.text();
342
+ return await source.text();
344
343
  case format === BodyFormat.File:
345
344
  {
346
- const formData = await clone.formData();
345
+ const formData = await source.formData();
347
346
  return formData.get(FILE_FORM_KEY);
348
347
  }
349
348
  case format === BodyFormat.FormData:
350
349
  case contentType && contentType.startsWith("multipart/form-data"):
351
- return await clone.formData();
350
+ return await source.formData();
352
351
  case format === BodyFormat.URLSearchParams:
353
352
  case contentType && contentType.startsWith("application/x-www-form-urlencoded"):
354
- return new URLSearchParams(await clone.text());
353
+ return new URLSearchParams(await source.text());
355
354
  case format === BodyFormat.Blob:
356
- return await clone.blob();
355
+ return await source.blob();
357
356
  case format === BodyFormat.ArrayBuffer:
358
- return await clone.arrayBuffer();
357
+ return await source.arrayBuffer();
359
358
  case format === BodyFormat.Uint8Array:
360
- return new Uint8Array(await clone.arrayBuffer());
359
+ return new Uint8Array(await source.arrayBuffer());
361
360
  }
362
361
  return undefined;
363
362
  }
@@ -493,7 +492,7 @@ async function deserializeString(text, codecOptions) {
493
492
  }
494
493
  async function decodeResponse(response, codecOptions) {
495
494
  if (!response.body) return undefined;
496
- return await extractBody(response, codecOptions === undefined ? codecConfig.codec : codecOptions);
495
+ return await extractBody(response.clone(), codecOptions === undefined ? codecConfig.codec : codecOptions);
497
496
  }
498
497
  async function decodeResponsePayload(response, codecOptions) {
499
498
  const decoded = await decodeResponse(response, codecOptions);
@@ -573,6 +572,70 @@ function commitEventResponse(response, event = getRequestEvent()) {
573
572
  });
574
573
  }
575
574
 
575
+ let configuredSecret;
576
+ function setFlashSecret(secret) {
577
+ configuredSecret = secret;
578
+ }
579
+ function resolveSecret() {
580
+ return configuredSecret !== undefined ? configuredSecret : globalThis.__SOLID_SECRET__;
581
+ }
582
+ const FLASH_KEY_DOMAIN = "solid.flash.v1\0";
583
+ const FLASH_KEY_ITERATIONS = 100_000;
584
+ let cachedSecret;
585
+ let cachedKey;
586
+ function resolveFlashKey() {
587
+ const secret = resolveSecret();
588
+ if (typeof secret !== "string" || secret.length === 0) return null;
589
+ if (secret !== cachedSecret) {
590
+ cachedSecret = secret;
591
+ const encoder = new TextEncoder();
592
+ cachedKey = crypto.subtle.importKey("raw", encoder.encode(secret), "PBKDF2", false, ["deriveKey"]).then(material => crypto.subtle.deriveKey({
593
+ name: "PBKDF2",
594
+ salt: encoder.encode(FLASH_KEY_DOMAIN),
595
+ iterations: FLASH_KEY_ITERATIONS,
596
+ hash: "SHA-256"
597
+ }, material, {
598
+ name: "AES-GCM",
599
+ length: 256
600
+ }, false, ["encrypt", "decrypt"]));
601
+ }
602
+ return cachedKey;
603
+ }
604
+ const FLASH_FORMAT_VERSION = "1.";
605
+ const IV_BYTES = 12;
606
+ const GCM_TAG_BYTES = 16;
607
+ function toBase64url(bytes) {
608
+ let binary = "";
609
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
610
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
611
+ }
612
+ function fromBase64url(text) {
613
+ const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/"));
614
+ const bytes = new Uint8Array(binary.length);
615
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
616
+ return bytes;
617
+ }
618
+ async function encryptFlashValue(key, json) {
619
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
620
+ const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
621
+ name: "AES-GCM",
622
+ iv
623
+ }, key, new TextEncoder().encode(json)));
624
+ const packed = new Uint8Array(IV_BYTES + ciphertext.length);
625
+ packed.set(iv);
626
+ packed.set(ciphertext, IV_BYTES);
627
+ return FLASH_FORMAT_VERSION + toBase64url(packed);
628
+ }
629
+ async function decryptFlashValue(key, value) {
630
+ if (!value.startsWith(FLASH_FORMAT_VERSION)) return;
631
+ const packed = fromBase64url(value.slice(FLASH_FORMAT_VERSION.length));
632
+ if (packed.length <= IV_BYTES + GCM_TAG_BYTES) return;
633
+ const plain = await crypto.subtle.decrypt({
634
+ name: "AES-GCM",
635
+ iv: packed.subarray(0, IV_BYTES)
636
+ }, key, packed.subarray(IV_BYTES));
637
+ return new TextDecoder().decode(plain);
638
+ }
576
639
  function encodeInputValue(value) {
577
640
  if (value instanceof FormData) return {
578
641
  $f: [...value.entries()].filter(([, v]) => typeof v === "string")
@@ -593,7 +656,11 @@ function decodeInputValue(value) {
593
656
  }
594
657
  return value;
595
658
  }
596
- function encodeFlashCookie(url, result, input, thrown) {
659
+ async function encodeFlashCookie(url, result, input, thrown) {
660
+ const key = resolveFlashKey();
661
+ if (!key) {
662
+ return null;
663
+ }
597
664
  const isError = result instanceof Error;
598
665
  const payload = {
599
666
  url,
@@ -602,7 +669,7 @@ function encodeFlashCookie(url, result, input, thrown) {
602
669
  thrown: !!thrown,
603
670
  input: input.map(encodeInputValue)
604
671
  };
605
- if (fitsCookie(payload)) return flashCookie(payload);
672
+ if (fitsCookie(payload)) return flashCookie(payload, await key);
606
673
  payload.truncated = true;
607
674
  payload.input = [];
608
675
  if (!fitsCookie(payload)) {
@@ -619,24 +686,35 @@ function encodeFlashCookie(url, result, input, thrown) {
619
686
  payload.result = true;
620
687
  }
621
688
  }
622
- return flashCookie(payload);
689
+ if (!fitsCookie(payload)) return null;
690
+ return flashCookie(payload, await key);
623
691
  }
624
- function flashCookie(payload) {
625
- return serializeCookie(FLASH_COOKIE, JSON.stringify(payload), {
692
+ const FLASH_MAX_AGE_SECONDS = 60;
693
+ async function flashCookie(payload, key) {
694
+ return serializeCookie(FLASH_COOKIE, await encryptFlashValue(key, JSON.stringify(payload)), {
626
695
  secure: true,
627
- httpOnly: true
696
+ httpOnly: true,
697
+ sameSite: "lax",
698
+ maxAge: FLASH_MAX_AGE_SECONDS
628
699
  });
629
700
  }
630
701
  const COOKIE_PAIR_BUDGET = 4000;
631
702
  function fitsCookie(payload) {
632
- return FLASH_COOKIE.length + 1 + encodeURIComponent(JSON.stringify(payload)).length <= COOKIE_PAIR_BUDGET;
703
+ const plaintextBytes = new TextEncoder().encode(JSON.stringify(payload)).length;
704
+ const packedBytes = IV_BYTES + plaintextBytes + GCM_TAG_BYTES;
705
+ const valueLength = FLASH_FORMAT_VERSION.length + Math.ceil(packedBytes * 4 / 3);
706
+ return FLASH_COOKIE.length + 1 + valueLength <= COOKIE_PAIR_BUDGET;
633
707
  }
634
- function decodeFlashCookie(cookieHeader) {
708
+ async function decodeFlashCookie(cookieHeader) {
635
709
  const match = parseCookieHeader(cookieHeader)[FLASH_COOKIE];
636
710
  if (!match) return;
637
711
  try {
638
- const payload = JSON.parse(match);
639
- if (!payload || !payload.result) return;
712
+ const key = resolveFlashKey();
713
+ if (!key) return;
714
+ const json = await decryptFlashValue(await key, match);
715
+ if (json === undefined) return;
716
+ const payload = JSON.parse(json);
717
+ if (!payload || typeof payload !== "object" || !("result" in payload)) return;
640
718
  const result = payload.error ? new Error(payload.result) : payload.result;
641
719
  const submission = {
642
720
  input: Array.isArray(payload.input) ? payload.input.map(decodeInputValue) : [],
@@ -647,7 +725,6 @@ function decodeFlashCookie(cookieHeader) {
647
725
  if (payload.truncated) submission.truncated = true;
648
726
  return submission;
649
727
  } catch (error) {
650
- console.error(error);
651
728
  }
652
729
  }
653
730
 
@@ -676,7 +753,8 @@ function configureServerFunctionsServer({
676
753
  csrf,
677
754
  codec,
678
755
  bodySizeLimit,
679
- maxArguments
756
+ maxArguments,
757
+ secret
680
758
  } = {}) {
681
759
  if (provideEvent !== undefined) config.provideEvent = provideEvent;
682
760
  if (wrapInvocation !== undefined) config.wrapInvocation = wrapInvocation;
@@ -690,6 +768,7 @@ function configureServerFunctionsServer({
690
768
  if (codec !== undefined) configureServerFunctionsCodec(codec);
691
769
  if (bodySizeLimit !== undefined) config.bodySizeLimit = bodySizeLimit;
692
770
  if (maxArguments !== undefined) config.maxArguments = maxArguments;
771
+ if (secret !== undefined) setFlashSecret(secret);
693
772
  }
694
773
  const flightSources = new Map();
695
774
  function registerFlightDataSource(source, hook) {
@@ -699,13 +778,146 @@ function registerFlightDataSource(source, hook) {
699
778
  if (flightSources.get(source) === hook) flightSources.delete(source);
700
779
  };
701
780
  }
781
+ function resolveWrapInvocation(hook) {
782
+ if (hook === undefined || typeof hook === "function") return hook;
783
+ 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.`);
784
+ }
702
785
  function provideEvent(event, fn) {
703
786
  if (config.provideEvent) return config.provideEvent(event, fn);
704
787
  const ctx = globalThis[RequestContext];
705
788
  if (ctx) return ctx.run(event, fn);
706
789
  throw new Error("No request event provider. Configure one with configureServerFunctionsServer({ provideEvent }).");
707
790
  }
791
+ 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.";
792
+ 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.";
793
+ function provideEventOnce(provide, event, run) {
794
+ let invocations = 0;
795
+ const settle = () => {
796
+ if (invocations !== 1) throw new Error(invocations === 0 ? PROVIDE_EVENT_NEVER : PROVIDE_EVENT_TWICE);
797
+ };
798
+ const result = provide(event, () => {
799
+ if (++invocations > 1) throw new Error(PROVIDE_EVENT_TWICE);
800
+ return run();
801
+ });
802
+ const promised = nativePromise(result);
803
+ if (promised) {
804
+ return promised.then(value => {
805
+ settle();
806
+ return value;
807
+ });
808
+ }
809
+ settle();
810
+ return result;
811
+ }
708
812
  function scopeDeferredResult(value, scope) {
813
+ const bound = bindDeferredBody(value, scope);
814
+ if (bound !== value || value === null || typeof value !== "object") return bound;
815
+ return scopeDeferredContents(value, scope);
816
+ }
817
+ class ScopeFrame {
818
+ constructor(value, next, keys, descriptors) {
819
+ this.value = value;
820
+ this.next = next;
821
+ this.keys = keys;
822
+ this.descriptors = descriptors;
823
+ this.i = 0;
824
+ this.changed = false;
825
+ }
826
+ }
827
+ function enterScopeCarrier(value, state) {
828
+ if (value === null || typeof value !== "object" && typeof value !== "function") return value;
829
+ if (state.seen.has(value)) {
830
+ state.cyclic.add(value);
831
+ return state.seen.get(value);
832
+ }
833
+ const bound = bindDeferredBody(value, state.scope);
834
+ if (bound !== value) {
835
+ state.seen.set(value, bound);
836
+ return bound;
837
+ }
838
+ if (typeof value !== "object") return value;
839
+ if (Array.isArray(value)) {
840
+ if (Object.isFrozen(value)) {
841
+ state.seen.set(value, value);
842
+ return value;
843
+ }
844
+ const next = value.slice();
845
+ state.seen.set(value, next);
846
+ return new ScopeFrame(value, next, null, null);
847
+ }
848
+ const prototype = Object.getPrototypeOf(value);
849
+ if (prototype !== Object.prototype && prototype !== null || Object.isFrozen(value)) {
850
+ state.seen.set(value, value);
851
+ return value;
852
+ }
853
+ const descriptors = Object.getOwnPropertyDescriptors(value);
854
+ const next = Object.create(prototype, descriptors);
855
+ state.seen.set(value, next);
856
+ return new ScopeFrame(value, next, Object.keys(value), descriptors);
857
+ }
858
+ function scopeDeferredContents(root, scope) {
859
+ const state = {
860
+ seen: new Map(),
861
+ cyclic: new Set(),
862
+ scope
863
+ };
864
+ const entered = enterScopeCarrier(root, state);
865
+ if (!(entered instanceof ScopeFrame)) return entered;
866
+ const stack = [entered];
867
+ let delivered = NOTHING;
868
+ for (;;) {
869
+ const top = stack[stack.length - 1];
870
+ const length = top.keys ? top.keys.length : top.value.length;
871
+ let pushed = null;
872
+ while (top.i < length) {
873
+ const i = top.i;
874
+ let original;
875
+ let writable = true;
876
+ if (top.keys) {
877
+ const descriptor = top.descriptors[top.keys[i]];
878
+ writable = "value" in descriptor && descriptor.writable === true;
879
+ original = writable ? descriptor.value : undefined;
880
+ } else {
881
+ original = top.value[i];
882
+ }
883
+ if (!writable) {
884
+ top.i++;
885
+ continue;
886
+ }
887
+ let bound;
888
+ if (delivered !== NOTHING) {
889
+ bound = delivered;
890
+ delivered = NOTHING;
891
+ } else {
892
+ bound = enterScopeCarrier(original, state);
893
+ if (bound instanceof ScopeFrame) {
894
+ pushed = bound;
895
+ break;
896
+ }
897
+ }
898
+ if (bound !== original) {
899
+ if (top.keys) top.next[top.keys[i]] = bound;else top.next[i] = bound;
900
+ top.changed = true;
901
+ }
902
+ top.i++;
903
+ }
904
+ if (pushed !== null) {
905
+ stack.push(pushed);
906
+ continue;
907
+ }
908
+ stack.pop();
909
+ let out;
910
+ if (top.changed || state.cyclic.has(top.value)) {
911
+ out = top.next;
912
+ } else {
913
+ state.seen.set(top.value, top.value);
914
+ out = top.value;
915
+ }
916
+ if (stack.length === 0) return out;
917
+ delivered = out;
918
+ }
919
+ }
920
+ function bindDeferredBody(value, scope) {
709
921
  if (value === null || typeof value !== "object" && typeof value !== "function") return value;
710
922
  const promised = scope(() => nativePromise(value));
711
923
  if (promised) {
@@ -751,8 +963,17 @@ function scopeDeferredResult(value, scope) {
751
963
  }
752
964
  return value;
753
965
  }
754
- const REGISTRATIONS = new Map();
755
- const METHODS = new Map();
966
+ function processState(key, create) {
967
+ const slot = Symbol.for(key);
968
+ return globalThis[slot] || (globalThis[slot] = create());
969
+ }
970
+ const REGISTRATIONS = processState("solid.ServerFunctionRegistrations", () => new Map());
971
+ const METHODS = processState("solid.ServerFunctionMethods", () => new Map());
972
+ const REFERENCE_BINDINGS = processState("solid.ServerFunctionReferenceBindings", () => new WeakMap());
973
+ function declaresRead(id) {
974
+ const granted = METHODS.get(id);
975
+ return granted !== undefined && granted === REGISTRATIONS.get(id);
976
+ }
756
977
  const INVOCATIONS = new WeakMap();
757
978
  let rpcProvided = false;
758
979
  function provideRPC() {
@@ -849,9 +1070,10 @@ function createServerReference({
849
1070
  });
850
1071
  evt.serverOnly = true;
851
1072
  const scope = run => provideEvent(evt, run);
852
- let result = provideEvent(evt, () => {
1073
+ const wrap = resolveWrapInvocation(config.wrapInvocation);
1074
+ let result = provideEventOnce(provideEvent, evt, () => {
853
1075
  const run = () => fn.apply(thisArg, args);
854
- return config.wrapInvocation ? config.wrapInvocation(run, {
1076
+ return wrap ? wrap(run, {
855
1077
  id,
856
1078
  args,
857
1079
  event: evt,
@@ -874,16 +1096,45 @@ function createServerReference({
874
1096
  }), scope) : result;
875
1097
  }
876
1098
  });
1099
+ REFERENCE_BINDINGS.set(proxy, fn);
877
1100
  return proxy;
878
1101
  }
879
1102
  function GET(fn) {
880
1103
  if (!isServerFunction(fn) || typeof fn.id !== "string") {
881
1104
  throw new Error("GET expects a server function reference");
882
1105
  }
883
- METHODS.set(fn.id, "GET");
884
- return withMeta(fn, {
1106
+ const id = fn.id;
1107
+ const binding = REFERENCE_BINDINGS.has(fn) ? REFERENCE_BINDINGS.get(fn) : REGISTRATIONS.get(id);
1108
+ const existing = METHODS.get(id);
1109
+ if (existing !== undefined && existing !== binding) {
1110
+ if (DEV) {
1111
+ 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.`);
1112
+ }
1113
+ METHODS.delete(id);
1114
+ return fn;
1115
+ }
1116
+ METHODS.set(id, binding);
1117
+ const reference = withMeta(fn, {
885
1118
  method: "GET"
886
1119
  });
1120
+ guardDeclaredMethod(getServerFunctionMetadata(reference), id);
1121
+ return reference;
1122
+ }
1123
+ function guardDeclaredMethod(metadata, id) {
1124
+ let declared = metadata.method;
1125
+ Object.defineProperty(metadata, "method", {
1126
+ configurable: true,
1127
+ enumerable: true,
1128
+ get: () => declared,
1129
+ set(next) {
1130
+ if (next === declared) return;
1131
+ if (DEV) {
1132
+ 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.`);
1133
+ }
1134
+ METHODS.delete(id);
1135
+ declared = next;
1136
+ }
1137
+ });
887
1138
  }
888
1139
  function live(fn) {
889
1140
  if (!isServerFunction(fn) || typeof fn.id !== "string") {
@@ -996,10 +1247,23 @@ async function bufferBodyWithin(request, limit) {
996
1247
  body.set(chunk, offset);
997
1248
  offset += chunk.byteLength;
998
1249
  }
999
- return new Request(request, {
1250
+ return body;
1251
+ }
1252
+ function withBufferedBody(request, body) {
1253
+ return new Request(request.url, {
1254
+ method: request.method,
1255
+ headers: request.headers,
1256
+ signal: request.signal,
1000
1257
  body
1001
1258
  });
1002
1259
  }
1260
+ const KNOWN_BODY_FORMATS = new Set(Object.values(BodyFormat));
1261
+ const FORMAT_SKEW = Symbol("solid.serverFunction.formatSkew");
1262
+ function unknownFormatError(tag) {
1263
+ 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.");
1264
+ error[FORMAT_SKEW] = true;
1265
+ return error;
1266
+ }
1003
1267
  async function parseArguments(request, url, scripted, codec) {
1004
1268
  const parsed = [];
1005
1269
  const bodyFormat = request.method === "POST" ? request.headers.get(BODY_FORMAT_HEADER) : null;
@@ -1023,7 +1287,11 @@ async function parseArguments(request, url, scripted, codec) {
1023
1287
  parsed.push(url.searchParams);
1024
1288
  }
1025
1289
  if (request.method === "POST" && request.body !== null) {
1026
- const decoded = await extractBody(request.clone(), codec);
1290
+ if (bodyFormat !== null && !KNOWN_BODY_FORMATS.has(bodyFormat)) {
1291
+ throw unknownFormatError(bodyFormat);
1292
+ }
1293
+ const body = request.clone();
1294
+ const decoded = await extractBody(body, codec);
1027
1295
  if (bodyFormat === BodyFormat.Serialized || bodyFormat === BodyFormat.Json) {
1028
1296
  if (bodyFormat === BodyFormat.Json) assertDecodeDepth(decoded);
1029
1297
  if (!Array.isArray(decoded)) {
@@ -1032,7 +1300,7 @@ async function parseArguments(request, url, scripted, codec) {
1032
1300
  return stripUnsafeArgumentKeys(decoded);
1033
1301
  }
1034
1302
  if (decoded === undefined) {
1035
- if (bodyFormat === null && (await request.clone().arrayBuffer()).byteLength === 0) {
1303
+ if (bodyFormat === null && (await body.arrayBuffer()).byteLength === 0) {
1036
1304
  return parsed;
1037
1305
  }
1038
1306
  throw new TypeError("Server function body carries no usable encoding");
@@ -1062,13 +1330,14 @@ async function foldFlightData(hooks, event, headers, outcome, context = {}) {
1062
1330
  data
1063
1331
  }, context);
1064
1332
  if (transformed !== undefined) {
1065
- for (const cookie of headers.getSetCookie()) transformed.headers.append("Set-Cookie", cookie);
1333
+ const owned = ownResponse(transformed);
1334
+ for (const cookie of headers.getSetCookie()) owned.headers.append("Set-Cookie", cookie);
1066
1335
  headers.forEach((value, key) => {
1067
- if (key !== "set-cookie" && !transformed.headers.has(key)) {
1068
- transformed.headers.set(key, value);
1336
+ if (key !== "set-cookie" && !owned.headers.has(key)) {
1337
+ owned.headers.set(key, value);
1069
1338
  }
1070
1339
  });
1071
- return transformed;
1340
+ return owned;
1072
1341
  }
1073
1342
  }
1074
1343
  return outcome.value === undefined ? {
@@ -1189,7 +1458,7 @@ function warnScripted304(functionId) {
1189
1458
  function createNoJSHandler({
1190
1459
  base = ""
1191
1460
  } = {}) {
1192
- return function handleNoJS(result, request, args, thrown) {
1461
+ return async function handleNoJS(result, request, args, thrown) {
1193
1462
  const url = new URL(request.url);
1194
1463
  let back = new URL(base || "/", url.origin).toString();
1195
1464
  try {
@@ -1214,8 +1483,9 @@ function createNoJSHandler({
1214
1483
  Location: back
1215
1484
  });
1216
1485
  }
1217
- if (result && !(result instanceof Response)) {
1218
- headers.append("Set-Cookie", encodeFlashCookie(url.pathname + url.search, result, args, thrown));
1486
+ if (result !== undefined && !(result instanceof Response)) {
1487
+ const flash = await encodeFlashCookie(url.pathname, result, args, thrown);
1488
+ if (flash !== null) headers.append("Set-Cookie", flash);
1219
1489
  }
1220
1490
  return new Response(null, {
1221
1491
  status,
@@ -1453,7 +1723,7 @@ function enterGuard(value, state) {
1453
1723
  return new Frame(SET, value, next, [...value], null);
1454
1724
  }
1455
1725
  const prototype = Object.getPrototypeOf(value);
1456
- if (prototype !== Object.prototype && prototype !== null) {
1726
+ if (prototype !== Object.prototype && prototype !== null && !(value instanceof Error)) {
1457
1727
  state.seen.set(value, value);
1458
1728
  return value;
1459
1729
  }
@@ -1464,7 +1734,11 @@ function enterGuard(value, state) {
1464
1734
  }
1465
1735
  const next = Object.create(prototype, descriptors);
1466
1736
  state.seen.set(value, next);
1467
- return new Frame(OBJECT, value, next, Object.keys(value), descriptors);
1737
+ const children = !(value instanceof Error) ? Object.keys(value) : Object.getOwnPropertyNames(value).filter(key => {
1738
+ const descriptor = descriptors[key];
1739
+ return descriptor.enumerable || "value" in descriptor;
1740
+ });
1741
+ return new Frame(OBJECT, value, next, children, descriptors);
1468
1742
  }
1469
1743
  function keepGuarded(value, next, changed, state) {
1470
1744
  if (changed || state.cyclic.has(value)) return next;
@@ -1741,7 +2015,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1741
2015
  const method = request.method;
1742
2016
  const address = resolveAddress(url);
1743
2017
  const functionId = address && address.id;
1744
- const declaredRead = (method === "GET" || method === "HEAD") && functionId !== null && METHODS.get(functionId) === "GET";
2018
+ const declaredRead = (method === "GET" || method === "HEAD") && functionId !== null && declaresRead(functionId);
1745
2019
  const csrf = options.csrf !== undefined ? options.csrf : config.csrf;
1746
2020
  const protectsRequest = csrf !== false && (!declaredRead || typeof csrf === "object" && csrf.protectDeclaredReads === true);
1747
2021
  let serverFunction;
@@ -1772,7 +2046,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1772
2046
  const response = new Response(DEV ? `Method not allowed for server function: ${functionId}` : null, {
1773
2047
  status: 405,
1774
2048
  headers: {
1775
- Allow: METHODS.get(functionId) === "GET" ? "POST, GET, HEAD" : "POST"
2049
+ Allow: declaresRead(functionId) ? "POST, GET, HEAD" : "POST"
1776
2050
  }
1777
2051
  });
1778
2052
  return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
@@ -1794,24 +2068,22 @@ async function handleServerFunctionRequest(request, options = {}) {
1794
2068
  });
1795
2069
  return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1796
2070
  }
1797
- if (!(declared > 0)) {
1798
- let bounded;
1799
- try {
1800
- bounded = await bufferBodyWithin(request, bodySizeLimit);
1801
- } catch {
1802
- const response = new Response(DEV ? "Malformed server function arguments" : null, {
1803
- status: 400
1804
- });
1805
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1806
- }
1807
- if (bounded === null) {
1808
- const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
1809
- status: 413
1810
- });
1811
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1812
- }
1813
- request = bounded;
2071
+ let buffered;
2072
+ try {
2073
+ buffered = await bufferBodyWithin(request, bodySizeLimit);
2074
+ } catch {
2075
+ const response = new Response(DEV ? "Malformed server function arguments" : null, {
2076
+ status: 400
2077
+ });
2078
+ return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
1814
2079
  }
2080
+ if (buffered === null) {
2081
+ const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
2082
+ status: 413
2083
+ });
2084
+ return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2085
+ }
2086
+ request = withBufferedBody(request, buffered);
1815
2087
  }
1816
2088
  let event;
1817
2089
  try {
@@ -1839,7 +2111,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1839
2111
  const scope = run => provide(event, run);
1840
2112
  const flightHook = options.collectFlightData !== undefined ? options.collectFlightData : config.collectFlightData;
1841
2113
  const transformResult = options.transformResult !== undefined ? options.transformResult : config.transformResult;
1842
- const wrapInvocation = options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation;
2114
+ const wrapInvocation = resolveWrapInvocation(options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation);
1843
2115
  const transformFlightResult = options.transformFlightResult !== undefined ? options.transformFlightResult : config.transformFlightResult;
1844
2116
  let handleNoJS = options.handleNoJS !== undefined ? options.handleNoJS : config.handleNoJS;
1845
2117
  if (handleNoJS === undefined && !scripted && isFormPost(request)) {
@@ -1854,7 +2126,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1854
2126
  }
1855
2127
  }
1856
2128
  const flightHeader = scripted && method === "POST" ? request.headers.get(SINGLE_FLIGHT_HEADER) : null;
1857
- const flightHooks = flightHeader ? flightHeader.split(",").flatMap(source => {
2129
+ const flightHooks = flightHeader ? [...new Set(flightHeader.split(","))].flatMap(source => {
1858
2130
  const hook = source === "true" ? flightHook : flightSources.get(source);
1859
2131
  return hook ? [[source, hook]] : [];
1860
2132
  }) : [];
@@ -1862,8 +2134,9 @@ async function handleServerFunctionRequest(request, options = {}) {
1862
2134
  let parsed;
1863
2135
  try {
1864
2136
  parsed = await parseArguments(request, url, scripted, codec);
1865
- } catch {
1866
- const response = new Response(DEV ? "Malformed server function arguments" : null, {
2137
+ } catch (error) {
2138
+ const skewed = error !== null && typeof error === "object" && error[FORMAT_SKEW] === true;
2139
+ const response = new Response(DEV ? skewed ? error.message : "Malformed server function arguments" : null, {
1867
2140
  status: 400
1868
2141
  });
1869
2142
  return refuseCommitted(response);
@@ -1887,7 +2160,6 @@ async function handleServerFunctionRequest(request, options = {}) {
1887
2160
  const headers = new Headers();
1888
2161
  const dispatch = async () => {
1889
2162
  try {
1890
- let invocations = 0;
1891
2163
  const invokeOnce = async () => {
1892
2164
  INVOCATIONS.set(event, {
1893
2165
  id: functionId
@@ -1901,15 +2173,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1901
2173
  direct: false
1902
2174
  }) : run();
1903
2175
  };
1904
- let result = await provide(event, () => {
1905
- if (++invocations > 1) {
1906
- 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.");
1907
- }
1908
- return invokeOnce();
1909
- });
1910
- if (invocations !== 1) {
1911
- 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.");
1912
- }
2176
+ let result = await provideEventOnce(provide, event, invokeOnce);
1913
2177
  if (transformResult) {
1914
2178
  result = await transformResult(event, result, flightContext);
1915
2179
  }
@@ -1961,7 +2225,9 @@ async function handleServerFunctionRequest(request, options = {}) {
1961
2225
  if (result instanceof Response && result.headers.has("X-Content-Raw")) return result;
1962
2226
  }
1963
2227
  if (!scripted) {
1964
- if (handleNoJS) return handleNoJS(result ?? metadata, request, parsed);
2228
+ if (handleNoJS) {
2229
+ return handleNoJS(result == null && metadata !== undefined ? metadata : result, request, parsed);
2230
+ }
1965
2231
  if (result instanceof Response) return result;
1966
2232
  return encodeResult(result, headers, status, codec, request.signal, scope);
1967
2233
  }
@@ -1981,17 +2247,17 @@ async function handleServerFunctionRequest(request, options = {}) {
1981
2247
  headers.set(ERROR_HEADER, boundedErrorHeaderValue(error));
1982
2248
  return encodeResult(safe, headers, 500, codec, request.signal, scope);
1983
2249
  };
1984
- if (x instanceof Response || isResponseEnvelope(x)) {
1985
- if (transformResult) {
1986
- try {
1987
- x = await transformResult(event, x, {
1988
- ...flightContext,
1989
- thrown: true
1990
- });
1991
- } catch (hookError) {
1992
- return respondThrown(hookError);
1993
- }
2250
+ if (transformResult) {
2251
+ try {
2252
+ x = await transformResult(event, x, {
2253
+ ...flightContext,
2254
+ thrown: true
2255
+ });
2256
+ } catch (hookError) {
2257
+ return respondThrown(hookError);
1994
2258
  }
2259
+ }
2260
+ if (x instanceof Response || isResponseEnvelope(x)) {
1995
2261
  let status = 200;
1996
2262
  let metadata;
1997
2263
  if (isResponseEnvelope(x)) {