@tailor-platform/sdk 2.30.0 → 2.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/dist/ai/index.d.mts +112 -0
  3. package/dist/ai/index.mjs +2 -0
  4. package/dist/ai/index.mjs.map +1 -0
  5. package/dist/aigateway-DsWDjzk4.mjs.map +1 -1
  6. package/dist/application-D0xNJbag.mjs.map +1 -1
  7. package/dist/assert-WeXvmG4j.mjs.map +1 -1
  8. package/dist/authconnection-CynFBIv8.mjs.map +1 -1
  9. package/dist/brand-C8nMKhJC.mjs.map +1 -1
  10. package/dist/cli/lib.mjs +1 -1
  11. package/dist/cli/lib.mjs.map +1 -1
  12. package/dist/cli/main.mjs +6 -6
  13. package/dist/cli/main.mjs.map +1 -1
  14. package/dist/completion/zsh-worker.zsh +6 -2
  15. package/dist/configure/index.mjs.map +1 -1
  16. package/dist/context-D0QjfxzD.mjs.map +1 -1
  17. package/dist/crashreport-BCIy33Cz.mjs.map +1 -1
  18. package/dist/date-CgP7gMG_.mjs.map +1 -1
  19. package/dist/date-representation-Cr7W7Pn2.mjs.map +1 -1
  20. package/dist/errors-BOF68LJ5.mjs.map +1 -1
  21. package/dist/es-builtins-SfvXRVoG.mjs.map +1 -1
  22. package/dist/field-parse-C41e3UAF.mjs.map +1 -1
  23. package/dist/file-DKBOj5q4.mjs.map +1 -1
  24. package/dist/globals-BCmGX05J.mjs.map +1 -1
  25. package/dist/guards-yDXyKC9F.mjs.map +1 -1
  26. package/dist/iconv-DlFMt2gW.mjs.map +1 -1
  27. package/dist/idp-G_ojPBB5.mjs.map +1 -1
  28. package/dist/interceptor-DQg3cR_9.mjs.map +1 -1
  29. package/dist/kysely/index.mjs.map +1 -1
  30. package/dist/{kysely-type-BWMfV301.mjs → kysely-type-CBwsdx16.mjs} +6 -3
  31. package/dist/kysely-type-CBwsdx16.mjs.map +1 -0
  32. package/dist/logger-DP2BjQ93.mjs.map +1 -1
  33. package/dist/logger-RgtbhJ83.mjs.map +1 -1
  34. package/dist/manager-Bk-7vkwd.mjs.map +1 -1
  35. package/dist/migration-steps-C6F3zNdQ.mjs.map +1 -1
  36. package/dist/multiline-EyzjEwn9.mjs.map +1 -1
  37. package/dist/node-builtins-DYfhPBnz.mjs.map +1 -1
  38. package/dist/package-json-C690ceex.mjs.map +1 -1
  39. package/dist/platform-serialize-DkiTdHOt.mjs.map +1 -1
  40. package/dist/plugin/builtin/enum-constants/index.mjs.map +1 -1
  41. package/dist/plugin/builtin/file-utils/index.mjs.map +1 -1
  42. package/dist/plugin/builtin/kysely-type/index.mjs +1 -1
  43. package/dist/plugin/index.mjs.map +1 -1
  44. package/dist/{register-ts-hook-CDnN_Jx2.mjs → register-ts-hook-_dHIREtU.mjs} +127 -89
  45. package/dist/register-ts-hook-_dHIREtU.mjs.map +1 -0
  46. package/dist/registry-BijIDRVA.mjs.map +1 -1
  47. package/dist/repl-editor-DGJBfIt1.mjs.map +1 -1
  48. package/dist/schema-B6hJQWp6.mjs.map +1 -1
  49. package/dist/secret-file-C9wp_FCX.mjs.map +1 -1
  50. package/dist/secretmanager-vHQoXdQz.mjs.map +1 -1
  51. package/dist/seed/index.mjs.map +1 -1
  52. package/dist/seed-Cn-3JApy.mjs.map +1 -1
  53. package/dist/service-9SBPNpK8.mjs.map +1 -1
  54. package/dist/service-9rwi_I4d.mjs.map +1 -1
  55. package/dist/service_pb-Bbu2QSIr.mjs.map +1 -1
  56. package/dist/telemetry-DfT2UfI4.mjs +2 -0
  57. package/dist/telemetry-DfT2UfI4.mjs.map +1 -0
  58. package/dist/{telemetry-DpkFGBmu.mjs → telemetry-nqOtDWNO.mjs} +1 -1
  59. package/dist/type-source--ZNcV8RJ.mjs.map +1 -1
  60. package/dist/user-agent-vdHYF3QL.mjs.map +1 -1
  61. package/dist/utils/test/index.mjs.map +1 -1
  62. package/dist/vitest/environment.mjs.map +1 -1
  63. package/dist/vitest/index.mjs.map +1 -1
  64. package/dist/vitest/setup.mjs.map +1 -1
  65. package/dist/wait-point-invoker-eiP-IIux.mjs.map +1 -1
  66. package/dist/wait-point-registry-B-ESkTZX.mjs.map +1 -1
  67. package/dist/workflow-Cs9ISw6j.mjs.map +1 -1
  68. package/dist/workspace_resource_pb-CaoM2npP.mjs.map +1 -1
  69. package/docs/ai.md +92 -0
  70. package/docs/cli/tailordb.md +17 -15
  71. package/docs/cli/workspace.md +1 -1
  72. package/docs/github-actions.md +98 -11
  73. package/docs/services/tailordb/migration.md +45 -31
  74. package/docs/testing.md +2 -1
  75. package/package.json +16 -9
  76. package/dist/kysely-type-BWMfV301.mjs.map +0 -1
  77. package/dist/register-ts-hook-CDnN_Jx2.mjs.map +0 -1
  78. package/dist/telemetry-Xk7J829P.mjs +0 -2
  79. package/dist/telemetry-Xk7J829P.mjs.map +0 -1
package/dist/cli/main.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
- import{r as e}from"../field-parse-C41e3UAF.mjs";import{At as t,E as n,J as r,K as i,Lt as a,Wt as o}from"../workspace_resource_pb-CaoM2npP.mjs";import{t as s}from"../assert-WeXvmG4j.mjs";import{O as c,g as l,i as u,r as d}from"../service-9SBPNpK8.mjs";import{a as f,l as p,n as m,u as h}from"../logger-RgtbhJ83.mjs";import{$n as g,$t as _,Ai as v,Bi as y,Bn as b,Br as ee,Ci as x,Cn as S,Cr as te,D as ne,Di as re,Dr as ie,Dt as ae,Ei as oe,Er as se,F as ce,Fi as le,G as ue,Gi as de,Gn as fe,Gt as pe,H as me,Hi as C,Hn as he,I as ge,Ii as _e,In as ve,It as ye,J as be,Jn as xe,Jt as Se,K as Ce,Ki as we,Kn as Te,Kr as Ee,Kt as De,L as w,Li as Oe,Ln as ke,Lr as Ae,M as je,Mi as Me,Ni as Ne,Oi as Pe,Or as Fe,P as Ie,Pi as T,Pn as Le,Pt as Re,Q as ze,Qi as Be,Qn as Ve,Qr as He,Ri as Ue,Rn as We,Rr as Ge,Rt as Ke,S as qe,Si as Je,Sn as Ye,Sr as Xe,T as Ze,Ti as Qe,Tr as $e,Tt as et,Ui as tt,Un as nt,Ur as rt,Ut as it,V as at,Vi as E,Vn as ot,Vr as st,Vt as ct,Wn as lt,Wr as ut,Wt as dt,X as ft,Xi as pt,Xn as mt,Xr as ht,Yi as D,Yn as gt,Yr as _t,Zi as vt,Zn as yt,Zr as bt,Zt as xt,_i as St,_n as Ct,_r as O,_t as wt,a as Tt,aa as k,ai as Et,an as Dt,ar as Ot,b as kt,bi as At,br as jt,c as Mt,ca as Nt,ci as Pt,cn as Ft,cr as It,ct as Lt,di as Rt,dn as zt,dr as Bt,dt as Vt,ea as Ht,ei as Ut,en as Wt,er as Gt,et as Kt,f as qt,fi as Jt,fn as Yt,fr as Xt,ft as Zt,g as Qt,gi as A,gn as $t,gr as en,gt as tn,hi as j,hn as nn,hr as rn,ia as an,ii as on,in as sn,ir as cn,it as ln,ji as un,jt as dn,k as fn,ki as pn,kr as M,la as N,li as mn,ln as hn,lr as gn,m as _n,mi as P,mn as vn,mr as yn,mt as bn,n as xn,na as Sn,ni as Cn,nn as wn,nr as Tn,nt as En,o as Dn,oa as On,oi as kn,or as An,ot as jn,pi as F,pn as Mn,pr as Nn,qi as I,qn as Pn,qr as Fn,qt as In,ra as Ln,ri as Rn,rr as zn,sa as Bn,si as L,sn as Vn,sr as Hn,t as Un,ta as Wn,ti as R,tn as Gn,tr as Kn,u as qn,ui as Jn,un as Yn,ur as Xn,v as Zn,vi as z,vn as Qn,vr as $n,vt as er,w as tr,wi as nr,wr as rr,wt as ir,xi as ar,xr as or,xt as sr,yi as B,yn as cr,yr as V,yt as lr,z as ur,zi as dr,zn as fr}from"../register-ts-hook-CDnN_Jx2.mjs";import{$ as pr,B as mr,C as hr,F as gr,G as _r,H as vr,I as yr,L as br,P as xr,Q as Sr,R as Cr,S as wr,T as Tr,U as Er,V as Dr,W as Or,X as kr,Z as Ar,_ as jr,at as Mr,c as Nr,dt as Pr,g as Fr,l as Ir,lt as Lr,nt as Rr,o as zr,ot as Br,p as Vr,rt as Hr,s as Ur,st as Wr,tt as Gr,ut as Kr,w as qr,y as Jr,yt as Yr}from"../application-D0xNJbag.mjs";import{t as H}from"../multiline-EyzjEwn9.mjs";import{a as Xr,i as Zr,n as Qr,o as $r,r as U,s as ei,t as W}from"../errors-BOF68LJ5.mjs";import{t as ti}from"../package-json-C690ceex.mjs";import{t as ni}from"../user-agent-vdHYF3QL.mjs";import{t as ri}from"../service_pb-Bbu2QSIr.mjs";import{a as ii,i as ai,o as oi,r as si,t as ci}from"../crashreport-BCIy33Cz.mjs";import{t as li}from"../manager-Bk-7vkwd.mjs";import{a as ui,i as di,n as fi}from"../kysely-type-BWMfV301.mjs";import{arg as G,defineCommand as K,extractFields as pi,runMain as mi,toCamelCase as hi}from"@politty/zod";import{withCompletionCommand as gi}from"@politty/zod/completion";import{withSkillCommand as _i}from"@politty/zod/skill";import*as q from"pathe";import{dirname as vi,resolve as yi}from"pathe";import{resolvePackageJSON as bi}from"pkg-types";import{z as J}from"zod";import{ScalarType as Y,create as xi}from"@bufbuild/protobuf";import*as X from"node:fs";import{accessSync as Si,constants as Ci,readdirSync as wi}from"node:fs";import{timestampDate as Ti}from"@bufbuild/protobuf/wkt";import{Code as Z,ConnectError as Q}from"@connectrpc/connect";import{pathToFileURL as Ei}from"node:url";import{generateCodeVerifier as Di}from"@badgateway/oauth2-client";import*as Oi from"node:crypto";import{randomBytes as ki}from"node:crypto";import*as Ai from"node:http";import ji from"open";import*as Mi from"rolldown";import{parseSync as Ni}from"oxc-parser";import*as Pi from"node:os";import*as $ from"node:fs/promises";import{setTimeout as Fi}from"node:timers/promises";import{spawn as Ii,spawnSync as Li}from"node:child_process";import{TraceMap as Ri,generatedPositionFor as zi,originalPositionFor as Bi}from"@jridgewell/trace-mapping";const Vi=ri.methods.filter(e=>e.methodKind===`unary`);function listMethodNames(){return Vi.map(e=>e.name).toSorted()}function listMethodChoices(){return Vi.flatMap(e=>[e.name,`${ri.typeName}/${e.name}`]).toSorted()}function getMethodDescriptor(e){return Vi.find(t=>t.name===e)}function extractMethodName(e){return e.includes(`/`)?e.split(`/`).pop()??e:e}function nestedMessage(e){if(e.fieldKind===`message`||e.fieldKind===`list`&&e.listKind===`message`||e.fieldKind===`map`&&e.mapKind===`message`)return e.message}function isWellKnownType(e){return e.typeName.startsWith(`google.protobuf.`)}const Hi=/* @__PURE__ */ new Set([`google.protobuf.Struct`,`google.protobuf.Value`,`google.protobuf.ListValue`,`google.protobuf.NullValue`,`google.protobuf.Any`,`google.protobuf.Empty`]);function isUnrepresentableWellKnownType(e){return Hi.has(e.typeName)}function enumerateAllFieldCompletions(e){let t=getMethodDescriptor(e);if(!t)return[];let n=[],r=/* @__PURE__ */ new Set;function walk(e,t){r.add(e);for(let i of e.fields){if(i.fieldKind===`list`||i.fieldKind===`map`)continue;let e=t+i.localName;if(i.fieldKind===`message`){if(isUnrepresentableWellKnownType(i.message))continue;if(!isWellKnownType(i.message)){let t=i.message;n.push({value:`${e}.`,description:`${e} (message)`}),r.has(t)||walk(t,`${e}.`);continue}}if(n.push({value:`${e}=`,description:`Set ${e}`}),i.fieldKind===`enum`)for(let t of i.enum.values)n.push({value:`${e}=${t.name}`,description:t.name});else i.fieldKind===`scalar`&&i.scalar===Y.BOOL&&(n.push({value:`${e}=true`,description:`true`}),n.push({value:`${e}=false`,description:`false`}))}r.delete(e)}return walk(t.input,``),n}function resolveLeafField(e,t){let n=e;for(let e=0;e<t.length;e++){let r=n.fields.find(n=>n.localName===t[e]);if(!r)return;if(e===t.length-1)return r.fieldKind===`message`&&isUnrepresentableWellKnownType(r.message)?void 0:r;if(r.fieldKind!==`message`||isWellKnownType(r.message))return;n=r.message}}const Ui={[Y.DOUBLE]:`double`,[Y.FLOAT]:`float`,[Y.INT64]:`int64`,[Y.UINT64]:`uint64`,[Y.INT32]:`int32`,[Y.FIXED64]:`fixed64`,[Y.FIXED32]:`fixed32`,[Y.BOOL]:`bool`,[Y.STRING]:`string`,[Y.BYTES]:`bytes`,[Y.UINT32]:`uint32`,[Y.SFIXED32]:`sfixed32`,[Y.SFIXED64]:`sfixed64`,[Y.SINT32]:`sint32`,[Y.SINT64]:`sint64`};function shortName(e){let t=e.lastIndexOf(`.`);return t<0?e:e.slice(t+1)}function scalarLabel(e){return Ui[e]??`scalar(${e})`}function enumLabel(e){return`enum ${shortName(e.typeName)}`}function enumOf(e){if(e.fieldKind===`enum`||e.fieldKind===`list`&&e.listKind===`enum`)return e.enum}function describeFieldType(e){switch(e.fieldKind){case`scalar`:return scalarLabel(e.scalar);case`enum`:return enumLabel(e.enum);case`message`:return shortName(e.message.typeName);case`list`:{let t;return t=e.listKind===`scalar`?scalarLabel(e.scalar):e.listKind===`enum`?enumLabel(e.enum):shortName(e.message.typeName),`repeated ${t}`}case`map`:{let t=scalarLabel(e.mapKey),n;return n=e.mapKind===`scalar`?scalarLabel(e.scalar):e.mapKind===`enum`?enumLabel(e.enum):shortName(e.message.typeName),`map<${t}, ${n}>`}default:return`<unknown>`}}function fieldToJson(e,t){let n={name:e.localName,protoName:e.name,type:describeFieldType(e),fieldKind:e.fieldKind,repeated:e.fieldKind===`list`};e.oneof&&(n.oneof=e.oneof.name);let r=enumOf(e);r&&(n.enumValues=r.values.map(e=>e.name));let i=nestedMessage(e);return i&&!t.has(i)?(t.add(i),n.message={typeName:i.typeName,fields:i.fields.map(e=>fieldToJson(e,t))},t.delete(i)):i&&(n.message={typeName:i.typeName,fields:[],recursive:!0}),n}function renderInspectJson(e){let t=/* @__PURE__ */ new Set([e.input]);return{method:e.name,input:{typeName:e.input.typeName,fields:e.input.fields.map(e=>fieldToJson(e,t))},output:{typeName:e.output.typeName}}}function renderFieldText(e,t,n){let r=[],i=e.oneof?` (oneof ${e.oneof.name})`:``;r.push(`${t}${e.localName}: ${describeFieldType(e)}${i}`);let a=enumOf(e);if(a){let e=a.values.map(e=>e.name).join(`, `);r.push(`${t} values: ${e}`)}let o=nestedMessage(e);if(o&&!n.has(o)){n.add(o);for(let e of o.fields)r.push(...renderFieldText(e,`${t} `,n));n.delete(o)}else o&&r.push(`${t} …(recursive ${o.typeName})`);return r}function renderInspectText(e){let t=[];t.push(`${e.name}`),t.push(` request: ${e.input.typeName}`);let n=/* @__PURE__ */ new Set([e.input]);for(let r of e.input.fields)t.push(...renderFieldText(r,` `,n));return t.push(` response: ${e.output.typeName}`),t.join(`
2
+ import{r as e}from"../field-parse-C41e3UAF.mjs";import{At as t,E as n,J as r,K as i,Lt as a,Wt as o}from"../workspace_resource_pb-CaoM2npP.mjs";import{t as s}from"../assert-WeXvmG4j.mjs";import{O as c,g as l,i as u,r as d}from"../service-9SBPNpK8.mjs";import{a as f,l as p,n as m,u as h}from"../logger-RgtbhJ83.mjs";import{$n as g,$t as _,Ai as v,Bi as y,Bn as b,Br as ee,Ci as x,Cn as S,Cr as te,D as ne,Di as re,Dr as ie,Dt as ae,Ei as oe,Er as se,F as ce,Fi as le,G as ue,Gi as de,Gn as fe,Gt as pe,H as me,Hi as C,Hn as he,I as ge,Ii as _e,In as ve,It as ye,J as be,Jn as xe,Jt as Se,K as Ce,Ki as we,Kn as Te,Kr as Ee,Kt as De,L as w,Li as Oe,Ln as ke,Lr as Ae,M as je,Mi as Me,Ni as Ne,Oi as Pe,Or as Fe,P as Ie,Pi as T,Pn as Le,Pt as Re,Q as ze,Qi as Be,Qn as Ve,Qr as He,Ri as Ue,Rn as We,Rr as Ge,Rt as Ke,S as qe,Si as Je,Sn as Ye,Sr as Xe,T as Ze,Ti as Qe,Tr as $e,Tt as et,Ui as tt,Un as nt,Ur as rt,Ut as it,V as at,Vi as E,Vn as ot,Vr as st,Vt as ct,Wn as lt,Wr as ut,Wt as dt,X as ft,Xi as pt,Xn as mt,Xr as ht,Yi as D,Yn as gt,Yr as _t,Zi as vt,Zn as yt,Zr as bt,Zt as xt,_i as St,_n as Ct,_r as O,_t as wt,a as Tt,aa as k,ai as Et,an as Dt,ar as Ot,b as kt,bi as At,br as jt,c as Mt,ca as Nt,ci as Pt,cn as Ft,cr as It,ct as Lt,di as Rt,dn as zt,dr as Bt,dt as Vt,ea as Ht,ei as Ut,en as Wt,er as Gt,et as Kt,f as qt,fi as Jt,fn as Yt,fr as Xt,ft as Zt,g as Qt,gi as A,gn as $t,gr as en,gt as tn,hi as j,hn as nn,hr as rn,ia as an,ii as on,in as sn,ir as cn,it as ln,ji as un,jt as dn,k as fn,ki as pn,kr as M,la as N,li as mn,ln as hn,lr as gn,m as _n,mi as P,mn as vn,mr as yn,mt as bn,n as xn,na as Sn,ni as Cn,nn as wn,nr as Tn,nt as En,o as Dn,oa as On,oi as kn,or as An,ot as jn,pi as F,pn as Mn,pr as Nn,qi as I,qn as Pn,qr as Fn,qt as In,ra as Ln,ri as Rn,rr as zn,sa as Bn,si as L,sn as Vn,sr as Hn,t as Un,ta as Wn,ti as R,tn as Gn,tr as Kn,u as qn,ui as Jn,un as Yn,ur as Xn,v as Zn,vi as z,vn as Qn,vr as $n,vt as er,w as tr,wi as nr,wr as rr,wt as ir,xi as ar,xr as or,xt as sr,yi as B,yn as cr,yr as V,yt as lr,z as ur,zi as dr,zn as fr}from"../register-ts-hook-_dHIREtU.mjs";import{$ as pr,B as mr,C as hr,F as gr,G as _r,H as vr,I as yr,L as br,P as xr,Q as Sr,R as Cr,S as wr,T as Tr,U as Er,V as Dr,W as Or,X as kr,Z as Ar,_ as jr,at as Mr,c as Nr,dt as Pr,g as Fr,l as Ir,lt as Lr,nt as Rr,o as zr,ot as Br,p as Vr,rt as Hr,s as Ur,st as Wr,tt as Gr,ut as Kr,w as qr,y as Jr,yt as Yr}from"../application-D0xNJbag.mjs";import{t as H}from"../multiline-EyzjEwn9.mjs";import{a as Xr,i as Zr,n as Qr,o as $r,r as U,s as ei,t as W}from"../errors-BOF68LJ5.mjs";import{t as ti}from"../package-json-C690ceex.mjs";import{t as ni}from"../user-agent-vdHYF3QL.mjs";import{t as ri}from"../service_pb-Bbu2QSIr.mjs";import{a as ii,i as ai,o as oi,r as si,t as ci}from"../crashreport-BCIy33Cz.mjs";import{t as li}from"../manager-Bk-7vkwd.mjs";import{a as ui,i as di,n as fi}from"../kysely-type-CBwsdx16.mjs";import{arg as G,defineCommand as K,extractFields as pi,runMain as mi,toCamelCase as hi}from"@politty/zod";import{withCompletionCommand as gi}from"@politty/zod/completion";import{withSkillCommand as _i}from"@politty/zod/skill";import*as q from"pathe";import{dirname as vi,resolve as yi}from"pathe";import{resolvePackageJSON as bi}from"pkg-types";import{z as J}from"zod";import{ScalarType as Y,create as xi}from"@bufbuild/protobuf";import*as X from"node:fs";import{accessSync as Si,constants as Ci,readdirSync as wi}from"node:fs";import{timestampDate as Ti}from"@bufbuild/protobuf/wkt";import{Code as Z,ConnectError as Q}from"@connectrpc/connect";import{pathToFileURL as Ei}from"node:url";import{generateCodeVerifier as Di}from"@badgateway/oauth2-client";import*as Oi from"node:crypto";import{randomBytes as ki}from"node:crypto";import*as Ai from"node:http";import ji from"open";import*as Mi from"rolldown";import{parseSync as Ni}from"oxc-parser";import*as Pi from"node:os";import*as $ from"node:fs/promises";import{setTimeout as Fi}from"node:timers/promises";import{spawn as Ii,spawnSync as Li}from"node:child_process";import{TraceMap as Ri,generatedPositionFor as zi,originalPositionFor as Bi}from"@jridgewell/trace-mapping";const Vi=ri.methods.filter(e=>e.methodKind===`unary`);function listMethodNames(){return Vi.map(e=>e.name).toSorted()}function listMethodChoices(){return Vi.flatMap(e=>[e.name,`${ri.typeName}/${e.name}`]).toSorted()}function getMethodDescriptor(e){return Vi.find(t=>t.name===e)}function extractMethodName(e){return e.includes(`/`)?e.split(`/`).pop()??e:e}function nestedMessage(e){if(e.fieldKind===`message`||e.fieldKind===`list`&&e.listKind===`message`||e.fieldKind===`map`&&e.mapKind===`message`)return e.message}function isWellKnownType(e){return e.typeName.startsWith(`google.protobuf.`)}const Hi=/* @__PURE__ */ new Set([`google.protobuf.Struct`,`google.protobuf.Value`,`google.protobuf.ListValue`,`google.protobuf.NullValue`,`google.protobuf.Any`,`google.protobuf.Empty`]);function isUnrepresentableWellKnownType(e){return Hi.has(e.typeName)}function enumerateAllFieldCompletions(e){let t=getMethodDescriptor(e);if(!t)return[];let n=[],r=/* @__PURE__ */ new Set;function walk(e,t){r.add(e);for(let i of e.fields){if(i.fieldKind===`list`||i.fieldKind===`map`)continue;let e=t+i.localName;if(i.fieldKind===`message`){if(isUnrepresentableWellKnownType(i.message))continue;if(!isWellKnownType(i.message)){let t=i.message;n.push({value:`${e}.`,description:`${e} (message)`}),r.has(t)||walk(t,`${e}.`);continue}}if(n.push({value:`${e}=`,description:`Set ${e}`}),i.fieldKind===`enum`)for(let t of i.enum.values)n.push({value:`${e}=${t.name}`,description:t.name});else i.fieldKind===`scalar`&&i.scalar===Y.BOOL&&(n.push({value:`${e}=true`,description:`true`}),n.push({value:`${e}=false`,description:`false`}))}r.delete(e)}return walk(t.input,``),n}function resolveLeafField(e,t){let n=e;for(let e=0;e<t.length;e++){let r=n.fields.find(n=>n.localName===t[e]);if(!r)return;if(e===t.length-1)return r.fieldKind===`message`&&isUnrepresentableWellKnownType(r.message)?void 0:r;if(r.fieldKind!==`message`||isWellKnownType(r.message))return;n=r.message}}const Ui={[Y.DOUBLE]:`double`,[Y.FLOAT]:`float`,[Y.INT64]:`int64`,[Y.UINT64]:`uint64`,[Y.INT32]:`int32`,[Y.FIXED64]:`fixed64`,[Y.FIXED32]:`fixed32`,[Y.BOOL]:`bool`,[Y.STRING]:`string`,[Y.BYTES]:`bytes`,[Y.UINT32]:`uint32`,[Y.SFIXED32]:`sfixed32`,[Y.SFIXED64]:`sfixed64`,[Y.SINT32]:`sint32`,[Y.SINT64]:`sint64`};function shortName(e){let t=e.lastIndexOf(`.`);return t<0?e:e.slice(t+1)}function scalarLabel(e){return Ui[e]??`scalar(${e})`}function enumLabel(e){return`enum ${shortName(e.typeName)}`}function enumOf(e){if(e.fieldKind===`enum`||e.fieldKind===`list`&&e.listKind===`enum`)return e.enum}function describeFieldType(e){switch(e.fieldKind){case`scalar`:return scalarLabel(e.scalar);case`enum`:return enumLabel(e.enum);case`message`:return shortName(e.message.typeName);case`list`:{let t;return t=e.listKind===`scalar`?scalarLabel(e.scalar):e.listKind===`enum`?enumLabel(e.enum):shortName(e.message.typeName),`repeated ${t}`}case`map`:{let t=scalarLabel(e.mapKey),n;return n=e.mapKind===`scalar`?scalarLabel(e.scalar):e.mapKind===`enum`?enumLabel(e.enum):shortName(e.message.typeName),`map<${t}, ${n}>`}default:return`<unknown>`}}function fieldToJson(e,t){let n={name:e.localName,protoName:e.name,type:describeFieldType(e),fieldKind:e.fieldKind,repeated:e.fieldKind===`list`};e.oneof&&(n.oneof=e.oneof.name);let r=enumOf(e);r&&(n.enumValues=r.values.map(e=>e.name));let i=nestedMessage(e);return i&&!t.has(i)?(t.add(i),n.message={typeName:i.typeName,fields:i.fields.map(e=>fieldToJson(e,t))},t.delete(i)):i&&(n.message={typeName:i.typeName,fields:[],recursive:!0}),n}function renderInspectJson(e){let t=/* @__PURE__ */ new Set([e.input]);return{method:e.name,input:{typeName:e.input.typeName,fields:e.input.fields.map(e=>fieldToJson(e,t))},output:{typeName:e.output.typeName}}}function renderFieldText(e,t,n){let r=[],i=e.oneof?` (oneof ${e.oneof.name})`:``;r.push(`${t}${e.localName}: ${describeFieldType(e)}${i}`);let a=enumOf(e);if(a){let e=a.values.map(e=>e.name).join(`, `);r.push(`${t} values: ${e}`)}let o=nestedMessage(e);if(o&&!n.has(o)){n.add(o);for(let e of o.fields)r.push(...renderFieldText(e,`${t} `,n));n.delete(o)}else o&&r.push(`${t} …(recursive ${o.typeName})`);return r}function renderInspectText(e){let t=[];t.push(`${e.name}`),t.push(` request: ${e.input.typeName}`);let n=/* @__PURE__ */ new Set([e.input]);for(let r of e.input.fields)t.push(...renderFieldText(r,` `,n));return t.push(` response: ${e.output.typeName}`),t.join(`
3
3
  `)}const Wi=C({name:`inspect`,description:`Print the input message tree of an OperatorService endpoint.`,notes:"Combine with the global `--json` flag for a machine-readable descriptor. Recursive type references and `oneof` membership are annotated. Use `tailor api list` to discover endpoint names.",examples:[{cmd:`GetApplication`,desc:`Show fields of GetApplicationRequest.`},{cmd:`CreateExecutorExecutor`,desc:"Inspect a deeply nested input with `(oneof config)` annotations."}],args:J.strictObject({endpoint:G(J.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 W({code:`API_METHOD_UNKNOWN`,message:`unknown method: ${t}`,suggestion:"Run `tailor api list` to see available methods.",command:`api inspect`});f.jsonMode?f.out(renderInspectJson(n)):f.out(renderInspectText(n))}}),Gi=C({name:`list`,description:`List all invocable OperatorService methods.`,notes:`Only single-request (non-streaming) methods are listed, because the CLI issues a single JSON request and reads one JSON response.`,args:J.strictObject({}),run:()=>{let e=listMethodNames();if(f.jsonMode)f.out(e);else for(let t of e)f.out(t)}});function resolveNamespaceName(e,t){if(/Auth|Tenant|UserProfile/.test(e))return t.auth?.name;if(/IdP/.test(e))return t.idp?.length===1?s(t.idp[0],`idp config missing`).name:void 0;if(/TailorDB/.test(e)){let e=Object.keys(t.db??{});return e.length===1?e[0]:void 0}if(/Pipeline/.test(e)){let e=Object.keys(t.resolver??{});return e.length===1?e[0]:void 0}}function parseBodyAsObject(e){let t;try{t=JSON.parse(e)}catch{return}if(typeof t==`object`&&t&&!Array.isArray(t))return t}function setNestedPath(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){let n=s(t[e],`path segment missing`),i=r[n];(typeof i!=`object`||!i||Array.isArray(i))&&(r[n]={}),r=r[n]}r[s(t[t.length-1],`path last segment missing`)]=n}function coerceFieldValue(e,t){if(e&&e.fieldKind===`scalar`&&e.scalar===Y.BOOL){if(t===`true`)return!0;if(t===`false`)return!1;throw W({code:`API_FIELD_VALUE_INVALID`,message:`Invalid value for bool field: '${t}'. Expected 'true' or 'false'.`,command:`api`})}return t}function normalizeBodyFieldKeys(e,t){let n=/* @__PURE__ */ new Map;for(let e of t)n.set(e.name,e.localName),n.set(e.jsonName,e.localName);let r=!1;for(let t of Object.keys(e)){let i=n.get(t);i&&i!==t&&(Object.hasOwn(e,i)||(e[i]=e[t]),delete e[t],r=!0)}return r}const Ki=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`]),qi=J.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'`}),J.NEVER;let r=e.slice(0,n);if(r.length===0)return t.addIssue({code:`custom`,message:`Field key cannot be empty`}),J.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`}),J.NEVER;let a=i.find(e=>Ki.has(e));return a?(t.addIssue({code:`custom`,message:`Invalid field key: '${r}'. Segment '${a}' is not allowed.`}),J.NEVER):{path:i,value:e.slice(n+1)}}),Ji=C({name:`api`,description:`Call Tailor Platform API endpoints directly.`,notes:"Use `tailor api list` to enumerate invocable methods and `tailor api inspect <endpoint>` to print an endpoint's input message tree (combine with `--json` for machine-readable output).\n\nThe request body is inferred from the target endpoint's request schema, and commonly required fields are auto-injected so they can be omitted from `--body`:\n\n- `workspaceId` — resolved from `-w` / `TAILOR_PLATFORM_WORKSPACE_ID` / the selected profile.\n- `namespaceName` — resolved from `tailor.config.ts` based on the endpoint's service:\n - Auth / Tenant / UserProfile endpoints use `auth.name`.\n - IdP / TailorDB / Pipeline endpoints use the sole configured namespace when exactly one is defined.\n\nValues already present in `--body` are never overridden. If a value cannot be resolved (e.g. no config found), injection is silently skipped and the server-side validation error takes precedence.\n\nUse `--field key=value` (repeatable) to set request body fields without writing JSON. Dotted keys (e.g. `application.name=foo`) build nested objects. `--field` overrides matching fields in `--body` and tab-completes from the endpoint's request schema.",examples:[{cmd:`GetApplication -b '{"applicationName":"app-1"}'`,desc:`Call an endpoint; workspaceId is auto-injected.`},{cmd:`GetApplication -f applicationName=app-1`,desc:`Same as above, using --field instead of --body.`},{cmd:`list`,desc:`List all invocable OperatorService methods.`},{cmd:`inspect GetApplication`,desc:`Show the input message tree for an endpoint.`}],subCommands:{list:Gi,inspect:Wi},args:J.strictObject({...N,...we,body:G(J.string().default(`{}`),{alias:`b`,description:`Request body as JSON.`}),field:G(qi.array().optional(),{alias:`f`,description:"Set a body field as `key=value` (repeatable; dotted keys nest). Overrides --body.",completion:{custom:{expand:{dependsOn:[`endpoint`],enumerate:({endpoint:e})=>enumerateAllFieldCompletions(extractMethodName(e??``))}}}}),endpoint:G(J.string(),{positional:!0,description:`API endpoint to call (e.g., 'GetApplication' or 'tailor.v1.OperatorService/GetApplication').`,completion:{custom:{choices:listMethodChoices()}}})}),run:async e=>{await z({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 W({code:`API_OPTIONS_INVALID`,message:`--field requires --body to be a JSON object (or omitted).`,command:`api`});for(let t of e.field){let e=n?resolveLeafField(n.input,t.path):void 0;setNestedPath(r,t.path,coerceFieldValue(e,t.value))}i=!0}if(r&&n){normalizeBodyFieldKeys(r,n.input.fields)&&(i=!0);let a=n.input.fields.map(e=>e.localName);if(a.includes(`workspaceId`)&&!Object.hasOwn(r,`workspaceId`))try{r.workspaceId=await un({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 St({profile:e.profile,endpoint:e.endpoint,body:i&&r?JSON.stringify(r):e.body});f.out(JSON.stringify(a.data,null,2))}}),Yi=C({name:`status`,description:`Show the active Tailor Platform authentication status without printing tokens.`,args:J.strictObject({profile:N.profile}),run:async({profile:e})=>{let t=await Qe({profile:e});if(f.out(t),!t.authenticated)throw W({code:`NOT_AUTHENTICATED`,message:`Not authenticated.`,suggestion:`Log in and try again.`,next:{command:`tailor`,args:[`login`,...k({profile:e})]}})}}),Xi=C({name:`token`,description:`Print a valid Tailor Platform access token to stdout, refreshing it first if expired.`,args:J.strictObject({profile:N.profile}),run:async({profile:e})=>{let t=await nr({profile:e});f.out(t)}}),Zi=K({name:`auth`,description:`Authentication helpers for scripts and plugins.`,subCommands:{status:Yi,token:Xi}}),Qi={name:G(J.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 W({code:`OIDC_DISCOVERY_FAILED`,message:`Failed to fetch OIDC discovery from ${t}: ${$r(e).message}`,cause:e})});if(!n.ok)throw W({code:`OIDC_DISCOVERY_FAILED`,message:`Failed to fetch OIDC discovery from ${t}: ${n.status}`});return n.json()}function randomState$1(){return Oi.randomBytes(32).toString(`base64url`)}const $i=C({name:`authorize`,description:`Authorize an auth connection via OAuth2 flow.`,args:J.strictObject({...N,...Qi,scopes:J.string().optional().default(`openid,profile,email`).describe(`OAuth2 scopes to request (comma-separated)`),port:J.coerce.number().optional().default(8080).describe(`Local callback server port`),"no-browser":J.boolean().optional().default(!1).describe(`Don't open browser automatically`)}),run:async e=>{await z({profile:e.profile});let t=U({command:`tailor`,args:[`authconnection`,`open`,...k({profile:e.profile,workspaceId:e[`workspace-id`]})]}),{client:n,workspaceId:r}=await j({profile:e.profile,workspaceId:e[`workspace-id`]}),i=(await Sr(async(e,t)=>{let{connections:i,nextPageToken:a}=await n.listAuthConnections({workspaceId:r,pageToken:e,pageSize:t});return[i,a]})).find(t=>t.name===e.name);if(!i)throw W({code:`AUTH_CONNECTION_NOT_FOUND`,message:`Auth connection "${e.name}" not found.`});if(i.config.case!==`oauth2`)throw W({code:`AUTH_CONNECTION_NOT_OAUTH2`,message:`Auth connection "${e.name}" is not an OAuth2 connection.`});let a=i.config.value,o=`http://localhost:${e.port}/callback`,s=randomState$1(),c;c=a.authUrl?a.authUrl:(await fetchOIDCDiscovery(a.providerUrl)).authorization_endpoint;let l=new URL(c);l.searchParams.set(`client_id`,a.clientId),l.searchParams.set(`redirect_uri`,o),l.searchParams.set(`response_type`,`code`),l.searchParams.set(`scope`,e.scopes.replace(/,/g,` `)),l.searchParams.set(`state`,s),l.searchParams.set(`access_type`,`offline`),await new Promise((i,a)=>{let handleCallback=async(t,l)=>{if(!t.url?.startsWith(`/callback`))l.writeHead(404),l.end(`Not found`);else try{let a=new URL(t.url,`http://localhost:${e.port}`),u=a.searchParams.get(`code`),d=a.searchParams.get(`state`),p=a.searchParams.get(`error`);if(p)throw W({code:`AUTHORIZATION_FAILED`,message:`Authorization failed: ${p}`});if(d!==s)throw W({code:`AUTHORIZATION_STATE_MISMATCH`,message:`State mismatch — possible CSRF attack.`});if(!u)throw W({code:`AUTHORIZATION_CODE_MISSING`,message:`No authorization code received.`});f.registerSecret(u),await n.exchangeAuthConnectionAuthorizationCode({workspaceId:r,connectionName:e.name,authorizationCode:u,redirectUri:o}),l.writeHead(200,{"Content-Type":`text/html`}),l.end(`<html><body><h1>Authorization successful</h1><p>You can close this window.</p></body></html>`),c.close(),i()}catch(e){l.writeHead(400,{"Content-Type":`text/plain`}),l.end(`Authorization failed: ${e instanceof Error?e.message:`Unknown error`}`),c.close(),a($r(e))}},c=Ai.createServer((e,t)=>void handleCallback(e,t)),u=setTimeout(()=>{c.close(),a(W({code:`AUTHORIZATION_TIMEOUT`,message:`Authorization timeout exceeded (5 minutes).`}))},3e5);c.on(`close`,()=>{clearTimeout(u)}),c.on(`error`,n=>{clearTimeout(u);let r=n.code,i=r===`EADDRINUSE`||r===`EACCES`?`Try a different port with --port, or authorize via the Console instead:`:`Authorize via the Console instead:`;f.warn(`Could not start the local callback server on port ${e.port}${r?` (${r})`:``}.\n${i}\n ${t}`),a(n)});let announceAuthorizeUrl=async()=>{let n=l.toString();if(f.info(e[`no-browser`]?`Open this URL in your browser to authorize:\n\n${n}\n`:`Opening browser for authorization:\n\n${n}\n`),f.info(`If this flow doesn't complete, you can authorize via the Console instead:\n ${t}`),!e[`no-browser`])try{await ji(n)}catch{f.warn(`Failed to open browser automatically. Please open the URL above manually.`)}};c.listen(e.port,()=>void announceAuthorizeUrl())}),f.success(`Auth connection "${e.name}" authorized successfully.`),A({changed:!0,workspaceId:r,name:e.name})}}),ea=C({name:`delete`,description:`Delete an auth connection entirely.`,args:J.strictObject({...N,...Qi,...I}),run:async e=>{await z({profile:e.profile});let{client:t,workspaceId:n}=await j({profile:e.profile,workspaceId:e[`workspace-id`]});if(!e.yes&&await P.text({message:`Enter the connection name to confirm deletion ("${e.name}"):`})!==e.name)throw W({code:`AUTH_CONNECTION_DELETION_CANCELLED`,message:`Auth connection deletion cancelled: the entered name did not match.`,suggestion:`Run the command again and enter the name exactly as shown, or pass --yes to skip the confirmation.`});try{await t.deleteAuthConnection({workspaceId:n,connectionName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?W({code:`AUTH_CONNECTION_NOT_FOUND`,message:`Auth connection "${e.name}" not found.`,cause:t}):t}f.success(`Auth connection "${e.name}" deleted.`),A({changed:!0,workspaceId:n,name:e.name})}});function connectionInfo(e){let t=e.config.case===`oauth2`?e.config.value:void 0;return{name:e.name,type:e.config.case??`unknown`,providerUrl:t?.providerUrl??``,issuerUrl:t?.issuerUrl??``,clientId:t?.clientId??``,authUrl:t?.authUrl??``,tokenUrl:t?.tokenUrl??``,createdAt:e.createdAt?Ti(e.createdAt):null}}const ta=C({name:`list`,description:`List all auth connections.`,args:J.strictObject({...N,...Ln()}),run:async e=>{let{client:t,workspaceId:n}=await j({profile:e.profile,workspaceId:e[`workspace-id`]});try{let r=Nt(e.order),i=await Jt(e.limit,e=>Gr(async(e,i)=>{let{connections:a,nextPageToken:o}=await t.listAuthConnections({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e}));f.out(i.items.map(connectionInfo)),await F(i,e.limit)}catch(e){if(e instanceof Q&&e.code===Z.NotFound){f.out([]);return}throw e}}}),na=C({name:`open`,description:`Open the auth connections page in the Tailor Platform Console.`,args:J.strictObject({...N}),run:async e=>{let t=await un({workspaceId:e[`workspace-id`],profile:e.profile}),n=`/workspaces/${t}/services/auth-connections`,r=await re({profile:e.profile,...e[`workspace-id`]===void 0?{}:{allowMissingProfile:!0}}),i=new URL(n,r).toString(),a=f.jsonMode;f.info(`Opening auth connections page in Tailor Platform Console...`);let o=!0;try{await ji(i)}catch{o=!1}a?f.out({consoleUrl:i,workspaceId:t,opened:o}):o?(f.out(`Console URL: ${i}`),f.out(`Workspace ID: ${t}`)):f.warn(`Failed to open browser automatically. Please open this URL manually:\n${i}`)}}),ra=C({name:`revoke`,description:`Revoke an auth connection's tokens (keeps the connection; use 'delete' to remove it).`,notes:"Revoke invalidates the connection's active session and tokens but keeps the connection and its stored credentials, so it can be re-authorized later. Use `delete` to remove the connection entirely.",args:J.strictObject({...N,...Qi,...I}),run:async e=>{await z({profile:e.profile});let{client:t,workspaceId:n}=await j({profile:e.profile,workspaceId:e[`workspace-id`]});if(!e.yes&&await P.text({message:`Enter the connection name to confirm revocation ("${e.name}"):`})!==e.name)throw W({code:`AUTH_CONNECTION_REVOCATION_CANCELLED`,message:`Auth connection revocation cancelled: the entered name did not match.`,suggestion:`Run the command again and enter the name exactly as shown, or pass --yes to skip the confirmation.`});try{await t.revokeAuthConnection({workspaceId:n,connectionName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?W({code:`AUTH_CONNECTION_NOT_FOUND`,message:`Auth connection "${e.name}" not found.`,cause:t}):t}f.success(`Auth connection "${e.name}" revoked.`),A({changed:!0,workspaceId:n,name:e.name})}}),ia=K({name:`authconnection`,description:`Manage auth connections.`,subCommands:{authorize:$i,list:ta,open:na,revoke:ra,delete:ea},defaultSubCommand:`list`});function orderAndLimitCrashReports(e,t){let n=e.filter(e=>e.endsWith(ai)).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:q.join(t,e)}))}const aa=C({name:`list`,description:`List local crash report files.`,args:J.strictObject({...Ln()}),run:async e=>{let t=oi(),n=f.jsonMode;if(!t.localDir){f.info(`Crash report directory not available.`),n&&f.out([]);return}let r;try{r=X.readdirSync(t.localDir)}catch{f.info(`No crash reports found.`),n&&f.out([]);return}let i=await Jt(e.limit,async t=>orderAndLimitCrashReports(r,{order:e.order,limit:t})),a=i.items;if(a.length===0)f.info(`No crash reports found.`),n&&f.out([]);else if(n)f.out(formatCrashReportFiles(a,t.localDir)),await F(i,e.limit);else{f.info(`${a.length} crash report(s) in ${t.localDir}:`);for(let e of a)f.log(` ${e}`);await F(i,e.limit)}}}),oa=C({name:`send`,description:`Submit a crash report to help improve the SDK.`,args:J.strictObject({file:G(J.string(),{description:`Path to the crash report file`,required:!0,completion:{type:`file`,extensions:[`log`]}})}),run:async e=>{let t;try{t=X.readFileSync(e.file,`utf-8`)}catch{f.error(`Crash report file not found: ${e.file}`),process.exit(1)}let n=parseCrashLogFile(t);n||(f.error(`Failed to parse crash report file. The file may be corrupted.`),process.exit(1));let r=await ni();f.info(`Sending crash report...`),await si(n,r)?(f.success(`Crash report submitted successfully. Thank you!`),A({changed:!0,id:n.id,file:e.file})):(f.error(`Failed to submit crash report. The server may be unavailable.`),process.exit(1))}});function parseCrashLogFile(e){try{let t=e.replace(/\r\n/g,`
