@webpieces/http-client-browser 0.4.933 → 0.4.935
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/README.md +36 -0
- package/package.json +3 -3
- package/src/BrowserProxyClient.d.ts +18 -1
- package/src/BrowserProxyClient.js +32 -0
- package/src/BrowserProxyClient.js.map +1 -1
- package/src/ClientConfig.d.ts +31 -2
- package/src/ClientConfig.js +21 -1
- package/src/ClientConfig.js.map +1 -1
- package/src/RpcClientProvider.d.ts +5 -2
- package/src/RpcClientProvider.js +7 -3
- package/src/RpcClientProvider.js.map +1 -1
- package/src/ServiceWorkerRouting.d.ts +25 -0
- package/src/ServiceWorkerRouting.js +30 -0
- package/src/ServiceWorkerRouting.js.map +1 -0
- package/src/ServiceWorkerSyntheticResponse.d.ts +32 -0
- package/src/ServiceWorkerSyntheticResponse.js +60 -0
- package/src/ServiceWorkerSyntheticResponse.js.map +1 -0
- package/src/index.d.ts +3 -1
- package/src/index.js +9 -1
- package/src/index.js.map +1 -1
package/README.md
CHANGED
|
@@ -35,3 +35,39 @@ Opt a contract in with `CallRegistry.setStrategy(new RetryStrategy(...).run, Cat
|
|
|
35
35
|
only a `CallOutcome.TRANSIENT_FAILURE` (from `ClientRegistry.classify`) on a `READ` /
|
|
36
36
|
`WRITE_IDEMPOTENT` endpoint, logs each retried attempt as `[API-client-attempt-TRANSIENT]`, and gives
|
|
37
37
|
up with a 502 `ApiRetriesExhaustedError`. See [client timeouts and testing](../../../docs/client-timeouts.md).
|
|
38
|
+
|
|
39
|
+
## Angular's service worker is bypassed by default (#1293)
|
|
40
|
+
|
|
41
|
+
Angular's service worker (ngsw) intercepts every fetch, cross-origin RPC included, and when the network
|
|
42
|
+
rejects it answers with a synthetic `504 Gateway Timeout` instead of passing the rejection on — so a
|
|
43
|
+
dropped connection looked exactly like a real gateway timeout. Every RPC url therefore carries the
|
|
44
|
+
`ngsw-bypass=true` QUERY parameter (not the header: a custom header is not CORS-safelisted). The fetch
|
|
45
|
+
then rejects natively and is typed `ApiConnectionError`; a 504 always means a real gateway timeout
|
|
46
|
+
(`ApiDependencyTimeoutError`). webpieces servers bind query parameters by name, so the extra key is ignored.
|
|
47
|
+
|
|
48
|
+
An app that wants its service worker to serve or cache a contract opts out per client with
|
|
49
|
+
`new ClientConfig(svc, role, CallMode.FOREGROUND, ServiceWorkerRouting.ALLOW)`. The fallback still
|
|
50
|
+
applies: ngsw's synthetic response (status 504, statusText `Gateway Timeout`, null body, NO headers)
|
|
51
|
+
is re-typed as `ApiConnectionError` whose `cause` is a `ServiceWorkerSyntheticResponseError` holding the
|
|
52
|
+
`Response`. A real gateway 504 has headers and stays `ApiDependencyTimeoutError`.
|
|
53
|
+
|
|
54
|
+
## Background calls: a per-call marker carried on the error (#1293)
|
|
55
|
+
|
|
56
|
+
Whether the user waits on a call depends on the CALL SITE — the same `listItems` is foreground behind a
|
|
57
|
+
Refresh button and background behind a poll timer. Build a second client for the same contract:
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
const itemsApi = factory.createRpcClient(ItemsApi, new ClientConfig('server', ClientRole.END_USER_CLIENT));
|
|
61
|
+
const itemsPoller = factory.createRpcClient(
|
|
62
|
+
ItemsApi,
|
|
63
|
+
new ClientConfig('server', ClientRole.END_USER_CLIENT, CallMode.BACKGROUND),
|
|
64
|
+
);
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
A BACKGROUND client's routes reach the `RequestLifecycleListener` with `route.hideProgress === true` and
|
|
68
|
+
`route.callMode === CallMode.BACKGROUND`, so no endpoint declaration is needed to keep a poll out of the
|
|
69
|
+
progress bar. Every failure it rejects with carries `err.callMode === CallMode.BACKGROUND` (typed on
|
|
70
|
+
`ApiError`; `CallModeMarker.of(err)` reads it off any thrown value), so a global `ErrorHandler` can
|
|
71
|
+
"log + report, no dialog" with no app-side bookkeeping. The error's class is unchanged — every
|
|
72
|
+
`instanceof` keeps working — and the property is non-enumerable, so it never reaches JSON or a log
|
|
73
|
+
record. A client bound with `Binder.createRpcClientAndBind` is FOREGROUND.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpieces/http-client-browser",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.935",
|
|
4
4
|
"description": "Browser HTTP client for webpieces: DI-free (React or Angular), app-managed context store, no AsyncLocalStorage",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
"access": "public"
|
|
23
23
|
},
|
|
24
24
|
"dependencies": {
|
|
25
|
-
"@webpieces/core-util": "0.4.
|
|
26
|
-
"@webpieces/http-client-core": "0.4.
|
|
25
|
+
"@webpieces/core-util": "0.4.935",
|
|
26
|
+
"@webpieces/http-client-core": "0.4.935"
|
|
27
27
|
}
|
|
28
28
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ContextMgr, DestinationTrust, RouteMetadata, ClientRole } from '@webpieces/core-util';
|
|
1
|
+
import { ContextMgr, DestinationTrust, RouteMetadata, ClientRole, CallMode } from '@webpieces/core-util';
|
|
2
2
|
import { ApiPrototype, ByteReadableStream, ClientRequest, ProxyClient, RequestOutcome } from '@webpieces/http-client-core';
|
|
3
3
|
import { ClientConfig } from './ClientConfig';
|
|
4
4
|
import { RequestLifecycleListener } from './RequestLifecycleListener';
|
|
@@ -17,6 +17,9 @@ export declare class BrowserProxyClient extends ProxyClient {
|
|
|
17
17
|
private readonly lifecycleListener?;
|
|
18
18
|
protected selectAuthMethod(route: RouteMetadata): import('@webpieces/core-util').AuthMode;
|
|
19
19
|
private config;
|
|
20
|
+
/** The query parameter Angular's service worker (`Driver.onFetch`) honours to skip a request. */
|
|
21
|
+
static readonly NGSW_BYPASS_PARAM = "ngsw-bypass";
|
|
22
|
+
private readonly syntheticResponse;
|
|
20
23
|
constructor(contextMgr: ContextMgr, lifecycleListener?: RequestLifecycleListener | undefined);
|
|
21
24
|
/** Bind this client to one API contract + base URL. */
|
|
22
25
|
init(apiPrototype: ApiPrototype<object>, config: ClientConfig): void;
|
|
@@ -32,6 +35,20 @@ export declare class BrowserProxyClient extends ProxyClient {
|
|
|
32
35
|
* relative. No `window` access, so this stays SSR-safe and testable.
|
|
33
36
|
*/
|
|
34
37
|
protected clientRole(): ClientRole;
|
|
38
|
+
/** From {@link ClientConfig.callMode}: a BACKGROUND client stamps every route and failure with it. */
|
|
39
|
+
protected callMode(): CallMode;
|
|
40
|
+
/**
|
|
41
|
+
* Append `ngsw-bypass=true` unless {@link ClientConfig.serviceWorker} is ALLOW (#1293), so ngsw
|
|
42
|
+
* never intercepts the RPC and a network reject arrives as a native reject — which
|
|
43
|
+
* `NetworkRejectClassifier` types as `ApiConnectionError` — instead of ngsw's synthetic 504.
|
|
44
|
+
*/
|
|
45
|
+
protected transportUrl(request: ClientRequest): string;
|
|
46
|
+
/**
|
|
47
|
+
* One transmission, then the fallback for a service worker that intercepted anyway (ALLOW, or a
|
|
48
|
+
* worker other than ngsw honouring nothing): its synthetic 504 becomes `ApiConnectionError` with
|
|
49
|
+
* the response as cause. A real gateway 504 has headers, so it stays `ApiDependencyTimeoutError`.
|
|
50
|
+
*/
|
|
51
|
+
protected sendOnce(request: ClientRequest, signal: AbortSignal): Promise<Response>;
|
|
35
52
|
protected resolveBaseUrl(): Promise<string>;
|
|
36
53
|
/** Browser Fetch request streaming is specified as half-duplex, not concurrent duplex. */
|
|
37
54
|
protected supportsConcurrentDuplexFetch(): boolean;
|
|
@@ -4,6 +4,8 @@ exports.BrowserProxyClient = void 0;
|
|
|
4
4
|
const core_util_1 = require("@webpieces/core-util");
|
|
5
5
|
const BrowserApiCallContext_1 = require("./BrowserApiCallContext");
|
|
6
6
|
const http_client_core_1 = require("@webpieces/http-client-core");
|
|
7
|
+
const ServiceWorkerRouting_1 = require("./ServiceWorkerRouting");
|
|
8
|
+
const ServiceWorkerSyntheticResponse_1 = require("./ServiceWorkerSyntheticResponse");
|
|
7
9
|
/**
|
|
8
10
|
* The browser {@link ProxyClient}. Reads context from the app-held store (via {@link ContextMgr}),
|
|
9
11
|
* because a browser has no ambient request scope.
|
|
@@ -26,6 +28,10 @@ class BrowserProxyClient extends http_client_core_1.ProxyClient {
|
|
|
26
28
|
return selected;
|
|
27
29
|
}
|
|
28
30
|
config;
|
|
31
|
+
/** The query parameter Angular's service worker (`Driver.onFetch`) honours to skip a request. */
|
|
32
|
+
static NGSW_BYPASS_PARAM = 'ngsw-bypass';
|
|
33
|
+
// Stateless, so constructed here rather than injected — the browser bundle keeps no DI on the fetch path.
|
|
34
|
+
syntheticResponse = new ServiceWorkerSyntheticResponse_1.ServiceWorkerSyntheticResponse();
|
|
29
35
|
constructor(contextMgr, lifecycleListener) {
|
|
30
36
|
// The browser's ApiCallContext, constructed here rather than installed at startup: its store
|
|
31
37
|
// is static, so every instance stamps into the one slot BrowserApiCallContext.snapshot()
|
|
@@ -55,6 +61,32 @@ class BrowserProxyClient extends http_client_core_1.ProxyClient {
|
|
|
55
61
|
clientRole() {
|
|
56
62
|
return this.config.role;
|
|
57
63
|
}
|
|
64
|
+
/** From {@link ClientConfig.callMode}: a BACKGROUND client stamps every route and failure with it. */
|
|
65
|
+
callMode() {
|
|
66
|
+
return this.config.callMode;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Append `ngsw-bypass=true` unless {@link ClientConfig.serviceWorker} is ALLOW (#1293), so ngsw
|
|
70
|
+
* never intercepts the RPC and a network reject arrives as a native reject — which
|
|
71
|
+
* `NetworkRejectClassifier` types as `ApiConnectionError` — instead of ngsw's synthetic 504.
|
|
72
|
+
*/
|
|
73
|
+
transportUrl(request) {
|
|
74
|
+
const url = request.url;
|
|
75
|
+
if (this.config.serviceWorker === ServiceWorkerRouting_1.ServiceWorkerRouting.ALLOW) {
|
|
76
|
+
return url;
|
|
77
|
+
}
|
|
78
|
+
const separator = url.includes('?') ? '&' : '?';
|
|
79
|
+
return `${url}${separator}${BrowserProxyClient.NGSW_BYPASS_PARAM}=true`;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* One transmission, then the fallback for a service worker that intercepted anyway (ALLOW, or a
|
|
83
|
+
* worker other than ngsw honouring nothing): its synthetic 504 becomes `ApiConnectionError` with
|
|
84
|
+
* the response as cause. A real gateway 504 has headers, so it stays `ApiDependencyTimeoutError`.
|
|
85
|
+
*/
|
|
86
|
+
async sendOnce(request, signal) {
|
|
87
|
+
const response = await super.sendOnce(request, signal);
|
|
88
|
+
return this.syntheticResponse.rejectIfSynthetic(response, request.url);
|
|
89
|
+
}
|
|
58
90
|
async resolveBaseUrl() {
|
|
59
91
|
return (await core_util_1.ClientRegistry.tryResolve(this.config.svcName)) ?? '';
|
|
60
92
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BrowserProxyClient.js","sourceRoot":"","sources":["../../../../../packages/http/http-client-browser/src/BrowserProxyClient.ts"],"names":[],"mappings":";;;AAAA,oDAQ8B;AAC9B,mEAAgE;AAChE,kEAOqC;AAIrC;;;;;;;;;GASG;AACH,MAAa,kBAAmB,SAAQ,8BAAW;IAY1B;IACA;IAZF,gBAAgB,CAAC,KAAoB;QACpD,MAAM,QAAQ,GAAG,KAAK,CAAC,QAAQ,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC,MAA+C,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,KAAK,IAAI,MAAM,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC;QACtJ,IAAI,CAAC,QAAQ,EAAE,CAAC;YACZ,MAAM,OAAO,GAAG,KAAK,CAAC,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,MAA+C,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,WAAW,MAAM,CAAC,MAAM,iBAAiB,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,IAA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OAOG;IACgB,qBAAqB,CACpC,OAAgB,EAChB,WAA6B;QAE7B,IAAI,CAAC,UAAU,CAAC,qBAAqB,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;IAChE,CAAC;IAED;;;OAGG;IACgB,cAAc,CAAC,KAAoB;QAClD,IAAI,CAAC,iBAAiB,EAAE,cAAc,CAAC,KAAK,CAAC,CAAC;IAClD,CAAC;IAEkB,YAAY,CAAC,KAAoB,EAAE,OAAuB;QACzE,IAAI,CAAC,iBAAiB,EAAE,YAAY,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IACzD,CAAC;IAED;;;;;;;;;;;;;;;OAeG;IACgB,uBAAuB,CAAC,KAAoB;QAC3D,MAAM,UAAU,GAAG,KAAK,CAAC,UAAU,CAAC;QACpC,IAAI,KAAK,CAAC,SAAS,IAAI,KAAK,CAAC,SAAS,CAAC,SAAS,KAAK,2BAAe,CAAC,QAAQ,EAAE,CAAC;YAC5E,MAAM,IAAI,2CAAwB,CAC9B,SAAS,EACT,oEAAoE,UAAU,OAAO,KAAK,CAAC,SAAS,CAAC,SAAS,GAAG,CACpH,CAAC;QACN,CAAC;QACD,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC,CAAC;IACjC,CAAC;CACJ;AAlID,gDAkIC","sourcesContent":["import {\n ContextMgr,\n ClientRegistry,\n DestinationTrust,\n LogApiCallImpl,\n RouteMetadata,\n StreamDirection,\n ClientRole,\n} from '@webpieces/core-util';\nimport { BrowserApiCallContext } from './BrowserApiCallContext';\nimport {\n ApiPrototype,\n ByteReadableStream,\n ClientRequest,\n ProxyClient,\n RequestOutcome,\n StreamingCapabilityError,\n} from '@webpieces/http-client-core';\nimport { ClientConfig } from './ClientConfig';\nimport { RequestLifecycleListener } from './RequestLifecycleListener';\n\n/**\n * The browser {@link ProxyClient}. Reads context from the app-held store (via {@link ContextMgr}),\n * because a browser has no ambient request scope.\n *\n * It attaches NO outbound credential and does NO recording — both inherit the base's no-ops. A\n * browser cannot mint an OIDC token and must never hold a shared secret; the user's JWT travels as\n * an ordinary transferred context key, set on the store at login.\n *\n * This is the ONLY class in webpieces that names ContextMgr.\n */\nexport class BrowserProxyClient extends ProxyClient {\n protected override selectAuthMethod(route: RouteMetadata): import('@webpieces/core-util').AuthMode {\n const selected = route.authMeta?.methods.find((method: import('@webpieces/core-util').AuthMode) => method.kind === 'jwt' || method.kind === 'public');\n if (!selected) {\n const methods = route.authMeta?.methods.map((method: import('@webpieces/core-util').AuthMode) => method.kind === 'apikey' ? `apiKey('${method.regime}', credentials)` : method.kind).join(', ');\n throw new Error(`Endpoint ${route.apiName}.${route.methodName} declares ${methods}. A browser cannot hold these credentials; call it from a server-side client with the configured verifier credentials.`);\n }\n return selected;\n }\n private config!: ClientConfig;\n\n constructor(\n private readonly contextMgr: ContextMgr,\n private readonly lifecycleListener?: RequestLifecycleListener,\n ) {\n // The browser's ApiCallContext, constructed here rather than installed at startup: its store\n // is static, so every instance stamps into the one slot BrowserApiCallContext.snapshot()\n // reads — which is how a browser logger folds the `api` tag into each line.\n super(new LogApiCallImpl(new BrowserApiCallContext()));\n }\n\n /** Bind this client to one API contract + base URL. */\n init(apiPrototype: ApiPrototype<object>, config: ClientConfig): void {\n this.config = config;\n // The browser factory does not take app filters yet, so this client runs the framework\n // built-ins only (today: none). The chain itself is isomorphic and ready for them.\n this.initRoutes(apiPrototype, []);\n }\n\n /**\n * The same chain every client runs — a ClientRegistry mapping, else the installed deriver — but\n * with the BROWSER's fallback: `''`, which makes the URL RELATIVE (`/auth/oauth`) and therefore\n * same-origin, by definition. A browser app almost always calls the backend that served it, so\n * that is the default, and an unregistered svcName must NEVER throw the way it used to — a\n * forgotten registration silently killed sign-in, the request never leaving the page.\n *\n * A mapping still wins, which is exactly how an Angular dev server on :4201 reaches its backend\n * on :8201, while the same bundle served BY that backend in prod registers nothing and goes\n * relative. No `window` access, so this stays SSR-safe and testable.\n */\n protected override clientRole(): ClientRole {\n return this.config.role;\n }\n\n protected override async resolveBaseUrl(): Promise<string> {\n return (await ClientRegistry.tryResolve(this.config.svcName)) ?? '';\n }\n\n /** Browser Fetch request streaming is specified as half-duplex, not concurrent duplex. */\n protected override supportsConcurrentDuplexFetch(): boolean {\n return false;\n }\n\n protected override sendStreamingTransport(\n _request: ClientRequest,\n _signal: AbortSignal,\n _body: ByteReadableStream,\n ): Promise<Response> {\n return Promise.reject(\n new StreamingCapabilityError(\n 'browser',\n 'Fetch request streaming is half-duplex and has no safe bidirectional fallback.',\n ),\n );\n }\n\n /**\n * `destination` is always the un-verifying kind here — {@link assertEndpointSupported} below\n * refuses to bind an oidcSameProject() / oidcSvcs(...) / sharedSecret(...) contract, so every browser destination is\n * jwt() or @WpAuthPublic — which means a browser never puts a trusted context key on the wire. It is\n * still threaded rather than short-circuited: the rule lives in ContextMgr, one place, for both\n * environments.\n */\n protected override outboundContextHeaders(destination: DestinationTrust): Map<string, string> {\n return this.contextMgr.buildOutboundHeaders(destination);\n }\n\n /**\n * Into the app-held store, via the same {@link ContextMgr} that owns the outbound direction — so\n * a value a server set reaches the page without the page naming a header.\n *\n * TRUSTED response keys are dropped there, by type: a browser store holds only untrusted values.\n * `destination` is threaded anyway rather than short-circuited here, for the reason the outbound\n * direction gives — the rule lives in ContextMgr, one place, for both environments.\n */\n protected override acceptResponseContext(\n headers: Headers,\n destination: DestinationTrust,\n ): void {\n this.contextMgr.acceptResponseHeaders(headers, destination);\n }\n\n /**\n * Forward the call's lifecycle to the app's listener, if one was registered on the factory. The\n * optional chain makes both a no-op when no listener is present — the default browser case.\n */\n protected override onRequestStart(route: RouteMetadata): void {\n this.lifecycleListener?.onRequestStart(route);\n }\n\n protected override onRequestEnd(route: RouteMetadata, outcome: RequestOutcome): void {\n this.lifecycleListener?.onRequestEnd(route, outcome);\n }\n\n /**\n * Reject a contract this browser cannot satisfy, at bind time rather than on the first call.\n * Both service-to-service modes need credentials only a server has: OIDC (oidcSameProject() / oidcSvcs(...)) needs a runtime\n * service account to mint a token, sharedSecret(...) needs a secret no browser may ship.\n *\n * @WpLocalOnly is deliberately NOT rejected: a browser calling a dev-only endpoint on the\n * developer's own server is the motivating case for that mode (shipping browser logs into the\n * server log). It needs no credential — the server refuses it off-local by not having the route.\n *\n * An exhaustive switch with NO `default`, like {@link DestinationTrust.forAuthMode} and\n * `AuthFilter.verifiesCaller`. This was a NEGATIVE allow-list (`kind !== 'oidc' && kind !==\n * 'shared-secret'`), which silently WAVED THROUGH any future AuthMode kind — the browser would\n * have bound a contract it cannot satisfy and failed on the first call instead of at bind time.\n * Adding `local-only` is what surfaced it: the third reader of the union should fail to compile\n * on a NEW kind for the same reason the other two do.\n */\n protected override assertEndpointSupported(route: RouteMetadata): void {\n const methodName = route.methodName;\n if (route.streaming && route.streaming.direction !== StreamDirection.RESPONSE) {\n throw new StreamingCapabilityError(\n 'browser',\n `Browser Fetch supports only @WpStream(StreamDirection.RESPONSE); ${methodName} is ${route.streaming.direction}.`,\n );\n }\n this.selectAuthMethod(route);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"BrowserProxyClient.js","sourceRoot":"","sources":["../../../../../packages/http/http-client-browser/src/BrowserProxyClient.ts"],"names":[],"mappings":";;;AAAA,oDAS8B;AAC9B,mEAAgE;AAChE,kEAOqC;AAGrC,iEAA8D;AAC9D,qFAAkF;AAElF;;;;;;;;;GASG;AACH,MAAa,kBAAmB,SAAQ,8BAAW;IAkB1B;IACA;IAlBF,gBAAgB,CAAC,KAAoB;QACpD,MAAM,QAAQ,GAAG,KAAK,CAAC,QAAQ,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC,MAA+C,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,KAAK,IAAI,MAAM,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC;QACtJ,IAAI,CAAC,QAAQ,EAAE,CAAC;YACZ,MAAM,OAAO,GAAG,KAAK,CAAC,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,MAA+C,EAAE,EAAE,CAAC,MAAM,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CAAC,KAAK,CAAC,CAAC;IAClD,CAAC;IAEkB,YAAY,CAAC,KAAoB,EAAE,OAAuB;QACzE,IAAI,CAAC,iBAAiB,EAAE,YAAY,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IACzD,CAAC;IAED;;;;;;;;;;;;;;;OAeG;IACgB,uBAAuB,CAAC,KAAoB;QAC3D,MAAM,UAAU,GAAG,KAAK,CAAC,UAAU,CAAC;QACpC,IAAI,KAAK,CAAC,SAAS,IAAI,KAAK,CAAC,SAAS,CAAC,SAAS,KAAK,2BAAe,CAAC,QAAQ,EAAE,CAAC;YAC5E,MAAM,IAAI,2CAAwB,CAC9B,SAAS,EACT,oEAAoE,UAAU,OAAO,KAAK,CAAC,SAAS,CAAC,SAAS,GAAG,CACpH,CAAC;QACN,CAAC;QACD,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC,CAAC;IACjC,CAAC;;AApKL,gDAqKC","sourcesContent":["import {\n ContextMgr,\n ClientRegistry,\n DestinationTrust,\n LogApiCallImpl,\n RouteMetadata,\n StreamDirection,\n ClientRole,\n CallMode,\n} from '@webpieces/core-util';\nimport { BrowserApiCallContext } from './BrowserApiCallContext';\nimport {\n ApiPrototype,\n ByteReadableStream,\n ClientRequest,\n ProxyClient,\n RequestOutcome,\n StreamingCapabilityError,\n} from '@webpieces/http-client-core';\nimport { ClientConfig } from './ClientConfig';\nimport { RequestLifecycleListener } from './RequestLifecycleListener';\nimport { ServiceWorkerRouting } from './ServiceWorkerRouting';\nimport { ServiceWorkerSyntheticResponse } from './ServiceWorkerSyntheticResponse';\n\n/**\n * The browser {@link ProxyClient}. Reads context from the app-held store (via {@link ContextMgr}),\n * because a browser has no ambient request scope.\n *\n * It attaches NO outbound credential and does NO recording — both inherit the base's no-ops. A\n * browser cannot mint an OIDC token and must never hold a shared secret; the user's JWT travels as\n * an ordinary transferred context key, set on the store at login.\n *\n * This is the ONLY class in webpieces that names ContextMgr.\n */\nexport class BrowserProxyClient extends ProxyClient {\n protected override selectAuthMethod(route: RouteMetadata): import('@webpieces/core-util').AuthMode {\n const selected = route.authMeta?.methods.find((method: import('@webpieces/core-util').AuthMode) => method.kind === 'jwt' || method.kind === 'public');\n if (!selected) {\n const methods = route.authMeta?.methods.map((method: import('@webpieces/core-util').AuthMode) => method.kind === 'apikey' ? `apiKey('${method.regime}', credentials)` : method.kind).join(', ');\n throw new Error(`Endpoint ${route.apiName}.${route.methodName} declares ${methods}. A browser cannot hold these credentials; call it from a server-side client with the configured verifier credentials.`);\n }\n return selected;\n }\n private config!: ClientConfig;\n\n /** The query parameter Angular's service worker (`Driver.onFetch`) honours to skip a request. */\n static readonly NGSW_BYPASS_PARAM = 'ngsw-bypass';\n\n // Stateless, so constructed here rather than injected — the browser bundle keeps no DI on the fetch path.\n private readonly syntheticResponse = new ServiceWorkerSyntheticResponse();\n\n constructor(\n private readonly contextMgr: ContextMgr,\n private readonly lifecycleListener?: RequestLifecycleListener,\n ) {\n // The browser's ApiCallContext, constructed here rather than installed at startup: its store\n // is static, so every instance stamps into the one slot BrowserApiCallContext.snapshot()\n // reads — which is how a browser logger folds the `api` tag into each line.\n super(new LogApiCallImpl(new BrowserApiCallContext()));\n }\n\n /** Bind this client to one API contract + base URL. */\n init(apiPrototype: ApiPrototype<object>, config: ClientConfig): void {\n this.config = config;\n // The browser factory does not take app filters yet, so this client runs the framework\n // built-ins only (today: none). The chain itself is isomorphic and ready for them.\n this.initRoutes(apiPrototype, []);\n }\n\n /**\n * The same chain every client runs — a ClientRegistry mapping, else the installed deriver — but\n * with the BROWSER's fallback: `''`, which makes the URL RELATIVE (`/auth/oauth`) and therefore\n * same-origin, by definition. A browser app almost always calls the backend that served it, so\n * that is the default, and an unregistered svcName must NEVER throw the way it used to — a\n * forgotten registration silently killed sign-in, the request never leaving the page.\n *\n * A mapping still wins, which is exactly how an Angular dev server on :4201 reaches its backend\n * on :8201, while the same bundle served BY that backend in prod registers nothing and goes\n * relative. No `window` access, so this stays SSR-safe and testable.\n */\n protected override clientRole(): ClientRole {\n return this.config.role;\n }\n\n /** From {@link ClientConfig.callMode}: a BACKGROUND client stamps every route and failure with it. */\n protected override callMode(): CallMode {\n return this.config.callMode;\n }\n\n /**\n * Append `ngsw-bypass=true` unless {@link ClientConfig.serviceWorker} is ALLOW (#1293), so ngsw\n * never intercepts the RPC and a network reject arrives as a native reject — which\n * `NetworkRejectClassifier` types as `ApiConnectionError` — instead of ngsw's synthetic 504.\n */\n protected override transportUrl(request: ClientRequest): string {\n const url = request.url;\n if (this.config.serviceWorker === ServiceWorkerRouting.ALLOW) {\n return url;\n }\n const separator = url.includes('?') ? '&' : '?';\n return `${url}${separator}${BrowserProxyClient.NGSW_BYPASS_PARAM}=true`;\n }\n\n /**\n * One transmission, then the fallback for a service worker that intercepted anyway (ALLOW, or a\n * worker other than ngsw honouring nothing): its synthetic 504 becomes `ApiConnectionError` with\n * the response as cause. A real gateway 504 has headers, so it stays `ApiDependencyTimeoutError`.\n */\n protected override async sendOnce(request: ClientRequest, signal: AbortSignal): Promise<Response> {\n const response = await super.sendOnce(request, signal);\n return this.syntheticResponse.rejectIfSynthetic(response, request.url);\n }\n\n protected override async resolveBaseUrl(): Promise<string> {\n return (await ClientRegistry.tryResolve(this.config.svcName)) ?? '';\n }\n\n /** Browser Fetch request streaming is specified as half-duplex, not concurrent duplex. */\n protected override supportsConcurrentDuplexFetch(): boolean {\n return false;\n }\n\n protected override sendStreamingTransport(\n _request: ClientRequest,\n _signal: AbortSignal,\n _body: ByteReadableStream,\n ): Promise<Response> {\n return Promise.reject(\n new StreamingCapabilityError(\n 'browser',\n 'Fetch request streaming is half-duplex and has no safe bidirectional fallback.',\n ),\n );\n }\n\n /**\n * `destination` is always the un-verifying kind here — {@link assertEndpointSupported} below\n * refuses to bind an oidcSameProject() / oidcSvcs(...) / sharedSecret(...) contract, so every browser destination is\n * jwt() or @WpAuthPublic — which means a browser never puts a trusted context key on the wire. It is\n * still threaded rather than short-circuited: the rule lives in ContextMgr, one place, for both\n * environments.\n */\n protected override outboundContextHeaders(destination: DestinationTrust): Map<string, string> {\n return this.contextMgr.buildOutboundHeaders(destination);\n }\n\n /**\n * Into the app-held store, via the same {@link ContextMgr} that owns the outbound direction — so\n * a value a server set reaches the page without the page naming a header.\n *\n * TRUSTED response keys are dropped there, by type: a browser store holds only untrusted values.\n * `destination` is threaded anyway rather than short-circuited here, for the reason the outbound\n * direction gives — the rule lives in ContextMgr, one place, for both environments.\n */\n protected override acceptResponseContext(\n headers: Headers,\n destination: DestinationTrust,\n ): void {\n this.contextMgr.acceptResponseHeaders(headers, destination);\n }\n\n /**\n * Forward the call's lifecycle to the app's listener, if one was registered on the factory. The\n * optional chain makes both a no-op when no listener is present — the default browser case.\n */\n protected override onRequestStart(route: RouteMetadata): void {\n this.lifecycleListener?.onRequestStart(route);\n }\n\n protected override onRequestEnd(route: RouteMetadata, outcome: RequestOutcome): void {\n this.lifecycleListener?.onRequestEnd(route, outcome);\n }\n\n /**\n * Reject a contract this browser cannot satisfy, at bind time rather than on the first call.\n * Both service-to-service modes need credentials only a server has: OIDC (oidcSameProject() / oidcSvcs(...)) needs a runtime\n * service account to mint a token, sharedSecret(...) needs a secret no browser may ship.\n *\n * @WpLocalOnly is deliberately NOT rejected: a browser calling a dev-only endpoint on the\n * developer's own server is the motivating case for that mode (shipping browser logs into the\n * server log). It needs no credential — the server refuses it off-local by not having the route.\n *\n * An exhaustive switch with NO `default`, like {@link DestinationTrust.forAuthMode} and\n * `AuthFilter.verifiesCaller`. This was a NEGATIVE allow-list (`kind !== 'oidc' && kind !==\n * 'shared-secret'`), which silently WAVED THROUGH any future AuthMode kind — the browser would\n * have bound a contract it cannot satisfy and failed on the first call instead of at bind time.\n * Adding `local-only` is what surfaced it: the third reader of the union should fail to compile\n * on a NEW kind for the same reason the other two do.\n */\n protected override assertEndpointSupported(route: RouteMetadata): void {\n const methodName = route.methodName;\n if (route.streaming && route.streaming.direction !== StreamDirection.RESPONSE) {\n throw new StreamingCapabilityError(\n 'browser',\n `Browser Fetch supports only @WpStream(StreamDirection.RESPONSE); ${methodName} is ${route.streaming.direction}.`,\n );\n }\n this.selectAuthMethod(route);\n }\n}\n"]}
|
package/src/ClientConfig.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { ClientRole } from '@webpieces/core-util';
|
|
1
|
+
import { CallMode, ClientRole } from '@webpieces/core-util';
|
|
2
|
+
import { ServiceWorkerRouting } from './ServiceWorkerRouting';
|
|
2
3
|
/**
|
|
3
4
|
* Per-client STATE for a browser HTTP client — nothing else. A plain class; it extends nothing and
|
|
4
5
|
* is unrelated to the server package's ClientConfig.
|
|
@@ -24,6 +25,20 @@ export declare class ClientConfig {
|
|
|
24
25
|
* right answer is opposite for the two, so no default could be right for both.
|
|
25
26
|
*/
|
|
26
27
|
readonly role: ClientRole;
|
|
28
|
+
/**
|
|
29
|
+
* Whether the user waits on this client's calls (#1293). The same contract may be built twice:
|
|
30
|
+
* once FOREGROUND for the Refresh button, once {@link CallMode.BACKGROUND} for the timer that
|
|
31
|
+
* polls it. A BACKGROUND client's routes carry `hideProgress` and `callMode`, and every
|
|
32
|
+
* failure it rejects with carries `err.callMode === CallMode.BACKGROUND` — the error's class is
|
|
33
|
+
* unchanged. FOREGROUND, the ordinary call, when omitted.
|
|
34
|
+
*/
|
|
35
|
+
readonly callMode: CallMode;
|
|
36
|
+
/**
|
|
37
|
+
* Whether the page's service worker may intercept these calls. {@link ServiceWorkerRouting.BYPASS}
|
|
38
|
+
* (append `ngsw-bypass=true`) when omitted, so a dropped connection is an `ApiConnectionError`
|
|
39
|
+
* and never Angular's synthetic 504 — see {@link ServiceWorkerRouting}.
|
|
40
|
+
*/
|
|
41
|
+
readonly serviceWorker: ServiceWorkerRouting;
|
|
27
42
|
constructor(
|
|
28
43
|
/** Service name; resolved to a base URL via ClientRegistry (registered at app startup). */
|
|
29
44
|
svcName: string,
|
|
@@ -35,5 +50,19 @@ export declare class ClientConfig {
|
|
|
35
50
|
* "this service's own credential is broken" (a 500 to its caller) for a server — and the
|
|
36
51
|
* right answer is opposite for the two, so no default could be right for both.
|
|
37
52
|
*/
|
|
38
|
-
role: ClientRole
|
|
53
|
+
role: ClientRole,
|
|
54
|
+
/**
|
|
55
|
+
* Whether the user waits on this client's calls (#1293). The same contract may be built twice:
|
|
56
|
+
* once FOREGROUND for the Refresh button, once {@link CallMode.BACKGROUND} for the timer that
|
|
57
|
+
* polls it. A BACKGROUND client's routes carry `hideProgress` and `callMode`, and every
|
|
58
|
+
* failure it rejects with carries `err.callMode === CallMode.BACKGROUND` — the error's class is
|
|
59
|
+
* unchanged. FOREGROUND, the ordinary call, when omitted.
|
|
60
|
+
*/
|
|
61
|
+
callMode?: CallMode,
|
|
62
|
+
/**
|
|
63
|
+
* Whether the page's service worker may intercept these calls. {@link ServiceWorkerRouting.BYPASS}
|
|
64
|
+
* (append `ngsw-bypass=true`) when omitted, so a dropped connection is an `ApiConnectionError`
|
|
65
|
+
* and never Angular's synthetic 504 — see {@link ServiceWorkerRouting}.
|
|
66
|
+
*/
|
|
67
|
+
serviceWorker?: ServiceWorkerRouting);
|
|
39
68
|
}
|
package/src/ClientConfig.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.ClientConfig = void 0;
|
|
4
|
+
const core_util_1 = require("@webpieces/core-util");
|
|
5
|
+
const ServiceWorkerRouting_1 = require("./ServiceWorkerRouting");
|
|
4
6
|
/**
|
|
5
7
|
* Per-client STATE for a browser HTTP client — nothing else. A plain class; it extends nothing and
|
|
6
8
|
* is unrelated to the server package's ClientConfig.
|
|
@@ -17,6 +19,8 @@ exports.ClientConfig = void 0;
|
|
|
17
19
|
class ClientConfig {
|
|
18
20
|
svcName;
|
|
19
21
|
role;
|
|
22
|
+
callMode;
|
|
23
|
+
serviceWorker;
|
|
20
24
|
constructor(
|
|
21
25
|
/** Service name; resolved to a base URL via ClientRegistry (registered at app startup). */
|
|
22
26
|
svcName,
|
|
@@ -28,9 +32,25 @@ class ClientConfig {
|
|
|
28
32
|
* "this service's own credential is broken" (a 500 to its caller) for a server — and the
|
|
29
33
|
* right answer is opposite for the two, so no default could be right for both.
|
|
30
34
|
*/
|
|
31
|
-
role
|
|
35
|
+
role,
|
|
36
|
+
/**
|
|
37
|
+
* Whether the user waits on this client's calls (#1293). The same contract may be built twice:
|
|
38
|
+
* once FOREGROUND for the Refresh button, once {@link CallMode.BACKGROUND} for the timer that
|
|
39
|
+
* polls it. A BACKGROUND client's routes carry `hideProgress` and `callMode`, and every
|
|
40
|
+
* failure it rejects with carries `err.callMode === CallMode.BACKGROUND` — the error's class is
|
|
41
|
+
* unchanged. FOREGROUND, the ordinary call, when omitted.
|
|
42
|
+
*/
|
|
43
|
+
callMode = core_util_1.CallMode.FOREGROUND,
|
|
44
|
+
/**
|
|
45
|
+
* Whether the page's service worker may intercept these calls. {@link ServiceWorkerRouting.BYPASS}
|
|
46
|
+
* (append `ngsw-bypass=true`) when omitted, so a dropped connection is an `ApiConnectionError`
|
|
47
|
+
* and never Angular's synthetic 504 — see {@link ServiceWorkerRouting}.
|
|
48
|
+
*/
|
|
49
|
+
serviceWorker = ServiceWorkerRouting_1.ServiceWorkerRouting.BYPASS) {
|
|
32
50
|
this.svcName = svcName;
|
|
33
51
|
this.role = role;
|
|
52
|
+
this.callMode = callMode;
|
|
53
|
+
this.serviceWorker = serviceWorker;
|
|
34
54
|
}
|
|
35
55
|
}
|
|
36
56
|
exports.ClientConfig = ClientConfig;
|
package/src/ClientConfig.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ClientConfig.js","sourceRoot":"","sources":["../../../../../packages/http/http-client-browser/src/ClientConfig.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"ClientConfig.js","sourceRoot":"","sources":["../../../../../packages/http/http-client-browser/src/ClientConfig.ts"],"names":[],"mappings":";;;AAAA,oDAA4D;AAC5D,iEAA8D;AAE9D;;;;;;;;;;;;GAYG;AACH,MAAa,YAAY;IAGD;IASA;IAQA;IAMA;IAzBpB;IACI,2FAA2F;IAC3E,OAAe;IAC/B;;;;;;;OAOG;IACa,IAAgB;IAChC;;;;;;OAMG;IACa,WAAqB,oBAAQ,CAAC,UAAU;IACxD;;;;OAIG;IACa,gBAAsC,2CAAoB,CAAC,MAAM;QAvBjE,YAAO,GAAP,OAAO,CAAQ;QASf,SAAI,GAAJ,IAAI,CAAY;QAQhB,aAAQ,GAAR,QAAQ,CAAgC;QAMxC,kBAAa,GAAb,aAAa,CAAoD;IAClF,CAAC;CACP;AA5BD,oCA4BC","sourcesContent":["import { CallMode, ClientRole } from '@webpieces/core-util';\nimport { ServiceWorkerRouting } from './ServiceWorkerRouting';\n\n/**\n * Per-client STATE for a browser HTTP client — nothing else. A plain class; it extends nothing and\n * is unrelated to the server package's ClientConfig.\n *\n * The base URL is resolved from `svcName` through the global {@link ClientRegistry}: a registered\n * mapping, else the installed deriver, else RELATIVE — i.e. the origin that served the page, which\n * is what a browser app calling its own backend wants and needs NO configuration. Register a mapping\n * only when the backend is somewhere else (an Angular dev server on :4201 reaching :8201). So this\n * config is just the svcName, and an unregistered one never throws.\n *\n * The context store is NOT config: it is a dependency of {@link ClientHttpBrowserFactory}, shared\n * by every client it builds.\n */\nexport class ClientConfig {\n constructor(\n /** Service name; resolved to a base URL via ClientRegistry (registered at app startup). */\n public readonly svcName: string,\n /**\n * WHO receives this client's responses — {@link ClientRole.SERVER} for a server calling\n * another server, {@link ClientRole.END_USER_CLIENT} for a client acting for a person (a\n * browser bundle, an Expo shell, a remote MCP client). REQUIRED, with no default (#1173): it\n * decides what a received 401 means — \"the user must log in again\" for an end-user client,\n * \"this service's own credential is broken\" (a 500 to its caller) for a server — and the\n * right answer is opposite for the two, so no default could be right for both.\n */\n public readonly role: ClientRole,\n /**\n * Whether the user waits on this client's calls (#1293). The same contract may be built twice:\n * once FOREGROUND for the Refresh button, once {@link CallMode.BACKGROUND} for the timer that\n * polls it. A BACKGROUND client's routes carry `hideProgress` and `callMode`, and every\n * failure it rejects with carries `err.callMode === CallMode.BACKGROUND` — the error's class is\n * unchanged. FOREGROUND, the ordinary call, when omitted.\n */\n public readonly callMode: CallMode = CallMode.FOREGROUND,\n /**\n * Whether the page's service worker may intercept these calls. {@link ServiceWorkerRouting.BYPASS}\n * (append `ngsw-bypass=true`) when omitted, so a dropped connection is an `ApiConnectionError`\n * and never Angular's synthetic 504 — see {@link ServiceWorkerRouting}.\n */\n public readonly serviceWorker: ServiceWorkerRouting = ServiceWorkerRouting.BYPASS,\n ) {}\n}\n"]}
|
|
@@ -14,8 +14,11 @@ export declare class RpcClientProvider<T extends object> {
|
|
|
14
14
|
constructor(provide: BrowserToken, api: ApiPrototype<T>, destination: string);
|
|
15
15
|
/**
|
|
16
16
|
* The app's own DI-provided {@link ClientConfig} is where this browser host DECLARED its
|
|
17
|
-
* {@link ClientConfig.role}; every bound client
|
|
18
|
-
* from the binding, so
|
|
17
|
+
* {@link ClientConfig.role} and {@link ClientConfig.serviceWorker} routing; every bound client
|
|
18
|
+
* takes both from it and only the destination from the binding, so each is stated once, by the
|
|
19
|
+
* app. A bound client is always FOREGROUND: a BACKGROUND client is a second client for the same
|
|
20
|
+
* contract, built at the call site that polls with `factory.createRpcClient(Api,
|
|
21
|
+
* new ClientConfig(svc, role, CallMode.BACKGROUND))`.
|
|
19
22
|
*/
|
|
20
23
|
readonly useFactory: (factory: ClientHttpBrowserFactory, config: ClientConfig) => T;
|
|
21
24
|
}
|
package/src/RpcClientProvider.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.RpcClientProvider = void 0;
|
|
4
|
+
const core_util_1 = require("@webpieces/core-util");
|
|
4
5
|
const ClientHttpBrowserFactory_1 = require("./ClientHttpBrowserFactory");
|
|
5
6
|
const ClientConfig_1 = require("./ClientConfig");
|
|
6
7
|
/**
|
|
@@ -19,10 +20,13 @@ class RpcClientProvider {
|
|
|
19
20
|
}
|
|
20
21
|
/**
|
|
21
22
|
* The app's own DI-provided {@link ClientConfig} is where this browser host DECLARED its
|
|
22
|
-
* {@link ClientConfig.role}; every bound client
|
|
23
|
-
* from the binding, so
|
|
23
|
+
* {@link ClientConfig.role} and {@link ClientConfig.serviceWorker} routing; every bound client
|
|
24
|
+
* takes both from it and only the destination from the binding, so each is stated once, by the
|
|
25
|
+
* app. A bound client is always FOREGROUND: a BACKGROUND client is a second client for the same
|
|
26
|
+
* contract, built at the call site that polls with `factory.createRpcClient(Api,
|
|
27
|
+
* new ClientConfig(svc, role, CallMode.BACKGROUND))`.
|
|
24
28
|
*/
|
|
25
|
-
useFactory = (factory, config) => factory.createRpcClient(this.api, new ClientConfig_1.ClientConfig(this.destination, config.role));
|
|
29
|
+
useFactory = (factory, config) => factory.createRpcClient(this.api, new ClientConfig_1.ClientConfig(this.destination, config.role, core_util_1.CallMode.FOREGROUND, config.serviceWorker));
|
|
26
30
|
}
|
|
27
31
|
exports.RpcClientProvider = RpcClientProvider;
|
|
28
32
|
//# sourceMappingURL=RpcClientProvider.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RpcClientProvider.js","sourceRoot":"","sources":["../../../../../packages/http/http-client-browser/src/RpcClientProvider.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"RpcClientProvider.js","sourceRoot":"","sources":["../../../../../packages/http/http-client-browser/src/RpcClientProvider.ts"],"names":[],"mappings":";;;AAAA,oDAAgD;AAGhD,yEAAsE;AACtE,iDAA8C;AAE9C;;;GAGG;AACH,MAAa,iBAAiB;IAIN;IACC;IACA;IALZ,IAAI,GAAG,CAAC,mDAAwB,EAAE,2BAAY,CAAC,CAAC;IAEzD,YACoB,OAAqB,EACpB,GAAoB,EACpB,WAAmB;QAFpB,YAAO,GAAP,OAAO,CAAc;QACpB,QAAG,GAAH,GAAG,CAAiB;QACpB,gBAAW,GAAX,WAAW,CAAQ;IACrC,CAAC;IAEJ;;;;;;;OAOG;IACM,UAAU,GAAG,CAAC,OAAiC,EAAE,MAAoB,EAAK,EAAE,CACjF,OAAO,CAAC,eAAe,CACnB,IAAI,CAAC,GAAG,EACR,IAAI,2BAAY,CAAC,IAAI,CAAC,WAAW,EAAE,MAAM,CAAC,IAAI,EAAE,oBAAQ,CAAC,UAAU,EAAE,MAAM,CAAC,aAAa,CAAC,CAC7F,CAAC;CACT;AAtBD,8CAsBC","sourcesContent":["import { CallMode } from '@webpieces/core-util';\nimport type { ApiPrototype } from '@webpieces/http-client-core';\nimport type { BrowserToken } from './BrowserProviders';\nimport { ClientHttpBrowserFactory } from './ClientHttpBrowserFactory';\nimport { ClientConfig } from './ClientConfig';\n\n/**\n * Structurally compatible Angular factory provider, created by Binder.createRpcClientAndBind. The\n * token remains overrideable and the client is created lazily, on first inject.\n */\nexport class RpcClientProvider<T extends object> {\n readonly deps = [ClientHttpBrowserFactory, ClientConfig];\n\n constructor(\n public readonly provide: BrowserToken,\n private readonly api: ApiPrototype<T>,\n private readonly destination: string,\n ) {}\n\n /**\n * The app's own DI-provided {@link ClientConfig} is where this browser host DECLARED its\n * {@link ClientConfig.role} and {@link ClientConfig.serviceWorker} routing; every bound client\n * takes both from it and only the destination from the binding, so each is stated once, by the\n * app. A bound client is always FOREGROUND: a BACKGROUND client is a second client for the same\n * contract, built at the call site that polls with `factory.createRpcClient(Api,\n * new ClientConfig(svc, role, CallMode.BACKGROUND))`.\n */\n readonly useFactory = (factory: ClientHttpBrowserFactory, config: ClientConfig): T =>\n factory.createRpcClient(\n this.api,\n new ClientConfig(this.destination, config.role, CallMode.FOREGROUND, config.serviceWorker),\n );\n}\n"]}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether a browser RPC may be intercepted by the page's service worker (#1293).
|
|
3
|
+
*
|
|
4
|
+
* WHY the default BYPASSES: Angular's service worker (ngsw) intercepts EVERY fetch, cross-origin RPC
|
|
5
|
+
* included, and when the network rejects it does not pass the rejection on — `Driver.safeFetch`
|
|
6
|
+
* answers with a synthetic `504 Gateway Timeout` instead. The client then cannot tell "the request
|
|
7
|
+
* never reached a server" (`ApiConnectionError`, safe to retry a READ) from a real gateway 504, and
|
|
8
|
+
* a user is shown "Gateway Timeout — report a bug" for a dropped connection. With the bypass, the
|
|
9
|
+
* fetch rejects natively and a 504 always means a real gateway timeout.
|
|
10
|
+
*/
|
|
11
|
+
export declare enum ServiceWorkerRouting {
|
|
12
|
+
/**
|
|
13
|
+
* Append the `ngsw-bypass=true` QUERY parameter to every RPC url. A query parameter rather than
|
|
14
|
+
* the `ngsw-bypass` header, because a custom header is not CORS-safelisted and would need every
|
|
15
|
+
* server's `Access-Control-Allow-Headers` changed. webpieces servers bind query parameters by
|
|
16
|
+
* name, so the extra key is ignored.
|
|
17
|
+
*/
|
|
18
|
+
BYPASS = "BYPASS",
|
|
19
|
+
/**
|
|
20
|
+
* Leave the url alone, so a service worker may serve or cache the call (e.g. an ngsw
|
|
21
|
+
* `dataGroups` entry). ngsw's synthetic 504 is still recognised and re-typed as
|
|
22
|
+
* `ApiConnectionError` (see `ServiceWorkerSyntheticResponse`).
|
|
23
|
+
*/
|
|
24
|
+
ALLOW = "ALLOW"
|
|
25
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ServiceWorkerRouting = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Whether a browser RPC may be intercepted by the page's service worker (#1293).
|
|
6
|
+
*
|
|
7
|
+
* WHY the default BYPASSES: Angular's service worker (ngsw) intercepts EVERY fetch, cross-origin RPC
|
|
8
|
+
* included, and when the network rejects it does not pass the rejection on — `Driver.safeFetch`
|
|
9
|
+
* answers with a synthetic `504 Gateway Timeout` instead. The client then cannot tell "the request
|
|
10
|
+
* never reached a server" (`ApiConnectionError`, safe to retry a READ) from a real gateway 504, and
|
|
11
|
+
* a user is shown "Gateway Timeout — report a bug" for a dropped connection. With the bypass, the
|
|
12
|
+
* fetch rejects natively and a 504 always means a real gateway timeout.
|
|
13
|
+
*/
|
|
14
|
+
var ServiceWorkerRouting;
|
|
15
|
+
(function (ServiceWorkerRouting) {
|
|
16
|
+
/**
|
|
17
|
+
* Append the `ngsw-bypass=true` QUERY parameter to every RPC url. A query parameter rather than
|
|
18
|
+
* the `ngsw-bypass` header, because a custom header is not CORS-safelisted and would need every
|
|
19
|
+
* server's `Access-Control-Allow-Headers` changed. webpieces servers bind query parameters by
|
|
20
|
+
* name, so the extra key is ignored.
|
|
21
|
+
*/
|
|
22
|
+
ServiceWorkerRouting["BYPASS"] = "BYPASS";
|
|
23
|
+
/**
|
|
24
|
+
* Leave the url alone, so a service worker may serve or cache the call (e.g. an ngsw
|
|
25
|
+
* `dataGroups` entry). ngsw's synthetic 504 is still recognised and re-typed as
|
|
26
|
+
* `ApiConnectionError` (see `ServiceWorkerSyntheticResponse`).
|
|
27
|
+
*/
|
|
28
|
+
ServiceWorkerRouting["ALLOW"] = "ALLOW";
|
|
29
|
+
})(ServiceWorkerRouting || (exports.ServiceWorkerRouting = ServiceWorkerRouting = {}));
|
|
30
|
+
//# sourceMappingURL=ServiceWorkerRouting.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ServiceWorkerRouting.js","sourceRoot":"","sources":["../../../../../packages/http/http-client-browser/src/ServiceWorkerRouting.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;GASG;AACH,IAAY,oBAcX;AAdD,WAAY,oBAAoB;IAC5B;;;;;OAKG;IACH,yCAAiB,CAAA;IACjB;;;;OAIG;IACH,uCAAe,CAAA;AACnB,CAAC,EAdW,oBAAoB,oCAApB,oBAAoB,QAc/B","sourcesContent":["/**\n * Whether a browser RPC may be intercepted by the page's service worker (#1293).\n *\n * WHY the default BYPASSES: Angular's service worker (ngsw) intercepts EVERY fetch, cross-origin RPC\n * included, and when the network rejects it does not pass the rejection on — `Driver.safeFetch`\n * answers with a synthetic `504 Gateway Timeout` instead. The client then cannot tell \"the request\n * never reached a server\" (`ApiConnectionError`, safe to retry a READ) from a real gateway 504, and\n * a user is shown \"Gateway Timeout — report a bug\" for a dropped connection. With the bypass, the\n * fetch rejects natively and a 504 always means a real gateway timeout.\n */\nexport enum ServiceWorkerRouting {\n /**\n * Append the `ngsw-bypass=true` QUERY parameter to every RPC url. A query parameter rather than\n * the `ngsw-bypass` header, because a custom header is not CORS-safelisted and would need every\n * server's `Access-Control-Allow-Headers` changed. webpieces servers bind query parameters by\n * name, so the extra key is ignored.\n */\n BYPASS = 'BYPASS',\n /**\n * Leave the url alone, so a service worker may serve or cache the call (e.g. an ngsw\n * `dataGroups` entry). ngsw's synthetic 504 is still recognised and re-typed as\n * `ApiConnectionError` (see `ServiceWorkerSyntheticResponse`).\n */\n ALLOW = 'ALLOW',\n}\n"]}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `cause` of an {@link ApiConnectionError} minted from a service worker's synthetic 504 — it
|
|
3
|
+
* carries the `Response` itself, so a reporter or a debugger can see exactly what came back.
|
|
4
|
+
* An `Error` only because `ApiError`'s `cause` is typed `Error`; it is never thrown on its own.
|
|
5
|
+
*/
|
|
6
|
+
export declare class ServiceWorkerSyntheticResponseError extends Error {
|
|
7
|
+
readonly response: Response;
|
|
8
|
+
constructor(response: Response);
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Recognises the response Angular's service worker fabricates when its own network fetch rejects
|
|
12
|
+
* (#1293): `new Response(null, { status: 504, statusText: 'Gateway Timeout' })` from
|
|
13
|
+
* `Driver.safeFetch`. That shape is EXACT — status 504, statusText `Gateway Timeout`, a null body and
|
|
14
|
+
* NO headers at all — while a real load-balancer or gateway 504 carries headers (at least a
|
|
15
|
+
* `content-type` or a `date`). So a real 504 stays `ApiDependencyTimeoutError`, and only the
|
|
16
|
+
* fabricated one becomes `ApiConnectionError`.
|
|
17
|
+
*
|
|
18
|
+
* The fallback for an app that opts out with `ServiceWorkerRouting.ALLOW`; with the default bypass,
|
|
19
|
+
* ngsw never sees the call and the fetch rejects natively. It runs either way — a real response can
|
|
20
|
+
* never match it.
|
|
21
|
+
*/
|
|
22
|
+
export declare class ServiceWorkerSyntheticResponse {
|
|
23
|
+
/** True only for the exact synthetic shape; any header at all means a real server answered. */
|
|
24
|
+
isSynthetic(response: Response): boolean;
|
|
25
|
+
/**
|
|
26
|
+
* Return `response` untouched, or THROW an {@link ApiConnectionError} (cause: a
|
|
27
|
+
* {@link ServiceWorkerSyntheticResponseError} holding the response) when it is the synthetic one.
|
|
28
|
+
*/
|
|
29
|
+
rejectIfSynthetic(response: Response, url: string): Response;
|
|
30
|
+
/** `forEach`, not `keys()`: a consumer compiling without the `dom.iterable` lib has no `keys()`. */
|
|
31
|
+
private hasAnyHeader;
|
|
32
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ServiceWorkerSyntheticResponse = exports.ServiceWorkerSyntheticResponseError = void 0;
|
|
4
|
+
const core_util_1 = require("@webpieces/core-util");
|
|
5
|
+
/**
|
|
6
|
+
* The `cause` of an {@link ApiConnectionError} minted from a service worker's synthetic 504 — it
|
|
7
|
+
* carries the `Response` itself, so a reporter or a debugger can see exactly what came back.
|
|
8
|
+
* An `Error` only because `ApiError`'s `cause` is typed `Error`; it is never thrown on its own.
|
|
9
|
+
*/
|
|
10
|
+
class ServiceWorkerSyntheticResponseError extends Error {
|
|
11
|
+
response;
|
|
12
|
+
constructor(response) {
|
|
13
|
+
super(`A service worker answered with a synthetic ${response.status} ${response.statusText} ` +
|
|
14
|
+
`(null body, no headers) — the network fetch behind it rejected`);
|
|
15
|
+
this.response = response;
|
|
16
|
+
this.name = 'ServiceWorkerSyntheticResponseError';
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
exports.ServiceWorkerSyntheticResponseError = ServiceWorkerSyntheticResponseError;
|
|
20
|
+
/**
|
|
21
|
+
* Recognises the response Angular's service worker fabricates when its own network fetch rejects
|
|
22
|
+
* (#1293): `new Response(null, { status: 504, statusText: 'Gateway Timeout' })` from
|
|
23
|
+
* `Driver.safeFetch`. That shape is EXACT — status 504, statusText `Gateway Timeout`, a null body and
|
|
24
|
+
* NO headers at all — while a real load-balancer or gateway 504 carries headers (at least a
|
|
25
|
+
* `content-type` or a `date`). So a real 504 stays `ApiDependencyTimeoutError`, and only the
|
|
26
|
+
* fabricated one becomes `ApiConnectionError`.
|
|
27
|
+
*
|
|
28
|
+
* The fallback for an app that opts out with `ServiceWorkerRouting.ALLOW`; with the default bypass,
|
|
29
|
+
* ngsw never sees the call and the fetch rejects natively. It runs either way — a real response can
|
|
30
|
+
* never match it.
|
|
31
|
+
*/
|
|
32
|
+
class ServiceWorkerSyntheticResponse {
|
|
33
|
+
/** True only for the exact synthetic shape; any header at all means a real server answered. */
|
|
34
|
+
isSynthetic(response) {
|
|
35
|
+
return (response.status === 504 &&
|
|
36
|
+
response.statusText === 'Gateway Timeout' &&
|
|
37
|
+
response.body === null &&
|
|
38
|
+
!this.hasAnyHeader(response.headers));
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Return `response` untouched, or THROW an {@link ApiConnectionError} (cause: a
|
|
42
|
+
* {@link ServiceWorkerSyntheticResponseError} holding the response) when it is the synthetic one.
|
|
43
|
+
*/
|
|
44
|
+
rejectIfSynthetic(response, url) {
|
|
45
|
+
if (this.isSynthetic(response)) {
|
|
46
|
+
throw new core_util_1.ApiConnectionError(`Request to ${url} never reached a server (a service worker answered with its synthetic 504)`, new ServiceWorkerSyntheticResponseError(response));
|
|
47
|
+
}
|
|
48
|
+
return response;
|
|
49
|
+
}
|
|
50
|
+
/** `forEach`, not `keys()`: a consumer compiling without the `dom.iterable` lib has no `keys()`. */
|
|
51
|
+
hasAnyHeader(headers) {
|
|
52
|
+
let any = false;
|
|
53
|
+
headers.forEach(() => {
|
|
54
|
+
any = true;
|
|
55
|
+
});
|
|
56
|
+
return any;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
exports.ServiceWorkerSyntheticResponse = ServiceWorkerSyntheticResponse;
|
|
60
|
+
//# sourceMappingURL=ServiceWorkerSyntheticResponse.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ServiceWorkerSyntheticResponse.js","sourceRoot":"","sources":["../../../../../packages/http/http-client-browser/src/ServiceWorkerSyntheticResponse.ts"],"names":[],"mappings":";;;AAAA,oDAA0D;AAE1D;;;;GAIG;AACH,MAAa,mCAAoC,SAAQ,KAAK;IAC9B;IAA5B,YAA4B,QAAkB;QAC1C,KAAK,CACD,8CAA8C,QAAQ,CAAC,MAAM,IAAI,QAAQ,CAAC,UAAU,GAAG;YACnF,gEAAgE,CACvE,CAAC;QAJsB,aAAQ,GAAR,QAAQ,CAAU;QAK1C,IAAI,CAAC,IAAI,GAAG,qCAAqC,CAAC;IACtD,CAAC;CACJ;AARD,kFAQC;AAED;;;;;;;;;;;GAWG;AACH,MAAa,8BAA8B;IACvC,+FAA+F;IAC/F,WAAW,CAAC,QAAkB;QAC1B,OAAO,CACH,QAAQ,CAAC,MAAM,KAAK,GAAG;YACvB,QAAQ,CAAC,UAAU,KAAK,iBAAiB;YACzC,QAAQ,CAAC,IAAI,KAAK,IAAI;YACtB,CAAC,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,OAAO,CAAC,CACvC,CAAC;IACN,CAAC;IAED;;;OAGG;IACH,iBAAiB,CAAC,QAAkB,EAAE,GAAW;QAC7C,IAAI,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC7B,MAAM,IAAI,8BAAkB,CACxB,cAAc,GAAG,4EAA4E,EAC7F,IAAI,mCAAmC,CAAC,QAAQ,CAAC,CACpD,CAAC;QACN,CAAC;QACD,OAAO,QAAQ,CAAC;IACpB,CAAC;IAED,oGAAoG;IAC5F,YAAY,CAAC,OAAgB;QACjC,IAAI,GAAG,GAAG,KAAK,CAAC;QAChB,OAAO,CAAC,OAAO,CAAC,GAAS,EAAE;YACvB,GAAG,GAAG,IAAI,CAAC;QACf,CAAC,CAAC,CAAC;QACH,OAAO,GAAG,CAAC;IACf,CAAC;CACJ;AAjCD,wEAiCC","sourcesContent":["import { ApiConnectionError } from '@webpieces/core-util';\n\n/**\n * The `cause` of an {@link ApiConnectionError} minted from a service worker's synthetic 504 — it\n * carries the `Response` itself, so a reporter or a debugger can see exactly what came back.\n * An `Error` only because `ApiError`'s `cause` is typed `Error`; it is never thrown on its own.\n */\nexport class ServiceWorkerSyntheticResponseError extends Error {\n constructor(public readonly response: Response) {\n super(\n `A service worker answered with a synthetic ${response.status} ${response.statusText} ` +\n `(null body, no headers) — the network fetch behind it rejected`,\n );\n this.name = 'ServiceWorkerSyntheticResponseError';\n }\n}\n\n/**\n * Recognises the response Angular's service worker fabricates when its own network fetch rejects\n * (#1293): `new Response(null, { status: 504, statusText: 'Gateway Timeout' })` from\n * `Driver.safeFetch`. That shape is EXACT — status 504, statusText `Gateway Timeout`, a null body and\n * NO headers at all — while a real load-balancer or gateway 504 carries headers (at least a\n * `content-type` or a `date`). So a real 504 stays `ApiDependencyTimeoutError`, and only the\n * fabricated one becomes `ApiConnectionError`.\n *\n * The fallback for an app that opts out with `ServiceWorkerRouting.ALLOW`; with the default bypass,\n * ngsw never sees the call and the fetch rejects natively. It runs either way — a real response can\n * never match it.\n */\nexport class ServiceWorkerSyntheticResponse {\n /** True only for the exact synthetic shape; any header at all means a real server answered. */\n isSynthetic(response: Response): boolean {\n return (\n response.status === 504 &&\n response.statusText === 'Gateway Timeout' &&\n response.body === null &&\n !this.hasAnyHeader(response.headers)\n );\n }\n\n /**\n * Return `response` untouched, or THROW an {@link ApiConnectionError} (cause: a\n * {@link ServiceWorkerSyntheticResponseError} holding the response) when it is the synthetic one.\n */\n rejectIfSynthetic(response: Response, url: string): Response {\n if (this.isSynthetic(response)) {\n throw new ApiConnectionError(\n `Request to ${url} never reached a server (a service worker answered with its synthetic 504)`,\n new ServiceWorkerSyntheticResponseError(response),\n );\n }\n return response;\n }\n\n /** `forEach`, not `keys()`: a consumer compiling without the `dom.iterable` lib has no `keys()`. */\n private hasAnyHeader(headers: Headers): boolean {\n let any = false;\n headers.forEach((): void => {\n any = true;\n });\n return any;\n }\n}\n"]}
|
package/src/index.d.ts
CHANGED
|
@@ -27,13 +27,15 @@ export { ClientHttpBrowserFactory } from './ClientHttpBrowserFactory';
|
|
|
27
27
|
export { BrowserProxyClient } from './BrowserProxyClient';
|
|
28
28
|
export { BrowserApiCallContext } from './BrowserApiCallContext';
|
|
29
29
|
export { ClientConfig } from './ClientConfig';
|
|
30
|
+
export { ServiceWorkerRouting } from './ServiceWorkerRouting';
|
|
31
|
+
export { ServiceWorkerSyntheticResponse, ServiceWorkerSyntheticResponseError, } from './ServiceWorkerSyntheticResponse';
|
|
30
32
|
export { MutableContextStore } from './MutableContextStore';
|
|
31
33
|
export type { RequestLifecycleListener } from './RequestLifecycleListener';
|
|
32
34
|
export { ProxyClient, ClientErrorTranslator, RequestOutcome } from '@webpieces/http-client-core';
|
|
33
35
|
export type { ApiPrototype } from '@webpieces/http-client-core';
|
|
34
36
|
export { StreamingCapabilityError } from '@webpieces/http-client-core';
|
|
35
37
|
export { ContextMgr } from '@webpieces/core-util';
|
|
36
|
-
export { ContextReader, ContextWriter, ContextStore, ContextKey, HeaderRegistry, ClientRegistry, ClientRole, templateDeriver, WebpiecesCoreHeaders, } from '@webpieces/core-util';
|
|
38
|
+
export { ContextReader, ContextWriter, ContextStore, ContextKey, HeaderRegistry, ClientRegistry, ClientRole, CallMode, CallModeMarker, templateDeriver, WebpiecesCoreHeaders, } from '@webpieces/core-util';
|
|
37
39
|
export type { ServiceUrlDeriver } from '@webpieces/core-util';
|
|
38
40
|
export { ApiPath, Endpoint, PathParam, QueryParam, WpAuthPublic, WpAuth, WpAuthorization, AuthorizationType, WpLocalOnly, jwt, oidcSameProject, oidcSvcs, sharedSecret, webhook, apiKey, Rpc, PubSub, Queue, ValidateImplementation, } from '@webpieces/core-util';
|
|
39
41
|
export type { Wiring, AppWiring, BindModule } from './Wiring';
|
package/src/index.js
CHANGED
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
* The server twin is @webpieces/http-client-node.
|
|
26
26
|
*/
|
|
27
27
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
28
|
-
exports.WiringPolicy = exports.BrowserFactoryProvider = exports.BrowserExistingProvider = exports.BrowserClassProvider = exports.BrowserValueProvider = exports.UseExisting = exports.UseClass = exports.ExternalImpl = exports.BrowserWiringProviders = exports.ClientBindOptions = exports.Binder = exports.Queue = exports.PubSub = exports.Rpc = exports.apiKey = exports.webhook = exports.sharedSecret = exports.oidcSvcs = exports.oidcSameProject = exports.jwt = exports.WpLocalOnly = exports.AuthorizationType = exports.WpAuthorization = exports.WpAuth = exports.WpAuthPublic = exports.QueryParam = exports.PathParam = exports.Endpoint = exports.ApiPath = exports.WebpiecesCoreHeaders = exports.templateDeriver = exports.ClientRole = exports.ClientRegistry = exports.HeaderRegistry = exports.ContextKey = exports.ContextMgr = exports.StreamingCapabilityError = exports.RequestOutcome = exports.ClientErrorTranslator = exports.ProxyClient = exports.MutableContextStore = exports.ClientConfig = exports.BrowserApiCallContext = exports.BrowserProxyClient = exports.ClientHttpBrowserFactory = void 0;
|
|
28
|
+
exports.WiringPolicy = exports.BrowserFactoryProvider = exports.BrowserExistingProvider = exports.BrowserClassProvider = exports.BrowserValueProvider = exports.UseExisting = exports.UseClass = exports.ExternalImpl = exports.BrowserWiringProviders = exports.ClientBindOptions = exports.Binder = exports.Queue = exports.PubSub = exports.Rpc = exports.apiKey = exports.webhook = exports.sharedSecret = exports.oidcSvcs = exports.oidcSameProject = exports.jwt = exports.WpLocalOnly = exports.AuthorizationType = exports.WpAuthorization = exports.WpAuth = exports.WpAuthPublic = exports.QueryParam = exports.PathParam = exports.Endpoint = exports.ApiPath = exports.WebpiecesCoreHeaders = exports.templateDeriver = exports.CallModeMarker = exports.CallMode = exports.ClientRole = exports.ClientRegistry = exports.HeaderRegistry = exports.ContextKey = exports.ContextMgr = exports.StreamingCapabilityError = exports.RequestOutcome = exports.ClientErrorTranslator = exports.ProxyClient = exports.MutableContextStore = exports.ServiceWorkerSyntheticResponseError = exports.ServiceWorkerSyntheticResponse = exports.ServiceWorkerRouting = exports.ClientConfig = exports.BrowserApiCallContext = exports.BrowserProxyClient = exports.ClientHttpBrowserFactory = void 0;
|
|
29
29
|
var ClientHttpBrowserFactory_1 = require("./ClientHttpBrowserFactory");
|
|
30
30
|
Object.defineProperty(exports, "ClientHttpBrowserFactory", { enumerable: true, get: function () { return ClientHttpBrowserFactory_1.ClientHttpBrowserFactory; } });
|
|
31
31
|
var BrowserProxyClient_1 = require("./BrowserProxyClient");
|
|
@@ -37,6 +37,12 @@ var BrowserApiCallContext_1 = require("./BrowserApiCallContext");
|
|
|
37
37
|
Object.defineProperty(exports, "BrowserApiCallContext", { enumerable: true, get: function () { return BrowserApiCallContext_1.BrowserApiCallContext; } });
|
|
38
38
|
var ClientConfig_1 = require("./ClientConfig");
|
|
39
39
|
Object.defineProperty(exports, "ClientConfig", { enumerable: true, get: function () { return ClientConfig_1.ClientConfig; } });
|
|
40
|
+
// #1293: service-worker routing for every RPC, and ngsw's synthetic-504 fallback.
|
|
41
|
+
var ServiceWorkerRouting_1 = require("./ServiceWorkerRouting");
|
|
42
|
+
Object.defineProperty(exports, "ServiceWorkerRouting", { enumerable: true, get: function () { return ServiceWorkerRouting_1.ServiceWorkerRouting; } });
|
|
43
|
+
var ServiceWorkerSyntheticResponse_1 = require("./ServiceWorkerSyntheticResponse");
|
|
44
|
+
Object.defineProperty(exports, "ServiceWorkerSyntheticResponse", { enumerable: true, get: function () { return ServiceWorkerSyntheticResponse_1.ServiceWorkerSyntheticResponse; } });
|
|
45
|
+
Object.defineProperty(exports, "ServiceWorkerSyntheticResponseError", { enumerable: true, get: function () { return ServiceWorkerSyntheticResponse_1.ServiceWorkerSyntheticResponseError; } });
|
|
40
46
|
var MutableContextStore_1 = require("./MutableContextStore");
|
|
41
47
|
Object.defineProperty(exports, "MutableContextStore", { enumerable: true, get: function () { return MutableContextStore_1.MutableContextStore; } });
|
|
42
48
|
// The isomorphic engine, re-exported so a browser app needs one import.
|
|
@@ -56,6 +62,8 @@ Object.defineProperty(exports, "ContextKey", { enumerable: true, get: function (
|
|
|
56
62
|
Object.defineProperty(exports, "HeaderRegistry", { enumerable: true, get: function () { return core_util_2.HeaderRegistry; } });
|
|
57
63
|
Object.defineProperty(exports, "ClientRegistry", { enumerable: true, get: function () { return core_util_2.ClientRegistry; } });
|
|
58
64
|
Object.defineProperty(exports, "ClientRole", { enumerable: true, get: function () { return core_util_2.ClientRole; } });
|
|
65
|
+
Object.defineProperty(exports, "CallMode", { enumerable: true, get: function () { return core_util_2.CallMode; } });
|
|
66
|
+
Object.defineProperty(exports, "CallModeMarker", { enumerable: true, get: function () { return core_util_2.CallModeMarker; } });
|
|
59
67
|
Object.defineProperty(exports, "templateDeriver", { enumerable: true, get: function () { return core_util_2.templateDeriver; } });
|
|
60
68
|
Object.defineProperty(exports, "WebpiecesCoreHeaders", { enumerable: true, get: function () { return core_util_2.WebpiecesCoreHeaders; } });
|
|
61
69
|
// Re-export API decorators for convenience (same as http-routing does)
|
package/src/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/http/http-client-browser/src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;;;AAEH,uEAAsE;AAA7D,oIAAA,wBAAwB,OAAA;AACjC,2DAA0D;AAAjD,wHAAA,kBAAkB,OAAA;AAC3B,4FAA4F;AAC5F,kGAAkG;AAClG,8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AAA;AACd,uGAAA,UAAU,OAAA;AACV,qGAAA,QAAQ,OAAA;AACR,2GAAA,cAAc,OAAA;AACd,4GAAA,eAAe,OAAA;AACf,iHAAA,oBAAoB,OAAA;AAIxB,uEAAuE;AACvE,kDAoB8B;AAnB1B,oGAAA,OAAO,OAAA;AACP,qGAAA,QAAQ,OAAA;AACR,sGAAA,SAAS,OAAA;AACT,uGAAA,UAAU,OAAA;AACV,yGAAA,YAAY,OAAA;AACZ,mGAAA,MAAM,OAAA;AACN,4GAAA,eAAe,OAAA;AACf,8GAAA,iBAAiB,OAAA;AACjB,wGAAA,WAAW,OAAA;AACX,gGAAA,GAAG,OAAA;AACH,4GAAA,eAAe,OAAA;AACf,qGAAA,QAAQ,OAAA;AACR,yGAAA,YAAY,OAAA;AACZ,oGAAA,OAAO,OAAA;AACP,mGAAA,MAAM,OAAA;AACN,gGAAA,GAAG,OAAA;AACH,mGAAA,MAAM,OAAA;AACN,kGAAA,KAAK,OAAA;AAOT,mCAA6E;AAApE,gGAAA,MAAM,OAAA;AAAE,2GAAA,iBAAiB,OAAA;AAAE,gHAAA,sBAAsB,OAAA;AAC1D,+CAAqE;AAA5D,4GAAA,YAAY,OAAA;AAAE,wGAAA,QAAQ,OAAA;AAAE,2GAAA,WAAW,OAAA;AAE5C,uDAAiI;AAAxH,wHAAA,oBAAoB,OAAA;AAAE,wHAAA,oBAAoB,OAAA;AAAE,2HAAA,uBAAuB,OAAA;AAAE,0HAAA,sBAAsB,OAAA;AAGpG,gEAA2D;AAAlD,gHAAA,YAAY,OAAA","sourcesContent":["/**\n * @webpieces/http-client-browser\n *\n * The BROWSER HTTP client. Reads an API contract's decorators and generates type-safe HTTP\n * clients from it — the same contract the server implements.\n *\n * DI-free on purpose: this may be bundled by React or Angular, so it ships no inversify and no\n * @webpieces/core-context (which is AsyncLocalStorage-backed and Node-only). Browsers have no\n * ambient request scope, so the app holds a {@link MutableContextStore} and sets context values\n * as they become known; every outbound call then transfers them as headers.\n *\n * Usage:\n * ```typescript\n * import { ClientHttpBrowserFactory, ClientConfig, MutableContextStore } from '@webpieces/http-client-browser';\n *\n * HeaderRegistry.configure(CompanyHeaders.ALL_HEADERS, true);\n * const store = new MutableContextStore();\n * const factory = new ClientHttpBrowserFactory(store);\n *\n * const client = factory.createRpcClient(SaveApi, new ClientConfig('save-svc', ClientRole.END_USER_CLIENT));\n * const response = await client.save({ query: 'test' });\n * ```\n *\n * The server twin is @webpieces/http-client-node.\n */\n\nexport { ClientHttpBrowserFactory } from './ClientHttpBrowserFactory';\nexport { BrowserProxyClient } from './BrowserProxyClient';\n// Browser impl of the ApiCallContext seam, constructed by BrowserProxyClient. Exported so a\n// browser/Angular logger can read the current tag via the STATIC BrowserApiCallContext.snapshot()\n// and fold it into log lines.\nexport { BrowserApiCallContext } from './BrowserApiCallContext';\nexport { ClientConfig } from './ClientConfig';\n// #1293: service-worker routing for every RPC, and ngsw's synthetic-504 fallback.\nexport { ServiceWorkerRouting } from './ServiceWorkerRouting';\nexport {\n ServiceWorkerSyntheticResponse,\n ServiceWorkerSyntheticResponseError,\n} from './ServiceWorkerSyntheticResponse';\nexport { MutableContextStore } from './MutableContextStore';\nexport type { RequestLifecycleListener } from './RequestLifecycleListener';\n\n// The isomorphic engine, re-exported so a browser app needs one import.\nexport { ProxyClient, ClientErrorTranslator, RequestOutcome } from '@webpieces/http-client-core';\nexport type { ApiPrototype } from '@webpieces/http-client-core';\nexport { StreamingCapabilityError } from '@webpieces/http-client-core';\n\n// ContextMgr is the BROWSER's outbound-header propagation. This is the only package that may use\n// it; the server reads RequestContext directly (RequestContextHeaders in @webpieces/core-context).\nexport { ContextMgr } from '@webpieces/core-util';\n\n// Re-export the context-key contract from core-util for convenience (browser one-import)\nexport {\n ContextReader,\n ContextWriter,\n ContextStore,\n ContextKey,\n HeaderRegistry,\n ClientRegistry,\n ClientRole,\n CallMode,\n CallModeMarker,\n templateDeriver,\n WebpiecesCoreHeaders,\n} from '@webpieces/core-util';\nexport type { ServiceUrlDeriver } from '@webpieces/core-util';\n\n// Re-export API decorators for convenience (same as http-routing does)\nexport {\n ApiPath,\n Endpoint,\n PathParam,\n QueryParam,\n WpAuthPublic,\n WpAuth,\n WpAuthorization,\n AuthorizationType,\n WpLocalOnly,\n jwt,\n oidcSameProject,\n oidcSvcs,\n sharedSecret,\n webhook,\n apiKey,\n Rpc,\n PubSub,\n Queue,\n ValidateImplementation,\n} from '@webpieces/core-util';\n\n// The browser host's wiring: bind modules only (no route channel), the Binder they configure, and\n// the ExternalImpl recipes (UseClass / UseExisting) Binder.bindExternal takes.\nexport type { Wiring, AppWiring, BindModule } from './Wiring';\nexport { Binder, ClientBindOptions, BrowserWiringProviders } from './Wiring';\nexport { ExternalImpl, UseClass, UseExisting } from './ExternalImpl';\nexport type { ExternalClassType, ExternalExistingType } from './ExternalImpl';\nexport { BrowserValueProvider, BrowserClassProvider, BrowserExistingProvider, BrowserFactoryProvider } from './BrowserProviders';\nexport type { BrowserProvider, BrowserToken, BrowserType } from './BrowserProviders';\n\nexport { WiringPolicy } from '@webpieces/http-client-core';\n"]}
|