@tailor-platform/sdk 2.27.0 → 2.29.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +109 -0
- package/README.md +0 -8
- package/agent-skills/tailor/SKILL.md +4 -2
- package/dist/application-dalGHdrI.mjs +1 -0
- package/dist/application-rWYDAfNU.mjs +200 -0
- package/dist/application-rWYDAfNU.mjs.map +1 -0
- package/dist/cli/cache/bundle-cache.d.mts +1 -0
- package/dist/cli/commands/executor/get.d.mts +2 -1
- package/dist/cli/commands/executor/jobs.d.mts +2 -1
- package/dist/cli/commands/executor/trigger.d.mts +2 -1
- package/dist/cli/commands/function/get.d.mts +2 -1
- package/dist/cli/commands/function/list.d.mts +2 -1
- package/dist/cli/commands/organization/folder/create.d.mts +2 -1
- package/dist/cli/commands/organization/folder/delete.d.mts +2 -1
- package/dist/cli/commands/organization/folder/get.d.mts +2 -1
- package/dist/cli/commands/organization/folder/list.d.mts +2 -1
- package/dist/cli/commands/organization/folder/update.d.mts +2 -1
- package/dist/cli/commands/organization/get.d.mts +2 -1
- package/dist/cli/commands/organization/tree.d.mts +2 -1
- package/dist/cli/commands/organization/update.d.mts +2 -1
- package/dist/cli/commands/show.d.mts +2 -1
- package/dist/cli/commands/tailordb/migrate/diff-calculator.d.mts +2 -1
- package/dist/cli/commands/tailordb/migrate/snapshot-types.d.mts +3 -1
- package/dist/cli/commands/workflow/executions.d.mts +2 -1
- package/dist/cli/commands/workflow/get.d.mts +2 -1
- package/dist/cli/commands/workflow/start.d.mts +2 -1
- package/dist/cli/commands/workspace/app/health.d.mts +2 -1
- package/dist/cli/commands/workspace/app/list.d.mts +2 -1
- package/dist/cli/commands/workspace/create.d.mts +5 -2
- package/dist/cli/commands/workspace/delete.d.mts +2 -1
- package/dist/cli/commands/workspace/get.d.mts +2 -1
- package/dist/cli/commands/workspace/restore.d.mts +2 -1
- package/dist/cli/commands/workspace/user/invite.d.mts +2 -1
- package/dist/cli/commands/workspace/user/list.d.mts +2 -1
- package/dist/cli/commands/workspace/user/remove.d.mts +2 -1
- package/dist/cli/commands/workspace/user/update.d.mts +2 -1
- package/dist/cli/lib.d.mts +1 -1
- package/dist/cli/lib.mjs +1 -1
- package/dist/cli/lib.mjs.map +1 -1
- package/dist/cli/main.d.mts +7 -0
- package/dist/cli/main.mjs +55 -42
- package/dist/cli/main.mjs.map +1 -1
- package/dist/cli/query/index.d.mts +2 -1
- package/dist/cli/shared/args.d.mts +4 -2
- package/dist/cli/shared/client.d.mts +6 -1
- package/dist/cli/shared/context.d.mts +2 -1
- package/dist/cli/shared/logger.d.mts +5 -2
- package/dist/cli/shared/readonly-guard.d.mts +2 -1
- package/dist/cli/shared/seed-context.d.mts +5 -0
- package/dist/cli/shared/type-generator.d.mts +2 -1
- package/dist/cli/ts-hook.mjs +15 -11
- package/dist/completion/zsh-worker.zsh +275 -19
- package/dist/configure/config/types.d.mts +80 -1
- package/dist/configure/services/aigateway/types.d.mts +2 -1
- package/dist/configure/services/auth/types.d.mts +2 -1
- package/dist/configure/services/executor/executor.d.mts +2 -1
- package/dist/configure/services/executor/operation.d.mts +2 -1
- package/dist/configure/services/executor/trigger/event.d.mts +2 -1
- package/dist/configure/services/executor/trigger/schedule.d.mts +2 -1
- package/dist/configure/services/http-adapter/http-adapter.d.mts +2 -1
- package/dist/configure/services/idp/permission.d.mts +2 -1
- package/dist/configure/services/idp/types.d.mts +2 -1
- package/dist/configure/services/resolver/permission.d.mts +2 -1
- package/dist/configure/services/resolver/resolver.d.mts +2 -1
- package/dist/configure/services/secrets/types.d.mts +2 -1
- package/dist/configure/services/staticwebsite/types.d.mts +2 -1
- package/dist/configure/services/tailordb/permission.d.mts +2 -1
- package/dist/configure/services/tailordb/schema.d.mts +4 -3
- package/dist/configure/services/tailordb/types.d.mts +12 -1
- package/dist/configure/services/workflow/execution-policy.types.d.mts +2 -1
- package/dist/configure/services/workflow/job.d.mts +2 -1
- package/dist/configure/services/workflow/wait-point.d.mts +2 -1
- package/dist/configure/types/field.types.d.mts +2 -1
- package/dist/configure/types/permission-operand.types.d.mts +2 -1
- package/dist/configure/types/type.d.mts +2 -1
- package/dist/{crashreport-DFpRn-LS.mjs → crashreport-BAG8c7hB.mjs} +4 -4
- package/dist/{crashreport-DFpRn-LS.mjs.map → crashreport-BAG8c7hB.mjs.map} +1 -1
- package/dist/crashreport-BcXuocwI.mjs +1 -0
- package/dist/{errors-CpvSChyL.mjs → errors-D3qpNHR6.mjs} +2 -2
- package/dist/{errors-CpvSChyL.mjs.map → errors-D3qpNHR6.mjs.map} +1 -1
- package/dist/kysely-type-BWMfV301.mjs +48 -0
- package/dist/kysely-type-BWMfV301.mjs.map +1 -0
- package/dist/logger-DuaT2zY3.mjs +9 -0
- package/dist/logger-DuaT2zY3.mjs.map +1 -0
- package/dist/package-json-D1BRkjtr.mjs +1 -0
- package/dist/parser/service/tailordb/types.d.mts +3 -1
- package/dist/plugin/builtin/enum-constants/index.d.mts +2 -1
- package/dist/plugin/builtin/file-utils/index.d.mts +2 -1
- package/dist/plugin/builtin/kysely-type/index.d.mts +2 -1
- package/dist/plugin/builtin/kysely-type/index.mjs +1 -1
- package/dist/plugin/builtin/seed/index.d.mts +11 -1
- package/dist/plugin/builtin/seed/index.mjs +1 -1
- package/dist/register-ts-hook-CkfKqhJT.mjs +1014 -0
- package/dist/register-ts-hook-CkfKqhJT.mjs.map +1 -0
- package/dist/runtime/aigateway.mjs +1 -1
- package/dist/runtime/authconnection.mjs +1 -1
- package/dist/runtime/context.d.mts +2 -1
- package/dist/runtime/context.mjs +1 -1
- package/dist/runtime/date.d.mts +2 -1
- package/dist/runtime/field-parse.d.mts +2 -1
- package/dist/runtime/file.d.mts +2 -1
- package/dist/runtime/file.mjs +1 -1
- package/dist/runtime/globals.d.mts +2 -1
- package/dist/runtime/iconv.mjs +1 -1
- package/dist/runtime/idp.mjs +1 -1
- package/dist/runtime/logger.mjs +1 -1
- package/dist/runtime/secretmanager.mjs +1 -1
- package/dist/runtime/types.d.mts +2 -1
- package/dist/runtime/workflow.d.mts +2 -1
- package/dist/runtime/workflow.mjs +1 -1
- package/dist/schema-B6hJQWp6.mjs.map +1 -1
- package/dist/seed/index.d.mts +17 -4
- package/dist/seed/index.mjs +6 -6
- package/dist/seed/index.mjs.map +1 -1
- package/dist/seed-C3P_T_Eh.mjs.map +1 -1
- package/dist/{service-Cc7OY0Oh.mjs → service-CETr0AKY.mjs} +3 -3
- package/dist/service-CETr0AKY.mjs.map +1 -0
- package/dist/service-DREWLYxD.mjs +1 -0
- package/dist/{service-DFmt9UJP.mjs → service-b1g22NN9.mjs} +2 -2
- package/dist/{service-DFmt9UJP.mjs.map → service-b1g22NN9.mjs.map} +1 -1
- package/dist/service_pb-Bbu2QSIr.mjs +2 -0
- package/dist/service_pb-Bbu2QSIr.mjs.map +1 -0
- package/dist/service_pb-urxAIYHT.mjs +1 -0
- package/dist/tailor-proto/src/tailor/v1/events_pb.d.mts +53 -1
- package/dist/tailor-proto/src/tailor/v1/events_resource_pb.d.mts +33 -0
- package/dist/tailor-proto/src/tailor/v1/function_resource_pb.d.mts +0 -8
- package/dist/tailor-proto/src/tailor/v1/service_pb.d.mts +18 -1
- package/dist/tailor-proto/src/tailor/v1/tailordb_resource_pb.d.mts +4 -0
- package/dist/telemetry-DpkFGBmu.mjs +1 -0
- package/dist/{telemetry-Bklv9kQY.mjs → telemetry-Xk7J829P.mjs} +2 -2
- package/dist/{telemetry-Bklv9kQY.mjs.map → telemetry-Xk7J829P.mjs.map} +1 -1
- package/dist/types/tailordb.generated.d.mts +2 -0
- package/dist/vitest/index.mjs +1 -1
- package/dist/vitest/index.mjs.map +1 -1
- package/dist/vitest/mock-kysely.d.mts +2 -1
- package/dist/vitest/mocks/aigateway.d.mts +2 -1
- package/dist/vitest/mocks/authconnection.d.mts +2 -1
- package/dist/vitest/mocks/file.d.mts +2 -1
- package/dist/vitest/mocks/iconv.d.mts +2 -1
- package/dist/vitest/mocks/idp.d.mts +2 -1
- package/dist/vitest/mocks/logger.d.mts +2 -1
- package/dist/vitest/mocks/secretmanager.d.mts +2 -1
- package/dist/vitest/mocks/tailordb-pglite.d.mts +2 -1
- package/dist/vitest/mocks/tailordb.d.mts +2 -1
- package/dist/vitest/mocks/workflow.d.mts +3 -1
- package/dist/vitest/pglite-kysely.d.mts +2 -1
- package/dist/vitest/workflow-local.d.mts +2 -1
- package/dist/{workspace_resource_pb-ChWejcj0.mjs → workspace_resource_pb-CaoM2npP.mjs} +2 -2
- package/dist/{workspace_resource_pb-ChWejcj0.mjs.map → workspace_resource_pb-CaoM2npP.mjs.map} +1 -1
- package/docs/cli/application.md +21 -3
- package/docs/cli/data.md +105 -0
- package/docs/cli/secret.md +6 -6
- package/docs/cli/tailordb.md +52 -16
- package/docs/cli/user.md +37 -7
- package/docs/cli/workspace.md +9 -1
- package/docs/cli-reference.md +36 -3
- package/docs/configuration.md +62 -2
- package/docs/github-actions.md +179 -13
- package/docs/multi-environment.md +24 -0
- package/docs/plugin/custom.md +1 -1
- package/docs/services/idp.md +1 -1
- package/docs/services/resolver.md +1 -58
- package/docs/services/tailordb-migration.md +80 -12
- package/docs/services/tailordb.md +17 -4
- package/docs/services/workflow.md +2 -2
- package/docs/testing.md +3 -2
- package/package.json +22 -22
- package/dist/application-DFeuELRo.mjs +0 -200
- package/dist/application-DFeuELRo.mjs.map +0 -1
- package/dist/application-nT_4a5HO.mjs +0 -1
- package/dist/crashreport-CBaRJl5h.mjs +0 -1
- package/dist/kysely-type-RDX59E1j.mjs +0 -48
- package/dist/kysely-type-RDX59E1j.mjs.map +0 -1
- package/dist/logger-Db-YRTwK.mjs +0 -9
- package/dist/logger-Db-YRTwK.mjs.map +0 -1
- package/dist/package-json-CmqhDJ__.mjs +0 -1
- package/dist/register-ts-hook-D6KXrGrB.mjs +0 -1009
- package/dist/register-ts-hook-D6KXrGrB.mjs.map +0 -1
- package/dist/service-Cc7OY0Oh.mjs.map +0 -1
- package/dist/service-sH2MZ4_W.mjs +0 -1
- package/dist/service_pb-Dw2ilc1O.mjs +0 -2
- package/dist/service_pb-Dw2ilc1O.mjs.map +0 -1
- package/dist/service_pb-GDOqfwb6.mjs +0 -1
- package/dist/telemetry-DXHP3VVi.mjs +0 -1
package/dist/cli/main.mjs
CHANGED
|
@@ -1,22 +1,23 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{r as e}from"../field-parse-C41e3UAF.mjs";import{At as t,E as n,J as r,K as i,Lt as a,Wt as o}from"../workspace_resource_pb-
|
|
3
|
-
`)}const Mi=k({name:`inspect`,description:`Print the input message tree of an OperatorService endpoint.`,notes:"Combine with the global `--json` flag for a machine-readable descriptor. Recursive type references and `oneof` membership are annotated. Use `tailor api list` to discover endpoint names.",examples:[{cmd:`GetApplication`,desc:`Show fields of GetApplicationRequest.`},{cmd:`CreateExecutorExecutor`,desc:"Inspect a deeply nested input with `(oneof config)` annotations."}],args:q.strictObject({endpoint:W(q.string(),{positional:!0,description:`API endpoint to inspect (e.g., 'GetApplication' or 'tailor.v1.OperatorService/GetApplication').`,completion:{custom:{choices:listMethodNames()}}})}),run:e=>{let t=extractMethodName(e.endpoint),n=getMethodDescriptor(t);if(!n)throw U({code:`API_METHOD_UNKNOWN`,message:`unknown method: ${t}`,suggestion:"Run `tailor api list` to see available methods.",command:`api inspect`});C.jsonMode?C.out(renderInspectJson(n)):C.out(renderInspectText(n))}}),Ni=k({name:`list`,description:`List all invocable OperatorService methods.`,notes:`Only single-request (non-streaming) methods are listed, because the CLI issues a single JSON request and reads one JSON response.`,args:q.strictObject({}),run:()=>{let e=listMethodNames();if(C.jsonMode)C.out(e);else for(let t of e)C.out(t)}});function resolveNamespaceName(e,t){if(/Auth|Tenant|UserProfile/.test(e))return t.auth?.name;if(/IdP/.test(e))return t.idp?.length===1?s(t.idp[0],`idp config missing`).name:void 0;if(/TailorDB/.test(e)){let e=Object.keys(t.db??{});return e.length===1?e[0]:void 0}if(/Pipeline/.test(e)){let e=Object.keys(t.resolver??{});return e.length===1?e[0]:void 0}}function parseBodyAsObject(e){let t;try{t=JSON.parse(e)}catch{return}if(typeof t==`object`&&t&&!Array.isArray(t))return t}function setNestedPath(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){let n=s(t[e],`path segment missing`),i=r[n];(typeof i!=`object`||!i||Array.isArray(i))&&(r[n]={}),r=r[n]}r[s(t[t.length-1],`path last segment missing`)]=n}function coerceFieldValue(e,t){if(e&&e.fieldKind===`scalar`&&e.scalar===J.BOOL){if(t===`true`)return!0;if(t===`false`)return!1;throw U({code:`API_FIELD_VALUE_INVALID`,message:`Invalid value for bool field: '${t}'. Expected 'true' or 'false'.`,command:`api`})}return t}function normalizeBodyFieldKeys(e,t){let n=/* @__PURE__ */ new Map;for(let e of t)n.set(e.name,e.localName),n.set(e.jsonName,e.localName);let r=!1;for(let t of Object.keys(e)){let i=n.get(t);i&&i!==t&&(Object.hasOwn(e,i)||(e[i]=e[t]),delete e[t],r=!0)}return r}const Pi=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`]),Fi=q.string().transform((e,t)=>{let n=e.indexOf(`=`);if(n<0)return t.addIssue({code:`custom`,message:`Invalid field format: '${e}'. Expected format: 'key=value' or 'a.b.c=value'`}),q.NEVER;let r=e.slice(0,n);if(r.length===0)return t.addIssue({code:`custom`,message:`Field key cannot be empty`}),q.NEVER;let i=r.split(`.`);if(i.some(e=>e.length===0))return t.addIssue({code:`custom`,message:`Invalid field key: '${r}'. Dotted segments cannot be empty`}),q.NEVER;let a=i.find(e=>Pi.has(e));return a?(t.addIssue({code:`custom`,message:`Invalid field key: '${r}'. Segment '${a}' is not allowed.`}),q.NEVER):{path:i,value:e.slice(n+1)}}),Ii=k({name:`api`,description:`Call Tailor Platform API endpoints directly.`,notes:"Use `tailor api list` to enumerate invocable methods and `tailor api inspect <endpoint>` to print an endpoint's input message tree (combine with `--json` for machine-readable output).\n\nThe request body is inferred from the target endpoint's request schema, and commonly required fields are auto-injected so they can be omitted from `--body`:\n\n- `workspaceId` — resolved from `-w` / `TAILOR_PLATFORM_WORKSPACE_ID` / the selected profile.\n- `namespaceName` — resolved from `tailor.config.ts` based on the endpoint's service:\n - Auth / Tenant / UserProfile endpoints use `auth.name`.\n - IdP / TailorDB / Pipeline endpoints use the sole configured namespace when exactly one is defined.\n\nValues already present in `--body` are never overridden. If a value cannot be resolved (e.g. no config found), injection is silently skipped and the server-side validation error takes precedence.\n\nUse `--field key=value` (repeatable) to set request body fields without writing JSON. Dotted keys (e.g. `application.name=foo`) build nested objects. `--field` overrides matching fields in `--body` and tab-completes from the endpoint's request schema.",examples:[{cmd:`GetApplication -b '{"applicationName":"app-1"}'`,desc:`Call an endpoint; workspaceId is auto-injected.`},{cmd:`GetApplication -f applicationName=app-1`,desc:`Same as above, using --field instead of --body.`},{cmd:`list`,desc:`List all invocable OperatorService methods.`},{cmd:`inspect GetApplication`,desc:`Show the input message tree for an endpoint.`}],subCommands:{list:Ni,inspect:Mi},args:q.strictObject({...R,...It,body:W(q.string().default(`{}`),{alias:`b`,description:`Request body as JSON.`}),field:W(Fi.array().optional(),{alias:`f`,description:"Set a body field as `key=value` (repeatable; dotted keys nest). Overrides --body.",completion:{custom:{expand:{dependsOn:[`endpoint`],enumerate:({endpoint:e})=>enumerateAllFieldCompletions(extractMethodName(e??``))}}}}),endpoint:W(q.string(),{positional:!0,description:`API endpoint to call (e.g., 'GetApplication' or 'tailor.v1.OperatorService/GetApplication').`,completion:{custom:{choices:listMethodChoices()}}})}),run:async e=>{await F({profile:e.profile});let t=extractMethodName(e.endpoint),n=getMethodDescriptor(t),r=parseBodyAsObject(e.body),i=!1;if(e.field&&e.field.length>0){if(!r)throw U({code:`API_OPTIONS_INVALID`,message:`--field requires --body to be a JSON object (or omitted).`,command:`api`});for(let t of e.field){let e=n?resolveLeafField(n.input,t.path):void 0;setNestedPath(r,t.path,coerceFieldValue(e,t.value))}i=!0}if(r&&n){normalizeBodyFieldKeys(r,n.input.fields)&&(i=!0);let a=n.input.fields.map(e=>e.localName);if(a.includes(`workspaceId`)&&!Object.hasOwn(r,`workspaceId`))try{r.workspaceId=await ct({workspaceId:e[`workspace-id`],profile:e.profile}),i=!0}catch{}if(a.includes(`namespaceName`)&&!Object.hasOwn(r,`namespaceName`))try{let{config:n}=await P(e.config),a=resolveNamespaceName(t,n);a&&(r.namespaceName=a,i=!0)}catch{}}let a=await Hn({profile:e.profile,endpoint:e.endpoint,body:i&&r?JSON.stringify(r):e.body});C.out(JSON.stringify(a.data,null,2))}}),Li=k({name:`status`,description:`Show the active Tailor Platform authentication status without printing tokens.`,args:q.strictObject({profile:R.profile}),run:async({profile:e})=>{let t=await Ct({profile:e});if(C.out(t),!t.authenticated)throw U({code:`NOT_AUTHENTICATED`,message:`Not authenticated.`,suggestion:`Log in and try again.`,next:{command:`tailor`,args:[`login`,...gt({profile:e})]}})}}),Ri=k({name:`token`,description:`Print a valid Tailor Platform access token to stdout, refreshing it first if expired.`,args:q.strictObject({profile:R.profile}),run:async({profile:e})=>{let t=await Or({profile:e});C.out(t)}}),zi=G({name:`auth`,description:`Authentication helpers for scripts and plugins.`,subCommands:{status:Li,token:Ri}}),Bi={name:W(q.string(),{alias:`n`,description:`Auth connection name`})};async function fetchOIDCDiscovery(e){let t=e.replace(/\/$/,``)+`/.well-known/openid-configuration`,n=await fetch(t).catch(e=>{throw U({code:`OIDC_DISCOVERY_FAILED`,message:`Failed to fetch OIDC discovery from ${t}: ${Hr(e).message}`,cause:e})});if(!n.ok)throw U({code:`OIDC_DISCOVERY_FAILED`,message:`Failed to fetch OIDC discovery from ${t}: ${n.status}`});return n.json()}function randomState$1(){return gi.randomBytes(32).toString(`base64url`)}const Vi=k({name:`authorize`,description:`Authorize an auth connection via OAuth2 flow.`,args:q.strictObject({...R,...Bi,scopes:q.string().optional().default(`openid,profile,email`).describe(`OAuth2 scopes to request (comma-separated)`),port:q.coerce.number().optional().default(8080).describe(`Local callback server port`),"no-browser":q.boolean().optional().default(!1).describe(`Don't open browser automatically`)}),run:async e=>{await F({profile:e.profile});let t=H({command:`tailor`,args:[`authconnection`,`open`,...gt({profile:e.profile,workspaceId:e[`workspace-id`]})]}),{client:n,workspaceId:r}=await N({profile:e.profile,workspaceId:e[`workspace-id`]}),i=(await m(async(e,t)=>{let{connections:i,nextPageToken:a}=await n.listAuthConnections({workspaceId:r,pageToken:e,pageSize:t});return[i,a]})).find(t=>t.name===e.name);if(!i)throw U({code:`AUTH_CONNECTION_NOT_FOUND`,message:`Auth connection "${e.name}" not found.`});if(i.config.case!==`oauth2`)throw U({code:`AUTH_CONNECTION_NOT_OAUTH2`,message:`Auth connection "${e.name}" is not an OAuth2 connection.`});let a=i.config.value,o=`http://localhost:${e.port}/callback`,s=randomState$1(),c;c=a.authUrl?a.authUrl:(await fetchOIDCDiscovery(a.providerUrl)).authorization_endpoint;let l=new URL(c);l.searchParams.set(`client_id`,a.clientId),l.searchParams.set(`redirect_uri`,o),l.searchParams.set(`response_type`,`code`),l.searchParams.set(`scope`,e.scopes.replace(/,/g,` `)),l.searchParams.set(`state`,s),l.searchParams.set(`access_type`,`offline`),await new Promise((i,a)=>{let handleCallback=async(t,l)=>{if(!t.url?.startsWith(`/callback`)){l.writeHead(404),l.end(`Not found`);return}try{let a=new URL(t.url,`http://localhost:${e.port}`),u=a.searchParams.get(`code`),d=a.searchParams.get(`state`),f=a.searchParams.get(`error`);if(f)throw U({code:`AUTHORIZATION_FAILED`,message:`Authorization failed: ${f}`});if(d!==s)throw U({code:`AUTHORIZATION_STATE_MISMATCH`,message:`State mismatch — possible CSRF attack.`});if(!u)throw U({code:`AUTHORIZATION_CODE_MISSING`,message:`No authorization code received.`});C.registerSecret(u),await n.exchangeAuthConnectionAuthorizationCode({workspaceId:r,connectionName:e.name,authorizationCode:u,redirectUri:o}),l.writeHead(200,{"Content-Type":`text/html`}),l.end(`<html><body><h1>Authorization successful</h1><p>You can close this window.</p></body></html>`),c.close(),i()}catch(e){l.writeHead(400,{"Content-Type":`text/plain`}),l.end(`Authorization failed: ${e instanceof Error?e.message:`Unknown error`}`),c.close(),a(Hr(e))}},c=vi.createServer((e,t)=>void handleCallback(e,t)),u=setTimeout(()=>{c.close(),a(U({code:`AUTHORIZATION_TIMEOUT`,message:`Authorization timeout exceeded (5 minutes).`}))},3e5);c.on(`close`,()=>{clearTimeout(u)}),c.on(`error`,n=>{clearTimeout(u);let r=n.code,i=r===`EADDRINUSE`||r===`EACCES`?`Try a different port with --port, or authorize via the Console instead:`:`Authorize via the Console instead:`;C.warn(`Could not start the local callback server on port ${e.port}${r?` (${r})`:``}.\n${i}\n ${t}`),a(n)});let announceAuthorizeUrl=async()=>{let n=l.toString();if(C.info(e[`no-browser`]?`Open this URL in your browser to authorize:\n\n${n}\n`:`Opening browser for authorization:\n\n${n}\n`),C.info(`If this flow doesn't complete, you can authorize via the Console instead:\n ${t}`),!e[`no-browser`])try{await yi(n)}catch{C.warn(`Failed to open browser automatically. Please open the URL above manually.`)}};c.listen(e.port,()=>void announceAuthorizeUrl())}),C.success(`Auth connection "${e.name}" authorized successfully.`),z({changed:!0,workspaceId:r,name:e.name})}}),Hi=k({name:`delete`,description:`Delete an auth connection entirely.`,args:q.strictObject({...R,...Bi,...D}),run:async e=>{await F({profile:e.profile});let{client:t,workspaceId:n}=await N({profile:e.profile,workspaceId:e[`workspace-id`]});if(!e.yes&&await M.text({message:`Enter the connection name to confirm deletion ("${e.name}"):`})!==e.name)throw U({code:`AUTH_CONNECTION_DELETION_CANCELLED`,message:`Auth connection deletion cancelled: the entered name did not match.`,suggestion:`Run the command again and enter the name exactly as shown, or pass --yes to skip the confirmation.`});try{await t.deleteAuthConnection({workspaceId:n,connectionName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`AUTH_CONNECTION_NOT_FOUND`,message:`Auth connection "${e.name}" not found.`,cause:t}):t}C.success(`Auth connection "${e.name}" deleted.`),z({changed:!0,workspaceId:n,name:e.name})}});function connectionInfo(e){let t=e.config.case===`oauth2`?e.config.value:void 0;return{name:e.name,type:e.config.case??`unknown`,providerUrl:t?.providerUrl??``,issuerUrl:t?.issuerUrl??``,clientId:t?.clientId??``,authUrl:t?.authUrl??``,tokenUrl:t?.tokenUrl??``,createdAt:e.createdAt?X(e.createdAt):null}}const Ui=k({name:`list`,description:`List all auth connections.`,args:q.strictObject({...R,...Ht()}),run:async e=>{let{client:t,workspaceId:n}=await N({profile:e.profile,workspaceId:e[`workspace-id`]});try{let r=dr(e.order),i=await L(e.limit,e=>S(async(e,i)=>{let{connections:a,nextPageToken:o}=await t.listAuthConnections({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e}));C.out(i.items.map(connectionInfo)),await B(i,e.limit)}catch(e){if(e instanceof Q&&e.code===Z.NotFound){C.out([]);return}throw e}}}),Wi=k({name:`open`,description:`Open the auth connections page in the Tailor Platform Console.`,args:q.strictObject({...R}),run:async e=>{let t=await ct({workspaceId:e[`workspace-id`],profile:e.profile}),n=`/workspaces/${t}/services/auth-connections`,r=await Tr({profile:e.profile,...e[`workspace-id`]===void 0?{}:{allowMissingProfile:!0}}),i=new URL(n,r).toString(),a=C.jsonMode;C.info(`Opening auth connections page in Tailor Platform Console...`);let o=!0;try{await yi(i)}catch{o=!1}if(a){C.out({consoleUrl:i,workspaceId:t,opened:o});return}o?(C.out(`Console URL: ${i}`),C.out(`Workspace ID: ${t}`)):C.warn(`Failed to open browser automatically. Please open this URL manually:\n${i}`)}}),Gi=k({name:`revoke`,description:`Revoke an auth connection's tokens (keeps the connection; use 'delete' to remove it).`,notes:"Revoke invalidates the connection's active session and tokens but keeps the connection and its stored credentials, so it can be re-authorized later. Use `delete` to remove the connection entirely.",args:q.strictObject({...R,...Bi,...D}),run:async e=>{await F({profile:e.profile});let{client:t,workspaceId:n}=await N({profile:e.profile,workspaceId:e[`workspace-id`]});if(!e.yes&&await M.text({message:`Enter the connection name to confirm revocation ("${e.name}"):`})!==e.name)throw U({code:`AUTH_CONNECTION_REVOCATION_CANCELLED`,message:`Auth connection revocation cancelled: the entered name did not match.`,suggestion:`Run the command again and enter the name exactly as shown, or pass --yes to skip the confirmation.`});try{await t.revokeAuthConnection({workspaceId:n,connectionName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`AUTH_CONNECTION_NOT_FOUND`,message:`Auth connection "${e.name}" not found.`,cause:t}):t}C.success(`Auth connection "${e.name}" revoked.`),z({changed:!0,workspaceId:n,name:e.name})}}),Ki=G({name:`authconnection`,description:`Manage auth connections.`,subCommands:{authorize:Vi,list:Ui,open:Wi,revoke:Gi,delete:Hi},defaultSubCommand:`list`});function orderAndLimitCrashReports(e,t){let n=e.filter(e=>e.endsWith(Jr)).toSorted(),r=t.order===`asc`?n:n.toReversed();return t.limit&&t.limit>0?r.slice(0,t.limit):r}function formatCrashReportFiles(e,t){return e.map(e=>({file:e,path:K.join(t,e)}))}const qi=k({name:`list`,description:`List local crash report files.`,args:q.strictObject({...Ht()}),run:async e=>{let t=Yr(),n=C.jsonMode;if(!t.localDir){C.info(`Crash report directory not available.`),n&&C.out([]);return}let r;try{r=Y.readdirSync(t.localDir)}catch{C.info(`No crash reports found.`),n&&C.out([]);return}let i=await L(e.limit,async t=>orderAndLimitCrashReports(r,{order:e.order,limit:t})),a=i.items;if(a.length===0){C.info(`No crash reports found.`),n&&C.out([]);return}if(n){C.out(formatCrashReportFiles(a,t.localDir)),await B(i,e.limit);return}C.info(`${a.length} crash report(s) in ${t.localDir}:`);for(let e of a)C.log(` ${e}`);await B(i,e.limit)}}),Ji=k({name:`send`,description:`Submit a crash report to help improve the SDK.`,args:q.strictObject({file:W(q.string(),{description:`Path to the crash report file`,required:!0,completion:{type:`file`,extensions:[`log`]}})}),run:async e=>{let t;try{t=Y.readFileSync(e.file,`utf-8`)}catch{C.error(`Crash report file not found: ${e.file}`),process.exit(1)}let n=parseCrashLogFile(t);n||(C.error(`Failed to parse crash report file. The file may be corrupted.`),process.exit(1));let r=await Gr();C.info(`Sending crash report...`),await Xr(n,r)?(C.success(`Crash report submitted successfully. Thank you!`),z({changed:!0,id:n.id,file:e.file})):(C.error(`Failed to submit crash report. The server may be unavailable.`),process.exit(1))}});function parseCrashLogFile(e){try{let t=e.replace(/\r\n/g,`
|
|
4
|
-
`),n=`\n${
|
|
5
|
-
`)[0];return i?JSON.parse(i):void 0}catch{return}}const
|
|
2
|
+
import{r as e}from"../field-parse-C41e3UAF.mjs";import{At as t,E as n,J as r,K as i,Lt as a,Wt as o}from"../workspace_resource_pb-CaoM2npP.mjs";import{t as s}from"../assert-WeXvmG4j.mjs";import{$ as c,B as l,C as u,F as d,G as f,H as p,I as m,L as h,P as g,Q as _,R as v,S as y,St as b,T as ee,U as te,V as ne,W as re,X as ie,Z as ae,_ as oe,at as se,c as ce,dt as le,g as ue,l as de,lt as fe,nt as pe,o as me,ot as he,p as ge,rt as _e,s as ve,st as ye,tt as be,ut as xe,w as Se,y as Ce,yt as we}from"../application-rWYDAfNU.mjs";import{a as x,c as S,n as Te,s as Ee}from"../logger-DuaT2zY3.mjs";import{$n as De,$t as Oe,Ai as ke,Bi as Ae,Bn as je,Br as Me,Ci as Ne,Cn as Pe,Cr as Fe,D as Ie,Di as Le,Dr as Re,Dt as ze,Ei as Be,Er as Ve,F as He,Fi as Ue,G as We,Gi as Ge,Gn as Ke,Gt as qe,H as Je,Hi as C,Hn as Ye,I as Xe,Ii as Ze,In as Qe,It as $e,J as et,Jn as tt,Jt as nt,K as rt,Ki as it,Kn as at,Kr as ot,Kt as st,L as ct,Li as lt,Ln as ut,Lr as dt,M as ft,Mi as pt,Ni as mt,Oi as ht,Or as gt,P as _t,Pi as w,Pn as vt,Pt as yt,Q as bt,Qi as xt,Qn as St,Qr as Ct,Ri as wt,Rn as Tt,Rr as Et,Rt as Dt,S as Ot,Si as kt,Sn as At,Sr as jt,T as Mt,Ti as Nt,Tr as Pt,Tt as Ft,Ui as It,Un as Lt,Ur as Rt,Ut as zt,V as Bt,Vi as T,Vn as Vt,Vr as Ht,Vt as Ut,Wn as Wt,Wr as Gt,Wt as Kt,X as qt,Xi as Jt,Xn as Yt,Xr as Xt,Yi as E,Yn as Zt,Yr as Qt,Zi as $t,Zn as en,Zr as tn,Zt as nn,_i as rn,_n as an,_r as D,_t as on,a as sn,aa as O,ai as cn,an as ln,ar as un,b as dn,bi as fn,br as pn,c as mn,ca as hn,ci as gn,cn as _n,cr as vn,ct as yn,di as bn,dn as xn,dr as Sn,dt as Cn,ea as wn,ei as Tn,en as En,er as Dn,et as On,f as kn,fi as An,fn as jn,fr as Mn,ft as Nn,g as Pn,gi as k,gn as Fn,gr as In,gt as Ln,hi as A,hn as Rn,hr as zn,ia as Bn,ii as Vn,in as Hn,ir as Un,it as Wn,ji as Gn,jt as Kn,k as qn,ki as Jn,kr as j,la as M,li as Yn,ln as Xn,lr as Zn,m as Qn,mi as N,mn as $n,mr as er,mt as tr,n as nr,na as rr,ni as ir,nn as ar,nr as or,nt as sr,o as cr,oa as lr,oi as ur,or as dr,ot as fr,pi as P,pn as pr,pr as mr,qi as F,qn as hr,qr as gr,qt as _r,ra as vr,ri as yr,rr as br,sa as xr,si as I,sn as Sr,sr as Cr,t as wr,ta as Tr,ti as L,tn as Er,tr as Dr,u as Or,ui as kr,un as Ar,ur as jr,v as Mr,vi as R,vn as Nr,vr as Pr,vt as Fr,w as Ir,wi as Lr,wr as Rr,wt as zr,xi as Br,xr as Vr,xt as Hr,yi as z,yn as Ur,yr as B,yt as Wr,z as Gr,zi as Kr,zn as qr}from"../register-ts-hook-CkfKqhJT.mjs";import{g as Jr,i as Yr,r as Xr}from"../service-CETr0AKY.mjs";import{t as V}from"../multiline-EyzjEwn9.mjs";import{a as Zr,i as Qr,n as $r,o as ei,r as H,s as ti,t as U}from"../errors-D3qpNHR6.mjs";import{t as ni}from"../package-json-C690ceex.mjs";import{t as ri}from"../user-agent-vdHYF3QL.mjs";import{t as ii}from"../service_pb-Bbu2QSIr.mjs";import{a as ai,i as oi,o as si,r as ci,t as li}from"../crashreport-BAG8c7hB.mjs";import{t as ui}from"../manager-Bk-7vkwd.mjs";import{a as di,i as fi,n as pi}from"../kysely-type-BWMfV301.mjs";import{arg as W,defineCommand as G,extractFields as mi,runMain as hi,toCamelCase as gi}from"@politty/zod";import{withCompletionCommand as _i}from"@politty/zod/completion";import{withSkillCommand as vi}from"@politty/zod/skill";import*as K from"pathe";import{dirname as yi,resolve as bi}from"pathe";import{resolvePackageJSON as xi}from"pkg-types";import{z as q}from"zod";import{ScalarType as J,create as Si}from"@bufbuild/protobuf";import*as Y from"node:fs";import{accessSync as Ci,constants as wi,readdirSync as Ti}from"node:fs";import{timestampDate as X}from"@bufbuild/protobuf/wkt";import{Code as Z,ConnectError as Q}from"@connectrpc/connect";import{pathToFileURL as Ei}from"node:url";import{generateCodeVerifier as Di}from"@badgateway/oauth2-client";import*as Oi from"node:crypto";import{randomBytes as ki}from"node:crypto";import*as Ai from"node:http";import ji from"open";import*as Mi from"rolldown";import{parseSync as Ni}from"oxc-parser";import*as Pi from"node:os";import*as $ from"node:fs/promises";import{setTimeout as Fi}from"node:timers/promises";import{spawn as Ii,spawnSync as Li}from"node:child_process";import{TraceMap as Ri,generatedPositionFor as zi,originalPositionFor as Bi}from"@jridgewell/trace-mapping";const Vi=ii.methods.filter(e=>e.methodKind===`unary`);function listMethodNames(){return Vi.map(e=>e.name).toSorted()}function listMethodChoices(){return Vi.flatMap(e=>[e.name,`${ii.typeName}/${e.name}`]).toSorted()}function getMethodDescriptor(e){return Vi.find(t=>t.name===e)}function extractMethodName(e){return e.includes(`/`)?e.split(`/`).pop()??e:e}function nestedMessage(e){if(e.fieldKind===`message`||e.fieldKind===`list`&&e.listKind===`message`||e.fieldKind===`map`&&e.mapKind===`message`)return e.message}function isWellKnownType(e){return e.typeName.startsWith(`google.protobuf.`)}const Hi=/* @__PURE__ */ new Set([`google.protobuf.Struct`,`google.protobuf.Value`,`google.protobuf.ListValue`,`google.protobuf.NullValue`,`google.protobuf.Any`,`google.protobuf.Empty`]);function isUnrepresentableWellKnownType(e){return Hi.has(e.typeName)}function enumerateAllFieldCompletions(e){let t=getMethodDescriptor(e);if(!t)return[];let n=[],r=/* @__PURE__ */ new Set;function walk(e,t){r.add(e);for(let i of e.fields){if(i.fieldKind===`list`||i.fieldKind===`map`)continue;let e=t+i.localName;if(i.fieldKind===`message`){if(isUnrepresentableWellKnownType(i.message))continue;if(!isWellKnownType(i.message)){let t=i.message;n.push({value:`${e}.`,description:`${e} (message)`}),r.has(t)||walk(t,`${e}.`);continue}}if(n.push({value:`${e}=`,description:`Set ${e}`}),i.fieldKind===`enum`)for(let t of i.enum.values)n.push({value:`${e}=${t.name}`,description:t.name});else i.fieldKind===`scalar`&&i.scalar===J.BOOL&&(n.push({value:`${e}=true`,description:`true`}),n.push({value:`${e}=false`,description:`false`}))}r.delete(e)}return walk(t.input,``),n}function resolveLeafField(e,t){let n=e;for(let e=0;e<t.length;e++){let r=n.fields.find(n=>n.localName===t[e]);if(!r)return;if(e===t.length-1)return r.fieldKind===`message`&&isUnrepresentableWellKnownType(r.message)?void 0:r;if(r.fieldKind!==`message`||isWellKnownType(r.message))return;n=r.message}}const Ui={[J.DOUBLE]:`double`,[J.FLOAT]:`float`,[J.INT64]:`int64`,[J.UINT64]:`uint64`,[J.INT32]:`int32`,[J.FIXED64]:`fixed64`,[J.FIXED32]:`fixed32`,[J.BOOL]:`bool`,[J.STRING]:`string`,[J.BYTES]:`bytes`,[J.UINT32]:`uint32`,[J.SFIXED32]:`sfixed32`,[J.SFIXED64]:`sfixed64`,[J.SINT32]:`sint32`,[J.SINT64]:`sint64`};function shortName(e){let t=e.lastIndexOf(`.`);return t<0?e:e.slice(t+1)}function scalarLabel(e){return Ui[e]??`scalar(${e})`}function enumLabel(e){return`enum ${shortName(e.typeName)}`}function enumOf(e){if(e.fieldKind===`enum`||e.fieldKind===`list`&&e.listKind===`enum`)return e.enum}function describeFieldType(e){switch(e.fieldKind){case`scalar`:return scalarLabel(e.scalar);case`enum`:return enumLabel(e.enum);case`message`:return shortName(e.message.typeName);case`list`:{let t;return t=e.listKind===`scalar`?scalarLabel(e.scalar):e.listKind===`enum`?enumLabel(e.enum):shortName(e.message.typeName),`repeated ${t}`}case`map`:{let t=scalarLabel(e.mapKey),n;return n=e.mapKind===`scalar`?scalarLabel(e.scalar):e.mapKind===`enum`?enumLabel(e.enum):shortName(e.message.typeName),`map<${t}, ${n}>`}default:return`<unknown>`}}function fieldToJson(e,t){let n={name:e.localName,protoName:e.name,type:describeFieldType(e),fieldKind:e.fieldKind,repeated:e.fieldKind===`list`};e.oneof&&(n.oneof=e.oneof.name);let r=enumOf(e);r&&(n.enumValues=r.values.map(e=>e.name));let i=nestedMessage(e);return i&&!t.has(i)?(t.add(i),n.message={typeName:i.typeName,fields:i.fields.map(e=>fieldToJson(e,t))},t.delete(i)):i&&(n.message={typeName:i.typeName,fields:[],recursive:!0}),n}function renderInspectJson(e){let t=/* @__PURE__ */ new Set([e.input]);return{method:e.name,input:{typeName:e.input.typeName,fields:e.input.fields.map(e=>fieldToJson(e,t))},output:{typeName:e.output.typeName}}}function renderFieldText(e,t,n){let r=[],i=e.oneof?` (oneof ${e.oneof.name})`:``;r.push(`${t}${e.localName}: ${describeFieldType(e)}${i}`);let a=enumOf(e);if(a){let e=a.values.map(e=>e.name).join(`, `);r.push(`${t} values: ${e}`)}let o=nestedMessage(e);if(o&&!n.has(o)){n.add(o);for(let e of o.fields)r.push(...renderFieldText(e,`${t} `,n));n.delete(o)}else o&&r.push(`${t} …(recursive ${o.typeName})`);return r}function renderInspectText(e){let t=[];t.push(`${e.name}`),t.push(` request: ${e.input.typeName}`);let n=/* @__PURE__ */ new Set([e.input]);for(let r of e.input.fields)t.push(...renderFieldText(r,` `,n));return t.push(` response: ${e.output.typeName}`),t.join(`
|
|
3
|
+
`)}const Wi=C({name:`inspect`,description:`Print the input message tree of an OperatorService endpoint.`,notes:"Combine with the global `--json` flag for a machine-readable descriptor. Recursive type references and `oneof` membership are annotated. Use `tailor api list` to discover endpoint names.",examples:[{cmd:`GetApplication`,desc:`Show fields of GetApplicationRequest.`},{cmd:`CreateExecutorExecutor`,desc:"Inspect a deeply nested input with `(oneof config)` annotations."}],args:q.strictObject({endpoint:W(q.string(),{positional:!0,description:`API endpoint to inspect (e.g., 'GetApplication' or 'tailor.v1.OperatorService/GetApplication').`,completion:{custom:{choices:listMethodNames()}}})}),run:e=>{let t=extractMethodName(e.endpoint),n=getMethodDescriptor(t);if(!n)throw U({code:`API_METHOD_UNKNOWN`,message:`unknown method: ${t}`,suggestion:"Run `tailor api list` to see available methods.",command:`api inspect`});x.jsonMode?x.out(renderInspectJson(n)):x.out(renderInspectText(n))}}),Gi=C({name:`list`,description:`List all invocable OperatorService methods.`,notes:`Only single-request (non-streaming) methods are listed, because the CLI issues a single JSON request and reads one JSON response.`,args:q.strictObject({}),run:()=>{let e=listMethodNames();if(x.jsonMode)x.out(e);else for(let t of e)x.out(t)}});function resolveNamespaceName(e,t){if(/Auth|Tenant|UserProfile/.test(e))return t.auth?.name;if(/IdP/.test(e))return t.idp?.length===1?s(t.idp[0],`idp config missing`).name:void 0;if(/TailorDB/.test(e)){let e=Object.keys(t.db??{});return e.length===1?e[0]:void 0}if(/Pipeline/.test(e)){let e=Object.keys(t.resolver??{});return e.length===1?e[0]:void 0}}function parseBodyAsObject(e){let t;try{t=JSON.parse(e)}catch{return}if(typeof t==`object`&&t&&!Array.isArray(t))return t}function setNestedPath(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){let n=s(t[e],`path segment missing`),i=r[n];(typeof i!=`object`||!i||Array.isArray(i))&&(r[n]={}),r=r[n]}r[s(t[t.length-1],`path last segment missing`)]=n}function coerceFieldValue(e,t){if(e&&e.fieldKind===`scalar`&&e.scalar===J.BOOL){if(t===`true`)return!0;if(t===`false`)return!1;throw U({code:`API_FIELD_VALUE_INVALID`,message:`Invalid value for bool field: '${t}'. Expected 'true' or 'false'.`,command:`api`})}return t}function normalizeBodyFieldKeys(e,t){let n=/* @__PURE__ */ new Map;for(let e of t)n.set(e.name,e.localName),n.set(e.jsonName,e.localName);let r=!1;for(let t of Object.keys(e)){let i=n.get(t);i&&i!==t&&(Object.hasOwn(e,i)||(e[i]=e[t]),delete e[t],r=!0)}return r}const Ki=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`]),qi=q.string().transform((e,t)=>{let n=e.indexOf(`=`);if(n<0)return t.addIssue({code:`custom`,message:`Invalid field format: '${e}'. Expected format: 'key=value' or 'a.b.c=value'`}),q.NEVER;let r=e.slice(0,n);if(r.length===0)return t.addIssue({code:`custom`,message:`Field key cannot be empty`}),q.NEVER;let i=r.split(`.`);if(i.some(e=>e.length===0))return t.addIssue({code:`custom`,message:`Invalid field key: '${r}'. Dotted segments cannot be empty`}),q.NEVER;let a=i.find(e=>Ki.has(e));return a?(t.addIssue({code:`custom`,message:`Invalid field key: '${r}'. Segment '${a}' is not allowed.`}),q.NEVER):{path:i,value:e.slice(n+1)}}),Ji=C({name:`api`,description:`Call Tailor Platform API endpoints directly.`,notes:"Use `tailor api list` to enumerate invocable methods and `tailor api inspect <endpoint>` to print an endpoint's input message tree (combine with `--json` for machine-readable output).\n\nThe request body is inferred from the target endpoint's request schema, and commonly required fields are auto-injected so they can be omitted from `--body`:\n\n- `workspaceId` — resolved from `-w` / `TAILOR_PLATFORM_WORKSPACE_ID` / the selected profile.\n- `namespaceName` — resolved from `tailor.config.ts` based on the endpoint's service:\n - Auth / Tenant / UserProfile endpoints use `auth.name`.\n - IdP / TailorDB / Pipeline endpoints use the sole configured namespace when exactly one is defined.\n\nValues already present in `--body` are never overridden. If a value cannot be resolved (e.g. no config found), injection is silently skipped and the server-side validation error takes precedence.\n\nUse `--field key=value` (repeatable) to set request body fields without writing JSON. Dotted keys (e.g. `application.name=foo`) build nested objects. `--field` overrides matching fields in `--body` and tab-completes from the endpoint's request schema.",examples:[{cmd:`GetApplication -b '{"applicationName":"app-1"}'`,desc:`Call an endpoint; workspaceId is auto-injected.`},{cmd:`GetApplication -f applicationName=app-1`,desc:`Same as above, using --field instead of --body.`},{cmd:`list`,desc:`List all invocable OperatorService methods.`},{cmd:`inspect GetApplication`,desc:`Show the input message tree for an endpoint.`}],subCommands:{list:Gi,inspect:Wi},args:q.strictObject({...M,...it,body:W(q.string().default(`{}`),{alias:`b`,description:`Request body as JSON.`}),field:W(qi.array().optional(),{alias:`f`,description:"Set a body field as `key=value` (repeatable; dotted keys nest). Overrides --body.",completion:{custom:{expand:{dependsOn:[`endpoint`],enumerate:({endpoint:e})=>enumerateAllFieldCompletions(extractMethodName(e??``))}}}}),endpoint:W(q.string(),{positional:!0,description:`API endpoint to call (e.g., 'GetApplication' or 'tailor.v1.OperatorService/GetApplication').`,completion:{custom:{choices:listMethodChoices()}}})}),run:async e=>{await R({profile:e.profile});let t=extractMethodName(e.endpoint),n=getMethodDescriptor(t),r=parseBodyAsObject(e.body),i=!1;if(e.field&&e.field.length>0){if(!r)throw U({code:`API_OPTIONS_INVALID`,message:`--field requires --body to be a JSON object (or omitted).`,command:`api`});for(let t of e.field){let e=n?resolveLeafField(n.input,t.path):void 0;setNestedPath(r,t.path,coerceFieldValue(e,t.value))}i=!0}if(r&&n){normalizeBodyFieldKeys(r,n.input.fields)&&(i=!0);let a=n.input.fields.map(e=>e.localName);if(a.includes(`workspaceId`)&&!Object.hasOwn(r,`workspaceId`))try{r.workspaceId=await Gn({workspaceId:e[`workspace-id`],profile:e.profile}),i=!0}catch{}if(a.includes(`namespaceName`)&&!Object.hasOwn(r,`namespaceName`))try{let{config:n}=await z(e.config),a=resolveNamespaceName(t,n);a&&(r.namespaceName=a,i=!0)}catch{}}let a=await rn({profile:e.profile,endpoint:e.endpoint,body:i&&r?JSON.stringify(r):e.body});x.out(JSON.stringify(a.data,null,2))}}),Yi=C({name:`status`,description:`Show the active Tailor Platform authentication status without printing tokens.`,args:q.strictObject({profile:M.profile}),run:async({profile:e})=>{let t=await Nt({profile:e});if(x.out(t),!t.authenticated)throw U({code:`NOT_AUTHENTICATED`,message:`Not authenticated.`,suggestion:`Log in and try again.`,next:{command:`tailor`,args:[`login`,...O({profile:e})]}})}}),Xi=C({name:`token`,description:`Print a valid Tailor Platform access token to stdout, refreshing it first if expired.`,args:q.strictObject({profile:M.profile}),run:async({profile:e})=>{let t=await Lr({profile:e});x.out(t)}}),Zi=G({name:`auth`,description:`Authentication helpers for scripts and plugins.`,subCommands:{status:Yi,token:Xi}}),Qi={name:W(q.string(),{alias:`n`,description:`Auth connection name`})};async function fetchOIDCDiscovery(e){let t=e.replace(/\/$/,``)+`/.well-known/openid-configuration`,n=await fetch(t).catch(e=>{throw U({code:`OIDC_DISCOVERY_FAILED`,message:`Failed to fetch OIDC discovery from ${t}: ${ei(e).message}`,cause:e})});if(!n.ok)throw U({code:`OIDC_DISCOVERY_FAILED`,message:`Failed to fetch OIDC discovery from ${t}: ${n.status}`});return n.json()}function randomState$1(){return Oi.randomBytes(32).toString(`base64url`)}const $i=C({name:`authorize`,description:`Authorize an auth connection via OAuth2 flow.`,args:q.strictObject({...M,...Qi,scopes:q.string().optional().default(`openid,profile,email`).describe(`OAuth2 scopes to request (comma-separated)`),port:q.coerce.number().optional().default(8080).describe(`Local callback server port`),"no-browser":q.boolean().optional().default(!1).describe(`Don't open browser automatically`)}),run:async e=>{await R({profile:e.profile});let t=H({command:`tailor`,args:[`authconnection`,`open`,...O({profile:e.profile,workspaceId:e[`workspace-id`]})]}),{client:n,workspaceId:r}=await A({profile:e.profile,workspaceId:e[`workspace-id`]}),i=(await _(async(e,t)=>{let{connections:i,nextPageToken:a}=await n.listAuthConnections({workspaceId:r,pageToken:e,pageSize:t});return[i,a]})).find(t=>t.name===e.name);if(!i)throw U({code:`AUTH_CONNECTION_NOT_FOUND`,message:`Auth connection "${e.name}" not found.`});if(i.config.case!==`oauth2`)throw U({code:`AUTH_CONNECTION_NOT_OAUTH2`,message:`Auth connection "${e.name}" is not an OAuth2 connection.`});let a=i.config.value,o=`http://localhost:${e.port}/callback`,s=randomState$1(),c;c=a.authUrl?a.authUrl:(await fetchOIDCDiscovery(a.providerUrl)).authorization_endpoint;let l=new URL(c);l.searchParams.set(`client_id`,a.clientId),l.searchParams.set(`redirect_uri`,o),l.searchParams.set(`response_type`,`code`),l.searchParams.set(`scope`,e.scopes.replace(/,/g,` `)),l.searchParams.set(`state`,s),l.searchParams.set(`access_type`,`offline`),await new Promise((i,a)=>{let handleCallback=async(t,l)=>{if(!t.url?.startsWith(`/callback`))l.writeHead(404),l.end(`Not found`);else try{let a=new URL(t.url,`http://localhost:${e.port}`),u=a.searchParams.get(`code`),d=a.searchParams.get(`state`),f=a.searchParams.get(`error`);if(f)throw U({code:`AUTHORIZATION_FAILED`,message:`Authorization failed: ${f}`});if(d!==s)throw U({code:`AUTHORIZATION_STATE_MISMATCH`,message:`State mismatch — possible CSRF attack.`});if(!u)throw U({code:`AUTHORIZATION_CODE_MISSING`,message:`No authorization code received.`});x.registerSecret(u),await n.exchangeAuthConnectionAuthorizationCode({workspaceId:r,connectionName:e.name,authorizationCode:u,redirectUri:o}),l.writeHead(200,{"Content-Type":`text/html`}),l.end(`<html><body><h1>Authorization successful</h1><p>You can close this window.</p></body></html>`),c.close(),i()}catch(e){l.writeHead(400,{"Content-Type":`text/plain`}),l.end(`Authorization failed: ${e instanceof Error?e.message:`Unknown error`}`),c.close(),a(ei(e))}},c=Ai.createServer((e,t)=>void handleCallback(e,t)),u=setTimeout(()=>{c.close(),a(U({code:`AUTHORIZATION_TIMEOUT`,message:`Authorization timeout exceeded (5 minutes).`}))},3e5);c.on(`close`,()=>{clearTimeout(u)}),c.on(`error`,n=>{clearTimeout(u);let r=n.code,i=r===`EADDRINUSE`||r===`EACCES`?`Try a different port with --port, or authorize via the Console instead:`:`Authorize via the Console instead:`;x.warn(`Could not start the local callback server on port ${e.port}${r?` (${r})`:``}.\n${i}\n ${t}`),a(n)});let announceAuthorizeUrl=async()=>{let n=l.toString();if(x.info(e[`no-browser`]?`Open this URL in your browser to authorize:\n\n${n}\n`:`Opening browser for authorization:\n\n${n}\n`),x.info(`If this flow doesn't complete, you can authorize via the Console instead:\n ${t}`),!e[`no-browser`])try{await ji(n)}catch{x.warn(`Failed to open browser automatically. Please open the URL above manually.`)}};c.listen(e.port,()=>void announceAuthorizeUrl())}),x.success(`Auth connection "${e.name}" authorized successfully.`),k({changed:!0,workspaceId:r,name:e.name})}}),ea=C({name:`delete`,description:`Delete an auth connection entirely.`,args:q.strictObject({...M,...Qi,...F}),run:async e=>{await R({profile:e.profile});let{client:t,workspaceId:n}=await A({profile:e.profile,workspaceId:e[`workspace-id`]});if(!e.yes&&await N.text({message:`Enter the connection name to confirm deletion ("${e.name}"):`})!==e.name)throw U({code:`AUTH_CONNECTION_DELETION_CANCELLED`,message:`Auth connection deletion cancelled: the entered name did not match.`,suggestion:`Run the command again and enter the name exactly as shown, or pass --yes to skip the confirmation.`});try{await t.deleteAuthConnection({workspaceId:n,connectionName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`AUTH_CONNECTION_NOT_FOUND`,message:`Auth connection "${e.name}" not found.`,cause:t}):t}x.success(`Auth connection "${e.name}" deleted.`),k({changed:!0,workspaceId:n,name:e.name})}});function connectionInfo(e){let t=e.config.case===`oauth2`?e.config.value:void 0;return{name:e.name,type:e.config.case??`unknown`,providerUrl:t?.providerUrl??``,issuerUrl:t?.issuerUrl??``,clientId:t?.clientId??``,authUrl:t?.authUrl??``,tokenUrl:t?.tokenUrl??``,createdAt:e.createdAt?X(e.createdAt):null}}const ta=C({name:`list`,description:`List all auth connections.`,args:q.strictObject({...M,...vr()}),run:async e=>{let{client:t,workspaceId:n}=await A({profile:e.profile,workspaceId:e[`workspace-id`]});try{let r=hn(e.order),i=await An(e.limit,e=>be(async(e,i)=>{let{connections:a,nextPageToken:o}=await t.listAuthConnections({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e}));x.out(i.items.map(connectionInfo)),await P(i,e.limit)}catch(e){if(e instanceof Q&&e.code===Z.NotFound){x.out([]);return}throw e}}}),na=C({name:`open`,description:`Open the auth connections page in the Tailor Platform Console.`,args:q.strictObject({...M}),run:async e=>{let t=await Gn({workspaceId:e[`workspace-id`],profile:e.profile}),n=`/workspaces/${t}/services/auth-connections`,r=await Le({profile:e.profile,...e[`workspace-id`]===void 0?{}:{allowMissingProfile:!0}}),i=new URL(n,r).toString(),a=x.jsonMode;x.info(`Opening auth connections page in Tailor Platform Console...`);let o=!0;try{await ji(i)}catch{o=!1}a?x.out({consoleUrl:i,workspaceId:t,opened:o}):o?(x.out(`Console URL: ${i}`),x.out(`Workspace ID: ${t}`)):x.warn(`Failed to open browser automatically. Please open this URL manually:\n${i}`)}}),ra=C({name:`revoke`,description:`Revoke an auth connection's tokens (keeps the connection; use 'delete' to remove it).`,notes:"Revoke invalidates the connection's active session and tokens but keeps the connection and its stored credentials, so it can be re-authorized later. Use `delete` to remove the connection entirely.",args:q.strictObject({...M,...Qi,...F}),run:async e=>{await R({profile:e.profile});let{client:t,workspaceId:n}=await A({profile:e.profile,workspaceId:e[`workspace-id`]});if(!e.yes&&await N.text({message:`Enter the connection name to confirm revocation ("${e.name}"):`})!==e.name)throw U({code:`AUTH_CONNECTION_REVOCATION_CANCELLED`,message:`Auth connection revocation cancelled: the entered name did not match.`,suggestion:`Run the command again and enter the name exactly as shown, or pass --yes to skip the confirmation.`});try{await t.revokeAuthConnection({workspaceId:n,connectionName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`AUTH_CONNECTION_NOT_FOUND`,message:`Auth connection "${e.name}" not found.`,cause:t}):t}x.success(`Auth connection "${e.name}" revoked.`),k({changed:!0,workspaceId:n,name:e.name})}}),ia=G({name:`authconnection`,description:`Manage auth connections.`,subCommands:{authorize:$i,list:ta,open:na,revoke:ra,delete:ea},defaultSubCommand:`list`});function orderAndLimitCrashReports(e,t){let n=e.filter(e=>e.endsWith(oi)).toSorted(),r=t.order===`asc`?n:n.toReversed();return t.limit&&t.limit>0?r.slice(0,t.limit):r}function formatCrashReportFiles(e,t){return e.map(e=>({file:e,path:K.join(t,e)}))}const aa=C({name:`list`,description:`List local crash report files.`,args:q.strictObject({...vr()}),run:async e=>{let t=si(),n=x.jsonMode;if(!t.localDir){x.info(`Crash report directory not available.`),n&&x.out([]);return}let r;try{r=Y.readdirSync(t.localDir)}catch{x.info(`No crash reports found.`),n&&x.out([]);return}let i=await An(e.limit,async t=>orderAndLimitCrashReports(r,{order:e.order,limit:t})),a=i.items;if(a.length===0)x.info(`No crash reports found.`),n&&x.out([]);else if(n)x.out(formatCrashReportFiles(a,t.localDir)),await P(i,e.limit);else{x.info(`${a.length} crash report(s) in ${t.localDir}:`);for(let e of a)x.log(` ${e}`);await P(i,e.limit)}}}),oa=C({name:`send`,description:`Submit a crash report to help improve the SDK.`,args:q.strictObject({file:W(q.string(),{description:`Path to the crash report file`,required:!0,completion:{type:`file`,extensions:[`log`]}})}),run:async e=>{let t;try{t=Y.readFileSync(e.file,`utf-8`)}catch{x.error(`Crash report file not found: ${e.file}`),process.exit(1)}let n=parseCrashLogFile(t);n||(x.error(`Failed to parse crash report file. The file may be corrupted.`),process.exit(1));let r=await ri();x.info(`Sending crash report...`),await ci(n,r)?(x.success(`Crash report submitted successfully. Thank you!`),k({changed:!0,id:n.id,file:e.file})):(x.error(`Failed to submit crash report. The server may be unavailable.`),process.exit(1))}});function parseCrashLogFile(e){try{let t=e.replace(/\r\n/g,`
|
|
4
|
+
`),n=`\n${ai}\n`,r=t.lastIndexOf(n);if(r===-1)return;let i=t.slice(r+n.length).split(`
|
|
5
|
+
`)[0];return i?JSON.parse(i):void 0}catch{return}}const sa=G({name:`crashreport`,description:`Manage crash reports.`,subCommands:{list:aa,send:oa},defaultSubCommand:`list`});function delay(e){return e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve()}function assertSeedDataDirectory(e){let t;try{t=Y.statSync(e)}catch(t){throw t.code===`ENOENT`?U({code:`SEED_DATA_NOT_FOUND`,message:`Seed data directory not found: ${e}.`,suggestion:`Generate seed data before testing migrations.`,cause:t}):t}if(!t.isDirectory())throw U({code:`SEED_DATA_INVALID`,message:`Seed data path is not a directory: ${e}`})}function assertAssertionScript(e){let t=K.resolve(e),n;try{n=Y.statSync(t)}catch(e){throw e.code===`ENOENT`?U({code:`MIGRATION_ASSERTION_SCRIPT_NOT_FOUND`,message:`Migration assertion script not found: ${t}`,cause:e}):e}if(!n.isFile())throw U({code:`MIGRATION_ASSERTION_SCRIPT_INVALID`,message:`Migration assertion path is not a file: ${t}`})}function assertCloneTargetRegion(e,t){if(e!==t)throw U({code:`MIGRATION_TEST_REGION_MISMATCH`,message:`Clone mode requires source and target workspaces in the same region (source: ${e}, target: ${t}).`})}function assertTargetWorkspaceDiffers(e,t){if(t?.toLowerCase()===e.toLowerCase())throw U({code:`MIGRATION_TEST_TARGET_INVALID`,message:`The migration test target workspace must differ from the source workspace.`,command:`tailordb migration test`})}function resolveAssertionNamespace(e,t){let n=t??(e.length===1?e[0]:void 0);if(!n)throw U({code:`MIGRATION_TEST_ASSERT_NAMESPACE_REQUIRED`,message:`--assert-namespace is required when pending migrations span multiple namespaces.`,command:`tailordb migration test`});if(!e.includes(n))throw U({code:`MIGRATION_TEST_NO_PENDING_MIGRATIONS`,message:`Assertion namespace "${n}" has no pending migrations.`});return n}async function createMigrationTestBaselineSnapshots(e){let t=new Map([...e.baselines].map(([e,t])=>[e,t.snapshot]));if(e.dataMode!==`clone`)return t;let n=e.inputs.filter(e=>!t.has(e.namespace)),r=await Promise.all(n.map(t=>Tt(e.client,e.workspaceId,t.namespace)));return n.forEach((e,n)=>{t.set(e.namespace,s(r[n],`remote snapshot missing for "${e.namespace}"`))}),t}async function waitForCloneApplicationData(e,t){let n=t.pollInterval??3e3,r=t.timeout??18e5,i=t.errorCodePrefix??`MIGRATION_TEST_CLONE`,a=Date.now()+r,s;for(let c=r;c>0;c=a-Date.now()){let r;try{r=await e.getCloneApplicationDataOperation({sourceWorkspaceId:t.sourceWorkspaceId,targetWorkspaceId:t.targetWorkspaceId,operationId:t.operationId},Number.isFinite(c)?{timeoutMs:c}:void 0)}catch(e){if(e instanceof Q&&e.code===Z.DeadlineExceeded&&Date.now()>=a-100)break;throw e}if(r.status===o.COMPLETED)return;if(r.status===o.FAILED)throw U({code:`${i}_FAILED`,message:`Application data clone failed: ${r.errorMessage||`unknown platform error`}`});if(r.status!==o.PENDING&&r.status!==o.PROCESSING)throw Qr(`Application data clone returned unexpected status ${r.status}.`);r.status!==s&&(s=r.status,t.onStatus?.(r.status)),await delay(Math.min(n,Math.max(a-Date.now(),0)))}throw U({code:`${i}_TIMEOUT`,message:`Application data clone timed out after ${r<1e3?`${r} ms`:`${Math.round(r/1e3)} seconds`}.`,context:{operationId:t.operationId,sourceWorkspaceId:t.sourceWorkspaceId,targetWorkspaceId:t.targetWorkspaceId}})}function loadSnapshotSeedData(e,t,n){let r={};for(let i of t){let t=n?.tables[i],a=K.join(e,`${i}.jsonl`),o;try{o=Y.readFileSync(a,`utf8`).trim()}catch(e){if(e.code===`ENOENT`){r[i]=[];continue}throw e}r[i]=o?o.split(`
|
|
6
|
+
`).map((e,n)=>{let r;try{r=JSON.parse(e)}catch(e){throw U({code:`SEED_DATA_INVALID`,message:`Invalid JSON in ${a} at line ${n+1}: ${e instanceof Error?e.message:String(e)}`,cause:e})}if(typeof r!=`object`||!r||Array.isArray(r))throw U({code:`SEED_DATA_INVALID`,message:`Invalid seed row in ${a} at line ${n+1}: expected a JSON object`});let i=r;return t?projectSeedObject(i,t.fields,/* @__PURE__ */ new Set([`id`])):i}):[]}return r}function projectSeedObject(e,t,n=/* @__PURE__ */ new Set){return Object.fromEntries(Object.entries(e).flatMap(([e,r])=>{let i=t[e];return i?[[e,projectSeedValue(r,i)]]:n.has(e)?[[e,r]]:[]}))}function projectSeedValue(e,t){let n=t.fields;return n?t.array?Array.isArray(e)?e.map(e=>isJsonObject(e)?projectSeedObject(e,n):e):e:isJsonObject(e)?projectSeedObject(e,n):e:e}function isJsonObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function sortSeedTypesForSnapshot(e){let t=Object.keys(e.tables),n=new Set(t),r=/* @__PURE__ */ new Map,i=[];for(let[t,a]of Object.entries(e.tables)){let e=/* @__PURE__ */ new Set;for(let r of Object.values(a.fields)){let a=r.foreignKeyType;a&&(a===t?i.push(t):n.has(a)&&e.add(a))}r.set(t,[...e])}let a=/* @__PURE__ */ new Set,o=[],visit=e=>{if(!a.has(e)){a.add(e);for(let t of r.get(e)??[])visit(t);o.push(e)}};for(let e of t)visit(e);return{order:o,selfRefTypes:i}}function temporaryWorkspaceName(){return`migration-test-${(/* @__PURE__ */ new Date()).toISOString().replace(/[-:T.Z]/g,``).slice(0,14)}-${ki(3).toString(`hex`)}`}function stateOrThrow(e){return s(e,`migration test runtime was used before preparation`)}async function resolveSourceMigrationNumber(e,t,n,r,i,a){if(r.number!==null)return r.number;if(!r.metadataExists)throw U({code:`MIGRATION_TEST_SOURCE_CHECKPOINT_MISSING`,message:`Source namespace "${n.namespace}" has not been deployed.`,suggestion:`Deploy to the source workspace before testing.`});let o=j(n.migrationsDir,0);if(!o)throw U({code:`MIGRATION_BASELINE_NOT_FOUND`,message:`No migration baseline snapshot found for namespace "${n.namespace}".`});let s=await ut(e,t,n.namespace,o,i,a);if(s.length>0)throw U({code:`MIGRATION_TEST_SOURCE_INVALID`,message:`Source namespace "${n.namespace}" has no migration label and its schema differs from the initial migration snapshot (0000).`,details:Pt(s),suggestion:`Bring the source schema in line with 0000 or set its migration label.`});return 0}async function assertSourceBaselineFresh(e,t,n){let r=e.loaded,i=B(r.config,K.dirname(r.config.path)),a=r.application.tailorDBServices.map(Ye),o=(await Lt(e.client,n,i,r.config,a)).find(e=>e.hasDrift||e.checkpointMissingLocal||e.checkpointRepair);if(o)throw U({code:`MIGRATION_TEST_SOURCE_CHANGED`,message:`Source namespace "${o.namespace}" changed after migration test preparation.`,suggestion:`Run the migration test again.`});for(let o of i){let i=t.baselines.get(o.namespace);if(!i)continue;let s=await D(e.client,I(n,`tailordb`,o.namespace));In(s,o.namespace);let c=await resolveSourceMigrationNumber(e.client,n,o,s,r.config,a);if(c!==i.migrationNumber)throw U({code:`MIGRATION_TEST_SOURCE_CHANGED`,message:`Source namespace "${o.namespace}" moved from migration ${i.migrationNumber} to ${c} after migration test preparation.`,suggestion:`Run the migration test again.`})}let s=a.filter(e=>!t.baselines.has(e.namespace));for(let r of s){let i=t.baselineSnapshots.get(r.namespace);if(!i)continue;let a=await Tt(e.client,n,r.namespace);if(Ct(i,a).changes.length>0)throw U({code:`MIGRATION_TEST_SOURCE_CHANGED`,message:`Source namespace "${r.namespace}" schema changed after migration test preparation.`,suggestion:`Run the migration test again.`})}}async function deleteExistingUserProfileConfig(e,t){let n=e.loaded.application.authService;if(!n)return;let r=n.config.name;await he(()=>e.client.getUserProfileConfig({workspaceId:t,namespaceName:r}))&&await e.client.deleteUserProfileConfig({workspaceId:t,namespaceName:r})}function migrationConfig(e,t){return e.config.db?.[t]?.migration}function authExecutionContext(e,t,n){let r=e.loaded.application.authService;if(!r)throw U({code:`AUTH_CONFIG_REQUIRED`,message:`Auth configuration is required to execute migration test scripts.`});let i=n??Zt(migrationConfig(e.loaded,t),r.config.machineUsers?Object.keys(r.config.machineUsers):void 0);if(!i)throw U({code:`MACHINE_USER_REQUIRED`,message:`No machine user is available for namespace "${t}".`,suggestion:`Pass --machine-user or configure one in auth or db.${t}.migration.`});return{authNamespace:r.config.name,machineUserName:i}}async function prepareMigrationTest(e){let t=await Kt({configPath:e.configPath}),n=K.dirname(t.config.path),r=B(t.config,n);if(r.length===0)throw pn();for(let e of r)gt(e.migrationsDir,e.namespace);let i;e.data===`seed`&&(i=await zt({configPath:t.config.path}),assertSeedDataDirectory(K.join(i.distPath,`data`))),e.assertionPath&&assertAssertionScript(e.assertionPath);let a=t.application.tailorDBServices.map(Ye),o=await Lr({profile:e.profile}),c=await Jn({profile:e.profile}),l=await xe(o,c),u=await Gn({workspaceId:e.workspaceId,profile:e.profile});assertTargetWorkspaceDiffers(u,e.targetWorkspaceId);let[d,f,p]=await Promise.all([l.getWorkspace({workspaceId:u}),l.getApplication({workspaceId:u,applicationName:t.config.name}),e.data===`clone`&&e.targetWorkspaceId?l.getWorkspace({workspaceId:e.targetWorkspaceId}):Promise.resolve(void 0)]),m=s(d.workspace,`source workspace "${u}" not found`);s(f.application,`application "${t.config.name}" not found in source workspace`);let h=p?s(p.workspace,`target workspace "${e.targetWorkspaceId}" not found`):void 0,g=await Lt(l,u,r,t.config,a),_=g.find(e=>e.hasDrift||e.checkpointMissingLocal);if(_)throw U({code:`MIGRATION_TEST_SOURCE_INVALID`,message:`Source namespace "${_.namespace}" does not match its migration checkpoint.`,suggestion:`Validate the migration history first.`});let v=g.find(e=>e.checkpointRepair);if(v)throw U({code:`MIGRATION_TEST_SOURCE_REPAIR_PENDING`,message:`Source namespace "${v.namespace}" has a pending migration checkpoint repair.`,suggestion:`Deploy to the source workspace first.`});let y=/* @__PURE__ */ new Map,b=/* @__PURE__ */ new Map,ee=[];for(let e of r){let n=await D(l,I(u,`tailordb`,e.namespace));In(n,e.namespace);let r=await resolveSourceMigrationNumber(l,u,e,n,t.config,a),i=Ht(e.migrationsDir);if(r>i)throw U({code:`MIGRATION_TEST_SOURCE_AHEAD`,message:`Source namespace "${e.namespace}" is at migration ${r}, but the local history ends at ${i}.`});let o=j(e.migrationsDir,r);if(!o)throw U({code:`MIGRATION_BASELINE_NOT_FOUND`,message:`No migration baseline snapshot found for namespace "${e.namespace}".`});y.set(e.namespace,{migrationNumber:r,snapshot:o,historyId:o.rebaseline?.historyId??null});let s=j(e.migrationsDir,i);if(!s)throw U({code:`MIGRATION_TEST_SNAPSHOT_NOT_FOUND`,message:`No target migration snapshot found for namespace "${e.namespace}".`});b.set(e.namespace,s),r<i&&ee.push(e.namespace)}if(ee.length===0)throw U({code:`MIGRATION_TEST_NO_PENDING_MIGRATIONS`,message:`No pending TailorDB migrations found in the source workspace.`});let te=await createMigrationTestBaselineSnapshots({client:l,workspaceId:u,dataMode:e.data,inputs:a,baselines:y}),ne={sourceWorkspaceId:u,sourceApplicationName:t.config.name,temporaryWorkspace:{name:temporaryWorkspaceName(),region:m.region,...m.organizationId?{organizationId:m.organizationId}:{},...m.folderId?{folderId:m.folderId}:{}},baselines:y,baselineSnapshots:te,targetSnapshots:b,pendingNamespaces:ee,...h?{designatedTarget:{id:h.id,region:h.region}}:{}};return{state:{client:l,loaded:t,options:e,...i?{seedContext:i}:{}},prepared:ne}}function createMigrationTestDependencies(){let e;return{prepare:async t=>{let{state:n,prepared:r}=await prepareMigrationTest(t);return e=n,r},createWorkspace:async t=>{let n=stateOrThrow(e),r=await ln(n.client,t.temporaryWorkspace);return x.info(`Created temporary workspace ${r.name} (${r.id}).`),{id:r.id,name:r.name,...r.createdAt?{createdAt:r.createdAt}:{}}},recordWorkspaceExpiry:async(t,n,r=/* @__PURE__ */ new Date)=>{let i=stateOrThrow(e);await an(i.client,t,new Date(r.getTime()+Ur(n)))},deployBaseline:async({prepared:t,targetWorkspaceId:n})=>{let r=stateOrThrow(e);await deleteExistingUserProfileConfig(r,n),await En({configPath:r.loaded.config.path,profile:r.options.profile,workspaceId:n,yes:!0},t.baselines,t.baselineSnapshots);for(let[e,i]of t.baselines)await Yt(r.client,n,e,i.migrationNumber,i.historyId??void 0)},seedData:async({prepared:t,targetWorkspaceId:n})=>{let r=stateOrThrow(e),i=s(r.seedContext,`seed context missing after migration test preparation`),a=K.join(i.distPath,`data`);assertSeedDataDirectory(a);let o=new Map(r.loaded.application.tailorDBServices.map(e=>{let n=t.baselines.get(e.namespace),r=Ye(e);return[e.namespace,n?.snapshot??Tn({version:1,namespace:e.namespace,createdAt:(/* @__PURE__ */ new Date()).toISOString(),tables:r.types})]}));for(let[e,t]of o){let{order:o,selfRefTypes:s}=sortSeedTypesForSnapshot(t),c=loadSnapshotSeedData(a,o,t),l=o.filter(e=>(c[e]?.length??0)>0);if(l.length===0)continue;let u=await nn(e,l,K.dirname(r.loaded.config.path)),d=_r({data:c,order:o,codeByteSize:new TextEncoder().encode(u.bundledCode).length}),f=authExecutionContext(r,e,r.options.machineUser??i.machineUserName);for(let t of d){let i=await nt({client:r.client,workspaceId:n,name:`migration-test-seed-${e}.ts`,code:u.bundledCode,arg:{data:t.data,order:t.order,selfRefTypes:s,upsert:!1},invoker:{namespace:f.authNamespace,machineUserName:f.machineUserName}});if(!i.success)throw U({code:`MIGRATION_TEST_SEED_FAILED`,message:i.error??`Seed execution failed for namespace "${e}".`});if(JSON.parse(i.result||`{}`).success!==!0)throw U({code:`MIGRATION_TEST_SEED_FAILED`,message:`Seed execution reported failure for namespace "${e}".`})}}},cloneData:async({prepared:t,sourceWorkspaceId:n,targetWorkspaceId:r,applicationName:i,cloneTimeout:a})=>{let o=stateOrThrow(e);await assertSourceBaselineFresh(o,t,n),x.warn(`Clone mode copies TailorDB records only; IdP users and file blobs are not copied.`);let s;try{s=(await o.client.cloneApplicationData({sourceWorkspaceId:n,sourceApplicationName:i,targetWorkspaceId:r,targetApplicationName:i})).operationId}catch(e){throw e instanceof Q&&e.code===Z.Unimplemented?U({code:`MIGRATION_TEST_CLONE_UNAVAILABLE`,message:`Application data clone is not enabled for this platform.`,suggestion:`Retry with --data seed.`,cause:e}):e}if(!s)throw Qr(`Application data clone returned no operation ID.`);await waitForCloneApplicationData(o.client,{sourceWorkspaceId:n,targetWorkspaceId:r,operationId:s,timeout:a})},deployMigrations:async({prepared:t,targetWorkspaceId:n})=>{let r=stateOrThrow(e);await Er({configPath:r.loaded.config.path,profile:r.options.profile,workspaceId:n,yes:!0},t.targetSnapshots)},runAssertion:async({prepared:t,targetWorkspaceId:n,assertionPath:r,assertionNamespace:i,machineUser:a})=>{let o=stateOrThrow(e),s=resolveAssertionNamespace(t.pendingNamespaces,i),c=authExecutionContext(o,s,a),l=await Sn(r,s,0,o.loaded.config.env??{},K.dirname(o.loaded.config.path),st(o.loaded.plugins,`@tailor-platform/kysely-type`)?.temporal??!1,ce(o.loaded.config)),u=await nt({client:o.client,workspaceId:n,name:`migration-test-assert-${s}.ts`,code:l.bundledCode,invoker:{namespace:c.authNamespace,machineUserName:c.machineUserName}});if(!u.success)throw U({code:`MIGRATION_TEST_ASSERTION_FAILED`,message:u.error??`Migration assertion failed for namespace "${s}".`})},deleteWorkspace:async t=>{await stateOrThrow(e).client.deleteWorkspace({workspaceId:t})}}}const ca={from:W(q.string(),{description:`Workspace ID to copy data from`,completion:{type:`none`}}),to:W(q.string(),{description:`Workspace ID to copy data to`,completion:{type:`none`}})};function resumeCommandArgs(e){return[`data`,`operation`,`get`,`--from`,e.sourceWorkspaceId,`--to`,e.targetWorkspaceId,`--operation-id`,e.operationId,`--wait`,...O({profile:e.profile})]}function resumeHint(e){return H({command:`tailor`,args:resumeCommandArgs(e)})}async function hintOnInterrupt(e,t){let onInterrupt=()=>{x.info(`Stopped waiting. The clone keeps running on the platform. To wait for it: ${resumeHint(e)}`)};process.once(`SIGINT`,onInterrupt);try{return await t()}finally{process.off(`SIGINT`,onInterrupt)}}const la={[o.PENDING]:`pending`,[o.PROCESSING]:`processing`,[o.COMPLETED]:`completed`,[o.FAILED]:`failed`};function statusName(e){return la[e]??`unknown`}function reportStatus(e){x.info(`status: ${statusName(e)}`,{mode:`stream`})}function formatElapsed(e){let t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n>0?`${n}h ${r}m`:r>0?`${r}m ${i}s`:`${i}s`}async function $clone(e){let t=$t(e.config),n=t?[t]:[];if(e.sourceWorkspaceId===e.targetWorkspaceId)throw U({code:`DATA_CLONE_SAME_WORKSPACE`,message:`The source and target workspaces must be different.`,command:`data clone`});let r=await xe(await Lr({profile:e.profile}));try{await r.getApplication({workspaceId:e.targetWorkspaceId,applicationName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`DATA_CLONE_TARGET_APPLICATION_NOT_FOUND`,message:`Application "${e.name}" was not found in the target workspace "${e.targetWorkspaceId}".`,suggestion:e.nameFromConfig?`Check --to and that you have access to the target workspace, and deploy the application to it first so it has the same namespaces and schema.`:`Check --to and that you have access to the target workspace, and deploy the application "${e.name}" to it first so it has the same namespaces and schema.`,...e.nameFromConfig?{next:{command:`tailor`,args:[`deploy`,...O({workspaceId:e.targetWorkspaceId,profile:e.profile}),...n]}}:{},command:`data clone`,cause:t}):t}if(!e.yes&&!await N.confirm({message:`This will copy the data of application "${e.name}" from workspace "${e.sourceWorkspaceId}" to workspace "${e.targetWorkspaceId}". Continue?`,default:!1}))throw U({code:`DATA_CLONE_CANCELLED`,message:`Data clone cancelled.`});let i;try{i=(await r.cloneApplicationData({sourceWorkspaceId:e.sourceWorkspaceId,sourceApplicationName:e.name,targetWorkspaceId:e.targetWorkspaceId,targetApplicationName:e.name,copyFiles:e.copyFiles,copyIdpUsers:e.copyIdpUsers})).operationId}catch(t){throw t instanceof Q&&t.code===Z.Unimplemented?U({code:`DATA_CLONE_UNAVAILABLE`,message:`Application data clone is not enabled for this platform.`,command:`data clone`,cause:t}):t instanceof Q&&t.code===Z.FailedPrecondition?U({code:`DATA_CLONE_PRECONDITION_FAILED`,message:t.rawMessage,suggestion:`A clone needs both workspaces in the same region with the same namespaces, a matching TailorDB schema (deploy the same version to the target first), and an empty target for every copy type in scope. ${e.nameFromConfig?`To empty the target's TailorDB records, run ${H({command:`tailor`,args:[`tailordb`,`truncate`,`--all`,...O({workspaceId:e.targetWorkspaceId,profile:e.profile}),...n]})}.`:`To empty the target's TailorDB records, run tailor tailordb truncate for the namespaces of this application (see tailor tailordb truncate --help).`} That does not remove IdP users or files: with --copy-idp-users or --copy-files, remove those from the target separately.`,command:`data clone`,cause:t}):t instanceof Q&&t.code===Z.NotFound?U({code:`DATA_CLONE_NOT_FOUND`,message:t.rawMessage,suggestion:`Check that --from and --to are workspace IDs you can access and that the application exists in the source workspace.`,command:`data clone`,cause:t}):t}if(!i)throw Qr(`Application data clone returned no operation ID.`);x.info(`Clone started (operation: ${i})`);let a={sourceWorkspaceId:e.sourceWorkspaceId,targetWorkspaceId:e.targetWorkspaceId,operationId:i,profile:e.profile};if(e.noWait)return x.info(`The clone keeps running on the platform. To wait for it: ${resumeHint(a)}`),{operationId:i,status:`started`};let o=Date.now();return await hintOnInterrupt(a,()=>waitForCloneApplicationData(r,{sourceWorkspaceId:a.sourceWorkspaceId,targetWorkspaceId:a.targetWorkspaceId,operationId:i,timeout:1/0,errorCodePrefix:`DATA_CLONE`,onStatus:reportStatus})),x.success(`Cloned data of application "${e.name}" from "${e.sourceWorkspaceId}" to "${e.targetWorkspaceId}" in ${formatElapsed(Date.now()-o)}`),{operationId:i,status:`completed`}}const ua=C({name:`clone`,description:`Clone the data of an application (TailorDB namespaces registered in its subgraph) from one workspace to another.`,notes:"\nThe platform rejects the clone with a failed precondition unless all of the following hold:\n- The source and target workspaces are in the same region.\n- The target workspace has the same namespaces as the source.\n- The TailorDB schema of the target matches the source, so deploy the same version to the target first.\n- The target is empty for every namespace and copy type in scope (TailorDB records, plus files and IdP users when `--copy-files` / `--copy-idp-users` are given).\n\nThe command waits until the clone finishes. Pressing Ctrl+C or passing --no-wait does not stop the clone, which keeps running on the platform. Use `tailor data operation get --wait` with the operation ID printed at the start to keep waiting, or without --wait to check the status once.\n\nWith --json, the result carries `status`: `completed` once the clone has finished, or `started` with --no-wait.\n",args:q.strictObject({...F,profile:W(q.string().optional(),{alias:`p`,description:`Workspace profile`,env:`TAILOR_PLATFORM_PROFILE`,completion:{type:`none`}}),...ca,name:W(q.string().optional(),{alias:`n`,description:`Application name, the same in the source and the target workspace (default: the name in the config file)`,completion:{type:`none`}}),...it,"copy-files":W(q.boolean().default(!1),{description:`Also copy TailorDB file content`}),"copy-idp-users":W(q.boolean().default(!1),{description:`Also copy IdP users, including their passwords`}),"no-wait":W(q.boolean().default(!1),{description:`Start the clone and exit without waiting for it to finish`})}),run:async e=>{await R({profile:e.profile});let t=e.name??(await z(e.config)).config.name,{operationId:n,status:r}=await $clone({sourceWorkspaceId:e.from,targetWorkspaceId:e.to,name:t,config:e.config,nameFromConfig:e.name===void 0,copyFiles:e[`copy-files`],copyIdpUsers:e[`copy-idp-users`],noWait:e[`no-wait`],profile:e.profile,yes:e.yes});k({changed:!0,sourceWorkspaceId:e.from,targetWorkspaceId:e.to,operationId:n,status:r})}}),da=C({name:`get`,description:`Show the status of a data clone, or wait for it to finish.`,notes:`Without --wait, the command prints the current status once and exits. With --wait, it waits until the clone completes or fails, and exits with an error if it fails. Pressing Ctrl+C stops waiting; the clone keeps running on the platform.`,args:q.strictObject({profile:W(q.string().optional(),{alias:`p`,description:`Workspace profile`,env:`TAILOR_PLATFORM_PROFILE`,completion:{type:`none`}}),...ca,"operation-id":W(q.string(),{description:`Operation ID printed when the clone started`,completion:{type:`none`}}),wait:W(q.boolean().default(!1),{description:`Wait until the clone completes or fails`})}),run:async e=>{let t=await xe(await Lr({profile:e.profile})),n={sourceWorkspaceId:e.from,targetWorkspaceId:e.to,operationId:e[`operation-id`],profile:e.profile};if(!e.wait){let e=await t.getCloneApplicationDataOperation({sourceWorkspaceId:n.sourceWorkspaceId,targetWorkspaceId:n.targetWorkspaceId,operationId:n.operationId}),r=statusName(e.status);x.info(`Clone operation ${n.operationId}: ${r}`),e.errorMessage&&x.info(`Message: ${e.errorMessage}`),x.out({operationId:n.operationId,status:r,...e.errorMessage?{errorMessage:e.errorMessage}:{}});return}let r=Date.now();await hintOnInterrupt(n,()=>waitForCloneApplicationData(t,{sourceWorkspaceId:n.sourceWorkspaceId,targetWorkspaceId:n.targetWorkspaceId,operationId:n.operationId,timeout:1/0,errorCodePrefix:`DATA_CLONE`,onStatus:reportStatus})),x.success(`Clone operation ${n.operationId} completed (waited ${formatElapsed(Date.now()-r)})`),x.out({operationId:n.operationId,status:`completed`})}}),fa=G({name:`operation`,description:`Inspect asynchronous application data operations.`,subCommands:{get:da}}),pa=G({name:`data`,description:`Manage application data across workspaces.`,subCommands:{clone:ua,operation:fa}}),ma=C({name:`deploy`,description:`Deploy your application by applying the Tailor configuration.`,notes:"Workspace creation uses the selected user's default organization and folder set by `user update` when neither location is given and TAILOR_PLATFORM_TOKEN is not set. Giving --organization-id or --folder-id replaces both defaults. Organization and folder IDs loaded by --env-file also replace the defaults; command-line options take precedence, and empty env-file values are ignored. With --create-workspace, an existing workspace must match the resolved name, region, organization, and folder to be reused.",args:q.strictObject({...M,...Tr,...F,"create-workspace":W(q.boolean().optional(),{description:`Create a workspace when the account has none`}),"workspace-name":W(q.string().optional(),{description:`Name for a workspace created during deploy`}),"workspace-region":W(q.string().optional(),{description:`Region for a workspace created during deploy`}),"organization-id":W(q.string().optional(),{description:`Organization ID for a workspace created during deploy`,env:`TAILOR_PLATFORM_ORGANIZATION_ID`}),"folder-id":W(q.string().optional(),{description:`Folder ID for a workspace created during deploy`,env:`TAILOR_PLATFORM_FOLDER_ID`}),"dry-run":W(q.boolean().optional(),{alias:`d`,description:`Run the command without making any changes`}),"no-schema-check":W(q.boolean().optional(),{description:`Skip schema diff check against migration snapshots`}),"migration-skip-steps":W(q.string().optional(),{description:`Skip steps of a partially applied multi-step migration that already succeeded (comma-separated namespace/step entries)`}),"no-validate":W(q.boolean().optional(),{description:`Skip client-side validation against platform resource constraints`}),"no-cache":W(q.boolean().optional(),{description:`Disable bundle caching for this run`}),"clean-cache":W(q.boolean().optional(),{description:`Clean the bundle cache before building`})}),run:async e=>{await R({profile:e.profile});let{initTelemetry:t}=await import(`../telemetry-DpkFGBmu.mjs`);await t(),await Oe({workspaceId:e[`workspace-id`],profile:e.profile,configPath:e.config,dryRun:e[`dry-run`],yes:e.yes,createWorkspace:e[`create-workspace`],workspaceName:e[`workspace-name`],workspaceRegion:e[`workspace-region`],...wn(e),noSchemaCheck:e[`no-schema-check`],migrationSkipSteps:Wt(e[`migration-skip-steps`]),noValidate:e[`no-validate`],noCache:e[`no-cache`],cleanCache:e[`clean-cache`]},{envFile:e[`env-file`],envFileIfExists:e[`env-file-if-exists`],verbose:e.verbose,json:e.json})}}),ha=G({name:`executor`,description:`Manage executors`,subCommands:{trigger:Ft,jobs:Kn,list:ze,get:Ut,webhook:zr},defaultSubCommand:`list`});function scriptNameToRegistryName(e,t){if(t===r.JOB)return`workflow--${e}`;let n=/^([^.]+)\.(.+)\.body\.js$/.exec(e);if(n){let[,e,t]=n;return`resolver--${e}--${t}`}let i=/^(.+)\.operation\.js$/.exec(e);if(i){let[,e]=i;return`executor--${e}`}let a=/^([^.]+)\.([^.]+)\.hook\.js$/.exec(e);if(a){let[,e,t]=a;return`auth-hook--${e}--${t}`}return t===r.UNSPECIFIED&&!e.includes(`.`)?`workflow--${e}`:null}async function downloadFunctionScript(e){let{client:t,workspaceId:n,name:r,contentHash:i}=e;try{let e=[];for await(let a of t.downloadFunctionRegistryScript({workspaceId:n,name:r,contentHash:i}))a.payload.case===`chunk`&&e.push(a.payload.value);return e.length===0?null:{code:Buffer.concat(e).toString(`utf-8`)}}catch(t){return x.debug(`Failed to download function script "${e.name}": ${t}`),null}}const ga=/^\s+at\s+(?:(.+?)\s+\()?(file:\/\/\/.+?):(\d+):(\d+)\)?$/;function parseStackTrace(e){let t=e.split(`
|
|
6
7
|
`),n=[],r=[];for(let e of t)/^\s+at\s+/.test(e)?r.push(e):r.length===0&&n.push(e);let i=n.join(`
|
|
7
|
-
`);i.startsWith(`rpc error: code = Aborted desc = `)&&(i=i.slice(33));let a=[];for(let e of r){let t=
|
|
8
|
-
`),r=Math.max(0,t-1-2),i=Math.min(n.length,t+2),a=String(i).length,o=[];for(let e=r;e<i;e++){let r=e+1,i=String(r).padStart(a),s=n[e];r===t?o.push(` ${
|
|
9
|
-
`)}function formatMappedError(e,t,n,r){let i=[` ${
|
|
10
|
-
`)}function formatErrorWithSourcemap(e,t,n){try{let{errorMessage:r,frames:i}=parseStackTrace(e);if(i.length===0)return null;let a=extractInlineSourcemap(t);if(!a)return null;let o=mapStackFrames(i,a);return o.some(e=>e.mapped!==null)?formatMappedError(r,o,a,n):null}catch{return null}}function functionExecutionTypeToString(e){return
|
|
8
|
+
`);i.startsWith(`rpc error: code = Aborted desc = `)&&(i=i.slice(33));let a=[];for(let e of r){let t=ga.exec(e);t&&a.push({functionName:t[1]||`<anonymous>`,file:s(t[2],`stack frame file missing`),line:Number(s(t[3],`stack frame line missing`)),column:Number(s(t[4],`stack frame column missing`))})}return{errorMessage:i,frames:a}}const _a=/\/\/[#@]\s*sourceMappingURL=data:application\/json[^,]*;base64,(.+)$/m;function extractInlineSourcemap(e){let t=_a.exec(e);if(!t)return null;try{let e=Buffer.from(s(t[1],`sourcemap base64 data missing`),`base64`).toString(`utf-8`),n=JSON.parse(e);return new Ri(n)}catch{return null}}function mapStackFrames(e,t){return e.map(e=>{if(!t)return{original:e,mapped:null};try{for(let n=t.sources.length-1;n>=0;n--){let r=t.sources[n];if(r==null)continue;let i=zi(t,{source:r,line:e.line,column:e.column-1});if(i.line==null)continue;let a=Bi(t,{line:i.line,column:i.column});if(a.source===r&&a.line===e.line&&a.column===e.column-1)return{original:e,mapped:{source:r,line:e.line,column:e.column,name:null}}}return{original:e,mapped:null}}catch{return{original:e,mapped:null}}})}function detectEditorScheme(){let e=process.env.VISUAL||process.env.EDITOR||``;return/\bcode\b/.test(e)?`vscode`:null}function osc8Link(e,t){return`\x1b]8;;${e}\x07${t}\x1b]8;;\x07`}function buildSourceLink(e,t,n,r){let i=`${e}:${n}:${r}`;return detectEditorScheme()===`vscode`?osc8Link(`vscode://file${t}:${n}:${r}`,i):osc8Link(`file://${t}`,i)}function buildCodeSnippet(e,t){let n=e.split(`
|
|
9
|
+
`),r=Math.max(0,t-1-2),i=Math.min(n.length,t+2),a=String(i).length,o=[];for(let e=r;e<i;e++){let r=e+1,i=String(r).padStart(a),s=n[e];r===t?o.push(` ${S.error(`>`)} ${S.error(`${i} | ${s}`)}`):o.push(` ${S.dim(`${i} | ${s}`)}`)}return o.join(`
|
|
10
|
+
`)}function readInstalledSource(e){try{let t=Y.realpathSync(e);return m(t)===void 0?void 0:Y.readFileSync(t,`utf-8`)}catch{return}}function formatMappedError(e,t,n,r){let i=[` ${S.error(e)}`];for(let e of t)if(e.mapped){let{source:t,line:a,column:o,name:s}=e.mapped,c=r?K.resolve(r,t):K.resolve(t),l=K.relative(process.cwd(),c),u=l.startsWith(`..`)?l:`./${l}`,d=s??e.original.functionName,f=buildSourceLink(u,c,a,o);if(i.push(`\n at ${d} (${f})`),n){let e=n.sources.indexOf(t),r=(e===-1?void 0:n.sourcesContent?.[e])||readInstalledSource(c);r&&i.push(buildCodeSnippet(r,a))}}else{let t=`${e.original.file.replace(/^file:\/\/\//,``)}:${e.original.line}:${e.original.column}`;i.push(`\n ${S.dim(`at ${e.original.functionName} (${t})`)}`)}return i.join(`
|
|
11
|
+
`)}function formatErrorWithSourcemap(e,t,n){try{let{errorMessage:r,frames:i}=parseStackTrace(e);if(i.length===0)return null;let a=extractInlineSourcemap(t);if(!a)return null;let o=mapStackFrames(i,a);return o.some(e=>e.mapped!==null)?formatMappedError(r,o,a,n):null}catch{return null}}function functionExecutionTypeToString(e){return Zn(r,e)??`UNSPECIFIED`}function functionErrorKindToString(e){return Zn(i,e)??`UNSPECIFIED`}function toFunctionExecutionListInfo(e){return{id:e.id,scriptName:e.scriptName,status:Un(e.status),type:functionExecutionTypeToString(e.type),startedAt:e.startedAt?X(e.startedAt):null,finishedAt:e.finishedAt?X(e.finishedAt):null,errorKind:functionErrorKindToString(e.errorKind),errorName:e.error?.name||null,errorMessage:e.error?.message||null}}function toFunctionExecutionDetailInfo(e){return{...toFunctionExecutionListInfo(e),logs:dr(e.logEntries),logEntries:e.logEntries.map(Cr),result:e.result,error:e.error?{name:e.error.name,message:e.error.message,stackTrace:e.error.stackTrace}:null}}function composeExecutionErrorString(e){let{name:t,message:n,stackTrace:r}=e,i=t&&n?`${t}: ${n}`:t||n;if(!r)return i;let a=r.split(`
|
|
11
12
|
`,1)[0]??``;return/^\s+at\s+/.test(a)?`${i}\n${r}`:r}function formatExecutionErrorFallback(e){let[t=``,...n]=composeExecutionErrorString(e).split(`
|
|
12
|
-
`);return[` ${
|
|
13
|
-
`)}function formatExecutionError(e,t){if(t&&e.stackTrace){let n=formatErrorWithSourcemap(composeExecutionErrorString(e),t,
|
|
14
|
-
Logs:`));for(let e of t)
|
|
15
|
-
Result:`));try{let e=JSON.parse(t.result);
|
|
13
|
+
`);return[` ${S.error(t)}`,...n.map(e=>` ${S.dim(e)}`)].join(`
|
|
14
|
+
`)}function deployedBundleDir(){return K.join(process.cwd(),`dist`)}function formatExecutionError(e,t){if(t&&e.stackTrace){let n=formatErrorWithSourcemap(composeExecutionErrorString(e),t,deployedBundleDir());if(n)return n}return formatExecutionErrorFallback(e)}const formatDate=e=>e?e.toISOString():`N/A`;function printFunctionExecutionSummary(e){let t=[[`id`,e.id],[`scriptName`,e.scriptName],[`status`,e.status],[`type`,e.type],[`startedAt`,formatDate(e.startedAt)],[`finishedAt`,formatDate(e.finishedAt)],[`errorKind`,e.errorKind]];x.out(Ar(t))}function printFunctionExecutionLogs(e){let t=br(e.logEntries);if(t.length!==0){x.log(S.bold(`
|
|
15
|
+
Logs:`));for(let e of t)x.log(` ${e}`)}}function printFunctionExecutionOutcome(e){let{detail:t,bundledCode:n}=e;if(t.result){x.log(S.bold(`
|
|
16
|
+
Result:`));try{let e=JSON.parse(t.result);x.log(` ${JSON.stringify(e,null,2).split(`
|
|
16
17
|
`).join(`
|
|
17
|
-
`)}`)}catch{
|
|
18
|
-
Error:`)),
|
|
19
|
-
Logs:`));for(let e of n.logEntries.slice(a))
|
|
18
|
+
`)}`)}catch{x.log(` ${t.result}`)}}t.error&&(x.log(S.bold(`
|
|
19
|
+
Error:`)),x.log(formatExecutionError(t.error,n??null)))}async function fetchFunctionExecution(e){let{execution:t}=await e.client.getFunctionExecution({workspaceId:e.workspaceId,executionId:e.executionId},{signal:e.signal});if(!t)throw U({code:`FUNCTION_EXECUTION_NOT_FOUND`,message:`Function execution '${e.executionId}' not found.`});return t}async function followFunctionExecution(e){let{interval:t,timeout:n,showProgress:r}=e,i=Date.now(),a=0,o,remainingMs=()=>n===void 0?void 0:n-(Date.now()-i),timedOut=()=>{let e=remainingMs();return e!==void 0&&e<=0},timeoutError=()=>{let t=o===void 0?`unknown`:Un(o);return U({code:`FUNCTION_EXECUTION_TIMEOUT`,message:`Timed out waiting for function execution '${e.executionId}' to complete. Last status: ${t}.`})},sleep=async()=>{let e=remainingMs();if(e===void 0)await Fi(t);else{if(e<=0)throw timeoutError();await Fi(Math.min(t,e))}};for(;;){let t=remainingMs();if(t!==void 0&&t<=0)throw timeoutError();let n;try{n=await fetchFunctionExecution({...e,signal:t===void 0?void 0:AbortSignal.timeout(t)})}catch(e){if(timedOut())throw timeoutError();if(!Dn(e))throw e;x.warn(`Retrying function execution poll: ${De(e)}`,{mode:`stream`}),await sleep();continue}if(r){if(o===void 0&&(printFunctionExecutionSummary(toFunctionExecutionListInfo(n)),un(n.status)||x.info(`Following log entries until the execution completes (Ctrl+C to stop)`,{mode:`stream`})),n.logEntries.length>a){a===0&&x.log(S.bold(`
|
|
20
|
+
Logs:`));for(let e of n.logEntries.slice(a))x.log(` ${or(Cr(e))}`);a=n.logEntries.length}if(o!==void 0&&n.status!==o){let e=Dr(Un(n.status));x.info(`Status: ${e}`,{mode:`stream`})}}let i=o!==void 0;if(o=n.status,un(n.status))return{execution:n,printedEntries:a,followed:i};await sleep()}}async function downloadScriptForMapping(e){let{client:t,workspaceId:n,scriptName:r,executionType:i,executionContentHash:a}=e,o=scriptNameToRegistryName(r,i);if(o==null)return x.debug(`Script "${r}" is not a deployed registry script (e.g. function run or seed); skipping sourcemap mapping.`),null;if(a===``)return x.debug(`Function execution "${r}" has no contentHash; skipping sourcemap mapping because the exact bundle cannot be identified.`),null;let s=await downloadFunctionScript({client:t,workspaceId:n,name:o,contentHash:a});return s==null?(x.debug(`Could not download pinned script "${r}" (registry: "${o}", contentHash: "${a}") for stack trace mapping; showing raw stack trace.`),null):s.code}const va=C({name:`logs`,description:`List or get function execution logs.`,notes:"Each execution includes `errorKind`, which tells you where a failure came from: `USER_RUNTIME` (your code threw while running, or exceeded its time, memory, or CPU limit), `USER_NON_RUNTIME` (your script failed while loading, before your function was called, such as when its top-level code threw), `PLATFORM` (a failure on the Platform side, or the Platform aborting the run because of its own deadline or cancellation), `NONE` (no error), or `UNSPECIFIED` (not recorded, or a kind this CLI version does not recognize). A workflow job waiting on another job also reports `USER_NON_RUNTIME` when that job fails or is canceled. `errorName` and `errorMessage` hold the error's name and message, or `null` when none was recorded. The list table omits `errorMessage`; use `--json` or the execution details to read it.\n\nExecution details include `logEntries`, the structured log lines (message, severity, timestamp) recorded while the function ran. They are available while the execution is still running. The `logs` string joins their messages with newlines.\n\nUse `--follow` to keep polling a running execution and print new log entries as they arrive until it completes. Polling continues while the execution is suspended at a wait point, and indefinitely unless `--timeout` is set. With `--json`, `--follow` waits for completion and then emits the final execution details once.\n\nWhen viewing a specific execution that failed, the command displays error details with the stack trace mapped back to your original source files (clickable file links and code snippets, matching `function run` output).\n\nStack traces are mapped only when the execution includes a content hash for the exact build that ran. If the content hash is missing or the build is no longer available, the command falls back to a plain-text error display.",examples:[{cmd:``,desc:`List all function execution logs`},{cmd:`<execution-id>`,desc:`Get execution details with logs`},{cmd:`--json`,desc:`Output as JSON`},{cmd:`<execution-id> --json`,desc:`Get execution details as JSON`},{cmd:`<execution-id> --follow`,desc:`Stream log entries of a running execution until it completes`}],args:q.strictObject({...M,...rr,"execution-id":W(q.string().optional(),{positional:!0,description:`Execution ID (if provided, shows details with logs)`}),follow:W(q.boolean().default(!1),{alias:`f`,description:`Keep polling a running execution and print new log entries as they arrive (detail mode only)`}),interval:W(Jt.default(`3s`),{alias:`i`,description:`Polling interval for --follow (e.g., '3s', '500ms', '1m')`}),timeout:W(Jt.optional(),{alias:`t`,description:`Maximum time to keep following (e.g., '30s', '10m'); unbounded by default`})}),run:async e=>{if(e.follow&&!e.executionId)throw U({code:`FUNCTION_LOGS_OPTIONS_INVALID`,message:`--follow requires an execution ID.`,command:`function logs`});let{client:t,workspaceId:n}=await A({profile:e.profile,workspaceId:e[`workspace-id`]});if(e.executionId){let r=x.jsonMode||e.json,i={client:t,workspaceId:n,executionId:e.executionId},{execution:a,printedEntries:o,followed:s}=e.follow?await followFunctionExecution({...i,interval:Bn(e.interval),timeout:e.timeout===void 0?void 0:Bn(e.timeout),showProgress:!r}):{execution:await fetchFunctionExecution(i),printedEntries:0,followed:!1},c=toFunctionExecutionDetailInfo(a);if(r){x.out(c);return}(!e.follow||s)&&printFunctionExecutionSummary(c),o===0&&printFunctionExecutionLogs(c),printFunctionExecutionOutcome({detail:c,bundledCode:c.error?await downloadScriptForMapping({client:t,workspaceId:n,scriptName:c.scriptName,executionType:a.type,executionContentHash:a.contentHash}):null})}else{let r=hn(e.order),i=await An(e.limit,e=>be(async(e,i)=>{let{executions:a,nextPageToken:o}=await t.listFunctionExecutions({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e})),a=i.items.map(toFunctionExecutionListInfo);if(a.length===0&&!e.json){x.info(`No function execution logs found.`);return}x.out(a,{display:{errorMessage:null}}),await P(i,e.limit)}}});async function bundleForRun(e){let{detected:t,sourceFile:n,baseDir:r,env:i={},machineUser:a,workspaceId:o,dateDefault:s=`legacy`}=e,c=me(e.inlineSourcemap),u=te(e.logLevel),m=K.resolve(ve(),`test-run`);Y.mkdirSync(m,{recursive:!0});let _=`test-run--${t.name}`,y=`${_}.js`,b=K.join(m,`${_}.entry.js`),ee=generateEntry({detected:t,sourceFile:n,env:i,machineUser:a,workspaceId:o,defaultPermission:e.defaultPermission,dateDefault:s});Y.writeFileSync(b,ee);let ie=await h(r),ae=re({tsconfig:ie}),oe=await Mi.build({plugins:[g(b,r),f(),v(t.type===`resolver`?Se(t.fields,s):{date:!0,temporal:!0},s)],input:b,write:!1,output:{format:`esm`,sourcemap:!0,minify:!c||{mangle:{keepNames:!0}},codeSplitting:!1,dir:process.cwd()},tsconfig:ie,treeshake:l([p(u),ne(e.treeshake)]),...ae.options});return ae.assertAllResolved(),{bundledCode:d({chunk:oe.output[0],inlineSourcemap:c,dependencySources:e.inlineSourcemapDependencySources??!1}),scriptName:y}}function generateEntry(e){let{detected:t,sourceFile:n,env:r,machineUser:i,workspaceId:a,defaultPermission:o,dateDefault:c}=e,l=K.resolve(n);switch(t.type){case`plain`:return t.namedMain?V`
|
|
20
21
|
export { main } from "${l}";
|
|
21
22
|
`:V`
|
|
22
23
|
import _fn from "${l}";
|
|
@@ -28,7 +29,7 @@ Logs:`));for(let e of n.logEntries.slice(a))C.log(` ${Ut(mr(e))}`);a=n.logEntri
|
|
|
28
29
|
|
|
29
30
|
const $tailor_resolver_body = async (rawInput) => {
|
|
30
31
|
const _caller = ${e};
|
|
31
|
-
const invoker = (${
|
|
32
|
+
const invoker = (${Ce}) ?? _caller;
|
|
32
33
|
const context = { input: rawInput, env: ${JSON.stringify(r)}, caller: _caller, invoker };
|
|
33
34
|
const input = ${n};
|
|
34
35
|
const result = await _internalResolver.body({ ...context, input });
|
|
@@ -43,7 +44,7 @@ Logs:`));for(let e of n.logEntries.slice(a))C.log(` ${Ut(mr(e))}`);a=n.logEntri
|
|
|
43
44
|
const _actor = ${e};
|
|
44
45
|
|
|
45
46
|
const __executor_function = async (args) => {
|
|
46
|
-
const _invoker = ${
|
|
47
|
+
const _invoker = ${Ce} ?? _actor;
|
|
47
48
|
return _internalExecutor.operation.body({ ...args, env: _env, actor: _actor, invoker: _invoker });
|
|
48
49
|
};
|
|
49
50
|
|
|
@@ -55,40 +56,39 @@ Logs:`));for(let e of n.logEntries.slice(a))C.log(` ${Ut(mr(e))}`);a=n.logEntri
|
|
|
55
56
|
const fallbackInvoker = ${n};
|
|
56
57
|
|
|
57
58
|
export async function main(input) {
|
|
58
|
-
const invoker = ${
|
|
59
|
+
const invoker = ${Ce} ?? fallbackInvoker;
|
|
59
60
|
return await ${e}.body(input, { env, invoker });
|
|
60
61
|
}
|
|
61
|
-
`}}}function buildMachinePrincipalExpr(e,t){return JSON.stringify({id:e.id,type:`machine_user`,workspaceId:t,attributes:e.attributes??{},attributeList:e.attributeList})}async function detectFunctionType(t){let{filePath:n,jobName:r}=t,i=await import(
|
|
62
|
+
`}}}function buildMachinePrincipalExpr(e,t){return JSON.stringify({id:e.id,type:`machine_user`,workspaceId:t,attributes:e.attributes??{},attributeList:e.attributeList})}async function detectFunctionType(t){let{filePath:n,jobName:r}=t,i=await import(Ei(n).href),a=oe.safeParse(i.default);if(a.success){let t=i.default.input,n;if(t){let r=t;n={parse:t=>e({...t,fields:r})}}return{type:`resolver`,name:a.data.name,hasInput:t!=null,inputSchema:n,permission:a.data.permission,fields:{input:a.data.input,output:a.data.output}}}let o=Yr.safeParse(Xr(i.default));if(o.success){let{operation:e}=o.data;if(e.kind===`function`||e.kind===`jobFunction`)return{type:`executor`,name:o.data.name}}let s=detectWorkflowJob(i,r);if(s)return s;if(typeof i.default==`function`)return{type:`plain`,name:deriveNameFromPath(n)};if(typeof i.main==`function`)return{type:`plain`,name:deriveNameFromPath(n),namedMain:!0};throw U({code:`FUNCTION_TYPE_UNDETECTED`,message:`Could not detect function type from ${n}.`,details:`The file must have one of:
|
|
62
63
|
- A default-exported resolver (createResolver)
|
|
63
64
|
- A default-exported executor (createExecutor) with function/jobFunction operation
|
|
64
65
|
- A named-exported workflow job (createWorkflowJob)
|
|
65
66
|
- A default-exported function
|
|
66
|
-
- A named-exported "main" function`})}function detectWorkflowJob(e,t){let n=[];for(let[t,r]of Object.entries(e)){if(t==="default")continue;let e=
|
|
67
|
+
- A named-exported "main" function`})}function detectWorkflowJob(e,t){let n=[];for(let[t,r]of Object.entries(e)){if(t==="default")continue;let e=ge.safeParse(r);e.success&&n.push({name:e.data.name,exportName:t})}if(n.length===0)return null;if(t){let e=n.find(e=>e.name===t);if(!e){let e=n.map(e=>` - "${e.name}" (export: ${e.exportName})`).join(`
|
|
67
68
|
`);throw U({code:`WORKFLOW_JOB_NOT_FOUND`,message:`Workflow job "${t}" not found.`,details:`Available jobs:\n${e}`})}return{type:`workflow-job`,name:e.name,exportName:e.exportName}}if(n.length===1){let[e]=n,t=s(e,`workflow job missing`);return{type:`workflow-job`,name:t.name,exportName:t.exportName}}let r=n.map(e=>` - "${e.name}" (export: ${e.exportName})`).join(`
|
|
68
|
-
`);throw U({code:`WORKFLOW_JOB_AMBIGUOUS`,message:`Multiple workflow jobs found.`,details:`Available jobs:\n${r}`,suggestion:`Specify one with --name.`})}function deriveNameFromPath(e){return K.basename(e,K.extname(e))}const
|
|
69
|
-
`);function generateScriptDbTypes(e,t=!1){let n=Object.values(e.tables).map(e=>
|
|
70
|
-
`)}function loadScriptSchemaSnapshot(e){let t=K.join(K.dirname(e),
|
|
69
|
+
`);throw U({code:`WORKFLOW_JOB_AMBIGUOUS`,message:`Multiple workflow jobs found.`,details:`Available jobs:\n${r}`,suggestion:`Specify one with --name.`})}function deriveNameFromPath(e){return K.basename(e,K.extname(e))}const ya=`db.ts`,ba=`db.snapshot.json`,xa=[`/**`,` * Auto-generated Kysely types for one-off scripts in this directory.`," * Generated by `tailor function script` from the selected TailorDB schema.",` *`," * DO NOT EDIT - Re-run `tailor function script` to refresh.",` */`].join(`
|
|
70
|
+
`);function generateScriptDbTypes(e,t=!1){let n=Object.values(e.tables).map(e=>di(e.name,e.fields,t)),r=fi([{namespace:e.namespace,types:n}],t);return`${xa}\n\n${r}`}function isGeneratedScriptDbTypes(e){return e.includes("Generated by `tailor function script`")}function assertGeneratedTypeScript(e,t){let{errors:n}=Ni(K.basename(e),t);if(n.length>0)throw Qr(`Generated ${e} does not parse as TypeScript: ${n.map(e=>e.message).join(`; `)}`)}function generateScriptSkeleton(e){let{getDBImportPath:t,namespace:n}=e;return[`/**`,` * One-off script. Run it on the platform without deploying:`,` *`,` * tailor function run <this file>`,` *`,` * For large tables, batch updates by primary-key range instead of one`,` * statement over the whole table; see the "Performance and Large Tables"`,` * section in @tailor-platform/sdk's docs/services/tailordb-migration.md.`,` */`,``,`import { getDB } from ${JSON.stringify(t)};`,``,`export default async function main() {`,` const db = getDB(${JSON.stringify(n)});`,``,` // A transaction rolls every change back when any statement fails.`,` await db.transaction().execute(async (trx) => {`,` // e.g. await trx.updateTable("MyTable").set({ ... }).where("id", "=", "...").execute();`,` });`,`}`,``].join(`
|
|
71
|
+
`)}function loadScriptSchemaSnapshot(e){let t=K.join(K.dirname(e),ba);if(!Y.existsSync(t))return null;let n;try{n=JSON.parse(Y.readFileSync(t,`utf-8`))}catch(e){throw U({code:`SCRIPT_SNAPSHOT_INVALID`,message:`Failed to parse schema snapshot ${t}: ${e instanceof Error?e.message:e}.`,suggestion:"Re-run `tailor function script` to regenerate it.",cause:e})}let r=n;if(typeof r!=`object`||!r||typeof r.namespace!=`string`||typeof r.tables!=`object`||r.tables===null)throw unexpectedSnapshotShapeError(t);let i=r.source??`remote`;if(i!==`local`&&i!==`remote`)throw unexpectedSnapshotShapeError(t);let a={...r};delete a.source;try{return{snapshotPath:t,source:i,snapshot:Tn(a)}}catch{throw unexpectedSnapshotShapeError(t)}}function unexpectedSnapshotShapeError(e){return U({code:`SCRIPT_SNAPSHOT_INVALID`,message:`Schema snapshot ${e} has an unexpected shape.`,suggestion:"Re-run `tailor function script` to regenerate it."})}async function verifyScriptSchemaSnapshot(e){let{client:t,workspaceId:n,config:r,configArgValue:i,sidecar:a}=e,{snapshot:o}=a,s=o.namespace;if(Fr(r).includes(s)){let{namespaces:t}=await qe({configPath:i,namespaces:[s]}),n=t[0];if(n){let t=Object.fromEntries(Object.values(n.tables).map(e=>[e.name,Re(e)])),r=Ct(generatedContractSnapshot(o),generatedContractSnapshot({...o,tables:t}));if(cn(r))throw schemaDriftError(`the local table definitions`,r,e)}}let c=await Tt(t,n,s),l=Ct(a.source===`local`?generatedContractSnapshot(o):Tn(pickTableFields(o)),a.source===`local`?generatedContractSnapshot(c):Tn(pickTableFields(c)));if(cn(l))throw schemaDriftError(`the deployed schema`,l,e)}function fieldsOnlySnapshot(e){return Tn(pickTableFields(Rr(e)))}function generatedContractSnapshot(e){let t=fieldsOnlySnapshot(e),n=Object.fromEntries(Object.entries(t.tables).map(([t,n])=>{let r=e.tables[t],i=Object.fromEntries(Object.entries(n.fields).map(([e,t])=>[e,preserveGeneratedContract(t,r?.fields[e])]));return[t,{...n,fields:i}]}));return Tn({...t,tables:n})}function preserveGeneratedContract(e,t){let n=e.fields?Object.fromEntries(Object.entries(e.fields).map(([e,n])=>[e,preserveGeneratedContract(n,t?.fields?.[e])])):void 0,r=t?.hooks?.create!==void 0||t?.default!==void 0||t?.optionalOnCreate===!0;return{...e,...n===void 0?{}:{fields:n},...r?{optionalOnCreate:!0}:{}}}function pickTableFields(e){let t=Object.fromEntries(Object.entries(e.tables).map(([e,t])=>[e,{name:t.name,pluralForm:t.pluralForm,fields:t.fields}]));return{...e,tables:t}}function schemaDriftError(e,t,n){let r=[...n.configArgValue===`tailor.config.ts`?[]:[`--config=${n.configArgValue}`],`--workspace-id=${n.workspaceId}`,...n.profileArgValue===void 0?[]:[`--profile=${n.profileArgValue}`]],i=H({command:`tailor`,args:[`function`,`script`,n.scriptArgValue,...n.sidecar.source===`remote`?[`--remote`]:[],...r]}),a=H({command:`tailor`,args:[`function`,`run`,n.scriptArgValue,`--allow-schema-drift`,...r]});return U({code:`SCRIPT_SCHEMA_DRIFT`,message:`Schema drift detected: ${ba} next to the script no longer matches ${e}.`,details:Vn(t),suggestion:`Refresh the generated types with ${i}, or run anyway with ${a}.`})}const Sa=C({name:`run`,aliases:[`test-run`],description:`Run a function on the Tailor Platform server without deploying.`,args:q.object({...M,file:W(q.string(),{positional:!0,description:`Path to the function file`}),name:W(q.string().optional(),{alias:`n`,description:"Workflow job name to run (matches the `name` field of createWorkflowJob)"}),arg:W(q.string().optional(),{alias:`a`,description:`JSON argument to pass to the function`}),"machine-user":W(q.string().optional(),{alias:`m`,description:`Machine user name for authentication. Falls back to the active profile's default machine user.`,env:`TAILOR_PLATFORM_MACHINE_USER_NAME`}),config:W(q.string().default(`tailor.config.ts`),{alias:`c`,description:`Path to SDK config file`}),"allow-schema-drift":W(q.boolean().default(!1),{description:`Run a scaffolded script even when its schema snapshot no longer matches`})}),notes:"You can pass either a source file (`.ts`) or a pre-bundled file (`.js`).\nWhen a `.js` file is provided, detection and bundling are skipped and the file is executed as-is.\n\nA script scaffolded by `function script` with a generated `db.ts` is checked against its `db.snapshot.json` before execution and refused on schema drift; pass `--allow-schema-drift` to run it anyway. The check compares table and field structure; hook and validator code changes are not detected.\n\n`test-run` is a deprecated alias of this command and will be removed in v3.\n\n> [!WARNING]\n> Workflow job `.start()` calls do not work in this mode.\n> Started jobs are not executed; only the target job's `body` function runs in isolation.",examples:[{cmd:`resolvers/add.ts --arg '{"a":1,"b":2}'`,desc:`Run a resolver with input arguments`},{cmd:`workflows/sample.ts --name validate-order`,desc:`Run a specific workflow job by name`},{cmd:`build/resolvers/add.js --arg '{"a":1,"b":2}'`,desc:`Run a pre-bundled .js file directly`}],run:async e=>{invokedViaTestRunAlias(process.argv)&&x.warn("`tailor function test-run` is deprecated and will be removed in v3. Use `tailor function run` instead.");let n=x.jsonMode,r=K.resolve(e.file);if(!Y.existsSync(r))throw U({code:`FILE_NOT_FOUND`,message:`File not found: ${r}`});let{config:i}=await z(e.config),a=resolveAuthNamespace(i.auth),o=await resolveMachineUserName({cliMachineUser:e[`machine-user`],cliMachineUserSource:xr(e[`machine-user`]),profile:e.profile,authConfig:i.auth}),{client:s,workspaceId:c}=await A({profile:e.profile,workspaceId:e[`workspace-id`]}),l=await resolveMachineUser({client:s,workspaceId:c,authNamespace:a,machineUserName:o,authConfig:i.auth}),u=K.relative(process.cwd(),r),d=r.endsWith(`.js`);if(!d){if(e[`allow-schema-drift`])Y.existsSync(K.join(K.dirname(r),`db.snapshot.json`))&&x.warn(`Skipping the schema snapshot check (--allow-schema-drift).`);else{let t=loadScriptSchemaSnapshot(r);t&&(x.info(`Checking the script's schema snapshot for drift...`),await verifyScriptSchemaSnapshot({client:s,workspaceId:c,config:i,configArgValue:e.config,scriptArgValue:e.file,profileArgValue:e.profile,sidecar:t}))}}let f,p,m,h;if(d)p=K.basename(r),f=Y.readFileSync(r,`utf-8`),x.info(`Using pre-bundled script ${S.bold(p)}`);else{x.info(`Detecting function type from ${S.path(u)}`);let t=await detectFunctionType({filePath:r,jobName:e.name});m=t.type,h=t.name,x.info(`Detected: ${S.bold(t.type)} ${S.info(`"${t.name}"`)}`),t.type===`resolver`&&e.arg&&!t.hasInput&&(x.warn(`--arg is ignored because this resolver has no input schema. Define "input" in your resolver to use --arg.`),e.arg=void 0),x.info(`Bundling...`);let n=de(i),a=K.dirname(i.path);({bundledCode:f,scriptName:p}=await bundleForRun({detected:t,sourceFile:r,baseDir:a,defaultPermission:t.type===`resolver`?ue({config:i.resolver,filePath:r,baseDir:a}):void 0,env:i.env??{},inlineSourcemap:n.inlineSourcemap,inlineSourcemapDependencySources:n.inlineSourcemapDependencySources,logLevel:n.logLevel,treeshake:n.treeshake,dateDefault:ce(i),machineUser:l,workspaceId:c})),x.info(`Bundled as ${S.bold(p)}`)}let g=Si(t,{namespace:a,machineUserName:l.name});x.info(`Executing on workspace ${S.dim(c)}...`);let _;if(e.arg!==void 0)try{_=JSON.parse(e.arg)}catch(e){throw U({code:`FUNCTION_ARG_INVALID`,message:`Invalid --arg JSON: ${e instanceof Error?e.message:e}`,command:`function run`,cause:e})}let v=await nt({client:s,workspaceId:c,name:p,code:f,arg:_,invoker:g});if(n)x.out({success:v.success,scriptName:p,functionType:m,functionName:h,logs:v.logs,result:v.result,error:v.error});else{if(v.success?x.success(`Execution succeeded`):x.error(`Execution failed`),v.logs.trim()){x.log(S.bold(`
|
|
71
72
|
Logs:`));for(let e of v.logs.split(`
|
|
72
|
-
`))
|
|
73
|
-
Result:`));try{let e=JSON.parse(v.result);
|
|
73
|
+
`))x.log(` ${e}`)}if(v.result&&v.success){x.log(S.bold(`
|
|
74
|
+
Result:`));try{let e=JSON.parse(v.result);x.log(` ${JSON.stringify(e,null,2).split(`
|
|
74
75
|
`).join(`
|
|
75
|
-
`)}`)}catch{
|
|
76
|
-
Error:`));let e=formatErrorWithSourcemap(v.error,f,process.cwd());e?
|
|
77
|
-
`),m.push(a),h=`./db`}else{if(r)throw U({code:`SCRIPT_EXISTS`,message:`Script already exists: ${K.relative(process.cwd(),t)}.`,suggestion:`It imports the project's generated Kysely types, so there is nothing to refresh.`});let e=resolveKyselyTypesPath(c);h=toImportSpecifier(K.relative(n,e)),Y.existsSync(e)||
|
|
78
|
-
`)}function retryInstruction(e){if(e.loginMode===`machine-user`)return`Then retry the original machine-user login command.`;let t=quoteCommandArg(e.profile);return t?`Then run:\n tailor login --profile ${t}`:`Then retry the browser login with the same profile value.`}function profileUserMismatchError(e){let t=profileUpdateCommand(e),n=retryInstruction(e);return U({code:`PROFILE_USER_MISMATCH`,message:`Profile "${e.profile}" is configured for "${e.oldUser}", but login authenticated "${e.authenticatedUser}".`,details:`The authenticated user has been saved.`,suggestion:`To use it with this profile, run:\n ${t}\n${n}`,context:{profile:e.profile,configuredUser:e.oldUser,authenticatedUser:e.authenticatedUser}})}function shouldUpdateCurrentUser(e,t){return!e||me(t)}const startAuthServer=async(e={})=>{let t=ne(e.platformConfig),n=randomState(),r=await hi(),i=await t.authorizationCode.getAuthorizeUri({redirectUri:da,state:n,codeVerifier:r}).catch(e=>{throw U({code:`LOGIN_AUTHORIZATION_URL_FAILED`,message:`Failed to prepare the login authorization URL: ${Hr(e).message}`,cause:e})});return new Promise((a,o)=>{let handleCallback=async(i,u)=>{try{if(!i.url?.startsWith(`/callback`))throw U({code:`LOGIN_CALLBACK_INVALID`,message:`Invalid callback URL`});let o=`http://${i.headers.host}${i.url}`,l=new URL(o).searchParams.get(`code`);l&&C.registerSecret(l);let d=await t.authorizationCode.getTokenFromCodeRedirect(o,{redirectUri:da,state:n,codeVerifier:r});In({accessToken:d.accessToken,refreshToken:d.refreshToken??void 0});let f=await c(d.accessToken,e.platformConfig),p=await T();await Re(p,f.sub,{accessToken:d.accessToken,refreshToken:d.refreshToken??void 0},new Date(s(d.expiresAt,`token response missing expiresAt`)).toISOString(),{platformConfig:e.platformConfig,email:f.email});let m=getProfileUserMismatch(e,f.email,f.sub);if(m)throw O(p),profileUserMismatchError(m);(e.updateCurrentUser??!0)&&(p.current_user=f.sub),await it(p,f.email,f.sub,e.platformConfig),O(p),u.writeHead(200,{"Content-Type":`application/json`}),u.end(JSON.stringify({status:`ok`,message:`Successfully authenticated. Please close this window.`})),a({user:f.sub,email:f.email})}catch(e){u.writeHead(401),u.end(`Authentication failed`),o(Hr(e))}finally{l.close()}},l=vi.createServer((e,t)=>void handleCallback(e,t)),u=setTimeout(()=>{l.close(),o(U({code:`LOGIN_TIMEOUT`,message:`Login timeout exceeded`}))},3e5);l.on(`close`,()=>{clearTimeout(u)}),l.on(`error`,e=>{o(e)});let openBrowser=async()=>{C.info(`Opening browser for login:\n\n${i}\n`);try{await yi(i)}catch{C.warn(`Failed to open browser automatically. Please open the URL above manually.`)}};l.listen(ua,()=>void openBrowser())})};async function loginAsMachineUser(e){let t=e.clientSecret??await M.password({message:`Client secret`}),n=await _(e.clientId,t,e.platformConfig),r=await T();await Re(r,e.clientId,{accessToken:n.accessToken},new Date(s(n.expiresAt,`token response missing expiresAt`)).toISOString(),{platformConfig:e.platformConfig});let i=getProfileUserMismatch(e,e.clientId);if(i)throw O(r),profileUserMismatchError(i);return(e.updateCurrentUser??!0)&&(r.current_user=e.clientId),O(r),{user:e.clientId,email:null}}const fa=k({name:`login`,description:`Login to Tailor Platform.`,args:q.xor([q.strictObject({profile:W(q.string().optional(),{alias:`p`,description:`Workspace profile whose platform settings should be used for login.`,env:`TAILOR_PLATFORM_PROFILE`})}).describe(`User Login`),q.strictObject({"machine-user":W(q.literal(!0),{description:`Login as a platform machine user.`,required:!0}),"client-id":W(q.string(),{description:`Client ID`,env:`TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID`,required:!0}),"client-secret":W(q.string().optional(),{description:`Client secret`,env:`TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET`}),profile:W(q.string().optional(),{alias:`p`,description:`Workspace profile whose platform settings should be used for login.`,env:`TAILOR_PLATFORM_PROFILE`})}).describe(`Machine User Login`)]),run:async e=>{try{let t,n;if(`profile`in e&&e.profile){let r=(await T()).profiles[e.profile];if(!r)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${e.profile}" not found`});t=Rn(r),n=r.user}let r=shouldUpdateCurrentUser(e.profile,t),i;i=`machine-user`in e?await loginAsMachineUser({clientId:e.clientId,clientSecret:e.clientSecret,profile:e.profile,profileUser:n,platformConfig:t,updateCurrentUser:r,loginMode:`machine-user`}):await startAuthServer({profile:e.profile,profileUser:n,platformConfig:t,updateCurrentUser:r,loginMode:`user`}),C.success(`Successfully logged in to Tailor Platform.`),z({changed:!0,...i})}finally{await h()}}}),pa=k({name:`logout`,description:`Logout from Tailor Platform.`,args:q.strictObject({profile:W(q.string().optional(),{alias:`p`,description:`Workspace profile whose platform settings should be used for logout.`,env:`TAILOR_PLATFORM_PROFILE`})}),run:async e=>{let t=e.profile||process.env.TAILOR_PLATFORM_PROFILE,n=await T(),r=t?n.profiles[t]:void 0;if(t&&!r)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${t}" not found`});let i=r?Rn(r):void 0,a=r?r.user:n.current_user,o=me(i),s=t?{allowLegacyUserKey:!0}:void 0;if(!a){C.info(`You are not logged in.`),z({changed:!1,user:null,revoked:!1});return}let hasDefaultUserToken=()=>sn(n,a,{platformUrl:de}),shouldClearCurrentUser=()=>n.current_user===a&&(o||!jr(n,a))&&!hasDefaultUserToken(),c,l=!1;try{c=await Fe(n,a,i,s)}catch(e){l=!0,C.warn(`Failed to revoke token: ${e instanceof Error?e.message:e}`)}if(!c&&!l){C.info(`You are not logged in.`);let e=shouldClearCurrentUser();e&&(n.current_user=null),O(n),z({changed:e,user:a,revoked:!1});return}let u=!1;if(c)try{let e=ne(i),t=c.refreshToken?`refresh_token`:`access_token`;await e.revoke({accessToken:c.accessToken,refreshToken:c.refreshToken??null,expiresAt:Date.parse(c.userEntry.token_expires_at)},t),u=!0}catch(e){C.warn(`Failed to revoke token: ${e instanceof Error?e.message:e}`)}await Qt(n,a,i,s),shouldClearCurrentUser()&&(n.current_user=null),O(n),C.success(`Successfully logged out from Tailor Platform.`),z({changed:!0,user:a,revoked:u})}}),ma=G({name:`machineuser`,description:`Manage machine users in your Tailor Platform application.`,subCommands:{list:kn,token:Mn},defaultSubCommand:`list`}),ha=G({name:`oauth2client`,description:`Manage OAuth2 clients in your Tailor Platform application.`,subCommands:{list:vr,get:Tn},defaultSubCommand:`list`}),ga=k({name:`open`,description:`Open Tailor Platform Console.`,args:q.strictObject({...j}),run:async e=>{let t=await ct({workspaceId:e[`workspace-id`],profile:e.profile}),{config:n}=await P(e.config),r=n.name,i=`/workspaces/${t}/services/applications/${encodeURIComponent(r)}`,a=await Tr({profile:e.profile,...e[`workspace-id`]===void 0?{}:{allowMissingProfile:!0}}),o=new URL(i,a).toString(),s=C.jsonMode;C.info(`Opening Tailor Platform Console...`);let c=!0;try{await yi(o)}catch{c=!1}if(s){C.out({consoleUrl:o,workspaceId:t,applicationName:r,opened:c});return}c?(C.out(`Console URL: ${o}`),C.out(`Workspace ID: ${t}`),C.out(`Application Name: ${r}`)):C.warn(`Failed to open browser automatically. Please open this URL manually:\n${o}`)}}),_a=G({name:`folder`,description:`Manage organization folders.`,subCommands:{create:mn,delete:$n,get:Fn,list:Yn,update:xn}}),va=G({name:`organization`,description:`Manage Tailor Platform organizations.`,subCommands:{folder:_a,get:ht,list:Vt,tree:Gt,update:Ze},defaultSubCommand:`list`}),ya=/* @__PURE__ */ `api.auth.authconnection.crashreport.deploy.executor.function.generate.init.login.logout.machineuser.oauth2client.open.organization.plugin.profile.query.remove.secret.show.skills.staticwebsite.tailordb.upgrade.user.workflow.workspace`.split(`.`),ba={seed:`@tailor-platform/sdk-plugin-seed`,setup:`@tailor-platform/sdk-plugin-setup`,"tailordb-erd":`@tailor-platform/sdk-plugin-tailordb-erd`},xa=process.platform===`win32`?`;`:`:`;function*ancestorDirs(e){let t=K.resolve(e),n=K.dirname(t);for(;n!==t;)yield t,t=n,n=K.dirname(t);yield t}function windowsExecutableExts(){return(process.env.PATHEXT??`.COM;.EXE;.BAT;.CMD;.PS1`).split(`;`).map(e=>e.trim().toLowerCase()).filter(Boolean)}function isExecutable(e){try{di(e,process.platform===`win32`?fi.F_OK:fi.X_OK)}catch{return!1}if(process.platform===`win32`){let t=K.extname(e).toLowerCase();return t===``||windowsExecutableExts().includes(t)}return!0}function binaryCandidates(e){return process.platform===`win32`?[e,...windowsExecutableExts().map(t=>`${e}${t}`)]:[e]}function pathDirs(){return(process.env.PATH??``).split(xa).filter(Boolean)}function nodeModulesBinDirs(){let e=[];for(let t of ancestorDirs(process.cwd()))e.push(K.join(t,`node_modules`,`.bin`));return e}function findExecutableIn(e,t){let n=binaryCandidates(t);for(let t of e)for(let e of n){let n=K.join(t,e);if(isExecutable(n))return n}}function resolvePlugin(e,t){if(e.includes(`/`)||e.includes(`\\`)||e.includes(`\0`))return null;let n=`${t}-${e}`,r=findExecutableIn(nodeModulesBinDirs(),n);if(r)return{name:e,path:r,source:`node_modules`};let i=findExecutableIn(pathDirs(),n);return i?{name:e,path:i,source:`path`}:null}function stripBinExt(e){if(process.platform!==`win32`)return e;let t=K.extname(e);return t?e.slice(0,-t.length):e}function listPlugins(e){let t=`${e}-`,n=/* @__PURE__ */ new Map,scan=(e,r)=>{for(let i of e){let e;try{e=pi(i)}catch{continue}for(let a of e){let e=stripBinExt(a);if(!e.startsWith(t)||e.length===t.length)continue;let o=e.slice(t.length);if(n.has(o))continue;let s=K.join(i,a);isExecutable(s)&&n.set(o,{name:o,path:s,source:r})}}};return scan(nodeModulesBinDirs(),`node_modules`),scan(pathDirs(),`path`),[...n.values()]}async function resolveActiveUser(e){let t=await T(),n=e?t.profiles[e]?.user:t.current_user;if(n)return t.users[n]?.email??n}async function buildPluginEnv(e={}){let{profile:t}=e,n={},r=process.argv[1];r&&(n.TAILOR_BIN=r);try{let{version:e}=await Wr();e&&(n.TAILOR_VERSION=e)}catch{}let i=Ae();if(i&&(n.TAILOR_CONFIG_PATH=i),e.skipPlatformContext)return n;let a;try{a=await Ie({profile:t,allowMissingProfile:!0})}catch{}n.TAILOR_PLATFORM_URL=fe(a),n.TAILOR_PLATFORM_OAUTH2_CLIENT_ID=he(a);try{n.TAILOR_PLATFORM_WORKSPACE_ID=await ct({profile:t})}catch{}try{let e=await resolveActiveUser(t);e&&(n.TAILOR_PLATFORM_USER=e)}catch{}try{let e=await Or({profile:t});e&&(n.TAILOR_PLATFORM_TOKEN=e)}catch{}return n}function signalToExitCode(e){let t=Si.constants.signals[e];return typeof t==`number`?128+t:1}function buildSpawnTarget(e,t){if(process.platform!==`win32`)return{command:e,args:[...t],shell:!1};let n=K.extname(e).toLowerCase();return n===`.exe`||n===`.com`?{command:e,args:[...t],shell:!1}:n===`.cmd`||n===`.bat`?{command:e,args:[...t],shell:!0}:n===`.ps1`?{command:findExecutableIn(pathDirs(),`pwsh`)??findExecutableIn(pathDirs(),`powershell`)??`powershell`,args:[`-NoProfile`,`-ExecutionPolicy`,`Bypass`,`-File`,e,...t],shell:!1}:{command:findExecutableIn(pathDirs(),`sh`)??`sh`,args:[`-c`,`command "$@"`,`--`,e,...t],shell:!1}}function hasEnvFileFlag(e){for(let t of e){if(t===`--`)return!1;if(t===`--env-file`||t===`-e`||t===`--env-file-if-exists`||t.startsWith(`--env-file=`)||t.startsWith(`-e=`)||t.startsWith(`--env-file-if-exists=`))return!0}return!1}function explicitProfileFromArgs(e){let t;for(let n=0;n<e.length;n++){let r=e[n];if(r===void 0||r===`--`)break;if(r===`--profile`||r===`-p`){let r=e[n+1];r!==void 0&&!r.startsWith(`-`)&&(t=r,n++);continue}r.startsWith(`--profile=`)?t=r.slice(10):r.startsWith(`-p=`)&&(t=r.slice(3))}return t||void 0}function pluginSlug(e,t){return[...e??[],t].join(`-`)}async function dispatchPlugin(e){let t=pluginSlug(e.commandPath,e.name),n=resolvePlugin(t,e.cliName);if(!n)return;let r=explicitProfileFromArgs(e.args)??e.profile,i={...process.env,...await buildPluginEnv({profile:r,skipPlatformContext:hasEnvFileFlag(e.args)})},{command:a,args:o,shell:s}=buildSpawnTarget(n.path,e.args);return await new Promise(n=>{let r=wi(a,o,{stdio:`inherit`,env:i,shell:s});r.on(`error`,r=>{C.error(`Failed to run plugin "${e.cliName}-${t}": ${r.message}`),n(1)}),r.on(`close`,(e,t)=>{n(t?signalToExitCode(t):e??0)})})}async function dispatchPluginWithInstallHint(e){let t=await dispatchPlugin(e);if(t!==void 0)return t;let n=ba[pluginSlug(e.commandPath,e.name)];if(!n)return;let r=[e.cliName,...e.commandPath??[],e.name].join(` `);return C.error(`"${r}" is provided by the ${n} CLI plugin, which is not installed.`),C.info(`Install it with: npm install -D ${n}`),1}const Sa=k({name:`list`,description:"List discovered plugins (executables named `<cli>-<name>` on PATH or node_modules/.bin).",args:q.strictObject({}),run:async()=>{let e=await Wr(),t=Object.keys(e.bin??{})[0]||`tailor`,n=new Set(ya),r=listPlugins(t);if(r.length===0){C.info(V`
|
|
76
|
+
`)}`)}catch{x.log(` ${v.result}`)}}if(v.error&&!v.success){x.log(S.bold(`
|
|
77
|
+
Error:`));let e=formatErrorWithSourcemap(v.error,f,process.cwd());e?x.log(e):x.log(` ${S.error(v.error)}`)}}v.success||process.exit(1)}}),Ca=new Set(mi(q.strictObject(Ge)).fields.filter(e=>e.type!==`boolean`).flatMap(e=>[e.cliName,...e.alias??[]].flatMap(toFlagTokens)));function toFlagTokens(e){return e.length===1?[`-${e}`]:[`--${e}`,`--${gi(e)}`]}function invokedViaTestRunAlias(e){let t=[];for(let n=2;n<e.length&&t.length<2;n++){let r=e[n];if(r===void 0||r===`--`)break;r.startsWith(`-`)?!r.includes(`=`)&&Ca.has(r)&&n++:t.push(r)}return t[0]===`function`&&t[1]===`test-run`}function resolveAuthNamespace(e){if(e?.name)return e.name;throw U({code:`AUTH_CONFIG_REQUIRED`,message:`Auth namespace is required.`,suggestion:`Ensure tailor.config.ts has an auth config.`})}async function resolveMachineUserName(e){let{cliMachineUser:t,cliMachineUserSource:n,profile:r,authConfig:i}=e,a=await ht({machineUser:t,machineUserSource:n,profile:r});if(a)return a;if(i&&!(`external`in i&&i.external)){let e=i.machineUsers;if(e){let t=Object.keys(e);if(t.length>0)return s(t[0],`machine user key missing`)}}throw U({code:`MACHINE_USER_REQUIRED`,message:`Machine user is required.`,suggestion:`Provide --machine-user, set TAILOR_PLATFORM_MACHINE_USER_NAME, set a profile default with 'tailor profile update <profile> --machine-user <name>', or ensure tailor.config.ts has machine users configured.`})}async function resolveMachineUser(e){let{client:t,workspaceId:n,authNamespace:r,machineUserName:i,authConfig:a}=e,o=`00000000-0000-0000-0000-000000000000`;try{let{machineUser:e}=await t.getAuthMachineUser({workspaceId:n,authNamespace:r,name:i});e?.id&&(o=e.id)}catch{x.debug(`Could not fetch machine user "${i}" from server, using nil UUID`)}let s=a?.machineUsers?.[i],c=null,l=[];if(s&&typeof s==`object`){let e=s;c=e.attributes??null,l=e.attributeList??[]}return{name:i,id:o,attributes:c,attributeList:l}}const wa=C({name:`script`,description:"Scaffold a one-off script to run with `function run`.",args:q.object({...M,...it,file:W(q.string(),{positional:!0,description:`Path to create the script at (must end with .ts)`}),namespace:W(q.string().optional(),{description:`Target TailorDB namespace (required when the config does not pin one)`}),remote:W(q.boolean().default(!1),{description:`Generate script-scoped DB types from the deployed schema`})}),notes:"The scaffolded script is a plain default-exported function; execute it with `tailor function run <file>`.\n\nBy default, when the project configures `kyselyTypePlugin`, the skeleton imports `getDB()` from the plugin's generated types. Without the plugin, the command uses the namespace's local table definitions to write a script-scoped `db.ts` plus a `db.snapshot.json` next to the script; `function run` refuses to run the script when that snapshot no longer matches the deployed or locally defined table and field structure.\n\nPass `--remote` to generate the script-scoped files from the deployed schema instead, even when `kyselyTypePlugin` is configured. This is required for an external namespace. Re-running the command refreshes `db.ts` and `db.snapshot.json` from the selected source and leaves the script itself untouched.",examples:[{cmd:`scripts/fix-prices.ts`,desc:`Scaffold a one-off script (single-namespace project)`},{cmd:`scripts/fix-prices.ts --namespace tailordb`,desc:`Scaffold a script targeting a specific namespace`},{cmd:`scripts/fix-prices.ts --namespace shared --remote`,desc:`Scaffold from a deployed or external namespace`}],run:async e=>{let t=K.resolve(e.file);if(!t.endsWith(`.ts`))throw U({code:`SCRIPT_PATH_INVALID`,message:`Script path must end with .ts: ${e.file}`,command:`function script`});let n=K.dirname(t),r=Y.existsSync(t),i=K.join(n,ya),a=K.join(n,ba);if(t===i)throw U({code:`SCRIPT_PATH_INVALID`,message:`${ya} is reserved for the generated Kysely types written next to the script. Choose a different script file name.`,command:`function script`});let{config:o,plugins:c}=await z(e.config),l=c.find(e=>e.id===pi),u=Y.existsSync(a);if(e.remote&&l!==void 0&&r&&!u)throw U({code:`SCRIPT_EXISTS`,message:`Script already exists: ${K.relative(process.cwd(),t)}.`,suggestion:`Scaffold --remote at a new path so the generated script imports its script-scoped db.ts.`});let d=e.remote||l===void 0||u,f;if(d)try{f=loadScriptSchemaSnapshot(t)?.snapshot.namespace}catch{}let p=resolveNamespace({config:o,explicit:e.namespace,sidecarNamespace:f,remote:e.remote});if(f!==void 0&&f!==p)throw U({code:`SCRIPT_NAMESPACE_MISMATCH`,message:`This directory's generated types target namespace "${f}" (${ba}).`,suggestion:`Scaffold scripts for namespace "${p}" in a separate directory.`});let m=[],h,g;if(d){let t;if(e.remote){let{client:n,workspaceId:r}=await A({profile:e.profile,workspaceId:e[`workspace-id`]});g=r,x.info(`Fetching deployed schema of namespace ${S.bold(p)}...`),t=await Tt(n,r,p)}else{x.info(`Loading local definitions of namespace ${S.bold(p)}...`);let{namespaces:n}=await qe({configPath:e.config,namespaces:[p]}),r=s(n[0],`namespace ${p}`);t=Ve(r.tables,p)}if(Object.keys(t.tables).length===0){let t=e.remote?`deployed tables in workspace ${s(g,`workspace ID`)}`:`locally defined tables`;throw U({code:`SCRIPT_SCHEMA_NOT_FOUND`,message:`Namespace "${p}" has no ${t}.`})}if(Y.existsSync(i)&&!isGeneratedScriptDbTypes(Y.readFileSync(i,`utf-8`)))throw U({code:`GENERATED_TYPES_NOT_OWNED`,message:`Refusing to overwrite ${K.relative(process.cwd(),i)}: it was not generated by \`tailor function script\`.`});let r=generateScriptDbTypes(t,st(c,`@tailor-platform/kysely-type`)?.temporal??!1);assertGeneratedTypeScript(i,r),Y.mkdirSync(n,{recursive:!0}),Y.writeFileSync(i,r),m.push(i),Y.writeFileSync(a,JSON.stringify({...t,source:e.remote?`remote`:`local`},null,2)+`
|
|
78
|
+
`),m.push(a),h=`./db`}else{if(r)throw U({code:`SCRIPT_EXISTS`,message:`Script already exists: ${K.relative(process.cwd(),t)}.`,suggestion:`It imports the project's generated Kysely types, so there is nothing to refresh.`});let e=resolveKyselyTypesPath(c);h=toImportSpecifier(K.relative(n,e)),Y.existsSync(e)||x.warn(`Generated Kysely types not found at ${S.path(K.relative(process.cwd(),e))}. Run \`tailor generate\` before executing the script.`)}if(!r){let e=generateScriptSkeleton({getDBImportPath:h,namespace:p});assertGeneratedTypeScript(t,e),Y.mkdirSync(n,{recursive:!0}),Y.writeFileSync(t,e),m.unshift(t)}let _=[`function`,`run`,K.relative(process.cwd(),t)];e.config!==`tailor.config.ts`&&_.push(`--config=${e.config}`);let v=g??e[`workspace-id`];if(v!==void 0&&_.push(`--workspace-id=${v}`),e.profile!==void 0&&_.push(`--profile=${e.profile}`),x.jsonMode)x.out({script:t,created:m,namespace:p,usesGeneratedDbTypes:d});else{r&&x.info(`Script already exists; refreshed generated types only.`);for(let e of m)x.success(`Created ${S.path(K.relative(process.cwd(),e))}`);x.info(`Next: edit the script, then run ${H({command:`tailor`,args:_})}`)}}});function resolveNamespace(e){let{config:t,explicit:n,sidecarNamespace:r,remote:i}=e,a=on(t),o=Fr(t),s=i?a:o;if(n){if(!i&&!o.includes(n))throw U({code:`SCRIPT_NAMESPACE_REQUIRES_REMOTE`,message:`Namespace "${n}" is not owned by the config and requires --remote.`,command:`function script`});return n}if(r!==void 0){if(!i&&!o.includes(r))throw U({code:`SCRIPT_NAMESPACE_REQUIRES_REMOTE`,message:`Namespace "${r}" is not owned by the config and requires --remote.`,command:`function script`});return r}if(s.length===1){let e=s[0];if(e!==void 0)return e}throw s.length>1?U({code:`TAILORDB_NAMESPACE_REQUIRED`,message:`Multiple TailorDB namespaces are defined (${s.join(`, `)}). Specify one with --namespace.`,command:`function script`}):!i&&a.length>0?U({code:`TAILORDB_NAMESPACE_NOT_CONFIGURED`,message:`No owned TailorDB namespace is defined in the config. External namespaces require --remote: ${a.join(`, `)}.`}):U({code:`TAILORDB_NAMESPACE_NOT_CONFIGURED`,message:`No TailorDB namespace is defined in the config.`})}function resolveKyselyTypesPath(e){let t=st(e,`@tailor-platform/kysely-type`)?.distPath??`./generated/tailordb.ts`;if(t.length===0)throw U({code:`KYSELY_TYPE_PLUGIN_INVALID`,message:`kyselyTypePlugin is configured without a distPath; cannot locate getDB().`});return K.resolve(t)}function toImportSpecifier(e){let t=e.replace(/\.ts$/,``);return t.startsWith(`.`)?t:`./${t}`}const Ta=G({name:`function`,description:`Manage functions`,subCommands:{get:Hr,list:Wr,logs:va,run:Sa,script:wa},defaultSubCommand:`list`}),Ea=C({name:`generate`,description:`Generate files using Tailor configuration.`,args:q.strictObject({config:W(q.string().default(`tailor.config.ts`),{alias:`c`,description:`Path to SDK config file`})}),run:async e=>{let{initTelemetry:t}=await import(`../telemetry-DpkFGBmu.mjs`);await t(),await tr({configPath:e.config})}}),detectPackageManager=()=>{let e=[`npm`,`yarn`,`pnpm`,`bun`],t=process.env.npm_config_user_agent;if(!t)return;let[n]=t.split(`/`);if(e.includes(n))return n},Da=C({name:`init`,description:`Initialize a new project using create-sdk.`,args:q.strictObject({name:W(q.string().optional(),{positional:!0,description:`Project name`}),template:W(q.string().optional(),{alias:`t`,description:`Template name`})}),run:async e=>{let t=await ni(),n=t.version&&t.version!==`0.0.0`?t.version:`latest`,r=detectPackageManager();r||=(x.warn(`Could not detect package manager, defaulting to npm`),`npm`);let i=[`create`,`@tailor-platform/sdk@${n}`,...e.name?[e.name]:[],...r===`npm`?[`--`]:[],...e.template?[`--template`,e.template]:[]];x.log(`Running: ${r} ${i.join(` `)}`);let a=Li(r,i,{stdio:`inherit`}),o={command:r,args:i};if(a.error)throw U({code:`INIT_SPAWN_FAILED`,message:`Failed to run ${r}: ${a.error.message}`,suggestion:`Check that ${r} is installed and executable.`,command:`init`,context:o,cause:a.error});if(a.status!==0)throw U({code:`INIT_FAILED`,message:a.signal===null?`${r} create exited with code ${a.status}.`:`${r} create was terminated by ${a.signal}.`,command:`init`,context:{...o,exitCode:a.status??void 0,signal:a.signal??void 0}})}}),Oa=8085,ka=`http://localhost:${Oa}/callback`;function randomState(){return Oi.randomBytes(32).toString(`base64url`)}function getProfileUserMismatch(e,t,n){if(e.profile&&e.profileUser&&t!==e.profileUser&&n!==e.profileUser)return{profile:e.profile,oldUser:e.profileUser,authenticatedUser:t,loginMode:e.loginMode??`user`}}function quoteCommandArg(e,t=process.platform){return t===`win32`?/^[A-Za-z0-9_./:@+=,-]+$/.test(e)?e:void 0:`'${e.replaceAll(`'`,`'\\''`)}'`}function profileUpdateCommand(e){let t=quoteCommandArg(e.profile),n=quoteCommandArg(e.authenticatedUser);return t&&n?`tailor profile update --user ${n} -- ${t}`:[`tailor profile update --user <authenticated-user> -- <profile>`,`profile = ${JSON.stringify(e.profile)}`,`authenticated user = ${JSON.stringify(e.authenticatedUser)}`].join(`
|
|
79
|
+
`)}function retryInstruction(e){if(e.loginMode===`machine-user`)return`Then retry the original machine-user login command.`;let t=quoteCommandArg(e.profile);return t?`Then run:\n tailor login --profile ${t}`:`Then retry the browser login with the same profile value.`}function profileUserMismatchError(e){let t=profileUpdateCommand(e),n=retryInstruction(e);return U({code:`PROFILE_USER_MISMATCH`,message:`Profile "${e.profile}" is configured for "${e.oldUser}", but login authenticated "${e.authenticatedUser}".`,details:`The authenticated user has been saved.`,suggestion:`To use it with this profile, run:\n ${t}\n${n}`,context:{profile:e.profile,configuredUser:e.oldUser,authenticatedUser:e.authenticatedUser}})}function shouldUpdateCurrentUser(e,t){return!e||le(t)}const startAuthServer=async(e={})=>{let t=fe(e.platformConfig),n=randomState(),r=await Di(),i=await t.authorizationCode.getAuthorizeUri({redirectUri:ka,state:n,codeVerifier:r}).catch(e=>{throw U({code:`LOGIN_AUTHORIZATION_URL_FAILED`,message:`Failed to prepare the login authorization URL: ${ei(e).message}`,cause:e})});return new Promise((a,o)=>{let handleCallback=async(i,l)=>{try{if(!i.url?.startsWith(`/callback`))throw U({code:`LOGIN_CALLBACK_INVALID`,message:`Invalid callback URL`});let o=`http://${i.headers.host}${i.url}`,c=new URL(o).searchParams.get(`code`);c&&x.registerSecret(c);let u=await t.authorizationCode.getTokenFromCodeRedirect(o,{redirectUri:ka,state:n,codeVerifier:r});Ue({accessToken:u.accessToken,refreshToken:u.refreshToken??void 0});let d=await _e(u.accessToken,e.platformConfig),f=await w();await Ae(f,d.sub,{accessToken:u.accessToken,refreshToken:u.refreshToken??void 0},new Date(s(u.expiresAt,`token response missing expiresAt`)).toISOString(),{platformConfig:e.platformConfig,email:d.email});let p=getProfileUserMismatch(e,d.email,d.sub);if(p)throw T(f),profileUserMismatchError(p);(e.updateCurrentUser??!0)&&(f.current_user=d.sub),await Ze(f,d.email,d.sub,e.platformConfig),T(f),l.writeHead(200,{"Content-Type":`application/json`}),l.end(JSON.stringify({status:`ok`,message:`Successfully authenticated. Please close this window.`})),a({user:d.sub,email:d.email})}catch(e){l.writeHead(401),l.end(`Authentication failed`),o(ei(e))}finally{c.close()}},c=Ai.createServer((e,t)=>void handleCallback(e,t)),l=setTimeout(()=>{c.close(),o(U({code:`LOGIN_TIMEOUT`,message:`Login timeout exceeded`}))},3e5);c.on(`close`,()=>{clearTimeout(l)}),c.on(`error`,e=>{o(e)});let openBrowser=async()=>{x.info(`Opening browser for login:\n\n${i}\n`);try{await ji(i)}catch{x.warn(`Failed to open browser automatically. Please open the URL above manually.`)}};c.listen(Oa,()=>void openBrowser())})};async function loginAsMachineUser(e){let t=e.clientSecret??await N.password({message:`Client secret`}),n=await pe(e.clientId,t,e.platformConfig),r=await w();await Ae(r,e.clientId,{accessToken:n.accessToken},new Date(s(n.expiresAt,`token response missing expiresAt`)).toISOString(),{platformConfig:e.platformConfig});let i=getProfileUserMismatch(e,e.clientId);if(i)throw T(r),profileUserMismatchError(i);return(e.updateCurrentUser??!0)&&(r.current_user=e.clientId),T(r),{user:e.clientId,email:null}}const Aa=C({name:`login`,description:`Login to Tailor Platform.`,args:q.xor([q.strictObject({profile:W(q.string().optional(),{alias:`p`,description:`Workspace profile whose platform settings should be used for login.`,env:`TAILOR_PLATFORM_PROFILE`})}).describe(`User Login`),q.strictObject({"machine-user":W(q.literal(!0),{description:`Login as a platform machine user.`,required:!0}),"client-id":W(q.string(),{description:`Client ID`,env:`TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID`,required:!0}),"client-secret":W(q.string().optional(),{description:`Client secret`,env:`TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET`}),profile:W(q.string().optional(),{alias:`p`,description:`Workspace profile whose platform settings should be used for login.`,env:`TAILOR_PLATFORM_PROFILE`})}).describe(`Machine User Login`)]),run:async e=>{try{let t,n;if(`profile`in e&&e.profile){let r=(await w()).profiles[e.profile];if(!r)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${e.profile}" not found`});t=pt(r),n=r.user}let r=shouldUpdateCurrentUser(e.profile,t),i;i=`machine-user`in e?await loginAsMachineUser({clientId:e.clientId,clientSecret:e.clientSecret,profile:e.profile,profileUser:n,platformConfig:t,updateCurrentUser:r,loginMode:`machine-user`}):await startAuthServer({profile:e.profile,profileUser:n,platformConfig:t,updateCurrentUser:r,loginMode:`user`}),x.success(`Successfully logged in to Tailor Platform.`),k({changed:!0,...i})}finally{await ie()}}}),ja=C({name:`logout`,description:`Logout from Tailor Platform.`,args:q.strictObject({profile:W(q.string().optional(),{alias:`p`,description:`Workspace profile whose platform settings should be used for logout.`,env:`TAILOR_PLATFORM_PROFILE`})}),run:async e=>{let t=e.profile||process.env.TAILOR_PLATFORM_PROFILE,n=await w(),r=t?n.profiles[t]:void 0;if(t&&!r)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${t}" not found`});let i=r?pt(r):void 0,a=r?r.user:n.current_user,o=le(i),s=t?{allowLegacyUserKey:!0}:void 0;if(!a){x.info(`You are not logged in.`),k({changed:!1,user:null,revoked:!1});return}let hasDefaultUserToken=()=>Ne(n,a,{platformUrl:ae}),shouldClearCurrentUser=()=>n.current_user===a&&(o||!kt(n,a))&&!hasDefaultUserToken(),c,l=!1;try{c=await ke(n,a,i,s)}catch(e){l=!0,x.warn(`Failed to revoke token: ${e instanceof Error?e.message:e}`)}if(!c&&!l){x.info(`You are not logged in.`);let e=shouldClearCurrentUser();e&&(n.current_user=null),T(n),k({changed:e,user:a,revoked:!1});return}let u=!1;if(c)try{let e=fe(i),t=c.refreshToken?`refresh_token`:`access_token`;await e.revoke({accessToken:c.accessToken,refreshToken:c.refreshToken??null,expiresAt:Date.parse(c.userEntry.token_expires_at)},t),u=!0}catch(e){x.warn(`Failed to revoke token: ${e instanceof Error?e.message:e}`)}await fn(n,a,i,s),shouldClearCurrentUser()&&(n.current_user=null),T(n),x.success(`Successfully logged out from Tailor Platform.`),k({changed:!0,user:a,revoked:u})}}),Ma=G({name:`machineuser`,description:`Manage machine users in your Tailor Platform application.`,subCommands:{list:Nn,token:Cn},defaultSubCommand:`list`}),Na=G({name:`oauth2client`,description:`Manage OAuth2 clients in your Tailor Platform application.`,subCommands:{list:fr,get:yn},defaultSubCommand:`list`}),Pa=C({name:`open`,description:`Open Tailor Platform Console.`,args:q.strictObject({...E}),run:async e=>{let t=await Gn({workspaceId:e[`workspace-id`],profile:e.profile}),{config:n}=await z(e.config),r=n.name,i=`/workspaces/${t}/services/applications/${encodeURIComponent(r)}`,a=await Le({profile:e.profile,...e[`workspace-id`]===void 0?{}:{allowMissingProfile:!0}}),o=new URL(i,a).toString(),s=x.jsonMode;x.info(`Opening Tailor Platform Console...`);let c=!0;try{await ji(o)}catch{c=!1}s?x.out({consoleUrl:o,workspaceId:t,applicationName:r,opened:c}):c?(x.out(`Console URL: ${o}`),x.out(`Workspace ID: ${t}`),x.out(`Application Name: ${r}`)):x.warn(`Failed to open browser automatically. Please open this URL manually:\n${o}`)}}),Fa=G({name:`folder`,description:`Manage organization folders.`,subCommands:{create:Wn,delete:sr,get:On,list:bt,update:qt}}),Ia=G({name:`organization`,description:`Manage Tailor Platform organizations.`,subCommands:{folder:Fa,get:et,list:rt,tree:We,update:Je},defaultSubCommand:`list`}),La=/* @__PURE__ */ `api.auth.authconnection.crashreport.data.deploy.executor.function.generate.init.login.logout.machineuser.oauth2client.open.organization.plugin.profile.query.remove.secret.show.skills.staticwebsite.tailordb.upgrade.user.workflow.workspace`.split(`.`),Ra={seed:`@tailor-platform/sdk-plugin-seed`,setup:`@tailor-platform/sdk-plugin-setup`,"tailordb-erd":`@tailor-platform/sdk-plugin-tailordb-erd`},za=process.platform===`win32`?`;`:`:`;function*ancestorDirs(e){let t=K.resolve(e),n=K.dirname(t);for(;n!==t;)yield t,t=n,n=K.dirname(t);yield t}function windowsExecutableExts(){return(process.env.PATHEXT??`.COM;.EXE;.BAT;.CMD;.PS1`).split(`;`).map(e=>e.trim().toLowerCase()).filter(Boolean)}function isExecutable(e){try{Ci(e,process.platform===`win32`?wi.F_OK:wi.X_OK)}catch{return!1}if(process.platform===`win32`){let t=K.extname(e).toLowerCase();return t===``||windowsExecutableExts().includes(t)}return!0}function binaryCandidates(e){return process.platform===`win32`?[e,...windowsExecutableExts().map(t=>`${e}${t}`)]:[e]}function pathDirs(){return(process.env.PATH??``).split(za).filter(Boolean)}function nodeModulesBinDirs(){let e=[];for(let t of ancestorDirs(process.cwd()))e.push(K.join(t,`node_modules`,`.bin`));return e}function findExecutableIn(e,t){let n=binaryCandidates(t);for(let t of e)for(let e of n){let n=K.join(t,e);if(isExecutable(n))return n}}function resolvePlugin(e,t){if(e.includes(`/`)||e.includes(`\\`)||e.includes(`\0`))return null;let n=`${t}-${e}`,r=findExecutableIn(nodeModulesBinDirs(),n);if(r)return{name:e,path:r,source:`node_modules`};let i=findExecutableIn(pathDirs(),n);return i?{name:e,path:i,source:`path`}:null}function stripBinExt(e){if(process.platform!==`win32`)return e;let t=K.extname(e);return t?e.slice(0,-t.length):e}function listPlugins(e){let t=`${e}-`,n=/* @__PURE__ */ new Map,scan=(e,r)=>{for(let i of e){let e;try{e=Ti(i)}catch{continue}for(let a of e){let e=stripBinExt(a);if(!e.startsWith(t)||e.length===t.length)continue;let o=e.slice(t.length);if(n.has(o))continue;let s=K.join(i,a);isExecutable(s)&&n.set(o,{name:o,path:s,source:r})}}};return scan(nodeModulesBinDirs(),`node_modules`),scan(pathDirs(),`path`),[...n.values()]}async function resolveActiveUser(e){let t=await w(),n=e?t.profiles[e]?.user:t.current_user;if(n)return t.users[n]?.email??n}async function buildPluginEnv(e={}){let{profile:t}=e,n={},r=process.argv[1];r&&(n.TAILOR_BIN=r);try{let{version:e}=await ni();e&&(n.TAILOR_VERSION=e)}catch{}let i=Be();if(i&&(n.TAILOR_CONFIG_PATH=i),e.skipPlatformContext)return n;let a;try{a=await Jn({profile:t,allowMissingProfile:!0})}catch{}n.TAILOR_PLATFORM_URL=ye(a),n.TAILOR_PLATFORM_OAUTH2_CLIENT_ID=se(a);try{n.TAILOR_PLATFORM_WORKSPACE_ID=await Gn({profile:t})}catch{}try{let e=await resolveActiveUser(t);e&&(n.TAILOR_PLATFORM_USER=e)}catch{}try{let e=await Lr({profile:t});e&&(n.TAILOR_PLATFORM_TOKEN=e)}catch{}return n}function signalToExitCode(e){let t=Pi.constants.signals[e];return typeof t==`number`?128+t:1}function buildSpawnTarget(e,t){if(process.platform!==`win32`)return{command:e,args:[...t],shell:!1};let n=K.extname(e).toLowerCase();return n===`.exe`||n===`.com`?{command:e,args:[...t],shell:!1}:n===`.cmd`||n===`.bat`?{command:e,args:[...t],shell:!0}:n===`.ps1`?{command:findExecutableIn(pathDirs(),`pwsh`)??findExecutableIn(pathDirs(),`powershell`)??`powershell`,args:[`-NoProfile`,`-ExecutionPolicy`,`Bypass`,`-File`,e,...t],shell:!1}:{command:findExecutableIn(pathDirs(),`sh`)??`sh`,args:[`-c`,`command "$@"`,`--`,e,...t],shell:!1}}function hasEnvFileFlag(e){for(let t of e){if(t===`--`)return!1;if(t===`--env-file`||t===`-e`||t===`--env-file-if-exists`||t.startsWith(`--env-file=`)||t.startsWith(`-e=`)||t.startsWith(`--env-file-if-exists=`))return!0}return!1}function explicitProfileFromArgs(e){let t;for(let n=0;n<e.length;n++){let r=e[n];if(r===void 0||r===`--`)break;if(r===`--profile`||r===`-p`){let r=e[n+1];r!==void 0&&!r.startsWith(`-`)&&(t=r,n++)}else r.startsWith(`--profile=`)?t=r.slice(10):r.startsWith(`-p=`)&&(t=r.slice(3))}return t||void 0}function pluginSlug(e,t){return[...e??[],t].join(`-`)}async function dispatchPlugin(e){let t=pluginSlug(e.commandPath,e.name),n=resolvePlugin(t,e.cliName);if(!n)return;let r=explicitProfileFromArgs(e.args)??e.profile,i={...process.env,...await buildPluginEnv({profile:r,skipPlatformContext:hasEnvFileFlag(e.args)})},{command:a,args:o,shell:s}=buildSpawnTarget(n.path,e.args);return await new Promise(n=>{let r=Ii(a,o,{stdio:`inherit`,env:i,shell:s});r.on(`error`,r=>{x.error(`Failed to run plugin "${e.cliName}-${t}": ${r.message}`),n(1)}),r.on(`close`,(e,t)=>{n(t?signalToExitCode(t):e??0)})})}async function dispatchPluginWithInstallHint(e){let t=await dispatchPlugin(e);if(t!==void 0)return t;let n=Ra[pluginSlug(e.commandPath,e.name)];if(!n)return;let r=[e.cliName,...e.commandPath??[],e.name].join(` `);return x.error(`"${r}" is provided by the ${n} CLI plugin, which is not installed.`),x.info(`Install it with: npm install -D ${n}`),1}const Ba=C({name:`list`,description:"List discovered plugins (executables named `<cli>-<name>` on PATH or node_modules/.bin).",args:q.strictObject({}),run:async()=>{let e=await ni(),t=Object.keys(e.bin??{})[0]||`tailor`,n=new Set(La),r=listPlugins(t);if(r.length===0){x.info(V`
|
|
79
80
|
No plugins found.
|
|
80
81
|
Install an executable named "${t}-<name>" on your PATH or in node_modules/.bin,
|
|
81
82
|
then run it with "${t} <name>".
|
|
82
|
-
`),
|
|
83
|
+
`),x.jsonMode&&x.out([]);return}let i=r.map(e=>({name:e.name,source:e.source,path:e.path,shadowed:n.has(e.name)}));x.out(i);for(let e of i)e.shadowed&&x.warn(`Plugin "${t}-${e.name}" is shadowed by the builtin "${t} ${e.name}" command and will not be dispatched.`)}}),Va=G({name:`plugin`,description:`Manage and inspect CLI plugins (beta).`,subCommands:{list:Ba},defaultSubCommand:`list`}),Ha=C({name:`create`,description:`Create a new profile.`,args:q.strictObject({name:W(q.string(),{positional:!0,description:`Profile name`}),user:W(q.string(),{alias:`u`,description:`User email address or machine user client ID`}),"workspace-id":W(q.string(),{alias:`w`,description:`Workspace ID`}),permission:W(q.enum([`write`,`read`]).default(`write`),{description:`Profile permission. 'read' blocks all write commands while the profile is active.`}),"machine-user":W(q.string().optional(),{alias:`m`,description:`Default machine user name for application-data commands (query, workflow start, function run, machineuser token).`}),"machine-user-override":W(q.enum([`allow`,`deny`]).optional(),{description:`Whether the command line or TAILOR_PLATFORM_MACHINE_USER_NAME may override the profile's machine user. 'deny' requires --machine-user.`}),"platform-url":W(q.url().optional(),{description:`Platform API base URL for this profile.`,env:`TAILOR_PLATFORM_URL`}),"oauth2-client-id":W(q.string().optional(),{description:`OAuth2 client ID for logging in to this profile's platform.`,env:`TAILOR_PLATFORM_OAUTH2_CLIENT_ID`}),"console-url":W(q.url().optional(),{description:`Console base URL for this profile.`,env:`TAILOR_PLATFORM_CONSOLE_URL`})}),run:async e=>{if(e[`machine-user-override`]===`deny`&&!e[`machine-user`])throw U({code:`PROFILE_OPTIONS_INVALID`,message:`--machine-user-override deny requires --machine-user.`,command:`profile create`});let t=await w();if(t.profiles[e.name])throw U({code:`PROFILE_EXISTS`,message:`Profile "${e.name}" already exists.`});let n={...e[`platform-url`]?{platformUrl:e[`platform-url`]}:{},...e[`oauth2-client-id`]?{oauth2ClientId:e[`oauth2-client-id`]}:{},...e[`console-url`]?{consoleUrl:e[`console-url`]}:{}},r=Object.keys(n).length>0?n:void 0,{accessToken:i,user:a}=await Br(t,e.user,r),o=await xe(i,r);if(!(await _(async(e,t)=>{let{workspaces:n,nextPageToken:r}=await o.listWorkspaces({pageToken:e,pageSize:t});return[n,r]})).find(t=>t.id===e[`workspace-id`]))throw U({code:`WORKSPACE_NOT_FOUND`,message:`Workspace "${e[`workspace-id`]}" not found.`});t.profiles[e.name]={user:a,workspace_id:e[`workspace-id`],...e.permission===`read`?{readonly:!0}:{},...e[`machine-user`]?{machine_user:e[`machine-user`]}:{},...e[`machine-user-override`]===`deny`?{machine_user_override:`deny`}:{},...e[`platform-url`]?{platform_url:e[`platform-url`]}:{},...e[`oauth2-client-id`]?{oauth2_client_id:e[`oauth2-client-id`]}:{},...e[`console-url`]?{console_url:e[`console-url`]}:{}},T(t),e.json||x.success(`Profile "${e.name}" created successfully.`);let s={name:e.name,user:a,workspaceId:e[`workspace-id`],permission:e.permission,...e[`machine-user`]?{machineUser:e[`machine-user`],machineUserOverride:e[`machine-user-override`]??`allow`}:{},...e[`platform-url`]?{platformUrl:e[`platform-url`]}:{},...e[`oauth2-client-id`]?{oauth2ClientId:e[`oauth2-client-id`]}:{},...e[`console-url`]?{consoleUrl:e[`console-url`]}:{}};x.out(s)}}),Ua=C({name:`delete`,description:`Delete a profile.`,args:q.strictObject({name:W(q.string(),{positional:!0,description:`Profile name`})}),run:async e=>{let t=await w();if(!t.profiles[e.name])throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${e.name}" not found.`});delete t.profiles[e.name],T(t),x.success(`Profile "${e.name}" deleted successfully.`),k({changed:!0,name:e.name})}}),Wa=C({name:`list`,description:`List all profiles.`,args:q.strictObject({}),run:async()=>{let e=await w(),t=x.jsonMode,n=Object.entries(e.profiles);if(n.length===0){x.info(V`
|
|
83
84
|
No profiles found.
|
|
84
85
|
Please create a profile first using 'tailor profile create' command.
|
|
85
|
-
`),t&&C.out([]);return}let r=n.map(([e,t])=>{let n=s(t,`profile entry "${e}" is undefined`);return{name:e,user:n.user,workspaceId:n.workspace_id,permission:n.readonly===!0?`read`:`write`,...n.machine_user?{machineUser:n.machine_user,machineUserOverride:n.machine_user_override??`allow`}:{},...n.platform_url?{platformUrl:n.platform_url}:{},...n.oauth2_client_id?{oauth2ClientId:n.oauth2_client_id}:{},...n.console_url?{consoleUrl:n.console_url}:{}}});C.out(r)}}),Da=k({name:`update`,description:`Update profile properties.`,args:q.strictObject({name:W(q.string(),{positional:!0,description:`Profile name`}),user:W(q.string().optional(),{alias:`u`,description:`New user email address or machine user client ID`}),"workspace-id":W(q.string().optional(),{alias:`w`,description:`New workspace ID`}),permission:W(q.enum([`write`,`read`]).optional(),{description:`Profile permission. 'read' blocks all write commands; 'write' lifts the restriction.`}),"machine-user":W(q.string().optional(),{alias:`m`,description:`Default machine user name for application-data commands (query, workflow start, function run, machineuser token). Pass an empty string to clear.`}),"machine-user-override":W(q.enum([`allow`,`deny`]).optional(),{description:`Whether the command line or TAILOR_PLATFORM_MACHINE_USER_NAME may override the profile's machine user. 'deny' requires --machine-user; 'allow' lifts the restriction.`}),"platform-url":W(q.union([q.url(),q.literal(``)]).optional(),{description:`Platform API base URL for this profile. Pass an empty string to clear.`}),"oauth2-client-id":W(q.string().optional(),{description:`OAuth2 client ID for logging in to this profile's platform. Pass an empty string to clear.`}),"console-url":W(q.union([q.url(),q.literal(``)]).optional(),{description:`Console base URL for this profile. Pass an empty string to clear.`})}),run:async e=>{let t=await T(),n=t.profiles[e.name];if(!n)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${e.name}" not found.`});if(!e.user&&!e[`workspace-id`]&&e.permission===void 0&&e[`machine-user`]===void 0&&e[`machine-user-override`]===void 0&&e[`platform-url`]===void 0&&e[`oauth2-client-id`]===void 0&&e[`console-url`]===void 0)throw U({code:`PROFILE_UPDATE_EMPTY`,message:`Please provide at least one property to update.`,command:`profile update`});let r=n.user,i=e.user||r,a=n.workspace_id,o=e[`workspace-id`]||a,s=i,c=e[`machine-user`]===``?void 0:e[`machine-user`]??n.machine_user,l=e[`machine-user-override`]===`allow`?void 0:e[`machine-user-override`]??n.machine_user_override,u=e[`platform-url`]===``?void 0:e[`platform-url`]??n.platform_url,d=e[`oauth2-client-id`]===``?void 0:e[`oauth2-client-id`]??n.oauth2_client_id,f=e[`console-url`]===``?void 0:e[`console-url`]??n.console_url,p={...u?{platformUrl:u}:{},...d?{oauth2ClientId:d}:{},...f?{consoleUrl:f}:{}},h=Object.keys(p).length>0?p:void 0,g=e[`platform-url`]===``?Rn(n):h;if((e[`machine-user`]!==void 0||e[`machine-user-override`]!==void 0)&&l===`deny`&&!c)throw e[`machine-user-override`]===`deny`?U({code:`PROFILE_OPTIONS_INVALID`,message:`--machine-user-override deny requires --machine-user.`,command:`profile update`}):U({code:`PROFILE_OPTIONS_INVALID`,message:`Cannot clear the machine user while machine-user-override is "deny". Also pass --machine-user-override allow.`,command:`profile update`});if(e.user!==void 0||e[`workspace-id`]!==void 0||e[`platform-url`]!==void 0){let n=await br(t,i,g,e.name);s=n.user;let r=await le(n.accessToken,h);if(!(await m(async(e,t)=>{let{workspaces:n,nextPageToken:i}=await r.listWorkspaces({pageToken:e,pageSize:t});return[n,i]})).find(e=>e.id===o))throw U({code:`WORKSPACE_NOT_FOUND`,message:`Workspace "${o}" not found.`})}n.user=s,n.workspace_id=o,e.permission===`read`?n.readonly=!0:e.permission===`write`&&delete n.readonly,e[`machine-user`]!==void 0&&(e[`machine-user`]===``?delete n.machine_user:n.machine_user=e[`machine-user`]),e[`machine-user-override`]===`deny`?n.machine_user_override=`deny`:e[`machine-user-override`]===`allow`&&delete n.machine_user_override,e[`platform-url`]!==void 0&&(e[`platform-url`]===``?delete n.platform_url:n.platform_url=e[`platform-url`]),e[`oauth2-client-id`]!==void 0&&(e[`oauth2-client-id`]===``?delete n.oauth2_client_id:n.oauth2_client_id=e[`oauth2-client-id`]),e[`console-url`]!==void 0&&(e[`console-url`]===``?delete n.console_url:n.console_url=e[`console-url`]),O(t),e.json||C.success(`Profile "${e.name}" updated successfully`);let _={name:e.name,user:s,workspaceId:o,permission:n.readonly===!0?`read`:`write`,...n.machine_user?{machineUser:n.machine_user,machineUserOverride:n.machine_user_override??`allow`}:{},...n.platform_url?{platformUrl:n.platform_url}:{},...n.oauth2_client_id?{oauth2ClientId:n.oauth2_client_id}:{},...n.console_url?{consoleUrl:n.console_url}:{}};C.out(_)}}),Oa=G({name:`profile`,description:`Manage workspace profiles (user + workspace combinations).`,subCommands:{create:wa,delete:Ta,list:Ea,update:Da},defaultSubCommand:`list`});async function resolveSecretValue(e,t,n){if(e.value!==void 0)return e.value;let missing=e=>U({code:`SECRET_VALUE_REQUIRED`,message:`No secret value was given: --value is omitted and standard input ${e}.`,suggestion:`Pass --value, or pipe or redirect the value into the command.`,command:n});if(t.isTTY===!0)throw missing(`is a terminal`);let tooLarge=()=>U({code:`SECRET_VALUE_TOO_LARGE`,message:`The secret value read from standard input exceeds 128 KiB.`,command:n}),r=[],i=0;for await(let e of t){let t=typeof e==`string`?Buffer.from(e):e;if(i+=t.length,i>131074)throw tooLarge();r.push(t)}let a;try{a=new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}).decode(Buffer.concat(r))}catch(e){throw U({code:`SECRET_VALUE_INVALID_UTF8`,message:`The secret value read from standard input is not valid UTF-8.`,command:n,cause:e})}let o=a.replace(/\r?\n$/,``);if(Buffer.byteLength(o)>131072)throw tooLarge();if(o===``)throw missing(`is empty`);return o}const ka={"vault-name":W(q.string(),{alias:`V`,description:`Vault name`})},Aa={...ka,name:W(q.string(),{alias:`n`,description:`Secret name`})},ja={...Aa,value:W(q.string().optional(),{alias:`v`,description:`Secret value (read from standard input when omitted)`})};function secretValueNotes(e){return`Pass the value with \`--value\`, or omit \`--value\` and pipe the value in to keep it out of shell history and process listings, for example \`printf '%s' "$STRIPE_KEY" | tailor secret ${e} --vault-name api-keys --name stripe-secret-key\`. A piped value can be up to 128 KiB, and one trailing newline is removed from it. In a vault managed by \`defineSecretManager()\`, the command asks for confirmation before releasing the vault from the config, which needs an interactive terminal, so pass \`--yes\` when piping the value.`}async function checkVaultManaged(e){let{client:t,workspaceId:n,vaultName:r}=e,i=I(n,`vault`,r),a={isManaged:!1,trn:i,existingLabels:{}},o,s;try{let{metadata:e}=await t.getMetadata({trn:i});s=e?.labels??{},o=s[Zn]}catch{return a}return o?(C.warn(`Vault "${r}" is managed by defineSecretManager() in tailor.config.ts (owner: "${o}"). Changes made via CLI may conflict with the config on the next apply.`),{isManaged:!0,trn:i,existingLabels:s}):a}async function releaseVaultOwnership(e){let{client:t,trn:n}=e;await dn(t,{trn:n,remove:[Zn,sr,nn]}),C.info(`Config ownership has been removed from this vault. Remove it from defineSecretManager() in your config to prevent the next apply from re-claiming it.`)}const Ma=k({name:`create`,description:`Create a secret in a vault.`,args:q.strictObject({...R,...ja,...D}),notes:secretValueNotes(`create`),run:async e=>{let t=await resolveSecretValue(e,process.stdin,`secret create`);C.registerSecret(t),await F({profile:e.profile});let{client:n,workspaceId:r}=await N({profile:e.profile,workspaceId:e[`workspace-id`]}),i=await checkVaultManaged({client:n,workspaceId:r,vaultName:e[`vault-name`]});if(i.isManaged&&!e.yes&&!await M.confirm({message:`Do you want to proceed?`,default:!1}))throw U({code:`SECRET_CREATION_CANCELLED`,message:`Secret creation cancelled. The vault is still managed by the config.`});try{await n.createSecretManagerSecret({workspaceId:r,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name,secretmanagerSecretValue:t})}catch(t){if(t instanceof Q){if(t.code===Z.NotFound)throw U({code:`VAULT_NOT_FOUND`,message:`Vault "${e[`vault-name`]}" not found.`,cause:t});if(t.code===Z.AlreadyExists)throw U({code:`SECRET_EXISTS`,message:`Secret "${e.name}" already exists.`,cause:t})}throw t}i.isManaged&&await releaseVaultOwnership({client:n,...i}),C.success(`Secret: ${e.name} created in vault: ${e[`vault-name`]}`),z({changed:!0,workspaceId:r,vaultName:e[`vault-name`],name:e.name,vaultOwnershipReleased:i.isManaged})}}),Na=k({name:`delete`,description:`Delete a secret in a vault.`,args:q.strictObject({...R,...Aa,...D}),run:async e=>{await F({profile:e.profile});let{client:t,workspaceId:n}=await N({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e[`vault-name`]});if(!e.yes&&await M.text({message:`Enter the secret name to confirm deletion ("${e.name}"):`})!==e.name)throw U({code:`SECRET_DELETION_CANCELLED`,message:`Secret deletion cancelled: the entered name did not match.`,suggestion:`Run the command again and enter the name exactly as shown, or pass --yes to skip the confirmation.`});try{await t.deleteSecretManagerSecret({workspaceId:n,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`SECRET_NOT_FOUND`,message:`Secret "${e.name}" not found in vault "${e[`vault-name`]}".`,cause:t}):t}r.isManaged&&await releaseVaultOwnership({client:t,...r}),C.success(`Secret: ${e.name} deleted from vault: ${e[`vault-name`]}`),z({changed:!0,workspaceId:n,vaultName:e[`vault-name`],name:e.name,vaultOwnershipReleased:r.isManaged})}});function secretInfo(e){return{name:e.name,createdAt:e.createTime?X(e.createTime):null,updatedAt:e.updateTime?X(e.updateTime):null}}async function secretList(e){let{client:t,workspaceId:n}=await N({profile:e.profile,workspaceId:e.workspaceId}),r=dr(e.order);return(await S(async(i,a)=>{let{secrets:o,nextPageToken:s}=await t.listSecretManagerSecrets({workspaceId:n,secretmanagerVaultName:e.vaultName,pageToken:i,pageSize:a,pageDirection:r});return[o,s]},{limit:e.limit})).map(secretInfo)}const Pa=k({name:`list`,description:`List all secrets in a vault.`,args:q.strictObject({...R,...ka,...Ht()}),run:async e=>{try{let t=await L(e.limit,t=>secretList({workspaceId:e[`workspace-id`],profile:e.profile,vaultName:e[`vault-name`],order:e.order,limit:t})),n=t.items;C.out(n),await B(t,e.limit)}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`VAULT_NOT_FOUND`,message:`Vault "${e[`vault-name`]}" not found.`,cause:t}):t}}}),Fa=k({name:`update`,description:`Update a secret in a vault.`,args:q.strictObject({...R,...ja,...D}),notes:secretValueNotes(`update`),run:async e=>{let t=await resolveSecretValue(e,process.stdin,`secret update`);C.registerSecret(t),await F({profile:e.profile});let{client:n,workspaceId:r}=await N({profile:e.profile,workspaceId:e[`workspace-id`]}),i=await checkVaultManaged({client:n,workspaceId:r,vaultName:e[`vault-name`]});if(i.isManaged&&!e.yes&&!await M.confirm({message:`Do you want to proceed?`,default:!1}))throw U({code:`SECRET_UPDATE_CANCELLED`,message:`Secret update cancelled. The vault is still managed by the config.`});try{await n.updateSecretManagerSecret({workspaceId:r,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name,secretmanagerSecretValue:t})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`SECRET_NOT_FOUND`,message:`Secret "${e.name}" not found in vault "${e[`vault-name`]}".`,cause:t}):t}i.isManaged&&await releaseVaultOwnership({client:n,...i}),C.success(`Secret: ${e.name} updated in vault: ${e[`vault-name`]}`),z({changed:!0,workspaceId:r,vaultName:e[`vault-name`],name:e.name,vaultOwnershipReleased:i.isManaged})}}),Ia={name:W(q.string(),{positional:!0,description:`Vault name`})},La=k({name:`create`,description:`Create a new Secret Manager vault.`,args:q.strictObject({...R,...Ia}),run:async e=>{await F({profile:e.profile});let{client:t,workspaceId:n}=await N({profile:e.profile,workspaceId:e[`workspace-id`]});try{await t.createSecretManagerVault({workspaceId:n,secretmanagerVaultName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.AlreadyExists?U({code:`VAULT_EXISTS`,message:`Vault "${e.name}" already exists.`,cause:t}):t}C.success(`Vault: ${e.name} created`),z({changed:!0,workspaceId:n,name:e.name})}}),Ra=k({name:`delete`,description:`Delete a Secret Manager vault.`,args:q.strictObject({...R,...Ia,...D}),run:async e=>{await F({profile:e.profile});let{client:t,workspaceId:n}=await N({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e.name});if(!e.yes&&await M.text({message:`Enter the vault name to confirm deletion ("${e.name}"):`})!==e.name)throw U({code:`VAULT_DELETION_CANCELLED`,message:`Vault deletion cancelled: the entered name did not match.`,suggestion:`Run the command again and enter the name exactly as shown, or pass --yes to skip the confirmation.`});try{await t.deleteSecretManagerVault({workspaceId:n,secretmanagerVaultName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`VAULT_NOT_FOUND`,message:`Vault "${e.name}" not found.`,cause:t}):t}r.isManaged&&C.info(`Remove this vault from defineSecretManager() in your config to prevent the next apply from re-creating it.`),C.success(`Vault: ${e.name} deleted`),z({changed:!0,workspaceId:n,name:e.name,managed:r.isManaged})}});function vaultInfo(e){return{name:e.name,createdAt:e.createTime?X(e.createTime):null,updatedAt:e.updateTime?X(e.updateTime):null}}async function vaultList(e){let{client:t,workspaceId:n}=await N({profile:e?.profile,workspaceId:e?.workspaceId}),r=dr(e?.order);return(await S(async(e,i)=>{let{vaults:a,nextPageToken:o}=await t.listSecretManagerVaults({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e?.limit})).map(vaultInfo)}const za=k({name:`list`,description:`List all Secret Manager vaults in the workspace.`,args:q.strictObject({...R,...Ht()}),run:async e=>{let t=await L(e.limit,t=>vaultList({workspaceId:e[`workspace-id`],profile:e.profile,order:e.order,limit:t})),n=t.items;C.out(n),await B(t,e.limit)}}),Ba=G({name:`vault`,description:`Manage Secret Manager vaults.`,subCommands:{create:La,delete:Ra,list:za},defaultSubCommand:`list`}),Va=G({name:`secret`,description:`Manage Secret Manager vaults and secrets.`,subCommands:{vault:Ba,create:Ma,update:Fa,list:Pa,delete:Na},defaultSubCommand:`vault`}),Ha={[n.UNSPECIFIED]:`unspecified`,[n.PENDING]:`pending`,[n.VERIFYING]:`verifying`,[n.CERT_ISSUED]:`cert_issued`,[n.ACTIVE]:`active`,[n.FAILED]:`failed`},Ua=k({name:`get`,description:`Get details of a custom domain.`,args:q.strictObject({...R,domain:W(q.string(),{positional:!0,description:`Custom domain name`})}),run:async e=>{let{client:t,workspaceId:n}=await N({profile:e.profile,workspaceId:e[`workspace-id`]}),r=`Custom domain "${e.domain}" not found.`;try{let{customDomain:i}=await t.getCustomDomain({workspaceId:n,domain:e.domain});if(!i)throw U({code:`STATIC_WEBSITE_DOMAIN_NOT_FOUND`,message:r});let a={domain:i.domain,status:Ha[i.status]??`unknown`,trafficCnameTarget:i.trafficCnameTarget,certificateCnameTarget:i.certificateCnameTarget,errorMessage:i.errorMessage||void 0};C.out(a)}catch(e){throw e instanceof Q&&e.code===Z.NotFound?U({code:`STATIC_WEBSITE_DOMAIN_NOT_FOUND`,message:r,cause:e}):e}}}),Wa=k({name:`list`,description:`List custom domains for a static website.`,args:q.strictObject({...R,name:W(q.string(),{positional:!0,description:`Static website name`})}),run:async e=>{let{client:t,workspaceId:n}=await N({profile:e.profile,workspaceId:e[`workspace-id`]});try{let{customDomains:r}=await t.listCustomDomains({workspaceId:n,staticWebsiteName:e.name});if(r.length===0){C.info(`No custom domains found.`),C.jsonMode&&C.out([]);return}let i=r.map(e=>({domain:e.domain,status:Ha[e.status]??`unknown`,trafficCnameTarget:e.trafficCnameTarget,certificateCnameTarget:e.certificateCnameTarget}));C.out(i)}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`STATIC_WEBSITE_NOT_FOUND`,message:`Static website "${e.name}" not found.`,cause:t}):t}}}),Ga=G({name:`domain`,description:`Manage custom domains for static websites.`,subCommands:{list:Wa,get:Ua}}),Ka=k({name:`get`,description:`Get details of a specific static website.`,args:q.strictObject({...R,name:W(q.string(),{positional:!0,description:`Static website name`})}),run:async e=>{let{client:t,workspaceId:n}=await N({profile:e.profile,workspaceId:e[`workspace-id`]}),r=`Static website "${e.name}" not found.`;try{let{staticwebsite:i}=await t.getStaticWebsite({workspaceId:n,name:e.name});if(!i)throw U({code:`STATIC_WEBSITE_NOT_FOUND`,message:r});let a={workspaceId:n,name:i.name,description:i.description,url:i.url,allowedIpAddresses:e.json?i.allowedIpAddresses:i.allowedIpAddresses.join(`
|
|
86
|
-
`)};C.out(a)}catch(e){throw e instanceof Q&&e.code===Z.NotFound?U({code:`STATIC_WEBSITE_NOT_FOUND`,message:r,cause:e}):e}}});async function listStaticWebsites(e){let{client:t,workspaceId:n}=await N({profile:e?.profile,workspaceId:e?.workspaceId}),r=dr(e?.order);return(await S(async(e,i)=>{let{staticwebsites:a,nextPageToken:o}=await t.listStaticWebsites({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e?.limit})).map(e=>({workspaceId:n,name:e.name,description:e.description,url:e.url,allowedIpAddresses:e.allowedIpAddresses}))}const qa=k({name:`list`,description:`List all static websites in a workspace.`,args:q.strictObject({...R,...Ht()}),run:async e=>{let t=C.jsonMode,n=await L(e.limit,t=>listStaticWebsites({workspaceId:e[`workspace-id`],profile:e.profile,order:e.order,limit:t})),r=n.items,i=t?r:r.map(({allowedIpAddresses:e,...t})=>{if(e.length===0)return{...t,allowedIpAddresses:`No allowed IP addresses`};let n=e.length,r=n===1?`1 IP address`:`${n} IP addresses`;return{...t,allowedIpAddresses:r}});C.out(i),await B(n,e.limit)}}),Ja=G({name:`staticwebsite`,description:`Manage static websites in your workspace.`,subCommands:{deploy:ft,domain:Ga,list:qa,get:Ka},defaultSubCommand:`list`}),Ya=new Set(Object.values(pt));async function activateBaseline(e,t,n,r){let i=await $.realpath(e),a=K.dirname(i),o=K.basename(i),s=await $.mkdtemp(K.join(a,`.${o}-rebaseline-`)),c=`${s}-previous`,l=!1,u=!1;try{await $.cp(i,s,{recursive:!0});for(let e of await $.readdir(s,{withFileTypes:!0})){if(!e.isDirectory()||!ze.test(e.name))continue;let t=K.join(s,e.name);(await $.readdir(t)).some(e=>Ya.has(e))&&await $.rm(t,{recursive:!0,force:!0})}let e={...t,namespace:n,version:8,createdAt:(/* @__PURE__ */ new Date()).toISOString(),rebaseline:r},a=await Te(e,s,0);Bt(a.filePath),await $.rename(i,c),l=!0;try{await $.rename(s,i),u=!0}catch(e){throw await $.rename(c,i),l=!1,e}try{await $.rm(c,{recursive:!0,force:!0})}catch(e){C.warn(`The previous migration directory remains at ${c}: ${e instanceof Error?e.message:String(e)}`)}l=!1}finally{Y.existsSync(s)&&await $.rm(s,{recursive:!0,force:!0}),!u&&l&&Y.existsSync(c)&&await $.rename(c,i)}}async function rebaseline(e){Ft(`tailordb migration`);let{config:t,plugins:n}=await P(e.configPath),r=K.dirname(t.path),i=Sr(On(t,r),e.namespace),a=`First run ${H({command:`tailor`,args:[`tailordb`,`migration`,`generate`,`--config`,t.path]})}.`;kt(i.migrationsDir,i.namespace);let o=E(i.migrationsDir);if(!o)throw U({code:`MIGRATION_HISTORY_NOT_FOUND`,message:`No migration history found for namespace "${i.namespace}".`,suggestion:a});let s=xt(i.migrationsDir),c=E(i.migrationsDir,0)?.rebaseline?.historyId??null,l=cn([i])[i.namespace],u=n.length>0?new Qr(n):void 0,{defineApplication:d}=await import(`../application-nT_4a5HO.mjs`),f=d({config:t,pluginManager:u});for(let e of f.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let p=f.tailorDBServices.find(e=>e.namespace===i.namespace);if(!p)throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${i.namespace}"`});let assertLocalTypesReady=()=>{let e=Me(p.types,i.namespace),t=Xe(o,e.tables,i.namespace);if(Kn(t))throw C.error(`Migration history does not reproduce the current local schema for namespace ${w.bold(i.namespace)}:`),C.log(fr(t)),U({code:`MIGRATION_HISTORY_MISMATCH`,message:`Refusing to re-baseline: the migration history must reproduce the current local schema.`,suggestion:a})},localSourceFiles=()=>[t.path,...Ir(p.config,r)];assertLocalTypesReady();let m=Nr(localSourceFiles()),{client:h,workspaceId:g}=await N({profile:e.profile,workspaceId:e.workspaceId}),_=[`--config`,t.path,...gt({workspaceId:g,profile:e.profile})],v=`Run ${H({command:`tailor`,args:[`tailordb`,`migration`,`set`,`0`,`--namespace`,i.namespace,..._]})}`,y=`after resolving the connection error, deploy with schema checks enabled by running ${H({command:`tailor`,args:[`deploy`,..._]})}.`,assertConnectedWorkspaceReady=async(e,n)=>{let r=await Wn(h,I(g,`tailordb`,i.namespace));tr(r,i.namespace);let a=r.number;if(a!==s){let e=a===null?`<unset>`:A(a);throw U({code:`REBASELINE_CHECKPOINT_BEHIND`,message:`The connected workspace must be at the latest migration ${A(s)} before re-baselining; current checkpoint is ${e}.`})}if(r.historyIdInvalid)throw U({code:`REBASELINE_REMOTE_HISTORY_INVALID`,message:`Refusing to re-baseline: the connected workspace has an invalid migration history marker.`});if(r.historyId!==e)throw U(n===`confirmation`?{code:`REBASELINE_STATE_CHANGED`,message:`The connected workspace migration history changed while waiting for confirmation.`,suggestion:`Run the command again.`}:{code:`REBASELINE_REMOTE_HISTORY_MISMATCH`,message:`Refusing to re-baseline: the connected workspace does not match the local migration history.`});let o=await Mt(h,g,[i],t,[We(p)]),c=o[0];if(!c||c.remoteMigrationNumber!==s||c.hasDrift||c.checkpointMissingLocal)throw c?.hasDrift&&(C.error(`Remote schema drift detected:`),C.log(Fr(o))),U({code:`REBASELINE_REMOTE_SCHEMA_MISMATCH`,message:`Refusing to re-baseline: the connected workspace remote schema must match the latest migration.`})};if(await assertConnectedWorkspaceReady(c,`initial`),C.newline(),C.warn(`This will replace the migration history for ${w.bold(i.namespace)}.`),C.log(` Latest migration: ${A(s)}`),C.log(` New history: 0000/schema.json only`),C.log(` migrate.ts and db.ts files will disappear from the working tree.`),C.log(` Committed migration files will remain in Git history. Preserve any uncommitted files before continuing.`),C.log(` Every other environment must already be at the latest migration.`),C.log(` The connected workspace checkpoint will be reset to 0000.`),C.newline(),!e.yes&&!await M.confirm({message:`Re-baseline this migration history and reset the connected workspace checkpoint?`,default:!1}))throw U({code:`REBASELINE_CANCELLED`,message:`Migration re-baseline cancelled.`});if(kt(i.migrationsDir,i.namespace),cn([i])[i.namespace]!==l)throw U({code:`REBASELINE_STATE_CHANGED`,message:`Migration files changed while waiting for confirmation.`,suggestion:`Run the command again.`});if(Nr(localSourceFiles())!==m)throw U({code:`REBASELINE_STATE_CHANGED`,message:`Local TailorDB table or config files changed.`,suggestion:`Run the command again.`});assertLocalTypesReady(),await assertConnectedWorkspaceReady(c,`confirmation`);let b={historyId:et(),replacedHistoryId:c,replacedLatestMigration:s};await activateBaseline(i.migrationsDir,o,i.namespace,b);try{await $e(h,g,i.namespace,0,b.historyId)}catch(e){throw U({code:`REBASELINE_CHECKPOINT_UPDATE_FAILED`,message:`The local migration history was re-baselined, but the connected workspace checkpoint could not be updated.`,suggestion:`${v}, or ${y}`,cause:e})}return C.success(`Re-baselined ${w.bold(i.namespace)} and reset the connected workspace checkpoint to 0000.`),{changed:!0,workspaceId:g,namespace:i.namespace,...b,schemaPath:Oe(i.migrationsDir,0,`schema`)}}const Xa=k({name:`rebaseline`,description:`Collapse the full migration history into a new 0000 baseline.`,notes:`Re-baselining removes migrations after 0000 from the working tree, records a new migration history ID, and resets the connected workspace checkpoint without changing its schema or data. Every environment must already have applied the latest migration before you run this command.`,args:q.strictObject({...j,...D,namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await F({profile:e.profile});let t=await rebaseline({configPath:e.config,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile});z(t)}});async function set(e){Ft(`tailordb migration`);let t=Se(e.number),{config:n}=await P(e.configPath),r=K.dirname(n.path),i=On(n,r),a=Sr(i,e.namespace),o=a.namespace;kt(a.migrationsDir,o),nt(a.migrationsDir,t);let s=E(a.migrationsDir,0)?.rebaseline?.historyId,{client:c,workspaceId:l}=await N({profile:e.profile,workspaceId:e.workspaceId}),u=I(l,`tailordb`,o),d=await Wn(c,u),f=d.inProgress?.number===t;f||tr(d,o);let p=d.number,m=p??0,h=d.historyIdInvalid?`<invalid>`:d.historyId??`<unset>`,g=s??`<unset>`;if(C.newline(),C.warn(`This operation will change TailorDB migration state metadata.`),C.log(`Namespace: ${w.bold(o)}`),C.log(`Current migration: ${p===null?`<unset>`:w.bold(A(p))}`),C.log(`New migration: ${w.bold(A(t))}`),C.log(`Current migration history ID: ${w.bold(h)}`),C.log(`New migration history ID: ${w.bold(g)}`),C.newline(),f&&(C.warn(`Migration ${A(t)} is in progress. Setting the checkpoint to it marks it as completed and clears its in-progress record; do this only when its schema changes are already applied.`),C.newline()),t<m?(C.warn(`Setting migration number backwards (${A(m)} → ${A(t)}) will cause previous migrations to be re-executed on next apply.`),C.newline()):t>m&&(C.warn(`Setting migration number forwards (${A(m)} → ${A(t)}) will skip migrations ${A(m+1)} to ${A(t)}.`),C.newline()),!e.yes){if(!await M.confirm({message:`Continue with migration checkpoint and history ID update?`,default:!1}))throw U({code:`MIGRATION_SET_CANCELLED`,message:`Migration checkpoint update cancelled.`});C.newline()}let _=await $e(c,l,o,t,s);return C.success(`Migration checkpoint set to ${w.bold(A(t))} for namespace ${w.bold(o)}`),{changed:_,workspaceId:l,namespace:o,previousMigrationNumber:p,migrationNumber:t,historyId:s??null}}const Za=k({name:`set`,description:`Set migration checkpoint to a specific number.`,notes:"The migration number must be a 4-digit value (e.g. `0001`) or a bare integer (e.g. `1`) within 0–9999, and must exist in the local migration history; `0` is always accepted as the baseline, provided the local history passes validation. A gapped history is rejected.\n\nMetadata lookup failures (authentication, permission, or network errors) are reported as errors; only a not-yet-deployed namespace is treated as having no checkpoint.",args:q.strictObject({...j,...D,number:W(q.string(),{positional:!0,description:`Migration number to set (e.g., 0001 or 1)`}),namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await F({profile:e.profile});let t=await set({configPath:e.config,number:e.number,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile});z(t)}});function isStatusFailure(e){return e.status===`error`}async function collectMigrationStatuses(e){let{config:t}=await P(e.configPath),n=K.dirname(t.path),r=On(t,n);if(r.length===0)throw en();let i=e.namespace?r.filter(t=>t.namespace===e.namespace):r;if(i.length===0)throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`Namespace "${e.namespace}" not found or does not have migrations configured`});let a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map;for(let{namespace:e,migrationsDir:t}of i)try{let n=Rt(t),r=/* @__PURE__ */ new Map,i=null;for(let e of n){if(e.type===`schema`){let t=Bt(e.path);e.number===0&&(i=t.rebaseline?.historyId??null);continue}try{let t=Nt(e.path);t.description&&r.set(e.number,t.description)}catch(e){if(zr(e)&&e.code===`MIGRATION_FILE_VERSION_UNSUPPORTED`)throw e}}a.set(e,{migrationFiles:n,descriptions:r,historyId:i})}catch(t){o.set(e,Vr(t))}if(a.size===0)return i.map(({namespace:e})=>({status:`error`,namespace:e,error:o.get(e)??`Failed to read local migration history.`}));let{client:s,workspaceId:c}=await N({profile:e.profile,workspaceId:e.workspaceId}),l=[];for(let{namespace:e}of i){if(o.has(e)){l.push({status:`error`,namespace:e,error:o.get(e)??`Failed to read local migration history.`});continue}let t=a.get(e);if(!t){l.push({status:`error`,namespace:e,error:`Failed to read local migration history.`});continue}let{migrationFiles:n,descriptions:r,historyId:i}=t,u=I(c,`tailordb`,e),d;try{d=await Wn(s,u)}catch(t){l.push({status:`error`,namespace:e,error:t instanceof Error?t.message:String(t)});continue}let f=d.number??0;if(d.historyIdInvalid){l.push({status:`error`,namespace:e,error:`Remote migration history ID is invalid.`});continue}if(d.inProgressInvalid){l.push({status:`error`,namespace:e,error:`Remote in-progress migration record is invalid.`});continue}if((d.number!==null||d.historyId!==null)&&d.historyId!==i){l.push({status:`error`,namespace:e,error:`Remote migration history ID ${d.historyId??`<unset>`} does not match local migration history ID ${i??`<unset>`}.`});continue}let p=n.map(e=>e.number).filter((e,t,n)=>n.indexOf(e)===t).toSorted((e,t)=>e-t).filter(e=>e>f).map(e=>({number:e,label:A(e),...r.has(e)?{description:r.get(e)}:{}})),m=jn(d)?null:d.inProgress;l.push({status:`ok`,namespace:e,currentMigration:f,currentMigrationLabel:A(f),pendingMigrations:p,...m?{inProgressMigration:m.number,inProgressMigrationLabel:A(m.number)}:{}})}return l}function printMigrationStatuses(e){for(let t of e){if(C.newline(),C.info(`Namespace: ${w.bold(t.namespace)}`),isStatusFailure(t)){C.error(` Migration status error: ${t.error}`);continue}if(C.log(` Current migration: ${w.bold(t.currentMigrationLabel)}`),t.inProgressMigrationLabel&&C.log(` In progress: ${w.bold(t.inProgressMigrationLabel)} (partially applied; the next deploy resumes it)`),t.pendingMigrations.length>0){C.log(` Pending migrations:`);for(let e of t.pendingMigrations)e.description?C.log(` - ${e.label}: ${e.description}`):C.log(` - ${e.label}`)}else C.log(` Pending migrations: (none)`)}C.newline()}async function status(e){Ft(`tailordb migration`);let t=await collectMigrationStatuses(e);e.json?C.out(t):printMigrationStatuses(t);let n=t.filter(isStatusFailure);if(n.length>0){let e=n.map(e=>e.namespace).join(`, `);throw U({code:`MIGRATION_STATUS_FAILED`,message:`Migration status check failed for ${n.length} namespace${n.length===1?``:`s`}: ${e}`})}}const Qa=k({name:`status`,description:`Show the current migration status for TailorDB namespaces, including applied and pending migrations.`,notes:`Every local migration file is checked for a compatible format version, and deployed migration history IDs must match the local baseline. Compatibility errors, history mismatches, and metadata lookup failures are reported per namespace and make the command exit non-zero; only a not-yet-deployed namespace is treated as having no applied migrations.`,args:q.strictObject({...j,namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (shows all namespaces if not specified)`})}),run:async e=>{await status({configPath:e.config,namespace:e.namespace,workspaceId:e[`workspace-id`],profile:e.profile,json:C.jsonMode})}});async function fetchRemoteGqlPermissions(e,t,n){return x(async(r,i)=>{let{permissions:a,nextPageToken:o}=await e.listTailorDBGQLPermissions({workspaceId:t,namespaceName:n,pageToken:r,pageSize:i});return[a,o]})}async function fetchRemoteTypes(e,t,n){return m(async(r,i)=>{try{let{tailordbTypes:a,nextPageToken:o}=await e.listTailorDBTypes({workspaceId:t,namespaceName:n,pageToken:r,pageSize:i});return[a,o]}catch(e){throw e instanceof Q&&e.code===Z.NotFound?U({code:`MIGRATION_NAMESPACE_NOT_DEPLOYED`,message:`Cannot sync: TailorDB namespace "${n}" has not been deployed yet.`,suggestion:`Deploy the namespace before syncing its migration history.`,cause:e}):e}})}async function assertMigrationsReproduceLocalTypes(e,t){let{config:n,plugins:r}=e,i=r.length>0?new Qr(r):void 0,{defineApplication:a,generatePluginFilesIfNeeded:o}=await import(`../application-nT_4a5HO.mjs`),s=a({config:n,pluginManager:i}),c=s.tailorDBServices.find(e=>e.namespace===t.namespace);if(!c)throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${t.namespace}"`});for(let e of s.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let l=o(i,s.tailorDBServices,n.path),u=s.executorService??(l.length>0?(await import(`../service-sH2MZ4_W.mjs`)).createExecutorService({config:{files:[]},baseDir:K.dirname(n.path)}):void 0);await u?.loadExecutors(),l.length>0&&await u?.loadPluginExecutorFiles([...l]);let d=/* @__PURE__ */ new Set;for(let e of Object.values(u?.executors??{}))ar(e)&&e.trigger.kind===`tailordb`&&d.add(e.trigger.tableName);let f={executorUsedTables:d,namespaceGqlOperations:c.config.gqlOperations},p=E(t.migrationsDir);if(!p)return f;let m=Me(c.types,t.namespace),h=Xe(p,m.tables,t.namespace);if(!Kn(h))return f;throw C.error(`Migration history does not reproduce the current local schema for namespace ${w.bold(t.namespace)}:`),C.log(fr(h)),C.newline(),C.info(`This usually means one of the following:`),C.info(` - Migration files were edited and replaying them no longer matches the table definitions — fix the migration files.`,{mode:`plain`}),C.info(` - Table definitions changed without a new migration — run 'tailor tailordb migration generate' first.`,{mode:`plain`}),C.newline(),U({code:`MIGRATION_HISTORY_MISMATCH`,message:`Refusing to sync: the migration history must reproduce the current local schema before it can be applied to the remote.`,suggestion:`Generate a migration for the pending schema changes first.`})}async function sync(e){Ft(`tailordb migration`);let t=Se(e.number),n=await P(e.configPath),{config:r}=n,i=K.dirname(r.path),a=On(r,i),o=Sr(a,e.namespace);kt(o.migrationsDir,o.namespace);let s=nt(o.migrationsDir,t),c=E(o.migrationsDir,t);if(!c)throw U({code:`MIGRATION_BASELINE_NOT_FOUND`,message:`No initial schema snapshot found in ${o.migrationsDir}. Expected 0000/schema.json.`,suggestion:`Create the initial schema snapshot first.`});let l=await assertMigrationsReproduceLocalTypes(n,o),{client:u,workspaceId:d}=await N({profile:e.profile,workspaceId:e.workspaceId}),f=I(d,`tailordb`,o.namespace),p=await Wn(u,f);tr(p,o.namespace);let m=p.number,h=await fetchRemoteTypes(u,d,o.namespace),g=new Set(h.map(e=>e.name)),{creates:_,updates:v,deletes:y}=Qn(c,g),b=await fetchRemoteGqlPermissions(u,d,o.namespace),ee=new Set(b.map(e=>e.typeName)),x=Object.entries(c.tables).flatMap(([e,t])=>t.permissions?.gql?[{typeName:e,permission:pn(t.permissions.gql)}]:[]),S=new Set(x.map(e=>e.typeName)),te=b.filter(e=>!S.has(e.typeName));C.newline(),C.info(`Namespace: ${w.bold(o.namespace)}`),C.log(` Current migration: ${m===null?`<unset>`:w.bold(A(m))}`),C.log(` Target migration: ${w.bold(A(t))}`),C.log(` Tables to create: ${w.bold(String(_.length))}`),C.log(` Tables to update: ${w.bold(String(v.length))}`),C.log(` Tables to delete: ${w.bold(String(y.length))}`),C.log(` GQL permissions to set: ${w.bold(String(x.length))}`),C.log(` GQL permissions to delete: ${w.bold(String(te.length))}`),C.newline();let ne=_.length+v.length+y.length+x.length+te.length;if(ne===0?C.info(`No tables to apply; only the migration label will be updated.`):(C.warn(`This operation will overwrite remote TailorDB tables to match the selected snapshot.`),y.length>0&&C.warn(`Existing data in deleted tables will be lost.`),C.newline()),C.warn(`Sync never runs migrate.ts scripts; it only applies the schema snapshot and moves the migration label.`),C.newline(),m!==null&&t<m?(C.warn(`Migrations ${A(t+1)}–${A(m)} will become pending again and re-execute on the next deploy, including their migrate.ts scripts. Make sure those scripts are idempotent (safe to re-run).`),C.newline()):m!==null&&t>m&&(C.warn(`Moving the migration label forwards (${A(m)} → ${A(t)}): migrate.ts scripts for migrations ${A(m+1)}–${A(t)} will not run on the next deploy.`),C.newline()),!e.yes){if(!await M.confirm({message:`Continue and set migration label to ${A(t)}?`,default:!1}))throw U({code:`MIGRATION_SYNC_CANCELLED`,message:`Migration sync cancelled.`});C.newline()}let re=lr(c,l),manifestFor=e=>{let t=re.get(e);if(!t)throw Br(`Internal error: no manifest generated for table "${e}". No changes were applied.`);return t},ie=_.map(e=>manifestFor(e)),ae=v.map(e=>manifestFor(e));try{await Promise.all([...ie.map(e=>u.createTailorDBType({workspaceId:d,namespaceName:o.namespace,tailordbType:e})),...ae.map(e=>u.updateTailorDBType({workspaceId:d,namespaceName:o.namespace,tailordbType:e}))])}catch(e){rr(e,[`The target snapshot marks a field as required, but existing remote records have no value for it.`,`Populate those records first (e.g. with a migration script applied via 'tailor deploy'), then re-run the sync.`])}await Promise.all(x.map(({typeName:e,permission:t})=>{let n={workspaceId:d,namespaceName:o.namespace,typeName:e,permission:t};return ee.has(e)?u.updateTailorDBGQLPermission(n):u.createTailorDBGQLPermission(n)})),await Promise.all(te.map(e=>u.deleteTailorDBGQLPermission({workspaceId:d,namespaceName:o.namespace,typeName:e.typeName}))),await Promise.all(y.map(e=>u.deleteTailorDBType({workspaceId:d,namespaceName:o.namespace,tailordbTypeName:e})));let oe=c.rebaseline?.historyId,se=await $e(u,d,o.namespace,t,oe);return C.success(`Synced namespace ${w.bold(o.namespace)} to migration ${w.bold(A(t))}.`),t<s&&(C.newline(),C.info(`Run 'tailor deploy' to apply migrations ${A(t+1)}–${A(s)} from the working tree.`)),{changed:ne>0||se,workspaceId:d,namespace:o.namespace,previousMigrationNumber:m,migrationNumber:t,historyId:oe??null,tables:{created:_,updated:v,deleted:y},gqlPermissions:{set:x.map(({typeName:e})=>e),deleted:te.map(({typeName:e})=>e)}}}const $a=k({name:`sync`,description:`Sync remote TailorDB schema to a specific migration snapshot (recovery from --no-schema-check drift).`,args:q.strictObject({...j,...D,number:W(q.string(),{positional:!0,description:`Migration number to sync to (e.g., 0001 or 1; 0 targets the baseline snapshot)`}),namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await F({profile:e.profile});let t=await sync({configPath:e.config,number:e.number,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile});z(t)}});function delay(e){return e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve()}function assertSeedDataDirectory(e){let t;try{t=Y.statSync(e)}catch(t){throw t.code===`ENOENT`?U({code:`SEED_DATA_NOT_FOUND`,message:`Seed data directory not found: ${e}.`,suggestion:`Generate seed data before testing migrations.`,cause:t}):t}if(!t.isDirectory())throw U({code:`SEED_DATA_INVALID`,message:`Seed data path is not a directory: ${e}`})}function assertAssertionScript(e){let t=K.resolve(e),n;try{n=Y.statSync(t)}catch(e){throw e.code===`ENOENT`?U({code:`MIGRATION_ASSERTION_SCRIPT_NOT_FOUND`,message:`Migration assertion script not found: ${t}`,cause:e}):e}if(!n.isFile())throw U({code:`MIGRATION_ASSERTION_SCRIPT_INVALID`,message:`Migration assertion path is not a file: ${t}`})}function assertCloneTargetRegion(e,t){if(e!==t)throw U({code:`MIGRATION_TEST_REGION_MISMATCH`,message:`Clone mode requires source and target workspaces in the same region (source: ${e}, target: ${t}).`})}function assertTargetWorkspaceDiffers(e,t){if(t?.toLowerCase()===e.toLowerCase())throw U({code:`MIGRATION_TEST_TARGET_INVALID`,message:`The migration test target workspace must differ from the source workspace.`,command:`tailordb migration test`})}function resolveAssertionNamespace(e,t){let n=t??(e.length===1?e[0]:void 0);if(!n)throw U({code:`MIGRATION_TEST_ASSERT_NAMESPACE_REQUIRED`,message:`--assert-namespace is required when pending migrations span multiple namespaces.`,command:`tailordb migration test`});if(!e.includes(n))throw U({code:`MIGRATION_TEST_NO_PENDING_MIGRATIONS`,message:`Assertion namespace "${n}" has no pending migrations.`});return n}async function createMigrationTestBaselineSnapshots(e){let t=new Map([...e.baselines].map(([e,t])=>[e,t.snapshot]));if(e.dataMode!==`clone`)return t;let n=e.inputs.filter(e=>!t.has(e.namespace)),r=await Promise.all(n.map(t=>bt(e.client,e.workspaceId,t.namespace)));return n.forEach((e,n)=>{t.set(e.namespace,s(r[n],`remote snapshot missing for "${e.namespace}"`))}),t}async function waitForCloneApplicationData(e,t){let n=t.pollInterval??1e3,r=t.timeout??3e5,i=Date.now()+r;for(;Date.now()<=i;){let r=await e.getCloneApplicationDataOperation({sourceWorkspaceId:t.sourceWorkspaceId,targetWorkspaceId:t.targetWorkspaceId,operationId:t.operationId});if(r.status===o.COMPLETED)return;if(r.status===o.FAILED)throw U({code:`MIGRATION_TEST_CLONE_FAILED`,message:`Application data clone failed: ${r.errorMessage||`unknown platform error`}`});if(r.status!==o.PENDING&&r.status!==o.PROCESSING)throw Br(`Application data clone returned unexpected status ${r.status}.`);await delay(n)}throw U({code:`MIGRATION_TEST_CLONE_TIMEOUT`,message:`Application data clone timed out after ${Math.round(r/1e3)} seconds.`})}function loadSnapshotSeedData(e,t,n){let r={};for(let i of t){let t=n?.tables[i],a=K.join(e,`${i}.jsonl`),o;try{o=Y.readFileSync(a,`utf8`).trim()}catch(e){if(e.code===`ENOENT`){r[i]=[];continue}throw e}r[i]=o?o.split(`
|
|
87
|
-
`).map((e,n)=>{let r;try{r=JSON.parse(e)}catch(e){throw U({code:`SEED_DATA_INVALID`,message:`Invalid JSON in ${a} at line ${n+1}: ${e instanceof Error?e.message:String(e)}`,cause:e})}if(typeof r!=`object`||!r||Array.isArray(r))throw U({code:`SEED_DATA_INVALID`,message:`Invalid seed row in ${a} at line ${n+1}: expected a JSON object`});let i=r;return t?projectSeedObject(i,t.fields,/* @__PURE__ */ new Set([`id`])):i}):[]}return r}function projectSeedObject(e,t,n=/* @__PURE__ */ new Set){return Object.fromEntries(Object.entries(e).flatMap(([e,r])=>{let i=t[e];return i?[[e,projectSeedValue(r,i)]]:n.has(e)?[[e,r]]:[]}))}function projectSeedValue(e,t){let n=t.fields;return n?t.array?Array.isArray(e)?e.map(e=>isJsonObject(e)?projectSeedObject(e,n):e):e:isJsonObject(e)?projectSeedObject(e,n):e:e}function isJsonObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function sortSeedTypesForSnapshot(e){let t=Object.keys(e.tables),n=new Set(t),r=/* @__PURE__ */ new Map,i=[];for(let[t,a]of Object.entries(e.tables)){let e=/* @__PURE__ */ new Set;for(let r of Object.values(a.fields)){let a=r.foreignKeyType;a&&(a===t?i.push(t):n.has(a)&&e.add(a))}r.set(t,[...e])}let a=/* @__PURE__ */ new Set,o=[],visit=e=>{if(!a.has(e)){a.add(e);for(let t of r.get(e)??[])visit(t);o.push(e)}};for(let e of t)visit(e);return{order:o,selfRefTypes:i}}function temporaryWorkspaceName(){return`migration-test-${(/* @__PURE__ */ new Date()).toISOString().replace(/[-:T.Z]/g,``).slice(0,14)}-${_i(3).toString(`hex`)}`}function stateOrThrow(e){return s(e,`migration test runtime was used before preparation`)}async function resolveSourceMigrationNumber(e,t,n,r,i,a){if(r.number!==null)return r.number;if(!r.metadataExists)throw U({code:`MIGRATION_TEST_SOURCE_CHECKPOINT_MISSING`,message:`Source namespace "${n.namespace}" has not been deployed.`,suggestion:`Deploy to the source workspace before testing.`});let o=E(n.migrationsDir,0);if(!o)throw U({code:`MIGRATION_BASELINE_NOT_FOUND`,message:`No migration baseline snapshot found for namespace "${n.namespace}".`});let s=await tt(e,t,n.namespace,o,i,a);if(s.length>0)throw U({code:`MIGRATION_TEST_SOURCE_INVALID`,message:`Source namespace "${n.namespace}" has no migration label and its schema differs from the initial migration snapshot (0000).`,details:Tt(s),suggestion:`Bring the source schema in line with 0000 or set its migration label.`});return 0}async function assertSourceBaselineFresh(e,t,n){let r=e.loaded,i=On(r.config,K.dirname(r.config.path)),a=r.application.tailorDBServices.map(We),o=(await Mt(e.client,n,i,r.config,a)).find(e=>e.hasDrift||e.checkpointMissingLocal||e.checkpointRepair);if(o)throw U({code:`MIGRATION_TEST_SOURCE_CHANGED`,message:`Source namespace "${o.namespace}" changed after migration test preparation.`,suggestion:`Run the migration test again.`});for(let o of i){let i=t.baselines.get(o.namespace);if(!i)continue;let s=await Wn(e.client,I(n,`tailordb`,o.namespace));tr(s,o.namespace);let c=await resolveSourceMigrationNumber(e.client,n,o,s,r.config,a);if(c!==i.migrationNumber)throw U({code:`MIGRATION_TEST_SOURCE_CHANGED`,message:`Source namespace "${o.namespace}" moved from migration ${i.migrationNumber} to ${c} after migration test preparation.`,suggestion:`Run the migration test again.`})}let s=a.filter(e=>!t.baselines.has(e.namespace));for(let r of s){let i=t.baselineSnapshots.get(r.namespace);if(!i)continue;let a=await bt(e.client,n,r.namespace);if(Jt(i,a).changes.length>0)throw U({code:`MIGRATION_TEST_SOURCE_CHANGED`,message:`Source namespace "${r.namespace}" schema changed after migration test preparation.`,suggestion:`Run the migration test again.`})}}async function deleteExistingUserProfileConfig(e,t){let n=e.loaded.application.authService;if(!n)return;let r=n.config.name;await se(()=>e.client.getUserProfileConfig({workspaceId:t,namespaceName:r}))&&await e.client.deleteUserProfileConfig({workspaceId:t,namespaceName:r})}function migrationConfig(e,t){return e.config.db?.[t]?.migration}function authExecutionContext(e,t,n){let r=e.loaded.application.authService;if(!r)throw U({code:`AUTH_CONFIG_REQUIRED`,message:`Auth configuration is required to execute migration test scripts.`});let i=n??He(migrationConfig(e.loaded,t),r.config.machineUsers?Object.keys(r.config.machineUsers):void 0);if(!i)throw U({code:`MACHINE_USER_REQUIRED`,message:`No machine user is available for namespace "${t}".`,suggestion:`Pass --machine-user or configure one in auth or db.${t}.migration.`});return{authNamespace:r.config.name,machineUserName:i}}async function prepareMigrationTest(e){let t=await Et({configPath:e.configPath}),n=K.dirname(t.config.path),r=On(t.config,n);if(r.length===0)throw en();for(let e of r)kt(e.migrationsDir,e.namespace);let i;e.data===`seed`&&(i=await at({configPath:t.config.path}),assertSeedDataDirectory(K.join(i.distPath,`data`))),e.assertionPath&&assertAssertionScript(e.assertionPath);let a=t.application.tailorDBServices.map(We),o=await Or({profile:e.profile}),c=await Ie({profile:e.profile}),l=await le(o,c),u=await ct({workspaceId:e.workspaceId,profile:e.profile});assertTargetWorkspaceDiffers(u,e.targetWorkspaceId);let[d,f,p]=await Promise.all([l.getWorkspace({workspaceId:u}),l.getApplication({workspaceId:u,applicationName:t.config.name}),e.data===`clone`&&e.targetWorkspaceId?l.getWorkspace({workspaceId:e.targetWorkspaceId}):Promise.resolve(void 0)]),m=s(d.workspace,`source workspace "${u}" not found`);s(f.application,`application "${t.config.name}" not found in source workspace`);let h=p?s(p.workspace,`target workspace "${e.targetWorkspaceId}" not found`):void 0,g=await Mt(l,u,r,t.config,a),_=g.find(e=>e.hasDrift||e.checkpointMissingLocal);if(_)throw U({code:`MIGRATION_TEST_SOURCE_INVALID`,message:`Source namespace "${_.namespace}" does not match its migration checkpoint.`,suggestion:`Validate the migration history first.`});let v=g.find(e=>e.checkpointRepair);if(v)throw U({code:`MIGRATION_TEST_SOURCE_REPAIR_PENDING`,message:`Source namespace "${v.namespace}" has a pending migration checkpoint repair.`,suggestion:`Deploy to the source workspace first.`});let y=/* @__PURE__ */ new Map,b=/* @__PURE__ */ new Map,ee=[];for(let e of r){let n=await Wn(l,I(u,`tailordb`,e.namespace));tr(n,e.namespace);let r=await resolveSourceMigrationNumber(l,u,e,n,t.config,a),i=xt(e.migrationsDir);if(r>i)throw U({code:`MIGRATION_TEST_SOURCE_AHEAD`,message:`Source namespace "${e.namespace}" is at migration ${r}, but the local history ends at ${i}.`});let o=E(e.migrationsDir,r);if(!o)throw U({code:`MIGRATION_BASELINE_NOT_FOUND`,message:`No migration baseline snapshot found for namespace "${e.namespace}".`});y.set(e.namespace,{migrationNumber:r,snapshot:o,historyId:o.rebaseline?.historyId??null});let s=E(e.migrationsDir,i);if(!s)throw U({code:`MIGRATION_TEST_SNAPSHOT_NOT_FOUND`,message:`No target migration snapshot found for namespace "${e.namespace}".`});b.set(e.namespace,s),r<i&&ee.push(e.namespace)}if(ee.length===0)throw U({code:`MIGRATION_TEST_NO_PENDING_MIGRATIONS`,message:`No pending TailorDB migrations found in the source workspace.`});let x=await createMigrationTestBaselineSnapshots({client:l,workspaceId:u,dataMode:e.data,inputs:a,baselines:y}),S={sourceWorkspaceId:u,sourceApplicationName:t.config.name,temporaryWorkspace:{name:temporaryWorkspaceName(),region:m.region,...m.organizationId?{organizationId:m.organizationId}:{},...m.folderId?{folderId:m.folderId}:{}},baselines:y,baselineSnapshots:x,targetSnapshots:b,pendingNamespaces:ee,...h?{designatedTarget:{id:h.id,region:h.region}}:{}};return{state:{client:l,loaded:t,options:e,...i?{seedContext:i}:{}},prepared:S}}function createMigrationTestDependencies(){let e;return{prepare:async t=>{let{state:n,prepared:r}=await prepareMigrationTest(t);return e=n,r},createWorkspace:async t=>{let n=stateOrThrow(e),r=await rn(n.client,t.temporaryWorkspace);return C.info(`Created temporary workspace ${r.name} (${r.id}).`),{id:r.id,name:r.name}},deployBaseline:async({prepared:t,targetWorkspaceId:n})=>{let r=stateOrThrow(e);await deleteExistingUserProfileConfig(r,n),await yn({configPath:r.loaded.config.path,profile:r.options.profile,workspaceId:n,yes:!0},t.baselines,t.baselineSnapshots);for(let[e,i]of t.baselines)await $e(r.client,n,e,i.migrationNumber,i.historyId??void 0)},seedData:async({prepared:t,targetWorkspaceId:n})=>{let r=stateOrThrow(e),i=s(r.seedContext,`seed context missing after migration test preparation`),a=K.join(i.distPath,`data`);assertSeedDataDirectory(a);let o=new Map(r.loaded.application.tailorDBServices.map(e=>{let n=t.baselines.get(e.namespace),r=We(e);return[e.namespace,n?.snapshot??Zt({version:1,namespace:e.namespace,createdAt:(/* @__PURE__ */ new Date()).toISOString(),tables:r.types})]}));for(let[e,t]of o){let{order:o,selfRefTypes:s}=sortSeedTypesForSnapshot(t),c=loadSnapshotSeedData(a,o,t),l=o.filter(e=>(c[e]?.length??0)>0);if(l.length===0)continue;let u=await Ge(e,l,K.dirname(r.loaded.config.path)),d=ut({data:c,order:o,codeByteSize:new TextEncoder().encode(u.bundledCode).length}),f=authExecutionContext(r,e,r.options.machineUser??i.machineUserName);for(let t of d){let i=await Le({client:r.client,workspaceId:n,name:`migration-test-seed-${e}.ts`,code:u.bundledCode,arg:{data:t.data,order:t.order,selfRefTypes:s,upsert:!1},invoker:{namespace:f.authNamespace,machineUserName:f.machineUserName}});if(!i.success)throw U({code:`MIGRATION_TEST_SEED_FAILED`,message:i.error??`Seed execution failed for namespace "${e}".`});if(JSON.parse(i.result||`{}`).success!==!0)throw U({code:`MIGRATION_TEST_SEED_FAILED`,message:`Seed execution reported failure for namespace "${e}".`})}}},cloneData:async({prepared:t,sourceWorkspaceId:n,targetWorkspaceId:r,applicationName:i})=>{let a=stateOrThrow(e);await assertSourceBaselineFresh(a,t,n),C.warn(`Clone mode copies TailorDB records only; IdP users and file blobs are not copied.`);let o;try{o=(await a.client.cloneApplicationData({sourceWorkspaceId:n,sourceApplicationName:i,targetWorkspaceId:r,targetApplicationName:i})).operationId}catch(e){throw e instanceof Q&&e.code===Z.Unimplemented?U({code:`MIGRATION_TEST_CLONE_UNAVAILABLE`,message:`Application data clone is not enabled for this platform.`,suggestion:`Retry with --data seed.`,cause:e}):e}if(!o)throw Br(`Application data clone returned no operation ID.`);await waitForCloneApplicationData(a.client,{sourceWorkspaceId:n,targetWorkspaceId:r,operationId:o})},deployMigrations:async({prepared:t,targetWorkspaceId:n})=>{let r=stateOrThrow(e);await pr({configPath:r.loaded.config.path,profile:r.options.profile,workspaceId:n,yes:!0},t.targetSnapshots)},runAssertion:async({prepared:t,targetWorkspaceId:n,assertionPath:r,assertionNamespace:i,machineUser:a})=>{let o=stateOrThrow(e),s=resolveAssertionNamespace(t.pendingNamespaces,i),c=authExecutionContext(o,s,a),l=await an(r,s,0,o.loaded.config.env??{},K.dirname(o.loaded.config.path),Ar(o.loaded.plugins,`@tailor-platform/kysely-type`)?.temporal??!1,re(o.loaded.config)),u=await Le({client:o.client,workspaceId:n,name:`migration-test-assert-${s}.ts`,code:l.bundledCode,invoker:{namespace:c.authNamespace,machineUserName:c.machineUserName}});if(!u.success)throw U({code:`MIGRATION_TEST_ASSERTION_FAILED`,message:u.error??`Migration assertion failed for namespace "${s}".`})},deleteWorkspace:async t=>{await stateOrThrow(e).client.deleteWorkspace({workspaceId:t})}}}async function runMigrationTest(e,t=createMigrationTestDependencies()){if(e.targetWorkspaceId&&!e.yes)throw U({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`--target-workspace-id requires --yes because the target may be overwritten.`,command:`tailordb migration test`});if(e.keep&&e.targetWorkspaceId)throw U({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`--keep applies only to automatically created workspaces; a designated target is always retained.`,command:`tailordb migration test`});if(e.assertionNamespace&&!e.assertionPath)throw U({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`--assert is required when --assert-namespace is provided.`,command:`tailordb migration test`});let n=await t.prepare(e);if(assertTargetWorkspaceDiffers(n.sourceWorkspaceId,e.targetWorkspaceId),e.assertionPath&&resolveAssertionNamespace(n.pendingNamespaces,e.assertionNamespace),e.data===`clone`&&e.targetWorkspaceId){let e=s(n.designatedTarget,`designated clone target was not loaded during preparation`);assertCloneTargetRegion(n.temporaryWorkspace.region,e.region)}let r=e.targetWorkspaceId===void 0,i=r?await t.createWorkspace(n):{id:s(e.targetWorkspaceId,`designated target workspace missing`),name:void 0},a,o=!1,c=!1;try{let r={prepared:n,targetWorkspaceId:i.id};await t.deployBaseline(r);let a={...r,sourceWorkspaceId:n.sourceWorkspaceId,applicationName:n.sourceApplicationName};e.data===`clone`?await t.cloneData(a):await t.seedData(a),await t.deployMigrations(r),e.assertionPath&&await t.runAssertion({...r,assertionPath:e.assertionPath,assertionNamespace:e.assertionNamespace,machineUser:e.machineUser})}catch(e){a=e,o=!0}if(r&&e.keep)C.info(`Keeping temporary workspace ${i.name??i.id}.`);else if(r)try{await t.deleteWorkspace(i.id),c=!0}catch(t){if(!o)throw U({code:`MIGRATION_TEST_WORKSPACE_CLEANUP_FAILED`,message:`Failed to delete temporary workspace ${i.id}: ${t instanceof Error?t.message:String(t)}`,suggestion:e.profile?`Delete the temporary workspace manually with TAILOR_PLATFORM_PROFILE=${e.profile}.`:`Delete the temporary workspace manually.`,next:{command:`tailor`,args:[`workspace`,`delete`,`--workspace-id`,i.id]},cause:t});C.warn(`Failed to delete temporary workspace ${i.id}: ${t instanceof Error?t.message:String(t)}`)}if(o)throw a;return{success:!0,workspaceId:i.id,...i.name?{workspaceName:i.name}:{},temporary:r,deleted:c,data:e.data,pendingNamespaces:n.pendingNamespaces}}async function migrationTest(e){Ft(`tailordb migration`);let t=await runMigrationTest(e);if(e.json){C.out(t);return}C.success(`Pending migrations completed in workspace ${t.workspaceName??t.workspaceId}.`)}const eo=k({name:`test`,description:`Test pending migrations with seed fixtures or cloned data in a temporary workspace.`,notes:`The source workspace is read-only. Without --target-workspace-id, the command creates a workspace in the source workspace's region and deletes it after success or failure; pass --keep to retain it for inspection. A designated target is retained and requires --yes. Clone mode copies TailorDB records only; it does not copy IdP users or file blobs.`,args:q.strictObject({...j,yes:W(q.boolean().default(!1),{alias:`y`,description:`Acknowledge that a designated target workspace may be overwritten`}),data:W(q.enum([`seed`,`clone`]).default(`seed`),{description:`Data source for the migration test (seed or clone)`}),"target-workspace-id":W(q.uuid().optional(),{description:`Existing throwaway workspace to retain after the test (requires --yes)`}),keep:W(q.boolean().default(!1),{description:`Keep the automatically created workspace after the test`}),assert:W(q.string().optional(),{description:`Path to a TypeScript assertion script to run after migrations`,completion:{type:`file`,extensions:[`ts`]}}),"assert-namespace":W(q.string().optional(),{description:`TailorDB namespace exposed to the assertion script`}),"machine-user":W(q.string().optional(),{description:`Machine user for seed and assertion script execution`})}),run:async e=>{await F({profile:e.profile}),await migrationTest({configPath:e.config,workspaceId:e[`workspace-id`],profile:e.profile,data:e.data,targetWorkspaceId:e[`target-workspace-id`],keep:e.keep,assertionPath:e.assert,assertionNamespace:e[`assert-namespace`],machineUser:e[`machine-user`],yes:e.yes,json:C.jsonMode})}});function assertMigrationScriptsReady(e,t,n){let r=[],i=[],a=[],o=[],s=[];for(let t of Rt(e)){if(t.type!==`diff`)continue;let n=Nt(t.path),c=Oe(e,t.number,`migrate`),l=Y.existsSync(c);l&&s.push([t.number,c]),n.requiresMigrationScript&&!n.scriptSkipped&&!l&&r.push(t.number),n.scriptSkipped&&l&&i.push(t.number),l&&gn(c)>0&&a.push(t.number),n.hasWarnings&&!n.scriptSkipped&&!l&&o.push({migrationNumber:t.number,warnings:n.warnings})}if(r.length>0)throw U({code:`MIGRATION_SCRIPT_REQUIRED`,message:`Migration(s) ${r.map(A).join(`, `)} in namespace "${t}" require a migration script but have no migrate.ts.`,suggestion:`Add one with 'tailor tailordb migration script <number>', or record that no script is needed with 'tailor tailordb migration script <number> --no-script --reason "..."'.`});if(i.length>0){let e=i.map(e=>` ${Pn({migrationNumber:e,namespace:t,configPath:n})}`).join(`
|
|
88
|
-
`);throw U({code:`MIGRATION_SCRIPT_SKIP_CONFLICT`,message:`Migration(s) ${i.map(A).join(`, `)} in namespace "${t}" have both a --no-script skip acknowledgment and migrate.ts.`,suggestion:`Clear the stale acknowledgment(s):\n${e}\nOr delete migrate.ts to keep the skip.`})}if(a.length>0)throw U({code:`MIGRATION_SCRIPT_REVIEW_REQUIRED`,message:`Migration(s) ${a.map(A).join(`, `)} in namespace "${t}" still have a TODO() call or review marker in migrate.ts, where the generated script leaves a value or logic for you to decide.`,suggestion:Bn});for(let[e,n]of s){let r=_r(n);r.kind===`main`&&r.ignoredSteps&&C.warn(wn(`${t}/${A(e)}`))}return o}function buildValidationReports(e){let{targetNamespaces:t,migrationFileErrors:n,localResults:r,remoteResults:i,unacknowledgedWarnings:a}=e;return t.map(e=>{let t=n.get(e.namespace);if(t!==void 0)return{namespace:e.namespace,valid:!1,migrationFiles:{valid:!1,error:t}};let o=s(r.find(t=>t.namespace===e.namespace),`local schema check result missing for namespace "${e.namespace}"`),c={hasDiff:o.hasDiff,...o.diff?{diff:o.diff}:{}};if(i===void 0)return{namespace:e.namespace,valid:!1,migrationFiles:{valid:!0},localSchema:c,remoteSchema:{skipped:`check_failed`}};let l=s(i.find(t=>t.namespace===e.namespace),`remote schema check result missing for namespace "${e.namespace}"`),u=l.checkpointMissingLocal===!0,d={remoteMigrationNumber:l.remoteMigrationNumber,hasDrift:l.hasDrift,drifts:l.drifts,...l.skipped?{skipped:l.skipped}:{},...u?{checkpointMissingLocal:!0}:{},...l.rebaselinePending?{rebaselinePending:l.rebaselinePending}:{},...l.checkpointRepair?{checkpointRepair:l.checkpointRepair}:{}},f=a?.get(e.namespace),p;if(f!==void 0){let e=f.filter(e=>e.migrationNumber>l.remoteMigrationNumber);p={valid:e.length===0,missing:e}}return{namespace:e.namespace,valid:!c.hasDiff&&!d.hasDrift&&!u&&p?.valid!==!1,migrationFiles:{valid:!0},localSchema:c,remoteSchema:d,...p?{warningAcknowledgments:p}:{}}})}async function collectValidationReports(e){let{config:t,plugins:n}=await P(e.configPath),r=K.dirname(t.path),i=On(t,r);if(i.length===0)throw en();let a=e.namespace?i.filter(t=>t.namespace===e.namespace):i;if(a.length===0)throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`Namespace "${e.namespace}" not found or does not have migrations configured`});let o=n.length>0?new Qr(n):void 0,{defineApplication:s}=await import(`../application-nT_4a5HO.mjs`),c=s({config:t,pluginManager:o});for(let e of c.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();b({tailorDBServices:c.tailorDBServices});for(let{namespace:e}of a)if(!c.tailorDBServices.some(t=>t.namespace===e))throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${e}"`});let l=c.tailorDBServices.map(We),u=new Map(l.map(e=>[e.namespace,e.types])),d=/* @__PURE__ */ new Map,f=[],p=e.strict?/* @__PURE__ */ new Map:void 0;for(let t of a)try{kt(t.migrationsDir,t.namespace),E(t.migrationsDir);let n=assertMigrationScriptsReady(t.migrationsDir,t.namespace,e.configPath);p?.set(t.namespace,n),f.push(t)}catch(e){d.set(t.namespace,Vr(e))}let m={targetNamespaces:a,migrationFileErrors:d,localResults:await Ke(u,f),...p?{unacknowledgedWarnings:p}:{}};if(f.length===0)return{reports:buildValidationReports(m)};let h;try{let{client:n,workspaceId:r}=await N({profile:e.profile,workspaceId:e.workspaceId});h=await Mt(n,r,f,t,l)}catch(e){return{reports:buildValidationReports(m),remoteError:e}}return{reports:buildValidationReports({...m,remoteResults:h})}}function printValidationReports(e){for(let t of e){if(C.newline(),C.info(`Namespace: ${w.bold(t.namespace)}`),!t.migrationFiles.valid){C.log(` Migration files: ${w.error(`invalid`)}`),C.log(` ${t.migrationFiles.error}`);continue}C.log(` Migration files: ${w.success(`OK`)}`);let e=t.localSchema;e?.hasDiff?e.diff?(C.log(` Local schema: ${w.error(`changes not in migration files`)}`),C.log(` ${vn(e.diff)}`),C.log(fr(e.diff))):C.log(` Local schema: ${w.error(`no migration snapshot found`)}`):C.log(` Local schema: ${w.success(`OK`)}`);let n=t.remoteSchema;n?.skipped===`check_failed`?C.log(` Remote schema: ${w.error(`not checked`)}`):n?.checkpointRepair?C.log(` Remote schema: ${w.success(`OK`)} (next deploy will reset the checkpoint to 0000 from ${A(n.checkpointRepair.from)})`):n?.checkpointMissingLocal?(C.log(` Remote schema: ${w.error(`remote migration ${A(n.remoteMigrationNumber)} is not in the local migration history`)}`),n.rebaselinePending&&C.log(` Fell behind before 'migration rebaseline' ran; must reach ${A(n.rebaselinePending.replacedLatestMigration)} first.`)):n?.hasDrift?(C.log(` Remote schema: ${w.error(`drift detected`)} (remote migration: ${A(n.remoteMigrationNumber)})`),C.log(Tt(n.drifts))):n?.skipped===`not_deployed`?C.log(` Remote schema: ${w.dim(`skipped (namespace not deployed)`)}`):n?.skipped===`no_migration_label`?C.log(` Remote schema: ${w.dim(`skipped (deployed namespace has no migration state)`)}`):n?.skipped===`no_snapshot`?C.log(` Remote schema: ${w.dim(`skipped (no local snapshot for remote migration ${A(n.remoteMigrationNumber)})`)}`):n&&C.log(` Remote schema: ${w.success(`OK`)} (remote migration: ${A(n.remoteMigrationNumber)})`);let r=t.warningAcknowledgments;if(r){if(r.valid)C.log(` Warning acknowledgments: ${w.success(`OK`)}`);else{C.log(` Warning acknowledgments: ${w.error(`missing for pending migration(s) with possible data loss`)}`);for(let e of r.missing){let t=A(e.migrationNumber);for(let n of e.warnings){let e=n.fieldName?`.${n.fieldName}`:``;C.log(` ${t}: ${n.tableName}${e}: ${n.reason}`)}}}}}C.newline()}function hasMissingCheckpoint(e){return e.remoteSchema?.checkpointMissingLocal===!0}function printResolutionHints(e,t){e.some(e=>e.localSchema?.hasDiff&&!e.localSchema.diff)&&C.info(`Run 'tailor tailordb migration generate' to create the initial snapshot.`),e.some(e=>e.localSchema?.diff)&&C.info(`Run 'tailor tailordb migration generate' to create migration files.`);let n=e.filter(hasMissingCheckpoint);n.length>0&&De(n.map(e=>({namespace:e.namespace,remoteMigrationNumber:e.remoteSchema.remoteMigrationNumber,...e.remoteSchema.rebaselinePending?{rebaselinePending:e.remoteSchema.rebaselinePending}:{}}))),e.some(e=>e.remoteSchema?.hasDrift)&&Lt(e.map(e=>({hasDrift:e.remoteSchema?.hasDrift??!1,drifts:e.remoteSchema?.drifts??[]})));let r=e.filter(e=>e.warningAcknowledgments&&!e.warningAcknowledgments.valid);if(r.length>0){C.info(`For each migration listed, either add a data migration script with 'tailor tailordb migration script <number>' or record why none is needed:`);for(let e of r)for(let n of e.warningAcknowledgments?.missing??[])C.info(` ${Pn({migrationNumber:n.migrationNumber,namespace:e.namespace,configPath:t,noScript:!0})}`,{mode:`plain`})}}async function validate(e){Ft(`tailordb migration`);let t=await collectValidationReports(e),{reports:n}=t,r=n.filter(e=>!e.valid).length;if(e.json?C.out(n):(printValidationReports(n),r===0&&!(`remoteError`in t)?C.success(`All migration validation checks passed.`):printResolutionHints(n,e.configPath)),`remoteError`in t)throw t.remoteError;if(r>0)throw U({code:`MIGRATION_VALIDATION_FAILED`,message:`Migration validation failed for ${r} namespace(s)`})}const to=k({name:`validate`,description:`Validate the full migration history, unreviewed generated migration scripts, and schema drift (local tables vs. migration snapshot, remote schema vs. migration checkpoint) without deploying. This includes the migration and schema-drift checks used by 'deploy' and exits with a non-zero code when issues are found.`,args:q.strictObject({...j,namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (validates all namespaces if not specified)`}),strict:W(q.boolean().default(!1),{description:`Also fail when a pending migration can drop data without an acknowledgment`})}),run:async e=>{await validate({configPath:e.config,namespace:e.namespace,workspaceId:e[`workspace-id`],profile:e.profile,json:C.jsonMode,strict:e.strict})}}),no=G({name:`migration`,description:`Manage TailorDB schema migrations.`,subCommands:{generate:vt,rebaseline:Xa,script:Pr,set:Za,status:Qa,sync:$a,test:eo,validate:to}}),ro=G({name:`tailordb`,description:`Manage TailorDB tables and data.`,notes:"The `tailordb erd` commands are provided by the @tailor-platform/sdk-plugin-tailordb-erd CLI plugin.",subCommands:{truncate:rt,migration:no}}),io=k({name:`upgrade`,description:`Run codemods to upgrade your project to a newer SDK version.`,args:q.strictObject({from:W(q.string(),{description:`SDK version before the upgrade (e.g., 1.33.0)`}),"dry-run":W(q.boolean().default(!1),{alias:`d`,description:`Preview changes without modifying files`}),path:W(q.string().default(`.`),{description:`Project directory to upgrade`,completion:{type:`directory`}})}),run:async e=>{let{initTelemetry:t}=await import(`../telemetry-DXHP3VVi.mjs`);await t();let{upgrade:n}=await import(`../service-DFmt9UJP.mjs`);await n({from:e.from,dryRun:e[`dry-run`],path:K.resolve(e.path)})}}),ao=k({name:`current`,description:`Show current user.`,args:q.strictObject({profile:R.profile}),run:async e=>{let t=await T(),n=e.profile||process.env.TAILOR_PLATFORM_PROFILE,r=n?t.profiles[n]:void 0;if(n&&!r)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${n}" not found`});let i=r?Rn(r):void 0,a=n?r?.user??null:t.current_user,o=C.jsonMode;if(!a)throw U({code:`USER_NOT_SET`,message:`Current user not set.`,suggestion:`Log in first to register a user.`,next:{command:`tailor`,args:[`login`,...gt({profile:n})]}});if(!sn(t,a,i))throw U({code:`USER_NOT_FOUND`,message:`Current user '${a}' not found in registered users.`,suggestion:`Log in again to register the user.`,next:{command:`tailor`,args:[`login`,...gt({profile:n})]}});if(o){C.out({user:a});return}C.out(a)}});function activeCurrentUserKey(e,t){if(!t)return e.current_user?dt(e,e.current_user):null;let n=e.profiles[t];if(!n)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${t}" not found`});return dt(e,n.user,Rn(n))}function toUserListInfo(e,t){let n=e.indexOf(`|`),r=n===-1?null:e.slice(0,n);return{user:n===-1?e:e.slice(n+1),platformUrl:r,current:t===e}}function formatUserListInfo(e){return`${e.user}${e.platformUrl?` [${e.platformUrl}]`:``}${e.current?` (current)`:``}`}const oo=k({name:`list`,description:`List all users.`,args:q.strictObject({profile:R.profile}),run:async e=>{let t=await T(),n=C.jsonMode,r=activeCurrentUserKey(t,e.profile||process.env.TAILOR_PLATFORM_PROFILE),i=Object.keys(t.users);if(i.length===0){C.info(V`
|
|
86
|
+
`),t&&x.out([]);return}let r=n.map(([e,t])=>{let n=s(t,`profile entry "${e}" is undefined`);return{name:e,user:n.user,workspaceId:n.workspace_id,permission:n.readonly===!0?`read`:`write`,...n.machine_user?{machineUser:n.machine_user,machineUserOverride:n.machine_user_override??`allow`}:{},...n.platform_url?{platformUrl:n.platform_url}:{},...n.oauth2_client_id?{oauth2ClientId:n.oauth2_client_id}:{},...n.console_url?{consoleUrl:n.console_url}:{}}});x.out(r)}}),Ga=C({name:`update`,description:`Update profile properties.`,args:q.strictObject({name:W(q.string(),{positional:!0,description:`Profile name`}),user:W(q.string().optional(),{alias:`u`,description:`New user email address or machine user client ID`}),"workspace-id":W(q.string().optional(),{alias:`w`,description:`New workspace ID`}),permission:W(q.enum([`write`,`read`]).optional(),{description:`Profile permission. 'read' blocks all write commands; 'write' lifts the restriction.`}),"machine-user":W(q.string().optional(),{alias:`m`,description:`Default machine user name for application-data commands (query, workflow start, function run, machineuser token). Pass an empty string to clear.`}),"machine-user-override":W(q.enum([`allow`,`deny`]).optional(),{description:`Whether the command line or TAILOR_PLATFORM_MACHINE_USER_NAME may override the profile's machine user. 'deny' requires --machine-user; 'allow' lifts the restriction.`}),"platform-url":W(q.union([q.url(),q.literal(``)]).optional(),{description:`Platform API base URL for this profile. Pass an empty string to clear.`}),"oauth2-client-id":W(q.string().optional(),{description:`OAuth2 client ID for logging in to this profile's platform. Pass an empty string to clear.`}),"console-url":W(q.union([q.url(),q.literal(``)]).optional(),{description:`Console base URL for this profile. Pass an empty string to clear.`})}),run:async e=>{let t=await w(),n=t.profiles[e.name];if(!n)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${e.name}" not found.`});if(!e.user&&!e[`workspace-id`]&&e.permission===void 0&&e[`machine-user`]===void 0&&e[`machine-user-override`]===void 0&&e[`platform-url`]===void 0&&e[`oauth2-client-id`]===void 0&&e[`console-url`]===void 0)throw U({code:`PROFILE_UPDATE_EMPTY`,message:`Please provide at least one property to update.`,command:`profile update`});let r=n.user,i=e.user||r,a=n.workspace_id,o=e[`workspace-id`]||a,s=i,c=e[`machine-user`]===``?void 0:e[`machine-user`]??n.machine_user,l=e[`machine-user-override`]===`allow`?void 0:e[`machine-user-override`]??n.machine_user_override,u=e[`platform-url`]===``?void 0:e[`platform-url`]??n.platform_url,d=e[`oauth2-client-id`]===``?void 0:e[`oauth2-client-id`]??n.oauth2_client_id,f=e[`console-url`]===``?void 0:e[`console-url`]??n.console_url,p={...u?{platformUrl:u}:{},...d?{oauth2ClientId:d}:{},...f?{consoleUrl:f}:{}},m=Object.keys(p).length>0?p:void 0,h=e[`platform-url`]===``?pt(n):m;if((e[`machine-user`]!==void 0||e[`machine-user-override`]!==void 0)&&l===`deny`&&!c)throw e[`machine-user-override`]===`deny`?U({code:`PROFILE_OPTIONS_INVALID`,message:`--machine-user-override deny requires --machine-user.`,command:`profile update`}):U({code:`PROFILE_OPTIONS_INVALID`,message:`Cannot clear the machine user while machine-user-override is "deny". Also pass --machine-user-override allow.`,command:`profile update`});if(e.user!==void 0||e[`workspace-id`]!==void 0||e[`platform-url`]!==void 0){let n=await Br(t,i,h,e.name);s=n.user;let r=await xe(n.accessToken,m);if(!(await _(async(e,t)=>{let{workspaces:n,nextPageToken:i}=await r.listWorkspaces({pageToken:e,pageSize:t});return[n,i]})).find(e=>e.id===o))throw U({code:`WORKSPACE_NOT_FOUND`,message:`Workspace "${o}" not found.`})}n.user=s,n.workspace_id=o,e.permission===`read`?n.readonly=!0:e.permission===`write`&&delete n.readonly,e[`machine-user`]!==void 0&&(e[`machine-user`]===``?delete n.machine_user:n.machine_user=e[`machine-user`]),e[`machine-user-override`]===`deny`?n.machine_user_override=`deny`:e[`machine-user-override`]===`allow`&&delete n.machine_user_override,e[`platform-url`]!==void 0&&(e[`platform-url`]===``?delete n.platform_url:n.platform_url=e[`platform-url`]),e[`oauth2-client-id`]!==void 0&&(e[`oauth2-client-id`]===``?delete n.oauth2_client_id:n.oauth2_client_id=e[`oauth2-client-id`]),e[`console-url`]!==void 0&&(e[`console-url`]===``?delete n.console_url:n.console_url=e[`console-url`]),T(t),e.json||x.success(`Profile "${e.name}" updated successfully`);let g={name:e.name,user:s,workspaceId:o,permission:n.readonly===!0?`read`:`write`,...n.machine_user?{machineUser:n.machine_user,machineUserOverride:n.machine_user_override??`allow`}:{},...n.platform_url?{platformUrl:n.platform_url}:{},...n.oauth2_client_id?{oauth2ClientId:n.oauth2_client_id}:{},...n.console_url?{consoleUrl:n.console_url}:{}};x.out(g)}}),Ka=G({name:`profile`,description:`Manage workspace profiles (user + workspace combinations).`,subCommands:{create:Ha,delete:Ua,list:Wa,update:Ga},defaultSubCommand:`list`});async function resolveSecretValue(e,t,n){if(e.value!==void 0)return e.value;let missing=e=>U({code:`SECRET_VALUE_REQUIRED`,message:`No secret value was given: --value is omitted and standard input ${e}.`,suggestion:`Pass --value, or pipe or redirect the value into the command.`,command:n});if(t.isTTY===!0)throw missing(`is a terminal`);let tooLarge=()=>U({code:`SECRET_VALUE_TOO_LARGE`,message:`The secret value read from standard input exceeds 128 KiB.`,command:n}),r=[],i=0;for await(let e of t){let t=typeof e==`string`?Buffer.from(e):e;if(i+=t.length,i>131074)throw tooLarge();r.push(t)}let a;try{a=new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}).decode(Buffer.concat(r))}catch(e){throw U({code:`SECRET_VALUE_INVALID_UTF8`,message:`The secret value read from standard input is not valid UTF-8.`,command:n,cause:e})}let o=a.replace(/\r?\n$/,``);if(Buffer.byteLength(o)>131072)throw tooLarge();if(o===``)throw missing(`is empty`);return o}const qa={"vault-name":W(q.string(),{alias:`V`,description:`Vault name`})},Ja={...qa,name:W(q.string(),{alias:`n`,description:`Secret name`})},Ya={...Ja,value:W(q.string().optional(),{alias:`v`,description:`Secret value (read from standard input when omitted)`})};function secretValueNotes(e){return`Pass the value with \`--value\`, or omit \`--value\` and pipe the value in to keep it out of shell history and process listings, for example \`printf '%s' "$STRIPE_KEY" | tailor secret ${e} --vault-name api-keys --name stripe-secret-key\`. A piped value can be up to 128 KiB, and one trailing newline is removed from it. In a vault managed by \`defineSecretManager()\`, the command asks for confirmation before releasing the vault from the config, which needs an interactive terminal, so pass \`--yes\` when piping the value.`}async function checkVaultManaged(e){let{client:t,workspaceId:n,vaultName:r}=e,i=I(n,`vault`,r),a={isManaged:!1,trn:i,existingLabels:{}},o,s;try{let{metadata:e}=await t.getMetadata({trn:i});s=e?.labels??{},o=s[Yn]}catch{return a}return o?(x.warn(`Vault "${r}" is managed by defineSecretManager() in tailor.config.ts (owner: "${o}"). Changes made via CLI may conflict with the config on the next apply.`),{isManaged:!0,trn:i,existingLabels:s}):a}async function releaseVaultOwnership(e){let{client:t,trn:n}=e;await bn(t,{trn:n,remove:[Yn,kr,gn]}),x.info(`Config ownership has been removed from this vault. Remove it from defineSecretManager() in your config to prevent the next apply from re-claiming it.`)}const Xa=C({name:`create`,description:`Create a secret in a vault.`,args:q.strictObject({...M,...Ya,...F}),notes:secretValueNotes(`create`),run:async e=>{let t=await resolveSecretValue(e,process.stdin,`secret create`);x.registerSecret(t),await R({profile:e.profile});let{client:n,workspaceId:r}=await A({profile:e.profile,workspaceId:e[`workspace-id`]}),i=await checkVaultManaged({client:n,workspaceId:r,vaultName:e[`vault-name`]});if(i.isManaged&&!e.yes&&!await N.confirm({message:`Do you want to proceed?`,default:!1}))throw U({code:`SECRET_CREATION_CANCELLED`,message:`Secret creation cancelled. The vault is still managed by the config.`});try{await n.createSecretManagerSecret({workspaceId:r,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name,secretmanagerSecretValue:t})}catch(t){if(t instanceof Q){if(t.code===Z.NotFound)throw U({code:`VAULT_NOT_FOUND`,message:`Vault "${e[`vault-name`]}" not found.`,cause:t});if(t.code===Z.AlreadyExists)throw U({code:`SECRET_EXISTS`,message:`Secret "${e.name}" already exists.`,cause:t})}throw t}i.isManaged&&await releaseVaultOwnership({client:n,...i}),x.success(`Secret: ${e.name} created in vault: ${e[`vault-name`]}`),k({changed:!0,workspaceId:r,vaultName:e[`vault-name`],name:e.name,vaultOwnershipReleased:i.isManaged})}}),Za=C({name:`delete`,description:`Delete a secret in a vault.`,args:q.strictObject({...M,...Ja,...F}),run:async e=>{await R({profile:e.profile});let{client:t,workspaceId:n}=await A({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e[`vault-name`]});if(!e.yes&&await N.text({message:`Enter the secret name to confirm deletion ("${e.name}"):`})!==e.name)throw U({code:`SECRET_DELETION_CANCELLED`,message:`Secret deletion cancelled: the entered name did not match.`,suggestion:`Run the command again and enter the name exactly as shown, or pass --yes to skip the confirmation.`});try{await t.deleteSecretManagerSecret({workspaceId:n,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`SECRET_NOT_FOUND`,message:`Secret "${e.name}" not found in vault "${e[`vault-name`]}".`,cause:t}):t}r.isManaged&&await releaseVaultOwnership({client:t,...r}),x.success(`Secret: ${e.name} deleted from vault: ${e[`vault-name`]}`),k({changed:!0,workspaceId:n,vaultName:e[`vault-name`],name:e.name,vaultOwnershipReleased:r.isManaged})}});function secretInfo(e){return{name:e.name,createdAt:e.createTime?X(e.createTime):null,updatedAt:e.updateTime?X(e.updateTime):null}}async function secretList(e){let{client:t,workspaceId:n}=await A({profile:e.profile,workspaceId:e.workspaceId}),r=hn(e.order);return(await be(async(i,a)=>{let{secrets:o,nextPageToken:s}=await t.listSecretManagerSecrets({workspaceId:n,secretmanagerVaultName:e.vaultName,pageToken:i,pageSize:a,pageDirection:r});return[o,s]},{limit:e.limit})).map(secretInfo)}const Qa=C({name:`list`,description:`List all secrets in a vault.`,args:q.strictObject({...M,...qa,...vr()}),run:async e=>{try{let t=await An(e.limit,t=>secretList({workspaceId:e[`workspace-id`],profile:e.profile,vaultName:e[`vault-name`],order:e.order,limit:t})),n=t.items;x.out(n),await P(t,e.limit)}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`VAULT_NOT_FOUND`,message:`Vault "${e[`vault-name`]}" not found.`,cause:t}):t}}}),$a=C({name:`update`,description:`Update a secret in a vault.`,args:q.strictObject({...M,...Ya,...F}),notes:secretValueNotes(`update`),run:async e=>{let t=await resolveSecretValue(e,process.stdin,`secret update`);x.registerSecret(t),await R({profile:e.profile});let{client:n,workspaceId:r}=await A({profile:e.profile,workspaceId:e[`workspace-id`]}),i=await checkVaultManaged({client:n,workspaceId:r,vaultName:e[`vault-name`]});if(i.isManaged&&!e.yes&&!await N.confirm({message:`Do you want to proceed?`,default:!1}))throw U({code:`SECRET_UPDATE_CANCELLED`,message:`Secret update cancelled. The vault is still managed by the config.`});try{await n.updateSecretManagerSecret({workspaceId:r,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name,secretmanagerSecretValue:t})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`SECRET_NOT_FOUND`,message:`Secret "${e.name}" not found in vault "${e[`vault-name`]}".`,cause:t}):t}i.isManaged&&await releaseVaultOwnership({client:n,...i}),x.success(`Secret: ${e.name} updated in vault: ${e[`vault-name`]}`),k({changed:!0,workspaceId:r,vaultName:e[`vault-name`],name:e.name,vaultOwnershipReleased:i.isManaged})}}),eo={name:W(q.string(),{positional:{named:!0},description:`Vault name`})},to=C({name:`create`,description:`Create a new Secret Manager vault.`,args:q.strictObject({...M,...eo}),run:async e=>{await R({profile:e.profile});let{client:t,workspaceId:n}=await A({profile:e.profile,workspaceId:e[`workspace-id`]});try{await t.createSecretManagerVault({workspaceId:n,secretmanagerVaultName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.AlreadyExists?U({code:`VAULT_EXISTS`,message:`Vault "${e.name}" already exists.`,cause:t}):t}x.success(`Vault: ${e.name} created`),k({changed:!0,workspaceId:n,name:e.name})}}),no=C({name:`delete`,description:`Delete a Secret Manager vault.`,args:q.strictObject({...M,...eo,...F}),run:async e=>{await R({profile:e.profile});let{client:t,workspaceId:n}=await A({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e.name});if(!e.yes&&await N.text({message:`Enter the vault name to confirm deletion ("${e.name}"):`})!==e.name)throw U({code:`VAULT_DELETION_CANCELLED`,message:`Vault deletion cancelled: the entered name did not match.`,suggestion:`Run the command again and enter the name exactly as shown, or pass --yes to skip the confirmation.`});try{await t.deleteSecretManagerVault({workspaceId:n,secretmanagerVaultName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`VAULT_NOT_FOUND`,message:`Vault "${e.name}" not found.`,cause:t}):t}r.isManaged&&x.info(`Remove this vault from defineSecretManager() in your config to prevent the next apply from re-creating it.`),x.success(`Vault: ${e.name} deleted`),k({changed:!0,workspaceId:n,name:e.name,managed:r.isManaged})}});function vaultInfo(e){return{name:e.name,createdAt:e.createTime?X(e.createTime):null,updatedAt:e.updateTime?X(e.updateTime):null}}async function vaultList(e){let{client:t,workspaceId:n}=await A({profile:e?.profile,workspaceId:e?.workspaceId}),r=hn(e?.order);return(await be(async(e,i)=>{let{vaults:a,nextPageToken:o}=await t.listSecretManagerVaults({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e?.limit})).map(vaultInfo)}const ro=C({name:`list`,description:`List all Secret Manager vaults in the workspace.`,args:q.strictObject({...M,...vr()}),run:async e=>{let t=await An(e.limit,t=>vaultList({workspaceId:e[`workspace-id`],profile:e.profile,order:e.order,limit:t})),n=t.items;x.out(n),await P(t,e.limit)}}),io=G({name:`vault`,description:`Manage Secret Manager vaults.`,subCommands:{create:to,delete:no,list:ro},defaultSubCommand:`list`}),ao=G({name:`secret`,description:`Manage Secret Manager vaults and secrets.`,subCommands:{vault:io,create:Xa,update:$a,list:Qa,delete:Za},defaultSubCommand:`vault`}),oo={[n.UNSPECIFIED]:`unspecified`,[n.PENDING]:`pending`,[n.VERIFYING]:`verifying`,[n.CERT_ISSUED]:`cert_issued`,[n.ACTIVE]:`active`,[n.FAILED]:`failed`},so=C({name:`get`,description:`Get details of a custom domain.`,args:q.strictObject({...M,domain:W(q.string(),{positional:!0,description:`Custom domain name`})}),run:async e=>{let{client:t,workspaceId:n}=await A({profile:e.profile,workspaceId:e[`workspace-id`]}),r=`Custom domain "${e.domain}" not found.`;try{let{customDomain:i}=await t.getCustomDomain({workspaceId:n,domain:e.domain});if(!i)throw U({code:`STATIC_WEBSITE_DOMAIN_NOT_FOUND`,message:r});let a={domain:i.domain,status:oo[i.status]??`unknown`,trafficCnameTarget:i.trafficCnameTarget,certificateCnameTarget:i.certificateCnameTarget,errorMessage:i.errorMessage||void 0};x.out(a)}catch(e){throw e instanceof Q&&e.code===Z.NotFound?U({code:`STATIC_WEBSITE_DOMAIN_NOT_FOUND`,message:r,cause:e}):e}}}),co=C({name:`list`,description:`List custom domains for a static website.`,args:q.strictObject({...M,name:W(q.string(),{positional:!0,description:`Static website name`})}),run:async e=>{let{client:t,workspaceId:n}=await A({profile:e.profile,workspaceId:e[`workspace-id`]});try{let{customDomains:r}=await t.listCustomDomains({workspaceId:n,staticWebsiteName:e.name});if(r.length===0){x.info(`No custom domains found.`),x.jsonMode&&x.out([]);return}let i=r.map(e=>({domain:e.domain,status:oo[e.status]??`unknown`,trafficCnameTarget:e.trafficCnameTarget,certificateCnameTarget:e.certificateCnameTarget}));x.out(i)}catch(t){throw t instanceof Q&&t.code===Z.NotFound?U({code:`STATIC_WEBSITE_NOT_FOUND`,message:`Static website "${e.name}" not found.`,cause:t}):t}}}),lo=G({name:`domain`,description:`Manage custom domains for static websites.`,subCommands:{list:co,get:so}}),uo=C({name:`get`,description:`Get details of a specific static website.`,args:q.strictObject({...M,name:W(q.string(),{positional:!0,description:`Static website name`})}),run:async e=>{let{client:t,workspaceId:n}=await A({profile:e.profile,workspaceId:e[`workspace-id`]}),r=`Static website "${e.name}" not found.`;try{let{staticwebsite:i}=await t.getStaticWebsite({workspaceId:n,name:e.name});if(!i)throw U({code:`STATIC_WEBSITE_NOT_FOUND`,message:r});let a={workspaceId:n,name:i.name,description:i.description,url:i.url,allowedIpAddresses:e.json?i.allowedIpAddresses:i.allowedIpAddresses.join(`
|
|
87
|
+
`)};x.out(a)}catch(e){throw e instanceof Q&&e.code===Z.NotFound?U({code:`STATIC_WEBSITE_NOT_FOUND`,message:r,cause:e}):e}}});async function listStaticWebsites(e){let{client:t,workspaceId:n}=await A({profile:e?.profile,workspaceId:e?.workspaceId}),r=hn(e?.order);return(await be(async(e,i)=>{let{staticwebsites:a,nextPageToken:o}=await t.listStaticWebsites({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e?.limit})).map(e=>({workspaceId:n,name:e.name,description:e.description,url:e.url,allowedIpAddresses:e.allowedIpAddresses}))}const fo=C({name:`list`,description:`List all static websites in a workspace.`,args:q.strictObject({...M,...vr()}),run:async e=>{let t=x.jsonMode,n=await An(e.limit,t=>listStaticWebsites({workspaceId:e[`workspace-id`],profile:e.profile,order:e.order,limit:t})),r=n.items,i=t?r:r.map(({allowedIpAddresses:e,...t})=>{if(e.length===0)return{...t,allowedIpAddresses:`No allowed IP addresses`};let n=e.length,r=n===1?`1 IP address`:`${n} IP addresses`;return{...t,allowedIpAddresses:r}});x.out(i),await P(n,e.limit)}}),po=G({name:`staticwebsite`,description:`Manage static websites in your workspace.`,subCommands:{deploy:vt,domain:lo,list:fo,get:uo},defaultSubCommand:`list`}),mo=new Set(Object.values(dt));async function activateBaseline(e,t,n,r){let i=await $.realpath(e),a=K.dirname(i),o=K.basename(i),s=await $.mkdtemp(K.join(a,`.${o}-rebaseline-`)),c=`${s}-previous`,l=!1,u=!1;try{await $.cp(i,s,{recursive:!0});for(let e of await $.readdir(s,{withFileTypes:!0})){if(!e.isDirectory()||!Et.test(e.name))continue;let t=K.join(s,e.name);(await $.readdir(t)).some(e=>mo.has(e))&&await $.rm(t,{recursive:!0,force:!0})}let e={...t,namespace:n,version:8,createdAt:(/* @__PURE__ */ new Date()).toISOString(),rebaseline:r},a=await Xe(e,s,0);gr(a.filePath),await $.rename(i,c),l=!0;try{await $.rename(s,i),u=!0}catch(e){throw await $.rename(c,i),l=!1,e}try{await $.rm(c,{recursive:!0,force:!0})}catch(e){x.warn(`The previous migration directory remains at ${c}: ${e instanceof Error?e.message:String(e)}`)}l=!1}finally{Y.existsSync(s)&&await $.rm(s,{recursive:!0,force:!0}),!u&&l&&Y.existsSync(c)&&await $.rename(c,i)}}async function rebaseline(e){ct(`tailordb migration`);let{config:t,plugins:n}=await z(e.configPath),r=K.dirname(t.path),i=Vr(B(t,r),e.namespace),a=`First run ${H({command:`tailor`,args:[`tailordb`,`migration`,`generate`,`--config`,t.path]})}.`;gt(i.migrationsDir,i.namespace);let o=j(i.migrationsDir);if(!o)throw U({code:`MIGRATION_HISTORY_NOT_FOUND`,message:`No migration history found for namespace "${i.namespace}".`,suggestion:a});let s=Ht(i.migrationsDir),c=j(i.migrationsDir,0)?.rebaseline?.historyId??null,l=Fe([i])[i.namespace],u=n.length>0?new ui(n):void 0,{defineApplication:d}=await import(`../application-dalGHdrI.mjs`),f=d({config:t,pluginManager:u});for(let e of f.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let p=f.tailorDBServices.find(e=>e.namespace===i.namespace);if(!p)throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${i.namespace}"`});let assertLocalTypesReady=()=>{let e=Ve(p.types,i.namespace),t=tn(o,e.tables,i.namespace);if(cn(t))throw x.error(`Migration history does not reproduce the current local schema for namespace ${S.bold(i.namespace)}:`),x.log(Vn(t)),U({code:`MIGRATION_HISTORY_MISMATCH`,message:`Refusing to re-baseline: the migration history must reproduce the current local schema.`,suggestion:a})},localSourceFiles=()=>[t.path,...Jr(p.config,r)];assertLocalTypesReady();let m=jt(localSourceFiles()),{client:h,workspaceId:g}=await A({profile:e.profile,workspaceId:e.workspaceId}),_=[`--config`,t.path,...O({workspaceId:g,profile:e.profile})],v=`Run ${H({command:`tailor`,args:[`tailordb`,`migration`,`set`,`0`,`--namespace`,i.namespace,..._]})}`,y=`after resolving the connection error, deploy with schema checks enabled by running ${H({command:`tailor`,args:[`deploy`,..._]})}.`,assertConnectedWorkspaceReady=async(e,n)=>{let r=await D(h,I(g,`tailordb`,i.namespace));In(r,i.namespace);let a=r.number;if(a!==s){let e=a===null?`<unset>`:L(a);throw U({code:`REBASELINE_CHECKPOINT_BEHIND`,message:`The connected workspace must be at the latest migration ${L(s)} before re-baselining; current checkpoint is ${e}.`})}if(r.historyIdInvalid)throw U({code:`REBASELINE_REMOTE_HISTORY_INVALID`,message:`Refusing to re-baseline: the connected workspace has an invalid migration history marker.`});if(r.historyId!==e)throw U(n===`confirmation`?{code:`REBASELINE_STATE_CHANGED`,message:`The connected workspace migration history changed while waiting for confirmation.`,suggestion:`Run the command again.`}:{code:`REBASELINE_REMOTE_HISTORY_MISMATCH`,message:`Refusing to re-baseline: the connected workspace does not match the local migration history.`});let o=await Lt(h,g,[i],t,[Ye(p)]),c=o[0];if(!c||c.remoteMigrationNumber!==s||c.hasDrift||c.checkpointMissingLocal)throw c?.hasDrift&&(x.error(`Remote schema drift detected:`),x.log(qr(o))),U({code:`REBASELINE_REMOTE_SCHEMA_MISMATCH`,message:`Refusing to re-baseline: the connected workspace remote schema must match the latest migration.`})};if(await assertConnectedWorkspaceReady(c,`initial`),x.newline(),x.warn(`This will replace the migration history for ${S.bold(i.namespace)}.`),x.log(` Latest migration: ${L(s)}`),x.log(` New history: 0000/schema.json only`),x.log(` migrate.ts and db.ts files will disappear from the working tree.`),x.log(` Committed migration files will remain in Git history. Preserve any uncommitted files before continuing.`),x.log(` Every other environment must already be at the latest migration.`),x.log(` The connected workspace checkpoint will be reset to 0000.`),x.newline(),!e.yes&&!await N.confirm({message:`Re-baseline this migration history and reset the connected workspace checkpoint?`,default:!1}))throw U({code:`REBASELINE_CANCELLED`,message:`Migration re-baseline cancelled.`});if(gt(i.migrationsDir,i.namespace),Fe([i])[i.namespace]!==l)throw U({code:`REBASELINE_STATE_CHANGED`,message:`Migration files changed while waiting for confirmation.`,suggestion:`Run the command again.`});if(jt(localSourceFiles())!==m)throw U({code:`REBASELINE_STATE_CHANGED`,message:`Local TailorDB table or config files changed.`,suggestion:`Run the command again.`});assertLocalTypesReady(),await assertConnectedWorkspaceReady(c,`confirmation`);let b={historyId:Qt(),replacedHistoryId:c,replacedLatestMigration:s};await activateBaseline(i.migrationsDir,o,i.namespace,b);try{await Yt(h,g,i.namespace,0,b.historyId)}catch(e){throw U({code:`REBASELINE_CHECKPOINT_UPDATE_FAILED`,message:`The local migration history was re-baselined, but the connected workspace checkpoint could not be updated.`,suggestion:`${v}, or ${y}`,cause:e})}return x.success(`Re-baselined ${S.bold(i.namespace)} and reset the connected workspace checkpoint to 0000.`),{changed:!0,workspaceId:g,namespace:i.namespace,...b,schemaPath:Rt(i.migrationsDir,0,`schema`)}}const ho=C({name:`rebaseline`,description:`Collapse the full migration history into a new 0000 baseline.`,notes:`Re-baselining removes migrations after 0000 from the working tree, records a new migration history ID, and resets the connected workspace checkpoint without changing its schema or data. Every environment must already have applied the latest migration before you run this command.`,args:q.strictObject({...E,...F,namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await R({profile:e.profile});let t=await rebaseline({configPath:e.config,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile});k(t)}});async function fetchRemoteGqlPermissions(e){let{client:t,workspaceId:n,namespace:r}=e;return c(async(e,i)=>{let{permissions:a,nextPageToken:o}=await t.listTailorDBGQLPermissions({workspaceId:n,namespaceName:r,pageToken:e,pageSize:i});return[a,o]})}async function fetchRemoteTypes(e){let{client:t,workspaceId:n,namespace:r}=e;return _(async(e,i)=>{try{let{tailordbTypes:a,nextPageToken:o}=await t.listTailorDBTypes({workspaceId:n,namespaceName:r,pageToken:e,pageSize:i});return[a,o]}catch(e){throw e instanceof Q&&e.code===Z.NotFound?U({code:`MIGRATION_NAMESPACE_NOT_DEPLOYED`,message:`Cannot apply the snapshot: TailorDB namespace "${r}" has not been deployed yet.`,suggestion:`Deploy the namespace first.`,cause:e}):e}})}async function planSnapshotApply(e){let{snapshot:t,...n}=e,r=await fetchRemoteTypes(n),i=new Set(r.map(e=>e.name)),{creates:a,updates:o,deletes:s}=Ke(t,i),c=await fetchRemoteGqlPermissions(n),l=new Set(c.map(e=>e.typeName)),u=Object.entries(t.tables).flatMap(([e,t])=>t.permissions?.gql?[{typeName:e,permission:hr(t.permissions.gql)}]:[]),d=new Set(u.map(e=>e.typeName));return{creates:a,updates:o,deletes:s,desiredGqlPermissions:u,gqlPermissionDeletes:c.filter(e=>!d.has(e.typeName)),remoteGqlPermissionTypes:l}}async function applySnapshotPlan(e){let{client:t,workspaceId:n,namespace:r,snapshot:i,manifestOptions:a,plan:o}=e,{creates:s,updates:c,deletes:l,desiredGqlPermissions:u,gqlPermissionDeletes:d}=o,f=at(i,a),manifestFor=e=>{let t=f.get(e);if(!t)throw Qr(`Internal error: no manifest generated for table "${e}". No changes were applied.`);return t},p=s.map(e=>manifestFor(e)),m=c.map(e=>manifestFor(e));await Promise.all([...p.map(e=>t.createTailorDBType({workspaceId:n,namespaceName:r,tailordbType:e})),...m.map(e=>t.updateTailorDBType({workspaceId:n,namespaceName:r,tailordbType:e}))]),await Promise.all(u.map(({typeName:e,permission:i})=>{let a={workspaceId:n,namespaceName:r,typeName:e,permission:i};return o.remoteGqlPermissionTypes.has(e)?t.updateTailorDBGQLPermission(a):t.createTailorDBGQLPermission(a)})),await Promise.all(d.map(e=>t.deleteTailorDBGQLPermission({workspaceId:n,namespaceName:r,typeName:e.typeName}))),await Promise.all(l.map(e=>t.deleteTailorDBType({workspaceId:n,namespaceName:r,tailordbTypeName:e})))}async function assertMigrationsReproduceLocalTypes(e,t){let{config:n,plugins:r}=e,i=r.length>0?new ui(r):void 0,{defineApplication:a,generatePluginFilesIfNeeded:o}=await import(`../application-dalGHdrI.mjs`),s=a({config:n,pluginManager:i}),c=s.tailorDBServices.find(e=>e.namespace===t.namespace);if(!c)throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${t.namespace}"`});for(let e of s.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let l=o(i,s.tailorDBServices,n.path),u=s.executorService??(l.length>0?(await import(`../service-DREWLYxD.mjs`)).createExecutorService({config:{files:[]},baseDir:K.dirname(n.path)}):void 0);await u?.loadExecutors(),l.length>0&&await u?.loadPluginExecutorFiles([...l]);let d=/* @__PURE__ */ new Set;for(let e of Object.values(u?.executors??{}))ur(e)&&e.trigger.kind===`tailordb`&&d.add(e.trigger.tableName);let f={executorUsedTables:d,namespaceGqlOperations:c.config.gqlOperations},p=j(t.migrationsDir);if(!p)return f;let m=Ve(c.types,t.namespace),h=tn(p,m.tables,t.namespace);if(!cn(h))return f;throw x.error(`Migration history does not reproduce the current local schema for namespace ${S.bold(t.namespace)}:`),x.log(Vn(h)),x.newline(),x.info(`This usually means one of the following:`),x.info(` - Migration files were edited and replaying them no longer matches the table definitions — fix the migration files.`,{mode:`plain`}),x.info(` - Table definitions changed without a new migration — run 'tailor tailordb migration generate' first.`,{mode:`plain`}),x.newline(),U({code:`MIGRATION_HISTORY_MISMATCH`,message:`Refusing to continue: the migration history must reproduce the current local schema before it can be applied to the remote.`,suggestion:`Generate a migration for the pending schema changes first.`})}async function sync(e){ct(`tailordb migration`);let t=ir(e.number),n=await z(e.configPath),{config:r}=n,i=K.dirname(r.path),a=B(r,i),o=Vr(a,e.namespace);gt(o.migrationsDir,o.namespace);let s=Me(o.migrationsDir,t),c=j(o.migrationsDir,t);if(!c)throw U({code:`MIGRATION_BASELINE_NOT_FOUND`,message:`No initial schema snapshot found in ${o.migrationsDir}. Expected 0000/schema.json.`,suggestion:`Create the initial schema snapshot first.`});let l=await assertMigrationsReproduceLocalTypes(n,o),{client:u,workspaceId:d}=await A({profile:e.profile,workspaceId:e.workspaceId}),f=I(d,`tailordb`,o.namespace),p=await D(u,f);In(p,o.namespace);let m=p.number,h=await planSnapshotApply({client:u,workspaceId:d,namespace:o.namespace,snapshot:c}),{creates:g,updates:_,deletes:v,desiredGqlPermissions:y,gqlPermissionDeletes:b}=h;x.newline(),x.info(`Namespace: ${S.bold(o.namespace)}`),x.log(` Current migration: ${m===null?`<unset>`:S.bold(L(m))}`),x.log(` Target migration: ${S.bold(L(t))}`),x.log(` Tables to create: ${S.bold(String(g.length))}`),x.log(` Tables to update: ${S.bold(String(_.length))}`),x.log(` Tables to delete: ${S.bold(String(v.length))}`),x.log(` GQL permissions to set: ${S.bold(String(y.length))}`),x.log(` GQL permissions to delete: ${S.bold(String(b.length))}`),x.newline();let ee=g.length+_.length+v.length+y.length+b.length;if(ee===0?x.info(`No tables to apply; only the migration label will be updated.`):(x.warn(`This operation will overwrite remote TailorDB tables to match the selected snapshot.`),v.length>0&&x.warn(`Existing data in deleted tables will be lost.`),x.newline()),x.warn(`Sync never runs migrate.ts scripts; it only applies the schema snapshot and moves the migration label.`),x.newline(),m!==null&&t<m?(x.warn(`Migrations ${L(t+1)}–${L(m)} will become pending again and re-execute on the next deploy, including their migrate.ts scripts. Make sure those scripts are idempotent (safe to re-run).`),x.newline()):m!==null&&t>m&&(x.warn(`Moving the migration label forwards (${L(m)} → ${L(t)}): migrate.ts scripts for migrations ${L(m+1)}–${L(t)} will not run on the next deploy.`),x.newline()),!e.yes){if(!await N.confirm({message:`Continue and set migration label to ${L(t)}?`,default:!1}))throw U({code:`MIGRATION_SYNC_CANCELLED`,message:`Migration sync cancelled.`});x.newline()}try{await applySnapshotPlan({client:u,workspaceId:d,namespace:o.namespace,snapshot:c,manifestOptions:l,plan:h})}catch(e){Xt(e,[`The target snapshot marks a field as required, but existing remote records have no value for it.`,`Populate those records first (e.g. with a migration script applied via 'tailor deploy'), then re-run the sync.`])}let te=c.rebaseline?.historyId,ne=await Yt(u,d,o.namespace,t,te);return x.success(`Synced namespace ${S.bold(o.namespace)} to migration ${S.bold(L(t))}.`),t<s&&(x.newline(),x.info(`Run 'tailor deploy' to apply migrations ${L(t+1)}–${L(s)} from the working tree.`)),{changed:ee>0||ne,workspaceId:d,namespace:o.namespace,previousMigrationNumber:m,migrationNumber:t,historyId:te??null,tables:{created:g,updated:_,deleted:v},gqlPermissions:{set:y.map(({typeName:e})=>e),deleted:b.map(({typeName:e})=>e)}}}const go=C({name:`sync`,description:`Sync remote TailorDB schema to a specific migration snapshot (recovery from --no-schema-check drift).`,args:q.strictObject({...E,...F,number:W(q.string(),{positional:!0,description:`Migration number to sync to (e.g., 0001 or 1; 0 targets the baseline snapshot)`}),namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await R({profile:e.profile});let t=await sync({configPath:e.config,number:e.number,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile});k(t)}});async function assertMigrationStateUnchanged(e){let{client:t,workspaceId:n,namespace:r,before:i}=e,a=await D(t,I(n,`tailordb`,r));if(a.number!==i.number||a.historyId!==i.historyId||a.inProgress?.number!==i.inProgress?.number||a.inProgress?.executionId!==i.inProgress?.executionId)throw U({code:`MIGRATION_RESOLVE_STATE_CHANGED`,message:`The migration state of namespace "${r}" changed while the command was running.`,suggestion:`Run the command again.`})}async function resolve$1(e){ct(`tailordb migration`);let t=await z(e.configPath),n=K.dirname(t.config.path),r=Vr(B(t.config,n),e.namespace),{namespace:i}=r;gt(r.migrationsDir,i);let{client:a,workspaceId:o}=await A({profile:e.profile,workspaceId:e.workspaceId}),s=await D(a,I(o,`tailordb`,i));if(s.inProgressInvalid)throw U({code:`MIGRATION_RESOLVE_RECORD_UNREADABLE`,message:`Namespace "${i}" records a partially applied migration that cannot be read.`,suggestion:`Run 'tailor tailordb migration status --namespace ${i}' to inspect the migration state.`});if(!s.inProgress||Pr(s))throw U({code:`MIGRATION_RESOLVE_NO_IN_PROGRESS`,message:`No migration is in progress for namespace "${i}".`,suggestion:`Run 'tailor tailordb migration status --namespace ${i}' to check the migration state.`});let c=j(r.migrationsDir,0)?.rebaseline?.historyId??null;if((s.number!==null||s.historyId!==null||s.historyIdInvalid)&&(s.historyIdInvalid||s.historyId!==c))throw U({code:`MIGRATION_RESOLVE_HISTORY_MISMATCH`,message:`The migration history of namespace "${i}" on the workspace does not match the local migration history.`,suggestion:`Run the command from a checkout of the migration history that was deployed to the workspace.`});let l=s.inProgress.number,u=e.resolution===`rollback`?l-1:l;Me(r.migrationsDir,u);let d=j(r.migrationsDir,u);if(!d)throw U({code:`MIGRATION_BASELINE_NOT_FOUND`,message:`No initial schema snapshot found in ${r.migrationsDir}. Expected 0000/schema.json.`,suggestion:`Create the initial schema snapshot first.`});let f=await assertMigrationsReproduceLocalTypes(t,r),p=await planSnapshotApply({client:a,workspaceId:o,namespace:i,snapshot:d});x.newline(),x.info(`Namespace: ${S.bold(i)}`),x.log(` In progress: ${S.bold(L(l))}`),x.log(` Resolution: ${S.bold(e.resolution)} (schema of migration ${S.bold(L(u))})`),x.log(` Tables to create: ${S.bold(String(p.creates.length))}`),x.log(` Tables to update: ${S.bold(String(p.updates.length))}`),x.log(` Tables to delete: ${S.bold(String(p.deletes.length))}`),x.newline();let m=L(l);if(p.deletes.length>0&&x.warn(`Existing data in deleted tables will be lost.`),e.resolution===`rollback`?x.warn(`Rolling back does not undo the data changes made by steps of migration ${m} that already completed. When migration ${m} is deployed again, its steps run again from the first step, so make sure every step is safe to run twice.`):x.warn(`Completing applies the schema of migration ${m} without running its migrate.ts again; do this only after the data it needs is in place.`),x.newline(),!e.yes){if(!await N.confirm({message:`Continue and ${e.resolution} migration ${L(l)}?`,default:!1}))throw U({code:`MIGRATION_RESOLVE_CANCELLED`,message:`Migration resolve cancelled.`});x.newline()}await assertMigrationStateUnchanged({client:a,workspaceId:o,namespace:i,before:s}),await en(a,o,i,l);try{await applySnapshotPlan({client:a,workspaceId:o,namespace:i,snapshot:d,manifestOptions:f,plan:p})}catch(e){Xt(e,[`The schema of migration ${m} marks a field as required, but records still have no value for it.`,`Fill in those records first (for example with 'tailor query'), then run the command again; the migration stays in progress until the update goes through.`])}s.maintenanceModeCheckpoint!==null&&await tt(a,o,i);let h=await Yt(a,o,i,u,d.rebaseline?.historyId);try{await St(a,o,i,l)}catch(e){x.warn(`Could not remove the temporary resources of migration ${L(l)}: ${e instanceof Error?e.message:String(e)}. The next deploy removes them.`)}x.success(`Resolved migration ${S.bold(L(l))} of namespace ${S.bold(i)} (${e.resolution}); the checkpoint is ${S.bold(L(u))}.`);let{creates:g,updates:_,deletes:v,desiredGqlPermissions:y,gqlPermissionDeletes:b}=p;return{changed:g.length+_.length+v.length+y.length+b.length>0||h,workspaceId:o,namespace:i,resolution:e.resolution,migrationNumber:l,checkpoint:u,tables:{created:g,updated:_,deleted:v},gqlPermissions:{set:y.map(({typeName:e})=>e),deleted:b.map(({typeName:e})=>e)}}}const _o=C({name:`resolve`,description:`Settle a migration that a failed deploy left partially applied.`,notes:"Use this after a deploy failed partway through a migration whose `migrate.ts` exports `steps`. The failed migration stays in progress: when `maintenanceMode` is on in your config, the tables of its namespace stay in maintenance mode, and `sync` and `rebaseline` are refused, while `set` accepts only the number of the in-progress migration.\n\n- `--rollback` sends the schema of the migration before the failed one. The next deploy runs the failed migration again from its first step. Data changes made by steps that already completed are not undone.\n- `--complete` sends the schema of the failed migration itself and records it as completed, without running its `migrate.ts` again. Fix the data first (for example with `tailor query`), and make sure no record lacks a value for a field that becomes required.\n\nBoth options remove the in-progress record, take the tables out of maintenance mode, and remove the temporary resources of the failed run, so `deploy` and the other migration commands work again. As with `tailordb migration sync`, the local migration history must reproduce the current table definitions. If sending the schema stops partway, run the command again.",args:q.strictObject({...E,...F,rollback:W(q.boolean().default(!1),{description:`Return the namespace to the schema before the in-progress migration`}),complete:W(q.boolean().default(!1),{description:`Apply the schema of the in-progress migration and mark it as completed`}),namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{if(e.rollback===e.complete)throw U({code:`MIGRATION_RESOLVE_DIRECTION_REQUIRED`,message:`Specify exactly one of --rollback or --complete.`});await R({profile:e.profile});let t=await resolve$1({configPath:e.config,resolution:e.rollback?`rollback`:`complete`,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile});k(t)}});async function set(e){ct(`tailordb migration`);let t=ir(e.number),{config:n}=await z(e.configPath),r=K.dirname(n.path),i=B(n,r),a=Vr(i,e.namespace),o=a.namespace;gt(a.migrationsDir,o),Me(a.migrationsDir,t);let s=j(a.migrationsDir,0)?.rebaseline?.historyId,{client:c,workspaceId:l}=await A({profile:e.profile,workspaceId:e.workspaceId}),u=I(l,`tailordb`,o),d=await D(c,u),f=d.inProgress?.number===t;f||In(d,o);let p=d.number,m=p??0,h=d.historyIdInvalid?`<invalid>`:d.historyId??`<unset>`,g=s??`<unset>`;if(x.newline(),x.warn(`This operation will change TailorDB migration state metadata.`),x.log(`Namespace: ${S.bold(o)}`),x.log(`Current migration: ${p===null?`<unset>`:S.bold(L(p))}`),x.log(`New migration: ${S.bold(L(t))}`),x.log(`Current migration history ID: ${S.bold(h)}`),x.log(`New migration history ID: ${S.bold(g)}`),x.newline(),f&&(x.warn(`Migration ${L(t)} is in progress. Setting the checkpoint to it marks it as completed and clears its in-progress record; do this only when its schema changes are already applied.`),x.newline()),t<m?(x.warn(`Setting migration number backwards (${L(m)} → ${L(t)}) will cause previous migrations to be re-executed on next apply.`),x.newline()):t>m&&(x.warn(`Setting migration number forwards (${L(m)} → ${L(t)}) will skip migrations ${L(m+1)} to ${L(t)}.`),x.newline()),!e.yes){if(!await N.confirm({message:`Continue with migration checkpoint and history ID update?`,default:!1}))throw U({code:`MIGRATION_SET_CANCELLED`,message:`Migration checkpoint update cancelled.`});x.newline()}let _=await Yt(c,l,o,t,s);return x.success(`Migration checkpoint set to ${S.bold(L(t))} for namespace ${S.bold(o)}`),{changed:_,workspaceId:l,namespace:o,previousMigrationNumber:p,migrationNumber:t,historyId:s??null}}const vo=C({name:`set`,description:`Set migration checkpoint to a specific number.`,notes:"The migration number must be a 4-digit value (e.g. `0001`) or a bare integer (e.g. `1`) within 0–9999, and must exist in the local migration history; `0` is always accepted as the baseline, provided the local history passes validation. A gapped history is rejected.\n\nMetadata lookup failures (authentication, permission, or network errors) are reported as errors; only a not-yet-deployed namespace is treated as having no checkpoint.",args:q.strictObject({...E,...F,number:W(q.string(),{positional:!0,description:`Migration number to set (e.g., 0001 or 1)`}),namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await R({profile:e.profile});let t=await set({configPath:e.config,number:e.number,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile});k(t)}});function isStatusFailure(e){return e.status===`error`}async function collectMigrationStatuses(e){let{config:t}=await z(e.configPath),n=K.dirname(t.path),r=B(t,n);if(r.length===0)throw pn();let i=e.namespace?r.filter(t=>t.namespace===e.namespace):r;if(i.length===0)throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`Namespace "${e.namespace}" not found or does not have migrations configured`});let a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map;for(let{namespace:e,migrationsDir:t}of i)try{let n=Gt(t),r=/* @__PURE__ */ new Map,i=null;for(let e of n)if(e.type===`schema`){let t=gr(e.path);e.number===0&&(i=t.rebaseline?.historyId??null)}else try{let t=ot(e.path);t.description&&r.set(e.number,t.description)}catch(e){if(Zr(e)&&e.code===`MIGRATION_FILE_VERSION_UNSUPPORTED`)throw e}a.set(e,{migrationFiles:n,descriptions:r,historyId:i})}catch(t){o.set(e,$r(t))}if(a.size===0)return i.map(({namespace:e})=>({status:`error`,namespace:e,error:o.get(e)??`Failed to read local migration history.`}));let{client:s,workspaceId:c}=await A({profile:e.profile,workspaceId:e.workspaceId}),l=[];for(let{namespace:e}of i){if(o.has(e)){l.push({status:`error`,namespace:e,error:o.get(e)??`Failed to read local migration history.`});continue}let t=a.get(e);if(!t){l.push({status:`error`,namespace:e,error:`Failed to read local migration history.`});continue}let{migrationFiles:n,descriptions:r,historyId:i}=t,u=I(c,`tailordb`,e),d;try{d=await D(s,u)}catch(t){l.push({status:`error`,namespace:e,error:t instanceof Error?t.message:String(t)});continue}let f=d.number??0;if(d.historyIdInvalid){l.push({status:`error`,namespace:e,error:`Remote migration history ID is invalid.`});continue}if(d.inProgressInvalid){l.push({status:`error`,namespace:e,error:`Remote in-progress migration record is invalid.`});continue}if((d.number!==null||d.historyId!==null)&&d.historyId!==i){l.push({status:`error`,namespace:e,error:`Remote migration history ID ${d.historyId??`<unset>`} does not match local migration history ID ${i??`<unset>`}.`});continue}let p=n.map(e=>e.number).filter((e,t,n)=>n.indexOf(e)===t).toSorted((e,t)=>e-t).filter(e=>e>f).map(e=>({number:e,label:L(e),...r.has(e)?{description:r.get(e)}:{}})),m=Pr(d)?null:d.inProgress;l.push({status:`ok`,namespace:e,currentMigration:f,currentMigrationLabel:L(f),pendingMigrations:p,...m?{inProgressMigration:m.number,inProgressMigrationLabel:L(m.number)}:{}})}return l}function printMigrationStatuses(e){for(let t of e)if(x.newline(),x.info(`Namespace: ${S.bold(t.namespace)}`),isStatusFailure(t))x.error(` Migration status error: ${t.error}`);else if(x.log(` Current migration: ${S.bold(t.currentMigrationLabel)}`),t.inProgressMigrationLabel&&x.log(` In progress: ${S.bold(t.inProgressMigrationLabel)} (partially applied; the next deploy resumes it)`),t.pendingMigrations.length>0){x.log(` Pending migrations:`);for(let e of t.pendingMigrations)e.description?x.log(` - ${e.label}: ${e.description}`):x.log(` - ${e.label}`)}else x.log(` Pending migrations: (none)`);x.newline()}async function status(e){ct(`tailordb migration`);let t=await collectMigrationStatuses(e);e.json?x.out(t):printMigrationStatuses(t);let n=t.filter(isStatusFailure);if(n.length>0){let e=n.map(e=>e.namespace).join(`, `);throw U({code:`MIGRATION_STATUS_FAILED`,message:`Migration status check failed for ${n.length} namespace${n.length===1?``:`s`}: ${e}`})}}const yo=C({name:`status`,description:`Show the current migration status for TailorDB namespaces, including applied and pending migrations.`,notes:`Every local migration file is checked for a compatible format version, and deployed migration history IDs must match the local baseline. Compatibility errors, history mismatches, and metadata lookup failures are reported per namespace and make the command exit non-zero; only a not-yet-deployed namespace is treated as having no applied migrations.`,args:q.strictObject({...E,namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (shows all namespaces if not specified)`})}),run:async e=>{await status({configPath:e.config,namespace:e.namespace,workspaceId:e[`workspace-id`],profile:e.profile,json:x.jsonMode})}});async function runMigrationTest(e,t=createMigrationTestDependencies()){if(e.targetWorkspaceId&&!e.yes)throw U({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`--target-workspace-id requires --yes because the target may be overwritten.`,command:`tailordb migration test`});if(e.keep&&e.targetWorkspaceId)throw U({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`--keep applies only to automatically created workspaces; a designated target is always retained.`,command:`tailordb migration test`});if(e.keepTtl!==void 0&&!e.keep)throw U({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`--keep-ttl was given without --keep.`,suggestion:`Pass --keep together with --keep-ttl, or remove --keep-ttl.`,command:`tailordb migration test`});if(e.cloneTimeout!==void 0&&e.data!==`clone`)throw U({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`--clone-timeout was given without --data clone.`,suggestion:`Pass --data clone, or remove --clone-timeout.`,command:`tailordb migration test`});if(e.assertionNamespace&&!e.assertionPath)throw U({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`--assert is required when --assert-namespace is provided.`,command:`tailordb migration test`});let n=await t.prepare(e);if(assertTargetWorkspaceDiffers(n.sourceWorkspaceId,e.targetWorkspaceId),e.assertionPath&&resolveAssertionNamespace(n.pendingNamespaces,e.assertionNamespace),e.data===`clone`&&e.targetWorkspaceId){let e=s(n.designatedTarget,`designated clone target was not loaded during preparation`);assertCloneTargetRegion(n.temporaryWorkspace.region,e.region)}let r=e.targetWorkspaceId===void 0,i=r?await t.createWorkspace(n):{id:s(e.targetWorkspaceId,`designated target workspace missing`),name:void 0,createdAt:void 0},a=!1;if(r&&e.keepTtl!==void 0)try{await t.recordWorkspaceExpiry(i.id,e.keepTtl,i.createdAt),a=!0}catch(t){x.warn(`Failed to record an expiry on temporary workspace ${i.id}: ${t instanceof Error?t.message:String(t)}. Record one with ${H({command:`tailor`,args:[`workspace`,`ttl`,`set`,`--ttl`,e.keepTtl,`--workspace-id=${i.id}`,...e.profile?[`--profile=${e.profile}`]:[]]})}.`)}let o,c=!1,l=!1;try{let r={prepared:n,targetWorkspaceId:i.id};await t.deployBaseline(r);let a={...r,sourceWorkspaceId:n.sourceWorkspaceId,applicationName:n.sourceApplicationName,cloneTimeout:e.cloneTimeout};e.data===`clone`?await t.cloneData(a):await t.seedData(a),await t.deployMigrations(r),e.assertionPath&&await t.runAssertion({...r,assertionPath:e.assertionPath,assertionNamespace:e.assertionNamespace,machineUser:e.machineUser})}catch(e){o=e,c=!0}if(r&&e.keep)x.info(`Keeping temporary workspace ${i.name??i.id}${a?`; it can be pruned after ${e.keepTtl}`:``}.`);else if(r)try{await t.deleteWorkspace(i.id),l=!0}catch(t){if(!c)throw U({code:`MIGRATION_TEST_WORKSPACE_CLEANUP_FAILED`,message:`Failed to delete temporary workspace ${i.id}: ${t instanceof Error?t.message:String(t)}`,suggestion:e.profile?`Delete the temporary workspace manually with TAILOR_PLATFORM_PROFILE=${e.profile}.`:`Delete the temporary workspace manually.`,next:{command:`tailor`,args:[`workspace`,`delete`,`--workspace-id`,i.id]},cause:t});x.warn(`Failed to delete temporary workspace ${i.id}: ${t instanceof Error?t.message:String(t)}`)}if(c)throw o;return{success:!0,workspaceId:i.id,...i.name?{workspaceName:i.name}:{},temporary:r,deleted:l,data:e.data,pendingNamespaces:n.pendingNamespaces}}async function migrationTest(e){ct(`tailordb migration`);let t=await runMigrationTest(e);e.json?x.out(t):x.success(`Pending migrations completed in workspace ${t.workspaceName??t.workspaceId}.`)}const bo=C({name:`test`,description:`Test pending migrations with seed fixtures or cloned data in a temporary workspace.`,notes:`The source workspace is read-only. Without --target-workspace-id, the command creates a workspace in the source workspace's region and deletes it after success or failure; pass --keep to retain it for inspection. A designated target is retained and requires --yes. Clone mode copies TailorDB records only; it does not copy IdP users or file blobs. With --keep-ttl, the kept workspace records an expiry; it is not deleted automatically, but workspace prune --expired removes it once the expiry has passed.`,args:q.strictObject({...E,yes:W(q.boolean().default(!1),{alias:`y`,description:`Acknowledge that a designated target workspace may be overwritten`}),data:W(q.enum([`seed`,`clone`]).default(`seed`),{description:`Data source for the migration test (seed or clone)`}),"target-workspace-id":W(q.uuid().optional(),{description:`Existing throwaway workspace to retain after the test (requires --yes)`}),keep:W(q.boolean().default(!1),{description:`Keep the automatically created workspace after the test`}),assert:W(q.string().optional(),{description:`Path to a TypeScript assertion script to run after migrations`,completion:{type:`file`,extensions:[`ts`]}}),"assert-namespace":W(q.string().optional(),{description:`TailorDB namespace exposed to the assertion script`}),"keep-ttl":W(Nr.optional(),{description:`Record an expiry on the kept workspace, e.g. 24h or 7d, so workspace prune --expired can delete it (requires --keep)`,completion:{type:`none`}}),"clone-timeout":W(Jt.optional(),{description:`How long to wait for the clone to finish with --data clone, e.g. 30s or 10m (default: 30m)`,completion:{type:`none`}}),"machine-user":W(q.string().optional(),{description:`Machine user for seed and assertion script execution`})}),run:async e=>{await R({profile:e.profile}),await migrationTest({configPath:e.config,workspaceId:e[`workspace-id`],profile:e.profile,data:e.data,targetWorkspaceId:e[`target-workspace-id`],keep:e.keep,keepTtl:e[`keep-ttl`],assertionPath:e.assert,assertionNamespace:e[`assert-namespace`],machineUser:e[`machine-user`],cloneTimeout:e[`clone-timeout`]===void 0?void 0:Bn(e[`clone-timeout`]),yes:e.yes,json:x.jsonMode})}});function assertMigrationScriptsReady(e,t,n){let r=[],i=[],a=[],o=[],s=[];for(let t of Gt(e)){if(t.type!==`diff`)continue;let n=ot(t.path),c=Rt(e,t.number,`migrate`),l=Y.existsSync(c);l&&s.push([t.number,c]),n.requiresMigrationScript&&!n.scriptSkipped&&!l&&r.push(t.number),n.scriptSkipped&&l&&i.push(t.number),l&&er(c)>0&&a.push(t.number),n.hasWarnings&&!n.scriptSkipped&&!l&&o.push({migrationNumber:t.number,warnings:n.warnings})}if(r.length>0)throw U({code:`MIGRATION_SCRIPT_REQUIRED`,message:`Migration(s) ${r.map(L).join(`, `)} in namespace "${t}" require a migration script but have no migrate.ts.`,suggestion:`Add one with 'tailor tailordb migration script <number>', or record that no script is needed with 'tailor tailordb migration script <number> --no-script --reason "..."'.`});if(i.length>0){let e=i.map(e=>` ${jr({migrationNumber:e,namespace:t,configPath:n})}`).join(`
|
|
88
|
+
`);throw U({code:`MIGRATION_SCRIPT_SKIP_CONFLICT`,message:`Migration(s) ${i.map(L).join(`, `)} in namespace "${t}" have both a --no-script skip acknowledgment and migrate.ts.`,suggestion:`Clear the stale acknowledgment(s):\n${e}\nOr delete migrate.ts to keep the skip.`})}if(a.length>0)throw U({code:`MIGRATION_SCRIPT_REVIEW_REQUIRED`,message:`Migration(s) ${a.map(L).join(`, `)} in namespace "${t}" still have a TODO() call or review marker in migrate.ts, where the generated script leaves a value or logic for you to decide.`,suggestion:Mn});for(let[e,n]of s){let r=mr(n);r.kind===`main`&&r.ignoredSteps&&x.warn(zn(`${t}/${L(e)}`))}return o}function buildValidationReports(e){let{targetNamespaces:t,migrationFileErrors:n,localResults:r,remoteResults:i,unacknowledgedWarnings:a}=e;return t.map(e=>{let t=n.get(e.namespace);if(t!==void 0)return{namespace:e.namespace,valid:!1,migrationFiles:{valid:!1,error:t}};let o=s(r.find(t=>t.namespace===e.namespace),`local schema check result missing for namespace "${e.namespace}"`),c={hasDiff:o.hasDiff,...o.diff?{diff:o.diff}:{}};if(i===void 0)return{namespace:e.namespace,valid:!1,migrationFiles:{valid:!0},localSchema:c,remoteSchema:{skipped:`check_failed`}};let l=s(i.find(t=>t.namespace===e.namespace),`remote schema check result missing for namespace "${e.namespace}"`),u=l.checkpointMissingLocal===!0,d={remoteMigrationNumber:l.remoteMigrationNumber,hasDrift:l.hasDrift,drifts:l.drifts,...l.skipped?{skipped:l.skipped}:{},...u?{checkpointMissingLocal:!0}:{},...l.rebaselinePending?{rebaselinePending:l.rebaselinePending}:{},...l.checkpointRepair?{checkpointRepair:l.checkpointRepair}:{}},f=a?.get(e.namespace),p;if(f!==void 0){let e=f.filter(e=>e.migrationNumber>l.remoteMigrationNumber);p={valid:e.length===0,missing:e}}return{namespace:e.namespace,valid:!c.hasDiff&&!d.hasDrift&&!u&&p?.valid!==!1,migrationFiles:{valid:!0},localSchema:c,remoteSchema:d,...p?{warningAcknowledgments:p}:{}}})}async function collectValidationReports(e){let{config:t,plugins:n}=await z(e.configPath),r=K.dirname(t.path),i=B(t,r);if(i.length===0)throw pn();let a=e.namespace?i.filter(t=>t.namespace===e.namespace):i;if(a.length===0)throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`Namespace "${e.namespace}" not found or does not have migrations configured`});let o=n.length>0?new ui(n):void 0,{defineApplication:s}=await import(`../application-dalGHdrI.mjs`),c=s({config:t,pluginManager:o});for(let e of c.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();ee({tailorDBServices:c.tailorDBServices});for(let{namespace:e}of a)if(!c.tailorDBServices.some(t=>t.namespace===e))throw U({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${e}"`});let l=c.tailorDBServices.map(Ye),u=new Map(l.map(e=>[e.namespace,e.types])),d=/* @__PURE__ */ new Map,f=[],p=e.strict?/* @__PURE__ */ new Map:void 0;for(let t of a)try{gt(t.migrationsDir,t.namespace),j(t.migrationsDir);let n=assertMigrationScriptsReady(t.migrationsDir,t.namespace,e.configPath);p?.set(t.namespace,n),f.push(t)}catch(e){d.set(t.namespace,$r(e))}let m={targetNamespaces:a,migrationFileErrors:d,localResults:await Qe(u,f),...p?{unacknowledgedWarnings:p}:{}};if(f.length===0)return{reports:buildValidationReports(m)};let h;try{let{client:n,workspaceId:r}=await A({profile:e.profile,workspaceId:e.workspaceId});h=await Lt(n,r,f,t,l)}catch(e){return{reports:buildValidationReports(m),remoteError:e}}return{reports:buildValidationReports({...m,remoteResults:h})}}function printValidationReports(e){for(let t of e){if(x.newline(),x.info(`Namespace: ${S.bold(t.namespace)}`),!t.migrationFiles.valid){x.log(` Migration files: ${S.error(`invalid`)}`),x.log(` ${t.migrationFiles.error}`);continue}x.log(` Migration files: ${S.success(`OK`)}`);let e=t.localSchema;e?.hasDiff?e.diff?(x.log(` Local schema: ${S.error(`changes not in migration files`)}`),x.log(` ${yr(e.diff)}`),x.log(Vn(e.diff))):x.log(` Local schema: ${S.error(`no migration snapshot found`)}`):x.log(` Local schema: ${S.success(`OK`)}`);let n=t.remoteSchema;n?.skipped===`check_failed`?x.log(` Remote schema: ${S.error(`not checked`)}`):n?.checkpointRepair?x.log(` Remote schema: ${S.success(`OK`)} (next deploy will reset the checkpoint to 0000 from ${L(n.checkpointRepair.from)})`):n?.checkpointMissingLocal?(x.log(` Remote schema: ${S.error(`remote migration ${L(n.remoteMigrationNumber)} is not in the local migration history`)}`),n.rebaselinePending&&x.log(` Fell behind before 'migration rebaseline' ran; must reach ${L(n.rebaselinePending.replacedLatestMigration)} first.`)):n?.hasDrift?(x.log(` Remote schema: ${S.error(`drift detected`)} (remote migration: ${L(n.remoteMigrationNumber)})`),x.log(Pt(n.drifts))):n?.skipped===`not_deployed`?x.log(` Remote schema: ${S.dim(`skipped (namespace not deployed)`)}`):n?.skipped===`no_migration_label`?x.log(` Remote schema: ${S.dim(`skipped (deployed namespace has no migration state)`)}`):n?.skipped===`no_snapshot`?x.log(` Remote schema: ${S.dim(`skipped (no local snapshot for remote migration ${L(n.remoteMigrationNumber)})`)}`):n&&x.log(` Remote schema: ${S.success(`OK`)} (remote migration: ${L(n.remoteMigrationNumber)})`);let r=t.warningAcknowledgments;if(r){if(r.valid)x.log(` Warning acknowledgments: ${S.success(`OK`)}`);else{x.log(` Warning acknowledgments: ${S.error(`missing for pending migration(s) with possible data loss`)}`);for(let e of r.missing){let t=L(e.migrationNumber);for(let n of e.warnings){let e=n.fieldName?`.${n.fieldName}`:``;x.log(` ${t}: ${n.tableName}${e}: ${n.reason}`)}}}}}x.newline()}function hasMissingCheckpoint(e){return e.remoteSchema?.checkpointMissingLocal===!0}function printResolutionHints(e,t){e.some(e=>e.localSchema?.hasDiff&&!e.localSchema.diff)&&x.info(`Run 'tailor tailordb migration generate' to create the initial snapshot.`),e.some(e=>e.localSchema?.diff)&&x.info(`Run 'tailor tailordb migration generate' to create migration files.`);let n=e.filter(hasMissingCheckpoint);n.length>0&&je(n.map(e=>({namespace:e.namespace,remoteMigrationNumber:e.remoteSchema.remoteMigrationNumber,...e.remoteSchema.rebaselinePending?{rebaselinePending:e.remoteSchema.rebaselinePending}:{}}))),e.some(e=>e.remoteSchema?.hasDrift)&&Vt(e.map(e=>({hasDrift:e.remoteSchema?.hasDrift??!1,drifts:e.remoteSchema?.drifts??[]})));let r=e.filter(e=>e.warningAcknowledgments&&!e.warningAcknowledgments.valid);if(r.length>0){x.info(`For each migration listed, either add a data migration script with 'tailor tailordb migration script <number>' or record why none is needed:`);for(let e of r)for(let n of e.warningAcknowledgments?.missing??[])x.info(` ${jr({migrationNumber:n.migrationNumber,namespace:e.namespace,configPath:t,noScript:!0})}`,{mode:`plain`})}}async function validate(e){ct(`tailordb migration`);let t=await collectValidationReports(e),{reports:n}=t,r=n.filter(e=>!e.valid).length;if(e.json?x.out(n):(printValidationReports(n),r===0&&!(`remoteError`in t)?x.success(`All migration validation checks passed.`):printResolutionHints(n,e.configPath)),`remoteError`in t)throw t.remoteError;if(r>0)throw U({code:`MIGRATION_VALIDATION_FAILED`,message:`Migration validation failed for ${r} namespace(s)`})}const xo=C({name:`validate`,description:`Validate the full migration history, unreviewed generated migration scripts, and schema drift (local tables vs. migration snapshot, remote schema vs. migration checkpoint) without deploying. This includes the migration and schema-drift checks used by 'deploy' and exits with a non-zero code when issues are found.`,args:q.strictObject({...E,namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (validates all namespaces if not specified)`}),strict:W(q.boolean().default(!1),{description:`Also fail when a pending migration can drop data without an acknowledgment`})}),run:async e=>{await validate({configPath:e.config,namespace:e.namespace,workspaceId:e[`workspace-id`],profile:e.profile,json:x.jsonMode,strict:e.strict})}}),So=G({name:`migration`,description:`Manage TailorDB schema migrations.`,subCommands:{generate:_t,rebaseline:ho,resolve:_o,script:He,set:vo,status:yo,sync:go,test:bo,validate:xo}}),Co=G({name:`tailordb`,description:`Manage TailorDB tables and data.`,notes:"The `tailordb erd` commands are provided by the @tailor-platform/sdk-plugin-tailordb-erd CLI plugin.",subCommands:{truncate:ft,migration:So}}),wo=C({name:`upgrade`,description:`Run codemods to upgrade your project to a newer SDK version.`,args:q.strictObject({from:W(q.string(),{description:`SDK version before the upgrade (e.g., 1.33.0)`}),"dry-run":W(q.boolean().default(!1),{alias:`d`,description:`Preview changes without modifying files`}),path:W(q.string().default(`.`),{description:`Project directory to upgrade`,completion:{type:`directory`}})}),run:async e=>{let{initTelemetry:t}=await import(`../telemetry-DpkFGBmu.mjs`);await t();let{upgrade:n}=await import(`../service-b1g22NN9.mjs`);await n({from:e.from,dryRun:e[`dry-run`],path:K.resolve(e.path)})}}),To=C({name:`current`,description:`Show current user.`,args:q.strictObject({profile:M.profile}),run:async e=>{let t=await w(),n=e.profile||process.env.TAILOR_PLATFORM_PROFILE,r=n?t.profiles[n]:void 0;if(n&&!r)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${n}" not found`});let i=r?pt(r):void 0,a=n?r?.user??null:t.current_user,o=x.jsonMode;if(!a)throw U({code:`USER_NOT_SET`,message:`Current user not set.`,suggestion:`Log in first to register a user.`,next:{command:`tailor`,args:[`login`,...O({profile:n})]}});if(!Ne(t,a,i))throw U({code:`USER_NOT_FOUND`,message:`Current user '${a}' not found in registered users.`,suggestion:`Log in again to register the user.`,next:{command:`tailor`,args:[`login`,...O({profile:n})]}});o?x.out({user:a}):x.out(a)}});function activeCurrentUserKey(e,t){if(!t)return e.current_user?Kr(e,e.current_user):null;let n=e.profiles[t];if(!n)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${t}" not found`});return Kr(e,n.user,pt(n))}function toUserListInfo(e,t){let n=e.indexOf(`|`),r=n===-1?null:e.slice(0,n);return{user:n===-1?e:e.slice(n+1),platformUrl:r,current:t===e}}function formatUserListInfo(e){return`${e.user}${e.platformUrl?` [${e.platformUrl}]`:``}${e.current?` (current)`:``}`}const Eo=C({name:`list`,description:`List all users.`,args:q.strictObject({profile:M.profile}),run:async e=>{let t=await w(),n=x.jsonMode,r=activeCurrentUserKey(t,e.profile||process.env.TAILOR_PLATFORM_PROFILE),i=Object.keys(t.users);if(i.length===0){x.info(V`
|
|
89
89
|
No users found.
|
|
90
90
|
Please login first using 'tailor login' command to register a user.
|
|
91
|
-
`),n&&
|
|
91
|
+
`),n&&x.out([]);return}let a=i.map(e=>toUserListInfo(e,r));n?x.out([...new Set(a.map(e=>e.user))]):a.forEach(e=>{e.current?x.success(formatUserListInfo(e),{mode:`plain`}):x.log(formatUserListInfo(e))})}}),Do={[a.PAT_SCOPE_UNSPECIFIED]:`unknown`,[a.PAT_SCOPE_READ]:`read`,[a.PAT_SCOPE_WRITE]:`write`};function patScopeToString(e){return vn(Do,e,`unknown`)}function transformPersonalAccessToken(e){return{name:e.name,scopes:e.scopes.map(patScopeToString),createdAt:xn(e.createdAt),lastUsedAt:xn(e.lastUsedAt)}}function getScopesFromWriteFlag(e){return e?[a.PAT_SCOPE_READ,a.PAT_SCOPE_WRITE]:[a.PAT_SCOPE_READ]}function getScopeStringsFromWriteFlag(e){return e?[`read`,`write`]:[`read`]}function printCreatedToken(e,t,n,r){let i=getScopeStringsFromWriteFlag(n);x.jsonMode?x.out({name:e,scopes:i,token:t}):x.out(V`
|
|
92
92
|
Personal access token ${r} successfully.
|
|
93
93
|
|
|
94
94
|
name: ${e}
|
|
@@ -96,24 +96,37 @@ Error:`));let e=formatErrorWithSourcemap(v.error,f,process.cwd());e?C.log(e):C.l
|
|
|
96
96
|
token: ${t}
|
|
97
97
|
|
|
98
98
|
Please save this token in a secure location. You won't be able to see it again.
|
|
99
|
-
`)}async function createPatOperatorClient(e){let t=await
|
|
99
|
+
`)}async function createPatOperatorClient(e){let t=await Lr({profile:e});return await xe(t)}const Oo=C({name:`create`,description:`Create a new personal access token.`,args:q.strictObject({name:W(q.string(),{positional:!0,description:`Token name`}),write:W(q.boolean().default(!1),{alias:`W`,description:`Grant write permission (default: read-only)`}),profile:M.profile}),run:async e=>{await R({profile:e.profile});let t=await createPatOperatorClient(e.profile),n=getScopesFromWriteFlag(e.write),r=await t.createPersonalAccessToken({name:e.name,scopes:n});if(!r.accessToken)throw Qr(`Failed to create personal access token`);x.registerSecret(r.accessToken),printCreatedToken(e.name,r.accessToken,e.write,`created`)}}),ko=C({name:`delete`,description:`Delete a personal access token.`,args:q.strictObject({name:W(q.string(),{positional:!0,description:`Token name`}),profile:M.profile}),run:async e=>{await R({profile:e.profile}),await(await createPatOperatorClient(e.profile)).deletePersonalAccessToken({name:e.name}),x.success(`Personal access token "${e.name}" deleted successfully.`),k({changed:!0,name:e.name})}}),Ao=C({name:`list`,description:`List all personal access tokens.`,args:q.strictObject({...vr(),profile:M.profile}),run:async e=>{let t=x.jsonMode,n=await createPatOperatorClient(e.profile),r=hn(e.order),i=await An(e.limit,e=>be(async(e,t)=>{let{personalAccessTokens:i,nextPageToken:a}=await n.listPersonalAccessTokens({pageToken:e,pageSize:t,pageDirection:r});return[i,a]},{limit:e})),a=i.items;if(a.length===0&&(x.info(V`
|
|
100
100
|
No personal access tokens found.
|
|
101
101
|
Please create a token using 'tailor user pat create' command.
|
|
102
|
-
`),!t))return;let o=a.map(transformPersonalAccessToken);
|
|
102
|
+
`),!t))return;let o=a.map(transformPersonalAccessToken);x.out(o,{display:{scopes:e=>e.join(`/`),lastUsedAt:e=>e===null?`never`:jn(e)}}),await P(i,e.limit)}}),jo=C({name:`update`,description:`Update a personal access token (delete and recreate).`,args:q.strictObject({name:W(q.string(),{positional:!0,description:`Token name`}),write:W(q.boolean().default(!1),{alias:`W`,description:`Grant write permission (if not specified, keeps read-only)`}),profile:M.profile}),run:async e=>{await R({profile:e.profile});let t=await createPatOperatorClient(e.profile);await t.deletePersonalAccessToken({name:e.name});let n=getScopesFromWriteFlag(e.write),r=await t.createPersonalAccessToken({name:e.name,scopes:n});if(!r.accessToken)throw Qr(`Failed to create personal access token`);x.registerSecret(r.accessToken),printCreatedToken(e.name,r.accessToken,e.write,`updated`)}}),Mo=G({name:`pat`,description:`Manage personal access tokens.`,subCommands:{list:Ao,create:Oo,delete:ko,update:jo},defaultSubCommand:`list`}),No=C({name:`switch`,description:`Set current user.`,args:q.strictObject({user:W(q.string(),{positional:!0,description:`User email address or machine user client ID`}),profile:M.profile}),run:async e=>{let t=await w(),n=e.profile||process.env.TAILOR_PLATFORM_PROFILE,r=n?t.profiles[n]:void 0;if(n&&!r)throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${n}" not found`});let i=r?pt(r):void 0;if(e.user.includes(`|`))throw U({code:`USER_NAME_INVALID`,message:`User "${e.user}" looks like a platform-scoped token key. Pass the user name without the platform URL and select the platform with TAILOR_PLATFORM_URL or a profile.`,command:`user switch`});let a=lt(t,e.user,i);if(!a)throw U({code:`USER_NOT_FOUND`,message:`User "${e.user}" not found.`,suggestion:`Log in first to register this user.`,next:{command:`tailor`,args:[`login`,...O({profile:n})]}});let o=r?r.user:t.current_user;r?r.user=a:t.current_user=a,T(t),x.success(`Current user set to "${a}" successfully.`),k({changed:o!==a,user:a,profile:n||null})}}),Po=q.union([q.uuid(),q.literal(``)]),Fo=C({name:`update`,description:`Set the current user's default organization and folder for new workspaces.`,notes:V`
|
|
103
|
+
\`workspace create\`, workspace creation during \`deploy\`, and the programmatic \`createWorkspace()\` use the default folder, or directly use the default organization when no folder is set. Giving either an organization or a folder replaces both defaults for that run. For the CLI, use --organization-id or --folder-id, or TAILOR_PLATFORM_ORGANIZATION_ID / TAILOR_PLATFORM_FOLDER_ID. The defaults are not used while TAILOR_PLATFORM_TOKEN is set, because that token does not belong to a user logged in here.
|
|
104
|
+
|
|
105
|
+
Each run replaces both defaults: --default-organization-id alone clears the default folder, --default-folder-id is accepted only together with --default-organization-id, and --default-organization-id "" clears both. The IDs are not checked against the Platform here; \`workspace create\` and \`deploy\` point back to them when the Platform cannot find them or denies access to them.
|
|
106
|
+
|
|
107
|
+
The defaults belong to this user's login on the selected platform, so \`logout\` removes them, and older SDK versions drop them when they rewrite the CLI config file.
|
|
108
|
+
`,args:q.strictObject({"default-organization-id":W(Po.optional(),{alias:`o`,description:"Organization that `workspace create` uses when no location is given. Pass an empty string to clear the defaults."}),"default-folder-id":W(Po.optional(),{alias:`f`,description:"Folder in the default organization that `workspace create` uses (requires --default-organization-id)"}),profile:M.profile}),run:async e=>{let t=e[`default-organization-id`],n=e[`default-folder-id`];if(t===void 0&&n===void 0)throw U({code:`USER_UPDATE_EMPTY`,message:`Please provide at least one property to update.`,command:`user update`});if(t===void 0||t===``&&n)throw U({code:`USER_DEFAULT_FOLDER_WITHOUT_ORGANIZATION`,message:`--default-folder-id requires a --default-organization-id.`,suggestion:`Pass the organization that owns the folder with --default-organization-id.`,command:`user update`});let r=await w(),i=wt(r,{profile:e.profile});if(!i){let t=e.profile||process.env.TAILOR_PLATFORM_PROFILE;throw U({code:`PROFILE_NOT_FOUND`,message:`Profile "${t}" not found`})}let{profile:a,user:o,userEntry:s}=i,c={command:`tailor`,args:[`login`,...O({profile:a})]};if(!o)throw U({code:`USER_NOT_SET`,message:`Current user not set.`,suggestion:`Log in first to register a user.`,next:c});if(!s)throw U({code:`USER_NOT_FOUND`,message:`User "${o}" has no login of its own on the selected platform.`,suggestion:`Log in on that platform to store the defaults with that login.`,next:c});let l=s.default_organization_id??null,u=s.default_folder_id??null;delete s.default_organization_id,delete s.default_folder_id,t&&(s.default_organization_id=t,n&&(s.default_folder_id=n)),T(r);let d=s.default_organization_id??null,f=s.default_folder_id??null;x.success(d?`Default organization for new workspaces set to ${d} ${f?`with folder ${f}`:`with no default folder`}.`:`Default organization and folder for new workspaces cleared.`),d&&mt()&&x.warn("`workspace create` does not use these defaults while TAILOR_PLATFORM_TOKEN is set."),k({changed:l!==d||u!==f,user:o,profile:a||null,defaultOrganizationId:d,defaultFolderId:f})}}),Io=G({name:`user`,description:`Manage Tailor Platform users.`,subCommands:{current:To,list:Eo,switch:No,update:Fo,pat:Mo},defaultSubCommand:`list`}),Lo=G({name:`workflow`,description:`Manage workflows and workflow executions.`,subCommands:{list:qn,get:$e,start:yt,wait:Mt,executions:Dt,resume:Ie},defaultSubCommand:`list`}),Ro=G({name:`app`,description:`Manage workspace applications`,subCommands:{health:Ir,list:Ot},defaultSubCommand:`list`}),locationIdsArg=()=>q.array(q.union([q.literal(``),q.uuid()])).optional(),zo=q.preprocess(e=>typeof e==`string`&&e.trim()===``?NaN:e,q.coerce.number().int().nonnegative());function matchesName(e,t){return t.nameRegexes.length===0||t.nameRegexes.some(t=>t.test(e.name))}function hasLocation(e){return e.organizationRoots.length>0||e.folderIds.length>0||e.personal}function matchesScope(e,t){return hasLocation(t)?e.folderId?t.folderIds.includes(e.folderId):e.organizationId?t.organizationRoots.includes(e.organizationId):t.personal:!0}function staleCandidateReason(e,t){if(e.deleteProtection)return`delete protection was turned on`;if(!matchesScope(e,t))return`it moved outside the requested scope`;if(!matchesName(e,t))return`it no longer matches the name filter`;if(t.exclude.has(e.name))return`it is now excluded by --exclude`}function selectPruneCandidates(e,t,n){let r={candidates:[],excluded:[],protectedSkipped:[],missingCreateTime:[],tooYoung:[]};for(let i of e)if(matchesScope(i,t)&&matchesName(i,t)){if(t.exclude.has(i.name))r.excluded.push(i);else if(i.deleteProtection)r.protectedSkipped.push(i);else{if(t.olderThanMs!==void 0){let e=xn(i.createTime);if(!e){r.missingCreateTime.push(i);continue}if(e.getTime()>n.getTime()-t.olderThanMs){r.tooYoung.push(i);continue}}r.candidates.push(i)}}return r}async function partitionByExpiry(e,t,n){let r=we(),i=await Promise.all(t.map(async t=>({workspace:t,result:await r(()=>Fn(e,t.id,n))}))),a={expired:[],pending:[],unset:[],unreadable:[]};for(let{workspace:e,result:t}of i)`error`in t?a.unreadable.push({workspace:e,reason:t.error.message}):recordExpiryState(a,e,t.expiry);return a}function recordExpiryState(e,t,n){switch(n.state){case`expired`:e.expired.push(t);return;case`pending`:e.pending.push(t);return;case`unset`:e.unset.push(t);return;case`invalid`:e.unreadable.push({workspace:t,reason:`recorded expiry "${n.value}" is not a value this CLI wrote`})}}async function fetchAllWorkspaces(e){return be(async(t,n)=>{let{workspaces:r,nextPageToken:i}=await e.listWorkspaces({pageToken:t,pageSize:n});return[r,i]})}function compileNameRegex(e){try{return new RegExp(e),RegExp(`^(?:${e})$`)}catch(t){throw U({code:`INVALID_NAME_PATTERN`,message:`Invalid --name "${e}".`,details:t instanceof Error?t.message:String(t)})}}const Bo=[{key:`excluded`,selection:`excluded`,reason:`excluded by --exclude`},{key:`deleteProtection`,selection:`protectedSkipped`,reason:`delete protection is on`},{key:`unknownAge`,selection:`missingCreateTime`,reason:`creation time is unknown`}],Vo="Specify --organization-root, --folder-id, or --personal on the command line. The default organization/folder set by `tailor user update` is not used by prune.",Ho=C({name:`prune`,description:`Delete stale temporary workspaces, by name and age or by the expiry each recorded at creation.`,notes:V`
|
|
103
109
|
Use this to reclaim workspaces left behind by CI runs, preview deployments, or interrupted local test runs. A workspace is deleted only when its whole name matches a --name pattern, it was created at least --older-than ago, and it is not excluded, delete-protected, or outside the requested locations. Run with --dry-run first to see what would be deleted.
|
|
104
110
|
|
|
105
111
|
With --expired the workspaces select themselves instead: each one is deleted only once the --ttl expiry it recorded at creation has passed, so callers need no --name or --older-than. A workspace that records no expiry is never deleted this way, and neither is one whose recorded expiry cannot be read. Because that expiry is recorded on the workspace rather than derived from its name, anything able to write the workspace's metadata can bring its deletion forward -- and writing a workspace's metadata is a lesser permission than deleting it. --expired therefore requires at least one location, and --name still applies on top.
|
|
106
112
|
|
|
107
|
-
Every workspace lives in exactly one location, and the location options name them explicitly: --organization-root selects the workspaces directly under an organization and none inside its folders, --folder-id selects the workspaces in one folder, and --personal selects the workspaces belonging to no organization and no folder. Each option can be given more than once, they combine as a union, and none of them is read from the environment -- a sweep covers exactly the locations spelled out on the command line. Selecting --personal is a deliberate choice to accept, for every organization-less workspace visible to this login, the expiry that anyone able to write a workspace's metadata may have recorded. Without any location option, a --name / --older-than sweep considers every visible workspace.
|
|
113
|
+
Every workspace lives in exactly one location, and the location options name them explicitly: --organization-root selects the workspaces directly under an organization and none inside its folders, --folder-id selects the workspaces in one folder, and --personal selects the workspaces belonging to no organization and no folder. Each option can be given more than once, they combine as a union, and none of them is read from the environment or from the default organization/folder set by \`user update\` -- a sweep covers exactly the locations spelled out on the command line. Selecting --personal is a deliberate choice to accept, for every organization-less workspace visible to this login, the expiry that anyone able to write a workspace's metadata may have recorded. Without any location option, a --name / --older-than sweep considers every visible workspace.
|
|
114
|
+
|
|
115
|
+
Without a location option, prune warns before listing workspaces that every workspace visible to this login is a candidate for the name and age filters, even with --yes or --dry-run. The default organization/folder set by \`tailor user update\` is not used.
|
|
108
116
|
|
|
109
117
|
Restoring a workspace does not clear its recorded expiry, so a workspace restored after expiring is deleted again by the next --expired run. Restore it, then run \`workspace ttl set\` or \`workspace ttl clear\` before the next run — or keep it out of that run with --exclude.
|
|
110
118
|
|
|
111
119
|
Safety guards: the command aborts without deleting anything when more workspaces match than --limit allows (--dry-run still lists them all), both --expired and --older-than 0s (no age check) are only accepted together with at least one location option, and a location option that resolves to an empty value (an unset CI secret) is rejected instead of silently widening the sweep -- even when another location is given alongside it. Each workspace is re-read immediately before it is deleted and skipped when it no longer matches the name, location, exclusion, or delete-protection criteria that selected it. Unlike \`workspace delete\`, a single confirmation covers every listed candidate; pass --yes to skip it in CI. Deleted workspaces can be restored with \`workspace restore\` for a limited time.
|
|
112
120
|
|
|
113
121
|
Only workspaces visible to the current login (or the machine user in CI) are considered.
|
|
114
|
-
`,args:q.strictObject({name:W(q.array(q.string().min(1)).optional(),{description:`Select workspaces whose whole name matches this regular expression (repeatable)`}),"older-than":W(
|
|
122
|
+
`,args:q.strictObject({name:W(q.array(q.string().min(1)).optional(),{description:`Select workspaces whose whole name matches this regular expression (repeatable)`}),"older-than":W(Nr.optional(),{description:`Minimum age since creation, such as 30m, 24h, or 7d. 0s disables the age check and requires a location. Required unless --expired is given`}),expired:W(q.boolean().default(!1),{description:`Select workspaces whose own --ttl expiry has passed, instead of by name and age. Requires --organization-root, --folder-id, or --personal`}),"organization-root":W(locationIdsArg(),{placeholder:`ORGANIZATION_ID`,description:`Consider the workspaces directly under this organization, excluding those in its folders (repeatable)`}),"folder-id":W(locationIdsArg(),{description:`Consider the workspaces in this folder (repeatable)`}),personal:W(q.boolean().default(!1),{description:`Consider the workspaces belonging to no organization and no folder`}),exclude:W(q.array(q.string().min(1)).optional(),{description:`Keep a workspace with this exact name even when it matches (repeatable)`}),limit:W(zo.default(20),{description:`Abort when more workspaces match than this, without deleting anything. 0 removes the cap`}),"dry-run":W(q.boolean().default(!1),{description:`List the workspaces that would be deleted without deleting them`}),profile:W(At.optional(),{description:`Workspace profile used for authentication and Platform selection`,env:`TAILOR_PLATFORM_PROFILE`}),...F}),run:async e=>{let t=e.name??[],n=e[`older-than`];if(e.expired&&n!==void 0)throw U({code:`CONFLICTING_AGE_FILTER`,message:`--expired and --older-than cannot be combined.`,details:`--expired defers to the expiry each workspace recorded at creation, which --older-than would override.`});if(!e.expired&&n===void 0)throw U({code:`MISSING_AGE_FILTER`,message:`Specify --older-than, or --expired to use each workspace's recorded expiry.`});if(!e.expired&&t.length===0)throw U({code:`MISSING_NAME_FILTER`,message:`Specify at least one --name.`,details:`Only workspaces whose name matches the filter are considered for deletion.`});let r=e[`organization-root`]??[],i=e[`folder-id`]??[],a=[[`--organization-root`,r],[`--folder-id`,i]].filter(([,e])=>e.includes(``)).map(([e])=>e);if(a.length>0)throw U({code:`EMPTY_SCOPE`,message:`${a.join(` and `)} resolved to an empty value.`,details:`An empty location is indistinguishable from an omitted one, so the sweep would not cover what the caller meant. This usually means an unset CI secret.`,suggestion:`Set the id, or drop the option on purpose.`});let o=n===void 0?void 0:Ur(n),s={nameRegexes:t.map(compileNameRegex),...o===void 0?{}:{olderThanMs:o},organizationRoots:r,folderIds:i,personal:e.personal,exclude:new Set(e.exclude??[])};if(e.expired&&!hasLocation(s))throw U({code:`UNSCOPED_EXPIRED`,message:`--expired requires --organization-root, --folder-id, or --personal.`,suggestion:Vo,details:`The expiry lives on the workspace, and writing a workspace's metadata is a lesser permission than deleting it, so an unscoped sweep would delete on behalf of anyone able to write that metadata.`});if(o===0&&!hasLocation(s))throw U({code:`UNSCOPED_ZERO_AGE`,message:`--older-than 0s requires --organization-root, --folder-id, or --personal.`,suggestion:Vo,details:`Without an age check the name filter is the only guard, so the sweep must name the organization roots, folders, or personal workspaces it covers.`});await R({profile:e.profile}),hasLocation(s)||x.warn(`No location was specified. Every workspace visible to this login is a candidate for the name and age filters. ${Vo}`);let c=await Lr({profile:e.profile}),l=await Jn({profile:e.profile}),u=await xe(c,l),d=/* @__PURE__ */ new Date,f=selectPruneCandidates(await fetchAllWorkspaces(u),s,d),p={dryRun:e[`dry-run`],candidates:[],deleted:[],failed:[],skipped:{excluded:[],deleteProtection:[],unknownAge:[],notExpired:[],noExpiry:[],unreadableExpiry:[],expiryChanged:[],changed:[]}};if(e.expired){let e=await partitionByExpiry(u,f.candidates,d);f.candidates=e.expired;for(let t of e.pending)p.skipped.notExpired.push(t.name);for(let t of e.unset)p.skipped.noExpiry.push(t.name);for(let{workspace:t,reason:n}of e.unreadable)p.skipped.unreadableExpiry.push(t.name),x.warn(`Keeping ${t.name} (${t.id}): ${n}.`);x.info(`${e.pending.length} workspace(s) have not expired and ${e.unset.length} record no expiry; both were kept.`)}for(let{key:e,selection:t,reason:n}of Bo)for(let r of f[t])p.skipped[e].push(r.name),x.warn(`Keeping ${r.name} (${r.id}): ${n}.`);if(f.tooYoung.length>0&&x.info(`${f.tooYoung.length} matching workspace(s) are younger than ${e[`older-than`]} and were kept.`),f.candidates.length===0){x.info(`No stale workspaces matched.`),x.jsonMode&&x.out(p);return}let m=e.limit>0&&f.candidates.length>e.limit;if(m&&!e[`dry-run`])throw U({code:`PRUNE_LIMIT_EXCEEDED`,message:`${f.candidates.length} workspaces matched, but --limit is ${e.limit}. Nothing was deleted.`,details:`A match count this high usually means the name filter is broader than intended.`,suggestion:`Check the filter with --dry-run, then raise --limit (or pass --limit 0) if every match should be deleted.`});if(p.candidates=await _n(u,f.candidates),x.jsonMode||x.out(p.candidates,{display:{name:Xn,folderName:null,organizationId:null,folderId:null,updatedAt:null}}),e[`dry-run`]){m&&x.warn(`${p.candidates.length} workspaces matched, but --limit is ${e.limit}: a real run would abort without deleting anything.`),x.info(`Dry run: ${p.candidates.length} workspace(s) would be deleted.`),x.jsonMode&&x.out(p);return}if(!e.yes&&!await N.confirm({message:`Delete these ${p.candidates.length} workspace(s)? They can be restored with "tailor workspace restore" for a limited time.`,default:!1}))throw U({code:`PRUNE_CANCELLED`,message:`Prune cancelled. No workspaces were deleted.`});let h=/* @__PURE__ */ new Set;for(let t of p.candidates){let n=Sr(t);try{let{workspace:r}=await u.getWorkspace({workspaceId:t.id}),i=r?staleCandidateReason(r,s):void 0;if(i){p.skipped.changed.push(t.name),x.warn(`Keeping ${n} (${t.id}): ${i}.`);continue}if(e.expired){let e=await Fn(u,t.id,/* @__PURE__ */ new Date);if(`error`in e&&e.error instanceof Q&&e.error.code===Z.NotFound)throw e.error;if((`error`in e?`unreadable`:e.expiry.state)!==`expired`){p.skipped.expiryChanged.push(n),x.info(`Skipped ${n} (${t.id}): its recorded expiry no longer selects it.`);continue}}h.add(t.id),await u.deleteWorkspace({workspaceId:t.id}),p.deleted.push(t),x.success(`Deleted ${n} (${t.id}).`)}catch(e){if(e instanceof Q&&e.code===Z.NotFound){h.add(t.id),p.deleted.push(t),x.info(`${n} (${t.id}) was already deleted.`);continue}let r=e instanceof Error?e.message:String(e);p.failed.push({workspace:t,error:r}),x.error(`Failed to delete ${n} (${t.id}): ${r}`)}}let g=await dn(h);if(g.length>0&&x.info(`Removed ${g.length} local profile(s) that pointed at deleted workspaces: ${g.join(`, `)}.`),x.jsonMode&&x.out(p),x.success(`Deleted ${p.deleted.length} workspace(s).`),p.failed.length>0)throw U({code:`PRUNE_INCOMPLETE`,message:`Failed to delete ${p.failed.length} workspace(s).`,suggestion:`Fix the reported errors and run the command again; deleted workspaces are not retried.`})}}),Uo=q.object({workspaceId:q.uuid({message:`workspace-id must be a valid UUID`}).optional(),profile:q.string().optional()});async function clearWorkspaceTtl(e){let t=Pe(Uo,e),{client:n,workspaceId:r}=await A({profile:t.profile,workspaceId:t.workspaceId});return{workspaceId:r,changed:await pr(n,r)}}const Wo=C({name:`clear`,description:`Drop a workspace's recorded prune expiry.`,notes:`
|
|
115
123
|
A workspace recording no expiry is never deleted by \`workspace prune --expired\`. Clearing an expiry the workspace does not record succeeds without changing anything.
|
|
116
|
-
`,args:q.strictObject({...
|
|
117
|
-
|
|
118
|
-
|
|
124
|
+
`,args:q.strictObject({...M}),run:async e=>{await R({profile:e.profile});let{workspaceId:t,changed:n}=await clearWorkspaceTtl({workspaceId:e[`workspace-id`],profile:e.profile});x.success(`Workspace records no prune expiry.`),k({changed:n,workspaceId:t,expiresAt:null})}}),Go=q.object({workspaceId:q.uuid({message:`workspace-id must be a valid UUID`}).optional(),profile:q.string().optional(),ttl:Nr});async function setWorkspaceTtl(e){let t=Pe(Go,e),{client:n,workspaceId:r}=await A({profile:t.profile,workspaceId:t.workspaceId}),i=new Date(Date.now()+Ur(t.ttl));return{workspaceId:r,expiresAt:i,changed:await an(n,r,i)}}const Ko=C({name:`set`,description:`Record when a workspace becomes prunable, replacing any expiry it already records.`,notes:"\n The expiry runs from now, not from when the workspace was created, so `--ttl 24h` always leaves a full day regardless of the workspace's age. Use this to give a restored workspace a new expiry, or to record one after `workspace create --ttl` failed to.\n\n This is not an auto-delete timer: it only makes the workspace eligible for `workspace prune --expired`, which still honors delete protection and its own filters.\n ",args:q.strictObject({...M,ttl:W(Nr,{description:`Time from now until the workspace becomes prunable, such as 30m, 24h, or 7d`})}),run:async e=>{await R({profile:e.profile});let{workspaceId:t,expiresAt:n,changed:r}=await setWorkspaceTtl({workspaceId:e[`workspace-id`],profile:e.profile,ttl:e.ttl});x.success(`Workspace becomes prunable at ${n.toISOString()}.`);let i=s($n(Rn(n)),`encoded workspace expiry must decode`);k({changed:r,workspaceId:t,expiresAt:i.toISOString()})}}),qo=G({name:`ttl`,description:`Manage when a workspace becomes prunable.`,subCommands:{set:Ko,clear:Wo},async run(){await It(qo,[`--help`])}}),Jo=G({name:`user`,description:`Manage workspace users`,subCommands:{invite:kn,list:Or,remove:mn,update:cr},defaultSubCommand:`list`}),Yo=G({name:`workspace`,description:`Manage Tailor Platform workspaces.`,subCommands:{app:Ro,create:Hn,delete:Mr,get:Pn,list:ar,prune:Ho,restore:Qn,ttl:qo,user:Jo},defaultSubCommand:`list`});await wr(new URL(`./ts-hook.mjs`,import.meta.url)),li();const Xo=await ni(),Zo=Object.keys(Xo.bin??{})[0]||`tailor`,Qo=Xo.name??`@tailor-platform/sdk`,$o=await xi(import.meta.url),es=bi(yi($o),`agent-skills`),ts=bi(yi($o),`docs`,`cli-reference.md`),ns=`AI coding agent detected:
|
|
125
|
+
|
|
126
|
+
- Unless \`--json=false\` or \`${Te}=false\` is set, commands that return structured results print JSON to stdout. Parse it instead of the table output, which is formatted for humans and may change.
|
|
127
|
+
- CLI plugin commands keep the table unless you pass \`--json\` or set \`${Te}=true\`.
|
|
128
|
+
- Pass \`--help-json\` to a command for machine-readable help.
|
|
129
|
+
- Full command reference: \`${ts}\``;function defaultSkillsRunToAdd(e){let{run:t,...n}=e;return{...n,defaultSubCommand:`add`}}const rs=vi(G({name:Zo,description:Xo.description||`Tailor CLI for managing Tailor Platform SDK applications`,notes:`CLI plugins (beta): an unknown subcommand is dispatched to an external plugin executable named \`${Zo}-<name>\` (found on your PATH or in node_modules/.bin), similar to \`gh\` extensions.
|
|
130
|
+
Run \`${Zo} plugin list\` to see which plugins are installed and where they resolve from.
|
|
131
|
+
The \`setup\` commands are provided by the @tailor-platform/sdk-plugin-setup CLI plugin.`,subCommands:{api:Ji,auth:Zi,authconnection:ia,crashreport:sa,data:pa,deploy:ma,executor:ha,function:Ta,generate:Ea,init:Da,login:Aa,logout:ja,machineuser:Ma,oauth2client:Na,open:Pa,organization:Ia,plugin:Va,profile:Ka,query:sn,remove:Bt,secret:ao,show:Gr,staticwebsite:po,tailordb:Co,upgrade:wo,user:Io,workflow:Lo,workspace:Yo}}),{sourceDir:es,package:Qo,mode:`copy`,descriptionAppend:!1,globalArgs:q.object(Ge),commandMap:{add:[`add`],remove:[`remove`]},unknownKeys:`strict`,descriptions:{skills:`Manage Tailor SDK agent skills.`,add:`Install Tailor SDK agent skills.`,list:`List Tailor SDK agent skills.`,remove:`Remove installed Tailor SDK agent skills.`,sync:`Remove and reinstall Tailor SDK agent skills.`}}),is=_i({...rs,subCommands:{...rs.subCommands,skills:defaultSkillsRunToAdd(rs.subCommands.skills)}});hi(is,{version:Xo.version,globalArgs:q.object(Ge),displayErrors:!1,agentHelp:ns,setup:({agent:e})=>{Ee(e?.id)},onUnknownSubcommand:({commandPath:e,name:t,args:n,precedingArgs:r})=>dispatchPluginWithInstallHint({commandPath:e,name:t,args:[...r,...n],cliName:Zo,profile:process.env.TAILOR_PLATFORM_PROFILE}),cleanup:async({error:e})=>{if(e){xt()||lr(e,process.argv.slice(2));let t;if(x.jsonMode?x.log(Ln(e,{includeStack:x.verbose})):Zr(e)?(x.log(e.format()),x.verbose&&e.stack&&x.debug(`\nStack trace:\n${e.stack}`)):e instanceof Error?(x.error(e.message),t=b(e).suggestion??ti(e),t&&x.log(` ${S.info(`Suggestion:`)} ${t}`),x.verbose&&e.stack&&x.debug(`\nStack trace:\n${e.stack}`)):x.error(`Unknown error: ${e}`),nr(e,{jsonMode:x.jsonMode,suggestion:t}),!Zr(e)&&(!(e instanceof Error)||e instanceof TypeError||e instanceof RangeError)){let{reportCrash:t}=await import(`../crashreport-BcXuocwI.mjs`);await t(e,`handledError`)}}let{shutdownTelemetry:t}=await import(`../telemetry-DpkFGBmu.mjs`);await t()}});export{is as mainCommand};
|
|
119
132
|
//# sourceMappingURL=main.mjs.map
|