@tailor-platform/sdk 2.14.2 → 2.15.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 +38 -0
- package/bin/tailor.mjs +2 -2
- package/dist/{application-BAqZFMWP.mjs → application-BpoMu4Af.mjs} +18 -18
- package/dist/application-BpoMu4Af.mjs.map +1 -0
- package/dist/application-fIhVKX78.mjs +1 -0
- package/dist/cli/commands/deploy/app-id-lock.d.mts +97 -0
- package/dist/cli/commands/tailordb/migrate/diff-calculator.d.mts +15 -1
- package/dist/cli/commands/tailordb/migrate/generate.d.mts +5 -2
- package/dist/cli/commands/tailordb/migrate/rename-detection.d.mts +13 -0
- package/dist/cli/commands/tailordb/migrate/snapshot-comparison.d.mts +7 -1
- package/dist/cli/commands/workflow/executions.d.mts +2 -0
- package/dist/cli/lib.d.mts +4 -2
- package/dist/cli/lib.mjs +1 -1
- package/dist/cli/lib.mjs.map +1 -1
- package/dist/cli/main.d.mts +8 -8
- package/dist/cli/main.mjs +42 -44
- package/dist/cli/main.mjs.map +1 -1
- package/dist/cli/shared/command.d.mts +1 -1
- package/dist/cli/shared/function-execution.d.mts +14 -0
- package/dist/completion/zsh-worker.zsh +8 -3
- package/dist/configure/config/types.d.mts +23 -6
- package/dist/configure/index.mjs +1 -1
- package/dist/configure/index.mjs.map +1 -1
- package/dist/configure/services/executor/trigger/event.d.mts +5 -2
- package/dist/date-CGBZbMW5.mjs +2 -0
- package/dist/date-CGBZbMW5.mjs.map +1 -0
- package/dist/file-DKBOj5q4.mjs +2 -0
- package/dist/file-DKBOj5q4.mjs.map +1 -0
- package/dist/plugin/builtin/file-utils/index.mjs +27 -1
- package/dist/plugin/builtin/file-utils/index.mjs.map +1 -1
- package/dist/register-ts-hook-CAUcxCt4.mjs +711 -0
- package/dist/register-ts-hook-CAUcxCt4.mjs.map +1 -0
- package/dist/runtime/file.d.mts +46 -2
- package/dist/runtime/file.mjs +1 -1
- package/dist/runtime/index.mjs +1 -1
- package/dist/{schema-DMlLMsWA.mjs → schema-BTioi2dP.mjs} +2 -2
- package/dist/{schema-DMlLMsWA.mjs.map → schema-BTioi2dP.mjs.map} +1 -1
- package/dist/service_pb-DKrsO1_u.mjs +1 -0
- package/dist/service_pb-DprmLNsq.mjs +2 -0
- package/dist/{service_pb-BdzjiHfC.mjs.map → service_pb-DprmLNsq.mjs.map} +1 -1
- package/dist/types/auth.generated.d.mts +1 -19
- package/dist/types/executor.generated.d.mts +5 -3
- package/dist/types/field.generated.d.mts +40 -0
- package/dist/types/helpers.d.mts +9 -1
- package/dist/types/resolver.generated.d.mts +5 -40
- package/dist/vitest/index.d.mts +2 -3
- package/dist/vitest/index.mjs +1 -1
- package/dist/vitest/index.mjs.map +1 -1
- package/dist/vitest/mocks/file.d.mts +2 -2
- package/dist/vitest/setup.d.mts +0 -37
- package/dist/vitest/setup.mjs +1 -1
- package/dist/vitest/setup.mjs.map +1 -1
- package/dist/{workspace_resource_pb-C4EY-Gns.mjs → workspace_resource_pb-BOoRts_z.mjs} +2 -2
- package/dist/{workspace_resource_pb-C4EY-Gns.mjs.map → workspace_resource_pb-BOoRts_z.mjs.map} +1 -1
- package/docs/cli/application.md +1 -1
- package/docs/cli/function.md +19 -6
- package/docs/cli/tailordb.md +11 -11
- package/docs/configuration.md +20 -3
- package/docs/github-actions.md +45 -13
- package/docs/migration/v3.md +38 -0
- package/docs/runtime.md +39 -0
- package/docs/services/resolver.md +3 -1
- package/docs/services/tailordb-migration.md +25 -5
- package/docs/testing.md +3 -7
- package/package.json +7 -7
- package/dist/application-BAqZFMWP.mjs.map +0 -1
- package/dist/application-BKlOiD1x.mjs +0 -1
- package/dist/date-DrUO8rOJ.mjs +0 -2
- package/dist/date-DrUO8rOJ.mjs.map +0 -1
- package/dist/file-COPYfju_.mjs +0 -2
- package/dist/file-COPYfju_.mjs.map +0 -1
- package/dist/register-ts-hook-Cphn4r8s.mjs +0 -642
- package/dist/register-ts-hook-Cphn4r8s.mjs.map +0 -1
- package/dist/service_pb-BdzjiHfC.mjs +0 -2
- package/dist/service_pb-p68oLtp9.mjs +0 -1
package/dist/cli/main.mjs
CHANGED
|
@@ -1,37 +1,35 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{r as e}from"../schema-
|
|
3
|
-
`)}const Hr=D({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 rr({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))}}),Ur=D({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?o(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=o(t[e],`path segment missing`),i=r[n];(typeof i!=`object`||!i||Array.isArray(i))&&(r[n]={}),r=r[n]}r[o(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 Error(`Invalid value for bool field: '${t}'. Expected 'true' or 'false'.`)}return t}function normalizeBodyFieldKeys(e,t){let n=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 Wr=new Set([`__proto__`,`constructor`,`prototype`]),Gr=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=>Wr.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)}}),Kr=D({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:Ur,inspect:Hr},args:q.strictObject({...P,...qe,body:W(q.string().default(`{}`),{alias:`b`,description:`Request body as JSON.`}),field:W(Gr.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 j({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 Error(`--field requires --body to be a JSON object (or omitted).`);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 Ne({workspaceId:e[`workspace-id`],profile:e.profile}),i=!0}catch{}if(a.includes(`namespaceName`)&&!Object.hasOwn(r,`namespaceName`))try{let{config:n}=await w(e.config),a=resolveNamespaceName(t,n);a&&(r.namespaceName=a,i=!0)}catch{}}let a=await cn({profile:e.profile,endpoint:e.endpoint,body:i&&r?JSON.stringify(r):e.body});c.out(JSON.stringify(a.data,null,2))}}),qr=D({name:`status`,description:`Show the active Tailor Platform authentication status without printing tokens.`,args:q.strictObject({profile:P.profile}),run:async({profile:e})=>{let t=await ye({profile:e});if(c.out(t),!t.authenticated)throw Error(`Not authenticated. Run 'tailor login' and try again.`)}}),Jr=D({name:`token`,description:`Print a valid Tailor Platform access token to stdout, refreshing it first if expired.`,args:q.strictObject({profile:P.profile}),run:async({profile:e})=>{let t=await Et({profile:e});c.out(t)}}),Yr=G({name:`auth`,description:`Authentication helpers for scripts and plugins.`,subCommands:{status:qr,token:Jr}}),Xr={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 Error(`Failed to fetch OIDC discovery from ${t}: ${Qn(e).message}`,{cause:e})});if(!n.ok)throw Error(`Failed to fetch OIDC discovery from ${t}: ${n.status}`);return n.json()}function randomState$1(){return Dr.randomBytes(32).toString(`base64url`)}const Zr=D({name:`authorize`,description:`Authorize an auth connection via OAuth2 flow.`,args:q.strictObject({...P,...Xr,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 j({profile:e.profile});let{client:t,workspaceId:n}=await v({profile:e.profile,workspaceId:e[`workspace-id`]}),r=(await wn(async(e,r)=>{let{connections:i,nextPageToken:a}=await t.listAuthConnections({workspaceId:n,pageToken:e,pageSize:r});return[i,a]})).find(t=>t.name===e.name);if(!r)throw Error(`Auth connection "${e.name}" not found.`);if(r.config.case!==`oauth2`)throw Error(`Auth connection "${e.name}" is not an OAuth2 connection.`);let i=r.config.value,a=`http://localhost:${e.port}/callback`,o=randomState$1(),s;s=i.authUrl?i.authUrl:(await fetchOIDCDiscovery(i.providerUrl)).authorization_endpoint;let l=new URL(s);l.searchParams.set(`client_id`,i.clientId),l.searchParams.set(`redirect_uri`,a),l.searchParams.set(`response_type`,`code`),l.searchParams.set(`scope`,e.scopes.replace(/,/g,` `)),l.searchParams.set(`state`,o),l.searchParams.set(`access_type`,`offline`),await new Promise((r,i)=>{let handleCallback=async(c,l)=>{if(!c.url?.startsWith(`/callback`)){l.writeHead(404),l.end(`Not found`);return}try{let i=new URL(c.url,`http://localhost:${e.port}`),u=i.searchParams.get(`code`),d=i.searchParams.get(`state`),f=i.searchParams.get(`error`);if(f)throw Error(`Authorization failed: ${f}`);if(d!==o)throw Error(`State mismatch — possible CSRF attack.`);if(!u)throw Error(`No authorization code received.`);await t.exchangeAuthConnectionAuthorizationCode({workspaceId:n,connectionName:e.name,authorizationCode:u,redirectUri:a}),l.writeHead(200,{"Content-Type":`text/html`}),l.end(`<html><body><h1>Authorization successful</h1><p>You can close this window.</p></body></html>`),s.close(),r()}catch(e){l.writeHead(400,{"Content-Type":`text/plain`}),l.end(`Authorization failed: ${e instanceof Error?e.message:`Unknown error`}`),s.close(),i(Qn(e))}},s=kr.createServer((e,t)=>void handleCallback(e,t)),u=setTimeout(()=>{s.close(),i(Error(`Authorization timeout exceeded (5 minutes).`))},3e5);s.on(`close`,()=>{clearTimeout(u)}),s.on(`error`,t=>{clearTimeout(u);let n=t.code,r=n===`EADDRINUSE`||n===`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}${n?` (${n})`:``}.\n${r}\n tailor authconnection open`),i(t)});let announceAuthorizeUrl=async()=>{let t=l.toString();if(c.info(e[`no-browser`]?`Open this URL in your browser to authorize:\n\n${t}\n`:`Opening browser for authorization:\n\n${t}\n`),c.info(`If this flow doesn't complete, you can authorize via the Console instead:
|
|
4
|
-
tailor authconnection open`),!e[`no-browser`])try{await
|
|
5
|
-
`),n=`\n${
|
|
6
|
-
`)[0];return i?JSON.parse(i):void 0}catch{return}}const
|
|
2
|
+
import{r as e}from"../schema-BTioi2dP.mjs";import{E as t,It as n,Ut as r,kt as i,q as a}from"../workspace_resource_pb-BOoRts_z.mjs";import{t as o}from"../assert-WeXvmG4j.mjs";import{a as s,n as c,r as l}from"../logger-CCjs1DuH.mjs";import{$ as u,$r as d,$t as f,An as p,Ar as m,B as h,Bn as g,Br as _,C as v,Cr as y,Ct as b,Dn as x,Dr as S,Dt as C,E as ee,Er as te,Fn as w,Fr as T,Ft as ne,Gn as re,Gr as ie,Hn as ae,Hr as oe,Ht as se,I as ce,In as le,Ir as E,Jn as ue,Jr as de,K as fe,Kn as pe,Kr as me,Kt as he,L as ge,Ln as _e,Lr as ve,M as ye,Mn as be,Mr as xe,Mt as Se,N as Ce,Nn as we,Nr as Te,Nt as Ee,O as De,On as Oe,Or as ke,P as Ae,Pn as je,Pr as Me,Qn as D,Qr as O,Qt as Ne,R as Pe,Rn as Fe,Rr as k,Sr as Ie,St as Le,Tn as Re,Tr as ze,Tt as Be,Un as A,Ur as Ve,V as He,Vn as Ue,Vr as We,W as Ge,Wn as Ke,Wr as qe,Wt as Je,X as Ye,Xn as Xe,Xr as Ze,Xt as Qe,Yn as $e,Yr as et,Yt as tt,Z as nt,Zn as j,Zr as rt,Zt as it,_i as at,_r as ot,_t as st,a as ct,ai as M,ar as lt,at as ut,bi as N,br as dt,bt as ft,c as pt,ci as mt,cn as ht,cr as gt,di as P,dn as _t,dr as vt,dt as yt,ei as bt,en as xt,f as St,fi as Ct,fn as wt,g as Tt,gi as F,gn as Et,gr as Dt,gt as Ot,hi as kt,hn as At,hr as jt,ii as I,ir as Mt,j as Nt,jn as Pt,jr as Ft,kn as It,kr as Lt,kt as Rt,li as L,ln as zt,lt as Bt,m as Vt,mi as Ht,mn as Ut,mr as Wt,ni as Gt,nn as Kt,o as qt,on as Jt,pr as Yt,pt as Xt,q as Zt,qn as Qt,qr as $t,r as en,ri as tn,rn as nn,rt as rn,si as an,sn as on,sr as sn,st as cn,t as ln,ti as un,tn as dn,tt as fn,u as pn,ur as mn,v as hn,vi as gn,vr as _n,w as vn,wr as R,wt as yn,x as bn,xr as xn,xt as Sn,yi as z,yr as Cn,yt as wn,z as Tn,zn as En,zr as B,zt as Dn}from"../register-ts-hook-CAUcxCt4.mjs";import{$ as On,A as kn,B as An,D as jn,E as Mn,G as V,H as Nn,K as Pn,M as Fn,N as In,O as Ln,Q as Rn,U as zn,V as Bn,X as Vn,Y as Hn,Z as Un,d as Wn,et as Gn,f as Kn,h as qn,j as Jn,k as Yn,o as Xn,p as Zn,q as Qn,s as $n,v as er,y as tr}from"../application-BpoMu4Af.mjs";import{g as nr,i as rr,r as ir}from"../service-7SCy2bhm.mjs";import{t as H}from"../multiline-EyzjEwn9.mjs";import{t as ar}from"../package-json-C690ceex.mjs";import{t as or}from"../user-agent-vdHYF3QL.mjs";import{a as sr,i as cr,n as lr,o as ur,r as dr,t as fr}from"../errors-BlX4gUw5.mjs";import{t as pr}from"../service_pb-DprmLNsq.mjs";import{a as mr,i as hr,o as gr,r as _r,t as vr}from"../crashreport-BN28xp5B.mjs";import{a as yr,i as br,n as xr}from"../kysely-type-B-BOlXH7.mjs";import{arg as U,defineCommand as W,extractFields as Sr,runCommand as G,runMain as Cr,toCamelCase as wr}from"@politty/zod";import{withCompletionCommand as Tr}from"@politty/zod/completion";import{withSkillCommand as Er}from"@politty/zod/skill";import*as K from"pathe";import{dirname as Dr,resolve as Or}from"pathe";import{resolvePackageJSON as kr}from"pkg-types";import{z as q}from"zod";import{ScalarType as J,create as Ar}from"@bufbuild/protobuf";import*as Y from"node:fs";import{accessSync as jr,constants as Mr,readdirSync as Nr}from"node:fs";import{timestampDate as X}from"@bufbuild/protobuf/wkt";import{pathToFileURL as Pr}from"node:url";import{generateCodeVerifier as Fr}from"@badgateway/oauth2-client";import{Code as Z,ConnectError as Q}from"@connectrpc/connect";import*as Ir from"node:crypto";import{randomBytes as Lr}from"node:crypto";import*as Rr from"node:http";import zr from"open";import*as Br from"rolldown";import{parseSync as Vr}from"oxc-parser";import*as Hr from"node:os";import*as $ from"node:fs/promises";import{setTimeout as Ur}from"node:timers/promises";import{TraceMap as Wr,generatedPositionFor as Gr,originalPositionFor as Kr}from"@jridgewell/trace-mapping";import{spawn as qr,spawnSync as Jr}from"node:child_process";const Yr=pr.methods.filter(e=>e.methodKind===`unary`);function listMethodNames(){return Yr.map(e=>e.name).toSorted()}function listMethodChoices(){return Yr.flatMap(e=>[e.name,`${pr.typeName}/${e.name}`]).toSorted()}function getMethodDescriptor(e){return Yr.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 Xr=new Set([`google.protobuf.Struct`,`google.protobuf.Value`,`google.protobuf.ListValue`,`google.protobuf.NullValue`,`google.protobuf.Any`,`google.protobuf.Empty`]);function isUnrepresentableWellKnownType(e){return Xr.has(e.typeName)}function enumerateAllFieldCompletions(e){let t=getMethodDescriptor(e);if(!t)return[];let n=[],r=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 Zr={[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 Zr[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=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=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 Qr=M({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:U(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 fr({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))}}),$r=M({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?o(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=o(t[e],`path segment missing`),i=r[n];(typeof i!=`object`||!i||Array.isArray(i))&&(r[n]={}),r=r[n]}r[o(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 Error(`Invalid value for bool field: '${t}'. Expected 'true' or 'false'.`)}return t}function normalizeBodyFieldKeys(e,t){let n=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 ei=new Set([`__proto__`,`constructor`,`prototype`]),ti=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=>ei.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)}}),ni=M({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:$r,inspect:Qr},args:q.strictObject({...N,...mt,body:U(q.string().default(`{}`),{alias:`b`,description:`Request body as JSON.`}),field:U(ti.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:U(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 k({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 Error(`--field requires --body to be a JSON object (or omitted).`);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 rt({workspaceId:e[`workspace-id`],profile:e.profile}),i=!0}catch{}if(a.includes(`namespaceName`)&&!Object.hasOwn(r,`namespaceName`))try{let{config:n}=await B(e.config),a=resolveNamespaceName(t,n);a&&(r.namespaceName=a,i=!0)}catch{}}let a=await ve({profile:e.profile,endpoint:e.endpoint,body:i&&r?JSON.stringify(r):e.body});c.out(JSON.stringify(a.data,null,2))}}),ri=M({name:`status`,description:`Show the active Tailor Platform authentication status without printing tokens.`,args:q.strictObject({profile:N.profile}),run:async({profile:e})=>{let t=await ie({profile:e});if(c.out(t),!t.authenticated)throw Error(`Not authenticated. Run 'tailor login' and try again.`)}}),ii=M({name:`token`,description:`Print a valid Tailor Platform access token to stdout, refreshing it first if expired.`,args:q.strictObject({profile:N.profile}),run:async({profile:e})=>{let t=await qe({profile:e});c.out(t)}}),ai=W({name:`auth`,description:`Authentication helpers for scripts and plugins.`,subCommands:{status:ri,token:ii}}),oi={name:U(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 Error(`Failed to fetch OIDC discovery from ${t}: ${sr(e).message}`,{cause:e})});if(!n.ok)throw Error(`Failed to fetch OIDC discovery from ${t}: ${n.status}`);return n.json()}function randomState$1(){return Ir.randomBytes(32).toString(`base64url`)}const si=M({name:`authorize`,description:`Authorize an auth connection via OAuth2 flow.`,args:q.strictObject({...N,...oi,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 k({profile:e.profile});let{client:t,workspaceId:n}=await E({profile:e.profile,workspaceId:e[`workspace-id`]}),r=(await Nn(async(e,r)=>{let{connections:i,nextPageToken:a}=await t.listAuthConnections({workspaceId:n,pageToken:e,pageSize:r});return[i,a]})).find(t=>t.name===e.name);if(!r)throw Error(`Auth connection "${e.name}" not found.`);if(r.config.case!==`oauth2`)throw Error(`Auth connection "${e.name}" is not an OAuth2 connection.`);let i=r.config.value,a=`http://localhost:${e.port}/callback`,o=randomState$1(),s;s=i.authUrl?i.authUrl:(await fetchOIDCDiscovery(i.providerUrl)).authorization_endpoint;let l=new URL(s);l.searchParams.set(`client_id`,i.clientId),l.searchParams.set(`redirect_uri`,a),l.searchParams.set(`response_type`,`code`),l.searchParams.set(`scope`,e.scopes.replace(/,/g,` `)),l.searchParams.set(`state`,o),l.searchParams.set(`access_type`,`offline`),await new Promise((r,i)=>{let handleCallback=async(c,l)=>{if(!c.url?.startsWith(`/callback`)){l.writeHead(404),l.end(`Not found`);return}try{let i=new URL(c.url,`http://localhost:${e.port}`),u=i.searchParams.get(`code`),d=i.searchParams.get(`state`),f=i.searchParams.get(`error`);if(f)throw Error(`Authorization failed: ${f}`);if(d!==o)throw Error(`State mismatch — possible CSRF attack.`);if(!u)throw Error(`No authorization code received.`);await t.exchangeAuthConnectionAuthorizationCode({workspaceId:n,connectionName:e.name,authorizationCode:u,redirectUri:a}),l.writeHead(200,{"Content-Type":`text/html`}),l.end(`<html><body><h1>Authorization successful</h1><p>You can close this window.</p></body></html>`),s.close(),r()}catch(e){l.writeHead(400,{"Content-Type":`text/plain`}),l.end(`Authorization failed: ${e instanceof Error?e.message:`Unknown error`}`),s.close(),i(sr(e))}},s=Rr.createServer((e,t)=>void handleCallback(e,t)),u=setTimeout(()=>{s.close(),i(Error(`Authorization timeout exceeded (5 minutes).`))},3e5);s.on(`close`,()=>{clearTimeout(u)}),s.on(`error`,t=>{clearTimeout(u);let n=t.code,r=n===`EADDRINUSE`||n===`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}${n?` (${n})`:``}.\n${r}\n tailor authconnection open`),i(t)});let announceAuthorizeUrl=async()=>{let t=l.toString();if(c.info(e[`no-browser`]?`Open this URL in your browser to authorize:\n\n${t}\n`:`Opening browser for authorization:\n\n${t}\n`),c.info(`If this flow doesn't complete, you can authorize via the Console instead:
|
|
4
|
+
tailor authconnection open`),!e[`no-browser`])try{await zr(t)}catch{c.warn(`Failed to open browser automatically. Please open the URL above manually.`)}};s.listen(e.port,()=>void announceAuthorizeUrl())}),c.success(`Auth connection "${e.name}" authorized successfully.`)}}),ci=M({name:`delete`,description:`Delete an auth connection entirely.`,args:q.strictObject({...N,...oi,...L}),run:async e=>{await k({profile:e.profile});let{client:t,workspaceId:n}=await E({profile:e.profile,workspaceId:e[`workspace-id`]});if(!e.yes&&await T.text({message:`Enter the connection name to confirm deletion ("${e.name}"):`})!==e.name){c.info(`Auth connection deletion cancelled.`);return}try{await t.deleteAuthConnection({workspaceId:n,connectionName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?Error(`Auth connection "${e.name}" not found.`,{cause:t}):t}c.success(`Auth connection "${e.name}" deleted.`)}});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 li=M({name:`list`,description:`List all auth connections.`,args:q.strictObject({...N,...F()}),run:async e=>{let{client:t,workspaceId:n}=await E({profile:e.profile,workspaceId:e[`workspace-id`]});try{let r=z(e.order),i=await V(async(e,i)=>{let{connections:a,nextPageToken:o}=await t.listAuthConnections({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e.limit});c.out(i.map(connectionInfo))}catch(e){if(e instanceof Q&&e.code===Z.NotFound){c.out([]);return}throw e}}}),ui=M({name:`open`,description:`Open the auth connections page in the Tailor Platform Console.`,args:q.strictObject({...N}),run:async e=>{let t=await rt({workspaceId:e[`workspace-id`],profile:e.profile}),n=s(process.env.TAILOR_CONSOLE_NEXT)===!0?`/workspaces/${t}/services/auth-connections`:`/workspaces/${t}/settings/connections`,r=await $t({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 zr(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}`)}}),di=M({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({...N,...oi,...L}),run:async e=>{await k({profile:e.profile});let{client:t,workspaceId:n}=await E({profile:e.profile,workspaceId:e[`workspace-id`]});if(!e.yes&&await T.text({message:`Enter the connection name to confirm revocation ("${e.name}"):`})!==e.name){c.info(`Auth connection revocation cancelled.`);return}try{await t.revokeAuthConnection({workspaceId:n,connectionName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?Error(`Auth connection "${e.name}" not found.`,{cause:t}):t}c.success(`Auth connection "${e.name}" revoked.`)}}),fi=W({name:`authconnection`,description:`Manage auth connections.`,subCommands:{authorize:si,list:li,open:ui,revoke:di,delete:ci},async run(){await G(li,[])}});function orderAndLimitCrashReports(e,t){let n=e.filter(e=>e.endsWith(hr)).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 pi=M({name:`list`,description:`List local crash report files.`,args:q.strictObject({...F()}),run:async e=>{let t=gr(),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=orderAndLimitCrashReports(r,{order:e.order,limit:e.limit});if(i.length===0){c.info(`No crash reports found.`),n&&c.out([]);return}if(n){c.out(formatCrashReportFiles(i,t.localDir));return}c.info(`${i.length} crash report(s) in ${t.localDir}:`);for(let e of i)c.log(` ${e}`)}}),mi=M({name:`send`,description:`Submit a crash report to help improve the SDK.`,args:q.strictObject({file:U(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 or();c.info(`Sending crash report...`),await _r(n,r)?c.success(`Crash report submitted successfully. Thank you!`):(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,`
|
|
5
|
+
`),n=`\n${mr}\n`,r=t.lastIndexOf(n);if(r===-1)return;let i=t.slice(r+n.length).split(`
|
|
6
|
+
`)[0];return i?JSON.parse(i):void 0}catch{return}}const hi=W({name:`crashreport`,description:`Manage crash reports.`,subCommands:{list:pi,send:mi},async run(){await G(pi,[])}}),gi=M({name:`deploy`,description:`Deploy your application by applying the Tailor configuration.`,args:q.strictObject({...N,...Ht,...L,"create-workspace":U(q.boolean().optional(),{description:`Create a workspace when the account has none`}),"workspace-name":U(q.string().optional(),{description:`Name for a workspace created during deploy`}),"workspace-region":U(q.string().optional(),{description:`Region for a workspace created during deploy`}),"organization-id":U(q.string().optional(),{description:`Organization ID for a workspace created during deploy`,env:`TAILOR_PLATFORM_ORGANIZATION_ID`}),"folder-id":U(q.string().optional(),{description:`Folder ID for a workspace created during deploy`,env:`TAILOR_PLATFORM_FOLDER_ID`}),"dry-run":U(q.boolean().optional(),{alias:`d`,description:`Run the command without making any changes`}),"no-schema-check":U(q.boolean().optional(),{description:`Skip schema diff check against migration snapshots`}),"no-validate":U(q.boolean().optional(),{description:`Skip client-side validation against platform resource constraints`}),"no-cache":U(q.boolean().optional(),{description:`Disable bundle caching for this run`}),"clean-cache":U(q.boolean().optional(),{description:`Clean the bundle cache before building`})}),run:async e=>{await k({profile:e.profile});let{initTelemetry:t}=await import(`../telemetry-DXHP3VVi.mjs`);await t(),await Jt({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`],organizationId:e[`organization-id`],folderId:e[`folder-id`],noSchemaCheck:e[`no-schema-check`],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})}}),_i=W({name:`executor`,description:`Manage executors`,subCommands:{trigger:Ee,jobs:Dn,list:ne,get:nn,webhook:Se},async run(){await G(ne,[])}});function scriptNameToRegistryName(e,t){if(t===a.JOB)return`workflow--${e}`;let n=/^([^.]+)\.(.+)\.body\.js$/.exec(e);if(n){let[,e,t]=n;return`resolver--${e}--${t}`}let r=/^(.+)\.operation\.js$/.exec(e);if(r){let[,e]=r;return`executor--${e}`}let i=/^([^.]+)\.([^.]+)\.hook\.js$/.exec(e);if(i){let[,e,t]=i;return`auth-hook--${e}--${t}`}return t===a.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 c.debug(`Failed to download function script "${e.name}": ${t}`),null}}const vi=/^\s+at\s+(?:(.+?)\s+\()?(file:\/\/\/.+?):(\d+):(\d+)\)?$/;function parseStackTrace(e){let t=e.split(`
|
|
7
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(`
|
|
8
|
-
`);i.startsWith(`rpc error: code = Aborted desc = `)&&(i=i.slice(33));let a=[];for(let e of r){let t=
|
|
8
|
+
`);i.startsWith(`rpc error: code = Aborted desc = `)&&(i=i.slice(33));let a=[];for(let e of r){let t=vi.exec(e);t&&a.push({functionName:t[1]||`<anonymous>`,file:o(t[2],`stack frame file missing`),line:Number(o(t[3],`stack frame line missing`)),column:Number(o(t[4],`stack frame column missing`))})}return{errorMessage:i,frames:a}}const yi=/\/\/[#@]\s*sourceMappingURL=data:application\/json[^,]*;base64,(.+)$/m;function extractInlineSourcemap(e){let t=yi.exec(e);if(!t)return null;try{let e=Buffer.from(o(t[1],`sourcemap base64 data missing`),`base64`).toString(`utf-8`),n=JSON.parse(e);return new Wr(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=Gr(t,{source:r,line:e.line,column:e.column-1});if(i.line==null)continue;let a=Kr(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
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(` ${l.error(`>`)} ${l.error(`${i} | ${s}`)}`):o.push(` ${l.dim(`${i} | ${s}`)}`)}return o.join(`
|
|
10
|
-
`)}function formatMappedError(e,t,n,r){let i=[` ${l.error(e)}`];for(let e of t)if(e.mapped){let{source:t,line:a,column:o,name:s}=e.mapped,c=r?
|
|
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){switch(e){case a.STANDARD:return`STANDARD`;case a.JOB:return`JOB`;default:return`UNSPECIFIED`}}function toFunctionExecutionListInfo(e){return{id:e.id,scriptName:e.scriptName,status:
|
|
10
|
+
`)}function formatMappedError(e,t,n,r){let i=[` ${l.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);if(e!==-1){let t=n.sourcesContent?.[e];t&&i.push(buildCodeSnippet(t,a))}}}else{let t=`${e.original.file.replace(/^file:\/\/\//,``)}:${e.original.line}:${e.original.column}`;i.push(`\n ${l.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){switch(e){case a.STANDARD:return`STANDARD`;case a.JOB:return`JOB`;default:return`UNSPECIFIED`}}function toFunctionExecutionListInfo(e){return{id:e.id,scriptName:e.scriptName,status:xt(e.status),type:functionExecutionTypeToString(e.type),startedAt:e.startedAt?X(e.startedAt):null,finishedAt:e.finishedAt?X(e.finishedAt):null}}function toFunctionExecutionDetailInfo(e){return{...toFunctionExecutionListInfo(e),logs:e.logs,logEntries:e.logEntries.map(Kt),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;if(!r)return`${t}: ${n}`;let i=r.split(`
|
|
12
12
|
`,1)[0]??``;return/^\s+at\s+/.test(i)?`${t}: ${n}\n${r}`:r}function formatExecutionErrorFallback(e){let[t=``,...n]=composeExecutionErrorString(e).split(`
|
|
13
13
|
`);return[` ${l.error(t)}`,...n.map(e=>` ${l.dim(e)}`)].join(`
|
|
14
|
-
`)}function formatExecutionError(e,t){if(t&&e.stackTrace){let n=formatErrorWithSourcemap(composeExecutionErrorString(e),t,process.cwd());if(n)return n}return formatExecutionErrorFallback(e)}
|
|
15
|
-
Logs:`));for(let e of t.
|
|
16
|
-
`))c.log(` ${e}`)}if(t.result){c.log(l.bold(`
|
|
14
|
+
`)}function formatExecutionError(e,t){if(t&&e.stackTrace){let n=formatErrorWithSourcemap(composeExecutionErrorString(e),t,process.cwd());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)]];c.out(Ut(t))}function printFunctionExecutionLogs(e){let t=f(e.logEntries,e.logs);if(t.length!==0){c.log(l.bold(`
|
|
15
|
+
Logs:`));for(let e of t)c.log(` ${e}`)}}function printFunctionExecutionOutcome(e){let{detail:t,bundledCode:n}=e;if(t.result){c.log(l.bold(`
|
|
17
16
|
Result:`));try{let e=JSON.parse(t.result);c.log(` ${JSON.stringify(e,null,2).split(`
|
|
18
17
|
`).join(`
|
|
19
18
|
`)}`)}catch{c.log(` ${t.result}`)}}t.error&&(c.log(l.bold(`
|
|
20
|
-
Error:`)),c.log(formatExecutionError(t.error,n??null)))}async function
|
|
21
|
-
|
|
22
|
-
Stack 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`}],args:q.strictObject({...P,...Zt,"execution-id":W(q.string().optional(),{positional:!0,description:`Execution ID (if provided, shows details with logs)`})}),run:async e=>{let{client:t,workspaceId:n}=await v({profile:e.profile,workspaceId:e[`workspace-id`]});if(e.executionId){let{execution:r}=await t.getFunctionExecution({workspaceId:n,executionId:e.executionId});if(!r)throw Error(`Function execution '${e.executionId}' not found.`);let i=toFunctionExecutionDetailInfo(r);e.json?c.out(i):printFunctionExecutionDetail({detail:i,bundledCode:i.error?await downloadScriptForMapping({client:t,workspaceId:n,scriptName:i.scriptName,executionType:r.type,executionContentHash:r.contentHash}):null})}else{let r=I(e.order),i=(await V(async(e,i)=>{let{executions:a,nextPageToken:o}=await t.listFunctionExecutions({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e.limit})).map(toFunctionExecutionListInfo);if(i.length===0&&!e.json){c.info(`No function execution logs found.`);return}c.out(i)}}});async function bundleForRun(e){let{detected:t,sourceFile:n,baseDir:r,env:i={},machineUser:a,workspaceId:o}=e,s=Vn(e.inlineSourcemap),c=En(e.logLevel),l=U.resolve(Wn(),`test-run`);Y.mkdirSync(l,{recursive:!0});let u=`test-run--${t.name}`,d=`${u}.js`,f=U.join(l,`${u}.entry.js`),p=generateEntry({detected:t,sourceFile:n,env:i,machineUser:a,workspaceId:o,defaultPermission:e.defaultPermission});Y.writeFileSync(f,p);let m=await On(r),h=Dn({tsconfig:m}),g=await jr.build({plugins:[Cn(f,r),Sn(),Bn],input:f,write:!1,output:{format:`esm`,sourcemap:!s||`inline`,minify:!s||{mangle:{keepNames:!0}},codeSplitting:!1,dir:process.cwd()},tsconfig:m,treeshake:bn([zn(c)]),...h.options});return h.assertAllResolved(),{bundledCode:g.output[0].code,scriptName:d}}function generateEntry(e){let{detected:t,sourceFile:n,env:r,machineUser:i,workspaceId:a,defaultPermission:s}=e,c=U.resolve(n);switch(t.type){case`plain`:return t.namedMain?H`
|
|
19
|
+
Error:`)),c.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 Error(`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`:xt(o);return Error(`Timed out waiting for function execution '${e.executionId}' to complete. Last status: ${t}.`)},sleep=async()=>{let e=remainingMs();if(e===void 0){await Ur(t);return}if(e<=0)throw timeoutError();await Ur(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(!Qe(e))throw e;c.warn(`Retrying function execution poll: ${tt(e)}`,{mode:`stream`}),await sleep();continue}if(r){if(o===void 0&&(printFunctionExecutionSummary(toFunctionExecutionListInfo(n)),dn(n.status)||c.info(`Following log entries until the execution completes (Ctrl+C to stop)`,{mode:`stream`})),n.logEntries.length>a){a===0&&c.log(l.bold(`
|
|
20
|
+
Logs:`));for(let e of n.logEntries.slice(a))c.log(` ${Ne(Kt(e))}`);a=n.logEntries.length}if(o!==void 0&&n.status!==o){let e=it(xt(n.status));c.info(`Status: ${e}`,{mode:`stream`})}}let i=o!==void 0;if(o=n.status,dn(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 c.debug(`Script "${r}" is not a deployed registry script (e.g. function run or seed); skipping sourcemap mapping.`),null;if(a===``)return c.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?(c.debug(`Could not download pinned script "${r}" (registry: "${o}", contentHash: "${a}") for stack trace mapping; showing raw stack trace.`),null):s.code}const bi=M({name:`logs`,description:`List or get function execution logs.`,notes:"Execution details include `logEntries`, the structured log lines (message, severity, timestamp) recorded while the function ran. They are available while the execution is still running, whereas the flat `logs` string is filled in only after completion. The human-readable view shows the structured entries when present and falls back to `logs` otherwise.\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. On environments where no structured entries are returned, `--follow` shows the flat `logs` string once the execution completes. 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({...N,...kt,"execution-id":U(q.string().optional(),{positional:!0,description:`Execution ID (if provided, shows details with logs)`}),follow:U(q.boolean().default(!1),{alias:`f`,description:`Keep polling a running execution and print new log entries as they arrive (detail mode only)`}),interval:U(Ct.default(`3s`),{alias:`i`,description:`Polling interval for --follow (e.g., '3s', '500ms', '1m')`}),timeout:U(Ct.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 Error(`--follow requires an execution ID.`);let{client:t,workspaceId:n}=await E({profile:e.profile,workspaceId:e[`workspace-id`]});if(e.executionId){let r=c.jsonMode||e.json,i={client:t,workspaceId:n,executionId:e.executionId},{execution:a,printedEntries:o,followed:s}=e.follow?await followFunctionExecution({...i,interval:at(e.interval),timeout:e.timeout===void 0?void 0:at(e.timeout),showProgress:!r}):{execution:await fetchFunctionExecution(i),printedEntries:0,followed:!1},l=toFunctionExecutionDetailInfo(a);if(r){c.out(l);return}(!e.follow||s)&&printFunctionExecutionSummary(l),o===0&&printFunctionExecutionLogs(l),printFunctionExecutionOutcome({detail:l,bundledCode:l.error?await downloadScriptForMapping({client:t,workspaceId:n,scriptName:l.scriptName,executionType:a.type,executionContentHash:a.contentHash}):null})}else{let r=z(e.order),i=(await V(async(e,i)=>{let{executions:a,nextPageToken:o}=await t.listFunctionExecutions({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e.limit})).map(toFunctionExecutionListInfo);if(i.length===0&&!e.json){c.info(`No function execution logs found.`);return}c.out(i)}}});async function bundleForRun(e){let{detected:t,sourceFile:n,baseDir:r,env:i={},machineUser:a,workspaceId:o}=e,s=Xn(e.inlineSourcemap),c=Fn(e.logLevel),l=K.resolve($n(),`test-run`);Y.mkdirSync(l,{recursive:!0});let u=`test-run--${t.name}`,d=`${u}.js`,f=K.join(l,`${u}.entry.js`),p=generateEntry({detected:t,sourceFile:n,env:i,machineUser:a,workspaceId:o,defaultPermission:e.defaultPermission});Y.writeFileSync(f,p);let m=await Ln(r),h=In({tsconfig:m}),g=await Br.build({plugins:[Mn(f,r),jn(),Yn],input:f,write:!1,output:{format:`esm`,sourcemap:!s||`inline`,minify:!s||{mangle:{keepNames:!0}},codeSplitting:!1,dir:process.cwd()},tsconfig:m,treeshake:kn([Jn(c)]),...h.options});return h.assertAllResolved(),{bundledCode:g.output[0].code,scriptName:d}}function generateEntry(e){let{detected:t,sourceFile:n,env:r,machineUser:i,workspaceId:a,defaultPermission:s}=e,c=K.resolve(n);switch(t.type){case`plain`:return t.namedMain?H`
|
|
23
21
|
export { main } from "${c}";
|
|
24
22
|
`:H`
|
|
25
23
|
import _fn from "${c}";
|
|
26
24
|
export { _fn as main };
|
|
27
|
-
`;case`resolver`:{let e=buildMachinePrincipalExpr(i,a),n=
|
|
25
|
+
`;case`resolver`:{let e=buildMachinePrincipalExpr(i,a),n=er({permission:t.permission,defaultPermission:s});return H`
|
|
28
26
|
import _internalResolver from "${c}";
|
|
29
27
|
import { t } from "@tailor-platform/sdk";
|
|
30
28
|
import { serializeDateFields } from "@tailor-platform/sdk/runtime";
|
|
31
29
|
|
|
32
30
|
const $tailor_resolver_body = async (rawInput) => {
|
|
33
31
|
const _caller = ${e};
|
|
34
|
-
const invoker = (${
|
|
32
|
+
const invoker = (${qn}) ?? _caller;
|
|
35
33
|
const context = { input: rawInput, env: ${JSON.stringify(r)}, caller: _caller, invoker };
|
|
36
34
|
const input = ${n};
|
|
37
35
|
const result = await _internalResolver.body({ ...context, input });
|
|
@@ -46,7 +44,7 @@ Stack traces are mapped only when the execution includes a content hash for the
|
|
|
46
44
|
const _actor = ${e};
|
|
47
45
|
|
|
48
46
|
const __executor_function = async (args) => {
|
|
49
|
-
const _invoker = ${
|
|
47
|
+
const _invoker = ${qn} ?? _actor;
|
|
50
48
|
return _internalExecutor.operation.body({ ...args, env: _env, actor: _actor, invoker: _invoker });
|
|
51
49
|
};
|
|
52
50
|
|
|
@@ -58,52 +56,52 @@ Stack traces are mapped only when the execution includes a content hash for the
|
|
|
58
56
|
const fallbackInvoker = ${n};
|
|
59
57
|
|
|
60
58
|
export async function main(input) {
|
|
61
|
-
const invoker = ${
|
|
59
|
+
const invoker = ${qn} ?? fallbackInvoker;
|
|
62
60
|
return await ${e}.body(input, { env, invoker });
|
|
63
61
|
}
|
|
64
|
-
`}}}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(Pr(n).href),a=Zn.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}}let o=rr.safeParse(ir(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 Error(`Could not detect function type from ${n}.\nThe file must have one of:
|
|
65
63
|
- A default-exported resolver (createResolver)
|
|
66
64
|
- A default-exported executor (createExecutor) with function/jobFunction operation
|
|
67
65
|
- A named-exported workflow job (createWorkflowJob)
|
|
68
66
|
- A default-exported function
|
|
69
|
-
- 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=Wn.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(`
|
|
70
68
|
`);throw Error(`Workflow job "${t}" not found. Available jobs:\n${e}`)}return{type:`workflow-job`,name:e.name,exportName:e.exportName}}if(n.length===1){let[e]=n,t=o(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(`
|
|
71
|
-
`);throw Error(`Multiple workflow jobs found. Specify one with --name:\n${r}`)}function deriveNameFromPath(e){return
|
|
72
|
-
`);function generateScriptDbTypes(e){let t=Object.values(e.tables).map(e=>
|
|
73
|
-
`)}function loadScriptSchemaSnapshot(e){let t=
|
|
74
|
-
Logs:`));for(let e of
|
|
75
|
-
`))c.log(` ${e}`)}if(
|
|
76
|
-
Result:`));try{let e=JSON.parse(
|
|
69
|
+
`);throw Error(`Multiple workflow jobs found. Specify one with --name:\n${r}`)}function deriveNameFromPath(e){return K.basename(e,K.extname(e))}const xi=`db.ts`,Si=`db.snapshot.json`,Ci=[`/**`,` * 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){let t=Object.values(e.tables).map(e=>yr(e.name,e.fields)),n=br([{namespace:e.namespace,types:t}]);return`${Ci}\n\n${n}`}function isGeneratedScriptDbTypes(e){return e.includes("Generated by `tailor function script`")}function assertGeneratedTypeScript(e,t){let{errors:n}=Vr(K.basename(e),t);if(n.length>0)throw Error(`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),Si);if(!Y.existsSync(t))return null;let n;try{n=JSON.parse(Y.readFileSync(t,`utf-8`))}catch(e){throw Error(`Failed to parse schema snapshot ${t}: ${e instanceof Error?e.message:e}. 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:y(a)}}catch{throw unexpectedSnapshotShapeError(t)}}function unexpectedSnapshotShapeError(e){return Error(`Schema snapshot ${e} has an unexpected shape. 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(yn(r).includes(s)){let{namespaces:t}=await Le({configPath:i,namespaces:[s]}),n=t[0];if(n){let t=Object.fromEntries(Object.values(n.tables).map(e=>[e.name,Xe(e)])),r=xn(generatedContractSnapshot(o),generatedContractSnapshot({...o,tables:t}));if(ke(r))throw schemaDriftError(`the local table definitions`,r,e)}}let c=await Oe(t,n,s),l=xn(a.source===`local`?generatedContractSnapshot(o):y(pickTableFields(o)),a.source===`local`?generatedContractSnapshot(c):y(pickTableFields(c)));if(ke(l))throw schemaDriftError(`the deployed schema`,l,e)}function fieldsOnlySnapshot(e){return y(pickTableFields(Qt(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 y({...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=lr([`tailor`,`function`,`script`,n.scriptArgValue,...n.sidecar.source===`remote`?[`--remote`]:[],...r]),a=lr([`tailor`,`function`,`run`,n.scriptArgValue,`--allow-schema-drift`,...r]);return Error(`Schema drift detected: ${Si} next to the script no longer matches ${e}.\n\n${S(t)}\n\nRefresh the generated types with ${i}, or run anyway with ${a}.`)}const wi=M({name:`run`,aliases:[`test-run`],description:`Run a function on the Tailor Platform server without deploying.`,args:q.object({...N,file:U(q.string(),{positional:!0,description:`Path to the function file`}),name:U(q.string().optional(),{alias:`n`,description:"Workflow job name to run (matches the `name` field of createWorkflowJob)"}),arg:U(q.string().optional(),{alias:`a`,description:`JSON argument to pass to the function`}),"machine-user":U(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:U(q.string().default(`tailor.config.ts`),{alias:`c`,description:`Path to SDK config file`}),"allow-schema-drift":U(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)&&c.warn("`tailor function test-run` is deprecated and will be removed in v3. Use `tailor function run` instead.");let t=c.jsonMode,n=K.resolve(e.file);if(!Y.existsSync(n))throw Error(`File not found: ${n}`);let{config:r}=await B(e.config),a=resolveAuthNamespace(r.auth),o=await resolveMachineUserName({cliMachineUser:e[`machine-user`],cliMachineUserSource:gn(e[`machine-user`]),profile:e.profile,authConfig:r.auth}),{client:s,workspaceId:u}=await E({profile:e.profile,workspaceId:e[`workspace-id`]}),d=await resolveMachineUser({client:s,workspaceId:u,authNamespace:a,machineUserName:o,authConfig:r.auth}),f=K.relative(process.cwd(),n),p=n.endsWith(`.js`);if(!p){if(e[`allow-schema-drift`])Y.existsSync(K.join(K.dirname(n),`db.snapshot.json`))&&c.warn(`Skipping the schema snapshot check (--allow-schema-drift).`);else{let t=loadScriptSchemaSnapshot(n);t&&(c.info(`Checking the script's schema snapshot for drift...`),await verifyScriptSchemaSnapshot({client:s,workspaceId:u,config:r,configArgValue:e.config,scriptArgValue:e.file,profileArgValue:e.profile,sidecar:t}))}}let m,h,g,_;if(p)h=K.basename(n),m=Y.readFileSync(n,`utf-8`),c.info(`Using pre-bundled script ${l.bold(h)}`);else{c.info(`Detecting function type from ${l.path(f)}`);let t=await detectFunctionType({filePath:n,jobName:e.name});g=t.type,_=t.name,c.info(`Detected: ${l.bold(t.type)} ${l.info(`"${t.name}"`)}`),t.type===`resolver`&&e.arg&&!t.hasInput&&(c.warn(`--arg is ignored because this resolver has no input schema. Define "input" in your resolver to use --arg.`),e.arg=void 0),c.info(`Bundling...`);let i=K.dirname(r.path);({bundledCode:m,scriptName:h}=await bundleForRun({detected:t,sourceFile:n,baseDir:i,defaultPermission:t.type===`resolver`?Kn({config:r.resolver,filePath:n,baseDir:i}):void 0,env:r.env??{},inlineSourcemap:r.inlineSourcemap,logLevel:r.logLevel,machineUser:d,workspaceId:u})),c.info(`Bundled as ${l.bold(h)}`)}let v=Ar(i,{namespace:a,machineUserName:d.name});c.info(`Executing on workspace ${l.dim(u)}...`);let y;if(e.arg!==void 0)try{y=JSON.parse(e.arg)}catch(e){throw Error(`Invalid --arg JSON: ${e instanceof Error?e.message:e}`,{cause:e})}let b=await Be({client:s,workspaceId:u,name:h,code:m,arg:y,invoker:v});if(t)c.out({success:b.success,scriptName:h,functionType:g,functionName:_,logs:b.logs,result:b.result,error:b.error});else{if(b.success?c.success(`Execution succeeded`):c.error(`Execution failed`),b.logs.trim()){c.log(l.bold(`
|
|
72
|
+
Logs:`));for(let e of b.logs.split(`
|
|
73
|
+
`))c.log(` ${e}`)}if(b.result&&b.success){c.log(l.bold(`
|
|
74
|
+
Result:`));try{let e=JSON.parse(b.result);c.log(` ${JSON.stringify(e,null,2).split(`
|
|
77
75
|
`).join(`
|
|
78
|
-
`)}`)}catch{c.log(` ${
|
|
79
|
-
Error:`));let e=formatErrorWithSourcemap(
|
|
80
|
-
`),g.push(a),_=`./db`}else{if(r)throw Error(`Script already exists: ${
|
|
76
|
+
`)}`)}catch{c.log(` ${b.result}`)}}if(b.error&&!b.success){c.log(l.bold(`
|
|
77
|
+
Error:`));let e=formatErrorWithSourcemap(b.error,m,process.cwd());e?c.log(e):c.log(` ${l.error(b.error)}`)}}b.success||process.exit(1)}}),Ti=new Set(Sr(q.strictObject(an)).fields.filter(e=>e.type!==`boolean`).flatMap(e=>[e.cliName,...e.alias??[]].flatMap(toFlagTokens)));function toFlagTokens(e){return e.length===1?[`-${e}`]:[`--${e}`,`--${wr(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;if(!r.startsWith(`-`)){t.push(r);continue}!r.includes(`=`)&&Ti.has(r)&&n++}return t[0]===`function`&&t[1]===`test-run`}function resolveAuthNamespace(e){if(e?.name)return e.name;throw Error(`Auth namespace is required. Ensure tailor.config.ts has an auth config.`)}async function resolveMachineUserName(e){let{cliMachineUser:t,cliMachineUserSource:n,profile:r,authConfig:i}=e,a=await de({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 o(t[0],`machine user key missing`)}}throw Error(`Machine user is required. 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{c.debug(`Could not fetch machine user "${i}" from server, using nil UUID`)}let s=a?.machineUsers?.[i],l=null,u=[];if(s&&typeof s==`object`){let e=s;l=e.attributes??null,u=e.attributeList??[]}return{name:i,id:o,attributes:l,attributeList:u}}const Ei=M({name:`script`,description:"Scaffold a one-off script to run with `function run`.",args:q.object({...N,...mt,file:U(q.string(),{positional:!0,description:`Path to create the script at (must end with .ts)`}),namespace:U(q.string().optional(),{description:`Target TailorDB namespace (required when the config does not pin one)`}),remote:U(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 Error(`Script path must end with .ts: ${e.file}`);let n=K.dirname(t),r=Y.existsSync(t),i=K.join(n,xi),a=K.join(n,Si);if(t===i)throw Error(`${xi} is reserved for the generated Kysely types written next to the script. Choose a different script file name.`);let{config:s,plugins:u}=await B(e.config),d=u.find(e=>e.id===xr),f=Y.existsSync(a);if(e.remote&&d!==void 0&&r&&!f)throw Error(`Script already exists: ${K.relative(process.cwd(),t)}. Scaffold --remote at a new path so the generated script imports its script-scoped db.ts.`);let p=e.remote||d===void 0||f,m;if(p)try{m=loadScriptSchemaSnapshot(t)?.snapshot.namespace}catch{}let h=resolveNamespace({config:s,explicit:e.namespace,sidecarNamespace:m,remote:e.remote});if(m!==void 0&&m!==h)throw Error(`This directory's generated types target namespace "${m}" (${Si}). Scaffold scripts for namespace "${h}" in a separate directory.`);let g=[],_,v;if(p){let t;if(e.remote){let{client:n,workspaceId:r}=await E({profile:e.profile,workspaceId:e[`workspace-id`]});v=r,c.info(`Fetching deployed schema of namespace ${l.bold(h)}...`),t=await Oe(n,r,h)}else{c.info(`Loading local definitions of namespace ${l.bold(h)}...`);let{namespaces:n}=await Le({configPath:e.config,namespaces:[h]}),r=o(n[0],`namespace ${h}`);t=$e(r.tables,h)}if(Object.keys(t.tables).length===0){let t=e.remote?`deployed tables in workspace ${o(v,`workspace ID`)}`:`locally defined tables`;throw Error(`Namespace "${h}" has no ${t}.`)}if(Y.existsSync(i)&&!isGeneratedScriptDbTypes(Y.readFileSync(i,`utf-8`)))throw Error(`Refusing to overwrite ${K.relative(process.cwd(),i)}: it was not generated by \`tailor function script\`.`);let r=generateScriptDbTypes(t);assertGeneratedTypeScript(i,r),Y.mkdirSync(n,{recursive:!0}),Y.writeFileSync(i,r),g.push(i),Y.writeFileSync(a,JSON.stringify({...t,source:e.remote?`remote`:`local`},null,2)+`
|
|
78
|
+
`),g.push(a),_=`./db`}else{if(r)throw Error(`Script already exists: ${K.relative(process.cwd(),t)}. It imports the project's generated Kysely types, so there is nothing to refresh.`);let e=resolveKyselyTypesPath(u);_=toImportSpecifier(K.relative(n,e)),Y.existsSync(e)||c.warn(`Generated Kysely types not found at ${l.path(K.relative(process.cwd(),e))}. Run \`tailor generate\` before executing the script.`)}if(!r){let e=generateScriptSkeleton({getDBImportPath:_,namespace:h});assertGeneratedTypeScript(t,e),Y.mkdirSync(n,{recursive:!0}),Y.writeFileSync(t,e),g.unshift(t)}let y=[`tailor`,`function`,`run`,K.relative(process.cwd(),t)];e.config!==`tailor.config.ts`&&y.push(`--config=${e.config}`);let b=v??e[`workspace-id`];if(b!==void 0&&y.push(`--workspace-id=${b}`),e.profile!==void 0&&y.push(`--profile=${e.profile}`),c.jsonMode){c.out({script:t,created:g,namespace:h,usesGeneratedDbTypes:p});return}r&&c.info(`Script already exists; refreshed generated types only.`);for(let e of g)c.success(`Created ${l.path(K.relative(process.cwd(),e))}`);c.info(`Next: edit the script, then run ${lr(y)}`)}});function resolveNamespace(e){let{config:t,explicit:n,sidecarNamespace:r,remote:i}=e,a=b(t),o=yn(t),s=i?a:o;if(n){if(!i&&!o.includes(n))throw Error(`Namespace "${n}" is not owned by the config and requires --remote.`);return n}if(r!==void 0){if(!i&&!o.includes(r))throw Error(`Namespace "${r}" is not owned by the config and requires --remote.`);return r}if(s.length===1){let e=s[0];if(e!==void 0)return e}throw s.length>1?Error(`Multiple TailorDB namespaces are defined (${s.join(`, `)}). Specify one with --namespace.`):!i&&a.length>0?Error(`No owned TailorDB namespace is defined in the config. External namespaces require --remote: ${a.join(`, `)}.`):Error(`No TailorDB namespace is defined in the config.`)}function resolveKyselyTypesPath(e){let t=ft(e,`@tailor-platform/kysely-type`)?.distPath??`./generated/tailordb.ts`;if(t.length===0)throw Error(`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 Di=W({name:`function`,description:`Manage functions`,subCommands:{get:Rt,list:C,logs:bi,run:wi,script:Ei},async run(){await G(C,[])}}),Oi=M({name:`generate`,description:`Generate files using Tailor configuration.`,args:q.strictObject({config:U(q.string().default(`tailor.config.ts`),{alias:`c`,description:`Path to SDK config file`})}),run:async e=>{let{initTelemetry:t}=await import(`../telemetry-DXHP3VVi.mjs`);await t(),await wn({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},ki=M({name:`init`,description:`Initialize a new project using create-sdk.`,args:q.strictObject({name:U(q.string().optional(),{positional:!0,description:`Project name`}),template:U(q.string().optional(),{alias:`t`,description:`Template name`})}),run:async e=>{let t=await ar(),n=t.version&&t.version!==`0.0.0`?t.version:`latest`,r=detectPackageManager();r||=(c.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]:[]];c.log(`Running: ${r} ${i.join(` `)}`),Jr(r,i,{stdio:`inherit`})}}),Ai=8085,ji=`http://localhost:${Ai}/callback`;function randomState(){return Ir.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(`
|
|
81
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 Error(H`
|
|
82
80
|
Profile "${e.profile}" is configured for "${e.oldUser}", but login authenticated "${e.authenticatedUser}".
|
|
83
81
|
The authenticated user has been saved. To use it with this profile, run:
|
|
84
82
|
${t}
|
|
85
83
|
${n}
|
|
86
|
-
`)}function shouldUpdateCurrentUser(e,t){return!e||In(t)}const startAuthServer=async(e={})=>{let t=kn(e.platformConfig),n=randomState(),r=await Er(),i=await t.authorizationCode.getAuthorizeUri({redirectUri:xi,state:n,codeVerifier:r}).catch(e=>{throw Error(`Failed to prepare the login authorization URL: ${Qn(e).message}`,{cause:e})});return new Promise((a,s)=>{let handleCallback=async(i,c)=>{try{if(!i.url?.startsWith(`/callback`))throw Error(`Invalid callback URL`);let s=await t.authorizationCode.getTokenFromCodeRedirect(`http://${i.headers.host}${i.url}`,{redirectUri:xi,state:n,codeVerifier:r}),l=await Un(s.accessToken,e.platformConfig),u=await h();await He(u,l.sub,{accessToken:s.accessToken,refreshToken:s.refreshToken??void 0},new Date(o(s.expiresAt,`token response missing expiresAt`)).toISOString(),{platformConfig:e.platformConfig,email:l.email});let d=getProfileUserMismatch(e,l.email,l.sub);if(d)throw E(u),profileUserMismatchError(d);(e.updateCurrentUser??!0)&&(u.current_user=l.sub),await Be(u,l.email,l.sub,e.platformConfig),E(u),c.writeHead(200,{"Content-Type":`application/json`}),c.end(JSON.stringify({status:`ok`,message:`Successfully authenticated. Please close this window.`})),a()}catch(e){c.writeHead(401),c.end(`Authentication failed`),s(Qn(e))}finally{l.close()}},l=kr.createServer((e,t)=>void handleCallback(e,t)),u=setTimeout(()=>{l.close(),s(Error(`Login timeout exceeded`))},3e5);l.on(`close`,()=>{clearTimeout(u)}),l.on(`error`,e=>{s(e)});let openBrowser=async()=>{c.info(`Opening browser for login:\n\n${i}\n`);try{await Ar(i)}catch{c.warn(`Failed to open browser automatically. Please open the URL above manually.`)}};l.listen(bi,()=>void openBrowser())})};async function loginAsMachineUser(e){let t=e.clientSecret??await A.password({message:`Client secret`}),n=await Tn(e.clientId,t,e.platformConfig),r=await h();await He(r,e.clientId,{accessToken:n.accessToken},new Date(o(n.expiresAt,`token response missing expiresAt`)).toISOString(),{platformConfig:e.platformConfig});let i=getProfileUserMismatch(e,e.clientId);if(i)throw E(r),profileUserMismatchError(i);(e.updateCurrentUser??!0)&&(r.current_user=e.clientId),E(r)}const Si=D({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 h()).profiles[e.profile];if(!r)throw Error(`Profile "${e.profile}" not found`);t=B(r),n=r.user}let r=shouldUpdateCurrentUser(e.profile,t);`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.`)}finally{await xn()}}}),Ci=D({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 h(),r=t?n.profiles[t]:void 0;if(t&&!r)throw Error(`Profile "${t}" not found`);let i=r?B(r):void 0,a=r?r.user:n.current_user,o=In(i),s=t?{allowLegacyUserKey:!0}:void 0;if(!a){c.info(`You are not logged in.`);return}let hasDefaultUserToken=()=>p(n,a,{platformUrl:jn}),shouldClearCurrentUser=()=>n.current_user===a&&(o||!Ot(n,a))&&!hasDefaultUserToken(),l,u=!1;try{l=await ge(n,a,i,s)}catch(e){u=!0,c.warn(`Failed to revoke token: ${e instanceof Error?e.message:e}`)}if(!l&&!u){c.info(`You are not logged in.`),shouldClearCurrentUser()&&(n.current_user=null),E(n);return}if(l)try{let e=kn(i),t=l.refreshToken?`refresh_token`:`access_token`;await e.revoke({accessToken:l.accessToken,refreshToken:l.refreshToken??null,expiresAt:Date.parse(l.userEntry.token_expires_at)},t)}catch(e){c.warn(`Failed to revoke token: ${e instanceof Error?e.message:e}`)}await x(n,a,i,s),shouldClearCurrentUser()&&(n.current_user=null),E(n),c.success(`Successfully logged out from Tailor Platform.`)}}),wi=G({name:`machineuser`,description:`Manage machine users in your Tailor Platform application.`,subCommands:{list:Qe,token:yt},async run(){await K(Qe,[])}}),Ti=G({name:`oauth2client`,description:`Manage OAuth2 clients in your Tailor Platform application.`,subCommands:{list:lt,get:Vt},async run(){await K(lt,[])}}),Ei=D({name:`open`,description:`Open Tailor Platform Console.`,args:q.strictObject({...O}),run:async e=>{let t=await Ne({workspaceId:e[`workspace-id`],profile:e.profile}),{config:n}=await w(e.config),r=n.name,i=s(process.env.TAILOR_CONSOLE_NEXT)===!0?`/workspaces/${t}/services/applications/${encodeURIComponent(r)}`:`/workspaces/${t}/applications/${encodeURIComponent(r)}/overview`,a=await Ae({profile:e.profile,...e[`workspace-id`]===void 0?{}:{allowMissingProfile:!0}}),o=new URL(i,a).toString(),l=c.jsonMode;c.info(`Opening Tailor Platform Console...`);let u=!0;try{await Ar(o)}catch{u=!1}if(l){c.out({consoleUrl:o,workspaceId:t,applicationName:r,opened:u});return}u?(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}`)}}),Di=G({name:`folder`,description:`Manage organization folders.`,subCommands:{create:Mt,delete:Yt,get:nt,list:Kt,update:en}}),Oi=G({name:`organization`,description:`Manage Tailor Platform organizations.`,subCommands:{folder:Di,get:u,list:Ye,tree:We,update:Ht},async run(){await K(Ye,[])}}),ki=`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(`.`),Ai={seed:`@tailor-platform/sdk-plugin-seed`,setup:`@tailor-platform/sdk-plugin-setup`,"tailordb-erd":`@tailor-platform/sdk-plugin-tailordb-erd`},ji=process.platform===`win32`?`;`:`:`;function*ancestorDirs(e){let t=U.resolve(e),n=U.dirname(t);for(;n!==t;)yield t,t=n,n=U.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{Sr(e,process.platform===`win32`?Cr.F_OK:Cr.X_OK)}catch{return!1}if(process.platform===`win32`){let t=U.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(ji).filter(Boolean)}function nodeModulesBinDirs(){let e=[];for(let t of ancestorDirs(process.cwd()))e.push(U.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=U.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=U.extname(e);return t?e.slice(0,-t.length):e}function listPlugins(e){let t=`${e}-`,n=new Map,scan=(e,r)=>{for(let i of e){let e;try{e=wr(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=U.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 h(),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 Xn();e&&(n.TAILOR_VERSION=e)}catch{}let i=Ce();if(i&&(n.TAILOR_CONFIG_PATH=i),e.skipPlatformContext)return n;let a;try{a=await ce({profile:t,allowMissingProfile:!0})}catch{}n.TAILOR_PLATFORM_URL=Pn(a),n.TAILOR_PLATFORM_OAUTH2_CLIENT_ID=Nn(a);try{n.TAILOR_PLATFORM_WORKSPACE_ID=await Ne({profile:t})}catch{}try{let e=await resolveActiveUser(t);e&&(n.TAILOR_PLATFORM_USER=e)}catch{}try{let e=await Et({profile:t});e&&(n.TAILOR_PLATFORM_TOKEN=e)}catch{}return n}function signalToExitCode(e){let t=Nr.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=U.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=Lr(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=Ai[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 Mi=D({name:`list`,description:"List discovered plugins (executables named `<cli>-<name>` on PATH or node_modules/.bin).",args:q.strictObject({}),run:async()=>{let e=await Xn(),t=Object.keys(e.bin??{})[0]||`tailor`,n=new Set(ki),r=listPlugins(t);if(r.length===0){c.info(H`
|
|
84
|
+
`)}function shouldUpdateCurrentUser(e,t){return!e||Gn(t)}const startAuthServer=async(e={})=>{let t=Rn(e.platformConfig),n=randomState(),r=await Fr(),i=await t.authorizationCode.getAuthorizeUri({redirectUri:ji,state:n,codeVerifier:r}).catch(e=>{throw Error(`Failed to prepare the login authorization URL: ${sr(e).message}`,{cause:e})});return new Promise((a,s)=>{let handleCallback=async(i,c)=>{try{if(!i.url?.startsWith(`/callback`))throw Error(`Invalid callback URL`);let s=await t.authorizationCode.getTokenFromCodeRedirect(`http://${i.headers.host}${i.url}`,{redirectUri:ji,state:n,codeVerifier:r}),l=await Qn(s.accessToken,e.platformConfig),u=await d();await tn(u,l.sub,{accessToken:s.accessToken,refreshToken:s.refreshToken??void 0},new Date(o(s.expiresAt,`token response missing expiresAt`)).toISOString(),{platformConfig:e.platformConfig,email:l.email});let f=getProfileUserMismatch(e,l.email,l.sub);if(f)throw I(u),profileUserMismatchError(f);(e.updateCurrentUser??!0)&&(u.current_user=l.sub),await bt(u,l.email,l.sub,e.platformConfig),I(u),c.writeHead(200,{"Content-Type":`application/json`}),c.end(JSON.stringify({status:`ok`,message:`Successfully authenticated. Please close this window.`})),a()}catch(e){c.writeHead(401),c.end(`Authentication failed`),s(sr(e))}finally{l.close()}},l=Rr.createServer((e,t)=>void handleCallback(e,t)),u=setTimeout(()=>{l.close(),s(Error(`Login timeout exceeded`))},3e5);l.on(`close`,()=>{clearTimeout(u)}),l.on(`error`,e=>{s(e)});let openBrowser=async()=>{c.info(`Opening browser for login:\n\n${i}\n`);try{await zr(i)}catch{c.warn(`Failed to open browser automatically. Please open the URL above manually.`)}};l.listen(Ai,()=>void openBrowser())})};async function loginAsMachineUser(e){let t=e.clientSecret??await T.password({message:`Client secret`}),n=await Pn(e.clientId,t,e.platformConfig),r=await d();await tn(r,e.clientId,{accessToken:n.accessToken},new Date(o(n.expiresAt,`token response missing expiresAt`)).toISOString(),{platformConfig:e.platformConfig});let i=getProfileUserMismatch(e,e.clientId);if(i)throw I(r),profileUserMismatchError(i);(e.updateCurrentUser??!0)&&(r.current_user=e.clientId),I(r)}const Mi=M({name:`login`,description:`Login to Tailor Platform.`,args:q.xor([q.strictObject({profile:U(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":U(q.literal(!0),{description:`Login as a platform machine user.`,required:!0}),"client-id":U(q.string(),{description:`Client ID`,env:`TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID`,required:!0}),"client-secret":U(q.string().optional(),{description:`Client secret`,env:`TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET`}),profile:U(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 d()).profiles[e.profile];if(!r)throw Error(`Profile "${e.profile}" not found`);t=O(r),n=r.user}let r=shouldUpdateCurrentUser(e.profile,t);`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.`)}finally{await An()}}}),Ni=M({name:`logout`,description:`Logout from Tailor Platform.`,args:q.strictObject({profile:U(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 d(),r=t?n.profiles[t]:void 0;if(t&&!r)throw Error(`Profile "${t}" not found`);let i=r?O(r):void 0,a=r?r.user:n.current_user,o=Gn(i),s=t?{allowLegacyUserKey:!0}:void 0;if(!a){c.info(`You are not logged in.`);return}let hasDefaultUserToken=()=>Ve(n,a,{platformUrl:Bn}),shouldClearCurrentUser=()=>n.current_user===a&&(o||!oe(n,a))&&!hasDefaultUserToken(),l,u=!1;try{l=await Ze(n,a,i,s)}catch(e){u=!0,c.warn(`Failed to revoke token: ${e instanceof Error?e.message:e}`)}if(!l&&!u){c.info(`You are not logged in.`),shouldClearCurrentUser()&&(n.current_user=null),I(n);return}if(l)try{let e=Rn(i),t=l.refreshToken?`refresh_token`:`access_token`;await e.revoke({accessToken:l.accessToken,refreshToken:l.refreshToken??null,expiresAt:Date.parse(l.userEntry.token_expires_at)},t)}catch(e){c.warn(`Failed to revoke token: ${e instanceof Error?e.message:e}`)}await _(n,a,i,s),shouldClearCurrentUser()&&(n.current_user=null),I(n),c.success(`Successfully logged out from Tailor Platform.`)}}),Pi=W({name:`machineuser`,description:`Manage machine users in your Tailor Platform application.`,subCommands:{list:st,token:Ot},async run(){await G(st,[])}}),Fi=W({name:`oauth2client`,description:`Manage OAuth2 clients in your Tailor Platform application.`,subCommands:{list:yt,get:Xt},async run(){await G(yt,[])}}),Ii=M({name:`open`,description:`Open Tailor Platform Console.`,args:q.strictObject({...P}),run:async e=>{let t=await rt({workspaceId:e[`workspace-id`],profile:e.profile}),{config:n}=await B(e.config),r=n.name,i=s(process.env.TAILOR_CONSOLE_NEXT)===!0?`/workspaces/${t}/services/applications/${encodeURIComponent(r)}`:`/workspaces/${t}/applications/${encodeURIComponent(r)}/overview`,a=await $t({profile:e.profile,...e[`workspace-id`]===void 0?{}:{allowMissingProfile:!0}}),o=new URL(i,a).toString(),l=c.jsonMode;c.info(`Opening Tailor Platform Console...`);let u=!0;try{await zr(o)}catch{u=!1}if(l){c.out({consoleUrl:o,workspaceId:t,applicationName:r,opened:u});return}u?(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}`)}}),Li=W({name:`folder`,description:`Manage organization folders.`,subCommands:{create:Bt,delete:cn,get:ut,list:rn,update:fn}}),Ri=W({name:`organization`,description:`Manage Tailor Platform organizations.`,subCommands:{folder:Li,get:u,list:nt,tree:Ye,update:Zt},async run(){await G(nt,[])}}),zi=`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(`.`),Bi={seed:`@tailor-platform/sdk-plugin-seed`,setup:`@tailor-platform/sdk-plugin-setup`,"tailordb-erd":`@tailor-platform/sdk-plugin-tailordb-erd`},Vi=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{jr(e,process.platform===`win32`?Mr.F_OK:Mr.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(Vi).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=new Map,scan=(e,r)=>{for(let i of e){let e;try{e=Nr(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 d(),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 ar();e&&(n.TAILOR_VERSION=e)}catch{}let i=me();if(i&&(n.TAILOR_CONFIG_PATH=i),e.skipPlatformContext)return n;let a;try{a=await et({profile:t,allowMissingProfile:!0})}catch{}n.TAILOR_PLATFORM_URL=Un(a),n.TAILOR_PLATFORM_OAUTH2_CLIENT_ID=Hn(a);try{n.TAILOR_PLATFORM_WORKSPACE_ID=await rt({profile:t})}catch{}try{let e=await resolveActiveUser(t);e&&(n.TAILOR_PLATFORM_USER=e)}catch{}try{let e=await qe({profile:t});e&&(n.TAILOR_PLATFORM_TOKEN=e)}catch{}return n}function signalToExitCode(e){let t=Hr.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=qr(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=Bi[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 Hi=M({name:`list`,description:"List discovered plugins (executables named `<cli>-<name>` on PATH or node_modules/.bin).",args:q.strictObject({}),run:async()=>{let e=await ar(),t=Object.keys(e.bin??{})[0]||`tailor`,n=new Set(zi),r=listPlugins(t);if(r.length===0){c.info(H`
|
|
87
85
|
No plugins found.
|
|
88
86
|
Install an executable named "${t}-<name>" on your PATH or in node_modules/.bin,
|
|
89
87
|
then run it with "${t} <name>".
|
|
90
|
-
`),c.jsonMode&&c.out([]);return}let i=r.map(e=>({name:e.name,source:e.source,path:e.path,shadowed:n.has(e.name)}));c.out(i);for(let e of i)e.shadowed&&c.warn(`Plugin "${t}-${e.name}" is shadowed by the builtin "${t} ${e.name}" command and will not be dispatched.`)}}),
|
|
88
|
+
`),c.jsonMode&&c.out([]);return}let i=r.map(e=>({name:e.name,source:e.source,path:e.path,shadowed:n.has(e.name)}));c.out(i);for(let e of i)e.shadowed&&c.warn(`Plugin "${t}-${e.name}" is shadowed by the builtin "${t} ${e.name}" command and will not be dispatched.`)}}),Ui=W({name:`plugin`,description:`Manage and inspect CLI plugins (beta).`,subCommands:{list:Hi},async run(){await G(Hi,[])}}),Wi=M({name:`create`,description:`Create a new profile.`,args:q.strictObject({name:U(q.string(),{positional:!0,description:`Profile name`}),user:U(q.string(),{alias:`u`,description:`User email address or machine user client ID`}),"workspace-id":U(q.string(),{alias:`w`,description:`Workspace ID`}),permission:U(q.enum([`write`,`read`]).default(`write`),{description:`Profile permission. 'read' blocks all write commands while the profile is active.`}),"machine-user":U(q.string().optional(),{alias:`m`,description:`Default machine user name for application-data commands (query, workflow start, function run, machineuser token).`}),"machine-user-override":U(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":U(q.url().optional(),{description:`Platform API base URL for this profile.`,env:`TAILOR_PLATFORM_URL`}),"oauth2-client-id":U(q.string().optional(),{description:`OAuth2 client ID for logging in to this profile's platform.`,env:`TAILOR_PLATFORM_OAUTH2_CLIENT_ID`}),"console-url":U(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 Error(`--machine-user-override deny requires --machine-user.`);let t=await d();if(t.profiles[e.name])throw Error(`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 We(t,e.user,r),o=await On(i,r);if(!(await Nn(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 Error(`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`]}:{}},I(t),e.json||c.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`]}:{}};c.out(s)}}),Gi=M({name:`delete`,description:`Delete a profile.`,args:q.strictObject({name:U(q.string(),{positional:!0,description:`Profile name`})}),run:async e=>{let t=await d();if(!t.profiles[e.name])throw Error(`Profile "${e.name}" not found.`);delete t.profiles[e.name],I(t),c.success(`Profile "${e.name}" deleted successfully.`)}}),Ki=M({name:`list`,description:`List all profiles.`,args:q.strictObject({}),run:async()=>{let e=await d(),t=c.jsonMode,n=Object.entries(e.profiles);if(n.length===0){c.info(H`
|
|
91
89
|
No profiles found.
|
|
92
90
|
Please create a profile first using 'tailor profile create' command.
|
|
93
|
-
`),t&&c.out([]);return}let r=n.map(([e,t])=>{let n=o(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)}}),Li=D({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 h(),n=t.profiles[e.name];if(!n)throw Error(`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 Error(`Please provide at least one property to update.`);let r=n.user,i=e.user||r,a=n.workspace_id,o=e[`workspace-id`]||a,s=i,l=e[`machine-user`]===``?void 0:e[`machine-user`]??n.machine_user,u=e[`machine-user-override`]===`allow`?void 0:e[`machine-user-override`]??n.machine_user_override,d=e[`platform-url`]===``?void 0:e[`platform-url`]??n.platform_url,f=e[`oauth2-client-id`]===``?void 0:e[`oauth2-client-id`]??n.oauth2_client_id,p=e[`console-url`]===``?void 0:e[`console-url`]??n.console_url,m={...d?{platformUrl:d}:{},...f?{oauth2ClientId:f}:{},...p?{consoleUrl:p}:{}},g=Object.keys(m).length>0?m:void 0,_=e[`platform-url`]===``?B(n):g;if((e[`machine-user`]!==void 0||e[`machine-user-override`]!==void 0)&&u===`deny`&&!l)throw e[`machine-user-override`]===`deny`?Error(`--machine-user-override deny requires --machine-user.`):Error(`Cannot clear the machine user while machine-user-override is "deny". Also pass --machine-user-override allow.`);if(e.user!==void 0||e[`workspace-id`]!==void 0||e[`platform-url`]!==void 0){let e=await De(t,i,_);s=e.user;let n=await yn(e.accessToken,g);if(!(await wn(async(e,t)=>{let{workspaces:r,nextPageToken:i}=await n.listWorkspaces({pageToken:e,pageSize:t});return[r,i]})).find(e=>e.id===o))throw Error(`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`]),E(t),e.json||c.success(`Profile "${e.name}" updated successfully`);let v={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(v)}}),Ri=G({name:`profile`,description:`Manage workspace profiles (user + workspace combinations).`,subCommands:{create:Pi,delete:Fi,list:Ii,update:Li},async run(){await K(Ii,[])}}),zi={"vault-name":W(q.string(),{alias:`V`,description:`Vault name`})},Bi={...zi,name:W(q.string(),{alias:`n`,description:`Secret name`})},Vi={...Bi,value:W(q.string(),{alias:`v`,description:`Secret value`})};async function checkVaultManaged(e){let{client:t,workspaceId:n,vaultName:r}=e,i=N(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[hn]}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 fn(t,{trn:n,remove:[hn,it,an]}),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 Hi=D({name:`create`,description:`Create a secret in a vault.`,args:q.strictObject({...P,...Vi,...M}),run:async e=>{await j({profile:e.profile});let{client:t,workspaceId:n}=await v({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e[`vault-name`]});if(!r.isManaged||e.yes||await A.confirm({message:`Do you want to proceed?`,default:!1})){try{await t.createSecretManagerSecret({workspaceId:n,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name,secretmanagerSecretValue:e.value})}catch(t){if(t instanceof Q){if(t.code===Z.NotFound)throw Error(`Vault "${e[`vault-name`]}" not found.`,{cause:t});if(t.code===Z.AlreadyExists)throw Error(`Secret "${e.name}" already exists.`,{cause:t})}throw t}r.isManaged&&await releaseVaultOwnership({client:t,...r}),c.success(`Secret: ${e.name} created in vault: ${e[`vault-name`]}`)}}}),Ui=D({name:`delete`,description:`Delete a secret in a vault.`,args:q.strictObject({...P,...Bi,...M}),run:async e=>{await j({profile:e.profile});let{client:t,workspaceId:n}=await v({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e[`vault-name`]});if(!e.yes&&await A.text({message:`Enter the secret name to confirm deletion ("${e.name}"):`})!==e.name){c.info(`Secret deletion cancelled.`);return}try{await t.deleteSecretManagerSecret({workspaceId:n,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?Error(`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`]}`)}});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 v({profile:e.profile,workspaceId:e.workspaceId}),r=I(e.order);return(await V(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 Wi=D({name:`list`,description:`List all secrets in a vault.`,args:q.strictObject({...P,...zi,...L()}),run:async e=>{try{let t=await secretList({workspaceId:e[`workspace-id`],profile:e.profile,vaultName:e[`vault-name`],order:e.order,limit:e.limit});c.out(t)}catch(t){throw t instanceof Q&&t.code===Z.NotFound?Error(`Vault "${e[`vault-name`]}" not found.`,{cause:t}):t}}}),Gi=D({name:`update`,description:`Update a secret in a vault.`,args:q.strictObject({...P,...Vi,...M}),run:async e=>{await j({profile:e.profile});let{client:t,workspaceId:n}=await v({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e[`vault-name`]});if(!r.isManaged||e.yes||await A.confirm({message:`Do you want to proceed?`,default:!1})){try{await t.updateSecretManagerSecret({workspaceId:n,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name,secretmanagerSecretValue:e.value})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?Error(`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} updated in vault: ${e[`vault-name`]}`)}}}),Ki={name:W(q.string(),{positional:!0,description:`Vault name`})},qi=D({name:`create`,description:`Create a new Secret Manager vault.`,args:q.strictObject({...P,...Ki}),run:async e=>{await j({profile:e.profile});let{client:t,workspaceId:n}=await v({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?Error(`Vault "${e.name}" already exists.`,{cause:t}):t}c.success(`Vault: ${e.name} created`)}}),Ji=D({name:`delete`,description:`Delete a Secret Manager vault.`,args:q.strictObject({...P,...Ki,...M}),run:async e=>{await j({profile:e.profile});let{client:t,workspaceId:n}=await v({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e.name});if(!e.yes&&await A.text({message:`Enter the vault name to confirm deletion ("${e.name}"):`})!==e.name){c.info(`Vault deletion cancelled.`);return}try{await t.deleteSecretManagerVault({workspaceId:n,secretmanagerVaultName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?Error(`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`)}});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 v({profile:e?.profile,workspaceId:e?.workspaceId}),r=I(e?.order);return(await V(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 Yi=D({name:`list`,description:`List all Secret Manager vaults in the workspace.`,args:q.strictObject({...P,...L()}),run:async e=>{let t=await vaultList({workspaceId:e[`workspace-id`],profile:e.profile,order:e.order,limit:e.limit});c.out(t)}}),Xi=G({name:`vault`,description:`Manage Secret Manager vaults.`,subCommands:{create:qi,delete:Ji,list:Yi},async run(){await K(Yi,[])}}),Zi=G({name:`secret`,description:`Manage Secret Manager vaults and secrets.`,subCommands:{vault:Xi,create:Hi,update:Gi,list:Wi,delete:Ui},async run(){await K(Xi,[])}}),Qi={[t.UNSPECIFIED]:`unspecified`,[t.PENDING]:`pending`,[t.VERIFYING]:`verifying`,[t.CERT_ISSUED]:`cert_issued`,[t.ACTIVE]:`active`,[t.FAILED]:`failed`},$i=D({name:`get`,description:`Get details of a custom domain.`,args:q.strictObject({...P,domain:W(q.string(),{positional:!0,description:`Custom domain name`})}),run:async e=>{let{client:t,workspaceId:n}=await v({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 Error(r);let a={domain:i.domain,status:Qi[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?Error(r,{cause:e}):e}}}),ea=D({name:`list`,description:`List custom domains for a static website.`,args:q.strictObject({...P,name:W(q.string(),{positional:!0,description:`Static website name`})}),run:async e=>{let{client:t,workspaceId:n}=await v({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:Qi[e.status]??`unknown`,trafficCnameTarget:e.trafficCnameTarget,certificateCnameTarget:e.certificateCnameTarget}));c.out(i)}catch(t){throw t instanceof Q&&t.code===Z.NotFound?Error(`Static website "${e.name}" not found.`,{cause:t}):t}}}),ta=G({name:`domain`,description:`Manage custom domains for static websites.`,subCommands:{list:ea,get:$i}}),na=D({name:`get`,description:`Get details of a specific static website.`,args:q.strictObject({...P,name:W(q.string(),{positional:!0,description:`Static website name`})}),run:async e=>{let{client:t,workspaceId:n}=await v({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 Error(r);let a={workspaceId:n,name:i.name,description:i.description,url:i.url,allowedIpAddresses:e.json?i.allowedIpAddresses:i.allowedIpAddresses.join(`
|
|
94
|
-
`)};c.out(a)}catch(e){throw e instanceof Q&&e.code===Z.NotFound?Error(r,{cause:e}):e}}});async function listStaticWebsites(e){let{client:t,workspaceId:n}=await v({profile:e?.profile,workspaceId:e?.workspaceId}),r=I(e?.order);return(await V(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 ra=D({name:`list`,description:`List all static websites in a workspace.`,args:q.strictObject({...P,...L()}),run:async e=>{let t=c.jsonMode,n=await listStaticWebsites({workspaceId:e[`workspace-id`],profile:e.profile,order:e.order,limit:e.limit}),r=t?n:n.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(r)}}),ia=G({name:`staticwebsite`,description:`Manage static websites in your workspace.`,subCommands:{deploy:ze,domain:ta,list:ra,get:na},async run(){await K(ra,[])}}),aa=new Set(Object.values(re));async function activateBaseline(e,t,n,r){let i=await $.realpath(e),a=U.dirname(i),o=U.basename(i),s=await $.mkdtemp(U.join(a,`.${o}-rebaseline-`)),l=`${s}-previous`,u=!1,d=!1;try{await $.cp(i,s,{recursive:!0});for(let e of await $.readdir(s,{withFileTypes:!0})){if(!e.isDirectory()||!fe.test(e.name))continue;let t=U.join(s,e.name);(await $.readdir(t)).some(e=>aa.has(e))&&await $.rm(t,{recursive:!0,force:!0})}let e={...t,namespace:n,version:5,createdAt:new Date().toISOString(),rebaseline:r},a=await _n(e,s,0);$t(a.filePath),await $.rename(i,l),u=!0;try{await $.rename(s,i),d=!0}catch(e){throw await $.rename(l,i),u=!1,e}try{await $.rm(l,{recursive:!0,force:!0})}catch(e){c.warn(`The previous migration directory remains at ${l}: ${e instanceof Error?e.message:String(e)}`)}u=!1}finally{Y.existsSync(s)&&await $.rm(s,{recursive:!0,force:!0}),!d&&u&&Y.existsSync(l)&&await $.rename(l,i)}}async function rebaseline(e){m(`tailordb migration`);let{config:t,plugins:n}=await w(e.configPath),r=U.dirname(t.path),i=Tt(f(t,r),e.namespace),a=nr({command:`tailor`,args:[`tailordb`,`migration`,`generate`,`--config`,t.path]});k(i.migrationsDir,i.namespace);let o=z(i.migrationsDir);if(!o)throw Error(`No migration history found for namespace "${i.namespace}". Run ${a} first.`);let s=Ke(i.migrationsDir),u=z(i.migrationsDir,0)?.rebaseline?.historyId??null,d=Se([i])[i.namespace],p=n.length>0?new mt(n):void 0,{defineApplication:h}=await import(`../application-BKlOiD1x.mjs`),g=h({config:t,pluginManager:p});for(let e of g.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let _=g.tailorDBServices.find(e=>e.namespace===i.namespace);if(!_)throw Error(`No TailorDB service found for namespace "${i.namespace}"`);let assertLocalTypesReady=()=>{let e=se(_.types,i.namespace),t=Jt(o,e.tables,i.namespace);if(xt(t))throw c.error(`Migration history does not reproduce the current local schema for namespace ${l.bold(i.namespace)}:`),c.log(Ft(t)),Error(`Refusing to re-baseline: the migration history must reproduce the current local schema. Run ${a} first.`)},localSourceFiles=()=>[t.path,...qn(_.config,r)];assertLocalTypesReady();let y=ve(localSourceFiles()),{client:b,workspaceId:x}=await v({profile:e.profile,workspaceId:e.workspaceId}),S=[`--config`,t.path,`--workspace-id`,x,...e.profile?[`--profile`,e.profile]:[]],C=nr({command:`tailor`,args:[`tailordb`,`migration`,`set`,`0`,`--namespace`,i.namespace,...S]}),ee=nr({command:`tailor`,args:[`deploy`,...S]}),assertConnectedWorkspaceReady=async(e,n)=>{let r=await Dt(b,N(x,`tailordb`,i.namespace)),a=r.number;if(a!==s){let e=a===null?`<unset>`:F(a);throw Error(`The connected workspace must be at the latest migration ${F(s)} before re-baselining; current checkpoint is ${e}.`)}if(r.historyIdInvalid)throw Error(`Refusing to re-baseline: the connected workspace has an invalid migration history marker.`);if(r.historyId!==e)throw Error(n===`confirmation`?`The connected workspace migration history changed while waiting for confirmation. Run the command again.`:`Refusing to re-baseline: the connected workspace does not match the local migration history.`);let o=await rt(b,x,[i],t,[mn(_)]),l=o[0];if(!l||l.remoteMigrationNumber!==s||l.hasDrift||l.checkpointMissingLocal)throw l?.hasDrift&&(c.error(`Remote schema drift detected:`),c.log(_t(o))),Error(`Refusing to re-baseline: the connected workspace remote schema must match the latest migration.`)};if(await assertConnectedWorkspaceReady(u,`initial`),c.newline(),c.warn(`This will replace the migration history for ${l.bold(i.namespace)}.`),c.log(` Latest migration: ${F(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 A.confirm({message:`Re-baseline this migration history and reset the connected workspace checkpoint?`,default:!1})){c.info(`Operation cancelled.`);return}if(k(i.migrationsDir,i.namespace),Se([i])[i.namespace]!==d)throw Error(`Migration files changed while waiting for confirmation. Run the command again.`);if(ve(localSourceFiles())!==y)throw Error(`Local TailorDB table or config files changed. Run the command again.`);assertLocalTypesReady(),await assertConnectedWorkspaceReady(u,`confirmation`);let T={historyId:Ct(),replacedHistoryId:u,replacedLatestMigration:s};await activateBaseline(i.migrationsDir,o,i.namespace,T);try{await Pe(b,x,i.namespace,0,T.historyId)}catch(e){throw Error(`The local migration history was re-baselined, but the connected workspace checkpoint could not be updated. Run ${C}, or run ${ee} with schema checks enabled after resolving the connection error.`,{cause:e})}c.success(`Re-baselined ${l.bold(i.namespace)} and reset the connected workspace checkpoint to 0000.`)}const oa=D({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({...O,...M,namespace:W(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await j({profile:e.profile}),await rebaseline({configPath:e.config,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile})}});async function set(e){m(`tailordb migration`);let t=ht(e.number),{config:n}=await w(e.configPath),r=U.dirname(n.path),i=f(n,r),a=Tt(i,e.namespace),o=a.namespace;k(a.migrationsDir,o),le(a.migrationsDir,t);let s=z(a.migrationsDir,0)?.rebaseline?.historyId,{client:u,workspaceId:d}=await v({profile:e.profile,workspaceId:e.workspaceId}),p=N(d,`tailordb`,o),h=await Dt(u,p),g=h.number,_=g??0,y=h.historyIdInvalid?`<invalid>`:h.historyId??`<unset>`,b=s??`<unset>`;if(c.newline(),c.warn(`This operation will change TailorDB migration state metadata.`),c.log(`Namespace: ${l.bold(o)}`),c.log(`Current migration: ${g===null?`<unset>`:l.bold(F(g))}`),c.log(`New migration: ${l.bold(F(t))}`),c.log(`Current migration history ID: ${l.bold(y)}`),c.log(`New migration history ID: ${l.bold(b)}`),c.newline(),t<_?(c.warn(`Setting migration number backwards (${F(_)} → ${F(t)}) will cause previous migrations to be re-executed on next apply.`),c.newline()):t>_&&(c.warn(`Setting migration number forwards (${F(_)} → ${F(t)}) will skip migrations ${F(_+1)} to ${F(t)}.`),c.newline()),!e.yes){if(!await A.confirm({message:`Continue with migration checkpoint and history ID update?`,default:!1})){c.info(`Operation cancelled.`);return}c.newline()}await fn(u,{trn:p,labels:{[Gt]:zt(t),...s?{[Lt]:s}:{}},remove:s?void 0:[Lt]}),c.success(`Migration checkpoint set to ${l.bold(F(t))} for namespace ${l.bold(o)}`)}const sa=D({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({...O,...M,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 j({profile:e.profile}),await set({configPath:e.config,number:e.number,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile})}});function isStatusFailure(e){return e.status===`error`}async function collectMigrationStatuses(e){let{config:t}=await w(e.configPath),n=U.dirname(t.path),r=f(t,n);if(r.length===0)throw Error(`No TailorDB services with migrations configuration found`);let i=e.namespace?r.filter(t=>t.namespace===e.namespace):r;if(i.length===0)throw Error(`Namespace "${e.namespace}" not found or does not have migrations configured`);let a=new Map,o=new Map;for(let{namespace:e,migrationsDir:t}of i)try{let n=je(t),r=new Map,i=null;for(let e of n){if(e.type===`schema`){let t=$t(e.path);e.number===0&&(i=t.rebaseline?.historyId??null);continue}try{let t=ft(e.path);t.description&&r.set(e.number,t.description)}catch(e){if(e instanceof jt)throw e}}a.set(e,{migrationFiles:n,descriptions:r,historyId:i})}catch(t){o.set(e,t instanceof Error?t.message:String(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 v({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=N(c,`tailordb`,e),d;try{d=await Dt(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.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:F(e),...r.has(e)?{description:r.get(e)}:{}}));l.push({status:`ok`,namespace:e,currentMigration:f,currentMigrationLabel:F(f),pendingMigrations:p})}return l}function printMigrationStatuses(e){for(let t of e){if(c.newline(),c.info(`Namespace: ${l.bold(t.namespace)}`),isStatusFailure(t)){c.error(` Migration status error: ${t.error}`);continue}if(c.log(` Current migration: ${l.bold(t.currentMigrationLabel)}`),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){m(`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 Error(`Migration status check failed for ${n.length} namespace${n.length===1?``:`s`}: ${e}`)}}const ca=D({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({...O,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 An(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 wn(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?Error(`Cannot sync: TailorDB namespace "${n}" has not been deployed yet.`,{cause:e}):e}})}async function assertMigrationsReproduceLocalTypes(e,t){let{config:n,plugins:r}=e,i=r.length>0?new mt(r):void 0,{defineApplication:a,generatePluginFilesIfNeeded:o}=await import(`../application-BKlOiD1x.mjs`),s=a({config:n,pluginManager:i}),u=s.tailorDBServices.find(e=>e.namespace===t.namespace);if(!u)throw Error(`No TailorDB service found for namespace "${t.namespace}"`);for(let e of s.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let d=o(i,s.tailorDBServices,n.path),f=s.executorService??(d.length>0?(await import(`../service-CWFQ8EVo.mjs`)).createExecutorService({config:{files:[]},baseDir:U.dirname(n.path)}):void 0);await f?.loadExecutors(),d.length>0&&await f?.loadPluginExecutorFiles([...d]);let p=new Set;for(let e of Object.values(f?.executors??{}))vt(e)&&e.trigger.kind===`tailordb`&&p.add(e.trigger.tableName);let m={executorUsedTables:p,namespaceGqlOperations:u.config.gqlOperations},h=z(t.migrationsDir);if(!h)return m;let g=se(u.types,t.namespace),_=Jt(h,g.tables,t.namespace);if(!xt(_))return m;throw c.error(`Migration history does not reproduce the current local schema for namespace ${l.bold(t.namespace)}:`),c.log(Ft(_)),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(),Error(`Refusing to sync: the migration history must reproduce the current local schema before it can be applied to the remote.`)}async function sync(e){m(`tailordb migration`);let t=ht(e.number),n=await w(e.configPath),{config:r}=n,i=U.dirname(r.path),a=f(r,i),o=Tt(a,e.namespace);k(o.migrationsDir,o.namespace);let s=le(o.migrationsDir,t),u=z(o.migrationsDir,t);if(!u)throw Error(`No initial schema snapshot found in ${o.migrationsDir}. Expected 0000/schema.json.`);let d=await assertMigrationsReproduceLocalTypes(n,o),{client:p,workspaceId:h}=await v({profile:e.profile,workspaceId:e.workspaceId}),g=N(h,`tailordb`,o.namespace),_=await Ee(p,g),y=await fetchRemoteTypes(p,h,o.namespace),x=new Set(y.map(e=>e.name)),{creates:S,updates:C,deletes:T}=Ie(u,x),te=await fetchRemoteGqlPermissions(p,h,o.namespace),ne=new Set(te.map(e=>e.typeName)),re=Object.entries(u.tables).flatMap(([e,t])=>t.permissions?.gql?[{typeName:e,permission:b(t.permissions.gql)}]:[]),E=new Set(re.map(e=>e.typeName)),ie=te.filter(e=>!E.has(e.typeName));if(c.newline(),c.info(`Namespace: ${l.bold(o.namespace)}`),c.log(` Current migration: ${_===null?`<unset>`:l.bold(F(_))}`),c.log(` Target migration: ${l.bold(F(t))}`),c.log(` Tables to create: ${l.bold(String(S.length))}`),c.log(` Tables to update: ${l.bold(String(C.length))}`),c.log(` Tables to delete: ${l.bold(String(T.length))}`),c.log(` GQL permissions to set: ${l.bold(String(re.length))}`),c.log(` GQL permissions to delete: ${l.bold(String(ie.length))}`),c.newline(),S.length+C.length+T.length+re.length+ie.length===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.`),T.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(),_!==null&&t<_?(c.warn(`Migrations ${F(t+1)}–${F(_)} 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()):_!==null&&t>_&&(c.warn(`Moving the migration label forwards (${F(_)} → ${F(t)}): migrate.ts scripts for migrations ${F(_+1)}–${F(t)} will not run on the next deploy.`),c.newline()),!e.yes){if(!await A.confirm({message:`Continue and set migration label to ${F(t)}?`,default:!1})){c.info(`Operation cancelled.`);return}c.newline()}let ae=ee(u,d),manifestFor=e=>{let t=ae.get(e);if(!t)throw Error(`Internal error: no manifest generated for table "${e}". No changes were applied.`);return t},oe=S.map(e=>manifestFor(e)),se=C.map(e=>manifestFor(e));try{await Promise.all([...oe.map(e=>p.createTailorDBType({workspaceId:h,namespaceName:o.namespace,tailordbType:e})),...se.map(e=>p.updateTailorDBType({workspaceId:h,namespaceName:o.namespace,tailordbType:e}))])}catch(e){tt(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(re.map(({typeName:e,permission:t})=>{let n={workspaceId:h,namespaceName:o.namespace,typeName:e,permission:t};return ne.has(e)?p.updateTailorDBGQLPermission(n):p.createTailorDBGQLPermission(n)})),await Promise.all(ie.map(e=>p.deleteTailorDBGQLPermission({workspaceId:h,namespaceName:o.namespace,typeName:e.typeName}))),await Promise.all(T.map(e=>p.deleteTailorDBType({workspaceId:h,namespaceName:o.namespace,tailordbTypeName:e}))),await fn(p,{trn:g,labels:{[Gt]:zt(t),...u.rebaseline?.historyId?{[Lt]:u.rebaseline.historyId}:{}},remove:u.rebaseline?.historyId?void 0:[Lt]}),c.success(`Synced namespace ${l.bold(o.namespace)} to migration ${l.bold(F(t))}.`),t<s&&(c.newline(),c.info(`Run 'tailor deploy' to apply migrations ${F(t+1)}–${F(s)} from the working tree.`))}const la=D({name:`sync`,description:`Sync remote TailorDB schema to a specific migration snapshot (recovery from --no-schema-check drift).`,args:q.strictObject({...O,...M,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 j({profile:e.profile}),await sync({configPath:e.config,number:e.number,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile})}});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`?Error(`Seed data directory not found: ${e}. Run 'tailor generate' before testing migrations.`,{cause:t}):t}if(!t.isDirectory())throw Error(`Seed data path is not a directory: ${e}`)}function assertAssertionScript(e){let t=U.resolve(e),n;try{n=Y.statSync(t)}catch(e){throw e.code===`ENOENT`?Error(`Migration assertion script not found: ${t}`,{cause:e}):e}if(!n.isFile())throw Error(`Migration assertion path is not a file: ${t}`)}function assertCloneTargetRegion(e,t){if(e!==t)throw Error(`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 Error(`The migration test target workspace must differ from the source workspace.`)}function resolveAssertionNamespace(e,t){let n=t??(e.length===1?e[0]:void 0);if(!n)throw Error(`--assert-namespace is required when pending migrations span multiple namespaces.`);if(!e.includes(n))throw Error(`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,o(r[n],`remote snapshot missing for "${e.namespace}"`))}),t}async function waitForCloneApplicationData(e,t){let n=t.pollInterval??1e3,i=t.timeout??3e5,a=Date.now()+i;for(;Date.now()<=a;){let i=await e.getCloneApplicationDataOperation({sourceWorkspaceId:t.sourceWorkspaceId,targetWorkspaceId:t.targetWorkspaceId,operationId:t.operationId});if(i.status===r.COMPLETED)return;if(i.status===r.FAILED)throw Error(`Application data clone failed: ${i.errorMessage||`unknown platform error`}`);if(i.status!==r.PENDING&&i.status!==r.PROCESSING)throw Error(`Application data clone returned unexpected status ${i.status}.`);await delay(n)}throw Error(`Application data clone timed out after ${Math.round(i/1e3)} seconds.`)}function loadSnapshotSeedData(e,t,n){let r={};for(let i of t){let t=n?.tables[i],a=U.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(`
|
|
95
|
-
`).map((e,n)=>{let r;try{r=JSON.parse(e)}catch(e){throw Error(`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 Error(`Invalid seed row in ${a} at line ${n+1}: expected a JSON object`);let i=r;return t?projectSeedObject(i,t.fields,new Set([`id`])):i}):[]}return r}function projectSeedObject(e,t,n=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=new Map,i=[];for(let[t,a]of Object.entries(e.tables)){let e=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=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-${new Date().toISOString().replace(/[-:T.Z]/g,``).slice(0,14)}-${Or(3).toString(`hex`)}`}function stateOrThrow(e){return o(e,`migration test runtime was used before preparation`)}async function assertSourceBaselineFresh(e,t,n){let r=e.loaded,i=f(r.config,U.dirname(r.config.path)),a=r.application.tailorDBServices.map(mn),o=(await rt(e.client,n,i,r.config,a)).find(e=>e.hasDrift||e.checkpointMissingLocal||e.checkpointRepair);if(o)throw Error(`Source namespace "${o.namespace}" changed after migration test preparation. Run the migration test again.`);for(let r of i){let i=t.baselines.get(r.namespace);if(!i)continue;let a=await Ee(e.client,N(n,`tailordb`,r.namespace));if(a!==i.migrationNumber)throw Error(`Source namespace "${r.namespace}" moved from migration ${i.migrationNumber} to ${a??`none`} after migration test preparation. 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(ct(i,a).changes.length>0)throw Error(`Source namespace "${r.namespace}" schema changed after migration test preparation. 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 Mn(()=>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 Error(`Auth configuration is required to execute migration test scripts.`);let i=n??dn(migrationConfig(e.loaded,t),r.config.machineUsers?Object.keys(r.config.machineUsers):void 0);if(!i)throw Error(`No machine user is available for namespace "${t}". 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 pn({configPath:e.configPath}),n=U.dirname(t.config.path),r=f(t.config,n);if(r.length===0)throw Error(`No TailorDB services with migrations configuration found.`);for(let e of r)k(e.migrationsDir,e.namespace);let i;e.data===`seed`&&(i=await _e({configPath:t.config.path}),assertSeedDataDirectory(U.join(i.distPath,`data`))),e.assertionPath&&assertAssertionScript(e.assertionPath);let a=t.application.tailorDBServices.map(mn),s=await Et({profile:e.profile}),c=await ce({profile:e.profile}),l=await yn(s,c),u=await Ne({workspaceId:e.workspaceId,profile:e.profile});assertTargetWorkspaceDiffers(u,e.targetWorkspaceId);let[d,p,m]=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)]),h=o(d.workspace,`source workspace "${u}" not found`);o(p.application,`application "${t.config.name}" not found in source workspace`);let g=m?o(m.workspace,`target workspace "${e.targetWorkspaceId}" not found`):void 0,_=await rt(l,u,r,t.config,a),v=_.find(e=>e.hasDrift||e.checkpointMissingLocal);if(v)throw Error(`Source namespace "${v.namespace}" does not match its migration checkpoint. Run 'tailor tailordb migration validate' first.`);let y=_.find(e=>e.checkpointRepair);if(y)throw Error(`Source namespace "${y.namespace}" has a pending migration checkpoint repair. Run 'tailor deploy' against the source workspace first.`);let b=new Map,x=new Map,S=[];for(let e of r){let t=await Ee(l,N(u,`tailordb`,e.namespace));if(t===null)throw Error(`Source namespace "${e.namespace}" has no sdk-migration checkpoint. Deploy or set its migration checkpoint before testing.`);let n=Ke(e.migrationsDir);if(t>n)throw Error(`Source namespace "${e.namespace}" is at migration ${t}, but the local history ends at ${n}.`);let r=z(e.migrationsDir,t);if(!r)throw Error(`No migration baseline snapshot found for namespace "${e.namespace}".`);b.set(e.namespace,{migrationNumber:t,snapshot:r,historyId:r.rebaseline?.historyId??null});let i=z(e.migrationsDir,n);if(!i)throw Error(`No target migration snapshot found for namespace "${e.namespace}".`);x.set(e.namespace,i),t<n&&S.push(e.namespace)}if(S.length===0)throw Error(`No pending TailorDB migrations found in the source workspace.`);let C=await createMigrationTestBaselineSnapshots({client:l,workspaceId:u,dataMode:e.data,inputs:a,baselines:b}),ee={sourceWorkspaceId:u,sourceApplicationName:t.config.name,temporaryWorkspace:{name:temporaryWorkspaceName(),region:h.region,...h.organizationId?{organizationId:h.organizationId}:{},...h.folderId?{folderId:h.folderId}:{}},baselines:b,baselineSnapshots:C,targetSnapshots:x,pendingNamespaces:S,...g?{designatedTarget:{id:g.id,region:g.region}}:{}};return{state:{client:l,loaded:t,options:e,...i?{seedContext:i}:{}},prepared:ee}}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 et(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 dt({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 Pe(r.client,n,e,i.migrationNumber,i.historyId??void 0)},seedData:async({prepared:t,targetWorkspaceId:n})=>{let r=stateOrThrow(e),i=o(r.seedContext,`seed context missing after migration test preparation`),a=U.join(i.distPath,`data`);assertSeedDataDirectory(a);let s=new Map(r.loaded.application.tailorDBServices.map(e=>{let n=t.baselines.get(e.namespace),r=mn(e);return[e.namespace,n?.snapshot??R({version:1,namespace:e.namespace,createdAt:new Date().toISOString(),tables:r.types})]}));for(let[e,t]of s){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 Oe(e,l,U.dirname(r.loaded.config.path)),d=xe({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 Error(i.error??`Seed execution failed for namespace "${e}".`);if(JSON.parse(i.result||`{}`).success!==!0)throw Error(`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?Error(`Application data clone is not enabled for this platform. Retry with '--data seed'.`,{cause:e}):e}if(!o)throw Error(`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 Qt({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??{},U.dirname(o.loaded.config.path)),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 Error(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 Error(`--target-workspace-id requires --yes because the target may be overwritten.`);if(e.keep&&e.targetWorkspaceId)throw Error(`--keep applies only to automatically created workspaces; a designated target is always retained.`);if(e.assertionNamespace&&!e.assertionPath)throw Error(`--assert is required when --assert-namespace is provided.`);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=o(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:o(e.targetWorkspaceId,`designated target workspace missing`),name:void 0},a,s=!1,l=!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,s=!0}if(r&&e.keep)c.info(`Keeping temporary workspace ${i.name??i.id}.`);else if(r)try{await t.deleteWorkspace(i.id),l=!0}catch(e){if(!s)throw Error(`Failed to delete temporary workspace ${i.id}: ${e instanceof Error?e.message:String(e)}`,{cause:e});c.warn(`Failed to delete temporary workspace ${i.id}: ${e instanceof Error?e.message:String(e)}`)}if(s)throw a;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){m(`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 ua=D({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({...O,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 j({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=[];for(let t of je(e)){if(t.type!==`diff`)continue;let n=ft(t.path),s=Xe(e,t.number,`migrate`),c=Y.existsSync(s);n.requiresMigrationScript&&!n.scriptSkipped&&!c&&r.push(t.number),n.scriptSkipped&&c&&i.push(t.number),c&&Y.readFileSync(s,`utf8`).includes(`TODO(tailor-migration-review)`)&&a.push(t.number),n.hasWarnings&&!n.scriptSkipped&&!c&&o.push({migrationNumber:t.number,warnings:n.warnings})}if(r.length>0)throw Error(`Migration(s) ${r.map(F).join(`, `)} in namespace "${t}" require a migration script but have no migrate.ts. 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=>` ${_({migrationNumber:e,namespace:t,configPath:n})}`).join(`
|
|
96
|
-
`);throw Error(`Migration(s) ${i.map(
|
|
97
|
-
${e}\nOr delete migrate.ts to keep the skip.`)}if(a.length>0)throw Error(`Migration(s) ${a.map(
|
|
91
|
+
`),t&&c.out([]);return}let r=n.map(([e,t])=>{let n=o(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)}}),qi=M({name:`update`,description:`Update profile properties.`,args:q.strictObject({name:U(q.string(),{positional:!0,description:`Profile name`}),user:U(q.string().optional(),{alias:`u`,description:`New user email address or machine user client ID`}),"workspace-id":U(q.string().optional(),{alias:`w`,description:`New workspace ID`}),permission:U(q.enum([`write`,`read`]).optional(),{description:`Profile permission. 'read' blocks all write commands; 'write' lifts the restriction.`}),"machine-user":U(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":U(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":U(q.union([q.url(),q.literal(``)]).optional(),{description:`Platform API base URL for this profile. Pass an empty string to clear.`}),"oauth2-client-id":U(q.string().optional(),{description:`OAuth2 client ID for logging in to this profile's platform. Pass an empty string to clear.`}),"console-url":U(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 d(),n=t.profiles[e.name];if(!n)throw Error(`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 Error(`Please provide at least one property to update.`);let r=n.user,i=e.user||r,a=n.workspace_id,o=e[`workspace-id`]||a,s=i,l=e[`machine-user`]===``?void 0:e[`machine-user`]??n.machine_user,u=e[`machine-user-override`]===`allow`?void 0:e[`machine-user-override`]??n.machine_user_override,f=e[`platform-url`]===``?void 0:e[`platform-url`]??n.platform_url,p=e[`oauth2-client-id`]===``?void 0:e[`oauth2-client-id`]??n.oauth2_client_id,m=e[`console-url`]===``?void 0:e[`console-url`]??n.console_url,h={...f?{platformUrl:f}:{},...p?{oauth2ClientId:p}:{},...m?{consoleUrl:m}:{}},g=Object.keys(h).length>0?h:void 0,_=e[`platform-url`]===``?O(n):g;if((e[`machine-user`]!==void 0||e[`machine-user-override`]!==void 0)&&u===`deny`&&!l)throw e[`machine-user-override`]===`deny`?Error(`--machine-user-override deny requires --machine-user.`):Error(`Cannot clear the machine user while machine-user-override is "deny". Also pass --machine-user-override allow.`);if(e.user!==void 0||e[`workspace-id`]!==void 0||e[`platform-url`]!==void 0){let e=await We(t,i,_);s=e.user;let n=await On(e.accessToken,g);if(!(await Nn(async(e,t)=>{let{workspaces:r,nextPageToken:i}=await n.listWorkspaces({pageToken:e,pageSize:t});return[r,i]})).find(e=>e.id===o))throw Error(`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`]),I(t),e.json||c.success(`Profile "${e.name}" updated successfully`);let v={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(v)}}),Ji=W({name:`profile`,description:`Manage workspace profiles (user + workspace combinations).`,subCommands:{create:Wi,delete:Gi,list:Ki,update:qi},async run(){await G(Ki,[])}}),Yi={"vault-name":U(q.string(),{alias:`V`,description:`Vault name`})},Xi={...Yi,name:U(q.string(),{alias:`n`,description:`Secret name`})},Zi={...Xi,value:U(q.string(),{alias:`v`,description:`Secret value`})};async function checkVaultManaged(e){let{client:t,workspaceId:n,vaultName:r}=e,i=m(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[xe]}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 Me(t,{trn:n,remove:[xe,Te,Ft]}),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 Qi=M({name:`create`,description:`Create a secret in a vault.`,args:q.strictObject({...N,...Zi,...L}),run:async e=>{await k({profile:e.profile});let{client:t,workspaceId:n}=await E({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e[`vault-name`]});if(!r.isManaged||e.yes||await T.confirm({message:`Do you want to proceed?`,default:!1})){try{await t.createSecretManagerSecret({workspaceId:n,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name,secretmanagerSecretValue:e.value})}catch(t){if(t instanceof Q){if(t.code===Z.NotFound)throw Error(`Vault "${e[`vault-name`]}" not found.`,{cause:t});if(t.code===Z.AlreadyExists)throw Error(`Secret "${e.name}" already exists.`,{cause:t})}throw t}r.isManaged&&await releaseVaultOwnership({client:t,...r}),c.success(`Secret: ${e.name} created in vault: ${e[`vault-name`]}`)}}}),$i=M({name:`delete`,description:`Delete a secret in a vault.`,args:q.strictObject({...N,...Xi,...L}),run:async e=>{await k({profile:e.profile});let{client:t,workspaceId:n}=await E({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e[`vault-name`]});if(!e.yes&&await T.text({message:`Enter the secret name to confirm deletion ("${e.name}"):`})!==e.name){c.info(`Secret deletion cancelled.`);return}try{await t.deleteSecretManagerSecret({workspaceId:n,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?Error(`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`]}`)}});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 E({profile:e.profile,workspaceId:e.workspaceId}),r=z(e.order);return(await V(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 ea=M({name:`list`,description:`List all secrets in a vault.`,args:q.strictObject({...N,...Yi,...F()}),run:async e=>{try{let t=await secretList({workspaceId:e[`workspace-id`],profile:e.profile,vaultName:e[`vault-name`],order:e.order,limit:e.limit});c.out(t)}catch(t){throw t instanceof Q&&t.code===Z.NotFound?Error(`Vault "${e[`vault-name`]}" not found.`,{cause:t}):t}}}),ta=M({name:`update`,description:`Update a secret in a vault.`,args:q.strictObject({...N,...Zi,...L}),run:async e=>{await k({profile:e.profile});let{client:t,workspaceId:n}=await E({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e[`vault-name`]});if(!r.isManaged||e.yes||await T.confirm({message:`Do you want to proceed?`,default:!1})){try{await t.updateSecretManagerSecret({workspaceId:n,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name,secretmanagerSecretValue:e.value})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?Error(`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} updated in vault: ${e[`vault-name`]}`)}}}),na={name:U(q.string(),{positional:!0,description:`Vault name`})},ra=M({name:`create`,description:`Create a new Secret Manager vault.`,args:q.strictObject({...N,...na}),run:async e=>{await k({profile:e.profile});let{client:t,workspaceId:n}=await E({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?Error(`Vault "${e.name}" already exists.`,{cause:t}):t}c.success(`Vault: ${e.name} created`)}}),ia=M({name:`delete`,description:`Delete a Secret Manager vault.`,args:q.strictObject({...N,...na,...L}),run:async e=>{await k({profile:e.profile});let{client:t,workspaceId:n}=await E({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e.name});if(!e.yes&&await T.text({message:`Enter the vault name to confirm deletion ("${e.name}"):`})!==e.name){c.info(`Vault deletion cancelled.`);return}try{await t.deleteSecretManagerVault({workspaceId:n,secretmanagerVaultName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?Error(`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`)}});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 E({profile:e?.profile,workspaceId:e?.workspaceId}),r=z(e?.order);return(await V(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 aa=M({name:`list`,description:`List all Secret Manager vaults in the workspace.`,args:q.strictObject({...N,...F()}),run:async e=>{let t=await vaultList({workspaceId:e[`workspace-id`],profile:e.profile,order:e.order,limit:e.limit});c.out(t)}}),oa=W({name:`vault`,description:`Manage Secret Manager vaults.`,subCommands:{create:ra,delete:ia,list:aa},async run(){await G(aa,[])}}),sa=W({name:`secret`,description:`Manage Secret Manager vaults and secrets.`,subCommands:{vault:oa,create:Qi,update:ta,list:ea,delete:$i},async run(){await G(oa,[])}}),ca={[t.UNSPECIFIED]:`unspecified`,[t.PENDING]:`pending`,[t.VERIFYING]:`verifying`,[t.CERT_ISSUED]:`cert_issued`,[t.ACTIVE]:`active`,[t.FAILED]:`failed`},la=M({name:`get`,description:`Get details of a custom domain.`,args:q.strictObject({...N,domain:U(q.string(),{positional:!0,description:`Custom domain name`})}),run:async e=>{let{client:t,workspaceId:n}=await E({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 Error(r);let a={domain:i.domain,status:ca[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?Error(r,{cause:e}):e}}}),ua=M({name:`list`,description:`List custom domains for a static website.`,args:q.strictObject({...N,name:U(q.string(),{positional:!0,description:`Static website name`})}),run:async e=>{let{client:t,workspaceId:n}=await E({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:ca[e.status]??`unknown`,trafficCnameTarget:e.trafficCnameTarget,certificateCnameTarget:e.certificateCnameTarget}));c.out(i)}catch(t){throw t instanceof Q&&t.code===Z.NotFound?Error(`Static website "${e.name}" not found.`,{cause:t}):t}}}),da=W({name:`domain`,description:`Manage custom domains for static websites.`,subCommands:{list:ua,get:la}}),fa=M({name:`get`,description:`Get details of a specific static website.`,args:q.strictObject({...N,name:U(q.string(),{positional:!0,description:`Static website name`})}),run:async e=>{let{client:t,workspaceId:n}=await E({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 Error(r);let a={workspaceId:n,name:i.name,description:i.description,url:i.url,allowedIpAddresses:e.json?i.allowedIpAddresses:i.allowedIpAddresses.join(`
|
|
92
|
+
`)};c.out(a)}catch(e){throw e instanceof Q&&e.code===Z.NotFound?Error(r,{cause:e}):e}}});async function listStaticWebsites(e){let{client:t,workspaceId:n}=await E({profile:e?.profile,workspaceId:e?.workspaceId}),r=z(e?.order);return(await V(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 pa=M({name:`list`,description:`List all static websites in a workspace.`,args:q.strictObject({...N,...F()}),run:async e=>{let t=c.jsonMode,n=await listStaticWebsites({workspaceId:e[`workspace-id`],profile:e.profile,order:e.order,limit:e.limit}),r=t?n:n.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(r)}}),ma=W({name:`staticwebsite`,description:`Manage static websites in your workspace.`,subCommands:{deploy:He,domain:da,list:pa,get:fa},async run(){await G(pa,[])}}),ha=new Set(Object.values(Mt));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-`)),l=`${s}-previous`,u=!1,d=!1;try{await $.cp(i,s,{recursive:!0});for(let e of await $.readdir(s,{withFileTypes:!0})){if(!e.isDirectory()||!lt.test(e.name))continue;let t=K.join(s,e.name);(await $.readdir(t)).some(e=>ha.has(e))&&await $.rm(t,{recursive:!0,force:!0})}let e={...t,namespace:n,version:6,createdAt:new Date().toISOString(),rebaseline:r},a=await Tn(e,s,0);Wt(a.filePath),await $.rename(i,l),u=!0;try{await $.rename(s,i),d=!0}catch(e){throw await $.rename(l,i),u=!1,e}try{await $.rm(l,{recursive:!0,force:!0})}catch(e){c.warn(`The previous migration directory remains at ${l}: ${e instanceof Error?e.message:String(e)}`)}u=!1}finally{Y.existsSync(s)&&await $.rm(s,{recursive:!0,force:!0}),!d&&u&&Y.existsSync(l)&&await $.rename(l,i)}}async function rebaseline(e){h(`tailordb migration`);let{config:t,plugins:n}=await B(e.configPath),r=K.dirname(t.path),i=Ke(A(t,r),e.namespace),a=dr({command:`tailor`,args:[`tailordb`,`migration`,`generate`,`--config`,t.path]});j(i.migrationsDir,i.namespace);let o=D(i.migrationsDir);if(!o)throw Error(`No migration history found for namespace "${i.namespace}". Run ${a} first.`);let s=gt(i.migrationsDir),u=D(i.migrationsDir,0)?.rebaseline?.historyId??null,d=pe([i])[i.namespace],f=n.length>0?new Re(n):void 0,{defineApplication:p}=await import(`../application-fIhVKX78.mjs`),g=p({config:t,pluginManager:f});for(let e of g.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let _=g.tailorDBServices.find(e=>e.namespace===i.namespace);if(!_)throw Error(`No TailorDB service found for namespace "${i.namespace}"`);let assertLocalTypesReady=()=>{let e=$e(_.types,i.namespace),t=dt(o,e.tables,i.namespace);if(ke(t))throw c.error(`Migration history does not reproduce the current local schema for namespace ${l.bold(i.namespace)}:`),c.log(S(t)),Error(`Refusing to re-baseline: the migration history must reproduce the current local schema. Run ${a} first.`)},localSourceFiles=()=>[t.path,...nr(_.config,r)];assertLocalTypesReady();let v=re(localSourceFiles()),{client:y,workspaceId:b}=await E({profile:e.profile,workspaceId:e.workspaceId}),x=[`--config`,t.path,`--workspace-id`,b,...e.profile?[`--profile`,e.profile]:[]],C=dr({command:`tailor`,args:[`tailordb`,`migration`,`set`,`0`,`--namespace`,i.namespace,...x]}),ee=dr({command:`tailor`,args:[`deploy`,...x]}),assertConnectedWorkspaceReady=async(e,n)=>{let r=await ae(y,m(b,`tailordb`,i.namespace)),a=r.number;if(a!==s){let e=a===null?`<unset>`:R(a);throw Error(`The connected workspace must be at the latest migration ${R(s)} before re-baselining; current checkpoint is ${e}.`)}if(r.historyIdInvalid)throw Error(`Refusing to re-baseline: the connected workspace has an invalid migration history marker.`);if(r.historyId!==e)throw Error(n===`confirmation`?`The connected workspace migration history changed while waiting for confirmation. Run the command again.`:`Refusing to re-baseline: the connected workspace does not match the local migration history.`);let o=await we(y,b,[i],t,[be(_)]),l=o[0];if(!l||l.remoteMigrationNumber!==s||l.hasDrift||l.checkpointMissingLocal)throw l?.hasDrift&&(c.error(`Remote schema drift detected:`),c.log(It(o))),Error(`Refusing to re-baseline: the connected workspace remote schema must match the latest migration.`)};if(await assertConnectedWorkspaceReady(u,`initial`),c.newline(),c.warn(`This will replace the migration history for ${l.bold(i.namespace)}.`),c.log(` Latest migration: ${R(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 T.confirm({message:`Re-baseline this migration history and reset the connected workspace checkpoint?`,default:!1})){c.info(`Operation cancelled.`);return}if(j(i.migrationsDir,i.namespace),pe([i])[i.namespace]!==d)throw Error(`Migration files changed while waiting for confirmation. Run the command again.`);if(re(localSourceFiles())!==v)throw Error(`Local TailorDB table or config files changed. Run the command again.`);assertLocalTypesReady(),await assertConnectedWorkspaceReady(u,`confirmation`);let te={historyId:ot(),replacedHistoryId:u,replacedLatestMigration:s};await activateBaseline(i.migrationsDir,o,i.namespace,te);try{await w(y,b,i.namespace,0,te.historyId)}catch(e){throw Error(`The local migration history was re-baselined, but the connected workspace checkpoint could not be updated. Run ${C}, or run ${ee} with schema checks enabled after resolving the connection error.`,{cause:e})}c.success(`Re-baselined ${l.bold(i.namespace)} and reset the connected workspace checkpoint to 0000.`)}const ga=M({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({...P,...L,namespace:U(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await k({profile:e.profile}),await rebaseline({configPath:e.config,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile})}});async function set(e){h(`tailordb migration`);let t=ze(e.number),{config:n}=await B(e.configPath),r=K.dirname(n.path),i=A(n,r),a=Ke(i,e.namespace),o=a.namespace;j(a.migrationsDir,o),sn(a.migrationsDir,t);let s=D(a.migrationsDir,0)?.rebaseline?.historyId,{client:u,workspaceId:d}=await E({profile:e.profile,workspaceId:e.workspaceId}),f=m(d,`tailordb`,o),p=await ae(u,f),g=p.number,_=g??0,v=p.historyIdInvalid?`<invalid>`:p.historyId??`<unset>`,y=s??`<unset>`;if(c.newline(),c.warn(`This operation will change TailorDB migration state metadata.`),c.log(`Namespace: ${l.bold(o)}`),c.log(`Current migration: ${g===null?`<unset>`:l.bold(R(g))}`),c.log(`New migration: ${l.bold(R(t))}`),c.log(`Current migration history ID: ${l.bold(v)}`),c.log(`New migration history ID: ${l.bold(y)}`),c.newline(),t<_?(c.warn(`Setting migration number backwards (${R(_)} → ${R(t)}) will cause previous migrations to be re-executed on next apply.`),c.newline()):t>_&&(c.warn(`Setting migration number forwards (${R(_)} → ${R(t)}) will skip migrations ${R(_+1)} to ${R(t)}.`),c.newline()),!e.yes){if(!await T.confirm({message:`Continue with migration checkpoint and history ID update?`,default:!1})){c.info(`Operation cancelled.`);return}c.newline()}await Me(u,{trn:f,labels:{[Dt]:Cn(t),...s?{[jt]:s}:{}},remove:s?void 0:[jt]}),c.success(`Migration checkpoint set to ${l.bold(R(t))} for namespace ${l.bold(o)}`)}const _a=M({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({...P,...L,number:U(q.string(),{positional:!0,description:`Migration number to set (e.g., 0001 or 1)`}),namespace:U(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await k({profile:e.profile}),await set({configPath:e.config,number:e.number,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile})}});function isStatusFailure(e){return e.status===`error`}async function collectMigrationStatuses(e){let{config:t}=await B(e.configPath),n=K.dirname(t.path),r=A(t,n);if(r.length===0)throw Error(`No TailorDB services with migrations configuration found`);let i=e.namespace?r.filter(t=>t.namespace===e.namespace):r;if(i.length===0)throw Error(`Namespace "${e.namespace}" not found or does not have migrations configured`);let a=new Map,o=new Map;for(let{namespace:e,migrationsDir:t}of i)try{let n=vt(t),r=new Map,i=null;for(let e of n){if(e.type===`schema`){let t=Wt(e.path);e.number===0&&(i=t.rebaseline?.historyId??null);continue}try{let t=Yt(e.path);t.description&&r.set(e.number,t.description)}catch(e){if(e instanceof Ie)throw e}}a.set(e,{migrationFiles:n,descriptions:r,historyId:i})}catch(t){o.set(e,t instanceof Error?t.message:String(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 E({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=m(c,`tailordb`,e),d;try{d=await ae(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.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:R(e),...r.has(e)?{description:r.get(e)}:{}}));l.push({status:`ok`,namespace:e,currentMigration:f,currentMigrationLabel:R(f),pendingMigrations:p})}return l}function printMigrationStatuses(e){for(let t of e){if(c.newline(),c.info(`Namespace: ${l.bold(t.namespace)}`),isStatusFailure(t)){c.error(` Migration status error: ${t.error}`);continue}if(c.log(` Current migration: ${l.bold(t.currentMigrationLabel)}`),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){h(`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 Error(`Migration status check failed for ${n.length} namespace${n.length===1?``:`s`}: ${e}`)}}const va=M({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({...P,namespace:U(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 zn(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 Nn(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?Error(`Cannot sync: TailorDB namespace "${n}" has not been deployed yet.`,{cause:e}):e}})}async function assertMigrationsReproduceLocalTypes(e,t){let{config:n,plugins:r}=e,i=r.length>0?new Re(r):void 0,{defineApplication:a,generatePluginFilesIfNeeded:o}=await import(`../application-fIhVKX78.mjs`),s=a({config:n,pluginManager:i}),u=s.tailorDBServices.find(e=>e.namespace===t.namespace);if(!u)throw Error(`No TailorDB service found for namespace "${t.namespace}"`);for(let e of s.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let d=o(i,s.tailorDBServices,n.path),f=s.executorService??(d.length>0?(await import(`../service-CWFQ8EVo.mjs`)).createExecutorService({config:{files:[]},baseDir:K.dirname(n.path)}):void 0);await f?.loadExecutors(),d.length>0&&await f?.loadPluginExecutorFiles([...d]);let p=new Set;for(let e of Object.values(f?.executors??{}))Lt(e)&&e.trigger.kind===`tailordb`&&p.add(e.trigger.tableName);let m={executorUsedTables:p,namespaceGqlOperations:u.config.gqlOperations},h=D(t.migrationsDir);if(!h)return m;let g=$e(u.types,t.namespace),_=dt(h,g.tables,t.namespace);if(!ke(_))return m;throw c.error(`Migration history does not reproduce the current local schema for namespace ${l.bold(t.namespace)}:`),c.log(S(_)),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(),Error(`Refusing to sync: the migration history must reproduce the current local schema before it can be applied to the remote.`)}async function sync(e){h(`tailordb migration`);let t=ze(e.number),n=await B(e.configPath),{config:r}=n,i=K.dirname(r.path),a=A(r,i),o=Ke(a,e.namespace);j(o.migrationsDir,o.namespace);let s=sn(o.migrationsDir,t),u=D(o.migrationsDir,t);if(!u)throw Error(`No initial schema snapshot found in ${o.migrationsDir}. Expected 0000/schema.json.`);let d=await assertMigrationsReproduceLocalTypes(n,o),{client:f,workspaceId:p}=await E({profile:e.profile,workspaceId:e.workspaceId}),_=m(p,`tailordb`,o.namespace),v=await Ue(f,_),y=await fetchRemoteTypes(f,p,o.namespace),b=new Set(y.map(e=>e.name)),{creates:x,updates:S,deletes:C}=Fe(u,b),ee=await fetchRemoteGqlPermissions(f,p,o.namespace),te=new Set(ee.map(e=>e.typeName)),w=Object.entries(u.tables).flatMap(([e,t])=>t.permissions?.gql?[{typeName:e,permission:g(t.permissions.gql)}]:[]),ne=new Set(w.map(e=>e.typeName)),re=ee.filter(e=>!ne.has(e.typeName));if(c.newline(),c.info(`Namespace: ${l.bold(o.namespace)}`),c.log(` Current migration: ${v===null?`<unset>`:l.bold(R(v))}`),c.log(` Target migration: ${l.bold(R(t))}`),c.log(` Tables to create: ${l.bold(String(x.length))}`),c.log(` Tables to update: ${l.bold(String(S.length))}`),c.log(` Tables to delete: ${l.bold(String(C.length))}`),c.log(` GQL permissions to set: ${l.bold(String(w.length))}`),c.log(` GQL permissions to delete: ${l.bold(String(re.length))}`),c.newline(),x.length+S.length+C.length+w.length+re.length===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.`),C.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(),v!==null&&t<v?(c.warn(`Migrations ${R(t+1)}–${R(v)} 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()):v!==null&&t>v&&(c.warn(`Moving the migration label forwards (${R(v)} → ${R(t)}): migrate.ts scripts for migrations ${R(v+1)}–${R(t)} will not run on the next deploy.`),c.newline()),!e.yes){if(!await T.confirm({message:`Continue and set migration label to ${R(t)}?`,default:!1})){c.info(`Operation cancelled.`);return}c.newline()}let ie=En(u,d),manifestFor=e=>{let t=ie.get(e);if(!t)throw Error(`Internal error: no manifest generated for table "${e}". No changes were applied.`);return t},ae=x.map(e=>manifestFor(e)),oe=S.map(e=>manifestFor(e));try{await Promise.all([...ae.map(e=>f.createTailorDBType({workspaceId:p,namespaceName:o.namespace,tailordbType:e})),...oe.map(e=>f.updateTailorDBType({workspaceId:p,namespaceName:o.namespace,tailordbType:e}))])}catch(e){_n(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(w.map(({typeName:e,permission:t})=>{let n={workspaceId:p,namespaceName:o.namespace,typeName:e,permission:t};return te.has(e)?f.updateTailorDBGQLPermission(n):f.createTailorDBGQLPermission(n)})),await Promise.all(re.map(e=>f.deleteTailorDBGQLPermission({workspaceId:p,namespaceName:o.namespace,typeName:e.typeName}))),await Promise.all(C.map(e=>f.deleteTailorDBType({workspaceId:p,namespaceName:o.namespace,tailordbTypeName:e}))),await Me(f,{trn:_,labels:{[Dt]:Cn(t),...u.rebaseline?.historyId?{[jt]:u.rebaseline.historyId}:{}},remove:u.rebaseline?.historyId?void 0:[jt]}),c.success(`Synced namespace ${l.bold(o.namespace)} to migration ${l.bold(R(t))}.`),t<s&&(c.newline(),c.info(`Run 'tailor deploy' to apply migrations ${R(t+1)}–${R(s)} from the working tree.`))}const ya=M({name:`sync`,description:`Sync remote TailorDB schema to a specific migration snapshot (recovery from --no-schema-check drift).`,args:q.strictObject({...P,...L,number:U(q.string(),{positional:!0,description:`Migration number to sync to (e.g., 0001 or 1; 0 targets the baseline snapshot)`}),namespace:U(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await k({profile:e.profile}),await sync({configPath:e.config,number:e.number,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile})}});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`?Error(`Seed data directory not found: ${e}. Run 'tailor generate' before testing migrations.`,{cause:t}):t}if(!t.isDirectory())throw Error(`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`?Error(`Migration assertion script not found: ${t}`,{cause:e}):e}if(!n.isFile())throw Error(`Migration assertion path is not a file: ${t}`)}function assertCloneTargetRegion(e,t){if(e!==t)throw Error(`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 Error(`The migration test target workspace must differ from the source workspace.`)}function resolveAssertionNamespace(e,t){let n=t??(e.length===1?e[0]:void 0);if(!n)throw Error(`--assert-namespace is required when pending migrations span multiple namespaces.`);if(!e.includes(n))throw Error(`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=>Oe(e.client,e.workspaceId,t.namespace)));return n.forEach((e,n)=>{t.set(e.namespace,o(r[n],`remote snapshot missing for "${e.namespace}"`))}),t}async function waitForCloneApplicationData(e,t){let n=t.pollInterval??1e3,i=t.timeout??3e5,a=Date.now()+i;for(;Date.now()<=a;){let i=await e.getCloneApplicationDataOperation({sourceWorkspaceId:t.sourceWorkspaceId,targetWorkspaceId:t.targetWorkspaceId,operationId:t.operationId});if(i.status===r.COMPLETED)return;if(i.status===r.FAILED)throw Error(`Application data clone failed: ${i.errorMessage||`unknown platform error`}`);if(i.status!==r.PENDING&&i.status!==r.PROCESSING)throw Error(`Application data clone returned unexpected status ${i.status}.`);await delay(n)}throw Error(`Application data clone timed out after ${Math.round(i/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(`
|
|
93
|
+
`).map((e,n)=>{let r;try{r=JSON.parse(e)}catch(e){throw Error(`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 Error(`Invalid seed row in ${a} at line ${n+1}: expected a JSON object`);let i=r;return t?projectSeedObject(i,t.fields,new Set([`id`])):i}):[]}return r}function projectSeedObject(e,t,n=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=new Map,i=[];for(let[t,a]of Object.entries(e.tables)){let e=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=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-${new Date().toISOString().replace(/[-:T.Z]/g,``).slice(0,14)}-${Lr(3).toString(`hex`)}`}function stateOrThrow(e){return o(e,`migration test runtime was used before preparation`)}async function assertSourceBaselineFresh(e,t,n){let r=e.loaded,i=A(r.config,K.dirname(r.config.path)),a=r.application.tailorDBServices.map(be),o=(await we(e.client,n,i,r.config,a)).find(e=>e.hasDrift||e.checkpointMissingLocal||e.checkpointRepair);if(o)throw Error(`Source namespace "${o.namespace}" changed after migration test preparation. Run the migration test again.`);for(let r of i){let i=t.baselines.get(r.namespace);if(!i)continue;let a=await Ue(e.client,m(n,`tailordb`,r.namespace));if(a!==i.migrationNumber)throw Error(`Source namespace "${r.namespace}" moved from migration ${i.migrationNumber} to ${a??`none`} after migration test preparation. 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 Oe(e.client,n,r.namespace);if(xn(i,a).changes.length>0)throw Error(`Source namespace "${r.namespace}" schema changed after migration test preparation. 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 Vn(()=>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 Error(`Auth configuration is required to execute migration test scripts.`);let i=n??je(migrationConfig(e.loaded,t),r.config.machineUsers?Object.keys(r.config.machineUsers):void 0);if(!i)throw Error(`No machine user is available for namespace "${t}". 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 Sn({configPath:e.configPath}),n=K.dirname(t.config.path),r=A(t.config,n);if(r.length===0)throw Error(`No TailorDB services with migrations configuration found.`);for(let e of r)j(e.migrationsDir,e.namespace);let i;e.data===`seed`&&(i=await ye({configPath:t.config.path}),assertSeedDataDirectory(K.join(i.distPath,`data`))),e.assertionPath&&assertAssertionScript(e.assertionPath);let a=t.application.tailorDBServices.map(be),s=await qe({profile:e.profile}),c=await et({profile:e.profile}),l=await On(s,c),u=await rt({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)]),h=o(d.workspace,`source workspace "${u}" not found`);o(f.application,`application "${t.config.name}" not found in source workspace`);let g=p?o(p.workspace,`target workspace "${e.targetWorkspaceId}" not found`):void 0,_=await we(l,u,r,t.config,a),v=_.find(e=>e.hasDrift||e.checkpointMissingLocal);if(v)throw Error(`Source namespace "${v.namespace}" does not match its migration checkpoint. Run 'tailor tailordb migration validate' first.`);let y=_.find(e=>e.checkpointRepair);if(y)throw Error(`Source namespace "${y.namespace}" has a pending migration checkpoint repair. Run 'tailor deploy' against the source workspace first.`);let b=new Map,x=new Map,S=[];for(let e of r){let t=await Ue(l,m(u,`tailordb`,e.namespace));if(t===null)throw Error(`Source namespace "${e.namespace}" has no sdk-migration checkpoint. Deploy or set its migration checkpoint before testing.`);let n=gt(e.migrationsDir);if(t>n)throw Error(`Source namespace "${e.namespace}" is at migration ${t}, but the local history ends at ${n}.`);let r=D(e.migrationsDir,t);if(!r)throw Error(`No migration baseline snapshot found for namespace "${e.namespace}".`);b.set(e.namespace,{migrationNumber:t,snapshot:r,historyId:r.rebaseline?.historyId??null});let i=D(e.migrationsDir,n);if(!i)throw Error(`No target migration snapshot found for namespace "${e.namespace}".`);x.set(e.namespace,i),t<n&&S.push(e.namespace)}if(S.length===0)throw Error(`No pending TailorDB migrations found in the source workspace.`);let C=await createMigrationTestBaselineSnapshots({client:l,workspaceId:u,dataMode:e.data,inputs:a,baselines:b}),ee={sourceWorkspaceId:u,sourceApplicationName:t.config.name,temporaryWorkspace:{name:temporaryWorkspaceName(),region:h.region,...h.organizationId?{organizationId:h.organizationId}:{},...h.folderId?{folderId:h.folderId}:{}},baselines:b,baselineSnapshots:C,targetSnapshots:x,pendingNamespaces:S,...g?{designatedTarget:{id:g.id,region:g.region}}:{}};return{state:{client:l,loaded:t,options:e,...i?{seedContext:i}:{}},prepared:ee}}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 wt(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 on({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 w(r.client,n,e,i.migrationNumber,i.historyId??void 0)},seedData:async({prepared:t,targetWorkspaceId:n})=>{let r=stateOrThrow(e),i=o(r.seedContext,`seed context missing after migration test preparation`),a=K.join(i.distPath,`data`);assertSeedDataDirectory(a);let s=new Map(r.loaded.application.tailorDBServices.map(e=>{let n=t.baselines.get(e.namespace),r=be(e);return[e.namespace,n?.snapshot??y({version:1,namespace:e.namespace,createdAt:new Date().toISOString(),tables:r.types})]}));for(let[e,t]of s){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 Ae(e,l,K.dirname(r.loaded.config.path)),d=Ce({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 Be({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 Error(i.error??`Seed execution failed for namespace "${e}".`);if(JSON.parse(i.result||`{}`).success!==!0)throw Error(`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?Error(`Application data clone is not enabled for this platform. Retry with '--data seed'.`,{cause:e}):e}if(!o)throw Error(`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 ht({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 _e(r,s,0,o.loaded.config.env??{},K.dirname(o.loaded.config.path)),u=await Be({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 Error(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 Error(`--target-workspace-id requires --yes because the target may be overwritten.`);if(e.keep&&e.targetWorkspaceId)throw Error(`--keep applies only to automatically created workspaces; a designated target is always retained.`);if(e.assertionNamespace&&!e.assertionPath)throw Error(`--assert is required when --assert-namespace is provided.`);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=o(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:o(e.targetWorkspaceId,`designated target workspace missing`),name:void 0},a,s=!1,l=!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,s=!0}if(r&&e.keep)c.info(`Keeping temporary workspace ${i.name??i.id}.`);else if(r)try{await t.deleteWorkspace(i.id),l=!0}catch(e){if(!s)throw Error(`Failed to delete temporary workspace ${i.id}: ${e instanceof Error?e.message:String(e)}`,{cause:e});c.warn(`Failed to delete temporary workspace ${i.id}: ${e instanceof Error?e.message:String(e)}`)}if(s)throw a;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){h(`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 ba=M({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({...P,yes:U(q.boolean().default(!1),{alias:`y`,description:`Acknowledge that a designated target workspace may be overwritten`}),data:U(q.enum([`seed`,`clone`]).default(`seed`),{description:`Data source for the migration test (seed or clone)`}),"target-workspace-id":U(q.uuid().optional(),{description:`Existing throwaway workspace to retain after the test (requires --yes)`}),keep:U(q.boolean().default(!1),{description:`Keep the automatically created workspace after the test`}),assert:U(q.string().optional(),{description:`Path to a TypeScript assertion script to run after migrations`,completion:{type:`file`,extensions:[`ts`]}}),"assert-namespace":U(q.string().optional(),{description:`TailorDB namespace exposed to the assertion script`}),"machine-user":U(q.string().optional(),{description:`Machine user for seed and assertion script execution`})}),run:async e=>{await k({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=[];for(let t of vt(e)){if(t.type!==`diff`)continue;let n=Yt(t.path),s=mn(e,t.number,`migrate`),c=Y.existsSync(s);n.requiresMigrationScript&&!n.scriptSkipped&&!c&&r.push(t.number),n.scriptSkipped&&c&&i.push(t.number),c&&Y.readFileSync(s,`utf8`).includes(`TODO(tailor-migration-review)`)&&a.push(t.number),n.hasWarnings&&!n.scriptSkipped&&!c&&o.push({migrationNumber:t.number,warnings:n.warnings})}if(r.length>0)throw Error(`Migration(s) ${r.map(R).join(`, `)} in namespace "${t}" require a migration script but have no migrate.ts. 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=>` ${le({migrationNumber:e,namespace:t,configPath:n})}`).join(`
|
|
94
|
+
`);throw Error(`Migration(s) ${i.map(R).join(`, `)} in namespace "${t}" have both a --no-script skip acknowledgment and migrate.ts. Clear the stale acknowledgment(s):
|
|
95
|
+
${e}\nOr delete migrate.ts to keep the skip.`)}if(a.length>0)throw Error(`Migration(s) ${a.map(R).join(`, `)} in namespace "${t}" contain generated normalization logic that still requires review in migrate.ts. Review each ${Pe} marker, then remove the marker and its associated \`never\` annotation.`);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 s=o(r.find(t=>t.namespace===e.namespace),`local schema check result missing for namespace "${e.namespace}"`),c={hasDiff:s.hasDiff,...s.diff?{diff:s.diff}:{}};if(i===void 0)return{namespace:e.namespace,valid:!1,migrationFiles:{valid:!0},localSchema:c,remoteSchema:{skipped:`check_failed`}};let l=o(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 B(e.configPath),r=K.dirname(t.path),i=A(t,r);if(i.length===0)throw Error(`No TailorDB services with migrations configuration found`);let a=e.namespace?i.filter(t=>t.namespace===e.namespace):i;if(a.length===0)throw Error(`Namespace "${e.namespace}" not found or does not have migrations configured`);let o=n.length>0?new Re(n):void 0,{defineApplication:s}=await import(`../application-fIhVKX78.mjs`),c=s({config:t,pluginManager:o});for(let e of c.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();tr({tailorDBServices:c.tailorDBServices});for(let{namespace:e}of a)if(!c.tailorDBServices.some(t=>t.namespace===e))throw Error(`No TailorDB service found for namespace "${e}"`);let l=c.tailorDBServices.map(be),u=new Map(l.map(e=>[e.namespace,e.types])),d=new Map,f=[],p=e.strict?new Map:void 0;for(let t of a)try{j(t.migrationsDir,t.namespace),D(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,e instanceof Error?e.message:String(e))}let m={targetNamespaces:a,migrationFileErrors:d,localResults:await x(u,f),...p?{unacknowledgedWarnings:p}:{}};if(f.length===0)return{reports:buildValidationReports(m)};let h;try{let{client:n,workspaceId:r}=await E({profile:e.profile,workspaceId:e.workspaceId});h=await we(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: ${l.bold(t.namespace)}`),!t.migrationFiles.valid){c.log(` Migration files: ${l.error(`invalid`)}`),c.log(` ${t.migrationFiles.error}`);continue}c.log(` Migration files: ${l.success(`OK`)}`);let e=t.localSchema;e?.hasDiff?e.diff?(c.log(` Local schema: ${l.error(`changes not in migration files`)}`),c.log(` ${te(e.diff)}`),c.log(S(e.diff))):c.log(` Local schema: ${l.error(`no migration snapshot found`)}`):c.log(` Local schema: ${l.success(`OK`)}`);let n=t.remoteSchema;n?.skipped===`check_failed`?c.log(` Remote schema: ${l.error(`not checked`)}`):n?.checkpointRepair?c.log(` Remote schema: ${l.success(`OK`)} (next deploy will reset the checkpoint to 0000 from ${R(n.checkpointRepair.from)})`):n?.checkpointMissingLocal?(c.log(` Remote schema: ${l.error(`remote migration ${R(n.remoteMigrationNumber)} is not in the local migration history`)}`),n.rebaselinePending&&c.log(` Fell behind before 'migration rebaseline' ran; must reach ${R(n.rebaselinePending.replacedLatestMigration)} first.`)):n?.hasDrift?(c.log(` Remote schema: ${l.error(`drift detected`)} (remote migration: ${R(n.remoteMigrationNumber)})`),c.log(ue(n.drifts))):n?.skipped===`not_deployed`?c.log(` Remote schema: ${l.dim(`skipped (namespace not deployed)`)}`):n?.skipped===`no_migration_label`?c.log(` Remote schema: ${l.dim(`skipped (deployed namespace has no migration state)`)}`):n?.skipped===`no_snapshot`?c.log(` Remote schema: ${l.dim(`skipped (no local snapshot for remote migration ${R(n.remoteMigrationNumber)})`)}`):n&&c.log(` Remote schema: ${l.success(`OK`)} (remote migration: ${R(n.remoteMigrationNumber)})`);let r=t.warningAcknowledgments;if(r){if(r.valid)c.log(` Warning acknowledgments: ${l.success(`OK`)}`);else{c.log(` Warning acknowledgments: ${l.error(`missing for pending migration(s) with possible data loss`)}`);for(let e of r.missing){let t=R(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&&p(n.map(e=>({namespace:e.namespace,remoteMigrationNumber:e.remoteSchema.remoteMigrationNumber,...e.remoteSchema.rebaselinePending?{rebaselinePending:e.remoteSchema.rebaselinePending}:{}}))),e.some(e=>e.remoteSchema?.hasDrift)&&Pt(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(` ${le({migrationNumber:n.migrationNumber,namespace:e.namespace,configPath:t,noScript:!0})}`,{mode:`plain`})}}async function validate(e){h(`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 Error(`Migration validation failed for ${r} namespace(s)`)}const xa=M({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({...P,namespace:U(q.string().optional(),{alias:`n`,description:`Target TailorDB namespace (validates all namespaces if not specified)`}),strict:U(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})}}),Sa=W({name:`migration`,description:`Manage TailorDB schema migrations.`,subCommands:{generate:ce,rebaseline:ga,script:ge,set:_a,status:va,sync:ya,test:ba,validate:xa}}),Ca=W({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:Nt,migration:Sa}}),wa=M({name:`upgrade`,description:`Run codemods to upgrade your project to a newer SDK version.`,args:q.strictObject({from:U(q.string(),{description:`SDK version before the upgrade (e.g., 1.33.0)`}),"dry-run":U(q.boolean().default(!1),{alias:`d`,description:`Preview changes without modifying files`}),path:U(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-CqbQXFDp.mjs`);await n({from:e.from,dryRun:e[`dry-run`],path:K.resolve(e.path)})}}),Ta=M({name:`current`,description:`Show current user.`,args:q.strictObject({profile:N.profile}),run:async e=>{let t=await d(),n=e.profile||process.env.TAILOR_PLATFORM_PROFILE,r=n?t.profiles[n]:void 0;if(n&&!r)throw Error(`Profile "${n}" not found`);let i=r?O(r):void 0,a=n?r?.user??null:t.current_user,o=c.jsonMode;if(!a)throw Error(H`
|
|
98
96
|
Current user not set.
|
|
99
97
|
Please login first using 'tailor login' command to register a user.
|
|
100
|
-
`);if(!
|
|
98
|
+
`);if(!Ve(t,a,i))throw Error(H`
|
|
101
99
|
Current user '${a}' not found in registered users.
|
|
102
100
|
Please login again using 'tailor login' command to register the user.
|
|
103
|
-
`);if(o){c.out({user:a});return}c.out(a)}});function activeCurrentUserKey(e,t){if(!t)return e.current_user?
|
|
101
|
+
`);if(o){c.out({user:a});return}c.out(a)}});function activeCurrentUserKey(e,t){if(!t)return e.current_user?Gt(e,e.current_user):null;let n=e.profiles[t];if(!n)throw Error(`Profile "${t}" not found`);return Gt(e,n.user,O(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 Ea=M({name:`list`,description:`List all users.`,args:q.strictObject({profile:N.profile}),run:async e=>{let t=await d(),n=c.jsonMode,r=activeCurrentUserKey(t,e.profile||process.env.TAILOR_PLATFORM_PROFILE),i=Object.keys(t.users);if(i.length===0){c.info(H`
|
|
104
102
|
No users found.
|
|
105
103
|
Please login first using 'tailor login' command to register a user.
|
|
106
|
-
`),n&&c.out([]);return}let a=i.map(e=>toUserListInfo(e,r));if(n){c.out([...new Set(a.map(e=>e.user))]);return}a.forEach(e=>{e.current?c.success(formatUserListInfo(e),{mode:`plain`}):c.log(formatUserListInfo(e))})}});function patScopeToString(e){switch(e){case n.PAT_SCOPE_READ:return`read`;case n.PAT_SCOPE_WRITE:return`write`;default:return`unknown`}}function transformPersonalAccessToken(e){return{name:e.name,scopes:e.scopes.map(patScopeToString),createdAt:
|
|
104
|
+
`),n&&c.out([]);return}let a=i.map(e=>toUserListInfo(e,r));if(n){c.out([...new Set(a.map(e=>e.user))]);return}a.forEach(e=>{e.current?c.success(formatUserListInfo(e),{mode:`plain`}):c.log(formatUserListInfo(e))})}});function patScopeToString(e){switch(e){case n.PAT_SCOPE_READ:return`read`;case n.PAT_SCOPE_WRITE:return`write`;default:return`unknown`}}function transformPersonalAccessToken(e){return{name:e.name,scopes:e.scopes.map(patScopeToString),createdAt:At(e.createdAt),lastUsedAt:At(e.lastUsedAt)}}function getScopesFromWriteFlag(e){return e?[n.PAT_SCOPE_READ,n.PAT_SCOPE_WRITE]:[n.PAT_SCOPE_READ]}function getScopeStringsFromWriteFlag(e){return e?[`read`,`write`]:[`read`]}function printCreatedToken(e,t,n,r){let i=getScopeStringsFromWriteFlag(n);c.jsonMode?c.out({name:e,scopes:i,token:t}):c.log(H`
|
|
107
105
|
Personal access token ${r} successfully.
|
|
108
106
|
|
|
109
107
|
name: ${e}
|
|
@@ -111,13 +109,13 @@ ${e}\nOr delete migrate.ts to keep the skip.`)}if(a.length>0)throw Error(`Migrat
|
|
|
111
109
|
token: ${t}
|
|
112
110
|
|
|
113
111
|
Please save this token in a secure location. You won't be able to see it again.
|
|
114
|
-
`)}async function createPatOperatorClient(e){let t=await
|
|
112
|
+
`)}async function createPatOperatorClient(e){let t=await qe({profile:e});return await On(t)}const Da=M({name:`create`,description:`Create a new personal access token.`,args:q.strictObject({name:U(q.string(),{positional:!0,description:`Token name`}),write:U(q.boolean().default(!1),{alias:`W`,description:`Grant write permission (default: read-only)`}),profile:N.profile}),run:async e=>{await k({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 Error(`Failed to create personal access token`);printCreatedToken(e.name,r.accessToken,e.write,`created`)}}),Oa=M({name:`delete`,description:`Delete a personal access token.`,args:q.strictObject({name:U(q.string(),{positional:!0,description:`Token name`}),profile:N.profile}),run:async e=>{await k({profile:e.profile}),await(await createPatOperatorClient(e.profile)).deletePersonalAccessToken({name:e.name}),c.success(`Personal access token "${e.name}" deleted successfully.`)}}),ka=M({name:`list`,description:`List all personal access tokens.`,args:q.strictObject({...F(),profile:N.profile}),run:async e=>{let t=c.jsonMode,n=await createPatOperatorClient(e.profile),r=z(e.order),i=await V(async(e,t)=>{let{personalAccessTokens:i,nextPageToken:a}=await n.listPersonalAccessTokens({pageToken:e,pageSize:t,pageDirection:r});return[i,a]},{limit:e.limit});if(i.length===0&&(c.info(H`
|
|
115
113
|
No personal access tokens found.
|
|
116
114
|
Please create a token using 'tailor user pat create' command.
|
|
117
|
-
`),!t))return;let a=i.map(transformPersonalAccessToken);c.out(a,{display:{scopes:e=>e.join(`/`),lastUsedAt:e=>e===null?`never`:
|
|
115
|
+
`),!t))return;let a=i.map(transformPersonalAccessToken);c.out(a,{display:{scopes:e=>e.join(`/`),lastUsedAt:e=>e===null?`never`:Et(e)}})}}),Aa=M({name:`update`,description:`Update a personal access token (delete and recreate).`,args:q.strictObject({name:U(q.string(),{positional:!0,description:`Token name`}),write:U(q.boolean().default(!1),{alias:`W`,description:`Grant write permission (if not specified, keeps read-only)`}),profile:N.profile}),run:async e=>{await k({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 Error(`Failed to create personal access token`);printCreatedToken(e.name,r.accessToken,e.write,`updated`)}}),ja=W({name:`pat`,description:`Manage personal access tokens.`,subCommands:{list:ka,create:Da,delete:Oa,update:Aa},async run(){await G(ka,[])}}),Ma=M({name:`switch`,description:`Set current user.`,args:q.strictObject({user:U(q.string(),{positional:!0,description:`User email address or machine user client ID`}),profile:N.profile}),run:async e=>{let t=await d(),n=e.profile||process.env.TAILOR_PLATFORM_PROFILE,r=n?t.profiles[n]:void 0;if(n&&!r)throw Error(`Profile "${n}" not found`);let i=r?O(r):void 0;if(e.user.includes(`|`))throw Error(`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.`);let a=un(t,e.user,i);if(!a)throw Error(H`
|
|
118
116
|
User "${e.user}" not found.
|
|
119
117
|
Please login first using 'tailor login' command to register this user.
|
|
120
|
-
`);r?r.user=a:t.current_user=a,
|
|
121
|
-
Run \`${
|
|
122
|
-
The \`setup\` commands are provided by the @tailor-platform/sdk-plugin-setup CLI plugin.`,subCommands:{api:
|
|
118
|
+
`);r?r.user=a:t.current_user=a,I(t),c.success(`Current user set to "${a}" successfully.`)}}),Na=W({name:`user`,description:`Manage Tailor Platform users.`,subCommands:{current:Ta,list:Ea,switch:Ma,pat:ja},async run(){await G(Ea,[])}}),Pa=W({name:`workflow`,description:`Manage workflows and workflow executions.`,subCommands:{list:De,get:Je,start:se,wait:vn,executions:he,resume:ee},async run(){await G(De,[])}}),Fa=W({name:`app`,description:`Manage workspace applications`,subCommands:{health:v,list:bn},async run(){await G(bn,[])}}),Ia=W({name:`user`,description:`Manage workspace users`,subCommands:{invite:St,list:pn,remove:pt,update:qt},async run(){await G(pn,[])}}),La=W({name:`workspace`,description:`Manage Tailor Platform workspaces.`,subCommands:{app:Fa,create:_t,delete:hn,get:Tt,list:zt,restore:Vt,user:Ia},async run(){await G(zt,[])}});await ln(new URL(`./ts-hook.mjs`,import.meta.url)),vr();const Ra=await ar(),za=Object.keys(Ra.bin??{})[0]||`tailor`,Ba=Ra.name??`@tailor-platform/sdk`,Va=await kr(import.meta.url),Ha=Or(Dr(Va),`agent-skills`);function defaultSkillsRunToAdd(e){let t=(e.subCommands??{}).add;return{...e,async run(){let e=await G(t,[]);if(!e.success)throw e.error}}}const Ua=Er(W({name:za,description:Ra.description||`Tailor CLI for managing Tailor Platform SDK applications`,notes:`CLI plugins (beta): an unknown subcommand is dispatched to an external plugin executable named \`${za}-<name>\` (found on your PATH or in node_modules/.bin), similar to \`gh\` extensions.
|
|
119
|
+
Run \`${za} plugin list\` to see which plugins are installed and where they resolve from.
|
|
120
|
+
The \`setup\` commands are provided by the @tailor-platform/sdk-plugin-setup CLI plugin.`,subCommands:{api:ni,auth:ai,authconnection:fi,crashreport:hi,deploy:gi,executor:_i,function:Di,generate:Oi,init:ki,login:Mi,logout:Ni,machineuser:Pi,oauth2client:Fi,open:Ii,organization:Ri,plugin:Ui,profile:Ji,query:ct,remove:fe,secret:sa,show:Ge,staticwebsite:ma,tailordb:Ca,upgrade:wa,user:Na,workflow:Pa,workspace:La}}),{sourceDir:Ha,package:Ba,mode:`copy`,descriptionAppend:!1,globalArgs:q.object(an),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.`}}),Wa=Tr({...Ua,subCommands:{...Ua.subCommands,skills:defaultSkillsRunToAdd(Ua.subCommands.skills)}});Cr(Wa,{version:Ra.version,globalArgs:q.object(an),displayErrors:!1,onUnknownSubcommand:({commandPath:e,name:t,args:n})=>dispatchPluginWithInstallHint({commandPath:e,name:t,args:n,cliName:za,profile:process.env.TAILOR_PLATFORM_PROFILE}),cleanup:async({error:e})=>{if(e){if(c.jsonMode)c.log(en(e,{includeStack:c.verbose}));else if(cr(e))c.log(e.format()),c.verbose&&e.stack&&c.debug(`\nStack trace:\n${e.stack}`);else if(e instanceof Error){c.error(e.message);let t=ur(e);t&&c.log(` ${l.info(`Suggestion:`)} ${t}`),c.verbose&&e.stack&&c.debug(`\nStack trace:\n${e.stack}`)}else c.error(`Unknown error: ${e}`);if(!cr(e)&&(!(e instanceof Error)||e instanceof TypeError||e instanceof RangeError)){let{reportCrash:t}=await import(`../crashreport-By23O2k-.mjs`);await t(e,`handledError`)}}let{shutdownTelemetry:t}=await import(`../telemetry-DXHP3VVi.mjs`);await t()}});export{Wa as mainCommand};
|
|
123
121
|
//# sourceMappingURL=main.mjs.map
|