@tailor-platform/sdk 2.22.0 → 2.23.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 (88) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/aigateway-DsWDjzk4.mjs.map +1 -1
  3. package/dist/application-BtZ8hmx9.mjs +1 -0
  4. package/dist/{application-BzO9ywXQ.mjs → application-m2G91kKI.mjs} +2 -2
  5. package/dist/application-m2G91kKI.mjs.map +1 -0
  6. package/dist/assert-WeXvmG4j.mjs.map +1 -1
  7. package/dist/authconnection-CynFBIv8.mjs.map +1 -1
  8. package/dist/brand-C8nMKhJC.mjs.map +1 -1
  9. package/dist/cli/lib.mjs +1 -1
  10. package/dist/cli/lib.mjs.map +1 -1
  11. package/dist/cli/main.mjs +33 -33
  12. package/dist/cli/main.mjs.map +1 -1
  13. package/dist/cli/shared/client.d.mts +17 -2
  14. package/dist/completion/zsh-worker.zsh +13 -7
  15. package/dist/configure/index.mjs.map +1 -1
  16. package/dist/context-D0QjfxzD.mjs.map +1 -1
  17. package/dist/crashreport-DFpRn-LS.mjs.map +1 -1
  18. package/dist/date-Dri6Yas-.mjs.map +1 -1
  19. package/dist/errors-CpvSChyL.mjs +7 -0
  20. package/dist/errors-CpvSChyL.mjs.map +1 -0
  21. package/dist/es-builtins-SfvXRVoG.mjs.map +1 -1
  22. package/dist/field-parse-DhnFs9WG.mjs.map +1 -1
  23. package/dist/file-DKBOj5q4.mjs.map +1 -1
  24. package/dist/globals-BCmGX05J.mjs.map +1 -1
  25. package/dist/guards-yDXyKC9F.mjs.map +1 -1
  26. package/dist/iconv-DlFMt2gW.mjs.map +1 -1
  27. package/dist/idp-G_ojPBB5.mjs.map +1 -1
  28. package/dist/interceptor-DQg3cR_9.mjs.map +1 -1
  29. package/dist/kysely/index.mjs.map +1 -1
  30. package/dist/kysely-type-C-iyFFH7.mjs.map +1 -1
  31. package/dist/logger-DP2BjQ93.mjs.map +1 -1
  32. package/dist/logger-Db-YRTwK.mjs.map +1 -1
  33. package/dist/manager-8-JOvuLl.mjs.map +1 -1
  34. package/dist/multiline-EyzjEwn9.mjs.map +1 -1
  35. package/dist/node-builtins-DYfhPBnz.mjs.map +1 -1
  36. package/dist/package-json-C690ceex.mjs.map +1 -1
  37. package/dist/platform-serialize-DkiTdHOt.mjs.map +1 -1
  38. package/dist/plugin/builtin/enum-constants/index.mjs.map +1 -1
  39. package/dist/plugin/builtin/file-utils/index.mjs.map +1 -1
  40. package/dist/plugin/index.mjs.map +1 -1
  41. package/dist/{register-ts-hook-z7ggXQy4.mjs → register-ts-hook-ztnEFW6n.mjs} +49 -49
  42. package/dist/register-ts-hook-ztnEFW6n.mjs.map +1 -0
  43. package/dist/registry-BijIDRVA.mjs.map +1 -1
  44. package/dist/repl-editor-DGJBfIt1.mjs.map +1 -1
  45. package/dist/schema-CRtAmDcl.mjs.map +1 -1
  46. package/dist/secret-file-C9wp_FCX.mjs.map +1 -1
  47. package/dist/secretmanager-5olfnI1b.mjs.map +1 -1
  48. package/dist/secretmanager-vHQoXdQz.mjs.map +1 -1
  49. package/dist/seed/index.mjs.map +1 -1
  50. package/dist/seed-C3P_T_Eh.mjs.map +1 -1
  51. package/dist/service-CL1Bp4It.mjs.map +1 -1
  52. package/dist/{service-DHVuH7-X.mjs → service-DFmt9UJP.mjs} +2 -2
  53. package/dist/service-DFmt9UJP.mjs.map +1 -0
  54. package/dist/service_pb-ZClWtj1X.mjs +2 -0
  55. package/dist/service_pb-ZClWtj1X.mjs.map +1 -0
  56. package/dist/service_pb-dB3RrGeh.mjs +1 -0
  57. package/dist/tailor-proto/src/tailor/v1/function_pb.d.mts +83 -1
  58. package/dist/tailor-proto/src/tailor/v1/function_resource_pb.d.mts +7 -1
  59. package/dist/tailor-proto/src/tailor/v1/service_pb.d.mts +79 -7
  60. package/dist/tailor-proto/src/tailor/v1/workflow_pb.d.mts +40 -1
  61. package/dist/tailor-proto/src/tailor/v1/workflow_resource_pb.d.mts +119 -2
  62. package/dist/tailor-proto/src/tailor/v1/workspace_pb.d.mts +7 -0
  63. package/dist/tailordb-ddl-DqInYupv.mjs.map +1 -1
  64. package/dist/telemetry-Bklv9kQY.mjs.map +1 -1
  65. package/dist/type-source--ZNcV8RJ.mjs.map +1 -1
  66. package/dist/user-agent-vdHYF3QL.mjs.map +1 -1
  67. package/dist/utils/test/index.mjs.map +1 -1
  68. package/dist/vitest/environment.mjs.map +1 -1
  69. package/dist/vitest/index.mjs.map +1 -1
  70. package/dist/vitest/setup.mjs.map +1 -1
  71. package/dist/wait-point-invoker-eiP-IIux.mjs.map +1 -1
  72. package/dist/wait-point-registry-B-ESkTZX.mjs.map +1 -1
  73. package/dist/workflow-Cs9ISw6j.mjs.map +1 -1
  74. package/dist/{workspace_resource_pb-D2njwgsE.mjs → workspace_resource_pb-CxR_6fyN.mjs} +2 -2
  75. package/dist/workspace_resource_pb-CxR_6fyN.mjs.map +1 -0
  76. package/docs/cli/application.md +23 -5
  77. package/docs/cli/function.md +2 -2
  78. package/package.json +3 -3
  79. package/dist/application-BE4vehXW.mjs +0 -1
  80. package/dist/application-BzO9ywXQ.mjs.map +0 -1
  81. package/dist/errors-C9zGf4nz.mjs +0 -7
  82. package/dist/errors-C9zGf4nz.mjs.map +0 -1
  83. package/dist/register-ts-hook-z7ggXQy4.mjs.map +0 -1
  84. package/dist/service-DHVuH7-X.mjs.map +0 -1
  85. package/dist/service_pb-DNskuJQC.mjs +0 -1
  86. package/dist/service_pb-y2GYIgfs.mjs +0 -2
  87. package/dist/service_pb-y2GYIgfs.mjs.map +0 -1
  88. package/dist/workspace_resource_pb-D2njwgsE.mjs.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # @tailor-platform/sdk
