@diagonal-hq/workflows 0.2.0 → 0.3.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/README.md CHANGED
@@ -4,15 +4,15 @@ This package is the authoring API of Diagonal managed workflows. A workflow modu
4
4
 
5
5
  ## Entry points
6
6
 
7
- | Entry point | Used by | Exports |
8
- | ---------------------------------- | ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
9
- | `@diagonal-hq/workflows` | Workflows | `defineWorkflow`, `respond`, `redirect`, `fail`, `validationError`, the input schema builder `v`, `transaction`, `data`, `mail`, `notification`, `sms`, and the generated capability wrappers |
10
- | `@diagonal-hq/workflows/test` | E2E setup and assert scripts | The helpers that call no host capability: `fail`, `validationError`, `HostError`, `WorkflowFailure`, and `v` |
11
- | `@diagonal-hq/workflows/migration` | Data migration scripts | The same helpers as `/test` |
12
- | `@diagonal-hq/workflows/testing` | Local workflow tests in Node | `MockTransport`, `runWorkflow`, and `fake` |
13
- | `@diagonal-hq/workflows/http` | Local runs against a real workspace | `HttpTransport` |
7
+ | Entry point | Used by | Exports |
8
+ | ---------------------------------- | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
9
+ | `@diagonal-hq/workflows` | Workflows | `defineWorkflow`, `respond`, `redirect`, `fail`, `validationError`, the input schema builder `v`, `transaction`, `data`, `mail`, `notification`, `sms`, and the generated capability wrappers |
10
+ | `@diagonal-hq/workflows/test` | E2E setup and assert scripts | Every capability wrapper except the test profile's deny list (`auth`), `transaction`, and the root helpers that call no host capability |
11
+ | `@diagonal-hq/workflows/migration` | Data migration scripts | Every capability wrapper except the migration profile's deny list (outbound calls, messages, payments, `auth`, and `workflow.run`), `transaction`, and the root helpers that call no host capability |
12
+ | `@diagonal-hq/workflows/testing` | Local workflow tests in Node | `MockTransport`, `runWorkflow`, and `fake` |
13
+ | `@diagonal-hq/workflows/http` | Local runs against a real workspace | `HttpTransport` |
14
14
 
15
- A profile entry point (`/test` or `/migration`) exports a capability only when its profile allows that capability. The capability sets of the profiles are not decided yet, so both entry points export only the helpers above. The compiler and the script host do not enforce the profiles yet.
15
+ A profile entry point (`/test` or `/migration`) exports every capability except its profile's deny list. `ScriptProfile` in the platform owns the deny lists, and `generated/capabilities.json` publishes the allowed names under `profiles`. The workflow script compiler reports a reference to a denied capability, and the script host refuses the call. Neither entry point exports `invoke` or `setTransport`, because the compiler cannot check a capability name that a script builds at run time.
16
16
 
17
17
  Only `/testing` imports Node built-in modules (`node:async_hooks` and `node:crypto`). The other entry points need no Node API.
18
18
 
@@ -31,7 +31,7 @@ const output = await runWorkflow(welcomeMember, {}, { transport });
31
31
 
32
32
  ## Source in the platform repository
33
33
 
34
- `src/` is the same SDK source that the workflow script compiler embeds and that the QuickJS runtime bundles. Existing workspace modules import it as `@diagonal/workflow`. `php artisan workflows:script-sdk:build` regenerates `generated/capabilities.json` and `src/generated/capabilities.ts`. Do not hand-edit them.
34
+ `src/` is the same SDK source that the workflow script compiler embeds and that the QuickJS runtime bundles. Existing workspace modules import it as `@diagonal/workflow`. `php artisan workflows:script-sdk:build` regenerates `generated/capabilities.json`, `src/generated/capabilities.ts`, and `src/generated/profiles/*.ts`. Do not hand-edit them.
35
35
 
