@diagonal-hq/cli 0.9.3 → 0.10.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 +9 -3
- package/dist/cli.mjs +137 -4
- package/dist/workflow/generated/capabilities.d.ts +2 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@ This package is the authoring SDK for file-based workspaces. A workspace reposit
|
|
|
7
7
|
- Editor types for the workflow script SDK: `@diagonal/workflow`, `@diagonal/workflow/testing`, and `@diagonal/workflow/workspace`.
|
|
8
8
|
- The `diagonal check` command. It runs the same build and checks that a platform deploy runs, including the workflow tests. It also writes `generated/resources.ts` and the missing definition uids.
|
|
9
9
|
- The `diagonal assets upload` and `diagonal assets list` commands. They upload Application Assets, update `assets.ts`, and list immutable references.
|
|
10
|
-
- The `diagonal workflows` and `diagonal
|
|
10
|
+
- The `diagonal workflows`, `diagonal run`, and `diagonal logs` commands. They list the deployed workflows, run a manual workflow by its file path, and print recent runs with the error of each failed run.
|
|
11
11
|
|
|
12
12
|
## Check a workspace
|
|
13
13
|
|
|
@@ -33,7 +33,7 @@ The API commands read `DIAGONAL_URL` and `DIAGONAL_API_KEY`. Workflow commands r
|
|
|
33
33
|
|
|
34
34
|
## Run a deployed workflow
|
|
35
35
|
|
|
36
|
-
`diagonal workflows` and `diagonal
|
|
36
|
+
`diagonal workflows`, `diagonal run`, and `diagonal logs` call the runtime API of a deployed workspace. Set two environment variables first:
|
|
37
37
|
|
|
38
38
|
- `DIAGONAL_URL` is the workspace URL, for example `https://acme.diagonal.app`.
|
|
39
39
|
- `DIAGONAL_API_KEY` is an API key of an account with `manage_workflows`.
|
|
@@ -41,11 +41,14 @@ The API commands read `DIAGONAL_URL` and `DIAGONAL_API_KEY`. Workflow commands r
|
|
|
41
41
|
```text
|
|
42
42
|
diagonal workflows [--json]
|
|
43
43
|
diagonal run <path> [--input '<json object>'] [--json]
|
|
44
|
+
diagonal logs [path | execution id] [--status <status>] [--limit <1-100>] [--json]
|
|
44
45
|
```
|
|
45
46
|
|
|
46
47
|
- `diagonal workflows` prints the path, the trigger type, and the title of each workflow of the active deployment. `--json` prints the API response, which also has each workflow id and version id.
|
|
47
48
|
- `diagonal run workflows/seed-catalog.ts` runs the manual workflow at that path in the active deployment and waits for it. It prints the terminal status, the execution id, and the output. `--input` gives the workflow input as a JSON object. `--json` prints the API response.
|
|
48
49
|
|
|
50
|
+
- `diagonal logs` prints the recent runs of the deployed workflows, oldest first: the start time, the status and the response status, the path, the trigger, the duration, and the execution id. Under a failed run it prints the error type and message, and each field error. A path narrows the list to one workflow. `--status` takes `success`, `error` (a declared failure or an exception), `exception`, `started`, or `pending`. `--limit` sets the number of runs (default 20). `diagonal logs <execution id>` prints one run with its full error or its output. `--json` prints the API response.
|
|
51
|
+
|
|
49
52
|
`diagonal run` exits with 0 when the run succeeds, with 1 when the request or the run fails, and with 2 for a usage error or a missing environment variable. A workflow that is not manual, or a path that the active deployment does not have, is a request failure.
|
|
50
53
|
|
|
51
54
|
## What the checks do
|
|
@@ -186,7 +189,10 @@ export default defineNotificationTemplate({
|
|
|
186
189
|
email: {
|
|
187
190
|
subject: 'Welcome to {{ workspace.name }}, {{ record.name }}',
|
|
188
191
|
layout: 'standard',
|
|
189
|
-
fields: {
|
|
192
|
+
fields: {
|
|
193
|
+
heading: 'Welcome aboard',
|
|
194
|
+
body: { file: './standard.email.liquid' }
|
|
195
|
+
}
|
|
190
196
|
},
|
|
191
197
|
sms: { body: { file: './standard.sms.liquid' } },
|
|
192
198
|
references: {
|
package/dist/cli.mjs
CHANGED
|
@@ -54,7 +54,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
54
54
|
var define_globalThis_DIAGONAL_SDK_RUNTIME_default;
|
|
55
55
|
var init_define_globalThis_DIAGONAL_SDK_RUNTIME = __esm({
|
|
56
56
|
"<define:globalThis.__DIAGONAL_SDK_RUNTIME__>"() {
|
|
57
|
-
define_globalThis_DIAGONAL_SDK_RUNTIME_default = { "workflow.js": 'import {\n HostError,\n InputField,\n InputSchema,\n WorkflowFailure,\n defineWorkflow,\n fail,\n invoke,\n parseWorkflowInput,\n redirect,\n respond,\n setTransport,\n v,\n validateWorkflowInput,\n validationError\n} from "./chunk-W7OQZ5UE.js";\n\n// packages/workflows/src/transaction.ts\nasync function transaction(fn) {\n await invoke("transaction.begin", {});\n let result;\n try {\n result = await fn();\n } catch (error) {\n await invoke("transaction.rollback", {});\n throw error;\n }\n try {\n await invoke("transaction.commit", {});\n } catch (error) {\n if (error instanceof HostError && error.code === "transaction_concurrent") {\n await invoke("transaction.rollback", {});\n }\n throw error;\n }\n return result;\n}\n\n// packages/workflows/src/generated/capabilities.ts\nvar SDK_VERSION = 55;\nvar ai = {\n /** Ask a decisions model typed questions about some content and get labelled answers with their probabilities */\n decide: (input) => invoke("ai.decide", input),\n /** Hand a prompt to the AI assistant, which can look up data and take action in your workspace */\n runPrompt: (input) => invoke("ai.run_prompt", input)\n};\nvar auth = {\n /** Impersonate an authenticatable user, switching the current session to act as that user */\n impersonate: (input) => invoke("auth.impersonate", input),\n /** Login an authenticatable record */\n login: (input) => invoke("auth.login", input)\n};\nvar calendar = {\n /** Generate a shareable calendar link (Google, Apple, Outlook) for an eventable record */\n generateLink: (input) => invoke("calendar.generate_link", input),\n /** 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 */\n searchEvents: (input) => invoke("calendar.search_events", input)\n};\nvar callback = {\n /** Get a callback value */\n get: (input) => invoke("callback.get", input),\n /** Remove a callback value */\n remove: (input) => invoke("callback.remove", input),\n /** Set a callback value */\n set: (input) => invoke("callback.set", input)\n};\nvar chart = {\n /** Group data by category for pie or donut charts */\n distribution: (input) => invoke("chart.distribution", input),\n /** Calculate a single metric value (total revenue, order count, etc.) */\n kpi: (input) => invoke("chart.kpi", input),\n /** Rank entities by a metric (top customers, best sellers, etc.) */\n leaderboard: (input) => invoke("chart.leaderboard", input),\n /** Aggregate data over time for line or area charts */\n timeSeries: (input) => invoke("chart.time_series", input)\n};\nvar data = {\n /** Compute grouped metrics (count, sum, avg, etc.) over records */\n aggregateMetrics: (input) => invoke("data.aggregate_metrics", input),\n /** Count the number of records matching the filters */\n count: (input) => invoke("data.count", input),\n /** Create a new record */\n create: (input) => invoke("data.create", input),\n /** Create many records at once */\n createMany: (input) => invoke("data.create-many", input),\n /** Delete a record */\n delete: (input) => invoke("data.delete", input),\n /** Delete all records matching filter conditions */\n deleteMany: (input) => invoke("data.delete-many", input),\n /** Find a single record by ID or by filters */\n find: (input) => invoke("data.find", input),\n /** Find a record by attributes, or create a new one when no match exists */\n findOrCreate: (input) => invoke("data.find-or-create", input),\n relation: {\n /** Attach a related record to a singular relation (BelongsTo, HasOne) */\n attach: (input) => invoke("data.relation.attach", input),\n /** Attach related records to a plural relation (BelongsToMany, HasMany) */\n attachMany: (input) => invoke("data.relation.attach-many", input),\n /** Detach a related record. */\n detach: (input) => invoke("data.relation.detach", input),\n /** Detach related records from a plural relation (BelongsToMany, HasMany) */\n detachMany: (input) => invoke("data.relation.detach-many", input),\n /** Sync related records for a relation (replaces all existing) */\n sync: (input) => invoke("data.relation.sync", input)\n },\n /** Restore an archived record */\n restore: (input) => invoke("data.restore", input),\n /** Search for records */\n search: (input) => invoke("data.search", input),\n /** Search for records by semantic similarity */\n semanticSearch: (input) => invoke("data.semantic_search", input),\n /** Sum a numeric field across records matching the filters */\n sum: (input) => invoke("data.sum", input),\n /** Update an existing record found by ID or by filters */\n update: (input) => invoke("data.update", input),\n /** Find a record by attributes and update it, or create a new one */\n updateOrCreate: (input) => invoke("data.update-or-create", input),\n /** Validate a record */\n validate: (input) => invoke("data.validate", input)\n};\nvar date = {\n /** Add N days/weeks/months/years to a date */\n add: (input) => invoke("date.add", input),\n /** Difference between two dates in a specified unit */\n diff: (input) => invoke("date.diff", input),\n /** Snap a date to the end of a period (week, month, quarter, year) */\n endOf: (input) => invoke("date.end_of", input),\n /** Format a date string using ICU date format syntax (e.g., "yyyy-MM-dd", "MMM d, yyyy"). */\n format: (input) => invoke("date.format", input),\n /** Snap a date to the start of a period (week, month, quarter, year) */\n startOf: (input) => invoke("date.start_of", input),\n /** Subtract N days/weeks/months/years from a date */\n subtract: (input) => invoke("date.subtract", input)\n};\nvar file = {\n /** Change a file\'s visibility by moving it between private and public storage */\n changeVisibility: (input) => invoke("file.change_visibility", input),\n /** Download a file from a public http(s) URL and save it privately in the workspace */\n createFromUrl: (input) => invoke("file.create_from_url", input),\n /** Create a public library master from an accessible workspace file, preserving external sources. Returns the library File ID */\n createMediaLibraryItem: (input) => invoke("file.create_media_library_item", input),\n /** Generate a QR code PNG image that encodes a value and save it privately in the workspace */\n createQrCode: (input) => invoke("file.create_qr_code", input)\n};\nvar guard = {\n /** Perform a validation check */\n validate: (input) => invoke("guard.validate", input)\n};\nvar http = {\n /** Send an HTTP request */\n request: (input) => invoke("http.request", input)\n};\nvar lifecycle = {\n /** Return modified record fields from a record lifecycle workflow */\n output: (input) => invoke("lifecycle.output", input)\n};\nvar mail = {\n /** 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 */\n search: (input) => invoke("mail.search", input),\n /** Send an email */\n send: (input) => invoke("mail.send", input),\n /** Send an email using a notification type and template */\n sendNotification: (input) => invoke("mail.send-notification", input)\n};\nvar markdown = {\n /** Convert rich Content into a markdown string */\n fromContent: (input) => invoke("markdown.from_content", input),\n /** Convert a markdown string into rich Content. Nodes a destination Content field disallows may be rejected by that field. */\n toContent: (input) => invoke("markdown.to_content", input)\n};\nvar mediaLibrary = {\n /** Create a media library folder */\n createFolder: (input) => invoke("media_library.create_folder", input),\n /** Detach a file from the media library */\n deleteItem: (input) => invoke("media_library.delete_item", input),\n /** Move media library items into a target folder */\n moveItems: (input) => invoke("media_library.move_items", input),\n /** Rename a media library item and/or move it into a folder */\n updateItem: (input) => invoke("media_library.update_item", input)\n};\nvar money = {\n /** Format a money value as a currency string */\n format: (input) => invoke("money.format", input)\n};\nvar notification = {\n /** Send a notification email to a notifiable record */\n send: (input) => invoke("notification.send", input),\n /** Find records with filters and send each record\u2019s notification to the type\u2019s configured recipient resource */\n sendBulkNotifications: (input) => invoke("notification.send-bulk-notifications", input),\n /** Send a notification template to a full record of the type\u2019s recipient resource */\n sendNotification: (input) => invoke("notification.send-notification", input),\n /** Record whether a notifiable record agreed to receive email or SMS */\n setConsent: (input) => invoke("notification.set-consent", input)\n};\nvar number = {\n /** Format a number with configurable decimal places */\n format: (input) => invoke("number.format", input)\n};\nvar package_ = {\n /** Read an input value collected when this package was installed */\n installInput: (input) => invoke("package.install-input", input)\n};\nvar page = {\n /** Get the URL for a page with route parameters */\n url: (input) => invoke("page.url", input)\n};\nvar payables = {\n /** Void an unpaid draft or open invoice. Rejects collected payments and payments in progress. Does not refund payments or cancel subscriptions. */\n void: (input) => invoke("payables.void", input),\n /** Write off all or part of an open invoice while preserving its original total. */\n writeOff: (input) => invoke("payables.write-off", input)\n};\nvar payment = {\n /** Record a manual payment against a payable record */\n createManual: (input) => invoke("payment.create_manual", input)\n};\nvar payments = {\n /** Charge a payable record using the payer default Stripe payment method */\n charge: (input) => invoke("payments.charge", input),\n /** Create a Stripe Checkout session to collect payment against a payable record */\n checkout: (input) => invoke("payments.checkout", input),\n /** 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. */\n confirm: (input) => invoke("payments.confirm", input),\n /** Process a full or partial refund against a payment record */\n refund: (input) => invoke("payments.refund", input)\n};\nvar phone = {\n /** Format a phone number into a human-readable string */\n format: (input) => invoke("phone.format", input)\n};\nvar scheduling = {\n /** 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 */\n bookSlot: (input) => invoke("scheduling.book_slot", input),\n /** 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 */\n findSlots: (input) => invoke("scheduling.find_slots", input)\n};\nvar schema = {\n /** Convert a schema definition into its JSON Schema document \u2014 the shape used to constrain AI and extraction output */\n toJsonSchema: (input) => invoke("schema.to_json_schema", input)\n};\nvar security = {\n /** Generate a secure random password */\n randomPassword: (input) => invoke("security.random_password", input)\n};\nvar sms = {\n /** Send a notification template by SMS to a full record of the type\u2019s recipient resource */\n sendNotification: (input) => invoke("sms.send-notification", input)\n};\nvar subscriptions = {\n /** Start a draft subscription using its snapshotted activation and trial policies */\n activate: (input) => invoke("subscriptions.activate", input),\n /** Cancel a subscription immediately, or at the end of the current billing period */\n cancel: (input) => invoke("subscriptions.cancel", input),\n /** 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. */\n changeItems: (input) => invoke("subscriptions.change_items", input),\n /** Create and activate a subscription for a payer in one step: the record, an item per price, and optionally the first invoice */\n create: (input) => invoke("subscriptions.create", input),\n /** Generate the payable invoice for the saved subscription schedule; partial calendar periods prorate recurring lines and full periods use the original prices */\n generateInvoice: (input) => invoke("subscriptions.generate_invoice", input),\n /** Pause a billing subscription so no further invoices generate until it is resumed */\n pause: (input) => invoke("subscriptions.pause", input),\n /** Preview initial subscription charges, covered dates, and renewal amounts without creating records or collecting payment */\n preview: (input) => invoke("subscriptions.preview", input),\n /** Preview a complete subscription item selection effective now, at the next renewal, or at a later billing period, without changing records */\n previewChange: (input) => invoke("subscriptions.preview_change", input),\n /** Resume a paused subscription; its status re-derives from the latest invoice */\n resume: (input) => invoke("subscriptions.resume", input),\n /** Safely replace the complete price selection that takes effect in the next billing period */\n setUpcomingItems: (input) => invoke("subscriptions.set_upcoming_items", input)\n};\nvar text = {\n /** Generate a random string with configurable character sets */\n generate: (input) => invoke("text.generate", input),\n /** Hash a text value */\n hash: (input) => invoke("text.hash", input),\n /** Generate a random UUID v7 */\n randomUuid: (input) => invoke("text.random_uuid", input),\n /** Convert a plain text string into rich Content */\n toContent: (input) => invoke("text.to_content", input)\n};\nvar time = {\n /** Add N seconds/minutes/hours/days/weeks/months/years to a datetime */\n add: (input) => invoke("time.add", input),\n /** Difference between two datetimes in a specified unit */\n diff: (input) => invoke("time.diff", input),\n /** Snap a datetime to the end of a period (hour, day, week, month, quarter, year) */\n endOf: (input) => invoke("time.end_of", input),\n /** Format a datetime string using ICU date format syntax (e.g., "yyyy-MM-dd HH:mm:ss", "MMM d, yyyy h:mm a"). */\n format: (input) => invoke("time.format", input),\n /** Snap a datetime to the start of a period (hour, day, week, month, quarter, year) */\n startOf: (input) => invoke("time.start_of", input),\n /** Subtract N seconds/minutes/hours/days/weeks/months/years from a datetime */\n subtract: (input) => invoke("time.subtract", input)\n};\nvar timezone = {\n /** 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). */\n format: (input) => invoke("timezone.format", input),\n /** Interpret a local date or datetime in a timezone and return the canonical UTC datetime string. */\n interpret: (input) => invoke("timezone.interpret", input)\n};\nvar tiptap = {\n /** Parse Tiptap content to HTML or text */\n parse: (input) => invoke("tiptap.parse", input)\n};\nvar user = {\n /** Check user permissions for authorization */\n authorize: (input) => invoke("user.authorize", input)\n};\nvar web = {\n /** Extract structured data from a web page, guided by a natural-language prompt and a required shape */\n agent: (input) => invoke("web.agent", input),\n /** Scrape multiple web pages in one batch and poll until every page is finished */\n batchScrape: (input) => invoke("web.batch_scrape", input),\n /** Crawl a site and return multi-page content (polls to completion) */\n crawl: (input) => invoke("web.crawl", input),\n /** Extract structured data from one or more web pages, guided by a required shape and a supporting prompt */\n extract: (input) => invoke("web.extract", input),\n /** Search Google and return the organic results */\n googleSearch: (input) => invoke("web.google_search", input),\n /** Map a site and return all of its discoverable URLs */\n map: (input) => invoke("web.map", input),\n /** Render a web page to a PDF document */\n pdf: (input) => invoke("web.pdf", input),\n /** Scrape a web page in content mode (markdown/HTML plus metadata) or JSON mode (structured data extracted against a schema) */\n scrape: (input) => invoke("web.scrape", input),\n /** Render a web page to a screenshot (PNG, JPEG, or WebP) */\n screenshot: (input) => invoke("web.screenshot", input),\n /** Search the web for a query and return ranked results */\n searchRanked: (input) => invoke("web.search_ranked", input)\n};\nvar workflow = {\n /** Runs a workflow using its published version */\n run: (input) => invoke("workflow.run", input),\n /** Get the URL for a workflow with route parameters */\n url: (input) => invoke("workflow.url", input)\n};\nvar workspace = {\n /** Get the login URL for an authenticatable resource */\n loginUrl: (input) => invoke("workspace.login_url", input),\n /** Set the value of a field in a workspace */\n setValue: (input) => invoke("workspace.set_value", input),\n /** Set multiple workspace field values at once from a key => value map */\n setValues: (input) => invoke("workspace.set_values", input),\n /** Get the value of a field in a workspace */\n value: (input) => invoke("workspace.value", input),\n /** Get all workspace field values as a dictionary */\n values: (input) => invoke("workspace.values", input)\n};\n\n// packages/workflows/src/data.ts\nvar EACH_PAGE_SIZE = 100;\nfunction each(input) {\n const { maxRecords, ...search } = input;\n if (maxRecords !== void 0 && (!Number.isInteger(maxRecords) || maxRecords < 1)) {\n throw new RangeError(`maxRecords must be a positive integer. Received ${maxRecords}.`);\n }\n const query = JSON.parse(JSON.stringify(search));\n return walk(query, maxRecords ?? Number.POSITIVE_INFINITY);\n}\nasync function* walk(query, maxRecords) {\n let remaining = maxRecords;\n let after = null;\n while (remaining > 0) {\n const page2 = await invoke("data.search", {\n ...query,\n paging: "cursor",\n pageSize: Math.min(EACH_PAGE_SIZE, remaining),\n ...after === null ? {} : { after }\n });\n for (const record of page2.data ?? []) {\n yield record;\n remaining--;\n if (remaining === 0) {\n return;\n }\n }\n if (typeof page2.cursor !== "string") {\n return;\n }\n after = page2.cursor;\n }\n}\nvar data2 = {\n ...data,\n create: (input) => invoke("data.create", input),\n find: (input) => invoke("data.find", input),\n update: (input) => invoke("data.update", input),\n search: (input) => invoke("data.search", input),\n each,\n delete: (input) => invoke("data.delete", input),\n restore: (input) => invoke("data.restore", input),\n count: (input) => invoke("data.count", input),\n findOrCreate: (input) => invoke("data.find-or-create", input),\n updateOrCreate: (input) => invoke("data.update-or-create", input),\n createMany: (input) => invoke("data.create-many", input),\n deleteMany: (input) => invoke("data.delete-many", input)\n};\n\n// packages/workflows/src/notifications.ts\nvar mail2 = {\n ...mail,\n sendNotification: (input) => invoke("mail.send-notification", input)\n};\nvar notification2 = {\n ...notification,\n sendNotification: (input) => invoke("notification.send-notification", input),\n sendBulkNotifications: (input) => invoke("notification.send-bulk-notifications", input),\n setConsent: (input) => invoke("notification.set-consent", input)\n};\nvar sms2 = {\n ...sms,\n sendNotification: (input) => invoke("sms.send-notification", input)\n};\nexport {\n HostError,\n InputField,\n InputSchema,\n SDK_VERSION,\n WorkflowFailure,\n ai,\n auth,\n calendar,\n callback,\n chart,\n data2 as data,\n date,\n defineWorkflow,\n fail,\n file,\n guard,\n http,\n invoke,\n lifecycle,\n mail2 as mail,\n markdown,\n mediaLibrary,\n money,\n notification2 as notification,\n number,\n package_ as package,\n page,\n parseWorkflowInput,\n payables,\n payment,\n payments,\n phone,\n redirect,\n respond,\n scheduling,\n schema,\n security,\n setTransport,\n sms2 as sms,\n subscriptions,\n text,\n time,\n timezone,\n tiptap,\n transaction,\n user,\n v,\n validateWorkflowInput,\n validationError,\n web,\n workflow,\n workspace\n};\n', "testing.js": 'import {\n HostError,\n parseWorkflowInput,\n setTransport,\n validateWorkflowInput\n} from "./chunk-W7OQZ5UE.js";\n\n// packages/workflows/src/testing/index.ts\nimport { AsyncLocalStorage } from "node:async_hooks";\nimport { randomUUID } from "node:crypto";\n\n// packages/workflows/src/serial-transaction-transport.ts\nvar PromiseConstructor = Promise;\nvar objectKeys = Object.keys;\nvar isArray = Array.isArray;\nvar SerialTransactionTransport = class {\n constructor(transport) {\n this.transport = transport;\n }\n transport;\n pending = 0;\n settled = null;\n transactionOpen = false;\n closing = false;\n async call(name, input) {\n const begins = name === "transaction.begin";\n const rollsBack = name === "transaction.rollback";\n const ends = rollsBack || name === "transaction.commit";\n if (begins || ends) {\n if (input === null || typeof input !== "object" || isArray(input) || objectKeys(input).length > 0) {\n throw new HostError(\n "Transaction controls accept an empty object.",\n "invalid_arguments",\n 422,\n null\n );\n }\n input = {};\n }\n if (this.closing || (this.transactionOpen || begins) && this.pending > 0 && !rollsBack) {\n throw new HostError(\n "Await each capability call before starting another call while a transaction is active.",\n "transaction_concurrent",\n 409,\n null\n );\n }\n const opens = begins && !this.transactionOpen;\n const closes = ends && this.transactionOpen;\n if (opens) {\n this.transactionOpen = true;\n }\n if (closes) {\n this.closing = true;\n }\n const previous = this.settled;\n let complete;\n let closed = closes;\n try {\n if (rollsBack && closes && previous !== null) {\n await previous;\n }\n this.pending++;\n this.settled = new PromiseConstructor((resolve) => {\n complete = resolve;\n });\n return await this.transport.call(name, input);\n } catch (error) {\n if (closes && error instanceof HostError && (error.code === "invalid_arguments" || error.code === "resolver_not_allowed" || error.code === "capability_denied" || error.code === "payload_too_large" || error.code === "validation" || error.code === "transaction_concurrent")) {\n closed = false;\n }\n if (opens) {\n this.transactionOpen = false;\n }\n throw error;\n } finally {\n if (complete !== void 0) {\n this.pending--;\n complete();\n if (this.pending === 0) {\n this.settled = null;\n }\n }\n if (closes) {\n this.transactionOpen = !closed;\n this.closing = false;\n }\n }\n }\n};\n\n// packages/workflows/src/testing/index.ts\nvar MockTransport = class {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor(handlers) {\n this.handlers = handlers;\n }\n handlers;\n calls = [];\n async call(name, input) {\n this.calls.push({ name, input });\n const handler = this.handlers[name];\n if (handler === void 0) {\n throw new HostError(`No mock for ${name}.`, "capability_denied", 403, null);\n }\n return handler(input);\n }\n};\nvar defaultContext = {\n user: null,\n callingUser: null,\n trigger: {},\n request: null,\n workspace: { id: "local", timezone: "UTC" },\n now: (/* @__PURE__ */ new Date(0)).toISOString()\n};\nvar runTransports = new AsyncLocalStorage();\nvar activeRuns = 0;\nvar runTransport = {\n call(name, input) {\n const transport = runTransports.getStore();\n if (transport === void 0) {\n return Promise.reject(\n new Error(`The ${name} call was made outside the runWorkflow call that owns a transport.`)\n );\n }\n return transport.call(name, input);\n }\n};\nasync function runWorkflow(workflow, input, options = {}) {\n const transport = options.transport ?? new MockTransport({});\n const suppliedExecution = options.context?.execution;\n const workflowId = suppliedExecution && "workflowId" in suppliedExecution && typeof suppliedExecution.workflowId === "string" ? suppliedExecution.workflowId : "local";\n const execution = {\n id: randomUUID(),\n kind: "workflow",\n workflowId,\n owner: { type: "workflow", id: workflowId }\n };\n const context = {\n ...defaultContext,\n ...options.context,\n execution: { ...execution, ...suppliedExecution }\n };\n activeRuns++;\n setTransport(runTransport);\n try {\n return await runTransports.run(new SerialTransactionTransport(transport), async () => {\n const parsed = parseWorkflowInput(workflow, input);\n if (options.validateInput) {\n await validateWorkflowInput(options.validateInput, parsed, context);\n }\n return await workflow.run(parsed, context);\n });\n } finally {\n activeRuns--;\n if (activeRuns === 0) {\n setTransport(null);\n }\n }\n}\nvar seed = 1;\nvar next = () => {\n seed = seed * 16807 % 2147483647;\n return seed;\n};\nvar pick = (values) => values[next() % values.length];\nvar fake = {\n reset() {\n seed = 1;\n return fake;\n },\n email: () => `${pick(["ada", "grace", "alan", "edsger"])}${next() % 1e3}@example.test`,\n name: () => `${pick(["Ada", "Grace", "Alan", "Edsger"])} ${pick(["Lovelace", "Hopper", "Turing", "Dijkstra"])}`,\n uuid: () => "00000000-0000-4000-8000-".concat(String(next()).padStart(12, "0").slice(-12)),\n number: (min = 0, max = 100) => min + next() % (max - min + 1)\n};\nexport {\n MockTransport,\n fake,\n runWorkflow\n};\n', "chunk-W7OQZ5UE.js": '// packages/workflows/src/errors.ts\nvar HostError = class extends Error {\n /**\n * @param failureId The host\'s ID for the failure of the call. When the error ends the run, the\n * host records that failure, so a run records the failure of the call that it rethrows.\n */\n constructor(message, code, status, details, failureId = null) {\n super(message);\n this.code = code;\n this.status = status;\n this.details = details;\n this.failureId = failureId;\n this.name = "HostError";\n }\n code;\n status;\n details;\n failureId;\n};\nvar WorkflowFailure = class extends Error {\n constructor(message, status, details = null) {\n super(message);\n this.status = status;\n this.details = details;\n this.name = "WorkflowFailure";\n }\n status;\n details;\n};\nfunction fail(message, options = {}) {\n throw new WorkflowFailure(message, options.status ?? 400, options.details ?? null);\n}\nfunction validationError(errors, options = {}) {\n throw new WorkflowFailure(options.message ?? "The given data was invalid.", 422, { errors });\n}\n\n// packages/workflows/src/transport.ts\nvar active = null;\nfunction setTransport(transport) {\n active = transport;\n}\nfunction invoke(name, input) {\n if (active === null) {\n return Promise.reject(\n new Error(\n "No Diagonal host transport is set. In tests, call setTransport(new MockTransport(...))."\n )\n );\n }\n return active.call(name, input);\n}\n\n// packages/workflows/src/input.ts\nvar InputField = class _InputField {\n constructor($spec) {\n this.$spec = $spec;\n }\n $spec;\n /** The key may be absent. */\n optional() {\n return new _InputField({ ...this.$spec, optional: true });\n }\n /** The value may be `null`. */\n nullable() {\n return new _InputField({ ...this.$spec, nullable: true });\n }\n /** At least `value`: a number\'s value, a text\'s length, or a list\'s item count. */\n min(value) {\n return this.rule(`min:${value}`);\n }\n /** At most `value`: a number\'s value, a text\'s length, or a list\'s item count. */\n max(value) {\n return this.rule(`max:${value}`);\n }\n /** Between `min` and `max`, inclusive, measured as for `min` and `max`. */\n between(min, max) {\n return this.rule(`between:${min},${max}`);\n }\n /** Exactly `value`, measured as for `min` and `max`. */\n size(value) {\n return this.rule(`size:${value}`);\n }\n /** The text matches the pattern. */\n regex(pattern) {\n return this.rule(`regex:/${pattern.source}/${pattern.flags}`);\n }\n /** Any other platform validation rule, such as `starts_with:INV-` or `after:today`. */\n rule(rule) {\n return new _InputField({ ...this.$spec, rules: [...this.$spec.rules, rule] });\n }\n label(label) {\n return new _InputField({ ...this.$spec, label });\n }\n description(description) {\n return new _InputField({ ...this.$spec, description });\n }\n};\nvar InputSchema = class extends InputField {\n constructor(shape) {\n super(objectSpec(shape));\n this.shape = shape;\n }\n shape;\n};\nfunction objectSpec(shape) {\n return {\n kind: "object",\n optional: false,\n nullable: false,\n rules: [],\n fields: Object.fromEntries(Object.entries(shape).map(([key, field2]) => [key, field2.$spec]))\n };\n}\nvar field = (kind, extra = {}) => new InputField({ kind, optional: false, nullable: false, rules: [], ...extra });\nvar v = {\n text: () => field("text"),\n email: () => field("email"),\n url: () => field("url"),\n uuid: () => field("uuid"),\n phone: () => field("phone"),\n /** A calendar date, `YYYY-MM-DD`. */\n date: () => field("date"),\n /** A date and time, ISO 8601. */\n datetime: () => field("datetime"),\n /** A time of day, `HH:MM`. */\n time: () => field("time"),\n timezone: () => field("timezone"),\n color: () => field("color"),\n number: () => field("number"),\n integer: () => field("integer"),\n /** An amount of money: `amount` in the currency\'s minor units, such as cents, and the lowercase ISO 4217 `currency`. */\n money: () => field("money"),\n boolean: () => field("boolean"),\n /** One of `options`. */\n select: (options) => field("select", { options }),\n /** A list whose items each satisfy `items`. */\n list: (items) => field("list", { items: items.$spec }),\n /** An object with the given fields. */\n object: (shape) => new InputSchema(shape),\n /**\n * The field values of a record of `resource`, checked against that resource\'s field\n * definitions: types, required fields, and each field\'s own rules.\n */\n record: (resource) => field("record", { resource }),\n /** The ID of an existing record of `resource`, in `scope`. */\n recordReference: (resource, options = {}) => field("recordReference", { resource, ...options }),\n /** The ID of an existing role. */\n roleReference: () => field("roleReference"),\n /**\n * A file: the ID of an existing file, or the temporary path of an upload. A data call that\n * writes the value to a file field of a record finalizes the upload.\n */\n file: (options = {}) => field("file", options),\n /** A rich text document with the formatting that `options` allows. */\n content: (options = {}) => field("content", Object.keys(options).length === 0 ? {} : { content: options })\n};\nvar NUMERIC = /^-?(\\d+\\.?\\d*|\\.\\d+)(e[-+]?\\d+)?$/i;\nfunction coerceNumber(value) {\n return typeof value === "string" && NUMERIC.test(value.trim()) ? Number(value) : value;\n}\nfunction coerceInput(spec, value) {\n if (value === null || value === void 0) {\n return value;\n }\n switch (spec.kind) {\n case "number":\n case "integer":\n return coerceNumber(value);\n case "money":\n return typeof value === "object" && !Array.isArray(value) && "amount" in value ? { ...value, amount: coerceNumber(value.amount) } : value;\n case "boolean":\n if (value === "true" || value === "1" || value === 1) {\n return true;\n }\n return value === "false" || value === "0" || value === 0 ? false : value;\n case "select":\n return typeof value === "string" && !spec.options?.includes(value) && spec.options?.includes(Number(value)) ? Number(value) : value;\n case "list":\n return Array.isArray(value) && spec.items ? value.map((item) => coerceInput(spec.items, item)) : value;\n case "object": {\n if (typeof value !== "object" || Array.isArray(value) || !spec.fields) {\n return value;\n }\n const result = { ...value };\n for (const [key, fieldSpec] of Object.entries(spec.fields)) {\n if (key in result) {\n result[key] = coerceInput(fieldSpec, result[key]);\n }\n }\n return result;\n }\n default:\n return value;\n }\n}\n\n// packages/workflows/src/workflow.ts\nfunction parseWorkflowInput(workflow, input) {\n return workflow.input === void 0 ? input : coerceInput(workflow.input, input);\n}\nasync function validateWorkflowInput(validator, input, ctx) {\n const reported = await validator(input, ctx);\n if (reported === void 0 || reported === null) {\n return;\n }\n if (typeof reported !== "object" || Array.isArray(reported)) {\n throw new TypeError(\n "validateInput must return an object of errors keyed by field, or nothing."\n );\n }\n const errors = {};\n for (const [field2, messages] of Object.entries(reported)) {\n const list = (Array.isArray(messages) ? messages : [messages]).filter(\n (message) => typeof message === "string" && message !== ""\n );\n if (list.length > 0) {\n errors[field2] = list;\n }\n }\n if (Object.keys(errors).length > 0) {\n validationError(errors);\n }\n}\nfunction defineWorkflow(inputOrHandler, maybeHandler) {\n if (typeof inputOrHandler === "function") {\n return { $diagonal: "workflow", run: async (input, ctx) => inputOrHandler(input, ctx) };\n }\n const spec = inputOrHandler.$spec;\n const handler = maybeHandler;\n if (handler === void 0) {\n throw new TypeError("defineWorkflow(input, handler) needs a handler after the input schema.");\n }\n return {\n $diagonal: "workflow",\n input: spec,\n run: async (input, ctx) => handler(input, ctx)\n };\n}\nfunction respond(body, options = {}) {\n return {\n $response_status: options.status ?? 200,\n $response_body: body,\n $response_content_type: options.contentType ?? "application/json"\n };\n}\nfunction redirect(url, options = {}) {\n const type = options.type ?? (/^\\/(?![/\\\\])/.test(url) ? "internal" : "external");\n const output = {\n redirect_url: url,\n redirect_type: type,\n permanent: type !== "back" && options.permanent === true\n };\n if (options.success !== void 0) {\n output.success = options.success;\n }\n return output;\n}\n\nexport {\n HostError,\n WorkflowFailure,\n fail,\n validationError,\n setTransport,\n invoke,\n InputField,\n InputSchema,\n v,\n parseWorkflowInput,\n validateWorkflowInput,\n defineWorkflow,\n respond,\n redirect\n};\n' };
|
|
57
|
+
define_globalThis_DIAGONAL_SDK_RUNTIME_default = { "workflow.js": 'import {\n HostError,\n InputField,\n InputSchema,\n WorkflowFailure,\n defineWorkflow,\n fail,\n invoke,\n parseWorkflowInput,\n redirect,\n respond,\n setTransport,\n v,\n validateWorkflowInput,\n validationError\n} from "./chunk-W7OQZ5UE.js";\n\n// packages/workflows/src/transaction.ts\nasync function transaction(fn) {\n await invoke("transaction.begin", {});\n let result;\n try {\n result = await fn();\n } catch (error) {\n await invoke("transaction.rollback", {});\n throw error;\n }\n try {\n await invoke("transaction.commit", {});\n } catch (error) {\n if (error instanceof HostError && error.code === "transaction_concurrent") {\n await invoke("transaction.rollback", {});\n }\n throw error;\n }\n return result;\n}\n\n// packages/workflows/src/generated/capabilities.ts\nvar SDK_VERSION = 56;\nvar ai = {\n /** Ask a decisions model typed questions about some content and get labelled answers with their probabilities */\n decide: (input) => invoke("ai.decide", input),\n /** Hand a prompt to the AI assistant, which can look up data and take action in your workspace */\n runPrompt: (input) => invoke("ai.run_prompt", input)\n};\nvar auth = {\n /** Impersonate an authenticatable user, switching the current session to act as that user */\n impersonate: (input) => invoke("auth.impersonate", input),\n /** Login an authenticatable record */\n login: (input) => invoke("auth.login", input)\n};\nvar calendar = {\n /** Generate a shareable calendar link (Google, Apple, Outlook) for an eventable record */\n generateLink: (input) => invoke("calendar.generate_link", input),\n /** 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 */\n searchEvents: (input) => invoke("calendar.search_events", input)\n};\nvar callback = {\n /** Get a callback value */\n get: (input) => invoke("callback.get", input),\n /** Remove a callback value */\n remove: (input) => invoke("callback.remove", input),\n /** Set a callback value */\n set: (input) => invoke("callback.set", input)\n};\nvar chart = {\n /** Group data by category for pie or donut charts */\n distribution: (input) => invoke("chart.distribution", input),\n /** Calculate a single metric value (total revenue, order count, etc.) */\n kpi: (input) => invoke("chart.kpi", input),\n /** Rank entities by a metric (top customers, best sellers, etc.) */\n leaderboard: (input) => invoke("chart.leaderboard", input),\n /** Aggregate data over time for line or area charts */\n timeSeries: (input) => invoke("chart.time_series", input)\n};\nvar data = {\n /** Compute grouped metrics (count, sum, avg, etc.) over records */\n aggregateMetrics: (input) => invoke("data.aggregate_metrics", input),\n /** Count the number of records matching the filters */\n count: (input) => invoke("data.count", input),\n /** Create a new record */\n create: (input) => invoke("data.create", input),\n /** Create many records at once */\n createMany: (input) => invoke("data.create-many", input),\n /** Delete a record */\n delete: (input) => invoke("data.delete", input),\n /** Delete all records matching filter conditions */\n deleteMany: (input) => invoke("data.delete-many", input),\n /** Find a single record by ID or by filters */\n find: (input) => invoke("data.find", input),\n /** Find a record by attributes, or create a new one when no match exists */\n findOrCreate: (input) => invoke("data.find-or-create", input),\n relation: {\n /** Attach a related record to a singular relation (BelongsTo, HasOne) */\n attach: (input) => invoke("data.relation.attach", input),\n /** Attach related records to a plural relation (BelongsToMany, HasMany) */\n attachMany: (input) => invoke("data.relation.attach-many", input),\n /** Detach a related record. */\n detach: (input) => invoke("data.relation.detach", input),\n /** Detach related records from a plural relation (BelongsToMany, HasMany) */\n detachMany: (input) => invoke("data.relation.detach-many", input),\n /** Sync related records for a relation (replaces all existing) */\n sync: (input) => invoke("data.relation.sync", input)\n },\n /** Restore an archived record */\n restore: (input) => invoke("data.restore", input),\n /** Search for records */\n search: (input) => invoke("data.search", input),\n /** Search for records by semantic similarity */\n semanticSearch: (input) => invoke("data.semantic_search", input),\n /** Sum a numeric field across records matching the filters */\n sum: (input) => invoke("data.sum", input),\n /** Update an existing record found by ID or by filters */\n update: (input) => invoke("data.update", input),\n /** Find a record by attributes and update it, or create a new one */\n updateOrCreate: (input) => invoke("data.update-or-create", input),\n /** Validate a record */\n validate: (input) => invoke("data.validate", input)\n};\nvar date = {\n /** Add N days/weeks/months/years to a date */\n add: (input) => invoke("date.add", input),\n /** Difference between two dates in a specified unit */\n diff: (input) => invoke("date.diff", input),\n /** Snap a date to the end of a period (week, month, quarter, year) */\n endOf: (input) => invoke("date.end_of", input),\n /** Format a date string using ICU date format syntax (e.g., "yyyy-MM-dd", "MMM d, yyyy"). */\n format: (input) => invoke("date.format", input),\n /** Snap a date to the start of a period (week, month, quarter, year) */\n startOf: (input) => invoke("date.start_of", input),\n /** Subtract N days/weeks/months/years from a date */\n subtract: (input) => invoke("date.subtract", input)\n};\nvar file = {\n /** Change a file\'s visibility by moving it between private and public storage */\n changeVisibility: (input) => invoke("file.change_visibility", input),\n /** Download a file from a public http(s) URL and save it privately in the workspace */\n createFromUrl: (input) => invoke("file.create_from_url", input),\n /** 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 */\n createMediaLibraryItem: (input) => invoke("file.create_media_library_item", input),\n /** Generate a QR code PNG image that encodes a value and save it privately in the workspace */\n createQrCode: (input) => invoke("file.create_qr_code", input)\n};\nvar guard = {\n /** Perform a validation check */\n validate: (input) => invoke("guard.validate", input)\n};\nvar http = {\n /** Send an HTTP request */\n request: (input) => invoke("http.request", input)\n};\nvar lifecycle = {\n /** Return modified record fields from a record lifecycle workflow */\n output: (input) => invoke("lifecycle.output", input)\n};\nvar mail = {\n /** 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 */\n search: (input) => invoke("mail.search", input),\n /** Send an email */\n send: (input) => invoke("mail.send", input),\n /** Send an email using a notification type and template */\n sendNotification: (input) => invoke("mail.send-notification", input)\n};\nvar markdown = {\n /** Convert rich Content into a markdown string */\n fromContent: (input) => invoke("markdown.from_content", input),\n /** Convert a markdown string into rich Content. Nodes a destination Content field disallows may be rejected by that field. */\n toContent: (input) => invoke("markdown.to_content", input)\n};\nvar mediaLibrary = {\n /** Create a media library folder */\n createFolder: (input) => invoke("media_library.create_folder", input),\n /** Detach a file from the media library */\n deleteItem: (input) => invoke("media_library.delete_item", input),\n /** Move media library items into a target folder */\n moveItems: (input) => invoke("media_library.move_items", input),\n /** Rename a media library item and/or move it into a folder */\n updateItem: (input) => invoke("media_library.update_item", input)\n};\nvar money = {\n /** Format a money value as a currency string */\n format: (input) => invoke("money.format", input)\n};\nvar notification = {\n /** Send a notification email to a notifiable record */\n send: (input) => invoke("notification.send", input),\n /** Find records with filters and send each record\u2019s notification to the type\u2019s configured recipient resource */\n sendBulkNotifications: (input) => invoke("notification.send-bulk-notifications", input),\n /** Send a notification template to a full record of the type\u2019s recipient resource */\n sendNotification: (input) => invoke("notification.send-notification", input),\n /** Record whether a notifiable record agreed to receive email or SMS */\n setConsent: (input) => invoke("notification.set-consent", input)\n};\nvar number = {\n /** Format a number with configurable decimal places */\n format: (input) => invoke("number.format", input)\n};\nvar package_ = {\n /** Read an input value collected when this package was installed */\n installInput: (input) => invoke("package.install-input", input)\n};\nvar page = {\n /** Get the URL for a page with route parameters */\n url: (input) => invoke("page.url", input)\n};\nvar payables = {\n /** Void an unpaid draft or open invoice. Rejects collected payments and payments in progress. Does not refund payments or cancel subscriptions. */\n void: (input) => invoke("payables.void", input),\n /** Write off all or part of an open invoice while preserving its original total. */\n writeOff: (input) => invoke("payables.write-off", input)\n};\nvar payment = {\n /** Record a manual payment against a payable record */\n createManual: (input) => invoke("payment.create_manual", input)\n};\nvar payments = {\n /** Charge a payable record using the payer default Stripe payment method */\n charge: (input) => invoke("payments.charge", input),\n /** Create a Stripe Checkout session to collect payment against a payable record */\n checkout: (input) => invoke("payments.checkout", input),\n /** 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. */\n confirm: (input) => invoke("payments.confirm", input),\n /** Process a full or partial refund against a payment record */\n refund: (input) => invoke("payments.refund", input)\n};\nvar phone = {\n /** Format a phone number into a human-readable string */\n format: (input) => invoke("phone.format", input)\n};\nvar scheduling = {\n /** 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 */\n bookSlot: (input) => invoke("scheduling.book_slot", input),\n /** 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 */\n findSlots: (input) => invoke("scheduling.find_slots", input)\n};\nvar schema = {\n /** Convert a schema definition into its JSON Schema document \u2014 the shape used to constrain AI and extraction output */\n toJsonSchema: (input) => invoke("schema.to_json_schema", input)\n};\nvar security = {\n /** Generate a secure random password */\n randomPassword: (input) => invoke("security.random_password", input)\n};\nvar sms = {\n /** Send a notification template by SMS to a full record of the type\u2019s recipient resource */\n sendNotification: (input) => invoke("sms.send-notification", input)\n};\nvar subscriptions = {\n /** Start a draft subscription using its snapshotted activation and trial policies */\n activate: (input) => invoke("subscriptions.activate", input),\n /** Cancel a subscription immediately, or at the end of the current billing period */\n cancel: (input) => invoke("subscriptions.cancel", input),\n /** 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. */\n changeItems: (input) => invoke("subscriptions.change_items", input),\n /** Create and activate a subscription for a payer in one step: the record, an item per price, and optionally the first invoice */\n create: (input) => invoke("subscriptions.create", input),\n /** Generate the payable invoice for the saved subscription schedule; partial calendar periods prorate recurring lines and full periods use the original prices */\n generateInvoice: (input) => invoke("subscriptions.generate_invoice", input),\n /** Pause a billing subscription so no further invoices generate until it is resumed */\n pause: (input) => invoke("subscriptions.pause", input),\n /** Preview initial subscription charges, covered dates, and renewal amounts without creating records or collecting payment */\n preview: (input) => invoke("subscriptions.preview", input),\n /** Preview a complete subscription item selection effective now, at the next renewal, or at a later billing period, without changing records */\n previewChange: (input) => invoke("subscriptions.preview_change", input),\n /** Resume a paused subscription; its status re-derives from the latest invoice */\n resume: (input) => invoke("subscriptions.resume", input),\n /** Safely replace the complete price selection that takes effect in the next billing period */\n setUpcomingItems: (input) => invoke("subscriptions.set_upcoming_items", input)\n};\nvar text = {\n /** Generate a random string with configurable character sets */\n generate: (input) => invoke("text.generate", input),\n /** Hash a text value */\n hash: (input) => invoke("text.hash", input),\n /** Generate a random UUID v7 */\n randomUuid: (input) => invoke("text.random_uuid", input),\n /** Convert a plain text string into rich Content */\n toContent: (input) => invoke("text.to_content", input)\n};\nvar time = {\n /** Add N seconds/minutes/hours/days/weeks/months/years to a datetime */\n add: (input) => invoke("time.add", input),\n /** Difference between two datetimes in a specified unit */\n diff: (input) => invoke("time.diff", input),\n /** Snap a datetime to the end of a period (hour, day, week, month, quarter, year) */\n endOf: (input) => invoke("time.end_of", input),\n /** Format a datetime string using ICU date format syntax (e.g., "yyyy-MM-dd HH:mm:ss", "MMM d, yyyy h:mm a"). */\n format: (input) => invoke("time.format", input),\n /** Snap a datetime to the start of a period (hour, day, week, month, quarter, year) */\n startOf: (input) => invoke("time.start_of", input),\n /** Subtract N seconds/minutes/hours/days/weeks/months/years from a datetime */\n subtract: (input) => invoke("time.subtract", input)\n};\nvar timezone = {\n /** 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). */\n format: (input) => invoke("timezone.format", input),\n /** Interpret a local date or datetime in a timezone and return the canonical UTC datetime string. */\n interpret: (input) => invoke("timezone.interpret", input)\n};\nvar tiptap = {\n /** Parse Tiptap content to HTML or text */\n parse: (input) => invoke("tiptap.parse", input)\n};\nvar user = {\n /** Check user permissions for authorization */\n authorize: (input) => invoke("user.authorize", input)\n};\nvar web = {\n /** Extract structured data from a web page, guided by a natural-language prompt and a required shape */\n agent: (input) => invoke("web.agent", input),\n /** Scrape multiple web pages in one batch and poll until every page is finished */\n batchScrape: (input) => invoke("web.batch_scrape", input),\n /** Crawl a site and return multi-page content (polls to completion) */\n crawl: (input) => invoke("web.crawl", input),\n /** Extract structured data from one or more web pages, guided by a required shape and a supporting prompt */\n extract: (input) => invoke("web.extract", input),\n /** Search Google and return the organic results */\n googleSearch: (input) => invoke("web.google_search", input),\n /** Map a site and return all of its discoverable URLs */\n map: (input) => invoke("web.map", input),\n /** Render a web page to a PDF document */\n pdf: (input) => invoke("web.pdf", input),\n /** Scrape a web page in content mode (markdown/HTML plus metadata) or JSON mode (structured data extracted against a schema) */\n scrape: (input) => invoke("web.scrape", input),\n /** Render a web page to a screenshot (PNG, JPEG, or WebP) */\n screenshot: (input) => invoke("web.screenshot", input),\n /** Search the web for a query and return ranked results */\n searchRanked: (input) => invoke("web.search_ranked", input)\n};\nvar workflow = {\n /** Runs a workflow using its published version */\n run: (input) => invoke("workflow.run", input),\n /** Get the URL for a workflow with route parameters */\n url: (input) => invoke("workflow.url", input)\n};\nvar workspace = {\n /** Get the login URL for an authenticatable resource */\n loginUrl: (input) => invoke("workspace.login_url", input),\n /** Set the value of a field in a workspace */\n setValue: (input) => invoke("workspace.set_value", input),\n /** Set multiple workspace field values at once from a key => value map */\n setValues: (input) => invoke("workspace.set_values", input),\n /** Get the value of a field in a workspace */\n value: (input) => invoke("workspace.value", input),\n /** Get all workspace field values as a dictionary */\n values: (input) => invoke("workspace.values", input)\n};\n\n// packages/workflows/src/data.ts\nvar EACH_PAGE_SIZE = 100;\nfunction each(input) {\n const { maxRecords, ...search } = input;\n if (maxRecords !== void 0 && (!Number.isInteger(maxRecords) || maxRecords < 1)) {\n throw new RangeError(`maxRecords must be a positive integer. Received ${maxRecords}.`);\n }\n const query = JSON.parse(JSON.stringify(search));\n return walk(query, maxRecords ?? Number.POSITIVE_INFINITY);\n}\nasync function* walk(query, maxRecords) {\n let remaining = maxRecords;\n let after = null;\n while (remaining > 0) {\n const page2 = await invoke("data.search", {\n ...query,\n paging: "cursor",\n pageSize: Math.min(EACH_PAGE_SIZE, remaining),\n ...after === null ? {} : { after }\n });\n for (const record of page2.data ?? []) {\n yield record;\n remaining--;\n if (remaining === 0) {\n return;\n }\n }\n if (typeof page2.cursor !== "string") {\n return;\n }\n after = page2.cursor;\n }\n}\nvar data2 = {\n ...data,\n create: (input) => invoke("data.create", input),\n find: (input) => invoke("data.find", input),\n update: (input) => invoke("data.update", input),\n search: (input) => invoke("data.search", input),\n each,\n delete: (input) => invoke("data.delete", input),\n restore: (input) => invoke("data.restore", input),\n count: (input) => invoke("data.count", input),\n findOrCreate: (input) => invoke("data.find-or-create", input),\n updateOrCreate: (input) => invoke("data.update-or-create", input),\n createMany: (input) => invoke("data.create-many", input),\n deleteMany: (input) => invoke("data.delete-many", input)\n};\n\n// packages/workflows/src/notifications.ts\nvar mail2 = {\n ...mail,\n sendNotification: (input) => invoke("mail.send-notification", input)\n};\nvar notification2 = {\n ...notification,\n sendNotification: (input) => invoke("notification.send-notification", input),\n sendBulkNotifications: (input) => invoke("notification.send-bulk-notifications", input),\n setConsent: (input) => invoke("notification.set-consent", input)\n};\nvar sms2 = {\n ...sms,\n sendNotification: (input) => invoke("sms.send-notification", input)\n};\nexport {\n HostError,\n InputField,\n InputSchema,\n SDK_VERSION,\n WorkflowFailure,\n ai,\n auth,\n calendar,\n callback,\n chart,\n data2 as data,\n date,\n defineWorkflow,\n fail,\n file,\n guard,\n http,\n invoke,\n lifecycle,\n mail2 as mail,\n markdown,\n mediaLibrary,\n money,\n notification2 as notification,\n number,\n package_ as package,\n page,\n parseWorkflowInput,\n payables,\n payment,\n payments,\n phone,\n redirect,\n respond,\n scheduling,\n schema,\n security,\n setTransport,\n sms2 as sms,\n subscriptions,\n text,\n time,\n timezone,\n tiptap,\n transaction,\n user,\n v,\n validateWorkflowInput,\n validationError,\n web,\n workflow,\n workspace\n};\n', "testing.js": 'import {\n HostError,\n parseWorkflowInput,\n setTransport,\n validateWorkflowInput\n} from "./chunk-W7OQZ5UE.js";\n\n// packages/workflows/src/testing/index.ts\nimport { AsyncLocalStorage } from "node:async_hooks";\nimport { randomUUID } from "node:crypto";\n\n// packages/workflows/src/serial-transaction-transport.ts\nvar PromiseConstructor = Promise;\nvar objectKeys = Object.keys;\nvar isArray = Array.isArray;\nvar SerialTransactionTransport = class {\n constructor(transport) {\n this.transport = transport;\n }\n transport;\n pending = 0;\n settled = null;\n transactionOpen = false;\n closing = false;\n async call(name, input) {\n const begins = name === "transaction.begin";\n const rollsBack = name === "transaction.rollback";\n const ends = rollsBack || name === "transaction.commit";\n if (begins || ends) {\n if (input === null || typeof input !== "object" || isArray(input) || objectKeys(input).length > 0) {\n throw new HostError(\n "Transaction controls accept an empty object.",\n "invalid_arguments",\n 422,\n null\n );\n }\n input = {};\n }\n if (this.closing || (this.transactionOpen || begins) && this.pending > 0 && !rollsBack) {\n throw new HostError(\n "Await each capability call before starting another call while a transaction is active.",\n "transaction_concurrent",\n 409,\n null\n );\n }\n const opens = begins && !this.transactionOpen;\n const closes = ends && this.transactionOpen;\n if (opens) {\n this.transactionOpen = true;\n }\n if (closes) {\n this.closing = true;\n }\n const previous = this.settled;\n let complete;\n let closed = closes;\n try {\n if (rollsBack && closes && previous !== null) {\n await previous;\n }\n this.pending++;\n this.settled = new PromiseConstructor((resolve) => {\n complete = resolve;\n });\n return await this.transport.call(name, input);\n } catch (error) {\n if (closes && error instanceof HostError && (error.code === "invalid_arguments" || error.code === "resolver_not_allowed" || error.code === "capability_denied" || error.code === "payload_too_large" || error.code === "validation" || error.code === "transaction_concurrent")) {\n closed = false;\n }\n if (opens) {\n this.transactionOpen = false;\n }\n throw error;\n } finally {\n if (complete !== void 0) {\n this.pending--;\n complete();\n if (this.pending === 0) {\n this.settled = null;\n }\n }\n if (closes) {\n this.transactionOpen = !closed;\n this.closing = false;\n }\n }\n }\n};\n\n// packages/workflows/src/testing/index.ts\nvar MockTransport = class {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor(handlers) {\n this.handlers = handlers;\n }\n handlers;\n calls = [];\n async call(name, input) {\n this.calls.push({ name, input });\n const handler = this.handlers[name];\n if (handler === void 0) {\n throw new HostError(`No mock for ${name}.`, "capability_denied", 403, null);\n }\n return handler(input);\n }\n};\nvar defaultContext = {\n user: null,\n callingUser: null,\n trigger: {},\n request: null,\n workspace: { id: "local", timezone: "UTC" },\n now: (/* @__PURE__ */ new Date(0)).toISOString()\n};\nvar runTransports = new AsyncLocalStorage();\nvar activeRuns = 0;\nvar runTransport = {\n call(name, input) {\n const transport = runTransports.getStore();\n if (transport === void 0) {\n return Promise.reject(\n new Error(`The ${name} call was made outside the runWorkflow call that owns a transport.`)\n );\n }\n return transport.call(name, input);\n }\n};\nasync function runWorkflow(workflow, input, options = {}) {\n const transport = options.transport ?? new MockTransport({});\n const suppliedExecution = options.context?.execution;\n const workflowId = suppliedExecution && "workflowId" in suppliedExecution && typeof suppliedExecution.workflowId === "string" ? suppliedExecution.workflowId : "local";\n const execution = {\n id: randomUUID(),\n kind: "workflow",\n workflowId,\n owner: { type: "workflow", id: workflowId }\n };\n const context = {\n ...defaultContext,\n ...options.context,\n execution: { ...execution, ...suppliedExecution }\n };\n activeRuns++;\n setTransport(runTransport);\n try {\n return await runTransports.run(new SerialTransactionTransport(transport), async () => {\n const parsed = parseWorkflowInput(workflow, input);\n if (options.validateInput) {\n await validateWorkflowInput(options.validateInput, parsed, context);\n }\n return await workflow.run(parsed, context);\n });\n } finally {\n activeRuns--;\n if (activeRuns === 0) {\n setTransport(null);\n }\n }\n}\nvar seed = 1;\nvar next = () => {\n seed = seed * 16807 % 2147483647;\n return seed;\n};\nvar pick = (values) => values[next() % values.length];\nvar fake = {\n reset() {\n seed = 1;\n return fake;\n },\n email: () => `${pick(["ada", "grace", "alan", "edsger"])}${next() % 1e3}@example.test`,\n name: () => `${pick(["Ada", "Grace", "Alan", "Edsger"])} ${pick(["Lovelace", "Hopper", "Turing", "Dijkstra"])}`,\n uuid: () => "00000000-0000-4000-8000-".concat(String(next()).padStart(12, "0").slice(-12)),\n number: (min = 0, max = 100) => min + next() % (max - min + 1)\n};\nexport {\n MockTransport,\n fake,\n runWorkflow\n};\n', "chunk-W7OQZ5UE.js": '// packages/workflows/src/errors.ts\nvar HostError = class extends Error {\n /**\n * @param failureId The host\'s ID for the failure of the call. When the error ends the run, the\n * host records that failure, so a run records the failure of the call that it rethrows.\n */\n constructor(message, code, status, details, failureId = null) {\n super(message);\n this.code = code;\n this.status = status;\n this.details = details;\n this.failureId = failureId;\n this.name = "HostError";\n }\n code;\n status;\n details;\n failureId;\n};\nvar WorkflowFailure = class extends Error {\n constructor(message, status, details = null) {\n super(message);\n this.status = status;\n this.details = details;\n this.name = "WorkflowFailure";\n }\n status;\n details;\n};\nfunction fail(message, options = {}) {\n throw new WorkflowFailure(message, options.status ?? 400, options.details ?? null);\n}\nfunction validationError(errors, options = {}) {\n throw new WorkflowFailure(options.message ?? "The given data was invalid.", 422, { errors });\n}\n\n// packages/workflows/src/transport.ts\nvar active = null;\nfunction setTransport(transport) {\n active = transport;\n}\nfunction invoke(name, input) {\n if (active === null) {\n return Promise.reject(\n new Error(\n "No Diagonal host transport is set. In tests, call setTransport(new MockTransport(...))."\n )\n );\n }\n return active.call(name, input);\n}\n\n// packages/workflows/src/input.ts\nvar InputField = class _InputField {\n constructor($spec) {\n this.$spec = $spec;\n }\n $spec;\n /** The key may be absent. */\n optional() {\n return new _InputField({ ...this.$spec, optional: true });\n }\n /** The value may be `null`. */\n nullable() {\n return new _InputField({ ...this.$spec, nullable: true });\n }\n /** At least `value`: a number\'s value, a text\'s length, or a list\'s item count. */\n min(value) {\n return this.rule(`min:${value}`);\n }\n /** At most `value`: a number\'s value, a text\'s length, or a list\'s item count. */\n max(value) {\n return this.rule(`max:${value}`);\n }\n /** Between `min` and `max`, inclusive, measured as for `min` and `max`. */\n between(min, max) {\n return this.rule(`between:${min},${max}`);\n }\n /** Exactly `value`, measured as for `min` and `max`. */\n size(value) {\n return this.rule(`size:${value}`);\n }\n /** The text matches the pattern. */\n regex(pattern) {\n return this.rule(`regex:/${pattern.source}/${pattern.flags}`);\n }\n /** Any other platform validation rule, such as `starts_with:INV-` or `after:today`. */\n rule(rule) {\n return new _InputField({ ...this.$spec, rules: [...this.$spec.rules, rule] });\n }\n label(label) {\n return new _InputField({ ...this.$spec, label });\n }\n description(description) {\n return new _InputField({ ...this.$spec, description });\n }\n};\nvar InputSchema = class extends InputField {\n constructor(shape) {\n super(objectSpec(shape));\n this.shape = shape;\n }\n shape;\n};\nfunction objectSpec(shape) {\n return {\n kind: "object",\n optional: false,\n nullable: false,\n rules: [],\n fields: Object.fromEntries(Object.entries(shape).map(([key, field2]) => [key, field2.$spec]))\n };\n}\nvar field = (kind, extra = {}) => new InputField({ kind, optional: false, nullable: false, rules: [], ...extra });\nvar v = {\n text: () => field("text"),\n email: () => field("email"),\n url: () => field("url"),\n uuid: () => field("uuid"),\n phone: () => field("phone"),\n /** A calendar date, `YYYY-MM-DD`. */\n date: () => field("date"),\n /** A date and time, ISO 8601. */\n datetime: () => field("datetime"),\n /** A time of day, `HH:MM`. */\n time: () => field("time"),\n timezone: () => field("timezone"),\n color: () => field("color"),\n number: () => field("number"),\n integer: () => field("integer"),\n /** An amount of money: `amount` in the currency\'s minor units, such as cents, and the lowercase ISO 4217 `currency`. */\n money: () => field("money"),\n boolean: () => field("boolean"),\n /** One of `options`. */\n select: (options) => field("select", { options }),\n /** A list whose items each satisfy `items`. */\n list: (items) => field("list", { items: items.$spec }),\n /** An object with the given fields. */\n object: (shape) => new InputSchema(shape),\n /**\n * The field values of a record of `resource`, checked against that resource\'s field\n * definitions: types, required fields, and each field\'s own rules.\n */\n record: (resource) => field("record", { resource }),\n /** The ID of an existing record of `resource`, in `scope`. */\n recordReference: (resource, options = {}) => field("recordReference", { resource, ...options }),\n /** The ID of an existing role. */\n roleReference: () => field("roleReference"),\n /**\n * A file: the ID of an existing file, or the temporary path of an upload. A data call that\n * writes the value to a file field of a record finalizes the upload.\n */\n file: (options = {}) => field("file", options),\n /** A rich text document with the formatting that `options` allows. */\n content: (options = {}) => field("content", Object.keys(options).length === 0 ? {} : { content: options })\n};\nvar NUMERIC = /^-?(\\d+\\.?\\d*|\\.\\d+)(e[-+]?\\d+)?$/i;\nfunction coerceNumber(value) {\n return typeof value === "string" && NUMERIC.test(value.trim()) ? Number(value) : value;\n}\nfunction coerceInput(spec, value) {\n if (value === null || value === void 0) {\n return value;\n }\n switch (spec.kind) {\n case "number":\n case "integer":\n return coerceNumber(value);\n case "money":\n return typeof value === "object" && !Array.isArray(value) && "amount" in value ? { ...value, amount: coerceNumber(value.amount) } : value;\n case "boolean":\n if (value === "true" || value === "1" || value === 1) {\n return true;\n }\n return value === "false" || value === "0" || value === 0 ? false : value;\n case "select":\n return typeof value === "string" && !spec.options?.includes(value) && spec.options?.includes(Number(value)) ? Number(value) : value;\n case "list":\n return Array.isArray(value) && spec.items ? value.map((item) => coerceInput(spec.items, item)) : value;\n case "object": {\n if (typeof value !== "object" || Array.isArray(value) || !spec.fields) {\n return value;\n }\n const result = { ...value };\n for (const [key, fieldSpec] of Object.entries(spec.fields)) {\n if (key in result) {\n result[key] = coerceInput(fieldSpec, result[key]);\n }\n }\n return result;\n }\n default:\n return value;\n }\n}\n\n// packages/workflows/src/workflow.ts\nfunction parseWorkflowInput(workflow, input) {\n return workflow.input === void 0 ? input : coerceInput(workflow.input, input);\n}\nasync function validateWorkflowInput(validator, input, ctx) {\n const reported = await validator(input, ctx);\n if (reported === void 0 || reported === null) {\n return;\n }\n if (typeof reported !== "object" || Array.isArray(reported)) {\n throw new TypeError(\n "validateInput must return an object of errors keyed by field, or nothing."\n );\n }\n const errors = {};\n for (const [field2, messages] of Object.entries(reported)) {\n const list = (Array.isArray(messages) ? messages : [messages]).filter(\n (message) => typeof message === "string" && message !== ""\n );\n if (list.length > 0) {\n errors[field2] = list;\n }\n }\n if (Object.keys(errors).length > 0) {\n validationError(errors);\n }\n}\nfunction defineWorkflow(inputOrHandler, maybeHandler) {\n if (typeof inputOrHandler === "function") {\n return { $diagonal: "workflow", run: async (input, ctx) => inputOrHandler(input, ctx) };\n }\n const spec = inputOrHandler.$spec;\n const handler = maybeHandler;\n if (handler === void 0) {\n throw new TypeError("defineWorkflow(input, handler) needs a handler after the input schema.");\n }\n return {\n $diagonal: "workflow",\n input: spec,\n run: async (input, ctx) => handler(input, ctx)\n };\n}\nfunction respond(body, options = {}) {\n return {\n $response_status: options.status ?? 200,\n $response_body: body,\n $response_content_type: options.contentType ?? "application/json"\n };\n}\nfunction redirect(url, options = {}) {\n const type = options.type ?? (/^\\/(?![/\\\\])/.test(url) ? "internal" : "external");\n const output = {\n redirect_url: url,\n redirect_type: type,\n permanent: type !== "back" && options.permanent === true\n };\n if (options.success !== void 0) {\n output.success = options.success;\n }\n return output;\n}\n\nexport {\n HostError,\n WorkflowFailure,\n fail,\n validationError,\n setTransport,\n invoke,\n InputField,\n InputSchema,\n v,\n parseWorkflowInput,\n validateWorkflowInput,\n defineWorkflow,\n respond,\n redirect\n};\n' };
|
|
58
58
|
}
|
|
59
59
|
});
|
|
60
60
|
|
|
@@ -247285,7 +247285,7 @@ import type { ResourceKeyWith } from '../data';
|
|
|
247285
247285
|
import type { ContentDocument } from '../input';
|
|
247286
247286
|
import { invoke } from '../transport';
|
|
247287
247287
|
|
|
247288
|
-
export const SDK_VERSION =
|
|
247288
|
+
export const SDK_VERSION = 56;
|
|
247289
247289
|
|
|
247290
247290
|
export interface AiDecideInput {
|
|
247291
247291
|
state: unknown;
|
|
@@ -248339,7 +248339,7 @@ export const file = {
|
|
|
248339
248339
|
changeVisibility: (input: FileChangeVisibilityInput): Promise<FileChangeVisibilityOutput> => invoke('file.change_visibility', input),
|
|
248340
248340
|
/** Download a file from a public http(s) URL and save it privately in the workspace */
|
|
248341
248341
|
createFromUrl: (input: FileCreateFromUrlInput): Promise<FileCreateFromUrlOutput> => invoke('file.create_from_url', input),
|
|
248342
|
-
/** Create a public library master from an accessible workspace file, preserving external sources. Returns the library File ID */
|
|
248342
|
+
/** 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 */
|
|
248343
248343
|
createMediaLibraryItem: (input: FileCreateMediaLibraryItemInput): Promise<FileCreateMediaLibraryItemOutput> => invoke('file.create_media_library_item', input),
|
|
248344
248344
|
/** Generate a QR code PNG image that encodes a value and save it privately in the workspace */
|
|
248345
248345
|
createQrCode: (input: FileCreateQrCodeInput): Promise<FileCreateQrCodeOutput> => invoke('file.create_qr_code', input),
|
|
@@ -249236,7 +249236,10 @@ import { resolve as resolve5 } from "node:path";
|
|
|
249236
249236
|
init_define_globalThis_DIAGONAL_SDK_RUNTIME();
|
|
249237
249237
|
var WORKFLOWS_USAGE = "Usage: diagonal workflows [--json]";
|
|
249238
249238
|
var RUN_USAGE = "Usage: diagonal run <path> [--input '<json object>'] [--json]";
|
|
249239
|
+
var LOGS_USAGE = "Usage: diagonal logs [path | execution id] [--status <success|error|exception|started|pending>] [--limit <1-100>] [--json]";
|
|
249239
249240
|
var SUCCESS = "execution.success";
|
|
249241
|
+
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
249242
|
+
var STATUSES = ["success", "error", "exception", "started", "pending"];
|
|
249240
249243
|
function credentials(env2, stderr) {
|
|
249241
249244
|
const url = env2.DIAGONAL_URL?.trim().replace(/\/+$/, "") ?? "";
|
|
249242
249245
|
const apiKey = env2.DIAGONAL_API_KEY?.trim() ?? "";
|
|
@@ -249369,7 +249372,9 @@ function parseRunArguments(args) {
|
|
|
249369
249372
|
return parsed;
|
|
249370
249373
|
}
|
|
249371
249374
|
if (parsed.positional.length !== 1) {
|
|
249372
|
-
return {
|
|
249375
|
+
return {
|
|
249376
|
+
error: "Give one workflow path, for example workflows/seed-catalog.ts"
|
|
249377
|
+
};
|
|
249373
249378
|
}
|
|
249374
249379
|
const json = parsed.booleans.has("--json");
|
|
249375
249380
|
const path = parsed.positional[0].replace(/^\.\//, "");
|
|
@@ -249427,6 +249432,131 @@ ${RUN_USAGE}
|
|
|
249427
249432
|
}
|
|
249428
249433
|
return succeeded ? 0 : 1;
|
|
249429
249434
|
}
|
|
249435
|
+
function parseLogsArguments(args) {
|
|
249436
|
+
const parsed = parseFlags(args, ["--status", "--limit"], ["--json"]);
|
|
249437
|
+
if (parsed.error !== void 0) {
|
|
249438
|
+
return parsed;
|
|
249439
|
+
}
|
|
249440
|
+
if (parsed.positional.length > 1) {
|
|
249441
|
+
return { error: "Give at most one workflow path or execution id" };
|
|
249442
|
+
}
|
|
249443
|
+
const target = parsed.positional[0]?.replace(/^\.\//, "") ?? null;
|
|
249444
|
+
const status = parsed.values["--status"] ?? null;
|
|
249445
|
+
const rawLimit = parsed.values["--limit"];
|
|
249446
|
+
const limit = rawLimit === void 0 ? null : Number(rawLimit);
|
|
249447
|
+
if (status !== null && !STATUSES.includes(status)) {
|
|
249448
|
+
return { error: `--status must be one of ${STATUSES.join(", ")}` };
|
|
249449
|
+
}
|
|
249450
|
+
if (limit !== null && (!Number.isInteger(limit) || limit < 1 || limit > 100)) {
|
|
249451
|
+
return { error: "--limit must be a whole number from 1 to 100" };
|
|
249452
|
+
}
|
|
249453
|
+
const execution = target !== null && UUID.test(target) ? target : null;
|
|
249454
|
+
if (execution !== null && (status !== null || limit !== null)) {
|
|
249455
|
+
return {
|
|
249456
|
+
error: "--status and --limit apply to a list of runs, not to one execution"
|
|
249457
|
+
};
|
|
249458
|
+
}
|
|
249459
|
+
return {
|
|
249460
|
+
execution,
|
|
249461
|
+
path: execution === null ? target : null,
|
|
249462
|
+
status,
|
|
249463
|
+
limit,
|
|
249464
|
+
json: parsed.booleans.has("--json")
|
|
249465
|
+
};
|
|
249466
|
+
}
|
|
249467
|
+
function runDuration(run) {
|
|
249468
|
+
if (run.duration_ms === null || run.duration_ms === void 0) {
|
|
249469
|
+
return "";
|
|
249470
|
+
}
|
|
249471
|
+
return run.duration_ms < 1e3 ? `${run.duration_ms}ms` : `${(run.duration_ms / 1e3).toFixed(1)}s`;
|
|
249472
|
+
}
|
|
249473
|
+
function errorLines(error, indent) {
|
|
249474
|
+
if (error === null || error === void 0) {
|
|
249475
|
+
return [];
|
|
249476
|
+
}
|
|
249477
|
+
const lines = [`${indent}${error.type ?? "Error"}: ${error.message ?? "(no message)"}`];
|
|
249478
|
+
const fieldErrors = Array.isArray(error.errors) ? error.errors : Object.entries(error.errors ?? {});
|
|
249479
|
+
for (const [field2, messages] of fieldErrors) {
|
|
249480
|
+
for (const message of Array.isArray(messages) ? messages : [messages]) {
|
|
249481
|
+
lines.push(`${indent} ${field2}: ${message}`);
|
|
249482
|
+
}
|
|
249483
|
+
}
|
|
249484
|
+
return lines;
|
|
249485
|
+
}
|
|
249486
|
+
function runLine(run) {
|
|
249487
|
+
const trigger = run.trigger?.request_path ?? run.trigger?.type ?? "";
|
|
249488
|
+
const status = run.response_status_code === null ? run.status : `${run.status} ${run.response_status_code}`;
|
|
249489
|
+
return [run.started_at, status, run.path, trigger, runDuration(run), run.execution_id].filter((part) => part !== "").join(" ");
|
|
249490
|
+
}
|
|
249491
|
+
async function showLogs(args, { env: env2, stdout, stderr }) {
|
|
249492
|
+
const parsed = parseLogsArguments(args);
|
|
249493
|
+
if (parsed.error !== void 0) {
|
|
249494
|
+
stderr.write(`${parsed.error}
|
|
249495
|
+
${LOGS_USAGE}
|
|
249496
|
+
`);
|
|
249497
|
+
return 2;
|
|
249498
|
+
}
|
|
249499
|
+
const target = credentials(env2, stderr);
|
|
249500
|
+
if (target === null) {
|
|
249501
|
+
return 2;
|
|
249502
|
+
}
|
|
249503
|
+
if (parsed.execution !== null) {
|
|
249504
|
+
const run = await request(
|
|
249505
|
+
target,
|
|
249506
|
+
"GET",
|
|
249507
|
+
`/api/runtime/executions/${parsed.execution}`,
|
|
249508
|
+
void 0,
|
|
249509
|
+
stderr
|
|
249510
|
+
);
|
|
249511
|
+
if (run === null) {
|
|
249512
|
+
return 1;
|
|
249513
|
+
}
|
|
249514
|
+
if (parsed.json) {
|
|
249515
|
+
stdout.write(`${JSON.stringify(run, null, 2)}
|
|
249516
|
+
`);
|
|
249517
|
+
return 0;
|
|
249518
|
+
}
|
|
249519
|
+
stdout.write(`${runLine(run)}
|
|
249520
|
+
`);
|
|
249521
|
+
if (run.error !== null) {
|
|
249522
|
+
stdout.write(`${JSON.stringify(run.error, null, 2)}
|
|
249523
|
+
`);
|
|
249524
|
+
} else if (run.output !== null) {
|
|
249525
|
+
stdout.write(`${JSON.stringify(run.output, null, 2)}
|
|
249526
|
+
`);
|
|
249527
|
+
}
|
|
249528
|
+
return 0;
|
|
249529
|
+
}
|
|
249530
|
+
const query = new URLSearchParams();
|
|
249531
|
+
if (parsed.path !== null) {
|
|
249532
|
+
query.set("workflow", parsed.path);
|
|
249533
|
+
}
|
|
249534
|
+
if (parsed.status !== null) {
|
|
249535
|
+
query.set("status", parsed.status);
|
|
249536
|
+
}
|
|
249537
|
+
if (parsed.limit !== null) {
|
|
249538
|
+
query.set("limit", String(parsed.limit));
|
|
249539
|
+
}
|
|
249540
|
+
const suffix = query.size === 0 ? "" : `?${query}`;
|
|
249541
|
+
const body = await request(target, "GET", `/api/runtime/executions${suffix}`, void 0, stderr);
|
|
249542
|
+
if (body === null) {
|
|
249543
|
+
return 1;
|
|
249544
|
+
}
|
|
249545
|
+
if (parsed.json) {
|
|
249546
|
+
stdout.write(`${JSON.stringify(body, null, 2)}
|
|
249547
|
+
`);
|
|
249548
|
+
return 0;
|
|
249549
|
+
}
|
|
249550
|
+
if (body.data.length === 0) {
|
|
249551
|
+
stdout.write("No runs.\n");
|
|
249552
|
+
return 0;
|
|
249553
|
+
}
|
|
249554
|
+
for (const run of [...body.data].reverse()) {
|
|
249555
|
+
stdout.write(`${[runLine(run), ...errorLines(run.error, " ")].join("\n")}
|
|
249556
|
+
`);
|
|
249557
|
+
}
|
|
249558
|
+
return 0;
|
|
249559
|
+
}
|
|
249430
249560
|
|
|
249431
249561
|
// scripts/lib/runtime-build/assets-cli.mjs
|
|
249432
249562
|
init_define_globalThis_DIAGONAL_SDK_RUNTIME();
|
|
@@ -302698,6 +302828,7 @@ var USAGE = [
|
|
|
302698
302828
|
CHECK_USAGE,
|
|
302699
302829
|
WORKFLOWS_USAGE,
|
|
302700
302830
|
RUN_USAGE,
|
|
302831
|
+
LOGS_USAGE,
|
|
302701
302832
|
ASSETS_UPLOAD_USAGE,
|
|
302702
302833
|
ASSETS_LIST_USAGE
|
|
302703
302834
|
].join("\n");
|
|
@@ -302772,6 +302903,8 @@ ${ASSETS_LIST_USAGE}
|
|
|
302772
302903
|
return listWorkflows(args, io);
|
|
302773
302904
|
case "run":
|
|
302774
302905
|
return runWorkflow(args, io);
|
|
302906
|
+
case "logs":
|
|
302907
|
+
return showLogs(args, io);
|
|
302775
302908
|
default:
|
|
302776
302909
|
io.stderr.write(`${USAGE}
|
|
302777
302910
|
`);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { ResourceKeyWith } from '../data';
|
|
2
2
|
import type { ContentDocument } from '../input';
|
|
3
|
-
export declare const SDK_VERSION =
|
|
3
|
+
export declare const SDK_VERSION = 56;
|
|
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>;
|