@customyai/cli 0.1.1 → 0.6.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.
@@ -0,0 +1,1102 @@
1
+ 'use strict';
2
+
3
+ var zod = require('zod');
4
+ var promises = require('fs/promises');
5
+ var path3 = require('path');
6
+ var provisioning = require('@customyai/provisioning');
7
+
8
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
9
+
10
+ var path3__default = /*#__PURE__*/_interopDefault(path3);
11
+
12
+ // src/codegen.ts
13
+ var literal = (value) => JSON.stringify(value);
14
+ var union = (values) => values.length ? values.map(literal).join(" | ") : "never";
15
+ var key = (name) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : literal(name);
16
+ function schemaToType(schema, indent = "") {
17
+ if (!schema || typeof schema !== "object") return "unknown";
18
+ if (Array.isArray(schema.enum)) return schema.enum.length ? schema.enum.map(literal).join(" | ") : "never";
19
+ const types = Array.isArray(schema.type) ? schema.type : schema.type ? [schema.type] : [];
20
+ if (types.length > 1) return types.map((type) => schemaToType({ ...schema, type }, indent)).join(" | ");
21
+ switch (types[0]) {
22
+ case "string":
23
+ return "string";
24
+ case "number":
25
+ case "integer":
26
+ return "number";
27
+ case "boolean":
28
+ return "boolean";
29
+ case "null":
30
+ return "null";
31
+ case "array":
32
+ return `Array<${schemaToType(schema.items, indent)}>`;
33
+ case "object": {
34
+ const required2 = new Set(schema.required ?? []);
35
+ const inner = `${indent} `;
36
+ const fields = Object.entries(schema.properties ?? {}).map(([name, value]) => `${inner}${key(name)}${required2.has(name) ? "" : "?"}: ${schemaToType(value, inner)};`);
37
+ if (schema.additionalProperties !== false && !schema.properties) return "Record<string, unknown>";
38
+ return fields.length ? `{
39
+ ${fields.join("\n")}
40
+ ${indent}}` : "Record<string, never>";
41
+ }
42
+ default:
43
+ return "unknown";
44
+ }
45
+ }
46
+ function generateAppTypes(manifest) {
47
+ const roles = manifest.roles ?? [];
48
+ const permissions = (manifest.permissions ?? []).map((permission) => permission.key);
49
+ const events = manifest.events.map((event) => ` ${literal(event.name)}: ${schemaToType(event.properties, " ")};`);
50
+ return [
51
+ `// Generado por \`customy apps codegen\` desde customy.app.json (${manifest.key}). No editar a mano.`,
52
+ "",
53
+ `export type CustomyEventName = ${union(manifest.events.map((event) => event.name))};`,
54
+ "",
55
+ "export type CustomyEventProperties = {",
56
+ ...events,
57
+ "};",
58
+ "",
59
+ `export type CustomyCapability = ${union(manifest.capabilities.map((capability) => capability.lookupKey))};`,
60
+ `export type CustomyPlan = ${union(manifest.plans.map((plan2) => plan2.code))};`,
61
+ `export type CustomyMeter = ${union(manifest.meters.map((meter) => meter.code))};`,
62
+ "",
63
+ "/** Permisos y roles del manifiesto (`permissions[]`, `roles[]`): la app pregunta por permisos y nunca escribe un nombre de rol. */",
64
+ `export type CustomyPermission = ${union(permissions)};`,
65
+ `export type CustomyRole = ${union(roles.map((role) => role.key))};`,
66
+ "",
67
+ "/** Lo que da cada rol, tal como lo declara el manifiesto. */",
68
+ `export const CUSTOMY_ROLE_PERMISSIONS = {
69
+ ${roles.map((role) => ` ${literal(role.key)}: ${literal(role.permissions)},`).join("\n")}
70
+ } as const satisfies Record<CustomyRole, readonly CustomyPermission[]>;`,
71
+ "",
72
+ "/** Los tipos de la app juntos: `createCustomy<CustomyAppTypes>()`, `createAccess<CustomyCapability, CustomyRole, CustomyPermission>()`. */",
73
+ "export type CustomyAppTypes = {",
74
+ " events: CustomyEventProperties;",
75
+ " meters: CustomyMeter;",
76
+ " capabilities: CustomyCapability;",
77
+ " roles: CustomyRole;",
78
+ " permissions: CustomyPermission;",
79
+ "};",
80
+ "",
81
+ "/** Prop\xF3sitos de consentimiento que exige cada evento. */",
82
+ `export const CUSTOMY_EVENT_PURPOSES = {
83
+ ${manifest.events.map((event) => ` ${literal(event.name)}: ${literal(event.purposes)},`).join("\n")}
84
+ } as const;`,
85
+ ""
86
+ ].join("\n");
87
+ }
88
+ var EntitlementMeterAggregationSchema = zod.z.enum(["sum", "count", "last"]);
89
+ var identifier = zod.z.string().regex(/^[a-z][a-z0-9-]{1,62}$/);
90
+ var ConnectedOperationSchema = zod.z.enum([
91
+ "read",
92
+ "propose",
93
+ "submit",
94
+ "read_owned",
95
+ "write_owned",
96
+ "research",
97
+ "deliver_budget_alert",
98
+ "deliver_notification",
99
+ "request_operator_approval"
100
+ ]);
101
+ var ConnectedBindingKindSchema = zod.z.enum([
102
+ "product",
103
+ "internal_service",
104
+ "external_destination",
105
+ "public_form",
106
+ "private_collection",
107
+ "external_source",
108
+ "external_automation",
109
+ "external_communication"
110
+ ]);
111
+ var ProductBindingSchema = zod.z.object({
112
+ kind: ConnectedBindingKindSchema,
113
+ /** Claves de recurso admitidas; sin lista, cualquiera. Son nombres del producto, nunca de apps. */
114
+ keys: zod.z.array(identifier).min(1).optional(),
115
+ /** Patrón que debe cumplir el identificador del recurso en el producto. */
116
+ resourceIdPattern: zod.z.string().min(1).optional(),
117
+ operations: zod.z.object({
118
+ allowed: zod.z.array(ConnectedOperationSchema).max(4),
119
+ /** exact: exactamente `allowed`; subset: un subconjunto no vacío. */
120
+ mode: zod.z.enum(["exact", "subset"]),
121
+ /** false: las operaciones pueden omitirse (si se dan, cumplen el modo). */
122
+ required: zod.z.boolean().default(true)
123
+ }).strict().optional(),
124
+ maxPerConnection: zod.z.number().int().positive().optional()
125
+ }).strict();
126
+ var ProductManifestSchema = zod.z.object({
127
+ schema: zod.z.literal("product/v1"),
128
+ key: zod.z.string().regex(/^customy-[a-z][a-z0-9-]*$/),
129
+ /** Audiencia de sus tokens de máquina (discovery). */
130
+ audience: zod.z.string().regex(/^customy-[a-z][a-z0-9-]*$/),
131
+ /** Si true, todo enlace debe declarar `bindingKind` (no admite el enlace implícito). */
132
+ bindingRequired: zod.z.boolean().default(false),
133
+ bindings: zod.z.array(ProductBindingSchema).default([]),
134
+ /** Productos a los que llama en nombre de una app (token exchange). Solo esos lo aceptan como actor. */
135
+ requires: zod.z.array(zod.z.string().regex(/^customy-[a-z][a-z0-9-]*$/)).default([])
136
+ }).strict().superRefine((manifest, context2) => {
137
+ const kinds = manifest.bindings.map((binding) => binding.kind);
138
+ if (new Set(kinds).size !== kinds.length) context2.addIssue({ code: zod.z.ZodIssueCode.custom, message: "Binding kinds must be unique per product" });
139
+ if (manifest.requires.includes(manifest.key)) context2.addIssue({ code: zod.z.ZodIssueCode.custom, message: "A product cannot require itself" });
140
+ });
141
+ var product = (key2, bindings = [], bindingRequired = false, requires = []) => ProductManifestSchema.parse({ schema: "product/v1", key: key2, audience: key2, bindingRequired, bindings, requires });
142
+ var CONNECTABLE_PRODUCT_MANIFESTS = [
143
+ product("customy-atlas", [{ kind: "internal_service", operations: { allowed: ["read", "propose"], mode: "subset" } }]),
144
+ product("customy-tables", [{ kind: "private_collection", keys: ["favorites", "comparisons", "preferences"], operations: { allowed: ["read_owned", "write_owned"], mode: "subset" } }]),
145
+ product("customy-agent", [{ kind: "external_automation", keys: ["catalog-updater"], operations: { allowed: ["research", "deliver_budget_alert"], mode: "subset" } }]),
146
+ product("customy-forms", [{ kind: "public_form", keys: ["subscription", "contact", "commercial"], resourceIdPattern: "^frm_[a-zA-Z0-9_-]+$", operations: { allowed: ["read", "submit"], mode: "exact" } }], false, ["customy-links"]),
147
+ product("customy-crm"),
148
+ product("customy-content", [{ kind: "external_destination", operations: { allowed: ["read"], mode: "exact" } }]),
149
+ product("customy-storage"),
150
+ product("customy-data", [{ kind: "external_source", keys: ["analytics-source"], operations: { allowed: ["submit"], mode: "exact" } }]),
151
+ // Experiments: las apps conectadas lo referencian para evaluar flags con su clave publicable; sin enlaces propios todavía (F5).
152
+ product("customy-experiments"),
153
+ product("customy-analytics"),
154
+ product("customy-campaigns", [{ kind: "external_communication", keys: ["weekly-brief"], operations: { allowed: ["read"], mode: "exact" } }]),
155
+ product("customy-engagement", [{ kind: "external_communication", keys: ["notification-delivery", "operator-approval"], operations: { allowed: ["deliver_notification", "request_operator_approval"], mode: "subset" } }]),
156
+ // Una referencia de solo lectura a un sitio de Pages del Workspace; no concede edición ni publicación.
157
+ product("customy-pages", [{ kind: "product", resourceIdPattern: "^[0-9]{6,20}$", operations: { allowed: ["read"], mode: "exact", required: false }, maxPerConnection: 1 }], true),
158
+ // La clave pública identifica el sitio SiteSight enlazado por un administrador del Workspace.
159
+ // Es una referencia publicable; Access comprueba el producto y el entorno propietario.
160
+ product("customy-sitesight", [{ kind: "product", keys: ["sitesight-site"], resourceIdPattern: "^ss_pub_[a-z0-9]{2,16}_[a-f0-9]{32}$", operations: { allowed: ["read"], mode: "exact" }, maxPerConnection: 1 }], true)
161
+ ];
162
+ function connectedResourceViolation(resource, manifests = CONNECTABLE_PRODUCT_MANIFESTS) {
163
+ const manifest = manifests.find((entry) => entry.key === resource.productKey);
164
+ if (!manifest) return "PRODUCT_NOT_CONNECTABLE";
165
+ if (manifest.bindingRequired && !resource.bindingKind) return "BINDING_KIND_REQUIRED";
166
+ const binding = resource.bindingKind ? manifest.bindings.find((entry) => entry.kind === resource.bindingKind) : void 0;
167
+ if (!binding) {
168
+ const plainReference = resource.bindingKind === void 0 || resource.bindingKind === "product";
169
+ if (plainReference && !resource.operations) return null;
170
+ return plainReference ? "OPERATIONS_REQUIRE_BINDING" : "BINDING_NOT_OFFERED";
171
+ }
172
+ if (binding.keys && !binding.keys.includes(resource.key)) return "BINDING_KEY_NOT_ALLOWED";
173
+ if (binding.resourceIdPattern && !new RegExp(binding.resourceIdPattern).test(resource.resourceId)) return "BINDING_RESOURCE_ID_INVALID";
174
+ const rule = binding.operations;
175
+ const operations = resource.operations;
176
+ if (!rule) return operations ? "OPERATIONS_REQUIRE_BINDING" : null;
177
+ if (!operations || operations.length === 0) return rule.required ? "BINDING_OPERATIONS_REQUIRED" : null;
178
+ if (operations.some((operation) => !rule.allowed.includes(operation))) return "BINDING_OPERATION_NOT_ALLOWED";
179
+ if (rule.mode === "exact" && (operations.length !== rule.allowed.length || rule.allowed.some((operation) => !operations.includes(operation)))) return "BINDING_OPERATIONS_MISMATCH";
180
+ return null;
181
+ }
182
+ function connectedResourceLimit(productKey2, manifests = CONNECTABLE_PRODUCT_MANIFESTS) {
183
+ const limits = manifests.find((entry) => entry.key === productKey2)?.bindings.map((binding) => binding.maxPerConnection).filter((value) => value !== void 0) ?? [];
184
+ return limits.length ? Math.min(...limits) : null;
185
+ }
186
+
187
+ // src/vendor/app-manifest.ts
188
+ var slug = zod.z.string().regex(/^[a-z][a-z0-9-]{1,38}[a-z0-9]$/);
189
+ var productKey = zod.z.string().regex(/^customy-[a-z][a-z0-9-]*$/);
190
+ var httpsOrigin = zod.z.string().url().max(512).refine((value) => {
191
+ const url = new URL(value);
192
+ return url.origin === value && (url.protocol === "https:" || ["localhost", "127.0.0.1"].includes(url.hostname));
193
+ }, "Origins must be bare https origins");
194
+ var eventName = zod.z.string().regex(/^[a-z][a-z0-9_.:-]{0,199}$/);
195
+ var lookupKey = zod.z.string().regex(/^[a-z][a-z0-9_.:-]{0,79}$/);
196
+ var AppProductUseSchema = zod.z.object({
197
+ product: productKey,
198
+ /** Scopes de producto que pedirán sus credenciales de máquina (`<producto>:<scope>`). */
199
+ scopes: zod.z.array(zod.z.string().regex(/^[a-z][a-z0-9_-]*:[a-z0-9_:.-]+$/)).max(64).default([])
200
+ }).strict();
201
+ var AppResourceSchema = zod.z.object({
202
+ key: zod.z.string().regex(/^[a-z][a-z0-9-]{1,62}$/),
203
+ product: productKey,
204
+ bindingKind: ConnectedBindingKindSchema.optional(),
205
+ operations: zod.z.array(ConnectedOperationSchema).min(1).max(2).optional()
206
+ }).strict();
207
+ var AppEventSchema = zod.z.object({
208
+ name: eventName,
209
+ type: zod.z.enum(["track", "identify", "group", "page", "screen", "alias"]),
210
+ schemaVersion: zod.z.number().int().positive(),
211
+ /** JSON Schema de `properties`; se publica como schema fijado del evento. */
212
+ properties: zod.z.record(zod.z.unknown()).default({ type: "object" }),
213
+ purposes: zod.z.array(zod.z.string().regex(/^[a-z][a-z0-9_.:-]{0,79}$/)).min(1).max(8)
214
+ }).strict();
215
+ var AppCapabilitySchema = zod.z.object({
216
+ lookupKey,
217
+ name: zod.z.string().min(1).max(120),
218
+ type: zod.z.enum(["boolean", "metered", "config"]),
219
+ meter: lookupKey.optional()
220
+ }).strict();
221
+ var AppPlanSchema = zod.z.object({
222
+ code: lookupKey,
223
+ name: zod.z.string().min(1).max(120),
224
+ rank: zod.z.number().int().nonnegative().default(100),
225
+ capabilities: zod.z.record(lookupKey, zod.z.unknown()).default({})
226
+ }).strict();
227
+ var AppMeterSchema = zod.z.object({
228
+ code: lookupKey,
229
+ aggregation: EntitlementMeterAggregationSchema,
230
+ unit: zod.z.string().min(1).max(40)
231
+ }).strict();
232
+ var APP_AUTHORIZATION_LIMITS = { permissions: 128, roles: 32, permissionsPerRole: 128 };
233
+ var authorizationKey = zod.z.string().min(3).max(120).regex(/^[a-z][a-z0-9-]*(\.[a-z][a-z0-9_-]*)+$/, "Keys are dotted lowercase identifiers without wildcards");
234
+ var AppPermissionDeclarationSchema = zod.z.object({
235
+ key: authorizationKey,
236
+ description: zod.z.string().trim().min(1).max(300)
237
+ }).strict();
238
+ var AppRoleDeclarationSchema = zod.z.object({
239
+ key: authorizationKey,
240
+ name: zod.z.string().trim().min(1).max(80),
241
+ description: zod.z.string().trim().max(300).default(""),
242
+ permissions: zod.z.array(authorizationKey).max(APP_AUTHORIZATION_LIMITS.permissionsPerRole)
243
+ }).strict();
244
+ var AppManifestSchema = zod.z.object({
245
+ /** Referencia opcional al JSON Schema publicado, para autocompletado en editores. */
246
+ $schema: zod.z.string().url().max(200).optional(),
247
+ schema: zod.z.literal("app/v1"),
248
+ key: slug,
249
+ name: zod.z.string().trim().min(1).max(80),
250
+ origins: zod.z.object({ staging: httpsOrigin.optional(), production: httpsOrigin.optional() }).strict().refine((origins) => Boolean(origins.staging || origins.production), "Declare at least one origin"),
251
+ products: zod.z.array(AppProductUseSchema).max(32).default([]),
252
+ resources: zod.z.array(AppResourceSchema).max(64).default([]),
253
+ events: zod.z.array(AppEventSchema).max(256).default([]),
254
+ capabilities: zod.z.array(AppCapabilitySchema).max(256).default([]),
255
+ plans: zod.z.array(AppPlanSchema).max(32).default([]),
256
+ meters: zod.z.array(AppMeterSchema).max(64).default([]),
257
+ /** Opcional: permisos y roles de la app (clave `<clave-de-la-app>.…`, sin comodines). */
258
+ permissions: zod.z.array(AppPermissionDeclarationSchema).max(APP_AUTHORIZATION_LIMITS.permissions).optional(),
259
+ roles: zod.z.array(AppRoleDeclarationSchema).max(APP_AUTHORIZATION_LIMITS.roles).optional()
260
+ }).strict();
261
+ var APP_ACCESS_SCOPES = [
262
+ "capabilities:read",
263
+ "users:contact:read",
264
+ "users:read",
265
+ "flags:read",
266
+ "catalog:read",
267
+ "app-relationships:read",
268
+ "app-relationships:write",
269
+ "app-plans:write",
270
+ "app-roles:read",
271
+ "app-roles:write"
272
+ ];
273
+ var APP_ACCESS_SCOPE_SET = new Set(APP_ACCESS_SCOPES);
274
+ function appScopeAllowed(product2, scope) {
275
+ if (product2 === "customy-access") return APP_ACCESS_SCOPE_SET.has(scope);
276
+ return scope.startsWith(`${product2.replace(/^customy-/, "")}:`);
277
+ }
278
+ function appManifestProblems(input, manifests = CONNECTABLE_PRODUCT_MANIFESTS) {
279
+ const parsed = AppManifestSchema.safeParse(input);
280
+ if (!parsed.success) return parsed.error.issues.map((issue) => ({ path: issue.path.join("."), code: "SCHEMA_INVALID" }));
281
+ const app = parsed.data;
282
+ const problems = [];
283
+ const unique = (items, key2, path4) => {
284
+ const seen = /* @__PURE__ */ new Set();
285
+ items.forEach((item, index) => {
286
+ const k = key2(item);
287
+ if (seen.has(k)) problems.push({ path: `${path4}.${index}`, code: "DUPLICATE" });
288
+ seen.add(k);
289
+ });
290
+ };
291
+ unique(app.products, (p) => p.product, "products");
292
+ unique(app.resources, (r) => r.key, "resources");
293
+ unique(app.events, (e) => e.name, "events");
294
+ unique(app.capabilities, (c) => c.lookupKey, "capabilities");
295
+ unique(app.plans, (p) => p.code, "plans");
296
+ unique(app.meters, (m) => m.code, "meters");
297
+ app.products.forEach((use, index) => {
298
+ use.scopes.forEach((scope, scopeIndex) => {
299
+ if (!appScopeAllowed(use.product, scope)) problems.push({ path: `products.${index}.scopes.${scopeIndex}`, code: "SCOPE_OUTSIDE_PRODUCT" });
300
+ });
301
+ });
302
+ const counts = /* @__PURE__ */ new Map();
303
+ app.resources.forEach((resource, index) => {
304
+ const violation = connectedResourceViolation({ ...resource, productKey: resource.product, resourceId: "manifest" }, manifests);
305
+ if (violation && violation !== "BINDING_RESOURCE_ID_INVALID") problems.push({ path: `resources.${index}`, code: violation });
306
+ counts.set(resource.product, (counts.get(resource.product) ?? 0) + 1);
307
+ });
308
+ for (const [product2, count] of counts) {
309
+ const limit = connectedResourceLimit(product2, manifests);
310
+ if (limit !== null && count > limit) problems.push({ path: "resources", code: "BINDING_LIMIT_EXCEEDED" });
311
+ }
312
+ const meters = new Set(app.meters.map((meter) => meter.code));
313
+ const capabilities = new Set(app.capabilities.map((capability) => capability.lookupKey));
314
+ app.capabilities.forEach((capability, index) => {
315
+ if (capability.type === "metered" && (!capability.meter || !meters.has(capability.meter))) problems.push({ path: `capabilities.${index}.meter`, code: "METER_UNDECLARED" });
316
+ if (capability.type !== "metered" && capability.meter) problems.push({ path: `capabilities.${index}.meter`, code: "METER_ON_UNMETERED" });
317
+ });
318
+ app.plans.forEach((plan2, index) => {
319
+ for (const key2 of Object.keys(plan2.capabilities)) if (!capabilities.has(key2)) problems.push({ path: `plans.${index}.capabilities.${key2}`, code: "CAPABILITY_UNDECLARED" });
320
+ });
321
+ const prefix = `${app.key}.`;
322
+ const permissionKeys = /* @__PURE__ */ new Set();
323
+ (app.permissions ?? []).forEach((permission, index) => {
324
+ if (!permission.key.startsWith(prefix)) problems.push({ path: `permissions.${index}.key`, code: "PERMISSION_NAMESPACE_VIOLATION" });
325
+ if (permissionKeys.has(permission.key)) problems.push({ path: `permissions.${index}`, code: "DUPLICATE" });
326
+ permissionKeys.add(permission.key);
327
+ });
328
+ const roleKeys = /* @__PURE__ */ new Set();
329
+ const roleNames = /* @__PURE__ */ new Set();
330
+ (app.roles ?? []).forEach((role, index) => {
331
+ if (!role.key.startsWith(prefix)) problems.push({ path: `roles.${index}.key`, code: "ROLE_NAMESPACE_VIOLATION" });
332
+ if (roleKeys.has(role.key)) problems.push({ path: `roles.${index}`, code: "DUPLICATE" });
333
+ if (roleNames.has(role.name.toLowerCase())) problems.push({ path: `roles.${index}.name`, code: "DUPLICATE" });
334
+ roleKeys.add(role.key);
335
+ roleNames.add(role.name.toLowerCase());
336
+ const inRole = /* @__PURE__ */ new Set();
337
+ role.permissions.forEach((code, permissionIndex) => {
338
+ if (!permissionKeys.has(code)) problems.push({ path: `roles.${index}.permissions.${permissionIndex}`, code: "PERMISSION_UNDECLARED" });
339
+ if (inRole.has(code)) problems.push({ path: `roles.${index}.permissions.${permissionIndex}`, code: "DUPLICATE" });
340
+ inRole.add(code);
341
+ });
342
+ });
343
+ return problems;
344
+ }
345
+
346
+ // src/apps.ts
347
+ var PROBLEM_HINTS = {
348
+ PERMISSION_NAMESPACE_VIOLATION: "la clave del permiso debe empezar por \xAB<clave-de-la-app>.\xBB",
349
+ ROLE_NAMESPACE_VIOLATION: "la clave del rol debe empezar por \xAB<clave-de-la-app>.\xBB",
350
+ PERMISSION_UNDECLARED: "el rol usa un permiso que no est\xE1 declarado en permissions[]"
351
+ };
352
+ function describeProblem(problem) {
353
+ const hint = PROBLEM_HINTS[problem.code];
354
+ return `\u2717 ${problem.path || "(ra\xEDz)"}: ${problem.code}${hint ? ` \u2014 ${hint}` : ""}`;
355
+ }
356
+ function authorizationSummary(manifest) {
357
+ return `${manifest.permissions?.length ?? 0} permisos, ${manifest.roles?.length ?? 0} roles`;
358
+ }
359
+ function validateManifest(input) {
360
+ const problems = appManifestProblems(input);
361
+ return problems.length ? { ok: false, problems } : { ok: true, manifest: AppManifestSchema.parse(input) };
362
+ }
363
+ var SyncError = class extends Error {
364
+ constructor(code, status) {
365
+ super(`${code} (${status})`);
366
+ this.code = code;
367
+ this.status = status;
368
+ }
369
+ code;
370
+ status;
371
+ };
372
+ async function syncApp(options) {
373
+ const base = options.accessUrl.replace(/\/$/, "");
374
+ if (!/^https:\/\//.test(base) && !/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(base)) throw new SyncError("ACCESS_URL_INSECURE", 0);
375
+ const call = async (method, path4, body) => {
376
+ const response = await (options.fetch ?? fetch)(`${base}${path4}`, {
377
+ method,
378
+ headers: { authorization: `Bearer ${options.token}`, "content-type": "application/json", "idempotency-key": crypto.randomUUID() },
379
+ body: JSON.stringify(body)
380
+ });
381
+ const json = await response.json().catch(() => ({}));
382
+ if (!response.ok) throw new SyncError(String(json.code ?? json.error ?? "ACCESS_REQUEST_FAILED"), response.status);
383
+ return json;
384
+ };
385
+ const env = encodeURIComponent(options.workspaceEnvironmentId);
386
+ const installed = await call("POST", `/api/admin/env/${env}/connected-applications/install`, { manifest: options.manifest, reason: options.reason });
387
+ const connection = installed.connection;
388
+ const reconciliation = (value) => value && typeof value === "object" ? value : {};
389
+ if (!installed.replayed) {
390
+ return { action: "installed", applicationId: connection.applicationId, environmentId: connection.environmentId, revision: connection.revision, reconciliation: reconciliation(installed.reconciliation) };
391
+ }
392
+ const updated = await call("PUT", `/api/admin/env/${encodeURIComponent(connection.environmentId)}/connected-application/manifest`, {
393
+ expectedRevision: connection.revision,
394
+ manifest: options.manifest,
395
+ reason: options.reason
396
+ });
397
+ const revision = Number(updated.revision ?? connection.revision);
398
+ return { action: updated.unchanged ? "unchanged" : "updated", applicationId: connection.applicationId, environmentId: connection.environmentId, revision, reconciliation: reconciliation(updated.reconciliation) };
399
+ }
400
+ var EXIT = { ok: 0, failure: 1, unsupported: 2, auth: 3, confirmation: 4 };
401
+ var PROVISIONING_GROUPS = ["users", "audit", "policy", "whoami", "login"];
402
+ var PROVISIONING_HELP = [
403
+ "Provisioning of TEST users (every command needs --env staging|production; there is no default):",
404
+ " customy users test create --env E --count N (--email-base me@x.com | --email-domain qa.example.com)",
405
+ ' [--currency USD --country US --locale es-CO --tag T --expires-in-days N --reason "..." --ticket X --batch-id Y]',
406
+ ' customy users test cleanup --env E (--batch ID | --mine) --reason "..."',
407
+ " customy users get <externalKey> --env E",
408
+ " customy users list --env E [--kind test|regular --batch ID --q PREFIX --limit N --all]",
409
+ ' customy users upsert <externalKey> --env E --email ... --reason "..." [--name N --kind test|regular --attr k=v ... --password generate|none]',
410
+ ' customy users delete <externalKey> --env E --reason "..."',
411
+ ' customy users signin-link <externalKey> --env E --reason "..."',
412
+ " customy audit list --env E [--actor --action --subject --batch --from --to --limit --all]",
413
+ " customy audit export --env E --format csv|ndjson [--out file] [filters]",
414
+ " customy audit verify --env E",
415
+ " customy policy get --env E | customy whoami --env E",
416
+ " customy login (device flow: not available yet)",
417
+ "Common flags: --json (one JSON document on stdout), --base-url URL (or CUSTOMY_ACCESS_URL),",
418
+ " --dry-run (writes: print the request, send nothing), --yes-i-am-sure production (non-interactive production writes).",
419
+ "Credentials: CUSTOMY_CLIENT_ID + CUSTOMY_CLIENT_SECRET (or CUSTOMY_TOKEN), never argv."
420
+ ];
421
+ var UsageError = class extends Error {
422
+ };
423
+ var Refused = class extends Error {
424
+ };
425
+ var COMMON = { env: "string", "base-url": "string", json: "boolean", "dry-run": "boolean", "yes-i-am-sure": "string", help: "boolean" };
426
+ function parse(args, spec, positionals) {
427
+ const known = { ...COMMON, ...spec };
428
+ const flags = {};
429
+ const rest = [];
430
+ for (let i = 0; i < args.length; i += 1) {
431
+ const arg = args[i];
432
+ if (!arg.startsWith("--")) {
433
+ rest.push(arg);
434
+ continue;
435
+ }
436
+ const eq = arg.indexOf("=");
437
+ const name = eq >= 0 ? arg.slice(2, eq) : arg.slice(2);
438
+ const kind = known[name];
439
+ if (!kind) throw new UsageError(`unknown flag --${name}`);
440
+ if (kind === "boolean") {
441
+ flags[name] = eq >= 0 ? arg.slice(eq + 1) !== "false" : true;
442
+ continue;
443
+ }
444
+ let value = eq >= 0 ? arg.slice(eq + 1) : args[i + 1];
445
+ if (eq < 0) i += 1;
446
+ if (value === void 0 || eq < 0 && value.startsWith("--")) throw new UsageError(`--${name} needs a value`);
447
+ if (kind === "list") flags[name] = [...flags[name] ?? [], value];
448
+ else flags[name] = value;
449
+ }
450
+ if (rest.length !== positionals) throw new UsageError(positionals === 0 ? `unexpected argument "${rest[0]}"` : `expected ${positionals} argument(s), got ${rest.length}`);
451
+ return { flags, rest };
452
+ }
453
+ var str = (flags, name) => typeof flags[name] === "string" ? flags[name] : void 0;
454
+ var bool = (flags, name) => flags[name] === true;
455
+ function int(flags, name, min, max) {
456
+ const raw = str(flags, name);
457
+ if (raw === void 0) return void 0;
458
+ const value = Number(raw);
459
+ if (!/^\d+$/.test(raw) || value < min || value > max) throw new UsageError(`--${name} must be an integer between ${min} and ${max}`);
460
+ return value;
461
+ }
462
+ function required(flags, name) {
463
+ const value = str(flags, name);
464
+ if (!value) throw new UsageError(`--${name} is required`);
465
+ return value;
466
+ }
467
+ function environmentOf(flags) {
468
+ const env = str(flags, "env");
469
+ if (env === void 0) throw new UsageError("--env is required (staging|production); there is no default environment");
470
+ if (env !== "staging" && env !== "production") throw new UsageError(`--env must be "staging" or "production", got "${env}"`);
471
+ return env;
472
+ }
473
+ function attributes(flags) {
474
+ const out = {};
475
+ for (const key2 of ["currency", "country", "locale"]) {
476
+ const value = str(flags, key2);
477
+ if (value) out[key2] = value;
478
+ }
479
+ for (const pair of flags.attr ?? []) {
480
+ const at = pair.indexOf("=");
481
+ if (at <= 0) throw new UsageError(`--attr expects key=value, got "${pair}"`);
482
+ out[pair.slice(0, at)] = pair.slice(at + 1);
483
+ }
484
+ return Object.keys(out).length ? out : void 0;
485
+ }
486
+ function expiry(flags) {
487
+ const days = int(flags, "expires-in-days", 1, 3650);
488
+ return days === void 0 ? void 0 : new Date(Date.now() + days * 864e5);
489
+ }
490
+ function dryRunClient(env) {
491
+ let captured;
492
+ const fakeFetch = (async (input, init) => {
493
+ const url = new URL(String(input));
494
+ if (url.pathname === "/oauth/token") return new Response(JSON.stringify({ access_token: "dry-run-token", expires_in: 900 }), { status: 200, headers: { "content-type": "application/json" } });
495
+ const headers = new Headers(init?.headers);
496
+ const query = {};
497
+ url.searchParams.forEach((value, name) => {
498
+ query[name] = value;
499
+ });
500
+ captured = {
501
+ method: init?.method ?? "GET",
502
+ path: url.pathname,
503
+ ...Object.keys(query).length ? { query } : {},
504
+ headers: { "Customy-Environment": headers.get("customy-environment") ?? env, ...headers.get("idempotency-key") ? { "Idempotency-Key": headers.get("idempotency-key") } : {}, ...headers.get("if-match") ? { "If-Match": headers.get("if-match") } : {} },
505
+ ...typeof init?.body === "string" ? { body: JSON.parse(init.body) } : {}
506
+ };
507
+ throw new Error("dry-run: request captured, nothing sent");
508
+ });
509
+ const api = provisioning.createProvisioning({ environment: env, baseUrl: "https://dry-run.invalid", clientId: "dry-run", clientSecret: "dry-run-secret", fetch: fakeFetch, retry: false });
510
+ return { api, captured: () => captured };
511
+ }
512
+ function liveClient(ctx) {
513
+ const baseUrl = str(ctx.flags, "base-url") ?? ctx.io.env.CUSTOMY_ACCESS_URL;
514
+ if (!baseUrl) throw new UsageError("the Access origin is required: pass --base-url or set CUSTOMY_ACCESS_URL (there is no default host)");
515
+ const { CUSTOMY_CLIENT_ID: clientId, CUSTOMY_CLIENT_SECRET: clientSecret, CUSTOMY_TOKEN: accessToken } = ctx.io.env;
516
+ const common = { environment: ctx.env, baseUrl, ...ctx.io.fetch ? { fetch: ctx.io.fetch } : {} };
517
+ if (clientId && clientSecret) return provisioning.createProvisioning({ ...common, clientId, clientSecret });
518
+ if (accessToken) return provisioning.createProvisioning({ ...common, accessToken });
519
+ throw new provisioning.CustomyAuthError({ code: "SDK_CREDENTIALS_REQUIRED", status: 0, message: "set CUSTOMY_CLIENT_ID and CUSTOMY_CLIENT_SECRET (or CUSTOMY_TOKEN) in the environment" });
520
+ }
521
+ async function confirmProduction(ctx, summary) {
522
+ if (ctx.env !== "production") return;
523
+ const given = str(ctx.flags, "yes-i-am-sure");
524
+ if (given !== void 0) {
525
+ if (given !== "production") throw new Refused(`--yes-i-am-sure must equal "production", got "${given}"`);
526
+ return;
527
+ }
528
+ if (!ctx.io.isTTY || !ctx.io.prompt) throw new Refused("production writes without a terminal need --yes-i-am-sure production");
529
+ ctx.io.err(`About to ${summary} in PRODUCTION.`);
530
+ const answer = await ctx.io.prompt('Type "production" to confirm: ');
531
+ if (answer.trim() !== "production") throw new Refused("confirmation refused: nothing was changed");
532
+ }
533
+ function emit(ctx, json, human) {
534
+ if (ctx.json) ctx.io.out(JSON.stringify(json, null, 2));
535
+ else for (const line of human) ctx.io.out(line);
536
+ }
537
+ function table(rows) {
538
+ const widths = rows[0].map((_, col) => Math.max(...rows.map((row) => (row[col] ?? "").length)));
539
+ return rows.map((row) => row.map((cell, col) => col === row.length - 1 ? cell : cell.padEnd(widths[col])).join(" ").trimEnd());
540
+ }
541
+ var SECRET_WARNING = "Store these now: passwords and links are shown ONCE and cannot be retrieved again.";
542
+ async function write(ctx, summary, run, render) {
543
+ if (bool(ctx.flags, "dry-run")) {
544
+ const dry = dryRunClient(ctx.env);
545
+ try {
546
+ await run(dry.api);
547
+ } catch (error) {
548
+ const request = dry.captured();
549
+ if (!request) throw error;
550
+ const { method, path: urlPath, query, headers, body } = request;
551
+ const doc = { dryRun: true, environment: ctx.env, request: { method, path: urlPath, ...query ? { query } : {}, headers, ...body !== void 0 ? { body } : {} } };
552
+ emit(ctx, doc, [
553
+ `DRY RUN (nothing sent): ${summary}`,
554
+ `environment: ${ctx.env}`,
555
+ `${method} ${urlPath}${query ? `?${new URLSearchParams(query)}` : ""}`,
556
+ ...Object.entries(headers).map(([name, value]) => `${name}: ${value}`),
557
+ ...body !== void 0 ? [JSON.stringify(body, null, 2)] : []
558
+ ]);
559
+ return EXIT.ok;
560
+ }
561
+ throw new Error("dry run did not capture a request");
562
+ }
563
+ await confirmProduction(ctx, summary);
564
+ const result = await run(liveClient(ctx));
565
+ const out = render(result);
566
+ if (out.secret && !ctx.json) ctx.io.err(SECRET_WARNING);
567
+ emit(ctx, out.json ?? result, out.human);
568
+ return EXIT.ok;
569
+ }
570
+ async function read(ctx, run, render) {
571
+ const result = await run(liveClient(ctx));
572
+ const out = render(result);
573
+ emit(ctx, out.json ?? result, out.human);
574
+ return EXIT.ok;
575
+ }
576
+ var userLines = (user) => [
577
+ `externalKey: ${user.externalKey}`,
578
+ `id: ${user.id}`,
579
+ `kind: ${user.kind}`,
580
+ `email: ${user.email}`,
581
+ `version: ${user.version}`,
582
+ `expiresAt: ${user.expiresAt ?? "-"}`,
583
+ `createdAt: ${user.createdAt}`,
584
+ ...user.batchId ? [`batch: ${user.batchId}`] : []
585
+ ];
586
+ var usersTable = (users2) => users2.length === 0 ? ["(no users)"] : table([["EXTERNAL KEY", "KIND", "EMAIL", "EXPIRES"], ...users2.map((u) => [u.externalKey, u.kind, u.email, u.expiresAt ?? "-"])]);
587
+ var auditTable = (entries) => entries.length === 0 ? ["(no entries)"] : table([["SEQ", "AT", "ACTION", "SUBJECT", "ACTOR"], ...entries.map((e) => [String(e.seq), e.at, e.action, e.subject.key, e.actor.id])]);
588
+ function batchLines(result) {
589
+ return [
590
+ `batch ${result.batch.id}: ${result.batch.count} users, expires ${result.batch.expiresAt ?? "-"}`,
591
+ ...table([["EXTERNAL KEY", "EMAIL", "PASSWORD"], ...result.users.map((u) => [u.externalKey, u.email, u.credentials.password ?? "(not returned)"])])
592
+ ];
593
+ }
594
+ async function users(args, io) {
595
+ const [first, ...tail] = args;
596
+ if (first === "test") {
597
+ const [action, ...rest] = tail;
598
+ if (action === "create") {
599
+ const { flags } = parse(rest, { count: "string", "email-base": "string", "email-domain": "string", currency: "string", country: "string", locale: "string", tag: "string", "expires-in-days": "string", reason: "string", ticket: "string", "batch-id": "string", attr: "list" }, 0);
600
+ const ctx = context(io, flags);
601
+ const count = int(flags, "count", 1, 1e3);
602
+ if (count === void 0) throw new UsageError("--count is required (1-1000)");
603
+ const emailBase = str(flags, "email-base");
604
+ const emailDomain = str(flags, "email-domain");
605
+ if (emailBase === void 0 === (emailDomain === void 0)) throw new UsageError("pass exactly one of --email-base or --email-domain");
606
+ const input = {
607
+ count,
608
+ ...emailBase !== void 0 ? { emailBase } : { emailDomain },
609
+ ...str(flags, "tag") ? { tag: str(flags, "tag") } : {},
610
+ ...attributes(flags) ? { attributes: attributes(flags) } : {},
611
+ ...expiry(flags) ? { expiresAt: expiry(flags) } : {},
612
+ ...str(flags, "ticket") ? { ticket: str(flags, "ticket") } : {},
613
+ ...str(flags, "batch-id") ? { batchId: str(flags, "batch-id") } : {},
614
+ reason: str(flags, "reason") ?? `customy cli: create ${count} test users`
615
+ };
616
+ return write(ctx, `create ${count} test users`, (api) => api.testUsers.batch(input), (result) => ({ human: batchLines(result), secret: true }));
617
+ }
618
+ if (action === "cleanup") {
619
+ const { flags } = parse(rest, { batch: "string", mine: "boolean", reason: "string", ticket: "string" }, 0);
620
+ const ctx = context(io, flags);
621
+ const batch = str(flags, "batch");
622
+ if (batch === void 0 === !bool(flags, "mine")) throw new UsageError("pass exactly one of --batch ID or --mine");
623
+ const reason = required(flags, "reason");
624
+ return write(
625
+ ctx,
626
+ batch ? `delete test users of batch ${batch}` : "delete all your test users",
627
+ (api) => api.testUsers.cleanup(batch ? { batch } : { mine: true }, { reason, ...str(flags, "ticket") ? { ticket: str(flags, "ticket") } : {} }),
628
+ (r) => ({ human: [`deleted ${r.deleted} test users${r.batch ? ` (batch ${r.batch})` : ""}`] })
629
+ );
630
+ }
631
+ throw new UsageError("usage: customy users test <create|cleanup> --env staging|production ...");
632
+ }
633
+ if (first === "get") {
634
+ const { flags, rest } = parse(tail, {}, 1);
635
+ const ctx = context(io, flags);
636
+ return read(ctx, (api) => api.users.get(rest[0]), (user) => ({ human: userLines(user) }));
637
+ }
638
+ if (first === "list") {
639
+ const { flags } = parse(tail, { kind: "string", batch: "string", q: "string", limit: "string", all: "boolean", cursor: "string", "created-by": "string" }, 0);
640
+ const ctx = context(io, flags);
641
+ const kind = str(flags, "kind");
642
+ if (kind !== void 0 && kind !== "test" && kind !== "regular") throw new UsageError("--kind must be test or regular");
643
+ const params = { ...kind ? { kind } : {}, ...str(flags, "batch") ? { batch: str(flags, "batch") } : {}, ...str(flags, "q") ? { q: str(flags, "q") } : {}, ...str(flags, "created-by") ? { createdBy: str(flags, "created-by") } : {}, ...int(flags, "limit", 1, 200) ? { limit: int(flags, "limit", 1, 200) } : {} };
644
+ if (bool(flags, "all")) {
645
+ return read(ctx, async (api) => {
646
+ const all = [];
647
+ for await (const user of api.users.listAll(params)) all.push(user);
648
+ return all;
649
+ }, (all) => ({ json: { data: all }, human: usersTable(all) }));
650
+ }
651
+ return read(ctx, (api) => api.users.list({ ...params, ...str(flags, "cursor") ? { cursor: str(flags, "cursor") } : {} }), (page) => ({
652
+ human: [...usersTable(page.data), ...page.page.nextCursor ? [`more results: --cursor ${page.page.nextCursor} (or --all)`] : []]
653
+ }));
654
+ }
655
+ if (first === "upsert") {
656
+ const { flags, rest } = parse(tail, { email: "string", name: "string", kind: "string", attr: "list", currency: "string", country: "string", locale: "string", password: "string", "expires-in-days": "string", reason: "string", ticket: "string", "expected-version": "string" }, 1);
657
+ const ctx = context(io, flags);
658
+ const kind = str(flags, "kind") ?? "test";
659
+ if (kind !== "test" && kind !== "regular") throw new UsageError("--kind must be test or regular");
660
+ const password = str(flags, "password") ?? (kind === "test" ? "generate" : "none");
661
+ if (password !== "generate" && password !== "none") throw new UsageError('--password accepts only "generate" or "none" (passwords never travel on the command line)');
662
+ const input = {
663
+ email: required(flags, "email"),
664
+ kind,
665
+ reason: required(flags, "reason"),
666
+ ...str(flags, "name") ? { name: str(flags, "name") } : {},
667
+ ...attributes(flags) ? { attributes: attributes(flags) } : {},
668
+ ...password === "generate" ? { password: "generate" } : {},
669
+ ...expiry(flags) ? { expiresAt: expiry(flags) } : {},
670
+ ...str(flags, "ticket") ? { ticket: str(flags, "ticket") } : {},
671
+ ...int(flags, "expected-version", 0, Number.MAX_SAFE_INTEGER) !== void 0 ? { expectedVersion: int(flags, "expected-version", 0, Number.MAX_SAFE_INTEGER) } : {}
672
+ };
673
+ return write(ctx, `upsert user ${rest[0]}`, (api) => api.users.upsert(rest[0], input), (result) => ({
674
+ human: [
675
+ `${result.created ? "created" : result.changed ? "updated" : "unchanged"} ${result.externalKey} (version ${result.version})`,
676
+ ...userLines(result),
677
+ ...result.credentials?.password ? [`password: ${result.credentials.password}`] : []
678
+ ],
679
+ secret: Boolean(result.credentials?.password)
680
+ }));
681
+ }
682
+ if (first === "delete") {
683
+ const { flags, rest } = parse(tail, { reason: "string", ticket: "string", "if-match": "string" }, 1);
684
+ const ctx = context(io, flags);
685
+ const reason = required(flags, "reason");
686
+ return write(
687
+ ctx,
688
+ `delete user ${rest[0]}`,
689
+ (api) => api.users.delete(rest[0], { reason, ...str(flags, "ticket") ? { ticket: str(flags, "ticket") } : {}, ...str(flags, "if-match") ? { ifMatch: str(flags, "if-match") } : {} }),
690
+ (r) => ({ human: [`deleted ${r.externalKey} (version ${r.version})`] })
691
+ );
692
+ }
693
+ if (first === "signin-link") {
694
+ const { flags, rest } = parse(tail, { reason: "string", ticket: "string" }, 1);
695
+ const ctx = context(io, flags);
696
+ const reason = required(flags, "reason");
697
+ return write(
698
+ ctx,
699
+ `issue a signin link for ${rest[0]}`,
700
+ (api) => api.users.signinLink(rest[0], { reason, ...str(flags, "ticket") ? { ticket: str(flags, "ticket") } : {} }),
701
+ (r) => ({ human: [`link: ${r.link ?? "(not returned)"}`, `expiresAt: ${r.expiresAt}`], secret: Boolean(r.link) })
702
+ );
703
+ }
704
+ throw new UsageError("usage: customy users <test create|test cleanup|get|list|upsert|delete|signin-link> --env staging|production ...");
705
+ }
706
+ async function audit(args, io) {
707
+ const [action, ...rest] = args;
708
+ const filters = { actor: "string", action: "string", subject: "string", batch: "string", from: "string", to: "string" };
709
+ const pick = (flags) => Object.fromEntries(Object.keys(filters).filter((name) => str(flags, name)).map((name) => [name, str(flags, name)]));
710
+ if (action === "list") {
711
+ const { flags } = parse(rest, { ...filters, limit: "string", all: "boolean", cursor: "string" }, 0);
712
+ const ctx = context(io, flags);
713
+ const limit = int(flags, "limit", 1, 200);
714
+ const params = { ...pick(flags), ...limit ? { limit } : {} };
715
+ if (bool(flags, "all")) {
716
+ return read(ctx, async (api) => {
717
+ const all = [];
718
+ for await (const entry of api.audit.listAll(params)) all.push(entry);
719
+ return all;
720
+ }, (all) => ({ json: { data: all }, human: auditTable(all) }));
721
+ }
722
+ return read(ctx, (api) => api.audit.list({ ...params, ...str(flags, "cursor") ? { cursor: str(flags, "cursor") } : {} }), (page) => ({
723
+ human: [...auditTable(page.data), ...page.page.nextCursor ? [`more results: --cursor ${page.page.nextCursor} (or --all)`] : []]
724
+ }));
725
+ }
726
+ if (action === "export") {
727
+ const { flags } = parse(rest, { ...filters, format: "string", out: "string" }, 0);
728
+ const ctx = context(io, flags);
729
+ const format = required(flags, "format");
730
+ if (format !== "csv" && format !== "ndjson") throw new UsageError("--format must be csv or ndjson");
731
+ const text = await liveClient(ctx).audit.export({ format, ...pick(flags) });
732
+ const out = str(flags, "out");
733
+ if (out) {
734
+ await promises.writeFile(path3__default.default.resolve(io.cwd, out), text);
735
+ emit(ctx, { out, bytes: text.length, format }, [`wrote ${text.length} characters of ${format} to ${out}`]);
736
+ } else io.out(text.replace(/\n$/, ""));
737
+ return EXIT.ok;
738
+ }
739
+ if (action === "verify") {
740
+ const { flags } = parse(rest, {}, 0);
741
+ const ctx = context(io, flags);
742
+ const result = await liveClient(ctx).audit.verify();
743
+ emit(ctx, result, [result.ok ? `audit chain OK: ${result.verified} entries verified (head seq ${result.headSeq})` : `audit chain BROKEN at seq ${result.brokenAtSeq}: ${result.reason}`]);
744
+ return result.ok ? EXIT.ok : EXIT.failure;
745
+ }
746
+ throw new UsageError("usage: customy audit <list|export|verify> --env staging|production ...");
747
+ }
748
+ async function policy(args, io) {
749
+ const [action, ...rest] = args;
750
+ if (action !== "get") throw new UsageError("usage: customy policy get --env staging|production");
751
+ const ctx = context(io, parse(rest, {}, 0).flags);
752
+ return read(ctx, (api) => api.policy.get(), (view) => ({
753
+ human: [
754
+ `policy version ${view.version}`,
755
+ `writes enabled (effective): ${view.effective.writesEnabled} (deployment ${view.effective.deployment.enabled ? "on" : "off"}, stage ${view.effective.stage})`,
756
+ `approval mode: ${view.policy.approvalMode}`,
757
+ ...Object.entries(view.policy.caps).map(([name, value]) => `${name}: ${value}`),
758
+ `allowRegularUsers: ${view.policy.allowRegularUsers}`,
759
+ `allowSigninLinks: ${view.policy.allowSigninLinks}`
760
+ ]
761
+ }));
762
+ }
763
+ async function whoami(args, io) {
764
+ const ctx = context(io, parse(args, {}, 0).flags);
765
+ return read(ctx, (api) => api.whoami(), (me) => ({
766
+ human: [`client: ${me.client.id} (owner ${me.client.owner})`, `environment: ${me.environmentId} (${me.stage})`, `audience: ${me.audience}`, `scopes: ${me.scopes.join(" ") || "-"}`, `writes: ${me.effective.writesEnabled ? "enabled" : "disabled"} (policy v${me.policy.version}, ${me.policy.approvalMode})`]
767
+ }));
768
+ }
769
+ function context(io, flags) {
770
+ return { io, flags, env: environmentOf(flags), json: bool(flags, "json") };
771
+ }
772
+ function login(io) {
773
+ io.err("customy login: the interactive device flow is not available yet.");
774
+ io.err("Use client credentials instead: export CUSTOMY_CLIENT_ID, CUSTOMY_CLIENT_SECRET and CUSTOMY_ACCESS_URL (an Access API key of the target environment),");
775
+ io.err("then pass --env staging|production. A pre-obtained bearer can be given as CUSTOMY_TOKEN.");
776
+ return EXIT.unsupported;
777
+ }
778
+ function report(error, io) {
779
+ if (error instanceof UsageError) {
780
+ io.err(`error: ${error.message}`);
781
+ io.err("run `customy --help` for usage");
782
+ return EXIT.failure;
783
+ }
784
+ if (error instanceof Refused) {
785
+ io.err(`refused: ${error.message}`);
786
+ return EXIT.confirmation;
787
+ }
788
+ if (error instanceof provisioning.CustomyProvisioningError) {
789
+ const request = error.requestId ? ` (request ${error.requestId})` : "";
790
+ io.err(`error ${error.code}${error.status ? ` [${error.status}]` : ""}: ${error.message}${request}`);
791
+ if (error instanceof provisioning.CustomyScopeError && error.scope) io.err(`missing scope: ${error.scope}`);
792
+ if (error instanceof provisioning.CustomyEnvironmentMismatchError) io.err("the API key belongs to another environment than --env");
793
+ if (error instanceof provisioning.CustomyConflictError && error.currentVersion !== void 0) io.err(`current version: ${error.currentVersion}`);
794
+ if (error instanceof provisioning.CustomyRateLimitError && error.retryAfter !== void 0) io.err(`retry after ${error.retryAfter}s`);
795
+ if (error instanceof provisioning.CustomyEnvironmentMismatchError) return EXIT.confirmation;
796
+ if (error instanceof provisioning.CustomyAuthError) return EXIT.auth;
797
+ return EXIT.failure;
798
+ }
799
+ io.err(`error: ${error instanceof Error ? error.message : "unexpected failure"}`);
800
+ return EXIT.failure;
801
+ }
802
+ async function runProvisioningCli(group, args, io) {
803
+ try {
804
+ if (args.includes("--help") && group !== "login") {
805
+ io.out(PROVISIONING_HELP.join("\n"));
806
+ return EXIT.ok;
807
+ }
808
+ switch (group) {
809
+ case "users":
810
+ return await users(args, io);
811
+ case "audit":
812
+ return await audit(args, io);
813
+ case "policy":
814
+ return await policy(args, io);
815
+ case "whoami":
816
+ return await whoami(args, io);
817
+ default:
818
+ return login(io);
819
+ }
820
+ } catch (error) {
821
+ return report(error, io);
822
+ }
823
+ }
824
+ var EXPERIMENTS_GROUPS = ["flags", "segments", "experiments"];
825
+ var EXPERIMENTS_EXIT = { ok: 0, failure: 1, auth: 3, conflict: 4 };
826
+ var EXPERIMENTS_HELP = [
827
+ "Customy Experiments (credential: CUSTOMY_EXPERIMENTS_TOKEN, origin: --base-url or CUSTOMY_EXPERIMENTS_URL):",
828
+ " customy flags list [--q TEXT --tag T --archived true|false --limit N --cursor C]",
829
+ ' customy flags get <key> | customy flags create --file flag.json --reason "..."',
830
+ ' customy flags update <key> --file patch.json --reason "..."',
831
+ ' customy flags archive|restore|delete <key> --reason "..." | customy flags kill <key> [--environment E] --reason "..."',
832
+ " customy segments list|get <key> | create --file segment.json --reason | update <key> --file patch.json --reason | delete <key> --reason",
833
+ ' customy segments members add|remove <key> --unit-keys a,b,c --reason "..."',
834
+ " customy experiments list|get <key> | create --file experiment.json --reason | update <key> --file patch.json --reason",
835
+ ' customy experiments start|pause <key> --reason "..." | customy experiments conclude <key> --decision ship|rollback|iterate --reason "..."',
836
+ "Common flags: --json (the response as one JSON document), --dry-run (writes: print the request, send nothing)."
837
+ ];
838
+ var UsageError2 = class extends Error {
839
+ };
840
+ var VALUE_FLAGS = /* @__PURE__ */ new Set(["file", "reason", "base-url", "q", "tag", "archived", "limit", "cursor", "environment", "unit-keys", "decision"]);
841
+ function parse2(args) {
842
+ const positional = [];
843
+ const flags = {};
844
+ for (let index = 0; index < args.length; index += 1) {
845
+ const arg = args[index];
846
+ if (!arg.startsWith("--")) {
847
+ positional.push(arg);
848
+ continue;
849
+ }
850
+ const name = arg.slice(2);
851
+ if (VALUE_FLAGS.has(name)) {
852
+ const value = args[index + 1];
853
+ if (value === void 0 || value.startsWith("--")) throw new UsageError2(`--${name} necesita un valor`);
854
+ flags[name] = value;
855
+ index += 1;
856
+ } else flags[name] = true;
857
+ }
858
+ return { positional, flags };
859
+ }
860
+ async function readBody(flags, io) {
861
+ const file = flags.file;
862
+ if (typeof file !== "string") throw new UsageError2("falta --file con el JSON de la petici\xF3n");
863
+ let parsed;
864
+ try {
865
+ parsed = JSON.parse(await promises.readFile(path3__default.default.resolve(io.cwd, file), "utf8"));
866
+ } catch (error) {
867
+ throw new UsageError2(`no se pudo leer ${file}: ${error instanceof Error ? error.message : String(error)}`);
868
+ }
869
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new UsageError2(`${file} debe contener un objeto JSON`);
870
+ return parsed;
871
+ }
872
+ function reasonOf(flags) {
873
+ const reason = typeof flags.reason === "string" ? flags.reason.trim() : "";
874
+ if (reason.length < 3) throw new UsageError2('toda escritura exige --reason "\u2026" (m\xEDnimo 3 caracteres)');
875
+ return reason;
876
+ }
877
+ function keyOf(positional, what) {
878
+ const key2 = positional[0];
879
+ if (!key2) throw new UsageError2(`falta la clave de ${what}`);
880
+ return encodeURIComponent(key2);
881
+ }
882
+ function listQuery(flags, names) {
883
+ const query = {};
884
+ for (const name of names) if (typeof flags[name] === "string") query[name] = flags[name];
885
+ return query;
886
+ }
887
+ async function plan(group, args, io) {
888
+ const [command, ...rest] = args;
889
+ const { positional, flags } = parse2(rest);
890
+ const withReason = async (call, extra = {}) => ({ ...call, write: true, body: { ...extra, reason: reasonOf(flags) } });
891
+ const fromFile = async (call) => ({ ...call, write: true, body: { ...await readBody(flags, io), reason: reasonOf(flags) } });
892
+ if (group === "flags") {
893
+ switch (command) {
894
+ case "list":
895
+ return { method: "GET", path: "/flags", query: listQuery(flags, ["q", "tag", "archived", "limit", "cursor"]), write: false };
896
+ case "get":
897
+ return { method: "GET", path: `/flags/${keyOf(positional, "flag")}`, write: false };
898
+ case "create":
899
+ return fromFile({ method: "POST", path: "/flags" });
900
+ case "update":
901
+ return fromFile({ method: "PATCH", path: `/flags/${keyOf(positional, "flag")}` });
902
+ case "archive":
903
+ case "restore":
904
+ return withReason({ method: "POST", path: `/flags/${keyOf(positional, "flag")}/${command}` });
905
+ case "delete":
906
+ return withReason({ method: "DELETE", path: `/flags/${keyOf(positional, "flag")}` });
907
+ case "kill":
908
+ return withReason({ method: "POST", path: `/flags/${keyOf(positional, "flag")}/kill` }, typeof flags.environment === "string" ? { environment: flags.environment } : {});
909
+ }
910
+ } else if (group === "segments") {
911
+ if (command === "members") {
912
+ const [action, ...more] = positional;
913
+ const unitKeys = typeof flags["unit-keys"] === "string" ? flags["unit-keys"].split(",").map((item) => item.trim()).filter(Boolean) : [];
914
+ if (action !== "add" && action !== "remove") throw new UsageError2('customy segments members add|remove <key> --unit-keys a,b --reason "\u2026"');
915
+ if (!unitKeys.length) throw new UsageError2("falta --unit-keys a,b,c");
916
+ return withReason({ method: action === "add" ? "POST" : "DELETE", path: `/segments/${keyOf(more, "segmento")}/members` }, { unitKeys });
917
+ }
918
+ switch (command) {
919
+ case "list":
920
+ return { method: "GET", path: "/segments", query: listQuery(flags, ["limit", "cursor"]), write: false };
921
+ case "get":
922
+ return { method: "GET", path: `/segments/${keyOf(positional, "segmento")}`, write: false };
923
+ case "create":
924
+ return fromFile({ method: "POST", path: "/segments" });
925
+ case "update":
926
+ return fromFile({ method: "PATCH", path: `/segments/${keyOf(positional, "segmento")}` });
927
+ case "delete":
928
+ return withReason({ method: "DELETE", path: `/segments/${keyOf(positional, "segmento")}` });
929
+ }
930
+ } else {
931
+ switch (command) {
932
+ case "list":
933
+ return { method: "GET", path: "/experiments", query: listQuery(flags, ["limit", "cursor"]), write: false };
934
+ case "get":
935
+ return { method: "GET", path: `/experiments/${keyOf(positional, "experimento")}`, write: false };
936
+ case "create":
937
+ return fromFile({ method: "POST", path: "/experiments" });
938
+ case "update":
939
+ return fromFile({ method: "PATCH", path: `/experiments/${keyOf(positional, "experimento")}` });
940
+ case "start":
941
+ case "pause":
942
+ return withReason({ method: "POST", path: `/experiments/${keyOf(positional, "experimento")}/${command}` });
943
+ case "conclude": {
944
+ const decision = flags.decision;
945
+ if (decision !== "ship" && decision !== "rollback" && decision !== "iterate") throw new UsageError2("conclude exige --decision ship|rollback|iterate");
946
+ return withReason({ method: "POST", path: `/experiments/${keyOf(positional, "experimento")}/conclude` }, { decision });
947
+ }
948
+ }
949
+ }
950
+ throw new UsageError2(`comando desconocido: customy ${group} ${command ?? ""}`.trim() + " (customy --help)");
951
+ }
952
+ function summarize(group, call, data) {
953
+ if (!data || typeof data !== "object") return ["\u2713 hecho"];
954
+ const record = data;
955
+ const rowOf = (item) => {
956
+ const row = item;
957
+ return `${String(row.key ?? row.id ?? "?")} ${String(row.name ?? "")} ${String(row.status ?? row.kind ?? "")}`;
958
+ };
959
+ if (Array.isArray(record.items)) return [...record.items.map(rowOf), ...record.nextCursor ? [`# m\xE1s: --cursor ${String(record.nextCursor)}`] : []];
960
+ if (call.write) return [`\u2713 ${group} ${call.method} ${call.path}${record.key ? ` (${String(record.key)})` : ""}`];
961
+ return [rowOf(data), ...typeof record.description === "string" ? [String(record.description)] : []];
962
+ }
963
+ async function runExperimentsCli(group, args, io) {
964
+ try {
965
+ if (args.includes("--help")) {
966
+ io.out(EXPERIMENTS_HELP.join("\n"));
967
+ return EXPERIMENTS_EXIT.ok;
968
+ }
969
+ const { flags } = parse2(args.slice(1));
970
+ const call = await plan(group, args, io);
971
+ const base = (typeof flags["base-url"] === "string" ? flags["base-url"] : io.env.CUSTOMY_EXPERIMENTS_URL)?.replace(/\/$/, "");
972
+ if (!base) throw new UsageError2("falta el origen: --base-url o CUSTOMY_EXPERIMENTS_URL");
973
+ const query = call.query && Object.keys(call.query).length ? `?${new URLSearchParams(call.query)}` : "";
974
+ const url = `${base}/v1/experiments${call.path}${query}`;
975
+ if (call.write && flags["dry-run"]) {
976
+ io.out(JSON.stringify({ dryRun: true, method: call.method, url, body: call.body }, null, 2));
977
+ return EXPERIMENTS_EXIT.ok;
978
+ }
979
+ const token = io.env.CUSTOMY_EXPERIMENTS_TOKEN;
980
+ if (!token) throw new UsageError2("falta CUSTOMY_EXPERIMENTS_TOKEN en el entorno (nunca por la l\xEDnea de comandos)");
981
+ const doFetch = io.fetch ?? fetch;
982
+ const response = await doFetch(url, {
983
+ method: call.method,
984
+ headers: { authorization: `Bearer ${token}`, accept: "application/json", "user-agent": "customy-cli", ...call.body !== void 0 ? { "content-type": "application/json" } : {} },
985
+ ...call.body !== void 0 ? { body: JSON.stringify(call.body) } : {}
986
+ });
987
+ const text = await response.text();
988
+ let data;
989
+ try {
990
+ data = text ? JSON.parse(text) : void 0;
991
+ } catch {
992
+ data = text;
993
+ }
994
+ if (!response.ok) {
995
+ const body = data && typeof data === "object" ? data : {};
996
+ io.err(`\u2717 HTTP ${response.status}${body.name ? ` ${body.name}` : ""}: ${body.message ?? (typeof data === "string" && data ? data : response.statusText)}`);
997
+ if (body.details !== void 0) io.err(JSON.stringify(body.details));
998
+ return response.status === 401 || response.status === 403 ? EXPERIMENTS_EXIT.auth : response.status === 409 || response.status === 412 ? EXPERIMENTS_EXIT.conflict : EXPERIMENTS_EXIT.failure;
999
+ }
1000
+ if (flags.json) io.out(JSON.stringify(data ?? null, null, 2));
1001
+ else for (const line of summarize(group, call, data)) io.out(line);
1002
+ return EXPERIMENTS_EXIT.ok;
1003
+ } catch (error) {
1004
+ if (error instanceof UsageError2) {
1005
+ io.err(`\u2717 ${error.message}`);
1006
+ return EXPERIMENTS_EXIT.failure;
1007
+ }
1008
+ io.err(`\u2717 ${error instanceof Error ? error.message : String(error)}`);
1009
+ return EXPERIMENTS_EXIT.failure;
1010
+ }
1011
+ }
1012
+ function option(args, name) {
1013
+ const index = args.indexOf(`--${name}`);
1014
+ return index >= 0 ? args[index + 1] : void 0;
1015
+ }
1016
+ async function loadManifest(args, io) {
1017
+ const file = path3__default.default.resolve(io.cwd, option(args, "file") ?? "customy.app.json");
1018
+ let raw;
1019
+ try {
1020
+ raw = JSON.parse(await promises.readFile(file, "utf8"));
1021
+ } catch (error) {
1022
+ io.err(`no se pudo leer ${path3__default.default.relative(io.cwd, file) || file}: ${error instanceof Error ? error.message : error}`);
1023
+ return null;
1024
+ }
1025
+ const result = validateManifest(raw);
1026
+ if (!result.ok) {
1027
+ for (const problem of result.problems) io.err(describeProblem(problem));
1028
+ return null;
1029
+ }
1030
+ return result.manifest;
1031
+ }
1032
+ async function runCli(argv, io) {
1033
+ const [group, command, ...args] = argv;
1034
+ if (group === "--help" || group === "help") {
1035
+ io.out(["uso: customy apps <validate|codegen|sync> [--file customy.app.json]", ...PROVISIONING_HELP, ...EXPERIMENTS_HELP].join("\n"));
1036
+ return 0;
1037
+ }
1038
+ if (PROVISIONING_GROUPS.includes(group ?? "")) return runProvisioningCli(group, argv.slice(1), io);
1039
+ if (EXPERIMENTS_GROUPS.includes(group ?? "")) return runExperimentsCli(group, argv.slice(1), io);
1040
+ if (group !== "apps" || !["validate", "codegen", "sync"].includes(command ?? "")) {
1041
+ io.err("uso: customy apps <validate|codegen|sync> [--file customy.app.json]");
1042
+ io.err(" customy users | audit | policy | whoami | login | flags | segments | experiments (customy --help)");
1043
+ return 2;
1044
+ }
1045
+ const manifest = await loadManifest(args, io);
1046
+ if (!manifest) return 1;
1047
+ if (command === "validate") {
1048
+ io.out(`\u2713 ${manifest.key}: manifiesto app/v1 v\xE1lido (${manifest.events.length} eventos, ${manifest.capabilities.length} capabilities, ${authorizationSummary(manifest)})`);
1049
+ return 0;
1050
+ }
1051
+ if (command === "codegen") {
1052
+ const out = path3__default.default.resolve(io.cwd, option(args, "out") ?? "customy.generated.ts");
1053
+ await promises.mkdir(path3__default.default.dirname(out), { recursive: true });
1054
+ await promises.writeFile(out, generateAppTypes(manifest));
1055
+ io.out(`\u2713 tipos de ${manifest.key} en ${path3__default.default.relative(io.cwd, out)}`);
1056
+ return 0;
1057
+ }
1058
+ const workspaceEnvironmentId = option(args, "workspace-env");
1059
+ const accessUrl = io.env.CUSTOMY_ACCESS_URL;
1060
+ const token = io.env.CUSTOMY_ACCESS_TOKEN;
1061
+ if (!workspaceEnvironmentId || !accessUrl || !token) {
1062
+ io.err("sync necesita --workspace-env y las variables CUSTOMY_ACCESS_URL y CUSTOMY_ACCESS_TOKEN");
1063
+ return 2;
1064
+ }
1065
+ try {
1066
+ const result = await syncApp({
1067
+ manifest,
1068
+ accessUrl,
1069
+ token,
1070
+ workspaceEnvironmentId,
1071
+ reason: option(args, "reason") ?? `customy apps sync ${manifest.key}`,
1072
+ fetch: io.fetch
1073
+ });
1074
+ const verb = { installed: "instalada", updated: "actualizada", unchanged: "sin cambios" }[result.action];
1075
+ io.out(`\u2713 ${manifest.key} ${verb}: aplicaci\xF3n ${result.applicationId}, entorno ${result.environmentId}, revisi\xF3n ${result.revision} (${authorizationSummary(manifest)})`);
1076
+ let failed = false;
1077
+ for (const [product2, outcome] of Object.entries(result.reconciliation)) {
1078
+ if (outcome.status === "failed") {
1079
+ failed = true;
1080
+ io.err(`\u2717 ${product2}: ${outcome.code}${outcome.conflicts?.length ? ` (${outcome.conflicts.join(", ")})` : ""} \u2014 vuelve a ejecutar sync para reintentar`);
1081
+ } else if (outcome.status === "reconciled") {
1082
+ const counts = outcome.permissions !== void 0 || outcome.roles !== void 0 ? ` (${outcome.permissions ?? 0} permisos, ${outcome.roles ?? 0} roles${outcome.rolesOrphaned ? `, ${outcome.rolesOrphaned} roles hu\xE9rfanos` : ""})` : "";
1083
+ io.out(`\u2713 ${product2}: ${outcome.changed ? "actualizado" : "al d\xEDa"}${outcome.resourceId ? ` (${outcome.resourceId})` : ""}${counts}`);
1084
+ }
1085
+ }
1086
+ return failed ? 1 : 0;
1087
+ } catch (error) {
1088
+ io.err(`\u2717 sync: ${error instanceof Error ? error.message : error}`);
1089
+ return 1;
1090
+ }
1091
+ }
1092
+
1093
+ exports.EXIT = EXIT;
1094
+ exports.EXPERIMENTS_EXIT = EXPERIMENTS_EXIT;
1095
+ exports.SyncError = SyncError;
1096
+ exports.generateAppTypes = generateAppTypes;
1097
+ exports.runCli = runCli;
1098
+ exports.runExperimentsCli = runExperimentsCli;
1099
+ exports.runProvisioningCli = runProvisioningCli;
1100
+ exports.schemaToType = schemaToType;
1101
+ exports.syncApp = syncApp;
1102
+ exports.validateManifest = validateManifest;