4
4
  `),n=`\n${ii}\n`,r=t.lastIndexOf(n);if(r===-1)return;let i=t.slice(r+n.length).split(`
5
5
  `)[0];return i?JSON.parse(i):void 0}catch{return}}const sa=K({name:`crashreport`,description:`Manage crash reports.`,subCommands:{list:aa,send:oa},defaultSubCommand:`list`});function delay(e){return e>0?new Promise(t=>setTimeout(t,e)):Promise.resolve()}function assertSeedDataDirectory(e){let t;try{t=X.statSync(e)}catch(t){throw t.code===`ENOENT`?W({code:`SEED_DATA_NOT_FOUND`,message:`Seed data directory not found: ${e}.`,suggestion:`Generate seed data before testing migrations.`,cause:t}):t}if(!t.isDirectory())throw W({code:`SEED_DATA_INVALID`,message:`Seed data path is not a directory: ${e}`})}function assertAssertionScript(e){let t=q.resolve(e),n;try{n=X.statSync(t)}catch(e){throw e.code===`ENOENT`?W({code:`MIGRATION_ASSERTION_SCRIPT_NOT_FOUND`,message:`Migration assertion script not found: ${t}`,cause:e}):e}if(!n.isFile())throw W({code:`MIGRATION_ASSERTION_SCRIPT_INVALID`,message:`Migration assertion path is not a file: ${t}`})}function assertCloneTargetRegion(e,t){if(e!==t)throw W({code:`MIGRATION_TEST_REGION_MISMATCH`,message:`Clone mode requires source and target workspaces in the same region (source: ${e}, target: ${t}).`})}function assertTargetWorkspaceDiffers(e,t){if(t?.toLowerCase()===e.toLowerCase())throw W({code:`MIGRATION_TEST_TARGET_INVALID`,message:`The migration test target workspace must differ from the source workspace.`,command:`tailordb migration test`})}function resolveAssertionNamespace(e,t){let n=t??(e.length===1?e[0]:void 0);if(!n)throw W({code:`MIGRATION_TEST_ASSERT_NAMESPACE_REQUIRED`,message:`--assert-namespace is required when pending migrations span multiple namespaces.`,command:`tailordb migration test`});if(!e.includes(n))throw W({code:`MIGRATION_TEST_NO_PENDING_MIGRATIONS`,message:`Assertion namespace "${n}" has no pending migrations.`});return n}async function createMigrationTestBaselineSnapshots(e){let t=new Map([...e.baselines].map(([e,t])=>[e,t.snapshot]));if(e.dataMode!==`clone`)return t;let n=e.inputs.filter(e=>!t.has(e.namespace)),r=await Promise.all(n.map(t=>We(e.client,e.workspaceId,t.namespace)));return n.forEach((e,n)=>{t.set(e.namespace,s(r[n],`remote snapshot missing for "${e.namespace}"`))}),t}async function waitForCloneApplicationData(e,t){let n=t.pollInterval??3e3,r=t.timeout??18e5,i=t.errorCodePrefix??`MIGRATION_TEST_CLONE`,a=Date.now()+r,s;for(let c=r;c>0;c=a-Date.now()){let r;try{r=await e.getCloneApplicationDataOperation({sourceWorkspaceId:t.sourceWorkspaceId,targetWorkspaceId:t.targetWorkspaceId,operationId:t.operationId},Number.isFinite(c)?{timeoutMs:c}:void 0)}catch(e){if(e instanceof Q&&e.code===Z.DeadlineExceeded&&Date.now()>=a-100)break;throw e}if(r.status===o.COMPLETED)return;if(r.status===o.FAILED)throw W({code:`${i}_FAILED`,message:`Application data clone failed: ${r.errorMessage||`unknown platform error`}`});if(r.status!==o.PENDING&&r.status!==o.PROCESSING)throw Zr(`Application data clone returned unexpected status ${r.status}.`);r.status!==s&&(s=r.status,t.onStatus?.(r.status)),await delay(Math.min(n,Math.max(a-Date.now(),0)))}throw W({code:`${i}_TIMEOUT`,message:`Application data clone timed out after ${r<1e3?`${r} ms`:`${Math.round(r/1e3)} seconds`}.`,context:{operationId:t.operationId,sourceWorkspaceId:t.sourceWorkspaceId,targetWorkspaceId:t.targetWorkspaceId}})}function loadSnapshotSeedData(e,t,n){let r={};for(let i of t){let t=n?.tables[i],a=q.join(e,`${i}.jsonl`),o;try{o=X.readFileSync(a,`utf8`).trim()}catch(e){if(e.code===`ENOENT`){r[i]=[];continue}throw e}r[i]=o?o.split(`
