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

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 (36) hide show
  1. package/dist/server.dev.js +626 -125
  2. package/dist/server.js +433 -95
  3. package/dist/server.observe.js +3980 -0
  4. package/dist/web.dev.js +208 -60
  5. package/dist/web.js +175 -58
  6. package/dist/web.observe.js +175 -58
  7. package/frames/dist/client.dev.js +103 -4
  8. package/frames/dist/client.js +5 -2
  9. package/frames/dist/client.observe.js +2123 -0
  10. package/frames/dist/server.dev.js +521 -79
  11. package/frames/dist/server.js +352 -52
  12. package/frames/dist/server.observe.js +4946 -0
  13. package/frames/package.json +12 -0
  14. package/package.json +87 -3
  15. package/server-functions/dist/client.dev.js +1102 -0
  16. package/server-functions/dist/client.js +74 -69
  17. package/server-functions/dist/client.observe.js +1102 -0
  18. package/server-functions/dist/server.dev.js +402 -31
  19. package/server-functions/dist/server.js +339 -30
  20. package/server-functions/dist/server.observe.js +2726 -0
  21. package/server-functions/package.json +12 -0
  22. package/types/client.d.ts +22 -1
  23. package/types/diagnostics.d.ts +24 -0
  24. package/types/frames/frame-transport.d.ts +1 -1
  25. package/types/index.d.ts +25 -15
  26. package/types/index.server.d.ts +35 -8
  27. package/types/jsx.d.ts +15 -4
  28. package/types/observe.d.ts +294 -0
  29. package/types/response.d.ts +18 -0
  30. package/types/server-functions/client.d.ts +32 -22
  31. package/types/server-functions/server.d.ts +28 -37
  32. package/types/server-functions/shared.d.ts +39 -9
  33. package/types/server-mock.d.ts +26 -4
  34. package/types/server-observe.d.ts +39 -0
  35. package/types/server.d.ts +104 -5
  36. package/types/trace.d.ts +79 -0
@@ -1,4 +1,5 @@
1
- import { sharedConfig } from 'solid-js';
1
+ import { OBSERVE, getOwner, DEV as DEV$1, sharedConfig } from 'solid-js';
2
+ import { reportServerError } from 'solid-js/internal';
2
3
 
3
4
  const COMPOSED_BODY_FRAMING = /*#__PURE__*/new Set(["content-length", "content-encoding", "transfer-encoding"]);
