@tailor-platform/sdk 2.24.0 → 2.25.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.
Files changed (36) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/dist/application-ChqHuhZW.mjs +1 -0
  3. package/dist/{application-CfqvzV3I.mjs → application-DS0XKBtK.mjs} +4 -4
  4. package/dist/application-DS0XKBtK.mjs.map +1 -0
  5. package/dist/cli/commands/deploy/deployment-target.d.mts +1 -0
  6. package/dist/cli/commands/machineuser/list.d.mts +1 -0
  7. package/dist/cli/commands/show.d.mts +13 -1
  8. package/dist/cli/lib.d.mts +2 -2
  9. package/dist/cli/lib.mjs +1 -1
  10. package/dist/cli/lib.mjs.map +1 -1
  11. package/dist/cli/main.mjs +46 -46
  12. package/dist/cli/main.mjs.map +1 -1
  13. package/dist/completion/zsh-worker.zsh +3 -3
  14. package/dist/configure/index.d.mts +2 -2
  15. package/dist/configure/index.mjs.map +1 -1
  16. package/dist/plugin/index.mjs +1 -1
  17. package/dist/plugin/index.mjs.map +1 -1
  18. package/dist/plugin/types.d.mts +97 -0
  19. package/dist/register-ts-hook-DPAW0Z4M.mjs +924 -0
  20. package/dist/register-ts-hook-DPAW0Z4M.mjs.map +1 -0
  21. package/docs/cli/application.md +23 -0
  22. package/docs/cli/secret.md +24 -16
  23. package/docs/cli-reference.md +25 -13
  24. package/docs/github-actions.md +69 -4
  25. package/docs/plugin/custom.md +76 -1
  26. package/docs/plugin/frontend.md +124 -0
  27. package/docs/plugin/index.md +24 -2
  28. package/docs/services/auth.md +2 -0
  29. package/docs/services/secret.md +5 -4
  30. package/docs/services/staticwebsite.md +2 -0
  31. package/docs/services/tailordb-migration.md +1 -1
  32. package/package.json +5 -5
  33. package/dist/application-BDqze-wy.mjs +0 -1
  34. package/dist/application-CfqvzV3I.mjs.map +0 -1
  35. package/dist/register-ts-hook-CVlI9Jzl.mjs +0 -922
  36. package/dist/register-ts-hook-CVlI9Jzl.mjs.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,53 @@
1
1
  # @tailor-platform/sdk
2
2
 