6
- `).map((e,n)=>{let r;try{r=JSON.parse(e)}catch(e){throw W({code:`SEED_DATA_INVALID`,message:`Invalid JSON in ${a} at line ${n+1}: ${e instanceof Error?e.message:String(e)}`,cause:e})}if(typeof r!=`object`||!r||Array.isArray(r))throw W({code:`SEED_DATA_INVALID`,message:`Invalid seed row in ${a} at line ${n+1}: expected a JSON object`});let i=r;return t?projectSeedObject(i,t.fields,/* @__PURE__ */ new Set([`id`])):i}):[]}return r}function projectSeedObject(e,t,n=/* @__PURE__ */ new Set){return Object.fromEntries(Object.entries(e).flatMap(([e,r])=>{let i=t[e];return i?[[e,projectSeedValue(r,i)]]:n.has(e)?[[e,r]]:[]}))}function projectSeedValue(e,t){let n=t.fields;return n?t.array?Array.isArray(e)?e.map(e=>isJsonObject(e)?projectSeedObject(e,n):e):e:isJsonObject(e)?projectSeedObject(e,n):e:e}function isJsonObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function sortSeedTypesForSnapshot(e){let t=Object.keys(e.tables),n=new Set(t),r=/* @__PURE__ */ new Map,i=[];for(let[t,a]of Object.entries(e.tables)){let e=/* @__PURE__ */ new Set;for(let r of Object.values(a.fields)){let a=r.foreignKeyType;a&&(a===t?i.push(t):n.has(a)&&e.add(a))}r.set(t,[...e])}let a=/* @__PURE__ */ new Set,o=[],visit=e=>{if(!a.has(e)){a.add(e);for(let t of r.get(e)??[])visit(t);o.push(e)}};for(let e of t)visit(e);return{order:o,selfRefTypes:i}}function temporaryWorkspaceName(){return`migration-test-${(/* @__PURE__ */ new Date()).toISOString().replace(/[-:T.Z]/g,``).slice(0,14)}-${ki(3).toString(`hex`)}`}function stateOrThrow(e){return s(e,`migration test runtime was used before preparation`)}async function resolveSourceMigrationNumber(e,t,n,r,i,a){if(r.number!==null)return r.number;if(!r.metadataExists)throw W({code:`MIGRATION_TEST_SOURCE_CHECKPOINT_MISSING`,message:`Source namespace "${n.namespace}" has not been deployed.`,suggestion:`Deploy to the source workspace before testing.`});let o=M(n.migrationsDir,0);if(!o)throw W({code:`MIGRATION_BASELINE_NOT_FOUND`,message:`No migration baseline snapshot found for namespace "${n.namespace}".`});let s=await ke(e,t,n.namespace,o,i,a);if(s.length>0)throw W({code:`MIGRATION_TEST_SOURCE_INVALID`,message:`Source namespace "${n.namespace}" has no migration label and its schema differs from the initial migration snapshot (0000).`,details:$e(s),suggestion:`Bring the source schema in line with 0000 or set its migration label.`});return 0}async function assertSourceBaselineFresh(e,t,n){let r=e.loaded,i=V(r.config,q.dirname(r.config.path)),a=r.application.tailorDBServices.map(he),o=(await nt(e.client,n,i,r.config,a)).find(e=>e.hasDrift||e.checkpointMissingLocal||e.checkpointRepair);if(o)throw W({code:`MIGRATION_TEST_SOURCE_CHANGED`,message:`Source namespace "${o.namespace}" changed after migration test preparation.`,suggestion:`Run the migration test again.`});for(let o of i){let i=t.baselines.get(o.namespace);if(!i)continue;let s=await O(e.client,L(n,`tailordb`,o.namespace));en(s,o.namespace);let c=await resolveSourceMigrationNumber(e.client,n,o,s,r.config,a);if(c!==i.migrationNumber)throw W({code:`MIGRATION_TEST_SOURCE_CHANGED`,message:`Source namespace "${o.namespace}" moved from migration ${i.migrationNumber} to ${c} after migration test preparation.`,suggestion:`Run the migration test again.`})}let s=a.filter(e=>!t.baselines.has(e.namespace));for(let r of s){let i=t.baselineSnapshots.get(r.namespace);if(!i)continue;let a=await We(e.client,n,r.namespace);if(He(i,a).changes.length>0)throw W({code:`MIGRATION_TEST_SOURCE_CHANGED`,message:`Source namespace "${r.namespace}" schema changed after migration test preparation.`,suggestion:`Run the migration test again.`})}}async function deleteExistingUserProfileConfig(e,t){let n=e.loaded.application.authService;if(!n)return;let r=n.config.name;await Br(()=>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 W({code:`AUTH_CONFIG_REQUIRED`,message:`Auth configuration is required to execute migration test scripts.`});let i=n??gt(migrationConfig(e.loaded,t),r.config.machineUsers?Object.keys(r.config.machineUsers):void 0);if(!i)throw W({code:`MACHINE_USER_REQUIRED`,message:`No machine user is available for namespace "${t}".`,suggestion:`Pass --machine-user or configure one in auth or db.${t}.migration.`});return{authNamespace:r.config.name,machineUserName:i}}async function prepareMigrationTest(e){let t=await dt({configPath:e.configPath}),n=q.dirname(t.config.path),r=V(t.config,n);if(r.length===0)throw jt();for(let e of r)Fe(e.migrationsDir,e.namespace);let i;e.data===`seed`&&(i=await it({configPath:t.config.path}),assertSeedDataDirectory(q.join(i.distPath,`data`))),e.assertionPath&&assertAssertionScript(e.assertionPath);let a=t.application.tailorDBServices.map(he),o=await nr({profile:e.profile}),c=await pn({profile:e.profile}),l=await Kr(o,c),u=await un({workspaceId:e.workspaceId,profile:e.profile});assertTargetWorkspaceDiffers(u,e.targetWorkspaceId);let[d,f,p]=await Promise.all([l.getWorkspace({workspaceId:u}),l.getApplication({workspaceId:u,applicationName:t.config.name}),e.data===`clone`&&e.targetWorkspaceId?l.getWorkspace({workspaceId:e.targetWorkspaceId}):Promise.resolve(void 0)]),m=s(d.workspace,`source workspace "${u}" not found`);s(f.application,`application "${t.config.name}" not found in source workspace`);let h=p?s(p.workspace,`target workspace "${e.targetWorkspaceId}" not found`):void 0,g=await nt(l,u,r,t.config,a),_=g.find(e=>e.hasDrift||e.checkpointMissingLocal);if(_)throw W({code:`MIGRATION_TEST_SOURCE_INVALID`,message:`Source namespace "${_.namespace}" does not match its migration checkpoint.`,suggestion:`Validate the migration history first.`});let v=g.find(e=>e.checkpointRepair);if(v)throw W({code:`MIGRATION_TEST_SOURCE_REPAIR_PENDING`,message:`Source namespace "${v.namespace}" has a pending migration checkpoint repair.`,suggestion:`Deploy to the source workspace first.`});let y=/* @__PURE__ */ new Map,b=/* @__PURE__ */ new Map,ee=[];for(let e of r){let n=await O(l,L(u,`tailordb`,e.namespace));en(n,e.namespace);let r=await resolveSourceMigrationNumber(l,u,e,n,t.config,a),i=st(e.migrationsDir);if(r>i)throw W({code:`MIGRATION_TEST_SOURCE_AHEAD`,message:`Source namespace "${e.namespace}" is at migration ${r}, but the local history ends at ${i}.`});let o=M(e.migrationsDir,r);if(!o)throw W({code:`MIGRATION_BASELINE_NOT_FOUND`,message:`No migration baseline snapshot found for namespace "${e.namespace}".`});y.set(e.namespace,{migrationNumber:r,snapshot:o,historyId:o.rebaseline?.historyId??null});let s=M(e.migrationsDir,i);if(!s)throw W({code:`MIGRATION_TEST_SNAPSHOT_NOT_FOUND`,message:`No target migration snapshot found for namespace "${e.namespace}".`});b.set(e.namespace,s),r<i&&ee.push(e.namespace)}if(ee.length===0)throw W({code:`MIGRATION_TEST_NO_PENDING_MIGRATIONS`,message:`No pending TailorDB migrations found in the source workspace.`});let x=await createMigrationTestBaselineSnapshots({client:l,workspaceId:u,dataMode:e.data,inputs:a,baselines:y}),S={sourceWorkspaceId:u,sourceApplicationName:t.config.name,temporaryWorkspace:{name:temporaryWorkspaceName(),region:m.region,...m.organizationId?{organizationId:m.organizationId}:{},...m.folderId?{folderId:m.folderId}:{}},baselines:y,baselineSnapshots:x,targetSnapshots:b,pendingNamespaces:ee,...h?{designatedTarget:{id:h.id,region:h.region}}:{}};return{state:{client:l,loaded:t,options:e,...i?{seedContext:i}:{}},prepared:S}}function createMigrationTestDependencies(){let e;return{prepare:async t=>{let{state:n,prepared:r}=await prepareMigrationTest(t);return e=n,r},createWorkspace:async t=>{let n=stateOrThrow(e),r=await Dt(n.client,t.temporaryWorkspace);return f.info(`Created temporary workspace ${r.name} (${r.id}).`),{id:r.id,name:r.name,...r.createdAt?{createdAt:r.createdAt}:{}}},recordWorkspaceExpiry:async(t,n,r=/* @__PURE__ */ new Date)=>{let i=stateOrThrow(e);await Ct(i.client,t,new Date(r.getTime()+cr(n)))},deployBaseline:async({prepared:t,targetWorkspaceId:n})=>{let r=stateOrThrow(e);await deleteExistingUserProfileConfig(r,n),await Wt({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 mt(r.client,n,e,i.migrationNumber,i.historyId??void 0)},seedData:async({prepared:t,targetWorkspaceId:n})=>{let r=stateOrThrow(e),i=s(r.seedContext,`seed context missing after migration test preparation`),a=q.join(i.distPath,`data`);assertSeedDataDirectory(a);let o=new Map(r.loaded.application.tailorDBServices.map(e=>{let n=t.baselines.get(e.namespace),r=he(e);return[e.namespace,n?.snapshot??Ut({version:1,namespace:e.namespace,createdAt:(/* @__PURE__ */ new Date()).toISOString(),tables:r.types})]}));for(let[e,t]of o){let{order:o,selfRefTypes:s}=sortSeedTypesForSnapshot(t),c=loadSnapshotSeedData(a,o,t),l=o.filter(e=>(c[e]?.length??0)>0);if(l.length===0)continue;let u=await xt(e,l,q.dirname(r.loaded.config.path)),d=In({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 Se({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 W({code:`MIGRATION_TEST_SEED_FAILED`,message:i.error??`Seed execution failed for namespace "${e}".`});if(JSON.parse(i.result||`{}`).success!==!0)throw W({code:`MIGRATION_TEST_SEED_FAILED`,message:`Seed execution reported failure for namespace "${e}".`})}}},cloneData:async({prepared:t,sourceWorkspaceId:n,targetWorkspaceId:r,applicationName:i,cloneTimeout:a})=>{let o=stateOrThrow(e);await assertSourceBaselineFresh(o,t,n),f.warn(`Clone mode copies TailorDB records only; IdP users and file blobs are not copied.`);let s;try{s=(await o.client.cloneApplicationData({sourceWorkspaceId:n,sourceApplicationName:i,targetWorkspaceId:r,targetApplicationName:i})).operationId}catch(e){throw e instanceof Q&&e.code===Z.Unimplemented?W({code:`MIGRATION_TEST_CLONE_UNAVAILABLE`,message:`Application data clone is not enabled for this platform.`,suggestion:`Retry with --data seed.`,cause:e}):e}if(!s)throw Zr(`Application data clone returned no operation ID.`);await waitForCloneApplicationData(o.client,{sourceWorkspaceId:n,targetWorkspaceId:r,operationId:s,timeout:a})},deployMigrations:async({prepared:t,targetWorkspaceId:n})=>{let r=stateOrThrow(e);await Gn({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 Bt(r,s,0,o.loaded.config.env??{},q.dirname(o.loaded.config.path),De(o.loaded.plugins,`@tailor-platform/kysely-type`)?.temporal??!1,Nr(o.loaded.config)),u=await Se({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 W({code:`MIGRATION_TEST_ASSERTION_FAILED`,message:u.error??`Migration assertion failed for namespace "${s}".`})},deleteWorkspace:async t=>{await stateOrThrow(e).client.deleteWorkspace({workspaceId:t})}}}const ca={from:G(J.string(),{description:`Workspace ID to copy data from`,completion:{type:`none`}}),to:G(J.string(),{description:`Workspace ID to copy data to`,completion:{type:`none`}})};function resumeCommandArgs(e){return[`data`,`operation`,`get`,`--from`,e.sourceWorkspaceId,`--to`,e.targetWorkspaceId,`--operation-id`,e.operationId,`--wait`,...k({profile:e.profile})]}function resumeHint(e){return U({command:`tailor`,args:resumeCommandArgs(e)})}async function hintOnInterrupt(e,t){let onInterrupt=()=>{f.info(`Stopped waiting. The clone keeps running on the platform. To wait for it: ${resumeHint(e)}`)};process.once(`SIGINT`,onInterrupt);try{return await t()}finally{process.off(`SIGINT`,onInterrupt)}}const la={[o.PENDING]:`pending`,[o.PROCESSING]:`processing`,[o.COMPLETED]:`completed`,[o.FAILED]:`failed`};function statusName(e){return la[e]??`unknown`}function reportStatus(e){f.info(`status: ${statusName(e)}`,{mode:`stream`})}function formatElapsed(e){let t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n>0?`${n}h ${r}m`:r>0?`${r}m ${i}s`:`${i}s`}async function $clone(e){let t=vt(e.config),n=t?[t]:[];if(e.sourceWorkspaceId===e.targetWorkspaceId)throw W({code:`DATA_CLONE_SAME_WORKSPACE`,message:`The source and target workspaces must be different.`,command:`data clone`});let r=await Kr(await nr({profile:e.profile}));try{await r.getApplication({workspaceId:e.targetWorkspaceId,applicationName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?W({code:`DATA_CLONE_TARGET_APPLICATION_NOT_FOUND`,message:`Application "${e.name}" was not found in the target workspace "${e.targetWorkspaceId}".`,suggestion:e.nameFromConfig?`Check --to and that you have access to the target workspace, and deploy the application to it first so it has the same namespaces and schema.`:`Check --to and that you have access to the target workspace, and deploy the application "${e.name}" to it first so it has the same namespaces and schema.`,...e.nameFromConfig?{next:{command:`tailor`,args:[`deploy`,...k({workspaceId:e.targetWorkspaceId,profile:e.profile}),...n]}}:{},command:`data clone`,cause:t}):t}if(!e.yes&&!await P.confirm({message:`This will copy the data of application "${e.name}" from workspace "${e.sourceWorkspaceId}" to workspace "${e.targetWorkspaceId}". Continue?`,default:!1}))throw W({code:`DATA_CLONE_CANCELLED`,message:`Data clone cancelled.`});let i;try{i=(await r.cloneApplicationData({sourceWorkspaceId:e.sourceWorkspaceId,sourceApplicationName:e.name,targetWorkspaceId:e.targetWorkspaceId,targetApplicationName:e.name,copyFiles:e.copyFiles,copyIdpUsers:e.copyIdpUsers})).operationId}catch(t){throw t instanceof Q&&t.code===Z.Unimplemented?W({code:`DATA_CLONE_UNAVAILABLE`,message:`Application data clone is not enabled for this platform.`,command:`data clone`,cause:t}):t instanceof Q&&t.code===Z.FailedPrecondition?W({code:`DATA_CLONE_PRECONDITION_FAILED`,message:t.rawMessage,suggestion:`A clone needs both workspaces in the same region with the same namespaces, a matching TailorDB schema (deploy the same version to the target first), and an empty target for every copy type in scope. ${e.nameFromConfig?`To empty the target's TailorDB records, run ${U({command:`tailor`,args:[`tailordb`,`truncate`,`--all`,...k({workspaceId:e.targetWorkspaceId,profile:e.profile}),...n]})}.`:`To empty the target's TailorDB records, run tailor tailordb truncate for the namespaces of this application (see tailor tailordb truncate --help).`} That does not remove IdP users or files: with --copy-idp-users or --copy-files, remove those from the target separately.`,command:`data clone`,cause:t}):t instanceof Q&&t.code===Z.NotFound?W({code:`DATA_CLONE_NOT_FOUND`,message:t.rawMessage,suggestion:`Check that --from and --to are workspace IDs you can access and that the application exists in the source workspace.`,command:`data clone`,cause:t}):t}if(!i)throw Zr(`Application data clone returned no operation ID.`);f.info(`Clone started (operation: ${i})`);let a={sourceWorkspaceId:e.sourceWorkspaceId,targetWorkspaceId:e.targetWorkspaceId,operationId:i,profile:e.profile};if(e.noWait)return f.info(`The clone keeps running on the platform. To wait for it: ${resumeHint(a)}`),{operationId:i,status:`started`};let o=Date.now();return await hintOnInterrupt(a,()=>waitForCloneApplicationData(r,{sourceWorkspaceId:a.sourceWorkspaceId,targetWorkspaceId:a.targetWorkspaceId,operationId:i,timeout:1/0,errorCodePrefix:`DATA_CLONE`,onStatus:reportStatus})),f.success(`Cloned data of application "${e.name}" from "${e.sourceWorkspaceId}" to "${e.targetWorkspaceId}" in ${formatElapsed(Date.now()-o)}`),{operationId:i,status:`completed`}}const ua=C({name:`clone`,description:`Clone the data of an application (TailorDB namespaces registered in its subgraph) from one workspace to another.`,notes:"\nThe platform rejects the clone with a failed precondition unless all of the following hold:\n- The source and target workspaces are in the same region.\n- The target workspace has the same namespaces as the source.\n- The TailorDB schema of the target matches the source, so deploy the same version to the target first.\n- The target is empty for every namespace and copy type in scope (TailorDB records, plus files and IdP users when `--copy-files` / `--copy-idp-users` are given).\n\nThe command waits until the clone finishes. Pressing Ctrl+C or passing --no-wait does not stop the clone, which keeps running on the platform. Use `tailor data operation get --wait` with the operation ID printed at the start to keep waiting, or without --wait to check the status once.\n\nWith --json, the result carries `status`: `completed` once the clone has finished, or `started` with --no-wait.\n",args:J.strictObject({...I,profile:G(J.string().optional(),{alias:`p`,description:`Workspace profile`,env:`TAILOR_PLATFORM_PROFILE`,completion:{type:`none`}}),...ca,name:G(J.string().optional(),{alias:`n`,description:`Application name, the same in the source and the target workspace (default: the name in the config file)`,completion:{type:`none`}}),...we,"copy-files":G(J.boolean().default(!1),{description:`Also copy TailorDB file content`}),"copy-idp-users":G(J.boolean().default(!1),{description:`Also copy IdP users, including their passwords`}),"no-wait":G(J.boolean().default(!1),{description:`Start the clone and exit without waiting for it to finish`})}),run:async e=>{await z({profile:e.profile});let t=e.name??(await B(e.config)).config.name,{operationId:n,status:r}=await $clone({sourceWorkspaceId:e.from,targetWorkspaceId:e.to,name:t,config:e.config,nameFromConfig:e.name===void 0,copyFiles:e[`copy-files`],copyIdpUsers:e[`copy-idp-users`],noWait:e[`no-wait`],profile:e.profile,yes:e.yes});A({changed:!0,sourceWorkspaceId:e.from,targetWorkspaceId:e.to,operationId:n,status:r})}}),da=C({name:`get`,description:`Show the status of a data clone, or wait for it to finish.`,notes:`Without --wait, the command prints the current status once and exits. With --wait, it waits until the clone completes or fails, and exits with an error if it fails. Pressing Ctrl+C stops waiting; the clone keeps running on the platform.`,args:J.strictObject({profile:G(J.string().optional(),{alias:`p`,description:`Workspace profile`,env:`TAILOR_PLATFORM_PROFILE`,completion:{type:`none`}}),...ca,"operation-id":G(J.string(),{description:`Operation ID printed when the clone started`,completion:{type:`none`}}),wait:G(J.boolean().default(!1),{description:`Wait until the clone completes or fails`})}),run:async e=>{let t=await Kr(await nr({profile:e.profile})),n={sourceWorkspaceId:e.from,targetWorkspaceId:e.to,operationId:e[`operation-id`],profile:e.profile};if(!e.wait){let e=await t.getCloneApplicationDataOperation({sourceWorkspaceId:n.sourceWorkspaceId,targetWorkspaceId:n.targetWorkspaceId,operationId:n.operationId}),r=statusName(e.status);f.info(`Clone operation ${n.operationId}: ${r}`),e.errorMessage&&f.info(`Message: ${e.errorMessage}`),f.out({operationId:n.operationId,status:r,...e.errorMessage?{errorMessage:e.errorMessage}:{}});return}let r=Date.now();await hintOnInterrupt(n,()=>waitForCloneApplicationData(t,{sourceWorkspaceId:n.sourceWorkspaceId,targetWorkspaceId:n.targetWorkspaceId,operationId:n.operationId,timeout:1/0,errorCodePrefix:`DATA_CLONE`,onStatus:reportStatus})),f.success(`Clone operation ${n.operationId} completed (waited ${formatElapsed(Date.now()-r)})`),f.out({operationId:n.operationId,status:`completed`})}}),fa=K({name:`operation`,description:`Inspect asynchronous application data operations.`,subCommands:{get:da}}),pa=K({name:`data`,description:`Manage application data across workspaces.`,subCommands:{clone:ua,operation:fa}}),ma=C({name:`deploy`,description:`Deploy your application by applying the Tailor configuration.`,notes:"Workspace creation uses the selected user's default organization and folder set by `user update` when neither location is given and TAILOR_PLATFORM_TOKEN is not set. Giving --organization-id or --folder-id replaces both defaults. Organization and folder IDs loaded by --env-file also replace the defaults; command-line options take precedence, and empty env-file values are ignored. With --create-workspace, an existing workspace must match the resolved name, region, organization, and folder to be reused.",args:J.strictObject({...N,...Wn,...I,"create-workspace":G(J.boolean().optional(),{description:`Create a workspace when the account has none`}),"workspace-name":G(J.string().optional(),{description:`Name for a workspace created during deploy`}),"workspace-region":G(J.string().optional(),{description:`Region for a workspace created during deploy`}),"organization-id":G(J.string().optional(),{description:`Organization ID for a workspace created during deploy`,env:`TAILOR_PLATFORM_ORGANIZATION_ID`}),"folder-id":G(J.string().optional(),{description:`Folder ID for a workspace created during deploy`,env:`TAILOR_PLATFORM_FOLDER_ID`}),"dry-run":G(J.boolean().optional(),{alias:`d`,description:`Run the command without making any changes`}),"no-schema-check":G(J.boolean().optional(),{description:`Skip schema diff check against migration snapshots`}),"migration-skip-steps":G(J.string().optional(),{description:`Skip steps of a partially applied multi-step migration that already succeeded (comma-separated namespace/step entries)`}),"no-validate":G(J.boolean().optional(),{description:`Skip client-side validation against platform resource constraints`}),"no-cache":G(J.boolean().optional(),{description:`Disable bundle caching for this run`}),"clean-cache":G(J.boolean().optional(),{description:`Clean the bundle cache before building`})}),run:async e=>{await z({profile:e.profile});let{initTelemetry:t}=await import(`../telemetry-DpkFGBmu.mjs`);await t(),await _({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`],...Ht(e),noSchemaCheck:e[`no-schema-check`],migrationSkipSteps:lt(e[`migration-skip-steps`]),noValidate:e[`no-validate`],noCache:e[`no-cache`],cleanCache:e[`clean-cache`]},{envFile:e[`env-file`],envFileIfExists:e[`env-file-if-exists`],verbose:e.verbose,json:e.json})}}),ha=K({name:`executor`,description:`Manage executors`,subCommands:{trigger:et,jobs:dn,list:ae,get:ct,webhook:ir},defaultSubCommand:`list`});function scriptNameToRegistryName(e,t){if(t===r.JOB)return`workflow--${e}`;let n=/^([^.]+)\.(.+)\.body\.js$/.exec(e);if(n){let[,e,t]=n;return`resolver--${e}--${t}`}let i=/^(.+)\.operation\.js$/.exec(e);if(i){let[,e]=i;return`executor--${e}`}let a=/^([^.]+)\.([^.]+)\.hook\.js$/.exec(e);if(a){let[,e,t]=a;return`auth-hook--${e}--${t}`}return t===r.UNSPECIFIED&&!e.includes(`.`)?`workflow--${e}`:null}async function downloadFunctionScript(e){let{client:t,workspaceId:n,name:r,contentHash:i}=e;try{let e=[];for await(let a of t.downloadFunctionRegistryScript({workspaceId:n,name:r,contentHash:i}))a.payload.case===`chunk`&&e.push(a.payload.value);return e.length===0?null:{code:Buffer.concat(e).toString(`utf-8`)}}catch(t){return f.debug(`Failed to download function script "${e.name}": ${t}`),null}}const ga=/^\s+at\s+(?:(.+?)\s+\()?(file:\/\/\/.+?):(\d+):(\d+)\)?$/;function parseStackTrace(e){let t=e.split(`
6
+ `).map((e,n)=>{let r;try{r=JSON.parse(e)}catch(e){throw W({code:`SEED_DATA_INVALID`,message:`Invalid JSON in ${a} at line ${n+1}: ${e instanceof Error?e.message:String(e)}`,cause:e})}if(typeof r!=`object`||!r||Array.isArray(r))throw W({code:`SEED_DATA_INVALID`,message:`Invalid seed row in ${a} at line ${n+1}: expected a JSON object`});let i=r;return t?projectSeedObject(i,t.fields,/* @__PURE__ */ new Set([`id`])):i}):[]}return r}function projectSeedObject(e,t,n=/* @__PURE__ */ new Set){return Object.fromEntries(Object.entries(e).flatMap(([e,r])=>{let i=t[e];return i?[[e,projectSeedValue(r,i)]]:n.has(e)?[[e,r]]:[]}))}function projectSeedValue(e,t){let n=t.fields;return n?t.array?Array.isArray(e)?e.map(e=>isJsonObject(e)?projectSeedObject(e,n):e):e:isJsonObject(e)?projectSeedObject(e,n):e:e}function isJsonObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function sortSeedTypesForSnapshot(e){let t=Object.keys(e.tables),n=new Set(t),r=/* @__PURE__ */ new Map,i=[];for(let[t,a]of Object.entries(e.tables)){let e=/* @__PURE__ */ new Set;for(let r of Object.values(a.fields)){let a=r.foreignKeyType;a&&(a===t?i.push(t):n.has(a)&&e.add(a))}r.set(t,[...e])}let a=/* @__PURE__ */ new Set,o=[],visit=e=>{if(!a.has(e)){a.add(e);for(let t of r.get(e)??[])visit(t);o.push(e)}};for(let e of t)visit(e);return{order:o,selfRefTypes:i}}function temporaryWorkspaceName(){return`migration-test-${(/* @__PURE__ */ new Date()).toISOString().replace(/[-:T.Z]/g,``).slice(0,14)}-${ki(3).toString(`hex`)}`}function stateOrThrow(e){return s(e,`migration test runtime was used before preparation`)}async function resolveTemporaryWorkspaceLocation(e,t,n){if(!n.organizationId&&!n.folderId)return{...t.organizationId?{organizationId:t.organizationId}:{},...t.folderId?{folderId:t.folderId}:{}};let{folderId:r}=n,i=n.organizationId??(t.organizationId||void 0);if(r&&!i)throw W({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`--folder-id requires --organization-id.`,details:`The source workspace is not in an organization.`,suggestion:`Pass --organization-id together with --folder-id.`});if(r&&i&&!await Br(async()=>{let{folder:t}=await e.getOrganizationFolder({organizationId:i,folderId:r});return t}))throw W({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`Folder "${r}" was not found in organization "${i}"${n.organizationId?``:` (the source workspace's organization)`}.`,details:`The folder does not exist there, belongs to a different organization, or is not accessible.`,suggestion:n.organizationId?`Pass a --folder-id that belongs to --organization-id.`:`Pass --organization-id together with --folder-id if the folder is in another organization.`});return{...i?{organizationId:i}:{},...r?{folderId:r}:{}}}function assertTargetMatchesLocation(e,t){let n=[{flag:`--organization-id`,kind:`organization`,wanted:t.organizationId,actual:e.organizationId},{flag:`--folder-id`,kind:`folder`,wanted:t.folderId,actual:e.folderId}];for(let{flag:t,kind:r,wanted:i,actual:a}of n)if(i!==void 0&&i.toLowerCase()!==a?.toLowerCase())throw W({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`${t} "${i}" does not match the designated target workspace "${e.id}", which ${a?`is in ${r} "${a}"`:`has no ${r}`}.`,suggestion:`Pass the ${r} the target workspace is in, or omit ${t}.`})}async function resolveSourceMigrationNumber(e,t,n,r,i,a){if(r.number!==null)return r.number;if(!r.metadataExists)throw W({code:`MIGRATION_TEST_SOURCE_CHECKPOINT_MISSING`,message:`Source namespace "${n.namespace}" has not been deployed.`,suggestion:`Deploy to the source workspace before testing.`});let o=M(n.migrationsDir,0);if(!o)throw W({code:`MIGRATION_BASELINE_NOT_FOUND`,message:`No migration baseline snapshot found for namespace "${n.namespace}".`});let s=await ke(e,t,n.namespace,o,i,a);if(s.length>0)throw W({code:`MIGRATION_TEST_SOURCE_INVALID`,message:`Source namespace "${n.namespace}" has no migration label and its schema differs from the initial migration snapshot (0000).`,details:$e(s),suggestion:`Bring the source schema in line with 0000 or set its migration label.`});return 0}async function assertSourceBaselineFresh(e,t,n){let r=e.loaded,i=V(r.config,q.dirname(r.config.path)),a=r.application.tailorDBServices.map(he),o=(await nt(e.client,n,i,r.config,a)).find(e=>e.hasDrift||e.checkpointMissingLocal||e.checkpointRepair);if(o)throw W({code:`MIGRATION_TEST_SOURCE_CHANGED`,message:`Source namespace "${o.namespace}" changed after migration test preparation.`,suggestion:`Run the migration test again.`});for(let o of i){let i=t.baselines.get(o.namespace);if(!i)continue;let s=await O(e.client,L(n,`tailordb`,o.namespace));en(s,o.namespace);let c=await resolveSourceMigrationNumber(e.client,n,o,s,r.config,a);if(c!==i.migrationNumber)throw W({code:`MIGRATION_TEST_SOURCE_CHANGED`,message:`Source namespace "${o.namespace}" moved from migration ${i.migrationNumber} to ${c} after migration test preparation.`,suggestion:`Run the migration test again.`})}let s=a.filter(e=>!t.baselines.has(e.namespace));for(let r of s){let i=t.baselineSnapshots.get(r.namespace);if(!i)continue;let a=await We(e.client,n,r.namespace);if(He(i,a).changes.length>0)throw W({code:`MIGRATION_TEST_SOURCE_CHANGED`,message:`Source namespace "${r.namespace}" schema changed after migration test preparation.`,suggestion:`Run the migration test again.`})}}async function deleteExistingUserProfileConfig(e,t){let n=e.loaded.application.authService;if(!n)return;let r=n.config.name;await Br(()=>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 W({code:`AUTH_CONFIG_REQUIRED`,message:`Auth configuration is required to execute migration test scripts.`});let i=n??gt(migrationConfig(e.loaded,t),r.config.machineUsers?Object.keys(r.config.machineUsers):void 0);if(!i)throw W({code:`MACHINE_USER_REQUIRED`,message:`No machine user is available for namespace "${t}".`,suggestion:`Pass --machine-user or configure one in auth or db.${t}.migration.`});return{authNamespace:r.config.name,machineUserName:i}}async function prepareMigrationTest(e){let t=await dt({configPath:e.configPath}),n=q.dirname(t.config.path),r=V(t.config,n);if(r.length===0)throw jt();for(let e of r)Fe(e.migrationsDir,e.namespace);let i;e.data===`seed`&&(i=await it({configPath:t.config.path}),assertSeedDataDirectory(q.join(i.distPath,`data`))),e.assertionPath&&assertAssertionScript(e.assertionPath);let a=t.application.tailorDBServices.map(he),o=await nr({profile:e.profile}),c=await pn({profile:e.profile}),l=await Kr(o,c),u=await un({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.targetWorkspaceId?l.getWorkspace({workspaceId:e.targetWorkspaceId}):Promise.resolve(void 0)]),m=s(d.workspace,`source workspace "${u}" not found`);s(f.application,`application "${t.config.name}" not found in source workspace`);let h=p?s(p.workspace,`target workspace "${e.targetWorkspaceId}" not found`):void 0;h&&assertTargetMatchesLocation(h,e);let g=await resolveTemporaryWorkspaceLocation(l,m,h?{}:e),_=await nt(l,u,r,t.config,a),v=_.find(e=>e.hasDrift||e.checkpointMissingLocal);if(v)throw W({code:`MIGRATION_TEST_SOURCE_INVALID`,message:`Source namespace "${v.namespace}" does not match its migration checkpoint.`,suggestion:`Validate the migration history first.`});let y=_.find(e=>e.checkpointRepair);if(y)throw W({code:`MIGRATION_TEST_SOURCE_REPAIR_PENDING`,message:`Source namespace "${y.namespace}" has a pending migration checkpoint repair.`,suggestion:`Deploy to the source workspace first.`});let b=/* @__PURE__ */ new Map,ee=/* @__PURE__ */ new Map,x=[];for(let e of r){let n=await O(l,L(u,`tailordb`,e.namespace));en(n,e.namespace);let r=await resolveSourceMigrationNumber(l,u,e,n,t.config,a),i=st(e.migrationsDir);if(r>i)throw W({code:`MIGRATION_TEST_SOURCE_AHEAD`,message:`Source namespace "${e.namespace}" is at migration ${r}, but the local history ends at ${i}.`});let o=M(e.migrationsDir,r);if(!o)throw W({code:`MIGRATION_BASELINE_NOT_FOUND`,message:`No migration baseline snapshot found for namespace "${e.namespace}".`});b.set(e.namespace,{migrationNumber:r,snapshot:o,historyId:o.rebaseline?.historyId??null});let s=M(e.migrationsDir,i);if(!s)throw W({code:`MIGRATION_TEST_SNAPSHOT_NOT_FOUND`,message:`No target migration snapshot found for namespace "${e.namespace}".`});ee.set(e.namespace,s),r<i&&x.push(e.namespace)}if(x.length===0)throw W({code:`MIGRATION_TEST_NO_PENDING_MIGRATIONS`,message:`No pending TailorDB migrations found in the source workspace.`});let S=await createMigrationTestBaselineSnapshots({client:l,workspaceId:u,dataMode:e.data,inputs:a,baselines:b}),te={sourceWorkspaceId:u,sourceApplicationName:t.config.name,temporaryWorkspace:{name:temporaryWorkspaceName(),region:m.region,...g},baselines:b,baselineSnapshots:S,targetSnapshots:ee,pendingNamespaces:x,...h?{designatedTarget:{id:h.id,region:h.region}}:{}};return{state:{client:l,loaded:t,options:e,...i?{seedContext:i}:{}},prepared:te}}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 Dt(n.client,t.temporaryWorkspace);return f.info(`Created temporary workspace ${r.name} (${r.id}).`),{id:r.id,name:r.name,...r.createdAt?{createdAt:r.createdAt}:{}}},recordWorkspaceExpiry:async(t,n,r=/* @__PURE__ */ new Date)=>{let i=stateOrThrow(e);await Ct(i.client,t,new Date(r.getTime()+cr(n)))},deployBaseline:async({prepared:t,targetWorkspaceId:n})=>{let r=stateOrThrow(e);await deleteExistingUserProfileConfig(r,n),await Wt({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 mt(r.client,n,e,i.migrationNumber,i.historyId??void 0)},seedData:async({prepared:t,targetWorkspaceId:n})=>{let r=stateOrThrow(e),i=s(r.seedContext,`seed context missing after migration test preparation`),a=q.join(i.distPath,`data`);assertSeedDataDirectory(a);let o=new Map(r.loaded.application.tailorDBServices.map(e=>{let n=t.baselines.get(e.namespace),r=he(e);return[e.namespace,n?.snapshot??Ut({version:1,namespace:e.namespace,createdAt:(/* @__PURE__ */ new Date()).toISOString(),tables:r.types})]}));for(let[e,t]of o){let{order:o,selfRefTypes:s}=sortSeedTypesForSnapshot(t),c=loadSnapshotSeedData(a,o,t),l=o.filter(e=>(c[e]?.length??0)>0);if(l.length===0)continue;let u=await xt(e,l,q.dirname(r.loaded.config.path)),d=In({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 Se({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 W({code:`MIGRATION_TEST_SEED_FAILED`,message:i.error??`Seed execution failed for namespace "${e}".`});if(JSON.parse(i.result||`{}`).success!==!0)throw W({code:`MIGRATION_TEST_SEED_FAILED`,message:`Seed execution reported failure for namespace "${e}".`})}}},cloneData:async({prepared:t,sourceWorkspaceId:n,targetWorkspaceId:r,applicationName:i,cloneTimeout:a})=>{let o=stateOrThrow(e);await assertSourceBaselineFresh(o,t,n),f.warn(`Clone mode copies TailorDB records only; IdP users and file blobs are not copied.`);let s;try{s=(await o.client.cloneApplicationData({sourceWorkspaceId:n,sourceApplicationName:i,targetWorkspaceId:r,targetApplicationName:i})).operationId}catch(e){throw e instanceof Q&&e.code===Z.Unimplemented?W({code:`MIGRATION_TEST_CLONE_UNAVAILABLE`,message:`Application data clone is not enabled for this platform.`,suggestion:`Retry with --data seed.`,cause:e}):e}if(!s)throw Zr(`Application data clone returned no operation ID.`);await waitForCloneApplicationData(o.client,{sourceWorkspaceId:n,targetWorkspaceId:r,operationId:s,timeout:a})},deployMigrations:async({prepared:t,targetWorkspaceId:n})=>{let r=stateOrThrow(e);await Gn({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 Bt(r,s,0,o.loaded.config.env??{},q.dirname(o.loaded.config.path),De(o.loaded.plugins,`@tailor-platform/kysely-type`)?.temporal??!1,Nr(o.loaded.config)),u=await Se({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 W({code:`MIGRATION_TEST_ASSERTION_FAILED`,message:u.error??`Migration assertion failed for namespace "${s}".`})},deleteWorkspace:async t=>{await stateOrThrow(e).client.deleteWorkspace({workspaceId:t})}}}const ca={from:G(J.string(),{description:`Workspace ID to copy data from`,completion:{type:`none`}}),to:G(J.string(),{description:`Workspace ID to copy data to`,completion:{type:`none`}})};function resumeCommandArgs(e){return[`data`,`operation`,`get`,`--from`,e.sourceWorkspaceId,`--to`,e.targetWorkspaceId,`--operation-id`,e.operationId,`--wait`,...k({profile:e.profile})]}function resumeHint(e){return U({command:`tailor`,args:resumeCommandArgs(e)})}async function hintOnInterrupt(e,t){let onInterrupt=()=>{f.info(`Stopped waiting. The clone keeps running on the platform. To wait for it: ${resumeHint(e)}`)};process.once(`SIGINT`,onInterrupt);try{return await t()}finally{process.off(`SIGINT`,onInterrupt)}}const la={[o.PENDING]:`pending`,[o.PROCESSING]:`processing`,[o.COMPLETED]:`completed`,[o.FAILED]:`failed`};function statusName(e){return la[e]??`unknown`}function reportStatus(e){f.info(`status: ${statusName(e)}`,{mode:`stream`})}function formatElapsed(e){let t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n>0?`${n}h ${r}m`:r>0?`${r}m ${i}s`:`${i}s`}async function $clone(e){let t=vt(e.config),n=t?[t]:[];if(e.sourceWorkspaceId===e.targetWorkspaceId)throw W({code:`DATA_CLONE_SAME_WORKSPACE`,message:`The source and target workspaces must be different.`,command:`data clone`});let r=await Kr(await nr({profile:e.profile}));try{await r.getApplication({workspaceId:e.targetWorkspaceId,applicationName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?W({code:`DATA_CLONE_TARGET_APPLICATION_NOT_FOUND`,message:`Application "${e.name}" was not found in the target workspace "${e.targetWorkspaceId}".`,suggestion:e.nameFromConfig?`Check --to and that you have access to the target workspace, and deploy the application to it first so it has the same namespaces and schema.`:`Check --to and that you have access to the target workspace, and deploy the application "${e.name}" to it first so it has the same namespaces and schema.`,...e.nameFromConfig?{next:{command:`tailor`,args:[`deploy`,...k({workspaceId:e.targetWorkspaceId,profile:e.profile}),...n]}}:{},command:`data clone`,cause:t}):t}if(!e.yes&&!await P.confirm({message:`This will copy the data of application "${e.name}" from workspace "${e.sourceWorkspaceId}" to workspace "${e.targetWorkspaceId}". Continue?`,default:!1}))throw W({code:`DATA_CLONE_CANCELLED`,message:`Data clone cancelled.`});let i;try{i=(await r.cloneApplicationData({sourceWorkspaceId:e.sourceWorkspaceId,sourceApplicationName:e.name,targetWorkspaceId:e.targetWorkspaceId,targetApplicationName:e.name,copyFiles:e.copyFiles,copyIdpUsers:e.copyIdpUsers})).operationId}catch(t){throw t instanceof Q&&t.code===Z.Unimplemented?W({code:`DATA_CLONE_UNAVAILABLE`,message:`Application data clone is not enabled for this platform.`,command:`data clone`,cause:t}):t instanceof Q&&t.code===Z.FailedPrecondition?W({code:`DATA_CLONE_PRECONDITION_FAILED`,message:t.rawMessage,suggestion:`A clone needs both workspaces in the same region with the same namespaces, a matching TailorDB schema (deploy the same version to the target first), and an empty target for every copy type in scope. ${e.nameFromConfig?`To empty the target's TailorDB records, run ${U({command:`tailor`,args:[`tailordb`,`truncate`,`--all`,...k({workspaceId:e.targetWorkspaceId,profile:e.profile}),...n]})}.`:`To empty the target's TailorDB records, run tailor tailordb truncate for the namespaces of this application (see tailor tailordb truncate --help).`} That does not remove IdP users or files: with --copy-idp-users or --copy-files, remove those from the target separately.`,command:`data clone`,cause:t}):t instanceof Q&&t.code===Z.NotFound?W({code:`DATA_CLONE_NOT_FOUND`,message:t.rawMessage,suggestion:`Check that --from and --to are workspace IDs you can access and that the application exists in the source workspace.`,command:`data clone`,cause:t}):t}if(!i)throw Zr(`Application data clone returned no operation ID.`);f.info(`Clone started (operation: ${i})`);let a={sourceWorkspaceId:e.sourceWorkspaceId,targetWorkspaceId:e.targetWorkspaceId,operationId:i,profile:e.profile};if(e.noWait)return f.info(`The clone keeps running on the platform. To wait for it: ${resumeHint(a)}`),{operationId:i,status:`started`};let o=Date.now();return await hintOnInterrupt(a,()=>waitForCloneApplicationData(r,{sourceWorkspaceId:a.sourceWorkspaceId,targetWorkspaceId:a.targetWorkspaceId,operationId:i,timeout:1/0,errorCodePrefix:`DATA_CLONE`,onStatus:reportStatus})),f.success(`Cloned data of application "${e.name}" from "${e.sourceWorkspaceId}" to "${e.targetWorkspaceId}" in ${formatElapsed(Date.now()-o)}`),{operationId:i,status:`completed`}}const ua=C({name:`clone`,description:`Clone the data of an application (TailorDB namespaces registered in its subgraph) from one workspace to another.`,notes:"\nThe platform rejects the clone with a failed precondition unless all of the following hold:\n- The source and target workspaces are in the same region.\n- The target workspace has the same namespaces as the source.\n- The TailorDB schema of the target matches the source, so deploy the same version to the target first.\n- The target is empty for every namespace and copy type in scope (TailorDB records, plus files and IdP users when `--copy-files` / `--copy-idp-users` are given).\n\nThe command waits until the clone finishes. Pressing Ctrl+C or passing --no-wait does not stop the clone, which keeps running on the platform. Use `tailor data operation get --wait` with the operation ID printed at the start to keep waiting, or without --wait to check the status once.\n\nWith --json, the result carries `status`: `completed` once the clone has finished, or `started` with --no-wait.\n",args:J.strictObject({...I,profile:G(J.string().optional(),{alias:`p`,description:`Workspace profile`,env:`TAILOR_PLATFORM_PROFILE`,completion:{type:`none`}}),...ca,name:G(J.string().optional(),{alias:`n`,description:`Application name, the same in the source and the target workspace (default: the name in the config file)`,completion:{type:`none`}}),...we,"copy-files":G(J.boolean().default(!1),{description:`Also copy TailorDB file content`}),"copy-idp-users":G(J.boolean().default(!1),{description:`Also copy IdP users, including their passwords`}),"no-wait":G(J.boolean().default(!1),{description:`Start the clone and exit without waiting for it to finish`})}),run:async e=>{await z({profile:e.profile});let t=e.name??(await B(e.config)).config.name,{operationId:n,status:r}=await $clone({sourceWorkspaceId:e.from,targetWorkspaceId:e.to,name:t,config:e.config,nameFromConfig:e.name===void 0,copyFiles:e[`copy-files`],copyIdpUsers:e[`copy-idp-users`],noWait:e[`no-wait`],profile:e.profile,yes:e.yes});A({changed:!0,sourceWorkspaceId:e.from,targetWorkspaceId:e.to,operationId:n,status:r})}}),da=C({name:`get`,description:`Show the status of a data clone, or wait for it to finish.`,notes:`Without --wait, the command prints the current status once and exits. With --wait, it waits until the clone completes or fails, and exits with an error if it fails. Pressing Ctrl+C stops waiting; the clone keeps running on the platform.`,args:J.strictObject({profile:G(J.string().optional(),{alias:`p`,description:`Workspace profile`,env:`TAILOR_PLATFORM_PROFILE`,completion:{type:`none`}}),...ca,"operation-id":G(J.string(),{description:`Operation ID printed when the clone started`,completion:{type:`none`}}),wait:G(J.boolean().default(!1),{description:`Wait until the clone completes or fails`})}),run:async e=>{let t=await Kr(await nr({profile:e.profile})),n={sourceWorkspaceId:e.from,targetWorkspaceId:e.to,operationId:e[`operation-id`],profile:e.profile};if(!e.wait){let e=await t.getCloneApplicationDataOperation({sourceWorkspaceId:n.sourceWorkspaceId,targetWorkspaceId:n.targetWorkspaceId,operationId:n.operationId}),r=statusName(e.status);f.info(`Clone operation ${n.operationId}: ${r}`),e.errorMessage&&f.info(`Message: ${e.errorMessage}`),f.out({operationId:n.operationId,status:r,...e.errorMessage?{errorMessage:e.errorMessage}:{}});return}let r=Date.now();await hintOnInterrupt(n,()=>waitForCloneApplicationData(t,{sourceWorkspaceId:n.sourceWorkspaceId,targetWorkspaceId:n.targetWorkspaceId,operationId:n.operationId,timeout:1/0,errorCodePrefix:`DATA_CLONE`,onStatus:reportStatus})),f.success(`Clone operation ${n.operationId} completed (waited ${formatElapsed(Date.now()-r)})`),f.out({operationId:n.operationId,status:`completed`})}}),fa=K({name:`operation`,description:`Inspect asynchronous application data operations.`,subCommands:{get:da}}),pa=K({name:`data`,description:`Manage application data across workspaces.`,subCommands:{clone:ua,operation:fa}}),ma=C({name:`deploy`,description:`Deploy your application by applying the Tailor configuration.`,notes:"Workspace creation uses the selected user's default organization and folder set by `user update` when neither location is given and TAILOR_PLATFORM_TOKEN is not set. Giving --organization-id or --folder-id replaces both defaults. Organization and folder IDs loaded by --env-file also replace the defaults; command-line options take precedence, and empty env-file values are ignored. With --create-workspace, an existing workspace must match the resolved name, region, organization, and folder to be reused.",args:J.strictObject({...N,...Wn,...I,"create-workspace":G(J.boolean().optional(),{description:`Create a workspace when the account has none`}),"workspace-name":G(J.string().optional(),{description:`Name for a workspace created during deploy`}),"workspace-region":G(J.string().optional(),{description:`Region for a workspace created during deploy`}),"organization-id":G(J.string().optional(),{description:`Organization ID for a workspace created during deploy`,env:`TAILOR_PLATFORM_ORGANIZATION_ID`}),"folder-id":G(J.string().optional(),{description:`Folder ID for a workspace created during deploy`,env:`TAILOR_PLATFORM_FOLDER_ID`}),"dry-run":G(J.boolean().optional(),{alias:`d`,description:`Run the command without making any changes`}),"no-schema-check":G(J.boolean().optional(),{description:`Skip schema diff check against migration snapshots`}),"migration-skip-steps":G(J.string().optional(),{description:`Skip steps of a partially applied multi-step migration that already succeeded (comma-separated namespace/step entries)`}),"no-validate":G(J.boolean().optional(),{description:`Skip client-side validation against platform resource constraints`}),"no-cache":G(J.boolean().optional(),{description:`Disable bundle caching for this run`}),"clean-cache":G(J.boolean().optional(),{description:`Clean the bundle cache before building`})}),run:async e=>{await z({profile:e.profile});let{initTelemetry:t}=await import(`../telemetry-nqOtDWNO.mjs`);await t(),await _({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`],...Ht(e),noSchemaCheck:e[`no-schema-check`],migrationSkipSteps:lt(e[`migration-skip-steps`]),noValidate:e[`no-validate`],noCache:e[`no-cache`],cleanCache:e[`clean-cache`]},{envFile:e[`env-file`],envFileIfExists:e[`env-file-if-exists`],verbose:e.verbose,json:e.json})}}),ha=K({name:`executor`,description:`Manage executors`,subCommands:{trigger:et,jobs:dn,list:ae,get:ct,webhook:ir},defaultSubCommand:`list`});function scriptNameToRegistryName(e,t){if(t===r.JOB)return`workflow--${e}`;let n=/^([^.]+)\.(.+)\.body\.js$/.exec(e);if(n){let[,e,t]=n;return`resolver--${e}--${t}`}let i=/^(.+)\.operation\.js$/.exec(e);if(i){let[,e]=i;return`executor--${e}`}let a=/^([^.]+)\.([^.]+)\.hook\.js$/.exec(e);if(a){let[,e,t]=a;return`auth-hook--${e}--${t}`}return t===r.UNSPECIFIED&&!e.includes(`.`)?`workflow--${e}`:null}async function downloadFunctionScript(e){let{client:t,workspaceId:n,name:r,contentHash:i}=e;try{let e=[];for await(let a of t.downloadFunctionRegistryScript({workspaceId:n,name:r,contentHash:i}))a.payload.case===`chunk`&&e.push(a.payload.value);return e.length===0?null:{code:Buffer.concat(e).toString(`utf-8`)}}catch(t){return f.debug(`Failed to download function script "${e.name}": ${t}`),null}}const ga=/^\s+at\s+(?:(.+?)\s+\()?(file:\/\/\/.+?):(\d+):(\d+)\)?$/;function parseStackTrace(e){let t=e.split(`
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
8
  `);i.startsWith(`rpc error: code = Aborted desc = `)&&(i=i.slice(33));let a=[];for(let e of r){let t=ga.exec(e);t&&a.push({functionName:t[1]||`<anonymous>`,file:s(t[2],`stack frame file missing`),line:Number(s(t[3],`stack frame line missing`)),column:Number(s(t[4],`stack frame column missing`))})}return{errorMessage:i,frames:a}}const _a=/\/\/[#@]\s*sourceMappingURL=data:application\/json[^,]*;base64,(.+)$/m;function extractInlineSourcemap(e){let t=_a.exec(e);if(!t)return null;try{let e=Buffer.from(s(t[1],`sourcemap base64 data missing`),`base64`).toString(`utf-8`),n=JSON.parse(e);return new Ri(n)}catch{return null}}function mapStackFrames(e,t){return e.map(e=>{if(!t)return{original:e,mapped:null};try{for(let n=t.sources.length-1;n>=0;n--){let r=t.sources[n];if(r==null)continue;let i=zi(t,{source:r,line:e.line,column:e.column-1});if(i.line==null)continue;let a=Bi(t,{line:i.line,column:i.column});if(a.source===r&&a.line===e.line&&a.column===e.column-1)return{original:e,mapped:{source:r,line:e.line,column:e.column,name:null}}}return{original:e,mapped:null}}catch{return{original:e,mapped:null}}})}function detectEditorScheme(){let e=process.env.VISUAL||process.env.EDITOR||``;return/\bcode\b/.test(e)?`vscode`:null}function osc8Link(e,t){return`\x1b]8;;${e}\x07${t}\x1b]8;;\x07`}function buildSourceLink(e,t,n,r){let i=`${e}:${n}:${r}`;return detectEditorScheme()===`vscode`?osc8Link(`vscode://file${t}:${n}:${r}`,i):osc8Link(`file://${t}`,i)}function buildCodeSnippet(e,t){let n=e.split(`
9
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(` ${h.error(`>`)} ${h.error(`${i} | ${s}`)}`):o.push(` ${h.dim(`${i} | ${s}`)}`)}return o.join(`
@@ -75,7 +75,7 @@ Result:`));try{let e=JSON.parse(b.result);f.log(` ${JSON.stringify(e,null,2).sp
75
75
  `).join(`
76
76
  `)}`)}catch{f.log(` ${b.result}`)}}if(b.error&&!b.success){f.log(h.bold(`
