@ondewo/nlu-client-typescript 6.13.0 → 6.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,175 @@
1
+ /**
2
+ * Minimal structural type of the fetch Response fields this helper reads. Keeps the module
3
+ * self-contained (no DOM lib dependency) while still typing the injectable `fetchImpl`.
4
+ */
5
+ export interface TokenFetchResponse {
6
+ /** Whether the HTTP status is in the 2xx success range. */
7
+ ok: boolean;
8
+ /** The numeric HTTP status code. */
9
+ status: number;
10
+ /**
11
+ * Read the full response body as text.
12
+ *
13
+ * @returns A promise resolving to the raw body string.
14
+ */
15
+ text(): Promise<string>;
16
+ }
17
+ /** Init object passed to the injectable fetch. */
18
+ export interface TokenFetchInit {
19
+ /** HTTP method (always `"POST"` for the token endpoint). */
20
+ method: string;
21
+ /** Request headers (content-type and accept). */
22
+ headers: Record<string, string>;
23
+ /** The form-encoded request body. */
24
+ body: string;
25
+ /**
26
+ * Optional undici dispatcher (Node only). The default transport attaches an insecure
27
+ * `Agent({ connect: { rejectUnauthorized: false } })` here when `verifySsl` is `false`; the global
28
+ * WHATWG fetch honours it. Never set on an injected `fetchImpl` and ignored in a browser bundle.
29
+ */
30
+ dispatcher?: unknown;
31
+ }
32
+ /**
33
+ * Injectable fetch signature (a subset of the global `fetch`) used by the token endpoint call.
34
+ *
35
+ * @param url - The token endpoint URL to POST to.
36
+ * @param init - The request init (method, headers, body).
37
+ * @returns A promise resolving to the (structurally minimal) response.
38
+ */
39
+ export type TokenFetch = (url: string, init: TokenFetchInit) => Promise<TokenFetchResponse>;
40
+ /** Options for the D18 headless-SDK offline-token login. */
41
+ export interface OfflineTokenLoginOptions {
42
+ /** Base Keycloak URL, e.g. "https://auth.example.com/auth" (trailing slash tolerated). */
43
+ keycloakUrl: string;
44
+ /** Realm name, e.g. "ondewo-ccai-platform". */
45
+ realm: string;
46
+ /** Public SDK client id, e.g. "ondewo-nlu-cai-sdk-public". NO client_secret (Q1). */
47
+ clientId: string;
48
+ /** 2FA-exempt technical-user email. */
49
+ username: string;
50
+ /** Technical-user password. */
51
+ password: string;
52
+ /** Optional cap (seconds) on how long the auto-refresh loop runs after login. */
53
+ tokenExpirationInS?: number;
54
+ /** Optional fetch override (tests inject a mock); defaults to the global fetch. */
55
+ fetchImpl?: TokenFetch;
56
+ /**
57
+ * Verify the Keycloak TLS certificate on the token-endpoint call. Default `true` (secure). Set
58
+ * `false` ONLY for a self-signed local Envoy (e.g. `https://localhost:12001/auth`). Node-only: it is
59
+ * ignored in a browser bundle (the browser owns TLS) and ignored when a custom `fetchImpl` is
60
+ * injected. When `false` under Node the default transport attaches an insecure undici dispatcher.
61
+ */
62
+ keycloakVerifySsl?: boolean;
63
+ /** Optional clock override returning epoch ms (tests); defaults to Date.now. */
64
+ nowInMs?: () => number;
65
+ }
66
+ /** Error raised on any token-endpoint or token-shape failure. */
67
+ export declare class TokenError extends Error {
68
+ /**
69
+ * Construct a token error.
70
+ *
71
+ * @param message - Human-readable description of the token failure.
72
+ */
73
+ constructor(message: string);
74
+ }
75
+ /**
76
+ * Build the DEFAULT token transport (used only when no `fetchImpl` is injected). It delegates to the
77
+ * global WHATWG fetch, and -- when `verifySsl` is `false` under Node -- attaches an insecure undici
78
+ * dispatcher to the request init so the token POST skips certificate verification. With `verifySsl`
79
+ * `true` (the default) it is a plain pass-through to `globalThis.fetch`, i.e. unchanged behavior.
80
+ *
81
+ * @param verifySsl - Whether to verify the Keycloak TLS certificate; `false` opts into the insecure path.
82
+ * @returns A {@link TokenFetch} that resolves the global fetch at call time (honoring test overrides).
83
+ */
84
+ export declare function createDefaultTokenFetch(verifySsl: boolean): TokenFetch;
85
+ /**
86
+ * A live access-token holder backed by a bounded auto-refresh loop. Obtain one from {@link login};
87
+ * read {@link getAuthorizationHeader} for the gRPC `Authorization` metadata and call {@link stop} when done.
88
+ */
89
+ export declare class OfflineTokenProvider {
90
+ /** The realm token endpoint derived from `keycloakUrl` + `realm`. */
91
+ private readonly tokenEndpoint;
92
+ /** The public SDK client id sent on every grant. */
93
+ private readonly clientId;
94
+ /** Optional cap (seconds) on how long the refresh loop runs after login; `undefined` = unbounded. */
95
+ private readonly tokenExpirationInS;
96
+ /** The fetch transport (real global fetch or an injected mock). */
97
+ private readonly fetchImpl;
98
+ /** Epoch-ms clock (injectable for deterministic tests; defaults to `Date.now`). */
99
+ private readonly nowInMs;
100
+ /** The current access token, or `null` before bootstrap / after the loop has lapsed. */
101
+ private accessToken;
102
+ /** The current offline refresh token, or `null` before bootstrap. */
103
+ private refreshToken;
104
+ /** The pending refresh timer handle, or `null` when no refresh is armed. */
105
+ private timer;
106
+ /** Whether {@link stop} has been called; suppresses further refresh scheduling. */
107
+ private stopped;
108
+ /** Epoch-ms instant past which the loop stops renewing, or `null` when unbounded. */
109
+ private deadlineInMs;
110
+ /** Optional callback invoked with the error of a failed background refresh. */
111
+ private onRefreshErrorHandler;
112
+ /**
113
+ * Construct an (un-bootstrapped) provider from login options. Call {@link bootstrap} (or use the
114
+ * module-level {@link login}) before reading a token.
115
+ *
116
+ * @param options - The D18 headless-SDK offline-token login options.
117
+ */
118
+ constructor(options: OfflineTokenLoginOptions);
119
+ /**
120
+ * Perform the one-time ROPC login and arm the first refresh. Awaited by {@link login}.
121
+ *
122
+ * @param username - The 2FA-exempt technical-user email.
123
+ * @param password - The technical-user password.
124
+ * @returns A promise that resolves once the initial token is held and the first refresh is armed.
125
+ * @throws {TokenError} When the token endpoint fails or the response carries no refresh token.
126
+ */
127
+ bootstrap(username: string, password: string): Promise<void>;
128
+ /**
129
+ * Exchange the offline refresh token for a fresh access token and re-arm the next refresh.
130
+ *
131
+ * @returns A promise that resolves once the token is refreshed (or the loop has stopped).
132
+ * @throws {TokenError} When the refresh token-endpoint call fails or returns an invalid body.
133
+ */
134
+ private refresh;
135
+ /**
136
+ * Arm a single timer for the next refresh, clamped to the bounded deadline. Stops silently once
137
+ * `tokenExpirationInS` has elapsed (no further renewal -> access lapses -> re-login required).
138
+ *
139
+ * @param expiresInRaw - The `expires_in` (seconds) reported by Keycloak; absent/non-positive
140
+ * values fall back to {@link MIN_REFRESH_DELAY_IN_S}.
141
+ */
142
+ private scheduleRefresh;
143
+ /**
144
+ * Register a callback invoked with the error of a failed background refresh (optional diagnostics).
145
+ *
146
+ * @param handler - The callback to receive the refresh error; replaces any previously registered one.
147
+ */
148
+ onRefreshError(handler: (error: unknown) => void): void;
149
+ /**
150
+ * Read the current access token.
151
+ *
152
+ * @returns The current access token, or `null` before bootstrap / after the bounded loop has lapsed.
153
+ */
154
+ getAccessToken(): string | null;
155
+ /**
156
+ * Build the value for an `Authorization` gRPC metadata header.
157
+ *
158
+ * @returns The `Bearer <access_token>` header value.
159
+ * @throws {TokenError} When no access token is available (login not completed or already lapsed).
160
+ */
161
+ getAuthorizationHeader(): string;
162
+ /** Stop the auto-refresh loop. Idempotent; safe to call from any state. */
163
+ stop(): void;
164
+ }
165
+ /**
166
+ * One-time ROPC + offline_access login against the PUBLIC SDK client, returning a live token provider
167
+ * whose access token is auto-refreshed in the background until `tokenExpirationInS` elapses.
168
+ *
169
+ * @param options - The headless-SDK login options (`keycloakUrl`, `realm`, `clientId`, `username`,
170
+ * `password` are required; `tokenExpirationInS`, `fetchImpl`, `nowInMs` are optional).
171
+ * @returns A bootstrapped {@link OfflineTokenProvider} holding a live access token.
172
+ * @throws {TokenError} When required options are missing/empty, the token endpoint fails, or the
173
+ * response lacks an access or refresh token.
174
+ */
175
+ export declare function login(options: OfflineTokenLoginOptions): Promise<OfflineTokenProvider>;
@@ -0,0 +1,356 @@
1
+ "use strict";
2
+ // Copyright 2021-2026 ONDEWO GmbH
3
+ //
4
+ // Licensed under the Apache License, Version 2.0 (the "License");
5
+ // you may not use this file except in compliance with the License.
6
+ // You may obtain a copy of the License at
7
+ //
8
+ // http://www.apache.org/licenses/LICENSE-2.0
9
+ //
10
+ // Unless required by applicable law or agreed to in writing, software
11
+ // distributed under the License is distributed on an "AS IS" BASIS,
12
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ // See the License for the specific language governing permissions and
14
+ // limitations under the License.
15
+ //
16
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
17
+ if (k2 === undefined) k2 = k;
18
+ var desc = Object.getOwnPropertyDescriptor(m, k);
19
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
20
+ desc = { enumerable: true, get: function() { return m[k]; } };
21
+ }
22
+ Object.defineProperty(o, k2, desc);
23
+ }) : (function(o, m, k, k2) {
24
+ if (k2 === undefined) k2 = k;
25
+ o[k2] = m[k];
26
+ }));
27
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
28
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
29
+ }) : function(o, v) {
30
+ o["default"] = v;
31
+ });
32
+ var __importStar = (this && this.__importStar) || (function () {
33
+ var ownKeys = function(o) {
34
+ ownKeys = Object.getOwnPropertyNames || function (o) {
35
+ var ar = [];
36
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
37
+ return ar;
38
+ };
39
+ return ownKeys(o);
40
+ };
41
+ return function (mod) {
42
+ if (mod && mod.__esModule) return mod;
43
+ var result = {};
44
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
45
+ __setModuleDefault(result, mod);
46
+ return result;
47
+ };
48
+ })();
49
+ Object.defineProperty(exports, "__esModule", { value: true });
50
+ exports.OfflineTokenProvider = exports.TokenError = void 0;
51
+ exports.createDefaultTokenFetch = createDefaultTokenFetch;
52
+ exports.login = login;
53
+ // D18 headless-SDK auth helper (keycloak-migration-plan §7.8 + D18).
54
+ //
55
+ // One-time ROPC login (grant_type=password, scope=offline_access) against the PUBLIC SDK client
56
+ // `ondewo-nlu-cai-sdk-public` (no client_secret -- Q1), then a bounded background loop that refreshes
57
+ // the short-lived access token from the offline refresh token before it expires. The current access
58
+ // token is exposed for an `Authorization: Bearer <token>` gRPC metadata header. The refresh loop stops
59
+ // after `tokenExpirationInS` (if given) has elapsed since login.
60
+ /**
61
+ * Seconds of head-room subtracted from a token's `expires_in` so the refresh fires before the access
62
+ * token actually lapses (covers clock skew + the round-trip to Keycloak).
63
+ */
64
+ const REFRESH_SKEW_IN_S = 30;
65
+ /** Lower bound for the scheduled refresh delay so a tiny/zero `expires_in` cannot spin a hot loop. */
66
+ const MIN_REFRESH_DELAY_IN_S = 1;
67
+ /** Error raised on any token-endpoint or token-shape failure. */
68
+ class TokenError extends Error {
69
+ /**
70
+ * Construct a token error.
71
+ *
72
+ * @param message - Human-readable description of the token failure.
73
+ */
74
+ constructor(message) {
75
+ super(message);
76
+ this.name = "TokenError";
77
+ }
78
+ }
79
+ exports.TokenError = TokenError;
80
+ /**
81
+ * Build the OIDC token endpoint URL for a realm, tolerating a trailing slash on `keycloakUrl` and an
82
+ * optional `/auth` relative path already baked into it.
83
+ *
84
+ * @param keycloakUrl - Base Keycloak URL (trailing slashes are stripped).
85
+ * @param realm - Realm name (URL-encoded into the path).
86
+ * @returns The fully-qualified `.../realms/<realm>/protocol/openid-connect/token` endpoint URL.
87
+ */
88
+ function buildTokenEndpoint(keycloakUrl, realm) {
89
+ const base = keycloakUrl.replace(/\/+$/, "");
90
+ return `${base}/realms/${encodeURIComponent(realm)}/protocol/openid-connect/token`;
91
+ }
92
+ /**
93
+ * POST an `application/x-www-form-urlencoded` body to the token endpoint and return the parsed JSON.
94
+ * Raises TokenError on a non-2xx response or unparseable / access_token-less body.
95
+ *
96
+ * @param tokenEndpoint - The realm token endpoint URL to POST to.
97
+ * @param params - The form fields to URL-encode into the request body.
98
+ * @param fetchImpl - The fetch transport to use (real or injected mock).
99
+ * @returns The parsed Keycloak token response.
100
+ * @throws {TokenError} On a non-2xx status, a non-JSON body, or a body without an `access_token`.
101
+ */
102
+ async function postTokenRequest(tokenEndpoint, params, fetchImpl) {
103
+ const body = new URLSearchParams(params).toString();
104
+ const response = await fetchImpl(tokenEndpoint, {
105
+ method: "POST",
106
+ headers: {
107
+ "Content-Type": "application/x-www-form-urlencoded",
108
+ Accept: "application/json"
109
+ },
110
+ body
111
+ });
112
+ const text = await response.text();
113
+ if (!response.ok) {
114
+ throw new TokenError(`Keycloak token endpoint returned HTTP ${response.status}: ${text}`);
115
+ }
116
+ let parsed;
117
+ try {
118
+ parsed = JSON.parse(text);
119
+ }
120
+ catch {
121
+ throw new TokenError(`Keycloak token endpoint returned a non-JSON body: ${text}`);
122
+ }
123
+ if (typeof parsed.access_token !== "string" || parsed.access_token.length === 0) {
124
+ throw new TokenError("Keycloak token response did not contain an access_token");
125
+ }
126
+ return parsed;
127
+ }
128
+ /** Cached insecure undici dispatcher (built once, reused) so `verifySsl:false` costs one Agent. */
129
+ let insecureNodeDispatcher;
130
+ /**
131
+ * Lazily build a cached undici `Agent` that skips TLS certificate verification -- the Node analog of
132
+ * Python's `requests.post(..., verify=False)`. Node-guarded and loaded via a dynamic `import("undici")`
133
+ * so a browser bundle never pulls in `undici` and the flag stays a hard no-op outside Node.
134
+ *
135
+ * @returns The insecure dispatcher under Node, or `undefined` in a browser (TLS is owned by the browser).
136
+ */
137
+ async function getInsecureNodeDispatcher() {
138
+ const nodeProcess = globalThis.process;
139
+ /* c8 ignore next 3 -- browser guard: not exercised under the Node test runner */
140
+ if (nodeProcess === undefined || nodeProcess.versions === undefined || nodeProcess.versions.node === undefined) {
141
+ return undefined;
142
+ }
143
+ if (insecureNodeDispatcher === undefined) {
144
+ const undiciModuleName = "undici";
145
+ const undici = (await Promise.resolve(`${undiciModuleName}`).then(s => __importStar(require(s))));
146
+ insecureNodeDispatcher = new undici.Agent({ connect: { rejectUnauthorized: false } });
147
+ }
148
+ return insecureNodeDispatcher;
149
+ }
150
+ /**
151
+ * Build the DEFAULT token transport (used only when no `fetchImpl` is injected). It delegates to the
152
+ * global WHATWG fetch, and -- when `verifySsl` is `false` under Node -- attaches an insecure undici
153
+ * dispatcher to the request init so the token POST skips certificate verification. With `verifySsl`
154
+ * `true` (the default) it is a plain pass-through to `globalThis.fetch`, i.e. unchanged behavior.
155
+ *
156
+ * @param verifySsl - Whether to verify the Keycloak TLS certificate; `false` opts into the insecure path.
157
+ * @returns A {@link TokenFetch} that resolves the global fetch at call time (honoring test overrides).
158
+ */
159
+ function createDefaultTokenFetch(verifySsl) {
160
+ return async (url, init) => {
161
+ const dispatcher = verifySsl ? undefined : await getInsecureNodeDispatcher();
162
+ const effectiveInit = dispatcher !== undefined ? { ...init, dispatcher } : init;
163
+ const globalFetch = globalThis.fetch;
164
+ return globalFetch(url, effectiveInit);
165
+ };
166
+ }
167
+ /**
168
+ * A live access-token holder backed by a bounded auto-refresh loop. Obtain one from {@link login};
169
+ * read {@link getAuthorizationHeader} for the gRPC `Authorization` metadata and call {@link stop} when done.
170
+ */
171
+ class OfflineTokenProvider {
172
+ /**
173
+ * Construct an (un-bootstrapped) provider from login options. Call {@link bootstrap} (or use the
174
+ * module-level {@link login}) before reading a token.
175
+ *
176
+ * @param options - The D18 headless-SDK offline-token login options.
177
+ */
178
+ constructor(options) {
179
+ this.tokenEndpoint = buildTokenEndpoint(options.keycloakUrl, options.realm);
180
+ this.clientId = options.clientId;
181
+ this.tokenExpirationInS = options.tokenExpirationInS;
182
+ // A custom fetchImpl always wins (the verifySsl flag is ignored for injected transports); only the
183
+ // DEFAULT transport honors verifySsl, and only under Node. Absent/undefined verifySsl => secure (true).
184
+ const verifySsl = options.keycloakVerifySsl !== false;
185
+ this.fetchImpl =
186
+ options.fetchImpl !== undefined ? options.fetchImpl : createDefaultTokenFetch(verifySsl);
187
+ this.nowInMs = options.nowInMs !== undefined ? options.nowInMs : Date.now;
188
+ this.accessToken = null;
189
+ this.refreshToken = null;
190
+ this.timer = null;
191
+ this.stopped = false;
192
+ this.deadlineInMs = null;
193
+ this.onRefreshErrorHandler = null;
194
+ }
195
+ /**
196
+ * Perform the one-time ROPC login and arm the first refresh. Awaited by {@link login}.
197
+ *
198
+ * @param username - The 2FA-exempt technical-user email.
199
+ * @param password - The technical-user password.
200
+ * @returns A promise that resolves once the initial token is held and the first refresh is armed.
201
+ * @throws {TokenError} When the token endpoint fails or the response carries no refresh token.
202
+ */
203
+ async bootstrap(username, password) {
204
+ const tokenResponse = await postTokenRequest(this.tokenEndpoint, {
205
+ grant_type: "password",
206
+ client_id: this.clientId,
207
+ username,
208
+ password,
209
+ scope: "offline_access"
210
+ }, this.fetchImpl);
211
+ this.accessToken = tokenResponse.access_token;
212
+ this.refreshToken = typeof tokenResponse.refresh_token === "string" ? tokenResponse.refresh_token : null;
213
+ if (this.refreshToken === null) {
214
+ throw new TokenError("Keycloak token response did not contain a refresh_token; the SDK client must have " +
215
+ "directAccessGrants + the offline_access scope (ondewo-nlu-cai-sdk-public)");
216
+ }
217
+ if (this.tokenExpirationInS !== undefined) {
218
+ const expirationInMs = this.tokenExpirationInS * 1000;
219
+ this.deadlineInMs = this.nowInMs() + expirationInMs;
220
+ }
221
+ this.scheduleRefresh(tokenResponse.expires_in);
222
+ }
223
+ /**
224
+ * Exchange the offline refresh token for a fresh access token and re-arm the next refresh.
225
+ *
226
+ * @returns A promise that resolves once the token is refreshed (or the loop has stopped).
227
+ * @throws {TokenError} When the refresh token-endpoint call fails or returns an invalid body.
228
+ */
229
+ async refresh() {
230
+ /* c8 ignore next 3 -- unreachable: stop() always clears the only timer that calls refresh() */
231
+ if (this.stopped) {
232
+ return;
233
+ }
234
+ // Re-check the bounded deadline at fire time (not just at schedule time): once it has elapsed the
235
+ // loop stops with no further renewal -> the access token lapses -> re-login is required.
236
+ if (this.deadlineInMs !== null && this.nowInMs() >= this.deadlineInMs) {
237
+ this.stop();
238
+ return;
239
+ }
240
+ const tokenResponse = await postTokenRequest(this.tokenEndpoint, {
241
+ grant_type: "refresh_token",
242
+ client_id: this.clientId,
243
+ refresh_token: this.refreshToken
244
+ }, this.fetchImpl);
245
+ this.accessToken = tokenResponse.access_token;
246
+ // Keycloak may rotate the offline refresh token; keep the newest one when present.
247
+ if (typeof tokenResponse.refresh_token === "string" && tokenResponse.refresh_token.length > 0) {
248
+ this.refreshToken = tokenResponse.refresh_token;
249
+ }
250
+ this.scheduleRefresh(tokenResponse.expires_in);
251
+ }
252
+ /**
253
+ * Arm a single timer for the next refresh, clamped to the bounded deadline. Stops silently once
254
+ * `tokenExpirationInS` has elapsed (no further renewal -> access lapses -> re-login required).
255
+ *
256
+ * @param expiresInRaw - The `expires_in` (seconds) reported by Keycloak; absent/non-positive
257
+ * values fall back to {@link MIN_REFRESH_DELAY_IN_S}.
258
+ */
259
+ scheduleRefresh(expiresInRaw) {
260
+ if (this.stopped) {
261
+ return;
262
+ }
263
+ const expiresInS = typeof expiresInRaw === "number" && expiresInRaw > 0 ? expiresInRaw : MIN_REFRESH_DELAY_IN_S;
264
+ let delayInS = Math.max(expiresInS - REFRESH_SKEW_IN_S, MIN_REFRESH_DELAY_IN_S);
265
+ if (this.deadlineInMs !== null) {
266
+ const remainingInMs = this.deadlineInMs - this.nowInMs();
267
+ if (remainingInMs <= 0) {
268
+ this.stop();
269
+ return;
270
+ }
271
+ delayInS = Math.min(delayInS, remainingInMs / 1000);
272
+ }
273
+ this.timer = setTimeout(() => {
274
+ this.refresh().catch((refreshError) => {
275
+ // Swallow a transient refresh failure but surface it so the caller can react; the next
276
+ // gRPC call gets the stale (possibly expired) token and re-logs in on UNAUTHENTICATED.
277
+ if (this.onRefreshErrorHandler !== null) {
278
+ this.onRefreshErrorHandler(refreshError);
279
+ }
280
+ });
281
+ }, delayInS * 1000);
282
+ // Do not keep the event loop alive solely for the refresh timer.
283
+ /* c8 ignore next 3 -- the else branch is unreachable: Node's Timeout always exposes unref() */
284
+ if (typeof this.timer.unref === "function") {
285
+ this.timer.unref();
286
+ }
287
+ }
288
+ /**
289
+ * Register a callback invoked with the error of a failed background refresh (optional diagnostics).
290
+ *
291
+ * @param handler - The callback to receive the refresh error; replaces any previously registered one.
292
+ */
293
+ onRefreshError(handler) {
294
+ this.onRefreshErrorHandler = handler;
295
+ }
296
+ /**
297
+ * Read the current access token.
298
+ *
299
+ * @returns The current access token, or `null` before bootstrap / after the bounded loop has lapsed.
300
+ */
301
+ getAccessToken() {
302
+ return this.accessToken;
303
+ }
304
+ /**
305
+ * Build the value for an `Authorization` gRPC metadata header.
306
+ *
307
+ * @returns The `Bearer <access_token>` header value.
308
+ * @throws {TokenError} When no access token is available (login not completed or already lapsed).
309
+ */
310
+ getAuthorizationHeader() {
311
+ if (this.accessToken === null) {
312
+ throw new TokenError("No access token available; login() has not completed or has lapsed");
313
+ }
314
+ return `Bearer ${this.accessToken}`;
315
+ }
316
+ /** Stop the auto-refresh loop. Idempotent; safe to call from any state. */
317
+ stop() {
318
+ this.stopped = true;
319
+ if (this.timer !== null) {
320
+ clearTimeout(this.timer);
321
+ this.timer = null;
322
+ }
323
+ }
324
+ }
325
+ exports.OfflineTokenProvider = OfflineTokenProvider;
326
+ /**
327
+ * One-time ROPC + offline_access login against the PUBLIC SDK client, returning a live token provider
328
+ * whose access token is auto-refreshed in the background until `tokenExpirationInS` elapses.
329
+ *
330
+ * @param options - The headless-SDK login options (`keycloakUrl`, `realm`, `clientId`, `username`,
331
+ * `password` are required; `tokenExpirationInS`, `fetchImpl`, `nowInMs` are optional).
332
+ * @returns A bootstrapped {@link OfflineTokenProvider} holding a live access token.
333
+ * @throws {TokenError} When required options are missing/empty, the token endpoint fails, or the
334
+ * response lacks an access or refresh token.
335
+ */
336
+ async function login(options) {
337
+ if (options === undefined || options === null) {
338
+ throw new TokenError("login() requires an options object");
339
+ }
340
+ const requiredKeys = [
341
+ "keycloakUrl",
342
+ "realm",
343
+ "clientId",
344
+ "username",
345
+ "password"
346
+ ];
347
+ for (const key of requiredKeys) {
348
+ const value = options[key];
349
+ if (typeof value !== "string" || value.length === 0) {
350
+ throw new TokenError(`login() option "${key}" is required and must be a non-empty string`);
351
+ }
352
+ }
353
+ const provider = new OfflineTokenProvider(options);
354
+ await provider.bootstrap(options.username, options.password);
355
+ return provider;
356
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ondewo/nlu-client-typescript",
3
- "version": "6.13.0",
3
+ "version": "6.14.0",
4
4
  "description": "ONDEWO Natural Language Understanding (NLU) Client library for Typescript",
5
5
  "author": "ONDEWO GmbH <office@ondewo.com>",
6
6
  "homepage": "https://ondewo.com",
@@ -22,7 +22,8 @@
22
22
  "dependencies": {
23
23
  "google-protobuf": "3.21.4",
24
24
  "grpc-web": "^1.5.0",
25
- "tslib": "^2.8.1"
25
+ "tslib": "^2.8.1",
26
+ "undici": "^6.27.0"
26
27
  },
27
28
  "devDependencies": {
28
29
  "@eslint/eslintrc": "^3.1.0",
package/public-api.d.ts CHANGED
@@ -1,44 +1,44 @@
1
- export * from './api/ondewo/qa/qa_grpc_web_pb.d';
2
- export * from './api/ondewo/qa/qa_pb.d';
1
+ export * from './api/ondewo/nlu/user_pb.d';
3
2
  export * from './api/ondewo/nlu/session_grpc_web_pb.d';
4
3
  export * from './api/ondewo/nlu/user_grpc_web_pb.d';
5
- export * from './api/ondewo/nlu/project_role_grpc_web_pb.d';
6
- export * from './api/ondewo/nlu/entity_type_pb.d';
7
- export * from './api/ondewo/nlu/webhook_pb.d';
8
- export * from './api/ondewo/nlu/agent_pb.d';
9
- export * from './api/ondewo/nlu/session_pb.d';
10
- export * from './api/ondewo/nlu/common_pb.d';
11
- export * from './api/ondewo/nlu/operation_metadata_pb.d';
12
- export * from './api/ondewo/nlu/rag_pb.d';
13
- export * from './api/ondewo/nlu/server_statistics_pb.d';
14
- export * from './api/ondewo/nlu/aiservices_pb.d';
4
+ export * from './api/ondewo/nlu/project_role_pb.d';
5
+ export * from './api/ondewo/nlu/context_pb.d';
6
+ export * from './api/ondewo/nlu/intent_pb.d';
15
7
  export * from './api/ondewo/nlu/server_statistics_grpc_web_pb.d';
8
+ export * from './api/ondewo/nlu/webhook_grpc_web_pb.d';
9
+ export * from './api/ondewo/nlu/webhook_pb.d';
16
10
  export * from './api/ondewo/nlu/context_grpc_web_pb.d';
17
- export * from './api/ondewo/nlu/operations_pb.d';
18
- export * from './api/ondewo/nlu/aiservices_grpc_web_pb.d';
19
11
  export * from './api/ondewo/nlu/llm_evaluation_grpc_web_pb.d';
12
+ export * from './api/ondewo/nlu/entity_type_pb.d';
20
13
  export * from './api/ondewo/nlu/project_statistics_grpc_web_pb.d';
21
- export * from './api/ondewo/nlu/rag_grpc_web_pb.d';
22
- export * from './api/ondewo/nlu/context_pb.d';
23
- export * from './api/ondewo/nlu/intent_pb.d';
24
- export * from './api/ondewo/nlu/utility_pb.d';
14
+ export * from './api/ondewo/nlu/agent_grpc_web_pb.d';
25
15
  export * from './api/ondewo/nlu/operations_grpc_web_pb.d';
16
+ export * from './api/ondewo/nlu/session_pb.d';
17
+ export * from './api/ondewo/nlu/rag_pb.d';
18
+ export * from './api/ondewo/nlu/agent_pb.d';
19
+ export * from './api/ondewo/nlu/intent_grpc_web_pb.d';
20
+ export * from './api/ondewo/nlu/aiservices_grpc_web_pb.d';
21
+ export * from './api/ondewo/nlu/operations_pb.d';
22
+ export * from './api/ondewo/nlu/common_pb.d';
23
+ export * from './api/ondewo/nlu/operation_metadata_pb.d';
26
24
  export * from './api/ondewo/nlu/ccai_project_pb.d';
27
- export * from './api/ondewo/nlu/webhook_grpc_web_pb.d';
28
- export * from './api/ondewo/nlu/project_role_pb.d';
25
+ export * from './api/ondewo/nlu/project_role_grpc_web_pb.d';
29
26
  export * from './api/ondewo/nlu/entity_type_grpc_web_pb.d';
30
- export * from './api/ondewo/nlu/utility_grpc_web_pb.d';
31
- export * from './api/ondewo/nlu/project_statistics_pb.d';
32
27
  export * from './api/ondewo/nlu/ccai_project_grpc_web_pb.d';
33
- export * from './api/ondewo/nlu/user_pb.d';
28
+ export * from './api/ondewo/nlu/utility_pb.d';
29
+ export * from './api/ondewo/nlu/rag_grpc_web_pb.d';
34
30
  export * from './api/ondewo/nlu/llm_evaluation_pb.d';
35
- export * from './api/ondewo/nlu/intent_grpc_web_pb.d';
36
- export * from './api/ondewo/nlu/agent_grpc_web_pb.d';
37
- export * from './api/google/api/annotations_pb.d';
38
- export * from './api/google/type/latlng_pb.d';
39
- export * from './api/google/rpc/status_pb.d';
40
- export * from './api/google/protobuf/any_pb.d';
41
- export * from './api/google/protobuf/field_mask_pb.d';
42
- export * from './api/google/protobuf/struct_pb.d';
31
+ export * from './api/ondewo/nlu/project_statistics_pb.d';
32
+ export * from './api/ondewo/nlu/aiservices_pb.d';
33
+ export * from './api/ondewo/nlu/server_statistics_pb.d';
34
+ export * from './api/ondewo/nlu/utility_grpc_web_pb.d';
35
+ export * from './api/ondewo/qa/qa_pb.d';
36
+ export * from './api/ondewo/qa/qa_grpc_web_pb.d';
43
37
  export * from './api/google/protobuf/timestamp_pb.d';
38
+ export * from './api/google/protobuf/field_mask_pb.d';
44
39
  export * from './api/google/protobuf/empty_pb.d';
40
+ export * from './api/google/protobuf/struct_pb.d';
41
+ export * from './api/google/protobuf/any_pb.d';
42
+ export * from './api/google/type/latlng_pb.d';
43
+ export * from './api/google/api/annotations_pb.d';
44
+ export * from './api/google/rpc/status_pb.d';