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