@tailor-platform/sdk 1.74.0 → 1.74.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.
Files changed (55) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/{application-DwmoI6ZQ.mjs → application-BsH6tkZC.mjs} +43 -5
  3. package/dist/application-BsH6tkZC.mjs.map +1 -0
  4. package/dist/application-CSUhZMb5.mjs +3 -0
  5. package/dist/cli/commands/tailordb/migrate/snapshot.d.mts +1 -16
  6. package/dist/cli/index.mjs +22 -33
  7. package/dist/cli/index.mjs.map +1 -1
  8. package/dist/cli/lib.d.mts +2 -2
  9. package/dist/cli/lib.mjs +3 -3
  10. package/dist/cli/lib.mjs.map +1 -1
  11. package/dist/completion/zsh-worker.zsh +1 -1
  12. package/dist/configure/index.mjs +2 -2
  13. package/dist/configure/services/tailordb/schema.d.mts +5 -19
  14. package/dist/configure/types/field-runtime.d.mts +17 -0
  15. package/dist/configure/types/type.d.mts +1 -18
  16. package/dist/field-runtime-9bfXBAOK.mjs +183 -0
  17. package/dist/field-runtime-9bfXBAOK.mjs.map +1 -0
  18. package/dist/plugin/builtin/seed/index.mjs +1 -1
  19. package/dist/{runtime-Zkg3SUwi.mjs → runtime-DV1EnfMs.mjs} +229 -394
  20. package/dist/runtime-DV1EnfMs.mjs.map +1 -0
  21. package/dist/{schema-DAdZSFOd.mjs → schema-Dl_y0m9e.mjs} +8 -167
  22. package/dist/schema-Dl_y0m9e.mjs.map +1 -0
  23. package/dist/secretmanager-Bd45j7an.mjs +98 -0
  24. package/dist/secretmanager-Bd45j7an.mjs.map +1 -0
  25. package/dist/{seed-DoMTMLcm.mjs → seed-fm0LeYP2.mjs} +14 -3
  26. package/dist/seed-fm0LeYP2.mjs.map +1 -0
  27. package/dist/types-BwzB2okW.mjs +199 -0
  28. package/dist/types-BwzB2okW.mjs.map +1 -0
  29. package/dist/types-KlawuVKa.mjs +4 -0
  30. package/dist/vitest/index.d.mts +8 -1
  31. package/dist/vitest/index.mjs +776 -1
  32. package/dist/vitest/index.mjs.map +1 -1
  33. package/dist/vitest/mock.d.mts +8 -363
  34. package/dist/vitest/mocks/aigateway.d.mts +30 -0
  35. package/dist/vitest/mocks/authconnection.d.mts +28 -0
  36. package/dist/vitest/mocks/file.d.mts +41 -0
  37. package/dist/vitest/mocks/iconv.d.mts +27 -0
  38. package/dist/vitest/mocks/idp.d.mts +44 -0
  39. package/dist/vitest/mocks/secretmanager.d.mts +33 -0
  40. package/dist/vitest/mocks/tailordb.d.mts +71 -0
  41. package/dist/vitest/mocks/workflow.d.mts +115 -0
  42. package/dist/vitest/setup.mjs +1 -1
  43. package/package.json +8 -8
  44. package/dist/application-BndtMTFY.mjs +0 -3
  45. package/dist/application-DwmoI6ZQ.mjs.map +0 -1
  46. package/dist/field-DOsJCPFa.mjs +0 -22
  47. package/dist/field-DOsJCPFa.mjs.map +0 -1
  48. package/dist/mock-Ce1GCi4-.mjs +0 -871
  49. package/dist/mock-Ce1GCi4-.mjs.map +0 -1
  50. package/dist/runtime-Zkg3SUwi.mjs.map +0 -1
  51. package/dist/schema-DAdZSFOd.mjs.map +0 -1
  52. package/dist/seed-DoMTMLcm.mjs.map +0 -1
  53. package/dist/types-qhFZ8y9B.mjs +0 -4
  54. package/dist/types-ywCGpzDZ.mjs +0 -360
  55. package/dist/types-ywCGpzDZ.mjs.map +0 -1