77
77
  Error:`));let e=formatErrorWithSourcemap(b.error,p,process.cwd());e?f.log(e):f.log(` ${h.error(b.error)}`)}}b.success||process.exit(1)}}),Ca=new Set(pi(J.strictObject(de)).fields.filter(e=>e.type!==`boolean`).flatMap(e=>[e.cliName,...e.alias??[]].flatMap(toFlagTokens)));function toFlagTokens(e){return e.length===1?[`-${e}`]:[`--${e}`,`--${hi(e)}`]}function invokedViaTestRunAlias(e){let t=[];for(let n=2;n<e.length&&t.length<2;n++){let r=e[n];if(r===void 0||r===`--`)break;r.startsWith(`-`)?!r.includes(`=`)&&Ca.has(r)&&n++:t.push(r)}return t[0]===`function`&&t[1]===`test-run`}function resolveAuthNamespace(e){if(e?.name)return e.name;throw W({code:`AUTH_CONFIG_REQUIRED`,message:`Auth namespace is required.`,suggestion:`Ensure tailor.config.ts has an auth config.`})}async function resolveMachineUserName(e){let{cliMachineUser:t,cliMachineUserSource:n,profile:r,authConfig:i}=e,a=await Pe({machineUser:t,machineUserSource:n,profile:r});if(a)return a;if(i&&!(`external`in i&&i.external)){let e=i.machineUsers;if(e){let t=Object.keys(e);if(t.length>0)return s(t[0],`machine user key missing`)}}throw W({code:`MACHINE_USER_REQUIRED`,message:`Machine user is required.`,suggestion:`Provide --machine-user, set TAILOR_PLATFORM_MACHINE_USER_NAME, set a profile default with 'tailor profile update <profile> --machine-user <name>', or ensure tailor.config.ts has machine users configured.`})}async function resolveMachineUser(e){let{client:t,workspaceId:n,authNamespace:r,machineUserName:i,authConfig:a}=e,o=`00000000-0000-0000-0000-000000000000`;try{let{machineUser:e}=await t.getAuthMachineUser({workspaceId:n,authNamespace:r,name:i});e?.id&&(o=e.id)}catch{f.debug(`Could not fetch machine user "${i}" from server, using nil UUID`)}let s=a?.machineUsers?.[i],c=null,l=[];if(s&&typeof s==`object`){let e=s;c=e.attributes??null,l=e.attributeList??[]}return{name:i,id:o,attributes:c,attributeList:l}}const wa=C({name:`script`,description:"Scaffold a one-off script to run with `function run`.",args:J.object({...N,...we,file:G(J.string(),{positional:!0,description:`Path to create the script at (must end with .ts)`}),namespace:G(J.string().optional(),{description:`Target TailorDB namespace (required when the config does not pin one)`}),remote:G(J.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=q.resolve(e.file);if(!t.endsWith(`.ts`))throw W({code:`SCRIPT_PATH_INVALID`,message:`Script path must end with .ts: ${e.file}`,command:`function script`});let n=q.dirname(t),r=X.existsSync(t),i=q.join(n,ya),a=q.join(n,ba);if(t===i)throw W({code:`SCRIPT_PATH_INVALID`,message:`${ya} is reserved for the generated Kysely types written next to the script. Choose a different script file name.`,command:`function script`});let{config:o,plugins:c}=await B(e.config),l=c.find(e=>e.id===fi),u=X.existsSync(a);if(e.remote&&l!==void 0&&r&&!u)throw W({code:`SCRIPT_EXISTS`,message:`Script already exists: ${q.relative(process.cwd(),t)}.`,suggestion:`Scaffold --remote at a new path so the generated script imports its script-scoped db.ts.`});let d=e.remote||l===void 0||u,p;if(d)try{p=loadScriptSchemaSnapshot(t)?.snapshot.namespace}catch{}let m=resolveNamespace({config:o,explicit:e.namespace,sidecarNamespace:p,remote:e.remote});if(p!==void 0&&p!==m)throw W({code:`SCRIPT_NAMESPACE_MISMATCH`,message:`This directory's generated types target namespace "${p}" (${ba}).`,suggestion:`Scaffold scripts for namespace "${m}" in a separate directory.`});let g=[],_,v;if(d){let t;if(e.remote){let{client:n,workspaceId:r}=await j({profile:e.profile,workspaceId:e[`workspace-id`]});v=r,f.info(`Fetching deployed schema of namespace ${h.bold(m)}...`),t=await We(n,r,m)}else{f.info(`Loading local definitions of namespace ${h.bold(m)}...`);let{namespaces:n}=await pe({configPath:e.config,namespaces:[m]}),r=s(n[0],`namespace ${m}`);t=se(r.tables,m)}if(Object.keys(t.tables).length===0){let t=e.remote?`deployed tables in workspace ${s(v,`workspace ID`)}`:`locally defined tables`;throw W({code:`SCRIPT_SCHEMA_NOT_FOUND`,message:`Namespace "${m}" has no ${t}.`})}if(X.existsSync(i)&&!isGeneratedScriptDbTypes(X.readFileSync(i,`utf-8`)))throw W({code:`GENERATED_TYPES_NOT_OWNED`,message:`Refusing to overwrite ${q.relative(process.cwd(),i)}: it was not generated by \`tailor function script\`.`});let r=generateScriptDbTypes(t,De(c,`@tailor-platform/kysely-type`)?.temporal??!1);assertGeneratedTypeScript(i,r),X.mkdirSync(n,{recursive:!0}),X.writeFileSync(i,r),g.push(i),X.writeFileSync(a,JSON.stringify({...t,source:e.remote?`remote`:`local`},null,2)+`
