@tuvl/client 0.0.1 → 2026.2.1-beta.2

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,840 @@
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/crud.ts
125
+ var CrudClient = class {
126
+ constructor(transport, modelName) {
127
+ this.transport = transport;
128
+ this.basePath = `/models/${modelName.toLowerCase()}`;
129
+ }
130
+ // ── Private helpers ──────────────────────────────────────────────────────
131
+ /** Build query string from list options. */
132
+ _buildQuery(options) {
133
+ const params = new URLSearchParams();
134
+ if (options.limit !== void 0) params.set("limit", String(options.limit));
135
+ if (options.offset !== void 0) params.set("offset", String(options.offset));
136
+ if (options.filters) {
137
+ for (const [key, value] of Object.entries(options.filters)) {
138
+ params.set(`filter[${key}]`, value);
139
+ }
140
+ }
141
+ if (options.include && options.include.length > 0) {
142
+ params.set("include", options.include.join(","));
143
+ }
144
+ const qs = params.toString();
145
+ return qs ? `?${qs}` : "";
146
+ }
147
+ /** Build ?include= query string for get-by-id calls. */
148
+ _buildGetQuery(options) {
149
+ if (!options.include || options.include.length === 0) return "";
150
+ const params = new URLSearchParams({ include: options.include.join(",") });
151
+ return `?${params.toString()}`;
152
+ }
153
+ // ── Public CRUD methods ──────────────────────────────────────────────────
154
+ /**
155
+ * GET /models/{model}/
156
+ * Returns all records matching the given filters (server default: up to 100).
157
+ */
158
+ async list(options = {}) {
159
+ const qs = this._buildQuery(options);
160
+ return this.transport.get(`${this.basePath}/${qs}`, {
161
+ token: options.token,
162
+ signal: options.signal
163
+ });
164
+ }
165
+ /**
166
+ * GET /models/{model}/{id}
167
+ * Returns a single record by UUID, optionally with embedded relations.
168
+ */
169
+ async get(id, options = {}) {
170
+ const qs = this._buildGetQuery(options);
171
+ return this.transport.get(`${this.basePath}/${encodeURIComponent(id)}${qs}`, {
172
+ token: options.token,
173
+ signal: options.signal
174
+ });
175
+ }
176
+ /**
177
+ * POST /models/{model}/
178
+ * Creates a new record and returns the created resource (HTTP 201).
179
+ */
180
+ async create(body, options = {}) {
181
+ return this.transport.post(`${this.basePath}/`, body, {
182
+ token: options.token,
183
+ signal: options.signal
184
+ });
185
+ }
186
+ /**
187
+ * PATCH /models/{model}/{id}
188
+ * Partially updates a record (only fields present in `body` are changed).
189
+ */
190
+ async update(id, body, options = {}) {
191
+ return this.transport.patch(
192
+ `${this.basePath}/${encodeURIComponent(id)}`,
193
+ body,
194
+ { token: options.token, signal: options.signal }
195
+ );
196
+ }
197
+ /**
198
+ * DELETE /models/{model}/{id}
199
+ * Deletes a record (HTTP 204). Throws if the record is not found.
200
+ */
201
+ async delete(id, options = {}) {
202
+ return this.transport.delete(`${this.basePath}/${encodeURIComponent(id)}`, {
203
+ token: options.token,
204
+ signal: options.signal
205
+ });
206
+ }
207
+ };
208
+
209
+ // src/sse.ts
210
+ async function* parseSseStream(response, signal) {
211
+ if (!response.body) {
212
+ throw new Error("SSE response has no body");
213
+ }
214
+ const reader = response.body.getReader();
215
+ const decoder = new TextDecoder("utf-8");
216
+ let buffer = "";
217
+ let currentEventType = "message";
218
+ let currentDataLines = [];
219
+ const flush = function* () {
220
+ const dataStr = currentDataLines.join("\n");
221
+ const eventType = currentEventType;
222
+ currentDataLines = [];
223
+ currentEventType = "message";
224
+ if (!dataStr) return;
225
+ let parsed;
226
+ try {
227
+ parsed = JSON.parse(dataStr);
228
+ } catch {
229
+ return;
230
+ }
231
+ if (typeof parsed !== "object" || parsed === null) return;
232
+ const frame = { ...parsed, event_type: eventType };
233
+ yield frame;
234
+ };
235
+ try {
236
+ while (true) {
237
+ if (signal?.aborted) break;
238
+ const { done, value } = await reader.read();
239
+ if (done) break;
240
+ buffer += decoder.decode(value, { stream: true });
241
+ const lines = buffer.split("\n");
242
+ buffer = lines.pop() ?? "";
243
+ for (const rawLine of lines) {
244
+ const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
245
+ if (line.startsWith("event:")) {
246
+ currentEventType = line.slice(6).trim();
247
+ } else if (line.startsWith("data:")) {
248
+ currentDataLines.push(line.slice(5).trim());
249
+ } else if (line === "") {
250
+ for (const frame of flush()) {
251
+ yield frame;
252
+ if (frame.event_type === "done" || frame.event_type === "error" || frame.event_type === "suspended") {
253
+ return;
254
+ }
255
+ }
256
+ }
257
+ }
258
+ }
259
+ for (const frame of flush()) {
260
+ yield frame;
261
+ }
262
+ } finally {
263
+ reader.releaseLock();
264
+ }
265
+ }
266
+
267
+ // src/transport.ts
268
+ var Transport = class {
269
+ constructor(options) {
270
+ this.baseUrl = options.baseUrl.replace(/\/$/, "");
271
+ this.defaultToken = options.defaultToken;
272
+ }
273
+ /** Update the default token (e.g. after refresh). */
274
+ setToken(token) {
275
+ this.defaultToken = token;
276
+ }
277
+ /** Build the Authorization header value, or undefined if no token. */
278
+ authHeader(overrideToken) {
279
+ const tok = overrideToken ?? this.defaultToken;
280
+ return tok ? `Bearer ${tok}` : void 0;
281
+ }
282
+ /** Perform a plain JSON POST and return the parsed response body. */
283
+ async post(path, body, options) {
284
+ const headers = {
285
+ "Content-Type": "application/json",
286
+ Accept: "application/json"
287
+ };
288
+ const auth = this.authHeader(options?.token);
289
+ if (auth) headers["Authorization"] = auth;
290
+ const response = await fetch(`${this.baseUrl}${path}`, {
291
+ method: "POST",
292
+ headers,
293
+ body: JSON.stringify(body),
294
+ signal: options?.signal
295
+ });
296
+ if (!response.ok) {
297
+ const text = await response.text();
298
+ throw new Error(`tuvl POST ${path} \u2192 HTTP ${response.status}: ${text}`);
299
+ }
300
+ return response.json();
301
+ }
302
+ /**
303
+ * Open an SSE-capable stream and return the raw Response.
304
+ * Callers are responsible for reading `response.body`.
305
+ */
306
+ async postStream(path, body, options) {
307
+ const headers = {
308
+ "Content-Type": "application/json",
309
+ Accept: "text/event-stream",
310
+ "Cache-Control": "no-cache"
311
+ };
312
+ const auth = this.authHeader(options?.token);
313
+ if (auth) headers["Authorization"] = auth;
314
+ const response = await fetch(`${this.baseUrl}${path}`, {
315
+ method: "POST",
316
+ headers,
317
+ body: JSON.stringify(body),
318
+ signal: options?.signal
319
+ });
320
+ if (!response.ok) {
321
+ const text = await response.text();
322
+ throw new Error(`tuvl SSE ${path} \u2192 HTTP ${response.status}: ${text}`);
323
+ }
324
+ return response;
325
+ }
326
+ /** Simple GET returning parsed JSON. */
327
+ async get(path, options) {
328
+ const headers = { Accept: "application/json" };
329
+ const auth = this.authHeader(options?.token);
330
+ if (auth) headers["Authorization"] = auth;
331
+ const response = await fetch(`${this.baseUrl}${path}`, {
332
+ method: "GET",
333
+ headers,
334
+ signal: options?.signal
335
+ });
336
+ if (!response.ok) {
337
+ const text = await response.text();
338
+ throw new Error(`tuvl GET ${path} \u2192 HTTP ${response.status}: ${text}`);
339
+ }
340
+ return response.json();
341
+ }
342
+ /** Perform a JSON PATCH and return the parsed response body. */
343
+ async patch(path, body, options) {
344
+ const headers = {
345
+ "Content-Type": "application/json",
346
+ Accept: "application/json"
347
+ };
348
+ const auth = this.authHeader(options?.token);
349
+ if (auth) headers["Authorization"] = auth;
350
+ const response = await fetch(`${this.baseUrl}${path}`, {
351
+ method: "PATCH",
352
+ headers,
353
+ body: JSON.stringify(body),
354
+ signal: options?.signal
355
+ });
356
+ if (!response.ok) {
357
+ const text = await response.text();
358
+ throw new Error(`tuvl PATCH ${path} \u2192 HTTP ${response.status}: ${text}`);
359
+ }
360
+ return response.json();
361
+ }
362
+ /** Perform a DELETE request. Expects a 204 No Content response. */
363
+ async delete(path, options) {
364
+ const headers = {};
365
+ const auth = this.authHeader(options?.token);
366
+ if (auth) headers["Authorization"] = auth;
367
+ const response = await fetch(`${this.baseUrl}${path}`, {
368
+ method: "DELETE",
369
+ headers,
370
+ signal: options?.signal
371
+ });
372
+ if (!response.ok) {
373
+ const text = await response.text();
374
+ throw new Error(`tuvl DELETE ${path} \u2192 HTTP ${response.status}: ${text}`);
375
+ }
376
+ }
377
+ };
378
+
379
+ // src/types.ts
380
+ var TuvlWorkflowError = class extends Error {
381
+ constructor(message, data, error) {
382
+ super(message);
383
+ this.name = "TuvlWorkflowError";
384
+ this.data = data;
385
+ this.error = error;
386
+ }
387
+ };
388
+ var TuvlWorkflowSuspendedError = class extends Error {
389
+ constructor(suspended) {
390
+ super(`tuvl workflow suspended at step '${suspended.paused_step_id ?? "?"}'`);
391
+ this.name = "TuvlWorkflowSuspendedError";
392
+ this.suspended = suspended;
393
+ }
394
+ };
395
+
396
+ // src/client.ts
397
+ var TuvlClient = class {
398
+ constructor(options) {
399
+ this.manifestCache = /* @__PURE__ */ new Map();
400
+ this.transport = new Transport({
401
+ baseUrl: options.baseUrl,
402
+ defaultToken: options.token
403
+ });
404
+ this.manifestCacheTtl = options.manifestCacheTtl ?? 6e4;
405
+ }
406
+ /** Update the default auth token (e.g. after token refresh). */
407
+ setToken(token) {
408
+ this.transport.setToken(token);
409
+ }
410
+ /** Expose the base URL for callers that need raw access (e.g. gRPC). */
411
+ get baseUrl() {
412
+ return this.transport.baseUrl;
413
+ }
414
+ // ── Manifest ──────────────────────────────────────────────────────────────
415
+ /** Fetch (and cache) the manifest for a single workflow. */
416
+ async getManifest(workflowName, options) {
417
+ const cached = this.manifestCache.get(workflowName);
418
+ if (cached && Date.now() < cached.expiresAt) {
419
+ return cached.manifest;
420
+ }
421
+ const manifest = await this.transport.get(
422
+ `/api/_system/workflows/${encodeURIComponent(workflowName)}`,
423
+ options
424
+ );
425
+ if (this.manifestCacheTtl > 0) {
426
+ this.manifestCache.set(workflowName, {
427
+ manifest,
428
+ expiresAt: Date.now() + this.manifestCacheTtl
429
+ });
430
+ }
431
+ return manifest;
432
+ }
433
+ /** Fetch manifests for all registered workflows. */
434
+ async listWorkflows(options) {
435
+ return this.transport.get("/api/_system/workflows", options);
436
+ }
437
+ /** Invalidate the cached manifest for a workflow (or all if no name given). */
438
+ invalidateManifest(workflowName) {
439
+ if (workflowName) {
440
+ this.manifestCache.delete(workflowName);
441
+ } else {
442
+ this.manifestCache.clear();
443
+ }
444
+ }
445
+ // ── Execute ───────────────────────────────────────────────────────────────
446
+ /**
447
+ * Execute a workflow and return its `data` payload.
448
+ *
449
+ * Transport selection:
450
+ * 1. mode="grpc" → gRPC-Web (always, regardless of onProgress)
451
+ * 2. mode="sse" → SSE stream
452
+ * 3. onProgress provided → SSE if workflow has_slow_steps, else REST
453
+ * 4. default → REST
454
+ *
455
+ * @throws {TuvlWorkflowError} when the workflow returns success=false
456
+ * @throws {TuvlWorkflowSuspendedError} when the workflow suspends at HITL
457
+ * @throws {Error} on transport / engine failures
458
+ */
459
+ async execute(workflowName, options = {}) {
460
+ const { payload = {}, onProgress, onSuspended, mode, token, signal } = options;
461
+ const manifest = await this.getManifest(workflowName, { token, signal });
462
+ const useSse = mode === "sse" || mode !== "rest" && mode !== "grpc" && !!onProgress && manifest.has_slow_steps;
463
+ if (mode === "grpc") {
464
+ return this._executeGrpc(manifest, payload, onProgress, onSuspended, token, signal);
465
+ }
466
+ if (useSse) {
467
+ return this._executeSse(manifest, payload, onProgress, onSuspended, token, signal);
468
+ }
469
+ const envelope = await this.transport.post(
470
+ manifest.trigger_path,
471
+ payload,
472
+ { token, signal }
473
+ );
474
+ return this._unwrapRest(envelope, manifest.name);
475
+ }
476
+ /**
477
+ * Execute a specific version of a workflow via `/{version}/run/{name}`.
478
+ *
479
+ * Useful when you want to pin to a particular schema_version without
480
+ * relying on the currently-active default trigger path.
481
+ *
482
+ * @throws {TuvlWorkflowError} when the workflow returns success=false
483
+ * @throws {TuvlWorkflowSuspendedError} when the workflow suspends at HITL
484
+ * @throws {Error} on transport / engine failures
485
+ */
486
+ async executeVersioned(workflowName, version, options = {}) {
487
+ const { payload = {}, onProgress, onSuspended, mode, token, signal } = options;
488
+ const triggerPath = `/${version}/run/${workflowName}`;
489
+ let cachedManifest;
490
+ try {
491
+ cachedManifest = await this.getManifest(workflowName, { token, signal });
492
+ } catch {
493
+ }
494
+ const syntheticManifest = {
495
+ name: workflowName,
496
+ trigger_path: triggerPath,
497
+ trigger_method: "POST",
498
+ has_slow_steps: cachedManifest?.has_slow_steps ?? false,
499
+ slow_kinds_present: cachedManifest?.slow_kinds_present ?? [],
500
+ required_scope: cachedManifest?.required_scope ?? null,
501
+ required_group: cachedManifest?.required_group ?? null,
502
+ steps: cachedManifest?.steps ?? []
503
+ };
504
+ const useSse = mode === "sse" || mode !== "rest" && mode !== "grpc" && !!onProgress && syntheticManifest.has_slow_steps;
505
+ if (mode === "grpc") {
506
+ return this._executeGrpc(
507
+ syntheticManifest,
508
+ payload,
509
+ onProgress,
510
+ onSuspended,
511
+ token,
512
+ signal
513
+ );
514
+ }
515
+ if (useSse) {
516
+ return this._executeSse(
517
+ syntheticManifest,
518
+ payload,
519
+ onProgress,
520
+ onSuspended,
521
+ token,
522
+ signal
523
+ );
524
+ }
525
+ const envelope = await this.transport.post(
526
+ triggerPath,
527
+ payload,
528
+ { token, signal }
529
+ );
530
+ return this._unwrapRest(envelope, workflowName);
531
+ }
532
+ /**
533
+ * Resume a HITL-suspended workflow instance.
534
+ *
535
+ * After the workflow throws `TuvlWorkflowSuspendedError`, capture the
536
+ * `event.instance_id` from the suspended event and pass it here along with
537
+ * the human-provided data to continue execution.
538
+ *
539
+ * @throws {TuvlWorkflowError} when the resumed workflow returns success=false
540
+ * @throws {TuvlWorkflowSuspendedError} when the workflow suspends again at another HITL step
541
+ * @throws {Error} on transport / engine failures
542
+ */
543
+ async resumeWorkflow(options) {
544
+ const { instanceId, humanInput = {}, onProgress, onSuspended, mode, token, signal } = options;
545
+ const body = {
546
+ instance_id: instanceId,
547
+ human_input: humanInput
548
+ };
549
+ if (mode === "sse" || mode !== "rest" && !!onProgress) {
550
+ const syntheticManifest = {
551
+ name: `(resumed:${instanceId})`,
552
+ trigger_path: "/api/workflows/resume",
553
+ trigger_method: "POST",
554
+ has_slow_steps: true,
555
+ slow_kinds_present: [],
556
+ required_scope: null,
557
+ required_group: null,
558
+ steps: []
559
+ };
560
+ return this._executeSse(
561
+ syntheticManifest,
562
+ body,
563
+ onProgress,
564
+ onSuspended,
565
+ token,
566
+ signal
567
+ );
568
+ }
569
+ const envelope = await this.transport.post(
570
+ "/api/workflows/resume",
571
+ body,
572
+ { token, signal }
573
+ );
574
+ return this._unwrapRest(envelope, `(resumed:${instanceId})`);
575
+ }
576
+ // ── SSE transport ─────────────────────────────────────────────────────────
577
+ async _executeSse(manifest, payload, onProgress, onSuspended, token, signal) {
578
+ const response = await this.transport.postStream(manifest.trigger_path, payload, {
579
+ token,
580
+ signal
581
+ });
582
+ let done;
583
+ for await (const frame of parseSseStream(response, signal)) {
584
+ switch (frame.event_type) {
585
+ case "step":
586
+ onProgress?.(frame);
587
+ break;
588
+ case "done":
589
+ done = frame;
590
+ break;
591
+ case "suspended":
592
+ onSuspended?.(frame);
593
+ throw new TuvlWorkflowSuspendedError(frame);
594
+ case "error": {
595
+ const err = frame;
596
+ throw new Error(
597
+ `tuvl workflow '${manifest.name}' engine error: ${err.message}` + (err.details ? ` \u2014 ${err.details}` : "")
598
+ );
599
+ }
600
+ }
601
+ }
602
+ if (!done) {
603
+ throw new Error(`tuvl SSE stream for '${manifest.name}' ended without a done event`);
604
+ }
605
+ if (!done.success) {
606
+ throw new TuvlWorkflowError(
607
+ `tuvl workflow '${manifest.name}' failed`,
608
+ done.data,
609
+ done.error
610
+ );
611
+ }
612
+ return done.data;
613
+ }
614
+ // ── gRPC-Web transport ────────────────────────────────────────────────────
615
+ async _executeGrpc(manifest, payload, onProgress, onSuspended, token, signal) {
616
+ const { openGrpcStream: openGrpcStream2 } = await Promise.resolve().then(() => (init_grpc(), grpc_exports));
617
+ let finalSnapshot;
618
+ for await (const event of openGrpcStream2({
619
+ baseUrl: this.baseUrl,
620
+ workflowName: manifest.name,
621
+ payloadJson: JSON.stringify(payload),
622
+ token,
623
+ signal
624
+ })) {
625
+ switch (event.event_type) {
626
+ case "step":
627
+ onProgress?.(event);
628
+ break;
629
+ case "done":
630
+ finalSnapshot = event.snapshot;
631
+ break;
632
+ case "suspended": {
633
+ const snap = event.snapshot;
634
+ const suspended = {
635
+ event_type: "suspended",
636
+ paused_step_id: event.step_id,
637
+ ...snap
638
+ };
639
+ onSuspended?.(suspended);
640
+ throw new TuvlWorkflowSuspendedError(suspended);
641
+ }
642
+ case "error":
643
+ throw new Error(
644
+ `tuvl workflow '${manifest.name}' gRPC error: ${event.error_detail ?? "unknown"}`
645
+ );
646
+ }
647
+ }
648
+ if (finalSnapshot === void 0) {
649
+ throw new Error(`tuvl gRPC stream for '${manifest.name}' ended without a done event`);
650
+ }
651
+ if ("_last_error" in finalSnapshot) {
652
+ throw new TuvlWorkflowError(
653
+ `tuvl workflow '${manifest.name}' failed`,
654
+ finalSnapshot,
655
+ finalSnapshot._last_error ?? null
656
+ );
657
+ }
658
+ if ("_response" in finalSnapshot) {
659
+ return finalSnapshot._response;
660
+ }
661
+ return finalSnapshot;
662
+ }
663
+ // ── REST envelope ─────────────────────────────────────────────────────────
664
+ _unwrapRest(envelope, workflowName) {
665
+ if (!envelope || typeof envelope !== "object") {
666
+ return envelope;
667
+ }
668
+ if (envelope.success === false) {
669
+ throw new TuvlWorkflowError(
670
+ `tuvl workflow '${workflowName}' failed`,
671
+ envelope.data,
672
+ envelope.error
673
+ );
674
+ }
675
+ return envelope.data ?? envelope;
676
+ }
677
+ // ── CRUD ──────────────────────────────────────────────────────────────────
678
+ /**
679
+ * Return a typed CRUD client for a tuvl model endpoint.
680
+ *
681
+ * The returned client targets `/models/{modelName}/` and shares the
682
+ * same transport (base URL + auth token) as this TuvlClient instance.
683
+ *
684
+ * @example
685
+ * ```ts
686
+ * // List all candidates
687
+ * const all = await client.crud("candidate").list();
688
+ *
689
+ * // With filters + embedded relations
690
+ * const results = await client.crud("candidate").list({
691
+ * filters: { stage: "screening" },
692
+ * include: ["posting"],
693
+ * limit: 50,
694
+ * });
695
+ *
696
+ * // Get one record
697
+ * const c = await client.crud("candidate").get("uuid-here");
698
+ *
699
+ * // Strongly-typed variant
700
+ * const c2 = await client
701
+ * .crud<CandidateRead, CandidateCreate>("candidate")
702
+ * .create({ name: "Alice", email: "alice@example.com" });
703
+ * ```
704
+ */
705
+ crud(modelName) {
706
+ return new CrudClient(this.transport, modelName);
707
+ }
708
+ };
709
+
710
+ // src/auth.ts
711
+ var TuvlAuth = class {
712
+ constructor(options) {
713
+ this.baseUrl = options.baseUrl.replace(/\/$/, "");
714
+ }
715
+ /**
716
+ * Decode the current token server-side and return the user's identity,
717
+ * role memberships (`groups`), and permission scopes.
718
+ *
719
+ * Biscuit tokens are protobuf-encoded and cannot be decoded in pure JS,
720
+ * so this is the correct way to read "who is logged in" and "what can
721
+ * they do" from the TypeScript SDK.
722
+ *
723
+ * @throws if the token is invalid, expired, or revoked.
724
+ */
725
+ async getMe(token) {
726
+ const response = await fetch(`${this.baseUrl}/auth/me`, {
727
+ method: "GET",
728
+ headers: {
729
+ Authorization: `Bearer ${token}`,
730
+ Accept: "application/json"
731
+ }
732
+ });
733
+ if (!response.ok) {
734
+ const text = await response.text();
735
+ throw new Error(`tuvl getMe failed (HTTP ${response.status}): ${text}`);
736
+ }
737
+ return response.json();
738
+ }
739
+ /**
740
+ * Exchange an email + password for a Biscuit bearer token.
741
+ *
742
+ * Calls `POST /auth/token` with an `application/x-www-form-urlencoded`
743
+ * body (OAuth2 password-grant). The `username` field must be the user's
744
+ * email address.
745
+ */
746
+ async loginWithPassword(email, password) {
747
+ const body = new URLSearchParams({ username: email, password });
748
+ const response = await fetch(`${this.baseUrl}/auth/token`, {
749
+ method: "POST",
750
+ headers: {
751
+ "Content-Type": "application/x-www-form-urlencoded",
752
+ Accept: "application/json"
753
+ },
754
+ body
755
+ });
756
+ if (!response.ok) {
757
+ const text = await response.text();
758
+ throw new Error(`tuvl login failed (HTTP ${response.status}): ${text}`);
759
+ }
760
+ return response.json();
761
+ }
762
+ /**
763
+ * Create the first superadmin user (one-time IAM bootstrap).
764
+ *
765
+ * Calls `POST /auth/bootstrap`. Returns 409 on every subsequent call
766
+ * once any user exists.
767
+ */
768
+ async bootstrap(req) {
769
+ const response = await fetch(`${this.baseUrl}/auth/bootstrap`, {
770
+ method: "POST",
771
+ headers: {
772
+ "Content-Type": "application/json",
773
+ Accept: "application/json"
774
+ },
775
+ body: JSON.stringify(req)
776
+ });
777
+ if (!response.ok) {
778
+ const text = await response.text();
779
+ throw new Error(`tuvl bootstrap failed (HTTP ${response.status}): ${text}`);
780
+ }
781
+ return response.json();
782
+ }
783
+ /**
784
+ * Return the URL the browser should navigate to in order to start an
785
+ * OAuth2 login flow for the given provider.
786
+ *
787
+ * Supported built-ins: `"google"`, `"github"`, `"microsoft"`. Any
788
+ * provider configured in the project's `federation/` directory also
789
+ * works.
790
+ *
791
+ * After the OAuth dance the server either:
792
+ * - redirects to `TUVL_OAUTH_UI_REDIRECT_URL?token=<biscuit_b64>`, OR
793
+ * - returns a JSON `{access_token, token_type}` body (CLI / server flows).
794
+ */
795
+ getOAuthLoginUrl(provider) {
796
+ return `${this.baseUrl}/auth/oauth/${encodeURIComponent(provider)}/start`;
797
+ }
798
+ /**
799
+ * Exchange a valid (non-expired, non-revoked) token for a fresh one.
800
+ * The old token is immediately blacklisted — discard it after this call.
801
+ */
802
+ async refresh(token) {
803
+ const response = await fetch(`${this.baseUrl}/auth/refresh`, {
804
+ method: "POST",
805
+ headers: {
806
+ Authorization: `Bearer ${token}`,
807
+ Accept: "application/json"
808
+ }
809
+ });
810
+ if (!response.ok) {
811
+ const text = await response.text();
812
+ throw new Error(`tuvl token refresh failed (HTTP ${response.status}): ${text}`);
813
+ }
814
+ return response.json();
815
+ }
816
+ /**
817
+ * Revoke the given token (logout). After this the token is blacklisted
818
+ * across all workers that share a Redis instance. Resolves silently on
819
+ * success (HTTP 204).
820
+ */
821
+ async logout(token) {
822
+ const response = await fetch(`${this.baseUrl}/auth/logout`, {
823
+ method: "POST",
824
+ headers: {
825
+ Authorization: `Bearer ${token}`
826
+ }
827
+ });
828
+ if (!response.ok && response.status !== 204) {
829
+ const text = await response.text();
830
+ throw new Error(`tuvl logout failed (HTTP ${response.status}): ${text}`);
831
+ }
832
+ }
833
+ };
834
+
835
+ // src/index.ts
836
+ init_grpc();
837
+
838
+ export { CrudClient, Transport, TuvlAuth, TuvlClient, TuvlWorkflowError, TuvlWorkflowSuspendedError, openGrpcStream, parseSseStream };
839
+ //# sourceMappingURL=index.mjs.map
840
+ //# sourceMappingURL=index.mjs.map