@diagonal-hq/cli 0.11.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.mjs +365 -114
- package/dist/workflow/generated/capabilities.d.ts +1 -1
- package/package.json +1 -1
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 = 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' };
|
|
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 = 57;\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
|
|
|
@@ -4640,7 +4640,7 @@ var require_globals2 = __commonJS({
|
|
|
4640
4640
|
var require_typescript = __commonJS({
|
|
4641
4641
|
"node_modules/typescript/lib/typescript.js"(exports, module) {
|
|
4642
4642
|
init_define_globalThis_DIAGONAL_SDK_RUNTIME();
|
|
4643
|
-
var
|
|
4643
|
+
var ts8 = {};
|
|
4644
4644
|
((module2) => {
|
|
4645
4645
|
"use strict";
|
|
4646
4646
|
var __defProp2 = Object.defineProperty;
|
|
@@ -216159,9 +216159,9 @@ Additional information: BADCLIENT: Bad error code, ${badCode} not found in range
|
|
|
216159
216159
|
};
|
|
216160
216160
|
}
|
|
216161
216161
|
})({ get exports() {
|
|
216162
|
-
return
|
|
216162
|
+
return ts8;
|
|
216163
216163
|
}, set exports(v) {
|
|
216164
|
-
|
|
216164
|
+
ts8 = v;
|
|
216165
216165
|
if (typeof module !== "undefined" && module.exports) {
|
|
216166
216166
|
module.exports = v;
|
|
216167
216167
|
}
|
|
@@ -244490,9 +244490,9 @@ var require_resolve_block_scalar = __commonJS({
|
|
|
244490
244490
|
default: {
|
|
244491
244491
|
const message = `Unexpected token in block scalar header: ${token.type}`;
|
|
244492
244492
|
onError(token, "UNEXPECTED_TOKEN", message);
|
|
244493
|
-
const
|
|
244494
|
-
if (
|
|
244495
|
-
length +=
|
|
244493
|
+
const ts8 = token.source;
|
|
244494
|
+
if (ts8 && typeof ts8 === "string")
|
|
244495
|
+
length += ts8.length;
|
|
244496
244496
|
}
|
|
244497
244497
|
}
|
|
244498
244498
|
}
|
|
@@ -244804,9 +244804,9 @@ var require_compose_scalar = __commonJS({
|
|
|
244804
244804
|
if (schema.compat) {
|
|
244805
244805
|
const compat = schema.compat.find((tag2) => tag2.default && tag2.test?.test(value)) ?? schema[identity.SCALAR];
|
|
244806
244806
|
if (tag.tag !== compat.tag) {
|
|
244807
|
-
const
|
|
244807
|
+
const ts8 = directives.tagString(tag.tag);
|
|
244808
244808
|
const cs = directives.tagString(compat.tag);
|
|
244809
|
-
const msg = `Value may be parsed as either ${
|
|
244809
|
+
const msg = `Value may be parsed as either ${ts8} or ${cs}`;
|
|
244810
244810
|
onError(token, "TAG_RESOLVE_FAILED", msg, true);
|
|
244811
244811
|
}
|
|
244812
244812
|
}
|
|
@@ -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 = 57;
|
|
247289
247289
|
|
|
247290
247290
|
export interface AiDecideInput {
|
|
247291
247291
|
state: unknown;
|
|
@@ -248587,7 +248587,7 @@ export const workspace = {
|
|
|
248587
248587
|
values: (input: WorkspaceValuesInput): Promise<WorkspaceValuesOutput> => invoke('workspace.values', input),
|
|
248588
248588
|
};
|
|
248589
248589
|
|
|
248590
|
-
`, "/sdk/index.ts": "import './console';\n\nexport { HostError, WorkflowFailure, fail, validationError } from './errors';\nexport { invoke, setTransport, type HostTransport } from './transport';\nexport { transaction } from './transaction';\nexport { data } from './data';\nexport { mail, notification, sms } from './notifications';\nexport {\n InputField,\n InputSchema,\n v,\n type ContentDocument,\n type ContentNode,\n type ContentOptions,\n type FileVisibility,\n type Infer,\n type InferInput,\n type InputFieldKind,\n type InputFieldSpec,\n type InputShape,\n type Money,\n type RecordScope\n} from './input';\nexport {\n defineWorkflow,\n parseWorkflowInput,\n redirect,\n respond,\n validateWorkflowInput,\n type Identity,\n type InputErrors,\n type InputValidator,\n type RequestContext,\n type ScriptExecution,\n type WorkflowContext,\n type WorkflowDefinition,\n type WorkflowExecution\n} from './workflow';\nexport * from './generated/capabilities';\n\n/** The embedding host selects its execution context through its supplied declarations. */\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface ScriptHostContext {}\n\n/** Declaration-merged by the generated workspace module with one entry per resource. */\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface WorkspaceResources {}\n\n/**\n * Declaration-merged by the generated workspace module with one entry per notification type:\n * its id, the unions of its template ids (all, email-enabled, and SMS-enabled), and the shape\n * of its variables.\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface WorkspaceNotificationTypes {}\n", "/sdk/input.ts": "import type { InputOf, ResourceKey } from './data';\n\n/**\n * A declared input field, as data. The compiler reads a workflow's input schema from its source\n * and saves each field as a workflow input variable, so the platform validates a run's input\n * against these rules before the script starts. The same data travels with the workflow at run\n * time, where the SDK uses it to coerce string values to the declared types.\n */\nexport interface InputFieldSpec {\n readonly kind: InputFieldKind;\n readonly optional: boolean;\n readonly nullable: boolean;\n /** Validation rules in the platform's rule syntax, such as `min:1` or `regex:/^[a-z]+$/`. */\n readonly rules: readonly string[];\n readonly label?: string;\n readonly description?: string;\n /** `select`: the allowed values. */\n readonly options?: readonly (string | number)[];\n /** `list`: the item field. */\n readonly items?: InputFieldSpec;\n /** `object`: the nested fields. */\n readonly fields?: Readonly<Record<string, InputFieldSpec>>;\n /** `record` and `recordReference`: the resource whose definitions or records the value must match. */\n readonly resource?: string;\n /** `recordReference`: the records the ID can name. The platform default is `active`. */\n readonly scope?: RecordScope;\n /** `file`: the accepted MIME types. */\n readonly accept?: readonly string[];\n /** `file`: the visibility of the file. */\n readonly visibility?: FileVisibility;\n /** `content`: the formatting the document may use. */\n readonly content?: ContentOptions;\n}\n\n/**\n * A money value as the platform stores it. It is a type alias, not an interface, so that it is\n * assignable to the open money objects of capability inputs such as `money.format`.\n */\nexport type Money = {\n amount: number;\n currency: string;\n};\n\nexport type InputFieldKind =\n | 'text'\n | 'email'\n | 'url'\n | 'uuid'\n | 'phone'\n | 'date'\n | 'datetime'\n | 'time'\n | 'timezone'\n | 'color'\n | 'number'\n | 'integer'\n | 'money'\n | 'boolean'\n | 'select'\n | 'list'\n | 'object'\n | 'record'\n | 'recordReference'\n | 'roleReference'\n | 'file'\n | 'content';\n\n/** The records a record ID can name: `active`, `archived` (deleted), or `activeOrArchived` (all). */\nexport type RecordScope = 'active' | 'archived' | 'activeOrArchived';\n\nexport type FileVisibility = 'public' | 'private';\n\nexport interface ContentOptions {\n /** `false` allows one paragraph only. The default is `true`. */\n readonly multiLine?: boolean;\n /** The marks the text may use. Each mark is allowed unless it is `false`. */\n readonly extensions?: Readonly<\n Partial<Record<'bold' | 'italic' | 'strike' | 'underline' | 'link', boolean>>\n >;\n /** The block nodes the document may use. Each node is allowed unless it is `false`. */\n readonly allowedNodes?: Readonly<\n Partial<Record<'heading' | 'blockquote' | 'bulletList' | 'orderedList' | 'media', boolean>>\n >;\n}\n\n/** A rich text node in the platform's content format. */\nexport interface ContentNode {\n type: string;\n attrs?: Record<string, unknown>;\n content?: ContentNode[];\n marks?: { type: string; attrs?: Record<string, unknown> }[];\n text?: string;\n}\n\n/** A rich text document in the platform's content format. */\nexport interface ContentDocument extends ContentNode {\n type: 'doc';\n}\n\n/**\n * One field of a workflow's input schema. `T` is the value type the handler receives; `O` is\n * whether the key may be absent. Every modifier returns a new field, so a field can be shared.\n */\nexport class InputField<T, O extends boolean = false> {\n /** Phantom members that carry the static types; they hold no value at run time. */\n declare readonly $value: T;\n declare readonly $optional: O;\n\n constructor(readonly $spec: InputFieldSpec) {}\n\n /** The key may be absent. */\n optional(): InputField<T | undefined, true> {\n return new InputField({ ...this.$spec, optional: true });\n }\n\n /** The value may be `null`. */\n nullable(): InputField<T | null, O> {\n return new InputField({ ...this.$spec, nullable: true });\n }\n\n /** At least `value`: a number's value, a text's length, or a list's item count. */\n min(value: number): InputField<T, O> {\n return this.rule(`min:${value}`);\n }\n\n /** At most `value`: a number's value, a text's length, or a list's item count. */\n max(value: number): InputField<T, O> {\n return this.rule(`max:${value}`);\n }\n\n /** Between `min` and `max`, inclusive, measured as for `min` and `max`. */\n between(min: number, max: number): InputField<T, O> {\n return this.rule(`between:${min},${max}`);\n }\n\n /** Exactly `value`, measured as for `min` and `max`. */\n size(value: number): InputField<T, O> {\n return this.rule(`size:${value}`);\n }\n\n /** The text matches the pattern. */\n regex(pattern: RegExp): InputField<T, O> {\n return this.rule(`regex:/${pattern.source}/${pattern.flags}`);\n }\n\n /** Any other platform validation rule, such as `starts_with:INV-` or `after:today`. */\n rule(rule: string): InputField<T, O> {\n return new InputField({ ...this.$spec, rules: [...this.$spec.rules, rule] });\n }\n\n label(label: string): InputField<T, O> {\n return new InputField({ ...this.$spec, label });\n }\n\n description(description: string): InputField<T, O> {\n return new InputField({ ...this.$spec, description });\n }\n}\n\nexport type InputShape = Record<string, InputField<unknown, boolean>>;\n\ntype Simplify<T> = { [K in keyof T]: T[K] } & {};\n\n/** The value an input schema describes: optional fields become optional keys. */\nexport type InferInput<S extends InputShape> = Simplify<\n { [K in keyof S as S[K]['$optional'] extends true ? never : K]: S[K]['$value'] } & {\n [K in keyof S as S[K]['$optional'] extends true ? K : never]?: S[K]['$value'];\n }\n>;\n\n/** The value a field or schema describes: `Infer<typeof Input>`. */\nexport type Infer<F extends InputField<unknown, boolean>> = F['$value'];\n\n/** A workflow's input schema: the fields of an object. */\nexport class InputSchema<S extends InputShape> extends InputField<InferInput<S>> {\n constructor(readonly shape: S) {\n super(objectSpec(shape));\n }\n}\n\nfunction objectSpec(shape: InputShape): InputFieldSpec {\n return {\n kind: 'object',\n optional: false,\n nullable: false,\n rules: [],\n fields: Object.fromEntries(Object.entries(shape).map(([key, field]) => [key, field.$spec]))\n };\n}\n\nconst field = <T>(kind: InputFieldKind, extra: Partial<InputFieldSpec> = {}): InputField<T> =>\n new InputField<T>({ kind, optional: false, nullable: false, rules: [], ...extra });\n\n/** Builders for a workflow's input schema. */\nexport const v = {\n text: () => field<string>('text'),\n email: () => field<string>('email'),\n url: () => field<string>('url'),\n uuid: () => field<string>('uuid'),\n phone: () => field<string>('phone'),\n /** A calendar date, `YYYY-MM-DD`. */\n date: () => field<string>('date'),\n /** A date and time, ISO 8601. */\n datetime: () => field<string>('datetime'),\n /** A time of day, `HH:MM`. */\n time: () => field<string>('time'),\n timezone: () => field<string>('timezone'),\n color: () => field<string>('color'),\n number: () => field<number>('number'),\n integer: () => field<number>('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>('money'),\n boolean: () => field<boolean>('boolean'),\n /** One of `options`. */\n select: <const V extends readonly (string | number)[]>(options: V) =>\n field<V[number]>('select', { options }),\n /** A list whose items each satisfy `items`. */\n list: <T>(items: InputField<T, boolean>) =>\n field<Exclude<T, undefined>[]>('list', { items: items.$spec }),\n /** An object with the given fields. */\n object: <S extends InputShape>(shape: S) => 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: <R extends ResourceKey>(resource: R) => field<InputOf<R>>('record', { resource }),\n /** The ID of an existing record of `resource`, in `scope`. */\n recordReference: <R extends ResourceKey>(resource: R, options: { scope?: RecordScope } = {}) =>\n field<string>('recordReference', { resource, ...options }),\n /** The ID of an existing role. */\n roleReference: () => field<string>('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: { accept?: readonly string[]; visibility?: FileVisibility } = {}) =>\n field<string>('file', options),\n /** A rich text document with the formatting that `options` allows. */\n content: (options: ContentOptions = {}) =>\n field<ContentDocument>('content', Object.keys(options).length === 0 ? {} : { content: options })\n};\n\nconst NUMERIC = /^-?(\\d+\\.?\\d*|\\.\\d+)(e[-+]?\\d+)?$/i;\n\nfunction coerceNumber(value: unknown): unknown {\n return typeof value === 'string' && NUMERIC.test(value.trim()) ? Number(value) : value;\n}\n\n/**\n * Converts the string forms a request carries (`\"5\"`, `\"true\"`) to the declared types. It runs\n * after the platform validated the input against the same schema, so a value it cannot convert\n * is left as it is.\n */\nexport function coerceInput(spec: InputFieldSpec, value: unknown): unknown {\n if (value === null || value === undefined) {\n return value;\n }\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\n ? { ...value, amount: coerceNumber(value.amount) }\n : value;\n case 'boolean':\n if (value === 'true' || value === '1' || value === 1) {\n return true;\n }\n\n return value === 'false' || value === '0' || value === 0 ? false : value;\n case 'select':\n return typeof value === 'string' &&\n !spec.options?.includes(value) &&\n spec.options?.includes(Number(value))\n ? Number(value)\n : value;\n case 'list':\n return Array.isArray(value) && spec.items\n ? value.map((item) => coerceInput(spec.items!, item))\n : value;\n case 'object': {\n if (typeof value !== 'object' || Array.isArray(value) || !spec.fields) {\n return value;\n }\n\n const result: Record<string, unknown> = { ...(value as Record<string, unknown>) };\n\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\n return result;\n }\n default:\n return value;\n }\n}\n", "/sdk/notifications.ts": "import type { ResourceKey } from './data';\nimport {\n mail as generatedMail,\n notification as generatedNotification,\n sms as generatedSms,\n type MailSendNotificationInput,\n type MailSendNotificationOutput,\n type NotificationSendBulkNotificationsInput,\n type NotificationSendBulkNotificationsOutput,\n type NotificationSendNotificationInput,\n type NotificationSendNotificationOutput,\n type NotificationSetConsentInput,\n type NotificationSetConsentOutput,\n type SmsSendNotificationInput,\n type SmsSendNotificationOutput\n} from './generated/capabilities';\nimport type { WorkspaceNotificationTypes } from './index';\nimport { invoke } from './transport';\n\ntype Entry = WorkspaceNotificationTypes[keyof WorkspaceNotificationTypes];\ntype Declared = [keyof WorkspaceNotificationTypes] extends [never] ? false : true;\nexport type NotificationTypeKey = Declared extends true\n ? Entry extends { id: infer I }\n ? I\n : never\n : string;\ntype EntryFor<T> = Extract<Entry, { id: T }>;\n/**\n * The template ids of one notification type under `Channel`: every template, or only the\n * templates with email or SMS on. Any string while the workspace declares no types.\n */\nexport type NotificationTemplateKey<\n T,\n Channel extends 'template' | 'emailTemplate' | 'smsTemplate' = 'template'\n> = Declared extends true ? (EntryFor<T> extends Record<Channel, infer K> ? K : never) : string;\n/** The variables one notification type declares; any dictionary while the workspace declares no types. */\nexport type NotificationVariables<T> = Declared extends true\n ? EntryFor<T> extends { variables: infer V }\n ? V\n : never\n : Record<string, unknown>;\n\ntype NotificationInput<\n I,\n T,\n Channel extends 'template' | 'emailTemplate' | 'smsTemplate' = 'template'\n> = Omit<I, 'notificationType' | 'notificationTemplate' | 'variables'> & {\n notificationType: T;\n notificationTemplate?: NotificationTemplateKey<T, Channel>;\n} & ({} extends NotificationVariables<T>\n ? { variables?: NotificationVariables<T> }\n : { variables: NotificationVariables<T> });\n\nexport const mail = {\n ...generatedMail,\n sendNotification: <T extends NotificationTypeKey>(\n input: NotificationInput<MailSendNotificationInput, T, 'emailTemplate'>\n ) => invoke<MailSendNotificationOutput>('mail.send-notification', input)\n};\n\nexport const notification = {\n ...generatedNotification,\n sendNotification: <T extends NotificationTypeKey>(\n input: NotificationInput<NotificationSendNotificationInput, T>\n ) => invoke<NotificationSendNotificationOutput>('notification.send-notification', input),\n sendBulkNotifications: <T extends NotificationTypeKey, R extends ResourceKey>(\n input: Omit<NotificationInput<NotificationSendBulkNotificationsInput, T>, 'resource'> & {\n resource: R;\n }\n ) =>\n invoke<NotificationSendBulkNotificationsOutput>('notification.send-bulk-notifications', input),\n setConsent: <R extends NotificationSetConsentInput['resource']>(\n input: Omit<NotificationSetConsentInput, 'resource'> & { resource: R }\n ) => invoke<NotificationSetConsentOutput>('notification.set-consent', input)\n};\n\nexport const sms = {\n ...generatedSms,\n sendNotification: <T extends NotificationTypeKey>(\n input: NotificationInput<SmsSendNotificationInput, T, 'smsTemplate'>\n ) => invoke<SmsSendNotificationOutput>('sms.send-notification', input)\n};\n", "/sdk/profiles/migration.ts": "// The `@diagonal-hq/workflows/migration` entry point of data migration scripts. It exports only\n// helpers that call no host capability. Export a capability here only when the migration profile\n// allows it, because a script that imports this module sees nothing else.\nimport '../console';\n\nexport { HostError, WorkflowFailure, fail, validationError } from '../errors';\nexport {\n InputField,\n InputSchema,\n v,\n type ContentDocument,\n type ContentNode,\n type ContentOptions,\n type FileVisibility,\n type Infer,\n type InferInput,\n type InputFieldKind,\n type InputFieldSpec,\n type InputShape,\n type Money,\n type RecordScope\n} from '../input';\n", "/sdk/profiles/test.ts": "// The `@diagonal-hq/workflows/test` entry point of E2E setup and assert scripts. It exports only\n// helpers that call no host capability. Export a capability here only when the test profile\n// allows it, because a script that imports this module sees nothing else.\nimport '../console';\n\nexport { HostError, WorkflowFailure, fail, validationError } from '../errors';\nexport {\n InputField,\n InputSchema,\n v,\n type ContentDocument,\n type ContentNode,\n type ContentOptions,\n type FileVisibility,\n type Infer,\n type InferInput,\n type InputFieldKind,\n type InputFieldSpec,\n type InputShape,\n type Money,\n type RecordScope\n} from '../input';\n", "/sdk/runtime/quickjs.ts": "// The sandbox entry. scripts/build-workflow-code-runtime.mjs bundles this file and the SDK into\n// the QuickJS runtime. It must not import http-transport.ts or testing/, which need DOM types.\n\nimport { HostError } from '../errors';\n// oxlint-disable-next-line import/no-namespace -- `require('@diagonal/workflow')` returns the whole SDK module.\nimport * as sdk from '../index';\nimport { SerialTransactionTransport } from '../serial-transaction-transport';\nimport type { WorkflowContext, WorkflowDefinition } from '../workflow';\n\ntype HostBridge = (name: string, argsJson: string) => Promise<string>;\n\ntype HostReply = {\n ok: boolean;\n value: unknown;\n error: {\n message: string;\n code: string;\n status: number;\n details: unknown;\n failure_id?: number;\n } | null;\n};\n\nconst guest = globalThis as unknown as Record<string, unknown>;\n\n// Scripts reach the host only through the SDK, so the bridge leaves the global scope here.\nconst host = guest.__host as HostBridge;\ndelete guest.__host;\n\nclass QuickJsTransport implements sdk.HostTransport {\n async call(name: string, input: Record<string, unknown>): Promise<unknown> {\n const reply = JSON.parse(await host(name, JSON.stringify([input]))) as HostReply;\n\n if (!reply.ok) {\n const error = reply.error ?? {\n message: 'The call failed.',\n code: 'internal_error',\n status: 500,\n details: null\n };\n throw new HostError(\n error.message,\n error.code,\n error.status,\n error.details,\n error.failure_id ?? null\n );\n }\n\n return reply.value;\n }\n}\n\nguest.__runWorkflow = async (\n code: string,\n input: unknown,\n context: WorkflowContext,\n workspace: {\n resources: Record<string, string>;\n notificationTypes: Record<string, string>;\n notificationTemplates: Record<string, Record<string, string>>;\n }\n): Promise<unknown> => {\n sdk.setTransport(new SerialTransactionTransport(new QuickJsTransport()));\n const module = { exports: {} as Record<string, unknown> };\n const require = (specifier: string): unknown => {\n if (specifier === '@diagonal/workflow') {\n return sdk;\n }\n\n if (specifier === '@diagonal/workflow/workspace') {\n return workspace;\n }\n\n throw new Error(`Cannot import ${specifier}.`);\n };\n\n // The compiled module is CommonJS text produced by the Diagonal compiler. It runs inside\n // QuickJS, which is the sandbox boundary.\n // oxlint-disable-next-line typescript/no-implied-eval\n new Function('exports', 'require', 'module', code)(module.exports, require, module);\n\n const workflow = module.exports.default as WorkflowDefinition<unknown, unknown> | undefined;\n\n if (workflow?.$diagonal !== 'workflow') {\n throw new Error('The script has no default workflow export.');\n }\n\n const validateInput = module.exports.validateInput;\n const parsed = sdk.parseWorkflowInput(workflow, input);\n\n if (validateInput !== undefined) {\n if (typeof validateInput !== 'function') {\n throw new TypeError('The validateInput export must be a function.');\n }\n\n await sdk.validateWorkflowInput(validateInput as sdk.InputValidator<unknown>, parsed, context);\n }\n\n return workflow.run(parsed, context);\n};\n", "/sdk/serial-transaction-transport.ts": "import { HostError } from './errors';\nimport type { HostTransport } from './transport';\n\nconst PromiseConstructor = Promise;\nconst objectKeys = Object.keys;\nconst isArray = Array.isArray;\n\nexport class SerialTransactionTransport implements HostTransport {\n private pending = 0;\n private settled: Promise<void> | null = null;\n private transactionOpen = false;\n private closing = false;\n\n constructor(private readonly transport: HostTransport) {}\n\n async call(name: string, input: Record<string, unknown>): Promise<unknown> {\n const begins = name === 'transaction.begin';\n const rollsBack = name === 'transaction.rollback';\n const ends = rollsBack || name === 'transaction.commit';\n\n if (begins || ends) {\n if (\n input === null ||\n typeof input !== 'object' ||\n isArray(input) ||\n objectKeys(input).length > 0\n ) {\n throw new HostError(\n 'Transaction controls accept an empty object.',\n 'invalid_arguments',\n 422,\n null\n );\n }\n\n input = {};\n }\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\n const opens = begins && !this.transactionOpen;\n const closes = ends && this.transactionOpen;\n\n if (opens) {\n this.transactionOpen = true;\n }\n\n if (closes) {\n this.closing = true;\n }\n\n const previous = this.settled;\n let complete: (() => void) | undefined;\n let closed = closes;\n\n try {\n // Promise.all can reject while an accepted call still waits on PHP. Rollback must follow\n // that call, and no new call may enter while cleanup waits.\n if (rollsBack && closes && previous !== null) {\n await previous;\n }\n\n this.pending++;\n this.settled = new PromiseConstructor<void>((resolve) => {\n complete = resolve;\n });\n\n return await this.transport.call(name, input);\n } catch (error) {\n if (\n closes &&\n error instanceof HostError &&\n (error.code === 'invalid_arguments' ||\n error.code === 'resolver_not_allowed' ||\n error.code === 'capability_denied' ||\n error.code === 'payload_too_large' ||\n error.code === 'validation' ||\n error.code === 'transaction_concurrent')\n ) {\n closed = false;\n }\n\n if (opens) {\n this.transactionOpen = false;\n }\n\n throw error;\n } finally {\n if (complete !== undefined) {\n this.pending--;\n complete();\n\n if (this.pending === 0) {\n this.settled = null;\n }\n }\n\n if (closes) {\n this.transactionOpen = !closed;\n this.closing = false;\n }\n }\n }\n}\n", "/sdk/transaction.ts": "import { HostError } from './errors';\nimport { invoke } from './transport';\n\nexport async function transaction<T>(fn: () => Promise<T>): Promise<T> {\n await invoke('transaction.begin', {});\n\n let result: T;\n\n try {\n result = await fn();\n } catch (error) {\n await invoke('transaction.rollback', {});\n throw error;\n }\n\n // The host closes the transaction when a commit fails, so a rollback here would only hide the commit error.\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\n throw error;\n }\n\n return result;\n}\n", "/sdk/transport.ts": "export interface HostTransport {\n call(name: string, input: Record<string, unknown>): Promise<unknown>;\n}\n\nlet active: HostTransport | null = null;\n\nexport function setTransport(transport: HostTransport | null): void {\n active = transport;\n}\n\nexport function invoke<T>(name: string, input: object): Promise<T> {\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\n return active.call(name, input as Record<string, unknown>) as Promise<T>;\n}\n", "/sdk/workflow.ts": "import type { ResourceKeyWith } from './data';\nimport { validationError } from './errors';\nimport type { ScriptHostContext } from './index';\nimport {\n coerceInput,\n type InferInput,\n type InputFieldSpec,\n type InputSchema,\n type InputShape\n} from './input';\n\nexport interface Identity {\n id: string;\n /** The identity's resource has the Authenticatable capability. */\n resourceId: ResourceKeyWith<'authenticatable'>;\n email: string | null;\n name: string | null;\n permissions: string[];\n}\n\nexport interface RequestContext {\n method: string;\n url: string;\n params: Record<string, string>;\n query: Record<string, unknown>;\n body: Record<string, unknown>;\n headers: Record<string, string>;\n}\n\nexport interface ScriptExecution {\n id: string;\n kind: 'workflow' | 'embedded';\n owner: { type: string; id: string };\n}\n\nexport interface WorkflowExecution extends ScriptExecution {\n kind: 'workflow';\n workflowId: string;\n}\n\nexport interface WorkflowContext {\n user: Identity | null;\n callingUser: Identity | null;\n trigger: Record<string, unknown>;\n request: RequestContext | null;\n workspace: { id: string; timezone: string };\n execution: ScriptHostContext extends { embedded: true } ? ScriptExecution : WorkflowExecution;\n now: string;\n}\n\nexport interface WorkflowDefinition<I, O> {\n readonly $diagonal: 'workflow';\n /** The declared input schema, when the workflow has one. */\n readonly input?: InputFieldSpec;\n /** Runs the handler with input that {@link parseWorkflowInput} already converted. */\n run(input: I, ctx: WorkflowContext): Promise<O>;\n}\n\n/**\n * Converts a run's raw input to the declared types. A runner calls it once and passes the result\n * to both `validateInput` and `run`, so the validator and the handler receive the same input.\n */\nexport function parseWorkflowInput<I>(workflow: WorkflowDefinition<I, unknown>, input: unknown): I {\n return (workflow.input === undefined ? input : coerceInput(workflow.input, input)) as I;\n}\n\n/**\n * The errors an input validator reports, keyed by input field. A key outside the input's own fields\n * (a nested path such as `tags.0`) is allowed; an empty or absent message means the field is valid.\n */\nexport type InputErrors<I> = Partial<Record<keyof I & string, string | string[]>> &\n Record<string, string | string[] | undefined>;\n\n/**\n * The `validateInput` export a script may define beside its workflow. It runs before the handler\n * with the same input and context; when it reports any error, the run ends with a 422 and those\n * errors, and the handler does not run.\n */\nexport type InputValidator<I> = (\n input: I,\n ctx: WorkflowContext\n) => InputErrors<I> | void | Promise<InputErrors<I> | void>;\n\n/** Runs a script's input validator and ends the run with a validation error when it reports one. */\nexport async function validateWorkflowInput<I>(\n validator: InputValidator<I>,\n input: I,\n ctx: WorkflowContext\n): Promise<void> {\n const reported = await validator(input, ctx);\n\n if (reported === undefined || reported === null) {\n return;\n }\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\n const errors: Record<string, string[]> = {};\n\n for (const [field, messages] of Object.entries(reported)) {\n const list = (Array.isArray(messages) ? messages : [messages]).filter(\n (message): message is string => typeof message === 'string' && message !== ''\n );\n\n if (list.length > 0) {\n errors[field] = list;\n }\n }\n\n if (Object.keys(errors).length > 0) {\n validationError(errors);\n }\n}\n\ntype Handler<I, O> = (input: I, ctx: WorkflowContext) => Promise<O> | O;\n\n/**\n * Declares a workflow. With an input schema first, the platform validates every run's input\n * against it before the script starts, and the handler's `input` type comes from the schema.\n */\nexport function defineWorkflow<S extends InputShape, O = unknown>(\n input: InputSchema<S>,\n handler: Handler<InferInput<S>, O>\n): WorkflowDefinition<InferInput<S>, O>;\nexport function defineWorkflow<I = Record<string, unknown>, O = unknown>(\n handler: Handler<I, O>\n): WorkflowDefinition<I, O>;\nexport function defineWorkflow<I, O>(\n inputOrHandler: InputSchema<InputShape> | Handler<I, O>,\n maybeHandler?: Handler<I, O>\n): WorkflowDefinition<I, O> {\n if (typeof inputOrHandler === 'function') {\n return { $diagonal: 'workflow', run: async (input, ctx) => inputOrHandler(input, ctx) };\n }\n\n const spec = inputOrHandler.$spec;\n const handler = maybeHandler;\n\n if (handler === undefined) {\n throw new TypeError('defineWorkflow(input, handler) needs a handler after the input schema.');\n }\n\n return {\n $diagonal: 'workflow',\n input: spec,\n run: async (input, ctx) => handler(input, ctx)\n };\n}\n\nexport type ResponseOutput = {\n $response_status: number;\n $response_body: unknown;\n $response_content_type: string;\n};\nexport type RedirectType = 'internal' | 'external' | 'back';\nexport type RedirectOutput = {\n redirect_url: string;\n redirect_type: RedirectType;\n permanent: boolean;\n success?: string;\n};\n\nexport function respond(\n body: unknown,\n options: { status?: number; contentType?: string } = {}\n): ResponseOutput {\n return {\n $response_status: options.status ?? 200,\n $response_body: body,\n $response_content_type: options.contentType ?? 'application/json'\n };\n}\n\n/**\n * Builds the output of a graph `http.redirect` step, with the same `redirect_type` and\n * `permanent` keys. Without a `type`, a path such as `/done` redirects as `internal`. Any other\n * URL, including a protocol-relative `//host`, redirects as `external`, because an Inertia\n * request cannot follow a plain redirect to another origin. A `back` redirect is never permanent.\n */\nexport function redirect(\n url: string,\n options: { success?: string; type?: RedirectType; permanent?: boolean } = {}\n): RedirectOutput {\n const type = options.type ?? (/^\\/(?![/\\\\])/.test(url) ? 'internal' : 'external');\n const output: RedirectOutput = {\n redirect_url: url,\n redirect_type: type,\n permanent: type !== 'back' && options.permanent === true\n };\n\n if (options.success !== undefined) {\n output.success = options.success;\n }\n\n return output;\n}\n", "/sdk/workspace.ts": "// The editor's slot for `@diagonal/workflow/workspace`: it replaces this file with the workspace's\n// declarations. Local runs import the file `diagonal-workflow pull-types` writes instead.\nexport const resources: Record<string, string> = {};\nexport const notificationTypes: Record<string, string> = {};\nexport const notificationTemplates: Record<string, Record<string, string>> = {};\n" };
|
|
248590
|
+
`, "/sdk/generated/profiles/migration.ts": "// AUTO-GENERATED by `php artisan workflows:script-sdk:build`. Do not edit by hand.\nimport { data as rootData } from '../../data';\nimport { calendar as rootCalendar, callback as rootCallback, chart as rootChart, date as rootDate, file as rootFile, guard as rootGuard, lifecycle as rootLifecycle, mail as rootMail, markdown as rootMarkdown, mediaLibrary as rootMediaLibrary, money as rootMoney, notification as rootNotification, number as rootNumber, package as rootPackage, page as rootPage, payables as rootPayables, payment as rootPayment, phone as rootPhone, scheduling as rootScheduling, schema as rootSchema, security as rootSecurity, subscriptions as rootSubscriptions, text as rootText, time as rootTime, timezone as rootTimezone, tiptap as rootTiptap, user as rootUser, workflow as rootWorkflow, workspace as rootWorkspace } from '../capabilities';\n\nexport const calendar: {\n generateLink: typeof rootCalendar.generateLink;\n searchEvents: typeof rootCalendar.searchEvents;\n} = {\n generateLink: rootCalendar.generateLink,\n searchEvents: rootCalendar.searchEvents,\n};\n\nexport const callback: {\n get: typeof rootCallback.get;\n remove: typeof rootCallback.remove;\n set: typeof rootCallback.set;\n} = {\n get: rootCallback.get,\n remove: rootCallback.remove,\n set: rootCallback.set,\n};\n\nexport const chart: {\n distribution: typeof rootChart.distribution;\n kpi: typeof rootChart.kpi;\n leaderboard: typeof rootChart.leaderboard;\n timeSeries: typeof rootChart.timeSeries;\n} = {\n distribution: rootChart.distribution,\n kpi: rootChart.kpi,\n leaderboard: rootChart.leaderboard,\n timeSeries: rootChart.timeSeries,\n};\n\nexport const data: {\n aggregateMetrics: typeof rootData.aggregateMetrics;\n count: typeof rootData.count;\n create: typeof rootData.create;\n createMany: typeof rootData.createMany;\n delete: typeof rootData.delete;\n deleteMany: typeof rootData.deleteMany;\n find: typeof rootData.find;\n findOrCreate: typeof rootData.findOrCreate;\n relation: {\n attach: typeof rootData.relation.attach;\n attachMany: typeof rootData.relation.attachMany;\n detach: typeof rootData.relation.detach;\n detachMany: typeof rootData.relation.detachMany;\n sync: typeof rootData.relation.sync;\n };\n restore: typeof rootData.restore;\n search: typeof rootData.search;\n semanticSearch: typeof rootData.semanticSearch;\n sum: typeof rootData.sum;\n update: typeof rootData.update;\n updateOrCreate: typeof rootData.updateOrCreate;\n validate: typeof rootData.validate;\n} = {\n aggregateMetrics: rootData.aggregateMetrics,\n count: rootData.count,\n create: rootData.create,\n createMany: rootData.createMany,\n delete: rootData.delete,\n deleteMany: rootData.deleteMany,\n find: rootData.find,\n findOrCreate: rootData.findOrCreate,\n relation: {\n attach: rootData.relation.attach,\n attachMany: rootData.relation.attachMany,\n detach: rootData.relation.detach,\n detachMany: rootData.relation.detachMany,\n sync: rootData.relation.sync,\n },\n restore: rootData.restore,\n search: rootData.search,\n semanticSearch: rootData.semanticSearch,\n sum: rootData.sum,\n update: rootData.update,\n updateOrCreate: rootData.updateOrCreate,\n validate: rootData.validate,\n};\n\nexport const date: {\n add: typeof rootDate.add;\n diff: typeof rootDate.diff;\n endOf: typeof rootDate.endOf;\n format: typeof rootDate.format;\n startOf: typeof rootDate.startOf;\n subtract: typeof rootDate.subtract;\n} = {\n add: rootDate.add,\n diff: rootDate.diff,\n endOf: rootDate.endOf,\n format: rootDate.format,\n startOf: rootDate.startOf,\n subtract: rootDate.subtract,\n};\n\nexport const file: {\n changeVisibility: typeof rootFile.changeVisibility;\n createMediaLibraryItem: typeof rootFile.createMediaLibraryItem;\n createQrCode: typeof rootFile.createQrCode;\n} = {\n changeVisibility: rootFile.changeVisibility,\n createMediaLibraryItem: rootFile.createMediaLibraryItem,\n createQrCode: rootFile.createQrCode,\n};\n\nexport const guard: {\n validate: typeof rootGuard.validate;\n} = {\n validate: rootGuard.validate,\n};\n\nexport const lifecycle: {\n output: typeof rootLifecycle.output;\n} = {\n output: rootLifecycle.output,\n};\n\nexport const mail: {\n search: typeof rootMail.search;\n} = {\n search: rootMail.search,\n};\n\nexport const markdown: {\n fromContent: typeof rootMarkdown.fromContent;\n toContent: typeof rootMarkdown.toContent;\n} = {\n fromContent: rootMarkdown.fromContent,\n toContent: rootMarkdown.toContent,\n};\n\nexport const mediaLibrary: {\n createFolder: typeof rootMediaLibrary.createFolder;\n deleteItem: typeof rootMediaLibrary.deleteItem;\n moveItems: typeof rootMediaLibrary.moveItems;\n updateItem: typeof rootMediaLibrary.updateItem;\n} = {\n createFolder: rootMediaLibrary.createFolder,\n deleteItem: rootMediaLibrary.deleteItem,\n moveItems: rootMediaLibrary.moveItems,\n updateItem: rootMediaLibrary.updateItem,\n};\n\nexport const money: {\n format: typeof rootMoney.format;\n} = {\n format: rootMoney.format,\n};\n\nexport const notification: {\n setConsent: typeof rootNotification.setConsent;\n} = {\n setConsent: rootNotification.setConsent,\n};\n\nexport const number: {\n format: typeof rootNumber.format;\n} = {\n format: rootNumber.format,\n};\n\nconst package_: {\n installInput: typeof rootPackage.installInput;\n} = {\n installInput: rootPackage.installInput,\n};\nexport { package_ as package };\n\nexport const page: {\n url: typeof rootPage.url;\n} = {\n url: rootPage.url,\n};\n\nexport const payables: {\n void: typeof rootPayables.void;\n writeOff: typeof rootPayables.writeOff;\n} = {\n void: rootPayables.void,\n writeOff: rootPayables.writeOff,\n};\n\nexport const payment: {\n createManual: typeof rootPayment.createManual;\n} = {\n createManual: rootPayment.createManual,\n};\n\nexport const phone: {\n format: typeof rootPhone.format;\n} = {\n format: rootPhone.format,\n};\n\nexport const scheduling: {\n bookSlot: typeof rootScheduling.bookSlot;\n findSlots: typeof rootScheduling.findSlots;\n} = {\n bookSlot: rootScheduling.bookSlot,\n findSlots: rootScheduling.findSlots,\n};\n\nexport const schema: {\n toJsonSchema: typeof rootSchema.toJsonSchema;\n} = {\n toJsonSchema: rootSchema.toJsonSchema,\n};\n\nexport const security: {\n randomPassword: typeof rootSecurity.randomPassword;\n} = {\n randomPassword: rootSecurity.randomPassword,\n};\n\nexport const subscriptions: {\n activate: typeof rootSubscriptions.activate;\n cancel: typeof rootSubscriptions.cancel;\n changeItems: typeof rootSubscriptions.changeItems;\n create: typeof rootSubscriptions.create;\n generateInvoice: typeof rootSubscriptions.generateInvoice;\n pause: typeof rootSubscriptions.pause;\n preview: typeof rootSubscriptions.preview;\n previewChange: typeof rootSubscriptions.previewChange;\n resume: typeof rootSubscriptions.resume;\n setUpcomingItems: typeof rootSubscriptions.setUpcomingItems;\n} = {\n activate: rootSubscriptions.activate,\n cancel: rootSubscriptions.cancel,\n changeItems: rootSubscriptions.changeItems,\n create: rootSubscriptions.create,\n generateInvoice: rootSubscriptions.generateInvoice,\n pause: rootSubscriptions.pause,\n preview: rootSubscriptions.preview,\n previewChange: rootSubscriptions.previewChange,\n resume: rootSubscriptions.resume,\n setUpcomingItems: rootSubscriptions.setUpcomingItems,\n};\n\nexport const text: {\n generate: typeof rootText.generate;\n hash: typeof rootText.hash;\n randomUuid: typeof rootText.randomUuid;\n toContent: typeof rootText.toContent;\n} = {\n generate: rootText.generate,\n hash: rootText.hash,\n randomUuid: rootText.randomUuid,\n toContent: rootText.toContent,\n};\n\nexport const time: {\n add: typeof rootTime.add;\n diff: typeof rootTime.diff;\n endOf: typeof rootTime.endOf;\n format: typeof rootTime.format;\n startOf: typeof rootTime.startOf;\n subtract: typeof rootTime.subtract;\n} = {\n add: rootTime.add,\n diff: rootTime.diff,\n endOf: rootTime.endOf,\n format: rootTime.format,\n startOf: rootTime.startOf,\n subtract: rootTime.subtract,\n};\n\nexport const timezone: {\n format: typeof rootTimezone.format;\n interpret: typeof rootTimezone.interpret;\n} = {\n format: rootTimezone.format,\n interpret: rootTimezone.interpret,\n};\n\nexport const tiptap: {\n parse: typeof rootTiptap.parse;\n} = {\n parse: rootTiptap.parse,\n};\n\nexport const user: {\n authorize: typeof rootUser.authorize;\n} = {\n authorize: rootUser.authorize,\n};\n\nexport const workflow: {\n url: typeof rootWorkflow.url;\n} = {\n url: rootWorkflow.url,\n};\n\nexport const workspace: {\n loginUrl: typeof rootWorkspace.loginUrl;\n setValue: typeof rootWorkspace.setValue;\n setValues: typeof rootWorkspace.setValues;\n value: typeof rootWorkspace.value;\n values: typeof rootWorkspace.values;\n} = {\n loginUrl: rootWorkspace.loginUrl,\n setValue: rootWorkspace.setValue,\n setValues: rootWorkspace.setValues,\n value: rootWorkspace.value,\n values: rootWorkspace.values,\n};\n", "/sdk/generated/profiles/test.ts": "// AUTO-GENERATED by `php artisan workflows:script-sdk:build`. Do not edit by hand.\nimport { data as rootData } from '../../data';\nimport { ai as rootAi, calendar as rootCalendar, callback as rootCallback, chart as rootChart, date as rootDate, file as rootFile, guard as rootGuard, http as rootHttp, lifecycle as rootLifecycle, mail as rootMail, markdown as rootMarkdown, mediaLibrary as rootMediaLibrary, money as rootMoney, notification as rootNotification, number as rootNumber, package as rootPackage, page as rootPage, payables as rootPayables, payment as rootPayment, payments as rootPayments, phone as rootPhone, scheduling as rootScheduling, schema as rootSchema, security as rootSecurity, sms as rootSms, subscriptions as rootSubscriptions, text as rootText, time as rootTime, timezone as rootTimezone, tiptap as rootTiptap, user as rootUser, web as rootWeb, workflow as rootWorkflow, workspace as rootWorkspace } from '../capabilities';\n\nexport const ai: {\n decide: typeof rootAi.decide;\n runPrompt: typeof rootAi.runPrompt;\n} = {\n decide: rootAi.decide,\n runPrompt: rootAi.runPrompt,\n};\n\nexport const calendar: {\n generateLink: typeof rootCalendar.generateLink;\n searchEvents: typeof rootCalendar.searchEvents;\n} = {\n generateLink: rootCalendar.generateLink,\n searchEvents: rootCalendar.searchEvents,\n};\n\nexport const callback: {\n get: typeof rootCallback.get;\n remove: typeof rootCallback.remove;\n set: typeof rootCallback.set;\n} = {\n get: rootCallback.get,\n remove: rootCallback.remove,\n set: rootCallback.set,\n};\n\nexport const chart: {\n distribution: typeof rootChart.distribution;\n kpi: typeof rootChart.kpi;\n leaderboard: typeof rootChart.leaderboard;\n timeSeries: typeof rootChart.timeSeries;\n} = {\n distribution: rootChart.distribution,\n kpi: rootChart.kpi,\n leaderboard: rootChart.leaderboard,\n timeSeries: rootChart.timeSeries,\n};\n\nexport const data: {\n aggregateMetrics: typeof rootData.aggregateMetrics;\n count: typeof rootData.count;\n create: typeof rootData.create;\n createMany: typeof rootData.createMany;\n delete: typeof rootData.delete;\n deleteMany: typeof rootData.deleteMany;\n find: typeof rootData.find;\n findOrCreate: typeof rootData.findOrCreate;\n relation: {\n attach: typeof rootData.relation.attach;\n attachMany: typeof rootData.relation.attachMany;\n detach: typeof rootData.relation.detach;\n detachMany: typeof rootData.relation.detachMany;\n sync: typeof rootData.relation.sync;\n };\n restore: typeof rootData.restore;\n search: typeof rootData.search;\n semanticSearch: typeof rootData.semanticSearch;\n sum: typeof rootData.sum;\n update: typeof rootData.update;\n updateOrCreate: typeof rootData.updateOrCreate;\n validate: typeof rootData.validate;\n} = {\n aggregateMetrics: rootData.aggregateMetrics,\n count: rootData.count,\n create: rootData.create,\n createMany: rootData.createMany,\n delete: rootData.delete,\n deleteMany: rootData.deleteMany,\n find: rootData.find,\n findOrCreate: rootData.findOrCreate,\n relation: {\n attach: rootData.relation.attach,\n attachMany: rootData.relation.attachMany,\n detach: rootData.relation.detach,\n detachMany: rootData.relation.detachMany,\n sync: rootData.relation.sync,\n },\n restore: rootData.restore,\n search: rootData.search,\n semanticSearch: rootData.semanticSearch,\n sum: rootData.sum,\n update: rootData.update,\n updateOrCreate: rootData.updateOrCreate,\n validate: rootData.validate,\n};\n\nexport const date: {\n add: typeof rootDate.add;\n diff: typeof rootDate.diff;\n endOf: typeof rootDate.endOf;\n format: typeof rootDate.format;\n startOf: typeof rootDate.startOf;\n subtract: typeof rootDate.subtract;\n} = {\n add: rootDate.add,\n diff: rootDate.diff,\n endOf: rootDate.endOf,\n format: rootDate.format,\n startOf: rootDate.startOf,\n subtract: rootDate.subtract,\n};\n\nexport const file: {\n changeVisibility: typeof rootFile.changeVisibility;\n createFromUrl: typeof rootFile.createFromUrl;\n createMediaLibraryItem: typeof rootFile.createMediaLibraryItem;\n createQrCode: typeof rootFile.createQrCode;\n} = {\n changeVisibility: rootFile.changeVisibility,\n createFromUrl: rootFile.createFromUrl,\n createMediaLibraryItem: rootFile.createMediaLibraryItem,\n createQrCode: rootFile.createQrCode,\n};\n\nexport const guard: {\n validate: typeof rootGuard.validate;\n} = {\n validate: rootGuard.validate,\n};\n\nexport const http: {\n request: typeof rootHttp.request;\n} = {\n request: rootHttp.request,\n};\n\nexport const lifecycle: {\n output: typeof rootLifecycle.output;\n} = {\n output: rootLifecycle.output,\n};\n\nexport const mail: {\n search: typeof rootMail.search;\n send: typeof rootMail.send;\n sendNotification: typeof rootMail.sendNotification;\n} = {\n search: rootMail.search,\n send: rootMail.send,\n sendNotification: rootMail.sendNotification,\n};\n\nexport const markdown: {\n fromContent: typeof rootMarkdown.fromContent;\n toContent: typeof rootMarkdown.toContent;\n} = {\n fromContent: rootMarkdown.fromContent,\n toContent: rootMarkdown.toContent,\n};\n\nexport const mediaLibrary: {\n createFolder: typeof rootMediaLibrary.createFolder;\n deleteItem: typeof rootMediaLibrary.deleteItem;\n moveItems: typeof rootMediaLibrary.moveItems;\n updateItem: typeof rootMediaLibrary.updateItem;\n} = {\n createFolder: rootMediaLibrary.createFolder,\n deleteItem: rootMediaLibrary.deleteItem,\n moveItems: rootMediaLibrary.moveItems,\n updateItem: rootMediaLibrary.updateItem,\n};\n\nexport const money: {\n format: typeof rootMoney.format;\n} = {\n format: rootMoney.format,\n};\n\nexport const notification: {\n send: typeof rootNotification.send;\n sendBulkNotifications: typeof rootNotification.sendBulkNotifications;\n sendNotification: typeof rootNotification.sendNotification;\n setConsent: typeof rootNotification.setConsent;\n} = {\n send: rootNotification.send,\n sendBulkNotifications: rootNotification.sendBulkNotifications,\n sendNotification: rootNotification.sendNotification,\n setConsent: rootNotification.setConsent,\n};\n\nexport const number: {\n format: typeof rootNumber.format;\n} = {\n format: rootNumber.format,\n};\n\nconst package_: {\n installInput: typeof rootPackage.installInput;\n} = {\n installInput: rootPackage.installInput,\n};\nexport { package_ as package };\n\nexport const page: {\n url: typeof rootPage.url;\n} = {\n url: rootPage.url,\n};\n\nexport const payables: {\n void: typeof rootPayables.void;\n writeOff: typeof rootPayables.writeOff;\n} = {\n void: rootPayables.void,\n writeOff: rootPayables.writeOff,\n};\n\nexport const payment: {\n createManual: typeof rootPayment.createManual;\n} = {\n createManual: rootPayment.createManual,\n};\n\nexport const payments: {\n charge: typeof rootPayments.charge;\n checkout: typeof rootPayments.checkout;\n confirm: typeof rootPayments.confirm;\n refund: typeof rootPayments.refund;\n} = {\n charge: rootPayments.charge,\n checkout: rootPayments.checkout,\n confirm: rootPayments.confirm,\n refund: rootPayments.refund,\n};\n\nexport const phone: {\n format: typeof rootPhone.format;\n} = {\n format: rootPhone.format,\n};\n\nexport const scheduling: {\n bookSlot: typeof rootScheduling.bookSlot;\n findSlots: typeof rootScheduling.findSlots;\n} = {\n bookSlot: rootScheduling.bookSlot,\n findSlots: rootScheduling.findSlots,\n};\n\nexport const schema: {\n toJsonSchema: typeof rootSchema.toJsonSchema;\n} = {\n toJsonSchema: rootSchema.toJsonSchema,\n};\n\nexport const security: {\n randomPassword: typeof rootSecurity.randomPassword;\n} = {\n randomPassword: rootSecurity.randomPassword,\n};\n\nexport const sms: {\n sendNotification: typeof rootSms.sendNotification;\n} = {\n sendNotification: rootSms.sendNotification,\n};\n\nexport const subscriptions: {\n activate: typeof rootSubscriptions.activate;\n cancel: typeof rootSubscriptions.cancel;\n changeItems: typeof rootSubscriptions.changeItems;\n create: typeof rootSubscriptions.create;\n generateInvoice: typeof rootSubscriptions.generateInvoice;\n pause: typeof rootSubscriptions.pause;\n preview: typeof rootSubscriptions.preview;\n previewChange: typeof rootSubscriptions.previewChange;\n resume: typeof rootSubscriptions.resume;\n setUpcomingItems: typeof rootSubscriptions.setUpcomingItems;\n} = {\n activate: rootSubscriptions.activate,\n cancel: rootSubscriptions.cancel,\n changeItems: rootSubscriptions.changeItems,\n create: rootSubscriptions.create,\n generateInvoice: rootSubscriptions.generateInvoice,\n pause: rootSubscriptions.pause,\n preview: rootSubscriptions.preview,\n previewChange: rootSubscriptions.previewChange,\n resume: rootSubscriptions.resume,\n setUpcomingItems: rootSubscriptions.setUpcomingItems,\n};\n\nexport const text: {\n generate: typeof rootText.generate;\n hash: typeof rootText.hash;\n randomUuid: typeof rootText.randomUuid;\n toContent: typeof rootText.toContent;\n} = {\n generate: rootText.generate,\n hash: rootText.hash,\n randomUuid: rootText.randomUuid,\n toContent: rootText.toContent,\n};\n\nexport const time: {\n add: typeof rootTime.add;\n diff: typeof rootTime.diff;\n endOf: typeof rootTime.endOf;\n format: typeof rootTime.format;\n startOf: typeof rootTime.startOf;\n subtract: typeof rootTime.subtract;\n} = {\n add: rootTime.add,\n diff: rootTime.diff,\n endOf: rootTime.endOf,\n format: rootTime.format,\n startOf: rootTime.startOf,\n subtract: rootTime.subtract,\n};\n\nexport const timezone: {\n format: typeof rootTimezone.format;\n interpret: typeof rootTimezone.interpret;\n} = {\n format: rootTimezone.format,\n interpret: rootTimezone.interpret,\n};\n\nexport const tiptap: {\n parse: typeof rootTiptap.parse;\n} = {\n parse: rootTiptap.parse,\n};\n\nexport const user: {\n authorize: typeof rootUser.authorize;\n} = {\n authorize: rootUser.authorize,\n};\n\nexport const web: {\n agent: typeof rootWeb.agent;\n batchScrape: typeof rootWeb.batchScrape;\n crawl: typeof rootWeb.crawl;\n extract: typeof rootWeb.extract;\n googleSearch: typeof rootWeb.googleSearch;\n map: typeof rootWeb.map;\n pdf: typeof rootWeb.pdf;\n scrape: typeof rootWeb.scrape;\n screenshot: typeof rootWeb.screenshot;\n searchRanked: typeof rootWeb.searchRanked;\n} = {\n agent: rootWeb.agent,\n batchScrape: rootWeb.batchScrape,\n crawl: rootWeb.crawl,\n extract: rootWeb.extract,\n googleSearch: rootWeb.googleSearch,\n map: rootWeb.map,\n pdf: rootWeb.pdf,\n scrape: rootWeb.scrape,\n screenshot: rootWeb.screenshot,\n searchRanked: rootWeb.searchRanked,\n};\n\nexport const workflow: {\n run: typeof rootWorkflow.run;\n url: typeof rootWorkflow.url;\n} = {\n run: rootWorkflow.run,\n url: rootWorkflow.url,\n};\n\nexport const workspace: {\n loginUrl: typeof rootWorkspace.loginUrl;\n setValue: typeof rootWorkspace.setValue;\n setValues: typeof rootWorkspace.setValues;\n value: typeof rootWorkspace.value;\n values: typeof rootWorkspace.values;\n} = {\n loginUrl: rootWorkspace.loginUrl,\n setValue: rootWorkspace.setValue,\n setValues: rootWorkspace.setValues,\n value: rootWorkspace.value,\n values: rootWorkspace.values,\n};\n", "/sdk/index.ts": "import './console';\n\nexport { HostError, WorkflowFailure, fail, validationError } from './errors';\nexport { invoke, setTransport, type HostTransport } from './transport';\nexport { transaction } from './transaction';\nexport { data } from './data';\nexport { mail, notification, sms } from './notifications';\nexport {\n InputField,\n InputSchema,\n v,\n type ContentDocument,\n type ContentNode,\n type ContentOptions,\n type FileVisibility,\n type Infer,\n type InferInput,\n type InputFieldKind,\n type InputFieldSpec,\n type InputShape,\n type Money,\n type RecordScope\n} from './input';\nexport {\n defineWorkflow,\n parseWorkflowInput,\n redirect,\n respond,\n validateWorkflowInput,\n type Identity,\n type InputErrors,\n type InputValidator,\n type RequestContext,\n type ScriptExecution,\n type WorkflowContext,\n type WorkflowDefinition,\n type WorkflowExecution\n} from './workflow';\nexport * from './generated/capabilities';\n\n/** The embedding host selects its execution context through its supplied declarations. */\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface ScriptHostContext {}\n\n/** Declaration-merged by the generated workspace module with one entry per resource. */\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface WorkspaceResources {}\n\n/**\n * Declaration-merged by the generated workspace module with one entry per notification type:\n * its id, the unions of its template ids (all, email-enabled, and SMS-enabled), and the shape\n * of its variables.\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface WorkspaceNotificationTypes {}\n", "/sdk/input.ts": "import type { InputOf, ResourceKey } from './data';\n\n/**\n * A declared input field, as data. The compiler reads a workflow's input schema from its source\n * and saves each field as a workflow input variable, so the platform validates a run's input\n * against these rules before the script starts. The same data travels with the workflow at run\n * time, where the SDK uses it to coerce string values to the declared types.\n */\nexport interface InputFieldSpec {\n readonly kind: InputFieldKind;\n readonly optional: boolean;\n readonly nullable: boolean;\n /** Validation rules in the platform's rule syntax, such as `min:1` or `regex:/^[a-z]+$/`. */\n readonly rules: readonly string[];\n readonly label?: string;\n readonly description?: string;\n /** `select`: the allowed values. */\n readonly options?: readonly (string | number)[];\n /** `list`: the item field. */\n readonly items?: InputFieldSpec;\n /** `object`: the nested fields. */\n readonly fields?: Readonly<Record<string, InputFieldSpec>>;\n /** `record` and `recordReference`: the resource whose definitions or records the value must match. */\n readonly resource?: string;\n /** `recordReference`: the records the ID can name. The platform default is `active`. */\n readonly scope?: RecordScope;\n /** `file`: the accepted MIME types. */\n readonly accept?: readonly string[];\n /** `file`: the visibility of the file. */\n readonly visibility?: FileVisibility;\n /** `content`: the formatting the document may use. */\n readonly content?: ContentOptions;\n}\n\n/**\n * A money value as the platform stores it. It is a type alias, not an interface, so that it is\n * assignable to the open money objects of capability inputs such as `money.format`.\n */\nexport type Money = {\n amount: number;\n currency: string;\n};\n\nexport type InputFieldKind =\n | 'text'\n | 'email'\n | 'url'\n | 'uuid'\n | 'phone'\n | 'date'\n | 'datetime'\n | 'time'\n | 'timezone'\n | 'color'\n | 'number'\n | 'integer'\n | 'money'\n | 'boolean'\n | 'select'\n | 'list'\n | 'object'\n | 'record'\n | 'recordReference'\n | 'roleReference'\n | 'file'\n | 'content';\n\n/** The records a record ID can name: `active`, `archived` (deleted), or `activeOrArchived` (all). */\nexport type RecordScope = 'active' | 'archived' | 'activeOrArchived';\n\nexport type FileVisibility = 'public' | 'private';\n\nexport interface ContentOptions {\n /** `false` allows one paragraph only. The default is `true`. */\n readonly multiLine?: boolean;\n /** The marks the text may use. Each mark is allowed unless it is `false`. */\n readonly extensions?: Readonly<\n Partial<Record<'bold' | 'italic' | 'strike' | 'underline' | 'link', boolean>>\n >;\n /** The block nodes the document may use. Each node is allowed unless it is `false`. */\n readonly allowedNodes?: Readonly<\n Partial<Record<'heading' | 'blockquote' | 'bulletList' | 'orderedList' | 'media', boolean>>\n >;\n}\n\n/** A rich text node in the platform's content format. */\nexport interface ContentNode {\n type: string;\n attrs?: Record<string, unknown>;\n content?: ContentNode[];\n marks?: { type: string; attrs?: Record<string, unknown> }[];\n text?: string;\n}\n\n/** A rich text document in the platform's content format. */\nexport interface ContentDocument extends ContentNode {\n type: 'doc';\n}\n\n/**\n * One field of a workflow's input schema. `T` is the value type the handler receives; `O` is\n * whether the key may be absent. Every modifier returns a new field, so a field can be shared.\n */\nexport class InputField<T, O extends boolean = false> {\n /** Phantom members that carry the static types; they hold no value at run time. */\n declare readonly $value: T;\n declare readonly $optional: O;\n\n constructor(readonly $spec: InputFieldSpec) {}\n\n /** The key may be absent. */\n optional(): InputField<T | undefined, true> {\n return new InputField({ ...this.$spec, optional: true });\n }\n\n /** The value may be `null`. */\n nullable(): InputField<T | null, O> {\n return new InputField({ ...this.$spec, nullable: true });\n }\n\n /** At least `value`: a number's value, a text's length, or a list's item count. */\n min(value: number): InputField<T, O> {\n return this.rule(`min:${value}`);\n }\n\n /** At most `value`: a number's value, a text's length, or a list's item count. */\n max(value: number): InputField<T, O> {\n return this.rule(`max:${value}`);\n }\n\n /** Between `min` and `max`, inclusive, measured as for `min` and `max`. */\n between(min: number, max: number): InputField<T, O> {\n return this.rule(`between:${min},${max}`);\n }\n\n /** Exactly `value`, measured as for `min` and `max`. */\n size(value: number): InputField<T, O> {\n return this.rule(`size:${value}`);\n }\n\n /** The text matches the pattern. */\n regex(pattern: RegExp): InputField<T, O> {\n return this.rule(`regex:/${pattern.source}/${pattern.flags}`);\n }\n\n /** Any other platform validation rule, such as `starts_with:INV-` or `after:today`. */\n rule(rule: string): InputField<T, O> {\n return new InputField({ ...this.$spec, rules: [...this.$spec.rules, rule] });\n }\n\n label(label: string): InputField<T, O> {\n return new InputField({ ...this.$spec, label });\n }\n\n description(description: string): InputField<T, O> {\n return new InputField({ ...this.$spec, description });\n }\n}\n\nexport type InputShape = Record<string, InputField<unknown, boolean>>;\n\ntype Simplify<T> = { [K in keyof T]: T[K] } & {};\n\n/** The value an input schema describes: optional fields become optional keys. */\nexport type InferInput<S extends InputShape> = Simplify<\n { [K in keyof S as S[K]['$optional'] extends true ? never : K]: S[K]['$value'] } & {\n [K in keyof S as S[K]['$optional'] extends true ? K : never]?: S[K]['$value'];\n }\n>;\n\n/** The value a field or schema describes: `Infer<typeof Input>`. */\nexport type Infer<F extends InputField<unknown, boolean>> = F['$value'];\n\n/** A workflow's input schema: the fields of an object. */\nexport class InputSchema<S extends InputShape> extends InputField<InferInput<S>> {\n constructor(readonly shape: S) {\n super(objectSpec(shape));\n }\n}\n\nfunction objectSpec(shape: InputShape): InputFieldSpec {\n return {\n kind: 'object',\n optional: false,\n nullable: false,\n rules: [],\n fields: Object.fromEntries(Object.entries(shape).map(([key, field]) => [key, field.$spec]))\n };\n}\n\nconst field = <T>(kind: InputFieldKind, extra: Partial<InputFieldSpec> = {}): InputField<T> =>\n new InputField<T>({ kind, optional: false, nullable: false, rules: [], ...extra });\n\n/** Builders for a workflow's input schema. */\nexport const v = {\n text: () => field<string>('text'),\n email: () => field<string>('email'),\n url: () => field<string>('url'),\n uuid: () => field<string>('uuid'),\n phone: () => field<string>('phone'),\n /** A calendar date, `YYYY-MM-DD`. */\n date: () => field<string>('date'),\n /** A date and time, ISO 8601. */\n datetime: () => field<string>('datetime'),\n /** A time of day, `HH:MM`. */\n time: () => field<string>('time'),\n timezone: () => field<string>('timezone'),\n color: () => field<string>('color'),\n number: () => field<number>('number'),\n integer: () => field<number>('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>('money'),\n boolean: () => field<boolean>('boolean'),\n /** One of `options`. */\n select: <const V extends readonly (string | number)[]>(options: V) =>\n field<V[number]>('select', { options }),\n /** A list whose items each satisfy `items`. */\n list: <T>(items: InputField<T, boolean>) =>\n field<Exclude<T, undefined>[]>('list', { items: items.$spec }),\n /** An object with the given fields. */\n object: <S extends InputShape>(shape: S) => 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: <R extends ResourceKey>(resource: R) => field<InputOf<R>>('record', { resource }),\n /** The ID of an existing record of `resource`, in `scope`. */\n recordReference: <R extends ResourceKey>(resource: R, options: { scope?: RecordScope } = {}) =>\n field<string>('recordReference', { resource, ...options }),\n /** The ID of an existing role. */\n roleReference: () => field<string>('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: { accept?: readonly string[]; visibility?: FileVisibility } = {}) =>\n field<string>('file', options),\n /** A rich text document with the formatting that `options` allows. */\n content: (options: ContentOptions = {}) =>\n field<ContentDocument>('content', Object.keys(options).length === 0 ? {} : { content: options })\n};\n\nconst NUMERIC = /^-?(\\d+\\.?\\d*|\\.\\d+)(e[-+]?\\d+)?$/i;\n\nfunction coerceNumber(value: unknown): unknown {\n return typeof value === 'string' && NUMERIC.test(value.trim()) ? Number(value) : value;\n}\n\n/**\n * Converts the string forms a request carries (`\"5\"`, `\"true\"`) to the declared types. It runs\n * after the platform validated the input against the same schema, so a value it cannot convert\n * is left as it is.\n */\nexport function coerceInput(spec: InputFieldSpec, value: unknown): unknown {\n if (value === null || value === undefined) {\n return value;\n }\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\n ? { ...value, amount: coerceNumber(value.amount) }\n : value;\n case 'boolean':\n if (value === 'true' || value === '1' || value === 1) {\n return true;\n }\n\n return value === 'false' || value === '0' || value === 0 ? false : value;\n case 'select':\n return typeof value === 'string' &&\n !spec.options?.includes(value) &&\n spec.options?.includes(Number(value))\n ? Number(value)\n : value;\n case 'list':\n return Array.isArray(value) && spec.items\n ? value.map((item) => coerceInput(spec.items!, item))\n : value;\n case 'object': {\n if (typeof value !== 'object' || Array.isArray(value) || !spec.fields) {\n return value;\n }\n\n const result: Record<string, unknown> = { ...(value as Record<string, unknown>) };\n\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\n return result;\n }\n default:\n return value;\n }\n}\n", "/sdk/notifications.ts": "import type { ResourceKey } from './data';\nimport {\n mail as generatedMail,\n notification as generatedNotification,\n sms as generatedSms,\n type MailSendNotificationInput,\n type MailSendNotificationOutput,\n type NotificationSendBulkNotificationsInput,\n type NotificationSendBulkNotificationsOutput,\n type NotificationSendNotificationInput,\n type NotificationSendNotificationOutput,\n type NotificationSetConsentInput,\n type NotificationSetConsentOutput,\n type SmsSendNotificationInput,\n type SmsSendNotificationOutput\n} from './generated/capabilities';\nimport type { WorkspaceNotificationTypes } from './index';\nimport { invoke } from './transport';\n\ntype Entry = WorkspaceNotificationTypes[keyof WorkspaceNotificationTypes];\ntype Declared = [keyof WorkspaceNotificationTypes] extends [never] ? false : true;\nexport type NotificationTypeKey = Declared extends true\n ? Entry extends { id: infer I }\n ? I\n : never\n : string;\ntype EntryFor<T> = Extract<Entry, { id: T }>;\n/**\n * The template ids of one notification type under `Channel`: every template, or only the\n * templates with email or SMS on. Any string while the workspace declares no types.\n */\nexport type NotificationTemplateKey<\n T,\n Channel extends 'template' | 'emailTemplate' | 'smsTemplate' = 'template'\n> = Declared extends true ? (EntryFor<T> extends Record<Channel, infer K> ? K : never) : string;\n/** The variables one notification type declares; any dictionary while the workspace declares no types. */\nexport type NotificationVariables<T> = Declared extends true\n ? EntryFor<T> extends { variables: infer V }\n ? V\n : never\n : Record<string, unknown>;\n\ntype NotificationInput<\n I,\n T,\n Channel extends 'template' | 'emailTemplate' | 'smsTemplate' = 'template'\n> = Omit<I, 'notificationType' | 'notificationTemplate' | 'variables'> & {\n notificationType: T;\n notificationTemplate?: NotificationTemplateKey<T, Channel>;\n} & ({} extends NotificationVariables<T>\n ? { variables?: NotificationVariables<T> }\n : { variables: NotificationVariables<T> });\n\nexport const mail = {\n ...generatedMail,\n sendNotification: <T extends NotificationTypeKey>(\n input: NotificationInput<MailSendNotificationInput, T, 'emailTemplate'>\n ) => invoke<MailSendNotificationOutput>('mail.send-notification', input)\n};\n\nexport const notification = {\n ...generatedNotification,\n sendNotification: <T extends NotificationTypeKey>(\n input: NotificationInput<NotificationSendNotificationInput, T>\n ) => invoke<NotificationSendNotificationOutput>('notification.send-notification', input),\n sendBulkNotifications: <T extends NotificationTypeKey, R extends ResourceKey>(\n input: Omit<NotificationInput<NotificationSendBulkNotificationsInput, T>, 'resource'> & {\n resource: R;\n }\n ) =>\n invoke<NotificationSendBulkNotificationsOutput>('notification.send-bulk-notifications', input),\n setConsent: <R extends NotificationSetConsentInput['resource']>(\n input: Omit<NotificationSetConsentInput, 'resource'> & { resource: R }\n ) => invoke<NotificationSetConsentOutput>('notification.set-consent', input)\n};\n\nexport const sms = {\n ...generatedSms,\n sendNotification: <T extends NotificationTypeKey>(\n input: NotificationInput<SmsSendNotificationInput, T, 'smsTemplate'>\n ) => invoke<SmsSendNotificationOutput>('sms.send-notification', input)\n};\n", "/sdk/profiles/migration.ts": "// The `@diagonal-hq/workflows/migration` entry point of data migration scripts. It exports every\n// capability wrapper except the migration profile's deny list (outbound calls, messages,\n// payments, sign-in changes, and `workflow.run`), the `transaction()` helper, and the root\n// exports that call no host capability. The script host refuses each denied capability.\nimport '../console';\nimport { data as rootData } from '../data';\nimport { data as migrationData } from '../generated/profiles/migration';\n\nexport * from './shared';\nexport * from '../generated/profiles/migration';\nexport { transaction } from '../transaction';\n\nexport const data: typeof migrationData & { each: typeof rootData.each } = {\n ...migrationData,\n each: rootData.each\n};\n", "/sdk/profiles/shared.ts": "// The root exports that call no host capability. Each profile entry point re-exports them.\nexport { HostError, WorkflowFailure, fail, validationError } from '../errors';\nexport {\n InputField,\n InputSchema,\n v,\n type ContentDocument,\n type ContentNode,\n type ContentOptions,\n type FileVisibility,\n type Infer,\n type InferInput,\n type InputFieldKind,\n type InputFieldSpec,\n type InputShape,\n type Money,\n type RecordScope\n} from '../input';\nexport {\n defineWorkflow,\n parseWorkflowInput,\n redirect,\n respond,\n validateWorkflowInput,\n type Identity,\n type InputErrors,\n type InputValidator,\n type RequestContext,\n type ScriptExecution,\n type WorkflowContext,\n type WorkflowDefinition,\n type WorkflowExecution\n} from '../workflow';\nexport type { ScriptHostContext, WorkspaceNotificationTypes, WorkspaceResources } from '../index';\n", "/sdk/profiles/test.ts": "// The `@diagonal-hq/workflows/test` entry point of E2E setup and assert scripts. It exports every\n// capability wrapper except the test profile's deny list (sign-in changes), the `transaction()`\n// helper, and the root exports that call no host capability. The script host refuses each\n// denied capability.\nimport '../console';\nimport { data as rootData } from '../data';\nimport { data as testData } from '../generated/profiles/test';\n\nexport * from './shared';\nexport * from '../generated/profiles/test';\nexport { transaction } from '../transaction';\n\nexport const data: typeof testData & { each: typeof rootData.each } = {\n ...testData,\n each: rootData.each\n};\n", "/sdk/runtime/quickjs.ts": "// The sandbox entry. scripts/build-workflow-code-runtime.mjs bundles this file and the SDK into\n// the QuickJS runtime. It must not import http-transport.ts or testing/, which need DOM types.\n\nimport { HostError } from '../errors';\n// oxlint-disable-next-line import/no-namespace -- `require('@diagonal/workflow')` returns the whole SDK module.\nimport * as sdk from '../index';\nimport { SerialTransactionTransport } from '../serial-transaction-transport';\nimport type { WorkflowContext, WorkflowDefinition } from '../workflow';\n\ntype HostBridge = (name: string, argsJson: string) => Promise<string>;\n\ntype HostReply = {\n ok: boolean;\n value: unknown;\n error: {\n message: string;\n code: string;\n status: number;\n details: unknown;\n failure_id?: number;\n } | null;\n};\n\nconst guest = globalThis as unknown as Record<string, unknown>;\n\n// Scripts reach the host only through the SDK, so the bridge leaves the global scope here.\nconst host = guest.__host as HostBridge;\ndelete guest.__host;\n\nclass QuickJsTransport implements sdk.HostTransport {\n async call(name: string, input: Record<string, unknown>): Promise<unknown> {\n const reply = JSON.parse(await host(name, JSON.stringify([input]))) as HostReply;\n\n if (!reply.ok) {\n const error = reply.error ?? {\n message: 'The call failed.',\n code: 'internal_error',\n status: 500,\n details: null\n };\n throw new HostError(\n error.message,\n error.code,\n error.status,\n error.details,\n error.failure_id ?? null\n );\n }\n\n return reply.value;\n }\n}\n\nguest.__runWorkflow = async (\n code: string,\n input: unknown,\n context: WorkflowContext,\n workspace: {\n resources: Record<string, string>;\n notificationTypes: Record<string, string>;\n notificationTemplates: Record<string, Record<string, string>>;\n }\n): Promise<unknown> => {\n sdk.setTransport(new SerialTransactionTransport(new QuickJsTransport()));\n const module = { exports: {} as Record<string, unknown> };\n const require = (specifier: string): unknown => {\n if (specifier === '@diagonal/workflow') {\n return sdk;\n }\n\n if (specifier === '@diagonal/workflow/workspace') {\n return workspace;\n }\n\n throw new Error(`Cannot import ${specifier}.`);\n };\n\n // The compiled module is CommonJS text produced by the Diagonal compiler. It runs inside\n // QuickJS, which is the sandbox boundary.\n // oxlint-disable-next-line typescript/no-implied-eval\n new Function('exports', 'require', 'module', code)(module.exports, require, module);\n\n const workflow = module.exports.default as WorkflowDefinition<unknown, unknown> | undefined;\n\n if (workflow?.$diagonal !== 'workflow') {\n throw new Error('The script has no default workflow export.');\n }\n\n const validateInput = module.exports.validateInput;\n const parsed = sdk.parseWorkflowInput(workflow, input);\n\n if (validateInput !== undefined) {\n if (typeof validateInput !== 'function') {\n throw new TypeError('The validateInput export must be a function.');\n }\n\n await sdk.validateWorkflowInput(validateInput as sdk.InputValidator<unknown>, parsed, context);\n }\n\n return workflow.run(parsed, context);\n};\n", "/sdk/serial-transaction-transport.ts": "import { HostError } from './errors';\nimport type { HostTransport } from './transport';\n\nconst PromiseConstructor = Promise;\nconst objectKeys = Object.keys;\nconst isArray = Array.isArray;\n\nexport class SerialTransactionTransport implements HostTransport {\n private pending = 0;\n private settled: Promise<void> | null = null;\n private transactionOpen = false;\n private closing = false;\n\n constructor(private readonly transport: HostTransport) {}\n\n async call(name: string, input: Record<string, unknown>): Promise<unknown> {\n const begins = name === 'transaction.begin';\n const rollsBack = name === 'transaction.rollback';\n const ends = rollsBack || name === 'transaction.commit';\n\n if (begins || ends) {\n if (\n input === null ||\n typeof input !== 'object' ||\n isArray(input) ||\n objectKeys(input).length > 0\n ) {\n throw new HostError(\n 'Transaction controls accept an empty object.',\n 'invalid_arguments',\n 422,\n null\n );\n }\n\n input = {};\n }\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\n const opens = begins && !this.transactionOpen;\n const closes = ends && this.transactionOpen;\n\n if (opens) {\n this.transactionOpen = true;\n }\n\n if (closes) {\n this.closing = true;\n }\n\n const previous = this.settled;\n let complete: (() => void) | undefined;\n let closed = closes;\n\n try {\n // Promise.all can reject while an accepted call still waits on PHP. Rollback must follow\n // that call, and no new call may enter while cleanup waits.\n if (rollsBack && closes && previous !== null) {\n await previous;\n }\n\n this.pending++;\n this.settled = new PromiseConstructor<void>((resolve) => {\n complete = resolve;\n });\n\n return await this.transport.call(name, input);\n } catch (error) {\n if (\n closes &&\n error instanceof HostError &&\n (error.code === 'invalid_arguments' ||\n error.code === 'resolver_not_allowed' ||\n error.code === 'capability_denied' ||\n error.code === 'payload_too_large' ||\n error.code === 'validation' ||\n error.code === 'transaction_concurrent')\n ) {\n closed = false;\n }\n\n if (opens) {\n this.transactionOpen = false;\n }\n\n throw error;\n } finally {\n if (complete !== undefined) {\n this.pending--;\n complete();\n\n if (this.pending === 0) {\n this.settled = null;\n }\n }\n\n if (closes) {\n this.transactionOpen = !closed;\n this.closing = false;\n }\n }\n }\n}\n", "/sdk/transaction.ts": "import { HostError } from './errors';\nimport { invoke } from './transport';\n\nexport async function transaction<T>(fn: () => Promise<T>): Promise<T> {\n await invoke('transaction.begin', {});\n\n let result: T;\n\n try {\n result = await fn();\n } catch (error) {\n await invoke('transaction.rollback', {});\n throw error;\n }\n\n // The host closes the transaction when a commit fails, so a rollback here would only hide the commit error.\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\n throw error;\n }\n\n return result;\n}\n", "/sdk/transport.ts": "export interface HostTransport {\n call(name: string, input: Record<string, unknown>): Promise<unknown>;\n}\n\nlet active: HostTransport | null = null;\n\nexport function setTransport(transport: HostTransport | null): void {\n active = transport;\n}\n\nexport function invoke<T>(name: string, input: object): Promise<T> {\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\n return active.call(name, input as Record<string, unknown>) as Promise<T>;\n}\n", "/sdk/workflow.ts": "import type { ResourceKeyWith } from './data';\nimport { validationError } from './errors';\nimport type { ScriptHostContext } from './index';\nimport {\n coerceInput,\n type InferInput,\n type InputFieldSpec,\n type InputSchema,\n type InputShape\n} from './input';\n\nexport interface Identity {\n id: string;\n /** The identity's resource has the Authenticatable capability. */\n resourceId: ResourceKeyWith<'authenticatable'>;\n email: string | null;\n name: string | null;\n permissions: string[];\n}\n\nexport interface RequestContext {\n method: string;\n url: string;\n params: Record<string, string>;\n query: Record<string, unknown>;\n body: Record<string, unknown>;\n headers: Record<string, string>;\n}\n\nexport interface ScriptExecution {\n id: string;\n kind: 'workflow' | 'embedded';\n owner: { type: string; id: string };\n}\n\nexport interface WorkflowExecution extends ScriptExecution {\n kind: 'workflow';\n workflowId: string;\n}\n\nexport interface WorkflowContext {\n user: Identity | null;\n callingUser: Identity | null;\n trigger: Record<string, unknown>;\n request: RequestContext | null;\n workspace: { id: string; timezone: string };\n execution: ScriptHostContext extends { embedded: true } ? ScriptExecution : WorkflowExecution;\n now: string;\n}\n\nexport interface WorkflowDefinition<I, O> {\n readonly $diagonal: 'workflow';\n /** The declared input schema, when the workflow has one. */\n readonly input?: InputFieldSpec;\n /** Runs the handler with input that {@link parseWorkflowInput} already converted. */\n run(input: I, ctx: WorkflowContext): Promise<O>;\n}\n\n/**\n * Converts a run's raw input to the declared types. A runner calls it once and passes the result\n * to both `validateInput` and `run`, so the validator and the handler receive the same input.\n */\nexport function parseWorkflowInput<I>(workflow: WorkflowDefinition<I, unknown>, input: unknown): I {\n return (workflow.input === undefined ? input : coerceInput(workflow.input, input)) as I;\n}\n\n/**\n * The errors an input validator reports, keyed by input field. A key outside the input's own fields\n * (a nested path such as `tags.0`) is allowed; an empty or absent message means the field is valid.\n */\nexport type InputErrors<I> = Partial<Record<keyof I & string, string | string[]>> &\n Record<string, string | string[] | undefined>;\n\n/**\n * The `validateInput` export a script may define beside its workflow. It runs before the handler\n * with the same input and context; when it reports any error, the run ends with a 422 and those\n * errors, and the handler does not run.\n */\nexport type InputValidator<I> = (\n input: I,\n ctx: WorkflowContext\n) => InputErrors<I> | void | Promise<InputErrors<I> | void>;\n\n/** Runs a script's input validator and ends the run with a validation error when it reports one. */\nexport async function validateWorkflowInput<I>(\n validator: InputValidator<I>,\n input: I,\n ctx: WorkflowContext\n): Promise<void> {\n const reported = await validator(input, ctx);\n\n if (reported === undefined || reported === null) {\n return;\n }\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\n const errors: Record<string, string[]> = {};\n\n for (const [field, messages] of Object.entries(reported)) {\n const list = (Array.isArray(messages) ? messages : [messages]).filter(\n (message): message is string => typeof message === 'string' && message !== ''\n );\n\n if (list.length > 0) {\n errors[field] = list;\n }\n }\n\n if (Object.keys(errors).length > 0) {\n validationError(errors);\n }\n}\n\ntype Handler<I, O> = (input: I, ctx: WorkflowContext) => Promise<O> | O;\n\n/**\n * Declares a workflow. With an input schema first, the platform validates every run's input\n * against it before the script starts, and the handler's `input` type comes from the schema.\n */\nexport function defineWorkflow<S extends InputShape, O = unknown>(\n input: InputSchema<S>,\n handler: Handler<InferInput<S>, O>\n): WorkflowDefinition<InferInput<S>, O>;\nexport function defineWorkflow<I = Record<string, unknown>, O = unknown>(\n handler: Handler<I, O>\n): WorkflowDefinition<I, O>;\nexport function defineWorkflow<I, O>(\n inputOrHandler: InputSchema<InputShape> | Handler<I, O>,\n maybeHandler?: Handler<I, O>\n): WorkflowDefinition<I, O> {\n if (typeof inputOrHandler === 'function') {\n return { $diagonal: 'workflow', run: async (input, ctx) => inputOrHandler(input, ctx) };\n }\n\n const spec = inputOrHandler.$spec;\n const handler = maybeHandler;\n\n if (handler === undefined) {\n throw new TypeError('defineWorkflow(input, handler) needs a handler after the input schema.');\n }\n\n return {\n $diagonal: 'workflow',\n input: spec,\n run: async (input, ctx) => handler(input, ctx)\n };\n}\n\nexport type ResponseOutput = {\n $response_status: number;\n $response_body: unknown;\n $response_content_type: string;\n};\nexport type RedirectType = 'internal' | 'external' | 'back';\nexport type RedirectOutput = {\n redirect_url: string;\n redirect_type: RedirectType;\n permanent: boolean;\n success?: string;\n};\n\nexport function respond(\n body: unknown,\n options: { status?: number; contentType?: string } = {}\n): ResponseOutput {\n return {\n $response_status: options.status ?? 200,\n $response_body: body,\n $response_content_type: options.contentType ?? 'application/json'\n };\n}\n\n/**\n * Builds the output of a graph `http.redirect` step, with the same `redirect_type` and\n * `permanent` keys. Without a `type`, a path such as `/done` redirects as `internal`. Any other\n * URL, including a protocol-relative `//host`, redirects as `external`, because an Inertia\n * request cannot follow a plain redirect to another origin. A `back` redirect is never permanent.\n */\nexport function redirect(\n url: string,\n options: { success?: string; type?: RedirectType; permanent?: boolean } = {}\n): RedirectOutput {\n const type = options.type ?? (/^\\/(?![/\\\\])/.test(url) ? 'internal' : 'external');\n const output: RedirectOutput = {\n redirect_url: url,\n redirect_type: type,\n permanent: type !== 'back' && options.permanent === true\n };\n\n if (options.success !== undefined) {\n output.success = options.success;\n }\n\n return output;\n}\n", "/sdk/workspace.ts": "// The editor's slot for `@diagonal/workflow/workspace`: it replaces this file with the workspace's\n// declarations. Local runs import the file `diagonal-workflow pull-types` writes instead.\nexport const resources: Record<string, string> = {};\nexport const notificationTypes: Record<string, string> = {};\nexport const notificationTemplates: Record<string, Record<string, string>> = {};\n" };
|
|
248591
248591
|
LIB_FILES = { "lib.es2023.d.ts": '/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved.\nLicensed under the Apache License, Version 2.0 (the "License"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0\n\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\nMERCHANTABILITY OR NON-INFRINGEMENT.\n\nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n/// <reference lib="es2022" />\n/// <reference lib="es2023.array" />\n/// <reference lib="es2023.collection" />\n/// <reference lib="es2023.intl" />\n', "lib.es2023.intl.d.ts": '/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved.\nLicensed under the Apache License, Version 2.0 (the "License"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0\n\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\nMERCHANTABILITY OR NON-INFRINGEMENT.\n\nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\ndeclare namespace Intl {\n interface NumberFormatOptionsUseGroupingRegistry {\n min2: never;\n auto: never;\n always: never;\n }\n\n interface NumberFormatOptionsSignDisplayRegistry {\n negative: never;\n }\n\n interface NumberFormatRangePartTypeRegistry extends NumberFormatPartTypeRegistry {\n approximatelySign: never;\n }\n\n type NumberFormatRangePartTypes = keyof NumberFormatRangePartTypeRegistry;\n\n interface NumberFormatOptions {\n roundingPriority?: "auto" | "morePrecision" | "lessPrecision" | undefined;\n roundingIncrement?: 1 | 2 | 5 | 10 | 20 | 25 | 50 | 100 | 200 | 250 | 500 | 1000 | 2000 | 2500 | 5000 | undefined;\n roundingMode?: "ceil" | "floor" | "expand" | "trunc" | "halfCeil" | "halfFloor" | "halfExpand" | "halfTrunc" | "halfEven" | undefined;\n trailingZeroDisplay?: "auto" | "stripIfInteger" | undefined;\n }\n\n interface ResolvedNumberFormatOptions {\n roundingPriority: "auto" | "morePrecision" | "lessPrecision";\n roundingMode: "ceil" | "floor" | "expand" | "trunc" | "halfCeil" | "halfFloor" | "halfExpand" | "halfTrunc" | "halfEven";\n roundingIncrement: 1 | 2 | 5 | 10 | 20 | 25 | 50 | 100 | 200 | 250 | 500 | 1000 | 2000 | 2500 | 5000;\n trailingZeroDisplay: "auto" | "stripIfInteger";\n }\n\n interface NumberRangeFormatPart {\n type: NumberFormatRangePartTypes;\n value: string;\n source: "startRange" | "endRange" | "shared";\n }\n\n type StringNumericLiteral = `${number}` | "Infinity" | "-Infinity" | "+Infinity";\n\n interface NumberFormat {\n format(value: number | bigint | StringNumericLiteral): string;\n formatToParts(value: number | bigint | StringNumericLiteral): NumberFormatPart[];\n formatRange(start: number | bigint | StringNumericLiteral, end: number | bigint | StringNumericLiteral): string;\n formatRangeToParts(start: number | bigint | StringNumericLiteral, end: number | bigint | StringNumericLiteral): NumberRangeFormatPart[];\n }\n}\n', "lib.es2023.collection.d.ts": '/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved.\nLicensed under the Apache License, Version 2.0 (the "License"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0\n\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\nMERCHANTABILITY OR NON-INFRINGEMENT.\n\nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\ninterface WeakKeyTypes {\n symbol: symbol;\n}\n', "lib.es2023.array.d.ts": "/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved.\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0\n\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\nMERCHANTABILITY OR NON-INFRINGEMENT.\n\nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\ninterface Array<T> {\n /**\n * Returns the value of the last element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate findLast calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found, findLast\n * immediately returns that element value. Otherwise, findLast returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findLast<S extends T>(predicate: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S | undefined;\n findLast(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): T | undefined;\n\n /**\n * Returns the index of the last element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate findLastIndex calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findLastIndex(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): number;\n\n /**\n * Returns a copy of an array with its elements reversed.\n */\n toReversed(): T[];\n\n /**\n * Returns a copy of an array with its elements sorted.\n * @param compareFn Function used to determine the order of the elements. It is expected to return\n * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive\n * value otherwise. If omitted, the elements are sorted in ascending, UTF-16 code unit order.\n * ```ts\n * [11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22]\n * ```\n */\n toSorted(compareFn?: (a: T, b: T) => number): T[];\n\n /**\n * Copies an array and removes elements and, if necessary, inserts new elements in their place. Returns the copied array.\n * @param start The zero-based location in the array from which to start removing elements.\n * @param deleteCount The number of elements to remove.\n * @param items Elements to insert into the copied array in place of the deleted elements.\n * @returns The copied array.\n */\n toSpliced(start: number, deleteCount: number, ...items: T[]): T[];\n\n /**\n * Copies an array and removes elements while returning the remaining elements.\n * @param start The zero-based location in the array from which to start removing elements.\n * @param deleteCount The number of elements to remove.\n * @returns A copy of the original array with the remaining elements.\n */\n toSpliced(start: number, deleteCount?: number): T[];\n\n /**\n * Copies an array, then overwrites the value at the provided index with the\n * given value. If the index is negative, then it replaces from the end\n * of the array.\n * @param index The index of the value to overwrite. If the index is\n * negative, then it replaces from the end of the array.\n * @param value The value to write into the copied array.\n * @returns The copied array with the updated value.\n */\n with(index: number, value: T): T[];\n}\n\ninterface ReadonlyArray<T> {\n /**\n * Returns the value of the last element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate findLast calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found, findLast\n * immediately returns that element value. Otherwise, findLast returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findLast<S extends T>(\n predicate: (value: T, index: number, array: readonly T[]) => value is S,\n thisArg?: any,\n ): S | undefined;\n findLast(\n predicate: (value: T, index: number, array: readonly T[]) => unknown,\n thisArg?: any,\n ): T | undefined;\n\n /**\n * Returns the index of the last element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate findLastIndex calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findLastIndex(\n predicate: (value: T, index: number, array: readonly T[]) => unknown,\n thisArg?: any,\n ): number;\n\n /**\n * Copies the array and returns the copied array with all of its elements reversed.\n */\n toReversed(): T[];\n\n /**\n * Copies and sorts the array.\n * @param compareFn Function used to determine the order of the elements. It is expected to return\n * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive\n * value otherwise. If omitted, the elements are sorted in ascending, UTF-16 code unit order.\n * ```ts\n * [11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22]\n * ```\n */\n toSorted(compareFn?: (a: T, b: T) => number): T[];\n\n /**\n * Copies an array and removes elements while, if necessary, inserting new elements in their place, returning the remaining elements.\n * @param start The zero-based location in the array from which to start removing elements.\n * @param deleteCount The number of elements to remove.\n * @param items Elements to insert into the copied array in place of the deleted elements.\n * @returns A copy of the original array with the remaining elements.\n */\n toSpliced(start: number, deleteCount: number, ...items: T[]): T[];\n\n /**\n * Copies an array and removes elements while returning the remaining elements.\n * @param start The zero-based location in the array from which to start removing elements.\n * @param deleteCount The number of elements to remove.\n * @returns A copy of the original array with the remaining elements.\n */\n toSpliced(start: number, deleteCount?: number): T[];\n\n /**\n * Copies an array, then overwrites the value at the provided index with the\n * given value. If the index is negative, then it replaces from the end\n * of the array\n * @param index The index of the value to overwrite. If the index is\n * negative, then it replaces from the end of the array.\n * @param value The value to insert into the copied array.\n * @returns A copy of the original array with the inserted value.\n */\n with(index: number, value: T): T[];\n}\n\ninterface Int8Array<TArrayBuffer extends ArrayBufferLike> {\n /**\n * Returns the value of the last element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate findLast calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found, findLast\n * immediately returns that element value. Otherwise, findLast returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findLast<S extends number>(\n predicate: (\n value: number,\n index: number,\n array: this,\n ) => value is S,\n thisArg?: any,\n ): S | undefined;\n findLast(\n predicate: (value: number, index: number, array: this) => unknown,\n thisArg?: any,\n ): number | undefined;\n\n /**\n * Returns the index of the last element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate findLastIndex calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findLastIndex(\n predicate: (value: number, index: number, array: this) => unknown,\n thisArg?: any,\n ): number;\n\n /**\n * Copies the array and returns the copy with the elements in reverse order.\n */\n toReversed(): Int8Array<ArrayBuffer>;\n\n /**\n * Copies and sorts the array.\n * @param compareFn Function used to determine the order of the elements. It is expected to return\n * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive\n * value otherwise. If omitted, the elements are sorted in ascending order.\n * ```ts\n * const myNums = Int8Array.from([11, 2, 22, 1]);\n * myNums.toSorted((a, b) => a - b) // Int8Array(4) [1, 2, 11, 22]\n * ```\n */\n toSorted(compareFn?: (a: number, b: number) => number): Int8Array<ArrayBuffer>;\n\n /**\n * Copies the array and inserts the given number at the provided index.\n * @param index The index of the value to overwrite. If the index is\n * negative, then it replaces from the end of the array.\n * @param value The value to insert into the copied array.\n * @returns A copy of the original array with the inserted value.\n */\n with(index: number, value: number): Int8Array<ArrayBuffer>;\n}\n\ninterface Uint8Array<TArrayBuffer extends ArrayBufferLike> {\n /**\n * Returns the value of the last element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate findLast calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found, findLast\n * immediately returns that element value. Otherwise, findLast returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findLast<S extends number>(\n predicate: (\n value: number,\n index: number,\n array: this,\n ) => value is S,\n thisArg?: any,\n ): S | undefined;\n findLast(\n predicate: (value: number, index: number, array: this) => unknown,\n thisArg?: any,\n ): number | undefined;\n\n /**\n * Returns the index of the last element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate findLastIndex calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findLastIndex(\n predicate: (value: number, index: number, array: this) => unknown,\n thisArg?: any,\n ): number;\n\n /**\n * Copies the array and returns the copy with the elements in reverse order.\n */\n toReversed(): Uint8Array<ArrayBuffer>;\n\n /**\n * Copies and sorts the array.\n * @param compareFn Function used to determine the order of the elements. It is expected to return\n * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive\n * value otherwise. If omitted, the elements are sorted in ascending order.\n * ```ts\n * const myNums = Uint8Array.from([11, 2, 22, 1]);\n * myNums.toSorted((a, b) => a - b) // Uint8Array(4) [1, 2, 11, 22]\n * ```\n */\n toSorted(compareFn?: (a: number, b: number) => number): Uint8Array<ArrayBuffer>;\n\n /**\n * Copies the array and inserts the given number at the provided index.\n * @param index The index of the value to overwrite. If the index is\n * negative, then it replaces from the end of the array.\n * @param value The value to insert into the copied array.\n * @returns A copy of the original array with the inserted value.\n */\n with(index: number, value: number): Uint8Array<ArrayBuffer>;\n}\n\ninterface Uint8ClampedArray<TArrayBuffer extends ArrayBufferLike> {\n /**\n * Returns the value of the last element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate findLast calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found, findLast\n * immediately returns that element value. Otherwise, findLast returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findLast<S extends number>(\n predicate: (\n value: number,\n index: number,\n array: this,\n ) => value is S,\n thisArg?: any,\n ): S | undefined;\n findLast(\n predicate: (\n value: number,\n index: number,\n array: this,\n ) => unknown,\n thisArg?: any,\n ): number | undefined;\n\n /**\n * Returns the index of the last element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate findLastIndex calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findLastIndex(\n predicate: (\n value: number,\n index: number,\n array: this,\n ) => unknown,\n thisArg?: any,\n ): number;\n\n /**\n * Copies the array and returns the copy with the elements in reverse order.\n */\n toReversed(): Uint8ClampedArray<ArrayBuffer>;\n\n /**\n * Copies and sorts the array.\n * @param compareFn Function used to determine the order of the elements. It is expected to return\n * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive\n * value otherwise. If omitted, the elements are sorted in ascending order.\n * ```ts\n * const myNums = Uint8ClampedArray.from([11, 2, 22, 1]);\n * myNums.toSorted((a, b) => a - b) // Uint8ClampedArray(4) [1, 2, 11, 22]\n * ```\n */\n toSorted(compareFn?: (a: number, b: number) => number): Uint8ClampedArray<ArrayBuffer>;\n\n /**\n * Copies the array and inserts the given number at the provided index.\n * @param index The index of the value to overwrite. If the index is\n * negative, then it replaces from the end of the array.\n * @param value The value to insert into the copied array.\n * @returns A copy of the original array with the inserted value.\n */\n with(index: number, value: number): Uint8ClampedArray<ArrayBuffer>;\n}\n\ninterface Int16Array<TArrayBuffer extends ArrayBufferLike> {\n /**\n * Returns the value of the last element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate findLast calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found, findLast\n * immediately returns that element value. Otherwise, findLast returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findLast<S extends number>(\n predicate: (\n value: number,\n index: number,\n array: this,\n ) => value is S,\n thisArg?: any,\n ): S | undefined;\n findLast(\n predicate: (value: number, index: number, array: this) => unknown,\n thisArg?: any,\n ): number | undefined;\n\n /**\n * Returns the index of the last element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate findLastIndex calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findLastIndex(\n predicate: (value: number, index: number, array: this) => unknown,\n thisArg?: any,\n ): number;\n\n /**\n * Copies the array and returns the copy with the elements in reverse order.\n */\n toReversed(): Int16Array<ArrayBuffer>;\n\n /**\n * Copies and sorts the array.\n * @param compareFn Function used to determine the order of the elements. It is expected to return\n * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive\n * value otherwise. If omitted, the elements are sorted in ascending order.\n * ```ts\n * const myNums = Int16Array.from([11, 2, -22, 1]);\n * myNums.toSorted((a, b) => a - b) // Int16Array(4) [-22, 1, 2, 11]\n * ```\n */\n toSorted(compareFn?: (a: number, b: number) => number): Int16Array<ArrayBuffer>;\n\n /**\n * Copies the array and inserts the given number at the provided index.\n * @param index The index of the value to overwrite. If the index is\n * negative, then it replaces from the end of the array.\n * @param value The value to insert into the copied array.\n * @returns A copy of the original array with the inserted value.\n */\n with(index: number, value: number): Int16Array<ArrayBuffer>;\n}\n\ninterface Uint16Array<TArrayBuffer extends ArrayBufferLike> {\n /**\n * Returns the value of the last element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate findLast calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found, findLast\n * immediately returns that element value. Otherwise, findLast returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findLast<S extends number>(\n predicate: (\n value: number,\n index: number,\n array: this,\n ) => value is S,\n thisArg?: any,\n ): S | undefined;\n findLast(\n predicate: (\n value: number,\n index: number,\n array: this,\n ) => unknown,\n thisArg?: any,\n ): number | undefined;\n\n /**\n * Returns the index of the last element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate findLastIndex calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findLastIndex(\n predicate: (\n value: number,\n index: number,\n array: this,\n ) => unknown,\n thisArg?: any,\n ): number;\n\n /**\n * Copies the array and returns the copy with the elements in reverse order.\n */\n toReversed(): Uint16Array<ArrayBuffer>;\n\n /**\n * Copies and sorts the array.\n * @param compareFn Function used to determine the order of the elements. It is expected to return\n * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive\n * value otherwise. If omitted, the elements are sorted in ascending order.\n * ```ts\n * const myNums = Uint16Array.from([11, 2, 22, 1]);\n * myNums.toSorted((a, b) => a - b) // Uint16Array(4) [1, 2, 11, 22]\n * ```\n */\n toSorted(compareFn?: (a: number, b: number) => number): Uint16Array<ArrayBuffer>;\n\n /**\n * Copies the array and inserts the given number at the provided index.\n * @param index The index of the value to overwrite. If the index is\n * negative, then it replaces from the end of the array.\n * @param value The value to insert into the copied array.\n * @returns A copy of the original array with the inserted value.\n */\n with(index: number, value: number): Uint16Array<ArrayBuffer>;\n}\n\ninterface Int32Array<TArrayBuffer extends ArrayBufferLike> {\n /**\n * Returns the value of the last element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate findLast calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found, findLast\n * immediately returns that element value. Otherwise, findLast returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findLast<S extends number>(\n predicate: (\n value: number,\n index: number,\n array: this,\n ) => value is S,\n thisArg?: any,\n ): S | undefined;\n findLast(\n predicate: (value: number, index: number, array: this) => unknown,\n thisArg?: any,\n ): number | undefined;\n\n /**\n * Returns the index of the last element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate findLastIndex calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findLastIndex(\n predicate: (value: number, index: number, array: this) => unknown,\n thisArg?: any,\n ): number;\n\n /**\n * Copies the array and returns the copy with the elements in reverse order.\n */\n toReversed(): Int32Array<ArrayBuffer>;\n\n /**\n * Copies and sorts the array.\n * @param compareFn Function used to determine the order of the elements. It is expected to return\n * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive\n * value otherwise. If omitted, the elements are sorted in ascending order.\n * ```ts\n * const myNums = Int32Array.from([11, 2, -22, 1]);\n * myNums.toSorted((a, b) => a - b) // Int32Array(4) [-22, 1, 2, 11]\n * ```\n */\n toSorted(compareFn?: (a: number, b: number) => number): Int32Array<ArrayBuffer>;\n\n /**\n * Copies the array and inserts the given number at the provided index.\n * @param index The index of the value to overwrite. If the index is\n * negative, then it replaces from the end of the array.\n * @param value The value to insert into the copied array.\n * @returns A copy of the original array with the inserted value.\n */\n with(index: number, value: number): Int32Array<ArrayBuffer>;\n}\n\ninterface Uint32Array<TArrayBuffer extends ArrayBufferLike> {\n /**\n * Returns the value of the last element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate findLast calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found, findLast\n * immediately returns that element value. Otherwise, findLast returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findLast<S extends number>(\n predicate: (\n value: number,\n index: number,\n array: this,\n ) => value is S,\n thisArg?: any,\n ): S | undefined;\n findLast(\n predicate: (\n value: number,\n index: number,\n array: this,\n ) => unknown,\n thisArg?: any,\n ): number | undefined;\n\n /**\n * Returns the index of the last element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate findLastIndex calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findLastIndex(\n predicate: (\n value: number,\n index: number,\n array: this,\n ) => unknown,\n thisArg?: any,\n ): number;\n\n /**\n * Copies the array and returns the copy with the elements in reverse order.\n */\n toReversed(): Uint32Array<ArrayBuffer>;\n\n /**\n * Copies and sorts the array.\n * @param compareFn Function used to determine the order of the elements. It is expected to return\n * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive\n * value otherwise. If omitted, the elements are sorted in ascending order.\n * ```ts\n * const myNums = Uint32Array.from([11, 2, 22, 1]);\n * myNums.toSorted((a, b) => a - b) // Uint32Array(4) [1, 2, 11, 22]\n * ```\n */\n toSorted(compareFn?: (a: number, b: number) => number): Uint32Array<ArrayBuffer>;\n\n /**\n * Copies the array and inserts the given number at the provided index.\n * @param index The index of the value to overwrite. If the index is\n * negative, then it replaces from the end of the array.\n * @param value The value to insert into the copied array.\n * @returns A copy of the original array with the inserted value.\n */\n with(index: number, value: number): Uint32Array<ArrayBuffer>;\n}\n\ninterface Float32Array<TArrayBuffer extends ArrayBufferLike> {\n /**\n * Returns the value of the last element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate findLast calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found, findLast\n * immediately returns that element value. Otherwise, findLast returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findLast<S extends number>(\n predicate: (\n value: number,\n index: number,\n array: this,\n ) => value is S,\n thisArg?: any,\n ): S | undefined;\n findLast(\n predicate: (\n value: number,\n index: number,\n array: this,\n ) => unknown,\n thisArg?: any,\n ): number | undefined;\n\n /**\n * Returns the index of the last element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate findLastIndex calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findLastIndex(\n predicate: (\n value: number,\n index: number,\n array: this,\n ) => unknown,\n thisArg?: any,\n ): number;\n\n /**\n * Copies the array and returns the copy with the elements in reverse order.\n */\n toReversed(): Float32Array<ArrayBuffer>;\n\n /**\n * Copies and sorts the array.\n * @param compareFn Function used to determine the order of the elements. It is expected to return\n * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive\n * value otherwise. If omitted, the elements are sorted in ascending order.\n * ```ts\n * const myNums = Float32Array.from([11.25, 2, -22.5, 1]);\n * myNums.toSorted((a, b) => a - b) // Float32Array(4) [-22.5, 1, 2, 11.5]\n * ```\n */\n toSorted(compareFn?: (a: number, b: number) => number): Float32Array<ArrayBuffer>;\n\n /**\n * Copies the array and inserts the given number at the provided index.\n * @param index The index of the value to overwrite. If the index is\n * negative, then it replaces from the end of the array.\n * @param value The value to insert into the copied array.\n * @returns A copy of the original array with the inserted value.\n */\n with(index: number, value: number): Float32Array<ArrayBuffer>;\n}\n\ninterface Float64Array<TArrayBuffer extends ArrayBufferLike> {\n /**\n * Returns the value of the last element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate findLast calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found, findLast\n * immediately returns that element value. Otherwise, findLast returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findLast<S extends number>(\n predicate: (\n value: number,\n index: number,\n array: this,\n ) => value is S,\n thisArg?: any,\n ): S | undefined;\n findLast(\n predicate: (\n value: number,\n index: number,\n array: this,\n ) => unknown,\n thisArg?: any,\n ): number | undefined;\n\n /**\n * Returns the index of the last element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate findLastIndex calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findLastIndex(\n predicate: (\n value: number,\n index: number,\n array: this,\n ) => unknown,\n thisArg?: any,\n ): number;\n\n /**\n * Copies the array and returns the copy with the elements in reverse order.\n */\n toReversed(): Float64Array<ArrayBuffer>;\n\n /**\n * Copies and sorts the array.\n * @param compareFn Function used to determine the order of the elements. It is expected to return\n * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive\n * value otherwise. If omitted, the elements are sorted in ascending order.\n * ```ts\n * const myNums = Float64Array.from([11.25, 2, -22.5, 1]);\n * myNums.toSorted((a, b) => a - b) // Float64Array(4) [-22.5, 1, 2, 11.5]\n * ```\n */\n toSorted(compareFn?: (a: number, b: number) => number): Float64Array<ArrayBuffer>;\n\n /**\n * Copies the array and inserts the given number at the provided index.\n * @param index The index of the value to overwrite. If the index is\n * negative, then it replaces from the end of the array.\n * @param value The value to insert into the copied array.\n * @returns A copy of the original array with the inserted value.\n */\n with(index: number, value: number): Float64Array<ArrayBuffer>;\n}\n\ninterface BigInt64Array<TArrayBuffer extends ArrayBufferLike> {\n /**\n * Returns the value of the last element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate findLast calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found, findLast\n * immediately returns that element value. Otherwise, findLast returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findLast<S extends bigint>(\n predicate: (\n value: bigint,\n index: number,\n array: this,\n ) => value is S,\n thisArg?: any,\n ): S | undefined;\n findLast(\n predicate: (\n value: bigint,\n index: number,\n array: this,\n ) => unknown,\n thisArg?: any,\n ): bigint | undefined;\n\n /**\n * Returns the index of the last element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate findLastIndex calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findLastIndex(\n predicate: (\n value: bigint,\n index: number,\n array: this,\n ) => unknown,\n thisArg?: any,\n ): number;\n\n /**\n * Copies the array and returns the copy with the elements in reverse order.\n */\n toReversed(): BigInt64Array<ArrayBuffer>;\n\n /**\n * Copies and sorts the array.\n * @param compareFn Function used to determine the order of the elements. It is expected to return\n * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive\n * value otherwise. If omitted, the elements are sorted in ascending order.\n * ```ts\n * const myNums = BigInt64Array.from([11n, 2n, -22n, 1n]);\n * myNums.toSorted((a, b) => Number(a - b)) // BigInt64Array(4) [-22n, 1n, 2n, 11n]\n * ```\n */\n toSorted(compareFn?: (a: bigint, b: bigint) => number): BigInt64Array<ArrayBuffer>;\n\n /**\n * Copies the array and inserts the given bigint at the provided index.\n * @param index The index of the value to overwrite. If the index is\n * negative, then it replaces from the end of the array.\n * @param value The value to insert into the copied array.\n * @returns A copy of the original array with the inserted value.\n */\n with(index: number, value: bigint): BigInt64Array<ArrayBuffer>;\n}\n\ninterface BigUint64Array<TArrayBuffer extends ArrayBufferLike> {\n /**\n * Returns the value of the last element in the array where predicate is true, and undefined\n * otherwise.\n * @param predicate findLast calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found, findLast\n * immediately returns that element value. Otherwise, findLast returns undefined.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findLast<S extends bigint>(\n predicate: (\n value: bigint,\n index: number,\n array: this,\n ) => value is S,\n thisArg?: any,\n ): S | undefined;\n findLast(\n predicate: (\n value: bigint,\n index: number,\n array: this,\n ) => unknown,\n thisArg?: any,\n ): bigint | undefined;\n\n /**\n * Returns the index of the last element in the array where predicate is true, and -1\n * otherwise.\n * @param predicate findLastIndex calls predicate once for each element of the array, in descending\n * order, until it finds one where predicate returns true. If such an element is found,\n * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.\n * @param thisArg If provided, it will be used as the this value for each invocation of\n * predicate. If it is not provided, undefined is used instead.\n */\n findLastIndex(\n predicate: (\n value: bigint,\n index: number,\n array: this,\n ) => unknown,\n thisArg?: any,\n ): number;\n\n /**\n * Copies the array and returns the copy with the elements in reverse order.\n */\n toReversed(): BigUint64Array<ArrayBuffer>;\n\n /**\n * Copies and sorts the array.\n * @param compareFn Function used to determine the order of the elements. It is expected to return\n * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive\n * value otherwise. If omitted, the elements are sorted in ascending order.\n * ```ts\n * const myNums = BigUint64Array.from([11n, 2n, 22n, 1n]);\n * myNums.toSorted((a, b) => Number(a - b)) // BigUint64Array(4) [1n, 2n, 11n, 22n]\n * ```\n */\n toSorted(compareFn?: (a: bigint, b: bigint) => number): BigUint64Array<ArrayBuffer>;\n\n /**\n * Copies the array and inserts the given bigint at the provided index.\n * @param index The index of the value to overwrite. If the index is\n * negative, then it replaces from the end of the array.\n * @param value The value to insert into the copied array.\n * @returns A copy of the original array with the inserted value.\n */\n with(index: number, value: bigint): BigUint64Array<ArrayBuffer>;\n}\n", "lib.es2022.d.ts": '/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved.\nLicensed under the Apache License, Version 2.0 (the "License"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0\n\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\nMERCHANTABILITY OR NON-INFRINGEMENT.\n\nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n/// <reference lib="es2021" />\n/// <reference lib="es2022.array" />\n/// <reference lib="es2022.error" />\n/// <reference lib="es2022.intl" />\n/// <reference lib="es2022.object" />\n/// <reference lib="es2022.regexp" />\n/// <reference lib="es2022.string" />\n', "lib.es2022.string.d.ts": '/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved.\nLicensed under the Apache License, Version 2.0 (the "License"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0\n\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\nMERCHANTABILITY OR NON-INFRINGEMENT.\n\nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\ninterface String {\n /**\n * Returns a new String consisting of the single UTF-16 code unit located at the specified index.\n * @param index The zero-based index of the desired code unit. A negative index will count back from the last item.\n */\n at(index: number): string | undefined;\n}\n', "lib.es2022.regexp.d.ts": '/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved.\nLicensed under the Apache License, Version 2.0 (the "License"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0\n\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\nMERCHANTABILITY OR NON-INFRINGEMENT.\n\nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\ninterface RegExpMatchArray {\n indices?: RegExpIndicesArray;\n}\n\ninterface RegExpExecArray {\n indices?: RegExpIndicesArray;\n}\n\ninterface RegExpIndicesArray extends Array<[number, number] | undefined> {\n groups?: {\n [key: string]: [number, number];\n };\n}\n\ninterface RegExp {\n /**\n * Returns a Boolean value indicating the state of the hasIndices flag (d) used with a regular expression.\n * Default is false. Read-only.\n */\n readonly hasIndices: boolean;\n}\n', "lib.es2022.object.d.ts": '/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved.\nLicensed under the Apache License, Version 2.0 (the "License"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0\n\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\nMERCHANTABILITY OR NON-INFRINGEMENT.\n\nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\ninterface ObjectConstructor {\n /**\n * Determines whether an object has a property with the specified name.\n * @param o An object.\n * @param v A property name.\n */\n hasOwn(o: object, v: PropertyKey): boolean;\n}\n', "lib.es2022.intl.d.ts": '/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved.\nLicensed under the Apache License, Version 2.0 (the "License"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0\n\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\nMERCHANTABILITY OR NON-INFRINGEMENT.\n\nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\ndeclare namespace Intl {\n /**\n * An object with some or all properties of the `Intl.Segmenter` constructor `options` parameter.\n *\n * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/Segmenter#parameters)\n */\n interface SegmenterOptions {\n /** The locale matching algorithm to use. For information about this option, see [Intl page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation). */\n localeMatcher?: "best fit" | "lookup" | undefined;\n /** The type of input to be split */\n granularity?: "grapheme" | "word" | "sentence" | undefined;\n }\n\n /**\n * The `Intl.Segmenter` object enables locale-sensitive text segmentation, enabling you to get meaningful items (graphemes, words or sentences) from a string.\n *\n * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter)\n */\n interface Segmenter {\n /**\n * Returns `Segments` object containing the segments of the input string, using the segmenter\'s locale and granularity.\n *\n * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment)\n *\n * @param input - The text to be segmented as a `string`.\n *\n * @returns A new iterable Segments object containing the segments of the input string, using the segmenter\'s locale and granularity.\n */\n segment(input: string): Segments;\n /**\n * The `resolvedOptions()` method of `Intl.Segmenter` instances returns a new object with properties reflecting the options computed during initialization of this `Segmenter` object.\n *\n * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/resolvedOptions)\n */\n resolvedOptions(): ResolvedSegmenterOptions;\n }\n\n interface ResolvedSegmenterOptions {\n locale: string;\n granularity: "grapheme" | "word" | "sentence";\n }\n\n interface SegmentIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> {\n [Symbol.iterator](): SegmentIterator<T>;\n }\n\n /**\n * A `Segments` object is an iterable collection of the segments of a text string. It is returned by a call to the `segment()` method of an `Intl.Segmenter` object.\n *\n * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment/Segments)\n */\n interface Segments {\n /**\n * Returns an object describing the segment in the original string that includes the code unit at a specified index.\n *\n * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment/Segments/containing)\n *\n * @param codeUnitIndex - A number specifying the index of the code unit in the original input string. If the value is omitted, it defaults to `0`.\n */\n containing(codeUnitIndex?: number): SegmentData | undefined;\n\n /** Returns an iterator to iterate over the segments. */\n [Symbol.iterator](): SegmentIterator<SegmentData>;\n }\n\n interface SegmentData {\n /** A string containing the segment extracted from the original input string. */\n segment: string;\n /** The code unit index in the original input string at which the segment begins. */\n index: number;\n /** The complete input string that was segmented. */\n input: string;\n /**\n * A boolean value only if granularity is "word"; otherwise, undefined.\n * If granularity is "word", then isWordLike is true when the segment is word-like (i.e., consists of letters/numbers/ideographs/etc.); otherwise, false.\n */\n isWordLike?: boolean;\n }\n\n /**\n * The `Intl.Segmenter` object enables locale-sensitive text segmentation, enabling you to get meaningful items (graphemes, words or sentences) from a string.\n *\n * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter)\n */\n const Segmenter: {\n prototype: Segmenter;\n\n /**\n * Creates a new `Intl.Segmenter` object.\n *\n * @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings.\n * For the general form and interpretation of the `locales` argument,\n * see the [`Intl` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation).\n *\n * @param options - An [object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/Segmenter#parameters)\n * with some or all options of `SegmenterOptions`.\n *\n * @returns [Intl.Segmenter](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segments) object.\n *\n * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter).\n */\n new (locales?: LocalesArgument, options?: SegmenterOptions): Segmenter;\n\n /**\n * Returns an array containing those of the provided locales that are supported without having to fall back to the runtime\'s default locale.\n *\n * @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings.\n * For the general form and interpretation of the `locales` argument,\n * see the [`Intl` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation).\n *\n * @param options An [object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/supportedLocalesOf#parameters).\n * with some or all possible options.\n *\n * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/supportedLocalesOf)\n */\n supportedLocalesOf(locales: LocalesArgument, options?: Pick<SegmenterOptions, "localeMatcher">): UnicodeBCP47LocaleIdentifier[];\n };\n\n /**\n * Returns a sorted array of the supported collation, calendar, currency, numbering system, timezones, and units by the implementation.\n * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/supportedValuesOf)\n *\n * @param key A string indicating the category of values to return.\n * @returns A sorted array of the supported values.\n */\n function supportedValuesOf(key: "calendar" | "collation" | "currency" | "numberingSystem" | "timeZone" | "unit"): string[];\n}\n', "lib.es2022.error.d.ts": '/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved.\nLicensed under the Apache License, Version 2.0 (the "License"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0\n\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\nMERCHANTABILITY OR NON-INFRINGEMENT.\n\nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n/// <reference lib="es2021.promise" />\n\ninterface ErrorOptions {\n cause?: unknown;\n}\n\ninterface Error {\n cause?: unknown;\n}\n\ninterface ErrorConstructor {\n new (message?: string, options?: ErrorOptions): Error;\n (message?: string, options?: ErrorOptions): Error;\n}\n\ninterface EvalErrorConstructor {\n new (message?: string, options?: ErrorOptions): EvalError;\n (message?: string, options?: ErrorOptions): EvalError;\n}\n\ninterface RangeErrorConstructor {\n new (message?: string, options?: ErrorOptions): RangeError;\n (message?: string, options?: ErrorOptions): RangeError;\n}\n\ninterface ReferenceErrorConstructor {\n new (message?: string, options?: ErrorOptions): ReferenceError;\n (message?: string, options?: ErrorOptions): ReferenceError;\n}\n\ninterface SyntaxErrorConstructor {\n new (message?: string, options?: ErrorOptions): SyntaxError;\n (message?: string, options?: ErrorOptions): SyntaxError;\n}\n\ninterface TypeErrorConstructor {\n new (message?: string, options?: ErrorOptions): TypeError;\n (message?: string, options?: ErrorOptions): TypeError;\n}\n\ninterface URIErrorConstructor {\n new (message?: string, options?: ErrorOptions): URIError;\n (message?: string, options?: ErrorOptions): URIError;\n}\n\ninterface AggregateErrorConstructor {\n new (\n errors: Iterable<any>,\n message?: string,\n options?: ErrorOptions,\n ): AggregateError;\n (\n errors: Iterable<any>,\n message?: string,\n options?: ErrorOptions,\n ): AggregateError;\n}\n', "lib.es2021.promise.d.ts": '/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved.\nLicensed under the Apache License, Version 2.0 (the "License"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0\n\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\nMERCHANTABILITY OR NON-INFRINGEMENT.\n\nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\ninterface AggregateError extends Error {\n errors: any[];\n}\n\ninterface AggregateErrorConstructor {\n new (errors: Iterable<any>, message?: string): AggregateError;\n (errors: Iterable<any>, message?: string): AggregateError;\n readonly prototype: AggregateError;\n}\n\ndeclare var AggregateError: AggregateErrorConstructor;\n\n/**\n * Represents the completion of an asynchronous operation\n */\ninterface PromiseConstructor {\n /**\n * The any function returns a promise that is fulfilled by the first given promise to be fulfilled, or rejected with an AggregateError containing an array of rejection reasons if all of the given promises are rejected. It resolves all elements of the passed iterable to promises as it runs this algorithm.\n * @param values An array or iterable of Promises.\n * @returns A new Promise.\n */\n any<T extends readonly unknown[] | []>(values: T): Promise<Awaited<T[number]>>;\n\n /**\n * The any function returns a promise that is fulfilled by the first given promise to be fulfilled, or rejected with an AggregateError containing an array of rejection reasons if all of the given promises are rejected. It resolves all elements of the passed iterable to promises as it runs this algorithm.\n * @param values An array or iterable of Promises.\n * @returns A new Promise.\n */\n any<T>(values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>>;\n}\n', "lib.es2022.array.d.ts": '/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved.\nLicensed under the Apache License, Version 2.0 (the "License"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0\n\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\nMERCHANTABILITY OR NON-INFRINGEMENT.\n\nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\ninterface Array<T> {\n /**\n * Returns the item located at the specified index.\n * @param index The zero-based index of the desired code unit. A negative index will count back from the last item.\n */\n at(index: number): T | undefined;\n}\n\ninterface ReadonlyArray<T> {\n /**\n * Returns the item located at the specified index.\n * @param index The zero-based index of the desired code unit. A negative index will count back from the last item.\n */\n at(index: number): T | undefined;\n}\n\ninterface Int8Array<TArrayBuffer extends ArrayBufferLike> {\n /**\n * Returns the item located at the specified index.\n * @param index The zero-based index of the desired code unit. A negative index will count back from the last item.\n */\n at(index: number): number | undefined;\n}\n\ninterface Uint8Array<TArrayBuffer extends ArrayBufferLike> {\n /**\n * Returns the item located at the specified index.\n * @param index The zero-based index of the desired code unit. A negative index will count back from the last item.\n */\n at(index: number): number | undefined;\n}\n\ninterface Uint8ClampedArray<TArrayBuffer extends ArrayBufferLike> {\n /**\n * Returns the item located at the specified index.\n * @param index The zero-based index of the desired code unit. A negative index will count back from the last item.\n */\n at(index: number): number | undefined;\n}\n\ninterface Int16Array<TArrayBuffer extends ArrayBufferLike> {\n /**\n * Returns the item located at the specified index.\n * @param index The zero-based index of the desired code unit. A negative index will count back from the last item.\n */\n at(index: number): number | undefined;\n}\n\ninterface Uint16Array<TArrayBuffer extends ArrayBufferLike> {\n /**\n * Returns the item located at the specified index.\n * @param index The zero-based index of the desired code unit. A negative index will count back from the last item.\n */\n at(index: number): number | undefined;\n}\n\ninterface Int32Array<TArrayBuffer extends ArrayBufferLike> {\n /**\n * Returns the item located at the specified index.\n * @param index The zero-based index of the desired code unit. A negative index will count back from the last item.\n */\n at(index: number): number | undefined;\n}\n\ninterface Uint32Array<TArrayBuffer extends ArrayBufferLike> {\n /**\n * Returns the item located at the specified index.\n * @param index The zero-based index of the desired code unit. A negative index will count back from the last item.\n */\n at(index: number): number | undefined;\n}\n\ninterface Float32Array<TArrayBuffer extends ArrayBufferLike> {\n /**\n * Returns the item located at the specified index.\n * @param index The zero-based index of the desired code unit. A negative index will count back from the last item.\n */\n at(index: number): number | undefined;\n}\n\ninterface Float64Array<TArrayBuffer extends ArrayBufferLike> {\n /**\n * Returns the item located at the specified index.\n * @param index The zero-based index of the desired code unit. A negative index will count back from the last item.\n */\n at(index: number): number | undefined;\n}\n\ninterface BigInt64Array<TArrayBuffer extends ArrayBufferLike> {\n /**\n * Returns the item located at the specified index.\n * @param index The zero-based index of the desired code unit. A negative index will count back from the last item.\n */\n at(index: number): bigint | undefined;\n}\n\ninterface BigUint64Array<TArrayBuffer extends ArrayBufferLike> {\n /**\n * Returns the item located at the specified index.\n * @param index The zero-based index of the desired code unit. A negative index will count back from the last item.\n */\n at(index: number): bigint | undefined;\n}\n', "lib.es2021.d.ts": '/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved.\nLicensed under the Apache License, Version 2.0 (the "License"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0\n\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\nMERCHANTABILITY OR NON-INFRINGEMENT.\n\nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n/// <reference lib="es2020" />\n/// <reference lib="es2021.promise" />\n/// <reference lib="es2021.string" />\n/// <reference lib="es2021.weakref" />\n/// <reference lib="es2021.intl" />\n', "lib.es2021.intl.d.ts": '/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved.\nLicensed under the Apache License, Version 2.0 (the "License"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0\n\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\nMERCHANTABILITY OR NON-INFRINGEMENT.\n\nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\ndeclare namespace Intl {\n interface DateTimeFormatPartTypesRegistry {\n fractionalSecond: any;\n }\n\n interface DateTimeFormatOptions {\n formatMatcher?: "basic" | "best fit" | "best fit" | undefined;\n dateStyle?: "full" | "long" | "medium" | "short" | undefined;\n timeStyle?: "full" | "long" | "medium" | "short" | undefined;\n dayPeriod?: "narrow" | "short" | "long" | undefined;\n fractionalSecondDigits?: 1 | 2 | 3 | undefined;\n }\n\n interface DateTimeRangeFormatPart extends DateTimeFormatPart {\n source: "startRange" | "endRange" | "shared";\n }\n\n interface DateTimeFormat {\n formatRange(startDate: Date | number | bigint, endDate: Date | number | bigint): string;\n formatRangeToParts(startDate: Date | number | bigint, endDate: Date | number | bigint): DateTimeRangeFormatPart[];\n }\n\n interface ResolvedDateTimeFormatOptions {\n formatMatcher?: "basic" | "best fit" | "best fit";\n dateStyle?: "full" | "long" | "medium" | "short";\n timeStyle?: "full" | "long" | "medium" | "short";\n hourCycle?: "h11" | "h12" | "h23" | "h24";\n dayPeriod?: "narrow" | "short" | "long";\n fractionalSecondDigits?: 1 | 2 | 3;\n }\n\n /**\n * The locale matching algorithm to use.\n *\n * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters).\n */\n type ListFormatLocaleMatcher = "lookup" | "best fit";\n\n /**\n * The format of output message.\n *\n * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters).\n */\n type ListFormatType = "conjunction" | "disjunction" | "unit";\n\n /**\n * The length of the formatted message.\n *\n * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters).\n */\n type ListFormatStyle = "long" | "short" | "narrow";\n\n /**\n * An object with some or all properties of the `Intl.ListFormat` constructor `options` parameter.\n *\n * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters).\n */\n interface ListFormatOptions {\n /** The locale matching algorithm to use. For information about this option, see [Intl page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation). */\n localeMatcher?: ListFormatLocaleMatcher | undefined;\n /** The format of output message. */\n type?: ListFormatType | undefined;\n /** The length of the internationalized message. */\n style?: ListFormatStyle | undefined;\n }\n\n interface ResolvedListFormatOptions {\n locale: string;\n style: ListFormatStyle;\n type: ListFormatType;\n }\n\n interface ListFormat {\n /**\n * Returns a string with a language-specific representation of the list.\n *\n * @param list - An iterable object, such as an [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array).\n *\n * @throws `TypeError` if `list` includes something other than the possible values.\n *\n * @returns {string} A language-specific formatted string representing the elements of the list.\n *\n * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/format).\n */\n format(list: Iterable<string>): string;\n\n /**\n * Returns an Array of objects representing the different components that can be used to format a list of values in a locale-aware fashion.\n *\n * @param list - An iterable object, such as an [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array), to be formatted according to a locale.\n *\n * @throws `TypeError` if `list` includes something other than the possible values.\n *\n * @returns {{ type: "element" | "literal", value: string; }[]} An Array of components which contains the formatted parts from the list.\n *\n * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/formatToParts).\n */\n formatToParts(list: Iterable<string>): { type: "element" | "literal"; value: string; }[];\n\n /**\n * Returns a new object with properties reflecting the locale and style\n * formatting options computed during the construction of the current\n * `Intl.ListFormat` object.\n *\n * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/resolvedOptions).\n */\n resolvedOptions(): ResolvedListFormatOptions;\n }\n\n const ListFormat: {\n prototype: ListFormat;\n\n /**\n * Creates [Intl.ListFormat](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat) objects that\n * enable language-sensitive list formatting.\n *\n * @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings.\n * For the general form and interpretation of the `locales` argument,\n * see the [`Intl` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation).\n *\n * @param options - An [object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters)\n * with some or all options of `ListFormatOptions`.\n *\n * @returns [Intl.ListFormatOptions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat) object.\n *\n * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat).\n */\n new (locales?: LocalesArgument, options?: ListFormatOptions): ListFormat;\n\n /**\n * Returns an array containing those of the provided locales that are\n * supported in list formatting without having to fall back to the runtime\'s default locale.\n *\n * @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings.\n * For the general form and interpretation of the `locales` argument,\n * see the [`Intl` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation).\n *\n * @param options - An [object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/supportedLocalesOf#parameters).\n * with some or all possible options.\n *\n * @returns An array of strings representing a subset of the given locale tags that are supported in list\n * formatting without having to fall back to the runtime\'s default locale.\n *\n * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/supportedLocalesOf).\n */\n supportedLocalesOf(locales: LocalesArgument, options?: Pick<ListFormatOptions, "localeMatcher">): UnicodeBCP47LocaleIdentifier[];\n };\n}\n', "lib.es2021.weakref.d.ts": `/*! *****************************************************************************
|
|
248592
248592
|
Copyright (c) Microsoft Corporation. All rights reserved.
|
|
248593
248593
|
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
|
@@ -295331,7 +295331,7 @@ var APP_IMPORTS_FILE = "appImports.d.ts";
|
|
|
295331
295331
|
var PAGE_KEYS_FILE = "pageKeyCatalog.d.ts";
|
|
295332
295332
|
var sourceFileCache = /* @__PURE__ */ new Map();
|
|
295333
295333
|
function typeCheckPage(userSource, {
|
|
295334
|
-
ts:
|
|
295334
|
+
ts: ts8,
|
|
295335
295335
|
sdkLib: sdkLib2,
|
|
295336
295336
|
libFiles: libFiles3,
|
|
295337
295337
|
resources,
|
|
@@ -295386,7 +295386,7 @@ function typeCheckPage(userSource, {
|
|
|
295386
295386
|
virtual.set(file2.fileName, file2.content);
|
|
295387
295387
|
}
|
|
295388
295388
|
const options2 = {
|
|
295389
|
-
jsx:
|
|
295389
|
+
jsx: ts8.JsxEmit.React,
|
|
295390
295390
|
// Keep dynamic authoring conveniences such as implicit any, but enforce
|
|
295391
295391
|
// nullable SDK contracts so editor diagnostics and persistence gates catch
|
|
295392
295392
|
// unguarded null/undefined values before runtime. `noImplicitAny` is on for
|
|
@@ -295398,19 +295398,19 @@ function typeCheckPage(userSource, {
|
|
|
295398
295398
|
noEmit: true,
|
|
295399
295399
|
allowJs: true,
|
|
295400
295400
|
checkJs: true,
|
|
295401
|
-
target:
|
|
295401
|
+
target: ts8.ScriptTarget.ES2023,
|
|
295402
295402
|
// Modern browser runtime libs, shared with the editor (pageTypeCheckConfig.ts).
|
|
295403
295403
|
lib: [...TYPE_CHECK_LIB],
|
|
295404
295404
|
types: [],
|
|
295405
295405
|
...appPaths.length > 0 ? {
|
|
295406
|
-
module:
|
|
295407
|
-
moduleResolution:
|
|
295406
|
+
module: ts8.ModuleKind.ESNext,
|
|
295407
|
+
moduleResolution: ts8.ModuleResolutionKind.Bundler,
|
|
295408
295408
|
allowImportingTsExtensions: true,
|
|
295409
295409
|
paths: { "@app/*": ["/app/*"] }
|
|
295410
295410
|
} : {}
|
|
295411
295411
|
};
|
|
295412
|
-
const defaultLib =
|
|
295413
|
-
const libDir = libFiles3 ? null : dirname2(
|
|
295412
|
+
const defaultLib = ts8.getDefaultLibFileName(options2);
|
|
295413
|
+
const libDir = libFiles3 ? null : dirname2(ts8.getDefaultLibFilePath(options2));
|
|
295414
295414
|
const readLib = (name) => {
|
|
295415
295415
|
if (libFiles3) {
|
|
295416
295416
|
return libFiles3.get(name);
|
|
@@ -295426,14 +295426,14 @@ function typeCheckPage(userSource, {
|
|
|
295426
295426
|
return void 0;
|
|
295427
295427
|
}
|
|
295428
295428
|
if (name === USER_FILE) {
|
|
295429
|
-
return
|
|
295429
|
+
return ts8.createSourceFile(name, text, languageVersion, true);
|
|
295430
295430
|
}
|
|
295431
295431
|
const cacheKey = `${name}:${languageVersion}`;
|
|
295432
295432
|
const cached = sourceFileCache.get(cacheKey);
|
|
295433
295433
|
if (cached !== void 0 && cached.text === text) {
|
|
295434
295434
|
return cached.file;
|
|
295435
295435
|
}
|
|
295436
|
-
const file2 =
|
|
295436
|
+
const file2 = ts8.createSourceFile(name, text, languageVersion, true);
|
|
295437
295437
|
sourceFileCache.set(cacheKey, { text, file: file2 });
|
|
295438
295438
|
return file2;
|
|
295439
295439
|
},
|
|
@@ -295468,14 +295468,14 @@ function typeCheckPage(userSource, {
|
|
|
295468
295468
|
if (virtual.has(APP_IMPORTS_FILE)) {
|
|
295469
295469
|
rootFiles.push(APP_IMPORTS_FILE);
|
|
295470
295470
|
}
|
|
295471
|
-
const program3 =
|
|
295471
|
+
const program3 = ts8.createProgram(rootFiles, options2, host);
|
|
295472
295472
|
const userFile = program3.getSourceFile(USER_FILE);
|
|
295473
295473
|
const diagnostics = [
|
|
295474
295474
|
...program3.getSyntacticDiagnostics(userFile),
|
|
295475
295475
|
...program3.getSemanticDiagnostics(userFile)
|
|
295476
295476
|
];
|
|
295477
295477
|
return diagnostics.map((diagnostic2) => {
|
|
295478
|
-
const message =
|
|
295478
|
+
const message = ts8.flattenDiagnosticMessageText(diagnostic2.messageText, "\n");
|
|
295479
295479
|
let line = 0;
|
|
295480
295480
|
let column = 0;
|
|
295481
295481
|
if (diagnostic2.file && diagnostic2.start !== void 0) {
|
|
@@ -300795,7 +300795,7 @@ init_define_globalThis_DIAGONAL_SDK_RUNTIME();
|
|
|
300795
300795
|
|
|
300796
300796
|
// scripts/lib/workflow-script/compile.mjs
|
|
300797
300797
|
init_define_globalThis_DIAGONAL_SDK_RUNTIME();
|
|
300798
|
-
var
|
|
300798
|
+
var import_typescript7 = __toESM(require_typescript(), 1);
|
|
300799
300799
|
|
|
300800
300800
|
// scripts/lib/workflow-script/ast.mjs
|
|
300801
300801
|
init_define_globalThis_DIAGONAL_SDK_RUNTIME();
|
|
@@ -301113,8 +301113,193 @@ function readLibClosure(root = ROOT_LIB) {
|
|
|
301113
301113
|
|
|
301114
301114
|
// scripts/lib/workflow-script/lint-rules.mjs
|
|
301115
301115
|
init_define_globalThis_DIAGONAL_SDK_RUNTIME();
|
|
301116
|
+
var import_typescript6 = __toESM(require_typescript(), 1);
|
|
301117
|
+
|
|
301118
|
+
// scripts/lib/workflow-script/profile-rules.mjs
|
|
301119
|
+
init_define_globalThis_DIAGONAL_SDK_RUNTIME();
|
|
301116
301120
|
var import_typescript5 = __toESM(require_typescript(), 1);
|
|
301117
|
-
var
|
|
301121
|
+
var PROFILES = {
|
|
301122
|
+
workflow: {
|
|
301123
|
+
label: "A workflow script",
|
|
301124
|
+
imports: ["@diagonal/workflow", "@diagonal/workflow/workspace"],
|
|
301125
|
+
specifier: null,
|
|
301126
|
+
entry: null
|
|
301127
|
+
},
|
|
301128
|
+
test: {
|
|
301129
|
+
label: "A test script",
|
|
301130
|
+
imports: ["@diagonal/workflow", "@diagonal-hq/workflows/test", "@diagonal/workflow/workspace"],
|
|
301131
|
+
specifier: "@diagonal-hq/workflows/test",
|
|
301132
|
+
entry: "/sdk/profiles/test.ts"
|
|
301133
|
+
},
|
|
301134
|
+
migration: {
|
|
301135
|
+
label: "A migration script",
|
|
301136
|
+
imports: ["@diagonal-hq/workflows/migration", "@diagonal/workflow/workspace"],
|
|
301137
|
+
specifier: "@diagonal-hq/workflows/migration",
|
|
301138
|
+
entry: "/sdk/profiles/migration.ts"
|
|
301139
|
+
}
|
|
301140
|
+
};
|
|
301141
|
+
var PROFILE_SPECIFIERS = new Set(
|
|
301142
|
+
Object.values(PROFILES).flatMap(({ specifier }) => specifier === null ? [] : [specifier])
|
|
301143
|
+
);
|
|
301144
|
+
var SDK_SPECIFIERS = /* @__PURE__ */ new Set(["@diagonal/workflow", ...PROFILE_SPECIFIERS]);
|
|
301145
|
+
function resolveProfile(name) {
|
|
301146
|
+
if (name === void 0 || name === null) {
|
|
301147
|
+
return "workflow";
|
|
301148
|
+
}
|
|
301149
|
+
if (typeof name !== "string" || !Object.hasOwn(PROFILES, name)) {
|
|
301150
|
+
throw new Error(`Unknown workflow script profile: ${String(name)}`);
|
|
301151
|
+
}
|
|
301152
|
+
return name;
|
|
301153
|
+
}
|
|
301154
|
+
function profileFindings(file2, checker, program3, profile) {
|
|
301155
|
+
const { entry, label, specifier } = PROFILES[profile];
|
|
301156
|
+
if (entry === null) {
|
|
301157
|
+
return [];
|
|
301158
|
+
}
|
|
301159
|
+
const entryFile = program3.getSourceFile(entry);
|
|
301160
|
+
const entrySymbol = entryFile && checker.getSymbolAtLocation(entryFile);
|
|
301161
|
+
if (!entrySymbol) {
|
|
301162
|
+
throw new Error(`The SDK has no ${entry} module.`);
|
|
301163
|
+
}
|
|
301164
|
+
const exports = new Map(
|
|
301165
|
+
checker.getExportsOfModule(entrySymbol).map((symbol) => [symbol.getName(), symbol])
|
|
301166
|
+
);
|
|
301167
|
+
const findings = [];
|
|
301168
|
+
const forbidden = (node, path) => findings.push({
|
|
301169
|
+
node,
|
|
301170
|
+
code: "profile-capability",
|
|
301171
|
+
message: `${label} cannot use ${path}. Use only the exports of ${specifier}.`
|
|
301172
|
+
});
|
|
301173
|
+
const exportType = (name) => {
|
|
301174
|
+
const symbol = exports.get(name);
|
|
301175
|
+
const target = symbol && symbol.flags & import_typescript5.default.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
|
|
301176
|
+
return target && target.flags & import_typescript5.default.SymbolFlags.Value ? checker.getTypeOfSymbolAtLocation(target, entryFile) : null;
|
|
301177
|
+
};
|
|
301178
|
+
const checkMembers = (identifier4, type, path) => {
|
|
301179
|
+
let node = identifier4;
|
|
301180
|
+
let current = type;
|
|
301181
|
+
let currentPath = path;
|
|
301182
|
+
while (current !== null) {
|
|
301183
|
+
const parent = node.parent;
|
|
301184
|
+
const isMemberAccess = import_typescript5.default.isPropertyAccessExpression(parent) && parent.expression === node || import_typescript5.default.isElementAccessExpression(parent) && parent.expression === node && import_typescript5.default.isStringLiteralLike(parent.argumentExpression);
|
|
301185
|
+
if (!isMemberAccess) {
|
|
301186
|
+
if (current.getCallSignatures().length === 0 && hasRestrictedMembers(current, currentPath)) {
|
|
301187
|
+
forbidden(node, `${currentPath} as a value`);
|
|
301188
|
+
}
|
|
301189
|
+
return;
|
|
301190
|
+
}
|
|
301191
|
+
const member = import_typescript5.default.isPropertyAccessExpression(parent) ? parent.name.text : parent.argumentExpression.text;
|
|
301192
|
+
const property = current.getProperty(member);
|
|
301193
|
+
currentPath = `${currentPath}.${member}`;
|
|
301194
|
+
if (!property) {
|
|
301195
|
+
forbidden(parent, currentPath);
|
|
301196
|
+
return;
|
|
301197
|
+
}
|
|
301198
|
+
current = checker.getTypeOfSymbolAtLocation(property, entryFile);
|
|
301199
|
+
node = parent;
|
|
301200
|
+
}
|
|
301201
|
+
};
|
|
301202
|
+
const hasRestrictedMembers = (profileType, path) => {
|
|
301203
|
+
const rootType = rootNamespaceTypes.get(path);
|
|
301204
|
+
return rootType !== void 0 && rootType.getProperties().some((property) => !profileType.getProperty(property.getName()));
|
|
301205
|
+
};
|
|
301206
|
+
const rootNamespaceTypes = /* @__PURE__ */ new Map();
|
|
301207
|
+
const rootFile = program3.getSourceFile("/sdk/index.ts");
|
|
301208
|
+
const rootSymbol = rootFile && checker.getSymbolAtLocation(rootFile);
|
|
301209
|
+
for (const symbol of rootSymbol ? checker.getExportsOfModule(rootSymbol) : []) {
|
|
301210
|
+
const target = symbol.flags & import_typescript5.default.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
|
|
301211
|
+
if (target.flags & import_typescript5.default.SymbolFlags.Value) {
|
|
301212
|
+
collectNamespaceTypes(
|
|
301213
|
+
checker,
|
|
301214
|
+
symbol.getName(),
|
|
301215
|
+
checker.getTypeOfSymbolAtLocation(target, rootFile),
|
|
301216
|
+
rootFile,
|
|
301217
|
+
rootNamespaceTypes
|
|
301218
|
+
);
|
|
301219
|
+
}
|
|
301220
|
+
}
|
|
301221
|
+
const valueSymbol = (node) => import_typescript5.default.isShorthandPropertyAssignment(node.parent) && node.parent.name === node ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node);
|
|
301222
|
+
const references = (binding) => {
|
|
301223
|
+
const symbol = checker.getSymbolAtLocation(binding);
|
|
301224
|
+
const found2 = [];
|
|
301225
|
+
const visit = (node) => {
|
|
301226
|
+
if (import_typescript5.default.isIdentifier(node) && node !== binding && valueSymbol(node) === symbol && !import_typescript5.default.isImportSpecifier(node.parent)) {
|
|
301227
|
+
found2.push(node);
|
|
301228
|
+
}
|
|
301229
|
+
import_typescript5.default.forEachChild(node, visit);
|
|
301230
|
+
};
|
|
301231
|
+
visit(file2);
|
|
301232
|
+
return found2;
|
|
301233
|
+
};
|
|
301234
|
+
const checkNamespace = (binding) => {
|
|
301235
|
+
for (const reference of references(binding)) {
|
|
301236
|
+
const parent = reference.parent;
|
|
301237
|
+
if (!import_typescript5.default.isPropertyAccessExpression(parent) || parent.expression !== reference) {
|
|
301238
|
+
forbidden(reference, "the SDK namespace as a value");
|
|
301239
|
+
continue;
|
|
301240
|
+
}
|
|
301241
|
+
const name = parent.name.text;
|
|
301242
|
+
if (!exports.has(name)) {
|
|
301243
|
+
forbidden(parent, name);
|
|
301244
|
+
continue;
|
|
301245
|
+
}
|
|
301246
|
+
const type = exportType(name);
|
|
301247
|
+
if (type !== null) {
|
|
301248
|
+
checkMembers(parent, type, name);
|
|
301249
|
+
}
|
|
301250
|
+
}
|
|
301251
|
+
};
|
|
301252
|
+
for (const statement2 of file2.statements) {
|
|
301253
|
+
if (import_typescript5.default.isImportEqualsDeclaration(statement2) && import_typescript5.default.isExternalModuleReference(statement2.moduleReference) && import_typescript5.default.isStringLiteral(statement2.moduleReference.expression) && SDK_SPECIFIERS.has(statement2.moduleReference.expression.text)) {
|
|
301254
|
+
checkNamespace(statement2.name);
|
|
301255
|
+
continue;
|
|
301256
|
+
}
|
|
301257
|
+
if (!import_typescript5.default.isImportDeclaration(statement2) || !import_typescript5.default.isStringLiteral(statement2.moduleSpecifier) || !SDK_SPECIFIERS.has(statement2.moduleSpecifier.text) || !statement2.importClause) {
|
|
301258
|
+
continue;
|
|
301259
|
+
}
|
|
301260
|
+
const clause = statement2.importClause;
|
|
301261
|
+
if (clause.name) {
|
|
301262
|
+
forbidden(clause.name, "a default import of the SDK");
|
|
301263
|
+
}
|
|
301264
|
+
const bindings = clause.namedBindings;
|
|
301265
|
+
if (bindings && import_typescript5.default.isNamespaceImport(bindings)) {
|
|
301266
|
+
checkNamespace(bindings.name);
|
|
301267
|
+
continue;
|
|
301268
|
+
}
|
|
301269
|
+
for (const element of bindings && import_typescript5.default.isNamedImports(bindings) ? bindings.elements : []) {
|
|
301270
|
+
const name = (element.propertyName ?? element.name).text;
|
|
301271
|
+
if (!exports.has(name)) {
|
|
301272
|
+
forbidden(element, name);
|
|
301273
|
+
continue;
|
|
301274
|
+
}
|
|
301275
|
+
const type = exportType(name);
|
|
301276
|
+
if (type === null || element.isTypeOnly || clause.isTypeOnly) {
|
|
301277
|
+
continue;
|
|
301278
|
+
}
|
|
301279
|
+
for (const reference of references(element.name)) {
|
|
301280
|
+
checkMembers(reference, type, name);
|
|
301281
|
+
}
|
|
301282
|
+
}
|
|
301283
|
+
}
|
|
301284
|
+
return findings;
|
|
301285
|
+
}
|
|
301286
|
+
function collectNamespaceTypes(checker, path, type, location, into) {
|
|
301287
|
+
if (type.getCallSignatures().length > 0 || !(type.flags & import_typescript5.default.TypeFlags.Object)) {
|
|
301288
|
+
return;
|
|
301289
|
+
}
|
|
301290
|
+
into.set(path, type);
|
|
301291
|
+
for (const property of type.getProperties()) {
|
|
301292
|
+
collectNamespaceTypes(
|
|
301293
|
+
checker,
|
|
301294
|
+
`${path}.${property.getName()}`,
|
|
301295
|
+
checker.getTypeOfSymbolAtLocation(property, location),
|
|
301296
|
+
location,
|
|
301297
|
+
into
|
|
301298
|
+
);
|
|
301299
|
+
}
|
|
301300
|
+
}
|
|
301301
|
+
|
|
301302
|
+
// scripts/lib/workflow-script/lint-rules.mjs
|
|
301118
301303
|
var UNSUPPORTED_GLOBALS = {
|
|
301119
301304
|
Intl: "The sandbox has no Intl. Use date.format, time.format, money.format, or number.format.",
|
|
301120
301305
|
crypto: "The sandbox has no crypto. Use text.hash, text.randomUuid, or security.randomPassword.",
|
|
@@ -301132,31 +301317,31 @@ var MAIL_TEMPLATE_CAPABILITIES = {
|
|
|
301132
301317
|
var MAIL_REFERENCES_KEY = "$references";
|
|
301133
301318
|
var composedMailTextMessage = (capability, field2) => `Do not write values into the ${capability} ${field2}. The email evaluates this text as Liquid, so a value such as "{{ workspace.name }}" renders. Put each value in layoutData.${MAIL_REFERENCES_KEY} and write {{ ref.<key> }} in the text.`;
|
|
301134
301319
|
function staticPropertyName(property) {
|
|
301135
|
-
if (!
|
|
301320
|
+
if (!import_typescript6.default.isPropertyAssignment(property) && !import_typescript6.default.isShorthandPropertyAssignment(property)) {
|
|
301136
301321
|
return null;
|
|
301137
301322
|
}
|
|
301138
301323
|
return propertyNameText(property.name);
|
|
301139
301324
|
}
|
|
301140
301325
|
function floatingPromiseCalls(expression2, holdsPromise) {
|
|
301141
|
-
const node =
|
|
301142
|
-
if (
|
|
301326
|
+
const node = import_typescript6.default.skipParentheses(expression2);
|
|
301327
|
+
if (import_typescript6.default.isConditionalExpression(node)) {
|
|
301143
301328
|
return [
|
|
301144
301329
|
...floatingPromiseCalls(node.whenTrue, holdsPromise),
|
|
301145
301330
|
...floatingPromiseCalls(node.whenFalse, holdsPromise)
|
|
301146
301331
|
];
|
|
301147
301332
|
}
|
|
301148
|
-
if (
|
|
301149
|
-
|
|
301150
|
-
|
|
301151
|
-
|
|
301152
|
-
|
|
301333
|
+
if (import_typescript6.default.isBinaryExpression(node) && [
|
|
301334
|
+
import_typescript6.default.SyntaxKind.AmpersandAmpersandToken,
|
|
301335
|
+
import_typescript6.default.SyntaxKind.BarBarToken,
|
|
301336
|
+
import_typescript6.default.SyntaxKind.QuestionQuestionToken,
|
|
301337
|
+
import_typescript6.default.SyntaxKind.CommaToken
|
|
301153
301338
|
].includes(node.operatorToken.kind)) {
|
|
301154
301339
|
return [
|
|
301155
301340
|
...floatingPromiseCalls(node.left, holdsPromise),
|
|
301156
301341
|
...floatingPromiseCalls(node.right, holdsPromise)
|
|
301157
301342
|
];
|
|
301158
301343
|
}
|
|
301159
|
-
return (
|
|
301344
|
+
return (import_typescript6.default.isCallExpression(node) || import_typescript6.default.isArrayLiteralExpression(node)) && holdsPromise(node) ? [node] : [];
|
|
301160
301345
|
}
|
|
301161
301346
|
function returnsPromise(fn, checker) {
|
|
301162
301347
|
const signature = checker.getSignatureFromDeclaration(fn);
|
|
@@ -301165,21 +301350,25 @@ function returnsPromise(fn, checker) {
|
|
|
301165
301350
|
function contextuallyReturnsVoid(fn, checker) {
|
|
301166
301351
|
const signatures = checker.getContextualType(fn)?.getCallSignatures() ?? [];
|
|
301167
301352
|
return signatures.length > 0 && signatures.every(
|
|
301168
|
-
(signature) => (checker.getReturnTypeOfSignature(signature).flags &
|
|
301353
|
+
(signature) => (checker.getReturnTypeOfSignature(signature).flags & import_typescript6.default.TypeFlags.Void) !== 0
|
|
301169
301354
|
);
|
|
301170
301355
|
}
|
|
301171
301356
|
function isMemberName(node) {
|
|
301172
301357
|
const parent = node.parent;
|
|
301173
|
-
if (
|
|
301358
|
+
if (import_typescript6.default.isPropertyAccessExpression(parent) || import_typescript6.default.isQualifiedName(parent)) {
|
|
301174
301359
|
return parent.name === node || parent.right === node;
|
|
301175
301360
|
}
|
|
301176
|
-
if (
|
|
301361
|
+
if (import_typescript6.default.isBindingElement(parent) || import_typescript6.default.isImportSpecifier(parent) || import_typescript6.default.isExportSpecifier(parent)) {
|
|
301177
301362
|
return parent.propertyName === node;
|
|
301178
301363
|
}
|
|
301179
|
-
return (
|
|
301364
|
+
return (import_typescript6.default.isPropertyAssignment(parent) || import_typescript6.default.isPropertyDeclaration(parent) || import_typescript6.default.isPropertySignature(parent) || import_typescript6.default.isMethodDeclaration(parent) || import_typescript6.default.isMethodSignature(parent) || import_typescript6.default.isGetAccessorDeclaration(parent) || import_typescript6.default.isSetAccessorDeclaration(parent) || import_typescript6.default.isEnumMember(parent)) && parent.name === node;
|
|
301180
301365
|
}
|
|
301181
|
-
function lint2(file2, checker, { allowAppImports = false } = {}) {
|
|
301366
|
+
function lint2(file2, checker, { allowAppImports = false, profile = "workflow" } = {}) {
|
|
301182
301367
|
const findings = [];
|
|
301368
|
+
const { imports: allowedImports, label } = PROFILES[profile];
|
|
301369
|
+
const allowedImportList = new Intl.ListFormat("en", { type: "disjunction" }).format(
|
|
301370
|
+
allowedImports
|
|
301371
|
+
);
|
|
301183
301372
|
let defaultExport = null;
|
|
301184
301373
|
const isPromiseType = (type) => type.getSymbol()?.getName() === "Promise";
|
|
301185
301374
|
const holdsPromise = (node) => {
|
|
@@ -301200,31 +301389,31 @@ function lint2(file2, checker, { allowAppImports = false } = {}) {
|
|
|
301200
301389
|
};
|
|
301201
301390
|
const constValue = (expression2) => {
|
|
301202
301391
|
const node = unwrap(expression2);
|
|
301203
|
-
if (!
|
|
301392
|
+
if (!import_typescript6.default.isIdentifier(node)) {
|
|
301204
301393
|
return node;
|
|
301205
301394
|
}
|
|
301206
|
-
const symbol =
|
|
301395
|
+
const symbol = import_typescript6.default.isShorthandPropertyAssignment(node.parent) && node.parent.name === node ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node);
|
|
301207
301396
|
const declaration = symbol?.valueDeclaration;
|
|
301208
|
-
return declaration !== void 0 &&
|
|
301397
|
+
return declaration !== void 0 && import_typescript6.default.isVariableDeclaration(declaration) && declaration.initializer !== void 0 && declaration.getSourceFile() === file2 && (import_typescript6.default.getCombinedNodeFlags(declaration) & import_typescript6.default.NodeFlags.Const) !== 0 ? unwrap(declaration.initializer) : node;
|
|
301209
301398
|
};
|
|
301210
301399
|
const hasLiteralType = (node) => {
|
|
301211
301400
|
const type = checker.getTypeAtLocation(node);
|
|
301212
301401
|
return (type.isUnion() ? type.types : [type]).every(
|
|
301213
|
-
(member) => member.isLiteral() || (member.flags &
|
|
301402
|
+
(member) => member.isLiteral() || (member.flags & import_typescript6.default.TypeFlags.BooleanLiteral) !== 0
|
|
301214
301403
|
);
|
|
301215
301404
|
};
|
|
301216
301405
|
const isConstantText = (expression2, followed = /* @__PURE__ */ new Set()) => {
|
|
301217
301406
|
const node = unwrap(expression2);
|
|
301218
|
-
if (
|
|
301407
|
+
if (import_typescript6.default.isTemplateExpression(node)) {
|
|
301219
301408
|
return node.templateSpans.every((span) => isConstantText(span.expression, followed));
|
|
301220
301409
|
}
|
|
301221
|
-
if (
|
|
301410
|
+
if (import_typescript6.default.isBinaryExpression(node) && node.operatorToken.kind === import_typescript6.default.SyntaxKind.PlusToken) {
|
|
301222
301411
|
return isConstantText(node.left, followed) && isConstantText(node.right, followed);
|
|
301223
301412
|
}
|
|
301224
301413
|
if (hasLiteralType(node)) {
|
|
301225
301414
|
return true;
|
|
301226
301415
|
}
|
|
301227
|
-
const initializer =
|
|
301416
|
+
const initializer = import_typescript6.default.isIdentifier(node) ? constValue(node) : node;
|
|
301228
301417
|
if (initializer === node || followed.has(initializer)) {
|
|
301229
301418
|
return false;
|
|
301230
301419
|
}
|
|
@@ -301232,24 +301421,24 @@ function lint2(file2, checker, { allowAppImports = false } = {}) {
|
|
|
301232
301421
|
};
|
|
301233
301422
|
const composedMailText = (expression2) => {
|
|
301234
301423
|
const node = unwrap(expression2);
|
|
301235
|
-
if (
|
|
301424
|
+
if (import_typescript6.default.isConditionalExpression(node)) {
|
|
301236
301425
|
return composedMailText(node.whenTrue) ?? composedMailText(node.whenFalse);
|
|
301237
301426
|
}
|
|
301238
|
-
if (
|
|
301427
|
+
if (import_typescript6.default.isBinaryExpression(node) && [import_typescript6.default.SyntaxKind.BarBarToken, import_typescript6.default.SyntaxKind.QuestionQuestionToken].includes(
|
|
301239
301428
|
node.operatorToken.kind
|
|
301240
301429
|
)) {
|
|
301241
301430
|
return composedMailText(node.left) ?? composedMailText(node.right);
|
|
301242
301431
|
}
|
|
301243
|
-
const isConcatenation =
|
|
301244
|
-
return (
|
|
301432
|
+
const isConcatenation = import_typescript6.default.isBinaryExpression(node) && node.operatorToken.kind === import_typescript6.default.SyntaxKind.PlusToken && (checker.getTypeAtLocation(node).flags & import_typescript6.default.TypeFlags.StringLike) !== 0;
|
|
301433
|
+
return (import_typescript6.default.isTemplateExpression(node) || isConcatenation) && !isConstantText(node) ? node : null;
|
|
301245
301434
|
};
|
|
301246
301435
|
const checkMailTemplateCall = (call) => {
|
|
301247
301436
|
const capability = call.arguments.length > 0 ? mailTemplateCapability(call) : null;
|
|
301248
301437
|
const input = capability === null ? null : constValue(call.arguments[0]);
|
|
301249
|
-
if (input === null || !
|
|
301438
|
+
if (input === null || !import_typescript6.default.isObjectLiteralExpression(input)) {
|
|
301250
301439
|
return;
|
|
301251
301440
|
}
|
|
301252
|
-
const valueOf = (property) =>
|
|
301441
|
+
const valueOf = (property) => import_typescript6.default.isShorthandPropertyAssignment(property) ? property.name : property.initializer;
|
|
301253
301442
|
const check2 = (value, field2) => {
|
|
301254
301443
|
const composed = composedMailText(constValue(value));
|
|
301255
301444
|
if (composed !== null) {
|
|
@@ -301266,7 +301455,7 @@ function lint2(file2, checker, { allowAppImports = false } = {}) {
|
|
|
301266
301455
|
check2(valueOf(property), "subject");
|
|
301267
301456
|
}
|
|
301268
301457
|
const layoutData = name === "layoutData" ? constValue(valueOf(property)) : null;
|
|
301269
|
-
if (layoutData === null || !
|
|
301458
|
+
if (layoutData === null || !import_typescript6.default.isObjectLiteralExpression(layoutData)) {
|
|
301270
301459
|
continue;
|
|
301271
301460
|
}
|
|
301272
301461
|
for (const slot of layoutData.properties) {
|
|
@@ -301278,38 +301467,38 @@ function lint2(file2, checker, { allowAppImports = false } = {}) {
|
|
|
301278
301467
|
}
|
|
301279
301468
|
};
|
|
301280
301469
|
const checkModuleSpecifier = (node, specifier) => {
|
|
301281
|
-
if (specifier &&
|
|
301470
|
+
if (specifier && import_typescript6.default.isStringLiteral(specifier) && !allowedImports.includes(specifier.text) && !(allowAppImports && specifier.text.startsWith("@app/"))) {
|
|
301282
301471
|
findings.push({
|
|
301283
301472
|
node,
|
|
301284
301473
|
code: "allowed-imports",
|
|
301285
|
-
message: `Import only @diagonal/workflow or @diagonal/workflow/workspace, not ${specifier.text}.`
|
|
301474
|
+
message: profile === "workflow" ? `Import only @diagonal/workflow or @diagonal/workflow/workspace, not ${specifier.text}.` : `${label} imports only ${allowedImportList}, not ${specifier.text}.`
|
|
301286
301475
|
});
|
|
301287
301476
|
}
|
|
301288
301477
|
};
|
|
301289
301478
|
const visit = (node) => {
|
|
301290
|
-
if (
|
|
301479
|
+
if (import_typescript6.default.isImportDeclaration(node) || import_typescript6.default.isExportDeclaration(node)) {
|
|
301291
301480
|
checkModuleSpecifier(node, node.moduleSpecifier);
|
|
301292
301481
|
}
|
|
301293
|
-
if (
|
|
301482
|
+
if (import_typescript6.default.isImportEqualsDeclaration(node) && import_typescript6.default.isExternalModuleReference(node.moduleReference)) {
|
|
301294
301483
|
checkModuleSpecifier(node, node.moduleReference.expression);
|
|
301295
301484
|
}
|
|
301296
|
-
if (
|
|
301485
|
+
if (import_typescript6.default.isCallExpression(node) && node.expression.kind === import_typescript6.default.SyntaxKind.ImportKeyword) {
|
|
301297
301486
|
findings.push({ node, code: "allowed-imports", message: "Dynamic import is not supported." });
|
|
301298
301487
|
}
|
|
301299
|
-
if (
|
|
301488
|
+
if (import_typescript6.default.isCallExpression(node) && node.expression.kind !== import_typescript6.default.SyntaxKind.ImportKeyword) {
|
|
301300
301489
|
checkMailTemplateCall(node);
|
|
301301
301490
|
}
|
|
301302
|
-
if (
|
|
301491
|
+
if (import_typescript6.default.isExpressionStatement(node)) {
|
|
301303
301492
|
for (const call of floatingPromiseCalls(node.expression, holdsPromise)) {
|
|
301304
301493
|
findings.push({ node: call, code: "no-floating-capability", message: FLOATING_MESSAGE });
|
|
301305
301494
|
}
|
|
301306
301495
|
}
|
|
301307
|
-
if ((
|
|
301496
|
+
if ((import_typescript6.default.isArrowFunction(node) || import_typescript6.default.isFunctionExpression(node)) && import_typescript6.default.isCallExpression(node.parent) && node.parent.arguments.includes(node) && returnsPromise(node, checker) && contextuallyReturnsVoid(node, checker)) {
|
|
301308
301497
|
findings.push({ node, code: "no-floating-capability", message: FLOATING_MESSAGE });
|
|
301309
301498
|
}
|
|
301310
|
-
if (
|
|
301311
|
-
const isGlobalThisMember =
|
|
301312
|
-
const symbol =
|
|
301499
|
+
if (import_typescript6.default.isIdentifier(node) && Object.hasOwn(UNSUPPORTED_GLOBALS, node.text)) {
|
|
301500
|
+
const isGlobalThisMember = import_typescript6.default.isPropertyAccessExpression(node.parent) && node.parent.name === node && import_typescript6.default.isIdentifier(node.parent.expression) && node.parent.expression.text === "globalThis";
|
|
301501
|
+
const symbol = import_typescript6.default.isShorthandPropertyAssignment(node.parent) ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node);
|
|
301313
301502
|
const isGlobalReference = !isMemberName(node) && !isDeclaredInScript(symbol);
|
|
301314
301503
|
if (isGlobalThisMember || isGlobalReference) {
|
|
301315
301504
|
findings.push({
|
|
@@ -301319,10 +301508,10 @@ function lint2(file2, checker, { allowAppImports = false } = {}) {
|
|
|
301319
301508
|
});
|
|
301320
301509
|
}
|
|
301321
301510
|
}
|
|
301322
|
-
if (
|
|
301511
|
+
if (import_typescript6.default.isExportAssignment(node) && !node.isExportEquals) {
|
|
301323
301512
|
defaultExport = node.expression;
|
|
301324
301513
|
}
|
|
301325
|
-
|
|
301514
|
+
import_typescript6.default.forEachChild(node, visit);
|
|
301326
301515
|
};
|
|
301327
301516
|
for (const directive2 of file2.libReferenceDirectives) {
|
|
301328
301517
|
findings.push({
|
|
@@ -301343,11 +301532,11 @@ function lint2(file2, checker, { allowAppImports = false } = {}) {
|
|
|
301343
301532
|
return findings;
|
|
301344
301533
|
}
|
|
301345
301534
|
function isSdkDefineWorkflowCall(expression2, checker) {
|
|
301346
|
-
if (expression2 === null || !
|
|
301535
|
+
if (expression2 === null || !import_typescript6.default.isCallExpression(expression2) || !import_typescript6.default.isIdentifier(expression2.expression)) {
|
|
301347
301536
|
return false;
|
|
301348
301537
|
}
|
|
301349
301538
|
let symbol = checker.getSymbolAtLocation(expression2.expression);
|
|
301350
|
-
if (symbol && symbol.flags &
|
|
301539
|
+
if (symbol && symbol.flags & import_typescript6.default.SymbolFlags.Alias) {
|
|
301351
301540
|
symbol = checker.getAliasedSymbol(symbol);
|
|
301352
301541
|
}
|
|
301353
301542
|
return symbol?.getName() === "defineWorkflow" && (symbol.declarations?.some(
|
|
@@ -301371,13 +301560,19 @@ var WORKSPACE = "/sdk/workspace.generated.ts";
|
|
|
301371
301560
|
var APP_ROOT = "/app";
|
|
301372
301561
|
var LIB_DIR = "/lib";
|
|
301373
301562
|
var OPTIONS = {
|
|
301374
|
-
target:
|
|
301563
|
+
target: import_typescript7.default.ScriptTarget.ES2023,
|
|
301375
301564
|
lib: [ROOT_LIB],
|
|
301376
|
-
module:
|
|
301377
|
-
moduleResolution:
|
|
301565
|
+
module: import_typescript7.default.ModuleKind.CommonJS,
|
|
301566
|
+
moduleResolution: import_typescript7.default.ModuleResolutionKind.Bundler,
|
|
301378
301567
|
strict: true,
|
|
301379
301568
|
types: [],
|
|
301380
|
-
paths: {
|
|
301569
|
+
paths: {
|
|
301570
|
+
"@diagonal/workflow": ["/sdk/index.ts"],
|
|
301571
|
+
"@diagonal/workflow/workspace": [WORKSPACE],
|
|
301572
|
+
...Object.fromEntries(
|
|
301573
|
+
Object.values(PROFILES).filter(({ specifier }) => specifier !== null).map(({ specifier, entry }) => [specifier, [entry]])
|
|
301574
|
+
)
|
|
301575
|
+
}
|
|
301381
301576
|
};
|
|
301382
301577
|
var libFiles2;
|
|
301383
301578
|
try {
|
|
@@ -301393,7 +301588,7 @@ function libSourceFile(name, languageVersion) {
|
|
|
301393
301588
|
const text = readLibFile(name);
|
|
301394
301589
|
libSourceFiles.set(
|
|
301395
301590
|
name,
|
|
301396
|
-
text === void 0 ? void 0 :
|
|
301591
|
+
text === void 0 ? void 0 : import_typescript7.default.createSourceFile(`${LIB_DIR}/${name}`, text, languageVersion)
|
|
301397
301592
|
);
|
|
301398
301593
|
}
|
|
301399
301594
|
return libSourceFiles.get(name);
|
|
@@ -301408,12 +301603,12 @@ function position(file2, start) {
|
|
|
301408
301603
|
}
|
|
301409
301604
|
function inputValidatorPosition(file2) {
|
|
301410
301605
|
for (const statement2 of file2.statements) {
|
|
301411
|
-
if (
|
|
301606
|
+
if (import_typescript7.default.isFunctionDeclaration(statement2) && statement2.name?.text === "validateInput") {
|
|
301412
301607
|
return statement2.name.getStart(file2);
|
|
301413
301608
|
}
|
|
301414
|
-
if (
|
|
301609
|
+
if (import_typescript7.default.isVariableStatement(statement2)) {
|
|
301415
301610
|
for (const declaration of statement2.declarationList.declarations) {
|
|
301416
|
-
if (
|
|
301611
|
+
if (import_typescript7.default.isIdentifier(declaration.name) && declaration.name.text === "validateInput") {
|
|
301417
301612
|
return declaration.name.getStart(file2);
|
|
301418
301613
|
}
|
|
301419
301614
|
}
|
|
@@ -301428,55 +301623,55 @@ function workspaceResourceNames(file2, program3, workspaceDeclarations) {
|
|
|
301428
301623
|
const names2 = /* @__PURE__ */ new Set();
|
|
301429
301624
|
const ids = /* @__PURE__ */ new Map();
|
|
301430
301625
|
let needsAll = false;
|
|
301431
|
-
const key = (node) => node && (
|
|
301626
|
+
const key = (node) => node && (import_typescript7.default.isIdentifier(node) || import_typescript7.default.isStringLiteral(node) || import_typescript7.default.isNoSubstitutionTemplateLiteral(node)) ? node.text : null;
|
|
301432
301627
|
const unparenthesized = (node) => {
|
|
301433
|
-
while (node &&
|
|
301628
|
+
while (node && import_typescript7.default.isParenthesizedExpression(node)) {
|
|
301434
301629
|
node = node.expression;
|
|
301435
301630
|
}
|
|
301436
301631
|
return node;
|
|
301437
301632
|
};
|
|
301438
301633
|
const symbol = (node) => {
|
|
301439
|
-
if (
|
|
301634
|
+
if (import_typescript7.default.isShorthandPropertyAssignment(node.parent)) {
|
|
301440
301635
|
return checker.getShorthandAssignmentValueSymbol(node.parent);
|
|
301441
301636
|
}
|
|
301442
|
-
if (
|
|
301637
|
+
if (import_typescript7.default.isExportSpecifier(node.parent) && !node.parent.parent.parent.moduleSpecifier) {
|
|
301443
301638
|
return checker.getExportSpecifierLocalTargetSymbol(node.parent);
|
|
301444
301639
|
}
|
|
301445
301640
|
return checker.getSymbolAtLocation(node);
|
|
301446
301641
|
};
|
|
301447
|
-
const isNamespace = (node) => node &&
|
|
301642
|
+
const isNamespace = (node) => node && import_typescript7.default.isIdentifier(node) && namespaces2.has(symbol(node));
|
|
301448
301643
|
const member = (node) => {
|
|
301449
|
-
if (
|
|
301644
|
+
if (import_typescript7.default.isPropertyAccessExpression(node)) {
|
|
301450
301645
|
return node.name.text;
|
|
301451
301646
|
}
|
|
301452
|
-
if (
|
|
301647
|
+
if (import_typescript7.default.isElementAccessExpression(node)) {
|
|
301453
301648
|
const argument = unparenthesized(node.argumentExpression);
|
|
301454
|
-
return argument && (
|
|
301649
|
+
return argument && (import_typescript7.default.isStringLiteral(argument) || import_typescript7.default.isNoSubstitutionTemplateLiteral(argument)) ? argument.text : null;
|
|
301455
301650
|
}
|
|
301456
301651
|
return null;
|
|
301457
301652
|
};
|
|
301458
|
-
const isMap2 = (node) =>
|
|
301653
|
+
const isMap2 = (node) => import_typescript7.default.isIdentifier(node) && imports.has(symbol(node)) || (import_typescript7.default.isPropertyAccessExpression(node) || import_typescript7.default.isElementAccessExpression(node)) && isNamespace(unparenthesized(node.expression)) && member(node) === "resources";
|
|
301459
301654
|
for (const statement2 of file2.statements) {
|
|
301460
|
-
if (
|
|
301655
|
+
if (import_typescript7.default.isExportDeclaration(statement2) && !statement2.isTypeOnly && statement2.moduleSpecifier && import_typescript7.default.isStringLiteral(statement2.moduleSpecifier) && statement2.moduleSpecifier.text === "@diagonal/workflow/workspace" && (!statement2.exportClause || import_typescript7.default.isNamespaceExport(statement2.exportClause) || statement2.exportClause.elements.some(
|
|
301461
301656
|
(element) => !element.isTypeOnly && (element.propertyName ?? element.name).text === "resources"
|
|
301462
301657
|
))) {
|
|
301463
301658
|
return null;
|
|
301464
301659
|
}
|
|
301465
|
-
if (
|
|
301660
|
+
if (import_typescript7.default.isImportEqualsDeclaration(statement2)) {
|
|
301466
301661
|
const reference = statement2.moduleReference;
|
|
301467
|
-
if (!statement2.isTypeOnly &&
|
|
301662
|
+
if (!statement2.isTypeOnly && import_typescript7.default.isExternalModuleReference(reference) && reference.expression && import_typescript7.default.isStringLiteral(reference.expression) && reference.expression.text === "@diagonal/workflow/workspace") {
|
|
301468
301663
|
namespaces2.add(checker.getSymbolAtLocation(statement2.name));
|
|
301469
301664
|
}
|
|
301470
301665
|
continue;
|
|
301471
301666
|
}
|
|
301472
|
-
if (!
|
|
301667
|
+
if (!import_typescript7.default.isImportDeclaration(statement2) || statement2.moduleSpecifier.text !== "@diagonal/workflow/workspace" || statement2.importClause?.isTypeOnly) {
|
|
301473
301668
|
continue;
|
|
301474
301669
|
}
|
|
301475
301670
|
const bindings = statement2.importClause?.namedBindings;
|
|
301476
|
-
if (bindings &&
|
|
301671
|
+
if (bindings && import_typescript7.default.isNamespaceImport(bindings)) {
|
|
301477
301672
|
namespaces2.add(checker.getSymbolAtLocation(bindings.name));
|
|
301478
301673
|
}
|
|
301479
|
-
if (bindings &&
|
|
301674
|
+
if (bindings && import_typescript7.default.isNamedImports(bindings)) {
|
|
301480
301675
|
for (const binding of bindings.elements) {
|
|
301481
301676
|
if (!binding.isTypeOnly && (binding.propertyName ?? binding.name).text === "resources") {
|
|
301482
301677
|
imports.add(checker.getSymbolAtLocation(binding.name));
|
|
@@ -301484,40 +301679,40 @@ function workspaceResourceNames(file2, program3, workspaceDeclarations) {
|
|
|
301484
301679
|
}
|
|
301485
301680
|
}
|
|
301486
301681
|
}
|
|
301487
|
-
const workspace = program3.getSourceFile(WORKSPACE) ??
|
|
301682
|
+
const workspace = program3.getSourceFile(WORKSPACE) ?? import_typescript7.default.createSourceFile(WORKSPACE, workspaceDeclarations, import_typescript7.default.ScriptTarget.ES2023, true);
|
|
301488
301683
|
for (const statement2 of workspace.statements) {
|
|
301489
|
-
if (!
|
|
301684
|
+
if (!import_typescript7.default.isVariableStatement(statement2)) {
|
|
301490
301685
|
continue;
|
|
301491
301686
|
}
|
|
301492
301687
|
for (const declaration of statement2.declarationList.declarations) {
|
|
301493
|
-
if (!
|
|
301688
|
+
if (!import_typescript7.default.isIdentifier(declaration.name) || declaration.name.text !== "resources") {
|
|
301494
301689
|
continue;
|
|
301495
301690
|
}
|
|
301496
301691
|
const value = declaration.initializer && unwrap(declaration.initializer);
|
|
301497
|
-
if (!value || !
|
|
301692
|
+
if (!value || !import_typescript7.default.isObjectLiteralExpression(value)) {
|
|
301498
301693
|
continue;
|
|
301499
301694
|
}
|
|
301500
301695
|
for (const property of value.properties) {
|
|
301501
|
-
if (
|
|
301696
|
+
if (import_typescript7.default.isPropertyAssignment(property) && import_typescript7.default.isStringLiteral(property.initializer) && key(property.name) !== null) {
|
|
301502
301697
|
ids.set(property.initializer.text, key(property.name));
|
|
301503
301698
|
}
|
|
301504
301699
|
}
|
|
301505
301700
|
}
|
|
301506
301701
|
}
|
|
301507
301702
|
const visit = (node) => {
|
|
301508
|
-
if (needsAll ||
|
|
301703
|
+
if (needsAll || import_typescript7.default.isImportDeclaration(node) || import_typescript7.default.isImportEqualsDeclaration(node) && import_typescript7.default.isExternalModuleReference(node.moduleReference) || import_typescript7.default.isTypeNode(node)) {
|
|
301509
301704
|
return;
|
|
301510
301705
|
}
|
|
301511
|
-
if ((
|
|
301706
|
+
if ((import_typescript7.default.isStringLiteral(node) || import_typescript7.default.isNoSubstitutionTemplateLiteral(node)) && ids.has(node.text)) {
|
|
301512
301707
|
names2.add(ids.get(node.text));
|
|
301513
301708
|
}
|
|
301514
301709
|
let use = node;
|
|
301515
|
-
while (
|
|
301710
|
+
while (import_typescript7.default.isParenthesizedExpression(use.parent)) {
|
|
301516
301711
|
use = use.parent;
|
|
301517
301712
|
}
|
|
301518
301713
|
if (isMap2(node)) {
|
|
301519
301714
|
const parent = use.parent;
|
|
301520
|
-
const name = (
|
|
301715
|
+
const name = (import_typescript7.default.isPropertyAccessExpression(parent) || import_typescript7.default.isElementAccessExpression(parent)) && parent.expression === use ? member(parent) : null;
|
|
301521
301716
|
if (name === null) {
|
|
301522
301717
|
needsAll = true;
|
|
301523
301718
|
} else {
|
|
@@ -301527,10 +301722,10 @@ function workspaceResourceNames(file2, program3, workspaceDeclarations) {
|
|
|
301527
301722
|
needsAll = true;
|
|
301528
301723
|
}
|
|
301529
301724
|
if (!needsAll) {
|
|
301530
|
-
|
|
301725
|
+
import_typescript7.default.forEachChild(node, visit);
|
|
301531
301726
|
}
|
|
301532
301727
|
};
|
|
301533
|
-
|
|
301728
|
+
import_typescript7.default.forEachChild(file2, visit);
|
|
301534
301729
|
return needsAll ? null : [...names2].toSorted((left, right) => left.localeCompare(right));
|
|
301535
301730
|
}
|
|
301536
301731
|
function scriptResourceNames(file2, program3, workspaceDeclarations, appModules = {}) {
|
|
@@ -301552,7 +301747,14 @@ function scriptResourceNames(file2, program3, workspaceDeclarations, appModules
|
|
|
301552
301747
|
}
|
|
301553
301748
|
return [...names2].toSorted((left, right) => left.localeCompare(right));
|
|
301554
301749
|
}
|
|
301555
|
-
function createScriptProgram({
|
|
301750
|
+
function createScriptProgram({
|
|
301751
|
+
source,
|
|
301752
|
+
sdkFiles: sdkFiles2,
|
|
301753
|
+
workspaceDeclarations,
|
|
301754
|
+
appModules = {},
|
|
301755
|
+
profile
|
|
301756
|
+
}) {
|
|
301757
|
+
const entry = PROFILES[resolveProfile(profile)].entry;
|
|
301556
301758
|
const files = new Map(
|
|
301557
301759
|
Object.entries({
|
|
301558
301760
|
...sdkFiles2,
|
|
@@ -301573,7 +301775,7 @@ function createScriptProgram({ source, sdkFiles: sdkFiles2, workspaceDeclaration
|
|
|
301573
301775
|
if (lib !== null) {
|
|
301574
301776
|
return libSourceFile(lib, languageVersion);
|
|
301575
301777
|
}
|
|
301576
|
-
return files.has(name) ?
|
|
301778
|
+
return files.has(name) ? import_typescript7.default.createSourceFile(name, files.get(name), languageVersion, true) : void 0;
|
|
301577
301779
|
},
|
|
301578
301780
|
getDefaultLibFileName: () => `${LIB_DIR}/${ROOT_LIB}`,
|
|
301579
301781
|
getDefaultLibLocation: () => LIB_DIR,
|
|
@@ -301591,22 +301793,63 @@ function createScriptProgram({ source, sdkFiles: sdkFiles2, workspaceDeclaration
|
|
|
301591
301793
|
},
|
|
301592
301794
|
getDirectories: () => []
|
|
301593
301795
|
};
|
|
301594
|
-
const program3 =
|
|
301595
|
-
rootNames: [SCRIPT, INPUT_VALIDATOR_CHECK, WORKSPACE],
|
|
301796
|
+
const program3 = import_typescript7.default.createProgram({
|
|
301797
|
+
rootNames: [SCRIPT, INPUT_VALIDATOR_CHECK, WORKSPACE, ...entry === null ? [] : [entry]],
|
|
301596
301798
|
options: Object.keys(appModules).length === 0 ? OPTIONS : { ...OPTIONS, paths: { ...OPTIONS.paths, "@app/*": [`${APP_ROOT}/*`] } },
|
|
301597
301799
|
host
|
|
301598
301800
|
});
|
|
301599
301801
|
return { program: program3, file: program3.getSourceFile(SCRIPT) };
|
|
301600
301802
|
}
|
|
301803
|
+
function servedProfileImports(context) {
|
|
301804
|
+
const { factory } = context;
|
|
301805
|
+
const served = (specifier) => import_typescript7.default.isStringLiteral(specifier) && PROFILE_SPECIFIERS.has(specifier.text) ? factory.createStringLiteral("@diagonal/workflow") : specifier;
|
|
301806
|
+
return (sourceFile) => factory.updateSourceFile(
|
|
301807
|
+
sourceFile,
|
|
301808
|
+
sourceFile.statements.map((statement2) => {
|
|
301809
|
+
if (import_typescript7.default.isImportDeclaration(statement2)) {
|
|
301810
|
+
return factory.updateImportDeclaration(
|
|
301811
|
+
statement2,
|
|
301812
|
+
statement2.modifiers,
|
|
301813
|
+
statement2.importClause,
|
|
301814
|
+
served(statement2.moduleSpecifier),
|
|
301815
|
+
statement2.attributes
|
|
301816
|
+
);
|
|
301817
|
+
}
|
|
301818
|
+
if (import_typescript7.default.isImportEqualsDeclaration(statement2) && import_typescript7.default.isExternalModuleReference(statement2.moduleReference)) {
|
|
301819
|
+
return factory.updateImportEqualsDeclaration(
|
|
301820
|
+
statement2,
|
|
301821
|
+
statement2.modifiers,
|
|
301822
|
+
statement2.isTypeOnly,
|
|
301823
|
+
statement2.name,
|
|
301824
|
+
factory.updateExternalModuleReference(
|
|
301825
|
+
statement2.moduleReference,
|
|
301826
|
+
served(statement2.moduleReference.expression)
|
|
301827
|
+
)
|
|
301828
|
+
);
|
|
301829
|
+
}
|
|
301830
|
+
if (import_typescript7.default.isExportDeclaration(statement2) && statement2.moduleSpecifier) {
|
|
301831
|
+
return factory.updateExportDeclaration(
|
|
301832
|
+
statement2,
|
|
301833
|
+
statement2.modifiers,
|
|
301834
|
+
statement2.isTypeOnly,
|
|
301835
|
+
statement2.exportClause,
|
|
301836
|
+
served(statement2.moduleSpecifier),
|
|
301837
|
+
statement2.attributes
|
|
301838
|
+
);
|
|
301839
|
+
}
|
|
301840
|
+
return statement2;
|
|
301841
|
+
})
|
|
301842
|
+
);
|
|
301843
|
+
}
|
|
301601
301844
|
function compileWorkflowScript(request2, scriptProgram = createScriptProgram(request2)) {
|
|
301602
301845
|
let code2 = null;
|
|
301603
301846
|
const { program: program3, file: file2 } = scriptProgram;
|
|
301604
301847
|
const diagnostics = [];
|
|
301605
|
-
for (const diagnostic2 of
|
|
301848
|
+
for (const diagnostic2 of import_typescript7.default.getPreEmitDiagnostics(program3, file2)) {
|
|
301606
301849
|
diagnostics.push({
|
|
301607
301850
|
severity: "error",
|
|
301608
301851
|
code: `TS${diagnostic2.code}`,
|
|
301609
|
-
message:
|
|
301852
|
+
message: import_typescript7.default.flattenDiagnosticMessageText(diagnostic2.messageText, "\n"),
|
|
301610
301853
|
...position(diagnostic2.file, diagnostic2.start)
|
|
301611
301854
|
});
|
|
301612
301855
|
}
|
|
@@ -301616,14 +301859,16 @@ function compileWorkflowScript(request2, scriptProgram = createScriptProgram(req
|
|
|
301616
301859
|
diagnostics.push({
|
|
301617
301860
|
severity: "error",
|
|
301618
301861
|
code: `TS${diagnostic2.code}`,
|
|
301619
|
-
message: `validateInput must be (input, ctx) => InputErrors<Input> | void for this workflow's input. ${
|
|
301862
|
+
message: `validateInput must be (input, ctx) => InputErrors<Input> | void for this workflow's input. ${import_typescript7.default.flattenDiagnosticMessageText(diagnostic2.messageText, "\n")}`,
|
|
301620
301863
|
...position(file2, inputValidatorPosition(file2))
|
|
301621
301864
|
});
|
|
301622
301865
|
}
|
|
301623
301866
|
const inputSchema = extractInputSchema(file2, program3.getTypeChecker());
|
|
301624
301867
|
const allowAppImports = Object.keys(request2.appModules ?? {}).length > 0;
|
|
301868
|
+
const profile = resolveProfile(request2.profile);
|
|
301625
301869
|
for (const finding of [
|
|
301626
|
-
...lint2(file2, program3.getTypeChecker(), { allowAppImports }),
|
|
301870
|
+
...lint2(file2, program3.getTypeChecker(), { allowAppImports, profile }),
|
|
301871
|
+
...profileFindings(file2, program3.getTypeChecker(), program3, profile),
|
|
301627
301872
|
...inputSchema.findings
|
|
301628
301873
|
]) {
|
|
301629
301874
|
diagnostics.push({
|
|
@@ -301634,11 +301879,17 @@ function compileWorkflowScript(request2, scriptProgram = createScriptProgram(req
|
|
|
301634
301879
|
});
|
|
301635
301880
|
}
|
|
301636
301881
|
if (diagnostics.length === 0) {
|
|
301637
|
-
program3.emit(
|
|
301638
|
-
|
|
301639
|
-
|
|
301640
|
-
|
|
301641
|
-
|
|
301882
|
+
program3.emit(
|
|
301883
|
+
file2,
|
|
301884
|
+
(name, text) => {
|
|
301885
|
+
if (name === "/workflow.js") {
|
|
301886
|
+
code2 = text;
|
|
301887
|
+
}
|
|
301888
|
+
},
|
|
301889
|
+
void 0,
|
|
301890
|
+
false,
|
|
301891
|
+
{ before: [servedProfileImports] }
|
|
301892
|
+
);
|
|
301642
301893
|
}
|
|
301643
301894
|
return {
|
|
301644
301895
|
ok: diagnostics.length === 0 && code2 !== null,
|