@ultimat3/core 31.23.0 → 31.25.0

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.
@@ -1,5 +1,6 @@
1
1
  // Single responsibility: a concurrent map with a stated width — results in input order, the first
2
- // rejection (or the caller's abort) stops every item not yet started and tells the in-flight ones.
2
+ // rejection (or the caller's abort) stops every item not yet started and tells the in-flight ones;
3
+ // under `settle: 'all'` a rejection is that item's outcome and only the caller's abort stops it.
3
4
 
4
5
  import { renderThrowable } from './error-render';
5
6
  import { UltimateError } from './errors';
@@ -13,6 +14,12 @@ export interface MapBoundedOptions {
13
14
  readonly width: number;
14
15
  /** The deadline or the caller going away. Aborting stops every item not yet started. */
15
16
  readonly signal?: AbortSignal | undefined;
17
+ /**
18
+ * `'first'` (the default) rejects with the first failure, as `Promise.all`. `'all'` answers every
19
+ * item's `PromiseSettledResult` in input order, as `Promise.allSettled`: a rejection is recorded
20
+ * and frees its slot for the next item; only `signal` stops the map.
21
+ */
22
+ readonly settle?: 'first' | 'all' | undefined;
16
23
  }
17
24
 
18
25
  /**
@@ -22,22 +29,36 @@ export interface MapBoundedOptions {
22
29
  *
23
30
  * Rejects AT ONCE with the first failure, as `Promise.all` does: a sibling that ignores its signal
24
31
  * cannot hold the answer hostage. A later sibling's rejection is swallowed, never unhandled.
32
+ *
33
+ * `settle: 'all'` is `Promise.allSettled` with the same width: every outcome, in input order, and
34
+ * `fn`'s signal aborts only with `options.signal` — which still rejects the map with `X_ABORTED`.
25
35
  */