78
- `),g.push(a),_=`./db`}else{if(r)throw W({code:`SCRIPT_EXISTS`,message:`Script already exists: ${q.relative(process.cwd(),t)}.`,suggestion:`It imports the project's generated Kysely types, so there is nothing to refresh.`});let e=resolveKyselyTypesPath(c);_=toImportSpecifier(q.relative(n,e)),X.existsSync(e)||f.warn(`Generated Kysely types not found at ${h.path(q.relative(process.cwd(),e))}. Run \`tailor generate\` before executing the script.`)}if(!r){let e=generateScriptSkeleton({getDBImportPath:_,namespace:m});assertGeneratedTypeScript(t,e),X.mkdirSync(n,{recursive:!0}),X.writeFileSync(t,e),g.unshift(t)}let y=[`function`,`run`,q.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}`),f.jsonMode)f.out({script:t,created:g,namespace:m,usesGeneratedDbTypes:d});else{r&&f.info(`Script already exists; refreshed generated types only.`);for(let e of g)f.success(`Created ${h.path(q.relative(process.cwd(),e))}`);f.info(`Next: edit the script, then run ${U({command:`tailor`,args:y})}`)}}});function resolveNamespace(e){let{config:t,explicit:n,sidecarNamespace:r,remote:i}=e,a=wt(t),o=er(t),s=i?a:o;if(n){if(!i&&!o.includes(n))throw W({code:`SCRIPT_NAMESPACE_REQUIRES_REMOTE`,message:`Namespace "${n}" is not owned by the config and requires --remote.`,command:`function script`});return n}if(r!==void 0){if(!i&&!o.includes(r))throw W({code:`SCRIPT_NAMESPACE_REQUIRES_REMOTE`,message:`Namespace "${r}" is not owned by the config and requires --remote.`,command:`function script`});return r}if(s.length===1){let e=s[0];if(e!==void 0)return e}throw s.length>1?W({code:`TAILORDB_NAMESPACE_REQUIRED`,message:`Multiple TailorDB namespaces are defined (${s.join(`, `)}). Specify one with --namespace.`,command:`function script`}):!i&&a.length>0?W({code:`TAILORDB_NAMESPACE_NOT_CONFIGURED`,message:`No owned TailorDB namespace is defined in the config. External namespaces require --remote: ${a.join(`, `)}.`}):W({code:`TAILORDB_NAMESPACE_NOT_CONFIGURED`,message:`No TailorDB namespace is defined in the config.`})}function resolveKyselyTypesPath(e){let t=De(e,`@tailor-platform/kysely-type`)?.distPath??`./generated/tailordb.ts`;if(t.length===0)throw W({code:`KYSELY_TYPE_PLUGIN_INVALID`,message:`kyselyTypePlugin is configured without a distPath; cannot locate getDB().`});return q.resolve(t)}function toImportSpecifier(e){let t=e.replace(/\.ts$/,``);return t.startsWith(`.`)?t:`./${t}`}const Ta=K({name:`function`,description:`Manage functions`,subCommands:{get:sr,list:lr,logs:va,run:Sa,script:wa},defaultSubCommand:`list`}),Ea=C({name:`generate`,description:`Generate files using Tailor configuration.`,args:J.strictObject({config:G(J.string().default(`tailor.config.ts`),{alias:`c`,description:`Path to SDK config file`})}),run:async e=>{let{initTelemetry:t}=await import(`../telemetry-DpkFGBmu.mjs`);await t(),await bn({configPath:e.config})}}),detectPackageManager=()=>{let e=[`npm`,`yarn`,`pnpm`,`bun`],t=process.env.npm_config_user_agent;if(!t)return;let[n]=t.split(`/`);if(e.includes(n))return n},Da=C({name:`init`,description:`Initialize a new project using create-sdk.`,args:J.strictObject({name:G(J.string().optional(),{positional:!0,description:`Project name`}),template:G(J.string().optional(),{alias:`t`,description:`Template name`})}),run:async e=>{let t=await ti(),n=t.version&&t.version!==`0.0.0`?t.version:`latest`,r=detectPackageManager();r||=(f.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]:[]];f.log(`Running: ${r} ${i.join(` `)}`);let a=Li(r,i,{stdio:`inherit`}),o={command:r,args:i};if(a.error)throw W({code:`INIT_SPAWN_FAILED`,message:`Failed to run ${r}: ${a.error.message}`,suggestion:`Check that ${r} is installed and executable.`,command:`init`,context:o,cause:a.error});if(a.status!==0)throw W({code:`INIT_FAILED`,message:a.signal===null?`${r} create exited with code ${a.status}.`:`${r} create was terminated by ${a.signal}.`,command:`init`,context:{...o,exitCode:a.status??void 0,signal:a.signal??void 0}})}}),Oa=8085,ka=`http://localhost:${Oa}/callback`;function randomState(){return Oi.randomBytes(32).toString(`base64url`)}function getProfileUserMismatch(e,t,n){if(e.profile&&e.profileUser&&t!==e.profileUser&&n!==e.profileUser)return{profile:e.profile,oldUser:e.profileUser,authenticatedUser:t,loginMode:e.loginMode??`user`}}function quoteCommandArg(e,t=process.platform){return t===`win32`?/^[A-Za-z0-9_./:@+=,-]+$/.test(e)?e:void 0:`'${e.replaceAll(`'`,`'\\''`)}'`}function profileUpdateCommand(e){let t=quoteCommandArg(e.profile),n=quoteCommandArg(e.authenticatedUser);return t&&n?`tailor profile update --user ${n} -- ${t}`:[`tailor profile update --user <authenticated-user> -- <profile>`,`profile = ${JSON.stringify(e.profile)}`,`authenticated user = ${JSON.stringify(e.authenticatedUser)}`].join(`
78
+ `),g.push(a),_=`./db`}else{if(r)throw W({code:`SCRIPT_EXISTS`,message:`Script already exists: ${q.relative(process.cwd(),t)}.`,suggestion:`It imports the project's generated Kysely types, so there is nothing to refresh.`});let e=resolveKyselyTypesPath(c);_=toImportSpecifier(q.relative(n,e)),X.existsSync(e)||f.warn(`Generated Kysely types not found at ${h.path(q.relative(process.cwd(),e))}. Run \`tailor generate\` before executing the script.`)}if(!r){let e=generateScriptSkeleton({getDBImportPath:_,namespace:m});assertGeneratedTypeScript(t,e),X.mkdirSync(n,{recursive:!0}),X.writeFileSync(t,e),g.unshift(t)}let y=[`function`,`run`,q.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}`),f.jsonMode)f.out({script:t,created:g,namespace:m,usesGeneratedDbTypes:d});else{r&&f.info(`Script already exists; refreshed generated types only.`);for(let e of g)f.success(`Created ${h.path(q.relative(process.cwd(),e))}`);f.info(`Next: edit the script, then run ${U({command:`tailor`,args:y})}`)}}});function resolveNamespace(e){let{config:t,explicit:n,sidecarNamespace:r,remote:i}=e,a=wt(t),o=er(t),s=i?a:o;if(n){if(!i&&!o.includes(n))throw W({code:`SCRIPT_NAMESPACE_REQUIRES_REMOTE`,message:`Namespace "${n}" is not owned by the config and requires --remote.`,command:`function script`});return n}if(r!==void 0){if(!i&&!o.includes(r))throw W({code:`SCRIPT_NAMESPACE_REQUIRES_REMOTE`,message:`Namespace "${r}" is not owned by the config and requires --remote.`,command:`function script`});return r}if(s.length===1){let e=s[0];if(e!==void 0)return e}throw s.length>1?W({code:`TAILORDB_NAMESPACE_REQUIRED`,message:`Multiple TailorDB namespaces are defined (${s.join(`, `)}). Specify one with --namespace.`,command:`function script`}):!i&&a.length>0?W({code:`TAILORDB_NAMESPACE_NOT_CONFIGURED`,message:`No owned TailorDB namespace is defined in the config. External namespaces require --remote: ${a.join(`, `)}.`}):W({code:`TAILORDB_NAMESPACE_NOT_CONFIGURED`,message:`No TailorDB namespace is defined in the config.`})}function resolveKyselyTypesPath(e){let t=De(e,`@tailor-platform/kysely-type`)?.distPath??`./generated/tailordb.ts`;if(t.length===0)throw W({code:`KYSELY_TYPE_PLUGIN_INVALID`,message:`kyselyTypePlugin is configured without a distPath; cannot locate getDB().`});return q.resolve(t)}function toImportSpecifier(e){let t=e.replace(/\.ts$/,``);return t.startsWith(`.`)?t:`./${t}`}const Ta=K({name:`function`,description:`Manage functions`,subCommands:{get:sr,list:lr,logs:va,run:Sa,script:wa},defaultSubCommand:`list`}),Ea=C({name:`generate`,description:`Generate files using Tailor configuration.`,args:J.strictObject({config:G(J.string().default(`tailor.config.ts`),{alias:`c`,description:`Path to SDK config file`})}),run:async e=>{let{initTelemetry:t}=await import(`../telemetry-nqOtDWNO.mjs`);await t(),await bn({configPath:e.config})}}),detectPackageManager=()=>{let e=[`npm`,`yarn`,`pnpm`,`bun`],t=process.env.npm_config_user_agent;if(!t)return;let[n]=t.split(`/`);if(e.includes(n))return n},Da=C({name:`init`,description:`Initialize a new project using create-sdk.`,args:J.strictObject({name:G(J.string().optional(),{positional:!0,description:`Project name`}),template:G(J.string().optional(),{alias:`t`,description:`Template name`})}),run:async e=>{let t=await ti(),n=t.version&&t.version!==`0.0.0`?t.version:`latest`,r=detectPackageManager();r||=(f.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]:[]];f.log(`Running: ${r} ${i.join(` `)}`);let a=Li(r,i,{stdio:`inherit`}),o={command:r,args:i};if(a.error)throw W({code:`INIT_SPAWN_FAILED`,message:`Failed to run ${r}: ${a.error.message}`,suggestion:`Check that ${r} is installed and executable.`,command:`init`,context:o,cause:a.error});if(a.status!==0)throw W({code:`INIT_FAILED`,message:a.signal===null?`${r} create exited with code ${a.status}.`:`${r} create was terminated by ${a.signal}.`,command:`init`,context:{...o,exitCode:a.status??void 0,signal:a.signal??void 0}})}}),Oa=8085,ka=`http://localhost:${Oa}/callback`;function randomState(){return Oi.randomBytes(32).toString(`base64url`)}function getProfileUserMismatch(e,t,n){if(e.profile&&e.profileUser&&t!==e.profileUser&&n!==e.profileUser)return{profile:e.profile,oldUser:e.profileUser,authenticatedUser:t,loginMode:e.loginMode??`user`}}function quoteCommandArg(e,t=process.platform){return t===`win32`?/^[A-Za-z0-9_./:@+=,-]+$/.test(e)?e:void 0:`'${e.replaceAll(`'`,`'\\''`)}'`}function profileUpdateCommand(e){let t=quoteCommandArg(e.profile),n=quoteCommandArg(e.authenticatedUser);return t&&n?`tailor profile update --user ${n} -- ${t}`:[`tailor profile update --user <authenticated-user> -- <profile>`,`profile = ${JSON.stringify(e.profile)}`,`authenticated user = ${JSON.stringify(e.authenticatedUser)}`].join(`
79
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 W({code:`PROFILE_USER_MISMATCH`,message:`Profile "${e.profile}" is configured for "${e.oldUser}", but login authenticated "${e.authenticatedUser}".`,details:`The authenticated user has been saved.`,suggestion:`To use it with this profile, run:\n ${t}\n${n}`,context:{profile:e.profile,configuredUser:e.oldUser,authenticatedUser:e.authenticatedUser}})}function shouldUpdateCurrentUser(e,t){return!e||Pr(t)}const startAuthServer=async(e={})=>{let t=Lr(e.platformConfig),n=randomState(),r=await Di(),i=await t.authorizationCode.getAuthorizeUri({redirectUri:ka,state:n,codeVerifier:r}).catch(e=>{throw W({code:`LOGIN_AUTHORIZATION_URL_FAILED`,message:`Failed to prepare the login authorization URL: ${$r(e).message}`,cause:e})});return new Promise((a,o)=>{let handleCallback=async(i,l)=>{try{if(!i.url?.startsWith(`/callback`))throw W({code:`LOGIN_CALLBACK_INVALID`,message:`Invalid callback URL`});let o=`http://${i.headers.host}${i.url}`,c=new URL(o).searchParams.get(`code`);c&&f.registerSecret(c);let u=await t.authorizationCode.getTokenFromCodeRedirect(o,{redirectUri:ka,state:n,codeVerifier:r});le({accessToken:u.accessToken,refreshToken:u.refreshToken??void 0});let d=await Hr(u.accessToken,e.platformConfig),p=await T();await y(p,d.sub,{accessToken:u.accessToken,refreshToken:u.refreshToken??void 0},new Date(s(u.expiresAt,`token response missing expiresAt`)).toISOString(),{platformConfig:e.platformConfig,email:d.email});let m=getProfileUserMismatch(e,d.email,d.sub);if(m)throw E(p),profileUserMismatchError(m);(e.updateCurrentUser??!0)&&(p.current_user=d.sub),await _e(p,d.email,d.sub,e.platformConfig),E(p),l.writeHead(200,{"Content-Type":`application/json`}),l.end(JSON.stringify({status:`ok`,message:`Successfully authenticated. Please close this window.`})),a({user:d.sub,email:d.email})}catch(e){l.writeHead(401),l.end(`Authentication failed`),o($r(e))}finally{c.close()}},c=Ai.createServer((e,t)=>void handleCallback(e,t)),l=setTimeout(()=>{c.close(),o(W({code:`LOGIN_TIMEOUT`,message:`Login timeout exceeded`}))},3e5);c.on(`close`,()=>{clearTimeout(l)}),c.on(`error`,e=>{o(e)});let openBrowser=async()=>{f.info(`Opening browser for login:\n\n${i}\n`);try{await ji(i)}catch{f.warn(`Failed to open browser automatically. Please open the URL above manually.`)}};c.listen(Oa,()=>void openBrowser())})};async function loginAsMachineUser(e){let t=e.clientSecret??await P.password({message:`Client secret`}),n=await Rr(e.clientId,t,e.platformConfig),r=await T();await y(r,e.clientId,{accessToken:n.accessToken},new Date(s(n.expiresAt,`token response missing expiresAt`)).toISOString(),{platformConfig:e.platformConfig});let i=getProfileUserMismatch(e,e.clientId);if(i)throw E(r),profileUserMismatchError(i);return(e.updateCurrentUser??!0)&&(r.current_user=e.clientId),E(r),{user:e.clientId,email:null}}const Aa=C({name:`login`,description:`Login to Tailor Platform.`,args:J.xor([J.strictObject({profile:G(J.string().optional(),{alias:`p`,description:`Workspace profile whose platform settings should be used for login.`,env:`TAILOR_PLATFORM_PROFILE`})}).describe(`User Login`),J.strictObject({"machine-user":G(J.literal(!0),{description:`Login as a platform machine user.`,required:!0}),"client-id":G(J.string(),{description:`Client ID`,env:`TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID`,required:!0}),"client-secret":G(J.string().optional(),{description:`Client secret`,env:`TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET`}),profile:G(J.string().optional(),{alias:`p`,description:`Workspace profile whose platform settings should be used for login.`,env:`TAILOR_PLATFORM_PROFILE`})}).describe(`Machine User Login`)]),run:async e=>{try{let t,n;if(`profile`in e&&e.profile){let r=(await T()).profiles[e.profile];if(!r)throw W({code:`PROFILE_NOT_FOUND`,message:`Profile "${e.profile}" not found`});t=Me(r),n=r.user}let r=shouldUpdateCurrentUser(e.profile,t),i;i=`machine-user`in e?await loginAsMachineUser({clientId:e.clientId,clientSecret:e.clientSecret,profile:e.profile,profileUser:n,platformConfig:t,updateCurrentUser:r,loginMode:`machine-user`}):await startAuthServer({profile:e.profile,profileUser:n,platformConfig:t,updateCurrentUser:r,loginMode:`user`}),f.success(`Successfully logged in to Tailor Platform.`),A({changed:!0,...i})}finally{await kr()}}}),ja=C({name:`logout`,description:`Logout from Tailor Platform.`,args:J.strictObject({profile:G(J.string().optional(),{alias:`p`,description:`Workspace profile whose platform settings should be used for logout.`,env:`TAILOR_PLATFORM_PROFILE`})}),run:async e=>{let t=e.profile||process.env.TAILOR_PLATFORM_PROFILE,n=await T(),r=t?n.profiles[t]:void 0;if(t&&!r)throw W({code:`PROFILE_NOT_FOUND`,message:`Profile "${t}" not found`});let i=r?Me(r):void 0,a=r?r.user:n.current_user,o=Pr(i),s=t?{allowLegacyUserKey:!0}:void 0;if(!a){f.info(`You are not logged in.`),A({changed:!1,user:null,revoked:!1});return}let hasDefaultUserToken=()=>x(n,a,{platformUrl:Ar}),shouldClearCurrentUser=()=>n.current_user===a&&(o||!Je(n,a))&&!hasDefaultUserToken(),c,l=!1;try{c=await v(n,a,i,s)}catch(e){l=!0,f.warn(`Failed to revoke token: ${e instanceof Error?e.message:e}`)}if(!c&&!l){f.info(`You are not logged in.`);let e=shouldClearCurrentUser();e&&(n.current_user=null),E(n),A({changed:e,user:a,revoked:!1});return}let u=!1;if(c)try{let e=Lr(i),t=c.refreshToken?`refresh_token`:`access_token`;await e.revoke({accessToken:c.accessToken,refreshToken:c.refreshToken??null,expiresAt:Date.parse(c.userEntry.token_expires_at)},t),u=!0}catch(e){f.warn(`Failed to revoke token: ${e instanceof Error?e.message:e}`)}await At(n,a,i,s),shouldClearCurrentUser()&&(n.current_user=null),E(n),f.success(`Successfully logged out from Tailor Platform.`),A({changed:!0,user:a,revoked:u})}}),Ma=K({name:`machineuser`,description:`Manage machine users in your Tailor Platform application.`,subCommands:{list:Zt,token:Vt},defaultSubCommand:`list`}),Na=K({name:`oauth2client`,description:`Manage OAuth2 clients in your Tailor Platform application.`,subCommands:{list:jn,get:Lt},defaultSubCommand:`list`}),Pa=C({name:`open`,description:`Open Tailor Platform Console.`,args:J.strictObject({...D}),run:async e=>{let t=await un({workspaceId:e[`workspace-id`],profile:e.profile}),{config:n}=await B(e.config),r=n.name,i=`/workspaces/${t}/services/applications/${encodeURIComponent(r)}`,a=await re({profile:e.profile,...e[`workspace-id`]===void 0?{}:{allowMissingProfile:!0}}),o=new URL(i,a).toString(),s=f.jsonMode;f.info(`Opening Tailor Platform Console...`);let c=!0;try{await ji(o)}catch{c=!1}s?f.out({consoleUrl:o,workspaceId:t,applicationName:r,opened:c}):c?(f.out(`Console URL: ${o}`),f.out(`Workspace ID: ${t}`),f.out(`Application Name: ${r}`)):f.warn(`Failed to open browser automatically. Please open this URL manually:\n${o}`)}}),Fa=K({name:`folder`,description:`Manage organization folders.`,subCommands:{create:ln,delete:En,get:Kt,list:ze,update:ft}}),Ia=K({name:`organization`,description:`Manage Tailor Platform organizations.`,subCommands:{folder:Fa,get:be,list:Ce,tree:ue,update:me},defaultSubCommand:`list`}),La=/* @__PURE__ */ `api.auth.authconnection.crashreport.data.deploy.executor.function.generate.init.login.logout.machineuser.oauth2client.open.organization.plugin.profile.query.remove.secret.show.skills.staticwebsite.tailordb.upgrade.user.workflow.workspace`.split(`.`),Ra={seed:`@tailor-platform/sdk-plugin-seed`,setup:`@tailor-platform/sdk-plugin-setup`,"tailordb-erd":`@tailor-platform/sdk-plugin-tailordb-erd`},za=process.platform===`win32`?`;`:`:`;function*ancestorDirs(e){let t=q.resolve(e),n=q.dirname(t);for(;n!==t;)yield t,t=n,n=q.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{Si(e,process.platform===`win32`?Ci.F_OK:Ci.X_OK)}catch{return!1}if(process.platform===`win32`){let t=q.extname(e).toLowerCase();return t===``||windowsExecutableExts().includes(t)}return!0}function binaryCandidates(e){return process.platform===`win32`?[e,...windowsExecutableExts().map(t=>`${e}${t}`)]:[e]}function pathDirs(){return(process.env.PATH??``).split(za).filter(Boolean)}function nodeModulesBinDirs(){let e=[];for(let t of ancestorDirs(process.cwd()))e.push(q.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=q.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=q.extname(e);return t?e.slice(0,-t.length):e}function listPlugins(e){let t=`${e}-`,n=/* @__PURE__ */ new Map,scan=(e,r)=>{for(let i of e){let e;try{e=wi(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=q.join(i,a);isExecutable(s)&&n.set(o,{name:o,path:s,source:r})}}};return scan(nodeModulesBinDirs(),`node_modules`),scan(pathDirs(),`path`),[...n.values()]}async function resolveActiveUser(e){let t=await T(),n=e?t.profiles[e]?.user:t.current_user;if(n)return t.users[n]?.email??n}async function buildPluginEnv(e={}){let{profile:t}=e,n={},r=process.argv[1];r&&(n.TAILOR_BIN=r);try{let{version:e}=await ti();e&&(n.TAILOR_VERSION=e)}catch{}let i=oe();if(i&&(n.TAILOR_CONFIG_PATH=i),e.skipPlatformContext)return n;let a;try{a=await pn({profile:t,allowMissingProfile:!0})}catch{}n.TAILOR_PLATFORM_URL=Wr(a),n.TAILOR_PLATFORM_OAUTH2_CLIENT_ID=Mr(a);try{n.TAILOR_PLATFORM_WORKSPACE_ID=await un({profile:t})}catch{}try{let e=await resolveActiveUser(t);e&&(n.TAILOR_PLATFORM_USER=e)}catch{}try{let e=await nr({profile:t});e&&(n.TAILOR_PLATFORM_TOKEN=e)}catch{}return n}function signalToExitCode(e){let t=Pi.constants.signals[e];return typeof t==`number`?128+t:1}function buildSpawnTarget(e,t){if(process.platform!==`win32`)return{command:e,args:[...t],shell:!1};let n=q.extname(e).toLowerCase();return n===`.exe`||n===`.com`?{command:e,args:[...t],shell:!1}:n===`.cmd`||n===`.bat`?{command:e,args:[...t],shell:!0}:n===`.ps1`?{command:findExecutableIn(pathDirs(),`pwsh`)??findExecutableIn(pathDirs(),`powershell`)??`powershell`,args:[`-NoProfile`,`-ExecutionPolicy`,`Bypass`,`-File`,e,...t],shell:!1}:{command:findExecutableIn(pathDirs(),`sh`)??`sh`,args:[`-c`,`command "$@"`,`--`,e,...t],shell:!1}}function hasEnvFileFlag(e){for(let t of e){if(t===`--`)return!1;if(t===`--env-file`||t===`-e`||t===`--env-file-if-exists`||t.startsWith(`--env-file=`)||t.startsWith(`-e=`)||t.startsWith(`--env-file-if-exists=`))return!0}return!1}function explicitProfileFromArgs(e){let t;for(let n=0;n<e.length;n++){let r=e[n];if(r===void 0||r===`--`)break;if(r===`--profile`||r===`-p`){let r=e[n+1];r!==void 0&&!r.startsWith(`-`)&&(t=r,n++)}else r.startsWith(`--profile=`)?t=r.slice(10):r.startsWith(`-p=`)&&(t=r.slice(3))}return t||void 0}function pluginSlug(e,t){return[...e??[],t].join(`-`)}async function dispatchPlugin(e){let t=pluginSlug(e.commandPath,e.name),n=resolvePlugin(t,e.cliName);if(!n)return;let r=explicitProfileFromArgs(e.args)??e.profile,i={...process.env,...await buildPluginEnv({profile:r,skipPlatformContext:hasEnvFileFlag(e.args)})},{command:a,args:o,shell:s}=buildSpawnTarget(n.path,e.args);return await new Promise(n=>{let r=Ii(a,o,{stdio:`inherit`,env:i,shell:s});r.on(`error`,r=>{f.error(`Failed to run plugin "${e.cliName}-${t}": ${r.message}`),n(1)}),r.on(`close`,(e,t)=>{n(t?signalToExitCode(t):e??0)})})}async function dispatchPluginWithInstallHint(e){let t=await dispatchPlugin(e);if(t!==void 0)return t;let n=Ra[pluginSlug(e.commandPath,e.name)];if(!n)return;let r=[e.cliName,...e.commandPath??[],e.name].join(` `);return f.error(`"${r}" is provided by the ${n} CLI plugin, which is not installed.`),f.info(`Install it with: npm install -D ${n}`),1}const Ba=C({name:`list`,description:"List discovered plugins (executables named `<cli>-<name>` on PATH or node_modules/.bin).",args:J.strictObject({}),run:async()=>{let e=await ti(),t=Object.keys(e.bin??{})[0]||`tailor`,n=new Set(La),r=listPlugins(t);if(r.length===0){f.info(H`
80
80
  No plugins found.
81
81
  Install an executable named "${t}-<name>" on your PATH or in node_modules/.bin,
@@ -84,8 +84,8 @@ Error:`));let e=formatErrorWithSourcemap(b.error,p,process.cwd());e?f.log(e):f.l
84
84
  No profiles found.
85
85
  Please create a profile first using 'tailor profile create' command.
86
86
  `),t&&f.out([]);return}let r=n.map(([e,t])=>{let n=s(t,`profile entry "${e}" is undefined`);return{name:e,user:n.user,workspaceId:n.workspace_id,permission:n.readonly===!0?`read`:`write`,...n.machine_user?{machineUser:n.machine_user,machineUserOverride:n.machine_user_override??`allow`}:{},...n.platform_url?{platformUrl:n.platform_url}:{},...n.oauth2_client_id?{oauth2ClientId:n.oauth2_client_id}:{},...n.console_url?{consoleUrl:n.console_url}:{}}});f.out(r)}}),Ga=C({name:`update`,description:`Update profile properties.`,args:J.strictObject({name:G(J.string(),{positional:!0,description:`Profile name`}),user:G(J.string().optional(),{alias:`u`,description:`New user email address or machine user client ID`}),"workspace-id":G(J.string().optional(),{alias:`w`,description:`New workspace ID`}),permission:G(J.enum([`write`,`read`]).optional(),{description:`Profile permission. 'read' blocks all write commands; 'write' lifts the restriction.`}),"machine-user":G(J.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":G(J.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":G(J.union([J.url(),J.literal(``)]).optional(),{description:`Platform API base URL for this profile. Pass an empty string to clear.`}),"oauth2-client-id":G(J.string().optional(),{description:`OAuth2 client ID for logging in to this profile's platform. Pass an empty string to clear.`}),"console-url":G(J.union([J.url(),J.literal(``)]).optional(),{description:`Console base URL for this profile. Pass an empty string to clear.`})}),run:async e=>{let t=await T(),n=t.profiles[e.name];if(!n)throw W({code:`PROFILE_NOT_FOUND`,message:`Profile "${e.name}" not found.`});if(!e.user&&!e[`workspace-id`]&&e.permission===void 0&&e[`machine-user`]===void 0&&e[`machine-user-override`]===void 0&&e[`platform-url`]===void 0&&e[`oauth2-client-id`]===void 0&&e[`console-url`]===void 0)throw W({code:`PROFILE_UPDATE_EMPTY`,message:`Please provide at least one property to update.`,command:`profile update`});let r=n.user,i=e.user||r,a=n.workspace_id,o=e[`workspace-id`]||a,s=i,c=e[`machine-user`]===``?void 0:e[`machine-user`]??n.machine_user,l=e[`machine-user-override`]===`allow`?void 0:e[`machine-user-override`]??n.machine_user_override,u=e[`platform-url`]===``?void 0:e[`platform-url`]??n.platform_url,d=e[`oauth2-client-id`]===``?void 0:e[`oauth2-client-id`]??n.oauth2_client_id,p=e[`console-url`]===``?void 0:e[`console-url`]??n.console_url,m={...u?{platformUrl:u}:{},...d?{oauth2ClientId:d}:{},...p?{consoleUrl:p}:{}},h=Object.keys(m).length>0?m:void 0,g=e[`platform-url`]===``?Me(n):h;if((e[`machine-user`]!==void 0||e[`machine-user-override`]!==void 0)&&l===`deny`&&!c)throw e[`machine-user-override`]===`deny`?W({code:`PROFILE_OPTIONS_INVALID`,message:`--machine-user-override deny requires --machine-user.`,command:`profile update`}):W({code:`PROFILE_OPTIONS_INVALID`,message:`Cannot clear the machine user while machine-user-override is "deny". Also pass --machine-user-override allow.`,command:`profile update`});if(e.user!==void 0||e[`workspace-id`]!==void 0||e[`platform-url`]!==void 0){let n=await ar(t,i,g,e.name);s=n.user;let r=await Kr(n.accessToken,h);if(!(await Sr(async(e,t)=>{let{workspaces:n,nextPageToken:i}=await r.listWorkspaces({pageToken:e,pageSize:t});return[n,i]})).find(e=>e.id===o))throw W({code:`WORKSPACE_NOT_FOUND`,message:`Workspace "${o}" not found.`})}n.user=s,n.workspace_id=o,e.permission===`read`?n.readonly=!0:e.permission===`write`&&delete n.readonly,e[`machine-user`]!==void 0&&(e[`machine-user`]===``?delete n.machine_user:n.machine_user=e[`machine-user`]),e[`machine-user-override`]===`deny`?n.machine_user_override=`deny`:e[`machine-user-override`]===`allow`&&delete n.machine_user_override,e[`platform-url`]!==void 0&&(e[`platform-url`]===``?delete n.platform_url:n.platform_url=e[`platform-url`]),e[`oauth2-client-id`]!==void 0&&(e[`oauth2-client-id`]===``?delete n.oauth2_client_id:n.oauth2_client_id=e[`oauth2-client-id`]),e[`console-url`]!==void 0&&(e[`console-url`]===``?delete n.console_url:n.console_url=e[`console-url`]),E(t),e.json||f.success(`Profile "${e.name}" updated successfully`);let _={name:e.name,user:s,workspaceId:o,permission:n.readonly===!0?`read`:`write`,...n.machine_user?{machineUser:n.machine_user,machineUserOverride:n.machine_user_override??`allow`}:{},...n.platform_url?{platformUrl:n.platform_url}:{},...n.oauth2_client_id?{oauth2ClientId:n.oauth2_client_id}:{},...n.console_url?{consoleUrl:n.console_url}:{}};f.out(_)}}),Ka=K({name:`profile`,description:`Manage workspace profiles (user + workspace combinations).`,subCommands:{create:Ha,delete:Ua,list:Wa,update:Ga},defaultSubCommand:`list`});async function resolveSecretValue(e,t,n){if(e.value!==void 0)return e.value;let missing=e=>W({code:`SECRET_VALUE_REQUIRED`,message:`No secret value was given: --value is omitted and standard input ${e}.`,suggestion:`Pass --value, or pipe or redirect the value into the command.`,command:n});if(t.isTTY===!0)throw missing(`is a terminal`);let tooLarge=()=>W({code:`SECRET_VALUE_TOO_LARGE`,message:`The secret value read from standard input exceeds 128 KiB.`,command:n}),r=[],i=0;for await(let e of t){let t=typeof e==`string`?Buffer.from(e):e;if(i+=t.length,i>131074)throw tooLarge();r.push(t)}let a;try{a=new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}).decode(Buffer.concat(r))}catch(e){throw W({code:`SECRET_VALUE_INVALID_UTF8`,message:`The secret value read from standard input is not valid UTF-8.`,command:n,cause:e})}let o=a.replace(/\r?\n$/,``);if(Buffer.byteLength(o)>131072)throw tooLarge();if(o===``)throw missing(`is empty`);return o}const qa={"vault-name":G(J.string(),{alias:`V`,description:`Vault name`})},Ja={...qa,name:G(J.string(),{alias:`n`,description:`Secret name`})},Ya={...Ja,value:G(J.string().optional(),{alias:`v`,description:`Secret value (read from standard input when omitted)`})};function secretValueNotes(e){return`Pass the value with \`--value\`, or omit \`--value\` and pipe the value in to keep it out of shell history and process listings, for example \`printf '%s' "$STRIPE_KEY" | tailor secret ${e} --vault-name api-keys --name stripe-secret-key\`. A piped value can be up to 128 KiB, and one trailing newline is removed from it. In a vault managed by \`defineSecretManager()\`, the command asks for confirmation before releasing the vault from the config, which needs an interactive terminal, so pass \`--yes\` when piping the value.`}async function checkVaultManaged(e){let{client:t,workspaceId:n,vaultName:r}=e,i=L(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[mn]}catch{return a}return o?(f.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 Rt(t,{trn:n,remove:[mn,Jn,Pt]}),f.info(`Config ownership has been removed from this vault. Remove it from defineSecretManager() in your config to prevent the next apply from re-claiming it.`)}const Xa=C({name:`create`,description:`Create a secret in a vault.`,args:J.strictObject({...N,...Ya,...I}),notes:secretValueNotes(`create`),run:async e=>{let t=await resolveSecretValue(e,process.stdin,`secret create`);f.registerSecret(t),await z({profile:e.profile});let{client:n,workspaceId:r}=await j({profile:e.profile,workspaceId:e[`workspace-id`]}),i=await checkVaultManaged({client:n,workspaceId:r,vaultName:e[`vault-name`]});if(i.isManaged&&!e.yes&&!await P.confirm({message:`Do you want to proceed?`,default:!1}))throw W({code:`SECRET_CREATION_CANCELLED`,message:`Secret creation cancelled. The vault is still managed by the config.`});try{await n.createSecretManagerSecret({workspaceId:r,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name,secretmanagerSecretValue:t})}catch(t){if(t instanceof Q){if(t.code===Z.NotFound)throw W({code:`VAULT_NOT_FOUND`,message:`Vault "${e[`vault-name`]}" not found.`,cause:t});if(t.code===Z.AlreadyExists)throw W({code:`SECRET_EXISTS`,message:`Secret "${e.name}" already exists.`,cause:t})}throw t}i.isManaged&&await releaseVaultOwnership({client:n,...i}),f.success(`Secret: ${e.name} created in vault: ${e[`vault-name`]}`),A({changed:!0,workspaceId:r,vaultName:e[`vault-name`],name:e.name,vaultOwnershipReleased:i.isManaged})}}),Za=C({name:`delete`,description:`Delete a secret in a vault.`,args:J.strictObject({...N,...Ja,...I}),run:async e=>{await z({profile:e.profile});let{client:t,workspaceId:n}=await j({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e[`vault-name`]});if(!e.yes&&await P.text({message:`Enter the secret name to confirm deletion ("${e.name}"):`})!==e.name)throw W({code:`SECRET_DELETION_CANCELLED`,message:`Secret deletion cancelled: the entered name did not match.`,suggestion:`Run the command again and enter the name exactly as shown, or pass --yes to skip the confirmation.`});try{await t.deleteSecretManagerSecret({workspaceId:n,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?W({code:`SECRET_NOT_FOUND`,message:`Secret "${e.name}" not found in vault "${e[`vault-name`]}".`,cause:t}):t}r.isManaged&&await releaseVaultOwnership({client:t,...r}),f.success(`Secret: ${e.name} deleted from vault: ${e[`vault-name`]}`),A({changed:!0,workspaceId:n,vaultName:e[`vault-name`],name:e.name,vaultOwnershipReleased:r.isManaged})}});function secretInfo(e){return{name:e.name,createdAt:e.createTime?Ti(e.createTime):null,updatedAt:e.updateTime?Ti(e.updateTime):null}}async function secretList(e){let{client:t,workspaceId:n}=await j({profile:e.profile,workspaceId:e.workspaceId}),r=Nt(e.order);return(await Gr(async(i,a)=>{let{secrets:o,nextPageToken:s}=await t.listSecretManagerSecrets({workspaceId:n,secretmanagerVaultName:e.vaultName,pageToken:i,pageSize:a,pageDirection:r});return[o,s]},{limit:e.limit})).map(secretInfo)}const Qa=C({name:`list`,description:`List all secrets in a vault.`,args:J.strictObject({...N,...qa,...Ln()}),run:async e=>{try{let t=await Jt(e.limit,t=>secretList({workspaceId:e[`workspace-id`],profile:e.profile,vaultName:e[`vault-name`],order:e.order,limit:t})),n=t.items;f.out(n),await F(t,e.limit)}catch(t){throw t instanceof Q&&t.code===Z.NotFound?W({code:`VAULT_NOT_FOUND`,message:`Vault "${e[`vault-name`]}" not found.`,cause:t}):t}}}),$a=C({name:`update`,description:`Update a secret in a vault.`,args:J.strictObject({...N,...Ya,...I}),notes:secretValueNotes(`update`),run:async e=>{let t=await resolveSecretValue(e,process.stdin,`secret update`);f.registerSecret(t),await z({profile:e.profile});let{client:n,workspaceId:r}=await j({profile:e.profile,workspaceId:e[`workspace-id`]}),i=await checkVaultManaged({client:n,workspaceId:r,vaultName:e[`vault-name`]});if(i.isManaged&&!e.yes&&!await P.confirm({message:`Do you want to proceed?`,default:!1}))throw W({code:`SECRET_UPDATE_CANCELLED`,message:`Secret update cancelled. The vault is still managed by the config.`});try{await n.updateSecretManagerSecret({workspaceId:r,secretmanagerVaultName:e[`vault-name`],secretmanagerSecretName:e.name,secretmanagerSecretValue:t})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?W({code:`SECRET_NOT_FOUND`,message:`Secret "${e.name}" not found in vault "${e[`vault-name`]}".`,cause:t}):t}i.isManaged&&await releaseVaultOwnership({client:n,...i}),f.success(`Secret: ${e.name} updated in vault: ${e[`vault-name`]}`),A({changed:!0,workspaceId:r,vaultName:e[`vault-name`],name:e.name,vaultOwnershipReleased:i.isManaged})}}),eo={name:G(J.string(),{positional:{named:!0},description:`Vault name`})},to=C({name:`create`,description:`Create a new Secret Manager vault.`,args:J.strictObject({...N,...eo}),run:async e=>{await z({profile:e.profile});let{client:t,workspaceId:n}=await j({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?W({code:`VAULT_EXISTS`,message:`Vault "${e.name}" already exists.`,cause:t}):t}f.success(`Vault: ${e.name} created`),A({changed:!0,workspaceId:n,name:e.name})}}),no=C({name:`delete`,description:`Delete a Secret Manager vault.`,args:J.strictObject({...N,...eo,...I}),run:async e=>{await z({profile:e.profile});let{client:t,workspaceId:n}=await j({profile:e.profile,workspaceId:e[`workspace-id`]}),r=await checkVaultManaged({client:t,workspaceId:n,vaultName:e.name});if(!e.yes&&await P.text({message:`Enter the vault name to confirm deletion ("${e.name}"):`})!==e.name)throw W({code:`VAULT_DELETION_CANCELLED`,message:`Vault deletion cancelled: the entered name did not match.`,suggestion:`Run the command again and enter the name exactly as shown, or pass --yes to skip the confirmation.`});try{await t.deleteSecretManagerVault({workspaceId:n,secretmanagerVaultName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?W({code:`VAULT_NOT_FOUND`,message:`Vault "${e.name}" not found.`,cause:t}):t}r.isManaged&&f.info(`Remove this vault from defineSecretManager() in your config to prevent the next apply from re-creating it.`),f.success(`Vault: ${e.name} deleted`),A({changed:!0,workspaceId:n,name:e.name,managed:r.isManaged})}});function vaultInfo(e){return{name:e.name,createdAt:e.createTime?Ti(e.createTime):null,updatedAt:e.updateTime?Ti(e.updateTime):null}}async function vaultList(e){let{client:t,workspaceId:n}=await j({profile:e?.profile,workspaceId:e?.workspaceId}),r=Nt(e?.order);return(await Gr(async(e,i)=>{let{vaults:a,nextPageToken:o}=await t.listSecretManagerVaults({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e?.limit})).map(vaultInfo)}const ro=C({name:`list`,description:`List all Secret Manager vaults in the workspace.`,args:J.strictObject({...N,...Ln()}),run:async e=>{let t=await Jt(e.limit,t=>vaultList({workspaceId:e[`workspace-id`],profile:e.profile,order:e.order,limit:t})),n=t.items;f.out(n),await F(t,e.limit)}}),io=K({name:`vault`,description:`Manage Secret Manager vaults.`,subCommands:{create:to,delete:no,list:ro},defaultSubCommand:`list`}),ao=K({name:`secret`,description:`Manage Secret Manager vaults and secrets.`,subCommands:{vault:io,create:Xa,update:$a,list:Qa,delete:Za},defaultSubCommand:`vault`}),oo={[n.UNSPECIFIED]:`unspecified`,[n.PENDING]:`pending`,[n.VERIFYING]:`verifying`,[n.CERT_ISSUED]:`cert_issued`,[n.ACTIVE]:`active`,[n.FAILED]:`failed`},so=C({name:`get`,description:`Get details of a custom domain.`,args:J.strictObject({...N,domain:G(J.string(),{positional:!0,description:`Custom domain name`})}),run:async e=>{let{client:t,workspaceId:n}=await j({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 W({code:`STATIC_WEBSITE_DOMAIN_NOT_FOUND`,message:r});let a={domain:i.domain,status:oo[i.status]??`unknown`,trafficCnameTarget:i.trafficCnameTarget,certificateCnameTarget:i.certificateCnameTarget,errorMessage:i.errorMessage||void 0};f.out(a)}catch(e){throw e instanceof Q&&e.code===Z.NotFound?W({code:`STATIC_WEBSITE_DOMAIN_NOT_FOUND`,message:r,cause:e}):e}}}),co=C({name:`list`,description:`List custom domains for a static website.`,args:J.strictObject({...N,name:G(J.string(),{positional:!0,description:`Static website name`})}),run:async e=>{let{client:t,workspaceId:n}=await j({profile:e.profile,workspaceId:e[`workspace-id`]});try{let{customDomains:r}=await t.listCustomDomains({workspaceId:n,staticWebsiteName:e.name});if(r.length===0){f.info(`No custom domains found.`),f.jsonMode&&f.out([]);return}let i=r.map(e=>({domain:e.domain,status:oo[e.status]??`unknown`,trafficCnameTarget:e.trafficCnameTarget,certificateCnameTarget:e.certificateCnameTarget}));f.out(i)}catch(t){throw t instanceof Q&&t.code===Z.NotFound?W({code:`STATIC_WEBSITE_NOT_FOUND`,message:`Static website "${e.name}" not found.`,cause:t}):t}}}),lo=K({name:`domain`,description:`Manage custom domains for static websites.`,subCommands:{list:co,get:so}}),uo=C({name:`get`,description:`Get details of a specific static website.`,args:J.strictObject({...N,name:G(J.string(),{positional:!0,description:`Static website name`})}),run:async e=>{let{client:t,workspaceId:n}=await j({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 W({code:`STATIC_WEBSITE_NOT_FOUND`,message:r});let a={workspaceId:n,name:i.name,description:i.description,url:i.url,allowedIpAddresses:e.json?i.allowedIpAddresses:i.allowedIpAddresses.join(`
87
- `)};f.out(a)}catch(e){throw e instanceof Q&&e.code===Z.NotFound?W({code:`STATIC_WEBSITE_NOT_FOUND`,message:r,cause:e}):e}}});async function listStaticWebsites(e){let{client:t,workspaceId:n}=await j({profile:e?.profile,workspaceId:e?.workspaceId}),r=Nt(e?.order);return(await Gr(async(e,i)=>{let{staticwebsites:a,nextPageToken:o}=await t.listStaticWebsites({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e?.limit})).map(e=>({workspaceId:n,name:e.name,description:e.description,url:e.url,allowedIpAddresses:e.allowedIpAddresses}))}const fo=C({name:`list`,description:`List all static websites in a workspace.`,args:J.strictObject({...N,...Ln()}),run:async e=>{let t=f.jsonMode,n=await Jt(e.limit,t=>listStaticWebsites({workspaceId:e[`workspace-id`],profile:e.profile,order:e.order,limit:t})),r=n.items,i=t?r:r.map(({allowedIpAddresses:e,...t})=>{if(e.length===0)return{...t,allowedIpAddresses:`No allowed IP addresses`};let n=e.length,r=n===1?`1 IP address`:`${n} IP addresses`;return{...t,allowedIpAddresses:r}});f.out(i),await F(n,e.limit)}}),po=K({name:`staticwebsite`,description:`Manage static websites in your workspace.`,subCommands:{deploy:Le,domain:lo,list:fo,get:uo},defaultSubCommand:`list`}),mo=new Set(Object.values(Ae));async function activateBaseline(e,t,n,r){let i=await $.realpath(e),a=q.dirname(i),o=q.basename(i),s=await $.mkdtemp(q.join(a,`.${o}-rebaseline-`)),c=`${s}-previous`,l=!1,u=!1;try{await $.cp(i,s,{recursive:!0});for(let e of await $.readdir(s,{withFileTypes:!0})){if(!e.isDirectory()||!Ge.test(e.name))continue;let t=q.join(s,e.name);(await $.readdir(t)).some(e=>mo.has(e))&&await $.rm(t,{recursive:!0,force:!0})}let e={...t,namespace:n,version:8,createdAt:(/* @__PURE__ */ new Date()).toISOString(),rebaseline:r},a=await ge(e,s,0);Fn(a.filePath),await $.rename(i,c),l=!0;try{await $.rename(s,i),u=!0}catch(e){throw await $.rename(c,i),l=!1,e}try{await $.rm(c,{recursive:!0,force:!0})}catch(e){f.warn(`The previous migration directory remains at ${c}: ${e instanceof Error?e.message:String(e)}`)}l=!1}finally{X.existsSync(s)&&await $.rm(s,{recursive:!0,force:!0}),!u&&l&&X.existsSync(c)&&await $.rename(c,i)}}async function rebaseline(e){w(`tailordb migration`);let{config:t,plugins:n}=await B(e.configPath),r=q.dirname(t.path),i=or(V(t,r),e.namespace),a=`First run ${U({command:`tailor`,args:[`tailordb`,`migration`,`generate`,`--config`,t.path]})}.`;Fe(i.migrationsDir,i.namespace);let o=M(i.migrationsDir);if(!o)throw W({code:`MIGRATION_HISTORY_NOT_FOUND`,message:`No migration history found for namespace "${i.namespace}".`,suggestion:a});let s=st(i.migrationsDir),c=M(i.migrationsDir,0)?.rebaseline?.historyId??null,u=te([i])[i.namespace],d=n.length>0?new li(n):void 0,{defineApplication:p}=await import(`../application-C2bPmmbh.mjs`),m=p({config:t,pluginManager:d});for(let e of m.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let g=m.tailorDBServices.find(e=>e.namespace===i.namespace);if(!g)throw W({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${i.namespace}"`});let assertLocalTypesReady=()=>{let e=se(g.types,i.namespace),t=bt(o,e.tables,i.namespace);if(Et(t))throw f.error(`Migration history does not reproduce the current local schema for namespace ${h.bold(i.namespace)}:`),f.log(on(t)),W({code:`MIGRATION_HISTORY_MISMATCH`,message:`Refusing to re-baseline: the migration history must reproduce the current local schema.`,suggestion:a})},localSourceFiles=()=>[t.path,...l(g.config,r)];assertLocalTypesReady();let _=Xe(localSourceFiles()),{client:v,workspaceId:y}=await j({profile:e.profile,workspaceId:e.workspaceId}),b=[`--config`,t.path,...k({workspaceId:y,profile:e.profile})],ee=`Run ${U({command:`tailor`,args:[`tailordb`,`migration`,`set`,`0`,`--namespace`,i.namespace,...b]})}`,x=`after resolving the connection error, deploy with schema checks enabled by running ${U({command:`tailor`,args:[`deploy`,...b]})}.`,assertConnectedWorkspaceReady=async(e,n)=>{let r=await O(v,L(y,`tailordb`,i.namespace));en(r,i.namespace);let a=r.number;if(a!==s){let e=a===null?`<unset>`:R(a);throw W({code:`REBASELINE_CHECKPOINT_BEHIND`,message:`The connected workspace must be at the latest migration ${R(s)} before re-baselining; current checkpoint is ${e}.`})}if(r.historyIdInvalid)throw W({code:`REBASELINE_REMOTE_HISTORY_INVALID`,message:`Refusing to re-baseline: the connected workspace has an invalid migration history marker.`});if(r.historyId!==e)throw W(n===`confirmation`?{code:`REBASELINE_STATE_CHANGED`,message:`The connected workspace migration history changed while waiting for confirmation.`,suggestion:`Run the command again.`}:{code:`REBASELINE_REMOTE_HISTORY_MISMATCH`,message:`Refusing to re-baseline: the connected workspace does not match the local migration history.`});let o=await nt(v,y,[i],t,[he(g)]),c=o[0];if(!c||c.remoteMigrationNumber!==s||c.hasDrift||c.checkpointMissingLocal)throw c?.hasDrift&&(f.error(`Remote schema drift detected:`),f.log(fr(o))),W({code:`REBASELINE_REMOTE_SCHEMA_MISMATCH`,message:`Refusing to re-baseline: the connected workspace remote schema must match the latest migration.`})};if(await assertConnectedWorkspaceReady(c,`initial`),f.newline(),f.warn(`This will replace the migration history for ${h.bold(i.namespace)}.`),f.log(` Latest migration: ${R(s)}`),f.log(` New history: 0000/schema.json only`),f.log(` migrate.ts and db.ts files will disappear from the working tree.`),f.log(` Committed migration files will remain in Git history. Preserve any uncommitted files before continuing.`),f.log(` Every other environment must already be at the latest migration.`),f.log(` The connected workspace checkpoint will be reset to 0000.`),f.newline(),!e.yes&&!await P.confirm({message:`Re-baseline this migration history and reset the connected workspace checkpoint?`,default:!1}))throw W({code:`REBASELINE_CANCELLED`,message:`Migration re-baseline cancelled.`});if(Fe(i.migrationsDir,i.namespace),te([i])[i.namespace]!==u)throw W({code:`REBASELINE_STATE_CHANGED`,message:`Migration files changed while waiting for confirmation.`,suggestion:`Run the command again.`});if(Xe(localSourceFiles())!==_)throw W({code:`REBASELINE_STATE_CHANGED`,message:`Local TailorDB table or config files changed.`,suggestion:`Run the command again.`});assertLocalTypesReady(),await assertConnectedWorkspaceReady(c,`confirmation`);let S={historyId:_t(),replacedHistoryId:c,replacedLatestMigration:s};await activateBaseline(i.migrationsDir,o,i.namespace,S);try{await mt(v,y,i.namespace,0,S.historyId)}catch(e){throw W({code:`REBASELINE_CHECKPOINT_UPDATE_FAILED`,message:`The local migration history was re-baselined, but the connected workspace checkpoint could not be updated.`,suggestion:`${ee}, or ${x}`,cause:e})}return f.success(`Re-baselined ${h.bold(i.namespace)} and reset the connected workspace checkpoint to 0000.`),{changed:!0,workspaceId:y,namespace:i.namespace,...S,schemaPath:rt(i.migrationsDir,0,`schema`)}}const ho=C({name:`rebaseline`,description:`Collapse the full migration history into a new 0000 baseline.`,notes:`Re-baselining removes migrations after 0000 from the working tree, records a new migration history ID, and resets the connected workspace checkpoint without changing its schema or data. Every environment must already have applied the latest migration before you run this command.`,args:J.strictObject({...D,...I,namespace:G(J.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await z({profile:e.profile});let t=await rebaseline({configPath:e.config,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile});A(t)}});async function fetchRemoteGqlPermissions(e){let{client:t,workspaceId:n,namespace:r}=e;return pr(async(e,i)=>{let{permissions:a,nextPageToken:o}=await t.listTailorDBGQLPermissions({workspaceId:n,namespaceName:r,pageToken:e,pageSize:i});return[a,o]})}async function fetchRemoteTypes(e){let{client:t,workspaceId:n,namespace:r}=e;return Sr(async(e,i)=>{try{let{tailordbTypes:a,nextPageToken:o}=await t.listTailorDBTypes({workspaceId:n,namespaceName:r,pageToken:e,pageSize:i});return[a,o]}catch(e){throw e instanceof Q&&e.code===Z.NotFound?W({code:`MIGRATION_NAMESPACE_NOT_DEPLOYED`,message:`Cannot apply the snapshot: TailorDB namespace "${r}" has not been deployed yet.`,suggestion:`Deploy the namespace first.`,cause:e}):e}})}async function planSnapshotApply(e){let{snapshot:t,...n}=e,r=await fetchRemoteTypes(n),i=new Set(r.map(e=>e.name)),{creates:a,updates:o,deletes:s}=fe(t,i),c=await fetchRemoteGqlPermissions(n),l=new Set(c.map(e=>e.typeName)),u=Object.entries(t.tables).flatMap(([e,t])=>t.permissions?.gql?[{typeName:e,permission:Pn(t.permissions.gql)}]:[]),d=new Set(u.map(e=>e.typeName));return{creates:a,updates:o,deletes:s,desiredGqlPermissions:u,gqlPermissionDeletes:c.filter(e=>!d.has(e.typeName)),remoteGqlPermissionTypes:l}}async function applySnapshotPlan(e){let{client:t,workspaceId:n,namespace:r,snapshot:i,manifestOptions:a,plan:o}=e,{creates:s,updates:c,deletes:l,desiredGqlPermissions:u,gqlPermissionDeletes:d}=o,f=Te(i,a),manifestFor=e=>{let t=f.get(e);if(!t)throw Zr(`Internal error: no manifest generated for table "${e}". No changes were applied.`);return t},p=s.map(e=>manifestFor(e)),m=c.map(e=>manifestFor(e));await Promise.all([...p.map(e=>t.createTailorDBType({workspaceId:n,namespaceName:r,tailordbType:e})),...m.map(e=>t.updateTailorDBType({workspaceId:n,namespaceName:r,tailordbType:e}))]),await Promise.all(u.map(({typeName:e,permission:i})=>{let a={workspaceId:n,namespaceName:r,typeName:e,permission:i};return o.remoteGqlPermissionTypes.has(e)?t.updateTailorDBGQLPermission(a):t.createTailorDBGQLPermission(a)})),await Promise.all(d.map(e=>t.deleteTailorDBGQLPermission({workspaceId:n,namespaceName:r,typeName:e.typeName}))),await Promise.all(l.map(e=>t.deleteTailorDBType({workspaceId:n,namespaceName:r,tailordbTypeName:e})))}async function assertMigrationsReproduceLocalTypes(e,t){let{config:n,plugins:r}=e,i=r.length>0?new li(r):void 0,{defineApplication:a,generatePluginFilesIfNeeded:o}=await import(`../application-C2bPmmbh.mjs`),s=a({config:n,pluginManager:i}),c=s.tailorDBServices.find(e=>e.namespace===t.namespace);if(!c)throw W({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${t.namespace}"`});for(let e of s.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let l=o(i,s.tailorDBServices,n.path),u=s.executorService??(l.length>0?(await import(`../service-Ca1WwyIt.mjs`)).createExecutorService({config:{files:[]},baseDir:q.dirname(n.path)}):void 0);await u?.loadExecutors(),l.length>0&&await u?.loadPluginExecutorFiles([...l]);let d=/* @__PURE__ */ new Set;for(let e of Object.values(u?.executors??{}))kn(e)&&e.trigger.kind===`tailordb`&&d.add(e.trigger.tableName);let p={executorUsedTables:d,namespaceGqlOperations:c.config.gqlOperations},m=M(t.migrationsDir);if(!m)return p;let g=se(c.types,t.namespace),_=bt(m,g.tables,t.namespace);if(!Et(_))return p;throw f.error(`Migration history does not reproduce the current local schema for namespace ${h.bold(t.namespace)}:`),f.log(on(_)),f.newline(),f.info(`This usually means one of the following:`),f.info(` - Migration files were edited and replaying them no longer matches the table definitions — fix the migration files.`,{mode:`plain`}),f.info(` - Table definitions changed without a new migration — run 'tailor tailordb migration generate' first.`,{mode:`plain`}),f.newline(),W({code:`MIGRATION_HISTORY_MISMATCH`,message:`Refusing to continue: the migration history must reproduce the current local schema before it can be applied to the remote.`,suggestion:`Generate a migration for the pending schema changes first.`})}async function sync(e){w(`tailordb migration`);let t=Cn(e.number),n=await B(e.configPath),{config:r}=n,i=q.dirname(r.path),a=V(r,i),o=or(a,e.namespace);Fe(o.migrationsDir,o.namespace);let s=ee(o.migrationsDir,t),c=M(o.migrationsDir,t);if(!c)throw W({code:`MIGRATION_BASELINE_NOT_FOUND`,message:`No initial schema snapshot found in ${o.migrationsDir}. Expected 0000/schema.json.`,suggestion:`Create the initial schema snapshot first.`});let l=await assertMigrationsReproduceLocalTypes(n,o),{client:u,workspaceId:d}=await j({profile:e.profile,workspaceId:e.workspaceId}),p=L(d,`tailordb`,o.namespace),m=await O(u,p);en(m,o.namespace);let g=m.number,_=await planSnapshotApply({client:u,workspaceId:d,namespace:o.namespace,snapshot:c}),{creates:v,updates:y,deletes:b,desiredGqlPermissions:x,gqlPermissionDeletes:S}=_;f.newline(),f.info(`Namespace: ${h.bold(o.namespace)}`),f.log(` Current migration: ${g===null?`<unset>`:h.bold(R(g))}`),f.log(` Target migration: ${h.bold(R(t))}`),f.log(` Tables to create: ${h.bold(String(v.length))}`),f.log(` Tables to update: ${h.bold(String(y.length))}`),f.log(` Tables to delete: ${h.bold(String(b.length))}`),f.log(` GQL permissions to set: ${h.bold(String(x.length))}`),f.log(` GQL permissions to delete: ${h.bold(String(S.length))}`),f.newline();let te=v.length+y.length+b.length+x.length+S.length;if(te===0?f.info(`No tables to apply; only the migration label will be updated.`):(f.warn(`This operation will overwrite remote TailorDB tables to match the selected snapshot.`),b.length>0&&f.warn(`Existing data in deleted tables will be lost.`),f.newline()),f.warn(`Sync never runs migrate.ts scripts; it only applies the schema snapshot and moves the migration label.`),f.newline(),g!==null&&t<g?(f.warn(`Migrations ${R(t+1)}–${R(g)} 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).`),f.newline()):g!==null&&t>g&&(f.warn(`Moving the migration label forwards (${R(g)} → ${R(t)}): migrate.ts scripts for migrations ${R(g+1)}–${R(t)} will not run on the next deploy.`),f.newline()),!e.yes){if(!await P.confirm({message:`Continue and set migration label to ${R(t)}?`,default:!1}))throw W({code:`MIGRATION_SYNC_CANCELLED`,message:`Migration sync cancelled.`});f.newline()}try{await applySnapshotPlan({client:u,workspaceId:d,namespace:o.namespace,snapshot:c,manifestOptions:l,plan:_})}catch(e){ht(e,[`The target snapshot marks a field as required, but existing remote records have no value for it.`,`Populate those records first (e.g. with a migration script applied via 'tailor deploy'), then re-run the sync.`])}let ne=c.rebaseline?.historyId,re=await mt(u,d,o.namespace,t,ne);return f.success(`Synced namespace ${h.bold(o.namespace)} to migration ${h.bold(R(t))}.`),t<s&&(f.newline(),f.info(`Run 'tailor deploy' to apply migrations ${R(t+1)}–${R(s)} from the working tree.`)),{changed:te>0||re,workspaceId:d,namespace:o.namespace,previousMigrationNumber:g,migrationNumber:t,historyId:ne??null,tables:{created:v,updated:y,deleted:b},gqlPermissions:{set:x.map(({typeName:e})=>e),deleted:S.map(({typeName:e})=>e)}}}const go=C({name:`sync`,description:`Sync remote TailorDB schema to a specific migration snapshot (recovery from --no-schema-check drift).`,args:J.strictObject({...D,...I,number:G(J.string(),{positional:!0,description:`Migration number to sync to (e.g., 0001 or 1; 0 targets the baseline snapshot)`}),namespace:G(J.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await z({profile:e.profile});let t=await sync({configPath:e.config,number:e.number,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile});A(t)}});async function assertMigrationStateUnchanged(e){let{client:t,workspaceId:n,namespace:r,before:i}=e,a=await O(t,L(n,`tailordb`,r));if(a.number!==i.number||a.historyId!==i.historyId||a.inProgress?.number!==i.inProgress?.number||a.inProgress?.executionId!==i.inProgress?.executionId)throw W({code:`MIGRATION_RESOLVE_STATE_CHANGED`,message:`The migration state of namespace "${r}" changed while the command was running.`,suggestion:`Run the command again.`})}async function resolve$1(e){w(`tailordb migration`);let t=await B(e.configPath),n=q.dirname(t.config.path),r=or(V(t.config,n),e.namespace),{namespace:i}=r;Fe(r.migrationsDir,i);let{client:a,workspaceId:o}=await j({profile:e.profile,workspaceId:e.workspaceId}),s=await O(a,L(o,`tailordb`,i));if(s.inProgressInvalid)throw W({code:`MIGRATION_RESOLVE_RECORD_UNREADABLE`,message:`Namespace "${i}" records a partially applied migration that cannot be read.`,suggestion:`Run 'tailor tailordb migration status --namespace ${i}' to inspect the migration state.`});if(!s.inProgress||$n(s))throw W({code:`MIGRATION_RESOLVE_NO_IN_PROGRESS`,message:`No migration is in progress for namespace "${i}".`,suggestion:`Run 'tailor tailordb migration status --namespace ${i}' to check the migration state.`});let c=M(r.migrationsDir,0)?.rebaseline?.historyId??null;if((s.number!==null||s.historyId!==null||s.historyIdInvalid)&&(s.historyIdInvalid||s.historyId!==c))throw W({code:`MIGRATION_RESOLVE_HISTORY_MISMATCH`,message:`The migration history of namespace "${i}" on the workspace does not match the local migration history.`,suggestion:`Run the command from a checkout of the migration history that was deployed to the workspace.`});let l=s.inProgress.number,u=e.resolution===`rollback`?l-1:l;ee(r.migrationsDir,u);let d=M(r.migrationsDir,u);if(!d)throw W({code:`MIGRATION_BASELINE_NOT_FOUND`,message:`No initial schema snapshot found in ${r.migrationsDir}. Expected 0000/schema.json.`,suggestion:`Create the initial schema snapshot first.`});let p=await assertMigrationsReproduceLocalTypes(t,r),m=await planSnapshotApply({client:a,workspaceId:o,namespace:i,snapshot:d});f.newline(),f.info(`Namespace: ${h.bold(i)}`),f.log(` In progress: ${h.bold(R(l))}`),f.log(` Resolution: ${h.bold(e.resolution)} (schema of migration ${h.bold(R(u))})`),f.log(` Tables to create: ${h.bold(String(m.creates.length))}`),f.log(` Tables to update: ${h.bold(String(m.updates.length))}`),f.log(` Tables to delete: ${h.bold(String(m.deletes.length))}`),f.newline();let g=R(l);if(m.deletes.length>0&&f.warn(`Existing data in deleted tables will be lost.`),e.resolution===`rollback`?f.warn(`Rolling back does not undo the data changes made by steps of migration ${g} that already completed. When migration ${g} is deployed again, its steps run again from the first step, so make sure every step is safe to run twice.`):f.warn(`Completing applies the schema of migration ${g} without running its migrate.ts again; do this only after the data it needs is in place.`),f.newline(),!e.yes){if(!await P.confirm({message:`Continue and ${e.resolution} migration ${R(l)}?`,default:!1}))throw W({code:`MIGRATION_RESOLVE_CANCELLED`,message:`Migration resolve cancelled.`});f.newline()}await assertMigrationStateUnchanged({client:a,workspaceId:o,namespace:i,before:s}),await yt(a,o,i,l);try{await applySnapshotPlan({client:a,workspaceId:o,namespace:i,snapshot:d,manifestOptions:p,plan:m})}catch(e){ht(e,[`The schema of migration ${g} marks a field as required, but records still have no value for it.`,`Fill in those records first (for example with 'tailor query'), then run the command again; the migration stays in progress until the update goes through.`])}s.maintenanceModeCheckpoint!==null&&await xe(a,o,i);let _=await mt(a,o,i,u,d.rebaseline?.historyId);try{await Ve(a,o,i,l)}catch(e){f.warn(`Could not remove the temporary resources of migration ${R(l)}: ${e instanceof Error?e.message:String(e)}. The next deploy removes them.`)}f.success(`Resolved migration ${h.bold(R(l))} of namespace ${h.bold(i)} (${e.resolution}); the checkpoint is ${h.bold(R(u))}.`);let{creates:v,updates:y,deletes:b,desiredGqlPermissions:x,gqlPermissionDeletes:S}=m;return{changed:v.length+y.length+b.length+x.length+S.length>0||_,workspaceId:o,namespace:i,resolution:e.resolution,migrationNumber:l,checkpoint:u,tables:{created:v,updated:y,deleted:b},gqlPermissions:{set:x.map(({typeName:e})=>e),deleted:S.map(({typeName:e})=>e)}}}const _o=C({name:`resolve`,description:`Settle a migration that a failed deploy left partially applied.`,notes:"Use this after a deploy failed partway through a migration whose `migrate.ts` exports `steps`. The failed migration stays in progress: when `maintenanceMode` is on in your config, the tables of its namespace stay in maintenance mode, and `sync` and `rebaseline` are refused, while `set` accepts only the number of the in-progress migration.\n\n- `--rollback` sends the schema of the migration before the failed one. The next deploy runs the failed migration again from its first step. Data changes made by steps that already completed are not undone.\n- `--complete` sends the schema of the failed migration itself and records it as completed, without running its `migrate.ts` again. Fix the data first (for example with `tailor query`), and make sure no record lacks a value for a field that becomes required.\n\nBoth options remove the in-progress record, take the tables out of maintenance mode, and remove the temporary resources of the failed run, so `deploy` and the other migration commands work again. As with `tailordb migration sync`, the local migration history must reproduce the current table definitions. If sending the schema stops partway, run the command again.",args:J.strictObject({...D,...I,rollback:G(J.boolean().default(!1),{description:`Return the namespace to the schema before the in-progress migration`}),complete:G(J.boolean().default(!1),{description:`Apply the schema of the in-progress migration and mark it as completed`}),namespace:G(J.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{if(e.rollback===e.complete)throw W({code:`MIGRATION_RESOLVE_DIRECTION_REQUIRED`,message:`Specify exactly one of --rollback or --complete.`});await z({profile:e.profile});let t=await resolve$1({configPath:e.config,resolution:e.rollback?`rollback`:`complete`,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile});A(t)}});async function set(e){w(`tailordb migration`);let t=Cn(e.number),{config:n}=await B(e.configPath),r=q.dirname(n.path),i=V(n,r),a=or(i,e.namespace),o=a.namespace;Fe(a.migrationsDir,o),ee(a.migrationsDir,t);let s=M(a.migrationsDir,0)?.rebaseline?.historyId,{client:c,workspaceId:l}=await j({profile:e.profile,workspaceId:e.workspaceId}),u=L(l,`tailordb`,o),d=await O(c,u),p=d.inProgress?.number===t;p||en(d,o);let m=d.number,g=m??0,_=d.historyIdInvalid?`<invalid>`:d.historyId??`<unset>`,v=s??`<unset>`;if(f.newline(),f.warn(`This operation will change TailorDB migration state metadata.`),f.log(`Namespace: ${h.bold(o)}`),f.log(`Current migration: ${m===null?`<unset>`:h.bold(R(m))}`),f.log(`New migration: ${h.bold(R(t))}`),f.log(`Current migration history ID: ${h.bold(_)}`),f.log(`New migration history ID: ${h.bold(v)}`),f.newline(),p&&(f.warn(`Migration ${R(t)} is in progress. Setting the checkpoint to it marks it as completed and clears its in-progress record; do this only when its schema changes are already applied.`),f.newline()),t<g?(f.warn(`Setting migration number backwards (${R(g)} → ${R(t)}) will cause previous migrations to be re-executed on next apply.`),f.newline()):t>g&&(f.warn(`Setting migration number forwards (${R(g)} → ${R(t)}) will skip migrations ${R(g+1)} to ${R(t)}.`),f.newline()),!e.yes){if(!await P.confirm({message:`Continue with migration checkpoint and history ID update?`,default:!1}))throw W({code:`MIGRATION_SET_CANCELLED`,message:`Migration checkpoint update cancelled.`});f.newline()}let y=await mt(c,l,o,t,s);return f.success(`Migration checkpoint set to ${h.bold(R(t))} for namespace ${h.bold(o)}`),{changed:y,workspaceId:l,namespace:o,previousMigrationNumber:m,migrationNumber:t,historyId:s??null}}const vo=C({name:`set`,description:`Set migration checkpoint to a specific number.`,notes:"The migration number must be a 4-digit value (e.g. `0001`) or a bare integer (e.g. `1`) within 0–9999, and must exist in the local migration history; `0` is always accepted as the baseline, provided the local history passes validation. A gapped history is rejected.\n\nMetadata lookup failures (authentication, permission, or network errors) are reported as errors; only a not-yet-deployed namespace is treated as having no checkpoint.",args:J.strictObject({...D,...I,number:G(J.string(),{positional:!0,description:`Migration number to set (e.g., 0001 or 1)`}),namespace:G(J.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await z({profile:e.profile});let t=await set({configPath:e.config,number:e.number,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile});A(t)}});function isStatusFailure(e){return e.status===`error`}async function collectMigrationStatuses(e){let{config:t}=await B(e.configPath),n=q.dirname(t.path),r=V(t,n);if(r.length===0)throw jt();let i=e.namespace?r.filter(t=>t.namespace===e.namespace):r;if(i.length===0)throw W({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`Namespace "${e.namespace}" not found or does not have migrations configured`});let a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map;for(let{namespace:e,migrationsDir:t}of i)try{let n=ut(t),r=/* @__PURE__ */ new Map,i=null;for(let e of n)if(e.type===`schema`){let t=Fn(e.path);e.number===0&&(i=t.rebaseline?.historyId??null)}else try{let t=Ee(e.path);t.description&&r.set(e.number,t.description)}catch(e){if(Xr(e)&&e.code===`MIGRATION_FILE_VERSION_UNSUPPORTED`)throw e}a.set(e,{migrationFiles:n,descriptions:r,historyId:i})}catch(t){o.set(e,Qr(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 j({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=L(c,`tailordb`,e),d;try{d=await O(s,u)}catch(t){l.push({status:`error`,namespace:e,error:t instanceof Error?t.message:String(t)});continue}let f=d.number??0;if(d.historyIdInvalid){l.push({status:`error`,namespace:e,error:`Remote migration history ID is invalid.`});continue}if(d.inProgressInvalid){l.push({status:`error`,namespace:e,error:`Remote in-progress migration record is invalid.`});continue}if((d.number!==null||d.historyId!==null)&&d.historyId!==i){l.push({status:`error`,namespace:e,error:`Remote migration history ID ${d.historyId??`<unset>`} does not match local migration history ID ${i??`<unset>`}.`});continue}let p=n.map(e=>e.number).filter((e,t,n)=>n.indexOf(e)===t).toSorted((e,t)=>e-t).filter(e=>e>f).map(e=>({number:e,label:R(e),...r.has(e)?{description:r.get(e)}:{}})),m=$n(d)?null:d.inProgress;l.push({status:`ok`,namespace:e,currentMigration:f,currentMigrationLabel:R(f),pendingMigrations:p,...m?{inProgressMigration:m.number,inProgressMigrationLabel:R(m.number)}:{}})}return l}function printMigrationStatuses(e){for(let t of e)if(f.newline(),f.info(`Namespace: ${h.bold(t.namespace)}`),isStatusFailure(t))f.error(` Migration status error: ${t.error}`);else if(f.log(` Current migration: ${h.bold(t.currentMigrationLabel)}`),t.inProgressMigrationLabel&&f.log(` In progress: ${h.bold(t.inProgressMigrationLabel)} (partially applied; the next deploy resumes it)`),t.pendingMigrations.length>0){f.log(` Pending migrations:`);for(let e of t.pendingMigrations)e.description?f.log(` - ${e.label}: ${e.description}`):f.log(` - ${e.label}`)}else f.log(` Pending migrations: (none)`);f.newline()}async function status(e){w(`tailordb migration`);let t=await collectMigrationStatuses(e);e.json?f.out(t):printMigrationStatuses(t);let n=t.filter(isStatusFailure);if(n.length>0){let e=n.map(e=>e.namespace).join(`, `);throw W({code:`MIGRATION_STATUS_FAILED`,message:`Migration status check failed for ${n.length} namespace${n.length===1?``:`s`}: ${e}`})}}const yo=C({name:`status`,description:`Show the current migration status for TailorDB namespaces, including applied and pending migrations.`,notes:`Every local migration file is checked for a compatible format version, and deployed migration history IDs must match the local baseline. Compatibility errors, history mismatches, and metadata lookup failures are reported per namespace and make the command exit non-zero; only a not-yet-deployed namespace is treated as having no applied migrations.`,args:J.strictObject({...D,namespace:G(J.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:f.jsonMode})}});async function runMigrationTest(e,t=createMigrationTestDependencies()){if(e.targetWorkspaceId&&!e.yes)throw W({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`--target-workspace-id requires --yes because the target may be overwritten.`,command:`tailordb migration test`});if(e.keep&&e.targetWorkspaceId)throw W({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`--keep applies only to automatically created workspaces; a designated target is always retained.`,command:`tailordb migration test`});if(e.keepTtl!==void 0&&!e.keep)throw W({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`--keep-ttl was given without --keep.`,suggestion:`Pass --keep together with --keep-ttl, or remove --keep-ttl.`,command:`tailordb migration test`});if(e.cloneTimeout!==void 0&&e.data!==`clone`)throw W({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`--clone-timeout was given without --data clone.`,suggestion:`Pass --data clone, or remove --clone-timeout.`,command:`tailordb migration test`});if(e.assertionNamespace&&!e.assertionPath)throw W({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`--assert is required when --assert-namespace is provided.`,command:`tailordb migration test`});let n=await t.prepare(e);if(assertTargetWorkspaceDiffers(n.sourceWorkspaceId,e.targetWorkspaceId),e.assertionPath&&resolveAssertionNamespace(n.pendingNamespaces,e.assertionNamespace),e.data===`clone`&&e.targetWorkspaceId){let e=s(n.designatedTarget,`designated clone target was not loaded during preparation`);assertCloneTargetRegion(n.temporaryWorkspace.region,e.region)}let r=e.targetWorkspaceId===void 0,i=r?await t.createWorkspace(n):{id:s(e.targetWorkspaceId,`designated target workspace missing`),name:void 0,createdAt:void 0},a=!1;if(r&&e.keepTtl!==void 0)try{await t.recordWorkspaceExpiry(i.id,e.keepTtl,i.createdAt),a=!0}catch(t){f.warn(`Failed to record an expiry on temporary workspace ${i.id}: ${t instanceof Error?t.message:String(t)}. Record one with ${U({command:`tailor`,args:[`workspace`,`ttl`,`set`,`--ttl`,e.keepTtl,`--workspace-id=${i.id}`,...e.profile?[`--profile=${e.profile}`]:[]]})}.`)}let o,c=!1,l=!1;try{let r={prepared:n,targetWorkspaceId:i.id};await t.deployBaseline(r);let a={...r,sourceWorkspaceId:n.sourceWorkspaceId,applicationName:n.sourceApplicationName,cloneTimeout:e.cloneTimeout};e.data===`clone`?await t.cloneData(a):await t.seedData(a),await t.deployMigrations(r),e.assertionPath&&await t.runAssertion({...r,assertionPath:e.assertionPath,assertionNamespace:e.assertionNamespace,machineUser:e.machineUser})}catch(e){o=e,c=!0}if(r&&e.keep)f.info(`Keeping temporary workspace ${i.name??i.id}${a?`; it can be pruned after ${e.keepTtl}`:``}.`);else if(r)try{await t.deleteWorkspace(i.id),l=!0}catch(t){if(!c)throw W({code:`MIGRATION_TEST_WORKSPACE_CLEANUP_FAILED`,message:`Failed to delete temporary workspace ${i.id}: ${t instanceof Error?t.message:String(t)}`,suggestion:e.profile?`Delete the temporary workspace manually with TAILOR_PLATFORM_PROFILE=${e.profile}.`:`Delete the temporary workspace manually.`,next:{command:`tailor`,args:[`workspace`,`delete`,`--workspace-id`,i.id]},cause:t});f.warn(`Failed to delete temporary workspace ${i.id}: ${t instanceof Error?t.message:String(t)}`)}if(c)throw o;return{success:!0,workspaceId:i.id,...i.name?{workspaceName:i.name}:{},temporary:r,deleted:l,data:e.data,pendingNamespaces:n.pendingNamespaces}}async function migrationTest(e){w(`tailordb migration`);let t=await runMigrationTest(e);e.json?f.out(t):f.success(`Pending migrations completed in workspace ${t.workspaceName??t.workspaceId}.`)}const bo=C({name:`test`,description:`Test pending migrations with seed fixtures or cloned data in a temporary workspace.`,notes:`The source workspace is read-only. Without --target-workspace-id, the command creates a workspace in the source workspace's region and deletes it after success or failure; pass --keep to retain it for inspection. A designated target is retained and requires --yes. Clone mode copies TailorDB records only; it does not copy IdP users or file blobs. With --keep-ttl, the kept workspace records an expiry; it is not deleted automatically, but workspace prune --expired removes it once the expiry has passed.`,args:J.strictObject({...D,yes:G(J.boolean().default(!1),{alias:`y`,description:`Acknowledge that a designated target workspace may be overwritten`}),data:G(J.enum([`seed`,`clone`]).default(`seed`),{description:`Data source for the migration test (seed or clone)`}),"target-workspace-id":G(J.uuid().optional(),{description:`Existing throwaway workspace to retain after the test (requires --yes)`}),keep:G(J.boolean().default(!1),{description:`Keep the automatically created workspace after the test`}),assert:G(J.string().optional(),{description:`Path to a TypeScript assertion script to run after migrations`,completion:{type:`file`,extensions:[`ts`]}}),"assert-namespace":G(J.string().optional(),{description:`TailorDB namespace exposed to the assertion script`}),"keep-ttl":G(Qn.optional(),{description:`Record an expiry on the kept workspace, e.g. 24h or 7d, so workspace prune --expired can delete it (requires --keep)`,completion:{type:`none`}}),"clone-timeout":G(pt.optional(),{description:`How long to wait for the clone to finish with --data clone, e.g. 30s or 10m (default: 30m)`,completion:{type:`none`}}),"machine-user":G(J.string().optional(),{description:`Machine user for seed and assertion script execution`})}),run:async e=>{await z({profile:e.profile}),await migrationTest({configPath:e.config,workspaceId:e[`workspace-id`],profile:e.profile,data:e.data,targetWorkspaceId:e[`target-workspace-id`],keep:e.keep,keepTtl:e[`keep-ttl`],assertionPath:e.assert,assertionNamespace:e[`assert-namespace`],machineUser:e[`machine-user`],cloneTimeout:e[`clone-timeout`]===void 0?void 0:an(e[`clone-timeout`]),yes:e.yes,json:f.jsonMode})}});function assertMigrationScriptsReady(e,t,n){let r=[],i=[],a=[],o=[],s=[];for(let t of ut(e)){if(t.type!==`diff`)continue;let n=Ee(t.path),c=rt(e,t.number,`migrate`),l=X.existsSync(c);l&&s.push([t.number,c]),n.requiresMigrationScript&&!n.scriptSkipped&&!l&&r.push(t.number),n.scriptSkipped&&l&&i.push(t.number),l&&yn(c)>0&&a.push(t.number),n.hasWarnings&&!n.scriptSkipped&&!l&&o.push({migrationNumber:t.number,warnings:n.warnings})}if(r.length>0)throw W({code:`MIGRATION_SCRIPT_REQUIRED`,message:`Migration(s) ${r.map(R).join(`, `)} in namespace "${t}" require a migration script but have no migrate.ts.`,suggestion:`Add one with 'tailor tailordb migration script <number>', or record that no script is needed with 'tailor tailordb migration script <number> --no-script --reason "..."'.`});if(i.length>0){let e=i.map(e=>` ${Xn({migrationNumber:e,namespace:t,configPath:n})}`).join(`
88
- `);throw W({code:`MIGRATION_SCRIPT_SKIP_CONFLICT`,message:`Migration(s) ${i.map(R).join(`, `)} in namespace "${t}" have both a --no-script skip acknowledgment and migrate.ts.`,suggestion:`Clear the stale acknowledgment(s):\n${e}\nOr delete migrate.ts to keep the skip.`})}if(a.length>0)throw W({code:`MIGRATION_SCRIPT_REVIEW_REQUIRED`,message:`Migration(s) ${a.map(R).join(`, `)} in namespace "${t}" still have a TODO() call or review marker in migrate.ts, where the generated script leaves a value or logic for you to decide.`,suggestion:Xt});for(let[e,n]of s){let r=Nn(n);r.kind===`main`&&r.ignoredSteps&&f.warn(rn(`${t}/${R(e)}`))}return o}function buildValidationReports(e){let{targetNamespaces:t,migrationFileErrors:n,localResults:r,remoteResults:i,unacknowledgedWarnings:a}=e;return t.map(e=>{let t=n.get(e.namespace);if(t!==void 0)return{namespace:e.namespace,valid:!1,migrationFiles:{valid:!1,error:t}};let o=s(r.find(t=>t.namespace===e.namespace),`local schema check result missing for namespace "${e.namespace}"`),c={hasDiff:o.hasDiff,...o.diff?{diff:o.diff}:{}};if(i===void 0)return{namespace:e.namespace,valid:!1,migrationFiles:{valid:!0},localSchema:c,remoteSchema:{skipped:`check_failed`}};let l=s(i.find(t=>t.namespace===e.namespace),`remote schema check result missing for namespace "${e.namespace}"`),u=l.checkpointMissingLocal===!0,d={remoteMigrationNumber:l.remoteMigrationNumber,hasDrift:l.hasDrift,drifts:l.drifts,...l.skipped?{skipped:l.skipped}:{},...u?{checkpointMissingLocal:!0}:{},...l.rebaselinePending?{rebaselinePending:l.rebaselinePending}:{},...l.checkpointRepair?{checkpointRepair:l.checkpointRepair}:{}},f=a?.get(e.namespace),p;if(f!==void 0){let e=f.filter(e=>e.migrationNumber>l.remoteMigrationNumber);p={valid:e.length===0,missing:e}}return{namespace:e.namespace,valid:!c.hasDiff&&!d.hasDrift&&!u&&p?.valid!==!1,migrationFiles:{valid:!0},localSchema:c,remoteSchema:d,...p?{warningAcknowledgments:p}:{}}})}async function collectValidationReports(e){let{config:t,plugins:n}=await B(e.configPath),r=q.dirname(t.path),i=V(t,r);if(i.length===0)throw jt();let a=e.namespace?i.filter(t=>t.namespace===e.namespace):i;if(a.length===0)throw W({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`Namespace "${e.namespace}" not found or does not have migrations configured`});let o=n.length>0?new li(n):void 0,{defineApplication:s}=await import(`../application-C2bPmmbh.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 W({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${e}"`});let l=c.tailorDBServices.map(he),u=new Map(l.map(e=>[e.namespace,e.types])),d=/* @__PURE__ */ new Map,f=[],p=e.strict?/* @__PURE__ */ new Map:void 0;for(let t of a)try{Fe(t.migrationsDir,t.namespace),M(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,Qr(e))}let m={targetNamespaces:a,migrationFileErrors:d,localResults:await ve(u,f),...p?{unacknowledgedWarnings:p}:{}};if(f.length===0)return{reports:buildValidationReports(m)};let h;try{let{client:n,workspaceId:r}=await j({profile:e.profile,workspaceId:e.workspaceId});h=await nt(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(f.newline(),f.info(`Namespace: ${h.bold(t.namespace)}`),!t.migrationFiles.valid){f.log(` Migration files: ${h.error(`invalid`)}`),f.log(` ${t.migrationFiles.error}`);continue}f.log(` Migration files: ${h.success(`OK`)}`);let e=t.localSchema;e?.hasDiff?e.diff?(f.log(` Local schema: ${h.error(`changes not in migration files`)}`),f.log(` ${Rn(e.diff)}`),f.log(on(e.diff))):f.log(` Local schema: ${h.error(`no migration snapshot found`)}`):f.log(` Local schema: ${h.success(`OK`)}`);let n=t.remoteSchema;n?.skipped===`check_failed`?f.log(` Remote schema: ${h.error(`not checked`)}`):n?.checkpointRepair?f.log(` Remote schema: ${h.success(`OK`)} (next deploy will reset the checkpoint to 0000 from ${R(n.checkpointRepair.from)})`):n?.checkpointMissingLocal?(f.log(` Remote schema: ${h.error(`remote migration ${R(n.remoteMigrationNumber)} is not in the local migration history`)}`),n.rebaselinePending&&f.log(` Fell behind before 'migration rebaseline' ran; must reach ${R(n.rebaselinePending.replacedLatestMigration)} first.`)):n?.hasDrift?(f.log(` Remote schema: ${h.error(`drift detected`)} (remote migration: ${R(n.remoteMigrationNumber)})`),f.log($e(n.drifts))):n?.skipped===`not_deployed`?f.log(` Remote schema: ${h.dim(`skipped (namespace not deployed)`)}`):n?.skipped===`no_migration_label`?f.log(` Remote schema: ${h.dim(`skipped (deployed namespace has no migration state)`)}`):n?.skipped===`no_snapshot`?f.log(` Remote schema: ${h.dim(`skipped (no local snapshot for remote migration ${R(n.remoteMigrationNumber)})`)}`):n&&f.log(` Remote schema: ${h.success(`OK`)} (remote migration: ${R(n.remoteMigrationNumber)})`);let r=t.warningAcknowledgments;if(r){if(r.valid)f.log(` Warning acknowledgments: ${h.success(`OK`)}`);else{f.log(` Warning acknowledgments: ${h.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}`:``;f.log(` ${t}: ${n.tableName}${e}: ${n.reason}`)}}}}}f.newline()}function hasMissingCheckpoint(e){return e.remoteSchema?.checkpointMissingLocal===!0}function printResolutionHints(e,t){e.some(e=>e.localSchema?.hasDiff&&!e.localSchema.diff)&&f.info(`Run 'tailor tailordb migration generate' to create the initial snapshot.`),e.some(e=>e.localSchema?.diff)&&f.info(`Run 'tailor tailordb migration generate' to create migration files.`);let n=e.filter(hasMissingCheckpoint);n.length>0&&b(n.map(e=>({namespace:e.namespace,remoteMigrationNumber:e.remoteSchema.remoteMigrationNumber,...e.remoteSchema.rebaselinePending?{rebaselinePending:e.remoteSchema.rebaselinePending}:{}}))),e.some(e=>e.remoteSchema?.hasDrift)&&ot(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){f.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??[])f.info(` ${Xn({migrationNumber:n.migrationNumber,namespace:e.namespace,configPath:t,noScript:!0})}`,{mode:`plain`})}}async function validate(e){w(`tailordb migration`);let t=await collectValidationReports(e),{reports:n}=t,r=n.filter(e=>!e.valid).length;if(e.json?f.out(n):(printValidationReports(n),r===0&&!(`remoteError`in t)?f.success(`All migration validation checks passed.`):printResolutionHints(n,e.configPath)),`remoteError`in t)throw t.remoteError;if(r>0)throw W({code:`MIGRATION_VALIDATION_FAILED`,message:`Migration validation failed for ${r} namespace(s)`})}const xo=C({name:`validate`,description:`Validate the full migration history, unreviewed generated migration scripts, and schema drift (local tables vs. migration snapshot, remote schema vs. migration checkpoint) without deploying. This includes the migration and schema-drift checks used by 'deploy' and exits with a non-zero code when issues are found.`,args:J.strictObject({...D,namespace:G(J.string().optional(),{alias:`n`,description:`Target TailorDB namespace (validates all namespaces if not specified)`}),strict:G(J.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:f.jsonMode,strict:e.strict})}}),So=K({name:`migration`,description:`Manage TailorDB schema migrations.`,subCommands:{generate:Ie,rebaseline:ho,resolve:_o,script:ce,set:vo,status:yo,sync:go,test:bo,validate:xo}}),Co=K({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:je,migration:So}}),wo=C({name:`upgrade`,description:`Run codemods to upgrade your project to a newer SDK version.`,args:J.strictObject({from:G(J.string(),{description:`SDK version before the upgrade (e.g., 1.33.0)`}),"dry-run":G(J.boolean().default(!1),{alias:`d`,description:`Preview changes without modifying files`}),path:G(J.string().default(`.`),{description:`Project directory to upgrade`,completion:{type:`directory`}})}),run:async e=>{let{initTelemetry:t}=await import(`../telemetry-DpkFGBmu.mjs`);await t();let{upgrade:n}=await import(`../service-9rwi_I4d.mjs`);await n({from:e.from,dryRun:e[`dry-run`],path:q.resolve(e.path)})}}),To=C({name:`current`,description:`Show current user.`,args:J.strictObject({profile:N.profile}),run:async e=>{let t=await T(),n=e.profile||process.env.TAILOR_PLATFORM_PROFILE,r=n?t.profiles[n]:void 0;if(n&&!r)throw W({code:`PROFILE_NOT_FOUND`,message:`Profile "${n}" not found`});let i=r?Me(r):void 0,a=n?r?.user??null:t.current_user,o=f.jsonMode;if(!a)throw W({code:`USER_NOT_SET`,message:`Current user not set.`,suggestion:`Log in first to register a user.`,next:{command:`tailor`,args:[`login`,...k({profile:n})]}});if(!x(t,a,i))throw W({code:`USER_NOT_FOUND`,message:`Current user '${a}' not found in registered users.`,suggestion:`Log in again to register the user.`,next:{command:`tailor`,args:[`login`,...k({profile:n})]}});o?f.out({user:a}):f.out(a)}});function activeCurrentUserKey(e,t){if(!t)return e.current_user?dr(e,e.current_user):null;let n=e.profiles[t];if(!n)throw W({code:`PROFILE_NOT_FOUND`,message:`Profile "${t}" not found`});return dr(e,n.user,Me(n))}function toUserListInfo(e,t){let n=e.indexOf(`|`),r=n===-1?null:e.slice(0,n);return{user:n===-1?e:e.slice(n+1),platformUrl:r,current:t===e}}function formatUserListInfo(e){return`${e.user}${e.platformUrl?` [${e.platformUrl}]`:``}${e.current?` (current)`:``}`}const Eo=C({name:`list`,description:`List all users.`,args:J.strictObject({profile:N.profile}),run:async e=>{let t=await T(),n=f.jsonMode,r=activeCurrentUserKey(t,e.profile||process.env.TAILOR_PLATFORM_PROFILE),i=Object.keys(t.users);if(i.length===0){f.info(H`
87
+ `)};f.out(a)}catch(e){throw e instanceof Q&&e.code===Z.NotFound?W({code:`STATIC_WEBSITE_NOT_FOUND`,message:r,cause:e}):e}}});async function listStaticWebsites(e){let{client:t,workspaceId:n}=await j({profile:e?.profile,workspaceId:e?.workspaceId}),r=Nt(e?.order);return(await Gr(async(e,i)=>{let{staticwebsites:a,nextPageToken:o}=await t.listStaticWebsites({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e?.limit})).map(e=>({workspaceId:n,name:e.name,description:e.description,url:e.url,allowedIpAddresses:e.allowedIpAddresses}))}const fo=C({name:`list`,description:`List all static websites in a workspace.`,args:J.strictObject({...N,...Ln()}),run:async e=>{let t=f.jsonMode,n=await Jt(e.limit,t=>listStaticWebsites({workspaceId:e[`workspace-id`],profile:e.profile,order:e.order,limit:t})),r=n.items,i=t?r:r.map(({allowedIpAddresses:e,...t})=>{if(e.length===0)return{...t,allowedIpAddresses:`No allowed IP addresses`};let n=e.length,r=n===1?`1 IP address`:`${n} IP addresses`;return{...t,allowedIpAddresses:r}});f.out(i),await F(n,e.limit)}}),po=K({name:`staticwebsite`,description:`Manage static websites in your workspace.`,subCommands:{deploy:Le,domain:lo,list:fo,get:uo},defaultSubCommand:`list`}),mo=new Set(Object.values(Ae));async function activateBaseline(e,t,n,r){let i=await $.realpath(e),a=q.dirname(i),o=q.basename(i),s=await $.mkdtemp(q.join(a,`.${o}-rebaseline-`)),c=`${s}-previous`,l=!1,u=!1;try{await $.cp(i,s,{recursive:!0});for(let e of await $.readdir(s,{withFileTypes:!0})){if(!e.isDirectory()||!Ge.test(e.name))continue;let t=q.join(s,e.name);(await $.readdir(t)).some(e=>mo.has(e))&&await $.rm(t,{recursive:!0,force:!0})}let e={...t,namespace:n,version:8,createdAt:(/* @__PURE__ */ new Date()).toISOString(),rebaseline:r},a=await ge(e,s,0);Fn(a.filePath),await $.rename(i,c),l=!0;try{await $.rename(s,i),u=!0}catch(e){throw await $.rename(c,i),l=!1,e}try{await $.rm(c,{recursive:!0,force:!0})}catch(e){f.warn(`The previous migration directory remains at ${c}: ${e instanceof Error?e.message:String(e)}`)}l=!1}finally{X.existsSync(s)&&await $.rm(s,{recursive:!0,force:!0}),!u&&l&&X.existsSync(c)&&await $.rename(c,i)}}async function rebaseline(e){w(`tailordb migration`);let{config:t,plugins:n}=await B(e.configPath),r=q.dirname(t.path),i=or(V(t,r),e.namespace),a=`First run ${U({command:`tailor`,args:[`tailordb`,`migration`,`generate`,`--config`,t.path]})}.`;Fe(i.migrationsDir,i.namespace);let o=M(i.migrationsDir);if(!o)throw W({code:`MIGRATION_HISTORY_NOT_FOUND`,message:`No migration history found for namespace "${i.namespace}".`,suggestion:a});let s=st(i.migrationsDir),c=M(i.migrationsDir,0)?.rebaseline?.historyId??null,u=te([i])[i.namespace],d=n.length>0?new li(n):void 0,{defineApplication:p}=await import(`../application-C2bPmmbh.mjs`),m=p({config:t,pluginManager:d});for(let e of m.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let g=m.tailorDBServices.find(e=>e.namespace===i.namespace);if(!g)throw W({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${i.namespace}"`});let assertLocalTypesReady=()=>{let e=se(g.types,i.namespace),t=bt(o,e.tables,i.namespace);if(Et(t))throw f.error(`Migration history does not reproduce the current local schema for namespace ${h.bold(i.namespace)}:`),f.log(on(t)),W({code:`MIGRATION_HISTORY_MISMATCH`,message:`Refusing to re-baseline: the migration history must reproduce the current local schema.`,suggestion:a})},localSourceFiles=()=>[t.path,...l(g.config,r)];assertLocalTypesReady();let _=Xe(localSourceFiles()),{client:v,workspaceId:y}=await j({profile:e.profile,workspaceId:e.workspaceId}),b=[`--config`,t.path,...k({workspaceId:y,profile:e.profile})],ee=`Run ${U({command:`tailor`,args:[`tailordb`,`migration`,`set`,`0`,`--namespace`,i.namespace,...b]})}`,x=`after resolving the connection error, deploy with schema checks enabled by running ${U({command:`tailor`,args:[`deploy`,...b]})}.`,assertConnectedWorkspaceReady=async(e,n)=>{let r=await O(v,L(y,`tailordb`,i.namespace));en(r,i.namespace);let a=r.number;if(a!==s){let e=a===null?`<unset>`:R(a);throw W({code:`REBASELINE_CHECKPOINT_BEHIND`,message:`The connected workspace must be at the latest migration ${R(s)} before re-baselining; current checkpoint is ${e}.`})}if(r.historyIdInvalid)throw W({code:`REBASELINE_REMOTE_HISTORY_INVALID`,message:`Refusing to re-baseline: the connected workspace has an invalid migration history marker.`});if(r.historyId!==e)throw W(n===`confirmation`?{code:`REBASELINE_STATE_CHANGED`,message:`The connected workspace migration history changed while waiting for confirmation.`,suggestion:`Run the command again.`}:{code:`REBASELINE_REMOTE_HISTORY_MISMATCH`,message:`Refusing to re-baseline: the connected workspace does not match the local migration history.`});let o=await nt(v,y,[i],t,[he(g)]),c=o[0];if(!c||c.remoteMigrationNumber!==s||c.hasDrift||c.checkpointMissingLocal)throw c?.hasDrift&&(f.error(`Remote schema drift detected:`),f.log(fr(o))),W({code:`REBASELINE_REMOTE_SCHEMA_MISMATCH`,message:`Refusing to re-baseline: the connected workspace remote schema must match the latest migration.`})};if(await assertConnectedWorkspaceReady(c,`initial`),f.newline(),f.warn(`This will replace the migration history for ${h.bold(i.namespace)}.`),f.log(` Latest migration: ${R(s)}`),f.log(` New history: 0000/schema.json only`),f.log(` migrate.ts and db.ts files will disappear from the working tree.`),f.log(` Committed migration files will remain in Git history. Preserve any uncommitted files before continuing.`),f.log(` Every other environment must already be at the latest migration.`),f.log(` The connected workspace checkpoint will be reset to 0000.`),f.newline(),!e.yes&&!await P.confirm({message:`Re-baseline this migration history and reset the connected workspace checkpoint?`,default:!1}))throw W({code:`REBASELINE_CANCELLED`,message:`Migration re-baseline cancelled.`});if(Fe(i.migrationsDir,i.namespace),te([i])[i.namespace]!==u)throw W({code:`REBASELINE_STATE_CHANGED`,message:`Migration files changed while waiting for confirmation.`,suggestion:`Run the command again.`});if(Xe(localSourceFiles())!==_)throw W({code:`REBASELINE_STATE_CHANGED`,message:`Local TailorDB table or config files changed.`,suggestion:`Run the command again.`});assertLocalTypesReady(),await assertConnectedWorkspaceReady(c,`confirmation`);let S={historyId:_t(),replacedHistoryId:c,replacedLatestMigration:s};await activateBaseline(i.migrationsDir,o,i.namespace,S);try{await mt(v,y,i.namespace,0,S.historyId)}catch(e){throw W({code:`REBASELINE_CHECKPOINT_UPDATE_FAILED`,message:`The local migration history was re-baselined, but the connected workspace checkpoint could not be updated.`,suggestion:`${ee}, or ${x}`,cause:e})}return f.success(`Re-baselined ${h.bold(i.namespace)} and reset the connected workspace checkpoint to 0000.`),{changed:!0,workspaceId:y,namespace:i.namespace,...S,schemaPath:rt(i.migrationsDir,0,`schema`)}}const ho=C({name:`rebaseline`,description:`Collapse the full migration history into a new 0000 baseline.`,notes:`Re-baselining removes migrations after 0000 from the working tree, records a new migration history ID, and resets the connected workspace checkpoint without changing its schema or data. Every environment must already have applied the latest migration before you run this command.`,args:J.strictObject({...D,...I,namespace:G(J.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await z({profile:e.profile});let t=await rebaseline({configPath:e.config,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile});A(t)}});async function fetchRemoteGqlPermissions(e){let{client:t,workspaceId:n,namespace:r}=e;return pr(async(e,i)=>{let{permissions:a,nextPageToken:o}=await t.listTailorDBGQLPermissions({workspaceId:n,namespaceName:r,pageToken:e,pageSize:i});return[a,o]})}async function fetchRemoteTypes(e){let{client:t,workspaceId:n,namespace:r}=e;return Sr(async(e,i)=>{try{let{tailordbTypes:a,nextPageToken:o}=await t.listTailorDBTypes({workspaceId:n,namespaceName:r,pageToken:e,pageSize:i});return[a,o]}catch(e){throw e instanceof Q&&e.code===Z.NotFound?W({code:`MIGRATION_NAMESPACE_NOT_DEPLOYED`,message:`Cannot apply the snapshot: TailorDB namespace "${r}" has not been deployed yet.`,suggestion:`Deploy the namespace first.`,cause:e}):e}})}async function planSnapshotApply(e){let{snapshot:t,...n}=e,r=await fetchRemoteTypes(n),i=new Set(r.map(e=>e.name)),{creates:a,updates:o,deletes:s}=fe(t,i),c=await fetchRemoteGqlPermissions(n),l=new Set(c.map(e=>e.typeName)),u=Object.entries(t.tables).flatMap(([e,t])=>t.permissions?.gql?[{typeName:e,permission:Pn(t.permissions.gql)}]:[]),d=new Set(u.map(e=>e.typeName));return{creates:a,updates:o,deletes:s,desiredGqlPermissions:u,gqlPermissionDeletes:c.filter(e=>!d.has(e.typeName)),remoteGqlPermissionTypes:l}}async function applySnapshotPlan(e){let{client:t,workspaceId:n,namespace:r,snapshot:i,manifestOptions:a,plan:o}=e,{creates:s,updates:c,deletes:l,desiredGqlPermissions:u,gqlPermissionDeletes:d}=o,f=Te(i,a),manifestFor=e=>{let t=f.get(e);if(!t)throw Zr(`Internal error: no manifest generated for table "${e}". No changes were applied.`);return t},p=s.map(e=>manifestFor(e)),m=c.map(e=>manifestFor(e));await Promise.all([...p.map(e=>t.createTailorDBType({workspaceId:n,namespaceName:r,tailordbType:e})),...m.map(e=>t.updateTailorDBType({workspaceId:n,namespaceName:r,tailordbType:e}))]),await Promise.all(u.map(({typeName:e,permission:i})=>{let a={workspaceId:n,namespaceName:r,typeName:e,permission:i};return o.remoteGqlPermissionTypes.has(e)?t.updateTailorDBGQLPermission(a):t.createTailorDBGQLPermission(a)})),await Promise.all(d.map(e=>t.deleteTailorDBGQLPermission({workspaceId:n,namespaceName:r,typeName:e.typeName}))),await Promise.all(l.map(e=>t.deleteTailorDBType({workspaceId:n,namespaceName:r,tailordbTypeName:e})))}async function assertMigrationsReproduceLocalTypes(e,t){let{config:n,plugins:r}=e,i=r.length>0?new li(r):void 0,{defineApplication:a,generatePluginFilesIfNeeded:o}=await import(`../application-C2bPmmbh.mjs`),s=a({config:n,pluginManager:i}),c=s.tailorDBServices.find(e=>e.namespace===t.namespace);if(!c)throw W({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${t.namespace}"`});for(let e of s.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let l=o(i,s.tailorDBServices,n.path),u=s.executorService??(l.length>0?(await import(`../service-Ca1WwyIt.mjs`)).createExecutorService({config:{files:[]},baseDir:q.dirname(n.path)}):void 0);await u?.loadExecutors(),l.length>0&&await u?.loadPluginExecutorFiles([...l]);let d=/* @__PURE__ */ new Set;for(let e of Object.values(u?.executors??{}))kn(e)&&e.trigger.kind===`tailordb`&&d.add(e.trigger.tableName);let p={executorUsedTables:d,namespaceGqlOperations:c.config.gqlOperations},m=M(t.migrationsDir);if(!m)return p;let g=se(c.types,t.namespace),_=bt(m,g.tables,t.namespace);if(!Et(_))return p;throw f.error(`Migration history does not reproduce the current local schema for namespace ${h.bold(t.namespace)}:`),f.log(on(_)),f.newline(),f.info(`This usually means one of the following:`),f.info(` - Migration files were edited and replaying them no longer matches the table definitions — fix the migration files.`,{mode:`plain`}),f.info(` - Table definitions changed without a new migration — run 'tailor tailordb migration generate' first.`,{mode:`plain`}),f.newline(),W({code:`MIGRATION_HISTORY_MISMATCH`,message:`Refusing to continue: the migration history must reproduce the current local schema before it can be applied to the remote.`,suggestion:`Generate a migration for the pending schema changes first.`})}async function sync(e){w(`tailordb migration`);let t=Cn(e.number),n=await B(e.configPath),{config:r}=n,i=q.dirname(r.path),a=V(r,i),o=or(a,e.namespace);Fe(o.migrationsDir,o.namespace);let s=ee(o.migrationsDir,t),c=M(o.migrationsDir,t);if(!c)throw W({code:`MIGRATION_BASELINE_NOT_FOUND`,message:`No initial schema snapshot found in ${o.migrationsDir}. Expected 0000/schema.json.`,suggestion:`Create the initial schema snapshot first.`});let l=await assertMigrationsReproduceLocalTypes(n,o),{client:u,workspaceId:d}=await j({profile:e.profile,workspaceId:e.workspaceId}),p=L(d,`tailordb`,o.namespace),m=await O(u,p);en(m,o.namespace);let g=m.number,_=await planSnapshotApply({client:u,workspaceId:d,namespace:o.namespace,snapshot:c}),{creates:v,updates:y,deletes:b,desiredGqlPermissions:x,gqlPermissionDeletes:S}=_;f.newline(),f.info(`Namespace: ${h.bold(o.namespace)}`),f.log(` Current migration: ${g===null?`<unset>`:h.bold(R(g))}`),f.log(` Target migration: ${h.bold(R(t))}`),f.log(` Tables to create: ${h.bold(String(v.length))}`),f.log(` Tables to update: ${h.bold(String(y.length))}`),f.log(` Tables to delete: ${h.bold(String(b.length))}`),f.log(` GQL permissions to set: ${h.bold(String(x.length))}`),f.log(` GQL permissions to delete: ${h.bold(String(S.length))}`),f.newline();let te=v.length+y.length+b.length+x.length+S.length;if(te===0?f.info(`No tables to apply; only the migration label will be updated.`):(f.warn(`This operation will overwrite remote TailorDB tables to match the selected snapshot.`),b.length>0&&f.warn(`Existing data in deleted tables will be lost.`),f.newline()),f.warn(`Sync never runs migrate.ts scripts; it only applies the schema snapshot and moves the migration label.`),f.newline(),g!==null&&t<g?(f.warn(`Migrations ${R(t+1)}–${R(g)} 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).`),f.newline()):g!==null&&t>g&&(f.warn(`Moving the migration label forwards (${R(g)} → ${R(t)}): migrate.ts scripts for migrations ${R(g+1)}–${R(t)} will not run on the next deploy.`),f.newline()),!e.yes){if(!await P.confirm({message:`Continue and set migration label to ${R(t)}?`,default:!1}))throw W({code:`MIGRATION_SYNC_CANCELLED`,message:`Migration sync cancelled.`});f.newline()}try{await applySnapshotPlan({client:u,workspaceId:d,namespace:o.namespace,snapshot:c,manifestOptions:l,plan:_})}catch(e){ht(e,[`The target snapshot marks a field as required, but existing remote records have no value for it.`,`Populate those records first (e.g. with a migration script applied via 'tailor deploy'), then re-run the sync.`])}let ne=c.rebaseline?.historyId,re=await mt(u,d,o.namespace,t,ne);return f.success(`Synced namespace ${h.bold(o.namespace)} to migration ${h.bold(R(t))}.`),t<s&&(f.newline(),f.info(`Run 'tailor deploy' to apply migrations ${R(t+1)}–${R(s)} from the working tree.`)),{changed:te>0||re,workspaceId:d,namespace:o.namespace,previousMigrationNumber:g,migrationNumber:t,historyId:ne??null,tables:{created:v,updated:y,deleted:b},gqlPermissions:{set:x.map(({typeName:e})=>e),deleted:S.map(({typeName:e})=>e)}}}const go=C({name:`sync`,description:`Sync remote TailorDB schema to a specific migration snapshot (recovery from --no-schema-check drift).`,args:J.strictObject({...D,...I,number:G(J.string(),{positional:!0,description:`Migration number to sync to (e.g., 0001 or 1; 0 targets the baseline snapshot)`}),namespace:G(J.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await z({profile:e.profile});let t=await sync({configPath:e.config,number:e.number,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile});A(t)}});async function assertMigrationStateUnchanged(e){let{client:t,workspaceId:n,namespace:r,before:i}=e,a=await O(t,L(n,`tailordb`,r));if(a.number!==i.number||a.historyId!==i.historyId||a.inProgress?.number!==i.inProgress?.number||a.inProgress?.executionId!==i.inProgress?.executionId)throw W({code:`MIGRATION_RESOLVE_STATE_CHANGED`,message:`The migration state of namespace "${r}" changed while the command was running.`,suggestion:`Run the command again.`})}async function resolve$1(e){w(`tailordb migration`);let t=await B(e.configPath),n=q.dirname(t.config.path),r=or(V(t.config,n),e.namespace),{namespace:i}=r;Fe(r.migrationsDir,i);let{client:a,workspaceId:o}=await j({profile:e.profile,workspaceId:e.workspaceId}),s=await O(a,L(o,`tailordb`,i));if(s.inProgressInvalid)throw W({code:`MIGRATION_RESOLVE_RECORD_UNREADABLE`,message:`Namespace "${i}" records a partially applied migration that cannot be read.`,suggestion:`Run 'tailor tailordb migration status --namespace ${i}' to inspect the migration state.`});if(!s.inProgress||$n(s))throw W({code:`MIGRATION_RESOLVE_NO_IN_PROGRESS`,message:`No migration is in progress for namespace "${i}".`,suggestion:`Run 'tailor tailordb migration status --namespace ${i}' to check the migration state.`});let c=M(r.migrationsDir,0)?.rebaseline?.historyId??null;if((s.number!==null||s.historyId!==null||s.historyIdInvalid)&&(s.historyIdInvalid||s.historyId!==c))throw W({code:`MIGRATION_RESOLVE_HISTORY_MISMATCH`,message:`The migration history of namespace "${i}" on the workspace does not match the local migration history.`,suggestion:`Run the command from a checkout of the migration history that was deployed to the workspace.`});let l=s.inProgress.number,u=e.resolution===`rollback`?l-1:l;ee(r.migrationsDir,u);let d=M(r.migrationsDir,u);if(!d)throw W({code:`MIGRATION_BASELINE_NOT_FOUND`,message:`No initial schema snapshot found in ${r.migrationsDir}. Expected 0000/schema.json.`,suggestion:`Create the initial schema snapshot first.`});let p=await assertMigrationsReproduceLocalTypes(t,r),m=await planSnapshotApply({client:a,workspaceId:o,namespace:i,snapshot:d});f.newline(),f.info(`Namespace: ${h.bold(i)}`),f.log(` In progress: ${h.bold(R(l))}`),f.log(` Resolution: ${h.bold(e.resolution)} (schema of migration ${h.bold(R(u))})`),f.log(` Tables to create: ${h.bold(String(m.creates.length))}`),f.log(` Tables to update: ${h.bold(String(m.updates.length))}`),f.log(` Tables to delete: ${h.bold(String(m.deletes.length))}`),f.newline();let g=R(l);if(m.deletes.length>0&&f.warn(`Existing data in deleted tables will be lost.`),e.resolution===`rollback`?f.warn(`Rolling back does not undo the data changes made by steps of migration ${g} that already completed. When migration ${g} is deployed again, its steps run again from the first step, so make sure every step is safe to run twice.`):f.warn(`Completing applies the schema of migration ${g} without running its migrate.ts again; do this only after the data it needs is in place.`),f.newline(),!e.yes){if(!await P.confirm({message:`Continue and ${e.resolution} migration ${R(l)}?`,default:!1}))throw W({code:`MIGRATION_RESOLVE_CANCELLED`,message:`Migration resolve cancelled.`});f.newline()}await assertMigrationStateUnchanged({client:a,workspaceId:o,namespace:i,before:s}),await yt(a,o,i,l);try{await applySnapshotPlan({client:a,workspaceId:o,namespace:i,snapshot:d,manifestOptions:p,plan:m})}catch(e){ht(e,[`The schema of migration ${g} marks a field as required, but records still have no value for it.`,`Fill in those records first (for example with 'tailor query'), then run the command again; the migration stays in progress until the update goes through.`])}s.maintenanceModeCheckpoint!==null&&await xe(a,o,i);let _=await mt(a,o,i,u,d.rebaseline?.historyId);try{await Ve(a,o,i,l)}catch(e){f.warn(`Could not remove the temporary resources of migration ${R(l)}: ${e instanceof Error?e.message:String(e)}. The next deploy removes them.`)}f.success(`Resolved migration ${h.bold(R(l))} of namespace ${h.bold(i)} (${e.resolution}); the checkpoint is ${h.bold(R(u))}.`);let{creates:v,updates:y,deletes:b,desiredGqlPermissions:x,gqlPermissionDeletes:S}=m;return{changed:v.length+y.length+b.length+x.length+S.length>0||_,workspaceId:o,namespace:i,resolution:e.resolution,migrationNumber:l,checkpoint:u,tables:{created:v,updated:y,deleted:b},gqlPermissions:{set:x.map(({typeName:e})=>e),deleted:S.map(({typeName:e})=>e)}}}const _o=C({name:`resolve`,description:`Settle a migration that a failed deploy left partially applied.`,notes:"Use this after a deploy failed partway through a migration whose `migrate.ts` exports `steps`. The failed migration stays in progress: when `maintenanceMode` is on in your config, the tables of its namespace stay in maintenance mode, and `sync` and `rebaseline` are refused, while `set` accepts only the number of the in-progress migration.\n\n- `--rollback` sends the schema of the migration before the failed one. The next deploy runs the failed migration again from its first step. Data changes made by steps that already completed are not undone.\n- `--complete` sends the schema of the failed migration itself and records it as completed, without running its `migrate.ts` again. Fix the data first (for example with `tailor query`), and make sure no record lacks a value for a field that becomes required.\n\nBoth options remove the in-progress record, take the tables out of maintenance mode, and remove the temporary resources of the failed run, so `deploy` and the other migration commands work again. As with `tailordb migration sync`, the local migration history must reproduce the current table definitions. If sending the schema stops partway, run the command again.",args:J.strictObject({...D,...I,rollback:G(J.boolean().default(!1),{description:`Return the namespace to the schema before the in-progress migration`}),complete:G(J.boolean().default(!1),{description:`Apply the schema of the in-progress migration and mark it as completed`}),namespace:G(J.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{if(e.rollback===e.complete)throw W({code:`MIGRATION_RESOLVE_DIRECTION_REQUIRED`,message:`Specify exactly one of --rollback or --complete.`});await z({profile:e.profile});let t=await resolve$1({configPath:e.config,resolution:e.rollback?`rollback`:`complete`,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile});A(t)}});async function set(e){w(`tailordb migration`);let t=Cn(e.number),{config:n}=await B(e.configPath),r=q.dirname(n.path),i=V(n,r),a=or(i,e.namespace),o=a.namespace;Fe(a.migrationsDir,o),ee(a.migrationsDir,t);let s=M(a.migrationsDir,0)?.rebaseline?.historyId,{client:c,workspaceId:l}=await j({profile:e.profile,workspaceId:e.workspaceId}),u=L(l,`tailordb`,o),d=await O(c,u),p=d.inProgress?.number===t;p||en(d,o);let m=d.number,g=m??0,_=d.historyIdInvalid?`<invalid>`:d.historyId??`<unset>`,v=s??`<unset>`;if(f.newline(),f.warn(`This operation will change TailorDB migration state metadata.`),f.log(`Namespace: ${h.bold(o)}`),f.log(`Current migration: ${m===null?`<unset>`:h.bold(R(m))}`),f.log(`New migration: ${h.bold(R(t))}`),f.log(`Current migration history ID: ${h.bold(_)}`),f.log(`New migration history ID: ${h.bold(v)}`),f.newline(),p&&(f.warn(`Migration ${R(t)} is in progress. Setting the checkpoint to it marks it as completed and clears its in-progress record; do this only when its schema changes are already applied.`),f.newline()),t<g?(f.warn(`Setting migration number backwards (${R(g)} → ${R(t)}) will cause previous migrations to be re-executed on next apply.`),f.newline()):t>g&&(f.warn(`Setting migration number forwards (${R(g)} → ${R(t)}) will skip migrations ${R(g+1)} to ${R(t)}.`),f.newline()),!e.yes){if(!await P.confirm({message:`Continue with migration checkpoint and history ID update?`,default:!1}))throw W({code:`MIGRATION_SET_CANCELLED`,message:`Migration checkpoint update cancelled.`});f.newline()}let y=await mt(c,l,o,t,s);return f.success(`Migration checkpoint set to ${h.bold(R(t))} for namespace ${h.bold(o)}`),{changed:y,workspaceId:l,namespace:o,previousMigrationNumber:m,migrationNumber:t,historyId:s??null}}const vo=C({name:`set`,description:`Set migration checkpoint to a specific number.`,notes:"The migration number must be a 4-digit value (e.g. `0001`) or a bare integer (e.g. `1`) within 0–9999, and must exist in the local migration history; `0` is always accepted as the baseline, provided the local history passes validation. A gapped history is rejected.\n\nMetadata lookup failures (authentication, permission, or network errors) are reported as errors; only a not-yet-deployed namespace is treated as having no checkpoint.",args:J.strictObject({...D,...I,number:G(J.string(),{positional:!0,description:`Migration number to set (e.g., 0001 or 1)`}),namespace:G(J.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await z({profile:e.profile});let t=await set({configPath:e.config,number:e.number,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile});A(t)}});function isStatusFailure(e){return e.status===`error`}async function collectMigrationStatuses(e){let{config:t}=await B(e.configPath),n=q.dirname(t.path),r=V(t,n);if(r.length===0)throw jt();let i=e.namespace?r.filter(t=>t.namespace===e.namespace):r;if(i.length===0)throw W({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`Namespace "${e.namespace}" not found or does not have migrations configured`});let a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map;for(let{namespace:e,migrationsDir:t}of i)try{let n=ut(t),r=/* @__PURE__ */ new Map,i=null;for(let e of n)if(e.type===`schema`){let t=Fn(e.path);e.number===0&&(i=t.rebaseline?.historyId??null)}else try{let t=Ee(e.path);t.description&&r.set(e.number,t.description)}catch(e){if(Xr(e)&&e.code===`MIGRATION_FILE_VERSION_UNSUPPORTED`)throw e}a.set(e,{migrationFiles:n,descriptions:r,historyId:i})}catch(t){o.set(e,Qr(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 j({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=L(c,`tailordb`,e),d;try{d=await O(s,u)}catch(t){l.push({status:`error`,namespace:e,error:t instanceof Error?t.message:String(t)});continue}let f=d.number??0;if(d.historyIdInvalid){l.push({status:`error`,namespace:e,error:`Remote migration history ID is invalid.`});continue}if(d.inProgressInvalid){l.push({status:`error`,namespace:e,error:`Remote in-progress migration record is invalid.`});continue}if((d.number!==null||d.historyId!==null)&&d.historyId!==i){l.push({status:`error`,namespace:e,error:`Remote migration history ID ${d.historyId??`<unset>`} does not match local migration history ID ${i??`<unset>`}.`});continue}let p=n.map(e=>e.number).filter((e,t,n)=>n.indexOf(e)===t).toSorted((e,t)=>e-t).filter(e=>e>f).map(e=>({number:e,label:R(e),...r.has(e)?{description:r.get(e)}:{}})),m=$n(d)?null:d.inProgress;l.push({status:`ok`,namespace:e,currentMigration:f,currentMigrationLabel:R(f),pendingMigrations:p,...m?{inProgressMigration:m.number,inProgressMigrationLabel:R(m.number)}:{}})}return l}function printMigrationStatuses(e){for(let t of e)if(f.newline(),f.info(`Namespace: ${h.bold(t.namespace)}`),isStatusFailure(t))f.error(` Migration status error: ${t.error}`);else if(f.log(` Current migration: ${h.bold(t.currentMigrationLabel)}`),t.inProgressMigrationLabel&&f.log(` In progress: ${h.bold(t.inProgressMigrationLabel)} (partially applied; the next deploy resumes it)`),t.pendingMigrations.length>0){f.log(` Pending migrations:`);for(let e of t.pendingMigrations)e.description?f.log(` - ${e.label}: ${e.description}`):f.log(` - ${e.label}`)}else f.log(` Pending migrations: (none)`);f.newline()}async function status(e){w(`tailordb migration`);let t=await collectMigrationStatuses(e);e.json?f.out(t):printMigrationStatuses(t);let n=t.filter(isStatusFailure);if(n.length>0){let e=n.map(e=>e.namespace).join(`, `);throw W({code:`MIGRATION_STATUS_FAILED`,message:`Migration status check failed for ${n.length} namespace${n.length===1?``:`s`}: ${e}`})}}const yo=C({name:`status`,description:`Show the current migration status for TailorDB namespaces, including applied and pending migrations.`,notes:`Every local migration file is checked for a compatible format version, and deployed migration history IDs must match the local baseline. Compatibility errors, history mismatches, and metadata lookup failures are reported per namespace and make the command exit non-zero; only a not-yet-deployed namespace is treated as having no applied migrations.`,args:J.strictObject({...D,namespace:G(J.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:f.jsonMode})}});async function runMigrationTest(e,t=createMigrationTestDependencies()){if(e.targetWorkspaceId&&!e.yes)throw W({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`--target-workspace-id requires --yes because the target may be overwritten.`,command:`tailordb migration test`});if(e.keep&&e.targetWorkspaceId)throw W({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`--keep applies only to automatically created workspaces; a designated target is always retained.`,command:`tailordb migration test`});if(e.keepTtl!==void 0&&!e.keep)throw W({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`--keep-ttl was given without --keep.`,suggestion:`Pass --keep together with --keep-ttl, or remove --keep-ttl.`,command:`tailordb migration test`});if(e.cloneTimeout!==void 0&&e.data!==`clone`)throw W({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`--clone-timeout was given without --data clone.`,suggestion:`Pass --data clone, or remove --clone-timeout.`,command:`tailordb migration test`});if(e.assertionNamespace&&!e.assertionPath)throw W({code:`MIGRATION_TEST_OPTIONS_INVALID`,message:`--assert is required when --assert-namespace is provided.`,command:`tailordb migration test`});let n=await t.prepare(e);if(assertTargetWorkspaceDiffers(n.sourceWorkspaceId,e.targetWorkspaceId),e.assertionPath&&resolveAssertionNamespace(n.pendingNamespaces,e.assertionNamespace),e.data===`clone`&&e.targetWorkspaceId){let e=s(n.designatedTarget,`designated clone target was not loaded during preparation`);assertCloneTargetRegion(n.temporaryWorkspace.region,e.region)}let r=e.targetWorkspaceId===void 0,i=r?await t.createWorkspace(n):{id:s(e.targetWorkspaceId,`designated target workspace missing`),name:void 0,createdAt:void 0},a=e.keepTtl??(e.keep?void 0:`24h`),o=!1;if(r&&a!==void 0)try{await t.recordWorkspaceExpiry(i.id,a,i.createdAt),o=!0}catch(t){f.warn(`Failed to record an expiry on temporary workspace ${i.id}: ${t instanceof Error?t.message:String(t)}. Record one with ${U({command:`tailor`,args:[`workspace`,`ttl`,`set`,`--ttl`,a,`--workspace-id=${i.id}`,...e.profile?[`--profile=${e.profile}`]:[]]})}.`)}let c,l=!1,u=!1;try{let r={prepared:n,targetWorkspaceId:i.id};await t.deployBaseline(r);let a={...r,sourceWorkspaceId:n.sourceWorkspaceId,applicationName:n.sourceApplicationName,cloneTimeout:e.cloneTimeout};e.data===`clone`?await t.cloneData(a):await t.seedData(a),await t.deployMigrations(r),e.assertionPath&&await t.runAssertion({...r,assertionPath:e.assertionPath,assertionNamespace:e.assertionNamespace,machineUser:e.machineUser})}catch(e){c=e,l=!0}if(r&&e.keep)f.info(`Keeping temporary workspace ${i.name??i.id}${o?`; it can be pruned after ${a}`:``}.`);else if(r)try{await t.deleteWorkspace(i.id),u=!0}catch(t){if(!l)throw W({code:`MIGRATION_TEST_WORKSPACE_CLEANUP_FAILED`,message:`Failed to delete temporary workspace ${i.id}: ${t instanceof Error?t.message:String(t)}`,suggestion:e.profile?`Delete the temporary workspace manually with TAILOR_PLATFORM_PROFILE=${e.profile}.`:`Delete the temporary workspace manually.`,next:{command:`tailor`,args:[`workspace`,`delete`,`--workspace-id`,i.id]},cause:t});f.warn(`Failed to delete temporary workspace ${i.id}: ${t instanceof Error?t.message:String(t)}`)}if(l)throw c;return{success:!0,workspaceId:i.id,...i.name?{workspaceName:i.name}:{},temporary:r,deleted:u,data:e.data,pendingNamespaces:n.pendingNamespaces}}async function migrationTest(e){w(`tailordb migration`);let t=await runMigrationTest(e);e.json?f.out(t):f.success(`Pending migrations completed in workspace ${t.workspaceName??t.workspaceId}.`)}const bo=C({name:`test`,description:`Test pending migrations with seed fixtures or cloned data in a temporary workspace.`,notes:`The source workspace is read-only. Without --target-workspace-id, the command creates a workspace in the source workspace's region and deletes it after success or failure; pass --keep to retain it for inspection. Right after creating the workspace it records a 24h expiry (unless --keep is given without --keep-ttl), so if the run is interrupted before the command can delete the workspace, workspace prune --expired removes it later. A designated target is retained and requires --yes. Clone mode copies TailorDB records only; it does not copy IdP users or file blobs. With --keep-ttl, the kept workspace records an expiry; it is not deleted automatically, but workspace prune --expired removes it once the expiry has passed. Organization and folder IDs loaded by --env-file are used the same way as the options; command-line options take precedence, and empty env-file values are ignored.`,args:J.strictObject({...D,yes:G(J.boolean().default(!1),{alias:`y`,description:`Acknowledge that a designated target workspace may be overwritten`}),data:G(J.enum([`seed`,`clone`]).default(`seed`),{description:`Data source for the migration test (seed or clone)`}),"target-workspace-id":G(J.uuid().optional(),{description:`Existing throwaway workspace to retain after the test (requires --yes)`}),keep:G(J.boolean().default(!1),{description:`Keep the automatically created workspace after the test`}),"organization-id":G(J.uuid().optional(),{description:`Organization to create the temporary workspace in, at its root unless --folder-id is given (default: the source workspace's organization and folder). With --target-workspace-id, must match the target's organization`,env:`TAILOR_PLATFORM_ORGANIZATION_ID`}),"folder-id":G(J.uuid().optional(),{description:`Folder to create the temporary workspace in (default: the source workspace's folder). Requires --organization-id when the source workspace is not in an organization. With --target-workspace-id, must match the target's folder`,env:`TAILOR_PLATFORM_FOLDER_ID`}),assert:G(J.string().optional(),{description:`Path to a TypeScript assertion script to run after migrations`,completion:{type:`file`,extensions:[`ts`]}}),"assert-namespace":G(J.string().optional(),{description:`TailorDB namespace exposed to the assertion script`}),"keep-ttl":G(Qn.optional(),{description:`Record an expiry on the kept workspace, e.g. 24h or 7d, so workspace prune --expired can delete it (requires --keep)`,completion:{type:`none`}}),"clone-timeout":G(pt.optional(),{description:`How long to wait for the clone to finish with --data clone, e.g. 30s or 10m (default: 30m)`,completion:{type:`none`}}),"machine-user":G(J.string().optional(),{description:`Machine user for seed and assertion script execution`})}),run:async e=>{await z({profile:e.profile}),await migrationTest({configPath:e.config,workspaceId:e[`workspace-id`],profile:e.profile,data:e.data,targetWorkspaceId:e[`target-workspace-id`],keep:e.keep,keepTtl:e[`keep-ttl`],...Ht(e),assertionPath:e.assert,assertionNamespace:e[`assert-namespace`],machineUser:e[`machine-user`],cloneTimeout:e[`clone-timeout`]===void 0?void 0:an(e[`clone-timeout`]),yes:e.yes,json:f.jsonMode})}});function assertMigrationScriptsReady(e,t,n){let r=[],i=[],a=[],o=[],s=[];for(let t of ut(e)){if(t.type!==`diff`)continue;let n=Ee(t.path),c=rt(e,t.number,`migrate`),l=X.existsSync(c);l&&s.push([t.number,c]),n.requiresMigrationScript&&!n.scriptSkipped&&!l&&r.push(t.number),n.scriptSkipped&&l&&i.push(t.number),l&&yn(c)>0&&a.push(t.number),n.hasWarnings&&!n.scriptSkipped&&!l&&o.push({migrationNumber:t.number,warnings:n.warnings})}if(r.length>0)throw W({code:`MIGRATION_SCRIPT_REQUIRED`,message:`Migration(s) ${r.map(R).join(`, `)} in namespace "${t}" require a migration script but have no migrate.ts.`,suggestion:`Add one with 'tailor tailordb migration script <number>', or record that no script is needed with 'tailor tailordb migration script <number> --no-script --reason "..."'.`});if(i.length>0){let e=i.map(e=>` ${Xn({migrationNumber:e,namespace:t,configPath:n})}`).join(`
88
+ `);throw W({code:`MIGRATION_SCRIPT_SKIP_CONFLICT`,message:`Migration(s) ${i.map(R).join(`, `)} in namespace "${t}" have both a --no-script skip acknowledgment and migrate.ts.`,suggestion:`Clear the stale acknowledgment(s):\n${e}\nOr delete migrate.ts to keep the skip.`})}if(a.length>0)throw W({code:`MIGRATION_SCRIPT_REVIEW_REQUIRED`,message:`Migration(s) ${a.map(R).join(`, `)} in namespace "${t}" still have a TODO() call or review marker in migrate.ts, where the generated script leaves a value or logic for you to decide.`,suggestion:Xt});for(let[e,n]of s){let r=Nn(n);r.kind===`main`&&r.ignoredSteps&&f.warn(rn(`${t}/${R(e)}`))}return o}function buildValidationReports(e){let{targetNamespaces:t,migrationFileErrors:n,localResults:r,remoteResults:i,unacknowledgedWarnings:a}=e;return t.map(e=>{let t=n.get(e.namespace);if(t!==void 0)return{namespace:e.namespace,valid:!1,migrationFiles:{valid:!1,error:t}};let o=s(r.find(t=>t.namespace===e.namespace),`local schema check result missing for namespace "${e.namespace}"`),c={hasDiff:o.hasDiff,...o.diff?{diff:o.diff}:{}};if(i===void 0)return{namespace:e.namespace,valid:!1,migrationFiles:{valid:!0},localSchema:c,remoteSchema:{skipped:`check_failed`}};let l=s(i.find(t=>t.namespace===e.namespace),`remote schema check result missing for namespace "${e.namespace}"`),u=l.checkpointMissingLocal===!0,d={remoteMigrationNumber:l.remoteMigrationNumber,hasDrift:l.hasDrift,drifts:l.drifts,...l.skipped?{skipped:l.skipped}:{},...u?{checkpointMissingLocal:!0}:{},...l.rebaselinePending?{rebaselinePending:l.rebaselinePending}:{},...l.checkpointRepair?{checkpointRepair:l.checkpointRepair}:{}},f=a?.get(e.namespace),p;if(f!==void 0){let e=f.filter(e=>e.migrationNumber>l.remoteMigrationNumber);p={valid:e.length===0,missing:e}}return{namespace:e.namespace,valid:!c.hasDiff&&!d.hasDrift&&!u&&p?.valid!==!1,migrationFiles:{valid:!0},localSchema:c,remoteSchema:d,...p?{warningAcknowledgments:p}:{}}})}async function collectValidationReports(e){let{config:t,plugins:n}=await B(e.configPath),r=q.dirname(t.path),i=V(t,r);if(i.length===0)throw jt();let a=e.namespace?i.filter(t=>t.namespace===e.namespace):i;if(a.length===0)throw W({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`Namespace "${e.namespace}" not found or does not have migrations configured`});let o=n.length>0?new li(n):void 0,{defineApplication:s}=await import(`../application-C2bPmmbh.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 W({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${e}"`});let l=c.tailorDBServices.map(he),u=new Map(l.map(e=>[e.namespace,e.types])),d=/* @__PURE__ */ new Map,f=[],p=e.strict?/* @__PURE__ */ new Map:void 0;for(let t of a)try{Fe(t.migrationsDir,t.namespace),M(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,Qr(e))}let m={targetNamespaces:a,migrationFileErrors:d,localResults:await ve(u,f),...p?{unacknowledgedWarnings:p}:{}};if(f.length===0)return{reports:buildValidationReports(m)};let h;try{let{client:n,workspaceId:r}=await j({profile:e.profile,workspaceId:e.workspaceId});h=await nt(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(f.newline(),f.info(`Namespace: ${h.bold(t.namespace)}`),!t.migrationFiles.valid){f.log(` Migration files: ${h.error(`invalid`)}`),f.log(` ${t.migrationFiles.error}`);continue}f.log(` Migration files: ${h.success(`OK`)}`);let e=t.localSchema;e?.hasDiff?e.diff?(f.log(` Local schema: ${h.error(`changes not in migration files`)}`),f.log(` ${Rn(e.diff)}`),f.log(on(e.diff))):f.log(` Local schema: ${h.error(`no migration snapshot found`)}`):f.log(` Local schema: ${h.success(`OK`)}`);let n=t.remoteSchema;n?.skipped===`check_failed`?f.log(` Remote schema: ${h.error(`not checked`)}`):n?.checkpointRepair?f.log(` Remote schema: ${h.success(`OK`)} (next deploy will reset the checkpoint to 0000 from ${R(n.checkpointRepair.from)})`):n?.checkpointMissingLocal?(f.log(` Remote schema: ${h.error(`remote migration ${R(n.remoteMigrationNumber)} is not in the local migration history`)}`),n.rebaselinePending&&f.log(` Fell behind before 'migration rebaseline' ran; must reach ${R(n.rebaselinePending.replacedLatestMigration)} first.`)):n?.hasDrift?(f.log(` Remote schema: ${h.error(`drift detected`)} (remote migration: ${R(n.remoteMigrationNumber)})`),f.log($e(n.drifts))):n?.skipped===`not_deployed`?f.log(` Remote schema: ${h.dim(`skipped (namespace not deployed)`)}`):n?.skipped===`no_migration_label`?f.log(` Remote schema: ${h.dim(`skipped (deployed namespace has no migration state)`)}`):n?.skipped===`no_snapshot`?f.log(` Remote schema: ${h.dim(`skipped (no local snapshot for remote migration ${R(n.remoteMigrationNumber)})`)}`):n&&f.log(` Remote schema: ${h.success(`OK`)} (remote migration: ${R(n.remoteMigrationNumber)})`);let r=t.warningAcknowledgments;if(r){if(r.valid)f.log(` Warning acknowledgments: ${h.success(`OK`)}`);else{f.log(` Warning acknowledgments: ${h.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}`:``;f.log(` ${t}: ${n.tableName}${e}: ${n.reason}`)}}}}}f.newline()}function hasMissingCheckpoint(e){return e.remoteSchema?.checkpointMissingLocal===!0}function printResolutionHints(e,t){e.some(e=>e.localSchema?.hasDiff&&!e.localSchema.diff)&&f.info(`Run 'tailor tailordb migration generate' to create the initial snapshot.`),e.some(e=>e.localSchema?.diff)&&f.info(`Run 'tailor tailordb migration generate' to create migration files.`);let n=e.filter(hasMissingCheckpoint);n.length>0&&b(n.map(e=>({namespace:e.namespace,remoteMigrationNumber:e.remoteSchema.remoteMigrationNumber,...e.remoteSchema.rebaselinePending?{rebaselinePending:e.remoteSchema.rebaselinePending}:{}}))),e.some(e=>e.remoteSchema?.hasDrift)&&ot(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){f.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??[])f.info(` ${Xn({migrationNumber:n.migrationNumber,namespace:e.namespace,configPath:t,noScript:!0})}`,{mode:`plain`})}}async function validate(e){w(`tailordb migration`);let t=await collectValidationReports(e),{reports:n}=t,r=n.filter(e=>!e.valid).length;if(e.json?f.out(n):(printValidationReports(n),r===0&&!(`remoteError`in t)?f.success(`All migration validation checks passed.`):printResolutionHints(n,e.configPath)),`remoteError`in t)throw t.remoteError;if(r>0)throw W({code:`MIGRATION_VALIDATION_FAILED`,message:`Migration validation failed for ${r} namespace(s)`})}const xo=C({name:`validate`,description:`Validate the full migration history, unreviewed generated migration scripts, and schema drift (local tables vs. migration snapshot, remote schema vs. migration checkpoint) without deploying. This includes the migration and schema-drift checks used by 'deploy' and exits with a non-zero code when issues are found.`,args:J.strictObject({...D,namespace:G(J.string().optional(),{alias:`n`,description:`Target TailorDB namespace (validates all namespaces if not specified)`}),strict:G(J.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:f.jsonMode,strict:e.strict})}}),So=K({name:`migration`,description:`Manage TailorDB schema migrations.`,subCommands:{generate:Ie,rebaseline:ho,resolve:_o,script:ce,set:vo,status:yo,sync:go,test:bo,validate:xo}}),Co=K({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:je,migration:So}}),wo=C({name:`upgrade`,description:`Run codemods to upgrade your project to a newer SDK version.`,args:J.strictObject({from:G(J.string(),{description:`SDK version before the upgrade (e.g., 1.33.0)`}),"dry-run":G(J.boolean().default(!1),{alias:`d`,description:`Preview changes without modifying files`}),path:G(J.string().default(`.`),{description:`Project directory to upgrade`,completion:{type:`directory`}})}),run:async e=>{let{initTelemetry:t}=await import(`../telemetry-nqOtDWNO.mjs`);await t();let{upgrade:n}=await import(`../service-9rwi_I4d.mjs`);await n({from:e.from,dryRun:e[`dry-run`],path:q.resolve(e.path)})}}),To=C({name:`current`,description:`Show current user.`,args:J.strictObject({profile:N.profile}),run:async e=>{let t=await T(),n=e.profile||process.env.TAILOR_PLATFORM_PROFILE,r=n?t.profiles[n]:void 0;if(n&&!r)throw W({code:`PROFILE_NOT_FOUND`,message:`Profile "${n}" not found`});let i=r?Me(r):void 0,a=n?r?.user??null:t.current_user,o=f.jsonMode;if(!a)throw W({code:`USER_NOT_SET`,message:`Current user not set.`,suggestion:`Log in first to register a user.`,next:{command:`tailor`,args:[`login`,...k({profile:n})]}});if(!x(t,a,i))throw W({code:`USER_NOT_FOUND`,message:`Current user '${a}' not found in registered users.`,suggestion:`Log in again to register the user.`,next:{command:`tailor`,args:[`login`,...k({profile:n})]}});o?f.out({user:a}):f.out(a)}});function activeCurrentUserKey(e,t){if(!t)return e.current_user?dr(e,e.current_user):null;let n=e.profiles[t];if(!n)throw W({code:`PROFILE_NOT_FOUND`,message:`Profile "${t}" not found`});return dr(e,n.user,Me(n))}function toUserListInfo(e,t){let n=e.indexOf(`|`),r=n===-1?null:e.slice(0,n);return{user:n===-1?e:e.slice(n+1),platformUrl:r,current:t===e}}function formatUserListInfo(e){return`${e.user}${e.platformUrl?` [${e.platformUrl}]`:``}${e.current?` (current)`:``}`}const Eo=C({name:`list`,description:`List all users.`,args:J.strictObject({profile:N.profile}),run:async e=>{let t=await T(),n=f.jsonMode,r=activeCurrentUserKey(t,e.profile||process.env.TAILOR_PLATFORM_PROFILE),i=Object.keys(t.users);if(i.length===0){f.info(H`
89
89
  No users found.
90
90
  Please login first using 'tailor login' command to register a user.
91
91
  `),n&&f.out([]);return}let a=i.map(e=>toUserListInfo(e,r));n?f.out([...new Set(a.map(e=>e.user))]):a.forEach(e=>{e.current?f.success(formatUserListInfo(e),{mode:`plain`}):f.log(formatUserListInfo(e))})}}),Do={[a.PAT_SCOPE_UNSPECIFIED]:`unknown`,[a.PAT_SCOPE_READ]:`read`,[a.PAT_SCOPE_WRITE]:`write`};function patScopeToString(e){return It(Do,e,`unknown`)}function transformPersonalAccessToken(e){return{name:e.name,scopes:e.scopes.map(patScopeToString),createdAt:zt(e.createdAt),lastUsedAt:zt(e.lastUsedAt)}}function getScopesFromWriteFlag(e){return e?[a.PAT_SCOPE_READ,a.PAT_SCOPE_WRITE]:[a.PAT_SCOPE_READ]}function getScopeStringsFromWriteFlag(e){return e?[`read`,`write`]:[`read`]}function printCreatedToken(e,t,n,r){let i=getScopeStringsFromWriteFlag(n);f.jsonMode?f.out({name:e,scopes:i,token:t}):f.out(H`
@@ -128,5 +128,5 @@ Error:`));let e=formatErrorWithSourcemap(b.error,p,process.cwd());e?f.log(e):f.l
128
128
  - Pass \`--help-json\` to a command for machine-readable help.
129
129
  - Full command reference: \`${ts}\``;function defaultSkillsRunToAdd(e){let{run:t,...n}=e;return{...n,defaultSubCommand:`add`}}const rs=_i(K({name:Zo,description:Xo.description||`Tailor CLI for managing Tailor Platform SDK applications`,notes:`CLI plugins (beta): an unknown subcommand is dispatched to an external plugin executable named \`${Zo}-<name>\` (found on your PATH or in node_modules/.bin), similar to \`gh\` extensions.
130
130
  Run \`${Zo} plugin list\` to see which plugins are installed and where they resolve from.
131
- The \`setup\` commands are provided by the @tailor-platform/sdk-plugin-setup CLI plugin.`,subCommands:{api:Ji,auth:Zi,authconnection:ia,crashreport:sa,data:pa,deploy:ma,executor:ha,function:Ta,generate:Ea,init:Da,login:Aa,logout:ja,machineuser:Ma,oauth2client:Na,open:Pa,organization:Ia,plugin:Va,profile:Ka,query:Tt,remove:at,secret:ao,show:ur,staticwebsite:po,tailordb:Co,upgrade:wo,user:Io,workflow:Lo,workspace:Yo}}),{sourceDir:es,package:Qo,mode:`copy`,descriptionAppend:!1,globalArgs:J.object(de),commandMap:{add:[`add`],remove:[`remove`]},unknownKeys:`strict`,descriptions:{skills:`Manage Tailor SDK agent skills.`,add:`Install Tailor SDK agent skills.`,list:`List Tailor SDK agent skills.`,remove:`Remove installed Tailor SDK agent skills.`,sync:`Remove and reinstall Tailor SDK agent skills.`}}),is=gi({...rs,subCommands:{...rs.subCommands,skills:defaultSkillsRunToAdd(rs.subCommands.skills)}});mi(is,{version:Xo.version,globalArgs:J.object(de),displayErrors:!1,agentHelp:ns,setup:({agent:e})=>{p(e?.id)},onUnknownSubcommand:({commandPath:e,name:t,args:n,precedingArgs:r})=>dispatchPluginWithInstallHint({commandPath:e,name:t,args:[...r,...n],cliName:Zo,profile:process.env.TAILOR_PLATFORM_PROFILE}),cleanup:async({error:e})=>{if(e){Be()||On(e,process.argv.slice(2));let t;if(f.jsonMode?f.log(tn(e,{includeStack:f.verbose})):Xr(e)?(f.log(e.format()),f.verbose&&e.stack&&f.debug(`\nStack trace:\n${e.stack}`)):e instanceof Error?(f.error(e.message),t=c(e).suggestion??ei(e),t&&f.log(` ${h.info(`Suggestion:`)} ${t}`),f.verbose&&e.stack&&f.debug(`\nStack trace:\n${e.stack}`)):f.error(`Unknown error: ${e}`),xn(e,{jsonMode:f.jsonMode,suggestion:t}),!Xr(e)&&(!(e instanceof Error)||e instanceof TypeError||e instanceof RangeError)){let{reportCrash:t}=await import(`../crashreport-IN6H7GX3.mjs`);await t(e,`handledError`)}}let{shutdownTelemetry:t}=await import(`../telemetry-DpkFGBmu.mjs`);await t()}});export{is as mainCommand};
131
+ The \`setup\` commands are provided by the @tailor-platform/sdk-plugin-setup CLI plugin.`,subCommands:{api:Ji,auth:Zi,authconnection:ia,crashreport:sa,data:pa,deploy:ma,executor:ha,function:Ta,generate:Ea,init:Da,login:Aa,logout:ja,machineuser:Ma,oauth2client:Na,open:Pa,organization:Ia,plugin:Va,profile:Ka,query:Tt,remove:at,secret:ao,show:ur,staticwebsite:po,tailordb:Co,upgrade:wo,user:Io,workflow:Lo,workspace:Yo}}),{sourceDir:es,package:Qo,mode:`copy`,descriptionAppend:!1,globalArgs:J.object(de),commandMap:{add:[`add`],remove:[`remove`]},unknownKeys:`strict`,descriptions:{skills:`Manage Tailor SDK agent skills.`,add:`Install Tailor SDK agent skills.`,list:`List Tailor SDK agent skills.`,remove:`Remove installed Tailor SDK agent skills.`,sync:`Remove and reinstall Tailor SDK agent skills.`}}),is=gi({...rs,subCommands:{...rs.subCommands,skills:defaultSkillsRunToAdd(rs.subCommands.skills)}});mi(is,{version:Xo.version,globalArgs:J.object(de),displayErrors:!1,agentHelp:ns,setup:({agent:e})=>{p(e?.id)},onUnknownSubcommand:({commandPath:e,name:t,args:n,precedingArgs:r})=>dispatchPluginWithInstallHint({commandPath:e,name:t,args:[...r,...n],cliName:Zo,profile:process.env.TAILOR_PLATFORM_PROFILE}),cleanup:async({error:e})=>{if(e){Be()||On(e,process.argv.slice(2));let t;if(f.jsonMode?f.log(tn(e,{includeStack:f.verbose})):Xr(e)?(f.log(e.format()),f.verbose&&e.stack&&f.debug(`\nStack trace:\n${e.stack}`)):e instanceof Error?(f.error(e.message),t=c(e).suggestion??ei(e),t&&f.log(` ${h.info(`Suggestion:`)} ${t}`),f.verbose&&e.stack&&f.debug(`\nStack trace:\n${e.stack}`)):f.error(`Unknown error: ${e}`),xn(e,{jsonMode:f.jsonMode,suggestion:t}),!Xr(e)&&(!(e instanceof Error)||e instanceof TypeError||e instanceof RangeError)){let{reportCrash:t}=await import(`../crashreport-IN6H7GX3.mjs`);await t(e,`handledError`)}}let{shutdownTelemetry:t}=await import(`../telemetry-nqOtDWNO.mjs`);await t()}});export{is as mainCommand};
132
132
  //# sourceMappingURL=main.mjs.map