@tuvl/client 0.0.1 → 2026.2.1-beta.1

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/dist/index.mjs ADDED
@@ -0,0 +1,689 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res) => function __init() {
4
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
+ };
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+
11
+ // src/grpc.ts
12
+ var grpc_exports = {};
13
+ __export(grpc_exports, {
14
+ openGrpcStream: () => openGrpcStream
15
+ });
16
+ async function* openGrpcStream(options) {
17
+ let GrpcWebFetchTransport;
18
+ try {
19
+ const mod = await import('@protobuf-ts/grpcweb-transport');
20
+ GrpcWebFetchTransport = mod.GrpcWebFetchTransport;
21
+ } catch {
22
+ throw new Error(
23
+ "@tuvl/client: gRPC mode requires @protobuf-ts/grpcweb-transport. Install it with: npm i @protobuf-ts/grpcweb-transport @protobuf-ts/runtime-rpc"
24
+ );
25
+ }
26
+ const { BinaryWriter, BinaryReader, WireType } = await import('@protobuf-ts/runtime');
27
+ function encodeRunRequest(workflowName, payloadJson, tokenFallback) {
28
+ const writer = new BinaryWriter();
29
+ writer.tag(1, WireType.LengthDelimited).string(workflowName);
30
+ writer.tag(2, WireType.LengthDelimited).string(payloadJson);
31
+ if (tokenFallback) {
32
+ writer.tag(3, WireType.LengthDelimited).string(tokenFallback);
33
+ }
34
+ return writer.finish();
35
+ }
36
+ function decodeStepEvent(bytes) {
37
+ const reader = new BinaryReader(bytes);
38
+ let eventType = "";
39
+ let stepId = "";
40
+ let kind = "";
41
+ let signal = "";
42
+ let snapshotJson = "";
43
+ let durationMs = 0;
44
+ let errorDetail = "";
45
+ while (reader.pos < reader.len) {
46
+ const [fieldNo, wireType] = reader.tag();
47
+ switch (fieldNo) {
48
+ case 1:
49
+ eventType = reader.string();
50
+ break;
51
+ case 2:
52
+ stepId = reader.string();
53
+ break;
54
+ case 3:
55
+ kind = reader.string();
56
+ break;
57
+ case 4:
58
+ signal = reader.string();
59
+ break;
60
+ case 5:
61
+ snapshotJson = reader.string();
62
+ break;
63
+ case 6:
64
+ durationMs = reader.float();
65
+ break;
66
+ case 7:
67
+ errorDetail = reader.string();
68
+ break;
69
+ default:
70
+ reader.skip(wireType);
71
+ }
72
+ }
73
+ let snapshot = {};
74
+ if (snapshotJson) {
75
+ try {
76
+ snapshot = JSON.parse(snapshotJson);
77
+ } catch {
78
+ }
79
+ }
80
+ const et = eventType || "step";
81
+ return {
82
+ event_type: et,
83
+ step_id: stepId,
84
+ kind,
85
+ signal,
86
+ snapshot,
87
+ duration_ms: durationMs,
88
+ error_detail: errorDetail || void 0
89
+ };
90
+ }
91
+ const transport = new GrpcWebFetchTransport({
92
+ baseUrl: options.baseUrl,
93
+ fetchInit: options.token ? { headers: { Authorization: `Bearer ${options.token}` } } : void 0
94
+ });
95
+ const methodDescriptor = {
96
+ name: "/tuvl.v1.ExecutionService/RunWorkflow",
97
+ clientStreaming: false,
98
+ serverStreaming: true,
99
+ I: { create: () => ({}) },
100
+ O: { create: () => ({}) },
101
+ options: {}
102
+ };
103
+ const requestBytes = encodeRunRequest(
104
+ options.workflowName,
105
+ options.payloadJson,
106
+ options.tokenFallback ?? ""
107
+ );
108
+ const call = transport.serverStreaming(methodDescriptor, requestBytes, {
109
+ abort: options.signal
110
+ });
111
+ for await (const responseBytes of call.responses) {
112
+ const event = decodeStepEvent(responseBytes);
113
+ yield event;
114
+ if (event.event_type === "done" || event.event_type === "error" || event.event_type === "suspended") {
115
+ break;
116
+ }
117
+ }
118
+ }
119
+ var init_grpc = __esm({
120
+ "src/grpc.ts"() {
121
+ }
122
+ });
123
+
124
+ // src/sse.ts
125
+ async function* parseSseStream(response, signal) {
126
+ if (!response.body) {
127
+ throw new Error("SSE response has no body");
128
+ }
129
+ const reader = response.body.getReader();
130
+ const decoder = new TextDecoder("utf-8");
131
+ let buffer = "";
132
+ let currentEventType = "message";
133
+ let currentDataLines = [];
134
+ const flush = function* () {
135
+ const dataStr = currentDataLines.join("\n");
136
+ const eventType = currentEventType;
137
+ currentDataLines = [];
138
+ currentEventType = "message";
139
+ if (!dataStr) return;
140
+ let parsed;
141
+ try {
142
+ parsed = JSON.parse(dataStr);
143
+ } catch {
144
+ return;
145
+ }
146
+ if (typeof parsed !== "object" || parsed === null) return;
147
+ const frame = { ...parsed, event_type: eventType };
148
+ yield frame;
149
+ };
150
+ try {
151
+ while (true) {
152
+ if (signal?.aborted) break;
153
+ const { done, value } = await reader.read();
154
+ if (done) break;
155
+ buffer += decoder.decode(value, { stream: true });
156
+ const lines = buffer.split("\n");
157
+ buffer = lines.pop() ?? "";
158
+ for (const rawLine of lines) {
159
+ const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
160
+ if (line.startsWith("event:")) {
161
+ currentEventType = line.slice(6).trim();
162
+ } else if (line.startsWith("data:")) {
163
+ currentDataLines.push(line.slice(5).trim());
164
+ } else if (line === "") {
165
+ for (const frame of flush()) {
166
+ yield frame;
167
+ if (frame.event_type === "done" || frame.event_type === "error" || frame.event_type === "suspended") {
168
+ return;
169
+ }
170
+ }
171
+ }
172
+ }
173
+ }
174
+ for (const frame of flush()) {
175
+ yield frame;
176
+ }
177
+ } finally {
178
+ reader.releaseLock();
179
+ }
180
+ }
181
+
182
+ // src/transport.ts
183
+ var Transport = class {
184
+ constructor(options) {
185
+ this.baseUrl = options.baseUrl.replace(/\/$/, "");
186
+ this.defaultToken = options.defaultToken;
187
+ }
188
+ /** Update the default token (e.g. after refresh). */
189
+ setToken(token) {
190
+ this.defaultToken = token;
191
+ }
192
+ /** Build the Authorization header value, or undefined if no token. */
193
+ authHeader(overrideToken) {
194
+ const tok = overrideToken ?? this.defaultToken;
195
+ return tok ? `Bearer ${tok}` : void 0;
196
+ }
197
+ /** Perform a plain JSON POST and return the parsed response body. */
198
+ async post(path, body, options) {
199
+ const headers = {
200
+ "Content-Type": "application/json",
201
+ Accept: "application/json"
202
+ };
203
+ const auth = this.authHeader(options?.token);
204
+ if (auth) headers["Authorization"] = auth;
205
+ const response = await fetch(`${this.baseUrl}${path}`, {
206
+ method: "POST",
207
+ headers,
208
+ body: JSON.stringify(body),
209
+ signal: options?.signal
210
+ });
211
+ if (!response.ok) {
212
+ const text = await response.text();
213
+ throw new Error(`tuvl POST ${path} \u2192 HTTP ${response.status}: ${text}`);
214
+ }
215
+ return response.json();
216
+ }
217
+ /**
218
+ * Open an SSE-capable stream and return the raw Response.
219
+ * Callers are responsible for reading `response.body`.
220
+ */
221
+ async postStream(path, body, options) {
222
+ const headers = {
223
+ "Content-Type": "application/json",
224
+ Accept: "text/event-stream",
225
+ "Cache-Control": "no-cache"
226
+ };
227
+ const auth = this.authHeader(options?.token);
228
+ if (auth) headers["Authorization"] = auth;
229
+ const response = await fetch(`${this.baseUrl}${path}`, {
230
+ method: "POST",
231
+ headers,
232
+ body: JSON.stringify(body),
233
+ signal: options?.signal
234
+ });
235
+ if (!response.ok) {
236
+ const text = await response.text();
237
+ throw new Error(`tuvl SSE ${path} \u2192 HTTP ${response.status}: ${text}`);
238
+ }
239
+ return response;
240
+ }
241
+ /** Simple GET returning parsed JSON. */
242
+ async get(path, options) {
243
+ const headers = { Accept: "application/json" };
244
+ const auth = this.authHeader(options?.token);
245
+ if (auth) headers["Authorization"] = auth;
246
+ const response = await fetch(`${this.baseUrl}${path}`, {
247
+ method: "GET",
248
+ headers,
249
+ signal: options?.signal
250
+ });
251
+ if (!response.ok) {
252
+ const text = await response.text();
253
+ throw new Error(`tuvl GET ${path} \u2192 HTTP ${response.status}: ${text}`);
254
+ }
255
+ return response.json();
256
+ }
257
+ };
258
+
259
+ // src/types.ts
260
+ var TuvlWorkflowError = class extends Error {
261
+ constructor(message, data, error) {
262
+ super(message);
263
+ this.name = "TuvlWorkflowError";
264
+ this.data = data;
265
+ this.error = error;
266
+ }
267
+ };
268
+ var TuvlWorkflowSuspendedError = class extends Error {
269
+ constructor(suspended) {
270
+ super(`tuvl workflow suspended at step '${suspended.paused_step_id ?? "?"}'`);
271
+ this.name = "TuvlWorkflowSuspendedError";
272
+ this.suspended = suspended;
273
+ }
274
+ };
275
+
276
+ // src/client.ts
277
+ var TuvlClient = class {
278
+ constructor(options) {
279
+ this.manifestCache = /* @__PURE__ */ new Map();
280
+ this.transport = new Transport({
281
+ baseUrl: options.baseUrl,
282
+ defaultToken: options.token
283
+ });
284
+ this.manifestCacheTtl = options.manifestCacheTtl ?? 6e4;
285
+ }
286
+ /** Update the default auth token (e.g. after token refresh). */
287
+ setToken(token) {
288
+ this.transport.setToken(token);
289
+ }
290
+ /** Expose the base URL for callers that need raw access (e.g. gRPC). */
291
+ get baseUrl() {
292
+ return this.transport.baseUrl;
293
+ }
294
+ // ── Manifest ──────────────────────────────────────────────────────────────
295
+ /** Fetch (and cache) the manifest for a single workflow. */
296
+ async getManifest(workflowName, options) {
297
+ const cached = this.manifestCache.get(workflowName);
298
+ if (cached && Date.now() < cached.expiresAt) {
299
+ return cached.manifest;
300
+ }
301
+ const manifest = await this.transport.get(
302
+ `/api/_system/workflows/${encodeURIComponent(workflowName)}`,
303
+ options
304
+ );
305
+ if (this.manifestCacheTtl > 0) {
306
+ this.manifestCache.set(workflowName, {
307
+ manifest,
308
+ expiresAt: Date.now() + this.manifestCacheTtl
309
+ });
310
+ }
311
+ return manifest;
312
+ }
313
+ /** Fetch manifests for all registered workflows. */
314
+ async listWorkflows(options) {
315
+ return this.transport.get("/api/_system/workflows", options);
316
+ }
317
+ /** Invalidate the cached manifest for a workflow (or all if no name given). */
318
+ invalidateManifest(workflowName) {
319
+ if (workflowName) {
320
+ this.manifestCache.delete(workflowName);
321
+ } else {
322
+ this.manifestCache.clear();
323
+ }
324
+ }
325
+ // ── Execute ───────────────────────────────────────────────────────────────
326
+ /**
327
+ * Execute a workflow and return its `data` payload.
328
+ *
329
+ * Transport selection:
330
+ * 1. mode="grpc" → gRPC-Web (always, regardless of onProgress)
331
+ * 2. mode="sse" → SSE stream
332
+ * 3. onProgress provided → SSE if workflow has_slow_steps, else REST
333
+ * 4. default → REST
334
+ *
335
+ * @throws {TuvlWorkflowError} when the workflow returns success=false
336
+ * @throws {TuvlWorkflowSuspendedError} when the workflow suspends at HITL
337
+ * @throws {Error} on transport / engine failures
338
+ */
339
+ async execute(workflowName, options = {}) {
340
+ const { payload = {}, onProgress, onSuspended, mode, token, signal } = options;
341
+ const manifest = await this.getManifest(workflowName, { token, signal });
342
+ const useSse = mode === "sse" || mode !== "rest" && mode !== "grpc" && !!onProgress && manifest.has_slow_steps;
343
+ if (mode === "grpc") {
344
+ return this._executeGrpc(manifest, payload, onProgress, onSuspended, token, signal);
345
+ }
346
+ if (useSse) {
347
+ return this._executeSse(manifest, payload, onProgress, onSuspended, token, signal);
348
+ }
349
+ const envelope = await this.transport.post(
350
+ manifest.trigger_path,
351
+ payload,
352
+ { token, signal }
353
+ );
354
+ return this._unwrapRest(envelope, manifest.name);
355
+ }
356
+ /**
357
+ * Execute a specific version of a workflow via `/{version}/run/{name}`.
358
+ *
359
+ * Useful when you want to pin to a particular schema_version without
360
+ * relying on the currently-active default trigger path.
361
+ *
362
+ * @throws {TuvlWorkflowError} when the workflow returns success=false
363
+ * @throws {TuvlWorkflowSuspendedError} when the workflow suspends at HITL
364
+ * @throws {Error} on transport / engine failures
365
+ */
366
+ async executeVersioned(workflowName, version, options = {}) {
367
+ const { payload = {}, onProgress, onSuspended, mode, token, signal } = options;
368
+ const triggerPath = `/${version}/run/${workflowName}`;
369
+ let cachedManifest;
370
+ try {
371
+ cachedManifest = await this.getManifest(workflowName, { token, signal });
372
+ } catch {
373
+ }
374
+ const syntheticManifest = {
375
+ name: workflowName,
376
+ trigger_path: triggerPath,
377
+ trigger_method: "POST",
378
+ has_slow_steps: cachedManifest?.has_slow_steps ?? false,
379
+ slow_kinds_present: cachedManifest?.slow_kinds_present ?? [],
380
+ required_scope: cachedManifest?.required_scope ?? null,
381
+ required_group: cachedManifest?.required_group ?? null,
382
+ steps: cachedManifest?.steps ?? []
383
+ };
384
+ const useSse = mode === "sse" || mode !== "rest" && mode !== "grpc" && !!onProgress && syntheticManifest.has_slow_steps;
385
+ if (mode === "grpc") {
386
+ return this._executeGrpc(
387
+ syntheticManifest,
388
+ payload,
389
+ onProgress,
390
+ onSuspended,
391
+ token,
392
+ signal
393
+ );
394
+ }
395
+ if (useSse) {
396
+ return this._executeSse(
397
+ syntheticManifest,
398
+ payload,
399
+ onProgress,
400
+ onSuspended,
401
+ token,
402
+ signal
403
+ );
404
+ }
405
+ const envelope = await this.transport.post(
406
+ triggerPath,
407
+ payload,
408
+ { token, signal }
409
+ );
410
+ return this._unwrapRest(envelope, workflowName);
411
+ }
412
+ /**
413
+ * Resume a HITL-suspended workflow instance.
414
+ *
415
+ * After the workflow throws `TuvlWorkflowSuspendedError`, capture the
416
+ * `event.instance_id` from the suspended event and pass it here along with
417
+ * the human-provided data to continue execution.
418
+ *
419
+ * @throws {TuvlWorkflowError} when the resumed workflow returns success=false
420
+ * @throws {TuvlWorkflowSuspendedError} when the workflow suspends again at another HITL step
421
+ * @throws {Error} on transport / engine failures
422
+ */
423
+ async resumeWorkflow(options) {
424
+ const { instanceId, humanInput = {}, onProgress, onSuspended, mode, token, signal } = options;
425
+ const body = {
426
+ instance_id: instanceId,
427
+ human_input: humanInput
428
+ };
429
+ if (mode === "sse" || mode !== "rest" && !!onProgress) {
430
+ const syntheticManifest = {
431
+ name: `(resumed:${instanceId})`,
432
+ trigger_path: "/api/workflows/resume",
433
+ trigger_method: "POST",
434
+ has_slow_steps: true,
435
+ slow_kinds_present: [],
436
+ required_scope: null,
437
+ required_group: null,
438
+ steps: []
439
+ };
440
+ return this._executeSse(
441
+ syntheticManifest,
442
+ body,
443
+ onProgress,
444
+ onSuspended,
445
+ token,
446
+ signal
447
+ );
448
+ }
449
+ const envelope = await this.transport.post(
450
+ "/api/workflows/resume",
451
+ body,
452
+ { token, signal }
453
+ );
454
+ return this._unwrapRest(envelope, `(resumed:${instanceId})`);
455
+ }
456
+ // ── SSE transport ─────────────────────────────────────────────────────────
457
+ async _executeSse(manifest, payload, onProgress, onSuspended, token, signal) {
458
+ const response = await this.transport.postStream(manifest.trigger_path, payload, {
459
+ token,
460
+ signal
461
+ });
462
+ let done;
463
+ for await (const frame of parseSseStream(response, signal)) {
464
+ switch (frame.event_type) {
465
+ case "step":
466
+ onProgress?.(frame);
467
+ break;
468
+ case "done":
469
+ done = frame;
470
+ break;
471
+ case "suspended":
472
+ onSuspended?.(frame);
473
+ throw new TuvlWorkflowSuspendedError(frame);
474
+ case "error": {
475
+ const err = frame;
476
+ throw new Error(
477
+ `tuvl workflow '${manifest.name}' engine error: ${err.message}` + (err.details ? ` \u2014 ${err.details}` : "")
478
+ );
479
+ }
480
+ }
481
+ }
482
+ if (!done) {
483
+ throw new Error(`tuvl SSE stream for '${manifest.name}' ended without a done event`);
484
+ }
485
+ if (!done.success) {
486
+ throw new TuvlWorkflowError(
487
+ `tuvl workflow '${manifest.name}' failed`,
488
+ done.data,
489
+ done.error
490
+ );
491
+ }
492
+ return done.data;
493
+ }
494
+ // ── gRPC-Web transport ────────────────────────────────────────────────────
495
+ async _executeGrpc(manifest, payload, onProgress, onSuspended, token, signal) {
496
+ const { openGrpcStream: openGrpcStream2 } = await Promise.resolve().then(() => (init_grpc(), grpc_exports));
497
+ let finalSnapshot;
498
+ for await (const event of openGrpcStream2({
499
+ baseUrl: this.baseUrl,
500
+ workflowName: manifest.name,
501
+ payloadJson: JSON.stringify(payload),
502
+ token,
503
+ signal
504
+ })) {
505
+ switch (event.event_type) {
506
+ case "step":
507
+ onProgress?.(event);
508
+ break;
509
+ case "done":
510
+ finalSnapshot = event.snapshot;
511
+ break;
512
+ case "suspended": {
513
+ const snap = event.snapshot;
514
+ const suspended = {
515
+ event_type: "suspended",
516
+ paused_step_id: event.step_id,
517
+ ...snap
518
+ };
519
+ onSuspended?.(suspended);
520
+ throw new TuvlWorkflowSuspendedError(suspended);
521
+ }
522
+ case "error":
523
+ throw new Error(
524
+ `tuvl workflow '${manifest.name}' gRPC error: ${event.error_detail ?? "unknown"}`
525
+ );
526
+ }
527
+ }
528
+ if (finalSnapshot === void 0) {
529
+ throw new Error(`tuvl gRPC stream for '${manifest.name}' ended without a done event`);
530
+ }
531
+ if ("_last_error" in finalSnapshot) {
532
+ throw new TuvlWorkflowError(
533
+ `tuvl workflow '${manifest.name}' failed`,
534
+ finalSnapshot,
535
+ finalSnapshot._last_error ?? null
536
+ );
537
+ }
538
+ if ("_response" in finalSnapshot) {
539
+ return finalSnapshot._response;
540
+ }
541
+ return finalSnapshot;
542
+ }
543
+ // ── REST envelope ─────────────────────────────────────────────────────────
544
+ _unwrapRest(envelope, workflowName) {
545
+ if (!envelope || typeof envelope !== "object") {
546
+ return envelope;
547
+ }
548
+ if (envelope.success === false) {
549
+ throw new TuvlWorkflowError(
550
+ `tuvl workflow '${workflowName}' failed`,
551
+ envelope.data,
552
+ envelope.error
553
+ );
554
+ }
555
+ return envelope.data ?? envelope;
556
+ }
557
+ };
558
+
559
+ // src/auth.ts
560
+ var TuvlAuth = class {
561
+ constructor(options) {
562
+ this.baseUrl = options.baseUrl.replace(/\/$/, "");
563
+ }
564
+ /**
565
+ * Decode the current token server-side and return the user's identity,
566
+ * role memberships (`groups`), and permission scopes.
567
+ *
568
+ * Biscuit tokens are protobuf-encoded and cannot be decoded in pure JS,
569
+ * so this is the correct way to read "who is logged in" and "what can
570
+ * they do" from the TypeScript SDK.
571
+ *
572
+ * @throws if the token is invalid, expired, or revoked.
573
+ */
574
+ async getMe(token) {
575
+ const response = await fetch(`${this.baseUrl}/auth/me`, {
576
+ method: "GET",
577
+ headers: {
578
+ Authorization: `Bearer ${token}`,
579
+ Accept: "application/json"
580
+ }
581
+ });
582
+ if (!response.ok) {
583
+ const text = await response.text();
584
+ throw new Error(`tuvl getMe failed (HTTP ${response.status}): ${text}`);
585
+ }
586
+ return response.json();
587
+ }
588
+ /**
589
+ * Exchange an email + password for a Biscuit bearer token.
590
+ *
591
+ * Calls `POST /auth/token` with an `application/x-www-form-urlencoded`
592
+ * body (OAuth2 password-grant). The `username` field must be the user's
593
+ * email address.
594
+ */
595
+ async loginWithPassword(email, password) {
596
+ const body = new URLSearchParams({ username: email, password });
597
+ const response = await fetch(`${this.baseUrl}/auth/token`, {
598
+ method: "POST",
599
+ headers: {
600
+ "Content-Type": "application/x-www-form-urlencoded",
601
+ Accept: "application/json"
602
+ },
603
+ body
604
+ });
605
+ if (!response.ok) {
606
+ const text = await response.text();
607
+ throw new Error(`tuvl login failed (HTTP ${response.status}): ${text}`);
608
+ }
609
+ return response.json();
610
+ }
611
+ /**
612
+ * Create the first superadmin user (one-time IAM bootstrap).
613
+ *
614
+ * Calls `POST /auth/bootstrap`. Returns 409 on every subsequent call
615
+ * once any user exists.
616
+ */
617
+ async bootstrap(req) {
618
+ const response = await fetch(`${this.baseUrl}/auth/bootstrap`, {
619
+ method: "POST",
620
+ headers: {
621
+ "Content-Type": "application/json",
622
+ Accept: "application/json"
623
+ },
624
+ body: JSON.stringify(req)
625
+ });
626
+ if (!response.ok) {
627
+ const text = await response.text();
628
+ throw new Error(`tuvl bootstrap failed (HTTP ${response.status}): ${text}`);
629
+ }
630
+ return response.json();
631
+ }
632
+ /**
633
+ * Return the URL the browser should navigate to in order to start an
634
+ * OAuth2 login flow for the given provider.
635
+ *
636
+ * Supported built-ins: `"google"`, `"github"`, `"microsoft"`. Any
637
+ * provider configured in the project's `federation/` directory also
638
+ * works.
639
+ *
640
+ * After the OAuth dance the server either:
641
+ * - redirects to `TUVL_OAUTH_UI_REDIRECT_URL?token=<biscuit_b64>`, OR
642
+ * - returns a JSON `{access_token, token_type}` body (CLI / server flows).
643
+ */
644
+ getOAuthLoginUrl(provider) {
645
+ return `${this.baseUrl}/auth/oauth/${encodeURIComponent(provider)}/start`;
646
+ }
647
+ /**
648
+ * Exchange a valid (non-expired, non-revoked) token for a fresh one.
649
+ * The old token is immediately blacklisted — discard it after this call.
650
+ */
651
+ async refresh(token) {
652
+ const response = await fetch(`${this.baseUrl}/auth/refresh`, {
653
+ method: "POST",
654
+ headers: {
655
+ Authorization: `Bearer ${token}`,
656
+ Accept: "application/json"
657
+ }
658
+ });
659
+ if (!response.ok) {
660
+ const text = await response.text();
661
+ throw new Error(`tuvl token refresh failed (HTTP ${response.status}): ${text}`);
662
+ }
663
+ return response.json();
664
+ }
665
+ /**
666
+ * Revoke the given token (logout). After this the token is blacklisted
667
+ * across all workers that share a Redis instance. Resolves silently on
668
+ * success (HTTP 204).
669
+ */
670
+ async logout(token) {
671
+ const response = await fetch(`${this.baseUrl}/auth/logout`, {
672
+ method: "POST",
673
+ headers: {
674
+ Authorization: `Bearer ${token}`
675
+ }
676
+ });
677
+ if (!response.ok && response.status !== 204) {
678
+ const text = await response.text();
679
+ throw new Error(`tuvl logout failed (HTTP ${response.status}): ${text}`);
680
+ }
681
+ }
682
+ };
683
+
684
+ // src/index.ts
685
+ init_grpc();
686
+
687
+ export { Transport, TuvlAuth, TuvlClient, TuvlWorkflowError, TuvlWorkflowSuspendedError, openGrpcStream, parseSseStream };
688
+ //# sourceMappingURL=index.mjs.map
689
+ //# sourceMappingURL=index.mjs.map