@webpieces/http-client-core 0.4.798 → 0.4.799

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/http-client-core",
3
- "version": "0.4.798",
3
+ "version": "0.4.799",
4
4
  "description": "Isomorphic core of the webpieces HTTP client: the decorator-driven ProxyClient, error translation, and the Proxy trap shared by http-client-node and http-client-browser",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -21,6 +21,6 @@
21
21
  "access": "public"
22
22
  },
23
23
  "dependencies": {
24
- "@webpieces/core-util": "0.4.798"
24
+ "@webpieces/core-util": "0.4.799"
25
25
  }
26
26
  }
@@ -45,6 +45,11 @@ export declare abstract class ProxyClient {
45
45
  protected appFilters: ClientFilterDefinition[];
46
46
  private readonly networkRejectClassifier;
47
47
  private readonly bodyReader;
48
+ /**
49
+ * DTO -> wire bytes, in the encoding the endpoint declared. Stateless, so one instance per
50
+ * client; see {@link RequestBodySerializer} for why it lives outside this class.
51
+ */
52
+ private readonly bodySerializer;
48
53
  /**
49
54
  * fetch `Response` -> the transport-neutral {@link HttpResponseDto} the registered `ErrorTranslator`
50
55
  * sees. Normalising HERE is what makes `fromWire` receive the identical shape in node and in the
@@ -127,6 +132,21 @@ export declare abstract class ProxyClient {
127
132
  * The default is a no-op, so every existing subclass is unaffected.
128
133
  */
129
134
  protected onRequestEnd(_route: RouteMetadata, _outcome: RequestOutcome): void;
135
+ /**
136
+ * A settled response's headers -> the CALLER's context, so a value set by a callee travels UP the
137
+ * call tree hop by hop without anything in between naming HTTP.
138
+ *
139
+ * Fires on EVERY settled call, ok or error, because an error response carries the diagnostic
140
+ * headers you most want (which backend answered, why it was a cache miss). It does NOT fire when
141
+ * the transport never produced a response at all — there is nothing to read.
142
+ *
143
+ * The default is a no-op. Where the context LIVES is environment-specific (node: the ambient
144
+ * RequestContext; browser: the app-held store), so the two subclasses implement it and this class
145
+ * stays free of both. `destination` is threaded through unchanged from the request that produced
146
+ * this response: it is what decides whether a TRUSTED response key may be believed at all — see
147
+ * {@link DestinationTrust.allows}.
148
+ */
149
+ protected acceptResponseContext(_headers: Headers, _destination: DestinationTrust): void;
130
150
  /**
131
151
  * Bind this client to one API contract: read @ApiPath/@Endpoint/@Auth* off the prototype and
132
152
  * build the route map once. Each subclass's `init(api, config)` stores its own config, then
@@ -163,16 +183,19 @@ export declare abstract class ProxyClient {
163
183
  private responseStream;
164
184
  /** One streaming handshake. Subsequent events stay on this established transport. */
165
185
  private executeStreamingCall;
186
+ /**
187
+ * Hand a settled response's headers to {@link acceptResponseContext}, with the SAME
188
+ * {@link DestinationTrust} the request was built with. One private helper rather than the same
189
+ * four lines on each of the four settle paths, because a path that forgot it would silently stop
190
+ * propagating context upward with nothing failing.
191
+ */
192
+ private readResponseContext;
166
193
  private openStreamingTransport;
167
194
  /** Fresh filter-visible request metadata; the live request body is transport-owned. */
168
195
  private prepareStreamingRequest;
169
196
  private executeCall;
170
197
  /** Fresh mutable request for every attempt, including URL, headers, auth and body. */
171
198
  private prepareRequest;
172
- /** Serialize exactly the encoding the endpoint declared; GET is always bodyless. */
173
- private serializeBody;
174
- /** Flat form DTO -> deterministic urlencoded bytes, repeating array-valued fields. */
175
- private serializeForm;
176
199
  /**
177
200
  * ONE transmission — the bottom of the filter chain, and the only place `fetch` is called.
178
201
  *
@@ -6,6 +6,7 @@ const ClientRequest_1 = require("./ClientRequest");
6
6
  const ClientErrorTranslator_1 = require("./ClientErrorTranslator");
7
7
  const HttpResponseDtoFactory_1 = require("./HttpResponseDtoFactory");
8
8
  const RequestOutcome_1 = require("./RequestOutcome");
9
+ const RequestBodySerializer_1 = require("./RequestBodySerializer");
9
10
  const ResponseBodyReader_1 = require("./ResponseBodyReader");
10
11
  const NdjsonRequestStream_1 = require("./NdjsonRequestStream");
11
12
  const SseResponseStream_1 = require("./SseResponseStream");
@@ -62,6 +63,11 @@ class ProxyClient {
62
63
  networkRejectClassifier = new core_util_1.NetworkRejectClassifier();
63
64
  // Same shape and same reason: stateless, so it is constructed here rather than injected.
64
65
  bodyReader = new ResponseBodyReader_1.ResponseBodyReader();
66
+ /**
67
+ * DTO -> wire bytes, in the encoding the endpoint declared. Stateless, so one instance per
68
+ * client; see {@link RequestBodySerializer} for why it lives outside this class.
69
+ */
70
+ bodySerializer = new RequestBodySerializer_1.RequestBodySerializer();
65
71
  /**
66
72
  * fetch `Response` -> the transport-neutral {@link HttpResponseDto} the registered `ErrorTranslator`
67
73
  * sees. Normalising HERE is what makes `fromWire` receive the identical shape in node and in the
@@ -134,6 +140,21 @@ class ProxyClient {
134
140
  * The default is a no-op, so every existing subclass is unaffected.
135
141
  */
136
142
  onRequestEnd(_route, _outcome) { }
143
+ /**
144
+ * A settled response's headers -> the CALLER's context, so a value set by a callee travels UP the
145
+ * call tree hop by hop without anything in between naming HTTP.
146
+ *
147
+ * Fires on EVERY settled call, ok or error, because an error response carries the diagnostic
148
+ * headers you most want (which backend answered, why it was a cache miss). It does NOT fire when
149
+ * the transport never produced a response at all — there is nothing to read.
150
+ *
151
+ * The default is a no-op. Where the context LIVES is environment-specific (node: the ambient
152
+ * RequestContext; browser: the app-held store), so the two subclasses implement it and this class
153
+ * stays free of both. `destination` is threaded through unchanged from the request that produced
154
+ * this response: it is what decides whether a TRUSTED response key may be believed at all — see
155
+ * {@link DestinationTrust.allows}.
156
+ */
157
+ acceptResponseContext(_headers, _destination) { }
137
158
  // ---------------------------------------------------------------- contract binding
138
159
  /**
139
160
  * Bind this client to one API contract: read @ApiPath/@Endpoint/@Auth* off the prototype and
@@ -271,15 +292,29 @@ class ProxyClient {
271
292
  response = result.response;
272
293
  return result.upload;
273
294
  }), 30_000);
295
+ this.readResponseContext(route, response);
274
296
  this.onRequestEnd(route, new RequestOutcome_1.RequestOutcome(true, response?.status ?? 0, response?.headers));
275
297
  return requestStream;
276
298
  }
277
299
  catch (err) {
278
300
  const error = (0, core_util_1.toError)(err);
301
+ this.readResponseContext(route, response);
279
302
  this.onRequestEnd(route, new RequestOutcome_1.RequestOutcome(false, response?.status ?? 0, response?.headers, error));
280
303
  throw err;
281
304
  }
282
305
  }
306
+ /**
307
+ * Hand a settled response's headers to {@link acceptResponseContext}, with the SAME
308
+ * {@link DestinationTrust} the request was built with. One private helper rather than the same
309
+ * four lines on each of the four settle paths, because a path that forgot it would silently stop
310
+ * propagating context upward with nothing failing.
311
+ */
312
+ readResponseContext(route, response) {
313
+ if (response === undefined) {
314
+ return;
315
+ }
316
+ this.acceptResponseContext(response.headers, core_util_1.DestinationTrust.forAuthMode(route.authMeta?.mode));
317
+ }
283
318
  async openStreamingTransport(route, destination, deadlineSignal) {
284
319
  const metadata = route.streaming;
285
320
  if (!metadata)
@@ -341,9 +376,11 @@ class ProxyClient {
341
376
  }
342
377
  catch (err) {
343
378
  const error = (0, core_util_1.toError)(err);
379
+ this.readResponseContext(route, response);
344
380
  this.onRequestEnd(route, new RequestOutcome_1.RequestOutcome(false, response?.status ?? 0, response?.headers, error));
345
381
  throw err;
346
382
  }
383
+ this.readResponseContext(route, response);
347
384
  this.onRequestEnd(route, new RequestOutcome_1.RequestOutcome(true, response?.status ?? 0, response?.headers));
348
385
  return result;
349
386
  }
@@ -353,45 +390,12 @@ class ProxyClient {
353
390
  const baseUrl = await this.resolveBaseUrl();
354
391
  const mapped = core_util_1.HttpContractMapper.toWire(route.path, route.parameterBindings, route.bodyParameterIndex, args);
355
392
  const headers = new Map();
356
- const body = this.serializeBody(route, mapped.body, headers);
393
+ const body = this.bodySerializer.serialize(this.apiName, route, mapped.body, headers);
357
394
  const context = this.outboundContextHeaders(core_util_1.DestinationTrust.forAuthMode(route.authMeta?.mode));
358
395
  for (const entry of context.entries())
359
396
  headers.set(entry[0], entry[1]);
360
397
  return new ClientRequest_1.ClientRequest(route, this.apiName, baseUrl, headers, body, mapped.body, mapped.path);
361
398
  }
362
- /** Serialize exactly the encoding the endpoint declared; GET is always bodyless. */
363
- // webpieces-disable no-any-unknown -- request DTO type is erased at the generated proxy boundary
364
- serializeBody(route, requestDto, headers) {
365
- if (route.httpMethod === 'GET' || requestDto === undefined)
366
- return undefined;
367
- if (route.formPost) {
368
- headers.set('Content-Type', 'application/x-www-form-urlencoded');
369
- return this.serializeForm(requestDto, route);
370
- }
371
- headers.set('Content-Type', 'application/json');
372
- return JSON.stringify(requestDto);
373
- }
374
- /** Flat form DTO -> deterministic urlencoded bytes, repeating array-valued fields. */
375
- // webpieces-disable no-any-unknown -- form DTO fields are contract-owned and heterogeneous
376
- serializeForm(requestDto, route) {
377
- if (requestDto === null || typeof requestDto !== 'object' || Array.isArray(requestDto)) {
378
- throw new Error(`${this.apiName}.${route.methodName} declares formPost:true, so its body must be a flat object.`);
379
- }
380
- const params = new URLSearchParams();
381
- // webpieces-disable no-any-unknown -- checked object is narrowed to its contract-owned field bag
382
- for (const key of Object.keys(requestDto).sort()) {
383
- // webpieces-disable no-any-unknown -- checked object is narrowed to its contract-owned field bag
384
- const value = requestDto[key];
385
- if (value === undefined || value === null)
386
- continue;
387
- const values = Array.isArray(value) ? value : [value];
388
- for (const item of values) {
389
- if (item !== undefined && item !== null)
390
- params.append(key, String(item));
391
- }
392
- }
393
- return params.toString();
394
- }
395
399
  /**
396
400
  * ONE transmission — the bottom of the filter chain, and the only place `fetch` is called.
397
401
  *
@@ -1 +1 @@
1
- {"version":3,"file":"ProxyClient.js","sourceRoot":"","sources":["../../../../../packages/http/http-client-core/src/ProxyClient.ts"],"names":[],"mappings":";;;AAAA,oDAoB8B;AAG9B,mDAAgD;AAChD,mEAAgE;AAChE,qEAAkE;AAClE,qDAAkD;AAClD,6DAA0D;AAC1D,+DAA4D;AAC5D,2DAAwD;AACxD,yEAAsE;AAGtE,MAAM,wBAAwB;IAEb;IACA;IAFb,YACa,QAAkB,EAClB,MAA2B;QAD3B,aAAQ,GAAR,QAAQ,CAAU;QAClB,WAAM,GAAN,MAAM,CAAqB;IACrC,CAAC;CACP;A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Classifier,\n HttpContractMapper,\n RouteMetadataFactory,\n FilterChain,\n CallRegistry,\n CallDeadline,\n CallContext,\n DtoValue,\n RequestStream,\n ResponseStream,\n StreamTransportError,\n} from '@webpieces/core-util';\nimport { ApiPrototype } from './ApiPrototype';\nimport { ClientFilterDefinition } from './ClientFilter';\nimport { ClientRequest } from './ClientRequest';\nimport { ClientErrorTranslator } from './ClientErrorTranslator';\nimport { HttpResponseDtoFactory } from './HttpResponseDtoFactory';\nimport { RequestOutcome } from './RequestOutcome';\nimport { ResponseBodyReader } from './ResponseBodyReader';\nimport { NdjsonRequestStream } from './NdjsonRequestStream';\nimport { SseResponseStream } from './SseResponseStream';\nimport { StreamingCapabilityError } from './StreamingCapabilityError';\nimport { ByteReadableStream } from './ByteStream';\n\nclass OpenedStreamingTransport {\n constructor(\n readonly response: Response,\n readonly upload: NdjsonRequestStream,\n ) {}\n}\n\n/**\n * ProxyClient - the HTTP call engine behind one API contract's client proxy.\n *\n * Contains ONLY what a browser can run: the route map built from the contract's decorators, URL\n * assembly, `fetch`, error translation, and logging. It holds no context object, no credentials,\n * and no recorder — it ASKS ITSELF for those through the hooks below, and each subclass answers\n * from its own environment.\n *\n * That is why the class is abstract rather than parameterized by a collaborator: a shared\n * header-provider seam would drag Node's AsyncLocalStorage vocabulary into a browser bundle and the\n * browser's store vocabulary into a server, and neither has any use for the other.\n *\n * NodeProxyClient (@webpieces/http-client-node) -> RequestContext, Secrets, mintIdToken, recording\n * BrowserProxyClient (@webpieces/http-client-browser) -> an app-held store, no credentials, no recording\n *\n * TWO-PHASE: collaborators arrive on the subclass constructor (so a DI container can supply them),\n * while the per-client state — which contract, which target — arrives on the subclass's `init`,\n * which calls {@link initRoutes}. That is what lets a factory hold a `Provider<ProxyClient>` and\n * hand out a fresh, independently-configured client per contract.\n */\nexport abstract class ProxyClient {\n // Assigned by initRoutes(), which every subclass's init() calls immediately after construction.\n private routeMap!: Map<string, RouteMetadata>;\n private apiName!: string;\n private apiClass!: ApiPrototype<object>;\n\n /**\n * The OUTBOUND filter chain, built once at bind time from {@link clientFilters} and reused for\n * every call. Built once rather than per call because a filter is STATELESS by contract (the\n * per-call state is the {@link ClientRequest} the chain is handed), exactly as on the server.\n */\n private chain!: FilterChain<ClientRequest, Response>;\n\n /**\n * The app's own filters, as handed to `createRpcClient`. Set by {@link initRoutes} BEFORE it\n * calls {@link clientFilters}, so an environment's built-ins may read the app's intent off them\n * — @webpieces/http-client-node takes the SSRF policy from an installed `ContextBaseUrlFilter` / `ContextFullUrlFilter`\n * that way, which keeps the one legitimate relaxation at the same construction site as the\n * decision to be re-pointable at all.\n */\n protected appFilters: ClientFilterDefinition[] = [];\n\n // Stateless + dependency-free, so the browser bundle keeps no DI on the fetch path.\n private readonly networkRejectClassifier = new NetworkRejectClassifier();\n\n // Same shape and same reason: stateless, so it is constructed here rather than injected.\n private readonly bodyReader = new ResponseBodyReader();\n\n /**\n * fetch `Response` -> the transport-neutral {@link HttpResponseDto} the registered `ErrorTranslator`\n * sees. Normalising HERE is what makes `fromWire` receive the identical shape in node and in the\n * browser: both environments share this class, and this is the only place either builds a DTO.\n */\n private readonly responseDtoFactory = new HttpResponseDtoFactory();\n\n /**\n * @param logApiCall - built by the SUBCLASS's package around that environment's ApiCallContext\n * (node: RequestContextApiCallContext; browser: BrowserApiCallContext). REQUIRED, with no\n * default: core-util cannot construct either one, and a default here would have to reach for a\n * process-global — which is exactly the throw-on-first-call this parameter deleted.\n */\n constructor(protected readonly logApiCall: LogApiCallImpl) {}\n\n // ---------------------------------------------------------------- environment hooks\n\n /** The callee's base URL. Async because a server may derive it from container metadata. */\n protected abstract resolveBaseUrl(): Promise<string>;\n\n /**\n * Context headers to put on the wire. Server reads RequestContext; browser reads its store.\n *\n * `destination` is derived from THIS route's auth mode and decides whether TRUSTED context keys\n * (`x-user-id`, `x-org-id`, `x-webpieces-roles`) may ride along — see {@link DestinationTrust}.\n * It is a required argument on purpose: a defaulted \"send everything\" would put the permissive\n * answer one keystroke away and make the safe one opt-in.\n *\n * RENAMED from `outboundHeaders()` in the same change that added `destination`, and the rename IS\n * the migration. TypeScript accepts an override that declares FEWER parameters than its base, so a\n * downstream `protected override outboundHeaders(): Map<string, string>` would have kept compiling\n * and silently ignored the gate — the permissive behaviour surviving as a second spelling. Against\n * the NEW name that subclass fails twice over: `override` names a member the base no longer has,\n * and this abstract member is left unimplemented.\n */\n protected abstract outboundContextHeaders(destination: DestinationTrust): Map<string, string>;\n\n /**\n * Run the call. The default just logs it. Test-case RECORDING is a server concept, so\n * NodeProxyClient overrides this to capture the call when a recorder is in the context.\n *\n * Context fields are NOT passed in: a logging backend stamps them onto every record itself.\n */\n // webpieces-disable no-any-unknown -- DTO types are erased at the proxy boundary\n protected async execute(\n route: RouteMetadata,\n requestDto: unknown,\n // webpieces-disable no-any-unknown -- DTO types are erased at the proxy boundary\n method: () => Promise<unknown>,\n // webpieces-disable no-any-unknown -- DTO types are erased at the proxy boundary\n ): Promise<unknown> {\n // apiClass = the CONTRACT name (this.apiName, e.g. 'SaveApi') so this client log line MATCHES\n // the server's for the same call. A client has no impl class, so controllerName is omitted.\n const info = new ApiMethodInfo(\n 'client',\n this.apiName,\n route.methodName,\n undefined,\n route.mask,\n route.background,\n );\n return this.logApiCall.execute(info, requestDto, method);\n }\n\n /**\n * Reject, at bind time, an endpoint this environment cannot satisfy — e.g. a browser cannot\n * mint the OIDC token an @WpAuthOidc endpoint demands. Surfacing it here beats failing on the\n * first call in production. The default accepts everything.\n */\n protected assertEndpointSupported(_authMeta: AuthMeta | undefined, _methodName: string): void {}\n\n /**\n * The FRAMEWORK filters this environment installs on every client it builds, BENEATH whatever\n * the app passed to `createRpcClient`. The default installs none, so the browser runs the exact\n * code path it ran before the chain existed.\n *\n * \"Beneath\" is not a priority — see {@link initRoutes}. These are the filters that must judge\n * and sign what is ACTUALLY about to be sent, so no app priority may be allowed to get under\n * them: @webpieces/http-client-node installs its SSRF guard and its outbound-auth minter here,\n * and both would be defeated by an app filter that re-pointed the URL below them. Neither\n * concept can live in this class, because reading a RequestContext, resolving DNS and minting\n * an OIDC token are all things a browser bundle must never contain.\n */\n protected clientFilters(): ClientFilterDefinition[] {\n return [];\n }\n\n /** Whether fetch can read the response while its streaming request body remains open. */\n protected abstract supportsConcurrentDuplexFetch(): boolean;\n\n /** Environment-owned full-duplex transport after the shared filter chain has prepared it. */\n protected abstract sendStreamingTransport(\n request: ClientRequest,\n signal: AbortSignal,\n body: ByteReadableStream,\n ): Promise<Response>;\n\n /**\n * Fires before the logical call's attempts, once per RPC — the progress \"start marker\". Symmetric with\n * {@link onRequestEnd}: every start is followed by exactly one end, on every path, so a listener\n * can drive a counter (bar on / bar off) without leaking a permanently-spinning bar.\n *\n * The default is a no-op, so every existing subclass is unaffected.\n */\n protected onRequestStart(_route: RouteMetadata): void {}\n\n /**\n * Fires exactly ONCE after the call settles, on EVERY path (2xx, HTTP error, network reject) —\n * the \"stop marker\", carrying how it settled.\n *\n * Subsumes the older header-only hook: this is the ONLY place the `fetch` Response — and thus its\n * `Headers` — exists, so an app that needs to read a response header (e.g. a server-version stamp\n * for client↔server version matching) reads `outcome.headers` after settlement\n * and on both the ok and error paths. `outcome.ok`/`outcome.error` add the success-or-error\n * signal the header-only seam could not give.\n *\n * The default is a no-op, so every existing subclass is unaffected.\n */\n protected onRequestEnd(_route: RouteMetadata, _outcome: RequestOutcome): void {}\n\n // ---------------------------------------------------------------- contract binding\n\n /**\n * Bind this client to one API contract: read @ApiPath/@Endpoint/@Auth* off the prototype and\n * build the route map once. Each subclass's `init(api, config)` stores its own config, then\n * calls this.\n *\n * @param appFilters the app's OUTBOUND filters for this client, from `createRpcClient`. They are\n * merged with {@link clientFilters} and sorted by priority, highest OUTERMOST.\n * @throws Error if the prototype lacks @ApiPath, or declares an endpoint this environment\n * cannot satisfy (see {@link assertEndpointSupported}).\n */\n protected initRoutes(\n apiPrototype: ApiPrototype<object>,\n appFilters: ClientFilterDefinition[],\n ): void {\n this.appFilters = appFilters;\n this.apiClass = apiPrototype;\n if (!isApiPath(apiPrototype)) {\n const className = apiPrototype.name || 'Unknown';\n throw new Error(`Class ${className} must be decorated with @ApiPath()`);\n }\n\n const endpoints = getEndpoints(apiPrototype) || {};\n\n // apiName as the class name so client logs read \"SaveApi.save\", not \"undefined.save\"\n this.apiName = apiPrototype.name || 'UnknownApi';\n\n // Two endpoints on one method + path would dial the same URL; refuse the contract up front.\n RouteMetadataFactory.assertNoDuplicateRoutes(apiPrototype);\n\n this.routeMap = new Map<string, RouteMetadata>();\n for (const methodName of Object.keys(endpoints)) {\n // One shared factory joins and validates method/path/query/body metadata for every\n // transport, rather than letting each generated client reinterpret the decorators.\n const route = RouteMetadataFactory.create(apiPrototype, methodName);\n const authMeta = route.authMeta;\n this.assertEndpointSupported(authMeta, methodName);\n this.routeMap.set(methodName, route);\n }\n\n // APP filters first (highest priority OUTERMOST, matching the server's FilterMatcher), then\n // the framework built-ins, ALWAYS innermost. Two separate sorts rather than one over the\n // union, deliberately: an app priority orders app filters against each other and nothing\n // else, so no number an app can type — however large — gets underneath the SSRF guard or the\n // credential minter. A single sorted list would make \"displace the guard\" a matter of typing\n // a bigger integer, and a security control an app can outrank by accident is not a control.\n //\n // Sorted here, once, so FilterChain itself never sorts — priority lives on the DEFINITION,\n // not on the filter.\n const byPriority = (a: ClientFilterDefinition, b: ClientFilterDefinition): number =>\n b.priority - a.priority;\n const ordered = [\n ...[...this.appFilters].sort(byPriority),\n ...[...this.clientFilters()].sort(byPriority),\n ];\n this.chain = new FilterChain<ClientRequest, Response>(\n ordered.map((definition: ClientFilterDefinition) => definition.filter),\n );\n }\n\n /** The contract's class name, for logs and recordings. */\n protected contractName(): string {\n return this.apiName;\n }\n\n /** Check if a route exists for the given method name. */\n hasRoute(methodName: string): boolean {\n return this.routeMap.has(methodName);\n }\n\n /**\n * Get route metadata for a method name.\n * @throws Error if no route found\n */\n getRoute(methodName: string): RouteMetadata {\n const route = this.routeMap.get(methodName);\n if (!route) {\n throw new Error(`No route found for method ${methodName}`);\n }\n return route;\n }\n\n // ---------------------------------------------------------------- the call\n\n /**\n * FAIL FAST, PER METHOD, at call time: some endpoints exist for a caller that is not us, and this\n * proxy could only ever build a request they are obliged to reject. Refusing here rather than at\n * bind time means an api that MIXES such endpoints with normal ones still yields a working client\n * for the normal ones; only calling the un-callable method throws.\n *\n * @throws Error naming the endpoint, what it declared, and who its real caller is.\n */\n private refuseEndpointNoClientCanCall(route: RouteMetadata): void {\n const authMode = route.authMeta?.mode;\n // @WpAuthApiKey: the credential is a CUSTOMER-held key, and the header carrying it is the app's\n // ApiKeyHook's choice, so this client has nothing to send and the call is a guaranteed 401.\n if (authMode?.kind === 'apikey') {\n throw new Error(\n `${this.apiName}.${route.methodName} is @WpAuthApiKey('${authMode.regime}') — only the partner ` +\n `holding that api key can call it, and the header carrying it is the app's ApiKeyHook's choice, ` +\n `so a webpieces client has no credential to send.`,\n );\n }\n // @WpAuthWebhook is DELIBERATELY absent from this list. It used to be here, on the assumption\n // that the vendor is always somebody else — but `@WpAuthWebhook(name)` names a signing SCHEME,\n // not a direction, and for an OUTBOUND partner webhook WE are the vendor. The environment's\n // outbound-auth filter asks its bound signer to produce the signature, which is the exact\n // mirror of the inbound WebhookAuthCallback that verifies one.\n }\n\n /** One logical call: one lifecycle pair and log entry across all strategy attempts. */\n // webpieces-disable no-any-unknown -- request and response DTOs are erased at the proxy boundary\n async makeRequest(route: RouteMetadata, args: unknown[]): Promise<unknown> {\n this.refuseEndpointNoClientCanCall(route);\n if (route.streaming) return this.makeStreamingRequest(route, args);\n const mapped = HttpContractMapper.toWire(\n route.path,\n route.parameterBindings,\n route.bodyParameterIndex,\n args,\n );\n const logValue = mapped.body === undefined ? args : mapped.body;\n return this.execute(route, logValue, () => this.executeCall(route, args));\n }\n\n /** Open a typed stream without bypassing the ordinary context/auth/filter request pipeline. */\n // webpieces-disable no-any-unknown -- generated proxy arguments are runtime-validated here\n private async makeStreamingRequest(route: RouteMetadata, args: unknown[]): Promise<unknown> {\n if (!this.supportsConcurrentDuplexFetch()) {\n throw new StreamingCapabilityError(\n 'browser',\n 'Fetch request streaming is half-duplex and has no protocol-compatible full-duplex fallback.',\n );\n }\n const destination = this.responseStream(args);\n return this.execute(route, 'stream-open', () =>\n this.executeStreamingCall(route, destination),\n );\n }\n\n // webpieces-disable no-any-unknown -- generated proxy arguments are runtime-validated here\n private responseStream(args: unknown[]): ResponseStream<DtoValue> {\n const candidate = args[0];\n if (args.length !== 1 || typeof candidate !== 'object' || candidate === null) {\n throw new StreamTransportError(\n `${this.apiName} streaming methods require exactly one ResponseStream argument.`,\n );\n }\n // webpieces-disable no-any-unknown -- reflected method argument is narrowed by the method checks below\n const record = candidate as Record<string, unknown>;\n if (\n typeof record['event'] !== 'function' ||\n typeof record['fail'] !== 'function' ||\n typeof record['complete'] !== 'function' ||\n typeof record['onCancel'] !== 'function'\n ) {\n throw new StreamTransportError(\n `${this.apiName} streaming method argument does not implement ResponseStream.`,\n );\n }\n return candidate as ResponseStream<DtoValue>;\n }\n\n /** One streaming handshake. Subsequent events stay on this established transport. */\n private async executeStreamingCall(\n route: RouteMetadata,\n destination: ResponseStream<DtoValue>,\n ): Promise<RequestStream<DtoValue>> {\n this.onRequestStart(route);\n let response: Response | undefined;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- lifecycle reports the original handshake failure\n try {\n const requestStream = await CallRegistry.execute(\n this.apiClass,\n route.methodName,\n (timeoutMs: number) =>\n CallDeadline.run(\n timeoutMs,\n new CallContext(this.apiName, route.methodName),\n async (deadlineSignal: AbortSignal) => {\n const result = await this.openStreamingTransport(\n route,\n destination,\n deadlineSignal,\n );\n response = result.response;\n return result.upload;\n },\n ),\n 30_000,\n );\n this.onRequestEnd(\n route,\n new RequestOutcome(true, response?.status ?? 0, response?.headers),\n );\n return requestStream;\n } catch (err: unknown) {\n const error = toError(err);\n this.onRequestEnd(\n route,\n new RequestOutcome(false, response?.status ?? 0, response?.headers, error),\n );\n throw err;\n }\n }\n\n private async openStreamingTransport(\n route: RouteMetadata,\n destination: ResponseStream<DtoValue>,\n deadlineSignal: AbortSignal,\n ): Promise<OpenedStreamingTransport> {\n const metadata = route.streaming;\n if (!metadata) throw new StreamTransportError('Streaming metadata disappeared.');\n const request = await this.prepareStreamingRequest(route);\n const controller = new AbortController();\n deadlineSignal.addEventListener('abort', (): void => controller.abort(), { once: true });\n const upload = new NdjsonRequestStream(\n metadata,\n // webpieces-disable no-any-unknown -- AbortController accepts a platform-defined cancellation reason\n (reason?: unknown) => controller.abort(reason),\n );\n const response = await this.chain.execute(request, () =>\n this.sendStreamingOnce(request, controller.signal, upload.body),\n );\n if (!response.ok) {\n await upload.transportFailed(\n new StreamTransportError(\n `Streaming handshake failed with HTTP ${response.status}.`,\n ),\n );\n await this.readResponse(response, route);\n throw new StreamTransportError('Streaming handshake was rejected.');\n }\n const contentType = response.headers.get('content-type') ?? '';\n if (!contentType.toLowerCase().startsWith('text/event-stream')) {\n const error = new StreamTransportError(\n `Streaming response requires text/event-stream, received '${contentType || 'missing'}'.`,\n );\n await upload.transportFailed(error);\n throw error;\n }\n void new SseResponseStream()\n .consume(response, destination, metadata, upload)\n .catch(() => undefined);\n return new OpenedStreamingTransport(response, upload);\n }\n\n /** Fresh filter-visible request metadata; the live request body is transport-owned. */\n private async prepareStreamingRequest(route: RouteMetadata): Promise<ClientRequest> {\n const baseUrl = await this.resolveBaseUrl();\n const headers = new Map<string, string>();\n headers.set('Content-Type', 'application/x-ndjson');\n headers.set('Accept', 'text/event-stream');\n const context = this.outboundContextHeaders(\n DestinationTrust.forAuthMode(route.authMeta?.mode),\n );\n for (const entry of context.entries()) headers.set(entry[0], entry[1]);\n return new ClientRequest(route, this.apiName, baseUrl, headers, undefined, undefined);\n }\n\n // webpieces-disable no-any-unknown -- response DTO is erased at the proxy boundary\n private async executeCall(route: RouteMetadata, args: unknown[]): Promise<unknown> {\n this.onRequestStart(route);\n let response: Response | undefined;\n // webpieces-disable no-any-unknown -- response DTO is erased at the proxy boundary\n let result: unknown;\n // webpieces-disable no-unmanaged-exceptions -- report one logical END, preserving the original thrown value\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n result = await CallRegistry.execute(\n this.apiClass,\n route.methodName,\n (timeoutMs: number) => {\n response = undefined;\n return CallDeadline.run(\n timeoutMs,\n new CallContext(this.apiName, route.methodName),\n async (signal: AbortSignal) => {\n const request = await this.prepareRequest(route, args);\n CallDeadline.throwIfAborted(signal);\n const received = await this.chain.execute(request, () =>\n this.sendOnce(request, signal),\n );\n CallDeadline.throwIfAborted(signal);\n response = received;\n return this.readResponse(received, route);\n },\n );\n },\n 30_000,\n );\n } catch (err: unknown) {\n const error = toError(err);\n this.onRequestEnd(\n route,\n new RequestOutcome(false, response?.status ?? 0, response?.headers, error),\n );\n throw err;\n }\n this.onRequestEnd(\n route,\n new RequestOutcome(true, response?.status ?? 0, response?.headers),\n );\n return result;\n }\n\n /** Fresh mutable request for every attempt, including URL, headers, auth and body. */\n // webpieces-disable no-any-unknown -- request DTO is erased at the proxy boundary\n private async prepareRequest(route: RouteMetadata, args: unknown[]): Promise<ClientRequest> {\n const baseUrl = await this.resolveBaseUrl();\n const mapped = HttpContractMapper.toWire(\n route.path,\n route.parameterBindings,\n route.bodyParameterIndex,\n args,\n );\n const headers = new Map<string, string>();\n const body = this.serializeBody(route, mapped.body, headers);\n const context = this.outboundContextHeaders(\n DestinationTrust.forAuthMode(route.authMeta?.mode),\n );\n for (const entry of context.entries()) headers.set(entry[0], entry[1]);\n return new ClientRequest(\n route,\n this.apiName,\n baseUrl,\n headers,\n body,\n mapped.body,\n mapped.path,\n );\n }\n\n /** Serialize exactly the encoding the endpoint declared; GET is always bodyless. */\n // webpieces-disable no-any-unknown -- request DTO type is erased at the generated proxy boundary\n private serializeBody(\n route: RouteMetadata,\n requestDto: unknown,\n headers: Map<string, string>,\n ): string | undefined {\n if (route.httpMethod === 'GET' || requestDto === undefined) return undefined;\n if (route.formPost) {\n headers.set('Content-Type', 'application/x-www-form-urlencoded');\n return this.serializeForm(requestDto, route);\n }\n headers.set('Content-Type', 'application/json');\n return JSON.stringify(requestDto);\n }\n\n /** Flat form DTO -> deterministic urlencoded bytes, repeating array-valued fields. */\n // webpieces-disable no-any-unknown -- form DTO fields are contract-owned and heterogeneous\n private serializeForm(requestDto: unknown, route: RouteMetadata): string {\n if (requestDto === null || typeof requestDto !== 'object' || Array.isArray(requestDto)) {\n throw new Error(\n `${this.apiName}.${route.methodName} declares formPost:true, so its body must be a flat object.`,\n );\n }\n const params = new URLSearchParams();\n // webpieces-disable no-any-unknown -- checked object is narrowed to its contract-owned field bag\n for (const key of Object.keys(requestDto as Record<string, unknown>).sort()) {\n // webpieces-disable no-any-unknown -- checked object is narrowed to its contract-owned field bag\n const value = (requestDto as Record<string, unknown>)[key];\n if (value === undefined || value === null) continue;\n const values = Array.isArray(value) ? value : [value];\n for (const item of values) {\n if (item !== undefined && item !== null) params.append(key, String(item));\n }\n }\n return params.toString();\n }\n\n /**\n * ONE transmission — the bottom of the filter chain, and the only place `fetch` is called.\n *\n * Everything it sends comes off the {@link ClientRequest} as the chain left it, so a filter's\n * edits to the url, the headers or the serialized body are exactly what goes on the wire. It may\n * run more than once for a single RPC when a filter follows a redirect.\n *\n * A network reject (offline, DNS, CORS preflight) is classified into a typed ApiConnectionError here (a\n * genuine bug passes through untouched) so that filters above see the same typed error the caller\n * will, rather than a raw platform reject.\n */\n private async sendOnce(request: ClientRequest, signal: AbortSignal): Promise<Response> {\n CallDeadline.throwIfAborted(signal);\n const options: RequestInit = {\n method: request.route.httpMethod,\n signal,\n headers: request.headersAsRecord(),\n redirect:\n request.route.responseType === 'full' || !request.followRedirects\n ? 'manual'\n : 'follow',\n };\n if (request.body !== undefined) {\n options.body = request.body;\n }\n // webpieces-disable no-unmanaged-exceptions -- classify a network reject, then rethrow it typed\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-fetch -- this IS the generated-client implementation the rule points everyone to\n return await fetch(request.url, options);\n } catch (err: unknown) {\n const error = toError(err);\n throw this.networkRejectClassifier.toNetworkError(error, request.url);\n }\n }\n\n /** Node fetch's streaming upload option. Browser callers are refused before reaching here. */\n private async sendStreamingOnce(\n request: ClientRequest,\n signal: AbortSignal,\n body: ByteReadableStream,\n ): Promise<Response> {\n CallDeadline.throwIfAborted(signal);\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- platform rejects are normalized below\n try {\n return await this.sendStreamingTransport(request, signal, body);\n } catch (err: unknown) {\n const error = toError(err);\n throw this.networkRejectClassifier.toNetworkError(error, request.url);\n }\n }\n\n /** Body consumption is inside the attempt deadline, including non-JSON error bodies. */\n // webpieces-disable no-any-unknown -- response DTO is erased at the proxy boundary\n private async readResponse(response: Response, route: RouteMetadata): Promise<unknown> {\n const callId = `${this.apiName}.${route.methodName}`;\n if (route.responseType === 'full') {\n return this.responseDtoFactory.fromFetch(\n response,\n await this.readFullResponseBody(response),\n );\n }\n // 266 is protocol success, but its body represents an expected user exception.\n if (response.ok && response.status !== 266) {\n if (!this.bodyReader.isJson(response)) {\n throw new Error(\n this.bodyReader.describeForeignBody(response, callId, await response.text()),\n );\n }\n // webpieces-disable no-any-unknown -- a success body is the caller's own DTO, erased here\n const body: unknown = await response.json();\n // EVERY response passes the seam, 2xx included: an app whose 200 body signals failure\n // turns it into a throw here. The webpieces default returns silently, so the success\n // path is unchanged — and the body is parsed ONCE, because a fetch body reads once.\n ClientErrorTranslator.throwIfFailure(\n this.responseDtoFactory.fromFetch(response, body),\n );\n return body;\n }\n const protocolError = await this.bodyReader.readErrorBody(response, callId);\n // The mirror of what the SERVER's `toWire` wrote. `fromWire` throws, so this method cannot\n // return for a failure response — `throwIfFailure` puts the webpieces default behind an app\n // translator that forgets to, so the guarantee does not depend on app code being correct.\n ClientErrorTranslator.throwFailure(\n this.responseDtoFactory.fromFetch(response, protocolError),\n );\n }\n\n /** Preserve empty, JSON, and protocol text bodies for caller-owned full responses. */\n // webpieces-disable no-any-unknown -- a full response deliberately preserves the caller-owned body\n private async readFullResponseBody(response: Response): Promise<unknown> {\n if (response.status === 204 || response.status === 304) return undefined;\n const text = await response.text();\n if (text === '') return undefined;\n if (!this.bodyReader.isJson(response)) return text;\n // webpieces-disable no-any-unknown -- parsed JSON is returned untouched to the typed contract caller\n return JSON.parse(text) as unknown;\n }\n}\n"]}
1
+ {"version":3,"file":"ProxyClient.js","sourceRoot":"","sources":["../../../../../packages/http/http-client-core/src/ProxyClient.ts"],"names":[],"mappings":";;;AAAA,oDAoB8B;AAG9B,mDAAgD;AAChD,mEAAgE;AAChE,qEAAkE;AAClE,qDAAkD;AAClD,mEAAgE;AAChE,6DAA0D;AAC1D,+DAA4D;AAC5D,2DAAwD;AACxD,yEAAsE;AAGtE,MAAM,wBAAwB;IAEb;IACA;IAFb,YACa,QAAkB,EAClB,MAA2B;QAD3B,aAAQ,GAAR,QAAQ,CAAU;QAClB,WAAM,GAAN,MAAM,CAAqB;IACrC,CAAC;CACP;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAsB,WAAW;IA+CE;IA9C/B,gGAAgG;IACxF,QAAQ,CAA8B;IACtC,OAAO,CAAU;IACjB,QAAQ,CAAwB;IAExC;;;;OAIG;IACK,KAAK,CAAwC;IAErD;;;;;;OAMG;IACO,UAAU,GAA6B,EAAE,CAAC;IAEpD,oFAAoF;IACnE,uBAAuB,GAAG,IAAI,mCAAuB,EAAE,CAAC;IAEzE,yFAAyF;IACxE,UAAU,GAAG,IAAI,uCAAkB,EAAE,CAAC;IAEvD;;;OAGG;IACc,cAAc,GAAG,IAAI,6CAAqB,EAAE,CAAC;IAE9D;;;;OAIG;IACc,kBAAkB,GAAG,IAAI,+CAAsB,EAAE,CAAC;IAEnE;;;;;OAKG;IACH,YAA+B,UAA0B;QAA1B,eAAU,GAAV,UAAU,CAAgB;IAAG,CAAC;IAwB7D;;;;;OAKG;IACH,iFAAiF;IACvE,KAAK,CAAC,OAAO,CACnB,KAAoB,E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MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;YAC5C,sFAAsF;YACtF,qFAAqF;YACrF,oFAAoF;YACpF,6CAAqB,CAAC,cAAc,CAAC,IAAI,CAAC,kBAAkB,CAAC,SAAS,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC,CAAC;YACxF,OAAO,IAAI,CAAC;QAChB,CAAC;QACD,MAAM,aAAa,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,aAAa,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;QAC5E,2FAA2F;QAC3F,4FAA4F;QAC5F,0FAA0F;QAC1F,6CAAqB,CAAC,YAAY,CAC9B,IAAI,CAAC,kBAAkB,CAAC,SAAS,CAAC,QAAQ,EAAE,aAAa,CAAC,CAC7D,CAAC;IACN,CAAC;IAED,sFAAsF;IACtF,mGAAmG;IAC3F,KAAK,CAAC,oBAAoB,CAAC,QAAkB;QACjD,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG;YAAE,OAAO,SAAS,CAAC;QACzE,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QACnC,IAAI,IAAI,KAAK,EAAE;YAAE,OAAO,SAAS,CAAC;QAClC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,QAAQ,CAAC;YAAE,OAAO,IAAI,CAAC;QACnD,qGAAqG;QACrG,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAY,CAAC;IACvC,CAAC;CACJ;AA5mBD,kCA4mBC","sourcesContent":["import {\n isApiPath,\n getEndpoints,\n AuthMeta,\n DestinationTrust,\n RouteMetadata,\n LogApiCallImpl,\n ApiMethodInfo,\n toError,\n NetworkRejectClassifier,\n HttpContractMapper,\n RouteMetadataFactory,\n FilterChain,\n CallRegistry,\n CallDeadline,\n CallContext,\n DtoValue,\n RequestStream,\n ResponseStream,\n StreamTransportError,\n} from '@webpieces/core-util';\nimport { ApiPrototype } from './ApiPrototype';\nimport { ClientFilterDefinition } from './ClientFilter';\nimport { ClientRequest } from './ClientRequest';\nimport { ClientErrorTranslator } from './ClientErrorTranslator';\nimport { HttpResponseDtoFactory } from './HttpResponseDtoFactory';\nimport { RequestOutcome } from './RequestOutcome';\nimport { RequestBodySerializer } from './RequestBodySerializer';\nimport { ResponseBodyReader } from './ResponseBodyReader';\nimport { NdjsonRequestStream } from './NdjsonRequestStream';\nimport { SseResponseStream } from './SseResponseStream';\nimport { StreamingCapabilityError } from './StreamingCapabilityError';\nimport { ByteReadableStream } from './ByteStream';\n\nclass OpenedStreamingTransport {\n constructor(\n readonly response: Response,\n readonly upload: NdjsonRequestStream,\n ) {}\n}\n\n/**\n * ProxyClient - the HTTP call engine behind one API contract's client proxy.\n *\n * Contains ONLY what a browser can run: the route map built from the contract's decorators, URL\n * assembly, `fetch`, error translation, and logging. It holds no context object, no credentials,\n * and no recorder — it ASKS ITSELF for those through the hooks below, and each subclass answers\n * from its own environment.\n *\n * That is why the class is abstract rather than parameterized by a collaborator: a shared\n * header-provider seam would drag Node's AsyncLocalStorage vocabulary into a browser bundle and the\n * browser's store vocabulary into a server, and neither has any use for the other.\n *\n * NodeProxyClient (@webpieces/http-client-node) -> RequestContext, Secrets, mintIdToken, recording\n * BrowserProxyClient (@webpieces/http-client-browser) -> an app-held store, no credentials, no recording\n *\n * TWO-PHASE: collaborators arrive on the subclass constructor (so a DI container can supply them),\n * while the per-client state — which contract, which target — arrives on the subclass's `init`,\n * which calls {@link initRoutes}. That is what lets a factory hold a `Provider<ProxyClient>` and\n * hand out a fresh, independently-configured client per contract.\n */\nexport abstract class ProxyClient {\n // Assigned by initRoutes(), which every subclass's init() calls immediately after construction.\n private routeMap!: Map<string, RouteMetadata>;\n private apiName!: string;\n private apiClass!: ApiPrototype<object>;\n\n /**\n * The OUTBOUND filter chain, built once at bind time from {@link clientFilters} and reused for\n * every call. Built once rather than per call because a filter is STATELESS by contract (the\n * per-call state is the {@link ClientRequest} the chain is handed), exactly as on the server.\n */\n private chain!: FilterChain<ClientRequest, Response>;\n\n /**\n * The app's own filters, as handed to `createRpcClient`. Set by {@link initRoutes} BEFORE it\n * calls {@link clientFilters}, so an environment's built-ins may read the app's intent off them\n * — @webpieces/http-client-node takes the SSRF policy from an installed `ContextBaseUrlFilter` / `ContextFullUrlFilter`\n * that way, which keeps the one legitimate relaxation at the same construction site as the\n * decision to be re-pointable at all.\n */\n protected appFilters: ClientFilterDefinition[] = [];\n\n // Stateless + dependency-free, so the browser bundle keeps no DI on the fetch path.\n private readonly networkRejectClassifier = new NetworkRejectClassifier();\n\n // Same shape and same reason: stateless, so it is constructed here rather than injected.\n private readonly bodyReader = new ResponseBodyReader();\n\n /**\n * DTO -> wire bytes, in the encoding the endpoint declared. Stateless, so one instance per\n * client; see {@link RequestBodySerializer} for why it lives outside this class.\n */\n private readonly bodySerializer = new RequestBodySerializer();\n\n /**\n * fetch `Response` -> the transport-neutral {@link HttpResponseDto} the registered `ErrorTranslator`\n * sees. Normalising HERE is what makes `fromWire` receive the identical shape in node and in the\n * browser: both environments share this class, and this is the only place either builds a DTO.\n */\n private readonly responseDtoFactory = new HttpResponseDtoFactory();\n\n /**\n * @param logApiCall - built by the SUBCLASS's package around that environment's ApiCallContext\n * (node: RequestContextApiCallContext; browser: BrowserApiCallContext). REQUIRED, with no\n * default: core-util cannot construct either one, and a default here would have to reach for a\n * process-global — which is exactly the throw-on-first-call this parameter deleted.\n */\n constructor(protected readonly logApiCall: LogApiCallImpl) {}\n\n // ---------------------------------------------------------------- environment hooks\n\n /** The callee's base URL. Async because a server may derive it from container metadata. */\n protected abstract resolveBaseUrl(): Promise<string>;\n\n /**\n * Context headers to put on the wire. Server reads RequestContext; browser reads its store.\n *\n * `destination` is derived from THIS route's auth mode and decides whether TRUSTED context keys\n * (`x-user-id`, `x-org-id`, `x-webpieces-roles`) may ride along — see {@link DestinationTrust}.\n * It is a required argument on purpose: a defaulted \"send everything\" would put the permissive\n * answer one keystroke away and make the safe one opt-in.\n *\n * RENAMED from `outboundHeaders()` in the same change that added `destination`, and the rename IS\n * the migration. TypeScript accepts an override that declares FEWER parameters than its base, so a\n * downstream `protected override outboundHeaders(): Map<string, string>` would have kept compiling\n * and silently ignored the gate — the permissive behaviour surviving as a second spelling. Against\n * the NEW name that subclass fails twice over: `override` names a member the base no longer has,\n * and this abstract member is left unimplemented.\n */\n protected abstract outboundContextHeaders(destination: DestinationTrust): Map<string, string>;\n\n /**\n * Run the call. The default just logs it. Test-case RECORDING is a server concept, so\n * NodeProxyClient overrides this to capture the call when a recorder is in the context.\n *\n * Context fields are NOT passed in: a logging backend stamps them onto every record itself.\n */\n // webpieces-disable no-any-unknown -- DTO types are erased at the proxy boundary\n protected async execute(\n route: RouteMetadata,\n requestDto: unknown,\n // webpieces-disable no-any-unknown -- DTO types are erased at the proxy boundary\n method: () => Promise<unknown>,\n // webpieces-disable no-any-unknown -- DTO types are erased at the proxy boundary\n ): Promise<unknown> {\n // apiClass = the CONTRACT name (this.apiName, e.g. 'SaveApi') so this client log line MATCHES\n // the server's for the same call. A client has no impl class, so controllerName is omitted.\n const info = new ApiMethodInfo(\n 'client',\n this.apiName,\n route.methodName,\n undefined,\n route.mask,\n route.background,\n );\n return this.logApiCall.execute(info, requestDto, method);\n }\n\n /**\n * Reject, at bind time, an endpoint this environment cannot satisfy — e.g. a browser cannot\n * mint the OIDC token an @WpAuthOidc endpoint demands. Surfacing it here beats failing on the\n * first call in production. The default accepts everything.\n */\n protected assertEndpointSupported(_authMeta: AuthMeta | undefined, _methodName: string): void {}\n\n /**\n * The FRAMEWORK filters this environment installs on every client it builds, BENEATH whatever\n * the app passed to `createRpcClient`. The default installs none, so the browser runs the exact\n * code path it ran before the chain existed.\n *\n * \"Beneath\" is not a priority — see {@link initRoutes}. These are the filters that must judge\n * and sign what is ACTUALLY about to be sent, so no app priority may be allowed to get under\n * them: @webpieces/http-client-node installs its SSRF guard and its outbound-auth minter here,\n * and both would be defeated by an app filter that re-pointed the URL below them. Neither\n * concept can live in this class, because reading a RequestContext, resolving DNS and minting\n * an OIDC token are all things a browser bundle must never contain.\n */\n protected clientFilters(): ClientFilterDefinition[] {\n return [];\n }\n\n /** Whether fetch can read the response while its streaming request body remains open. */\n protected abstract supportsConcurrentDuplexFetch(): boolean;\n\n /** Environment-owned full-duplex transport after the shared filter chain has prepared it. */\n protected abstract sendStreamingTransport(\n request: ClientRequest,\n signal: AbortSignal,\n body: ByteReadableStream,\n ): Promise<Response>;\n\n /**\n * Fires before the logical call's attempts, once per RPC — the progress \"start marker\". Symmetric with\n * {@link onRequestEnd}: every start is followed by exactly one end, on every path, so a listener\n * can drive a counter (bar on / bar off) without leaking a permanently-spinning bar.\n *\n * The default is a no-op, so every existing subclass is unaffected.\n */\n protected onRequestStart(_route: RouteMetadata): void {}\n\n /**\n * Fires exactly ONCE after the call settles, on EVERY path (2xx, HTTP error, network reject) —\n * the \"stop marker\", carrying how it settled.\n *\n * Subsumes the older header-only hook: this is the ONLY place the `fetch` Response — and thus its\n * `Headers` — exists, so an app that needs to read a response header (e.g. a server-version stamp\n * for client↔server version matching) reads `outcome.headers` after settlement\n * and on both the ok and error paths. `outcome.ok`/`outcome.error` add the success-or-error\n * signal the header-only seam could not give.\n *\n * The default is a no-op, so every existing subclass is unaffected.\n */\n protected onRequestEnd(_route: RouteMetadata, _outcome: RequestOutcome): void {}\n\n /**\n * A settled response's headers -> the CALLER's context, so a value set by a callee travels UP the\n * call tree hop by hop without anything in between naming HTTP.\n *\n * Fires on EVERY settled call, ok or error, because an error response carries the diagnostic\n * headers you most want (which backend answered, why it was a cache miss). It does NOT fire when\n * the transport never produced a response at all — there is nothing to read.\n *\n * The default is a no-op. Where the context LIVES is environment-specific (node: the ambient\n * RequestContext; browser: the app-held store), so the two subclasses implement it and this class\n * stays free of both. `destination` is threaded through unchanged from the request that produced\n * this response: it is what decides whether a TRUSTED response key may be believed at all — see\n * {@link DestinationTrust.allows}.\n */\n protected acceptResponseContext(_headers: Headers, _destination: DestinationTrust): void {}\n\n // ---------------------------------------------------------------- contract binding\n\n /**\n * Bind this client to one API contract: read @ApiPath/@Endpoint/@Auth* off the prototype and\n * build the route map once. Each subclass's `init(api, config)` stores its own config, then\n * calls this.\n *\n * @param appFilters the app's OUTBOUND filters for this client, from `createRpcClient`. They are\n * merged with {@link clientFilters} and sorted by priority, highest OUTERMOST.\n * @throws Error if the prototype lacks @ApiPath, or declares an endpoint this environment\n * cannot satisfy (see {@link assertEndpointSupported}).\n */\n protected initRoutes(\n apiPrototype: ApiPrototype<object>,\n appFilters: ClientFilterDefinition[],\n ): void {\n this.appFilters = appFilters;\n this.apiClass = apiPrototype;\n if (!isApiPath(apiPrototype)) {\n const className = apiPrototype.name || 'Unknown';\n throw new Error(`Class ${className} must be decorated with @ApiPath()`);\n }\n\n const endpoints = getEndpoints(apiPrototype) || {};\n\n // apiName as the class name so client logs read \"SaveApi.save\", not \"undefined.save\"\n this.apiName = apiPrototype.name || 'UnknownApi';\n\n // Two endpoints on one method + path would dial the same URL; refuse the contract up front.\n RouteMetadataFactory.assertNoDuplicateRoutes(apiPrototype);\n\n this.routeMap = new Map<string, RouteMetadata>();\n for (const methodName of Object.keys(endpoints)) {\n // One shared factory joins and validates method/path/query/body metadata for every\n // transport, rather than letting each generated client reinterpret the decorators.\n const route = RouteMetadataFactory.create(apiPrototype, methodName);\n const authMeta = route.authMeta;\n this.assertEndpointSupported(authMeta, methodName);\n this.routeMap.set(methodName, route);\n }\n\n // APP filters first (highest priority OUTERMOST, matching the server's FilterMatcher), then\n // the framework built-ins, ALWAYS innermost. Two separate sorts rather than one over the\n // union, deliberately: an app priority orders app filters against each other and nothing\n // else, so no number an app can type — however large — gets underneath the SSRF guard or the\n // credential minter. A single sorted list would make \"displace the guard\" a matter of typing\n // a bigger integer, and a security control an app can outrank by accident is not a control.\n //\n // Sorted here, once, so FilterChain itself never sorts — priority lives on the DEFINITION,\n // not on the filter.\n const byPriority = (a: ClientFilterDefinition, b: ClientFilterDefinition): number =>\n b.priority - a.priority;\n const ordered = [\n ...[...this.appFilters].sort(byPriority),\n ...[...this.clientFilters()].sort(byPriority),\n ];\n this.chain = new FilterChain<ClientRequest, Response>(\n ordered.map((definition: ClientFilterDefinition) => definition.filter),\n );\n }\n\n /** The contract's class name, for logs and recordings. */\n protected contractName(): string {\n return this.apiName;\n }\n\n /** Check if a route exists for the given method name. */\n hasRoute(methodName: string): boolean {\n return this.routeMap.has(methodName);\n }\n\n /**\n * Get route metadata for a method name.\n * @throws Error if no route found\n */\n getRoute(methodName: string): RouteMetadata {\n const route = this.routeMap.get(methodName);\n if (!route) {\n throw new Error(`No route found for method ${methodName}`);\n }\n return route;\n }\n\n // ---------------------------------------------------------------- the call\n\n /**\n * FAIL FAST, PER METHOD, at call time: some endpoints exist for a caller that is not us, and this\n * proxy could only ever build a request they are obliged to reject. Refusing here rather than at\n * bind time means an api that MIXES such endpoints with normal ones still yields a working client\n * for the normal ones; only calling the un-callable method throws.\n *\n * @throws Error naming the endpoint, what it declared, and who its real caller is.\n */\n private refuseEndpointNoClientCanCall(route: RouteMetadata): void {\n const authMode = route.authMeta?.mode;\n // @WpAuthApiKey: the credential is a CUSTOMER-held key, and the header carrying it is the app's\n // ApiKeyHook's choice, so this client has nothing to send and the call is a guaranteed 401.\n if (authMode?.kind === 'apikey') {\n throw new Error(\n `${this.apiName}.${route.methodName} is @WpAuthApiKey('${authMode.regime}') — only the partner ` +\n `holding that api key can call it, and the header carrying it is the app's ApiKeyHook's choice, ` +\n `so a webpieces client has no credential to send.`,\n );\n }\n // @WpAuthWebhook is DELIBERATELY absent from this list. It used to be here, on the assumption\n // that the vendor is always somebody else — but `@WpAuthWebhook(name)` names a signing SCHEME,\n // not a direction, and for an OUTBOUND partner webhook WE are the vendor. The environment's\n // outbound-auth filter asks its bound signer to produce the signature, which is the exact\n // mirror of the inbound WebhookAuthCallback that verifies one.\n }\n\n /** One logical call: one lifecycle pair and log entry across all strategy attempts. */\n // webpieces-disable no-any-unknown -- request and response DTOs are erased at the proxy boundary\n async makeRequest(route: RouteMetadata, args: unknown[]): Promise<unknown> {\n this.refuseEndpointNoClientCanCall(route);\n if (route.streaming) return this.makeStreamingRequest(route, args);\n const mapped = HttpContractMapper.toWire(\n route.path,\n route.parameterBindings,\n route.bodyParameterIndex,\n args,\n );\n const logValue = mapped.body === undefined ? args : mapped.body;\n return this.execute(route, logValue, () => this.executeCall(route, args));\n }\n\n /** Open a typed stream without bypassing the ordinary context/auth/filter request pipeline. */\n // webpieces-disable no-any-unknown -- generated proxy arguments are runtime-validated here\n private async makeStreamingRequest(route: RouteMetadata, args: unknown[]): Promise<unknown> {\n if (!this.supportsConcurrentDuplexFetch()) {\n throw new StreamingCapabilityError(\n 'browser',\n 'Fetch request streaming is half-duplex and has no protocol-compatible full-duplex fallback.',\n );\n }\n const destination = this.responseStream(args);\n return this.execute(route, 'stream-open', () =>\n this.executeStreamingCall(route, destination),\n );\n }\n\n // webpieces-disable no-any-unknown -- generated proxy arguments are runtime-validated here\n private responseStream(args: unknown[]): ResponseStream<DtoValue> {\n const candidate = args[0];\n if (args.length !== 1 || typeof candidate !== 'object' || candidate === null) {\n throw new StreamTransportError(\n `${this.apiName} streaming methods require exactly one ResponseStream argument.`,\n );\n }\n // webpieces-disable no-any-unknown -- reflected method argument is narrowed by the method checks below\n const record = candidate as Record<string, unknown>;\n if (\n typeof record['event'] !== 'function' ||\n typeof record['fail'] !== 'function' ||\n typeof record['complete'] !== 'function' ||\n typeof record['onCancel'] !== 'function'\n ) {\n throw new StreamTransportError(\n `${this.apiName} streaming method argument does not implement ResponseStream.`,\n );\n }\n return candidate as ResponseStream<DtoValue>;\n }\n\n /** One streaming handshake. Subsequent events stay on this established transport. */\n private async executeStreamingCall(\n route: RouteMetadata,\n destination: ResponseStream<DtoValue>,\n ): Promise<RequestStream<DtoValue>> {\n this.onRequestStart(route);\n let response: Response | undefined;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- lifecycle reports the original handshake failure\n try {\n const requestStream = await CallRegistry.execute(\n this.apiClass,\n route.methodName,\n (timeoutMs: number) =>\n CallDeadline.run(\n timeoutMs,\n new CallContext(this.apiName, route.methodName),\n async (deadlineSignal: AbortSignal) => {\n const result = await this.openStreamingTransport(\n route,\n destination,\n deadlineSignal,\n );\n response = result.response;\n return result.upload;\n },\n ),\n 30_000,\n );\n this.readResponseContext(route, response);\n this.onRequestEnd(\n route,\n new RequestOutcome(true, response?.status ?? 0, response?.headers),\n );\n return requestStream;\n } catch (err: unknown) {\n const error = toError(err);\n this.readResponseContext(route, response);\n this.onRequestEnd(\n route,\n new RequestOutcome(false, response?.status ?? 0, response?.headers, error),\n );\n throw err;\n }\n }\n\n /**\n * Hand a settled response's headers to {@link acceptResponseContext}, with the SAME\n * {@link DestinationTrust} the request was built with. One private helper rather than the same\n * four lines on each of the four settle paths, because a path that forgot it would silently stop\n * propagating context upward with nothing failing.\n */\n private readResponseContext(route: RouteMetadata, response: Response | undefined): void {\n if (response === undefined) {\n return;\n }\n this.acceptResponseContext(\n response.headers,\n DestinationTrust.forAuthMode(route.authMeta?.mode),\n );\n }\n\n private async openStreamingTransport(\n route: RouteMetadata,\n destination: ResponseStream<DtoValue>,\n deadlineSignal: AbortSignal,\n ): Promise<OpenedStreamingTransport> {\n const metadata = route.streaming;\n if (!metadata) throw new StreamTransportError('Streaming metadata disappeared.');\n const request = await this.prepareStreamingRequest(route);\n const controller = new AbortController();\n deadlineSignal.addEventListener('abort', (): void => controller.abort(), { once: true });\n const upload = new NdjsonRequestStream(\n metadata,\n // webpieces-disable no-any-unknown -- AbortController accepts a platform-defined cancellation reason\n (reason?: unknown) => controller.abort(reason),\n );\n const response = await this.chain.execute(request, () =>\n this.sendStreamingOnce(request, controller.signal, upload.body),\n );\n if (!response.ok) {\n await upload.transportFailed(\n new StreamTransportError(\n `Streaming handshake failed with HTTP ${response.status}.`,\n ),\n );\n await this.readResponse(response, route);\n throw new StreamTransportError('Streaming handshake was rejected.');\n }\n const contentType = response.headers.get('content-type') ?? '';\n if (!contentType.toLowerCase().startsWith('text/event-stream')) {\n const error = new StreamTransportError(\n `Streaming response requires text/event-stream, received '${contentType || 'missing'}'.`,\n );\n await upload.transportFailed(error);\n throw error;\n }\n void new SseResponseStream()\n .consume(response, destination, metadata, upload)\n .catch(() => undefined);\n return new OpenedStreamingTransport(response, upload);\n }\n\n /** Fresh filter-visible request metadata; the live request body is transport-owned. */\n private async prepareStreamingRequest(route: RouteMetadata): Promise<ClientRequest> {\n const baseUrl = await this.resolveBaseUrl();\n const headers = new Map<string, string>();\n headers.set('Content-Type', 'application/x-ndjson');\n headers.set('Accept', 'text/event-stream');\n const context = this.outboundContextHeaders(\n DestinationTrust.forAuthMode(route.authMeta?.mode),\n );\n for (const entry of context.entries()) headers.set(entry[0], entry[1]);\n return new ClientRequest(route, this.apiName, baseUrl, headers, undefined, undefined);\n }\n\n // webpieces-disable no-any-unknown -- response DTO is erased at the proxy boundary\n private async executeCall(route: RouteMetadata, args: unknown[]): Promise<unknown> {\n this.onRequestStart(route);\n let response: Response | undefined;\n // webpieces-disable no-any-unknown -- response DTO is erased at the proxy boundary\n let result: unknown;\n // webpieces-disable no-unmanaged-exceptions -- report one logical END, preserving the original thrown value\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n result = await CallRegistry.execute(\n this.apiClass,\n route.methodName,\n (timeoutMs: number) => {\n response = undefined;\n return CallDeadline.run(\n timeoutMs,\n new CallContext(this.apiName, route.methodName),\n async (signal: AbortSignal) => {\n const request = await this.prepareRequest(route, args);\n CallDeadline.throwIfAborted(signal);\n const received = await this.chain.execute(request, () =>\n this.sendOnce(request, signal),\n );\n CallDeadline.throwIfAborted(signal);\n response = received;\n return this.readResponse(received, route);\n },\n );\n },\n 30_000,\n );\n } catch (err: unknown) {\n const error = toError(err);\n this.readResponseContext(route, response);\n this.onRequestEnd(\n route,\n new RequestOutcome(false, response?.status ?? 0, response?.headers, error),\n );\n throw err;\n }\n this.readResponseContext(route, response);\n this.onRequestEnd(\n route,\n new RequestOutcome(true, response?.status ?? 0, response?.headers),\n );\n return result;\n }\n\n /** Fresh mutable request for every attempt, including URL, headers, auth and body. */\n // webpieces-disable no-any-unknown -- request DTO is erased at the proxy boundary\n private async prepareRequest(route: RouteMetadata, args: unknown[]): Promise<ClientRequest> {\n const baseUrl = await this.resolveBaseUrl();\n const mapped = HttpContractMapper.toWire(\n route.path,\n route.parameterBindings,\n route.bodyParameterIndex,\n args,\n );\n const headers = new Map<string, string>();\n const body = this.bodySerializer.serialize(this.apiName, route, mapped.body, headers);\n const context = this.outboundContextHeaders(\n DestinationTrust.forAuthMode(route.authMeta?.mode),\n );\n for (const entry of context.entries()) headers.set(entry[0], entry[1]);\n return new ClientRequest(\n route,\n this.apiName,\n baseUrl,\n headers,\n body,\n mapped.body,\n mapped.path,\n );\n }\n\n /**\n * ONE transmission — the bottom of the filter chain, and the only place `fetch` is called.\n *\n * Everything it sends comes off the {@link ClientRequest} as the chain left it, so a filter's\n * edits to the url, the headers or the serialized body are exactly what goes on the wire. It may\n * run more than once for a single RPC when a filter follows a redirect.\n *\n * A network reject (offline, DNS, CORS preflight) is classified into a typed ApiConnectionError here (a\n * genuine bug passes through untouched) so that filters above see the same typed error the caller\n * will, rather than a raw platform reject.\n */\n private async sendOnce(request: ClientRequest, signal: AbortSignal): Promise<Response> {\n CallDeadline.throwIfAborted(signal);\n const options: RequestInit = {\n method: request.route.httpMethod,\n signal,\n headers: request.headersAsRecord(),\n redirect:\n request.route.responseType === 'full' || !request.followRedirects\n ? 'manual'\n : 'follow',\n };\n if (request.body !== undefined) {\n options.body = request.body;\n }\n // webpieces-disable no-unmanaged-exceptions -- classify a network reject, then rethrow it typed\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n // webpieces-disable no-fetch -- this IS the generated-client implementation the rule points everyone to\n return await fetch(request.url, options);\n } catch (err: unknown) {\n const error = toError(err);\n throw this.networkRejectClassifier.toNetworkError(error, request.url);\n }\n }\n\n /** Node fetch's streaming upload option. Browser callers are refused before reaching here. */\n private async sendStreamingOnce(\n request: ClientRequest,\n signal: AbortSignal,\n body: ByteReadableStream,\n ): Promise<Response> {\n CallDeadline.throwIfAborted(signal);\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- platform rejects are normalized below\n try {\n return await this.sendStreamingTransport(request, signal, body);\n } catch (err: unknown) {\n const error = toError(err);\n throw this.networkRejectClassifier.toNetworkError(error, request.url);\n }\n }\n\n /** Body consumption is inside the attempt deadline, including non-JSON error bodies. */\n // webpieces-disable no-any-unknown -- response DTO is erased at the proxy boundary\n private async readResponse(response: Response, route: RouteMetadata): Promise<unknown> {\n const callId = `${this.apiName}.${route.methodName}`;\n if (route.responseType === 'full') {\n return this.responseDtoFactory.fromFetch(\n response,\n await this.readFullResponseBody(response),\n );\n }\n // 266 is protocol success, but its body represents an expected user exception.\n if (response.ok && response.status !== 266) {\n if (!this.bodyReader.isJson(response)) {\n throw new Error(\n this.bodyReader.describeForeignBody(response, callId, await response.text()),\n );\n }\n // webpieces-disable no-any-unknown -- a success body is the caller's own DTO, erased here\n const body: unknown = await response.json();\n // EVERY response passes the seam, 2xx included: an app whose 200 body signals failure\n // turns it into a throw here. The webpieces default returns silently, so the success\n // path is unchanged — and the body is parsed ONCE, because a fetch body reads once.\n ClientErrorTranslator.throwIfFailure(this.responseDtoFactory.fromFetch(response, body));\n return body;\n }\n const protocolError = await this.bodyReader.readErrorBody(response, callId);\n // The mirror of what the SERVER's `toWire` wrote. `fromWire` throws, so this method cannot\n // return for a failure response — `throwIfFailure` puts the webpieces default behind an app\n // translator that forgets to, so the guarantee does not depend on app code being correct.\n ClientErrorTranslator.throwFailure(\n this.responseDtoFactory.fromFetch(response, protocolError),\n );\n }\n\n /** Preserve empty, JSON, and protocol text bodies for caller-owned full responses. */\n // webpieces-disable no-any-unknown -- a full response deliberately preserves the caller-owned body\n private async readFullResponseBody(response: Response): Promise<unknown> {\n if (response.status === 204 || response.status === 304) return undefined;\n const text = await response.text();\n if (text === '') return undefined;\n if (!this.bodyReader.isJson(response)) return text;\n // webpieces-disable no-any-unknown -- parsed JSON is returned untouched to the typed contract caller\n return JSON.parse(text) as unknown;\n }\n}\n"]}
@@ -0,0 +1,31 @@
1
+ import { RouteMetadata } from '@webpieces/core-util';
2
+ /**
3
+ * ONE outbound request DTO -> the bytes on the wire, in exactly the encoding the endpoint DECLARED.
4
+ *
5
+ * Extracted from {@link ProxyClient}, which had grown past this repo's file-size limit and was doing
6
+ * three unrelated jobs: driving the call lifecycle, talking to the transport, and turning a DTO into
7
+ * bytes. This is the third one, and it is the one with no dependency on any of the others — it is a
8
+ * pure transformation of a DTO plus its route, and it is where the `formPost` encoding rules live.
9
+ *
10
+ * Stateless, so `ProxyClient` holds one instance for its whole life. `apiName` is passed per call
11
+ * rather than bound at construction, because the serializer is built before the client is bound to a
12
+ * contract and the name is only ever used to make an error message say WHICH endpoint was wrong.
13
+ */
14
+ export declare class RequestBodySerializer {
15
+ /**
16
+ * The serialized body, or undefined when there is none — and the Content-Type header is SET here
17
+ * rather than by the caller, because the encoding and the header that declares it are one
18
+ * decision and splitting them is how they drift apart.
19
+ *
20
+ * GET is always bodyless: a GET with a body is accepted by some servers, dropped by some proxies
21
+ * and cached wrongly by others, so the contract's declared verb settles it.
22
+ */
23
+ serialize(apiName: string, route: RouteMetadata, requestDto: unknown, headers: Map<string, string>): string | undefined;
24
+ /**
25
+ * Flat form DTO -> deterministic urlencoded bytes, repeating array-valued fields.
26
+ *
27
+ * DETERMINISTIC (the keys are sorted) because a webhook vendor that signs a form body signs the
28
+ * bytes, so two runs of the same call have to produce the same string.
29
+ */
30
+ private serializeForm;
31
+ }
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RequestBodySerializer = void 0;
4
+ const core_util_1 = require("@webpieces/core-util");
5
+ /**
6
+ * ONE outbound request DTO -> the bytes on the wire, in exactly the encoding the endpoint DECLARED.
7
+ *
8
+ * Extracted from {@link ProxyClient}, which had grown past this repo's file-size limit and was doing
9
+ * three unrelated jobs: driving the call lifecycle, talking to the transport, and turning a DTO into
10
+ * bytes. This is the third one, and it is the one with no dependency on any of the others — it is a
11
+ * pure transformation of a DTO plus its route, and it is where the `formPost` encoding rules live.
12
+ *
13
+ * Stateless, so `ProxyClient` holds one instance for its whole life. `apiName` is passed per call
14
+ * rather than bound at construction, because the serializer is built before the client is bound to a
15
+ * contract and the name is only ever used to make an error message say WHICH endpoint was wrong.
16
+ */
17
+ class RequestBodySerializer {
18
+ /**
19
+ * The serialized body, or undefined when there is none — and the Content-Type header is SET here
20
+ * rather than by the caller, because the encoding and the header that declares it are one
21
+ * decision and splitting them is how they drift apart.
22
+ *
23
+ * GET is always bodyless: a GET with a body is accepted by some servers, dropped by some proxies
24
+ * and cached wrongly by others, so the contract's declared verb settles it.
25
+ */
26
+ // webpieces-disable no-any-unknown -- request DTO type is erased at the generated proxy boundary
27
+ serialize(apiName, route, requestDto, headers) {
28
+ if (route.httpMethod === 'GET' || requestDto === undefined) {
29
+ return undefined;
30
+ }
31
+ if (route.formPost) {
32
+ headers.set('Content-Type', 'application/x-www-form-urlencoded');
33
+ return this.serializeForm(apiName, requestDto, route);
34
+ }
35
+ headers.set('Content-Type', 'application/json');
36
+ return JSON.stringify(requestDto);
37
+ }
38
+ /**
39
+ * Flat form DTO -> deterministic urlencoded bytes, repeating array-valued fields.
40
+ *
41
+ * DETERMINISTIC (the keys are sorted) because a webhook vendor that signs a form body signs the
42
+ * bytes, so two runs of the same call have to produce the same string.
43
+ */
44
+ // webpieces-disable no-any-unknown -- form DTO fields are contract-owned and heterogeneous
45
+ serializeForm(apiName, requestDto, route) {
46
+ if (requestDto === null || typeof requestDto !== 'object' || Array.isArray(requestDto)) {
47
+ throw new core_util_1.ApiImplementationError(`${apiName}.${route.methodName} declares formPost:true, so its body must be a flat object.`);
48
+ }
49
+ const params = new URLSearchParams();
50
+ // webpieces-disable no-any-unknown -- checked object is narrowed to its contract-owned field bag
51
+ for (const key of Object.keys(requestDto).sort()) {
52
+ // webpieces-disable no-any-unknown -- checked object is narrowed to its contract-owned field bag
53
+ const value = requestDto[key];
54
+ if (value === undefined || value === null)
55
+ continue;
56
+ const values = Array.isArray(value) ? value : [value];
57
+ for (const item of values) {
58
+ if (item !== undefined && item !== null)
59
+ params.append(key, String(item));
60
+ }
61
+ }
62
+ return params.toString();
63
+ }
64
+ }
65
+ exports.RequestBodySerializer = RequestBodySerializer;
66
+ //# sourceMappingURL=RequestBodySerializer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RequestBodySerializer.js","sourceRoot":"","sources":["../../../../../packages/http/http-client-core/src/RequestBodySerializer.ts"],"names":[],"mappings":";;;AAAA,oDAA6E;AAE7E;;;;;;;;;;;GAWG;AACH,MAAa,qBAAqB;IAC9B;;;;;;;OAOG;IACH,iGAAiG;IACjG,SAAS,CACL,OAAe,EACf,KAAoB,EACpB,UAAmB,EACnB,OAA4B;QAE5B,IAAI,KAAK,CAAC,UAAU,KAAK,KAAK,IAAI,UAAU,KAAK,SAAS,EAAE,CAAC;YACzD,OAAO,SAAS,CAAC;QACrB,CAAC;QACD,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAC;YACjB,OAAO,CAAC,GAAG,CAAC,cAAc,EAAE,mCAAmC,CAAC,CAAC;YACjE,OAAO,IAAI,CAAC,aAAa,CAAC,OAAO,EAAE,UAAU,EAAE,KAAK,CAAC,CAAC;QAC1D,CAAC;QACD,OAAO,CAAC,GAAG,CAAC,cAAc,EAAE,kBAAkB,CAAC,CAAC;QAChD,OAAO,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;IACtC,CAAC;IAED;;;;;OAKG;IACH,2FAA2F;IACnF,aAAa,CAAC,OAAe,EAAE,UAAmB,EAAE,KAAoB;QAC5E,IAAI,UAAU,KAAK,IAAI,IAAI,OAAO,UAAU,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,CAAC;YACrF,MAAM,IAAI,kCAAsB,CAC5B,GAAG,OAAO,IAAI,KAAK,CAAC,UAAU,6DAA6D,CAC9F,CAAC;QACN,CAAC;QACD,MAAM,MAAM,GAAG,IAAI,eAAe,EAAE,CAAC;QACrC,iGAAiG;QACjG,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,UAAqC,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;YAC1E,iGAAiG;YACjG,MAAM,KAAK,GAAI,UAAsC,CAAC,GAAG,CAAC,CAAC;YAC3D,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI;gBAAE,SAAS;YACpD,MAAM,MAAM,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;YACtD,KAAK,MAAM,IAAI,IAAI,MAAM,EAAE,CAAC;gBACxB,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,KAAK,IAAI;oBAAE,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;YAC9E,CAAC;QACL,CAAC;QACD,OAAO,MAAM,CAAC,QAAQ,EAAE,CAAC;IAC7B,CAAC;CACJ;AArDD,sDAqDC","sourcesContent":["import { ApiImplementationError, RouteMetadata } from '@webpieces/core-util';\n\n/**\n * ONE outbound request DTO -> the bytes on the wire, in exactly the encoding the endpoint DECLARED.\n *\n * Extracted from {@link ProxyClient}, which had grown past this repo's file-size limit and was doing\n * three unrelated jobs: driving the call lifecycle, talking to the transport, and turning a DTO into\n * bytes. This is the third one, and it is the one with no dependency on any of the others — it is a\n * pure transformation of a DTO plus its route, and it is where the `formPost` encoding rules live.\n *\n * Stateless, so `ProxyClient` holds one instance for its whole life. `apiName` is passed per call\n * rather than bound at construction, because the serializer is built before the client is bound to a\n * contract and the name is only ever used to make an error message say WHICH endpoint was wrong.\n */\nexport class RequestBodySerializer {\n /**\n * The serialized body, or undefined when there is none — and the Content-Type header is SET here\n * rather than by the caller, because the encoding and the header that declares it are one\n * decision and splitting them is how they drift apart.\n *\n * GET is always bodyless: a GET with a body is accepted by some servers, dropped by some proxies\n * and cached wrongly by others, so the contract's declared verb settles it.\n */\n // webpieces-disable no-any-unknown -- request DTO type is erased at the generated proxy boundary\n serialize(\n apiName: string,\n route: RouteMetadata,\n requestDto: unknown,\n headers: Map<string, string>,\n ): string | undefined {\n if (route.httpMethod === 'GET' || requestDto === undefined) {\n return undefined;\n }\n if (route.formPost) {\n headers.set('Content-Type', 'application/x-www-form-urlencoded');\n return this.serializeForm(apiName, requestDto, route);\n }\n headers.set('Content-Type', 'application/json');\n return JSON.stringify(requestDto);\n }\n\n /**\n * Flat form DTO -> deterministic urlencoded bytes, repeating array-valued fields.\n *\n * DETERMINISTIC (the keys are sorted) because a webhook vendor that signs a form body signs the\n * bytes, so two runs of the same call have to produce the same string.\n */\n // webpieces-disable no-any-unknown -- form DTO fields are contract-owned and heterogeneous\n private serializeForm(apiName: string, requestDto: unknown, route: RouteMetadata): string {\n if (requestDto === null || typeof requestDto !== 'object' || Array.isArray(requestDto)) {\n throw new ApiImplementationError(\n `${apiName}.${route.methodName} declares formPost:true, so its body must be a flat object.`,\n );\n }\n const params = new URLSearchParams();\n // webpieces-disable no-any-unknown -- checked object is narrowed to its contract-owned field bag\n for (const key of Object.keys(requestDto as Record<string, unknown>).sort()) {\n // webpieces-disable no-any-unknown -- checked object is narrowed to its contract-owned field bag\n const value = (requestDto as Record<string, unknown>)[key];\n if (value === undefined || value === null) continue;\n const values = Array.isArray(value) ? value : [value];\n for (const item of values) {\n if (item !== undefined && item !== null) params.append(key, String(item));\n }\n }\n return params.toString();\n }\n}\n"]}
package/src/index.d.ts CHANGED
@@ -30,6 +30,7 @@ export type { ApiPrototype } from './ApiPrototype';
30
30
  export { buildClientProxy } from './buildClientProxy';
31
31
  export { ClientErrorTranslator } from './ClientErrorTranslator';
32
32
  export { HttpResponseDtoFactory } from './HttpResponseDtoFactory';
33
+ export { RequestBodySerializer } from './RequestBodySerializer';
33
34
  export { ResponseBodyReader } from './ResponseBodyReader';
34
35
  export { ClientRequest } from './ClientRequest';
35
36
  export { ClientFilterDefinition } from './ClientFilter';
package/src/index.js CHANGED
@@ -26,7 +26,7 @@
26
26
  * a browser bundle, and nothing browser-only (a ContextReader store) reaches a server.
27
27
  */
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.Utf8Codec = exports.StreamingCapabilityError = exports.StreamEnvelopeCodec = exports.SseResponseStream = exports.SseEventParser = exports.SseEvent = exports.NdjsonRequestStream = exports.ClientFilterDefinition = exports.ClientRequest = exports.ResponseBodyReader = exports.HttpResponseDtoFactory = exports.ClientErrorTranslator = exports.buildClientProxy = exports.RequestOutcome = exports.ProxyClient = void 0;
29
+ exports.Utf8Codec = exports.StreamingCapabilityError = exports.StreamEnvelopeCodec = exports.SseResponseStream = exports.SseEventParser = exports.SseEvent = exports.NdjsonRequestStream = exports.ClientFilterDefinition = exports.ClientRequest = exports.ResponseBodyReader = exports.RequestBodySerializer = exports.HttpResponseDtoFactory = exports.ClientErrorTranslator = exports.buildClientProxy = exports.RequestOutcome = exports.ProxyClient = void 0;
30
30
  var ProxyClient_1 = require("./ProxyClient");
31
31
  Object.defineProperty(exports, "ProxyClient", { enumerable: true, get: function () { return ProxyClient_1.ProxyClient; } });
32
32
  var RequestOutcome_1 = require("./RequestOutcome");
@@ -39,6 +39,8 @@ Object.defineProperty(exports, "ClientErrorTranslator", { enumerable: true, get:
39
39
  // ErrorTranslator sees, so node and browser hand `fromWire` the identical shape.
40
40
  var HttpResponseDtoFactory_1 = require("./HttpResponseDtoFactory");
41
41
  Object.defineProperty(exports, "HttpResponseDtoFactory", { enumerable: true, get: function () { return HttpResponseDtoFactory_1.HttpResponseDtoFactory; } });
42
+ var RequestBodySerializer_1 = require("./RequestBodySerializer");
43
+ Object.defineProperty(exports, "RequestBodySerializer", { enumerable: true, get: function () { return RequestBodySerializer_1.RequestBodySerializer; } });
42
44
  var ResponseBodyReader_1 = require("./ResponseBodyReader");
43
45
  Object.defineProperty(exports, "ResponseBodyReader", { enumerable: true, get: function () { return ResponseBodyReader_1.ResponseBodyReader; } });
44
46
  // The OUTBOUND filter chain: the mutable request a filter edits, and one registration of a filter
package/src/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/http/http-client-core/src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;;;AAEH,6CAA4C;AAAnC,0GAAA,WAAW,OAAA;AACpB,mDAAkD;AAAzC,gHAAA,cAAc,OAAA;AAEvB,uDAAsD;AAA7C,oHAAA,gBAAgB,OAAA;AACzB,iEAAgE;AAAvD,8HAAA,qBAAqB,OAAA;AAC9B,gGAAgG;AAChG,iFAAiF;AACjF,mEAAkE;AAAzD,gIAAA,sBAAsB,OAAA;AAC/B,2DAA0D;AAAjD,wHAAA,kBAAkB,OAAA;AAC3B,kGAAkG;AAClG,kFAAkF;AAClF,gEAAgE;AAChE,iDAAgD;AAAvC,8GAAA,aAAa,OAAA;AACtB,+CAAwD;AAA/C,sHAAA,sBAAsB,OAAA;AAE/B,6FAA6F;AAC7F,+FAA+F;AAC/F,6DAA4D;AAAnD,0HAAA,mBAAmB,OAAA;AAC5B,mDAA4D;AAAnD,0GAAA,QAAQ,OAAA;AAAE,gHAAA,cAAc,OAAA;AACjC,yDAAwD;AAA/C,sHAAA,iBAAiB,OAAA;AAC1B,6DAA4D;AAAnD,0HAAA,mBAAmB,OAAA;AAC5B,uEAAsE;AAA7D,oIAAA,wBAAwB,OAAA;AACjC,yCAAwC;AAA/B,sGAAA,SAAS,OAAA","sourcesContent":["/**\n * @webpieces/http-client-core\n *\n * The ISOMORPHIC core of the webpieces HTTP client — everything that reads an API contract's\n * decorators and turns a method call into an HTTP request, with no opinion about where the\n * magic context comes from or whether a DI container exists.\n *\n * You almost certainly want one of its two environment packages instead:\n * - Server: @webpieces/http-client-node (inversify-wired, reads RequestContext, mints OIDC)\n * - Browser: @webpieces/http-client-browser (no DI — React or Angular, app-managed context store)\n *\n * Architecture:\n * ```\n * http-api (defines the contract)\n * ^\n * +-- http-routing (server: contract -> handlers)\n * +-- http-client-core (contract -> HTTP requests) <- YOU ARE HERE\n * +-- http-client-node (RequestContext + Secrets + OIDC + inversify factory)\n * +-- http-client-browser (app-held store + plain factory, no DI)\n * ```\n *\n * There is no context/credential/recording seam here at all: ProxyClient is ABSTRACT and asks its\n * subclass for the base URL, the context headers, the log map, the outbound credential, and the\n * recorder. Nothing server-only (RequestContext, Secrets, mintIdToken, TestCaseRecorder) can reach\n * a browser bundle, and nothing browser-only (a ContextReader store) reaches a server.\n */\n\nexport { ProxyClient } from './ProxyClient';\nexport { RequestOutcome } from './RequestOutcome';\nexport type { ApiPrototype } from './ApiPrototype';\nexport { buildClientProxy } from './buildClientProxy';\nexport { ClientErrorTranslator } from './ClientErrorTranslator';\n// The CLIENT-side transport boundary: a fetch Response becomes the ONE HttpResponseDto an app's\n// ErrorTranslator sees, so node and browser hand `fromWire` the identical shape.\nexport { HttpResponseDtoFactory } from './HttpResponseDtoFactory';\nexport { ResponseBodyReader } from './ResponseBodyReader';\n// The OUTBOUND filter chain: the mutable request a filter edits, and one registration of a filter\n// at a priority. The `Filter`/`Service`/`FilterChain` abstraction itself lives in\n// @webpieces/core-util, shared with the server's inbound chain.\nexport { ClientRequest } from './ClientRequest';\nexport { ClientFilterDefinition } from './ClientFilter';\nexport type { ClientFilter } from './ClientFilter';\n// Generic streaming wire adapters: NDJSON uploads, request-scoped SSE downloads, and a typed\n// capability failure for runtimes that cannot safely keep both fetch halves open concurrently.\nexport { NdjsonRequestStream } from './NdjsonRequestStream';\nexport { SseEvent, SseEventParser } from './SseEventParser';\nexport { SseResponseStream } from './SseResponseStream';\nexport { StreamEnvelopeCodec } from './StreamEnvelopeCodec';\nexport { StreamingCapabilityError } from './StreamingCapabilityError';\nexport { Utf8Codec } from './Utf8Codec';\nexport type { ByteReadableStream, ByteStreamReader, ByteReadResult } from './ByteStream';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/http/http-client-core/src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;;;AAEH,6CAA4C;AAAnC,0GAAA,WAAW,OAAA;AACpB,mDAAkD;AAAzC,gHAAA,cAAc,OAAA;AAEvB,uDAAsD;AAA7C,oHAAA,gBAAgB,OAAA;AACzB,iEAAgE;AAAvD,8HAAA,qBAAqB,OAAA;AAC9B,gGAAgG;AAChG,iFAAiF;AACjF,mEAAkE;AAAzD,gIAAA,sBAAsB,OAAA;AAC/B,iEAAgE;AAAvD,8HAAA,qBAAqB,OAAA;AAC9B,2DAA0D;AAAjD,wHAAA,kBAAkB,OAAA;AAC3B,kGAAkG;AAClG,kFAAkF;AAClF,gEAAgE;AAChE,iDAAgD;AAAvC,8GAAA,aAAa,OAAA;AACtB,+CAAwD;AAA/C,sHAAA,sBAAsB,OAAA;AAE/B,6FAA6F;AAC7F,+FAA+F;AAC/F,6DAA4D;AAAnD,0HAAA,mBAAmB,OAAA;AAC5B,mDAA4D;AAAnD,0GAAA,QAAQ,OAAA;AAAE,gHAAA,cAAc,OAAA;AACjC,yDAAwD;AAA/C,sHAAA,iBAAiB,OAAA;AAC1B,6DAA4D;AAAnD,0HAAA,mBAAmB,OAAA;AAC5B,uEAAsE;AAA7D,oIAAA,wBAAwB,OAAA;AACjC,yCAAwC;AAA/B,sGAAA,SAAS,OAAA","sourcesContent":["/**\n * @webpieces/http-client-core\n *\n * The ISOMORPHIC core of the webpieces HTTP client — everything that reads an API contract's\n * decorators and turns a method call into an HTTP request, with no opinion about where the\n * magic context comes from or whether a DI container exists.\n *\n * You almost certainly want one of its two environment packages instead:\n * - Server: @webpieces/http-client-node (inversify-wired, reads RequestContext, mints OIDC)\n * - Browser: @webpieces/http-client-browser (no DI — React or Angular, app-managed context store)\n *\n * Architecture:\n * ```\n * http-api (defines the contract)\n * ^\n * +-- http-routing (server: contract -> handlers)\n * +-- http-client-core (contract -> HTTP requests) <- YOU ARE HERE\n * +-- http-client-node (RequestContext + Secrets + OIDC + inversify factory)\n * +-- http-client-browser (app-held store + plain factory, no DI)\n * ```\n *\n * There is no context/credential/recording seam here at all: ProxyClient is ABSTRACT and asks its\n * subclass for the base URL, the context headers, the log map, the outbound credential, and the\n * recorder. Nothing server-only (RequestContext, Secrets, mintIdToken, TestCaseRecorder) can reach\n * a browser bundle, and nothing browser-only (a ContextReader store) reaches a server.\n */\n\nexport { ProxyClient } from './ProxyClient';\nexport { RequestOutcome } from './RequestOutcome';\nexport type { ApiPrototype } from './ApiPrototype';\nexport { buildClientProxy } from './buildClientProxy';\nexport { ClientErrorTranslator } from './ClientErrorTranslator';\n// The CLIENT-side transport boundary: a fetch Response becomes the ONE HttpResponseDto an app's\n// ErrorTranslator sees, so node and browser hand `fromWire` the identical shape.\nexport { HttpResponseDtoFactory } from './HttpResponseDtoFactory';\nexport { RequestBodySerializer } from './RequestBodySerializer';\nexport { ResponseBodyReader } from './ResponseBodyReader';\n// The OUTBOUND filter chain: the mutable request a filter edits, and one registration of a filter\n// at a priority. The `Filter`/`Service`/`FilterChain` abstraction itself lives in\n// @webpieces/core-util, shared with the server's inbound chain.\nexport { ClientRequest } from './ClientRequest';\nexport { ClientFilterDefinition } from './ClientFilter';\nexport type { ClientFilter } from './ClientFilter';\n// Generic streaming wire adapters: NDJSON uploads, request-scoped SSE downloads, and a typed\n// capability failure for runtimes that cannot safely keep both fetch halves open concurrently.\nexport { NdjsonRequestStream } from './NdjsonRequestStream';\nexport { SseEvent, SseEventParser } from './SseEventParser';\nexport { SseResponseStream } from './SseResponseStream';\nexport { StreamEnvelopeCodec } from './StreamEnvelopeCodec';\nexport { StreamingCapabilityError } from './StreamingCapabilityError';\nexport { Utf8Codec } from './Utf8Codec';\nexport type { ByteReadableStream, ByteStreamReader, ByteReadResult } from './ByteStream';\n"]}