36
+ export async function mapBounded<T, R>(
37
+ items: readonly T[],
38
+ fn: (item: T, index: number, signal: AbortSignal) => R | Promise<R>,
39
+ options: MapBoundedOptions & { readonly settle: 'all' },
40
+ ): Promise<PromiseSettledResult<R>[]>;
41
+ export async function mapBounded<T, R>(
42
+ items: readonly T[],
43
+ fn: (item: T, index: number, signal: AbortSignal) => R | Promise<R>,
44
+ options: MapBoundedOptions & { readonly settle?: 'first' | undefined },
45
+ ): Promise<R[]>;
26
46
  export async function mapBounded<T, R>(
27
47
  items: readonly T[],
28
48
  fn: (item: T, index: number, signal: AbortSignal) => R | Promise<R>,
29
49
  options: MapBoundedOptions,
30
- ): Promise<R[]> {
50
+ ): Promise<R[] | PromiseSettledResult<R>[]> {
31
51
  const width = finiteCount('mapBounded', 'width', options.width, 1);
32
52
  const outer = options.signal;
33
53
  if (outer?.aborted) throw aborted(outer.reason, 0, items.length);
34
- const results = new Array<R>(items.length);
35
- if (items.length === 0) return results;
54
+ const all = options.settle === 'all';
55
+ const results = new Array<R | PromiseSettledResult<R>>(items.length);
56
+ if (items.length === 0) return [];
36
57
 
37
58
  const controller = new AbortController();
38
59
  let next = 0;
39
60
  let completed = 0;
40
- return new Promise<R[]>((resolve, reject) => {
61
+ return new Promise<R[] | PromiseSettledResult<R>[]>((resolve, reject) => {
41
62
  const fail = (error: unknown): void => {
42
63
  if (controller.signal.aborted) return;
43
64
  outer?.removeEventListener('abort', onAbort);
@@ -47,26 +68,34 @@ export async function mapBounded<T, R>(
47
68
  const onAbort = (): void => fail(aborted(outer?.reason, completed, items.length));
48
69
  outer?.addEventListener('abort', onAbort, { once: true });
49
70
 
50
- // No abort check here: `pull` runs only in the synchronous first loop or past the success
51
- // branch's own check, so an aborted map never reaches it.
71
+ const done = (index: number, outcome: R | PromiseSettledResult<R>): void => {
72
+ if (controller.signal.aborted) return;
73
+ results[index] = outcome;
74
+ completed += 1;
75
+ if (completed === items.length) {
76
+ outer?.removeEventListener('abort', onAbort);
77
+ // Every slot is written once `completed` reaches the length.
78
+ resolve(results as R[] | PromiseSettledResult<R>[]);
79
+ return;
80
+ }
81
+ pull();
82
+ };
83
+ // No abort check here: `pull` runs only in the synchronous first loop or past `done`'s own
84
+ // check, so an aborted map never reaches it.
52
85
  const pull = (): void => {
53
86
  if (next >= items.length) return;
54
87
  const index = next++;
55
88
  // `.then` rather than a direct call: a SYNCHRONOUS throw in `fn` becomes this item's
56
89
  // rejection instead of escaping the runner that pulled it.
57
- Promise.resolve()
58
- .then(() => fn(items[index] as T, index, controller.signal))
59
- .then((value) => {
60
- if (controller.signal.aborted) return;
61
- results[index] = value;
62
- completed += 1;
63
- if (completed === items.length) {
64
- outer?.removeEventListener('abort', onAbort);
65
- resolve(results);
66
- return;
67
- }
68
- pull();
69
- }, fail);
90
+ const run = Promise.resolve().then(() => fn(items[index] as T, index, controller.signal));
91
+ if (all) {
92
+ run.then(
93
+ (value) => done(index, { status: 'fulfilled', value }),
94
+ (reason: unknown) => done(index, { status: 'rejected', reason }),
95
+ );
96
+ } else {
97
+ run.then((value) => done(index, value), fail);
98
+ }
70
99
  };
71
100
  for (let slot = 0; slot < Math.min(width, items.length); slot += 1) pull();
72
101
  });
@@ -4,6 +4,7 @@
4
4
 
5
5
  import type { MetricAttributes, MetricPoint, ReadableMetric } from './metrics';
6
6
  import { collectMetrics, type HistogramPoint, type MetricCollection } from './metrics';
7
+ import { frameworkVersion } from './version';
7
8
 
8
9
  export const METRICS_PATH = '/metrics';
9
10
 
@@ -88,7 +89,7 @@ export function metricsText(collection: MetricCollection = collectMetrics()): st
88
89
  const lines = [
89
90
  '# HELP target_info the service these metrics describe',
90
91
  '# TYPE target_info gauge',
91
- `target_info{service_name="${escapeLabel(serviceName)}",service_version="${escapeLabel(serviceVersion)}"} 1`,
92
+ `target_info{service_name="${escapeLabel(serviceName)}",service_version="${escapeLabel(serviceVersion)}",framework_version="${escapeLabel(frameworkVersion())}"} 1`,
92
93
  ...collection.metrics.flatMap(metricLines),
93
94
  ];
94
95
  return `${lines.join('\n')}\n`;
package/src/otlp.ts CHANGED
@@ -8,6 +8,7 @@ import { renderFixShellArg } from './error-render';
8
8
  import { type CodedErrorInit, UltimateError } from './errors';
9
9
  import { otlpEndpointLabel } from './otlp-post';
10
10
  import type { AttributeValue, SpanResource } from './telemetry';
11
+ import { frameworkVersion } from './version';
11
12
 
12
13
  export class OtlpEndpointInvalidError extends UltimateError {
13
14
  static readonly code = 'X_OTLP_ENDPOINT_INVALID';
@@ -274,6 +275,9 @@ export function otlpResource(resource: SpanResource): {
274
275
  attributes: otlpAttributes({
275
276
  'service.name': resource.serviceName,
276
277
  'service.version': resource.serviceVersion,
278
+ // Which framework release emitted the signal. Mapped to Prometheus it is `target_info`'s
279
+ // `framework_version` label (`metrics-text.ts`): one fact, the same name on every signal.
280
+ 'framework.version': frameworkVersion(),
277
281
  }),
278
282
  };
279
283
  }
package/src/outage-log.ts CHANGED
@@ -1,7 +1,10 @@
1
- // Single responsibility: one condition that KEEPS failing, said rarely — on failures 1, 2, 4, 8, …
2
- // and once more when it ends. An outage is one fact; a line per retry per pod for as long as it
3
- // lasts is the fact buried under itself.
1
+ // Single responsibility: one condition that KEEPS failing, said rarely — once more when it ends.
2
+ // Two shapes of the one limiter: `outageLog` says it on failures 1, 2, 4, 8, …; `failureStreak`
3
+ // says it once per CAUSE. An outage is one fact; a line per retry per pod for as long as it lasts
4
+ // is the fact buried under itself.
4
5
 
6
+ import { renderThrowable } from './error-render';
7
+ import { isUltimateError } from './errors';
5
8
  import { type LogFields, logger } from './logger';
6
9
 
7
10
  export interface OutageLogOptions {
@@ -51,3 +54,91 @@ export function outageLog(options: OutageLogOptions): OutageLog {
51
54
  },
52
55
  };
53
56
  }
57
+
58
+ /**
59
+ * What a failure line carries: the rendered message, and for a coded error the code to search on
60
+ * and the `fix:` to run — what the operator reading the line at 3am needs, not a sentence.
61
+ */
62
+ export function failureFields(error: unknown): LogFields {
63
+ const message = renderThrowable(error);
64
+ return isUltimateError(error)
65
+ ? { error: message, code: error.code, cause: error.cause, fix: error.fix }
66
+ : { error: message };
67
+ }
68
+
69
+ export interface FailureStreakOptions {
70
+ /** The line that opens a streak, or changes its cause. Low cardinality: a monitor groups on it. */
71
+ readonly event: string;
72
+ /** The ONE `info` line that ends a streak, with `failures`, its count. */
73
+ readonly recoveredEvent: string;
74
+ /** Default `'error'`: a loop that cannot do its job. `'warn'` for one that retries its way back. */
75
+ readonly level?: 'warn' | 'error';
76
+ /** On every line the streak writes, its end included: what names the loop (`workerId`, `channel`). */
77
+ readonly fields?: LogFields;
78
+ }
79
+
80
+ export interface FailureStreak {
81
+ /**
82
+ * One more failure: logged when it opens a streak or changes its cause, counted otherwise. A new
83
+ * cause — a restart's refusal giving way to a missing column — is news: its line carries the
84
+ * streak it ends (`previous`, with that streak's count). `fields` go on this failure's line only.
85
+ * Answers whether it was logged.
86
+ */
87
+ failed(error: unknown, fields?: LogFields): boolean;
88
+ /** It works again: ends a streak, if one was open, with one line counting it. */
89
+ passed(): void;
90
+ /** The loop (re)started: whatever streak a stopped run left open is not this run's. */
91
+ reset(): void;
92
+ /** Failures in the open streak; 0 when none is. */
93
+ readonly failures: number;
94
+ }
95
+
96
+ interface Cause {
97
+ readonly key: string;
98
+ readonly label: Readonly<Record<string, string>>;
99
+ }
100
+
101
+ /** What makes two failures the same one: the code, or, uncoded, the rendered message. */
102
+ function causeOf(error: unknown): Cause {
103
+ if (isUltimateError(error)) return { key: `code:${error.code}`, label: { code: error.code } };
104
+ const message = renderThrowable(error);
105
+ return { key: `error:${message}`, label: { error: message } };
106
+ }
107
+
108
+ export function failureStreak(options: FailureStreakOptions): FailureStreak {
109
+ const level = options.level ?? 'error';
110
+ let failures = 0;
111
+ let cause: Cause | undefined;
112
+ const reset = (): void => {
113
+ failures = 0;
114
+ cause = undefined;
115
+ };
116
+ return {
117
+ get failures(): number {
118
+ return failures;
119
+ },
120
+ failed(error: unknown, fields?: LogFields): boolean {
121
+ const next = causeOf(error);
122
+ if (cause !== undefined && cause.key === next.key) {
123
+ failures += 1;
124
+ return false;
125
+ }
126
+ const previous = cause === undefined ? {} : { previous: { ...cause.label, failures } };
127
+ failures = 1;
128
+ cause = next;
129
+ logger[level](options.event, {
130
+ ...options.fields,
131
+ ...fields,
132
+ ...failureFields(error),
133
+ ...previous,
134
+ });
135
+ return true;
136
+ },
137
+ passed(): void {
138
+ if (failures === 0) return;
139
+ logger.info(options.recoveredEvent, { ...options.fields, failures });
140
+ reset();
141
+ },
142
+ reset,
143
+ };
144
+ }
@@ -1,4 +1,4 @@
1
- // Single responsibility: the ten refusals `outbound()` can end on, each built from the call's
1
+ // Single responsibility: the eleven refusals `outbound()` can end on, each built from the call's
2
2
  // redacted label. Never a query string, never a header: a cause reaches a log store and a
3
3
  // problem document, and a signed URL's query is the credential.
4
4
 
@@ -7,7 +7,7 @@ import { registerErrorRetry } from './error-retry';
7
7
  import { UltimateError } from './errors';
8
8
 
9
9
  /**
10
- * The ten codes' retry classes, registered HERE and not in `error-retry.ts`'s core table: that
10
+ * The eleven codes' retry classes, registered HERE and not in `error-retry.ts`'s core table: that
11
11
  * table rides every browser page, and these are server-only (axiom 6). The transport faults are
12
12
  * retryable, a stated delay is `retry-after`, and every answer the same request gets again is
13
13
  * terminal — unclassified, `retry()` would replay a 401 three times.
@@ -23,6 +23,7 @@ registerErrorRetry({
23
23
  X_OUTBOUND_REDIRECTED: 'terminal',
24
24
  X_OUTBOUND_RETRY_UNSAFE: 'terminal',
25
25
  X_OUTBOUND_BODY_INVALID: 'terminal',
26
+ X_OUTBOUND_PROXY_INVALID: 'terminal',
26
27
  });
27
28
 
28
29
  /** What a failure may say about the call: who, how, and where, never the query or a header. */
@@ -66,11 +67,14 @@ export function outboundTimeout(
66
67
  }
67
68
 
68
69
  /**
69
- * A transport failure in its own words with every query string cut (`?…`): a runtime's message
70
- * may quote the URL it was dialling, and the query is where a signed URL keeps its credential.
70
+ * A transport failure in its own words with every query string cut (`?…`) and every URL's
71
+ * userinfo cut (`//…@`): a runtime's message may quote the URL it was dialling, a signed URL keeps
72
+ * its credential in the query, and a proxy URL keeps it before the `@`.
71
73
  */
72
- const transportText = (error: unknown): string =>
73
- renderThrowable(error).replaceAll(/\?[^\s"'`)]*/g, '?…');
74
+ export const transportText = (error: unknown): string =>
75
+ renderThrowable(error)
76
+ .replaceAll(/\?[^\s"'`)]*/g, '?…')
77
+ .replaceAll(/\/\/[^\s"'`/?#@]*@/g, '//…@');
74
78
 
75
79
  /** The refusals that say the CALLER's bound ran out, not the vendor: a breaker hears nothing. */
76
80
  const CALLER_BOUND = new WeakSet<UltimateError>();
@@ -191,3 +195,22 @@ export function outboundBodyInvalid(site: OutboundSite, issues: readonly string[
191
195
  meta: { ...siteMeta(site), issues },
192
196
  });
193
197
  }
198
+
199
+ /**
200
+ * The proxy a hop was given cannot be used: not a URL, a scheme Bun's `fetch` does not tunnel
201
+ * through, or a resolver that threw. `reason` names the shape and the scheme, never the URL: a
202
+ * proxy URL carries its credential.
203
+ */
204
+ export function outboundProxyInvalid(
205
+ site: OutboundSite,
206
+ reason: string,
207
+ error?: unknown,
208
+ ): UltimateError {
209
+ return new UltimateError({
210
+ code: 'X_OUTBOUND_PROXY_INVALID',
211
+ cause: `${siteLabel(site)} was refused before dialling: ${reason}`,
212
+ fix: `outbound({ url, vendor: '${site.vendor}', dial, proxy: 'http://<user>:<password>@<proxy-host>:<port>' }) # an http: or https: proxy URL, or a resolver answering one (or undefined to dial direct)`,
213
+ meta: { ...siteMeta(site), reason },
214
+ ...(error === undefined ? {} : { sourceError: error }),
215
+ });
216
+ }
@@ -1,13 +1,14 @@
1
- // Single responsibility: one attempt's hops — dial the URL as `dial` says (screened and pinned, or
2
- // as named), and under `redirect: 'follow'` take each 3xx by hand, re-screening the next address
3
- // and dropping credentials at an origin change. The platform's own `follow` dials a hop itself,
1
+ // Single responsibility: one attempt's hops — dial as `dial` says (screened and pinned, or named),
2
+ // under `redirect: 'follow'` take each 3xx by hand, re-screening and dropping credentials at an
3
+ // origin change, and choose a proxy per hop AFTER the screen. The platform's own `follow` dials
4
4
  // unscreened: measured, a default redirect from a screened name reached loopback.
5
5
 
6
6
  import type { DialResolve } from './outbound-dial';
7
7
  import { publicUrlRefusal, screenDial } from './outbound-dial';
8
8
  import type { OutboundSite } from './outbound-errors';
9
9
  import { outboundHostBlocked, outboundRedirected, outboundUnreachable } from './outbound-errors';
10
- import type { OutboundBody, OutboundFetch, OutboundInit } from './outbound-types';
10
+ import { proxyFor } from './outbound-proxy';
11
+ import type { OutboundBody, OutboundFetch, OutboundInit, OutboundProxy } from './outbound-types';
11
12
  import { OUTBOUND_MAX_REDIRECTS } from './outbound-types';
12
13
 
13
14
  export interface HopCall {
@@ -22,6 +23,7 @@ export interface HopCall {
22
23
  readonly local: boolean;
23
24
  readonly fetch: OutboundFetch;
24
25
  readonly resolve: DialResolve | undefined;
26
+ readonly proxy: OutboundProxy | undefined;
25
27
  }
26
28
 
27
29
  /**
@@ -90,6 +92,11 @@ export async function sendHops(call: HopCall, signal: AbortSignal): Promise<Resp
90
92
  let headers: Record<string, string> = { ...call.headers };
91
93
  for (let hop = 0; ; hop += 1) {
92
94
  const target = await targetFor(call, url, hop);
95
+ // After the screen, by the NAMED url: a refused host never reaches the app's resolver, and the
96
+ // proxy is handed the approved address (`target.url`), so it resolves nothing itself. No
97
+ // proxy, no await: a call without one keeps the microtask order its timer tests pin.
98
+ const proxy =
99
+ call.proxy === undefined ? undefined : await proxyFor(call.site, call.proxy, url, signal);
93
100
  const init: OutboundInit = {
94
101
  method,
95
102
  // Last: a pinned request is reached AS the name that was screened.
@@ -104,6 +111,7 @@ export async function sendHops(call: HopCall, signal: AbortSignal): Promise<Resp
104
111
  },
105
112
  ...(body === undefined ? {} : { body }),
106
113
  ...(target.serverName === undefined ? {} : { tls: { serverName: target.serverName } }),
114
+ ...(proxy === undefined ? {} : { proxy }),
107
115
  signal,
108
116
  redirect: 'manual',
109
117
  };
@@ -0,0 +1,72 @@
1
+ // Single responsibility: which proxy one hop goes through — the request's `proxy`, or its resolver
2
+ // asked with the hop's NAMED url — validated into the `init.proxy` Bun's `fetch` takes. Asked only
3
+ // after the dial screen approved the hop: a refused host never reaches the app's resolver.
4
+
5
+ import type { OutboundSite } from './outbound-errors';
6
+ import { outboundProxyInvalid, transportText } from './outbound-errors';
7
+ import type { OutboundProxy, OutboundProxyInit, OutboundProxyTarget } from './outbound-types';
8
+
9
+ /** The schemes Bun 1.4.4's `fetch` tunnels through; `socks5:` fails at the dial (measured). */
10
+ const PROXY_SCHEMES: ReadonlySet<string> = new Set(['http:', 'https:']);
11
+
12
+ /**
13
+ * The app's resolver, raced against the hop's signal: a resolver that never answers is bounded by
14
+ * the call's deadline like the dial is. Rejects with the signal's REASON, which the attempt codes.
15
+ */
16
+ async function chosen(
17
+ site: OutboundSite,
18
+ proxy: OutboundProxy,
19
+ target: URL,
20
+ signal: AbortSignal,
21
+ ): Promise<OutboundProxyTarget | undefined> {
22
+ if (typeof proxy !== 'function') return proxy;
23
+ if (signal.aborted) throw signal.reason;
24
+ let stop = (): void => undefined;
25
+ const aborted = new Promise<never>((_resolve, reject) => {
26
+ stop = () => signal.removeEventListener('abort', onAbort);
27
+ const onAbort = (): void => reject(signal.reason);
28
+ signal.addEventListener('abort', onAbort, { once: true });
29
+ });
30
+ // A copy: the resolver is the app's, and the hop's URL is still read after it returns.
31
+ const asked = Promise.resolve()
32
+ .then(() => proxy(new URL(target.href)))
33
+ .catch((error: unknown) => {
34
+ throw outboundProxyInvalid(site, `the proxy resolver threw (${transportText(error)})`, error);
35
+ });
36
+ try {
37
+ return await Promise.race([asked, aborted]);
38
+ } finally {
39
+ stop();
40
+ // The loser is never unhandled: a resolver failing after the deadline is nobody's answer.
41
+ asked.catch(() => undefined);
42
+ aborted.catch(() => undefined);
43
+ }
44
+ }
45
+
46
+ /** The hop's `init.proxy`, or `undefined` to dial it direct. Throws `X_OUTBOUND_PROXY_INVALID`. */
47
+ export async function proxyFor(
48
+ site: OutboundSite,
49
+ proxy: OutboundProxy | undefined,
50
+ target: URL,
51
+ signal: AbortSignal,
52
+ ): Promise<OutboundProxyInit | undefined> {
53
+ if (proxy === undefined) return undefined;
54
+ const picked = await chosen(site, proxy, target, signal);
55
+ if (picked === undefined) return undefined;
56
+ const plain = typeof picked === 'string' || picked instanceof URL;
57
+ const raw = plain ? picked : picked.url;
58
+ const headers = plain ? undefined : picked.headers;
59
+ let url: URL;
60
+ try {
61
+ url = new URL(raw);
62
+ } catch {
63
+ throw outboundProxyInvalid(site, 'the proxy is not an absolute URL');
64
+ }
65
+ if (!PROXY_SCHEMES.has(url.protocol)) {
66
+ throw outboundProxyInvalid(
67
+ site,
68
+ `the proxy's scheme is ${url.protocol}, and fetch tunnels through http: and https: proxies only`,
69
+ );
70
+ }
71
+ return { url: url.href, ...(headers === undefined ? {} : { headers: { ...headers } }) };
72
+ }
@@ -15,6 +15,9 @@ export type {
15
15
  OutboundFetch,
16
16
  OutboundInit,
17
17
  OutboundMethod,
18
+ OutboundProxy,
19
+ OutboundProxyInit,
20
+ OutboundProxyTarget,
18
21
  OutboundRequest,
19
22
  OutboundStreamAnswer,
20
23
  } from './outbound-types';
@@ -20,11 +20,38 @@ export type OutboundBody =
20
20
  | URLSearchParams
21
21
  | FormData;
22
22
 
23
- /** What one hop is sent with. `tls.serverName` is the name a PINNED connection proves. */
23
+ /** A proxy as Bun's `fetch` takes it: an `http:`/`https:` URL, with the `CONNECT` headers. */
24
+ export interface OutboundProxyInit {
25
+ readonly url: string;
26
+ readonly headers?: Readonly<Record<string, string>> | undefined;
27
+ }
28
+
29
+ /**
30
+ * What one hop is sent with. `tls.serverName` is the name a PINNED connection proves; it applies
31
+ * to the target inside a proxy's tunnel, never to the proxy (Bun 1.4.4, measured).
32
+ */
24
33
  export type OutboundInit = RequestInit & {
25
34
  readonly tls?: { readonly serverName?: string } | undefined;
35
+ readonly proxy?: OutboundProxyInit | undefined;
26
36
  };
27
37
 
38
+ /** One proxy: its URL (credentials may ride it), or the URL and the headers its `CONNECT` sends. */
39
+ export type OutboundProxyTarget =
40
+ | string
41
+ | URL
42
+ | {
43
+ readonly url: string | URL;
44
+ readonly headers?: Readonly<Record<string, string>> | undefined;
45
+ };
46
+
47
+ /**
48
+ * A proxy for every hop, or a resolver asked once per hop with the hop's NAMED url (never the
49
+ * pinned address) — `undefined` dials that hop direct. Which proxy, and rotating them, is the app's.
50
+ */
51
+ export type OutboundProxy =
52
+ | OutboundProxyTarget
53
+ | ((target: URL) => OutboundProxyTarget | undefined | Promise<OutboundProxyTarget | undefined>);
54
+
28
55
  /** "Just the call", the seam `MailFetch` already is. Its `init` always carries the signal. */
29
56
  export type OutboundFetch = (url: string, init: OutboundInit) => Promise<Response>;
30
57
 
@@ -61,6 +88,12 @@ export interface OutboundRequest {
61
88
  readonly signal?: AbortSignal | undefined;
62
89
  /** Recorded once per call, after the retries: a 503 retried away is not a failure. */
63
90
  readonly breaker?: Breaker | undefined;
91
+ /**
92
+ * Send each hop through an HTTP proxy (`CONNECT` for `https:`). Under `dial: 'public'` the screen
93
+ * still runs first and the tunnel is opened to the approved ADDRESS, the certificate still proven
94
+ * against the name; the proxy itself is the app's own choice, like a `'named'` host.
95
+ */
96
+ readonly proxy?: OutboundProxy | undefined;
64
97
  }
65
98
 
66
99
  export interface OutboundDeps {
package/src/outbound.ts CHANGED
@@ -86,6 +86,7 @@ function prepare(request: OutboundRequest, deps: OutboundDeps): AttemptCall {
86
86
  local: isLocal({ env: deps.env, fallback: 'production' }),
87
87
  fetch: send,
88
88
  resolve: deps.resolve,
89
+ proxy: request.proxy,
89
90
  endsAt: now() + deadlineMs,
90
91
  deadlineMs,
91
92
  idleMs: finiteCount('outbound()', 'idleMs', request.idleMs ?? OUTBOUND_IDLE_MS, 1),
@@ -0,0 +1,68 @@
1
+ // Single responsibility: the APP table of which `meta` keys a code's problem document carries, and
2
+ // the one key rule. Moved down from `@ultimat3/http`'s `problem-meta.ts` as `public-cause.ts` was, so
3
+ // `defineError` (tier 0, on `./page`) can take `problemMeta:` in the code's one declaration. No
4
+ // titles table, no http: an island declaring an app code pays a `Map` and a regex for it.
5
+
6
+ import { renderCauseValue } from './error-render';
7
+
8
+ /**
9
+ * A key is spelled the way a code's `meta` key is spelled in source. `issues` and `issuesTruncated`
10
+ * each already have a top-level home in the document; a second copy under `meta` is two places for
11
+ * a client to read one fact. `__proto__` is refused because the receiving `JSON.parse` mints it as
12
+ * a real own key.
13
+ */
14
+ const KEY = /^[A-Za-z_$][\w$]*$/;
15
+
16
+ /**
17
+ * Why `key` may not ride a document, or `undefined` when it may. The one rule for every writer: an
18
+ * app's `defineError` and `registerProblemMeta` refuse on it, and http's framework table is held to
19
+ * it by a test.
20
+ */
21
+ export function metaKeyRefusal(key: unknown): string | undefined {
22
+ if (typeof key !== 'string' || !KEY.test(key)) {
23
+ return `${renderCauseValue(key)} is not a meta key`;
24
+ }
25
+ if (key === 'issues' || key === 'issuesTruncated') {
26
+ return `\`${key}\` already rides at the top level of the document`;
27
+ }
28
+ if (key === '__proto__') return `\`${key}\` is not a key a document may carry`;
29
+ return undefined;
30
+ }
31
+
32
+ /** Per app-owned code, the `meta` keys its documents carry. A `Map`: an own-key read, always. */
33
+ const DECLARED = new Map<string, readonly string[]>();
34
+
35
+ const sameKeys = (left: readonly string[], right: readonly string[]): boolean =>
36
+ left.length === right.length && left.every((key, at) => key === right[at]);
37
+
38
+ /**
39
+ * Why `keys` may not be recorded for `code`, or `undefined`. Read BEFORE any write, so a refused
40
+ * declaration leaves no half behind. Whether the framework owns `code` is the caller's question:
41
+ * `defineError` already refuses a registered code, http refuses one its status table maps.
42
+ */
43
+ export function problemMetaRefusal(code: string, keys: readonly unknown[]): string | undefined {
44
+ if (keys.length === 0) return 'the key list is empty — omit the code instead';
45
+ for (const key of keys) {
46
+ const refusal = metaKeyRefusal(key);
47
+ if (refusal !== undefined) return refusal;
48
+ }
49
+ const existing = DECLARED.get(code);
50
+ if (existing !== undefined && !sameKeys(existing, keys as readonly string[])) {
51
+ return `already declared as [${existing.join(', ')}] by this app`;
52
+ }
53
+ return undefined;
54
+ }
55
+
56
+ /** The write, after `problemMetaRefusal` answered `undefined`. Copied, never aliased. */
57
+ export const recordProblemMeta = (code: string, keys: readonly string[]): void => {
58
+ DECLARED.set(code, [...keys]);
59
+ };
60
+
61
+ /** The keys an app declared for `code`, or `undefined`. http's `problemMetaKeysFor` reads it. */
62
+ export const declaredProblemMeta = (code: string): readonly string[] | undefined =>
63
+ DECLARED.get(code);
64
+
65
+ /** Test seam. Production declares once at boot and never forgets. */
66
+ export const resetDeclaredProblemMeta = (): void => {
67
+ DECLARED.clear();
68
+ };