@tailor-platform/sdk 2.33.0 → 2.35.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 (336) hide show
  1. package/CHANGELOG.md +84 -0
  2. package/dist/ai/index.d.mts +1 -3
  3. package/dist/{application-Bet1K5C4.mjs → application-Bj2MtL-d.mjs} +1 -1
  4. package/dist/application-DIsQSnj3.mjs +207 -0
  5. package/dist/application-DIsQSnj3.mjs.map +1 -0
  6. package/dist/cli/cache/bundle-cache.d.mts +1 -0
  7. package/dist/cli/commands/api/api-call.d.mts +1 -3
  8. package/dist/cli/commands/deploy/aigateway.d.mts +1 -0
  9. package/dist/cli/commands/deploy/app-id-lock.d.mts +1 -3
  10. package/dist/cli/commands/deploy/application.d.mts +1 -0
  11. package/dist/cli/commands/deploy/auth.d.mts +1 -0
  12. package/dist/cli/commands/deploy/config-id-injector.d.mts +1 -3
  13. package/dist/cli/commands/deploy/confirm.d.mts +1 -0
  14. package/dist/cli/commands/deploy/deploy.d.mts +4 -3
  15. package/dist/cli/commands/deploy/executor.d.mts +1 -0
  16. package/dist/cli/commands/deploy/function-registry-types.d.mts +1 -3
  17. package/dist/cli/commands/deploy/function-registry.d.mts +1 -0
  18. package/dist/cli/commands/deploy/idp.d.mts +1 -0
  19. package/dist/cli/commands/deploy/owned-resource.d.mts +3 -0
  20. package/dist/cli/commands/deploy/resolver.d.mts +1 -0
  21. package/dist/cli/commands/deploy/secret-manager.d.mts +1 -0
  22. package/dist/cli/commands/deploy/staticwebsite.d.mts +1 -0
  23. package/dist/cli/commands/deploy/tailordb/migration-validation.d.mts +1 -2
  24. package/dist/cli/commands/deploy/tailordb/plan.d.mts +1 -0
  25. package/dist/cli/commands/deploy/workflow-execution-policy.d.mts +2 -1
  26. package/dist/cli/commands/deploy/workflow.d.mts +1 -0
  27. package/dist/cli/commands/executor/get.d.mts +0 -2
  28. package/dist/cli/commands/executor/jobs.d.mts +0 -2
  29. package/dist/cli/commands/executor/list.d.mts +1 -3
  30. package/dist/cli/commands/executor/transform.d.mts +1 -3
  31. package/dist/cli/commands/executor/trigger.d.mts +0 -2
  32. package/dist/cli/commands/executor/webhook.d.mts +1 -3
  33. package/dist/cli/commands/function/get.d.mts +0 -2
  34. package/dist/cli/commands/function/list.d.mts +0 -2
  35. package/dist/cli/commands/function/transform.d.mts +1 -3
  36. package/dist/cli/commands/generate/options.d.mts +1 -3
  37. package/dist/cli/commands/generate/seed/bundler.d.mts +1 -3
  38. package/dist/cli/commands/generate/service.d.mts +1 -3
  39. package/dist/cli/commands/machineuser/list.d.mts +1 -3
  40. package/dist/cli/commands/machineuser/token.d.mts +1 -3
  41. package/dist/cli/commands/oauth2client/get.d.mts +1 -3
  42. package/dist/cli/commands/oauth2client/list.d.mts +1 -3
  43. package/dist/cli/commands/oauth2client/transform.d.mts +1 -3
  44. package/dist/cli/commands/organization/folder/create.d.mts +0 -2
  45. package/dist/cli/commands/organization/folder/delete.d.mts +0 -2
  46. package/dist/cli/commands/organization/folder/get.d.mts +0 -2
  47. package/dist/cli/commands/organization/folder/list.d.mts +0 -2
  48. package/dist/cli/commands/organization/folder/update.d.mts +0 -2
  49. package/dist/cli/commands/organization/get.d.mts +0 -2
  50. package/dist/cli/commands/organization/list.d.mts +1 -3
  51. package/dist/cli/commands/organization/transform.d.mts +1 -3
  52. package/dist/cli/commands/organization/tree.d.mts +0 -2
  53. package/dist/cli/commands/organization/update.d.mts +0 -2
  54. package/dist/cli/commands/remove.d.mts +1 -3
  55. package/dist/cli/commands/show.d.mts +0 -2
  56. package/dist/cli/commands/staticwebsite/deploy.d.mts +1 -3
  57. package/dist/cli/commands/tailordb/migrate/bundler.d.mts +1 -3
  58. package/dist/cli/commands/tailordb/migrate/config.d.mts +1 -3
  59. package/dist/cli/commands/tailordb/migrate/diff-calculator.d.mts +0 -2
  60. package/dist/cli/commands/tailordb/migrate/generate.d.mts +2 -4
  61. package/dist/cli/commands/tailordb/migrate/rename-detection.d.mts +1 -3
  62. package/dist/cli/commands/tailordb/migrate/snapshot-comparison.d.mts +1 -3
  63. package/dist/cli/commands/tailordb/migrate/snapshot-files.d.mts +1 -3
  64. package/dist/cli/commands/tailordb/migrate/snapshot-local.d.mts +1 -3
  65. package/dist/cli/commands/tailordb/migrate/snapshot-migrations.d.mts +1 -3
  66. package/dist/cli/commands/tailordb/migrate/snapshot-types.d.mts +0 -2
  67. package/dist/cli/commands/tailordb/migrate/types.d.mts +1 -3
  68. package/dist/cli/commands/tailordb/truncate.d.mts +1 -3
  69. package/dist/cli/commands/workflow/executions.d.mts +0 -2
  70. package/dist/cli/commands/workflow/get.d.mts +0 -2
  71. package/dist/cli/commands/workflow/list.d.mts +1 -3
  72. package/dist/cli/commands/workflow/resume.d.mts +1 -3
  73. package/dist/cli/commands/workflow/start.d.mts +0 -2
  74. package/dist/cli/commands/workflow/status.d.mts +1 -3
  75. package/dist/cli/commands/workflow/transform.d.mts +1 -3
  76. package/dist/cli/commands/workflow/wait.d.mts +1 -3
  77. package/dist/cli/commands/workflow/waiter.d.mts +1 -3
  78. package/dist/cli/commands/workspace/app/health.d.mts +0 -2
  79. package/dist/cli/commands/workspace/app/list.d.mts +0 -2
  80. package/dist/cli/commands/workspace/app/transform.d.mts +1 -3
  81. package/dist/cli/commands/workspace/create.d.mts +0 -2
  82. package/dist/cli/commands/workspace/delete.d.mts +0 -2
  83. package/dist/cli/commands/workspace/expiry.d.mts +1 -3
  84. package/dist/cli/commands/workspace/get.d.mts +0 -2
  85. package/dist/cli/commands/workspace/list.d.mts +1 -3
  86. package/dist/cli/commands/workspace/restore.d.mts +0 -2
  87. package/dist/cli/commands/workspace/transform.d.mts +1 -3
  88. package/dist/cli/commands/workspace/user/invite.d.mts +0 -2
  89. package/dist/cli/commands/workspace/user/list.d.mts +0 -2
  90. package/dist/cli/commands/workspace/user/remove.d.mts +0 -2
  91. package/dist/cli/commands/workspace/user/transform.d.mts +1 -3
  92. package/dist/cli/commands/workspace/user/update.d.mts +0 -2
  93. package/dist/cli/lib.d.mts +1 -1
  94. package/dist/cli/lib.mjs +1 -1
  95. package/dist/cli/lib.mjs.map +1 -1
  96. package/dist/cli/main.d.mts +1 -3
  97. package/dist/cli/main.mjs +55 -51
  98. package/dist/cli/main.mjs.map +1 -1
  99. package/dist/cli/query/index.d.mts +0 -2
  100. package/dist/cli/services/application.d.mts +6 -4
  101. package/dist/cli/services/executor/service.d.mts +2 -2
  102. package/dist/cli/services/function-bundle.d.mts +8 -0
  103. package/dist/cli/services/http-adapter/bundler.d.mts +7 -1
  104. package/dist/cli/services/resolver/service.d.mts +2 -2
  105. package/dist/cli/services/workflow/bundler.d.mts +2 -3
  106. package/dist/cli/shared/args.d.mts +0 -2
  107. package/dist/cli/shared/beta.d.mts +1 -3
  108. package/dist/cli/shared/client.d.mts +4 -3
  109. package/dist/cli/shared/command.d.mts +2 -4
  110. package/dist/cli/shared/config-loader.d.mts +2 -4
  111. package/dist/cli/shared/config.d.mts +1 -3
  112. package/dist/cli/shared/context.d.mts +0 -2
  113. package/dist/cli/shared/error-diagnostics.d.mts +1 -3
  114. package/dist/cli/shared/error-json.d.mts +1 -3
  115. package/dist/cli/shared/function-execution.d.mts +1 -3
  116. package/dist/cli/shared/github-actions.d.mts +1 -3
  117. package/dist/cli/shared/logger.d.mts +7 -4
  118. package/dist/cli/shared/platform-bundle-plugin.d.mts +1 -0
  119. package/dist/cli/shared/prompt.d.mts +1 -3
  120. package/dist/cli/shared/readonly-guard.d.mts +0 -2
  121. package/dist/cli/shared/script-executor.d.mts +1 -3
  122. package/dist/cli/shared/sdk-builder-pure-plugin.d.mts +1 -0
  123. package/dist/cli/shared/seed-chunker.d.mts +1 -3
  124. package/dist/cli/shared/seed-context.d.mts +0 -2
  125. package/dist/cli/shared/sourcemap-sources.d.mts +1 -0
  126. package/dist/cli/shared/tailordb-namespaces.d.mts +1 -3
  127. package/dist/cli/shared/type-generator.d.mts +0 -2
  128. package/dist/cli/shared/workspace-name.d.mts +1 -3
  129. package/dist/completion/zsh-worker.zsh +5 -5
  130. package/dist/configure/config/index.d.mts +2 -4
  131. package/dist/configure/config/types.d.mts +27 -4
  132. package/dist/configure/index.d.mts +7 -9
  133. package/dist/configure/index.mjs +1 -1
  134. package/dist/configure/services/aigateway/index.d.mts +0 -2
  135. package/dist/configure/services/aigateway/types.d.mts +0 -2
  136. package/dist/configure/services/auth/index.d.mts +0 -2
  137. package/dist/configure/services/auth/types.d.mts +0 -2
  138. package/dist/configure/services/executor/executor.d.mts +0 -2
  139. package/dist/configure/services/executor/operation.d.mts +0 -2
  140. package/dist/configure/services/executor/trigger/event.d.mts +0 -2
  141. package/dist/configure/services/executor/trigger/index.d.mts +0 -2
  142. package/dist/configure/services/executor/trigger/schedule.d.mts +0 -2
  143. package/dist/configure/services/executor/trigger/webhook.d.mts +1 -3
  144. package/dist/configure/services/http-adapter/http-adapter.d.mts +0 -2
  145. package/dist/configure/services/idp/index.d.mts +0 -2
  146. package/dist/configure/services/idp/permission.d.mts +0 -2
  147. package/dist/configure/services/idp/types.d.mts +0 -2
  148. package/dist/configure/services/index.d.mts +5 -5
  149. package/dist/configure/services/resolver/index.d.mts +1 -1
  150. package/dist/configure/services/resolver/permission.d.mts +0 -2
  151. package/dist/configure/services/resolver/resolver.d.mts +1 -3
  152. package/dist/configure/services/resolver/types.d.mts +1 -3
  153. package/dist/configure/services/secrets/index.d.mts +0 -2
  154. package/dist/configure/services/secrets/types.d.mts +0 -2
  155. package/dist/configure/services/staticwebsite/index.d.mts +0 -2
  156. package/dist/configure/services/staticwebsite/types.d.mts +0 -2
  157. package/dist/configure/services/tailordb/permission.d.mts +0 -2
  158. package/dist/configure/services/tailordb/schema.d.mts +0 -2
  159. package/dist/configure/services/tailordb/types.d.mts +0 -2
  160. package/dist/configure/services/workflow/execution-policy.d.mts +0 -2
  161. package/dist/configure/services/workflow/execution-policy.types.d.mts +0 -2
  162. package/dist/configure/services/workflow/job.d.mts +0 -2
  163. package/dist/configure/services/workflow/wait-point.d.mts +0 -2
  164. package/dist/configure/services/workflow/workflow.d.mts +0 -2
  165. package/dist/configure/types/aigateway-name.d.mts +1 -3
  166. package/dist/configure/types/auth-namespace-name.d.mts +1 -3
  167. package/dist/configure/types/connection-name.d.mts +1 -3
  168. package/dist/configure/types/field.d.mts +1 -3
  169. package/dist/configure/types/field.types.d.mts +0 -2
  170. package/dist/configure/types/idp-name.d.mts +1 -3
  171. package/dist/configure/types/permission-operand.types.d.mts +0 -2
  172. package/dist/configure/types/secret-vault-name.d.mts +1 -3
  173. package/dist/configure/types/type.d.mts +0 -2
  174. package/dist/{crashreport-BCIy33Cz.mjs → crashreport-DGU6lwiX.mjs} +2 -2
  175. package/dist/{crashreport-BCIy33Cz.mjs.map → crashreport-DGU6lwiX.mjs.map} +1 -1
  176. package/dist/crashreport-WsYAWARW.mjs +1 -0
  177. package/dist/{logger-RgtbhJ83.mjs → errors-BXmGBX-7.mjs} +6 -3
  178. package/dist/errors-BXmGBX-7.mjs.map +1 -0
  179. package/dist/field-parse-BQhUAbpM.mjs +2 -0
  180. package/dist/{field-parse-C41e3UAF.mjs.map → field-parse-BQhUAbpM.mjs.map} +1 -1
  181. package/dist/guards-CiFVxoXR.mjs +2 -0
  182. package/dist/guards-CiFVxoXR.mjs.map +1 -0
  183. package/dist/kysely/index.d.mts +0 -2
  184. package/dist/{kysely-type-DxyIWXc6.mjs → kysely-type-B0ri1-Xs.mjs} +9 -7
  185. package/dist/kysely-type-B0ri1-Xs.mjs.map +1 -0
  186. package/dist/manager-B813m43t.mjs +2 -0
  187. package/dist/manager-B813m43t.mjs.map +1 -0
  188. package/dist/parser/service/idp/types.d.mts +1 -3
  189. package/dist/parser/service/tailordb/type-source.d.mts +1 -3
  190. package/dist/parser/service/tailordb/types.d.mts +0 -2
  191. package/dist/plugin/builtin/enum-constants/index.d.mts +0 -2
  192. package/dist/plugin/builtin/file-utils/index.d.mts +0 -2
  193. package/dist/plugin/builtin/kysely-type/index.d.mts +0 -2
  194. package/dist/plugin/builtin/kysely-type/index.mjs +1 -1
  195. package/dist/plugin/builtin/seed/index.d.mts +0 -2
  196. package/dist/plugin/builtin/seed/seed-type-processor.d.mts +1 -3
  197. package/dist/plugin/get-generated-table.d.mts +1 -3
  198. package/dist/plugin/index.mjs +1 -1
  199. package/dist/plugin/types.d.mts +0 -2
  200. package/dist/plugin/with-context.d.mts +1 -3
  201. package/dist/register-ts-hook-CQ7shKO5.mjs +1055 -0
  202. package/dist/register-ts-hook-CQ7shKO5.mjs.map +1 -0
  203. package/dist/runtime/aigateway.d.mts +1 -3
  204. package/dist/runtime/authconnection.d.mts +1 -3
  205. package/dist/runtime/context.d.mts +0 -2
  206. package/dist/runtime/date.d.mts +0 -2
  207. package/dist/runtime/field-parse.d.mts +0 -2
  208. package/dist/runtime/file.d.mts +0 -2
  209. package/dist/runtime/globals.d.mts +0 -2
  210. package/dist/runtime/iconv.d.mts +1 -3
  211. package/dist/runtime/idp.d.mts +1 -3
  212. package/dist/runtime/index.d.mts +1 -3
  213. package/dist/runtime/index.mjs +1 -1
  214. package/dist/runtime/logger.d.mts +1 -3
  215. package/dist/runtime/secretmanager.d.mts +1 -3
  216. package/dist/runtime/temporal.d.mts +0 -2
  217. package/dist/runtime/types.d.mts +0 -2
  218. package/dist/runtime/workflow.d.mts +0 -2
  219. package/dist/{schema-B6hJQWp6.mjs → schema-BU1aIQ63.mjs} +2 -2
  220. package/dist/{schema-B6hJQWp6.mjs.map → schema-BU1aIQ63.mjs.map} +1 -1
  221. package/dist/secret-file-BxZ-J_Nz.mjs +2 -0
  222. package/dist/secret-file-BxZ-J_Nz.mjs.map +1 -0
  223. package/dist/seed/idp-user-password.d.mts +0 -2
  224. package/dist/seed/index.d.mts +0 -2
  225. package/dist/service-CaGmqg0r.mjs +2 -0
  226. package/dist/{service-9rwi_I4d.mjs.map → service-CaGmqg0r.mjs.map} +1 -1
  227. package/dist/service-DEq_hdht.mjs +1 -0
  228. package/dist/{service-9SBPNpK8.mjs → service-eeXdVrDK.mjs} +4 -4
  229. package/dist/service-eeXdVrDK.mjs.map +1 -0
  230. package/dist/shared/src/color.d.mts +1 -3
  231. package/dist/tailor-proto/src/tailor/v1/aigateway_pb.d.mts +1 -3
  232. package/dist/tailor-proto/src/tailor/v1/aigateway_resource_pb.d.mts +1 -3
  233. package/dist/tailor-proto/src/tailor/v1/application_pb.d.mts +1 -3
  234. package/dist/tailor-proto/src/tailor/v1/application_resource_pb.d.mts +1 -3
  235. package/dist/tailor-proto/src/tailor/v1/auth_pb.d.mts +1 -3
  236. package/dist/tailor-proto/src/tailor/v1/auth_resource_pb.d.mts +1 -3
  237. package/dist/tailor-proto/src/tailor/v1/events_pb.d.mts +1 -3
  238. package/dist/tailor-proto/src/tailor/v1/events_resource_pb.d.mts +1 -3
  239. package/dist/tailor-proto/src/tailor/v1/executor_pb.d.mts +1 -3
  240. package/dist/tailor-proto/src/tailor/v1/executor_resource_pb.d.mts +1 -3
  241. package/dist/tailor-proto/src/tailor/v1/function_pb.d.mts +1 -3
  242. package/dist/tailor-proto/src/tailor/v1/function_registry_pb.d.mts +1 -3
  243. package/dist/tailor-proto/src/tailor/v1/function_resource_pb.d.mts +1 -3
  244. package/dist/tailor-proto/src/tailor/v1/http_adapter_resource_pb.d.mts +1 -3
  245. package/dist/tailor-proto/src/tailor/v1/idp_pb.d.mts +1 -3
  246. package/dist/tailor-proto/src/tailor/v1/idp_resource_pb.d.mts +1 -3
  247. package/dist/tailor-proto/src/tailor/v1/metadata_pb.d.mts +1 -3
  248. package/dist/tailor-proto/src/tailor/v1/metadata_resource_pb.d.mts +1 -3
  249. package/dist/tailor-proto/src/tailor/v1/meter_pb.d.mts +1 -3
  250. package/dist/tailor-proto/src/tailor/v1/pipeline_pb.d.mts +1 -3
  251. package/dist/tailor-proto/src/tailor/v1/pipeline_resource_pb.d.mts +1 -3
  252. package/dist/tailor-proto/src/tailor/v1/resource_pb.d.mts +1 -3
  253. package/dist/tailor-proto/src/tailor/v1/secret_manager_pb.d.mts +1 -3
  254. package/dist/tailor-proto/src/tailor/v1/secret_manager_resource_pb.d.mts +1 -3
  255. package/dist/tailor-proto/src/tailor/v1/security_pb.d.mts +1 -3
  256. package/dist/tailor-proto/src/tailor/v1/security_resource_pb.d.mts +1 -3
  257. package/dist/tailor-proto/src/tailor/v1/service_pb.d.mts +1 -3
  258. package/dist/tailor-proto/src/tailor/v1/stateflow_pb.d.mts +1 -3
  259. package/dist/tailor-proto/src/tailor/v1/stateflow_resource_pb.d.mts +1 -3
  260. package/dist/tailor-proto/src/tailor/v1/staticwebsite_pb.d.mts +1 -3
  261. package/dist/tailor-proto/src/tailor/v1/staticwebsite_resource_pb.d.mts +1 -3
  262. package/dist/tailor-proto/src/tailor/v1/tailordb_pb.d.mts +1 -3
  263. package/dist/tailor-proto/src/tailor/v1/tailordb_resource_pb.d.mts +1 -3
  264. package/dist/tailor-proto/src/tailor/v1/telemetryrouter_pb.d.mts +1 -3
  265. package/dist/tailor-proto/src/tailor/v1/telemetryrouter_resource_pb.d.mts +1 -3
  266. package/dist/tailor-proto/src/tailor/v1/workflow_pb.d.mts +1 -3
  267. package/dist/tailor-proto/src/tailor/v1/workflow_resource_pb.d.mts +1 -3
  268. package/dist/tailor-proto/src/tailor/v1/workspace_pb.d.mts +1 -3
  269. package/dist/tailor-proto/src/tailor/v1/workspace_resource_pb.d.mts +1 -3
  270. package/dist/types/aigateway.generated.d.mts +1 -3
  271. package/dist/types/app-config.generated.d.mts +1 -3
  272. package/dist/types/auth-connection.generated.d.mts +1 -3
  273. package/dist/types/auth.generated.d.mts +1 -3
  274. package/dist/types/executor.generated.d.mts +1 -3
  275. package/dist/types/field.generated.d.mts +1 -3
  276. package/dist/types/helpers.d.mts +1 -3
  277. package/dist/types/http-adapter.generated.d.mts +1 -3
  278. package/dist/types/idp.generated.d.mts +1 -3
  279. package/dist/types/resolver.generated.d.mts +1 -3
  280. package/dist/types/secrets.generated.d.mts +1 -3
  281. package/dist/types/staticwebsite.generated.d.mts +1 -3
  282. package/dist/types/tailordb.generated.d.mts +1 -3
  283. package/dist/types/workflow.generated.d.mts +1 -3
  284. package/dist/utils/test/index.d.mts +1 -3
  285. package/dist/utils/test/index.mjs +1 -1
  286. package/dist/vitest/date-representation.d.mts +1 -3
  287. package/dist/vitest/environment.d.mts +0 -2
  288. package/dist/vitest/index.d.mts +0 -2
  289. package/dist/vitest/migration-steps.d.mts +1 -3
  290. package/dist/vitest/mock-kysely.d.mts +0 -2
  291. package/dist/vitest/mocks/aigateway.d.mts +0 -2
  292. package/dist/vitest/mocks/authconnection.d.mts +0 -2
  293. package/dist/vitest/mocks/file.d.mts +0 -2
  294. package/dist/vitest/mocks/iconv.d.mts +0 -2
  295. package/dist/vitest/mocks/idp.d.mts +0 -2
  296. package/dist/vitest/mocks/logger.d.mts +0 -2
  297. package/dist/vitest/mocks/secretmanager.d.mts +0 -2
  298. package/dist/vitest/mocks/tailordb-pglite.d.mts +0 -2
  299. package/dist/vitest/mocks/tailordb.d.mts +0 -2
  300. package/dist/vitest/mocks/workflow.d.mts +0 -2
  301. package/dist/vitest/pglite-kysely.d.mts +0 -2
  302. package/dist/vitest/pglite-temporal.d.mts +1 -3
  303. package/dist/vitest/setup.d.mts +0 -2
  304. package/dist/vitest/workflow-local.d.mts +0 -2
  305. package/docs/cli/application.md +2 -1
  306. package/docs/cli/tailordb.md +9 -7
  307. package/docs/cli/user.md +5 -5
  308. package/docs/cli/workspace.md +1 -1
  309. package/docs/cli-reference.md +27 -26
  310. package/docs/configuration.md +15 -2
  311. package/docs/github-actions.md +33 -10
  312. package/docs/services/secret.md +6 -0
  313. package/docs/services/tailordb/index.md +23 -0
  314. package/docs/services/tailordb/migration.md +14 -9
  315. package/docs/testing.md +2 -2
  316. package/package.json +12 -12
  317. package/dist/application-B9_NHiUC.mjs +0 -207
  318. package/dist/application-B9_NHiUC.mjs.map +0 -1
  319. package/dist/cli/commands/tailordb/migrate/remote-state.d.mts +0 -1
  320. package/dist/crashreport-IN6H7GX3.mjs +0 -1
  321. package/dist/errors-BOF68LJ5.mjs +0 -5
  322. package/dist/errors-BOF68LJ5.mjs.map +0 -1
  323. package/dist/field-parse-C41e3UAF.mjs +0 -2
  324. package/dist/guards-yDXyKC9F.mjs +0 -2
  325. package/dist/guards-yDXyKC9F.mjs.map +0 -1
  326. package/dist/kysely-type-DxyIWXc6.mjs.map +0 -1
  327. package/dist/logger-RgtbhJ83.mjs.map +0 -1
  328. package/dist/manager-DTRhIupk.mjs +0 -2
  329. package/dist/manager-DTRhIupk.mjs.map +0 -1
  330. package/dist/register-ts-hook-Dp9reSRG.mjs +0 -1053
  331. package/dist/register-ts-hook-Dp9reSRG.mjs.map +0 -1
  332. package/dist/secret-file-C9wp_FCX.mjs +0 -2
  333. package/dist/secret-file-C9wp_FCX.mjs.map +0 -1
  334. package/dist/service-9SBPNpK8.mjs.map +0 -1
  335. package/dist/service-9rwi_I4d.mjs +0 -2
  336. package/dist/service-Ca1WwyIt.mjs +0 -1