@@ -1,871 +0,0 @@
1
- import { a as getRegisteredWorkflow, d as buildJobContext, f as clearWorkflowTestEnv, i as getRegisteredJob, m as platformSerialize, p as writeWorkflowTestEnv, t as TRIGGER_DEFAULT } from "./registry-BozuxbPp.mjs";
2
- import { t as assertDefined } from "./assert-DBxo8jPo.mjs";
3
- import { vi } from "vitest";
4
-
5
- //#region src/vitest/mock.ts
6
- /**
7
- * Mock controls for Tailor Platform APIs (vitest).
8
- *
9
- * Each `xMock()` factory installs `vi.fn()`-backed mocks for one platform
10
- * namespace onto `globalThis` when acquired, and restores the previous value
11
- * when the `using` scope exits. State lives in the per-acquisition vi.fns /
12
- * closures — there is no shared global state bag — so nested/sequential scopes
13
- * are isolated and namespaces never interfere with each other.
14
- *
15
- * Acquire a mock with a `using` declaration:
16
- *
17
- * ```ts
18
- * test("...", () => {
19
- * using wf = mockWorkflow();
20
- * wf.setJobHandler(() => ({ ok: true }));
21
- * }); // previous workflow mock restored here
22
- * ```
23
- *
24
- * The friendly helpers (`setJobHandler`, `enqueueResult`, `triggeredJobs`, …)
25
- * are thin wrappers over the underlying vi.fns, which are also exposed directly
26
- * (`wf.triggerJobFunction`) for native matchers like
27
- * `expect(wf.triggerJobFunction).toHaveBeenCalledWith(...)`.
28
- */
29
- function withDispose(facade, dispose) {
30
- Object.defineProperty(facade, Symbol.dispose, {
31
- value: dispose,
32
- enumerable: false,
33
- writable: true,
34
- configurable: true
35
- });
36
- return facade;
37
- }
38
- function tailorRoot() {
39
- const g = globalThis;
40
- if (!g.tailor) g.tailor = { context: { getInvoker: () => null } };
41
- return g.tailor;
42
- }
43
- function tailordbRoot() {
44
- const g = globalThis;
45
- if (!g.tailordb) g.tailordb = {};
46
- return g.tailordb;
47
- }
48
- var MockQueryResult = class {
49
- command;
50
- rowCount;
51
- rows;
52
- constructor(rows) {
53
- this.command = "";
54
- this.rowCount = rows.length;
55
- this.rows = rows;
56
- }
57
- };
58
- /**
59
- * Acquire a disposable mock for TailorDB operations. Installs a mock
60
- * `tailordb.Client` whose `queryObject` is a shared `vi.fn()` (so query
61
- * responses can be staged before the client is constructed). Restored on
62
- * dispose.
63
- * @returns Disposable TailorDB mock control object
64
- * @example
65
- * ```typescript
66
- * import { mockTailordb } from "@tailor-platform/sdk/vitest";
67
- *
68
- * test("order-based", async () => {
69
- * using db = mockTailordb();
70
- * db.enqueueResults([], [{ age: 30 }], []); // BEGIN / SELECT / COMMIT
71
- * // …
72
- * expect(db.queryObject).toHaveBeenCalledTimes(3);
73
- * expect(db.Client).toHaveBeenCalledWith({ namespace: "tailordb" });
74
- * });
75
- * ```
76
- */
77
- function mockTailordb() {
78
- const root = tailordbRoot();
79
- const prevClient = root.Client;
80
- const queryObject = vi.fn(async (_query, _params = []) => new MockQueryResult([]));
81
- const connect = vi.fn(async () => {});
82
- const createdClients = [];
83
- const Client = vi.fn(function(config) {
84
- const record = {
85
- namespace: config?.namespace,
86
- ended: false
87
- };
88
- createdClients.push(record);
89
- this.connect = connect;
90
- this.end = vi.fn(async () => {
91
- record.ended = true;
92
- });
93
- this.queryObject = queryObject;
94
- this.createTransaction = (name) => {
95
- if (!name) throw new Error("Transaction name must be a non-empty string");
96
- return {
97
- begin: async () => {},
98
- commit: async () => {},
99
- rollback: async () => {},
100
- queryObject
101
- };
102
- };
103
- });
104
- root.Client = Client;
105
- return withDispose({
106
- /** The mock `tailordb.Client` constructor (`vi.fn`). */
107
- Client,
108
- /** The shared `queryObject` `vi.fn` used by every client and transaction. */
109
- queryObject,
110
- /**
111
- * Set a fallback query resolver. Called when the enqueue queue is empty.
112
- * @param resolver - Function that returns rows for a given query and params
113
- */
114
- setQueryResolver(resolver) {
115
- queryObject.mockImplementation(async (query, params = []) => new MockQueryResult(resolver(query, params) ?? []));
116
- },
117
- /**
118
- * Enqueue rows for the next `queryObject` call (FIFO; takes priority over
119
- * `setQueryResolver`). Call with no arguments for an empty result.
120
- * @param rows - Row objects to return from the next `queryObject` call
121
- */
122
- enqueueResult(...rows) {
123
- queryObject.mockImplementationOnce(async () => new MockQueryResult(rows));
124
- },
125
- /**
126
- * Enqueue rows for multiple subsequent `queryObject` calls (FIFO).
127
- * @param rowsList - Rows arrays, one per upcoming query
128
- */
129
- enqueueResults(...rowsList) {
130
- for (const rows of rowsList) queryObject.mockImplementationOnce(async () => new MockQueryResult(rows));
131
- },
132
- /**
133
- * All queries executed via `queryObject`, in order, derived from the vi.fn
134
- * call records.
135
- * @returns Executed queries array
136
- */
137
- get executedQueries() {
138
- return queryObject.mock.calls.map(([query, params]) => ({
139
- query,
140
- params: params ?? []
141
- }));
142
- },
143
- /**
144
- * All TailorDB clients created, with their namespace and end state.
145
- * @returns Created clients array
146
- */
147
- get createdClients() {
148
- return createdClients;
149
- },
150
- /** Reset query responses and recorded calls (keeps the mock installed). */
151
- reset() {
152
- queryObject.mockReset();
153
- queryObject.mockImplementation(async () => new MockQueryResult([]));
154
- connect.mockClear();
155
- Client.mockClear();
156
- createdClients.length = 0;
157
- }
158
- }, () => {
159
- root.Client = prevClient;
160
- });
161
- }
162
- /**
163
- * Acquire a disposable mock for workflow operations (`tailor.workflow`).
164
- * Restored on dispose.
165
- * @returns Disposable workflow mock control object
166
- * @example
167
- * ```typescript
168
- * import { mockWorkflow } from "@tailor-platform/sdk/vitest";
169
- *
170
- * test("job handler", async () => {
171
- * using wf = mockWorkflow();
172
- * wf.setJobHandler((name) => (name === "validate" ? { valid: true } : null));
173
- * await runWorkflowUnderTest(); // calls tailor.workflow.triggerJobFunction("validate", {})
174
- * expect(wf.triggerJobFunction).toHaveBeenCalledWith("validate", {});
175
- * });
176
- * ```
177
- */
178
- function mockWorkflow() {
179
- const root = tailorRoot();
180
- const prev = root.workflow;
181
- const defaultTriggerJob = (jobName, args) => {
182
- const body = getRegisteredJob(jobName);
183
- return body ? body(args, buildJobContext()) : null;
184
- };
185
- const defaultTriggerWorkflow = async (workflowName, args, _options) => {
186
- const wf = getRegisteredWorkflow(workflowName);
187
- if (wf) await installedTriggerJobFunction(wf.mainJobName, args);
188
- return TRIGGER_DEFAULT;
189
- };
190
- const defaultResumeWorkflow = async (executionId) => executionId;
191
- const triggerJobFunction = vi.fn(defaultTriggerJob);
192
- const triggerWorkflow = vi.fn(defaultTriggerWorkflow);
193
- const resumeWorkflow = vi.fn(defaultResumeWorkflow);
194
- const wait = vi.fn((_key, _payload) => null);
195
- const resolve = vi.fn(async (_executionId, _key, _callback) => {});
196
- const installedTriggerJobFunction = (jobName, args) => {
197
- const out = triggerJobFunction(jobName, platformSerialize(args));
198
- return out instanceof Promise ? out.then((v) => platformSerialize(v)) : platformSerialize(out);
199
- };
200
- root.workflow = {
201
- triggerJobFunction: installedTriggerJobFunction,
202
- triggerWorkflow: (...call) => call.length >= 3 ? triggerWorkflow(call[0], platformSerialize(call[1]), call[2]) : triggerWorkflow(call[0], platformSerialize(call[1])),
203
- resumeWorkflow: (executionId) => resumeWorkflow(executionId),
204
- wait: (key, payload) => wait(key, platformSerialize(payload)),
205
- resolve: (executionId, key, callback) => resolve(executionId, key, (payload) => {
206
- const out = callback(payload);
207
- return out instanceof Promise ? out.then((v) => platformSerialize(v)) : platformSerialize(out);
208
- })
209
- };
210
- return withDispose({
211
- /** The `triggerJobFunction` `vi.fn`. */
212
- triggerJobFunction,
213
- /** The `triggerWorkflow` `vi.fn`. */
214
- triggerWorkflow,
215
- /** The `resumeWorkflow` `vi.fn`. */
216
- resumeWorkflow,
217
- /** The `wait` `vi.fn`. */
218
- wait,
219
- /** The `resolve` `vi.fn`. */
220
- resolve,
221
- /**
222
- * Set a fallback job handler. Called when the enqueue queue is empty.
223
- * @param handler - Function returning a result for a job name and args
224
- */
225
- setJobHandler(handler) {
226
- triggerJobFunction.mockImplementation((name, args) => handler(name, args));
227
- },
228
- /**
229
- * Enqueue a single result for the next `triggerJobFunction` call (FIFO;
230
- * takes priority over `setJobHandler`).
231
- * @param result - Result to return from the next call
232
- */
233
- enqueueResult(result) {
234
- triggerJobFunction.mockImplementationOnce(() => result);
235
- },
236
- /**
237
- * Enqueue results for multiple subsequent `triggerJobFunction` calls (FIFO).
238
- * @param results - Results to enqueue, one per upcoming call
239
- */
240
- enqueueResults(...results) {
241
- for (const result of results) triggerJobFunction.mockImplementationOnce(() => result);
242
- },
243
- /**
244
- * All jobs triggered via `triggerJobFunction`, in order.
245
- * @returns Triggered jobs array
246
- */
247
- get triggeredJobs() {
248
- return triggerJobFunction.mock.calls.map(([jobName, args]) => ({
249
- jobName,
250
- args
251
- }));
252
- },
253
- /**
254
- * Configure what `triggerWorkflow` returns. Pass a string (same id every
255
- * call) or `(name, args, options) => string`. Default: a placeholder UUID.
256
- * @param handler - Static execution ID or a function returning one
257
- */
258
- setTriggerHandler(handler) {
259
- triggerWorkflow.mockImplementation(typeof handler === "function" ? async (name, args, options) => handler(name, args, options) : async () => handler);
260
- },
261
- /**
262
- * Configure what `resumeWorkflow` returns. Pass a string (same id every
263
- * call) or `(executionId) => string`. Default: echoes the input executionId.
264
- * @param handler - Static execution ID or a function returning one
265
- */
266
- setResumeHandler(handler) {
267
- resumeWorkflow.mockImplementation(typeof handler === "function" ? async (executionId) => handler(executionId) : async () => handler);
268
- },
269
- /**
270
- * Configure what `wait` returns. Pass `(key, payload) => unknown` or any
271
- * other value to return it for every call. Default: `null`.
272
- * @param handler - Static value or a function returning one
273
- */
274
- setWaitHandler: ((handler) => {
275
- wait.mockImplementation(typeof handler === "function" ? (key, payload) => handler(key, payload) : () => handler);
276
- }),
277
- /**
278
- * Set the `env` passed to job bodies invoked via `createWorkflowJob().trigger()`.
279
- * Cleared on dispose / reset.
280
- * @param env - Env passed to job bodies.
281
- */
282
- setEnv(env) {
283
- writeWorkflowTestEnv({ ...env });
284
- },
285
- /**
286
- * Configure how `resolve` runs the user-supplied callback. Default: callback
287
- * is not invoked (records the call only).
288
- * @param handler - Function invoked per `resolve` call
289
- */
290
- setResolveHandler(handler) {
291
- resolve.mockImplementation(async (executionId, key, callback) => {
292
- await handler(executionId, key, callback);
293
- });
294
- },
295
- /**
296
- * `wait` calls reshaped as `{ key, payload }` for assertions.
297
- * @returns Wait call records
298
- */
299
- get waitCalls() {
300
- return wait.mock.calls.map(([key, payload]) => ({
301
- key,
302
- payload
303
- }));
304
- },
305
- /**
306
- * `resolve` calls reshaped as `{ executionId, key }` for assertions.
307
- * @returns Resolve call records
308
- */
309
- get resolveCalls() {
310
- return resolve.mock.calls.map(([executionId, key]) => ({
311
- executionId,
312
- key
313
- }));
314
- },
315
- /** Reset all workflow responses and recorded calls (keeps the mock installed). */
316
- reset() {
317
- triggerJobFunction.mockReset();
318
- triggerJobFunction.mockImplementation(defaultTriggerJob);
319
- triggerWorkflow.mockReset();
320
- triggerWorkflow.mockImplementation(defaultTriggerWorkflow);
321
- resumeWorkflow.mockReset();
322
- resumeWorkflow.mockImplementation(defaultResumeWorkflow);
323
- wait.mockReset();
324
- wait.mockImplementation(() => null);
325
- resolve.mockReset();
326
- resolve.mockImplementation(async () => {});
327
- clearWorkflowTestEnv();
328
- }
329
- }, () => {
330
- root.workflow = prev;
331
- clearWorkflowTestEnv();
332
- });
333
- }
334
- const SECRET_STORE = Symbol("tailorSecretStore");
335
- /**
336
- * Acquire a disposable mock for `tailor.secretmanager`. The secret store is
337
- * inherited (cloned) from the currently-installed mock on acquisition and
338
- * restored on dispose, so secrets seeded outside the test survive across
339
- * `using` scopes while per-test `setSecrets()` overrides stay isolated.
340
- * @returns Disposable SecretManager mock control object
341
- * @example
342
- * ```typescript
343
- * import { mockSecretmanager } from "@tailor-platform/sdk/vitest";
344
- *
345
- * test("reads secrets from vault", async () => {
346
- * using sm = mockSecretmanager();
347
- * sm.setSecrets({ "my-vault": { API_KEY: "sk-123" } });
348
- * // …
349
- * });
350
- * ```
351
- */
352
- function mockSecretmanager() {
353
- const root = tailorRoot();
354
- const prev = root.secretmanager;
355
- const holder = { store: structuredClone(prev?.[SECRET_STORE]?.store ?? {}) };
356
- const getSecret = vi.fn(async (vault, name) => holder.store[vault]?.[name]);
357
- const getSecrets = vi.fn(async (vault, names) => {
358
- const vaultData = holder.store[vault] ?? {};
359
- const result = {};
360
- for (const name of names) if (name in vaultData) result[name] = assertDefined(vaultData[name], `vault entry missing for: ${name}`);
361
- return result;
362
- });
363
- root.secretmanager = {
364
- getSecret,
365
- getSecrets,
366
- [SECRET_STORE]: holder
367
- };
368
- return withDispose({
369
- /** The `getSecret` `vi.fn`. */
370
- getSecret,
371
- /** The `getSecrets` `vi.fn`. */
372
- getSecrets,
373
- setSecrets(secrets) {
374
- holder.store = secrets;
375
- },
376
- get calls() {
377
- return [...getSecret.mock.calls.map((args, i) => ({
378
- order: getSecret.mock.invocationCallOrder[i] ?? 0,
379
- call: {
380
- method: "getSecret",
381
- vault: args[0],
382
- name: args[1]
383
- }
384
- })), ...getSecrets.mock.calls.map((args, i) => ({
385
- order: getSecrets.mock.invocationCallOrder[i] ?? 0,
386
- call: {
387
- method: "getSecrets",
388
- vault: args[0],
389
- names: args[1]
390
- }
391
- }))].toSorted((a, b) => a.order - b.order).map((e) => e.call);
392
- },
393
- reset() {
394
- holder.store = {};
395
- getSecret.mockClear();
396
- getSecrets.mockClear();
397
- }
398
- }, () => {
399
- root.secretmanager = prev;
400
- });
401
- }
402
- /**
403
- * Acquire a disposable mock for `tailor.authconnection`. Restored on dispose.
404
- * @returns Disposable AuthConnection mock control object
405
- * @example
406
- * ```typescript
407
- * import { mockAuthconnection } from "@tailor-platform/sdk/vitest";
408
- *
409
- * test("returns configured token", async () => {
410
- * using ac = mockAuthconnection();
411
- * ac.setTokens({ google: { access_token: "ya29.xxx" } });
412
- * // …
413
- * });
414
- * ```
415
- */
416
- function mockAuthconnection() {
417
- const root = tailorRoot();
418
- const prev = root.authconnection;
419
- let tokens = {};
420
- const getConnectionToken = vi.fn(async (connectionName) => tokens[connectionName] ?? { access_token: "mock-token" });
421
- root.authconnection = { getConnectionToken };
422
- return withDispose({
423
- /** The `getConnectionToken` `vi.fn`. */
424
- getConnectionToken,
425
- setTokens(value) {
426
- tokens = value;
427
- },
428
- get calls() {
429
- return getConnectionToken.mock.calls.map(([connectionName]) => ({ connectionName }));
430
- },
431
- reset() {
432
- tokens = {};
433
- getConnectionToken.mockClear();
434
- }
435
- }, () => {
436
- root.authconnection = prev;
437
- });
438
- }
439
- const IDP_DEFAULTS = {
440
- users: {
441
- users: [],
442
- nextPageToken: null,
443
- totalCount: 0
444
- },
445
- user: {
446
- id: "mock-id",
447
- name: "mock-user",
448
- disabled: false,
449
- mfaEnrolled: false,
450
- mfaFactorIds: []
451
- },
452
- userByName: {
453
- id: "mock-id",
454
- name: "mock-user",
455
- disabled: false,
456
- mfaEnrolled: false,
457
- mfaFactorIds: []
458
- },
459
- createUser: {
460
- id: "mock-id",
461
- name: "mock-user",
462
- disabled: false,
463
- mfaEnrolled: false,
464
- mfaFactorIds: []
465
- },
466
- updateUser: {
467
- id: "mock-id",
468
- name: "mock-user",
469
- disabled: false,
470
- mfaEnrolled: false,
471
- mfaFactorIds: []
472
- },
473
- deleteUser: true,
474
- sendPasswordResetEmail: true,
475
- unenrollMfa: true
476
- };
477
- /**
478
- * Acquire a disposable mock for `tailor.idp`. Restored on dispose.
479
- * @returns Disposable IDP mock control object
480
- * @example
481
- * ```typescript
482
- * import { mockIdp } from "@tailor-platform/sdk/vitest";
483
- *
484
- * test("resolver-based", async () => {
485
- * using idp = mockIdp();
486
- * idp.setResolver((method) =>
487
- * method === "user" ? { id: "u-1", name: "alice", disabled: false } : null,
488
- * );
489
- * // …
490
- * });
491
- * ```
492
- */
493
- function mockIdp() {
494
- const root = tailorRoot();
495
- const prev = root.idp;
496
- const queue = [];
497
- let resolver = () => null;
498
- const calls = [];
499
- function handle(method, args, namespace) {
500
- calls.push({
501
- method,
502
- args,
503
- namespace
504
- });
505
- if (queue.length > 0) return queue.shift();
506
- const resolved = resolver(method, args, namespace);
507
- if (resolved != null) return resolved;
508
- const fallback = IDP_DEFAULTS[method];
509
- return fallback === void 0 ? void 0 : structuredClone(fallback);
510
- }
511
- const Client = vi.fn(function(config) {
512
- const namespace = config.namespace;
513
- this.users = async (options) => handle("users", [options], namespace);
514
- this.user = async (userId) => handle("user", [userId], namespace);
515
- this.userByName = async (name) => handle("userByName", [name], namespace);
516
- this.createUser = async (input) => handle("createUser", [input], namespace);
517
- this.updateUser = async (input) => handle("updateUser", [input], namespace);
518
- this.deleteUser = async (userId) => handle("deleteUser", [userId], namespace);
519
- this.sendPasswordResetEmail = async (input) => handle("sendPasswordResetEmail", [input], namespace);
520
- this.unenrollMfa = async (input) => handle("unenrollMfa", [input], namespace);
521
- });
522
- root.idp = { Client };
523
- return withDispose({
524
- /** The mock IDP `Client` constructor (`vi.fn`). */
525
- Client,
526
- setResolver(value) {
527
- resolver = value;
528
- },
529
- /**
530
- * Enqueue a single result for the next IDP call (FIFO; falls back to
531
- * `setResolver` when exhausted).
532
- * @param result - Result to return from the next IDP call
533
- */
534
- enqueueResult(result) {
535
- queue.push(result);
536
- },
537
- /**
538
- * Enqueue results for multiple subsequent IDP calls.
539
- * @param results - Results to enqueue, one per upcoming call
540
- */
541
- enqueueResults(...results) {
542
- queue.push(...results);
543
- },
544
- get calls() {
545
- return calls;
546
- },
547
- reset() {
548
- queue.length = 0;
549
- resolver = () => null;
550
- calls.length = 0;
551
- }
552
- }, () => {
553
- root.idp = prev;
554
- });
555
- }
556
- function isUtf8(encoding) {
557
- return encoding === "UTF8" || encoding === "UTF-8";
558
- }
559
- function defaultIconvResult(method, args) {
560
- switch (method) {
561
- case "convert":
562
- case "convertBuffer": return isUtf8(args[2]) ? "" : /* @__PURE__ */ new Uint8Array();
563
- case "decode": return "";
564
- case "encode": return isUtf8(args[1]) ? "" : /* @__PURE__ */ new Uint8Array();
565
- case "encodings": return [];
566
- default: return;
567
- }
568
- }
569
- /**
570
- * Acquire a disposable mock for `tailor.iconv`. Restored on dispose.
571
- * @returns Disposable Iconv mock control object
572
- * @example
573
- * ```typescript
574
- * import { mockIconv } from "@tailor-platform/sdk/vitest";
575
- *
576
- * test("mock encoding conversion", () => {
577
- * using iconv = mockIconv();
578
- * iconv.setResolver((method) => (method === "decode" ? "decoded-text" : null));
579
- * // …
580
- * });
581
- * ```
582
- */
583
- function mockIconv() {
584
- const root = tailorRoot();
585
- const prev = root.iconv;
586
- let resolver = null;
587
- const calls = [];
588
- function handle(method, args) {
589
- calls.push({
590
- method,
591
- args: [...args]
592
- });
593
- if (resolver) {
594
- const result = resolver(method, args);
595
- if (result != null) return result;
596
- }
597
- return defaultIconvResult(method, args);
598
- }
599
- class MockIconv {
600
- #fromEncoding;
601
- #toEncoding;
602
- constructor(fromEncoding, toEncoding) {
603
- this.#fromEncoding = fromEncoding;
604
- this.#toEncoding = toEncoding;
605
- }
606
- convert(input) {
607
- return handle("convert", [
608
- input,
609
- this.#fromEncoding,
610
- this.#toEncoding
611
- ]);
612
- }
613
- }
614
- root.iconv = {
615
- convert: (str, from, to) => handle("convert", [
616
- str,
617
- from,
618
- to
619
- ]),
620
- convertBuffer: (buf, from, to) => handle("convertBuffer", [
621
- buf,
622
- from,
623
- to
624
- ]),
625
- decode: (buf, encoding) => handle("decode", [buf, encoding]),
626
- encode: (str, encoding) => handle("encode", [str, encoding]),
627
- encodings: () => handle("encodings", []),
628
- Iconv: MockIconv
629
- };
630
- return withDispose({
631
- setResolver(value) {
632
- resolver = value;
633
- },
634
- get calls() {
635
- return calls;
636
- },
637
- reset() {
638
- resolver = null;
639
- calls.length = 0;
640
- }
641
- }, () => {
642
- root.iconv = prev;
643
- });
644
- }
645
- const FILE_DEFAULTS = {
646
- upload: { metadata: {
647
- fileSize: 0,
648
- sha256sum: ""
649
- } },
650
- download: {
651
- data: /* @__PURE__ */ new Uint8Array(),
652
- metadata: {
653
- contentType: "",
654
- fileSize: 0,
655
- sha256sum: "",
656
- lastUploadedAt: ""
657
- }
658
- },
659
- downloadAsBase64: {
660
- data: "",
661
- metadata: {
662
- contentType: "",
663
- fileSize: 0,
664
- sha256sum: "",
665
- lastUploadedAt: ""
666
- }
667
- },
668
- delete: void 0,
669
- getMetadata: {
670
- contentType: "",
671
- fileSize: 0,
672
- sha256sum: "",
673
- urlPath: ""
674
- },
675
- downloadStream: null,
676
- uploadStream: { metadata: {
677
- fileSize: 0,
678
- sha256sum: ""
679
- } }
680
- };
681
- function toFileStream(value) {
682
- if (value !== null && typeof value === "object" && Symbol.asyncIterator in value && typeof value.close === "function") return value;
683
- if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) throw new TypeError("openDownloadStream expects an iterable of StreamValue items (e.g. [{ type: \"chunk\", data, position }, { type: \"complete\" }]); got raw bytes. Wrap the bytes in a structured chunk first.");
684
- if (value !== null && typeof value === "object" && (Symbol.iterator in value || Symbol.asyncIterator in value)) {
685
- const source = value;
686
- const inner = Symbol.asyncIterator in source ? source[Symbol.asyncIterator]() : source[Symbol.iterator]();
687
- const stream = {
688
- async next() {
689
- const r = await inner.next();
690
- if (!r.done) assertStreamValue(r.value);
691
- return r.done ? {
692
- done: true,
693
- value: void 0
694
- } : r;
695
- },
696
- async close() {},
697
- [Symbol.asyncIterator]() {
698
- return stream;
699
- }
700
- };
701
- return stream;
702
- }
703
- const empty = {
704
- async next() {
705
- return {
706
- done: true,
707
- value: void 0
708
- };
709
- },
710
- async close() {},
711
- [Symbol.asyncIterator]() {
712
- return empty;
713
- }
714
- };
715
- return empty;
716
- }
717
- function assertStreamValue(v) {
718
- if (v === null || typeof v !== "object") throw new TypeError(`openDownloadStream expected a StreamValue item ({ type: "metadata" | "chunk" | "complete", ... }); got ${typeof v === "object" ? "null" : typeof v}.`);
719
- if (v instanceof ArrayBuffer || ArrayBuffer.isView(v)) throw new TypeError("openDownloadStream expected a StreamValue item, got raw bytes. Wrap the bytes in a structured chunk first (e.g. { type: \"chunk\", data, position }).");
720
- const type = v.type;
721
- if (type !== "metadata" && type !== "chunk" && type !== "complete") throw new TypeError(`openDownloadStream expected a StreamValue item with type "metadata" | "chunk" | "complete"; got ${JSON.stringify(type)}.`);
722
- }
723
- /**
724
- * Acquire a disposable mock for `tailordb.file`. Restored on dispose.
725
- * @returns Disposable File mock control object
726
- * @example
727
- * ```typescript
728
- * import { mockFile } from "@tailor-platform/sdk/vitest";
729
- *
730
- * test("mock file download", async () => {
731
- * using file = mockFile();
732
- * file.enqueueResult({ data: new Uint8Array([1, 2, 3]), metadata: { ... } });
733
- * // …
734
- * });
735
- * ```
736
- */
737
- function mockFile() {
738
- const root = tailordbRoot();
739
- const prev = root.file;
740
- const queue = [];
741
- let resolver = () => null;
742
- const calls = [];
743
- function handle(method, namespace, typeName, fieldName, recordId) {
744
- const call = {
745
- method,
746
- namespace,
747
- typeName,
748
- fieldName,
749
- recordId
750
- };
751
- calls.push(call);
752
- if (queue.length > 0) return queue.shift();
753
- const resolved = resolver(method, call);
754
- if (resolved != null) return resolved;
755
- const fallback = FILE_DEFAULTS[method];
756
- return fallback === void 0 ? void 0 : structuredClone(fallback);
757
- }
758
- root.file = {
759
- async upload(namespace, typeName, fieldName, recordId) {
760
- return handle("upload", namespace, typeName, fieldName, recordId);
761
- },
762
- async download(namespace, typeName, fieldName, recordId) {
763
- return handle("download", namespace, typeName, fieldName, recordId);
764
- },
765
- async downloadAsBase64(namespace, typeName, fieldName, recordId) {
766
- return handle("downloadAsBase64", namespace, typeName, fieldName, recordId);
767
- },
768
- async delete(namespace, typeName, fieldName, recordId) {
769
- handle("delete", namespace, typeName, fieldName, recordId);
770
- },
771
- async getMetadata(namespace, typeName, fieldName, recordId) {
772
- return handle("getMetadata", namespace, typeName, fieldName, recordId);
773
- },
774
- async openDownloadStream(namespace, typeName, fieldName, recordId) {
775
- return toFileStream(handle("openDownloadStream", namespace, typeName, fieldName, recordId));
776
- },
777
- async downloadStream(namespace, typeName, fieldName, recordId) {
778
- const resolved = handle("downloadStream", namespace, typeName, fieldName, recordId);
779
- if (resolved != null) return resolved;
780
- return {
781
- body: new ReadableStream({ start(c) {
782
- c.close();
783
- } }),
784
- metadata: {
785
- contentType: "",
786
- fileSize: 0,
787
- sha256sum: "",
788
- lastUploadedAt: ""
789
- }
790
- };
791
- },
792
- async uploadStream(namespace, typeName, fieldName, recordId) {
793
- return handle("uploadStream", namespace, typeName, fieldName, recordId);
794
- }
795
- };
796
- return withDispose({
797
- setResolver(value) {
798
- resolver = value;
799
- },
800
- /**
801
- * Enqueue a single result for the next `tailordb.file` call (FIFO; falls
802
- * back to `setResolver` when exhausted).
803
- * @param result - Result to return from the next file call
804
- */
805
- enqueueResult(result) {
806
- queue.push(result);
807
- },
808
- /**
809
- * Enqueue results for multiple subsequent `tailordb.file` calls.
810
- * @param results - Results to enqueue, one per upcoming call
811
- */
812
- enqueueResults(...results) {
813
- queue.push(...results);
814
- },
815
- get calls() {
816
- return calls;
817
- },
818
- reset() {
819
- queue.length = 0;
820
- resolver = () => null;
821
- calls.length = 0;
822
- }
823
- }, () => {
824
- root.file = prev;
825
- });
826
- }
827
- /**
828
- * Acquire a disposable mock for `tailor.aigateway`. Restored on dispose.
829
- * @returns Disposable AI Gateway mock control object
830
- * @example
831
- * ```typescript
832
- * import { mockAigateway } from "@tailor-platform/sdk/vitest";
833
- *
834
- * test("resolves an AI Gateway URL", async () => {
835
- * using aigateway = mockAigateway();
836
- * aigateway.setUrls({ "my-aigateway": "https://my-aigateway.example.com" });
837
- * // …
838
- * });
839
- * ```
840
- */
841
- function mockAigateway() {
842
- const root = tailorRoot();
843
- const prev = root.aigateway;
844
- let urls = {};
845
- const get = vi.fn(async (name) => {
846
- const url = urls[name];
847
- if (url === void 0) throw new Error(`No AI Gateway registered for "${name}". Acquire mockAigateway() and call setUrls(...).`);
848
- return { url };
849
- });
850
- root.aigateway = { get };
851
- return withDispose({
852
- /** The `get` `vi.fn`. */
853
- get,
854
- setUrls(value) {
855
- urls = value;
856
- },
857
- get calls() {
858
- return get.mock.calls.map(([name]) => ({ name }));
859
- },
860
- reset() {
861
- urls = {};
862
- get.mockClear();
863
- }
864
- }, () => {
865
- root.aigateway = prev;
866
- });
867
- }
868
-
869
- //#endregion
870
- export { mockIdp as a, mockWorkflow as c, mockIconv as i, mockAuthconnection as n, mockSecretmanager as o, mockFile as r, mockTailordb as s, mockAigateway as t };
871
- //# sourceMappingURL=mock-Ce1GCi4-.mjs.map