3
+ ## 2.25.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#2449](https://github.com/tailor-platform/sdk/pull/2449) [`e4a0301`](https://github.com/tailor-platform/sdk/commit/e4a0301e24c97f4813f590467e56c50672083abb) Thanks [@toiroakr](https://github.com/toiroakr)! - `tailor open` and `tailor auth-connection open` now always open the new Tailor Platform Console UI, which has replaced the previous UI at `console.tailor.tech`. `tailor open` opens `/workspaces/{workspaceId}/services/applications/{applicationName}` (previously `/workspaces/{workspaceId}/applications/{applicationName}/overview`), and `tailor auth-connection open` opens `/workspaces/{workspaceId}/services/auth-connections` (previously `/workspaces/{workspaceId}/settings/connections`). The `TAILOR_CONSOLE_NEXT` environment variable is no longer read: a leftover `TAILOR_CONSOLE_NEXT=1` no longer redirects the console host to `console-next.`, so it can be removed.
8
+
9
+ - [#2468](https://github.com/tailor-platform/sdk/pull/2468) [`3c87be0`](https://github.com/tailor-platform/sdk/commit/3c87be0cdfbf3fe8b7cdedbdf0d64339b781c25e) Thanks [@toiroakr](https://github.com/toiroakr)! - Add an onDeployed plugin hook with deployed application IDs and URLs, public OAuth client IDs, and publishing to static websites. Hooks run after successful deploys, including deploys without resource changes, and can return structured JSON outputs.
10
+
11
+ - [#2468](https://github.com/tailor-platform/sdk/pull/2468) [`7451944`](https://github.com/tailor-platform/sdk/commit/74519445be5000fcbc0ce0f0bd3c6abfb3275b2f) Thanks [@toiroakr](https://github.com/toiroakr)! - Add `frontendPlugin` from `@tailor-platform/sdk-plugin-frontend` to build and upload frontend assets during `tailor deploy`. Frontend builds can use deployed URLs and public OAuth client IDs as environment variables, and deployment results include uploaded frontend details in `outputs.frontends`.
12
+
13
+ Add deployment hooks and shared context types to `@tailor-platform/sdk`. Successful `tailor deploy --json` results now include `workspaceId` and `applications` with deployed application, Static Website, and AI Gateway URLs, plus public OAuth client IDs, even when no deploy plugins are configured.
14
+
15
+ - [#2505](https://github.com/tailor-platform/sdk/pull/2505) [`3296f08`](https://github.com/tailor-platform/sdk/commit/3296f0874bca8c7f3b158abfa8527a34b7812dde) Thanks [@dqn](https://github.com/dqn)! - More state-changing commands now print a JSON result on stdout under `--json`, so scripts can confirm what changed without parsing stderr: `login`, `logout`, `remove`, `profile delete`, `user switch`, `user pat delete`, `secret vault create`, `authconnection authorize`, `workspace user invite`, `workspace user update`, `workspace ttl set`, `workspace ttl clear`, `crashreport send`, and `tailordb migration script`. Each result carries a `changed` boolean: `true` when the command did work, `false` when it did nothing, such as `logout` when nobody is logged in, `user switch` to the current user, or `workspace ttl clear` on a workspace with no TTL. Output without `--json` is unchanged.
16
+
17
+ - [#2497](https://github.com/tailor-platform/sdk/pull/2497) [`efcca78`](https://github.com/tailor-platform/sdk/commit/efcca789538fde0f7f05d8de4854c771b03ebbf0) Thanks [@tailor-bobbin](https://github.com/apps/tailor-bobbin)! - Include the machine user `id` in `tailor machineuser list` output so machine users can be matched against the invoker id available in resolvers and executors.
18
+
19
+ - [#2486](https://github.com/tailor-platform/sdk/pull/2486) [`caa34b4`](https://github.com/tailor-platform/sdk/commit/caa34b450fb92b8993e6f3c29c890918bb69b1f6) Thanks [@dqn](https://github.com/dqn)! - `tailor secret create` and `tailor secret update` now read the secret value from standard input when `--value` is omitted, keeping it out of shell history and process listings: `printf '%s' "$VALUE" | tailor secret create --vault-name <vault> --name <name>`. The piped value can be up to 128 KiB, and one trailing newline is removed from it. Without `--value`, a terminal or empty standard input fails with `SECRET_VALUE_REQUIRED`.
20
+
21
+ - [#2485](https://github.com/tailor-platform/sdk/pull/2485) [`d06f314`](https://github.com/tailor-platform/sdk/commit/d06f3143341a8c4161989e5cd906bda8fbbf5014) Thanks [@dqn](https://github.com/dqn)! - `tailor show` (and the programmatic `show()`) now also lists each deployed static website defined in `staticWebsites` with its URL and description, and each deployed OAuth2 client defined in `auth`'s `oauth2Clients` with its client ID, so a CI step can read both from one `tailor show --json` call right after `tailor deploy`. Client secrets are never included. Credentials that cannot list OAuth2 clients, such as the workspace viewer role, get a warning and `oauth2Clients: null`, which sets that case apart from an application with no deployed OAuth2 clients.
22
+
23
+ ### Patch Changes
24
+
25
+ - [#2487](https://github.com/tailor-platform/sdk/pull/2487) [`d160c86`](https://github.com/tailor-platform/sdk/commit/d160c865e0d0b9fce550b3e5a12000ef7108d360) Thanks [@dqn](https://github.com/dqn)! - Declining a confirmation prompt now makes the command exit non-zero with a `*_CANCELLED` error code, as `tailor deploy` and `tailor remove` already did, instead of exiting 0 as if the operation had succeeded. This covers `workspace delete` / `restore` / `prune`, `workspace user remove`, `organization folder delete`, `secret create` / `update` / `delete`, `secret vault delete`, `authconnection delete` / `revoke`, `tailordb truncate`, and `tailordb migration generate` / `set` / `sync` / `rebaseline`. For example, `tailor workspace delete` reports `WORKSPACE_DELETION_CANCELLED` when the entered name does not match, and `tailor tailordb migration generate` still generates the other namespaces before reporting `MIGRATION_GENERATE_CANCELLED` for the ones whose breaking changes were declined. Confirmation prompts appear only in an interactive terminal, so runs with `--yes`, in CI, or with `--json` are unaffected. `migrateGenerate()` now rejects with `MIGRATION_GENERATE_CANCELLED` when its prompt is declined, instead of resolving or exiting the process.
26
+
27
+ - [#2484](https://github.com/tailor-platform/sdk/pull/2484) [`7454455`](https://github.com/tailor-platform/sdk/commit/7454455239749dea7cd4660db76769e2fd4ca356) Thanks [@dqn](https://github.com/dqn)! - `tailor init` now exits non-zero when project scaffolding fails, instead of exiting 0. It reports `INIT_FAILED` when `create @tailor-platform/sdk` exits with a non-zero code or is terminated by a signal, and `INIT_SPAWN_FAILED` when the package manager cannot be started.
28
+
29
+ - [#2488](https://github.com/tailor-platform/sdk/pull/2488) [`608b7eb`](https://github.com/tailor-platform/sdk/commit/608b7eb8e46f8a72464b090f355f5a68f2af1243) Thanks [@dqn](https://github.com/dqn)! - Argument errors now follow `--json` and `TAILOR_JSON_OUTPUT`. An unknown option or subcommand, or an option value that fails validation, was printed as plain text even when JSON output was requested, because it happened before the flag took effect. It is now reported as the usual JSON error envelope on stderr with the code `INVALID_ARGUMENTS`, for example `{"error":{"code":"INVALID_ARGUMENTS","message":"Unknown flags: bogus"}}`. `--verbose` now also applies to these errors, adding the stack trace to the envelope or to the plain-text output, as it does for other failures. Otherwise, output without JSON mode is unchanged.
30
+
31
+ - [#2506](https://github.com/tailor-platform/sdk/pull/2506) [`69b3234`](https://github.com/tailor-platform/sdk/commit/69b32346618d022695fa9c7e06676eef34b83843) Thanks [@dqn](https://github.com/dqn)! - List commands now say when `--limit` cut their output short. When more items exist than `--limit` allows, the list is followed by `More results exist beyond --limit N. Raise --limit to see more.` on stderr, so a caller can tell a complete list from a partial one; stdout, including `--json` output, is unchanged. This matters most for `executor jobs`, `function logs`, and `workflow executions`, which list 50 items unless `--limit` says otherwise.
32
+
33
+ - [#2492](https://github.com/tailor-platform/sdk/pull/2492) [`46590a4`](https://github.com/tailor-platform/sdk/commit/46590a460ed382456109b4c440aeb411266a0adb) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update oxc
34
+
35
+ - [#2515](https://github.com/tailor-platform/sdk/pull/2515) [`ef00996`](https://github.com/tailor-platform/sdk/commit/ef00996f2b829726aa108f73aa89c81eaf0eb0ae) Thanks [@renovate](https://github.com/apps/renovate)! - chore(deps): lock file maintenance
36
+
37
+ - [#2517](https://github.com/tailor-platform/sdk/pull/2517) [`3220bc9`](https://github.com/tailor-platform/sdk/commit/3220bc99ec92b89835f663245d9e896ea5ee62da) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update dependency rolldown to v1.2.12
38
+
39
+ - [#2483](https://github.com/tailor-platform/sdk/pull/2483) [`ae6451e`](https://github.com/tailor-platform/sdk/commit/ae6451e6ab358d058a3cb38503dd222537163e35) Thanks [@toiroakr](https://github.com/toiroakr)! - `tailor setup ci branch`, `tailor setup ci tag`, and `tailor setup ci preview` accept `--dir` more than once. The generated workflow deploys every app to the same workspace in one multi-config run from the repository root, runs the generate check for each app directory (plus seed validation and the migration drift check on branch and tag workflows), and runs its jobs on changes under any of them. `--name` is required when `--dir` is repeated, and the root `package.json` must declare `@tailor-platform/sdk`. With `--erd-preview`, each TailorDB namespace is previewed from the app that owns it.
40
+
41
+ `tailor setup ci branch` and `tailor setup ci preview` also accept `--paths` (repeatable) to run the generated jobs on changes outside the app directories, such as a frontend or shared packages. A pattern supports `*`, `**`, and a leading `!` to exclude paths; other glob characters are rejected.
42
+
43
+ Branch and preview workflows with an app directory other than the repository root no longer filter their `on:` triggers by `paths`. Branch workflows start on every pull request and push, preview workflows on every pull request, and a new `tailor-changes` job skips the plan, deploy, and preview jobs when nothing under the app directories (or `--paths`) changed. Skipped jobs report success, so these checks can be required in branch protection. If the `tailor-changes` job itself fails, those jobs fail instead of being skipped, so a required check cannot pass without them. `setup` remains a beta command, so this ships as an immediate change rather than going through a deprecation cycle.
44
+
45
+ Branch workflows generated with `--erd-preview` now install the project dependencies before building the ERD preview, which the setup step does not do.
46
+
47
+ The workflow template version is bumped, so `tailor setup check` reports every generated target as outdated; run `tailor setup update` to regenerate them. Branch and preview workflows whose `--dir` is not the repository root switch to the `tailor-changes` job described above, and branch workflows generated with `--erd-preview` get the new ERD matrix and install step. Other workflows regenerate identically. `tailor setup update` keeps every app directory and `--paths` pattern of a multi-directory target.
48
+
49
+ - [#2489](https://github.com/tailor-platform/sdk/pull/2489) [`16175f6`](https://github.com/tailor-platform/sdk/commit/16175f6335e72f5775a2f706b65b043be1058a1e) Thanks [@toiroakr](https://github.com/toiroakr)! - You can add `environment:` to a managed job that `tailor setup ci` generates without one (`tailor-tag-guard`, and the `tailor-erd-preview*` jobs from `--erd-preview`), so a step you added there can read that GitHub Environment's secrets, such as a token for installing dependencies from a private registry. `tailor setup check` no longer reports it as a hand edit, and re-running `tailor setup ci` keeps it. The `environment:` of `tailor-plan`, `tailor-deploy`, and the preview jobs still comes from `--environment`.
50
+
3
51
  ## 2.24.0
4
52
 
5
53
  ### Minor Changes
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./application-DS0XKBtK.mjs";export{t as defineApplication,e as generatePluginFilesIfNeeded};
@@ -1,4 +1,4 @@
1
- import{r as e}from"./date-Dri6Yas-.mjs";import{n as t}from"./brand-C8nMKhJC.mjs";import{a as n,i as r,n as i,o as a}from"./wait-point-registry-B-ESkTZX.mjs";import{t as o}from"./assert-WeXvmG4j.mjs";import{c as s,i as c,o as l}from"./logger-Db-YRTwK.mjs";import{n as u,t as d}from"./es-builtins-SfvXRVoG.mjs";import{n as f,r as p,t as m}from"./node-builtins-DYfhPBnz.mjs";import{a as h,b as g,c as _,d as v,f as y,g as b,h as x,l as S,m as C,n as w,o as T,p as E,s as D,t as O,u as k,x as A}from"./service-CL1Bp4It.mjs";import{t as j}from"./multiline-EyzjEwn9.mjs";import{i as ee,t as M}from"./errors-CpvSChyL.mjs";import{t as te}from"./user-agent-vdHYF3QL.mjs";import{i as ne,n as re}from"./guards-yDXyKC9F.mjs";import{t as ie}from"./type-source--ZNcV8RJ.mjs";import{createRequire as ae}from"node:module";import*as N from"pathe";import{resolve as oe}from"pathe";import{resolveTSConfig as se}from"pkg-types";import{z as P}from"zod";import{create as ce}from"@bufbuild/protobuf";import*as F from"node:fs";import{readFileSync as le}from"node:fs";import{MethodOptions_IdempotencyLevel as ue}from"@bufbuild/protobuf/wkt";import{OAuth2Client as de}from"@badgateway/oauth2-client";import{Code as I,ConnectError as L,createClient as fe}from"@connectrpc/connect";import pe from"p-limit";import*as me from"node:crypto";import{createHash as he}from"node:crypto";import*as R from"rolldown";import{parseSync as z}from"oxc-parser";import{createPathsMatcher as ge,getTsconfig as _e}from"get-tsconfig";import*as B from"inflection";import*as ve from"node:os";function isForbiddenGlobal(e){return u.has(e)}const ye=[`DEBUG`,`INFO`,`WARN`,`ERROR`,`SILENT`];function isLogLevel(e){return ye.includes(e)}const be=/^\d*[1-9]\d*$/;function parsePositiveInt(e){if(e===void 0)return;let t=e.trim();if(!be.test(t))return;let n=Number.parseInt(t,10);return Number.isSafeInteger(n)?n:void 0}function resolveApplyConcurrency(){return parsePositiveInt(process.env.TAILOR_APPLY_CONCURRENCY)??16}function createApplyLimiter(){return pe(resolveApplyConcurrency())}function byName(e,t){return e.name<t.name?-1:+(e.name>t.name)}const xe=/* @__PURE__ */ new WeakMap;function withErrorDiagnostics(e,t){return xe.set(e,{...xe.get(e),...t}),e}function getErrorDiagnostics(e){return{...e instanceof L?{suggestion:rpcSuggestion(e.code)}:{},...xe.get(e)}}function rpcSuggestion(e){switch(e){case I.Unauthenticated:return"Check the active token and profile with `tailor auth status` (include the same --profile option). For an environment token, replace TAILOR_PLATFORM_TOKEN; otherwise use the original browser or --machine-user login method with the same profile. See `tailor login --help`.";case I.PermissionDenied:return"Check the active identity and profile with `tailor auth status` (include the same --profile option), then verify its workspace role and token permissions.";case I.Unavailable:case I.DeadlineExceeded:return`Check network connectivity and platform availability. A write may already have completed; inspect the current resource state before retrying.`;default:return}}const Se=`https://api.tailor.tech`,Ce=`/.well-known/oauth-authorization-server/oauth2/platform`,we=/* @__PURE__ */ new Map;function getEnvPlatformUrl(){return process.env.TAILOR_PLATFORM_URL??process.env.PLATFORM_URL}function getEnvOAuth2ClientId(){return process.env.TAILOR_PLATFORM_OAUTH2_CLIENT_ID??process.env.PLATFORM_OAUTH2_CLIENT_ID}function normalizeBaseUrl(e){let t=new URL(e);return t.hash=``,t.search=``,t.toString().replace(/\/$/,``)}function getEffectivePlatformConfig(e={}){let t=e.platformUrl??getEnvPlatformUrl(),n=e.oauth2ClientId??getEnvOAuth2ClientId(),r=e.consoleUrl??process.env.TAILOR_PLATFORM_CONSOLE_URL,i={...t?{platformUrl:t}:{},...n?{oauth2ClientId:n}:{},...r?{consoleUrl:r}:{}};return Object.keys(i).length>0?i:void 0}function rememberPlatformConfigForToken(e,t){let n=getEffectivePlatformConfig(t);n?we.set(e,n):we.delete(e)}function getPlatformConfigForToken(e){return we.get(e)}function getPlatformBaseUrl(e={}){return normalizeBaseUrl(e.platformUrl??getEnvPlatformUrl()??`https://api.tailor.tech`)}function isDefaultPlatform(e){return getPlatformBaseUrl(e)===normalizeBaseUrl(Se)}function getOAuth2ClientId(e={}){return e.oauth2ClientId??getEnvOAuth2ClientId()??`cpoc_0Iudir72fqSpqC6GQ58ri1cLAqcq5vJl`}function inferConsoleBaseUrl(e){let t=new URL(e);return t.hostname.startsWith(`api.`)?(t.hostname=t.hostname.replace(/^api\./,`console.`),normalizeBaseUrl(t.toString())):`https://console.tailor.tech`}function applyConsoleNext(e){if(s(process.env.TAILOR_CONSOLE_NEXT)!==!0)return e;let t=new URL(e);return t.hostname=t.hostname.replace(/^console\./,`console-next.`),normalizeBaseUrl(t.toString())}function getConsoleBaseUrl(e={}){if(e.consoleUrl)return normalizeBaseUrl(e.consoleUrl);if(e.platformUrl){let t=inferConsoleBaseUrl(e.platformUrl);if(t!==`https://console.tailor.tech`)return applyConsoleNext(t)}return process.env.TAILOR_PLATFORM_CONSOLE_URL?normalizeBaseUrl(process.env.TAILOR_PLATFORM_CONSOLE_URL):applyConsoleNext(inferConsoleBaseUrl(getPlatformBaseUrl(e)))}function initOAuth2Client(e){return new de({clientId:getOAuth2ClientId(e),server:getPlatformBaseUrl(e),discoveryEndpoint:Ce})}async function initOperatorClient(e,t){let n=t??getPlatformConfigForToken(e),[{createTracingInterceptor:r},{OperatorService:i}]=await Promise.all([import(`./interceptor-DQg3cR_9.mjs`),import(`./service_pb-dB3RrGeh.mjs`)]),a=[await userAgentInterceptor(),await bearerTokenInterceptor(e),retryInterceptor(),errorHandlingInterceptor(),r(),concurrencyLimitInterceptor()],o=getPlatformBaseUrl(n),s=createPooledStreamTransport(await createTransport(o,a),()=>createTransport(o,a),4);return fe(i,s)}async function createTransport(e,t){let{createConnectTransport:n}=await import(`@connectrpc/connect-node`);return n({httpVersion:`2`,baseUrl:e,interceptors:t})}const Te=/* @__PURE__ */ new Set([`CreateFunctionRegistry`,`UpdateFunctionRegistry`,`UploadFile`]);function createPooledStreamTransport(e,t,n){if(!Number.isInteger(n)||n<1)throw Error(`createPooledStreamTransport: maxConnections must be a positive integer, got ${n}`);let r=[e],i=[0],a=[],o=0;function acquireTransportIndex(e,s){return new Promise((c,l)=>{let u=!1,d;function cleanup(){u=!0,clearTimeout(d),e?.removeEventListener(`abort`,onAbort);let t=a.indexOf(attempt);t!==-1&&a.splice(t,1)}function onAbort(){cleanup(),l(L.from(e?.reason,I.Canceled))}function onTimeout(){cleanup(),l(new L(`the operation timed out`,I.DeadlineExceeded))}function claim(e){if(u){release(e);return}cleanup(),c(e)}function attempt(){let e=i.pop();if(e!==void 0){claim(e);return}if(r.length+o<n){o++,t().then(e=>{o--;let t=r.length;r.push(e),claim(t)},e=>{o--,cleanup(),l(e instanceof Error?e:Error(String(e))),wakeOneWaiter()});return}a.push(attempt)}if(e?.aborted){onAbort();return}if(e?.addEventListener(`abort`,onAbort,{once:!0}),s!==void 0){let e=s-performance.now();if(e<=0){onTimeout();return}d=setTimeout(onTimeout,e)}attempt()})}function wakeOneWaiter(){a.shift()?.()}function release(e){i.push(e),wakeOneWaiter()}return{unary(t,n,r,i,a,o){return e.unary(t,n,r,i,a,o)},async stream(t,n,i,a,o,s){if(!Te.has(t.name))return e.stream(t,n,i,a,o,s);let c=i!==void 0&&i>0?performance.now()+i:void 0,l=await acquireTransportIndex(n,c),u=r[l],d;try{if(n?.aborted)throw L.from(n.reason,I.Canceled);let e=c===void 0?i:Math.ceil(c-performance.now());if(c!==void 0&&e!==void 0&&e<=0)throw new L(`the operation timed out`,I.DeadlineExceeded);d=await u.stream(t,n,e,a,o,s)}catch(e){throw release(l),e}return{...d,message:releaseAfter(d.message,()=>release(l))}}}}async function*releaseAfter(e,t){try{yield*e}finally{t()}}async function userAgentInterceptor(){let e=await te();return t=>async n=>(n.header.set(`User-Agent`,e),await t(n))}async function bearerTokenInterceptor(e){return t=>async n=>(n.header.set(`Authorization`,`Bearer ${e}`),await t(n))}function retryInterceptor(){return e=>async t=>{if(t.stream)return await e(t);let n;for(let r=0;r<De;r++){r>0&&await waitRetryBackoff(r);try{return await e(t)}catch(e){if(isRetrySafeCreateAlreadyExists(e,t.method.name)){if(r>0)return c.debug(`retry: ${t.method.name} returned AlreadyExists on attempt ${r+1}; treating as success (prior attempt likely committed)`),synthesizeEmptyUnaryResponse(t);let{reportCrash:n}=await import(`./crashreport-CBaRJl5h.mjs`);await n(e,`handledError`)}if(t.method.name!==`CreateWorkspace`&&isRetirable(e,t.method.idempotency)){n=e,c.debug(`retry: ${t.method.name} attempt ${r+1} failed with ${retryErrorCodeName(e)}; retrying`);continue}throw e}}throw n}}function concurrencyLimitInterceptor(){let e=createApplyLimiter();return t=>async n=>n.stream?await t(n):await e(()=>t(n))}function retryErrorCodeName(e){return e instanceof L?I[e.code]:isTransportDisconnectError(e)?e.code:`unknown`}const Ee=/* @__PURE__ */ new Set([`CreateAIGateway`,`CreateApplication`,`CreateAuthConnection`,`CreateAuthHook`,`CreateAuthIDPConfig`,`CreateAuthMachineUser`,`CreateAuthOAuth2Client`,`CreateAuthSCIMConfig`,`CreateAuthSCIMResource`,`CreateAuthService`,`CreateExecutorExecutor`,`CreateIdPService`,`CreatePipelineResolver`,`CreatePipelineService`,`CreateSecretManagerSecret`,`CreateSecretManagerVault`,`CreateStaticWebsite`,`CreateTailorDBGQLPermission`,`CreateTailorDBService`,`CreateTailorDBType`,`CreateTenantConfig`,`CreateUserProfileConfig`,`CreateWorkflow`,`CreateWorkflowJobFunctionExecutionPolicy`]);function isRetrySafeCreateAlreadyExists(e,t){return e instanceof L&&e.code===I.AlreadyExists&&Ee.has(t)}function synthesizeEmptyUnaryResponse(e){return{stream:!1,service:e.service,method:e.method,header:new Headers,message:ce(e.method.output),trailer:new Headers}}const De=3;function waitRetryBackoff(e){let t=500*2**(e-1)*(1+.1*(Math.random()*2-1));return new Promise(e=>setTimeout(e,t))}const Oe=/* @__PURE__ */ new Set([`ERR_STREAM_PREMATURE_CLOSE`,`ECONNRESET`,`ETIMEDOUT`,`EPIPE`]);function isTransportDisconnectError(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&Oe.has(e.code)}function isRetirable(e,t){let n=t===ue.NO_SIDE_EFFECTS||t===ue.IDEMPOTENT;if(!(e instanceof L))return isTransportDisconnectError(e)&&n;switch(e.code){case I.ResourceExhausted:case I.Unavailable:return!0;case I.Aborted:case I.Internal:return n;default:return!1}}function errorHandlingInterceptor(){return e=>async t=>{try{return await e(t)}catch(e){if(e instanceof L){let{operation:n,resourceType:r}=parseMethodName(t.method.name),i=requestIdentifiers(t.message,t.method.name),a=Object.entries(i).map(([e,t])=>`${e}: ${t}`),o=a.length===0?``:` (${a.join(`, `)})`;throw withErrorDiagnostics(new L(`Failed to ${n} ${r}${o}: ${e.rawMessage}`,e.code,e.metadata),{context:{method:t.method.name,identifiers:i}})}throw isTransportDisconnectError(e)?withErrorDiagnostics(e,{code:`TRANSPORT_DISCONNECTED`,suggestion:`Check network connectivity and platform availability. A write may already have completed; inspect the current resource state before retrying.`,context:{method:t.method.name,transportCode:e.code,identifiers:requestIdentifiers(t.message,t.method.name)}}):e}}}function parseMethodName(e){let t=e.match(/^(Create|Update|Delete|Set|List|Get)(.+)$/);if(!t)return{operation:`perform`,resourceType:`resource`};let[,n,r]=t;return{operation:n.toLowerCase(),resourceType:r}}const ke=/* @__PURE__ */ new Set([`name`,`id`]),Ae=[`Name`,`Id`,`Namespace`],je=`name`,Me={GetMetadata:[`trn`],SetMetadata:[`trn`],AddCustomDomain:[`domain`],GetCustomDomain:[`domain`],RemoveCustomDomain:[`domain`],CreateWorkflowJobFunctionExecutionPolicy:[`executionPolicyKey`],UpdateWorkflowJobFunctionExecutionPolicy:[`executionPolicyKey`],GetWorkflowJobFunctionExecutionPolicyByKey:[`executionPolicyKey`]};function isIdentityKey(e,t){return e.startsWith(`$`)?!1:ke.has(e)||Ae.some(t=>e.endsWith(t))||(Me[t]?.includes(e)??!1)}function requestIdentifiers(e,t){if(typeof e!=`object`||!e)return{};let n={};for(let[r,i]of Object.entries(e))if(typeof i==`string`&&i!==``&&isIdentityKey(r,t))n[r]=i;else if(!r.startsWith(`$`)&&typeof i==`object`&&i&&!Array.isArray(i)&&typeof i.$typeName==`string`){let e=i[je];typeof e==`string`&&e!==``&&(n[`${r}.${je}`]=e)}return n}const Ne=1e3;async function fetchAll(e){let t=[],n=``;for(;;){let[r,i]=await e(n,Ne);if(t.push(...r),!i)break;n=i}return t}function isNotFoundError(e){return e instanceof L&&e.code===I.NotFound}async function fetchAllTolerant(e){return await fetchAll(async(t,n)=>{try{return await e(t,n)}catch(e){if(isNotFoundError(e))return[[],``];throw e}})}async function getOrNull(e){try{return await e()}catch(e){if(isNotFoundError(e))return;throw e}}async function fetchPaged(e,t){let n=t?.limit,r=n===void 0||n===0,i=[],a=``;for(;;){let t=r?Ne:Math.min(n-i.length,Ne);if(!r&&t<=0)break;let[o,s]=await e(a,t);if(i.push(...o),!r&&i.length>=n||!s)break;a=s}return!r&&i.length>n?i.slice(0,n):i}async function fetchUserInfo(e,t){let n=new URL(`/auth/platform/userinfo`,getPlatformBaseUrl(t)).href,r=await fetch(n,{headers:{Authorization:`Bearer ${e}`,"User-Agent":await te()}});if(!r.ok)throw Error(`Failed to fetch user info: ${r.statusText}`);let i=await r.json();return P.object({sub:P.string(),email:P.string()}).parse(i)}const V=/:url(\/.*)?$/;function hasStaticWebsiteUrlPlaceholder(e){return typeof e==`string`&&V.test(e)}function staticWebsiteNameFromPlaceholder(e){let t=e.match(V);return t?.index===void 0?e:e.substring(0,t.index)}async function resolveStaticWebsiteUrls(e,t,n,r,i={}){if(!n)return[];let{expectedLocalNames:a,keepUnresolved:o=!1,failOnUnexpectedError:s=!1}=i,unresolved=e=>o?[e]:[],l=o?`Leaving the ${r} value unresolved.`:`Excluding from ${r}.`,u=i.siteLookupCache??/* @__PURE__ */ new Map,lookupSite=n=>{let r=u.get(n);return r||(r=e.getStaticWebsite({workspaceId:t,name:n}),u.set(n,r)),r};return(await Promise.all(n.map(async e=>{let t=e.match(V);if(t&&t.index!==void 0){let n=e.substring(0,t.index),i=t[1]||``;try{let t=await lookupSite(n);if(t.staticwebsite?.url)return[t.staticwebsite.url+i];if(!a?.has(n)&&s)throw M({code:`STATIC_WEBSITE_URL_NOT_ASSIGNED`,message:`Static website "${n}" exists but has no URL assigned yet.`,suggestion:`Re-run the deploy once the static website's URL is available.`});return c.warn(`Static website "${n}" has no URL assigned yet. ${l}`),unresolved(e)}catch(t){if(isNotFoundError(t)){if(a?.has(n))return[e]}else if(s)throw t;return c.warn(`Static website "${n}" not found for ${r} configuration. ${l}`),unresolved(e)}}return[e]}))).flat()}async function resolveStaticWebsiteUrlsInEnv(e,t,n,r={}){if(!n||!Object.values(n).some(hasStaticWebsiteUrlPlaceholder))return n??{};let i=/* @__PURE__ */ new Map,a=await Promise.all(Object.entries(n).map(async([n,a])=>{if(!hasStaticWebsiteUrlPlaceholder(a))return[n,a];let[o]=await resolveStaticWebsiteUrls(e,t,[a],`env "${n}"`,{...r,keepUnresolved:!0,failOnUnexpectedError:!0,siteLookupCache:i});return[n,o??a]})),o=Object.fromEntries(a);return warnUnresolvedEnvPlaceholders(o,r.expectedLocalNames),o}function warnUnresolvedEnvPlaceholders(e,t){for(let[n,r]of Object.entries(e)){if(!hasStaticWebsiteUrlPlaceholder(r))continue;let e=r.slice(0,r.search(V));if(t?.has(e)){c.warn(`env "${n}" keeps the unresolved value "${r}" for now because static website "${e}" isn't available yet; this deploy rebuilds automatically once it is, to inject the real URL.`);continue}c.warn(`env "${n}" keeps the unresolved value "${r}". The literal pattern is passed to your code at runtime.`)}}async function fetchMachineUserToken(e,t,n){c.registerSecret(n);let r=new URL(`/oauth2/token`,e).href,i=new URLSearchParams;i.append(`grant_type`,`client_credentials`),i.append(`client_id`,t),i.append(`client_secret`,n);let a={method:`POST`,headers:{"User-Agent":await te(),"Content-Type":`application/x-www-form-urlencoded`},body:i},o=await withConnectTimeoutRetry(`machine user token request`,()=>fetch(r,a));if(!o.ok){let e=await o.text().catch(()=>``);throw Error(`Failed to fetch machine user token: ${o.status} ${o.statusText} ${e.slice(0,500)}`)}let s=await o.json(),l=P.object({token_type:P.string(),access_token:P.string(),expires_in:P.number()}).parse(s);return c.registerSecret(l.access_token),l}function isUndiciConnectTimeout(e){if(!(e instanceof TypeError))return!1;let t=e.cause;return t instanceof Error&&`code`in t&&t.code===`UND_ERR_CONNECT_TIMEOUT`}async function withConnectTimeoutRetry(e,t){for(let n=1;;n++)try{return await t()}catch(t){if(!isUndiciConnectTimeout(t)||n>=3)throw t;c.debug(`retry: ${e} attempt ${n} failed with UND_ERR_CONNECT_TIMEOUT; retrying`),await waitRetryBackoff(n)}}async function fetchPlatformMachineUserToken(e,t,n){c.registerSecret(t);let r=getPlatformBaseUrl(n),i=await withConnectTimeoutRetry(`platform machine user token request`,()=>new de({clientId:e,clientSecret:t,server:r,discoveryEndpoint:Ce}).clientCredentials());return c.registerSecret(i.accessToken),i.refreshToken&&c.registerSecret(i.refreshToken),i}async function closeConnectionPool(){let e=globalThis,t=e[Symbol.for(`undici.globalDispatcher.2`)]??e[Symbol.for(`undici.globalDispatcher.1`)];typeof t?.close==`function`&&await t.close()}function getPluginImportBaseDirs(e){return e?[N.dirname(e)]:[process.cwd()]}function resolveRelativePluginImportPath(e,t){if(!e.startsWith(`.`))return null;for(let n of t){let t=N.resolve(n,e);if(F.existsSync(t))return t}return null}function generatePluginExecutorFiles(e,t,n,r,i){if(e.length===0)return[];let a=[],o=getPluginImportBaseDirs(i);for(let i of e){let e=generateSingleExecutorFile(i,t,n,r,o);a.push(e);let s=N.relative(process.cwd(),e);c.log(` Plugin Executor File: ${l.success(s)} from plugin ${l.info(i.pluginId)}`)}return a}function generateSingleExecutorFile(e,t,n,r,i=[]){let a=sanitizePluginId$1(e.pluginId),o=N.join(t,a,`executors`);F.mkdirSync(o,{recursive:!0});let s=sanitizeExecutorFileName(e.executor.name),c=N.join(o,`${s}.ts`),l;return l=ne(e.executor)?generateExecutorFileContentNew(e,e.executor,t,n,r,i):generateExecutorFileContentLegacy(e.executor),F.writeFileSync(c,l),c}function generateExecutorFileContentNew(e,t,n,r,i,a=[]){let{resolve:o,context:s}=t,c=sanitizePluginId$1(e.pluginId),l=N.join(n,c,`executors`),u=resolveExecutorImportPath(o,e.pluginImportPath,l,a),d=collectTableImports(s,n,e.pluginId,r,i),f=[];for(let[,e]of d)f.push(`import { ${e.variableName} } from "${e.importPath}";`);let p=generateContextCode(s,d);return j`
1
+ import{r as e}from"./date-Dri6Yas-.mjs";import{n as t}from"./brand-C8nMKhJC.mjs";import{a as n,i as r,n as i,o as a}from"./wait-point-registry-B-ESkTZX.mjs";import{t as o}from"./assert-WeXvmG4j.mjs";import{c as s,i as c,o as l}from"./logger-Db-YRTwK.mjs";import{n as u,t as d}from"./es-builtins-SfvXRVoG.mjs";import{n as f,r as p,t as m}from"./node-builtins-DYfhPBnz.mjs";import{a as h,b as g,c as _,d as v,f as y,g as b,h as x,l as S,m as C,n as w,o as T,p as E,s as D,t as O,u as k,x as A}from"./service-CL1Bp4It.mjs";import{t as j}from"./multiline-EyzjEwn9.mjs";import{i as ee,t as M}from"./errors-CpvSChyL.mjs";import{t as te}from"./user-agent-vdHYF3QL.mjs";import{i as ne,n as re}from"./guards-yDXyKC9F.mjs";import{t as ie}from"./type-source--ZNcV8RJ.mjs";import{createRequire as ae}from"node:module";import*as N from"pathe";import{resolve as oe}from"pathe";import{resolveTSConfig as se}from"pkg-types";import{z as P}from"zod";import{create as ce}from"@bufbuild/protobuf";import*as F from"node:fs";import{readFileSync as le}from"node:fs";import{MethodOptions_IdempotencyLevel as ue}from"@bufbuild/protobuf/wkt";import{Code as I,ConnectError as L,createClient as de}from"@connectrpc/connect";import{OAuth2Client as fe}from"@badgateway/oauth2-client";import pe from"p-limit";import*as me from"node:crypto";import{createHash as he}from"node:crypto";import*as R from"rolldown";import{parseSync as z}from"oxc-parser";import{createPathsMatcher as ge,getTsconfig as _e}from"get-tsconfig";import*as B from"inflection";import*as ve from"node:os";const ye=/* @__PURE__ */ new WeakMap;function withErrorDiagnostics(e,t){return ye.set(e,{...ye.get(e),...t}),e}function getErrorDiagnostics(e){return{...e instanceof L?{suggestion:rpcSuggestion(e.code)}:{},...ye.get(e)}}function rpcSuggestion(e){switch(e){case I.Unauthenticated:return"Check the active token and profile with `tailor auth status` (include the same --profile option). For an environment token, replace TAILOR_PLATFORM_TOKEN; otherwise use the original browser or --machine-user login method with the same profile. See `tailor login --help`.";case I.PermissionDenied:return"Check the active identity and profile with `tailor auth status` (include the same --profile option), then verify its workspace role and token permissions.";case I.Unavailable:case I.DeadlineExceeded:return`Check network connectivity and platform availability. A write may already have completed; inspect the current resource state before retrying.`;default:return}}function isForbiddenGlobal(e){return u.has(e)}const be=[`DEBUG`,`INFO`,`WARN`,`ERROR`,`SILENT`];function isLogLevel(e){return be.includes(e)}const xe=/^\d*[1-9]\d*$/;function parsePositiveInt(e){if(e===void 0)return;let t=e.trim();if(!xe.test(t))return;let n=Number.parseInt(t,10);return Number.isSafeInteger(n)?n:void 0}function resolveApplyConcurrency(){return parsePositiveInt(process.env.TAILOR_APPLY_CONCURRENCY)??16}function createApplyLimiter(){return pe(resolveApplyConcurrency())}function byName(e,t){return e.name<t.name?-1:+(e.name>t.name)}const Se=`https://api.tailor.tech`,Ce=`/.well-known/oauth-authorization-server/oauth2/platform`,we=/* @__PURE__ */ new Map;function getEnvPlatformUrl(){return process.env.TAILOR_PLATFORM_URL??process.env.PLATFORM_URL}function getEnvOAuth2ClientId(){return process.env.TAILOR_PLATFORM_OAUTH2_CLIENT_ID??process.env.PLATFORM_OAUTH2_CLIENT_ID}function normalizeBaseUrl(e){let t=new URL(e);return t.hash=``,t.search=``,t.toString().replace(/\/$/,``)}function getEffectivePlatformConfig(e={}){let t=e.platformUrl??getEnvPlatformUrl(),n=e.oauth2ClientId??getEnvOAuth2ClientId(),r=e.consoleUrl??process.env.TAILOR_PLATFORM_CONSOLE_URL,i={...t?{platformUrl:t}:{},...n?{oauth2ClientId:n}:{},...r?{consoleUrl:r}:{}};return Object.keys(i).length>0?i:void 0}function rememberPlatformConfigForToken(e,t){let n=getEffectivePlatformConfig(t);n?we.set(e,n):we.delete(e)}function getPlatformConfigForToken(e){return we.get(e)}function getPlatformBaseUrl(e={}){return normalizeBaseUrl(e.platformUrl??getEnvPlatformUrl()??`https://api.tailor.tech`)}function isDefaultPlatform(e){return getPlatformBaseUrl(e)===normalizeBaseUrl(Se)}function getOAuth2ClientId(e={}){return e.oauth2ClientId??getEnvOAuth2ClientId()??`cpoc_0Iudir72fqSpqC6GQ58ri1cLAqcq5vJl`}function inferConsoleBaseUrl(e){let t=new URL(e);return t.hostname.startsWith(`api.`)?(t.hostname=t.hostname.replace(/^api\./,`console.`),normalizeBaseUrl(t.toString())):`https://console.tailor.tech`}function getConsoleBaseUrl(e={}){if(e.consoleUrl)return normalizeBaseUrl(e.consoleUrl);if(e.platformUrl){let t=inferConsoleBaseUrl(e.platformUrl);if(t!==`https://console.tailor.tech`)return t}return process.env.TAILOR_PLATFORM_CONSOLE_URL?normalizeBaseUrl(process.env.TAILOR_PLATFORM_CONSOLE_URL):inferConsoleBaseUrl(getPlatformBaseUrl(e))}function initOAuth2Client(e){return new fe({clientId:getOAuth2ClientId(e),server:getPlatformBaseUrl(e),discoveryEndpoint:Ce})}async function initOperatorClient(e,t){let n=t??getPlatformConfigForToken(e),[{createTracingInterceptor:r},{OperatorService:i}]=await Promise.all([import(`./interceptor-DQg3cR_9.mjs`),import(`./service_pb-dB3RrGeh.mjs`)]),a=[await userAgentInterceptor(),await bearerTokenInterceptor(e),retryInterceptor(),errorHandlingInterceptor(),r(),concurrencyLimitInterceptor()],o=getPlatformBaseUrl(n),s=createPooledStreamTransport(await createTransport(o,a),()=>createTransport(o,a),4);return de(i,s)}async function createTransport(e,t){let{createConnectTransport:n}=await import(`@connectrpc/connect-node`);return n({httpVersion:`2`,baseUrl:e,interceptors:t})}const Te=/* @__PURE__ */ new Set([`CreateFunctionRegistry`,`UpdateFunctionRegistry`,`UploadFile`]);function createPooledStreamTransport(e,t,n){if(!Number.isInteger(n)||n<1)throw Error(`createPooledStreamTransport: maxConnections must be a positive integer, got ${n}`);let r=[e],i=[0],a=[],o=0;function acquireTransportIndex(e,s){return new Promise((c,l)=>{let u=!1,d;function cleanup(){u=!0,clearTimeout(d),e?.removeEventListener(`abort`,onAbort);let t=a.indexOf(attempt);t!==-1&&a.splice(t,1)}function onAbort(){cleanup(),l(L.from(e?.reason,I.Canceled))}function onTimeout(){cleanup(),l(new L(`the operation timed out`,I.DeadlineExceeded))}function claim(e){if(u){release(e);return}cleanup(),c(e)}function attempt(){let e=i.pop();if(e!==void 0){claim(e);return}if(r.length+o<n){o++,t().then(e=>{o--;let t=r.length;r.push(e),claim(t)},e=>{o--,cleanup(),l(e instanceof Error?e:Error(String(e))),wakeOneWaiter()});return}a.push(attempt)}if(e?.aborted){onAbort();return}if(e?.addEventListener(`abort`,onAbort,{once:!0}),s!==void 0){let e=s-performance.now();if(e<=0){onTimeout();return}d=setTimeout(onTimeout,e)}attempt()})}function wakeOneWaiter(){a.shift()?.()}function release(e){i.push(e),wakeOneWaiter()}return{unary(t,n,r,i,a,o){return e.unary(t,n,r,i,a,o)},async stream(t,n,i,a,o,s){if(!Te.has(t.name))return e.stream(t,n,i,a,o,s);let c=i!==void 0&&i>0?performance.now()+i:void 0,l=await acquireTransportIndex(n,c),u=r[l],d;try{if(n?.aborted)throw L.from(n.reason,I.Canceled);let e=c===void 0?i:Math.ceil(c-performance.now());if(c!==void 0&&e!==void 0&&e<=0)throw new L(`the operation timed out`,I.DeadlineExceeded);d=await u.stream(t,n,e,a,o,s)}catch(e){throw release(l),e}return{...d,message:releaseAfter(d.message,()=>release(l))}}}}async function*releaseAfter(e,t){try{yield*e}finally{t()}}async function userAgentInterceptor(){let e=await te();return t=>async n=>(n.header.set(`User-Agent`,e),await t(n))}async function bearerTokenInterceptor(e){return t=>async n=>(n.header.set(`Authorization`,`Bearer ${e}`),await t(n))}function retryInterceptor(){return e=>async t=>{if(t.stream)return await e(t);let n;for(let r=0;r<De;r++){r>0&&await waitRetryBackoff(r);try{return await e(t)}catch(e){if(isRetrySafeCreateAlreadyExists(e,t.method.name)){if(r>0)return c.debug(`retry: ${t.method.name} returned AlreadyExists on attempt ${r+1}; treating as success (prior attempt likely committed)`),synthesizeEmptyUnaryResponse(t);let{reportCrash:n}=await import(`./crashreport-CBaRJl5h.mjs`);await n(e,`handledError`)}if(t.method.name!==`CreateWorkspace`&&isRetirable(e,t.method.idempotency)){n=e,c.debug(`retry: ${t.method.name} attempt ${r+1} failed with ${retryErrorCodeName(e)}; retrying`);continue}throw e}}throw n}}function concurrencyLimitInterceptor(){let e=createApplyLimiter();return t=>async n=>n.stream?await t(n):await e(()=>t(n))}function retryErrorCodeName(e){return e instanceof L?I[e.code]:isTransportDisconnectError(e)?e.code:`unknown`}const Ee=/* @__PURE__ */ new Set([`CreateAIGateway`,`CreateApplication`,`CreateAuthConnection`,`CreateAuthHook`,`CreateAuthIDPConfig`,`CreateAuthMachineUser`,`CreateAuthOAuth2Client`,`CreateAuthSCIMConfig`,`CreateAuthSCIMResource`,`CreateAuthService`,`CreateExecutorExecutor`,`CreateIdPService`,`CreatePipelineResolver`,`CreatePipelineService`,`CreateSecretManagerSecret`,`CreateSecretManagerVault`,`CreateStaticWebsite`,`CreateTailorDBGQLPermission`,`CreateTailorDBService`,`CreateTailorDBType`,`CreateTenantConfig`,`CreateUserProfileConfig`,`CreateWorkflow`,`CreateWorkflowJobFunctionExecutionPolicy`]);function isRetrySafeCreateAlreadyExists(e,t){return e instanceof L&&e.code===I.AlreadyExists&&Ee.has(t)}function synthesizeEmptyUnaryResponse(e){return{stream:!1,service:e.service,method:e.method,header:new Headers,message:ce(e.method.output),trailer:new Headers}}const De=3;function waitRetryBackoff(e){let t=500*2**(e-1)*(1+.1*(Math.random()*2-1));return new Promise(e=>setTimeout(e,t))}const Oe=/* @__PURE__ */ new Set([`ERR_STREAM_PREMATURE_CLOSE`,`ECONNRESET`,`ETIMEDOUT`,`EPIPE`]);function isTransportDisconnectError(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&Oe.has(e.code)}function isRetirable(e,t){let n=t===ue.NO_SIDE_EFFECTS||t===ue.IDEMPOTENT;if(!(e instanceof L))return isTransportDisconnectError(e)&&n;switch(e.code){case I.ResourceExhausted:case I.Unavailable:return!0;case I.Aborted:case I.Internal:return n;default:return!1}}function errorHandlingInterceptor(){return e=>async t=>{try{return await e(t)}catch(e){if(e instanceof L){let{operation:n,resourceType:r}=parseMethodName(t.method.name),i=requestIdentifiers(t.message,t.method.name),a=Object.entries(i).map(([e,t])=>`${e}: ${t}`),o=a.length===0?``:` (${a.join(`, `)})`;throw withErrorDiagnostics(new L(`Failed to ${n} ${r}${o}: ${e.rawMessage}`,e.code,e.metadata),{context:{method:t.method.name,identifiers:i}})}throw isTransportDisconnectError(e)?withErrorDiagnostics(e,{code:`TRANSPORT_DISCONNECTED`,suggestion:`Check network connectivity and platform availability. A write may already have completed; inspect the current resource state before retrying.`,context:{method:t.method.name,transportCode:e.code,identifiers:requestIdentifiers(t.message,t.method.name)}}):e}}}function parseMethodName(e){let t=e.match(/^(Create|Update|Delete|Set|List|Get)(.+)$/);if(!t)return{operation:`perform`,resourceType:`resource`};let[,n,r]=t;return{operation:n.toLowerCase(),resourceType:r}}const ke=/* @__PURE__ */ new Set([`name`,`id`]),Ae=[`Name`,`Id`,`Namespace`],je=`name`,Me={GetMetadata:[`trn`],SetMetadata:[`trn`],AddCustomDomain:[`domain`],GetCustomDomain:[`domain`],RemoveCustomDomain:[`domain`],CreateWorkflowJobFunctionExecutionPolicy:[`executionPolicyKey`],UpdateWorkflowJobFunctionExecutionPolicy:[`executionPolicyKey`],GetWorkflowJobFunctionExecutionPolicyByKey:[`executionPolicyKey`]};function isIdentityKey(e,t){return e.startsWith(`$`)?!1:ke.has(e)||Ae.some(t=>e.endsWith(t))||(Me[t]?.includes(e)??!1)}function requestIdentifiers(e,t){if(typeof e!=`object`||!e)return{};let n={};for(let[r,i]of Object.entries(e))if(typeof i==`string`&&i!==``&&isIdentityKey(r,t))n[r]=i;else if(!r.startsWith(`$`)&&typeof i==`object`&&i&&!Array.isArray(i)&&typeof i.$typeName==`string`){let e=i[je];typeof e==`string`&&e!==``&&(n[`${r}.${je}`]=e)}return n}const Ne=1e3;async function fetchAll(e){let t=[],n=``;for(;;){let[r,i]=await e(n,Ne);if(t.push(...r),!i)break;n=i}return t}function isNotFoundError(e){return e instanceof L&&e.code===I.NotFound}async function fetchAllTolerant(e){return await fetchAll(async(t,n)=>{try{return await e(t,n)}catch(e){if(isNotFoundError(e))return[[],``];throw e}})}async function getOrNull(e){try{return await e()}catch(e){if(isNotFoundError(e))return;throw e}}async function fetchPaged(e,t){let n=t?.limit,r=n===void 0||n===0,i=[],a=``;for(;;){let t=r?Ne:Math.min(n-i.length,Ne);if(!r&&t<=0)break;let[o,s]=await e(a,t);if(i.push(...o),!r&&i.length>=n||!s)break;a=s}return!r&&i.length>n?i.slice(0,n):i}async function fetchUserInfo(e,t){let n=new URL(`/auth/platform/userinfo`,getPlatformBaseUrl(t)).href,r=await fetch(n,{headers:{Authorization:`Bearer ${e}`,"User-Agent":await te()}});if(!r.ok)throw Error(`Failed to fetch user info: ${r.statusText}`);let i=await r.json();return P.object({sub:P.string(),email:P.string()}).parse(i)}const V=/:url(\/.*)?$/;function hasStaticWebsiteUrlPlaceholder(e){return typeof e==`string`&&V.test(e)}function staticWebsiteNameFromPlaceholder(e){let t=e.match(V);return t?.index===void 0?e:e.substring(0,t.index)}async function resolveStaticWebsiteUrls(e,t,n,r,i={}){if(!n)return[];let{expectedLocalNames:a,keepUnresolved:o=!1,failOnUnexpectedError:s=!1}=i,unresolved=e=>o?[e]:[],l=o?`Leaving the ${r} value unresolved.`:`Excluding from ${r}.`,u=i.siteLookupCache??/* @__PURE__ */ new Map,lookupSite=n=>{let r=u.get(n);return r||(r=e.getStaticWebsite({workspaceId:t,name:n}),u.set(n,r)),r};return(await Promise.all(n.map(async e=>{let t=e.match(V);if(t&&t.index!==void 0){let n=e.substring(0,t.index),i=t[1]||``;try{let t=await lookupSite(n);if(t.staticwebsite?.url)return[t.staticwebsite.url+i];if(!a?.has(n)&&s)throw M({code:`STATIC_WEBSITE_URL_NOT_ASSIGNED`,message:`Static website "${n}" exists but has no URL assigned yet.`,suggestion:`Re-run the deploy once the static website's URL is available.`});return c.warn(`Static website "${n}" has no URL assigned yet. ${l}`),unresolved(e)}catch(t){if(isNotFoundError(t)){if(a?.has(n))return[e]}else if(s)throw t;return c.warn(`Static website "${n}" not found for ${r} configuration. ${l}`),unresolved(e)}}return[e]}))).flat()}async function resolveStaticWebsiteUrlsInEnv(e,t,n,r={}){if(!n||!Object.values(n).some(hasStaticWebsiteUrlPlaceholder))return n??{};let i=/* @__PURE__ */ new Map,a=await Promise.all(Object.entries(n).map(async([n,a])=>{if(!hasStaticWebsiteUrlPlaceholder(a))return[n,a];let[o]=await resolveStaticWebsiteUrls(e,t,[a],`env "${n}"`,{...r,keepUnresolved:!0,failOnUnexpectedError:!0,siteLookupCache:i});return[n,o??a]})),o=Object.fromEntries(a);return warnUnresolvedEnvPlaceholders(o,r.expectedLocalNames),o}function warnUnresolvedEnvPlaceholders(e,t){for(let[n,r]of Object.entries(e)){if(!hasStaticWebsiteUrlPlaceholder(r))continue;let e=r.slice(0,r.search(V));if(t?.has(e)){c.warn(`env "${n}" keeps the unresolved value "${r}" for now because static website "${e}" isn't available yet; this deploy rebuilds automatically once it is, to inject the real URL.`);continue}c.warn(`env "${n}" keeps the unresolved value "${r}". The literal pattern is passed to your code at runtime.`)}}async function fetchMachineUserToken(e,t,n){c.registerSecret(n);let r=new URL(`/oauth2/token`,e).href,i=new URLSearchParams;i.append(`grant_type`,`client_credentials`),i.append(`client_id`,t),i.append(`client_secret`,n);let a={method:`POST`,headers:{"User-Agent":await te(),"Content-Type":`application/x-www-form-urlencoded`},body:i},o=await withConnectTimeoutRetry(`machine user token request`,()=>fetch(r,a));if(!o.ok){let e=await o.text().catch(()=>``);throw Error(`Failed to fetch machine user token: ${o.status} ${o.statusText} ${e.slice(0,500)}`)}let s=await o.json(),l=P.object({token_type:P.string(),access_token:P.string(),expires_in:P.number()}).parse(s);return c.registerSecret(l.access_token),l}function isUndiciConnectTimeout(e){if(!(e instanceof TypeError))return!1;let t=e.cause;return t instanceof Error&&`code`in t&&t.code===`UND_ERR_CONNECT_TIMEOUT`}async function withConnectTimeoutRetry(e,t){for(let n=1;;n++)try{return await t()}catch(t){if(!isUndiciConnectTimeout(t)||n>=3)throw t;c.debug(`retry: ${e} attempt ${n} failed with UND_ERR_CONNECT_TIMEOUT; retrying`),await waitRetryBackoff(n)}}async function fetchPlatformMachineUserToken(e,t,n){c.registerSecret(t);let r=getPlatformBaseUrl(n),i=await withConnectTimeoutRetry(`platform machine user token request`,()=>new fe({clientId:e,clientSecret:t,server:r,discoveryEndpoint:Ce}).clientCredentials());return c.registerSecret(i.accessToken),i.refreshToken&&c.registerSecret(i.refreshToken),i}async function closeConnectionPool(){let e=globalThis,t=e[Symbol.for(`undici.globalDispatcher.2`)]??e[Symbol.for(`undici.globalDispatcher.1`)];typeof t?.close==`function`&&await t.close()}function getPluginImportBaseDirs(e){return e?[N.dirname(e)]:[process.cwd()]}function resolveRelativePluginImportPath(e,t){if(!e.startsWith(`.`))return null;for(let n of t){let t=N.resolve(n,e);if(F.existsSync(t))return t}return null}function generatePluginExecutorFiles(e,t,n,r,i){if(e.length===0)return[];let a=[],o=getPluginImportBaseDirs(i);for(let i of e){let e=generateSingleExecutorFile(i,t,n,r,o);a.push(e);let s=N.relative(process.cwd(),e);c.log(` Plugin Executor File: ${l.success(s)} from plugin ${l.info(i.pluginId)}`)}return a}function generateSingleExecutorFile(e,t,n,r,i=[]){let a=sanitizePluginId$1(e.pluginId),o=N.join(t,a,`executors`);F.mkdirSync(o,{recursive:!0});let s=sanitizeExecutorFileName(e.executor.name),c=N.join(o,`${s}.ts`),l;return l=ne(e.executor)?generateExecutorFileContentNew(e,e.executor,t,n,r,i):generateExecutorFileContentLegacy(e.executor),F.writeFileSync(c,l),c}function generateExecutorFileContentNew(e,t,n,r,i,a=[]){let{resolve:o,context:s}=t,c=sanitizePluginId$1(e.pluginId),l=N.join(n,c,`executors`),u=resolveExecutorImportPath(o,e.pluginImportPath,l,a),d=collectTableImports(s,n,e.pluginId,r,i),f=[];for(let[,e]of d)f.push(`import { ${e.variableName} } from "${e.importPath}";`);let p=generateContextCode(s,d);return j`
2
2
  /**
3
3
  * Auto-generated executor by plugin: ${e.pluginId}
4
4
  * DO NOT EDIT - This file is generated by @tailor-platform/sdk
@@ -66,7 +66,7 @@ import{r as e}from"./date-Dri6Yas-.mjs";import{n as t}from"./brand-C8nMKhJC.mjs"
66
66
  `)},\n}`}const Fe={string:`string`,integer:`int`,float:`float`,boolean:`bool`,uuid:`uuid`,datetime:`datetime`,date:`date`,time:`time`,enum:`enum`,nested:`nested`};function generateSingleFieldCode(e){let t=e.type;if(!t)return null;let n=Fe[t]??t,r=e._metadata??e.metadata??{},i=[];r.required===!1&&i.push(`optional: true`);let a=i.length>0?`{ ${i.join(`, `)} }`:``;if(t===`enum`){let e=r.allowedValues,t=[];Array.isArray(e)&&(t=e.map(e=>e.value));let n=`db.enum(${JSON.stringify(t)}${a?`, ${a}`:``})`;return r.index&&(n+=`.index()`),r.unique&&(n+=`.unique()`),r.description&&(n+=`.description(${JSON.stringify(r.description)})`),n}let o=`db.${n}(${a})`;return r.index&&(o+=`.index()`),r.unique&&(o+=`.unique()`),r.description&&(o+=`.description(${JSON.stringify(r.description)})`),o}function sanitizePluginId(e){return e.replace(/^@/,``).replace(/\//g,`-`)}function toKebabCase(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}function toCamelCase(e){let t=e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``);return t.charAt(0).toLowerCase()+t.slice(1)}function createDepCollectorPlugin(){let e=/* @__PURE__ */ new Set,t={name:`cache-dep-collector`,load:{filter:{id:{include:[/\.[^/]+$/]}},handler(t){return!t.includes(`node_modules`)&&!t.endsWith(`.entry.js`)&&e.add(t),null}}};function getResult(){return Array.from(e).toSorted()}return{plugin:t,getResult}}function hashContent(e){return me.createHash(`sha256`).update(e,`utf-8`).digest(`hex`)}function hashFile(e){let t=F.readFileSync(e);return me.createHash(`sha256`).update(t).digest(`hex`)}function hashFiles(e){return hashContent(e.toSorted().map(e=>hashFileOrMissing(e)).join(``))}function hashFileOrMissing(e){try{return hashFile(e)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return`<missing>`;throw e}}function buildCacheKey(e,t,n){return n?`${e}:${n}:${t}`:`${e}:${t}`}function combineHash(e,t){return t?hashContent(e+t):e}function computeBundlerContextHash(e){let{sourceFile:t,extraContext:n,tsconfig:r,inlineSourcemap:i,bundleLogLevel:a,prefix:o}=e;return hashContent((o??``)+N.resolve(t)+n+(r?hashFile(r):``)+String(i??!1)+(a??``))}async function withCache(e){let{cache:t,kind:n,namespace:r,name:i,sourceFile:a,contextHash:o,build:s}=e;if(!t)return await s([],()=>{});let u=t.tryRestore({kind:n,namespace:r,name:i,contextHash:o});if(u!==void 0)return c.debug(` ${l.dim(`cached`)}: ${i}`),u;let d=/* @__PURE__ */ new Set,{plugin:f,getResult:p}=createDepCollectorPlugin(),m=await s([f],e=>d.add(e));return t.save({kind:n,namespace:r,name:i,sourceFile:a,content:m.code,packageRuntimeGlobals:m.packageRuntimeGlobals,dependencyPaths:[...p(),...d],contextHash:o}),m}function createBundleCache(e){function tryRestore(t){let n=buildCacheKey(t.kind,t.name,t.namespace),r=e.getEntry(n);if(!r)return;let i;try{i=combineHash(hashFiles(r.dependencyPaths),t.contextHash)}catch{return}if(i!==r.inputHash)return;let a=e.restoreBundleContent(n),o=r.outputFiles.find(e=>e.outputPath===n);if(a!==void 0&&o&&hashContent(a)===o.contentHash)return{code:a,packageRuntimeGlobals:r.packageRuntimeGlobals??{}}}function save(t){let{kind:n,namespace:r,name:i,sourceFile:a,content:o,packageRuntimeGlobals:s,dependencyPaths:c,contextHash:l}=t,u=buildCacheKey(n,i,r),d=c.includes(a)?c:[a,...c],f;try{f=combineHash(hashFiles(d),l)}catch{return}let p=hashContent(o);e.storeBundleContent(u,o),e.setEntry(u,{kind:`bundle`,inputHash:f,dependencyPaths:d,outputFiles:[{outputPath:u,contentHash:p}],...s&&Object.keys(s).length>0?{packageRuntimeGlobals:s}:{},createdAt:(/* @__PURE__ */ new Date()).toISOString()})}return{tryRestore,save}}function getModuleExportName(e){if(!e||typeof e!=`object`)return;let t=e;return t.name?t.name:typeof t.value==`string`?t.value:void 0}function isTailorSdkSource(e){return/^@tailor-platform\/sdk(\/|$)/.test(e)}function getImportSource(e){if(!e)return null;if(e.type===`ImportExpression`){let t=e.source;if(t.type===`Literal`&&typeof t.value==`string`)return t.value}if(e.type===`CallExpression`){let t=e;if(t.callee.type===`Identifier`&&t.callee.name===`require`){let e=t.arguments[0];if(e&&`type`in e&&e.type===`Literal`&&`value`in e&&typeof e.value==`string`)return e.value}}return null}function argumentSourceText(e,t){if(e&&typeof e==`object`&&`start`in e&&`end`in e)return t.slice(e.start,e.end)}function getStartCallInfo(e,t){if(!e||typeof e!=`object`||e.type!==`CallExpression`)return null;let n=e,r=n.callee;if(r.type!==`MemberExpression`)return null;let i=r;return i.computed||i.property.name!==`start`||i.object.type!==`Identifier`?null:{identifierName:i.object.name,callRange:{start:n.start,end:n.end},argsText:argumentSourceText(n.arguments[0],t)??``,optionsText:argumentSourceText(n.arguments[1],t)}}function getNamespaceStartCallInfo(e,t){if(!e||typeof e!=`object`||e.type!==`CallExpression`)return null;let n=e,r=n.callee;if(r.type!==`MemberExpression`||r.computed||r.property.name!==`start`)return null;let i=r.object;if(i.type!==`MemberExpression`)return null;let a=i.object;if(a.type!==`Identifier`)return null;let o=i.property,s=i.computed?typeof o.value==`string`?o.value:void 0:o.name;return s===void 0?null:{identifierName:a.name,memberName:s,calleeText:t.slice(r.start,r.end),callRange:{start:n.start,end:n.end},argsText:argumentSourceText(n.arguments[0],t)??``,optionsText:argumentSourceText(n.arguments[1],t)}}function unwrapAwait(e){return e?.type===`AwaitExpression`?e.argument:e}function isStringLiteral(e){return e?.type===`Literal`&&typeof e.value==`string`}function isFunctionExpression(e){return e?.type===`ArrowFunctionExpression`||e?.type===`FunctionExpression`}function findProperty(e,t){for(let n of e)if(n.type===`Property`){let e=n;if((e.key.type===`Identifier`?e.key.name:e.key.type===`Literal`?e.key.value:null)===t)return{key:e.key,value:e.value,start:e.start,end:e.end}}return null}function applyReplacements(e,t){let n=t.toSorted((e,t)=>t.start-e.start);for(let e=0;e+1<n.length;e++){let t=o(n[e],`replacement missing at index ${e}`),r=o(n[e+1],`replacement missing at index ${e+1}`);if(r.end>t.start)throw Error(`applyReplacements: overlapping replacement ranges [${r.start}, ${r.end}) and [${t.start}, ${t.end})`)}let r=e;for(let e of n)r=r.slice(0,e.start)+e.text+r.slice(e.end);return r}function findStatementEnd(e,t){let n=t;for(;n<e.length&&(e[n]===`;`||e[n]===` `||e[n]===` `);)n++;return n<e.length&&e[n]===`
67
67
  `&&n++,n}function collectSdkBindings(e,t){let n=/* @__PURE__ */ new Set;function walk(e){if(!e||typeof e!=`object`)return;let r=e.type;if(r===`ImportDeclaration`){let r=e,i=r.source.value;if(typeof i==`string`&&isTailorSdkSource(i)){for(let e of r.specifiers)if(e.type===`ImportSpecifier`){let r=e;(r.imported.type===`Identifier`?r.imported.name:r.imported.value)===t&&n.add(r.local.name)}else if(e.type===`ImportDefaultSpecifier`||e.type===`ImportNamespaceSpecifier`){let t=e;n.add(`__namespace__:${t.local.name}`)}}}if(r===`VariableDeclaration`){let r=e;for(let e of r.declarations){let r=getImportSource(unwrapAwait(e.init));if(r&&isTailorSdkSource(r)){let r=e.id;if(r.type===`Identifier`)n.add(`__namespace__:${r.name}`);else if(r.type===`ObjectPattern`){let e=r;for(let r of e.properties)if(r.type===`Property`){let e=r,i=e.key.type===`Identifier`?e.key.name:e.key.value;if(i===t){let t=e.value.type===`Identifier`?e.value.name:i;n.add(t)}}}}}}for(let t of Object.keys(e)){let n=e[t];Array.isArray(n)?n.forEach(e=>walk(e)):n&&typeof n==`object`&&walk(n)}}return walk(e),n}function isSdkFunctionCall(e,t,n){if(e.type!==`CallExpression`)return!1;let r=e.callee;if(r.type===`Identifier`){let e=r;return t.has(e.name)}if(r.type===`MemberExpression`){let e=r;if(!e.computed){let r=e.object,i=e.property;if(r.type===`Identifier`&&t.has(`__namespace__:${r.name}`)&&i.name===n)return!0}}return!1}function findAllJobs(e,t){let n=[],r=collectSdkBindings(e,`createWorkflowJob`);function walk(e,t=[]){if(!e||typeof e!=`object`)return;if(isSdkFunctionCall(e,r,`createWorkflowJob`)){let r=e.arguments,i=r[0];if(r.length>=1&&i?.type===`ObjectExpression`){let e=o(i,`createWorkflowJob first argument missing`),r=findProperty(e.properties,`name`),a=findProperty(e.properties,`body`);if(r&&isStringLiteral(r.value)&&a&&isFunctionExpression(a.value)){let e,i;for(let n=t.length-1;n>=0;n--){let r=o(t[n],`parent at index ${n} missing`);if(r.type===`VariableDeclarator`){let e=r;e.id?.type===`Identifier`&&(i=e.id.name)}(r.type===`ExportNamedDeclaration`||r.type===`VariableDeclaration`)&&(e={start:r.start,end:r.end})}n.push({name:r.value.value,exportName:i,nameRange:{start:r.start,end:r.end},bodyValueRange:{start:a.value.start,end:a.value.end},statementRange:e})}}}let i=[...t,e];for(let t of Object.keys(e)){let n=e[t];Array.isArray(n)?n.forEach(e=>walk(e,i)):n&&typeof n==`object`&&walk(n,i)}}return walk(e),n}function findAllWorkflows(e,t){let n=[],r=collectSdkBindings(e,`createWorkflow`);function walk(e,t=[]){if(!e||typeof e!=`object`)return;if(isSdkFunctionCall(e,r,`createWorkflow`)){let r=e.arguments,i=r[0];if(r.length>=1&&i?.type===`ObjectExpression`){let e=findProperty(o(i,`createWorkflow first argument missing`).properties,`name`);if(e&&isStringLiteral(e.value)){let r,i=!1;for(let e=t.length-1;e>=0;e--){let n=o(t[e],`parent at index ${e} missing`);if(n.type===`VariableDeclarator`){let e=n;if(e.id?.type===`Identifier`){r=e.id.name;break}}n.type===`ExportDefaultDeclaration`&&(i=!0)}n.push({name:e.value.value,exportName:r,isDefaultExport:i})}}}let i=[...t,e];for(let t of Object.keys(e)){let n=e[t];Array.isArray(n)?n.forEach(e=>walk(e,i)):n&&typeof n==`object`&&walk(n,i)}}return walk(e),n}function createTsconfigLookupCache(){return{tsconfigCache:/* @__PURE__ */ new Map,contextCache:/* @__PURE__ */ new Map}}function createTsconfigPathsPlugin(e={}){let{tsconfigCache:t,contextCache:n}=e.cache??createTsconfigLookupCache();return{name:`tailor-tsconfig-paths`,resolveId:{order:`post`,async handler(r,i){if(!i||r.startsWith(`.`)||r.startsWith(`/`)||r.startsWith(`\0`))return null;let a=i.startsWith(`\0`)?e.virtualEntrySourceFile:i;if(!a)return null;let o=getResolutionContext(N.dirname(a),t,n,e.onTsconfigRead);if(!o)return null;let s=o.matcher(r);if(s.length===0||await this.resolve(r,i,{skipSelf:!0}))return null;for(let e of s){let t=await this.resolve(e,i,{skipSelf:!0});if(t)return t}return null}}}}function matchTsconfigPaths(e,t,n){return getResolutionContext(t,n.tsconfigCache,n.contextCache)?.matcher(e)??[]}function getResolutionContext(e,t,n,r){let i=n.get(e);if(i!==void 0)return reportTsconfigDependencies(t,r),i;let a=_e(e,`tsconfig.json`,t);reportTsconfigDependencies(t,r);let o=a?.config.compilerOptions?.paths,s=o&&Object.keys(o).length>0?ge(a):null,c=s?{matcher:s}:null;return n.set(e,c),c}function reportTsconfigDependencies(e,t){if(!t)return;let n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set;for(let[t,i]of e){let e=dependencyPathFromCacheKey(t);e&&(t.startsWith(`statSync:`)&&isDirectoryStat(i)?n.add(e):r.add(e))}for(let e of r)n.has(e)||t(e)}function dependencyPathFromCacheKey(e){if(e.startsWith(`readFileSync:`)&&e.endsWith(`:utf8`))return e.slice(13,-5);for(let t of[`existsSync:`,`statSync:`])if(e.startsWith(t))return e.slice(t.length)}function isDirectoryStat(e){return typeof e==`object`&&!!e&&`isDirectory`in e&&typeof e.isDirectory==`function`&&e.isDirectory()}function normalizeFilePath(e){return N.resolve(e.replace(/[?#].*$/,``)).replace(/\.(ts|mts|cts|js|mjs|cjs)$/,``)}function createModuleBindings(e,t,n){let r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map;for(let e of findAllWorkflows(t,n)){let t={kind:`workflow`,name:e.name};e.exportName&&r.set(e.exportName,t),e.isDefaultExport&&i.set(`default`,t)}for(let e of findAllJobs(t,n))e.exportName&&r.set(e.exportName,{kind:`job`,name:e.name});for(let e of t.body){if(e.type===`ExportDefaultDeclaration`){let t=e.declaration;if(t?.type===`Identifier`){let e=r.get(t.name);e&&i.set(`default`,e)}continue}if(e.type!==`ExportNamedDeclaration`)continue;let t=e.declaration;if(t?.type===`VariableDeclaration`)for(let e of t.declarations){let t=e.id;if(t?.type!==`Identifier`)continue;let n=t.name,a=r.get(n);a&&i.set(n,a)}if(!e.source)for(let t of e.specifiers??[]){let e=getModuleExportName(t.local),n=getModuleExportName(t.exported);if(!e||!n)continue;let a=r.get(e);a&&i.set(n,a)}}return{sourceFile:e,localBindings:r,exports:i}}async function buildStartContext(e,t,n=process.cwd(),r=[],i=createTsconfigLookupCache()){let a=/* @__PURE__ */ new Map;if(!e)return{modules:a,authNamespace:t,tsconfigCache:i};for(let t of b(e,n))try{let e=await F.promises.readFile(t,`utf-8`),{program:n,errors:r}=z(t,e);if(r.length>0){c.warn(`Failed to parse workflow file ${t}: ${r.map(e=>e.message).join(`; `)}`,{mode:`stream`});continue}a.set(normalizeFilePath(t),createModuleBindings(t,n,e))}catch(e){let n=e instanceof Error?e.message:String(e);c.warn(`Failed to process workflow file ${t}: ${n}`,{mode:`stream`})}for(let{workflow:e,sourceFile:t}of r)a.get(normalizeFilePath(t))?.exports.set(`default`,{kind:`workflow`,name:e.name});return{modules:a,authNamespace:t,tsconfigCache:i}}function sortedTargets(e){return[...e].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t.kind,t.name])}function serializeStartContext(e){if(!e)return``;let t=[...e.modules].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,sortedTargets(t.localBindings),sortedTargets(t.exports)]);return JSON.stringify(t)+(e.authNamespace??``)}const Ie=/\.start(?:\s|\/\*[\s\S]*?\*\/|\/\/[^\n]*\n)*\(/;function hasStartCall(e){return Ie.test(e)}const Le=`__tailor_normalizeStartOptions`;function buildNormalizerHelperSource(e){return`const ${Le} = (o) => { if (!o) return o; const { invoker, ...rest } = o; return typeof invoker === "string" ? { ...rest, authInvoker: { namespace: ${JSON.stringify(e)}, machineUserName: invoker } } : typeof invoker === "object" ? { ...rest, authInvoker: invoker } : o; };\n`}function collectBindingNames(e,t){if(e&&typeof e==`object`)switch(e.type){case`Identifier`:t.add(e.name);return;case`ObjectPattern`:for(let n of e.properties)collectBindingNames(n.type===`RestElement`?n.argument:n.value,t);return;case`ArrayPattern`:for(let n of e.elements)collectBindingNames(n,t);return;case`AssignmentPattern`:collectBindingNames(e.left,t);return;case`RestElement`:collectBindingNames(e.argument,t);return;case`TSParameterProperty`:collectBindingNames(e.parameter,t)}}function declarationNode(e){return e.type===`ExportNamedDeclaration`||e.type===`ExportDefaultDeclaration`?e.declaration:e}function collectBlockBindings(e,t){for(let n of e){let e=declarationNode(n);if(e){if(e.type===`VariableDeclaration`){if(e.kind===`var`)continue;for(let n of e.declarations)collectBindingNames(n.id,t)}else(e.type===`FunctionDeclaration`||e.type===`ClassDeclaration`)&&collectBindingNames(e.id,t)}}}function collectFunctionVarBindings(e,t){function walk(n){if(n&&typeof n==`object`&&(n===e||n.type!==`FunctionDeclaration`&&n.type!==`FunctionExpression`&&n.type!==`ArrowFunctionExpression`&&n.type!==`StaticBlock`)){if(n.type===`VariableDeclaration`&&n.kind===`var`)for(let e of n.declarations)collectBindingNames(e.id,t);for(let e of Object.keys(n)){if(e===`parent`)continue;let t=n[e];if(Array.isArray(t))for(let e of t)walk(e);else t&&typeof t==`object`&&walk(t)}}}walk(e)}function collectScopeBindings(e){let t=/* @__PURE__ */ new Set;if(e.type===`FunctionDeclaration`||e.type===`FunctionExpression`||e.type===`ArrowFunctionExpression`){collectBindingNames(e.id,t);for(let n of e.params)collectBindingNames(n,t);return collectFunctionVarBindings(e,t),t}if(e.type===`BlockStatement`)return collectBlockBindings(e.body,t),t;if(e.type===`CatchClause`)return collectBindingNames(e.param,t),t;if(e.type===`ForStatement`||e.type===`ForInStatement`||e.type===`ForOfStatement`){let n=e.init??e.left;if(n?.type===`VariableDeclaration`&&n.kind!==`var`)for(let e of n.declarations)collectBindingNames(e.id,t);return t}}function addShadowedBindings(e,t,n){if(!t)return e;let r=[...t].filter(e=>n.has(e));return r.length===0?e:/* @__PURE__ */ new Set([...e,...r])}function walkBindingAware(e,t,n){function walk(e,r,i,a){if(!e||typeof e!=`object`||e.type===`ImportDeclaration`)return;let o=e.type===`Program`?r:addShadowedBindings(r,collectScopeBindings(e),t);n(e,o,i,a);for(let t of Object.keys(e)){if(t===`parent`)continue;let n=e[t];if(Array.isArray(n))for(let r of n)walk(r,o,e,t);else n&&typeof n==`object`&&walk(n,o,e,t)}}walk(e,/* @__PURE__ */ new Set)}function findModule(e,t){let n=normalizeFilePath(t);return e.modules.get(n)??e.modules.get(N.join(n,`index`))}function resolveImport(e,t,n,r){let i=N.dirname(t.replace(/[?#].*$/,``));if(n.startsWith(`.`))return findModule(e,N.resolve(i,n));for(let t of matchTsconfigPaths(n,i,r)){let n=findModule(e,t);if(n)return n}}function collectLocalTargets(e,t,n){let r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=t.modules.get(normalizeFilePath(n));if(o)for(let[e,t]of o.localBindings)r.set(e,t);let s=t.tsconfigCache??createTsconfigLookupCache();for(let o of e.body){if(o.type!==`ImportDeclaration`||o.importKind===`type`)continue;let e=o.source.value;if(typeof e!=`string`)continue;let c=resolveImport(t,n,e,s);if(c)for(let t of o.specifiers){if(t.type===`ImportNamespaceSpecifier`){a.set(t.local.name,{importSource:e,module:c});continue}if(t.type===`ImportSpecifier`&&t.importKind===`type`)continue;let n=t.type===`ImportDefaultSpecifier`?`default`:getModuleExportName(t.imported);if(!n)continue;let o=c.exports.get(n);if(!o){i.set(t.local.name,{importSource:e,importedName:n});continue}r.set(t.local.name,o)}}return{targets:r,undetectableImports:i,namespaceImports:a}}function undetectableStartCallError(e,t,{importSource:n,importedName:r}){let i=r==="default"?`default export`:`export "${r}"`;return/* @__PURE__ */ Error(`${e}() in ${t} cannot be rewritten: "${n}" is a workflow file, but its ${i} is not a workflow or job the build can detect. The build rewrites .start() on the file's default-exported workflow (including one returned from a helper function) and on workflows and jobs created in that file with createWorkflow({ name: "..." }) or createWorkflowJob({ name: "...", body }) using a literal name; any other .start() would fail at runtime after deploy.`)}function assertNoUndetectableStartCalls(e,t,{undetectableImports:n,namespaceImports:r},i){walkBindingAware(e,/* @__PURE__ */ new Set([...n.keys(),...r.keys()]),(e,a)=>{let o=getNamespaceStartCallInfo(e,t);if(o&&!a.has(o.identifierName)){let e=r.get(o.identifierName);if(e&&!e.module.exports.has(o.memberName))throw undetectableStartCallError(o.calleeText,i,{importSource:e.importSource,importedName:o.memberName})}let s=getStartCallInfo(e,t);if(!s||a.has(s.identifierName))return;let c=n.get(s.identifierName);if(c)throw undetectableStartCallError(`${s.identifierName}.start`,i,c)})}function detectStartCallsWithTargets(e,t,{targets:n,namespaceImports:r}){let i=[];return walkBindingAware(e,/* @__PURE__ */ new Set([...n.keys(),...r.keys()]),(e,a)=>{let o=getNamespaceStartCallInfo(e,t);if(o&&!a.has(o.identifierName)){let e=r.get(o.identifierName)?.module.exports.get(o.memberName);if(e){let{memberName:t,calleeText:n,...r}=o;i.push({...r,kind:e.kind,targetName:e.name})}return}let s=getStartCallInfo(e,t);if(!s||a.has(s.identifierName))return;let c=n.get(s.identifierName);c&&i.push({...s,kind:c.kind,targetName:c.name})}),i}function detectResolvedStartCalls(e,t,n,r){return detectStartCallsWithTargets(e,t,collectLocalTargets(e,n,r))}function transformStartCalls(e,t,n){let{program:r}=z(`input.ts`,e),i=collectLocalTargets(r,t,n);assertNoUndetectableStartCalls(r,e,i,n);let{authNamespace:a}=t,o=detectStartCallsWithTargets(r,e,i),s=[],l=o.filter(e=>{let t=o.find(t=>t!==e&&t.callRange.start<=e.callRange.start&&e.callRange.end<=t.callRange.end);return!t||(s.push({call:e,parent:t}),!1)});for(let{call:e,parent:t}of s)c.warn(`Nested start call "${e.identifierName}.start(...)" inside "${t.identifierName}.start(...)" cannot be converted. Move it to a separate statement and pass the result instead.`);let u=[],d=!1;for(let e of l){let t;if(e.kind===`workflow`){let n=``;e.optionsText!==void 0&&(a?(n=`, ${Le}(${e.optionsText})`,d=!0):n=`, ${e.optionsText}`),t=`tailor.workflow.startWorkflow(${JSON.stringify(e.targetName)}, ${e.argsText||`undefined`}${n})`}else{let n=e.optionsText===void 0?``:`, ${e.optionsText}`;t=`tailor.workflow.execJobFunction(${JSON.stringify(e.targetName)}, ${e.argsText||`undefined`}${n})`}u.push({start:e.callRange.start,end:e.callRange.end,text:t})}let f=applyReplacements(e,u);return d&&a?buildNormalizerHelperSource(a)+f:f}function createStartTransformPlugin(e){if(e&&e.modules.size!==0)return{name:`start-transform`,transform:{filter:{id:{include:[/\.(ts|mts|cts|js|mjs|cjs)$/]}},handler(t,n){return hasStartCall(t)?{code:transformStartCalls(t,e,n)}:null}}}}function createBundleLog(e={}){let t=/* @__PURE__ */ new Map;return{options:{logLevel:`warn`,onLog:(e,n)=>{n.code===`UNRESOLVED_IMPORT`&&t.set(JSON.stringify([n.exporter,n.id]),n)}},assertAllResolved(){if(t.size>0)throw unresolvedImportError([...t.values()],e.tsconfig)}}}function unresolvedImportError(e,t){let n=e.map(formatUnresolvedImport),r=n.length===1?`Could not resolve ${n[0]}.`:`Could not resolve ${n.length} imports.`,i=n.length===1?void 0:n.map(e=>`- ${e}`).join(`
68
68
  `),a=unresolvedImportSuggestion(e,t);return M({code:`UNRESOLVED_IMPORT`,message:r,details:i,suggestion:a})}function unresolvedImportSuggestion(e,t){let n=e.map(e=>e.exporter).filter(e=>e!==void 0).filter(p).map(f),r=e.some(e=>e.exporter===void 0||!p(e.exporter)),i=t?`Check that each import path is correct, and that a \`compilerOptions.paths\` entry covering it is declared in the importing file's own tsconfig.json or an ancestor. The build used "${t}".`:"No tsconfig.json was found, so `compilerOptions.paths` aliases were not applied. Add a tsconfig.json declaring the aliases these files import.";return[.../* @__PURE__ */ new Set([...n,...r?[i]:[]])].join(`
69
- `)}function formatUnresolvedImport(e){let t=e.exporter??`an imported module`,n=e.id?.startsWith(`\0`)?`a generated entry (${e.id.slice(1)})`:e.id&&`"${e.id}"`;return`"${t}"${n?` imported from ${n}`:``}`}const Re=[`console.info`,`console.table`,`console.dir`,`console.dirxml`,`console.count`,`console.countReset`,`console.time`,`console.timeLog`,`console.timeEnd`,`console.group`,`console.groupCollapsed`,`console.groupEnd`,`console.clear`],H=[`console.debug`,`console.log`,`console.trace`],ze=[`console.warn`],Be=[`console.error`],U=[`globalThis.tailor.logger.debug`],Ve=[`globalThis.tailor.logger.info`],He=[`globalThis.tailor.logger.warn`],Ue=[`globalThis.tailor.logger.error`],We={DEBUG:[],INFO:[...H,...U],WARN:[...H,...Re,...U,...Ve],ERROR:[...H,...Re,...ze,...U,...Ve,...He],SILENT:[...H,...Re,...ze,...Be,...U,...Ve,...He,...Ue]};function normalizeBundleLogLevel(e){let t=e.trim().toUpperCase();return isLogLevel(t)?t:void 0}function resolveBundleLogLevel(e){if(e===void 0)return`DEBUG`;let t=normalizeBundleLogLevel(e);if(t)return t;throw Error(`Invalid logLevel "${e}". Expected one of: ${ye.join(`, `)}`)}function manualPureFunctionsForLogLevel(e){return We[e]}function createLogLevelTreeshakeOptions(e){let t=manualPureFunctionsForLogLevel(e);return t.length>0?{manualPureFunctions:t}:{}}const Ge={moduleSideEffects:!1,annotations:!0,unknownGlobalSideEffects:!1};function mergeFunctionTreeshakeOptions(e){let t={},n=/* @__PURE__ */ new Set;for(let r of e){Object.assign(t,r);for(let e of r.manualPureFunctions??[])n.add(e)}return n.size>0?t.manualPureFunctions=[...n]:delete t.manualPureFunctions,t}function composeFunctionTreeshakeOptions(e=[]){return mergeFunctionTreeshakeOptions([Ge,...e])}const Ke=/(?<![\w$.])process\.env\.__TAILOR_PLATFORM_BUNDLE\b/g,qe=/(?<![\w$.])globalThis\.process\?\.env\.__TAILOR_PLATFORM_BUNDLE_WITHOUT_DATE\b/g,Je=/(?<![\w$.])globalThis\.process\?\.env\.__TAILOR_PLATFORM_BUNDLE_WITHOUT_TEMPORAL\b/g;function createPlatformBundleDefinePlugin(e={date:!0,temporal:!0}){return{name:`tailor-platform-bundle-define`,transform(t){return t.includes(`__TAILOR_PLATFORM_BUNDLE`)?{code:t.replace(Ke,`true`).replace(qe,String(!e.date)).replace(Je,String(!e.temporal))}:null},resolveId(e){return e===`node:async_hooks`?{id:e,external:!0}:null}}}const W=createPlatformBundleDefinePlugin(),Ye=/* @__PURE__ */ new Set;async function resolveTSConfigWithFallback(e){let t=await tryResolve(e);if(t||e===process.cwd())return t;let n=await tryResolve(process.cwd());return n&&!Ye.has(e)&&(Ye.add(e),c.warn(`No tsconfig found from "${e}"; falling back to the tsconfig resolved from process.cwd(). Move (or extend) a tsconfig into this directory before v2, when this fallback will be removed.`)),n}async function tryResolve(e){try{return await se(e)}catch{return}}function createVirtualEntry(e,t,n=`js`,r){let i=`tailor-entry:${e}.${n}`,a=`\0${i}`;return{input:i,plugin:{name:`tailor-virtual-entry`,async resolveId(e,t){return e===i&&t===void 0?a:t!==a||!r||e.startsWith(`.`)||N.isAbsolute(e)||e.startsWith(`\0`)?null:this.resolve(e,r,{skipSelf:!0})},load(e){return e===a?t:null}}}}function createGeneratedEntryResolverPlugin(e,t){let n=N.resolve(e),r=N.join(N.resolve(t),`__tailor_sdk_generated_entry__.js`);return{name:`tailor-generated-entry-resolver`,async resolveId(e,t){return t===void 0||N.resolve(t)!==n||e.startsWith(`.`)||N.isAbsolute(e)||e.startsWith(`\0`)?null:this.resolve(e,r,{skipSelf:!0})}}}async function bundleAuthHooks(e){let{configPath:t,authName:n,handlerAccessPath:r,env:i={},startContext:a,cache:o,inlineSourcemap:s,bundleLogLevel:u=`DEBUG`,baseDir:d,tsconfigCache:f}=e;c.newline(),c.log(`Bundling auth hook for ${l.info(`"${n}"`)}`);let p=N.resolve(t),m=await resolveTSConfigWithFallback(d),h=`auth-hook--${n}--before-login`,{code:g}=await withCache({cache:o,kind:`auth-hook`,name:h,sourceFile:p,contextHash:computeBundlerContextHash({sourceFile:p,extraContext:serializeStartContext(a),tsconfig:m,inlineSourcemap:s,bundleLogLevel:u,prefix:JSON.stringify(Object.fromEntries(Object.entries(i).toSorted(([e],[t])=>e.localeCompare(t))))}),async build(e,t){let n=j`
69
+ `)}function formatUnresolvedImport(e){let t=e.exporter??`an imported module`,n=e.id?.startsWith(`\0`)?`a generated entry (${e.id.slice(1)})`:e.id&&`"${e.id}"`;return`"${t}"${n?` imported from ${n}`:``}`}const Re=[`console.info`,`console.table`,`console.dir`,`console.dirxml`,`console.count`,`console.countReset`,`console.time`,`console.timeLog`,`console.timeEnd`,`console.group`,`console.groupCollapsed`,`console.groupEnd`,`console.clear`],H=[`console.debug`,`console.log`,`console.trace`],ze=[`console.warn`],Be=[`console.error`],U=[`globalThis.tailor.logger.debug`],Ve=[`globalThis.tailor.logger.info`],He=[`globalThis.tailor.logger.warn`],Ue=[`globalThis.tailor.logger.error`],We={DEBUG:[],INFO:[...H,...U],WARN:[...H,...Re,...U,...Ve],ERROR:[...H,...Re,...ze,...U,...Ve,...He],SILENT:[...H,...Re,...ze,...Be,...U,...Ve,...He,...Ue]};function normalizeBundleLogLevel(e){let t=e.trim().toUpperCase();return isLogLevel(t)?t:void 0}function resolveBundleLogLevel(e){if(e===void 0)return`DEBUG`;let t=normalizeBundleLogLevel(e);if(t)return t;throw Error(`Invalid logLevel "${e}". Expected one of: ${be.join(`, `)}`)}function manualPureFunctionsForLogLevel(e){return We[e]}function createLogLevelTreeshakeOptions(e){let t=manualPureFunctionsForLogLevel(e);return t.length>0?{manualPureFunctions:t}:{}}const Ge={moduleSideEffects:!1,annotations:!0,unknownGlobalSideEffects:!1};function mergeFunctionTreeshakeOptions(e){let t={},n=/* @__PURE__ */ new Set;for(let r of e){Object.assign(t,r);for(let e of r.manualPureFunctions??[])n.add(e)}return n.size>0?t.manualPureFunctions=[...n]:delete t.manualPureFunctions,t}function composeFunctionTreeshakeOptions(e=[]){return mergeFunctionTreeshakeOptions([Ge,...e])}const Ke=/(?<![\w$.])process\.env\.__TAILOR_PLATFORM_BUNDLE\b/g,qe=/(?<![\w$.])globalThis\.process\?\.env\.__TAILOR_PLATFORM_BUNDLE_WITHOUT_DATE\b/g,Je=/(?<![\w$.])globalThis\.process\?\.env\.__TAILOR_PLATFORM_BUNDLE_WITHOUT_TEMPORAL\b/g;function createPlatformBundleDefinePlugin(e={date:!0,temporal:!0}){return{name:`tailor-platform-bundle-define`,transform(t){return t.includes(`__TAILOR_PLATFORM_BUNDLE`)?{code:t.replace(Ke,`true`).replace(qe,String(!e.date)).replace(Je,String(!e.temporal))}:null},resolveId(e){return e===`node:async_hooks`?{id:e,external:!0}:null}}}const W=createPlatformBundleDefinePlugin(),Ye=/* @__PURE__ */ new Set;async function resolveTSConfigWithFallback(e){let t=await tryResolve(e);if(t||e===process.cwd())return t;let n=await tryResolve(process.cwd());return n&&!Ye.has(e)&&(Ye.add(e),c.warn(`No tsconfig found from "${e}"; falling back to the tsconfig resolved from process.cwd(). Move (or extend) a tsconfig into this directory before v2, when this fallback will be removed.`)),n}async function tryResolve(e){try{return await se(e)}catch{return}}function createVirtualEntry(e,t,n=`js`,r){let i=`tailor-entry:${e}.${n}`,a=`\0${i}`;return{input:i,plugin:{name:`tailor-virtual-entry`,async resolveId(e,t){return e===i&&t===void 0?a:t!==a||!r||e.startsWith(`.`)||N.isAbsolute(e)||e.startsWith(`\0`)?null:this.resolve(e,r,{skipSelf:!0})},load(e){return e===a?t:null}}}}function createGeneratedEntryResolverPlugin(e,t){let n=N.resolve(e),r=N.join(N.resolve(t),`__tailor_sdk_generated_entry__.js`);return{name:`tailor-generated-entry-resolver`,async resolveId(e,t){return t===void 0||N.resolve(t)!==n||e.startsWith(`.`)||N.isAbsolute(e)||e.startsWith(`\0`)?null:this.resolve(e,r,{skipSelf:!0})}}}async function bundleAuthHooks(e){let{configPath:t,authName:n,handlerAccessPath:r,env:i={},startContext:a,cache:o,inlineSourcemap:s,bundleLogLevel:u=`DEBUG`,baseDir:d,tsconfigCache:f}=e;c.newline(),c.log(`Bundling auth hook for ${l.info(`"${n}"`)}`);let p=N.resolve(t),m=await resolveTSConfigWithFallback(d),h=`auth-hook--${n}--before-login`,{code:g}=await withCache({cache:o,kind:`auth-hook`,name:h,sourceFile:p,contextHash:computeBundlerContextHash({sourceFile:p,extraContext:serializeStartContext(a),tsconfig:m,inlineSourcemap:s,bundleLogLevel:u,prefix:JSON.stringify(Object.fromEntries(Object.entries(i).toSorted(([e],[t])=>e.localeCompare(t))))}),async build(e,t){let n=j`
70
70
  import _config from "${p}";
71
71
  const __auth_hook_function = _config.${r};
72
72
  export async function main(args) {
@@ -196,5 +196,5 @@ globalThis.transform = __adapter.output;
196
196
  }
197
197
  `,f=createVirtualEntry(`workflow-job:${e.name}`,d,`js`,u),p=safeRealpath(e.sourceFile),m=t.filter(t=>t.name!==e.name&&safeRealpath(t.sourceFile)===p).map(e=>e.exportName),h=[f.plugin,{name:`workflow-transform`,transform:{filter:{id:{include:[/\.(ts|mts|cts|js|mjs|cjs)$/]}},handler(t,n){if(!t.includes(`createWorkflowJob`)&&!t.includes(`createWorkflow`)&&!hasStartCall(t))return null;let r=t;return safeRealpath(n)===p&&(r=transformWorkflowSource(t,e.name,e.exportName,m)),hasStartCall(r)&&(r=transformStartCalls(r,i,n)),r===t?null:{code:r}}}},createTsconfigPathsPlugin({onTsconfigRead:l,cache:c}),W,...a],g=createBundleLog({tsconfig:n}),_=await R.build({input:f.input,write:!1,output:{format:`esm`,sourcemap:!o||`inline`,minify:!o||{mangle:{keepNames:!0}},codeSplitting:!1},tsconfig:n,plugins:h,treeshake:composeFunctionTreeshakeOptions([createLogLevelTreeshakeOptions(s)]),...g.options});g.assertAllResolved();let[v]=_.output;return{code:v.code,packageRuntimeGlobals:checkForbiddenRuntimeGlobals(v,`Workflow job "${e.name}"`)}}});return assertPackageRuntimeGlobalsAllowed(m,`Workflow job "${e.name}"`,l),[e.name,p]}const bt=/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/,xt=/^[a-z0-9][a-z0-9_:.-]{0,62}[a-z0-9*]$/,St=`key must not end with '*'; omit the '*' and set matchType: "prefix" for wildcard policies (the SDK appends '*' automatically).`;function toPlatformExecutionPolicyKey(e,t){return t===`prefix`?`${e}*`:e}const Ct=[`ms`,`s`,`m`],wt={ms:1/1e3,s:1,m:60};function durationToSeconds(e){let t=/^(\d+)(ms|s|m)$/.exec(e);return t?.[1]===void 0||t[2]===void 0?null:parseInt(t[1],10)*wt[t[2]]}const X={maxRetries:{min:1,max:10},initialBackoffMaxSeconds:3600,maxBackoffMaxSeconds:86400,backoffMultiplierMin:1},Tt=P.strictObject({name:P.string().describe(`Job name (must be unique across the project)`),start:A.describe(`Start function that initiates the job`),body:A.describe(`Job implementation function`),publishEvents:P.boolean().optional().describe(`Enable publishing job execution events for this job`)}),seconds=e=>durationToSeconds(e)??0,Et=P.templateLiteral([P.number().int().positive(),P.enum(Ct)]),durationSchema=e=>Et.refine(t=>seconds(t)<=e,{message:`Duration must be at most ${e} seconds`}),Dt=P.strictObject({maxRetries:P.number().int().min(X.maxRetries.min).max(X.maxRetries.max).describe(`Maximum number of retries (1-10)`),initialBackoff:durationSchema(X.initialBackoffMaxSeconds).describe(`Initial backoff duration (e.g., '1s', '500ms', '1m', max 1h)`),maxBackoff:durationSchema(X.maxBackoffMaxSeconds).describe(`Maximum backoff duration (e.g., '30s', '5m', max 24h)`),backoffMultiplier:P.number().min(X.backoffMultiplierMin).describe(`Backoff multiplier (>= 1)`)}).refine(e=>seconds(e.initialBackoff)<=seconds(e.maxBackoff),{message:`initialBackoff must be less than or equal to maxBackoff`,path:[`initialBackoff`]}).refine(e=>seconds(e.initialBackoff)>0,{message:`initialBackoff must be greater than 0`,path:[`initialBackoff`]}),Ot=P.strictObject({maxConcurrentExecutions:P.number().int().min(1).max(1e3).describe(`Maximum number of concurrent executions (1-1000)`)}),kt=P.string().regex(bt,`Invalid execution policy name: must match [a-z0-9-] (3-63 chars; must start and end with [a-z0-9])`).describe(`Workspace-unique execution policy name embedded in the resource TRN`),At=P.string().regex(xt,`Invalid execution policy key: must match [a-z0-9_:.-] (2-64 chars; must start with [a-z0-9] and end with [a-z0-9] or a trailing '*')`).describe(`Execution policy key passed to execJobFunction's executionPolicyKey option`),jt=P.strictObject({name:kt,key:At,concurrencyPolicy:Ot.optional().describe(`Optional per-key concurrency cap for job function dispatches matching this policy`)}),Mt=P.strictObject({name:P.string().describe(`Workflow name`),mainJob:Tt.describe(`Main job that starts the workflow`),retryPolicy:Dt.optional().describe(`Retry policy for the workflow`),concurrencyPolicy:Ot.optional().describe(`Concurrency policy for the workflow`),publishEvents:P.boolean().optional().describe(`Enable publishing workflow execution events for this workflow`)});function stripRuntimeStart(e){if(!t(e,`workflow`)||typeof e!=`object`||!e||!(`start`in e))return e;let{start:n,...r}=e;return r}function createWorkflowService(e){let{config:t,baseDir:n}=e,r={},i=[],a=[],o=0,s=!1;return{config:t,get workflows(){return r},get workflowSources(){return i},get jobs(){return a},get fileCount(){return o},loadWorkflows:async()=>{if(s)return;let e=await loadAndCollectJobs(t,n);r=e.workflows,i=e.workflowSources,a=e.jobs,o=e.fileCount,s=!0},printLoadedWorkflows:()=>{if(o!==0){c.newline(),c.log(`Found ${l.highlight(o.toString())} workflow files`);for(let{workflow:e,sourceFile:t}of i){let n=N.relative(process.cwd(),t);c.debug(`Workflow: ${l.successBright(`"${e.name}"`)} loaded from ${l.path(n)}`)}}}}}async function loadAndCollectJobs(e,t){let n={},r=[],i=[];if(e.files.length===0)return{workflows:n,workflowSources:r,jobs:i,fileCount:0};let a=b(e,t),o=a.length,s=/* @__PURE__ */ new Map,c=await Promise.all(a.map(async e=>{let{jobs:t,workflow:n}=await loadFileContent(e);return{workflowFile:e,jobs:t,workflow:n}}));for(let{workflowFile:e,jobs:t,workflow:a}of c){a&&(r.push({workflow:a,sourceFile:e}),n[e]=a);for(let e of t){let t=s.get(e.name);if(t)throw Error(`Duplicate job name "${e.name}" found:\n - ${t.sourceFile} (export: ${t.exportName})\n - ${e.sourceFile} (export: ${e.exportName})\nEach job must have a unique name.`);s.set(e.name,e),i.push(e)}}return{workflows:n,workflowSources:r,jobs:i,fileCount:o}}async function loadFileContent(e){let n=[],r=null;try{let i=await g(e);for(let[a,o]of Object.entries(i)){if(a==="default"){let e=Mt.safeParse(stripRuntimeStart(o));if(e.success)r=e.data;else if(t(o,[`workflow`,`workflow-job`]))throw e.error;continue}let i=Tt.safeParse(o);if(i.success)n.push({name:i.data.name,exportName:a,sourceFile:e,...i.data.publishEvents===void 0?{}:{publishEvents:i.data.publishEvents}});else if(t(o,[`workflow`,`workflow-job`]))throw i.error}}catch(t){let n=N.relative(process.cwd(),e);throw c.error(`${l.error(`Failed to load workflow from`)} ${l.errorBright(n)}`),c.error(String(t)),t}return{jobs:n,workflow:r}}function getApplicationAuthNamespace(e){return e.authService?.config.name??e.config?.auth?.name}function requireApplicationAuthNamespace(e){let t=getApplicationAuthNamespace(e);if(!t)throw Error(`No Auth service configured`);return t}function buildOptionsOf(e){let{buildOptions:t={}}=e;return{inlineSourcemap:t.inlineSourcemap??e.inlineSourcemap,logLevel:t.logLevel??e.logLevel,allowedRuntimeGlobals:t.allowedRuntimeGlobals}}let Z=null;const getDistDir=()=>{let e=process.env.TAILOR_BUILD_OUTPUT_DIR;return e&&e!==Z?Z=e:Z===null&&(Z=e||`.tailor`),Z};function resolveInlineSourcemap(e){if(e!==void 0)return e;let t=s(process.env.TAILOR_INLINE_SOURCEMAP);return t===void 0||t}function resolverBundleKey(e,t){return`${e}:${t}`}const Nt=P.strictObject({name:P.string().regex(/^[a-z0-9][a-z0-9-]{1,28}[a-z0-9]$/,`Must be 3-30 lowercase alphanumeric characters or hyphens`).describe(`AI Gateway name`),authNamespace:P.string().regex(/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/,`Must be 3-63 lowercase alphanumeric characters or hyphens`).optional().describe(`Auth namespace used to resolve request tokens against the workspace's auth. Defaults to the application's own auth service when omitted; omitting it without an Auth service configured is rejected.`),cors:P.array(P.string()).optional().describe("Allowed CORS origins for browser-based clients. Each entry is `*`, `http(s)://*`, `http(s)://*.example.com`, or `http(s)://app.example.com`, optionally with `:port`. Empty list disables cross-origin access.")}),Pt=/^(\*|[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$/;function containsAllEmailDomains(e){return e.some(e=>e.trim()===`*`)}function hasImplicitAllEmailDomains(e){return e?.useNonEmailIdentifier===!0?!1:!e?.allowedEmailDomains||e.allowedEmailDomains.length===0}function normalizeIdPGqlOperations(e){return e===`query`?{create:!1,update:!1,delete:!1,read:!0,sendPasswordResetEmail:!1,requestMfaSettingsUrl:!0,unenrollMfa:!1}:e}const Ft=P.union([P.literal(`query`),P.strictObject({create:P.boolean().optional().describe(`Enable _createUser mutation (default: true)`),update:P.boolean().optional().describe(`Enable _updateUser mutation (default: true)`),delete:P.boolean().optional().describe(`Enable _deleteUser mutation (default: true)`),read:P.boolean().optional().describe(`Enable _users and _user queries (default: true)`),sendPasswordResetEmail:P.boolean().optional().describe(`Enable _sendPasswordResetEmail mutation (default: true)`),requestMfaSettingsUrl:P.boolean().optional().describe(`Enable _requestMfaSettingsUrl query (default: true)`),unenrollMfa:P.boolean().optional().describe(`Enable _unenrollMfa mutation (default: true)`)})]).describe(`Configuration for GraphQL operations on IdP users.
198
198
  All operations are enabled by default (undefined or true = enabled, false = disabled).`).transform(e=>normalizeIdPGqlOperations(e)),It=P.enum([`en`,`ja`]).describe(`IdP UI language`),Lt=P.strictObject({useNonEmailIdentifier:P.boolean().optional().describe(`Use non-email identifier for usernames`),allowSelfPasswordReset:P.boolean().optional().describe(`Allow users to reset their own passwords`),passwordRequireUppercase:P.boolean().optional().describe(`Require uppercase letters in passwords`),passwordRequireLowercase:P.boolean().optional().describe(`Require lowercase letters in passwords`),passwordRequireNonAlphanumeric:P.boolean().optional().describe(`Require non-alphanumeric characters in passwords`),passwordRequireNumeric:P.boolean().optional().describe(`Require numeric characters in passwords`),passwordMinLength:P.number().int().refine(e=>e>=6&&e<=30,{message:`passwordMinLength must be between 6 and 30`}).optional().describe(`Minimum password length (6-30)`),passwordMaxLength:P.number().int().refine(e=>e>=6&&e<=4096,{message:`passwordMaxLength must be between 6 and 4096`}).optional().describe(`Maximum password length (6-4096)`),allowedEmailDomains:P.array(P.string().regex(Pt,`must be a hostname, or * to allow all email domains`)).max(100,`allowedEmailDomains accepts at most 100 entries`).refine(e=>new Set(e.map(e=>e.toLowerCase())).size===e.length,{message:`allowedEmailDomains entries must be unique, compared case-insensitively`}).refine(e=>e.length<=1||!containsAllEmailDomains(e),{message:`allowedEmailDomains cannot contain other entries when * is set`}).optional().describe(`Restrict registration to these email domains. A lone * entry allows every domain`),allowGoogleOauth:P.boolean().optional().describe(`Enable Google OAuth login`),allowMicrosoftOauth:P.boolean().optional().describe(`Enable Microsoft OAuth login`),disablePasswordAuth:P.boolean().optional().describe(`Disable password-based authentication`),enableMfa:P.boolean().optional().describe(`Make TOTP MFA available for users in this namespace`),requireMfa:P.boolean().optional().describe(`Require TOTP MFA enrollment and challenge for password-authenticated users (requires enableMfa)`),allowedReturnOrigins:P.array(P.string().regex(/^(https?:\/\/[a-zA-Z0-9.-]+(:[0-9]+)?|[a-z0-9][a-z0-9-]{1,61}[a-z0-9]:url)$/,`must be an http(s) origin like "https://app.example.com" (scheme + host + optional port, no path/query/fragment) or a static-website placeholder like "<name>:url"`)).optional().describe(`Application origins (scheme + host + optional port) allowed as MFA self-service return targets`),mfaIssuer:P.string().max(64,`mfaIssuer must be 64 characters or less`).optional().describe(`Label shown next to the user account in authenticator apps`)}).refine(e=>e.passwordMinLength===void 0||e.passwordMaxLength===void 0||e.passwordMinLength<=e.passwordMaxLength,{message:`passwordMinLength must be less than or equal to passwordMaxLength`,path:[`passwordMinLength`]}).refine(e=>!e.allowedEmailDomains||e.allowedEmailDomains.length===0||!e.useNonEmailIdentifier,{message:`allowedEmailDomains cannot be set when useNonEmailIdentifier is true`,path:[`allowedEmailDomains`]}).refine(e=>e.allowGoogleOauth===void 0||e.allowGoogleOauth===!1||!e.useNonEmailIdentifier,{message:`allowGoogleOauth cannot be set when useNonEmailIdentifier is true`,path:[`allowGoogleOauth`]}).refine(e=>!e.allowGoogleOauth||e.allowedEmailDomains&&e.allowedEmailDomains.length>0,{message:`allowGoogleOauth requires a non-empty allowedEmailDomains (["*"] to allow every domain)`,path:[`allowGoogleOauth`]}).refine(e=>!e.allowMicrosoftOauth||!e.useNonEmailIdentifier,{message:`allowMicrosoftOauth cannot be set when useNonEmailIdentifier is true`,path:[`allowMicrosoftOauth`]}).refine(e=>!e.allowMicrosoftOauth||e.allowedEmailDomains&&e.allowedEmailDomains.length>0,{message:`allowMicrosoftOauth requires a non-empty allowedEmailDomains (["*"] to allow every domain)`,path:[`allowMicrosoftOauth`]}).refine(e=>!e.allowMicrosoftOauth||e.disablePasswordAuth===!0,{message:`allowMicrosoftOauth requires disablePasswordAuth to be enabled`,path:[`allowMicrosoftOauth`]}).refine(e=>!e.disablePasswordAuth||e.allowGoogleOauth===!0||e.allowMicrosoftOauth===!0,{message:`disablePasswordAuth requires allowGoogleOauth or allowMicrosoftOauth to be enabled`,path:[`disablePasswordAuth`]}).refine(e=>!e.disablePasswordAuth||!e.allowSelfPasswordReset,{message:`disablePasswordAuth cannot be used with allowSelfPasswordReset`,path:[`disablePasswordAuth`]}).refine(e=>!e.requireMfa||e.enableMfa===!0,{message:`requireMfa requires enableMfa to be enabled`,path:[`requireMfa`]}).refine(e=>!e.enableMfa||e.allowedReturnOrigins&&e.allowedReturnOrigins.length>0,{message:`enableMfa requires allowedReturnOrigins to list at least one origin so MFA self-service has a valid return target`,path:[`enableMfa`]}),Rt=P.string().max(200,`must be 200 characters or less`).regex(/^[^\r\n]*$/,`must not contain newline characters`),zt=P.strictObject({fromName:Rt.optional().describe(`Default sender display name for emails`),passwordResetSubject:Rt.optional().describe(`Default subject for password reset emails`)}).describe(`Namespace-level email configuration defaults`),Q=P.union([P.string(),P.boolean(),P.array(P.string()).readonly(),P.array(P.boolean()).readonly(),P.strictObject({user:P.string()}),P.strictObject({idpUser:P.enum([`id`,`name`,`disabled`])}),P.strictObject({oldIdpUser:P.enum([`id`,`name`,`disabled`])}),P.strictObject({newIdpUser:P.enum([`id`,`name`,`disabled`])})]),Bt=P.enum([`=`,`!=`,`in`,`not in`]),Vt=P.tuple([Q,Bt,Q]).readonly(),$=P.union([P.strictObject({conditions:P.union([Vt,P.array(Vt).readonly()]),description:P.string().optional(),permit:P.boolean().optional()}),P.tuple([Q,Bt,Q]).readonly(),P.tuple([Q,Bt,Q,P.boolean()]).readonly(),P.array(P.union([Vt,P.boolean()])).refine(e=>{let t=e.findIndex(e=>typeof e==`boolean`);return t===-1||t===e.length-1},{message:`Boolean permit flag must only appear at the end`}).readonly()]),Ht=P.strictObject({create:P.array($).readonly(),read:P.array($).readonly(),update:P.array($).readonly(),delete:P.array($).readonly(),sendPasswordResetEmail:P.array($).readonly().optional(),unenrollMfa:P.array($).readonly().optional()}).describe(`Per-operation permission policies for IdP users`),Ut=P.strictObject({name:P.string().describe(`IdP service name`),authorization:P.union([P.literal(`insecure`),P.literal(`loggedIn`),P.strictObject({cel:P.string()})]).optional().describe(`Authorization mode for IdP API access`),clients:P.array(P.string()).describe(`OAuth2 client names that can use this IdP`),lang:It.optional().describe(`UI language for IdP pages`),userAuthPolicy:Lt.transform(e=>Lt.parse(e??{})).optional().describe(`User authentication policy configuration`),publishEvents:P.boolean().optional().describe(`Enable publishing user lifecycle events`),gqlOperations:Ft.optional().describe(`Configure which GraphQL operations are enabled`),emailConfig:zt.optional().describe(`Namespace-level email configuration defaults`),permission:Ht.optional().describe(`Per-operation permission policies for IdP users`)}).refine(e=>!e.userAuthPolicy?.enableMfa||e.gqlOperations?.unenrollMfa===!1||e.permission!==void 0&&e.permission.unenrollMfa!==void 0,{message:`permission.unenrollMfa must be set explicitly when userAuthPolicy.enableMfa is true (set [{ conditions: [...], permit: true }] to allow, or [] to deny all). permission itself must also be defined. The requirement is only relaxed when gqlOperations.unenrollMfa is false.`,path:[`permission`,`unenrollMfa`]}).refine(e=>!e.permission||e.userAuthPolicy?.disablePasswordAuth===!0||e.gqlOperations?.sendPasswordResetEmail===!1||e.permission.sendPasswordResetEmail!==void 0,{message:`permission.sendPasswordResetEmail must be set explicitly when password authentication is enabled (set [{ conditions: [...], permit: true }] to allow, or [] to deny; only optional when userAuthPolicy.disablePasswordAuth is true or gqlOperations.sendPasswordResetEmail is false)`,path:[`permission`,`sendPasswordResetEmail`]}),Wt=P.string().regex(/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/),Gt=P.record(Wt,P.string().nullish()),Kt=P.strictObject({vaults:P.record(Wt,Gt),options:P.strictObject({ignoreNullishValues:P.boolean()})}),qt=P.strictObject({name:P.string().describe(`Static website name`),description:P.string().optional().describe(`Static website description`),allowedIpAddresses:P.array(P.string()).optional().describe(`IP addresses allowed to access the website`),customDomains:P.array(P.string()).optional().describe(`Custom domains for the static website`)}),Jt=/^[a-z0-9]+$/,Yt=/^[A-Za-z_][A-Za-z0-9_]*$/;function checkWaitPointKey(e){let{key:t,declaredBy:i}=e,o=t.split(`-`),s=o.filter(a);if(s.length>0&&i!==`define`)return i===`property`?`Invalid wait point key "${t}": $params cannot come from a property name. Pass the key to define instead, e.g. define.for("${t}")<Payload, Result>().`:`Invalid wait point key "${t}": createWaitPoint takes its type arguments first, which stops TypeScript inferring the key as a literal, so it cannot type the $params. Declare it through createWaitPoints instead: createWaitPoints((define) => ({ myWaitPoint: define.for("${t}")<Payload, Result>() })).`;let c=/* @__PURE__ */ new Set,l=0;for(let e of o){if(e.startsWith(`$`)){let n=e.slice(1);if(!Yt.test(n))return`Invalid wait point key "${t}": "${e}" is not a usable parameter name. Use letters, digits and underscores, starting with a letter or underscore.`;if(c.has(n))return`Invalid wait point key "${t}": parameter "$${n}" appears more than once.`;c.add(n);continue}if(e!==``){if(!Jt.test(e))return`Invalid wait point key "${t}": segment "${e}" may only contain [a-z0-9]. Wait point keys accept ${r}, with $params standing in for runtime values.`;l+=1}}if(l===0&&s.length>0)return t.startsWith(`-`)||t.endsWith(`-`)?`Invalid wait point key "${t}": must match ${r}.`:`Invalid wait point key "${t}": it needs at least one literal segment alongside its $params, otherwise the key carries no identity of its own and can collide with an unrelated wait point.`;if(s.length===0)return n.test(t)?void 0:`Invalid wait point key "${t}": must match ${r}.`;let u=o.map(e=>e.startsWith(`$`)?`0`:e).join(`-`);return u.length>63?`Wait point key "${t}" cannot fit in 63 characters: even single-character parameter values produce ${u.length}.`:n.test(u)?void 0:`Invalid wait point key "${t}": must match ${r}.`}function collectWaitPointKeyFailures(e){let t=[],n=/* @__PURE__ */ new Set;for(let r of e){let e=`${r.declaredBy} ${r.key}`;if(n.has(e))continue;n.add(e);let i=checkWaitPointKey(r);i&&t.push(i)}return t}function defineTailorDB(e,t,n){let r=[],i=[],a=[];if(!e)return{tailorDBServices:r,externalTailorDBNamespaces:i,subgraphs:a};for(let[o,s]of Object.entries(e)){if(`external`in s)i.push(o);else{let e=createTailorDBService({namespace:o,config:k.parse(s),pluginManager:n,baseDir:t});r.push(e)}a.push({Type:`tailordb`,Name:o})}return{tailorDBServices:r,externalTailorDBNamespaces:i,subgraphs:a}}function defineResolver(e,t){let n=[],r=[];if(!e)return{resolverServices:n,subgraphs:r};for(let[i,a]of Object.entries(e)){if(!(`external`in a)){let e=createResolverService(i,a,t);n.push(e)}r.push({Type:`pipeline`,Name:i})}return{resolverServices:n,subgraphs:r}}function stripIdpProviderHelper(e){let t=e;if(typeof t.provider!=`function`)return e;let{provider:n,...r}=t;return r}function defineIdp(e){let t=[],n=[];if(!e)return{idpServices:t,subgraphs:n};let r=/* @__PURE__ */ new Set;return e.forEach(e=>{let i=e.name;if(r.has(i))throw Error(`IdP with name "${i}" already defined.`);if(r.add(i),!(`external`in e)){let n=Ut.parse(stripIdpProviderHelper(e));t.push(n)}n.push({Type:`idp`,Name:i})}),{idpServices:t,subgraphs:n}}function defineAuth(e,t,n){let r=[];if(!e)return{authService:void 0,subgraphs:r};let i;return`external`in e||(i=createAuthService(h.parse(e),t,n)),r.push({Type:`auth`,Name:e.name}),{authService:i,subgraphs:r}}function defineExecutor(e,t,n){if(e||n)return O({config:e??{files:[]},baseDir:t})}function defineWorkflow(e,t){if(e)return createWorkflowService({config:e,baseDir:t})}function defineHttpAdapterService(e,t){if(e)return createHttpAdapterService({config:e,baseDir:t})}function stripStaticWebsiteUrlHelper(e){let t=e;if(t.url!==`${e.name}:url`)return e;let{url:n,...r}=t;return r}function defineStaticWebsites(e){let t=[],n=/* @__PURE__ */ new Set;return(e??[]).forEach(e=>{let r=qt.parse(stripStaticWebsiteUrlHelper(e));if(n.has(r.name))throw Error(`Static website with name "${r.name}" already defined.`);n.add(r.name),t.push(r)}),t}function defineAIGateways(e,t){let n=[],r=/* @__PURE__ */ new Set;return(e??[]).forEach(e=>{let i=Nt.parse(e);if(r.has(i.name))throw Error(`AI Gateway with name "${i.name}" already defined.`);if(r.add(i.name),i.authNamespace===void 0){if(!t)throw Error(`AI Gateway "${i.name}" has no "authNamespace" and no Auth service is configured to default to. Define an Auth service, or set "authNamespace" explicitly.`);i.authNamespace=t}n.push(i)}),n}function parseSecretManager(e){if(!e)return{secrets:[],ignoreNullishValues:!1};let t=Kt.parse(e),{ignoreNullishValues:n}=t.options,r=Object.entries(t.vaults).map(([e,t])=>({vaultName:e,secrets:Object.entries(t).map(([e,t])=>({name:e,value:t}))}));if(!n){for(let e of r)for(let t of e.secrets)if(t.value==null)throw Error(`Secret "${e.vaultName}/${t.name}" has no value. Use { ignoreNullishValues: true } option in defineSecretManager() to skip secrets without values.`)}return{secrets:r,ignoreNullishValues:n}}function defineServices(e,t,n){let r=defineTailorDB(e.db,t,n),i=defineResolver(e.resolver,t),a=defineIdp(e.idp),o=defineAuth(e.auth,r.tailorDBServices,r.externalTailorDBNamespaces),s=defineStaticWebsites(e.staticWebsites),c=defineAIGateways(e.aiGateways,getApplicationAuthNamespace({authService:o.authService,config:e})),{secrets:l,ignoreNullishValues:u}=parseSecretManager(e.secrets);return{tailordbResult:r,resolverResult:i,idpResult:a,authResult:o,staticWebsiteServices:s,aiGatewayServices:c,secrets:l,ignoreNullishValues:u}}function buildApplication(e){let t={name:e.config.name,id:e.config.id,config:e.config,subgraphs:[...e.tailordbResult.subgraphs,...e.resolverResult.subgraphs,...e.idpResult.subgraphs,...e.authResult.subgraphs],tailorDBServices:e.tailordbResult.tailorDBServices,externalTailorDBNamespaces:e.tailordbResult.externalTailorDBNamespaces,resolverServices:e.resolverResult.resolverServices,idpServices:e.idpResult.idpServices,authService:e.authResult.authService,executorService:e.executorService,workflowService:e.workflowService,httpAdapterService:e.httpAdapterService,staticWebsiteServices:e.staticWebsiteServices,aiGatewayServices:e.aiGatewayServices,secrets:e.secrets,ignoreNullishValues:e.ignoreNullishValues,env:e.env,get applications(){return[t]}};return t}function defineApplication(e){let{config:t,pluginManager:n}=e,r=N.dirname(t.path),i=defineServices(t,r,n),a=defineExecutor(t.executor,r,!1),o=defineWorkflow(t.workflow,r),s=defineHttpAdapterService(t.httpAdapter,r);return buildApplication({config:t,...i,executorService:a,workflowService:o,httpAdapterService:s,env:t.env??{}})}function generatePluginFilesIfNeeded(e,t,n){if(!e)return[];let r=/* @__PURE__ */ new Map;for(let e of t){let t=e.typeSourceInfo;for(let[e,n]of Object.entries(t))n.filePath&&r.set(e,{filePath:n.filePath,exportName:n.exportName})}return e.generatePluginFiles({outputDir:N.join(getDistDir(),`plugin`),sourceTableInfoMap:r,configPath:n,tableGenerator:generatePluginTableFiles,executorGenerator:generatePluginExecutorFiles})}function assertWaitPointKeys(){let e=collectWaitPointKeyFailures(i());if(e.length!==0)throw Error(e.join(`
199
- `))}async function loadApplication(e){let{config:t,pluginManager:n,bundleCache:r,client:i,workspaceId:a,expectedLocalStaticWebsiteNames:o,previous:s}=e,l=N.dirname(t.path);if(s)return reloadEnvDependentBundles({config:t,baseDir:l,client:i,workspaceId:a,expectedLocalStaticWebsiteNames:o,bundleCache:r,previous:s});let{tailordbResult:u,resolverResult:d,idpResult:f,authResult:p,staticWebsiteServices:m,aiGatewayServices:h,secrets:g,ignoreNullishValues:_}=defineServices(t,l,n),v=i&&a?await resolveStaticWebsiteUrlsInEnv(i,a,t.env??{},{expectedLocalNames:o??new Set(m.map(e=>e.name))}):t.env??{};for(let e of u.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();assertUniqueLocalTailorDBTypeNames({tailorDBServices:u.tailorDBServices});let y=generatePluginFilesIfNeeded(n,u.tailorDBServices,t.path),b=defineExecutor(t.executor,l,y.length>0),x=defineWorkflow(t.workflow,l);x&&await x.loadWorkflows();let S=defineHttpAdapterService(t.httpAdapter,l);S&&await S.loadAdapters();let C=createTsconfigLookupCache(),w=await buildStartContext(t.workflow,getApplicationAuthNamespace({authService:p.authService,config:t}),l,x?.workflowSources,C),T=buildOptionsOf(t),E=resolveInlineSourcemap(T.inlineSourcemap),D=resolveBundleLogLevel(T.logLevel),O={resolvers:/* @__PURE__ */ new Map,executors:/* @__PURE__ */ new Map,workflowJobs:/* @__PURE__ */ new Map,authHooks:/* @__PURE__ */ new Map};for(let e of d.resolverServices){let t=await bundleResolvers({namespace:e.namespace,config:e.config,baseDir:l,defaultPermission:e.defaultPermission,startContext:w,cache:r,inlineSourcemap:E,bundleLogLevel:D,tsconfigCache:C,allowedRuntimeGlobals:T.allowedRuntimeGlobals});for(let[n,r]of t)O.resolvers.set(resolverBundleKey(e.namespace,n),r)}b&&(O.executors=await bundleExecutors({config:b.config,startContext:w,additionalFiles:[...y],cache:r,inlineSourcemap:E,bundleLogLevel:D,baseDir:l,tsconfigCache:C,allowedRuntimeGlobals:T.allowedRuntimeGlobals}));let k;if(x&&x.jobs.length>0){let e=x.workflowSources.map(e=>e.workflow.mainJob.name);k=await bundleWorkflowJobs(x.jobs,e,v,w,l,r,E,D,C,void 0,T.allowedRuntimeGlobals),O.workflowJobs=k.bundledCode}let A;if(S&&S.adapters.length>0&&(A=await bundleHttpAdapters(S.adapters.map(e=>({name:e.adapter.name,sourceFile:e.sourceFile,methods:e.methods,hasOutput:e.hasOutput})),l,r,D,C)),p.authService?.config.hooks?.beforeLogin){let e=p.authService.config.name;O.authHooks=await bundleAuthHooks({configPath:t.path,authName:e,handlerAccessPath:`auth.hooks.beforeLogin.handler`,env:v,startContext:w,cache:r,inlineSourcemap:E,bundleLogLevel:D,baseDir:l,tsconfigCache:C})}for(let e of d.resolverServices)await e.loadResolvers();return b&&(await b.loadExecutors(),y.length>0&&await b.loadPluginExecutorFiles([...y])),assertWaitPointKeys(),x&&x.printLoadedWorkflows(),S&&S.printLoadedAdapters(),c.newline(),{application:buildApplication({config:t,tailordbResult:u,resolverResult:d,idpResult:f,authResult:p,executorService:b,workflowService:x,httpAdapterService:S,staticWebsiteServices:m,aiGatewayServices:h,secrets:g,ignoreNullishValues:_,env:v}),workflowBuildResult:k,httpAdapterBuildResult:A,bundledScripts:O,reusableBuildState:{startContext:w,tsconfigCache:C,inlineSourcemap:E,bundleLogLevel:D}}}async function reloadEnvDependentBundles(e){let{config:t,baseDir:n,client:r,workspaceId:i,expectedLocalStaticWebsiteNames:a,bundleCache:o,previous:s}=e,{application:c,reusableBuildState:l}=s,{startContext:u,tsconfigCache:d,inlineSourcemap:f,bundleLogLevel:p}=l,m=r&&i?await resolveStaticWebsiteUrlsInEnv(r,i,t.env??{},{expectedLocalNames:a??new Set(c.staticWebsiteServices.map(e=>e.name))}):t.env??{},h={...s.bundledScripts},g=c.workflowService,_=s.workflowBuildResult;if(g&&g.jobs.length>0){let e=g.workflowSources.map(e=>e.workflow.mainJob.name);_=await bundleWorkflowJobs(g.jobs,e,m,u,n,o,f,p,d,s.workflowBuildResult,buildOptionsOf(t).allowedRuntimeGlobals),h.workflowJobs=_.bundledCode}if(c.authService?.config.hooks?.beforeLogin){let e=c.authService.config.name;h.authHooks=await bundleAuthHooks({configPath:t.path,authName:e,handlerAccessPath:`auth.hooks.beforeLogin.handler`,env:m,startContext:u,cache:o,inlineSourcemap:f,bundleLogLevel:p,baseDir:n,tsconfigCache:d})}let v={...c,env:m,get applications(){return[v]}};return{application:v,workflowBuildResult:_,httpAdapterBuildResult:s.httpAdapterBuildResult,bundledScripts:h,reusableBuildState:l}}export{getConsoleBaseUrl as $,$e as A,createBundleLog as B,resolverDateRepresentations as C,createPermissionNormalizer as D,findUndefinedReferences as E,createPlatformBundleDefinePlugin as F,closeConnectionPool as G,createBundleCache as H,W as I,fetchAllTolerant as J,Se as K,composeFunctionTreeshakeOptions as L,assertParsableExpression as M,createGeneratedEntryResolverPlugin as N,hasOmittedPermit as O,resolveTSConfigWithFallback as P,fetchUserInfo as Q,createLogLevelTreeshakeOptions as R,buildResolverValidatedInputExpr as S,assertUniqueTailorDBTypeNamesWithExternal as T,hashContent as U,createTsconfigPathsPlugin as V,hashFile as W,fetchPaged as X,fetchMachineUserToken as Y,fetchPlatformMachineUserToken as Z,Y as _,ye as _t,resolverBundleKey as a,initOperatorClient as at,buildResolverOperationHookExpr as b,buildOptionsOf as c,normalizeBaseUrl as ct,jt as d,resolveStaticWebsiteUrlsInEnv as dt,getOAuth2ClientId as et,Tt as f,staticWebsiteNameFromPlaceholder as ft,vt as g,createApplyLimiter as gt,resolveResolverDefaultPermissionForFile as h,byName as ht,hasImplicitAllEmailDomains as i,initOAuth2Client as it,G as j,stringifyFunction as k,getApplicationAuthNamespace as l,rememberPlatformConfigForToken as lt,toPlatformExecutionPolicyKey as m,withErrorDiagnostics as mt,generatePluginFilesIfNeeded as n,getPlatformBaseUrl as nt,resolveInlineSourcemap as o,isDefaultPlatform as ot,St as p,getErrorDiagnostics as pt,fetchAll as q,loadApplication as r,hasStaticWebsiteUrlPlaceholder as rt,getDistDir as s,isNotFoundError as st,defineApplication as t,getOrNull as tt,requireApplicationAuthNamespace as u,resolveStaticWebsiteUrls as ut,q as v,isForbiddenGlobal as vt,assertUniqueLocalTailorDBTypeNames as w,buildResolverResultSerialization as x,buildExecutorArgsExpr as y,resolveBundleLogLevel as z};
200
- //# sourceMappingURL=application-CfqvzV3I.mjs.map
199
+ `))}async function loadApplication(e){let{config:t,pluginManager:n,bundleCache:r,client:i,workspaceId:a,expectedLocalStaticWebsiteNames:o,previous:s}=e,l=N.dirname(t.path);if(s)return reloadEnvDependentBundles({config:t,baseDir:l,client:i,workspaceId:a,expectedLocalStaticWebsiteNames:o,bundleCache:r,previous:s});let{tailordbResult:u,resolverResult:d,idpResult:f,authResult:p,staticWebsiteServices:m,aiGatewayServices:h,secrets:g,ignoreNullishValues:_}=defineServices(t,l,n),v=i&&a?await resolveStaticWebsiteUrlsInEnv(i,a,t.env??{},{expectedLocalNames:o??new Set(m.map(e=>e.name))}):t.env??{};for(let e of u.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();assertUniqueLocalTailorDBTypeNames({tailorDBServices:u.tailorDBServices});let y=generatePluginFilesIfNeeded(n,u.tailorDBServices,t.path),b=defineExecutor(t.executor,l,y.length>0),x=defineWorkflow(t.workflow,l);x&&await x.loadWorkflows();let S=defineHttpAdapterService(t.httpAdapter,l);S&&await S.loadAdapters();let C=createTsconfigLookupCache(),w=await buildStartContext(t.workflow,getApplicationAuthNamespace({authService:p.authService,config:t}),l,x?.workflowSources,C),T=buildOptionsOf(t),E=resolveInlineSourcemap(T.inlineSourcemap),D=resolveBundleLogLevel(T.logLevel),O={resolvers:/* @__PURE__ */ new Map,executors:/* @__PURE__ */ new Map,workflowJobs:/* @__PURE__ */ new Map,authHooks:/* @__PURE__ */ new Map};for(let e of d.resolverServices){let t=await bundleResolvers({namespace:e.namespace,config:e.config,baseDir:l,defaultPermission:e.defaultPermission,startContext:w,cache:r,inlineSourcemap:E,bundleLogLevel:D,tsconfigCache:C,allowedRuntimeGlobals:T.allowedRuntimeGlobals});for(let[n,r]of t)O.resolvers.set(resolverBundleKey(e.namespace,n),r)}b&&(O.executors=await bundleExecutors({config:b.config,startContext:w,additionalFiles:[...y],cache:r,inlineSourcemap:E,bundleLogLevel:D,baseDir:l,tsconfigCache:C,allowedRuntimeGlobals:T.allowedRuntimeGlobals}));let k;if(x&&x.jobs.length>0){let e=x.workflowSources.map(e=>e.workflow.mainJob.name);k=await bundleWorkflowJobs(x.jobs,e,v,w,l,r,E,D,C,void 0,T.allowedRuntimeGlobals),O.workflowJobs=k.bundledCode}let A;if(S&&S.adapters.length>0&&(A=await bundleHttpAdapters(S.adapters.map(e=>({name:e.adapter.name,sourceFile:e.sourceFile,methods:e.methods,hasOutput:e.hasOutput})),l,r,D,C)),p.authService?.config.hooks?.beforeLogin){let e=p.authService.config.name;O.authHooks=await bundleAuthHooks({configPath:t.path,authName:e,handlerAccessPath:`auth.hooks.beforeLogin.handler`,env:v,startContext:w,cache:r,inlineSourcemap:E,bundleLogLevel:D,baseDir:l,tsconfigCache:C})}for(let e of d.resolverServices)await e.loadResolvers();return b&&(await b.loadExecutors(),y.length>0&&await b.loadPluginExecutorFiles([...y])),assertWaitPointKeys(),x&&x.printLoadedWorkflows(),S&&S.printLoadedAdapters(),c.newline(),{application:buildApplication({config:t,tailordbResult:u,resolverResult:d,idpResult:f,authResult:p,executorService:b,workflowService:x,httpAdapterService:S,staticWebsiteServices:m,aiGatewayServices:h,secrets:g,ignoreNullishValues:_,env:v}),workflowBuildResult:k,httpAdapterBuildResult:A,bundledScripts:O,reusableBuildState:{startContext:w,tsconfigCache:C,inlineSourcemap:E,bundleLogLevel:D}}}async function reloadEnvDependentBundles(e){let{config:t,baseDir:n,client:r,workspaceId:i,expectedLocalStaticWebsiteNames:a,bundleCache:o,previous:s}=e,{application:c,reusableBuildState:l}=s,{startContext:u,tsconfigCache:d,inlineSourcemap:f,bundleLogLevel:p}=l,m=r&&i?await resolveStaticWebsiteUrlsInEnv(r,i,t.env??{},{expectedLocalNames:a??new Set(c.staticWebsiteServices.map(e=>e.name))}):t.env??{},h={...s.bundledScripts},g=c.workflowService,_=s.workflowBuildResult;if(g&&g.jobs.length>0){let e=g.workflowSources.map(e=>e.workflow.mainJob.name);_=await bundleWorkflowJobs(g.jobs,e,m,u,n,o,f,p,d,s.workflowBuildResult,buildOptionsOf(t).allowedRuntimeGlobals),h.workflowJobs=_.bundledCode}if(c.authService?.config.hooks?.beforeLogin){let e=c.authService.config.name;h.authHooks=await bundleAuthHooks({configPath:t.path,authName:e,handlerAccessPath:`auth.hooks.beforeLogin.handler`,env:m,startContext:u,cache:o,inlineSourcemap:f,bundleLogLevel:p,baseDir:n,tsconfigCache:d})}let v={...c,env:m,get applications(){return[v]}};return{application:v,workflowBuildResult:_,httpAdapterBuildResult:s.httpAdapterBuildResult,bundledScripts:h,reusableBuildState:l}}export{getConsoleBaseUrl as $,$e as A,createBundleLog as B,resolverDateRepresentations as C,createPermissionNormalizer as D,findUndefinedReferences as E,createPlatformBundleDefinePlugin as F,closeConnectionPool as G,createBundleCache as H,W as I,fetchAllTolerant as J,Se as K,composeFunctionTreeshakeOptions as L,assertParsableExpression as M,createGeneratedEntryResolverPlugin as N,hasOmittedPermit as O,resolveTSConfigWithFallback as P,fetchUserInfo as Q,createLogLevelTreeshakeOptions as R,buildResolverValidatedInputExpr as S,assertUniqueTailorDBTypeNamesWithExternal as T,hashContent as U,createTsconfigPathsPlugin as V,hashFile as W,fetchPaged as X,fetchMachineUserToken as Y,fetchPlatformMachineUserToken as Z,Y as _,getErrorDiagnostics as _t,resolverBundleKey as a,initOperatorClient as at,buildResolverOperationHookExpr as b,buildOptionsOf as c,normalizeBaseUrl as ct,jt as d,resolveStaticWebsiteUrlsInEnv as dt,getOAuth2ClientId as et,Tt as f,staticWebsiteNameFromPlaceholder as ft,vt as g,isForbiddenGlobal as gt,resolveResolverDefaultPermissionForFile as h,be as ht,hasImplicitAllEmailDomains as i,initOAuth2Client as it,G as j,stringifyFunction as k,getApplicationAuthNamespace as l,rememberPlatformConfigForToken as lt,toPlatformExecutionPolicyKey as m,createApplyLimiter as mt,generatePluginFilesIfNeeded as n,getPlatformBaseUrl as nt,resolveInlineSourcemap as o,isDefaultPlatform as ot,St as p,byName as pt,fetchAll as q,loadApplication as r,hasStaticWebsiteUrlPlaceholder as rt,getDistDir as s,isNotFoundError as st,defineApplication as t,getOrNull as tt,requireApplicationAuthNamespace as u,resolveStaticWebsiteUrls as ut,q as v,withErrorDiagnostics as vt,assertUniqueLocalTailorDBTypeNames as w,buildResolverResultSerialization as x,buildExecutorArgsExpr as y,resolveBundleLogLevel as z};
200
+ //# sourceMappingURL=application-DS0XKBtK.mjs.map