36
36
  `bin/diagonal-workflow.mjs` runs only from a platform checkout, so the package does not publish it. See `app/workflows/README.md`.
37
37
 
@@ -0,0 +1,428 @@
1
+ import {
2
+ invoke
3
+ } from "./chunk-RWZW4V74.js";
4
+ import {
5
+ HostError
6
+ } from "./chunk-OF5QITP7.js";
7
+
8
+ // packages/workflows/src/transaction.ts
9
+ async function transaction(fn) {
10
+ await invoke("transaction.begin", {});
11
+ let result;
12
+ try {
13
+ result = await fn();
14
+ } catch (error) {
15
+ await invoke("transaction.rollback", {});
16
+ throw error;
17
+ }
18
+ try {
19
+ await invoke("transaction.commit", {});
20
+ } catch (error) {
21
+ if (error instanceof HostError && error.code === "transaction_concurrent") {
22
+ await invoke("transaction.rollback", {});
23
+ }
24
+ throw error;
25
+ }
26
+ return result;
27
+ }
28
+
29
+ // packages/workflows/src/generated/capabilities.ts
30
+ var SDK_VERSION = 57;
31
+ var ai = {
32
+ /** Ask a decisions model typed questions about some content and get labelled answers with their probabilities */
33
+ decide: (input) => invoke("ai.decide", input),
34
+ /** Hand a prompt to the AI assistant, which can look up data and take action in your workspace */
35
+ runPrompt: (input) => invoke("ai.run_prompt", input)
36
+ };
37
+ var auth = {
38
+ /** Impersonate an authenticatable user, switching the current session to act as that user */
39
+ impersonate: (input) => invoke("auth.impersonate", input),
40
+ /** Login an authenticatable record */
41
+ login: (input) => invoke("auth.login", input)
42
+ };
43
+ var calendar = {
44
+ /** Generate a shareable calendar link (Google, Apple, Outlook) for an eventable record */
45
+ generateLink: (input) => invoke("calendar.generate_link", input),
46
+ /** Find eventable records occurring in a date window no wider than 3 months, expanding recurring events into one row per occurrence and per calendar the record appears on. Returns every match, so narrow the window or filters on a busy resource */
47
+ searchEvents: (input) => invoke("calendar.search_events", input)
48
+ };
49
+ var callback = {
50
+ /** Get a callback value */
51
+ get: (input) => invoke("callback.get", input),
52
+ /** Remove a callback value */
53
+ remove: (input) => invoke("callback.remove", input),
54
+ /** Set a callback value */
55
+ set: (input) => invoke("callback.set", input)
56
+ };
57
+ var chart = {
58
+ /** Group data by category for pie or donut charts */
59
+ distribution: (input) => invoke("chart.distribution", input),
60
+ /** Calculate a single metric value (total revenue, order count, etc.) */
61
+ kpi: (input) => invoke("chart.kpi", input),
62
+ /** Rank entities by a metric (top customers, best sellers, etc.) */
63
+ leaderboard: (input) => invoke("chart.leaderboard", input),
64
+ /** Aggregate data over time for line or area charts */
65
+ timeSeries: (input) => invoke("chart.time_series", input)
66
+ };
67
+ var data = {
68
+ /** Compute grouped metrics (count, sum, avg, etc.) over records */
69
+ aggregateMetrics: (input) => invoke("data.aggregate_metrics", input),
70
+ /** Count the number of records matching the filters */
71
+ count: (input) => invoke("data.count", input),
72
+ /** Create a new record */
73
+ create: (input) => invoke("data.create", input),
74
+ /** Create many records at once */
75
+ createMany: (input) => invoke("data.create-many", input),
76
+ /** Delete a record */
77
+ delete: (input) => invoke("data.delete", input),
78
+ /** Delete all records matching filter conditions */
79
+ deleteMany: (input) => invoke("data.delete-many", input),
80
+ /** Find a single record by ID or by filters */
81
+ find: (input) => invoke("data.find", input),
82
+ /** Find a record by attributes, or create a new one when no match exists */
83
+ findOrCreate: (input) => invoke("data.find-or-create", input),
84
+ relation: {
85
+ /** Attach a related record to a singular relation (BelongsTo, HasOne) */
86
+ attach: (input) => invoke("data.relation.attach", input),
87
+ /** Attach related records to a plural relation (BelongsToMany, HasMany) */
88
+ attachMany: (input) => invoke("data.relation.attach-many", input),
89
+ /** Detach a related record. */
90
+ detach: (input) => invoke("data.relation.detach", input),
91
+ /** Detach related records from a plural relation (BelongsToMany, HasMany) */
92
+ detachMany: (input) => invoke("data.relation.detach-many", input),
93
+ /** Sync related records for a relation (replaces all existing) */
94
+ sync: (input) => invoke("data.relation.sync", input)
95
+ },
96
+ /** Restore an archived record */
97
+ restore: (input) => invoke("data.restore", input),
98
+ /** Search for records */
99
+ search: (input) => invoke("data.search", input),
100
+ /** Search for records by semantic similarity */
101
+ semanticSearch: (input) => invoke("data.semantic_search", input),
102
+ /** Sum a numeric field across records matching the filters */
103
+ sum: (input) => invoke("data.sum", input),
104
+ /** Update an existing record found by ID or by filters */
105
+ update: (input) => invoke("data.update", input),
106
+ /** Find a record by attributes and update it, or create a new one */
107
+ updateOrCreate: (input) => invoke("data.update-or-create", input),
108
+ /** Validate a record */
109
+ validate: (input) => invoke("data.validate", input)
110
+ };
111
+ var date = {
112
+ /** Add N days/weeks/months/years to a date */
113
+ add: (input) => invoke("date.add", input),
114
+ /** Difference between two dates in a specified unit */
115
+ diff: (input) => invoke("date.diff", input),
116
+ /** Snap a date to the end of a period (week, month, quarter, year) */
117
+ endOf: (input) => invoke("date.end_of", input),
118
+ /** Format a date string using ICU date format syntax (e.g., "yyyy-MM-dd", "MMM d, yyyy"). */
119
+ format: (input) => invoke("date.format", input),
120
+ /** Snap a date to the start of a period (week, month, quarter, year) */
121
+ startOf: (input) => invoke("date.start_of", input),
122
+ /** Subtract N days/weeks/months/years from a date */
123
+ subtract: (input) => invoke("date.subtract", input)
124
+ };
125
+ var file = {
126
+ /** Change a file's visibility by moving it between private and public storage */
127
+ changeVisibility: (input) => invoke("file.change_visibility", input),
128
+ /** Download a file from a public http(s) URL and save it privately in the workspace */
129
+ createFromUrl: (input) => invoke("file.create_from_url", input),
130
+ /** Create a public library master from an accessible workspace file, preserving external sources. Accepts images, video, audio and PDF by the type detected from bytes. Store other files in a record file field. Returns the library File ID */
131
+ createMediaLibraryItem: (input) => invoke("file.create_media_library_item", input),
132
+ /** Generate a QR code PNG image that encodes a value and save it privately in the workspace */
133
+ createQrCode: (input) => invoke("file.create_qr_code", input)
134
+ };
135
+ var guard = {
136
+ /** Perform a validation check */
137
+ validate: (input) => invoke("guard.validate", input)
138
+ };
139
+ var http = {
140
+ /** Send an HTTP request */
141
+ request: (input) => invoke("http.request", input)
142
+ };
143
+ var lifecycle = {
144
+ /** Return modified record fields from a record lifecycle workflow */
145
+ output: (input) => invoke("lifecycle.output", input)
146
+ };
147
+ var mail = {
148
+ /** Find tracked emails by recipient, linked record, subject, sender, status, or date, newest first, with the delivery status of each recipient, including hard and soft bounces. Searches without a record, or that include the record's current addresses, require a Run As identity with the Manage Notifications permission */
149
+ search: (input) => invoke("mail.search", input),
150
+ /** Send an email */
151
+ send: (input) => invoke("mail.send", input),
152
+ /** Send an email using a notification type and template */
153
+ sendNotification: (input) => invoke("mail.send-notification", input)
154
+ };
155
+ var markdown = {
156
+ /** Convert rich Content into a markdown string */
157
+ fromContent: (input) => invoke("markdown.from_content", input),
158
+ /** Convert a markdown string into rich Content. Nodes a destination Content field disallows may be rejected by that field. */
159
+ toContent: (input) => invoke("markdown.to_content", input)
160
+ };
161
+ var mediaLibrary = {
162
+ /** Create a media library folder */
163
+ createFolder: (input) => invoke("media_library.create_folder", input),
164
+ /** Detach a file from the media library */
165
+ deleteItem: (input) => invoke("media_library.delete_item", input),
166
+ /** Move media library items into a target folder */
167
+ moveItems: (input) => invoke("media_library.move_items", input),
168
+ /** Rename a media library item and/or move it into a folder */
169
+ updateItem: (input) => invoke("media_library.update_item", input)
170
+ };
171
+ var money = {
172
+ /** Format a money value as a currency string */
173
+ format: (input) => invoke("money.format", input)
174
+ };
175
+ var notification = {
176
+ /** Send a notification email to a notifiable record */
177
+ send: (input) => invoke("notification.send", input),
178
+ /** Find records with filters and send each record’s notification to the type’s configured recipient resource */
179
+ sendBulkNotifications: (input) => invoke("notification.send-bulk-notifications", input),
180
+ /** Send a notification template to a full record of the type’s recipient resource */
181
+ sendNotification: (input) => invoke("notification.send-notification", input),
182
+ /** Record whether a notifiable record agreed to receive email or SMS */
183
+ setConsent: (input) => invoke("notification.set-consent", input)
184
+ };
185
+ var number = {
186
+ /** Format a number with configurable decimal places */
187
+ format: (input) => invoke("number.format", input)
188
+ };
189
+ var package_ = {
190
+ /** Read an input value collected when this package was installed */
191
+ installInput: (input) => invoke("package.install-input", input)
192
+ };
193
+ var page = {
194
+ /** Get the URL for a page with route parameters */
195
+ url: (input) => invoke("page.url", input)
196
+ };
197
+ var payables = {
198
+ /** Void an unpaid draft or open invoice. Rejects collected payments and payments in progress. Does not refund payments or cancel subscriptions. */
199
+ void: (input) => invoke("payables.void", input),
200
+ /** Write off all or part of an open invoice while preserving its original total. */
201
+ writeOff: (input) => invoke("payables.write-off", input)
202
+ };
203
+ var payment = {
204
+ /** Record a manual payment against a payable record */
205
+ createManual: (input) => invoke("payment.create_manual", input)
206
+ };
207
+ var payments = {
208
+ /** Charge a payable record using the payer default Stripe payment method */
209
+ charge: (input) => invoke("payments.charge", input),
210
+ /** Create a Stripe Checkout session to collect payment against a payable record */
211
+ checkout: (input) => invoke("payments.checkout", input),
212
+ /** Confirm new or saved payment details collected by PaymentForm. Return this output to the form for authentication. Run after committing checkout choices; Stripe charges cannot be rolled back. */
213
+ confirm: (input) => invoke("payments.confirm", input),
214
+ /** Process a full or partial refund against a payment record */
215
+ refund: (input) => invoke("payments.refund", input)
216
+ };
217
+ var phone = {
218
+ /** Format a phone number into a human-readable string */
219
+ format: (input) => invoke("phone.format", input)
220
+ };
221
+ var scheduling = {
222
+ /** Book a slot that Find Slots returned, as the run identity. Check the slot and return the booking with the caller's view. Return only the booking id if the caller cannot read the booking. Search accepts the Find Slots input with camelCase or snake_case keys. A pool tries its next free member when admission refuses the pick; a slot that is gone fails with the $capacity error */
223
+ bookSlot: (input) => invoke("scheduling.book_slot", input),
224
+ /** Find the times a booking can start across groups of Schedulable records, inside their open hours and outside the time bookings take, without changing records. A Request workflow that runs as another identity searches with the view of the person who called it */
225
+ findSlots: (input) => invoke("scheduling.find_slots", input)
226
+ };
227
+ var schema = {
228
+ /** Convert a schema definition into its JSON Schema document — the shape used to constrain AI and extraction output */
229
+ toJsonSchema: (input) => invoke("schema.to_json_schema", input)
230
+ };
231
+ var security = {
232
+ /** Generate a secure random password */
233
+ randomPassword: (input) => invoke("security.random_password", input)
234
+ };
235
+ var sms = {
236
+ /** Send a notification template by SMS to a full record of the type’s recipient resource */
237
+ sendNotification: (input) => invoke("sms.send-notification", input)
238
+ };
239
+ var subscriptions = {
240
+ /** Start a draft subscription using its snapshotted activation and trial policies */
241
+ activate: (input) => invoke("subscriptions.activate", input),
242
+ /** Cancel a subscription immediately, or at the end of the current billing period */
243
+ cancel: (input) => invoke("subscriptions.cancel", input),
244
+ /** Change subscription items now with optional proration, schedule the selection for the next renewal or a later billing period, or revise an eligible unpaid current or upcoming renewal invoice. An incomplete subscription can change now without a revision scope; this revises its first invoice in place. Renewal revisions use full-period prices without proration. Net prorated credits first reduce open current-period invoices of the subscription, then go to the payer balance. */
245
+ changeItems: (input) => invoke("subscriptions.change_items", input),
246
+ /** Create and activate a subscription for a payer in one step: the record, an item per price, and optionally the first invoice */
247
+ create: (input) => invoke("subscriptions.create", input),
248
+ /** Generate the payable invoice for the saved subscription schedule; partial calendar periods prorate recurring lines and full periods use the original prices */
249
+ generateInvoice: (input) => invoke("subscriptions.generate_invoice", input),
250
+ /** Pause a billing subscription so no further invoices generate until it is resumed */
251
+ pause: (input) => invoke("subscriptions.pause", input),
252
+ /** Preview initial subscription charges, covered dates, and renewal amounts without creating records or collecting payment */
253
+ preview: (input) => invoke("subscriptions.preview", input),
254
+ /** Preview a complete subscription item selection effective now, at the next renewal, or at a later billing period, without changing records */
255
+ previewChange: (input) => invoke("subscriptions.preview_change", input),
256
+ /** Resume a paused subscription; its status re-derives from the latest invoice */
257
+ resume: (input) => invoke("subscriptions.resume", input),
258
+ /** Safely replace the complete price selection that takes effect in the next billing period */
259
+ setUpcomingItems: (input) => invoke("subscriptions.set_upcoming_items", input)
260
+ };
261
+ var text = {
262
+ /** Generate a random string with configurable character sets */
263
+ generate: (input) => invoke("text.generate", input),
264
+ /** Hash a text value */
265
+ hash: (input) => invoke("text.hash", input),
266
+ /** Generate a random UUID v7 */
267
+ randomUuid: (input) => invoke("text.random_uuid", input),
268
+ /** Convert a plain text string into rich Content */
269
+ toContent: (input) => invoke("text.to_content", input)
270
+ };
271
+ var time = {
272
+ /** Add N seconds/minutes/hours/days/weeks/months/years to a datetime */
273
+ add: (input) => invoke("time.add", input),
274
+ /** Difference between two datetimes in a specified unit */
275
+ diff: (input) => invoke("time.diff", input),
276
+ /** Snap a datetime to the end of a period (hour, day, week, month, quarter, year) */
277
+ endOf: (input) => invoke("time.end_of", input),
278
+ /** Format a datetime string using ICU date format syntax (e.g., "yyyy-MM-dd HH:mm:ss", "MMM d, yyyy h:mm a"). */
279
+ format: (input) => invoke("time.format", input),
280
+ /** Snap a datetime to the start of a period (hour, day, week, month, quarter, year) */
281
+ startOf: (input) => invoke("time.start_of", input),
282
+ /** Subtract N seconds/minutes/hours/days/weeks/months/years from a datetime */
283
+ subtract: (input) => invoke("time.subtract", input)
284
+ };
285
+ var timezone = {
286
+ /** Format a timezone identifier into a human-readable string. Supports formats: full (region/city with offset), offset (UTC offset), abbreviation (timezone abbreviation), and city (city name only). */
287
+ format: (input) => invoke("timezone.format", input),
288
+ /** Interpret a local date or datetime in a timezone and return the canonical UTC datetime string. */
289
+ interpret: (input) => invoke("timezone.interpret", input)
290
+ };
291
+ var tiptap = {
292
+ /** Parse Tiptap content to HTML or text */
293
+ parse: (input) => invoke("tiptap.parse", input)
294
+ };
295
+ var user = {
296
+ /** Check user permissions for authorization */
297
+ authorize: (input) => invoke("user.authorize", input)
298
+ };
299
+ var web = {
300
+ /** Extract structured data from a web page, guided by a natural-language prompt and a required shape */
301
+ agent: (input) => invoke("web.agent", input),
302
+ /** Scrape multiple web pages in one batch and poll until every page is finished */
303
+ batchScrape: (input) => invoke("web.batch_scrape", input),
304
+ /** Crawl a site and return multi-page content (polls to completion) */
305
+ crawl: (input) => invoke("web.crawl", input),
306
+ /** Extract structured data from one or more web pages, guided by a required shape and a supporting prompt */
307
+ extract: (input) => invoke("web.extract", input),
308
+ /** Search Google and return the organic results */
309
+ googleSearch: (input) => invoke("web.google_search", input),
310
+ /** Map a site and return all of its discoverable URLs */
311
+ map: (input) => invoke("web.map", input),
312
+ /** Render a web page to a PDF document */
313
+ pdf: (input) => invoke("web.pdf", input),
314
+ /** Scrape a web page in content mode (markdown/HTML plus metadata) or JSON mode (structured data extracted against a schema) */
315
+ scrape: (input) => invoke("web.scrape", input),
316
+ /** Render a web page to a screenshot (PNG, JPEG, or WebP) */
317
+ screenshot: (input) => invoke("web.screenshot", input),
318
+ /** Search the web for a query and return ranked results */
319
+ searchRanked: (input) => invoke("web.search_ranked", input)
320
+ };
321
+ var workflow = {
322
+ /** Runs a workflow using its published version */
323
+ run: (input) => invoke("workflow.run", input),
324
+ /** Get the URL for a workflow with route parameters */
325
+ url: (input) => invoke("workflow.url", input)
326
+ };
327
+ var workspace = {
328
+ /** Get the login URL for an authenticatable resource */
329
+ loginUrl: (input) => invoke("workspace.login_url", input),
330
+ /** Set the value of a field in a workspace */
331
+ setValue: (input) => invoke("workspace.set_value", input),
332
+ /** Set multiple workspace field values at once from a key => value map */
333
+ setValues: (input) => invoke("workspace.set_values", input),
334
+ /** Get the value of a field in a workspace */
335
+ value: (input) => invoke("workspace.value", input),
336
+ /** Get all workspace field values as a dictionary */
337
+ values: (input) => invoke("workspace.values", input)
338
+ };
339
+
340
+ // packages/workflows/src/data.ts
341
+ var EACH_PAGE_SIZE = 100;
342
+ function each(input) {
343
+ const { maxRecords, ...search } = input;
344
+ if (maxRecords !== void 0 && (!Number.isInteger(maxRecords) || maxRecords < 1)) {
345
+ throw new RangeError(`maxRecords must be a positive integer. Received ${maxRecords}.`);
346
+ }
347
+ const query = JSON.parse(JSON.stringify(search));
348
+ return walk(query, maxRecords ?? Number.POSITIVE_INFINITY);
349
+ }
350
+ async function* walk(query, maxRecords) {
351
+ let remaining = maxRecords;
352
+ let after = null;
353
+ while (remaining > 0) {
354
+ const page2 = await invoke("data.search", {
355
+ ...query,
356
+ paging: "cursor",
357
+ pageSize: Math.min(EACH_PAGE_SIZE, remaining),
358
+ ...after === null ? {} : { after }
359
+ });
360
+ for (const record of page2.data ?? []) {
361
+ yield record;
362
+ remaining--;
363
+ if (remaining === 0) {
364
+ return;
365
+ }
366
+ }
367
+ if (typeof page2.cursor !== "string") {
368
+ return;
369
+ }
370
+ after = page2.cursor;
371
+ }
372
+ }
373
+ var data2 = {
374
+ ...data,
375
+ create: (input) => invoke("data.create", input),
376
+ find: (input) => invoke("data.find", input),
377
+ update: (input) => invoke("data.update", input),
378
+ search: (input) => invoke("data.search", input),
379
+ each,
380
+ delete: (input) => invoke("data.delete", input),
381
+ restore: (input) => invoke("data.restore", input),
382
+ count: (input) => invoke("data.count", input),
383
+ findOrCreate: (input) => invoke("data.find-or-create", input),
384
+ updateOrCreate: (input) => invoke("data.update-or-create", input),
385
+ createMany: (input) => invoke("data.create-many", input),
386
+ deleteMany: (input) => invoke("data.delete-many", input)
387
+ };
388
+
389
+ export {
390
+ transaction,
391
+ SDK_VERSION,
392
+ ai,
393
+ auth,
394
+ calendar,
395
+ callback,
396
+ chart,
397
+ date,
398
+ file,
399
+ guard,
400
+ http,
401
+ lifecycle,
402
+ mail,
403
+ markdown,
404
+ mediaLibrary,
405
+ money,
406
+ notification,
407
+ number,
408
+ package_,
409
+ page,
410
+ payables,
411
+ payment,
412
+ payments,
413
+ phone,
414
+ scheduling,
415
+ schema,
416
+ security,
417
+ sms,
418
+ subscriptions,
419
+ text,
420
+ time,
421
+ timezone,
422
+ tiptap,
423
+ user,
424
+ web,
425
+ workflow,
426
+ workspace,
427
+ data2 as data
428
+ };
@@ -1,3 +1,23 @@
1
+ import {
2
+ validationError
3
+ } from "./chunk-OF5QITP7.js";
4
+
5
+ // packages/workflows/src/transport.ts
6
+ var active = null;
7
+ function setTransport(transport) {
8
+ active = transport;
9
+ }
10
+ function invoke(name, input) {
11
+ if (active === null) {
12
+ return Promise.reject(
13
+ new Error(
14
+ "No Diagonal host transport is set. In tests, call setTransport(new MockTransport(...))."
15
+ )
16
+ );
17
+ }
18
+ return active.call(name, input);
19
+ }
20
+
1
21
  // packages/workflows/src/input.ts