2
2
 
3
+ ## 2.23.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#2440](https://github.com/tailor-platform/sdk/pull/2440) [`e2df6cf`](https://github.com/tailor-platform/sdk/commit/e2df6cfa8acd4acf1cbd46418855aa93127b70d3) Thanks [@dqn](https://github.com/dqn)! - `tailor deploy` now marks updates that show no configuration difference and are applied again only because the application's resources were last deployed with a different SDK version. The plan lists them with `[forced by SDK version]` and the summary counts them (`12 to update (11 forced by SDK version)`), so after an SDK upgrade you can tell them apart from real configuration changes. With `--json`, such changes carry `forcedBySdkVersion: true` and `summary.forcedBySdkVersion` counts them.
8
+
9
+ ### Patch Changes
10
+
11
+ - [#2442](https://github.com/tailor-platform/sdk/pull/2442) [`4a974b1`](https://github.com/tailor-platform/sdk/commit/4a974b1a16a5e2b9ff9e1e130962053b055a96af) Thanks [@dqn](https://github.com/dqn)! - Fix the `tailor deploy` plan leaving out workflow execution policies: their changes are now listed in the Workflow section, and unmanaged or conflicting execution policies and applications now appear in the plan's warnings and owner conflicts, including `--json` output.
12
+
13
+ - [#2462](https://github.com/tailor-platform/sdk/pull/2462) [`551179a`](https://github.com/tailor-platform/sdk/commit/551179ac9b0b44c3bfc46eca44b2507cad7c1511) Thanks [@k1LoW](https://github.com/k1LoW)! - Function execution logs are now read from the platform's structured log entries instead of the deprecated flat `logs` field. The `logs` string that `function run`, `function logs --json`, `workflow executions --logs`, `executor jobs --logs`, TailorDB migrations, and `executeScript()` return joins the messages of those entries with newlines, and `function logs` no longer falls back to the flat string when an execution has no structured entries.
14
+
15
+ - [#2448](https://github.com/tailor-platform/sdk/pull/2448) [`317ba1e`](https://github.com/tailor-platform/sdk/commit/317ba1eb287ad650ae59b16e000911da484edf47) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update dependency rolldown to v1.2.11
16
+
17
+ - [#2438](https://github.com/tailor-platform/sdk/pull/2438) [`feb8b23`](https://github.com/tailor-platform/sdk/commit/feb8b2365c202a732be2d552dcb4a5d841101e2d) Thanks [@dqn](https://github.com/dqn)! - On Windows, a suggested follow-up command whose arguments cmd.exe and PowerShell read differently (for example a profile named `dev$1`, a config path containing `%`, or the webhook trigger's JSON body) is now shown as one command to copy into PowerShell and one to copy into cmd.exe, instead of an `argv [...]` array or a double-quoted line that PowerShell misreads. The `tailor profile update` suggestions shown for a read-only profile or a denied machine-user override now quote the profile name instead of pasting it into the command unquoted. On every platform, these suggested follow-up commands are now set off in backticks.
18
+
19
+ - [#2462](https://github.com/tailor-platform/sdk/pull/2462) [`0dcbed6`](https://github.com/tailor-platform/sdk/commit/0dcbed6f3c4f1847e8864febb1c43d0d00fdffae) Thanks [@k1LoW](https://github.com/k1LoW)! - Workflow commands now recognize canceled workflow executions. `workflow start --wait`, `workflow wait`, `workflow executions <id> --wait`, and `executor jobs --wait` over a workflow stop at a canceled execution and fail with `WORKFLOW_EXECUTION_CANCELED` instead of polling until they time out, a TailorDB migration whose workflow is canceled fails instead of waiting indefinitely, the status is shown as `CANCELED` rather than `UNSPECIFIED`, and `workflow executions --status CANCELED` is accepted.
20
+
3
21
  ## 2.22.0
4
22
 
5
23
  ### Minor Changes
@@ -1 +1 @@
1
- {"version":3,"file":"aigateway-DsWDjzk4.mjs","names":[],"sources":["../src/runtime/aigateway.ts"],"sourcesContent":["/**\n * AI Gateway utilities.\n *\n * Thin typed wrapper around the platform-provided `tailor.aigateway` runtime API.\n * At runtime this delegates to `globalThis.tailor.aigateway`. Use `mockAigateway`\n * from `@tailor-platform/sdk/vitest` to mock these calls in unit tests.\n *\n * `name` is narrowed to the AI Gateway names defined via `defineAIGateway()`\n * once `tailor.d.ts` has been generated (via `tailor deploy`/`generate`).\n * @example\n * import { aigateway } from \"@tailor-platform/sdk/runtime\";\n *\n * const { url } = await aigateway.get(\"my-aigateway\");\n */\n\n// Import from the public entry (not `#/configure/types/aigateway-name`) so this d.ts\n// references `@tailor-platform/sdk` externally instead of inlining the registry — the\n// same generated `declare module \"@tailor-platform/sdk\"` that narrows\n// `authconnection.getConnectionToken` then also narrows this entry.\nimport type { AIGatewayName } from \"@tailor-platform/sdk\";\n\n/** Result of {@link TailorAigatewayAPI.get}. */\nexport interface GetAIGatewayResult {\n /** The platform-assigned URL of the AI Gateway. */\n url: string;\n}\n\n/**\n * Platform API surface for `tailor.aigateway`. Describes the shape the\n * platform runtime injects on `globalThis.tailor.aigateway`.\n */\nexport interface TailorAigatewayAPI {\n /**\n * Resolves an AI Gateway defined in the caller's own workspace.\n * @param name - AI Gateway name, as passed to `defineAIGateway()`\n * @returns The resolved AI Gateway's platform-assigned URL\n */\n get(name: AIGatewayName): Promise<GetAIGatewayResult>;\n}\n\nconst api = (): TailorAigatewayAPI =>\n (globalThis as unknown as { tailor: { aigateway: TailorAigatewayAPI } }).tailor.aigateway;\n\nconst get: TailorAigatewayAPI[\"get\"] = (...args) => api().get(...args);\n\n/** Runtime wrapper namespace for `tailor.aigateway`. */\nexport const aigateway = { get } as const satisfies TailorAigatewayAPI;\n"],"mappings":"AAwCA,MAAM,QACH,WAAwE,OAAO,UAKrE,EAAY,CAAE,KAHa,GAAG,IAAS,IAAI,CAAC,CAAC,IAAI,GAAG,CAAI,CAGtC"}
1
+ {"version":3,"file":"aigateway-DsWDjzk4.mjs","names":["aigateway","args"],"sources":["../src/runtime/aigateway.ts"],"sourcesContent":["/**\n * AI Gateway utilities.\n *\n * Thin typed wrapper around the platform-provided `tailor.aigateway` runtime API.\n * At runtime this delegates to `globalThis.tailor.aigateway`. Use `mockAigateway`\n * from `@tailor-platform/sdk/vitest` to mock these calls in unit tests.\n *\n * `name` is narrowed to the AI Gateway names defined via `defineAIGateway()`\n * once `tailor.d.ts` has been generated (via `tailor deploy`/`generate`).\n * @example\n * import { aigateway } from \"@tailor-platform/sdk/runtime\";\n *\n * const { url } = await aigateway.get(\"my-aigateway\");\n */\n\n// Import from the public entry (not `#/configure/types/aigateway-name`) so this d.ts\n// references `@tailor-platform/sdk` externally instead of inlining the registry — the\n// same generated `declare module \"@tailor-platform/sdk\"` that narrows\n// `authconnection.getConnectionToken` then also narrows this entry.\nimport type { AIGatewayName } from \"@tailor-platform/sdk\";\n\n/** Result of {@link TailorAigatewayAPI.get}. */\nexport interface GetAIGatewayResult {\n /** The platform-assigned URL of the AI Gateway. */\n url: string;\n}\n\n/**\n * Platform API surface for `tailor.aigateway`. Describes the shape the\n * platform runtime injects on `globalThis.tailor.aigateway`.\n */\nexport interface TailorAigatewayAPI {\n /**\n * Resolves an AI Gateway defined in the caller's own workspace.\n * @param name - AI Gateway name, as passed to `defineAIGateway()`\n * @returns The resolved AI Gateway's platform-assigned URL\n */\n get(name: AIGatewayName): Promise<GetAIGatewayResult>;\n}\n\nconst api = (): TailorAigatewayAPI =>\n (globalThis as unknown as { tailor: { aigateway: TailorAigatewayAPI } }).tailor.aigateway;\n\nconst get: TailorAigatewayAPI[\"get\"] = (...args) => api().get(...args);\n\n/** Runtime wrapper namespace for `tailor.aigateway`. */\nexport const aigateway = { get } as const satisfies TailorAigatewayAPI;\n"],"mappings":"AAwCA,MAAM,QACH,WAAwE,OAAO,UAKrEA,EAAY,CAAE,KAHa,GAAGC,IAAS,IAAI,CAAC,CAAC,IAAI,GAAGA,CAAI,CAGtC"}
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./application-m2G91kKI.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{a as u,b as d,c as f,d as p,f as m,g as h,h as g,l as _,m as v,n as y,o as b,p as x,s as S,t as C,u as w,x as T}from"./service-CL1Bp4It.mjs";import{t as E}from"./multiline-EyzjEwn9.mjs";import{a as D,t as O}from"./errors-C9zGf4nz.mjs";import{t as k}from"./user-agent-vdHYF3QL.mjs";import{i as ee,n as te}from"./guards-yDXyKC9F.mjs";import{n as ne,t as re}from"./es-builtins-SfvXRVoG.mjs";import{n as ie,r as ae,t as oe}from"./node-builtins-DYfhPBnz.mjs";import{t as se}from"./type-source--ZNcV8RJ.mjs";import{createRequire as ce}from"node:module";import*as A from"pathe";import{resolve as le}from"pathe";import{resolveTSConfig as ue}from"pkg-types";import{z as j}from"zod";import{create as de}from"@bufbuild/protobuf";import*as M from"node:fs";import{readFileSync as fe}from"node:fs";import{MethodOptions_IdempotencyLevel as pe}from"@bufbuild/protobuf/wkt";import{OAuth2Client as me}from"@badgateway/oauth2-client";import{Code as N,ConnectError as P,createClient as he}from"@connectrpc/connect";import ge from"p-limit";import*as _e from"node:crypto";import{createHash as ve}from"node:crypto";import*as F from"rolldown";import{parseSync as I}from"oxc-parser";import{createPathsMatcher as ye,getTsconfig as be}from"get-tsconfig";import*as L from"inflection";import*as xe from"node:os";const Se=[`DEBUG`,`INFO`,`WARN`,`ERROR`,`SILENT`];function isLogLevel(e){return Se.includes(e)}const Ce=/^\d*[1-9]\d*$/;function parsePositiveInt(e){if(e===void 0)return;let t=e.trim();if(!Ce.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 ge(resolveApplyConcurrency())}function byName(e,t){return e.name<t.name?-1:+(e.name>t.name)}const we=/* @__PURE__ */ new WeakMap;function withErrorDiagnostics(e,t){return we.set(e,{...we.get(e),...t}),e}function getErrorDiagnostics(e){return{...e instanceof P?{suggestion:rpcSuggestion(e.code)}:{},...we.get(e)}}function rpcSuggestion(e){switch(e){case N.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 N.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 N.Unavailable:case N.DeadlineExceeded:return`Check network connectivity and platform availability. A write may already have completed; inspect the current resource state before retrying.`;default:return}}const Te=`https://api.tailor.tech`,Ee=`/.well-known/oauth-authorization-server/oauth2/platform`,R=/* @__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?R.set(e,n):R.delete(e)}function getPlatformConfigForToken(e){return R.get(e)}function getPlatformBaseUrl(e={}){return normalizeBaseUrl(e.platformUrl??getEnvPlatformUrl()??`https://api.tailor.tech`)}function isDefaultPlatform(e){return getPlatformBaseUrl(e)===normalizeBaseUrl(Te)}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 me({clientId:getOAuth2ClientId(e),server:getPlatformBaseUrl(e),discoveryEndpoint:Ee})}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-DNskuJQC.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 he(i,s)}async function createTransport(e,t){let{createConnectTransport:n}=await import(`@connectrpc/connect-node`);return n({httpVersion:`2`,baseUrl:e,interceptors:t})}const De=/* @__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(P.from(e?.reason,N.Canceled))}function onTimeout(){cleanup(),l(new P(`the operation timed out`,N.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(!De.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 P.from(n.reason,N.Canceled);let e=c===void 0?i:Math.ceil(c-performance.now());if(c!==void 0&&e!==void 0&&e<=0)throw new P(`the operation timed out`,N.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 k();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<ke;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 P?N[e.code]:isTransportDisconnectError(e)?e.code:`unknown`}const Oe=/* @__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 P&&e.code===N.AlreadyExists&&Oe.has(t)}function synthesizeEmptyUnaryResponse(e){return{stream:!1,service:e.service,method:e.method,header:new Headers,message:de(e.method.output),trailer:new Headers}}const ke=3;function waitRetryBackoff(e){let t=500*2**(e-1)*(1+.1*(Math.random()*2-1));return new Promise(e=>setTimeout(e,t))}const Ae=/* @__PURE__ */ new Set([`ERR_STREAM_PREMATURE_CLOSE`,`ECONNRESET`,`ETIMEDOUT`,`EPIPE`]);function isTransportDisconnectError(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&Ae.has(e.code)}function isRetirable(e,t){let n=t===pe.NO_SIDE_EFFECTS||t===pe.IDEMPOTENT;if(!(e instanceof P))return isTransportDisconnectError(e)&&n;switch(e.code){case N.ResourceExhausted:case N.Unavailable:return!0;case N.Aborted:case N.Internal:return n;default:return!1}}function errorHandlingInterceptor(){return e=>async t=>{try{return await e(t)}catch(e){if(e instanceof P){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 P(`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 je=/* @__PURE__ */ new Set([`name`,`id`]),Me=[`Name`,`Id`,`Namespace`],Ne=`name`,Pe={GetMetadata:[`trn`],SetMetadata:[`trn`],AddCustomDomain:[`domain`],GetCustomDomain:[`domain`],RemoveCustomDomain:[`domain`],CreateWorkflowJobFunctionExecutionPolicy:[`executionPolicyKey`],UpdateWorkflowJobFunctionExecutionPolicy:[`executionPolicyKey`],GetWorkflowJobFunctionExecutionPolicyByKey:[`executionPolicyKey`]};function isIdentityKey(e,t){return e.startsWith(`$`)?!1:je.has(e)||Me.some(t=>e.endsWith(t))||(Pe[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[Ne];typeof e==`string`&&e!==``&&(n[`${r}.${Ne}`]=e)}return n}const z=1e3;async function fetchAll(e){let t=[],n=``;for(;;){let[r,i]=await e(n,z);if(t.push(...r),!i)break;n=i}return t}function isNotFoundError(e){return e instanceof P&&e.code===N.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?z:Math.min(n-i.length,z);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 k()}});if(!r.ok)throw Error(`Failed to fetch user info: ${r.statusText}`);let i=await r.json();return j.object({sub:j.string(),email:j.string()}).parse(i)}const B=/:url(\/.*)?$/;function hasStaticWebsiteUrlPlaceholder(e){return typeof e==`string`&&B.test(e)}function staticWebsiteNameFromPlaceholder(e){let t=e.match(B);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(B);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 O({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(B));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 k(),"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=j.object({token_type:j.string(),access_token:j.string(),expires_in:j.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 me({clientId:e,clientSecret:t,server:r,discoveryEndpoint:Ee}).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?[A.dirname(e)]:[process.cwd()]}function resolveRelativePluginImportPath(e,t){if(!e.startsWith(`.`))return null;for(let n of t){let t=A.resolve(n,e);if(M.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=A.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=A.join(t,a,`executors`);M.mkdirSync(o,{recursive:!0});let s=sanitizeExecutorFileName(e.executor.name),c=A.join(o,`${s}.ts`),l;return l=ee(e.executor)?generateExecutorFileContentNew(e,e.executor,t,n,r,i):generateExecutorFileContentLegacy(e.executor),M.writeFileSync(c,l),c}function generateExecutorFileContentNew(e,t,n,r,i,a=[]){let{resolve:o,context:s}=t,c=sanitizePluginId$1(e.pluginId),l=A.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 E`
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{a as u,b as d,c as f,d as p,f as m,g as h,h as g,l as _,m as v,n as y,o as b,p as x,s as S,t as C,u as w,x as T}from"./service-CL1Bp4It.mjs";import{t as E}from"./multiline-EyzjEwn9.mjs";import{i as D,t as O}from"./errors-CpvSChyL.mjs";import{t as k}from"./user-agent-vdHYF3QL.mjs";import{i as ee,n as te}from"./guards-yDXyKC9F.mjs";import{n as ne,t as re}from"./es-builtins-SfvXRVoG.mjs";import{n as ie,r as ae,t as oe}from"./node-builtins-DYfhPBnz.mjs";import{t as se}from"./type-source--ZNcV8RJ.mjs";import{createRequire as ce}from"node:module";import*as A from"pathe";import{resolve as le}from"pathe";import{resolveTSConfig as ue}from"pkg-types";import{z as j}from"zod";import{create as de}from"@bufbuild/protobuf";import*as M from"node:fs";import{readFileSync as fe}from"node:fs";import{MethodOptions_IdempotencyLevel as pe}from"@bufbuild/protobuf/wkt";import{OAuth2Client as me}from"@badgateway/oauth2-client";import{Code as N,ConnectError as P,createClient as he}from"@connectrpc/connect";import ge from"p-limit";import*as _e from"node:crypto";import{createHash as ve}from"node:crypto";import*as F from"rolldown";import{parseSync as I}from"oxc-parser";import{createPathsMatcher as ye,getTsconfig as be}from"get-tsconfig";import*as L from"inflection";import*as xe from"node:os";const Se=[`DEBUG`,`INFO`,`WARN`,`ERROR`,`SILENT`];function isLogLevel(e){return Se.includes(e)}const Ce=/^\d*[1-9]\d*$/;function parsePositiveInt(e){if(e===void 0)return;let t=e.trim();if(!Ce.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 ge(resolveApplyConcurrency())}function byName(e,t){return e.name<t.name?-1:+(e.name>t.name)}const we=/* @__PURE__ */ new WeakMap;function withErrorDiagnostics(e,t){return we.set(e,{...we.get(e),...t}),e}function getErrorDiagnostics(e){return{...e instanceof P?{suggestion:rpcSuggestion(e.code)}:{},...we.get(e)}}function rpcSuggestion(e){switch(e){case N.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 N.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 N.Unavailable:case N.DeadlineExceeded:return`Check network connectivity and platform availability. A write may already have completed; inspect the current resource state before retrying.`;default:return}}const Te=`https://api.tailor.tech`,Ee=`/.well-known/oauth-authorization-server/oauth2/platform`,R=/* @__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?R.set(e,n):R.delete(e)}function getPlatformConfigForToken(e){return R.get(e)}function getPlatformBaseUrl(e={}){return normalizeBaseUrl(e.platformUrl??getEnvPlatformUrl()??`https://api.tailor.tech`)}function isDefaultPlatform(e){return getPlatformBaseUrl(e)===normalizeBaseUrl(Te)}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 me({clientId:getOAuth2ClientId(e),server:getPlatformBaseUrl(e),discoveryEndpoint:Ee})}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 he(i,s)}async function createTransport(e,t){let{createConnectTransport:n}=await import(`@connectrpc/connect-node`);return n({httpVersion:`2`,baseUrl:e,interceptors:t})}const De=/* @__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(P.from(e?.reason,N.Canceled))}function onTimeout(){cleanup(),l(new P(`the operation timed out`,N.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(!De.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 P.from(n.reason,N.Canceled);let e=c===void 0?i:Math.ceil(c-performance.now());if(c!==void 0&&e!==void 0&&e<=0)throw new P(`the operation timed out`,N.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 k();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<ke;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 P?N[e.code]:isTransportDisconnectError(e)?e.code:`unknown`}const Oe=/* @__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 P&&e.code===N.AlreadyExists&&Oe.has(t)}function synthesizeEmptyUnaryResponse(e){return{stream:!1,service:e.service,method:e.method,header:new Headers,message:de(e.method.output),trailer:new Headers}}const ke=3;function waitRetryBackoff(e){let t=500*2**(e-1)*(1+.1*(Math.random()*2-1));return new Promise(e=>setTimeout(e,t))}const Ae=/* @__PURE__ */ new Set([`ERR_STREAM_PREMATURE_CLOSE`,`ECONNRESET`,`ETIMEDOUT`,`EPIPE`]);function isTransportDisconnectError(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&Ae.has(e.code)}function isRetirable(e,t){let n=t===pe.NO_SIDE_EFFECTS||t===pe.IDEMPOTENT;if(!(e instanceof P))return isTransportDisconnectError(e)&&n;switch(e.code){case N.ResourceExhausted:case N.Unavailable:return!0;case N.Aborted:case N.Internal:return n;default:return!1}}function errorHandlingInterceptor(){return e=>async t=>{try{return await e(t)}catch(e){if(e instanceof P){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 P(`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 je=/* @__PURE__ */ new Set([`name`,`id`]),Me=[`Name`,`Id`,`Namespace`],Ne=`name`,Pe={GetMetadata:[`trn`],SetMetadata:[`trn`],AddCustomDomain:[`domain`],GetCustomDomain:[`domain`],RemoveCustomDomain:[`domain`],CreateWorkflowJobFunctionExecutionPolicy:[`executionPolicyKey`],UpdateWorkflowJobFunctionExecutionPolicy:[`executionPolicyKey`],GetWorkflowJobFunctionExecutionPolicyByKey:[`executionPolicyKey`]};function isIdentityKey(e,t){return e.startsWith(`$`)?!1:je.has(e)||Me.some(t=>e.endsWith(t))||(Pe[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[Ne];typeof e==`string`&&e!==``&&(n[`${r}.${Ne}`]=e)}return n}const z=1e3;async function fetchAll(e){let t=[],n=``;for(;;){let[r,i]=await e(n,z);if(t.push(...r),!i)break;n=i}return t}function isNotFoundError(e){return e instanceof P&&e.code===N.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?z:Math.min(n-i.length,z);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 k()}});if(!r.ok)throw Error(`Failed to fetch user info: ${r.statusText}`);let i=await r.json();return j.object({sub:j.string(),email:j.string()}).parse(i)}const B=/:url(\/.*)?$/;function hasStaticWebsiteUrlPlaceholder(e){return typeof e==`string`&&B.test(e)}function staticWebsiteNameFromPlaceholder(e){let t=e.match(B);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(B);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 O({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(B));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 k(),"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=j.object({token_type:j.string(),access_token:j.string(),expires_in:j.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 me({clientId:e,clientSecret:t,server:r,discoveryEndpoint:Ee}).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?[A.dirname(e)]:[process.cwd()]}function resolveRelativePluginImportPath(e,t){if(!e.startsWith(`.`))return null;for(let n of t){let t=A.resolve(n,e);if(M.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=A.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=A.join(t,a,`executors`);M.mkdirSync(o,{recursive:!0});let s=sanitizeExecutorFileName(e.executor.name),c=A.join(o,`${s}.ts`),l;return l=ee(e.executor)?generateExecutorFileContentNew(e,e.executor,t,n,r,i):generateExecutorFileContentLegacy(e.executor),M.writeFileSync(c,l),c}function generateExecutorFileContentNew(e,t,n,r,i,a=[]){let{resolve:o,context:s}=t,c=sanitizePluginId$1(e.pluginId),l=A.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 E`
2
2
  /**
3
3
  * Auto-generated executor by plugin: ${e.pluginId}
4
4
  * DO NOT EDIT - This file is generated by @tailor-platform/sdk
@@ -196,4 +196,4 @@ globalThis.transform = __adapter.output;
196
196
  `,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}),G,...a],g=createBundleLog({tsconfig:n}),_=await F.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[0].code;return assertNoForbiddenRuntimeGlobals(v,`Workflow job "${e.name}"`),v}});return[e.name,f]}const vt=/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/,yt=/^[a-z0-9][a-z0-9_:.-]{0,62}[a-z0-9*]$/,bt=`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 xt=[`ms`,`s`,`m`],St={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)*St[t[2]]}const X={maxRetries:{min:1,max:10},initialBackoffMaxSeconds:3600,maxBackoffMaxSeconds:86400,backoffMultiplierMin:1},Ct=j.strictObject({name:j.string().describe(`Job name (must be unique across the project)`),start:T.describe(`Start function that initiates the job`),body:T.describe(`Job implementation function`),publishEvents:j.boolean().optional().describe(`Enable publishing job execution events for this job`)}),seconds=e=>durationToSeconds(e)??0,wt=j.templateLiteral([j.number().int().positive(),j.enum(xt)]),durationSchema=e=>wt.refine(t=>seconds(t)<=e,{message:`Duration must be at most ${e} seconds`}),Tt=j.strictObject({maxRetries:j.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:j.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`]}),Et=j.strictObject({maxConcurrentExecutions:j.number().int().min(1).max(1e3).describe(`Maximum number of concurrent executions (1-1000)`)}),Dt=j.string().regex(vt,`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`),Ot=j.string().regex(yt,`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`),kt=j.strictObject({name:Dt,key:Ot,concurrencyPolicy:Et.optional().describe(`Optional per-key concurrency cap for job function dispatches matching this policy`)}),At=j.strictObject({name:j.string().describe(`Workflow name`),mainJob:Ct.describe(`Main job that starts the workflow`),retryPolicy:Tt.optional().describe(`Retry policy for the workflow`),concurrencyPolicy:Et.optional().describe(`Concurrency policy for the workflow`),publishEvents:j.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=A.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=h(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 d(e);for(let[a,o]of Object.entries(i)){if(a==="default"){let e=At.safeParse(stripRuntimeStart(o));if(e.success)r=e.data;else if(t(o,[`workflow`,`workflow-job`]))throw e.error;continue}let i=Ct.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=A.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}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 jt=j.strictObject({name:j.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:j.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:j.array(j.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.")}),Mt=/^(\*|[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 Nt=j.union([j.literal(`query`),j.strictObject({create:j.boolean().optional().describe(`Enable _createUser mutation (default: true)`),update:j.boolean().optional().describe(`Enable _updateUser mutation (default: true)`),delete:j.boolean().optional().describe(`Enable _deleteUser mutation (default: true)`),read:j.boolean().optional().describe(`Enable _users and _user queries (default: true)`),sendPasswordResetEmail:j.boolean().optional().describe(`Enable _sendPasswordResetEmail mutation (default: true)`),requestMfaSettingsUrl:j.boolean().optional().describe(`Enable _requestMfaSettingsUrl query (default: true)`),unenrollMfa:j.boolean().optional().describe(`Enable _unenrollMfa mutation (default: true)`)})]).describe(`Configuration for GraphQL operations on IdP users.
197
197
  All operations are enabled by default (undefined or true = enabled, false = disabled).`).transform(e=>normalizeIdPGqlOperations(e)),Pt=j.enum([`en`,`ja`]).describe(`IdP UI language`),Ft=j.strictObject({useNonEmailIdentifier:j.boolean().optional().describe(`Use non-email identifier for usernames`),allowSelfPasswordReset:j.boolean().optional().describe(`Allow users to reset their own passwords`),passwordRequireUppercase:j.boolean().optional().describe(`Require uppercase letters in passwords`),passwordRequireLowercase:j.boolean().optional().describe(`Require lowercase letters in passwords`),passwordRequireNonAlphanumeric:j.boolean().optional().describe(`Require non-alphanumeric characters in passwords`),passwordRequireNumeric:j.boolean().optional().describe(`Require numeric characters in passwords`),passwordMinLength:j.number().int().refine(e=>e>=6&&e<=30,{message:`passwordMinLength must be between 6 and 30`}).optional().describe(`Minimum password length (6-30)`),passwordMaxLength:j.number().int().refine(e=>e>=6&&e<=4096,{message:`passwordMaxLength must be between 6 and 4096`}).optional().describe(`Maximum password length (6-4096)`),allowedEmailDomains:j.array(j.string().regex(Mt,`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:j.boolean().optional().describe(`Enable Google OAuth login`),allowMicrosoftOauth:j.boolean().optional().describe(`Enable Microsoft OAuth login`),disablePasswordAuth:j.boolean().optional().describe(`Disable password-based authentication`),enableMfa:j.boolean().optional().describe(`Make TOTP MFA available for users in this namespace`),requireMfa:j.boolean().optional().describe(`Require TOTP MFA enrollment and challenge for password-authenticated users (requires enableMfa)`),allowedReturnOrigins:j.array(j.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:j.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`]}),It=j.string().max(200,`must be 200 characters or less`).regex(/^[^\r\n]*$/,`must not contain newline characters`),Lt=j.strictObject({fromName:It.optional().describe(`Default sender display name for emails`),passwordResetSubject:It.optional().describe(`Default subject for password reset emails`)}).describe(`Namespace-level email configuration defaults`),Q=j.union([j.string(),j.boolean(),j.array(j.string()).readonly(),j.array(j.boolean()).readonly(),j.strictObject({user:j.string()}),j.strictObject({idpUser:j.enum([`id`,`name`,`disabled`])}),j.strictObject({oldIdpUser:j.enum([`id`,`name`,`disabled`])}),j.strictObject({newIdpUser:j.enum([`id`,`name`,`disabled`])})]),Rt=j.enum([`=`,`!=`,`in`,`not in`]),zt=j.tuple([Q,Rt,Q]).readonly(),$=j.union([j.strictObject({conditions:j.union([zt,j.array(zt).readonly()]),description:j.string().optional(),permit:j.boolean().optional()}),j.tuple([Q,Rt,Q]).readonly(),j.tuple([Q,Rt,Q,j.boolean()]).readonly(),j.array(j.union([zt,j.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()]),Bt=j.strictObject({create:j.array($).readonly(),read:j.array($).readonly(),update:j.array($).readonly(),delete:j.array($).readonly(),sendPasswordResetEmail:j.array($).readonly().optional(),unenrollMfa:j.array($).readonly().optional()}).describe(`Per-operation permission policies for IdP users`),Vt=j.strictObject({name:j.string().describe(`IdP service name`),authorization:j.union([j.literal(`insecure`),j.literal(`loggedIn`),j.strictObject({cel:j.string()})]).optional().describe(`Authorization mode for IdP API access`),clients:j.array(j.string()).describe(`OAuth2 client names that can use this IdP`),lang:Pt.optional().describe(`UI language for IdP pages`),userAuthPolicy:Ft.transform(e=>Ft.parse(e??{})).optional().describe(`User authentication policy configuration`),publishEvents:j.boolean().optional().describe(`Enable publishing user lifecycle events`),gqlOperations:Nt.optional().describe(`Configure which GraphQL operations are enabled`),emailConfig:Lt.optional().describe(`Namespace-level email configuration defaults`),permission:Bt.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`]}),Ht=j.string().regex(/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/),Ut=j.record(Ht,j.string().nullish()),Wt=j.strictObject({vaults:j.record(Ht,Ut),options:j.strictObject({ignoreNullishValues:j.boolean()})}),Gt=j.strictObject({name:j.string().describe(`Static website name`),description:j.string().optional().describe(`Static website description`),allowedIpAddresses:j.array(j.string()).optional().describe(`IP addresses allowed to access the website`),customDomains:j.array(j.string()).optional().describe(`Custom domains for the static website`)}),Kt=/^[a-z0-9]+$/,qt=/^[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(!qt.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(!Kt.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:w.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=Vt.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(u.parse(e),t,n)),r.push({Type:`auth`,Name:e.name}),{authService:i,subgraphs:r}}function defineExecutor(e,t,n){if(e||n)return C({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=Gt.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=jt.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=Wt.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=A.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:A.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(`
198
198
  `))}async function loadApplication(e){let{config:t,pluginManager:n,bundleCache:r,client:i,workspaceId:a,expectedLocalStaticWebsiteNames:o,previous:s}=e,l=A.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=await buildStartContext(t.workflow,getApplicationAuthNamespace({authService:p.authService,config:t}),l),w=resolveInlineSourcemap(t.inlineSourcemap),T=resolveBundleLogLevel(t.logLevel),E=createTsconfigLookupCache(),D={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:C,cache:r,inlineSourcemap:w,bundleLogLevel:T,tsconfigCache:E});for(let[n,r]of t)D.resolvers.set(resolverBundleKey(e.namespace,n),r)}b&&(D.executors=await bundleExecutors({config:b.config,startContext:C,additionalFiles:[...y],cache:r,inlineSourcemap:w,bundleLogLevel:T,baseDir:l,tsconfigCache:E}));let O;if(x&&x.jobs.length>0){let e=x.workflowSources.map(e=>e.workflow.mainJob.name);O=await bundleWorkflowJobs(x.jobs,e,v,C,l,r,w,T,E),D.workflowJobs=O.bundledCode}let k;if(S&&S.adapters.length>0&&(k=await bundleHttpAdapters(S.adapters.map(e=>({name:e.adapter.name,sourceFile:e.sourceFile,methods:e.methods,hasOutput:e.hasOutput})),l,r,T,E)),p.authService?.config.hooks?.beforeLogin){let e=p.authService.config.name;D.authHooks=await bundleAuthHooks({configPath:t.path,authName:e,handlerAccessPath:`auth.hooks.beforeLogin.handler`,env:v,startContext:C,cache:r,inlineSourcemap:w,bundleLogLevel:T,baseDir:l,tsconfigCache:E})}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:O,httpAdapterBuildResult:k,bundledScripts:D,reusableBuildState:{startContext:C,tsconfigCache:E,inlineSourcemap:w,bundleLogLevel:T}}}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),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{getOAuth2ClientId as $,K as A,createBundleLog as B,assertUniqueLocalTailorDBTypeNames as C,hasOmittedPermit as D,createPermissionNormalizer as E,createPlatformBundleDefinePlugin as F,Te as G,hashContent as H,G as I,fetchMachineUserToken as J,fetchAll as K,composeFunctionTreeshakeOptions as L,createGeneratedEntryResolverPlugin as M,createTsconfigPathsPlugin as N,stringifyFunction as O,resolveTSConfigWithFallback as P,getConsoleBaseUrl as Q,createLogLevelTreeshakeOptions as R,resolverDateRepresentations as S,findUndefinedReferences as T,hashFile as U,createBundleCache as V,closeConnectionPool as W,fetchPlatformMachineUserToken as X,fetchPaged as Y,fetchUserInfo as Z,q as _,resolverBundleKey as a,isDefaultPlatform as at,buildResolverResultSerialization as b,getApplicationAuthNamespace as c,rememberPlatformConfigForToken as ct,Ct as d,staticWebsiteNameFromPlaceholder as dt,getOrNull as et,bt as f,getErrorDiagnostics as ft,Y as g,Se as gt,gt as h,createApplyLimiter as ht,hasImplicitAllEmailDomains as i,initOperatorClient as it,assertParsableExpression as j,Qe as k,requireApplicationAuthNamespace as l,resolveStaticWebsiteUrls as lt,resolveResolverDefaultPermissionForFile as m,byName as mt,generatePluginFilesIfNeeded as n,hasStaticWebsiteUrlPlaceholder as nt,resolveInlineSourcemap as o,isNotFoundError as ot,toPlatformExecutionPolicyKey as p,withErrorDiagnostics as pt,fetchAllTolerant as q,loadApplication as r,initOAuth2Client as rt,getDistDir as s,normalizeBaseUrl as st,defineApplication as t,getPlatformBaseUrl as tt,kt as u,resolveStaticWebsiteUrlsInEnv as ut,buildExecutorArgsExpr as v,assertUniqueTailorDBTypeNamesWithExternal as w,buildResolverValidatedInputExpr as x,buildResolverOperationHookExpr as y,resolveBundleLogLevel as z};
199
- //# sourceMappingURL=application-BzO9ywXQ.mjs.map
199
+ //# sourceMappingURL=application-m2G91kKI.mjs.map