4
5
  function isHttpNavigationTarget(target) {
@@ -22,6 +23,164 @@ const REVALIDATE_HEADER = "X-Revalidate";
22
23
  const RESPONSE_HEADER_VALUE_LIMIT = 4096;
23
24
  const NULL_BODY_STATUSES = new Set([204, 205, 304]);
24
25
 
26
+ const PROVIDER = Symbol.for("solid-js/observe/server/provider");
27
+ function currentProvider() {
28
+ if (OBSERVE === undefined) return undefined;
29
+ const slot = OBSERVE.server.trace;
30
+ return slot && slot[PROVIDER];
31
+ }
32
+ const TRACEPARENT = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;
33
+ const ZERO_TRACE = "00000000000000000000000000000000";
34
+ const ZERO_SPAN = "0000000000000000";
35
+ function parseTraceparent(value) {
36
+ if (!value) return undefined;
37
+ const m = TRACEPARENT.exec(value.trim());
38
+ if (!m) return undefined;
39
+ const [, version, traceId, parentId, flags, rest] = m;
40
+ if (version === "ff") return undefined;
41
+ if (version === "00" && rest !== undefined) return undefined;
42
+ if (traceId === ZERO_TRACE || parentId === ZERO_SPAN) return undefined;
43
+ return {
44
+ traceId,
45
+ parentId,
46
+ sampled: (parseInt(flags, 16) & 1) === 1
47
+ };
48
+ }
49
+ function randomHex(bytes) {
50
+ const buffer = new Uint8Array(bytes);
51
+ crypto.getRandomValues(buffer);
52
+ let out = "";
53
+ for (let i = 0; i < buffer.length; i++) out += (buffer[i] < 16 ? "0" : "") + buffer[i].toString(16);
54
+ return out;
55
+ }
56
+ function randomTraceId() {
57
+ let id = randomHex(16);
58
+ while (id === ZERO_TRACE) id = randomHex(16);
59
+ return id;
60
+ }
61
+ function randomSpanId() {
62
+ let id = randomHex(8);
63
+ while (id === ZERO_SPAN) id = randomHex(8);
64
+ return id;
65
+ }
66
+ function formatTraceparent(context) {
67
+ return `00-${context.traceId}-${context.spanId}-${context.sampled === true ? "01" : "00"}`;
68
+ }
69
+ const RECORDS_KEY = Symbol.for("@solidjs/web/trace/records");
70
+ function records$1() {
71
+ const g = globalThis;
72
+ return g[RECORDS_KEY] || (g[RECORDS_KEY] = new WeakMap());
73
+ }
74
+ function traceFor(key, request) {
75
+ const store = records$1();
76
+ let record = store.get(key);
77
+ if (record) return record;
78
+ const headers = request ? request.headers : undefined;
79
+ const incoming = headers ? parseTraceparent(headers.get("traceparent")) : undefined;
80
+ const context = {
81
+ traceId: incoming ? incoming.traceId : randomTraceId(),
82
+ spanId: randomSpanId(),
83
+ entries: {}
84
+ };
85
+ if (incoming) {
86
+ context.parentId = incoming.parentId;
87
+ context.sampled = incoming.sampled;
88
+ }
89
+ if (headers) {
90
+ const state = headers.get("tracestate");
91
+ if (state) context.state = state;
92
+ const baggage = headers.get("baggage");
93
+ if (baggage) context.baggage = baggage;
94
+ }
95
+ let answered = false;
96
+ let providedEntries;
97
+ {
98
+ const provider = currentProvider();
99
+ if (provider) {
100
+ let answer;
101
+ try {
102
+ answer = provider(request);
103
+ } catch (error) {
104
+ console.error(error);
105
+ }
106
+ if (answer !== undefined && answer !== null) {
107
+ answered = true;
108
+ if (answer.traceId !== undefined) context.traceId = answer.traceId;
109
+ if (answer.spanId !== undefined) context.spanId = answer.spanId;
110
+ if (answer.parentId !== undefined) context.parentId = answer.parentId;
111
+ if (answer.sampled !== undefined) context.sampled = answer.sampled;
112
+ if (answer.state !== undefined) context.state = answer.state;
113
+ if (answer.baggage !== undefined) context.baggage = answer.baggage;
114
+ providedEntries = answer.entries;
115
+ }
116
+ }
117
+ }
118
+ context.entries.traceparent = formatTraceparent(context);
119
+ if (providedEntries) Object.assign(context.entries, providedEntries);
120
+ record = {
121
+ context,
122
+ emit: incoming !== undefined && incoming.sampled || answered
123
+ };
124
+ store.set(key, record);
125
+ return record;
126
+ }
127
+ const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
128
+ function splitServerTiming(value) {
129
+ const entries = [];
130
+ let start = 0;
131
+ let quoted = false;
132
+ for (let i = 0; i < value.length; i++) {
133
+ const c = value[i];
134
+ if (quoted) {
135
+ if (c === "\\") i++;else if (c === '"') quoted = false;
136
+ } else if (c === '"') quoted = true;else if (c === ",") {
137
+ entries.push(value.slice(start, i));
138
+ start = i + 1;
139
+ }
140
+ }
141
+ entries.push(value.slice(start));
142
+ return entries;
143
+ }
144
+ function metricName(entry) {
145
+ return entry.split(";")[0].trim().toLowerCase();
146
+ }
147
+ function namesOnServerTiming(headers) {
148
+ const names = new Set();
149
+ const existing = headers.get("server-timing");
150
+ if (existing) {
151
+ for (const entry of splitServerTiming(existing)) {
152
+ const name = metricName(entry);
153
+ if (name) names.add(name);
154
+ }
155
+ }
156
+ return names;
157
+ }
158
+ function quoteDesc(value) {
159
+ return value.replace(/[\x00-\x1f\x7f]/g, "").replace(/[\\"]/g, m => "\\" + m);
160
+ }
161
+ function appendTraceServerTiming(headers, record) {
162
+ if (!record.emit) return;
163
+ const entries = record.context.entries;
164
+ let present;
165
+ for (const name in entries) {
166
+ if (!TOKEN.test(name)) continue;
167
+ if (!present) present = namesOnServerTiming(headers);
168
+ if (present.has(name.toLowerCase())) continue;
169
+ headers.append("Server-Timing", `${name};desc="${quoteDesc(entries[name])}"`);
170
+ present.add(name.toLowerCase());
171
+ }
172
+ }
173
+ function mergeServerTiming(target, value) {
174
+ const present = namesOnServerTiming(target);
175
+ for (const entry of splitServerTiming(value)) {
176
+ const trimmed = entry.trim();
177
+ const name = metricName(trimmed);
178
+ if (!name || present.has(name)) continue;
179
+ target.append("Server-Timing", trimmed);
180
+ present.add(name);
181
+ }
182
+ }
183
+
25
184
  const SERVER_FUNCTION_METADATA = Symbol.for("solid.ServerFunctionMetadata");
26
185
  function getServerFunctionMetadata(fn) {
27
186
  if (typeof fn !== "function") return undefined;
@@ -168,6 +327,10 @@ function serverFunctionAddress(endpoint, id) {
168
327
  const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
169
328
  return `${mount}/${encodeURIComponent(id)}`;
170
329
  }
330
+ function serverFunctionDataAddress(endpoint, id) {
331
+ const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
332
+ return `${mount}/data/${encodeURIComponent(id)}`;
333
+ }
171
334
  function parseServerFunctionAddress(pathname, endpoint) {
172
335
  const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
173
336
  if (!pathname.startsWith(mount)) return null;
@@ -189,6 +352,40 @@ function parseServerFunctionAddress(pathname, endpoint) {
189
352
  return null;
190
353
  }
191
354
  }
355
+ const MAX_GET_URL_LENGTH = 2000;
356
+ function urlTargetId(target, helper) {
357
+ if (typeof target === "string") return target;
358
+ if (isServerFunction(target) && typeof target.id === "string") return target.id;
359
+ throw new Error(`${helper} expects a server function reference (or its id).`);
360
+ }
361
+ function serverFunctionActionUrlFor(endpoint, target, boundArgs) {
362
+ const address = serverFunctionAddress(endpoint, urlTargetId(target, "serverFunctionActionUrl"));
363
+ if (!boundArgs.length) return address;
364
+ if (!isJSONSafe(boundArgs)) {
365
+ throw new Error("Bound arguments in an action url must be JSON-safe: the server reads them the way it " + "reads a form post's, and that convention has no codec. Pass the value through the " + "function's body, or call the reference instead of rendering a url for it.");
366
+ }
367
+ return `${address}?args=${encodeURIComponent(JSON.stringify(boundArgs))}`;
368
+ }
369
+ function serverFunctionUrlFor(endpoint, fn, args) {
370
+ if (!isServerFunction(fn) || typeof fn.id !== "string") {
371
+ throw new Error("serverFunctionUrl expects a server function reference.");
372
+ }
373
+ const metadata = getServerFunctionMetadata(fn);
374
+ if (!metadata || metadata.method !== "GET") {
375
+ throw new Error(`serverFunctionUrl: "${fn.id}" is not a declared read. A call over the default ` + "transport is a POST — its arguments travel in the body, so no url describes it. " + "Declare the function with GET(fn) for a cacheable read that has a url, or start " + 'the call itself: invoke(fn, { priority: "low" }, ...args).');
376
+ }
377
+ const address = serverFunctionDataAddress(endpoint, fn.id);
378
+ if (!args.length) return address;
379
+ if (!isJSONSafe(args)) {
380
+ throw new Error("Arguments in a server function url must be JSON-safe: the transport encodes anything " + "else through the codec asynchronously, and a url rendered as a value cannot wait for " + "it. Pass JSON-safe arguments, or call the reference instead of rendering a url for it.");
381
+ }
382
+ const url = `${address}?args=${encodeURIComponent(JSON.stringify(args))}`;
383
+ const length = new URL(url, globalThis.location?.href || "http://localhost").href.length;
384
+ if (length > MAX_GET_URL_LENGTH) {
385
+ throw new Error(`serverFunctionUrl: the url for "${fn.id}" with these arguments is ${length} characters; ` + `past ${MAX_GET_URL_LENGTH} the call dispatches over POST (a cache miss rather than a ` + "414), so no url describes it. Shorten the arguments, or call the reference instead.");
386
+ }
387
+ return url;
388
+ }
192
389
  const ERROR_HEADER = "X-Server-Function-Error";
193
390
  const ERROR_HEADER_MARKER = "=?1?";
194
391
  const NEEDS_ENCODING = /[^\x20-\x7e\xa0-\xff]/;
@@ -214,7 +411,6 @@ function decodeErrorHeaderValue(value) {
214
411
  return value;
215
412
  }
216
413
  }
217
- const INSTANCE_HEADER = "X-Server-Function-Instance";
218
414
  const BODY_FORMAT_HEADER = "X-Server-Function-Format";
219
415
  const UNKNOWN_HEADER = "X-Server-Function-Unknown";
220
416
  const REDIRECT_HEADER = "X-Server-Function-Redirect";
@@ -527,21 +723,63 @@ async function decodeResponsePayload(response, codecOptions) {
527
723
  };
528
724
  }
529
725
 
726
+ function emitFinding(finding, subject = getOwner()) {
727
+ if (OBSERVE === undefined) return;
728
+ const entry = OBSERVE.diagnostics.emit(finding, subject);
729
+ if (DEV$1 !== undefined) DEV$1.report(entry);
730
+ }
731
+ function recordFinding(finding, subject = getOwner()) {
732
+ if (OBSERVE !== undefined) OBSERVE.diagnostics.emit(finding, subject);
733
+ }
734
+ function errorText(error) {
735
+ if (error instanceof Error) return error.message ? `${error.name}: ${error.message}` : error.name;
736
+ return String(error);
737
+ }
738
+
530
739
  typeof setImmediate === "function" ? setImmediate : fn => setTimeout(fn, 0);
531
740
  const RequestContext = Symbol.for("solid.RequestContext");
532
741
  function getRequestEvent() {
533
742
  return globalThis[RequestContext] ? globalThis[RequestContext].getStore() || sharedConfig.context && sharedConfig.context.event || console.warn("RequestEvent is missing. This is most likely due to accessing `getRequestEvent` non-managed async scope in a partially polyfilled environment. Try moving it above all `await` calls.") : undefined;
534
743
  }
744
+ function peekRequestEvent() {
745
+ const store = globalThis[RequestContext];
746
+ return store ? store.getStore() : undefined;
747
+ }
748
+ function traceForEvent(event) {
749
+ return traceFor(event.request || event, event.request);
750
+ }
751
+ function traceForStub(stub, event) {
752
+ if (!event) {
753
+ event = peekRequestEvent();
754
+ if (!event || event.response !== stub) return undefined;
755
+ }
756
+ return traceForEvent(event);
757
+ }
535
758
  function reportLostHeaderWrite(method, name) {
536
- const message = `Response header write dropped: headers.${method}(${JSON.stringify(String(name))}) ` + "ran after the response head was sent. Write headers before the shell flushes " + "(or before the handler returns).";
759
+ const message = `[LATE_HEADER_WRITE] Response header write dropped: headers.${method}(${JSON.stringify(String(name))}) ` + "ran after the response head was sent. Write headers before the shell flushes " + "(or before the handler returns).";
760
+ recordFinding({
761
+ code: "LATE_HEADER_WRITE",
762
+ kind: "head",
763
+ severity: "error",
764
+ message,
765
+ data: {
766
+ method,
767
+ name: String(name)
768
+ }
769
+ });
537
770
  throw new Error(message);
538
771
  }
539
772
  function commitResponseStub(stub, {
540
- allowLateLocation = false
773
+ allowLateLocation = false,
774
+ event
541
775
  } = {}) {
542
776
  if (!stub || stub.committed) return stub;
543
- stub.committed = true;
544
777
  const headers = stub.headers;
778
+ if (headers && typeof headers.append === "function") {
779
+ const trace = traceForStub(stub, event);
780
+ if (trace) appendTraceServerTiming(headers, trace);
781
+ }
782
+ stub.committed = true;
545
783
  if (!headers || typeof headers.set !== "function") return stub;
546
784
  for (const method of ["set", "append", "delete"]) {
547
785
  const original = headers[method].bind(headers);
@@ -572,19 +810,35 @@ function fillsStubGap(key, headers, response) {
572
810
  }
573
811
  function commitEventResponse(response, event = getRequestEvent()) {
574
812
  const stub = event && event.response;
575
- if (!stub || !stub.headers || stub.committed) return response;
813
+ if (!stub || !stub.headers || stub.committed) {
814
+ if (!event || stub) return response;
815
+ const trace = traceForEvent(event);
816
+ if (!trace.emit) return response;
817
+ const headers = copyInitHeaders(response.headers);
818
+ appendTraceServerTiming(headers, trace);
819
+ return new Response(response.body, {
820
+ status: response.status,
821
+ statusText: response.statusText,
822
+ headers
823
+ });
824
+ }
576
825
  const cookies = stub.headers.getSetCookie ? stub.headers.getSetCookie() : [];
577
- commitResponseStub(stub);
826
+ commitResponseStub(stub, {
827
+ event
828
+ });
578
829
  let hasGaps = false;
579
830
  stub.headers.forEach((value, key) => {
580
831
  if (fillsStubGap(key, response.headers, response)) hasGaps = true;
581
832
  });
582
- if (!cookies.length && !hasGaps) return response;
833
+ const timing = stub.headers.get("server-timing");
834
+ const mergesTiming = timing !== null && response.headers.has("server-timing");
835
+ if (!cookies.length && !hasGaps && !mergesTiming) return response;
583
836
  const headers = copyInitHeaders(response.headers);
584
837
  for (const cookie of cookies) headers.append("Set-Cookie", cookie);
585
838
  stub.headers.forEach((value, key) => {
586
839
  if (fillsStubGap(key, headers, response)) headers.set(key, value);
587
840
  });
841
+ if (mergesTiming) mergeServerTiming(headers, timing);
588
842
  return new Response(response.body, {
589
843
  status: response.status,
590
844
  statusText: response.statusText,
@@ -592,6 +846,71 @@ function commitEventResponse(response, event = getRequestEvent()) {
592
846
  });
593
847
  }
594
848
 
849
+ const RECORDS = Symbol.for("@solidjs/signals/observe/records");
850
+ function records() {
851
+ return globalThis[RECORDS];
852
+ }
853
+ function settledPromise(value) {
854
+ if (value instanceof Promise) return value;
855
+ try {
856
+ if (Object.prototype.toString.call(value) === "[object Promise]") return Promise.prototype.then.call(value, v => v);
857
+ } catch {}
858
+ return undefined;
859
+ }
860
+ function isDeferredBody(value) {
861
+ if (value === null || typeof value !== "object" && typeof value !== "function") return false;
862
+ if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) return true;
863
+ const v = value;
864
+ if (typeof v[Symbol.asyncIterator] === "function") return true;
865
+ return typeof v[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value);
866
+ }
867
+
868
+ function deliver(context, at, boundary, outcome, value) {
869
+ const record = {
870
+ id: context.id,
871
+ direct: context.direct,
872
+ at,
873
+ durationMs: performance.now() - at,
874
+ outcome
875
+ };
876
+ if (boundary !== undefined) record.boundary = boundary;
877
+ const live = {
878
+ event: context.event,
879
+ args: context.args
880
+ };
881
+ if (context.request !== undefined) live.request = context.request;
882
+ if (outcome === "ok") {
883
+ live.result = value;
884
+ if (isDeferredBody(value)) record.deferred = true;
885
+ } else live.error = value;
886
+ records().emit("invocation", record, live);
887
+ }
888
+ function observeInvocation(context, execute) {
889
+ const channel = records();
890
+ if (channel === undefined || !channel.observed("invocation")) return execute();
891
+ const at = performance.now();
892
+ const boundary = context.direct ? sharedConfig.context?._currentBoundaryId ?? undefined : undefined;
893
+ let result;
894
+ try {
895
+ result = execute();
896
+ } catch (error) {
897
+ deliver(context, at, boundary, "error", error);
898
+ throw error;
899
+ }
900
+ const promised = settledPromise(result);
901
+ if (promised !== undefined) {
902
+ return promised.then(value => {
903
+ deliver(context, at, boundary, "ok", value);
904
+ return value;
905
+ }, error => {
906
+ deliver(context, at, boundary, "error", error);
907
+ throw error;
908
+ });
909
+ }
910
+ deliver(context, at, boundary, "ok", result);
911
+ return result;
912
+ }
913
+
595
914
  let configuredSecret;
596
915
  function setFlashSecret(secret) {
597
916
  configuredSecret = secret;
@@ -1101,12 +1420,17 @@ function createServerReference({
1101
1420
  const wrap = resolveWrapInvocation(config.wrapInvocation);
1102
1421
  let result = provideEventOnce(provideEvent, evt, () => {
1103
1422
  const run = () => fn.apply(thisArg, args);
1104
- return wrap ? wrap(run, {
1423
+ return observeInvocation({
1424
+ id,
1425
+ direct: true,
1426
+ event: evt,
1427
+ args
1428
+ }, () => reportDirectFailure(() => wrap ? wrap(run, {
1105
1429
  id,
1106
1430
  args,
1107
1431
  event: evt,
1108
1432
  direct: true
1109
- }) : run();
1433
+ }) : run(), id));
1110
1434
  });
1111
1435
  result = scopeDeferredResult(result, scope);
1112
1436
  const transform = config.transformDirectResult;
@@ -1552,7 +1876,7 @@ function guardFailures(value, state) {
1552
1876
  try {
1553
1877
  top.accessorValue = descriptor.get.call(top.value);
1554
1878
  } catch (error) {
1555
- throw sanitizeServerError(error);
1879
+ throw wireServerFunctionError(error, "channel");
1556
1880
  }
1557
1881
  top.accessorRead = i;
1558
1882
  }
@@ -1662,7 +1986,7 @@ function enterGuard(value, state) {
1662
1986
  } = await guardOperation(state, () => reader.read());
1663
1987
  done ? controller.close() : controller.enqueue(guardOperation(state, () => guardFailures(chunk, state)));
1664
1988
  } catch (error) {
1665
- controller.error(guardOperation(state, () => sanitizeServerError(error)));
1989
+ controller.error(guardOperation(state, () => wireServerFunctionError(error, "channel")));
1666
1990
  }
1667
1991
  },
1668
1992
  cancel(reason) {
@@ -1676,7 +2000,7 @@ function enterGuard(value, state) {
1676
2000
  }
1677
2001
  if (typeof value.then === "function") {
1678
2002
  const guardedPromise = Promise.resolve(value).then(resolved => guardOperation(state, () => guardFailures(resolved, state)), error => {
1679
- throw guardOperation(state, () => sanitizeServerError(error));
2003
+ throw guardOperation(state, () => wireServerFunctionError(error, "channel"));
1680
2004
  });
1681
2005
  guardedPromise.catch(() => {});
1682
2006
  state.seen.set(value, guardedPromise);
@@ -1711,7 +2035,7 @@ function enterGuard(value, state) {
1711
2035
  value: guardOperation(state, () => guardFailures(step.value, state))
1712
2036
  };
1713
2037
  }, error => {
1714
- throw guardOperation(state, () => sanitizeServerError(error));
2038
+ throw guardOperation(state, () => wireServerFunctionError(error, "channel"));
1715
2039
  });
1716
2040
  return {
1717
2041
  next: () => finished || !gate || gate.wantsMore() ? step() : gate.awaitDemand().then(step),
@@ -1860,7 +2184,7 @@ function serializeResponseStream(value, codecOptions, signal, scope) {
1860
2184
  if (onAbort) signal.removeEventListener("abort", onAbort);
1861
2185
  finishSource();
1862
2186
  try {
1863
- const delivered = sanitizeServerError(DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error);
2187
+ const delivered = wireServerFunctionError(DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error, "channel");
1864
2188
  controller.enqueue(createChunk(encodeErrorTrailer(delivered)));
1865
2189
  controller.close();
1866
2190
  } catch {
@@ -1954,23 +2278,65 @@ let DEV = true === true;
1954
2278
  function setServerFunctionsDev(dev) {
1955
2279
  DEV = !!dev;
1956
2280
  }
2281
+ const REQUEST_ERROR_HOOKS = new WeakMap();
2282
+ function siteFor(handling, event, direct) {
2283
+ const invocation = event ? INVOCATIONS.get(event) : undefined;
2284
+ const site = {
2285
+ kind: "server-function",
2286
+ handling,
2287
+ direct
2288
+ };
2289
+ if (invocation) site.functionId = invocation.id;
2290
+ if (event) site.event = event;
2291
+ return site;
2292
+ }
2293
+ function wireServerFunctionError(value, handling, event = currentEvent()) {
2294
+ const report = reportServerError(value, siteFor(handling, event, false), null, event ? REQUEST_ERROR_HOOKS.get(event) : undefined);
2295
+ return report.mapped ? report.value : sanitizeServerError(value);
2296
+ }
2297
+ function currentEvent() {
2298
+ const store = globalThis[RequestContext];
2299
+ return store ? store.getStore() : undefined;
2300
+ }
2301
+ function reportDirectFailure(run, id) {
2302
+ const report = error => {
2303
+ reportServerError(error, {
2304
+ kind: "server-function",
2305
+ handling: "thrown",
2306
+ functionId: id,
2307
+ direct: true
2308
+ }, null);
2309
+ throw error;
2310
+ };
2311
+ let result;
2312
+ try {
2313
+ result = run();
2314
+ } catch (error) {
2315
+ report(error);
2316
+ }
2317
+ return result && typeof result.then === "function" ? result.then(undefined, report) : result;
2318
+ }
1957
2319
  function sanitizeServerError(value) {
1958
2320
  if (DEV) return value;
1959
2321
  if (isSafeError(value)) return value;
2322
+ emitFinding({
2323
+ code: "SERVER_FN_ERROR_SANITIZED",
2324
+ kind: "ssr",
2325
+ severity: "error",
2326
+ message: `[SERVER_FN_ERROR_SANITIZED] Server function error replaced with a generic Error before serialization: ${errorText(value)}`,
2327
+ data: {
2328
+ error: value
2329
+ }
2330
+ }, null);
1960
2331
  return new Error(GENERIC_SERVER_ERROR_MESSAGE);
1961
2332
  }
1962
- function observeServerFunctionCalls() {
1963
- return () => {};
2333
+ function serverFunctionUrl(fn, ...args) {
2334
+ return serverFunctionUrlFor(config.endpoint, fn, args);
1964
2335
  }
1965
- function serverFunctionUrl(id, boundArgs) {
1966
- const address = serverFunctionAddress(config.endpoint, id);
1967
- if (!boundArgs || !boundArgs.length) return address;
1968
- if (!isJSONSafe(boundArgs)) {
1969
- throw new Error("Bound arguments in an action url must be JSON-safe: the server reads them the way it " + "reads a form post's, and that convention has no codec. Pass the value through the " + "function's body, or call the reference instead of rendering a url for it.");
1970
- }
1971
- return `${address}?args=${encodeURIComponent(JSON.stringify(boundArgs))}`;
2336
+ function serverFunctionActionUrl(fn, ...boundArgs) {
2337
+ return serverFunctionActionUrlFor(config.endpoint, fn, boundArgs);
1972
2338
  }
1973
- function parseServerFunctionUrl(url) {
2339
+ function parseServerFunctionActionUrl(url) {
1974
2340
  const parsed = parseServerFunctionAddress(new URL(url, "http://localhost").pathname, config.endpoint);
1975
2341
  return parsed && parsed.id;
1976
2342
  }
@@ -2062,7 +2428,6 @@ async function handleServerFunctionRequest(request, options = {}) {
2062
2428
  if (protectsRequest && !(await allowsServerFunctionRequest(request, csrf === true ? {} : csrf))) {
2063
2429
  return finalizeTransportResponse(forbiddenResponse(), method);
2064
2430
  }
2065
- const instance = request.headers.get(INSTANCE_HEADER);
2066
2431
  if (!functionId) {
2067
2432
  const response = new Response(DEV ? "Server function not found" : null, {
2068
2433
  status: 404
@@ -2137,6 +2502,7 @@ async function handleServerFunctionRequest(request, options = {}) {
2137
2502
  };
2138
2503
  const provide = options.provideEvent || provideEvent;
2139
2504
  const scope = run => provide(event, run);
2505
+ if (options.onError !== undefined) REQUEST_ERROR_HOOKS.set(event, options.onError);
2140
2506
  const flightHook = options.collectFlightData !== undefined ? options.collectFlightData : config.collectFlightData;
2141
2507
  const transformResult = options.transformResult !== undefined ? options.transformResult : config.transformResult;
2142
2508
  const wrapInvocation = resolveWrapInvocation(options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation);
@@ -2179,7 +2545,6 @@ async function handleServerFunctionRequest(request, options = {}) {
2179
2545
  const flightContext = {
2180
2546
  id: functionId,
2181
2547
  args: parsed,
2182
- instance,
2183
2548
  request,
2184
2549
  collectsFlight,
2185
2550
  codec,
@@ -2193,13 +2558,19 @@ async function handleServerFunctionRequest(request, options = {}) {
2193
2558
  id: functionId
2194
2559
  });
2195
2560
  const run = () => serverFunction(...parsed);
2196
- return wrapInvocation ? wrapInvocation(run, {
2561
+ return observeInvocation({
2562
+ id: functionId,
2563
+ direct: false,
2564
+ event,
2565
+ request,
2566
+ args: parsed
2567
+ }, () => wrapInvocation ? wrapInvocation(run, {
2197
2568
  id: functionId,
2198
2569
  args: parsed,
2199
2570
  event,
2200
2571
  request,
2201
2572
  direct: false
2202
- }) : run();
2573
+ }) : run());
2203
2574
  };
2204
2575
  let result = await provideEventOnce(provide, event, invokeOnce);
2205
2576
  if (transformResult) {
@@ -2263,7 +2634,7 @@ async function handleServerFunctionRequest(request, options = {}) {
2263
2634
  return encodeResult(result, headers, status, codec, request.signal, scope);
2264
2635
  } catch (x) {
2265
2636
  const respondThrown = value => {
2266
- const safe = sanitizeServerError(value);
2637
+ const safe = wireServerFunctionError(value, "thrown", event);
2267
2638
  if (!scripted) {
2268
2639
  if (handleNoJS) return handleNoJS(safe, request, parsed, true);
2269
2640
  const message = safe instanceof Error ? safe.message : String(safe);
@@ -2381,4 +2752,4 @@ function finalizeTransportResponse(response, method) {
2381
2752
  return response;
2382
2753
  }
2383
2754
 
2384
- export { ERROR_HEADER, FLASH_COOKIE, GENERIC_SERVER_ERROR_MESSAGE, GET, INSTANCE_HEADER, REDIRECT_HEADER, SERVER_FUNCTION_INVOKE, SINGLE_FLIGHT_HEADER, UNKNOWN_HEADER, clearFlashCookie, configureServerFunctionsServer, createNoJSHandler, createServerReference, decodeErrorHeaderValue, decodeFlashCookie, decodeRedirectHeaderValue, decodeResponse, decodeResponsePayload, encodeErrorHeaderValue, encodeFlashCookie, foldSetCookies, getEventServerFunctionInvocation, getServerFunction, getServerFunctionInvocation, getServerFunctionMetadata, guardFailures, handleServerFunctionRequest, hasFlashCookie, invoke, isServerFunction, live, observeServerFunctionCalls, parseServerFunctionUrl, registerFlightDataSource, registerServerFunction, registerServerReference, sanitizeServerError, serializeResponseStream, serverFunctionUrl, setServerFunctionsDev, subscribeFlightData, withMeta };
2755
+ export { ERROR_HEADER, FLASH_COOKIE, GENERIC_SERVER_ERROR_MESSAGE, GET, REDIRECT_HEADER, SERVER_FUNCTION_INVOKE, SINGLE_FLIGHT_HEADER, UNKNOWN_HEADER, clearFlashCookie, configureServerFunctionsServer, createNoJSHandler, createServerReference, decodeErrorHeaderValue, decodeFlashCookie, decodeRedirectHeaderValue, decodeResponse, decodeResponsePayload, encodeErrorHeaderValue, encodeFlashCookie, foldSetCookies, getEventServerFunctionInvocation, getServerFunction, getServerFunctionInvocation, getServerFunctionMetadata, guardFailures, handleServerFunctionRequest, hasFlashCookie, invoke, isServerFunction, live, parseServerFunctionActionUrl, registerFlightDataSource, registerServerFunction, registerServerReference, sanitizeServerError, serializeResponseStream, serverFunctionActionUrl, serverFunctionUrl, setServerFunctionsDev, subscribeFlightData, withMeta };