2
22
  var InputField = class _InputField {
3
23
  constructor($spec) {
@@ -142,9 +162,77 @@ function coerceInput(spec, value) {
142
162
  }
143
163
  }
144
164
 
165
+ // packages/workflows/src/workflow.ts
166
+ function parseWorkflowInput(workflow, input) {
167
+ return workflow.input === void 0 ? input : coerceInput(workflow.input, input);
168
+ }
169
+ async function validateWorkflowInput(validator, input, ctx) {
170
+ const reported = await validator(input, ctx);
171
+ if (reported === void 0 || reported === null) {
172
+ return;
173
+ }
174
+ if (typeof reported !== "object" || Array.isArray(reported)) {
175
+ throw new TypeError(
176
+ "validateInput must return an object of errors keyed by field, or nothing."
177
+ );
178
+ }
179
+ const errors = {};
180
+ for (const [field2, messages] of Object.entries(reported)) {
181
+ const list = (Array.isArray(messages) ? messages : [messages]).filter(
182
+ (message) => typeof message === "string" && message !== ""
183
+ );
184
+ if (list.length > 0) {
185
+ errors[field2] = list;
186
+ }
187
+ }
188
+ if (Object.keys(errors).length > 0) {
189
+ validationError(errors);
190
+ }
191
+ }
192
+ function defineWorkflow(inputOrHandler, maybeHandler) {
193
+ if (typeof inputOrHandler === "function") {
194
+ return { $diagonal: "workflow", run: async (input, ctx) => inputOrHandler(input, ctx) };
195
+ }
196
+ const spec = inputOrHandler.$spec;
197
+ const handler = maybeHandler;
198
+ if (handler === void 0) {
199
+ throw new TypeError("defineWorkflow(input, handler) needs a handler after the input schema.");
200
+ }
201
+ return {
202
+ $diagonal: "workflow",
203
+ input: spec,
204
+ run: async (input, ctx) => handler(input, ctx)
205
+ };
206
+ }
207
+ function respond(body, options = {}) {
208
+ return {
209
+ $response_status: options.status ?? 200,
210
+ $response_body: body,
211
+ $response_content_type: options.contentType ?? "application/json"
212
+ };
213
+ }
214
+ function redirect(url, options = {}) {
215
+ const type = options.type ?? (/^\/(?![/\\])/.test(url) ? "internal" : "external");
216
+ const output = {
217
+ redirect_url: url,
218
+ redirect_type: type,
219
+ permanent: type !== "back" && options.permanent === true
220
+ };
221
+ if (options.success !== void 0) {
222
+ output.success = options.success;
223
+ }
224
+ return output;
225
+ }
226
+
145
227
  export {
228
+ setTransport,
229
+ invoke,
146
230
  InputField,
147
231
  InputSchema,
148
232
  v,
149
- coerceInput
233
+ parseWorkflowInput,
234
+ validateWorkflowInput,
235
+ defineWorkflow,
236
+ respond,
237
+ redirect
150
238
  };
@@ -1,6 +1,6 @@
1
1
  import type { ResourceKeyWith } from "../data.js";
2
2
  import type { ContentDocument } from "../input.js";
3
- export declare const SDK_VERSION = 55;
3
+ export declare const SDK_VERSION = 57;
4
4
  export interface AiDecideInput {
5
5
  state: unknown;
6
6
  questions: Array<{
@@ -1938,7 +1938,7 @@ export declare const file: {
1938
1938
  changeVisibility: (input: FileChangeVisibilityInput) => Promise<FileChangeVisibilityOutput>;
1939
1939
  /** Download a file from a public http(s) URL and save it privately in the workspace */
1940
1940
  createFromUrl: (input: FileCreateFromUrlInput) => Promise<FileCreateFromUrlOutput>;
1941
- /** Create a public library master from an accessible workspace file, preserving external sources. Returns the library File ID */
1941
+ /** Create a public library master from an accessible workspace file, preserving external sources. Accepts images, video, audio and PDF by the type detected from bytes. Store other files in a record file field. Returns the library File ID */
1942
1942
  createMediaLibraryItem: (input: FileCreateMediaLibraryItemInput) => Promise<FileCreateMediaLibraryItemOutput>;
1943
1943
  /** Generate a QR code PNG image that encodes a value and save it privately in the workspace */
1944
1944
  createQrCode: (input: FileCreateQrCodeInput) => Promise<FileCreateQrCodeOutput>;