package/dist/cli/main.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import{r as e}from"../field-parse-C41e3UAF.mjs";import{D as t,J as n,Kt as r,Mt as i,X as a,zt as o}from"../workspace_resource_pb-C4CkoYww.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 Oe,Li as ke,Ln as Ae,Lr as je,M as Me,Mi as Ne,Ni as Pe,Oi as Fe,Or as w,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-Dp9reSRG.mjs";import{$ as pr,C as mr,E as hr,F as gr,G as _r,H as vr,I as yr,K as br,L as xr,Q as Sr,R as Cr,T as wr,U as Tr,V as Er,W as Dr,Z as Or,_ as kr,b as Ar,bt as jr,c as Mr,ct as Nr,dt as Pr,et as Fr,ft as Ir,g as Lr,it as Rr,l as zr,nt as Br,ot as Vr,p as Hr,rt as Ur,s as Wr,st as Gr,ut as Kr,v as qr,w as Jr,z as Yr}from"../application-B9_NHiUC.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-6EkMfdOb.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-DTRhIupk.mjs";import{a as ui,i as di,n as fi}from"../kysely-type-DxyIWXc6.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
- `)}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={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`};function escapeHtml(e){return e.replace(/[&<>"']/g,e=>Qi[e])}const $i={success:`<svg viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12.5l4.5 4.5L19 7.5"/></svg>`,failure:`<svg viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>`},ea=`
2
+ import{r as e}from"../field-parse-BQhUAbpM.mjs";import{D as t,J as n,Kt as r,Mt as i,X as a,zt as o}from"../workspace_resource_pb-C4CkoYww.mjs";import{t as s}from"../assert-WeXvmG4j.mjs";import{_ as c,i as l,k as u,r as d}from"../service-eeXdVrDK.mjs";import{_ as f,a as p,f as m,g as h,i as g,l as _,n as v,o as y,r as b,s as x,t as S}from"../errors-BXmGBX-7.mjs";import{$n as C,Ai as ee,Ar as w,Bi as te,Bn as ne,Ci as T,Cn as re,Cr as ie,D as ae,Di as oe,Dr as se,Dt as ce,Ei as le,Er as ue,F as de,Fi as fe,Fn as pe,G as me,Gi as he,Gn as ge,Gr as _e,Gt as ve,H as ye,Hi as be,Hn as xe,Hr as Se,I as Ce,Ii as we,It as Te,J as Ee,Ji as E,Jn as De,Jr as Oe,Jt as ke,K as Ae,Ki as je,Kn as Me,Kr as Ne,Kt as Pe,L as Fe,Li as Ie,Ln as Le,M as Re,Mi as ze,Mr as Be,Ni as Ve,Nr as D,Oi as He,Or as Ue,P as We,Pi as Ge,Pr as O,Pt as Ke,Q as qe,Qi as k,Qn as Je,Qr as Ye,Qt as Xe,Ri as Ze,Rn as Qe,Rt as $e,S as et,Si as tt,Sr as A,T as nt,Ti as rt,Tr as it,Tt as at,Ui as ot,Un as st,Ur as ct,Ut as lt,V as ut,Vi as dt,Vn as ft,Vt as pt,Wi as mt,Wn as ht,Wt as gt,X as _t,Xi as vt,Xn as yt,Yn as bt,Yr as xt,Yt as St,Zi as Ct,Zn as wt,Zr as Tt,_i as Et,_n as Dt,_r as Ot,_t as kt,a as At,aa as jt,ai as Mt,an as Nt,ar as Pt,b as Ft,bi as j,bn as It,br as Lt,c as Rt,ca as zt,ci as Bt,cn as Vt,cr as Ht,ct as Ut,da as Wt,di as Gt,dn as Kt,dr as qt,dt as Jt,ea as M,ei as Yt,en as Xt,er as Zt,et as Qt,f as $t,fa as en,fi as N,fn as tn,fr as nn,ft as rn,g as an,gi as on,gn as sn,gr as cn,gt as ln,hi as un,hn as dn,hr as fn,ir as pn,it as mn,ji as hn,jr as gn,jt as _n,k as vn,ki as yn,kr as bn,la as xn,li as Sn,ln as Cn,lr as wn,m as Tn,ma as P,mi as En,mn as Dn,mr as On,mt as kn,n as An,na as jn,ni as Mn,nn as Nn,nr as Pn,nt as Fn,o as In,oa as Ln,oi as F,on as Rn,or as zn,ot as Bn,pa as Vn,pi as Hn,pn as Un,pr as Wn,qi as I,qn as Gn,qt as Kn,ra as qn,ri as Jn,rn as Yn,rr as Xn,sa as Zn,si as Qn,sr as $n,t as er,ta as tr,ti as nr,tn as rr,tr as ir,u as ar,ua as L,ui as or,un as sr,ur as cr,v as lr,vi as R,vn as ur,vr as dr,vt as fr,w as pr,wi as z,wn as mr,wr as B,wt as hr,xi as V,xr as gr,xt as _r,yi as H,yn as vr,yr,yt as br,z as xr,zi as U,zn as Sr}from"../register-ts-hook-CQ7shKO5.mjs";import{B as Cr,D as wr,E as Tr,F as Er,H as Dr,I as Or,J as kr,K as Ar,L as jr,R as Mr,T as Nr,U as Pr,W as Fr,Y as Ir,_ as Lr,at as Rr,c as zr,dt as Br,et as Vr,ht as Hr,l as Ur,lt as Wr,m as Gr,mt as Kr,nt as qr,ot as Jr,pt as Yr,q as Xr,rt as Zr,s as Qr,st as $r,tt as ei,u as ti,ut as ni,v as ri,w as ii,wt as ai,x as oi,y as si,z as ci}from"../application-DIsQSnj3.mjs";import{t as W}from"../multiline-EyzjEwn9.mjs";import{t as li}from"../package-json-C690ceex.mjs";import{t as ui}from"../user-agent-vdHYF3QL.mjs";import{t as di}from"../service_pb-6EkMfdOb.mjs";import{a as fi,i as pi,o as mi,r as hi,t as gi}from"../crashreport-DGU6lwiX.mjs";import{t as _i}from"../manager-B813m43t.mjs";import{a as vi,i as yi,n as bi}from"../kysely-type-B0ri1-Xs.mjs";import{arg as G,defineCommand as K,extractFields as xi,runMain as Si,toCamelCase as Ci}from"@politty/zod";import{withCompletionCommand as wi}from"@politty/zod/completion";import{withSkillCommand as Ti}from"@politty/zod/skill";import*as q from"pathe";import{dirname as Ei,resolve as Di}from"pathe";import{resolvePackageJSON as Oi}from"pkg-types";import{z as J}from"zod";import{ScalarType as Y,create as ki}from"@bufbuild/protobuf";import*as X from"node:fs";import{accessSync as Ai,constants as ji,readdirSync as Mi}from"node:fs";import{timestampDate as Ni}from"@bufbuild/protobuf/wkt";import{Code as Z,ConnectError as Q}from"@connectrpc/connect";import{pathToFileURL as Pi}from"node:url";import{generateCodeVerifier as Fi}from"@badgateway/oauth2-client";import*as Ii from"node:crypto";import{randomBytes as Li}from"node:crypto";import*as Ri from"node:os";import*as zi from"node:http";import Bi from"open";import*as Vi from"rolldown";import{parseSync as Hi}from"oxc-parser";import*as $ from"node:fs/promises";import{setTimeout as Ui}from"node:timers/promises";import{spawn as Wi,spawnSync as Gi}from"node:child_process";import{TraceMap as Ki,generatedPositionFor as qi,originalPositionFor as Ji}from"@jridgewell/trace-mapping";const Yi=di.methods.filter(e=>e.methodKind===`unary`);function listMethodNames(){return Yi.map(e=>e.name).toSorted()}function listMethodChoices(){return Yi.flatMap(e=>[e.name,`${di.typeName}/${e.name}`]).toSorted()}function getMethodDescriptor(e){return Yi.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 Xi=/* @__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 Xi.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 Zi={[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 Zi[e]??`scalar(${e})`}function enumLabel(e){return`enum ${shortName(e.typeName)}`}function enumOf(e){if(e.fieldKind===`enum`||e.fieldKind===`list`&&e.listKind===`enum`)return e.enum}function describeFieldType(e){switch(e.fieldKind){case`scalar`:return scalarLabel(e.scalar);case`enum`:return enumLabel(e.enum);case`message`:return shortName(e.message.typeName);case`list`:{let t;return t=e.listKind===`scalar`?scalarLabel(e.scalar):e.listKind===`enum`?enumLabel(e.enum):shortName(e.message.typeName),`repeated ${t}`}case`map`:{let t=scalarLabel(e.mapKey),n;return n=e.mapKind===`scalar`?scalarLabel(e.scalar):e.mapKind===`enum`?enumLabel(e.enum):shortName(e.message.typeName),`map<${t}, ${n}>`}default:return`<unknown>`}}function fieldToJson(e,t){let n={name:e.localName,protoName:e.name,type:describeFieldType(e),fieldKind:e.fieldKind,repeated:e.fieldKind===`list`};e.oneof&&(n.oneof=e.oneof.name);let r=enumOf(e);r&&(n.enumValues=r.values.map(e=>e.name));let i=nestedMessage(e);return i&&!t.has(i)?(t.add(i),n.message={typeName:i.typeName,fields:i.fields.map(e=>fieldToJson(e,t))},t.delete(i)):i&&(n.message={typeName:i.typeName,fields:[],recursive:!0}),n}function renderInspectJson(e){let t=/* @__PURE__ */ new Set([e.input]);return{method:e.name,input:{typeName:e.input.typeName,fields:e.input.fields.map(e=>fieldToJson(e,t))},output:{typeName:e.output.typeName}}}function renderFieldText(e,t,n){let r=[],i=e.oneof?` (oneof ${e.oneof.name})`:``;r.push(`${t}${e.localName}: ${describeFieldType(e)}${i}`);let a=enumOf(e);if(a){let e=a.values.map(e=>e.name).join(`, `);r.push(`${t} values: ${e}`)}let o=nestedMessage(e);if(o&&!n.has(o)){n.add(o);for(let e of o.fields)r.push(...renderFieldText(e,`${t} `,n));n.delete(o)}else o&&r.push(`${t} …(recursive ${o.typeName})`);return r}function renderInspectText(e){let t=[];t.push(`${e.name}`),t.push(` request: ${e.input.typeName}`);let n=/* @__PURE__ */ new Set([e.input]);for(let r of e.input.fields)t.push(...renderFieldText(r,` `,n));return t.push(` response: ${e.output.typeName}`),t.join(`
3
+ `)}const Qi=E({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 S({code:`API_METHOD_UNKNOWN`,message:`unknown method: ${t}`,suggestion:"Run `tailor api list` to see available methods.",command:`api inspect`});m.jsonMode?m.out(renderInspectJson(n)):m.out(renderInspectText(n))}}),$i=E({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(m.jsonMode)m.out(e);else for(let t of e)m.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 S({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 ea=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`]),ta=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=>ea.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)}}),na=E({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:$i,inspect:Qi},args:J.strictObject({...P,...Ct,body:G(J.string().default(`{}`),{alias:`b`,description:`Request body as JSON.`}),field:G(ta.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 T({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 S({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 we({workspaceId:e[`workspace-id`],profile:e.profile}),i=!0}catch{}if(a.includes(`namespaceName`)&&!Object.hasOwn(r,`namespaceName`))try{let{config:n}=await z(e.config),a=resolveNamespaceName(t,n);a&&(r.namespaceName=a,i=!0)}catch{}}let a=await tt({profile:e.profile,endpoint:e.endpoint,body:i&&r?JSON.stringify(r):e.body});m.out(JSON.stringify(a.data,null,2))}}),ra=E({name:`status`,description:`Show the active Tailor Platform authentication status without printing tokens.`,args:J.strictObject({profile:P.profile}),run:async({profile:e})=>{let t=await ee({profile:e});if(m.out(t),!t.authenticated)throw S({code:`NOT_AUTHENTICATED`,message:`Not authenticated.`,suggestion:`Log in and try again.`,next:{command:`tailor`,args:[`login`,...L({profile:e})]}})}}),ia=E({name:`token`,description:`Print a valid Tailor Platform access token to stdout, refreshing it first if it expires within five minutes.`,args:J.strictObject({profile:P.profile}),run:async({profile:e})=>{let t=await yn({profile:e});m.out(t)}}),aa=K({name:`auth`,description:`Authentication helpers for scripts and plugins.`,subCommands:{status:ra,token:ia}}),oa={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`};function escapeHtml(e){return e.replace(/[&<>"']/g,e=>oa[e])}const sa={success:`<svg viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12.5l4.5 4.5L19 7.5"/></svg>`,failure:`<svg viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>`},ca=`
4
4
  :root{color-scheme:light dark;--bg:#f5f6f8;--card:#fff;--text:#16181d;--muted:#5d6470;--border:#e2e5ea;--ok:#15803d;--ok-bg:#dcfce7;--ng:#b91c1c;--ng-bg:#fee2e2}
5
5
  @media (prefers-color-scheme: dark){:root{--bg:#0f1115;--card:#181b21;--text:#f2f4f8;--muted:#9aa3b2;--border:#2a2f38;--ok:#4ade80;--ok-bg:#12301d;--ng:#f87171;--ng-bg:#3a1717}}
6
6
  *{box-sizing:border-box}
@@ -11,36 +11,36 @@ main{width:100%;max-width:420px;padding:32px 28px;text-align:center;background:v
11
11
  .failure .icon{color:var(--ng);background:var(--ng-bg)}
12
12
  h1{margin:16px 0 8px;font-size:20px}
13
13
  p{margin:0;color:var(--muted);overflow-wrap:anywhere}
14
- `.replace(/\n/g,``);function renderCallbackPage(e){let t=escapeHtml(e.title),n=escapeHtml(e.message),r=e.status===`success`?`<script>window.close()<\/script>`:``;return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${t}</title><style>${ea}</style></head><body class="${e.status}"><main><div class="icon">${$i[e.status]}</div><h1>${t}</h1><p>${n}</p></main>${r}</body></html>`}const ta={"Content-Type":`text/html; charset=utf-8`};function sendCallbackSuccess(e,t){e.writeHead(200,ta),e.end(renderCallbackPage({status:`success`,title:t,message:`You can close this tab and return to the terminal.`}))}function sendCallbackFailure(e,t,n,r){e.writeHead(t,ta),e.end(renderCallbackPage({status:`failure`,title:n,message:Xr(r)?r.message:`Return to the terminal for details.`}))}const na={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 ra=C({name:`authorize`,description:`Authorize an auth connection via OAuth2 flow.`,args:J.strictObject({...N,...na,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 pr(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}),sendCallbackSuccess(l,`Authorization successful`),c.close(),i()}catch(e){sendCallbackFailure(l,400,`Authorization failed`,e),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})}}),ia=C({name:`delete`,description:`Delete an auth connection entirely.`,args:J.strictObject({...N,...na,...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 aa=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=>Br(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}}}),oa=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}`)}}),sa=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,...na,...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})}}),ca=K({name:`authconnection`,description:`Manage auth connections.`,subCommands:{authorize:ra,list:aa,open:oa,revoke:sa,delete:ia},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 la=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)}}}),ua=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,`
15
- `),n=`\n${ii}\n`,r=t.lastIndexOf(n);if(r===-1)return;let i=t.slice(r+n.length).split(`
16
- `)[0];return i?JSON.parse(i):void 0}catch{return}}const da=K({name:`crashreport`,description:`Manage crash reports.`,subCommands:{list:la,send:ua},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,i=t.timeout??18e5,a=t.errorCodePrefix??`MIGRATION_TEST_CLONE`,o=Date.now()+i,s;for(let c=i;c>0;c=o-Date.now()){let i;try{i=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()>=o-100)break;throw e}if(i.status===r.COMPLETED)return;if(i.status===r.FAILED)throw W({code:`${a}_FAILED`,message:`Application data clone failed: ${i.errorMessage||`unknown platform error`}`});if(i.status!==r.PENDING&&i.status!==r.PROCESSING)throw Zr(`Application data clone returned unexpected status ${i.status}.`);i.status!==s&&(s=i.status,t.onStatus?.(i.status)),await delay(Math.min(n,Math.max(o-Date.now(),0)))}throw W({code:`${a}_TIMEOUT`,message:`Application data clone timed out after ${i<1e3?`${i} ms`:`${Math.round(i/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(`
17
- `).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 Gr(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 Ae(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 Gr(()=>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)w(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 Pr(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,Mr(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 fa={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 pa={[r.PENDING]:`pending`,[r.PROCESSING]:`processing`,[r.COMPLETED]:`completed`,[r.FAILED]:`failed`};function statusName(e){return pa[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 Pr(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 ma=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`}}),...fa,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})}}),ha=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`}}),...fa,"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 Pr(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`})}}),ga=K({name:`operation`,description:`Inspect asynchronous application data operations.`,subCommands:{get:ha}}),_a=K({name:`data`,description:`Manage application data across workspaces.`,subCommands:{clone:ma,operation:ga}}),va=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})}}),ya=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===a.JOB)return`workflow--${e}`;let n=/^([^.]+)\.(.+)\.body\.js$/.exec(e);if(n){let[,e,t]=n;return`resolver--${e}--${t}`}let r=/^(.+)\.operation\.js$/.exec(e);if(r){let[,e]=r;return`executor--${e}`}let i=/^([^.]+)\.([^.]+)\.hook\.js$/.exec(e);if(i){let[,e,t]=i;return`auth-hook--${e}--${t}`}return t===a.UNSPECIFIED&&!e.includes(`.`)?`workflow--${e}`:null}async function downloadFunctionScript(e){let{client:t,workspaceId:n,name:r,contentHash:i}=e;try{let e=[];for await(let a of t.downloadFunctionRegistryScript({workspaceId:n,name:r,contentHash:i}))a.payload.case===`chunk`&&e.push(a.payload.value);return e.length===0?null:{code:Buffer.concat(e).toString(`utf-8`)}}catch(t){return f.debug(`Failed to download function script "${e.name}": ${t}`),null}}const ba=/^\s+at\s+(?:(.+?)\s+\()?(file:\/\/\/.+?):(\d+):(\d+)\)?$/;function parseStackTrace(e){let t=e.split(`
14
+ `.replace(/\n/g,``);function renderCallbackPage(e){let t=escapeHtml(e.title),n=escapeHtml(e.message),r=e.status===`success`?`<script>window.close()<\/script>`:``;return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${t}</title><style>${ca}</style></head><body class="${e.status}"><main><div class="icon">${sa[e.status]}</div><h1>${t}</h1><p>${n}</p></main>${r}</body></html>`}const la={"Content-Type":`text/html; charset=utf-8`};function sendCallbackSuccess(e,t){e.writeHead(200,la),e.end(renderCallbackPage({status:`success`,title:t,message:`You can close this tab and return to the terminal.`}))}function sendCallbackFailure(e,t,n,r){e.writeHead(t,la),e.end(renderCallbackPage({status:`failure`,title:n,message:p(r)?r.message:`Return to the terminal for details.`}))}const ua={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 S({code:`OIDC_DISCOVERY_FAILED`,message:`Failed to fetch OIDC discovery from ${t}: ${y(e).message}`,cause:e})});if(!n.ok)throw S({code:`OIDC_DISCOVERY_FAILED`,message:`Failed to fetch OIDC discovery from ${t}: ${n.status}`});return n.json()}function randomState$1(){return Ii.randomBytes(32).toString(`base64url`)}const da=E({name:`authorize`,description:`Authorize an auth connection via OAuth2 flow.`,args:J.strictObject({...P,...ua,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 T({profile:e.profile});let t=b({command:`tailor`,args:[`authconnection`,`open`,...L({profile:e.profile,workspaceId:e[`workspace-id`]})]}),{client:n,workspaceId:r}=await j({profile:e.profile,workspaceId:e[`workspace-id`]}),i=(await qr(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 S({code:`AUTH_CONNECTION_NOT_FOUND`,message:`Auth connection "${e.name}" not found.`});if(i.config.case!==`oauth2`)throw S({code:`AUTH_CONNECTION_NOT_OAUTH2`,message:`Auth connection "${e.name}" is not an OAuth2 connection.`});let a=i.config.value,o=`http://localhost:${e.port}/callback`,s=randomState$1(),c;c=a.authUrl?a.authUrl:(await fetchOIDCDiscovery(a.providerUrl)).authorization_endpoint;let l=new URL(c);l.searchParams.set(`client_id`,a.clientId),l.searchParams.set(`redirect_uri`,o),l.searchParams.set(`response_type`,`code`),l.searchParams.set(`scope`,e.scopes.replace(/,/g,` `)),l.searchParams.set(`state`,s),l.searchParams.set(`access_type`,`offline`),await new Promise((i,a)=>{let handleCallback=async(t,l)=>{if(!t.url?.startsWith(`/callback`))l.writeHead(404),l.end(`Not found`);else try{let a=new URL(t.url,`http://localhost:${e.port}`),u=a.searchParams.get(`code`),d=a.searchParams.get(`state`),f=a.searchParams.get(`error`);if(f)throw S({code:`AUTHORIZATION_FAILED`,message:`Authorization failed: ${f}`});if(d!==s)throw S({code:`AUTHORIZATION_STATE_MISMATCH`,message:`State mismatch — possible CSRF attack.`});if(!u)throw S({code:`AUTHORIZATION_CODE_MISSING`,message:`No authorization code received.`});m.registerSecret(u),await n.exchangeAuthConnectionAuthorizationCode({workspaceId:r,connectionName:e.name,authorizationCode:u,redirectUri:o}),sendCallbackSuccess(l,`Authorization successful`),c.close(),i()}catch(e){sendCallbackFailure(l,400,`Authorization failed`,e),c.close(),a(y(e))}},c=zi.createServer((e,t)=>void handleCallback(e,t)),u=setTimeout(()=>{c.close(),a(S({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:`;m.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(m.info(e[`no-browser`]?`Open this URL in your browser to authorize:\n\n${n}\n`:`Opening browser for authorization:\n\n${n}\n`),m.info(`If this flow doesn't complete, you can authorize via the Console instead:\n ${t}`),!e[`no-browser`])try{await Bi(n)}catch{m.warn(`Failed to open browser automatically. Please open the URL above manually.`)}};c.listen(e.port,()=>void announceAuthorizeUrl())}),m.success(`Auth connection "${e.name}" authorized successfully.`),V({changed:!0,workspaceId:r,name:e.name})}}),fa=E({name:`delete`,description:`Delete an auth connection entirely.`,args:J.strictObject({...P,...ua,...k}),run:async e=>{await T({profile:e.profile});let{client:t,workspaceId:n}=await j({profile:e.profile,workspaceId:e[`workspace-id`]});if(!e.yes&&await H.text({message:`Enter the connection name to confirm deletion ("${e.name}"):`})!==e.name)throw S({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?S({code:`AUTH_CONNECTION_NOT_FOUND`,message:`Auth connection "${e.name}" not found.`,cause:t}):t}m.success(`Auth connection "${e.name}" deleted.`),V({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?Ni(e.createdAt):null}}const pa=E({name:`list`,description:`List all auth connections.`,args:J.strictObject({...P,...zt()}),run:async e=>{let{client:t,workspaceId:n}=await j({profile:e.profile,workspaceId:e[`workspace-id`]});try{let r=Vn(e.order),i=await Et(e.limit,e=>Rr(async(e,i)=>{let{connections:a,nextPageToken:o}=await t.listAuthConnections({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e}));m.out(i.items.map(connectionInfo)),await R(i,e.limit)}catch(e){if(e instanceof Q&&e.code===Z.NotFound){m.out([]);return}throw e}}}),ma=E({name:`open`,description:`Open the auth connections page in the Tailor Platform Console.`,args:J.strictObject({...P}),run:async e=>{let t=await we({workspaceId:e[`workspace-id`],profile:e.profile}),n=`/workspaces/${t}/services/auth-connections`,r=await ze({profile:e.profile,...e[`workspace-id`]===void 0?{}:{allowMissingProfile:!0}}),i=new URL(n,r).toString(),a=m.jsonMode;m.info(`Opening auth connections page in Tailor Platform Console...`);let o=!0;try{await Bi(i)}catch{o=!1}a?m.out({consoleUrl:i,workspaceId:t,opened:o}):o?(m.out(`Console URL: ${i}`),m.out(`Workspace ID: ${t}`)):m.warn(`Failed to open browser automatically. Please open this URL manually:\n${i}`)}}),ha=E({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({...P,...ua,...k}),run:async e=>{await T({profile:e.profile});let{client:t,workspaceId:n}=await j({profile:e.profile,workspaceId:e[`workspace-id`]});if(!e.yes&&await H.text({message:`Enter the connection name to confirm revocation ("${e.name}"):`})!==e.name)throw S({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?S({code:`AUTH_CONNECTION_NOT_FOUND`,message:`Auth connection "${e.name}" not found.`,cause:t}):t}m.success(`Auth connection "${e.name}" revoked.`),V({changed:!0,workspaceId:n,name:e.name})}}),ga=K({name:`authconnection`,description:`Manage auth connections.`,subCommands:{authorize:da,list:pa,open:ma,revoke:ha,delete:fa},defaultSubCommand:`list`});function orderAndLimitCrashReports(e,t){let n=e.filter(e=>e.endsWith(pi)).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 _a=E({name:`list`,description:`List local crash report files.`,args:J.strictObject({...zt()}),run:async e=>{let t=mi(),n=m.jsonMode;if(!t.localDir){m.info(`Crash report directory not available.`),n&&m.out([]);return}let r;try{r=X.readdirSync(t.localDir)}catch{m.info(`No crash reports found.`),n&&m.out([]);return}let i=await Et(e.limit,async t=>orderAndLimitCrashReports(r,{order:e.order,limit:t})),a=i.items;if(a.length===0)m.info(`No crash reports found.`),n&&m.out([]);else if(n)m.out(formatCrashReportFiles(a,t.localDir)),await R(i,e.limit);else{m.info(`${a.length} crash report(s) in ${t.localDir}:`);for(let e of a)m.log(` ${e}`);await R(i,e.limit)}}}),va=E({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{m.error(`Crash report file not found: ${e.file}`),process.exit(1)}let n=parseCrashLogFile(t);n||(m.error(`Failed to parse crash report file. The file may be corrupted.`),process.exit(1));let r=await ui();m.info(`Sending crash report...`),await hi(n,r)?(m.success(`Crash report submitted successfully. Thank you!`),V({changed:!0,id:n.id,file:e.file})):(m.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,`
15
+ `),n=`\n${fi}\n`,r=t.lastIndexOf(n);if(r===-1)return;let i=t.slice(r+n.length).split(`
16
+ `)[0];return i?JSON.parse(i):void 0}catch{return}}const ya=K({name:`crashreport`,description:`Manage crash reports.`,subCommands:{list:_a,send:va},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`?S({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 S({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`?S({code:`MIGRATION_ASSERTION_SCRIPT_NOT_FOUND`,message:`Migration assertion script not found: ${t}`,cause:e}):e}if(!n.isFile())throw S({code:`MIGRATION_ASSERTION_SCRIPT_INVALID`,message:`Migration assertion path is not a file: ${t}`})}function assertCloneTargetRegion(e,t){if(e!==t)throw S({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 S({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 S({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 S({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=>Sr(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,i=t.timeout??18e5,a=t.errorCodePrefix??`MIGRATION_TEST_CLONE`,o=Date.now()+i,s;for(let c=i;c>0;c=o-Date.now()){let i;try{i=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()>=o-100)break;throw e}if(i.status===r.COMPLETED)return;if(i.status===r.FAILED)throw S({code:`${a}_FAILED`,message:`Application data clone failed: ${i.errorMessage||`unknown platform error`}`});if(i.status!==r.PENDING&&i.status!==r.PROCESSING)throw g(`Application data clone returned unexpected status ${i.status}.`);i.status!==s&&(s=i.status,t.onStatus?.(i.status)),await delay(Math.min(n,Math.max(o-Date.now(),0)))}throw S({code:`${a}_TIMEOUT`,message:`Application data clone timed out after ${i<1e3?`${i} ms`:`${Math.round(i/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(`
17
+ `).map((e,n)=>{let r;try{r=JSON.parse(e)}catch(e){throw S({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 S({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 Kn(a.fields))r===t?i.push(t):n.has(r)&&e.add(r);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)}-${Li(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 S({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 ni(async()=>{let{folder:t}=await e.getOrganizationFolder({organizationId:i,folderId:r});return t}))throw S({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 S({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 S({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=O(n.migrationsDir,0);if(!o)throw S({code:`MIGRATION_BASELINE_NOT_FOUND`,message:`No migration baseline snapshot found for namespace "${n.namespace}".`});let s=await Qe(e,t,n.namespace,o,i,a);if(s.length>0)throw S({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:w(s),suggestion:`Bring the source schema in line with 0000 or set its migration label.`});return 0}async function assertSourceBaselineFresh(e,t,n){let r=e.loaded,i=B(r.config,q.dirname(r.config.path)),a=r.application.tailorDBServices.map(st),o=(await ht(e.client,n,i,r.config,a)).find(e=>e.hasDrift||e.checkpointMissingLocal||e.checkpointRepair);if(o)throw S({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 A(e.client,N(n,`tailordb`,o.namespace));gr(s,o.namespace);let c=await resolveSourceMigrationNumber(e.client,n,o,s,r.config,a);if(c!==i.migrationNumber)throw S({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 Sr(e.client,n,r.namespace);if(Jn(i,a).changes.length>0)throw S({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 ni(()=>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 S({code:`AUTH_CONFIG_REQUIRED`,message:`Auth configuration is required to execute migration test scripts.`});let i=n??yt(migrationConfig(e.loaded,t),r.config.machineUsers?Object.keys(r.config.machineUsers):void 0);if(!i)throw S({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 gt({configPath:e.configPath}),n=q.dirname(t.config.path),r=B(t.config,n);if(r.length===0)throw it();for(let e of r)D(e.migrationsDir,e.namespace);let i;e.data===`seed`&&(i=await lt({configPath:t.config.path}),assertSeedDataDirectory(q.join(i.distPath,`data`))),e.assertionPath&&assertAssertionScript(e.assertionPath);let a=t.application.tailorDBServices.map(st),o=await yn({profile:e.profile}),c=await Ge({profile:e.profile}),l=await Kr(o,c),u=await we({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 ht(l,u,r,t.config,a),v=_.find(e=>e.hasDrift||e.checkpointMissingLocal);if(v)throw S({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 S({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,x=/* @__PURE__ */ new Map,C=[];for(let e of r){let n=await A(l,N(u,`tailordb`,e.namespace));gr(n,e.namespace);let r=await resolveSourceMigrationNumber(l,u,e,n,t.config,a),i=Ne(e.migrationsDir);if(r>i)throw S({code:`MIGRATION_TEST_SOURCE_AHEAD`,message:`Source namespace "${e.namespace}" is at migration ${r}, but the local history ends at ${i}.`});let o=O(e.migrationsDir,r);if(!o)throw S({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=O(e.migrationsDir,i);if(!s)throw S({code:`MIGRATION_TEST_SNAPSHOT_NOT_FOUND`,message:`No target migration snapshot found for namespace "${e.namespace}".`});x.set(e.namespace,s),r<i&&C.push(e.namespace)}if(C.length===0)throw S({code:`MIGRATION_TEST_NO_PENDING_MIGRATIONS`,message:`No pending TailorDB migrations found in the source workspace.`});let ee=await createMigrationTestBaselineSnapshots({client:l,workspaceId:u,dataMode:e.data,inputs:a,baselines:b}),w={sourceWorkspaceId:u,sourceApplicationName:t.config.name,temporaryWorkspace:{name:temporaryWorkspaceName(),region:m.region,...g},baselines:b,baselineSnapshots:ee,targetSnapshots:x,pendingNamespaces:C,...h?{designatedTarget:{id:h.id,region:h.region}}:{}};return{state:{client:l,loaded:t,options:e,...i?{seedContext:i}:{}},prepared:w}}function createMigrationTestDependencies(){let e;return{prepare:async t=>{let{state:n,prepared:r}=await prepareMigrationTest(t);return e=n,r},createWorkspace:async t=>{let n=stateOrThrow(e),r=await Rn(n.client,t.temporaryWorkspace);return m.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 ur(i.client,t,new Date(r.getTime()+It(n)))},deployBaseline:async({prepared:t,targetWorkspaceId:n})=>{let r=stateOrThrow(e);await deleteExistingUserProfileConfig(r,n),await rr({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 Je(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=st(e);return[e.namespace,n?.snapshot??Mt({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 Xe(e,l,q.dirname(r.loaded.config.path)),d=ke({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 St({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 S({code:`MIGRATION_TEST_SEED_FAILED`,message:i.error??`Seed execution failed for namespace "${e}".`});if(JSON.parse(i.result||`{}`).success!==!0)throw S({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),m.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?S({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 g(`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 Nn({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 cn(r,s,0,o.loaded.config.env??{},q.dirname(o.loaded.config.path),Pe(o.loaded.plugins,`@tailor-platform/kysely-type`)?.temporal??!1,zr(o.loaded.config)),u=await St({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 S({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 ba={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`,...L({profile:e.profile})]}function resumeHint(e){return b({command:`tailor`,args:resumeCommandArgs(e)})}async function hintOnInterrupt(e,t){let onInterrupt=()=>{m.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 xa={[r.PENDING]:`pending`,[r.PROCESSING]:`processing`,[r.COMPLETED]:`completed`,[r.FAILED]:`failed`};function statusName(e){return xa[e]??`unknown`}function reportStatus(e){m.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=jn(e.config),n=t?[t]:[];if(e.sourceWorkspaceId===e.targetWorkspaceId)throw S({code:`DATA_CLONE_SAME_WORKSPACE`,message:`The source and target workspaces must be different.`,command:`data clone`});let r=await Kr(await yn({profile:e.profile}));try{await r.getApplication({workspaceId:e.targetWorkspaceId,applicationName:e.name})}catch(t){throw t instanceof Q&&t.code===Z.NotFound?S({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`,...L({workspaceId:e.targetWorkspaceId,profile:e.profile}),...n]}}:{},command:`data clone`,cause:t}):t}if(!e.yes&&!await H.confirm({message:`This will copy the data of application "${e.name}" from workspace "${e.sourceWorkspaceId}" to workspace "${e.targetWorkspaceId}". Continue?`,default:!1}))throw S({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?S({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?S({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 ${b({command:`tailor`,args:[`tailordb`,`truncate`,`--all`,...L({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?S({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 g(`Application data clone returned no operation ID.`);m.info(`Clone started (operation: ${i})`);let a={sourceWorkspaceId:e.sourceWorkspaceId,targetWorkspaceId:e.targetWorkspaceId,operationId:i,profile:e.profile};if(e.noWait)return m.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})),m.success(`Cloned data of application "${e.name}" from "${e.sourceWorkspaceId}" to "${e.targetWorkspaceId}" in ${formatElapsed(Date.now()-o)}`),{operationId:i,status:`completed`}}const Sa=E({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({...k,profile:G(J.string().optional(),{alias:`p`,description:`Workspace profile`,env:`TAILOR_PLATFORM_PROFILE`,completion:{type:`none`}}),...ba,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`}}),...Ct,"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 T({profile:e.profile});let t=e.name??(await z(e.config)).config.name,{operationId:n,status:r}=await $clone({sourceWorkspaceId:e.from,targetWorkspaceId:e.to,name:t,config:e.config,nameFromConfig:e.name===void 0,copyFiles:e[`copy-files`],copyIdpUsers:e[`copy-idp-users`],noWait:e[`no-wait`],profile:e.profile,yes:e.yes});V({changed:!0,sourceWorkspaceId:e.from,targetWorkspaceId:e.to,operationId:n,status:r})}}),Ca=E({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`}}),...ba,"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 yn({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);m.info(`Clone operation ${n.operationId}: ${r}`),e.errorMessage&&m.info(`Message: ${e.errorMessage}`),m.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})),m.success(`Clone operation ${n.operationId} completed (waited ${formatElapsed(Date.now()-r)})`),m.out({operationId:n.operationId,status:`completed`})}}),wa=K({name:`operation`,description:`Inspect asynchronous application data operations.`,subCommands:{get:Ca}}),Ta=K({name:`data`,description:`Manage application data across workspaces.`,subCommands:{clone:Sa,operation:wa}}),Ea=E({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({...P,...Ln,...k,"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 T({profile:e.profile});let{initTelemetry:t}=await import(`../telemetry-nqOtDWNO.mjs`);await t(),await Xt({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`],...jt(e),noSchemaCheck:e[`no-schema-check`],migrationSkipSteps:ge(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})}}),Da=K({name:`executor`,description:`Manage executors`,subCommands:{trigger:at,jobs:_n,list:ce,get:pt,webhook:hr},defaultSubCommand:`list`});function scriptNameToRegistryName(e,t){if(t===a.JOB)return`workflow--${e}`;let n=/^([^.]+)\.(.+)\.body\.js$/.exec(e);if(n){let[,e,t]=n;return`resolver--${e}--${t}`}let r=/^(.+)\.operation\.js$/.exec(e);if(r){let[,e]=r;return`executor--${e}`}let i=/^([^.]+)\.([^.]+)\.hook\.js$/.exec(e);if(i){let[,e,t]=i;return`auth-hook--${e}--${t}`}return t===a.UNSPECIFIED&&!e.includes(`.`)?`workflow--${e}`:null}async function downloadFunctionScript(e){let{client:t,workspaceId:n,name:r,contentHash:i}=e;try{let e=[];for await(let a of t.downloadFunctionRegistryScript({workspaceId:n,name:r,contentHash:i}))a.payload.case===`chunk`&&e.push(a.payload.value);return e.length===0?null:{code:Buffer.concat(e).toString(`utf-8`)}}catch(t){return m.debug(`Failed to download function script "${e.name}": ${t}`),null}}const Oa=/^\s+at\s+(?:(.+?)\s+\()?(file:\/\/\/.+?):(\d+):(\d+)\)?$/;function parseStackTrace(e){let t=e.split(`
18
18
  `),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(`
19
- `);i.startsWith(`rpc error: code = Aborted desc = `)&&(i=i.slice(33));let a=[];for(let e of r){let t=ba.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 xa=/\/\/[#@]\s*sourceMappingURL=data:application\/json[^,]*;base64,(.+)$/m;function extractInlineSourcemap(e){let t=xa.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(`
20
- `),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(`
21
- `)}function readInstalledSource(e){try{let t=X.realpathSync(e);return xr(t)===void 0?void 0:X.readFileSync(t,`utf-8`)}catch{return}}function formatMappedError(e,t,n,r){let i=[` ${h.error(e)}`];for(let e of t)if(e.mapped){let{source:t,line:a,column:o,name:s}=e.mapped,c=r?q.resolve(r,t):q.resolve(t),l=q.relative(process.cwd(),c),u=l.startsWith(`..`)?l:`./${l}`,d=s??e.original.functionName,f=buildSourceLink(u,c,a,o);if(i.push(`\n at ${d} (${f})`),n){let e=n.sources.indexOf(t),r=(e===-1?void 0:n.sourcesContent?.[e])||readInstalledSource(c);r&&i.push(buildCodeSnippet(r,a))}}else{let t=`${e.original.file.replace(/^file:\/\/\//,``)}:${e.original.line}:${e.original.column}`;i.push(`\n ${h.dim(`at ${e.original.functionName} (${t})`)}`)}return i.join(`
22
- `)}function formatErrorWithSourcemap(e,t,n){try{let{errorMessage:r,frames:i}=parseStackTrace(e);if(i.length===0)return null;let a=extractInlineSourcemap(t);if(!a)return null;let o=mapStackFrames(i,a);return o.some(e=>e.mapped!==null)?formatMappedError(r,o,a,n):null}catch{return null}}function functionExecutionTypeToString(e){return gn(a,e)??`UNSPECIFIED`}function functionErrorKindToString(e){return gn(n,e)??`UNSPECIFIED`}function toFunctionExecutionListInfo(e){return{id:e.id,scriptName:e.scriptName,status:cn(e.status),type:functionExecutionTypeToString(e.type),startedAt:e.startedAt?Ti(e.startedAt):null,finishedAt:e.finishedAt?Ti(e.finishedAt):null,errorKind:functionErrorKindToString(e.errorKind),errorName:e.error?.name||null,errorMessage:e.error?.message||null}}function toFunctionExecutionDetailInfo(e){return{...toFunctionExecutionListInfo(e),logs:An(e.logEntries),logEntries:e.logEntries.map(Hn),result:e.result,error:e.error?{name:e.error.name,message:e.error.message,stackTrace:e.error.stackTrace}:null}}function composeExecutionErrorString(e){let{name:t,message:n,stackTrace:r}=e,i=t&&n?`${t}: ${n}`:t||n;if(!r)return i;let a=r.split(`
19
+ `);i.startsWith(`rpc error: code = Aborted desc = `)&&(i=i.slice(33));let a=[];for(let e of r){let t=Oa.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 ka=/\/\/[#@]\s*sourceMappingURL=data:application\/json[^,]*;base64,(.+)$/m;function extractInlineSourcemap(e){let t=ka.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 Ki(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=qi(t,{source:r,line:e.line,column:e.column-1});if(i.line==null)continue;let a=Ji(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(`
20
+ `),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(` ${f.error(`>`)} ${f.error(`${i} | ${s}`)}`):o.push(` ${f.dim(`${i} | ${s}`)}`)}return o.join(`
21
+ `)}function readInstalledSource(e){try{let t=X.realpathSync(e);return Mr(t)?X.readFileSync(t,`utf-8`):void 0}catch{return}}function formatMappedError(e,t,n,r){let i=[` ${f.error(e)}`];for(let e of t)if(e.mapped){let{source:t,line:a,column:o,name:s}=e.mapped,c=r?q.resolve(r,t):q.resolve(t),l=q.relative(process.cwd(),c),u=l.startsWith(`..`)?l:`./${l}`,d=s??e.original.functionName,f=buildSourceLink(u,c,a,o);if(i.push(`\n at ${d} (${f})`),n){let e=n.sources.indexOf(t),r=(e===-1?void 0:n.sourcesContent?.[e])||readInstalledSource(c);r&&i.push(buildCodeSnippet(r,a))}}else{let t=`${e.original.file.replace(/^file:\/\/\//,``)}:${e.original.line}:${e.original.column}`;i.push(`\n ${f.dim(`at ${e.original.functionName} (${t})`)}`)}return i.join(`
22
+ `)}function formatErrorWithSourcemap(e,t,n){try{let{errorMessage:r,frames:i}=parseStackTrace(e);if(i.length===0)return null;let a=extractInlineSourcemap(t);if(!a)return null;let o=mapStackFrames(i,a);return o.some(e=>e.mapped!==null)?formatMappedError(r,o,a,n):null}catch{return null}}function functionExecutionTypeToString(e){return On(a,e)??`UNSPECIFIED`}function functionErrorKindToString(e){return On(n,e)??`UNSPECIFIED`}function toFunctionExecutionListInfo(e){return{id:e.id,scriptName:e.scriptName,status:wn(e.status),type:functionExecutionTypeToString(e.type),startedAt:e.startedAt?Ni(e.startedAt):null,finishedAt:e.finishedAt?Ni(e.finishedAt):null,errorKind:functionErrorKindToString(e.errorKind),errorName:e.error?.name||null,errorMessage:e.error?.message||null}}function toFunctionExecutionDetailInfo(e){return{...toFunctionExecutionListInfo(e),logs:qt(e.logEntries),logEntries:e.logEntries.map(nn),result:e.result,error:e.error?{name:e.error.name,message:e.error.message,stackTrace:e.error.stackTrace}:null}}function composeExecutionErrorString(e){let{name:t,message:n,stackTrace:r}=e,i=t&&n?`${t}: ${n}`:t||n;if(!r)return i;let a=r.split(`
23
23
  `,1)[0]??``;return/^\s+at\s+/.test(a)?`${i}\n${r}`:r}function formatExecutionErrorFallback(e){let[t=``,...n]=composeExecutionErrorString(e).split(`
24
- `);return[` ${h.error(t)}`,...n.map(e=>` ${h.dim(e)}`)].join(`
25
- `)}function deployedBundleDir(){return q.join(process.cwd(),`dist`)}function formatExecutionError(e,t){if(t&&e.stackTrace){let n=formatErrorWithSourcemap(composeExecutionErrorString(e),t,deployedBundleDir());if(n)return n}return formatExecutionErrorFallback(e)}const formatDate=e=>e?e.toISOString():`N/A`;function printFunctionExecutionSummary(e){let t=[[`id`,e.id],[`scriptName`,e.scriptName],[`status`,e.status],[`type`,e.type],[`startedAt`,formatDate(e.startedAt)],[`finishedAt`,formatDate(e.finishedAt)],[`errorKind`,e.errorKind]];f.out(Yn(t))}function printFunctionExecutionLogs(e){let t=zn(e.logEntries);if(t.length!==0){f.log(h.bold(`
26
- Logs:`));for(let e of t)f.log(` ${e}`)}}function printFunctionExecutionOutcome(e){let{detail:t,bundledCode:n}=e;if(t.result){f.log(h.bold(`
27
- Result:`));try{let e=JSON.parse(t.result);f.log(` ${JSON.stringify(e,null,2).split(`
24
+ `);return[` ${f.error(t)}`,...n.map(e=>` ${f.dim(e)}`)].join(`
25
+ `)}function deployedBundleDir(){return q.join(process.cwd(),`dist`)}function formatExecutionError(e,t){if(t&&e.stackTrace){let n=formatErrorWithSourcemap(composeExecutionErrorString(e),t,deployedBundleDir());if(n)return n}return formatExecutionErrorFallback(e)}const formatDate=e=>e?e.toISOString():`N/A`;function printFunctionExecutionSummary(e){let t=[[`id`,e.id],[`scriptName`,e.scriptName],[`status`,e.status],[`type`,e.type],[`startedAt`,formatDate(e.startedAt)],[`finishedAt`,formatDate(e.finishedAt)],[`errorKind`,e.errorKind]];m.out(Kt(t))}function printFunctionExecutionLogs(e){let t=Ht(e.logEntries);if(t.length!==0){m.log(f.bold(`
26
+ Logs:`));for(let e of t)m.log(` ${e}`)}}function printFunctionExecutionOutcome(e){let{detail:t,bundledCode:n}=e;if(t.result){m.log(f.bold(`
27
+ Result:`));try{let e=JSON.parse(t.result);m.log(` ${JSON.stringify(e,null,2).split(`
28
28
  `).join(`
29
- `)}`)}catch{f.log(` ${t.result}`)}}t.error&&(f.log(h.bold(`
30
- Error:`)),f.log(formatExecutionError(t.error,n??null)))}async function fetchFunctionExecution(e){let{execution:t}=await e.client.getFunctionExecution({workspaceId:e.workspaceId,executionId:e.executionId},{signal:e.signal});if(!t)throw W({code:`FUNCTION_EXECUTION_NOT_FOUND`,message:`Function execution '${e.executionId}' not found.`});return t}async function followFunctionExecution(e){let{interval:t,timeout:n,showProgress:r}=e,i=Date.now(),a=0,o,remainingMs=()=>n===void 0?void 0:n-(Date.now()-i),timedOut=()=>{let e=remainingMs();return e!==void 0&&e<=0},timeoutError=()=>{let t=o===void 0?`unknown`:cn(o);return W({code:`FUNCTION_EXECUTION_TIMEOUT`,message:`Timed out waiting for function execution '${e.executionId}' to complete. Last status: ${t}.`})},sleep=async()=>{let e=remainingMs();if(e===void 0)await Fi(t);else{if(e<=0)throw timeoutError();await Fi(Math.min(t,e))}};for(;;){let t=remainingMs();if(t!==void 0&&t<=0)throw timeoutError();let n;try{n=await fetchFunctionExecution({...e,signal:t===void 0?void 0:AbortSignal.timeout(t)})}catch(e){if(timedOut())throw timeoutError();if(!Gt(e))throw e;f.warn(`Retrying function execution poll: ${g(e)}`,{mode:`stream`}),await sleep();continue}if(r){if(o===void 0&&(printFunctionExecutionSummary(toFunctionExecutionListInfo(n)),Ot(n.status)||f.info(`Following log entries until the execution completes (Ctrl+C to stop)`,{mode:`stream`})),n.logEntries.length>a){a===0&&f.log(h.bold(`
31
- Logs:`));for(let e of n.logEntries.slice(a))f.log(` ${Tn(Hn(e))}`);a=n.logEntries.length}if(o!==void 0&&n.status!==o){let e=Kn(cn(n.status));f.info(`Status: ${e}`,{mode:`stream`})}}let i=o!==void 0;if(o=n.status,Ot(n.status))return{execution:n,printedEntries:a,followed:i};await sleep()}}async function downloadScriptForMapping(e){let{client:t,workspaceId:n,scriptName:r,executionType:i,executionContentHash:a}=e,o=scriptNameToRegistryName(r,i);if(o==null)return f.debug(`Script "${r}" is not a deployed registry script (e.g. function run or seed); skipping sourcemap mapping.`),null;if(a===``)return f.debug(`Function execution "${r}" has no contentHash; skipping sourcemap mapping because the exact bundle cannot be identified.`),null;let s=await downloadFunctionScript({client:t,workspaceId:n,name:o,contentHash:a});return s==null?(f.debug(`Could not download pinned script "${r}" (registry: "${o}", contentHash: "${a}") for stack trace mapping; showing raw stack trace.`),null):s.code}const Sa=C({name:`logs`,description:`List or get function execution logs.`,notes:"Each execution includes `errorKind`, which tells you where a failure came from: `USER_RUNTIME` (your code threw while running, or exceeded its time, memory, or CPU limit), `USER_NON_RUNTIME` (your script failed while loading, before your function was called, such as when its top-level code threw), `PLATFORM` (a failure on the Platform side, or the Platform aborting the run because of its own deadline or cancellation), `NONE` (no error), or `UNSPECIFIED` (not recorded, or a kind this CLI version does not recognize). A workflow job waiting on another job also reports `USER_NON_RUNTIME` when that job fails or is canceled. `errorName` and `errorMessage` hold the error's name and message, or `null` when none was recorded. The list table omits `errorMessage`; use `--json` or the execution details to read it.\n\nExecution details include `logEntries`, the structured log lines (message, severity, timestamp) recorded while the function ran. They are available while the execution is still running. The `logs` string joins their messages with newlines.\n\nUse `--follow` to keep polling a running execution and print new log entries as they arrive until it completes. Polling continues while the execution is suspended at a wait point, and indefinitely unless `--timeout` is set. With `--json`, `--follow` waits for completion and then emits the final execution details once.\n\nWhen viewing a specific execution that failed, the command displays error details with the stack trace mapped back to your original source files (clickable file links and code snippets, matching `function run` output).\n\nStack traces are mapped only when the execution includes a content hash for the exact build that ran. If the content hash is missing or the build is no longer available, the command falls back to a plain-text error display.",examples:[{cmd:``,desc:`List all function execution logs`},{cmd:`<execution-id>`,desc:`Get execution details with logs`},{cmd:`--json`,desc:`Output as JSON`},{cmd:`<execution-id> --json`,desc:`Get execution details as JSON`},{cmd:`<execution-id> --follow`,desc:`Stream log entries of a running execution until it completes`}],args:J.strictObject({...N,...Sn,"execution-id":G(J.string().optional(),{positional:!0,description:`Execution ID (if provided, shows details with logs)`}),follow:G(J.boolean().default(!1),{alias:`f`,description:`Keep polling a running execution and print new log entries as they arrive (detail mode only)`}),interval:G(pt.default(`3s`),{alias:`i`,description:`Polling interval for --follow (e.g., '3s', '500ms', '1m')`}),timeout:G(pt.optional(),{alias:`t`,description:`Maximum time to keep following (e.g., '30s', '10m'); unbounded by default`})}),run:async e=>{if(e.follow&&!e.executionId)throw W({code:`FUNCTION_LOGS_OPTIONS_INVALID`,message:`--follow requires an execution ID.`,command:`function logs`});let{client:t,workspaceId:n}=await j({profile:e.profile,workspaceId:e[`workspace-id`]});if(e.executionId){let r=f.jsonMode||e.json,i={client:t,workspaceId:n,executionId:e.executionId},{execution:a,printedEntries:o,followed:s}=e.follow?await followFunctionExecution({...i,interval:an(e.interval),timeout:e.timeout===void 0?void 0:an(e.timeout),showProgress:!r}):{execution:await fetchFunctionExecution(i),printedEntries:0,followed:!1},c=toFunctionExecutionDetailInfo(a);if(r){f.out(c);return}(!e.follow||s)&&printFunctionExecutionSummary(c),o===0&&printFunctionExecutionLogs(c),printFunctionExecutionOutcome({detail:c,bundledCode:c.error?await downloadScriptForMapping({client:t,workspaceId:n,scriptName:c.scriptName,executionType:a.type,executionContentHash:a.contentHash}):null})}else{let r=Nt(e.order),i=await Jt(e.limit,e=>Br(async(e,i)=>{let{executions:a,nextPageToken:o}=await t.listFunctionExecutions({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e})),a=i.items.map(toFunctionExecutionListInfo);if(a.length===0&&!e.json){f.info(`No function execution logs found.`);return}f.out(a,{display:{errorMessage:null}}),await F(i,e.limit)}}});async function bundleForRun(e){let{detected:t,sourceFile:n,baseDir:r,env:i={},machineUser:a,workspaceId:o,dateDefault:s=`legacy`}=e,c=Wr(e.inlineSourcemap),l=Dr(e.logLevel),u=q.resolve(Lr(),`test-run`);X.mkdirSync(u,{recursive:!0});let d=`test-run--${t.name}`,f=`${d}.js`,p=q.join(u,`${d}.entry.js`),m=generateEntry({detected:t,sourceFile:n,env:i,machineUser:a,workspaceId:o,defaultPermission:e.defaultPermission,dateDefault:s});X.writeFileSync(p,m);let h=await Cr(r),g=_r({tsconfig:h}),_=await Mi.build({plugins:[gr(p,r),br(),Yr(t.type===`resolver`?wr(t.fields,s):{date:!0,temporal:!0},s)],input:p,write:!1,output:{format:`esm`,sourcemap:!0,minify:!c||{mangle:{keepNames:!0}},codeSplitting:!1,dir:process.cwd()},tsconfig:h,treeshake:Er([Tr(l),vr(e.treeshake)]),...g.options});return g.assertAllResolved(),{bundledCode:yr({chunk:_.output[0],inlineSourcemap:c,dependencySources:e.inlineSourcemapDependencySources??!1}),scriptName:f}}function generateEntry(e){let{detected:t,sourceFile:n,env:r,machineUser:i,workspaceId:a,defaultPermission:o,dateDefault:c}=e,l=q.resolve(n);switch(t.type){case`plain`:return t.namedMain?H`
29
+ `)}`)}catch{m.log(` ${t.result}`)}}t.error&&(m.log(f.bold(`
30
+ Error:`)),m.log(formatExecutionError(t.error,n??null)))}async function fetchFunctionExecution(e){let{execution:t}=await e.client.getFunctionExecution({workspaceId:e.workspaceId,executionId:e.executionId},{signal:e.signal});if(!t)throw S({code:`FUNCTION_EXECUTION_NOT_FOUND`,message:`Function execution '${e.executionId}' not found.`});return t}async function followFunctionExecution(e){let{interval:t,timeout:n,showProgress:r}=e,i=Date.now(),a=0,o,remainingMs=()=>n===void 0?void 0:n-(Date.now()-i),timedOut=()=>{let e=remainingMs();return e!==void 0&&e<=0},timeoutError=()=>{let t=o===void 0?`unknown`:wn(o);return S({code:`FUNCTION_EXECUTION_TIMEOUT`,message:`Timed out waiting for function execution '${e.executionId}' to complete. Last status: ${t}.`})},sleep=async()=>{let e=remainingMs();if(e===void 0)await Ui(t);else{if(e<=0)throw timeoutError();await Ui(Math.min(t,e))}};for(;;){let t=remainingMs();if(t!==void 0&&t<=0)throw timeoutError();let n;try{n=await fetchFunctionExecution({...e,signal:t===void 0?void 0:AbortSignal.timeout(t)})}catch(e){if(timedOut())throw timeoutError();if(!Pt(e))throw e;m.warn(`Retrying function execution poll: ${pn(e)}`,{mode:`stream`}),await sleep();continue}if(r){if(o===void 0&&(printFunctionExecutionSummary(toFunctionExecutionListInfo(n)),cr(n.status)||m.info(`Following log entries until the execution completes (Ctrl+C to stop)`,{mode:`stream`})),n.logEntries.length>a){a===0&&m.log(f.bold(`
31
+ Logs:`));for(let e of n.logEntries.slice(a))m.log(` ${$n(nn(e))}`);a=n.logEntries.length}if(o!==void 0&&n.status!==o){let e=zn(wn(n.status));m.info(`Status: ${e}`,{mode:`stream`})}}let i=o!==void 0;if(o=n.status,cr(n.status))return{execution:n,printedEntries:a,followed:i};await sleep()}}async function downloadScriptForMapping(e){let{client:t,workspaceId:n,scriptName:r,executionType:i,executionContentHash:a}=e,o=scriptNameToRegistryName(r,i);if(o==null)return m.debug(`Script "${r}" is not a deployed registry script (e.g. function run or seed); skipping sourcemap mapping.`),null;if(a===``)return m.debug(`Function execution "${r}" has no contentHash; skipping sourcemap mapping because the exact bundle cannot be identified.`),null;let s=await downloadFunctionScript({client:t,workspaceId:n,name:o,contentHash:a});return s==null?(m.debug(`Could not download pinned script "${r}" (registry: "${o}", contentHash: "${a}") for stack trace mapping; showing raw stack trace.`),null):s.code}const Aa=E({name:`logs`,description:`List or get function execution logs.`,notes:"Each execution includes `errorKind`, which tells you where a failure came from: `USER_RUNTIME` (your code threw while running, or exceeded its time, memory, or CPU limit), `USER_NON_RUNTIME` (your script failed while loading, before your function was called, such as when its top-level code threw), `PLATFORM` (a failure on the Platform side, or the Platform aborting the run because of its own deadline or cancellation), `NONE` (no error), or `UNSPECIFIED` (not recorded, or a kind this CLI version does not recognize). A workflow job waiting on another job also reports `USER_NON_RUNTIME` when that job fails or is canceled. `errorName` and `errorMessage` hold the error's name and message, or `null` when none was recorded. The list table omits `errorMessage`; use `--json` or the execution details to read it.\n\nExecution details include `logEntries`, the structured log lines (message, severity, timestamp) recorded while the function ran. They are available while the execution is still running. The `logs` string joins their messages with newlines.\n\nUse `--follow` to keep polling a running execution and print new log entries as they arrive until it completes. Polling continues while the execution is suspended at a wait point, and indefinitely unless `--timeout` is set. With `--json`, `--follow` waits for completion and then emits the final execution details once.\n\nWhen viewing a specific execution that failed, the command displays error details with the stack trace mapped back to your original source files (clickable file links and code snippets, matching `function run` output).\n\nStack traces are mapped only when the execution includes a content hash for the exact build that ran. If the content hash is missing or the build is no longer available, the command falls back to a plain-text error display.",examples:[{cmd:``,desc:`List all function execution logs`},{cmd:`<execution-id>`,desc:`Get execution details with logs`},{cmd:`--json`,desc:`Output as JSON`},{cmd:`<execution-id> --json`,desc:`Get execution details as JSON`},{cmd:`<execution-id> --follow`,desc:`Stream log entries of a running execution until it completes`}],args:J.strictObject({...P,...Zn,"execution-id":G(J.string().optional(),{positional:!0,description:`Execution ID (if provided, shows details with logs)`}),follow:G(J.boolean().default(!1),{alias:`f`,description:`Keep polling a running execution and print new log entries as they arrive (detail mode only)`}),interval:G(tr.default(`3s`),{alias:`i`,description:`Polling interval for --follow (e.g., '3s', '500ms', '1m')`}),timeout:G(tr.optional(),{alias:`t`,description:`Maximum time to keep following (e.g., '30s', '10m'); unbounded by default`})}),run:async e=>{if(e.follow&&!e.executionId)throw S({code:`FUNCTION_LOGS_OPTIONS_INVALID`,message:`--follow requires an execution ID.`,command:`function logs`});let{client:t,workspaceId:n}=await j({profile:e.profile,workspaceId:e[`workspace-id`]});if(e.executionId){let r=m.jsonMode||e.json,i={client:t,workspaceId:n,executionId:e.executionId},{execution:a,printedEntries:o,followed:s}=e.follow?await followFunctionExecution({...i,interval:xn(e.interval),timeout:e.timeout===void 0?void 0:xn(e.timeout),showProgress:!r}):{execution:await fetchFunctionExecution(i),printedEntries:0,followed:!1},c=toFunctionExecutionDetailInfo(a);if(r){m.out(c);return}(!e.follow||s)&&printFunctionExecutionSummary(c),o===0&&printFunctionExecutionLogs(c),printFunctionExecutionOutcome({detail:c,bundledCode:c.error?await downloadScriptForMapping({client:t,workspaceId:n,scriptName:c.scriptName,executionType:a.type,executionContentHash:a.contentHash}):null})}else{let r=Vn(e.order),i=await Et(e.limit,e=>Rr(async(e,i)=>{let{executions:a,nextPageToken:o}=await t.listFunctionExecutions({workspaceId:n,pageToken:e,pageSize:i,pageDirection:r});return[a,o]},{limit:e})),a=i.items.map(toFunctionExecutionListInfo);if(a.length===0&&!e.json){m.info(`No function execution logs found.`);return}m.out(a,{display:{errorMessage:null}}),await R(i,e.limit)}}});async function bundleForRun(e){let{detected:t,sourceFile:n,baseDir:r,env:i={},machineUser:a,workspaceId:o,dateDefault:s=`legacy`}=e,c=Qr(e.inlineSourcemap),l=Xr(e.logLevel),u=q.resolve(Lr(),`test-run`);X.mkdirSync(u,{recursive:!0});let d=`test-run--${t.name}`,f=`${d}.js`,p=q.join(u,`${d}.entry.js`),m=generateEntry({detected:t,sourceFile:n,env:i,machineUser:a,workspaceId:o,defaultPermission:e.defaultPermission,dateDefault:s});X.writeFileSync(p,m);let h=await Er(r),g=kr({tsconfig:h}),_=await Vi.build({plugins:[Or(p,r),Ir(),Cr(t.type===`resolver`?Tr(t.fields,s):{date:!0,temporal:!0},s),ci()],input:p,write:!1,output:{format:`esm`,sourcemap:!0,minify:!c||{mangle:{keepNames:!0}},comments:Dr,codeSplitting:!1,dir:process.cwd()},tsconfig:h,treeshake:Pr([Ar(l),Fr(e.treeshake)]),...g.options});return g.assertAllResolved(),{bundledCode:jr({chunk:_.output[0],inlineSourcemap:c,dependencySources:e.inlineSourcemapDependencySources??!1,projectSources:e.inlineSourcemapProjectSources,sourcesDir:process.cwd()}),scriptName:f}}function generateEntry(e){let{detected:t,sourceFile:n,env:r,machineUser:i,workspaceId:a,defaultPermission:o,dateDefault:c}=e,l=q.resolve(n);switch(t.type){case`plain`:return t.namedMain?W`
32
32
  export { main } from "${l}";
33
- `:H`
33
+ `:W`
34
34
  import _fn from "${l}";
35
35
  export { _fn as main };
36
- `;case`resolver`:{let e=buildMachinePrincipalExpr(i,a),n=Jr({permission:t.permission,defaultPermission:o}),{importStatement:s,resultExpr:u}=mr(t.fields?.output,c);return H`
36
+ `;case`resolver`:{let e=buildMachinePrincipalExpr(i,a),n=Nr({permission:t.permission,defaultPermission:o}),{importStatement:s,resultExpr:u}=ii(t.fields?.output,c);return W`
37
37
  import _internalResolver from "${l}";
38
38
  import { t } from "@tailor-platform/sdk";
39
39
  ${s}
40
40
 
41
41
  const $tailor_resolver_body = async (rawInput) => {
42
42
  const _caller = ${e};
43
- const invoker = (${Ar}) ?? _caller;
43
+ const invoker = (${oi}) ?? _caller;
44
44
  const context = { input: rawInput, env: ${JSON.stringify(r)}, caller: _caller, invoker };
45
45
  const input = ${n};
46
46
  const result = await _internalResolver.body({ ...context, input });
@@ -48,58 +48,62 @@ Logs:`));for(let e of n.logEntries.slice(a))f.log(` ${Tn(Hn(e))}`);a=n.logEntri
48
48
  };
49
49
 
50
50
  export { $tailor_resolver_body as main };
51
- `}case`executor`:{let e=buildMachinePrincipalExpr(i,a);return H`
51
+ `}case`executor`:{let e=buildMachinePrincipalExpr(i,a);return W`
52
52
  import _internalExecutor from "${l}";
53
53
 
54
54
  const _env = ${JSON.stringify(r)};
55
55
  const _actor = ${e};
56
56
 
57
57
  const __executor_function = async (args) => {
58
- const _invoker = ${Ar} ?? _actor;
58
+ const _invoker = ${oi} ?? _actor;
59
59
  return _internalExecutor.operation.body({ ...args, env: _env, actor: _actor, invoker: _invoker });
60
60
  };
61
61
 
62
62
  export { __executor_function as main };
63
- `}case`workflow-job`:{let e=s(t.exportName,`workflow job export name missing`),n=buildMachinePrincipalExpr(i,a);return H`
63
+ `}case`workflow-job`:{let e=s(t.exportName,`workflow job export name missing`),n=buildMachinePrincipalExpr(i,a);return W`
64
64
  import { ${e} } from "${l}";
65
65
 
66
66
  const env = ${JSON.stringify(r)};
67
67
  const fallbackInvoker = ${n};
68
68
 
69
69
  export async function main(input) {
70
- const invoker = ${Ar} ?? fallbackInvoker;
70
+ const invoker = ${oi} ?? fallbackInvoker;
71
71
  return await ${e}.body(input, { env, invoker });
72
72
  }
73
- `}}}function buildMachinePrincipalExpr(e,t){return JSON.stringify({id:e.id,type:`machine_user`,workspaceId:t,attributes:e.attributes??{},attributeList:e.attributeList})}async function detectFunctionType(t){let{filePath:n,jobName:r}=t,i=await import(Ei(n).href),a=qr.safeParse(i.default);if(a.success){let t=i.default.input,n;if(t){let r=t;n={parse:t=>e({...t,fields:r})}}return{type:`resolver`,name:a.data.name,hasInput:t!=null,inputSchema:n,permission:a.data.permission,fields:{input:a.data.input,output:a.data.output}}}let o=u.safeParse(d(i.default));if(o.success){let{operation:e}=o.data;if(e.kind===`function`||e.kind===`jobFunction`)return{type:`executor`,name:o.data.name}}let s=detectWorkflowJob(i,r);if(s)return s;if(typeof i.default==`function`)return{type:`plain`,name:deriveNameFromPath(n)};if(typeof i.main==`function`)return{type:`plain`,name:deriveNameFromPath(n),namedMain:!0};throw W({code:`FUNCTION_TYPE_UNDETECTED`,message:`Could not detect function type from ${n}.`,details:`The file must have one of:
73
+ `}}}function buildMachinePrincipalExpr(e,t){return JSON.stringify({id:e.id,type:`machine_user`,workspaceId:t,attributes:e.attributes??{},attributeList:e.attributeList})}async function detectFunctionType(t){let{filePath:n,jobName:r}=t,i=await import(Pi(n).href),a=si.safeParse(i.default);if(a.success){let t=i.default.input,n;if(t){let r=t;n={parse:t=>e({...t,fields:r})}}return{type:`resolver`,name:a.data.name,hasInput:t!=null,inputSchema:n,permission:a.data.permission,fields:{input:a.data.input,output:a.data.output}}}let o=l.safeParse(d(i.default));if(o.success){let{operation:e}=o.data;if(e.kind===`function`||e.kind===`jobFunction`)return{type:`executor`,name:o.data.name}}let s=detectWorkflowJob(i,r);if(s)return s;if(typeof i.default==`function`)return{type:`plain`,name:deriveNameFromPath(n)};if(typeof i.main==`function`)return{type:`plain`,name:deriveNameFromPath(n),namedMain:!0};throw S({code:`FUNCTION_TYPE_UNDETECTED`,message:`Could not detect function type from ${n}.`,details:`The file must have one of:
74
74
  - A default-exported resolver (createResolver)
75
75
  - A default-exported executor (createExecutor) with function/jobFunction operation
76
76
  - A named-exported workflow job (createWorkflowJob)
77
77
  - A default-exported function
78
- - A named-exported "main" function`})}function detectWorkflowJob(e,t){let n=[];for(let[t,r]of Object.entries(e)){if(t==="default")continue;let e=Hr.safeParse(r);e.success&&n.push({name:e.data.name,exportName:t})}if(n.length===0)return null;if(t){let e=n.find(e=>e.name===t);if(!e){let e=n.map(e=>` - "${e.name}" (export: ${e.exportName})`).join(`
79
- `);throw W({code:`WORKFLOW_JOB_NOT_FOUND`,message:`Workflow job "${t}" not found.`,details:`Available jobs:\n${e}`})}return{type:`workflow-job`,name:e.name,exportName:e.exportName}}if(n.length===1){let[e]=n,t=s(e,`workflow job missing`);return{type:`workflow-job`,name:t.name,exportName:t.exportName}}let r=n.map(e=>` - "${e.name}" (export: ${e.exportName})`).join(`
80
- `);throw W({code:`WORKFLOW_JOB_AMBIGUOUS`,message:`Multiple workflow jobs found.`,details:`Available jobs:\n${r}`,suggestion:`Specify one with --name.`})}function deriveNameFromPath(e){return q.basename(e,q.extname(e))}const Ca=`db.ts`,wa=`db.snapshot.json`,Ta=[`/**`,` * Auto-generated Kysely types for one-off scripts in this directory.`," * Generated by `tailor function script` from the selected TailorDB schema.",` *`," * DO NOT EDIT - Re-run `tailor function script` to refresh.",` */`].join(`
81
- `);function generateScriptDbTypes(e,t=!1){let n=Object.values(e.tables).map(e=>ui(e.name,e.fields,t)),r=di([{namespace:e.namespace,types:n}],t);return`${Ta}\n\n${r}`}function isGeneratedScriptDbTypes(e){return e.includes("Generated by `tailor function script`")}function assertGeneratedTypeScript(e,t){let{errors:n}=Ni(q.basename(e),t);if(n.length>0)throw Zr(`Generated ${e} does not parse as TypeScript: ${n.map(e=>e.message).join(`; `)}`)}function generateScriptSkeleton(e){let{getDBImportPath:t,namespace:n}=e;return[`/**`,` * One-off script. Run it on the platform without deploying:`,` *`,` * tailor function run <this file>`,` *`,` * For large tables, batch updates by primary-key range instead of one`,` * statement over the whole table; see the "Performance and Large Tables"`,` * section in @tailor-platform/sdk's docs/services/tailordb/migration.md.`,` */`,``,`import { getDB } from ${JSON.stringify(t)};`,``,`export default async function main() {`,` const db = getDB(${JSON.stringify(n)});`,``,` // A transaction rolls every change back when any statement fails.`,` await db.transaction().execute(async (trx) => {`,` // e.g. await trx.updateTable("MyTable").set({ ... }).where("id", "=", "...").execute();`,` });`,`}`,``].join(`
82
- `)}function loadScriptSchemaSnapshot(e){let t=q.join(q.dirname(e),wa);if(!X.existsSync(t))return null;let n;try{n=JSON.parse(X.readFileSync(t,`utf-8`))}catch(e){throw W({code:`SCRIPT_SNAPSHOT_INVALID`,message:`Failed to parse schema snapshot ${t}: ${e instanceof Error?e.message:e}.`,suggestion:"Re-run `tailor function script` to regenerate it.",cause:e})}let r=n;if(typeof r!=`object`||!r||typeof r.namespace!=`string`||typeof r.tables!=`object`||r.tables===null)throw unexpectedSnapshotShapeError(t);let i=r.source??`remote`;if(i!==`local`&&i!==`remote`)throw unexpectedSnapshotShapeError(t);let a={...r};delete a.source;try{return{snapshotPath:t,source:i,snapshot:Ut(a)}}catch{throw unexpectedSnapshotShapeError(t)}}function unexpectedSnapshotShapeError(e){return W({code:`SCRIPT_SNAPSHOT_INVALID`,message:`Schema snapshot ${e} has an unexpected shape.`,suggestion:"Re-run `tailor function script` to regenerate it."})}async function verifyScriptSchemaSnapshot(e){let{client:t,workspaceId:n,config:r,configArgValue:i,sidecar:a}=e,{snapshot:o}=a,s=o.namespace;if(er(r).includes(s)){let{namespaces:t}=await pe({configPath:i,namespaces:[s]}),n=t[0];if(n){let t=Object.fromEntries(Object.values(n.tables).map(e=>[e.name,ie(e)])),r=He(generatedContractSnapshot(o),generatedContractSnapshot({...o,tables:t}));if(Et(r))throw schemaDriftError(`the local table definitions`,r,e)}}let c=await We(t,n,s),l=He(a.source===`local`?generatedContractSnapshot(o):Ut(pickTableFields(o)),a.source===`local`?generatedContractSnapshot(c):Ut(pickTableFields(c)));if(Et(l))throw schemaDriftError(`the deployed schema`,l,e)}function fieldsOnlySnapshot(e){return Ut(pickTableFields(rr(e)))}function generatedContractSnapshot(e){let t=fieldsOnlySnapshot(e),n=Object.fromEntries(Object.entries(t.tables).map(([t,n])=>{let r=e.tables[t],i=Object.fromEntries(Object.entries(n.fields).map(([e,t])=>[e,preserveGeneratedContract(t,r?.fields[e])]));return[t,{...n,fields:i}]}));return Ut({...t,tables:n})}function preserveGeneratedContract(e,t){let n=e.fields?Object.fromEntries(Object.entries(e.fields).map(([e,n])=>[e,preserveGeneratedContract(n,t?.fields?.[e])])):void 0,r=t?.hooks?.create!==void 0||t?.default!==void 0||t?.optionalOnCreate===!0;return{...e,...n===void 0?{}:{fields:n},...r?{optionalOnCreate:!0}:{}}}function pickTableFields(e){let t=Object.fromEntries(Object.entries(e.tables).map(([e,t])=>[e,{name:t.name,pluralForm:t.pluralForm,fields:t.fields}]));return{...e,tables:t}}function schemaDriftError(e,t,n){let r=[...n.configArgValue===`tailor.config.ts`?[]:[`--config=${n.configArgValue}`],`--workspace-id=${n.workspaceId}`,...n.profileArgValue===void 0?[]:[`--profile=${n.profileArgValue}`]],i=U({command:`tailor`,args:[`function`,`script`,n.scriptArgValue,...n.sidecar.source===`remote`?[`--remote`]:[],...r]}),a=U({command:`tailor`,args:[`function`,`run`,n.scriptArgValue,`--allow-schema-drift`,...r]});return W({code:`SCRIPT_SCHEMA_DRIFT`,message:`Schema drift detected: ${wa} next to the script no longer matches ${e}.`,details:on(t),suggestion:`Refresh the generated types with ${i}, or run anyway with ${a}.`})}const Ea=C({name:`run`,aliases:[`test-run`],description:`Run a function on the Tailor Platform server without deploying.`,args:J.object({...N,file:G(J.string(),{positional:!0,description:`Path to the function file`}),name:G(J.string().optional(),{alias:`n`,description:"Workflow job name to run (matches the `name` field of createWorkflowJob)"}),arg:G(J.string().optional(),{alias:`a`,description:`JSON argument to pass to the function`}),"machine-user":G(J.string().optional(),{alias:`m`,description:`Machine user name for authentication. Falls back to the active profile's default machine user.`,env:`TAILOR_PLATFORM_MACHINE_USER_NAME`}),config:G(J.string().default(`tailor.config.ts`),{alias:`c`,description:`Path to SDK config file`}),"allow-schema-drift":G(J.boolean().default(!1),{description:`Run a scaffolded script even when its schema snapshot no longer matches`})}),notes:"You can pass either a source file (`.ts`) or a pre-bundled file (`.js`).\nWhen a `.js` file is provided, detection and bundling are skipped and the file is executed as-is.\n\nA script scaffolded by `function script` with a generated `db.ts` is checked against its `db.snapshot.json` before execution and refused on schema drift; pass `--allow-schema-drift` to run it anyway. The check compares table and field structure; hook and validator code changes are not detected.\n\n`test-run` is a deprecated alias of this command and will be removed in v3.\n\n> [!WARNING]\n> Workflow job `.start()` calls do not work in this mode.\n> Started jobs are not executed; only the target job's `body` function runs in isolation.",examples:[{cmd:`resolvers/add.ts --arg '{"a":1,"b":2}'`,desc:`Run a resolver with input arguments`},{cmd:`workflows/sample.ts --name validate-order`,desc:`Run a specific workflow job by name`},{cmd:`build/resolvers/add.js --arg '{"a":1,"b":2}'`,desc:`Run a pre-bundled .js file directly`}],run:async e=>{invokedViaTestRunAlias(process.argv)&&f.warn("`tailor function test-run` is deprecated and will be removed in v3. Use `tailor function run` instead.");let t=f.jsonMode,n=q.resolve(e.file);if(!X.existsSync(n))throw W({code:`FILE_NOT_FOUND`,message:`File not found: ${n}`});let{config:r}=await B(e.config),a=resolveAuthNamespace(r.auth),o=await resolveMachineUserName({cliMachineUser:e[`machine-user`],cliMachineUserSource:Bn(e[`machine-user`]),profile:e.profile,authConfig:r.auth}),{client:s,workspaceId:c}=await j({profile:e.profile,workspaceId:e[`workspace-id`]}),l=await resolveMachineUser({client:s,workspaceId:c,authNamespace:a,machineUserName:o,authConfig:r.auth}),u=q.relative(process.cwd(),n),d=n.endsWith(`.js`);if(!d){if(e[`allow-schema-drift`])X.existsSync(q.join(q.dirname(n),`db.snapshot.json`))&&f.warn(`Skipping the schema snapshot check (--allow-schema-drift).`);else{let t=loadScriptSchemaSnapshot(n);t&&(f.info(`Checking the script's schema snapshot for drift...`),await verifyScriptSchemaSnapshot({client:s,workspaceId:c,config:r,configArgValue:e.config,scriptArgValue:e.file,profileArgValue:e.profile,sidecar:t}))}}let p,m,g,_;if(d)m=q.basename(n),p=X.readFileSync(n,`utf-8`),f.info(`Using pre-bundled script ${h.bold(m)}`);else{f.info(`Detecting function type from ${h.path(u)}`);let t=await detectFunctionType({filePath:n,jobName:e.name});g=t.type,_=t.name,f.info(`Detected: ${h.bold(t.type)} ${h.info(`"${t.name}"`)}`),t.type===`resolver`&&e.arg&&!t.hasInput&&(f.warn(`--arg is ignored because this resolver has no input schema. Define "input" in your resolver to use --arg.`),e.arg=void 0),f.info(`Bundling...`);let i=zr(r),a=q.dirname(r.path);({bundledCode:p,scriptName:m}=await bundleForRun({detected:t,sourceFile:n,baseDir:a,defaultPermission:t.type===`resolver`?kr({config:r.resolver,filePath:n,baseDir:a}):void 0,env:r.env??{},inlineSourcemap:i.inlineSourcemap,inlineSourcemapDependencySources:i.inlineSourcemapDependencySources,logLevel:i.logLevel,treeshake:i.treeshake,dateDefault:Mr(r),machineUser:l,workspaceId:c})),f.info(`Bundled as ${h.bold(m)}`)}let v=xi(i,{namespace:a,machineUserName:l.name});f.info(`Executing on workspace ${h.dim(c)}...`);let y;if(e.arg!==void 0)try{y=JSON.parse(e.arg)}catch(e){throw W({code:`FUNCTION_ARG_INVALID`,message:`Invalid --arg JSON: ${e instanceof Error?e.message:e}`,command:`function run`,cause:e})}let b=await Se({client:s,workspaceId:c,name:m,code:p,arg:y,invoker:v});if(t)f.out({success:b.success,scriptName:m,functionType:g,functionName:_,logs:b.logs,result:b.result,error:b.error});else{if(b.success?f.success(`Execution succeeded`):f.error(`Execution failed`),b.logs.trim()){f.log(h.bold(`
78
+ - A named-exported "main" function`})}function detectWorkflowJob(e,t){let n=[];for(let[t,r]of Object.entries(e)){if(t==="default")continue;let e=Gr.safeParse(r);e.success&&n.push({name:e.data.name,exportName:t})}if(n.length===0)return null;if(t){let e=n.find(e=>e.name===t);if(!e){let e=n.map(e=>` - "${e.name}" (export: ${e.exportName})`).join(`
79
+ `);throw S({code:`WORKFLOW_JOB_NOT_FOUND`,message:`Workflow job "${t}" not found.`,details:`Available jobs:\n${e}`})}return{type:`workflow-job`,name:e.name,exportName:e.exportName}}if(n.length===1){let[e]=n,t=s(e,`workflow job missing`);return{type:`workflow-job`,name:t.name,exportName:t.exportName}}let r=n.map(e=>` - "${e.name}" (export: ${e.exportName})`).join(`
80
+ `);throw S({code:`WORKFLOW_JOB_AMBIGUOUS`,message:`Multiple workflow jobs found.`,details:`Available jobs:\n${r}`,suggestion:`Specify one with --name.`})}function deriveNameFromPath(e){return q.basename(e,q.extname(e))}const ja=`db.ts`,Ma=`db.snapshot.json`;function generateScriptDbTypes(e,t=!1){let n=Object.values(e.tables).map(e=>vi(e.name,e.fields,t));return`/**
81
+ * Auto-generated Kysely types for one-off scripts in this directory.
82
+ * Generated by \`tailor function script\` from the selected TailorDB schema.
83
+ *
84
+ * DO NOT EDIT - Re-run \`tailor function script\` to refresh.
85
+ */\n\n${yi([{namespace:e.namespace,types:n}],t)}`}function isGeneratedScriptDbTypes(e){return e.includes("Generated by `tailor function script`")}function assertGeneratedTypeScript(e,t){let{errors:n}=Hi(q.basename(e),t);if(n.length>0)throw g(`Generated ${e} does not parse as TypeScript: ${n.map(e=>e.message).join(`; `)}`)}function generateScriptSkeleton(e){let{getDBImportPath:t,namespace:n}=e;return[`/**`,` * One-off script. Run it on the platform without deploying:`,` *`,` * tailor function run <this file>`,` *`,` * For large tables, batch updates by primary-key range instead of one`,` * statement over the whole table; see the "Performance and Large Tables"`,` * section in @tailor-platform/sdk's docs/services/tailordb/migration.md.`,` */`,``,`import { getDB } from ${JSON.stringify(t)};`,``,`export default async function main() {`,` const db = getDB(${JSON.stringify(n)});`,``,` // A transaction rolls every change back when any statement fails.`,` await db.transaction().execute(async (trx) => {`,` // e.g. await trx.updateTable("MyTable").set({ ... }).where("id", "=", "...").execute();`,` });`,`}`,``].join(`
86
+ `)}function loadScriptSchemaSnapshot(e){let t=q.join(q.dirname(e),Ma);if(!X.existsSync(t))return null;let n;try{n=JSON.parse(X.readFileSync(t,`utf-8`))}catch(e){throw S({code:`SCRIPT_SNAPSHOT_INVALID`,message:`Failed to parse schema snapshot ${t}: ${e instanceof Error?e.message:e}.`,suggestion:"Re-run `tailor function script` to regenerate it.",cause:e})}let r=n;if(typeof r!=`object`||!r||typeof r.namespace!=`string`||typeof r.tables!=`object`||r.tables===null)throw unexpectedSnapshotShapeError(t);let i=r.source??`remote`;if(i!==`local`&&i!==`remote`)throw unexpectedSnapshotShapeError(t);let a={...r};delete a.source;try{return{snapshotPath:t,source:i,snapshot:Mt(a)}}catch{throw unexpectedSnapshotShapeError(t)}}function unexpectedSnapshotShapeError(e){return S({code:`SCRIPT_SNAPSHOT_INVALID`,message:`Schema snapshot ${e} has an unexpected shape.`,suggestion:"Re-run `tailor function script` to regenerate it."})}async function verifyScriptSchemaSnapshot(e){let{client:t,workspaceId:n,config:r,configArgValue:i,sidecar:a}=e,{snapshot:o}=a,s=o.namespace;if(fr(r).includes(s)){let{namespaces:t}=await ve({configPath:i,namespaces:[s]}),n=t[0];if(n){let t=Object.fromEntries(Object.values(n.tables).map(e=>[e.name,Be(e)])),r=Jn(generatedContractSnapshot(o),generatedContractSnapshot({...o,tables:t}));if(or(r))throw schemaDriftError(`the local table definitions`,r,e)}}let c=await Sr(t,n,s),l=Jn(a.source===`local`?generatedContractSnapshot(o):Mt(pickTableFields(o)),a.source===`local`?generatedContractSnapshot(c):Mt(pickTableFields(c)));if(or(l))throw schemaDriftError(`the deployed schema`,l,e)}function fieldsOnlySnapshot(e){return Mt(pickTableFields(bn(e)))}function generatedContractSnapshot(e){let t=fieldsOnlySnapshot(e),n=Object.fromEntries(Object.entries(t.tables).map(([t,n])=>{let r=e.tables[t],i=Object.fromEntries(Object.entries(n.fields).map(([e,t])=>[e,preserveGeneratedContract(t,r?.fields[e])]));return[t,{...n,fields:i}]}));return Mt({...t,tables:n})}function preserveGeneratedContract(e,t){let n=e.fields?Object.fromEntries(Object.entries(e.fields).map(([e,n])=>[e,preserveGeneratedContract(n,t?.fields?.[e])])):void 0,r=t?.hooks?.create!==void 0||t?.default!==void 0||t?.optionalOnCreate===!0;return{...e,...n===void 0?{}:{fields:n},...r?{optionalOnCreate:!0}:{}}}function pickTableFields(e){let t=Object.fromEntries(Object.entries(e.tables).map(([e,t])=>[e,{name:t.name,pluralForm:t.pluralForm,fields:t.fields}]));return{...e,tables:t}}function schemaDriftError(e,t,n){let r=[...n.configArgValue===`tailor.config.ts`?[]:[`--config=${n.configArgValue}`],`--workspace-id=${n.workspaceId}`,...n.profileArgValue===void 0?[]:[`--profile=${n.profileArgValue}`]],i=b({command:`tailor`,args:[`function`,`script`,n.scriptArgValue,...n.sidecar.source===`remote`?[`--remote`]:[],...r]}),a=b({command:`tailor`,args:[`function`,`run`,n.scriptArgValue,`--allow-schema-drift`,...r]});return S({code:`SCRIPT_SCHEMA_DRIFT`,message:`Schema drift detected: ${Ma} next to the script no longer matches ${e}.`,details:Sn(t),suggestion:`Refresh the generated types with ${i}, or run anyway with ${a}.`})}const Na=E({name:`run`,aliases:[`test-run`],description:`Run a function on the Tailor Platform server without deploying.`,args:J.object({...P,file:G(J.string(),{positional:!0,description:`Path to the function file`}),name:G(J.string().optional(),{alias:`n`,description:"Workflow job name to run (matches the `name` field of createWorkflowJob)"}),arg:G(J.string().optional(),{alias:`a`,description:`JSON argument to pass to the function`}),"machine-user":G(J.string().optional(),{alias:`m`,description:`Machine user name for authentication. Falls back to the active profile's default machine user.`,env:`TAILOR_PLATFORM_MACHINE_USER_NAME`}),config:G(J.string().default(`tailor.config.ts`),{alias:`c`,description:`Path to SDK config file`}),"allow-schema-drift":G(J.boolean().default(!1),{description:`Run a scaffolded script even when its schema snapshot no longer matches`})}),notes:"You can pass either a source file (`.ts`) or a pre-bundled file (`.js`).\nWhen a `.js` file is provided, detection and bundling are skipped and the file is executed as-is.\n\nA script scaffolded by `function script` with a generated `db.ts` is checked against its `db.snapshot.json` before execution and refused on schema drift; pass `--allow-schema-drift` to run it anyway. The check compares table and field structure; hook and validator code changes are not detected.\n\n`test-run` is a deprecated alias of this command and will be removed in v3.\n\n> [!WARNING]\n> Workflow job `.start()` calls do not work in this mode.\n> Started jobs are not executed; only the target job's `body` function runs in isolation.",examples:[{cmd:`resolvers/add.ts --arg '{"a":1,"b":2}'`,desc:`Run a resolver with input arguments`},{cmd:`workflows/sample.ts --name validate-order`,desc:`Run a specific workflow job by name`},{cmd:`build/resolvers/add.js --arg '{"a":1,"b":2}'`,desc:`Run a pre-bundled .js file directly`}],run:async e=>{invokedViaTestRunAlias(process.argv)&&m.warn("`tailor function test-run` is deprecated and will be removed in v3. Use `tailor function run` instead.");let t=m.jsonMode,n=q.resolve(e.file);if(!X.existsSync(n))throw S({code:`FILE_NOT_FOUND`,message:`File not found: ${n}`});let{config:r}=await z(e.config),a=resolveAuthNamespace(r.auth),o=await resolveMachineUserName({cliMachineUser:e[`machine-user`],cliMachineUserSource:en(e[`machine-user`]),profile:e.profile,authConfig:r.auth}),{client:s,workspaceId:c}=await j({profile:e.profile,workspaceId:e[`workspace-id`]}),l=await resolveMachineUser({client:s,workspaceId:c,authNamespace:a,machineUserName:o,authConfig:r.auth}),u=q.relative(process.cwd(),n),d=n.endsWith(`.js`);if(!d){if(e[`allow-schema-drift`])X.existsSync(q.join(q.dirname(n),`db.snapshot.json`))&&m.warn(`Skipping the schema snapshot check (--allow-schema-drift).`);else{let t=loadScriptSchemaSnapshot(n);t&&(m.info(`Checking the script's schema snapshot for drift...`),await verifyScriptSchemaSnapshot({client:s,workspaceId:c,config:r,configArgValue:e.config,scriptArgValue:e.file,profileArgValue:e.profile,sidecar:t}))}}let p,h,g,_;if(d)h=q.basename(n),p=X.readFileSync(n,`utf-8`),m.info(`Using pre-bundled script ${f.bold(h)}`);else{m.info(`Detecting function type from ${f.path(u)}`);let t=await detectFunctionType({filePath:n,jobName:e.name});g=t.type,_=t.name,m.info(`Detected: ${f.bold(t.type)} ${f.info(`"${t.name}"`)}`),t.type===`resolver`&&e.arg&&!t.hasInput&&(m.warn(`--arg is ignored because this resolver has no input schema. Define "input" in your resolver to use --arg.`),e.arg=void 0),m.info(`Bundling...`);let i=Ur(r),a=q.dirname(r.path);({bundledCode:p,scriptName:h}=await bundleForRun({detected:t,sourceFile:n,baseDir:a,defaultPermission:t.type===`resolver`?ri({config:r.resolver,filePath:n,baseDir:a}):void 0,env:r.env??{},inlineSourcemap:i.inlineSourcemap,inlineSourcemapDependencySources:i.inlineSourcemapDependencySources,inlineSourcemapProjectSources:ti({buildOptions:i,baseDir:a}),logLevel:i.logLevel,treeshake:i.treeshake,dateDefault:zr(r),machineUser:l,workspaceId:c})),m.info(`Bundled as ${f.bold(h)}`)}let v=ki(i,{namespace:a,machineUserName:l.name});m.info(`Executing on workspace ${f.dim(c)}...`);let y;if(e.arg!==void 0)try{y=JSON.parse(e.arg)}catch(e){throw S({code:`FUNCTION_ARG_INVALID`,message:`Invalid --arg JSON: ${e instanceof Error?e.message:e}`,command:`function run`,cause:e})}let b=await St({client:s,workspaceId:c,name:h,code:p,arg:y,invoker:v});if(t)m.out({success:b.success,scriptName:h,functionType:g,functionName:_,logs:b.logs,result:b.result,error:b.error});else{if(b.success?m.success(`Execution succeeded`):m.error(`Execution failed`),b.logs.trim()){m.log(f.bold(`
83
87
  Logs:`));for(let e of b.logs.split(`
84
- `))f.log(` ${e}`)}if(b.result&&b.success){f.log(h.bold(`
85
- Result:`));try{let e=JSON.parse(b.result);f.log(` ${JSON.stringify(e,null,2).split(`
88
+ `))m.log(` ${e}`)}if(b.result&&b.success){m.log(f.bold(`
89
+ Result:`));try{let e=JSON.parse(b.result);m.log(` ${JSON.stringify(e,null,2).split(`
86
90
  `).join(`
87
- `)}`)}catch{f.log(` ${b.result}`)}}if(b.error&&!b.success){f.log(h.bold(`
88
- Error:`));let e=formatErrorWithSourcemap(b.error,p,process.cwd());e?f.log(e):f.log(` ${h.error(b.error)}`)}}b.success||process.exit(1)}}),Da=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(`=`)&&Da.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 Fe({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 Oa=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,Ca),a=q.join(n,wa);if(t===i)throw W({code:`SCRIPT_PATH_INVALID`,message:`${Ca} 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}" (${wa}).`,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)+`
89
- `),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 ka=K({name:`function`,description:`Manage functions`,subCommands:{get:sr,list:lr,logs:Sa,run:Ea,script:Oa},defaultSubCommand:`list`}),Aa=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},ja=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}})}}),Ma=8085,Na=`http://localhost:${Ma}/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(`
90
- `)}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||Ir(t)}const startAuthServer=async(e={})=>{let t=Kr(e.platformConfig),n=randomState(),r=await Di(),i=await t.authorizationCode.getAuthorizeUri({redirectUri:Na,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:Na,state:n,codeVerifier:r});le({accessToken:u.accessToken,refreshToken:u.refreshToken??void 0});let d=await Rr(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),sendCallbackSuccess(l,`Authentication successful`),a({user:d.sub,email:d.email})}catch(e){sendCallbackFailure(l,401,`Authentication failed`,e),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(Ma,()=>void openBrowser())})};async function loginAsMachineUser(e){let t=e.clientSecret??await P.password({message:`Client secret`}),n=await Ur(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 Pa=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=Ne(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 Or()}}}),Fa=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?Ne(r):void 0,a=r?r.user:n.current_user,o=Ir(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:Sr}),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=Kr(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})}}),Ia=K({name:`machineuser`,description:`Manage machine users in your Tailor Platform application.`,subCommands:{list:Zt,token:Vt},defaultSubCommand:`list`}),La=K({name:`oauth2client`,description:`Manage OAuth2 clients in your Tailor Platform application.`,subCommands:{list:jn,get:Lt},defaultSubCommand:`list`}),Ra=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}`)}}),za=K({name:`folder`,description:`Manage organization folders.`,subCommands:{create:ln,delete:En,get:Kt,list:ze,update:ft}}),Ba=K({name:`organization`,description:`Manage Tailor Platform organizations.`,subCommands:{folder:za,get:be,list:Ce,tree:ue,update:me},defaultSubCommand:`list`}),Va=/* @__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(`.`),Ha={seed:`@tailor-platform/sdk-plugin-seed`,setup:`@tailor-platform/sdk-plugin-setup`,"tailordb-erd":`@tailor-platform/sdk-plugin-tailordb-erd`},Ua=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(Ua).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=Nr(a),n.TAILOR_PLATFORM_OAUTH2_CLIENT_ID=Vr(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=Ha[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 Wa=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(Va),r=listPlugins(t);if(r.length===0){f.info(H`
91
+ `)}`)}catch{m.log(` ${b.result}`)}}if(b.error&&!b.success){m.log(f.bold(`
92
+ Error:`));let e=formatErrorWithSourcemap(b.error,p,process.cwd());e?m.log(e):m.log(` ${f.error(b.error)}`)}}b.success||process.exit(1)}}),Pa=new Set(xi(J.strictObject(vt)).fields.filter(e=>e.type!==`boolean`).flatMap(e=>[e.cliName,...e.alias??[]].flatMap(toFlagTokens)));function toFlagTokens(e){return e.length===1?[`-${e}`]:[`--${e}`,`--${Ci(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(`=`)&&Pa.has(r)&&n++:t.push(r)}return t[0]===`function`&&t[1]===`test-run`}function resolveAuthNamespace(e){if(e?.name)return e.name;throw S({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 Ve({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 S({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{m.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 Fa=E({name:`script`,description:"Scaffold a one-off script to run with `function run`.",args:J.object({...P,...Ct,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 S({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,ja),a=q.join(n,Ma);if(t===i)throw S({code:`SCRIPT_PATH_INVALID`,message:`${ja} is reserved for the generated Kysely types written next to the script. Choose a different script file name.`,command:`function script`});let{config:o,plugins:c}=await z(e.config),l=c.find(e=>e.id===bi),u=X.existsSync(a);if(e.remote&&l!==void 0&&r&&!u)throw S({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 h=resolveNamespace({config:o,explicit:e.namespace,sidecarNamespace:p,remote:e.remote});if(p!==void 0&&p!==h)throw S({code:`SCRIPT_NAMESPACE_MISMATCH`,message:`This directory's generated types target namespace "${p}" (${Ma}).`,suggestion:`Scaffold scripts for namespace "${h}" 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,m.info(`Fetching deployed schema of namespace ${f.bold(h)}...`),t=await Sr(n,r,h)}else{m.info(`Loading local definitions of namespace ${f.bold(h)}...`);let{namespaces:n}=await ve({configPath:e.config,namespaces:[h]}),r=s(n[0],`namespace ${h}`);t=gn(r.tables,h)}if(Object.keys(t.tables).length===0){let t=e.remote?`deployed tables in workspace ${s(v,`workspace ID`)}`:`locally defined tables`;throw S({code:`SCRIPT_SCHEMA_NOT_FOUND`,message:`Namespace "${h}" has no ${t}.`})}if(X.existsSync(i)&&!isGeneratedScriptDbTypes(X.readFileSync(i,`utf-8`)))throw S({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,Pe(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)+`
93
+ `),g.push(a),_=`./db`}else{if(r)throw S({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)||m.warn(`Generated Kysely types not found at ${f.path(q.relative(process.cwd(),e))}. Run \`tailor generate\` before executing the script.`)}if(!r){let e=generateScriptSkeleton({getDBImportPath:_,namespace:h});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 x=v??e[`workspace-id`];if(x!==void 0&&y.push(`--workspace-id=${x}`),e.profile!==void 0&&y.push(`--profile=${e.profile}`),m.jsonMode)m.out({script:t,created:g,namespace:h,usesGeneratedDbTypes:d});else{r&&m.info(`Script already exists; refreshed generated types only.`);for(let e of g)m.success(`Created ${f.path(q.relative(process.cwd(),e))}`);m.info(`Next: edit the script, then run ${b({command:`tailor`,args:y})}`)}}});function resolveNamespace(e){let{config:t,explicit:n,sidecarNamespace:r,remote:i}=e,a=kt(t),o=fr(t),s=i?a:o;if(n){if(!i&&!o.includes(n))throw S({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 S({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?S({code:`TAILORDB_NAMESPACE_REQUIRED`,message:`Multiple TailorDB namespaces are defined (${s.join(`, `)}). Specify one with --namespace.`,command:`function script`}):!i&&a.length>0?S({code:`TAILORDB_NAMESPACE_NOT_CONFIGURED`,message:`No owned TailorDB namespace is defined in the config. External namespaces require --remote: ${a.join(`, `)}.`}):S({code:`TAILORDB_NAMESPACE_NOT_CONFIGURED`,message:`No TailorDB namespace is defined in the config.`})}function resolveKyselyTypesPath(e){let t=Pe(e,`@tailor-platform/kysely-type`)?.distPath??`./generated/tailordb.ts`;if(t.length===0)throw S({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 Ia=K({name:`function`,description:`Manage functions`,subCommands:{get:_r,list:br,logs:Aa,run:Na,script:Fa},defaultSubCommand:`list`}),La=E({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 kn({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},Ra=E({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 li(),n=t.version&&t.version!==`0.0.0`?t.version:`latest`,r=detectPackageManager();r||=(m.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]:[]];m.log(`Running: ${r} ${i.join(` `)}`);let a=Gi(r,i,{stdio:`inherit`}),o={command:r,args:i};if(a.error)throw S({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 S({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}})}}),za=8085,Ba=`http://localhost:${za}/callback`;function randomState(){return Ii.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(`
94
+ `)}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 S({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||Hr(t)}const startAuthServer=async(e={})=>{let t=Yr(e.platformConfig),n=randomState(),r=await Fi(),i=await t.authorizationCode.getAuthorizeUri({redirectUri:Ba,state:n,codeVerifier:r}).catch(e=>{throw S({code:`LOGIN_AUTHORIZATION_URL_FAILED`,message:`Failed to prepare the login authorization URL: ${y(e).message}`,cause:e})});return new Promise((a,o)=>{let handleCallback=async(i,l)=>{try{if(!i.url?.startsWith(`/callback`))throw S({code:`LOGIN_CALLBACK_INVALID`,message:`Invalid callback URL`});let o=`http://${i.headers.host}${i.url}`,c=new URL(o).searchParams.get(`code`);c&&m.registerSecret(c);let u=await t.authorizationCode.getTokenFromCodeRedirect(o,{redirectUri:Ba,state:n,codeVerifier:r});te({accessToken:u.accessToken,refreshToken:u.refreshToken??void 0});let d=await $r(u.accessToken,e.platformConfig),f=await U();await he(f,d.sub,{accessToken:u.accessToken,refreshToken:u.refreshToken??void 0},new Date(s(u.expiresAt,`token response missing expiresAt`)).toISOString(),{platformConfig:e.platformConfig,email:d.email});let p=getProfileUserMismatch(e,d.email,d.sub);if(p)throw I(f),profileUserMismatchError(p);(e.updateCurrentUser??!0)&&(f.current_user=d.sub),await dt(f,d.email,d.sub,e.platformConfig),I(f),sendCallbackSuccess(l,`Authentication successful`),a({user:d.sub,email:d.email})}catch(e){sendCallbackFailure(l,401,`Authentication failed`,e),o(y(e))}finally{c.close()}},c=zi.createServer((e,t)=>void handleCallback(e,t)),l=setTimeout(()=>{c.close(),o(S({code:`LOGIN_TIMEOUT`,message:`Login timeout exceeded`}))},3e5);c.on(`close`,()=>{clearTimeout(l)}),c.on(`error`,e=>{o(e)});let openBrowser=async()=>{m.info(`Opening browser for login:\n\n${i}\n`);try{await Bi(i)}catch{m.warn(`Failed to open browser automatically. Please open the URL above manually.`)}};c.listen(za,()=>void openBrowser())})};async function loginAsMachineUser(e){let t=e.clientSecret??await H.password({message:`Client secret`}),n=await Jr(e.clientId,t,e.platformConfig),r=await U();await he(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 I(r),profileUserMismatchError(i);return(e.updateCurrentUser??!0)&&(r.current_user=e.clientId),I(r),{user:e.clientId,email:null}}const Va=E({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 U()).profiles[e.profile];if(!r)throw S({code:`PROFILE_NOT_FOUND`,message:`Profile "${e.profile}" not found`});t=Ie(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`}),m.success(`Successfully logged in to Tailor Platform.`),V({changed:!0,...i})}finally{await Vr()}}}),Ha=E({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=>{await je(()=>logout(e.profile||process.env.TAILOR_PLATFORM_PROFILE))}});async function logout(e){let t=await U(),n=e?t.profiles[e]:void 0;if(e&&!n)throw S({code:`PROFILE_NOT_FOUND`,message:`Profile "${e}" not found`});let r=n?Ie(n):void 0,i=n?n.user:t.current_user,a=Hr(r),o=e?{allowLegacyUserKey:!0}:void 0;if(!i){m.info(`You are not logged in.`),V({changed:!1,user:null,revoked:!1});return}let hasDefaultUserToken=()=>He(t,i,{platformUrl:ei}),shouldClearCurrentUser=()=>t.current_user===i&&(a||!oe(t,i))&&!hasDefaultUserToken(),s,c=!1;try{s=await fe(t,i,r,o)}catch(e){c=!0,m.warn(`Failed to revoke token: ${e instanceof Error?e.message:e}`)}if(!s&&!c){m.info(`You are not logged in.`);let e=shouldClearCurrentUser();e&&(t.current_user=null),I(t),V({changed:e,user:i,revoked:!1});return}let l=!1;if(s)try{let e=Yr(r),t=s.refreshToken?`refresh_token`:`access_token`;await e.revoke({accessToken:s.accessToken,refreshToken:s.refreshToken??null,expiresAt:Date.parse(s.userEntry.token_expires_at)},t),l=!0}catch(e){m.warn(`Failed to revoke token: ${e instanceof Error?e.message:e}`)}await rt(t,i,r,o),shouldClearCurrentUser()&&(t.current_user=null),I(t),m.success(`Successfully logged out from Tailor Platform.`),V({changed:!0,user:i,revoked:l})}const Ua=K({name:`machineuser`,description:`Manage machine users in your Tailor Platform application.`,subCommands:{list:rn,token:Jt},defaultSubCommand:`list`}),Wa=K({name:`oauth2client`,description:`Manage OAuth2 clients in your Tailor Platform application.`,subCommands:{list:Bn,get:Ut},defaultSubCommand:`list`}),Ga=E({name:`open`,description:`Open Tailor Platform Console.`,args:J.strictObject({...M}),run:async e=>{let t=await we({workspaceId:e[`workspace-id`],profile:e.profile}),{config:n}=await z(e.config),r=n.name,i=`/workspaces/${t}/services/applications/${encodeURIComponent(r)}`,a=await ze({profile:e.profile,...e[`workspace-id`]===void 0?{}:{allowMissingProfile:!0}}),o=new URL(i,a).toString(),s=m.jsonMode;m.info(`Opening Tailor Platform Console...`);let c=!0;try{await Bi(o)}catch{c=!1}s?m.out({consoleUrl:o,workspaceId:t,applicationName:r,opened:c}):c?(m.out(`Console URL: ${o}`),m.out(`Workspace ID: ${t}`),m.out(`Application Name: ${r}`)):m.warn(`Failed to open browser automatically. Please open this URL manually:\n${o}`)}}),Ka=K({name:`folder`,description:`Manage organization folders.`,subCommands:{create:mn,delete:Fn,get:Qt,list:qe,update:_t}}),qa=K({name:`organization`,description:`Manage Tailor Platform organizations.`,subCommands:{folder:Ka,get:Ee,list:Ae,tree:me,update:ye},defaultSubCommand:`list`}),Ja=/* @__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(`.`),Ya={seed:`@tailor-platform/sdk-plugin-seed`,setup:`@tailor-platform/sdk-plugin-setup`,"tailordb-erd":`@tailor-platform/sdk-plugin-tailordb-erd`},Xa=process.platform===`win32`?`;`:`:`;function*ancestorDirs(e){let t=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{Ai(e,process.platform===`win32`?ji.F_OK:ji.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(Xa).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=Mi(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 U(),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 li();e&&(n.TAILOR_VERSION=e)}catch{}let i=hn();if(i&&(n.TAILOR_CONFIG_PATH=i),e.skipPlatformContext)return n;let a;try{a=await Ge({profile:t,allowMissingProfile:!0})}catch{}n.TAILOR_PLATFORM_URL=Br(a),n.TAILOR_PLATFORM_OAUTH2_CLIENT_ID=Wr(a);try{n.TAILOR_PLATFORM_WORKSPACE_ID=await we({profile:t})}catch{}try{let e=await resolveActiveUser(t);e&&(n.TAILOR_PLATFORM_USER=e)}catch{}try{let e=await yn({profile:t});e&&(n.TAILOR_PLATFORM_TOKEN=e)}catch{}return n}function signalToExitCode(e){let t=Ri.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=Wi(a,o,{stdio:`inherit`,env:i,shell:s});r.on(`error`,r=>{m.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=Ya[pluginSlug(e.commandPath,e.name)];if(!n)return;let r=[e.cliName,...e.commandPath??[],e.name].join(` `);return m.error(`"${r}" is provided by the ${n} CLI plugin, which is not installed.`),m.info(`Install it with: npm install -D ${n}`),1}const Za=E({name:`list`,description:"List discovered plugins (executables named `<cli>-<name>` on PATH or node_modules/.bin).",args:J.strictObject({}),run:async()=>{let e=await li(),t=Object.keys(e.bin??{})[0]||`tailor`,n=new Set(Ja),r=listPlugins(t);if(r.length===0){m.info(W`
91
95
  No plugins found.
92
96
  Install an executable named "${t}-<name>" on your PATH or in node_modules/.bin,
93
97
  then run it with "${t} <name>".
94
- `),f.jsonMode&&f.out([]);return}let i=r.map(e=>({name:e.name,source:e.source,path:e.path,shadowed:n.has(e.name)}));f.out(i);for(let e of i)e.shadowed&&f.warn(`Plugin "${t}-${e.name}" is shadowed by the builtin "${t} ${e.name}" command and will not be dispatched.`)}}),Ga=K({name:`plugin`,description:`Manage and inspect CLI plugins (beta).`,subCommands:{list:Wa},defaultSubCommand:`list`}),Ka=C({name:`create`,description:`Create a new profile.`,args:J.strictObject({name:G(J.string(),{positional:!0,description:`Profile name`}),user:G(J.string(),{alias:`u`,description:`User email address or machine user client ID`}),"workspace-id":G(J.string(),{alias:`w`,description:`Workspace ID`}),permission:G(J.enum([`write`,`read`]).default(`write`),{description:`Profile permission. 'read' blocks all write commands while the profile is active.`}),"machine-user":G(J.string().optional(),{alias:`m`,description:`Default machine user name for application-data commands (query, workflow start, function run, machineuser token).`}),"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.`}),"platform-url":G(J.url().optional(),{description:`Platform API base URL for this profile.`,env:`TAILOR_PLATFORM_URL`}),"oauth2-client-id":G(J.string().optional(),{description:`OAuth2 client ID for logging in to this profile's platform.`,env:`TAILOR_PLATFORM_OAUTH2_CLIENT_ID`}),"console-url":G(J.url().optional(),{description:`Console base URL for this profile.`,env:`TAILOR_PLATFORM_CONSOLE_URL`})}),run:async e=>{if(e[`machine-user-override`]===`deny`&&!e[`machine-user`])throw W({code:`PROFILE_OPTIONS_INVALID`,message:`--machine-user-override deny requires --machine-user.`,command:`profile create`});let t=await T();if(t.profiles[e.name])throw W({code:`PROFILE_EXISTS`,message:`Profile "${e.name}" already exists.`});let n={...e[`platform-url`]?{platformUrl:e[`platform-url`]}:{},...e[`oauth2-client-id`]?{oauth2ClientId:e[`oauth2-client-id`]}:{},...e[`console-url`]?{consoleUrl:e[`console-url`]}:{}},r=Object.keys(n).length>0?n:void 0,{accessToken:i,user:a}=await ar(t,e.user,r),o=await Pr(i,r);if(!(await pr(async(e,t)=>{let{workspaces:n,nextPageToken:r}=await o.listWorkspaces({pageToken:e,pageSize:t});return[n,r]})).find(t=>t.id===e[`workspace-id`]))throw W({code:`WORKSPACE_NOT_FOUND`,message:`Workspace "${e[`workspace-id`]}" not found.`});t.profiles[e.name]={user:a,workspace_id:e[`workspace-id`],...e.permission===`read`?{readonly:!0}:{},...e[`machine-user`]?{machine_user:e[`machine-user`]}:{},...e[`machine-user-override`]===`deny`?{machine_user_override:`deny`}:{},...e[`platform-url`]?{platform_url:e[`platform-url`]}:{},...e[`oauth2-client-id`]?{oauth2_client_id:e[`oauth2-client-id`]}:{},...e[`console-url`]?{console_url:e[`console-url`]}:{}},E(t),e.json||f.success(`Profile "${e.name}" created successfully.`);let s={name:e.name,user:a,workspaceId:e[`workspace-id`],permission:e.permission,...e[`machine-user`]?{machineUser:e[`machine-user`],machineUserOverride:e[`machine-user-override`]??`allow`}:{},...e[`platform-url`]?{platformUrl:e[`platform-url`]}:{},...e[`oauth2-client-id`]?{oauth2ClientId:e[`oauth2-client-id`]}:{},...e[`console-url`]?{consoleUrl:e[`console-url`]}:{}};f.out(s)}}),qa=C({name:`delete`,description:`Delete a profile.`,args:J.strictObject({name:G(J.string(),{positional:!0,description:`Profile name`})}),run:async e=>{let t=await T();if(!t.profiles[e.name])throw W({code:`PROFILE_NOT_FOUND`,message:`Profile "${e.name}" not found.`});delete t.profiles[e.name],E(t),f.success(`Profile "${e.name}" deleted successfully.`),A({changed:!0,name:e.name})}}),Ja=C({name:`list`,description:`List all profiles.`,args:J.strictObject({}),run:async()=>{let e=await T(),t=f.jsonMode,n=Object.entries(e.profiles);if(n.length===0){f.info(H`
98
+ `),m.jsonMode&&m.out([]);return}let i=r.map(e=>({name:e.name,source:e.source,path:e.path,shadowed:n.has(e.name)}));m.out(i);for(let e of i)e.shadowed&&m.warn(`Plugin "${t}-${e.name}" is shadowed by the builtin "${t} ${e.name}" command and will not be dispatched.`)}}),Qa=K({name:`plugin`,description:`Manage and inspect CLI plugins (beta).`,subCommands:{list:Za},defaultSubCommand:`list`});function assertProfileAvailable(e,t){if(e.profiles[t])throw S({code:`PROFILE_EXISTS`,message:`Profile "${t}" already exists.`})}const $a=E({name:`create`,description:`Create a new profile.`,args:J.strictObject({name:G(J.string(),{positional:!0,description:`Profile name`}),user:G(J.string(),{alias:`u`,description:`User email address or machine user client ID`}),"workspace-id":G(J.string(),{alias:`w`,description:`Workspace ID`}),permission:G(J.enum([`write`,`read`]).default(`write`),{description:`Profile permission. 'read' blocks all write commands while the profile is active.`}),"machine-user":G(J.string().optional(),{alias:`m`,description:`Default machine user name for application-data commands (query, workflow start, function run, machineuser token).`}),"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.`}),"platform-url":G(J.url().optional(),{description:`Platform API base URL for this profile.`,env:`TAILOR_PLATFORM_URL`}),"oauth2-client-id":G(J.string().optional(),{description:`OAuth2 client ID for logging in to this profile's platform.`,env:`TAILOR_PLATFORM_OAUTH2_CLIENT_ID`}),"console-url":G(J.url().optional(),{description:`Console base URL for this profile.`,env:`TAILOR_PLATFORM_CONSOLE_URL`})}),run:async e=>{if(e[`machine-user-override`]===`deny`&&!e[`machine-user`])throw S({code:`PROFILE_OPTIONS_INVALID`,message:`--machine-user-override deny requires --machine-user.`,command:`profile create`});let t=await U();assertProfileAvailable(t,e.name);let n={...e[`platform-url`]?{platformUrl:e[`platform-url`]}:{},...e[`oauth2-client-id`]?{oauth2ClientId:e[`oauth2-client-id`]}:{},...e[`console-url`]?{consoleUrl:e[`console-url`]}:{}},r=Object.keys(n).length>0?n:void 0,{accessToken:i,user:a}=await le(t,e.user,r);assertProfileAvailable(t,e.name);let o=await Kr(i,r);if(!(await qr(async(e,t)=>{let{workspaces:n,nextPageToken:r}=await o.listWorkspaces({pageToken:e,pageSize:t});return[n,r]})).find(t=>t.id===e[`workspace-id`]))throw S({code:`WORKSPACE_NOT_FOUND`,message:`Workspace "${e[`workspace-id`]}" not found.`});t.profiles[e.name]={user:a,workspace_id:e[`workspace-id`],...e.permission===`read`?{readonly:!0}:{},...e[`machine-user`]?{machine_user:e[`machine-user`]}:{},...e[`machine-user-override`]===`deny`?{machine_user_override:`deny`}:{},...e[`platform-url`]?{platform_url:e[`platform-url`]}:{},...e[`oauth2-client-id`]?{oauth2_client_id:e[`oauth2-client-id`]}:{},...e[`console-url`]?{console_url:e[`console-url`]}:{}},I(t),e.json||m.success(`Profile "${e.name}" created successfully.`);let s={name:e.name,user:a,workspaceId:e[`workspace-id`],permission:e.permission,...e[`machine-user`]?{machineUser:e[`machine-user`],machineUserOverride:e[`machine-user-override`]??`allow`}:{},...e[`platform-url`]?{platformUrl:e[`platform-url`]}:{},...e[`oauth2-client-id`]?{oauth2ClientId:e[`oauth2-client-id`]}:{},...e[`console-url`]?{consoleUrl:e[`console-url`]}:{}};m.out(s)}}),eo=E({name:`delete`,description:`Delete a profile.`,args:J.strictObject({name:G(J.string(),{positional:!0,description:`Profile name`})}),run:async e=>{let t=await U();if(!t.profiles[e.name])throw S({code:`PROFILE_NOT_FOUND`,message:`Profile "${e.name}" not found.`});delete t.profiles[e.name],I(t),m.success(`Profile "${e.name}" deleted successfully.`),V({changed:!0,name:e.name})}}),to=E({name:`list`,description:`List all profiles.`,args:J.strictObject({}),run:async()=>{let e=await U(),t=m.jsonMode,n=Object.entries(e.profiles);if(n.length===0){m.info(W`
95
99
  No profiles found.
96
100
  Please create a profile first using 'tailor profile create' command.
97
- `),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)}}),Ya=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`]===``?Ne(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 Pr(n.accessToken,h);if(!(await pr(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(_)}}),Xa=K({name:`profile`,description:`Manage workspace profiles (user + workspace combinations).`,subCommands:{create:Ka,delete:qa,list:Ja,update:Ya},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 Za={"vault-name":G(J.string(),{alias:`V`,description:`Vault name`})},Qa={...Za,name:G(J.string(),{alias:`n`,description:`Secret name`})},$a={...Qa,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 eo=C({name:`create`,description:`Create a secret in a vault.`,args:J.strictObject({...N,...$a,...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})}}),to=C({name:`delete`,description:`Delete a secret in a vault.`,args:J.strictObject({...N,...Qa,...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 Br(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 no=C({name:`list`,description:`List all secrets in a vault.`,args:J.strictObject({...N,...Za,...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}}}),ro=C({name:`update`,description:`Update a secret in a vault.`,args:J.strictObject({...N,...$a,...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})}}),io={name:G(J.string(),{positional:{named:!0},description:`Vault name`})},ao=C({name:`create`,description:`Create a new Secret Manager vault.`,args:J.strictObject({...N,...io}),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})}}),oo=C({name:`delete`,description:`Delete a Secret Manager vault.`,args:J.strictObject({...N,...io,...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 Br(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 so=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)}}),co=K({name:`vault`,description:`Manage Secret Manager vaults.`,subCommands:{create:ao,delete:oo,list:so},defaultSubCommand:`list`}),lo=K({name:`secret`,description:`Manage Secret Manager vaults and secrets.`,subCommands:{vault:co,create:eo,update:ro,list:no,delete:to},defaultSubCommand:`vault`}),uo={[t.UNSPECIFIED]:`unspecified`,[t.PENDING]:`pending`,[t.VERIFYING]:`verifying`,[t.CERT_ISSUED]:`cert_issued`,[t.ACTIVE]:`active`,[t.FAILED]:`failed`,[t.REMOVING]:`removing`},fo=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:uo[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}}}),po=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:uo[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}}}),mo=K({name:`domain`,description:`Manage custom domains for static websites.`,subCommands:{list:po,get:fo}}),ho=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(`
98
- `)};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 Br(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 go=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)}}),_o=K({name:`staticwebsite`,description:`Manage static websites in your workspace.`,subCommands:{deploy:Le,domain:mo,list:go,get:ho},defaultSubCommand:`list`}),vo=new Set(Object.values(je));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=>vo.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){Oe(`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]})}.`;w(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-Bet1K5C4.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(w(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 yo=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 Fr(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 pr(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-Bet1K5C4.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){Oe(`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);w(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 bo=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){Oe(`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;w(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 xo=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){Oe(`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;w(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 So=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){Oe(`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 Co=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){Oe(`tailordb migration`);let t=await runMigrationTest(e);e.json?f.out(t):f.success(`Pending migrations completed in workspace ${t.workspaceName??t.workspaceId}.`)}const wo=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(`
99
- `);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-Bet1K5C4.mjs`),c=s({config:t,pluginManager:o});for(let e of c.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();hr({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{w(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){Oe(`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 To=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})}}),Eo=K({name:`migration`,description:`Manage TailorDB schema migrations.`,subCommands:{generate:Ie,rebaseline:yo,resolve:xo,script:ce,set:So,status:Co,sync:bo,test:wo,validate:To}}),Do=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:Me,migration:Eo}}),Oo=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)})}}),ko=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?Ne(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,Ne(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 Ao=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`
101
+ `),t&&m.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}:{}}});m.out(r)}}),no=E({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 U(),n=t.profiles[e.name];if(!n)throw S({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 S({code:`PROFILE_UPDATE_EMPTY`,message:`Please provide at least one property to update.`,command:`profile update`});let r=n.user,i=e.user||r,a=n.workspace_id,o=e[`workspace-id`]||a,s=i,c=e[`machine-user`]===``?void 0:e[`machine-user`]??n.machine_user,l=e[`machine-user-override`]===`allow`?void 0:e[`machine-user-override`]??n.machine_user_override,u=e[`platform-url`]===``?void 0:e[`platform-url`]??n.platform_url,d=e[`oauth2-client-id`]===``?void 0:e[`oauth2-client-id`]??n.oauth2_client_id,f=e[`console-url`]===``?void 0:e[`console-url`]??n.console_url,p={...u?{platformUrl:u}:{},...d?{oauth2ClientId:d}:{},...f?{consoleUrl:f}:{}},h=Object.keys(p).length>0?p:void 0,g=e[`platform-url`]===``?Ie(n):h;if((e[`machine-user`]!==void 0||e[`machine-user-override`]!==void 0)&&l===`deny`&&!c)throw e[`machine-user-override`]===`deny`?S({code:`PROFILE_OPTIONS_INVALID`,message:`--machine-user-override deny requires --machine-user.`,command:`profile update`}):S({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 r=await le(t,i,g,e.name);if(t.profiles[e.name]!==n)throw S({code:`PROFILE_NOT_FOUND`,message:`Profile "${e.name}" not found.`});s=r.user;let a=await Kr(r.accessToken,h);if(!(await qr(async(e,t)=>{let{workspaces:n,nextPageToken:r}=await a.listWorkspaces({pageToken:e,pageSize:t});return[n,r]})).find(e=>e.id===o))throw S({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`]),I(t),e.json||m.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}:{}};m.out(_)}}),ro=K({name:`profile`,description:`Manage workspace profiles (user + workspace combinations).`,subCommands:{create:$a,delete:eo,list:to,update:no},defaultSubCommand:`list`});async function resolveSecretValue(e,t,n){if(e.value!==void 0)return e.value;let missing=e=>S({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=()=>S({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 S({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 io={"vault-name":G(J.string(),{alias:`V`,description:`Vault name`})},ao={...io,name:G(J.string(),{alias:`n`,description:`Secret name`})},oo={...ao,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=N(n,`vault`,r),a={isManaged:!1,trn:i,existingLabels:{}},o,s;try{let{metadata:e}=await t.getMetadata({trn:i});s=e?.labels??{},o=s[En]}catch{return a}return o?(m.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 on(t,{trn:n,remove:[En,un,Hn]}),m.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 so=E({name:`create`,description:`Create a secret in a vault.`,args:J.strictObject({...P,...oo,...k}),notes:secretValueNotes(`create`),run:async e=>{let t=await resolveSecretValue(e,process.stdin,`secret create`);m.registerSecret(t),await T({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 H.confirm({message:`Do you want to proceed?`,default:!1}))throw S({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 S({code:`VAULT_NOT_FOUND`,message:`Vault "${e[`vault-name`]}" not found.`,cause:t});if(t.code===Z.AlreadyExists)throw S({code:`SECRET_EXISTS`,message:`Secret "${e.name}" already exists.`,cause:t})}throw t}i.isManaged&&await releaseVaultOwnership({client:n,...i}),m.success(`Secret: ${e.name} created in vault: ${e[`vault-name`]}`),V({changed:!0,workspaceId:r,vaultName:e[`vault-name`],name:e.name,vaultOwnershipReleased:i.isManaged})}}),co=E({name:`delete`,description:`Delete a secret in a vault.`,args:J.strictObject({...P,...ao,...k}),run:async e=>{await T({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 H.text({message:`Enter the secret name to confirm deletion ("${e.name}"):`})!==e.name)throw S({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?S({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}),m.success(`Secret: ${e.name} deleted from vault: ${e[`vault-name`]}`),V({changed:!0,workspaceId:n,vaultName:e[`vault-name`],name:e.name,vaultOwnershipReleased:r.isManaged})}});function secretInfo(e){return{name:e.name,createdAt:e.createTime?Ni(e.createTime):null,updatedAt:e.updateTime?Ni(e.updateTime):null}}async function secretList(e){let{client:t,workspaceId:n}=await j({profile:e.profile,workspaceId:e.workspaceId}),r=Vn(e.order);return(await Rr(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 lo=E({name:`list`,description:`List all secrets in a vault.`,args:J.strictObject({...P,...io,...zt()}),run:async e=>{try{let t=await Et(e.limit,t=>secretList({workspaceId:e[`workspace-id`],profile:e.profile,vaultName:e[`vault-name`],order:e.order,limit:t})),n=t.items;m.out(n),await R(t,e.limit)}catch(t){throw t instanceof Q&&t.code===Z.NotFound?S({code:`VAULT_NOT_FOUND`,message:`Vault "${e[`vault-name`]}" not found.`,cause:t}):t}}}),uo=E({name:`update`,description:`Update a secret in a vault.`,args:J.strictObject({...P,...oo,...k}),notes:secretValueNotes(`update`),run:async e=>{let t=await resolveSecretValue(e,process.stdin,`secret update`);m.registerSecret(t),await T({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 H.confirm({message:`Do you want to proceed?`,default:!1}))throw S({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?S({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}),m.success(`Secret: ${e.name} updated in vault: ${e[`vault-name`]}`),V({changed:!0,workspaceId:r,vaultName:e[`vault-name`],name:e.name,vaultOwnershipReleased:i.isManaged})}}),fo={name:G(J.string(),{positional:{named:!0},description:`Vault name`})},po=E({name:`create`,description:`Create a new Secret Manager vault.`,args:J.strictObject({...P,...fo}),run:async e=>{await T({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?S({code:`VAULT_EXISTS`,message:`Vault "${e.name}" already exists.`,cause:t}):t}m.success(`Vault: ${e.name} created`),V({changed:!0,workspaceId:n,name:e.name})}}),mo=E({name:`delete`,description:`Delete a Secret Manager vault.`,args:J.strictObject({...P,...fo,...k}),run:async e=>{await T({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 H.text({message:`Enter the vault name to confirm deletion ("${e.name}"):`})!==e.name)throw S({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?S({code:`VAULT_NOT_FOUND`,message:`Vault "${e.name}" not found.`,cause:t}):t}r.isManaged&&m.info(`Remove this vault from defineSecretManager() in your config to prevent the next apply from re-creating it.`),m.success(`Vault: ${e.name} deleted`),V({changed:!0,workspaceId:n,name:e.name,managed:r.isManaged})}});function vaultInfo(e){return{name:e.name,createdAt:e.createTime?Ni(e.createTime):null,updatedAt:e.updateTime?Ni(e.updateTime):null}}async function vaultList(e){let{client:t,workspaceId:n}=await j({profile:e?.profile,workspaceId:e?.workspaceId}),r=Vn(e?.order);return(await Rr(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 ho=E({name:`list`,description:`List all Secret Manager vaults in the workspace.`,args:J.strictObject({...P,...zt()}),run:async e=>{let t=await Et(e.limit,t=>vaultList({workspaceId:e[`workspace-id`],profile:e.profile,order:e.order,limit:t})),n=t.items;m.out(n),await R(t,e.limit)}}),go=K({name:`vault`,description:`Manage Secret Manager vaults.`,subCommands:{create:po,delete:mo,list:ho},defaultSubCommand:`list`}),_o=K({name:`secret`,description:`Manage Secret Manager vaults and secrets.`,subCommands:{vault:go,create:so,update:uo,list:lo,delete:co},defaultSubCommand:`vault`}),vo={[t.UNSPECIFIED]:`unspecified`,[t.PENDING]:`pending`,[t.VERIFYING]:`verifying`,[t.CERT_ISSUED]:`cert_issued`,[t.ACTIVE]:`active`,[t.FAILED]:`failed`,[t.REMOVING]:`removing`},yo=E({name:`get`,description:`Get details of a custom domain.`,args:J.strictObject({...P,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 S({code:`STATIC_WEBSITE_DOMAIN_NOT_FOUND`,message:r});let a={domain:i.domain,status:vo[i.status]??`unknown`,trafficCnameTarget:i.trafficCnameTarget,certificateCnameTarget:i.certificateCnameTarget,errorMessage:i.errorMessage||void 0};m.out(a)}catch(e){throw e instanceof Q&&e.code===Z.NotFound?S({code:`STATIC_WEBSITE_DOMAIN_NOT_FOUND`,message:r,cause:e}):e}}}),bo=E({name:`list`,description:`List custom domains for a static website.`,args:J.strictObject({...P,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){m.info(`No custom domains found.`),m.jsonMode&&m.out([]);return}let i=r.map(e=>({domain:e.domain,status:vo[e.status]??`unknown`,trafficCnameTarget:e.trafficCnameTarget,certificateCnameTarget:e.certificateCnameTarget}));m.out(i)}catch(t){throw t instanceof Q&&t.code===Z.NotFound?S({code:`STATIC_WEBSITE_NOT_FOUND`,message:`Static website "${e.name}" not found.`,cause:t}):t}}}),xo=K({name:`domain`,description:`Manage custom domains for static websites.`,subCommands:{list:bo,get:yo}}),So=E({name:`get`,description:`Get details of a specific static website.`,args:J.strictObject({...P,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 S({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(`
102
+ `)};m.out(a)}catch(e){throw e instanceof Q&&e.code===Z.NotFound?S({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=Vn(e?.order);return(await Rr(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 Co=E({name:`list`,description:`List all static websites in a workspace.`,args:J.strictObject({...P,...zt()}),run:async e=>{let t=m.jsonMode,n=await Et(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}});m.out(i),await R(n,e.limit)}}),wo=K({name:`staticwebsite`,description:`Manage static websites in your workspace.`,subCommands:{deploy:pe,domain:xo,list:Co,get:So},defaultSubCommand:`list`}),To=new Set(Object.values(Se));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()||!ct.test(e.name))continue;let t=q.join(s,e.name);(await $.readdir(t)).some(e=>To.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 Ce(e,s,0);Ye(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){m.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){Fe(`tailordb migration`);let{config:t,plugins:n}=await z(e.configPath),r=q.dirname(t.path),i=ue(B(t,r),e.namespace),a=`First run ${b({command:`tailor`,args:[`tailordb`,`migration`,`generate`,`--config`,t.path]})}.`;D(i.migrationsDir,i.namespace);let o=O(i.migrationsDir);if(!o)throw S({code:`MIGRATION_HISTORY_NOT_FOUND`,message:`No migration history found for namespace "${i.namespace}".`,suggestion:a});let s=Ne(i.migrationsDir),l=O(i.migrationsDir,0)?.rebaseline?.historyId??null,u=Ue([i])[i.namespace],d=n.length>0?new _i(n):void 0,{defineApplication:p}=await import(`../application-Bj2MtL-d.mjs`),h=p({config:t,pluginManager:d});for(let e of h.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();let g=h.tailorDBServices.find(e=>e.namespace===i.namespace);if(!g)throw S({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${i.namespace}"`});let assertLocalTypesReady=()=>{let e=gn(g.types,i.namespace),t=Mn(o,e.tables,i.namespace);if(or(t))throw m.error(`Migration history does not reproduce the current local schema for namespace ${f.bold(i.namespace)}:`),m.log(Sn(t)),S({code:`MIGRATION_HISTORY_MISMATCH`,message:`Refusing to re-baseline: the migration history must reproduce the current local schema.`,suggestion:a})},localSourceFiles=()=>[t.path,...c(g.config,r)];assertLocalTypesReady();let _=se(localSourceFiles()),{client:v,workspaceId:y}=await j({profile:e.profile,workspaceId:e.workspaceId}),x=[`--config`,t.path,...L({workspaceId:y,profile:e.profile})],C=`Run ${b({command:`tailor`,args:[`tailordb`,`migration`,`set`,`0`,`--namespace`,i.namespace,...x]})}`,ee=`after resolving the connection error, deploy with schema checks enabled by running ${b({command:`tailor`,args:[`deploy`,...x]})}.`,assertConnectedWorkspaceReady=async(e,n)=>{let r=await A(v,N(y,`tailordb`,i.namespace));gr(r,i.namespace);let a=r.number;if(a!==s){let e=a===null?`<unset>`:F(a);throw S({code:`REBASELINE_CHECKPOINT_BEHIND`,message:`The connected workspace must be at the latest migration ${F(s)} before re-baselining; current checkpoint is ${e}.`})}if(r.historyIdInvalid)throw S({code:`REBASELINE_REMOTE_HISTORY_INVALID`,message:`Refusing to re-baseline: the connected workspace has an invalid migration history marker.`});if(r.historyId!==e)throw S(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 ht(v,y,[i],t,[st(g)]),c=o[0];if(!c||c.remoteMigrationNumber!==s||c.hasDrift||c.checkpointMissingLocal)throw c?.hasDrift&&(m.error(`Remote schema drift detected:`),m.log(ne(o))),S({code:`REBASELINE_REMOTE_SCHEMA_MISMATCH`,message:`Refusing to re-baseline: the connected workspace remote schema must match the latest migration.`})};if(await assertConnectedWorkspaceReady(l,`initial`),m.newline(),m.warn(`This will replace the migration history for ${f.bold(i.namespace)}.`),m.log(` Latest migration: ${F(s)}`),m.log(` New history: 0000/schema.json only`),m.log(` migrate.ts and db.ts files will disappear from the working tree.`),m.log(` Committed migration files will remain in Git history. Preserve any uncommitted files before continuing.`),m.log(` Every other environment must already be at the latest migration.`),m.log(` The connected workspace checkpoint will be reset to 0000.`),m.newline(),!e.yes&&!await H.confirm({message:`Re-baseline this migration history and reset the connected workspace checkpoint?`,default:!1}))throw S({code:`REBASELINE_CANCELLED`,message:`Migration re-baseline cancelled.`});if(D(i.migrationsDir,i.namespace),Ue([i])[i.namespace]!==u)throw S({code:`REBASELINE_STATE_CHANGED`,message:`Migration files changed while waiting for confirmation.`,suggestion:`Run the command again.`});if(se(localSourceFiles())!==_)throw S({code:`REBASELINE_STATE_CHANGED`,message:`Local TailorDB table or config files changed.`,suggestion:`Run the command again.`});assertLocalTypesReady(),await assertConnectedWorkspaceReady(l,`confirmation`);let w={historyId:Yt(),replacedHistoryId:l,replacedLatestMigration:s};await activateBaseline(i.migrationsDir,o,i.namespace,w);try{await Je(v,y,i.namespace,0,w.historyId)}catch(e){throw S({code:`REBASELINE_CHECKPOINT_UPDATE_FAILED`,message:`The local migration history was re-baselined, but the connected workspace checkpoint could not be updated.`,suggestion:`${C}, or ${ee}`,cause:e})}return m.success(`Re-baselined ${f.bold(i.namespace)} and reset the connected workspace checkpoint to 0000.`),{changed:!0,workspaceId:y,namespace:i.namespace,...w,schemaPath:Oe(i.migrationsDir,0,`schema`)}}const Eo=E({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({...M,...k,namespace:G(J.string().optional(),{alias:`n`,description:`Target TailorDB namespace (required if multiple namespaces exist)`})}),run:async e=>{await T({profile:e.profile});let t=await rebaseline({configPath:e.config,namespace:e.namespace,yes:e.yes,workspaceId:e[`workspace-id`],profile:e.profile});V(t)}});async function fetchRemoteGqlPermissions(e){let{client:t,workspaceId:n,namespace:r}=e;return Zr(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 qr(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?S({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}=Me(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:De(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=Gn(i,a),manifestFor=e=>{let t=f.get(e);if(!t)throw g(`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 _i(r):void 0,{defineApplication:a,generatePluginFilesIfNeeded:o}=await import(`../application-Bj2MtL-d.mjs`),s=a({config:n,pluginManager:i}),c=s.tailorDBServices.find(e=>e.namespace===t.namespace);if(!c)throw S({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-DEq_hdht.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??{}))Gt(e)&&e.trigger.kind===`tailordb`&&d.add(e.trigger.tableName);let p={executorUsedTables:d,namespaceGqlOperations:c.config.gqlOperations},h=O(t.migrationsDir);if(!h)return p;let g=gn(c.types,t.namespace),_=Mn(h,g.tables,t.namespace);if(!or(_))return p;throw m.error(`Migration history does not reproduce the current local schema for namespace ${f.bold(t.namespace)}:`),m.log(Sn(_)),m.newline(),m.info(`This usually means one of the following:`),m.info(` - Migration files were edited and replaying them no longer matches the table definitions — fix the migration files.`,{mode:`plain`}),m.info(` - Table definitions changed without a new migration — run 'tailor tailordb migration generate' first.`,{mode:`plain`}),m.newline(),S({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){Fe(`tailordb migration`);let t=Qn(e.number),n=await z(e.configPath),{config:r}=n,i=q.dirname(r.path),a=B(r,i),o=ue(a,e.namespace);D(o.migrationsDir,o.namespace);let s=_e(o.migrationsDir,t),c=O(o.migrationsDir,t);if(!c)throw S({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=N(d,`tailordb`,o.namespace),h=await A(u,p);gr(h,o.namespace);let g=h.number,_=await planSnapshotApply({client:u,workspaceId:d,namespace:o.namespace,snapshot:c}),{creates:v,updates:y,deletes:b,desiredGqlPermissions:x,gqlPermissionDeletes:C}=_;m.newline(),m.info(`Namespace: ${f.bold(o.namespace)}`),m.log(` Current migration: ${g===null?`<unset>`:f.bold(F(g))}`),m.log(` Target migration: ${f.bold(F(t))}`),m.log(` Tables to create: ${f.bold(String(v.length))}`),m.log(` Tables to update: ${f.bold(String(y.length))}`),m.log(` Tables to delete: ${f.bold(String(b.length))}`),m.log(` GQL permissions to set: ${f.bold(String(x.length))}`),m.log(` GQL permissions to delete: ${f.bold(String(C.length))}`),m.newline();let ee=v.length+y.length+b.length+x.length+C.length;if(ee===0?m.info(`No tables to apply; only the migration label will be updated.`):(m.warn(`This operation will overwrite remote TailorDB tables to match the selected snapshot.`),b.length>0&&m.warn(`Existing data in deleted tables will be lost.`),m.newline()),m.warn(`Sync never runs migrate.ts scripts; it only applies the schema snapshot and moves the migration label.`),m.newline(),g!==null&&t<g?(m.warn(`Migrations ${F(t+1)}–${F(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).`),m.newline()):g!==null&&t>g&&(m.warn(`Moving the migration label forwards (${F(g)} → ${F(t)}): migrate.ts scripts for migrations ${F(g+1)}–${F(t)} will not run on the next deploy.`),m.newline()),!e.yes){if(!await H.confirm({message:`Continue and set migration label to ${F(t)}?`,default:!1}))throw S({code:`MIGRATION_SYNC_CANCELLED`,message:`Migration sync cancelled.`});m.newline()}try{await applySnapshotPlan({client:u,workspaceId:d,namespace:o.namespace,snapshot:c,manifestOptions:l,plan:_})}catch(e){nr(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 w=c.rebaseline?.historyId,te=await Je(u,d,o.namespace,t,w);return m.success(`Synced namespace ${f.bold(o.namespace)} to migration ${f.bold(F(t))}.`),t<s&&(m.newline(),m.info(`Run 'tailor deploy' to apply migrations ${F(t+1)}–${F(s)} from the working tree.`)),{changed:ee>0||te,workspaceId:d,namespace:o.namespace,previousMigrationNumber:g,migrationNumber:t,historyId:w??null,tables:{created:v,updated:y,deleted:b},gqlPermissions:{set:x.map(({typeName:e})=>e),deleted:C.map(({typeName:e})=>e)}}}const Do=E({name:`sync`,description:`Sync remote TailorDB schema to a specific migration snapshot (recovery from --no-schema-check drift).`,args:J.strictObject({...M,...k,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 T({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});V(t)}});async function assertMigrationStateUnchanged(e){let{client:t,workspaceId:n,namespace:r,before:i}=e,a=await A(t,N(n,`tailordb`,r));if(a.number!==i.number||a.historyId!==i.historyId||a.inProgress?.number!==i.inProgress?.number||a.inProgress?.executionId!==i.inProgress?.executionId||a.inProgress?.kind!==i.inProgress?.kind)throw S({code:`MIGRATION_RESOLVE_STATE_CHANGED`,message:`The migration state of namespace "${r}" changed while the command was running.`,suggestion:`Run the command again.`})}function warnMainRunResolution(e){let{namespace:t,migrationNumber:n,resolution:r,runStatus:i}=e,a=F(n),o=Xn(i);r===`rollback`?(m.warn(`Rolling back does not undo what the script of migration ${a} changed in existing fields, and deletes the tables and fields the migration introduced together with their data. When migration ${a} is deployed again, its script runs again, so make sure it is safe to run twice.`),o===`complete`&&m.warn(`The run of migration ${a} succeeded. To keep what its script wrote, run the command with --complete instead.`)):(m.warn(`Completing applies the schema of migration ${a} without running its migrate.ts again; do this only after the data it needs is in place.`),o===`rollback`&&m.warn(`The run of migration ${a} did not succeed, so the data it migrates may not be in place. To run the script again on the next deploy, run the command with --rollback instead.`)),i===`unknown`&&m.warn(`Whether the run of migration ${a} succeeded could not be confirmed. Check it with 'tailor workflow executions --workflow-name ${Zt(t,n)}' before you continue.`)}async function resolve$1(e){Fe(`tailordb migration`);let t=await z(e.configPath),n=q.dirname(t.config.path),r=ue(B(t.config,n),e.namespace),{namespace:i}=r;D(r.migrationsDir,i);let{client:a,workspaceId:o}=await j({profile:e.profile,workspaceId:e.workspaceId}),s=await A(a,N(o,`tailordb`,i));if(s.inProgressInvalid)throw S({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||ie(s))throw S({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=s.number??0,l=c+1;if(s.inProgress.number!==l)throw S({code:`MIGRATION_RESOLVE_RECORD_INVALID`,message:`Namespace "${i}" records migration ${F(s.inProgress.number)} as in progress, but its checkpoint is ${F(c)}; the next migration to run would be ${F(l)}.`,details:`The checkpoint or the in-progress record changed after the deploy that started the migration wrote it.`,suggestion:`Run 'tailor tailordb migration status --namespace ${i}' to compare the checkpoint with the in-progress migration, and restore the changed label before resolving.`});let u=O(r.migrationsDir,0)?.rebaseline?.historyId??null;if((s.number!==null||s.historyId!==null||s.historyIdInvalid)&&(s.historyIdInvalid||s.historyId!==u))throw S({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 d=s.inProgress.number,p=F(d),h=s.inProgress.kind===`main`?await ir(a,o,i,s.inProgress):void 0;if(h===`running`)throw Pn(`The run of migration ${i}/${p} is still running.`,s.inProgress.executionId);let g=e.resolution===`rollback`?d-1:d;_e(r.migrationsDir,g);let _=O(r.migrationsDir,g);if(!_)throw S({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 v=await assertMigrationsReproduceLocalTypes(t,r),y=await planSnapshotApply({client:a,workspaceId:o,namespace:i,snapshot:_});if(m.newline(),m.info(`Namespace: ${f.bold(i)}`),m.log(` In progress: ${f.bold(p)}`),h&&m.log(` Run: ${f.bold(h)}`),m.log(` Resolution: ${f.bold(e.resolution)} (schema of migration ${f.bold(F(g))})`),m.log(` Tables to create: ${f.bold(String(y.creates.length))}`),m.log(` Tables to update: ${f.bold(String(y.updates.length))}`),m.log(` Tables to delete: ${f.bold(String(y.deletes.length))}`),m.newline(),y.deletes.length>0&&m.warn(`Existing data in deleted tables will be lost.`),h?warnMainRunResolution({namespace:i,migrationNumber:d,resolution:e.resolution,runStatus:h}):e.resolution===`rollback`?m.warn(`Rolling back does not undo the data changes made by steps of migration ${p} that already completed. When migration ${p} is deployed again, its steps run again from the first step, so make sure every step is safe to run twice.`):m.warn(`Completing applies the schema of migration ${p} without running its migrate.ts again; do this only after the data it needs is in place.`),m.newline(),!e.yes){if(!await H.confirm({message:`Continue and ${e.resolution} migration ${F(d)}?`,default:!1}))throw S({code:`MIGRATION_RESOLVE_CANCELLED`,message:`Migration resolve cancelled.`});m.newline()}await assertMigrationStateUnchanged({client:a,workspaceId:o,namespace:i,before:s}),await C(a,o,i,d);try{await applySnapshotPlan({client:a,workspaceId:o,namespace:i,snapshot:_,manifestOptions:v,plan:y})}catch(e){nr(e,[`The schema of migration ${p} 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 bt(a,o,i);let b=await Je(a,o,i,g,_.rebaseline?.historyId);await wt(a,o,i,d),m.success(`Resolved migration ${f.bold(F(d))} of namespace ${f.bold(i)} (${e.resolution}); the checkpoint is ${f.bold(F(g))}.`);let{creates:x,updates:ee,deletes:w,desiredGqlPermissions:te,gqlPermissionDeletes:ne}=y;return{changed:x.length+ee.length+w.length+te.length+ne.length>0||b,workspaceId:o,namespace:i,resolution:e.resolution,migrationNumber:d,checkpoint:g,...h?{runStatus:h}:{},tables:{created:x,updated:ee,deleted:w},gqlPermissions:{set:te.map(({typeName:e})=>e),deleted:ne.map(({typeName:e})=>e)}}}const Oo=E({name:`resolve`,description:`Settle a migration that a failed deploy left partially applied, or whose run a deploy could not confirm.`,notes:"Use this after a deploy failed partway through a migration whose `migrate.ts` exports `steps`, or after a deploy could not confirm whether the script of a migration ran (`MIGRATION_OUTCOME_UNKNOWN`). The 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. A deploy stops before changing anything while a run it could not confirm is not settled.\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 for a script that exports `steps`. Data changes the script already made 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\nFor a run that a deploy could not confirm, the command reads how the run ended and shows it before asking for confirmation: use `--complete` when it succeeded, and `--rollback` when it failed, was canceled, or did not start. It refuses while the run is still running, and warns when the option you chose does not fit how the run ended.\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({...M,...k,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 S({code:`MIGRATION_RESOLVE_DIRECTION_REQUIRED`,message:`Specify exactly one of --rollback or --complete.`});await T({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});V(t)}});async function set(e){Fe(`tailordb migration`);let t=Qn(e.number),{config:n}=await z(e.configPath),r=q.dirname(n.path),i=B(n,r),a=ue(i,e.namespace),o=a.namespace;D(a.migrationsDir,o),_e(a.migrationsDir,t);let s=O(a.migrationsDir,0)?.rebaseline?.historyId,{client:c,workspaceId:l}=await j({profile:e.profile,workspaceId:e.workspaceId}),u=N(l,`tailordb`,o),d=await A(c,u),p=d.inProgress?.number===t;p||gr(d,o);let h=d.number,g=h??0,_=d.historyIdInvalid?`<invalid>`:d.historyId??`<unset>`,v=s??`<unset>`;if(m.newline(),m.warn(`This operation will change TailorDB migration state metadata.`),m.log(`Namespace: ${f.bold(o)}`),m.log(`Current migration: ${h===null?`<unset>`:f.bold(F(h))}`),m.log(`New migration: ${f.bold(F(t))}`),m.log(`Current migration history ID: ${f.bold(_)}`),m.log(`New migration history ID: ${f.bold(v)}`),m.newline(),p&&(m.warn(`Migration ${F(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`+(d.inProgress?.kind===`main`?` and its run succeeded. 'tailor tailordb migration resolve' checks how the run ended before it settles the migration.`:`.`)),m.newline()),t<g?(m.warn(`Setting migration number backwards (${F(g)} → ${F(t)}) will cause previous migrations to be re-executed on next apply.`),m.newline()):t>g&&(m.warn(`Setting migration number forwards (${F(g)} → ${F(t)}) will skip migrations ${F(g+1)} to ${F(t)}.`),m.newline()),!e.yes){if(!await H.confirm({message:`Continue with migration checkpoint and history ID update?`,default:!1}))throw S({code:`MIGRATION_SET_CANCELLED`,message:`Migration checkpoint update cancelled.`});m.newline()}let y=await Je(c,l,o,t,s);return m.success(`Migration checkpoint set to ${f.bold(F(t))} for namespace ${f.bold(o)}`),{changed:y,workspaceId:l,namespace:o,previousMigrationNumber:h,migrationNumber:t,historyId:s??null}}const ko=E({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({...M,...k,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 T({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});V(t)}});function isStatusFailure(e){return e.status===`error`}async function collectMigrationStatuses(e){let{config:t}=await z(e.configPath),n=q.dirname(t.path),r=B(t,n);if(r.length===0)throw it();let i=e.namespace?r.filter(t=>t.namespace===e.namespace):r;if(i.length===0)throw S({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{D(t,e);let n=xt(t),r=/* @__PURE__ */ new Map,i=null;for(let e of n)if(e.type===`schema`){let t=Ye(e.path);e.number===0&&(i=t.rebaseline?.historyId??null)}else try{let t=Tt(e.path);t.description&&r.set(e.number,t.description)}catch(e){if(p(e)&&e.code===`MIGRATION_FILE_VERSION_UNSUPPORTED`)throw e}a.set(e,{migrationFiles:n,descriptions:r,historyId:i})}catch(t){o.set(e,v(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=N(c,`tailordb`,e),d;try{d=await A(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:F(e),...r.has(e)?{description:r.get(e)}:{}})),m=ie(d)?null:d.inProgress;l.push({status:`ok`,namespace:e,currentMigration:f,currentMigrationLabel:F(f),pendingMigrations:p,...m?{inProgressMigration:m.number,inProgressMigrationLabel:F(m.number),inProgressMigrationRun:m.kind}:{}})}return l}function printMigrationStatuses(e){for(let t of e)if(m.newline(),m.info(`Namespace: ${f.bold(t.namespace)}`),isStatusFailure(t))m.error(` Migration status error: ${t.error}`);else if(m.log(` Current migration: ${f.bold(t.currentMigrationLabel)}`),t.inProgressMigrationLabel&&m.log(t.inProgressMigrationRun===`main`?` In progress: ${f.bold(t.inProgressMigrationLabel)} (the outcome of its run is not settled; settle it with 'tailor tailordb migration resolve')`:` In progress: ${f.bold(t.inProgressMigrationLabel)} (partially applied; the next deploy resumes it)`),t.pendingMigrations.length>0){m.log(` Pending migrations:`);for(let e of t.pendingMigrations)e.description?m.log(` - ${e.label}: ${e.description}`):m.log(` - ${e.label}`)}else m.log(` Pending migrations: (none)`);m.newline()}async function status(e){Fe(`tailordb migration`);let t=await collectMigrationStatuses(e);e.json?m.out(t):printMigrationStatuses(t);let n=t.filter(isStatusFailure);if(n.length>0){let e=n.map(e=>e.namespace).join(`, `);throw S({code:`MIGRATION_STATUS_FAILED`,message:`Migration status check failed for ${n.length} namespace${n.length===1?``:`s`}: ${e}`})}}const Ao=E({name:`status`,description:`Show the current migration status for TailorDB namespaces, including applied and pending migrations.`,notes:`Local migration files are checked for a valid layout (numbering and required files in each migration directory) and a compatible format version, and deployed migration history IDs must match the local baseline. Invalid or incompatible files, 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({...M,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:m.jsonMode})}});async function runMigrationTest(e,t=createMigrationTestDependencies()){if(e.targetWorkspaceId&&!e.yes)throw S({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 S({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 S({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 S({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 S({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){m.warn(`Failed to record an expiry on temporary workspace ${i.id}: ${t instanceof Error?t.message:String(t)}. Record one with ${b({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)m.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 S({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});m.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){Fe(`tailordb migration`);let t=await runMigrationTest(e);e.json?m.out(t):m.success(`Pending migrations completed in workspace ${t.workspaceName??t.workspaceId}.`)}const jo=E({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({...M,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(vr.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(tr.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 T({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`],...jt(e),assertionPath:e.assert,assertionNamespace:e[`assert-namespace`],machineUser:e[`machine-user`],cloneTimeout:e[`clone-timeout`]===void 0?void 0:xn(e[`clone-timeout`]),yes:e.yes,json:m.jsonMode})}});function assertMigrationScriptsReady(e,t,n){let r=[],i=[],a=[],o=[],s=[];for(let t of xt(e)){if(t.type!==`diff`)continue;let n=Tt(t.path),c=Oe(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&&yr(c)>0&&a.push(t.number),n.hasWarnings&&!n.scriptSkipped&&!l&&o.push({migrationNumber:t.number,warnings:n.warnings})}if(r.length>0)throw S({code:`MIGRATION_SCRIPT_REQUIRED`,message:`Migration(s) ${r.map(F).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=>` ${fn({migrationNumber:e,namespace:t,configPath:n})}`).join(`
103
+ `);throw S({code:`MIGRATION_SCRIPT_SKIP_CONFLICT`,message:`Migration(s) ${i.map(F).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 S({code:`MIGRATION_SCRIPT_REVIEW_REQUIRED`,message:`Migration(s) ${a.map(F).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:Ot});for(let[e,n]of s){let r=dr(n);r.kind===`main`&&r.ignoredSteps&&m.warn(Lt(`${t}/${F(e)}`))}return o}function buildValidationReports(e){let{targetNamespaces:t,migrationFileErrors:n,localResults:r,remoteResults:i,unacknowledgedWarnings:a}=e;return t.map(e=>{let t=n.get(e.namespace);if(t!==void 0)return{namespace:e.namespace,valid:!1,migrationFiles:{valid:!1,error:t}};let o=s(r.find(t=>t.namespace===e.namespace),`local schema check result missing for namespace "${e.namespace}"`),c={hasDiff:o.hasDiff,...o.diff?{diff:o.diff}:{}};if(i===void 0)return{namespace:e.namespace,valid:!1,migrationFiles:{valid:!0},localSchema:c,remoteSchema:{skipped:`check_failed`}};let l=s(i.find(t=>t.namespace===e.namespace),`remote schema check result missing for namespace "${e.namespace}"`),u=l.checkpointMissingLocal===!0,d={remoteMigrationNumber:l.remoteMigrationNumber,hasDrift:l.hasDrift,drifts:l.drifts,...l.skipped?{skipped:l.skipped}:{},...u?{checkpointMissingLocal:!0}:{},...l.rebaselinePending?{rebaselinePending:l.rebaselinePending}:{},...l.checkpointRepair?{checkpointRepair:l.checkpointRepair}:{}},f=a?.get(e.namespace),p;if(f!==void 0){let e=f.filter(e=>e.migrationNumber>l.remoteMigrationNumber);p={valid:e.length===0,missing:e}}return{namespace:e.namespace,valid:!c.hasDiff&&!d.hasDrift&&!u&&p?.valid!==!1,migrationFiles:{valid:!0},localSchema:c,remoteSchema:d,...p?{warningAcknowledgments:p}:{}}})}async function collectValidationReports(e){let{config:t,plugins:n}=await z(e.configPath),r=q.dirname(t.path),i=B(t,r);if(i.length===0)throw it();let a=e.namespace?i.filter(t=>t.namespace===e.namespace):i;if(a.length===0)throw S({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`Namespace "${e.namespace}" not found or does not have migrations configured`});let o=n.length>0?new _i(n):void 0,{defineApplication:s}=await import(`../application-Bj2MtL-d.mjs`),c=s({config:t,pluginManager:o});for(let e of c.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();wr({tailorDBServices:c.tailorDBServices});for(let{namespace:e}of a)if(!c.tailorDBServices.some(t=>t.namespace===e))throw S({code:`TAILORDB_NAMESPACE_NOT_FOUND`,message:`No TailorDB service found for namespace "${e}"`});let l=c.tailorDBServices.map(st),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{D(t.migrationsDir,t.namespace),O(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,v(e))}let m={targetNamespaces:a,migrationFileErrors:d,localResults:await Le(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 ht(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(m.newline(),m.info(`Namespace: ${f.bold(t.namespace)}`),!t.migrationFiles.valid){m.log(` Migration files: ${f.error(`invalid`)}`),m.log(` ${t.migrationFiles.error}`);continue}m.log(` Migration files: ${f.success(`OK`)}`);let e=t.localSchema;e?.hasDiff?e.diff?(m.log(` Local schema: ${f.error(`changes not in migration files`)}`),m.log(` ${Bt(e.diff)}`),m.log(Sn(e.diff))):m.log(` Local schema: ${f.error(`no migration snapshot found`)}`):m.log(` Local schema: ${f.success(`OK`)}`);let n=t.remoteSchema;n?.skipped===`check_failed`?m.log(` Remote schema: ${f.error(`not checked`)}`):n?.checkpointRepair?m.log(` Remote schema: ${f.success(`OK`)} (next deploy will reset the checkpoint to 0000 from ${F(n.checkpointRepair.from)})`):n?.checkpointMissingLocal?(m.log(` Remote schema: ${f.error(`remote migration ${F(n.remoteMigrationNumber)} is not in the local migration history`)}`),n.rebaselinePending&&m.log(` Fell behind before 'migration rebaseline' ran; must reach ${F(n.rebaselinePending.replacedLatestMigration)} first.`)):n?.hasDrift?(m.log(` Remote schema: ${f.error(`drift detected`)} (remote migration: ${F(n.remoteMigrationNumber)})`),m.log(w(n.drifts))):n?.skipped===`not_deployed`?m.log(` Remote schema: ${f.dim(`skipped (namespace not deployed)`)}`):n?.skipped===`no_migration_label`?m.log(` Remote schema: ${f.dim(`skipped (deployed namespace has no migration state)`)}`):n?.skipped===`no_snapshot`?m.log(` Remote schema: ${f.dim(`skipped (no local snapshot for remote migration ${F(n.remoteMigrationNumber)})`)}`):n&&m.log(` Remote schema: ${f.success(`OK`)} (remote migration: ${F(n.remoteMigrationNumber)})`);let r=t.warningAcknowledgments;if(r){if(r.valid)m.log(` Warning acknowledgments: ${f.success(`OK`)}`);else{m.log(` Warning acknowledgments: ${f.error(`missing for pending migration(s) with possible data loss`)}`);for(let e of r.missing){let t=F(e.migrationNumber);for(let n of e.warnings){let e=n.fieldName?`.${n.fieldName}`:``;m.log(` ${t}: ${n.tableName}${e}: ${n.reason}`)}}}}}m.newline()}function hasMissingCheckpoint(e){return e.remoteSchema?.checkpointMissingLocal===!0}function printResolutionHints(e,t){e.some(e=>e.localSchema?.hasDiff&&!e.localSchema.diff)&&m.info(`Run 'tailor tailordb migration generate' to create the initial snapshot.`),e.some(e=>e.localSchema?.diff)&&m.info(`Run 'tailor tailordb migration generate' to create migration files.`);let n=e.filter(hasMissingCheckpoint);n.length>0&&ft(n.map(e=>({namespace:e.namespace,remoteMigrationNumber:e.remoteSchema.remoteMigrationNumber,...e.remoteSchema.rebaselinePending?{rebaselinePending:e.remoteSchema.rebaselinePending}:{}}))),e.some(e=>e.remoteSchema?.hasDrift)&&xe(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){m.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??[])m.info(` ${fn({migrationNumber:n.migrationNumber,namespace:e.namespace,configPath:t,noScript:!0})}`,{mode:`plain`})}}async function validate(e){Fe(`tailordb migration`);let t=await collectValidationReports(e),{reports:n}=t,r=n.filter(e=>!e.valid).length;if(e.json?m.out(n):(printValidationReports(n),r===0&&!(`remoteError`in t)?m.success(`All migration validation checks passed.`):printResolutionHints(n,e.configPath)),`remoteError`in t)throw t.remoteError;if(r>0)throw S({code:`MIGRATION_VALIDATION_FAILED`,message:`Migration validation failed for ${r} namespace(s)`})}const Mo=E({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({...M,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:m.jsonMode,strict:e.strict})}}),No=K({name:`migration`,description:`Manage TailorDB schema migrations.`,subCommands:{generate:We,rebaseline:Eo,resolve:Oo,script:de,set:ko,status:Ao,sync:Do,test:jo,validate:Mo}}),Po=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:Re,migration:No}}),Fo=E({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-CaGmqg0r.mjs`);await n({from:e.from,dryRun:e[`dry-run`],path:q.resolve(e.path)})}}),Io=E({name:`current`,description:`Show current user.`,args:J.strictObject({profile:P.profile}),run:async e=>{let t=await U(),n=e.profile||process.env.TAILOR_PLATFORM_PROFILE,r=n?t.profiles[n]:void 0;if(n&&!r)throw S({code:`PROFILE_NOT_FOUND`,message:`Profile "${n}" not found`});let i=r?Ie(r):void 0,a=n?r?.user??null:t.current_user,o=m.jsonMode;if(!a)throw S({code:`USER_NOT_SET`,message:`Current user not set.`,suggestion:`Log in first to register a user.`,next:{command:`tailor`,args:[`login`,...L({profile:n})]}});if(!He(t,a,i))throw S({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`,...L({profile:n})]}});o?m.out({user:a}):m.out(a)}});function activeCurrentUserKey(e,t){if(!t)return e.current_user?mt(e,e.current_user):null;let n=e.profiles[t];if(!n)throw S({code:`PROFILE_NOT_FOUND`,message:`Profile "${t}" not found`});return mt(e,n.user,Ie(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 Lo=E({name:`list`,description:`List all users.`,args:J.strictObject({profile:P.profile}),run:async e=>{let t=await U(),n=m.jsonMode,r=activeCurrentUserKey(t,e.profile||process.env.TAILOR_PLATFORM_PROFILE),i=Object.keys(t.users);if(i.length===0){m.info(W`
100
104
  No users found.
101
105
  Please login first using 'tailor login' command to register a user.
102
- `),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))})}}),jo={[o.PAT_SCOPE_UNSPECIFIED]:`unknown`,[o.PAT_SCOPE_READ]:`read`,[o.PAT_SCOPE_WRITE]:`write`};function patScopeToString(e){return It(jo,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?[o.PAT_SCOPE_READ,o.PAT_SCOPE_WRITE]:[o.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`
106
+ `),n&&m.out([]);return}let a=i.map(e=>toUserListInfo(e,r));n?m.out([...new Set(a.map(e=>e.user))]):a.forEach(e=>{e.current?m.success(formatUserListInfo(e),{mode:`plain`}):m.log(formatUserListInfo(e))})}}),Ro={[o.PAT_SCOPE_UNSPECIFIED]:`unknown`,[o.PAT_SCOPE_READ]:`read`,[o.PAT_SCOPE_WRITE]:`write`};function patScopeToString(e){return Wn(Ro,e,`unknown`)}function transformPersonalAccessToken(e){return{name:e.name,scopes:e.scopes.map(patScopeToString),createdAt:tn(e.createdAt),lastUsedAt:tn(e.lastUsedAt)}}function getScopesFromWriteFlag(e){return e?[o.PAT_SCOPE_READ,o.PAT_SCOPE_WRITE]:[o.PAT_SCOPE_READ]}function getScopeStringsFromWriteFlag(e){return e?[`read`,`write`]:[`read`]}function printCreatedToken(e,t,n,r){let i=getScopeStringsFromWriteFlag(n);m.jsonMode?m.out({name:e,scopes:i,token:t}):m.out(W`
103
107
  Personal access token ${r} successfully.
104
108
 
105
109
  name: ${e}
@@ -107,16 +111,16 @@ Error:`));let e=formatErrorWithSourcemap(b.error,p,process.cwd());e?f.log(e):f.l
107
111
  token: ${t}
108
112
 
109
113
  Please save this token in a secure location. You won't be able to see it again.
110
- `)}async function createPatOperatorClient(e){let t=await nr({profile:e});return await Pr(t)}const Mo=C({name:`create`,description:`Create a new personal access token.`,args:J.strictObject({name:G(J.string(),{positional:!0,description:`Token name`}),write:G(J.boolean().default(!1),{alias:`W`,description:`Grant write permission (default: read-only)`}),profile:N.profile}),run:async e=>{await z({profile:e.profile});let t=await createPatOperatorClient(e.profile),n=getScopesFromWriteFlag(e.write),r=await t.createPersonalAccessToken({name:e.name,scopes:n});if(!r.accessToken)throw Zr(`Failed to create personal access token`);f.registerSecret(r.accessToken),printCreatedToken(e.name,r.accessToken,e.write,`created`)}}),No=C({name:`delete`,description:`Delete a personal access token.`,args:J.strictObject({name:G(J.string(),{positional:!0,description:`Token name`}),profile:N.profile}),run:async e=>{await z({profile:e.profile}),await(await createPatOperatorClient(e.profile)).deletePersonalAccessToken({name:e.name}),f.success(`Personal access token "${e.name}" deleted successfully.`),A({changed:!0,name:e.name})}}),Po=C({name:`list`,description:`List all personal access tokens.`,args:J.strictObject({...Ln(),profile:N.profile}),run:async e=>{let t=f.jsonMode,n=await createPatOperatorClient(e.profile),r=Nt(e.order),i=await Jt(e.limit,e=>Br(async(e,t)=>{let{personalAccessTokens:i,nextPageToken:a}=await n.listPersonalAccessTokens({pageToken:e,pageSize:t,pageDirection:r});return[i,a]},{limit:e})),a=i.items;if(a.length===0&&(f.info(H`
114
+ `)}async function createPatOperatorClient(e){let t=await yn({profile:e});return await Kr(t)}const zo=E({name:`create`,description:`Create a new personal access token.`,args:J.strictObject({name:G(J.string(),{positional:!0,description:`Token name`}),write:G(J.boolean().default(!1),{alias:`W`,description:`Grant write permission (default: read-only)`}),profile:P.profile}),run:async e=>{await T({profile:e.profile});let t=await createPatOperatorClient(e.profile),n=getScopesFromWriteFlag(e.write),r=await t.createPersonalAccessToken({name:e.name,scopes:n});if(!r.accessToken)throw g(`Failed to create personal access token`);m.registerSecret(r.accessToken),printCreatedToken(e.name,r.accessToken,e.write,`created`)}}),Bo=E({name:`delete`,description:`Delete a personal access token.`,args:J.strictObject({name:G(J.string(),{positional:!0,description:`Token name`}),profile:P.profile}),run:async e=>{await T({profile:e.profile}),await(await createPatOperatorClient(e.profile)).deletePersonalAccessToken({name:e.name}),m.success(`Personal access token "${e.name}" deleted successfully.`),V({changed:!0,name:e.name})}}),Vo=E({name:`list`,description:`List all personal access tokens.`,args:J.strictObject({...zt(),profile:P.profile}),run:async e=>{let t=m.jsonMode,n=await createPatOperatorClient(e.profile),r=Vn(e.order),i=await Et(e.limit,e=>Rr(async(e,t)=>{let{personalAccessTokens:i,nextPageToken:a}=await n.listPersonalAccessTokens({pageToken:e,pageSize:t,pageDirection:r});return[i,a]},{limit:e})),a=i.items;if(a.length===0&&(m.info(W`
111
115
  No personal access tokens found.
112
116
  Please create a token using 'tailor user pat create' command.
113
- `),!t))return;let o=a.map(transformPersonalAccessToken);f.out(o,{display:{scopes:e=>e.join(`/`),lastUsedAt:e=>e===null?`never`:Yt(e)}}),await F(i,e.limit)}}),Fo=C({name:`update`,description:`Update a personal access token (delete and recreate).`,args:J.strictObject({name:G(J.string(),{positional:!0,description:`Token name`}),write:G(J.boolean().default(!1),{alias:`W`,description:`Grant write permission (if not specified, keeps read-only)`}),profile:N.profile}),run:async e=>{await z({profile:e.profile});let t=await createPatOperatorClient(e.profile);await t.deletePersonalAccessToken({name:e.name});let n=getScopesFromWriteFlag(e.write),r=await t.createPersonalAccessToken({name:e.name,scopes:n});if(!r.accessToken)throw Zr(`Failed to create personal access token`);f.registerSecret(r.accessToken),printCreatedToken(e.name,r.accessToken,e.write,`updated`)}}),Io=K({name:`pat`,description:`Manage personal access tokens.`,subCommands:{list:Po,create:Mo,delete:No,update:Fo},defaultSubCommand:`list`}),Lo=C({name:`switch`,description:`Set current user.`,args:J.strictObject({user:G(J.string(),{positional:!0,description:`User email address or machine user client ID`}),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?Ne(r):void 0;if(e.user.includes(`|`))throw W({code:`USER_NAME_INVALID`,message:`User "${e.user}" looks like a platform-scoped token key. Pass the user name without the platform URL and select the platform with TAILOR_PLATFORM_URL or a profile.`,command:`user switch`});let a=ke(t,e.user,i);if(!a)throw W({code:`USER_NOT_FOUND`,message:`User "${e.user}" not found.`,suggestion:`Log in first to register this user.`,next:{command:`tailor`,args:[`login`,...k({profile:n})]}});let o=r?r.user:t.current_user;r?r.user=a:t.current_user=a,E(t),f.success(`Current user set to "${a}" successfully.`),A({changed:o!==a,user:a,profile:n||null})}}),Ro=J.union([J.uuid(),J.literal(``)]),zo=C({name:`update`,description:`Set the current user's default organization and folder for new workspaces.`,notes:H`
117
+ `),!t))return;let o=a.map(transformPersonalAccessToken);m.out(o,{display:{scopes:e=>e.join(`/`),lastUsedAt:e=>e===null?`never`:Un(e)}}),await R(i,e.limit)}}),Ho=E({name:`update`,description:`Update a personal access token (delete and recreate).`,args:J.strictObject({name:G(J.string(),{positional:!0,description:`Token name`}),write:G(J.boolean().default(!1),{alias:`W`,description:`Grant write permission (if not specified, keeps read-only)`}),profile:P.profile}),run:async e=>{await T({profile:e.profile});let t=await createPatOperatorClient(e.profile);await t.deletePersonalAccessToken({name:e.name});let n=getScopesFromWriteFlag(e.write),r=await t.createPersonalAccessToken({name:e.name,scopes:n});if(!r.accessToken)throw g(`Failed to create personal access token`);m.registerSecret(r.accessToken),printCreatedToken(e.name,r.accessToken,e.write,`updated`)}}),Uo=K({name:`pat`,description:`Manage personal access tokens.`,subCommands:{list:Vo,create:zo,delete:Bo,update:Ho},defaultSubCommand:`list`}),Wo=E({name:`switch`,description:`Set current user.`,args:J.strictObject({user:G(J.string(),{positional:!0,description:`User email address or machine user client ID`}),profile:P.profile}),run:async e=>{let t=await U(),n=e.profile||process.env.TAILOR_PLATFORM_PROFILE,r=n?t.profiles[n]:void 0;if(n&&!r)throw S({code:`PROFILE_NOT_FOUND`,message:`Profile "${n}" not found`});let i=r?Ie(r):void 0;if(e.user.includes(`|`))throw S({code:`USER_NAME_INVALID`,message:`User "${e.user}" looks like a platform-scoped token key. Pass the user name without the platform URL and select the platform with TAILOR_PLATFORM_URL or a profile.`,command:`user switch`});let a=be(t,e.user,i);if(!a)throw S({code:`USER_NOT_FOUND`,message:`User "${e.user}" not found.`,suggestion:`Log in first to register this user.`,next:{command:`tailor`,args:[`login`,...L({profile:n})]}});let o=r?r.user:t.current_user;r?r.user=a:t.current_user=a,I(t),m.success(`Current user set to "${a}" successfully.`),V({changed:o!==a,user:a,profile:n||null})}}),Go=J.union([J.uuid(),J.literal(``)]),Ko=E({name:`update`,description:`Set the current user's default organization and folder for new workspaces.`,notes:W`
114
118
  \`workspace create\`, workspace creation during \`deploy\`, and the programmatic \`createWorkspace()\` use the default folder, or directly use the default organization when no folder is set. Giving either an organization or a folder replaces both defaults for that run. For the CLI, use --organization-id or --folder-id, or TAILOR_PLATFORM_ORGANIZATION_ID / TAILOR_PLATFORM_FOLDER_ID. The defaults are not used while TAILOR_PLATFORM_TOKEN is set, because that token does not belong to a user logged in here.
115
119
 
116
120
  Each run replaces both defaults: --default-organization-id alone clears the default folder, --default-folder-id is accepted only together with --default-organization-id, and --default-organization-id "" clears both. The IDs are not checked against the Platform here; \`workspace create\` and \`deploy\` point back to them when the Platform cannot find them or denies access to them.
117
121
 
118
122
  The defaults belong to this user's login on the selected platform, so \`logout\` removes them, and older SDK versions drop them when they rewrite the CLI config file.
119
- `,args:J.strictObject({"default-organization-id":G(Ro.optional(),{alias:`o`,description:"Organization that `workspace create` uses when no location is given. Pass an empty string to clear the defaults."}),"default-folder-id":G(Ro.optional(),{alias:`f`,description:"Folder in the default organization that `workspace create` uses (requires --default-organization-id)"}),profile:N.profile}),run:async e=>{let t=e[`default-organization-id`],n=e[`default-folder-id`];if(t===void 0&&n===void 0)throw W({code:`USER_UPDATE_EMPTY`,message:`Please provide at least one property to update.`,command:`user update`});if(t===void 0||t===``&&n)throw W({code:`USER_DEFAULT_FOLDER_WITHOUT_ORGANIZATION`,message:`--default-folder-id requires a --default-organization-id.`,suggestion:`Pass the organization that owns the folder with --default-organization-id.`,command:`user update`});let r=await T(),i=Ue(r,{profile:e.profile});if(!i){let t=e.profile||process.env.TAILOR_PLATFORM_PROFILE;throw W({code:`PROFILE_NOT_FOUND`,message:`Profile "${t}" not found`})}let{profile:a,user:o,userEntry:s}=i,c={command:`tailor`,args:[`login`,...k({profile:a})]};if(!o)throw W({code:`USER_NOT_SET`,message:`Current user not set.`,suggestion:`Log in first to register a user.`,next:c});if(!s)throw W({code:`USER_NOT_FOUND`,message:`User "${o}" has no login of its own on the selected platform.`,suggestion:`Log in on that platform to store the defaults with that login.`,next:c});let l=s.default_organization_id??null,u=s.default_folder_id??null;delete s.default_organization_id,delete s.default_folder_id,t&&(s.default_organization_id=t,n&&(s.default_folder_id=n)),E(r);let d=s.default_organization_id??null,p=s.default_folder_id??null;f.success(d?`Default organization for new workspaces set to ${d} ${p?`with folder ${p}`:`with no default folder`}.`:`Default organization and folder for new workspaces cleared.`),d&&Pe()&&f.warn("`workspace create` does not use these defaults while TAILOR_PLATFORM_TOKEN is set."),A({changed:l!==d||u!==p,user:o,profile:a||null,defaultOrganizationId:d,defaultFolderId:p})}}),Bo=K({name:`user`,description:`Manage Tailor Platform users.`,subCommands:{current:ko,list:Ao,switch:Lo,update:zo,pat:Io},defaultSubCommand:`list`}),Vo=K({name:`workflow`,description:`Manage workflows and workflow executions.`,subCommands:{list:fn,get:ye,start:Re,wait:Ze,executions:Ke,resume:ne},defaultSubCommand:`list`}),Ho=K({name:`app`,description:`Manage workspace applications`,subCommands:{health:tr,list:qe},defaultSubCommand:`list`}),locationIdsArg=()=>J.array(J.union([J.literal(``),J.uuid()])).optional(),Uo=J.preprocess(e=>typeof e==`string`&&e.trim()===``?NaN:e,J.coerce.number().int().nonnegative());function matchesName(e,t){return t.nameRegexes.length===0||t.nameRegexes.some(t=>t.test(e.name))}function hasLocation(e){return e.organizationRoots.length>0||e.folderIds.length>0||e.personal}function matchesScope(e,t){return hasLocation(t)?e.folderId?t.folderIds.includes(e.folderId):e.organizationId?t.organizationRoots.includes(e.organizationId):t.personal:!0}function staleCandidateReason(e,t){if(e.deleteProtection)return`delete protection was turned on`;if(!matchesScope(e,t))return`it moved outside the requested scope`;if(!matchesName(e,t))return`it no longer matches the name filter`;if(t.exclude.has(e.name))return`it is now excluded by --exclude`}function selectPruneCandidates(e,t,n){let r={candidates:[],excluded:[],protectedSkipped:[],missingCreateTime:[],tooYoung:[]};for(let i of e)if(matchesScope(i,t)&&matchesName(i,t)){if(t.exclude.has(i.name))r.excluded.push(i);else if(i.deleteProtection)r.protectedSkipped.push(i);else{if(t.olderThanMs!==void 0){let e=zt(i.createTime);if(!e){r.missingCreateTime.push(i);continue}if(e.getTime()>n.getTime()-t.olderThanMs){r.tooYoung.push(i);continue}}r.candidates.push(i)}}return r}async function partitionByExpiry(e,t,n){let r=jr(),i=await Promise.all(t.map(async t=>({workspace:t,result:await r(()=>$t(e,t.id,n))}))),a={expired:[],pending:[],unset:[],unreadable:[]};for(let{workspace:e,result:t}of i)`error`in t?a.unreadable.push({workspace:e,reason:t.error.message}):recordExpiryState(a,e,t.expiry);return a}function recordExpiryState(e,t,n){switch(n.state){case`expired`:e.expired.push(t);return;case`pending`:e.pending.push(t);return;case`unset`:e.unset.push(t);return;case`invalid`:e.unreadable.push({workspace:t,reason:`recorded expiry "${n.value}" is not a value this CLI wrote`})}}async function fetchAllWorkspaces(e){return Br(async(t,n)=>{let{workspaces:r,nextPageToken:i}=await e.listWorkspaces({pageToken:t,pageSize:n});return[r,i]})}function compileNameRegex(e){try{return new RegExp(e),RegExp(`^(?:${e})$`)}catch(t){throw W({code:`INVALID_NAME_PATTERN`,message:`Invalid --name "${e}".`,details:t instanceof Error?t.message:String(t)})}}const Wo=[{key:`excluded`,selection:`excluded`,reason:`excluded by --exclude`},{key:`deleteProtection`,selection:`protectedSkipped`,reason:`delete protection is on`},{key:`unknownAge`,selection:`missingCreateTime`,reason:`creation time is unknown`}],Go="Specify --organization-root, --folder-id, or --personal on the command line. The default organization/folder set by `tailor user update` is not used by prune.",Ko=C({name:`prune`,description:`Delete stale temporary workspaces, by name and age or by the expiry each recorded at creation.`,notes:H`
123
+ `,args:J.strictObject({"default-organization-id":G(Go.optional(),{alias:`o`,description:"Organization that `workspace create` uses when no location is given. Pass an empty string to clear the defaults."}),"default-folder-id":G(Go.optional(),{alias:`f`,description:"Folder in the default organization that `workspace create` uses (requires --default-organization-id)"}),profile:P.profile}),run:async e=>{let t=e[`default-organization-id`],n=e[`default-folder-id`];if(t===void 0&&n===void 0)throw S({code:`USER_UPDATE_EMPTY`,message:`Please provide at least one property to update.`,command:`user update`});if(t===void 0||t===``&&n)throw S({code:`USER_DEFAULT_FOLDER_WITHOUT_ORGANIZATION`,message:`--default-folder-id requires a --default-organization-id.`,suggestion:`Pass the organization that owns the folder with --default-organization-id.`,command:`user update`});let r=await U(),i=ot(r,{profile:e.profile});if(!i){let t=e.profile||process.env.TAILOR_PLATFORM_PROFILE;throw S({code:`PROFILE_NOT_FOUND`,message:`Profile "${t}" not found`})}let{profile:a,user:o,userEntry:s}=i,c={command:`tailor`,args:[`login`,...L({profile:a})]};if(!o)throw S({code:`USER_NOT_SET`,message:`Current user not set.`,suggestion:`Log in first to register a user.`,next:c});if(!s)throw S({code:`USER_NOT_FOUND`,message:`User "${o}" has no login of its own on the selected platform.`,suggestion:`Log in on that platform to store the defaults with that login.`,next:c});let l=s.default_organization_id??null,u=s.default_folder_id??null;delete s.default_organization_id,delete s.default_folder_id,t&&(s.default_organization_id=t,n&&(s.default_folder_id=n)),I(r);let d=s.default_organization_id??null,f=s.default_folder_id??null;m.success(d?`Default organization for new workspaces set to ${d} ${f?`with folder ${f}`:`with no default folder`}.`:`Default organization and folder for new workspaces cleared.`),d&&Ze()&&m.warn("`workspace create` does not use these defaults while TAILOR_PLATFORM_TOKEN is set."),V({changed:l!==d||u!==f,user:o,profile:a||null,defaultOrganizationId:d,defaultFolderId:f})}}),qo=K({name:`user`,description:`Manage Tailor Platform users.`,subCommands:{current:Io,list:Lo,switch:Wo,update:Ko,pat:Uo},defaultSubCommand:`list`}),Jo=K({name:`workflow`,description:`Manage workflows and workflow executions.`,subCommands:{list:vn,get:Te,start:Ke,wait:nt,executions:$e,resume:ae},defaultSubCommand:`list`}),Yo=K({name:`app`,description:`Manage workspace applications`,subCommands:{health:pr,list:et},defaultSubCommand:`list`}),locationIdsArg=()=>J.array(J.union([J.literal(``),J.uuid()])).optional(),Xo=J.preprocess(e=>typeof e==`string`&&e.trim()===``?NaN:e,J.coerce.number().int().nonnegative());function matchesName(e,t){return t.nameRegexes.length===0||t.nameRegexes.some(t=>t.test(e.name))}function hasLocation(e){return e.organizationRoots.length>0||e.folderIds.length>0||e.personal}function matchesScope(e,t){return hasLocation(t)?e.folderId?t.folderIds.includes(e.folderId):e.organizationId?t.organizationRoots.includes(e.organizationId):t.personal:!0}function staleCandidateReason(e,t){if(e.deleteProtection)return`delete protection was turned on`;if(!matchesScope(e,t))return`it moved outside the requested scope`;if(!matchesName(e,t))return`it no longer matches the name filter`;if(t.exclude.has(e.name))return`it is now excluded by --exclude`}function selectPruneCandidates(e,t,n){let r={candidates:[],excluded:[],protectedSkipped:[],missingCreateTime:[],tooYoung:[]};for(let i of e)if(matchesScope(i,t)&&matchesName(i,t)){if(t.exclude.has(i.name))r.excluded.push(i);else if(i.deleteProtection)r.protectedSkipped.push(i);else{if(t.olderThanMs!==void 0){let e=tn(i.createTime);if(!e){r.missingCreateTime.push(i);continue}if(e.getTime()>n.getTime()-t.olderThanMs){r.tooYoung.push(i);continue}}r.candidates.push(i)}}return r}async function partitionByExpiry(e,t,n){let r=ai(),i=await Promise.all(t.map(async t=>({workspace:t,result:await r(()=>Dt(e,t.id,n))}))),a={expired:[],pending:[],unset:[],unreadable:[]};for(let{workspace:e,result:t}of i)`error`in t?a.unreadable.push({workspace:e,reason:t.error.message}):recordExpiryState(a,e,t.expiry);return a}function recordExpiryState(e,t,n){switch(n.state){case`expired`:e.expired.push(t);return;case`pending`:e.pending.push(t);return;case`unset`:e.unset.push(t);return;case`invalid`:e.unreadable.push({workspace:t,reason:`recorded expiry "${n.value}" is not a value this CLI wrote`})}}async function fetchAllWorkspaces(e){return Rr(async(t,n)=>{let{workspaces:r,nextPageToken:i}=await e.listWorkspaces({pageToken:t,pageSize:n});return[r,i]})}function compileNameRegex(e){try{return new RegExp(e),RegExp(`^(?:${e})$`)}catch(t){throw S({code:`INVALID_NAME_PATTERN`,message:`Invalid --name "${e}".`,details:t instanceof Error?t.message:String(t)})}}const Zo=[{key:`excluded`,selection:`excluded`,reason:`excluded by --exclude`},{key:`deleteProtection`,selection:`protectedSkipped`,reason:`delete protection is on`},{key:`unknownAge`,selection:`missingCreateTime`,reason:`creation time is unknown`}],Qo="Specify --organization-root, --folder-id, or --personal on the command line. The default organization/folder set by `tailor user update` is not used by prune.",$o=E({name:`prune`,description:`Delete stale temporary workspaces, by name and age or by the expiry each recorded at creation.`,notes:W`
120
124
  Use this to reclaim workspaces left behind by CI runs, preview deployments, or interrupted local test runs. A workspace is deleted only when its whole name matches a --name pattern, it was created at least --older-than ago, and it is not excluded, delete-protected, or outside the requested locations. Run with --dry-run first to see what would be deleted.
121
125
 
122
126
  With --expired the workspaces select themselves instead: each one is deleted only once the --ttl expiry it recorded at creation has passed, so callers need no --name or --older-than. A workspace that records no expiry is never deleted this way, and neither is one whose recorded expiry cannot be read. Because that expiry is recorded on the workspace rather than derived from its name, anything able to write the workspace's metadata can bring its deletion forward -- and writing a workspace's metadata is a lesser permission than deleting it. --expired therefore requires at least one location, and --name still applies on top.
@@ -130,14 +134,14 @@ Error:`));let e=formatErrorWithSourcemap(b.error,p,process.cwd());e?f.log(e):f.l
130
134
  Safety guards: the command aborts without deleting anything when more workspaces match than --limit allows (--dry-run still lists them all), both --expired and --older-than 0s (no age check) are only accepted together with at least one location option, and a location option that resolves to an empty value (an unset CI secret) is rejected instead of silently widening the sweep -- even when another location is given alongside it. Each workspace is re-read immediately before it is deleted and skipped when it no longer matches the name, location, exclusion, or delete-protection criteria that selected it. Unlike \`workspace delete\`, a single confirmation covers every listed candidate; pass --yes to skip it in CI. Deleted workspaces can be restored with \`workspace restore\` for a limited time.
131
135
 
132
136
  Only workspaces visible to the current login (or the machine user in CI) are considered.
133
- `,args:J.strictObject({name:G(J.array(J.string().min(1)).optional(),{description:`Select workspaces whose whole name matches this regular expression (repeatable)`}),"older-than":G(Qn.optional(),{description:`Minimum age since creation, such as 30m, 24h, or 7d. 0s disables the age check and requires a location. Required unless --expired is given`}),expired:G(J.boolean().default(!1),{description:`Select workspaces whose own --ttl expiry has passed, instead of by name and age. Requires --organization-root, --folder-id, or --personal`}),"organization-root":G(locationIdsArg(),{placeholder:`ORGANIZATION_ID`,description:`Consider the workspaces directly under this organization, excluding those in its folders (repeatable)`}),"folder-id":G(locationIdsArg(),{description:`Consider the workspaces in this folder (repeatable)`}),personal:G(J.boolean().default(!1),{description:`Consider the workspaces belonging to no organization and no folder`}),exclude:G(J.array(J.string().min(1)).optional(),{description:`Keep a workspace with this exact name even when it matches (repeatable)`}),limit:G(Uo.default(20),{description:`Abort when more workspaces match than this, without deleting anything. 0 removes the cap`}),"dry-run":G(J.boolean().default(!1),{description:`List the workspaces that would be deleted without deleting them`}),profile:G(Ye.optional(),{description:`Workspace profile used for authentication and Platform selection`,env:`TAILOR_PLATFORM_PROFILE`}),...I}),run:async e=>{let t=e.name??[],n=e[`older-than`];if(e.expired&&n!==void 0)throw W({code:`CONFLICTING_AGE_FILTER`,message:`--expired and --older-than cannot be combined.`,details:`--expired defers to the expiry each workspace recorded at creation, which --older-than would override.`});if(!e.expired&&n===void 0)throw W({code:`MISSING_AGE_FILTER`,message:`Specify --older-than, or --expired to use each workspace's recorded expiry.`});if(!e.expired&&t.length===0)throw W({code:`MISSING_NAME_FILTER`,message:`Specify at least one --name.`,details:`Only workspaces whose name matches the filter are considered for deletion.`});let r=e[`organization-root`]??[],i=e[`folder-id`]??[],a=[[`--organization-root`,r],[`--folder-id`,i]].filter(([,e])=>e.includes(``)).map(([e])=>e);if(a.length>0)throw W({code:`EMPTY_SCOPE`,message:`${a.join(` and `)} resolved to an empty value.`,details:`An empty location is indistinguishable from an omitted one, so the sweep would not cover what the caller meant. This usually means an unset CI secret.`,suggestion:`Set the id, or drop the option on purpose.`});let o=n===void 0?void 0:cr(n),s={nameRegexes:t.map(compileNameRegex),...o===void 0?{}:{olderThanMs:o},organizationRoots:r,folderIds:i,personal:e.personal,exclude:new Set(e.exclude??[])};if(e.expired&&!hasLocation(s))throw W({code:`UNSCOPED_EXPIRED`,message:`--expired requires --organization-root, --folder-id, or --personal.`,suggestion:Go,details:`The expiry lives on the workspace, and writing a workspace's metadata is a lesser permission than deleting it, so an unscoped sweep would delete on behalf of anyone able to write that metadata.`});if(o===0&&!hasLocation(s))throw W({code:`UNSCOPED_ZERO_AGE`,message:`--older-than 0s requires --organization-root, --folder-id, or --personal.`,suggestion:Go,details:`Without an age check the name filter is the only guard, so the sweep must name the organization roots, folders, or personal workspaces it covers.`});await z({profile:e.profile}),hasLocation(s)||f.warn(`No location was specified. Every workspace visible to this login is a candidate for the name and age filters. ${Go}`);let c=await nr({profile:e.profile}),l=await pn({profile:e.profile}),u=await Pr(c,l),d=/* @__PURE__ */ new Date,p=selectPruneCandidates(await fetchAllWorkspaces(u),s,d),m={dryRun:e[`dry-run`],candidates:[],deleted:[],failed:[],skipped:{excluded:[],deleteProtection:[],unknownAge:[],notExpired:[],noExpiry:[],unreadableExpiry:[],expiryChanged:[],changed:[]}};if(e.expired){let e=await partitionByExpiry(u,p.candidates,d);p.candidates=e.expired;for(let t of e.pending)m.skipped.notExpired.push(t.name);for(let t of e.unset)m.skipped.noExpiry.push(t.name);for(let{workspace:t,reason:n}of e.unreadable)m.skipped.unreadableExpiry.push(t.name),f.warn(`Keeping ${t.name} (${t.id}): ${n}.`);f.info(`${e.pending.length} workspace(s) have not expired and ${e.unset.length} record no expiry; both were kept.`)}for(let{key:e,selection:t,reason:n}of Wo)for(let r of p[t])m.skipped[e].push(r.name),f.warn(`Keeping ${r.name} (${r.id}): ${n}.`);if(p.tooYoung.length>0&&f.info(`${p.tooYoung.length} matching workspace(s) are younger than ${e[`older-than`]} and were kept.`),p.candidates.length===0){f.info(`No stale workspaces matched.`),f.jsonMode&&f.out(m);return}let h=e.limit>0&&p.candidates.length>e.limit;if(h&&!e[`dry-run`])throw W({code:`PRUNE_LIMIT_EXCEEDED`,message:`${p.candidates.length} workspaces matched, but --limit is ${e.limit}. Nothing was deleted.`,details:`A match count this high usually means the name filter is broader than intended.`,suggestion:`Check the filter with --dry-run, then raise --limit (or pass --limit 0) if every match should be deleted.`});if(m.candidates=await Ft(u,p.candidates),f.jsonMode||f.out(m.candidates,{display:{name:hn,folderName:null,organizationId:null,folderId:null,updatedAt:null}}),e[`dry-run`]){h&&f.warn(`${m.candidates.length} workspaces matched, but --limit is ${e.limit}: a real run would abort without deleting anything.`),f.info(`Dry run: ${m.candidates.length} workspace(s) would be deleted.`),f.jsonMode&&f.out(m);return}if(!e.yes&&!await P.confirm({message:`Delete these ${m.candidates.length} workspace(s)? They can be restored with "tailor workspace restore" for a limited time.`,default:!1}))throw W({code:`PRUNE_CANCELLED`,message:`Prune cancelled. No workspaces were deleted.`});let g=/* @__PURE__ */ new Set;for(let t of m.candidates){let n=Vn(t);try{let{workspace:r}=await u.getWorkspace({workspaceId:t.id}),i=r?staleCandidateReason(r,s):void 0;if(i){m.skipped.changed.push(t.name),f.warn(`Keeping ${n} (${t.id}): ${i}.`);continue}if(e.expired){let e=await $t(u,t.id,/* @__PURE__ */ new Date);if(`error`in e&&e.error instanceof Q&&e.error.code===Z.NotFound)throw e.error;if((`error`in e?`unreadable`:e.expiry.state)!==`expired`){m.skipped.expiryChanged.push(n),f.info(`Skipped ${n} (${t.id}): its recorded expiry no longer selects it.`);continue}}g.add(t.id),await u.deleteWorkspace({workspaceId:t.id}),m.deleted.push(t),f.success(`Deleted ${n} (${t.id}).`)}catch(e){if(e instanceof Q&&e.code===Z.NotFound){g.add(t.id),m.deleted.push(t),f.info(`${n} (${t.id}) was already deleted.`);continue}let r=e instanceof Error?e.message:String(e);m.failed.push({workspace:t,error:r}),f.error(`Failed to delete ${n} (${t.id}): ${r}`)}}let _=await kt(g);if(_.length>0&&f.info(`Removed ${_.length} local profile(s) that pointed at deleted workspaces: ${_.join(`, `)}.`),f.jsonMode&&f.out(m),f.success(`Deleted ${m.deleted.length} workspace(s).`),m.failed.length>0)throw W({code:`PRUNE_INCOMPLETE`,message:`Failed to delete ${m.failed.length} workspace(s).`,suggestion:`Fix the reported errors and run the command again; deleted workspaces are not retried.`})}}),qo=J.object({workspaceId:J.uuid({message:`workspace-id must be a valid UUID`}).optional(),profile:J.string().optional()});async function clearWorkspaceTtl(e){let t=S(qo,e),{client:n,workspaceId:r}=await j({profile:t.profile,workspaceId:t.workspaceId});return{workspaceId:r,changed:await Mn(n,r)}}const Jo=C({name:`clear`,description:`Drop a workspace's recorded prune expiry.`,notes:`
137
+ `,args:J.strictObject({name:G(J.array(J.string().min(1)).optional(),{description:`Select workspaces whose whole name matches this regular expression (repeatable)`}),"older-than":G(vr.optional(),{description:`Minimum age since creation, such as 30m, 24h, or 7d. 0s disables the age check and requires a location. Required unless --expired is given`}),expired:G(J.boolean().default(!1),{description:`Select workspaces whose own --ttl expiry has passed, instead of by name and age. Requires --organization-root, --folder-id, or --personal`}),"organization-root":G(locationIdsArg(),{placeholder:`ORGANIZATION_ID`,description:`Consider the workspaces directly under this organization, excluding those in its folders (repeatable)`}),"folder-id":G(locationIdsArg(),{description:`Consider the workspaces in this folder (repeatable)`}),personal:G(J.boolean().default(!1),{description:`Consider the workspaces belonging to no organization and no folder`}),exclude:G(J.array(J.string().min(1)).optional(),{description:`Keep a workspace with this exact name even when it matches (repeatable)`}),limit:G(Xo.default(20),{description:`Abort when more workspaces match than this, without deleting anything. 0 removes the cap`}),"dry-run":G(J.boolean().default(!1),{description:`List the workspaces that would be deleted without deleting them`}),profile:G(re.optional(),{description:`Workspace profile used for authentication and Platform selection`,env:`TAILOR_PLATFORM_PROFILE`}),...k}),run:async e=>{let t=e.name??[],n=e[`older-than`];if(e.expired&&n!==void 0)throw S({code:`CONFLICTING_AGE_FILTER`,message:`--expired and --older-than cannot be combined.`,details:`--expired defers to the expiry each workspace recorded at creation, which --older-than would override.`});if(!e.expired&&n===void 0)throw S({code:`MISSING_AGE_FILTER`,message:`Specify --older-than, or --expired to use each workspace's recorded expiry.`});if(!e.expired&&t.length===0)throw S({code:`MISSING_NAME_FILTER`,message:`Specify at least one --name.`,details:`Only workspaces whose name matches the filter are considered for deletion.`});let r=e[`organization-root`]??[],i=e[`folder-id`]??[],a=[[`--organization-root`,r],[`--folder-id`,i]].filter(([,e])=>e.includes(``)).map(([e])=>e);if(a.length>0)throw S({code:`EMPTY_SCOPE`,message:`${a.join(` and `)} resolved to an empty value.`,details:`An empty location is indistinguishable from an omitted one, so the sweep would not cover what the caller meant. This usually means an unset CI secret.`,suggestion:`Set the id, or drop the option on purpose.`});let o=n===void 0?void 0:It(n),s={nameRegexes:t.map(compileNameRegex),...o===void 0?{}:{olderThanMs:o},organizationRoots:r,folderIds:i,personal:e.personal,exclude:new Set(e.exclude??[])};if(e.expired&&!hasLocation(s))throw S({code:`UNSCOPED_EXPIRED`,message:`--expired requires --organization-root, --folder-id, or --personal.`,suggestion:Qo,details:`The expiry lives on the workspace, and writing a workspace's metadata is a lesser permission than deleting it, so an unscoped sweep would delete on behalf of anyone able to write that metadata.`});if(o===0&&!hasLocation(s))throw S({code:`UNSCOPED_ZERO_AGE`,message:`--older-than 0s requires --organization-root, --folder-id, or --personal.`,suggestion:Qo,details:`Without an age check the name filter is the only guard, so the sweep must name the organization roots, folders, or personal workspaces it covers.`});await T({profile:e.profile}),hasLocation(s)||m.warn(`No location was specified. Every workspace visible to this login is a candidate for the name and age filters. ${Qo}`);let c=await yn({profile:e.profile}),l=await Ge({profile:e.profile}),u=await Kr(c,l),d=/* @__PURE__ */ new Date,f=selectPruneCandidates(await fetchAllWorkspaces(u),s,d),p={dryRun:e[`dry-run`],candidates:[],deleted:[],failed:[],skipped:{excluded:[],deleteProtection:[],unknownAge:[],notExpired:[],noExpiry:[],unreadableExpiry:[],expiryChanged:[],changed:[]}};if(e.expired){let e=await partitionByExpiry(u,f.candidates,d);f.candidates=e.expired;for(let t of e.pending)p.skipped.notExpired.push(t.name);for(let t of e.unset)p.skipped.noExpiry.push(t.name);for(let{workspace:t,reason:n}of e.unreadable)p.skipped.unreadableExpiry.push(t.name),m.warn(`Keeping ${t.name} (${t.id}): ${n}.`);m.info(`${e.pending.length} workspace(s) have not expired and ${e.unset.length} record no expiry; both were kept.`)}for(let{key:e,selection:t,reason:n}of Zo)for(let r of f[t])p.skipped[e].push(r.name),m.warn(`Keeping ${r.name} (${r.id}): ${n}.`);if(f.tooYoung.length>0&&m.info(`${f.tooYoung.length} matching workspace(s) are younger than ${e[`older-than`]} and were kept.`),f.candidates.length===0){m.info(`No stale workspaces matched.`),m.jsonMode&&m.out(p);return}let h=e.limit>0&&f.candidates.length>e.limit;if(h&&!e[`dry-run`])throw S({code:`PRUNE_LIMIT_EXCEEDED`,message:`${f.candidates.length} workspaces matched, but --limit is ${e.limit}. Nothing was deleted.`,details:`A match count this high usually means the name filter is broader than intended.`,suggestion:`Check the filter with --dry-run, then raise --limit (or pass --limit 0) if every match should be deleted.`});if(p.candidates=await Cn(u,f.candidates),m.jsonMode||m.out(p.candidates,{display:{name:sr,folderName:null,organizationId:null,folderId:null,updatedAt:null}}),e[`dry-run`]){h&&m.warn(`${p.candidates.length} workspaces matched, but --limit is ${e.limit}: a real run would abort without deleting anything.`),m.info(`Dry run: ${p.candidates.length} workspace(s) would be deleted.`),m.jsonMode&&m.out(p);return}if(!e.yes&&!await H.confirm({message:`Delete these ${p.candidates.length} workspace(s)? They can be restored with "tailor workspace restore" for a limited time.`,default:!1}))throw S({code:`PRUNE_CANCELLED`,message:`Prune cancelled. No workspaces were deleted.`});let g=/* @__PURE__ */ new Set;for(let t of p.candidates){let n=Vt(t);try{let{workspace:r}=await u.getWorkspace({workspaceId:t.id}),i=r?staleCandidateReason(r,s):void 0;if(i){p.skipped.changed.push(t.name),m.warn(`Keeping ${n} (${t.id}): ${i}.`);continue}if(e.expired){let e=await Dt(u,t.id,/* @__PURE__ */ new Date);if(`error`in e&&e.error instanceof Q&&e.error.code===Z.NotFound)throw e.error;if((`error`in e?`unreadable`:e.expiry.state)!==`expired`){p.skipped.expiryChanged.push(n),m.info(`Skipped ${n} (${t.id}): its recorded expiry no longer selects it.`);continue}}g.add(t.id),await u.deleteWorkspace({workspaceId:t.id}),p.deleted.push(t),m.success(`Deleted ${n} (${t.id}).`)}catch(e){if(e instanceof Q&&e.code===Z.NotFound){g.add(t.id),p.deleted.push(t),m.info(`${n} (${t.id}) was already deleted.`);continue}let r=e instanceof Error?e.message:String(e);p.failed.push({workspace:t,error:r}),m.error(`Failed to delete ${n} (${t.id}): ${r}`)}}let _=await Ft(g);if(_.length>0&&m.info(`Removed ${_.length} local profile(s) that pointed at deleted workspaces: ${_.join(`, `)}.`),m.jsonMode&&m.out(p),m.success(`Deleted ${p.deleted.length} workspace(s).`),p.failed.length>0)throw S({code:`PRUNE_INCOMPLETE`,message:`Failed to delete ${p.failed.length} workspace(s).`,suggestion:`Fix the reported errors and run the command again; deleted workspaces are not retried.`})}}),es=J.object({workspaceId:J.uuid({message:`workspace-id must be a valid UUID`}).optional(),profile:J.string().optional()});async function clearWorkspaceTtl(e){let t=mr(es,e),{client:n,workspaceId:r}=await j({profile:t.profile,workspaceId:t.workspaceId});return{workspaceId:r,changed:await Dn(n,r)}}const ts=E({name:`clear`,description:`Drop a workspace's recorded prune expiry.`,notes:`
134
138
  A workspace recording no expiry is never deleted by \`workspace prune --expired\`. Clearing an expiry the workspace does not record succeeds without changing anything.
135
- `,args:J.strictObject({...N}),run:async e=>{await z({profile:e.profile});let{workspaceId:t,changed:n}=await clearWorkspaceTtl({workspaceId:e[`workspace-id`],profile:e.profile});f.success(`Workspace records no prune expiry.`),A({changed:n,workspaceId:t,expiresAt:null})}}),Yo=J.object({workspaceId:J.uuid({message:`workspace-id must be a valid UUID`}).optional(),profile:J.string().optional(),ttl:Qn});async function setWorkspaceTtl(e){let t=S(Yo,e),{client:n,workspaceId:r}=await j({profile:t.profile,workspaceId:t.workspaceId}),i=new Date(Date.now()+cr(t.ttl));return{workspaceId:r,expiresAt:i,changed:await Ct(n,r,i)}}const Xo=C({name:`set`,description:`Record when a workspace becomes prunable, replacing any expiry it already records.`,notes:"\n The expiry runs from now, not from when the workspace was created, so `--ttl 24h` always leaves a full day regardless of the workspace's age. Use this to give a restored workspace a new expiry, or to record one after `workspace create --ttl` failed to.\n\n This is not an auto-delete timer: it only makes the workspace eligible for `workspace prune --expired`, which still honors delete protection and its own filters.\n ",args:J.strictObject({...N,ttl:G(Qn,{description:`Time from now until the workspace becomes prunable, such as 30m, 24h, or 7d`})}),run:async e=>{await z({profile:e.profile});let{workspaceId:t,expiresAt:n,changed:r}=await setWorkspaceTtl({workspaceId:e[`workspace-id`],profile:e.profile,ttl:e.ttl});f.success(`Workspace becomes prunable at ${n.toISOString()}.`);let i=s(vn(nn(n)),`encoded workspace expiry must decode`);A({changed:r,workspaceId:t,expiresAt:i.toISOString()})}}),Zo=K({name:`ttl`,description:`Manage when a workspace becomes prunable.`,subCommands:{set:Xo,clear:Jo},async run(){await tt(Zo,[`--help`])}}),Qo=K({name:`user`,description:`Manage workspace users`,subCommands:{invite:qt,list:qn,remove:Mt,update:Dn},defaultSubCommand:`list`}),$o=K({name:`workspace`,description:`Manage Tailor Platform workspaces.`,subCommands:{app:Ho,create:sn,delete:Zn,get:Qt,list:wn,prune:Ko,restore:_n,ttl:Zo,user:Qo},defaultSubCommand:`list`});await Un(new URL(`./ts-hook.mjs`,import.meta.url)),ci();const es=await ti(),ts=Object.keys(es.bin??{})[0]||`tailor`,ns=es.name??`@tailor-platform/sdk`,rs=await bi(import.meta.url),is=yi(vi(rs),`agent-skills`),as=yi(vi(rs),`docs`,`cli-reference.md`),os=`AI coding agent detected:
139
+ `,args:J.strictObject({...P}),run:async e=>{await T({profile:e.profile});let{workspaceId:t,changed:n}=await clearWorkspaceTtl({workspaceId:e[`workspace-id`],profile:e.profile});m.success(`Workspace records no prune expiry.`),V({changed:n,workspaceId:t,expiresAt:null})}}),ns=J.object({workspaceId:J.uuid({message:`workspace-id must be a valid UUID`}).optional(),profile:J.string().optional(),ttl:vr});async function setWorkspaceTtl(e){let t=mr(ns,e),{client:n,workspaceId:r}=await j({profile:t.profile,workspaceId:t.workspaceId}),i=new Date(Date.now()+It(t.ttl));return{workspaceId:r,expiresAt:i,changed:await ur(n,r,i)}}const rs=E({name:`set`,description:`Record when a workspace becomes prunable, replacing any expiry it already records.`,notes:"\n The expiry runs from now, not from when the workspace was created, so `--ttl 24h` always leaves a full day regardless of the workspace's age. Use this to give a restored workspace a new expiry, or to record one after `workspace create --ttl` failed to.\n\n This is not an auto-delete timer: it only makes the workspace eligible for `workspace prune --expired`, which still honors delete protection and its own filters.\n ",args:J.strictObject({...P,ttl:G(vr,{description:`Time from now until the workspace becomes prunable, such as 30m, 24h, or 7d`})}),run:async e=>{await T({profile:e.profile});let{workspaceId:t,expiresAt:n,changed:r}=await setWorkspaceTtl({workspaceId:e[`workspace-id`],profile:e.profile,ttl:e.ttl});m.success(`Workspace becomes prunable at ${n.toISOString()}.`);let i=s(dn(sn(n)),`encoded workspace expiry must decode`);V({changed:r,workspaceId:t,expiresAt:i.toISOString()})}}),is=K({name:`ttl`,description:`Manage when a workspace becomes prunable.`,subCommands:{set:rs,clear:ts}}),as=K({name:`user`,description:`Manage workspace users`,subCommands:{invite:$t,list:ar,remove:Rt,update:In},defaultSubCommand:`list`}),os=K({name:`workspace`,description:`Manage Tailor Platform workspaces.`,subCommands:{app:Yo,create:Nt,delete:lr,get:an,list:Yn,prune:$o,restore:Tn,ttl:is,user:as},defaultSubCommand:`list`});await er(new URL(`./ts-hook.mjs`,import.meta.url)),gi();const ss=await li(),cs=Object.keys(ss.bin??{})[0]||`tailor`,ls=ss.name??`@tailor-platform/sdk`,us=await Oi(import.meta.url),ds=Di(Ei(us),`agent-skills`),fs=Di(Ei(us),`docs`,`cli-reference.md`),ps=`AI coding agent detected:
136
140
 
137
- - Unless \`--json=false\` or \`${m}=false\` is set, commands that return structured results print JSON to stdout. Parse it instead of the table output, which is formatted for humans and may change.
138
- - CLI plugin commands keep the table unless you pass \`--json\` or set \`${m}=true\`.
141
+ - Unless \`--json=false\` or \`${_}=false\` is set, commands that return structured results print JSON to stdout. Parse it instead of the table output, which is formatted for humans and may change.
142
+ - CLI plugin commands keep the table unless you pass \`--json\` or set \`${_}=true\`.
139
143
  - Pass \`--help-json\` to a command for machine-readable help.
140
- - Full command reference: \`${as}\``;function defaultSkillsRunToAdd(e){let{run:t,...n}=e;return{...n,defaultSubCommand:`add`}}const ss=_i(K({name:ts,description:es.description||`Tailor CLI for managing Tailor Platform SDK applications`,notes:`CLI plugins (beta): an unknown subcommand is dispatched to an external plugin executable named \`${ts}-<name>\` (found on your PATH or in node_modules/.bin), similar to \`gh\` extensions.
141
- Run \`${ts} plugin list\` to see which plugins are installed and where they resolve from.
142
- The \`setup\` commands are provided by the @tailor-platform/sdk-plugin-setup CLI plugin.`,subCommands:{api:Ji,auth:Zi,authconnection:ca,crashreport:da,data:_a,deploy:va,executor:ya,function:ka,generate:Aa,init:ja,login:Pa,logout:Fa,machineuser:Ia,oauth2client:La,open:Ra,organization:Ba,plugin:Ga,profile:Xa,query:Tt,remove:at,secret:lo,show:ur,staticwebsite:_o,tailordb:Do,upgrade:Oo,user:Bo,workflow:Vo,workspace:$o}}),{sourceDir:is,package:ns,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.`}}),cs=gi({...ss,subCommands:{...ss.subCommands,skills:defaultSkillsRunToAdd(ss.subCommands.skills)}});mi(cs,{version:es.version,globalArgs:J.object(de),displayErrors:!1,agentHelp:os,setup:({agent:e})=>{p(e?.id)},onUnknownSubcommand:({commandPath:e,name:t,args:n,precedingArgs:r})=>dispatchPluginWithInstallHint({commandPath:e,name:t,args:[...r,...n],cliName:ts,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{cs as mainCommand};
144
+ - Full command reference: \`${fs}\``;function defaultSkillsRunToAdd(e){let{run:t,...n}=e;return{...n,defaultSubCommand:`add`}}const ms=Ti(K({name:cs,description:ss.description||`Tailor CLI for managing Tailor Platform SDK applications`,notes:`CLI plugins (beta): an unknown subcommand is dispatched to an external plugin executable named \`${cs}-<name>\` (found on your PATH or in node_modules/.bin), similar to \`gh\` extensions.
145
+ Run \`${cs} plugin list\` to see which plugins are installed and where they resolve from.
146
+ The \`setup\` commands are provided by the @tailor-platform/sdk-plugin-setup CLI plugin.`,subCommands:{api:na,auth:aa,authconnection:ga,crashreport:ya,data:Ta,deploy:Ea,executor:Da,function:Ia,generate:La,init:Ra,login:Va,logout:Ha,machineuser:Ua,oauth2client:Wa,open:Ga,organization:qa,plugin:Qa,profile:ro,query:At,remove:ut,secret:_o,show:xr,staticwebsite:wo,tailordb:Po,upgrade:Fo,user:qo,workflow:Jo,workspace:os}}),{sourceDir:ds,package:ls,mode:`copy`,descriptionAppend:!1,globalArgs:J.strictObject(vt),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.`}}),hs=wi({...ms,subCommands:{...ms.subCommands,skills:defaultSkillsRunToAdd(ms.subCommands.skills)}});Si(hs,{version:ss.version,globalArgs:J.strictObject(vt),displayErrors:!1,agentHelp:ps,setup:({agent:e})=>{h(e?.id)},onUnknownSubcommand:({commandPath:e,name:t,args:n,precedingArgs:r})=>dispatchPluginWithInstallHint({commandPath:e,name:t,args:[...r,...n],cliName:cs,profile:process.env.TAILOR_PLATFORM_PROFILE}),cleanup:async({error:e})=>{if(e){qn()||Wt(e,process.argv.slice(2));let t;if(m.jsonMode?m.log(ln(e,{includeStack:m.verbose})):p(e)?(m.log(e.format()),m.verbose&&e.stack&&m.debug(`\nStack trace:\n${e.stack}`)):e instanceof Error?(m.error(e.message),t=u(e).suggestion??x(e),t&&m.log(` ${f.info(`Suggestion:`)} ${t}`),m.verbose&&e.stack&&m.debug(`\nStack trace:\n${e.stack}`)):m.error(`Unknown error: ${e}`),An(e,{jsonMode:m.jsonMode,suggestion:t}),!p(e)&&(!(e instanceof Error)||e instanceof TypeError||e instanceof RangeError)){let{reportCrash:t}=await import(`../crashreport-WsYAWARW.mjs`);await t(e,`handledError`)}}let{shutdownTelemetry:t}=await import(`../telemetry-nqOtDWNO.mjs`);await t()}});export{hs as mainCommand};
143
147
  //# sourceMappingURL=main.mjs.map