anhedral 0.22.0 → 0.23.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 (92) hide show
  1. package/README.md +37 -51
  2. package/assets/contracts/deployment-provenance.json +4 -4
  3. package/assets/contracts/environment-provenance.json +2 -2
  4. package/dist/cli-commands.js +5 -17
  5. package/dist/cli-errors.js +1 -1
  6. package/dist/cli-output.js +1 -1
  7. package/dist/command-schema.d.ts +1 -0
  8. package/dist/command-schema.js +19 -1
  9. package/dist/completion.js +1 -1
  10. package/dist/{capability-catalog.d.ts → composition/catalog.d.ts} +2 -2
  11. package/dist/{capability-catalog.js → composition/catalog.js} +2 -2
  12. package/dist/{capability-command.d.ts → composition/command.d.ts} +3 -3
  13. package/dist/{capability-command.js → composition/command.js} +29 -22
  14. package/dist/{composition.d.ts → composition/composition.d.ts} +1 -1
  15. package/dist/{composition.js → composition/composition.js} +2 -2
  16. package/dist/{capability-editor.js → composition/editor.js} +1 -1
  17. package/dist/{capability-recipes.d.ts → composition/recipes.d.ts} +2 -2
  18. package/dist/{capability-recipes.js → composition/recipes.js} +7 -7
  19. package/dist/{capability-references.js → composition/references.js} +2 -2
  20. package/dist/{stack-update.d.ts → composition/update.d.ts} +3 -3
  21. package/dist/{stack-update.js → composition/update.js} +11 -11
  22. package/dist/contracts/cli-transport.d.ts +1 -1
  23. package/dist/contracts/deployment.d.ts +4 -65
  24. package/dist/contracts/deployment.js +0 -29
  25. package/dist/contracts/environment-file.d.ts +3 -0
  26. package/dist/contracts/environment-file.js +8 -5
  27. package/dist/contracts/production-transport.d.ts +2 -2
  28. package/dist/contracts/staging-transport.d.ts +2 -2
  29. package/dist/dependencies.d.ts +1 -1
  30. package/dist/dependencies.js +1 -1
  31. package/dist/launch.js +8 -8
  32. package/dist/platform/auth.d.ts +14 -0
  33. package/dist/platform/auth.js +62 -0
  34. package/dist/{platform-command.d.ts → platform/command.d.ts} +2 -2
  35. package/dist/platform/command.js +279 -0
  36. package/dist/{credential-helper.js → platform/credential-helper.js} +1 -1
  37. package/dist/platform/deploy.d.ts +2 -0
  38. package/dist/platform/deploy.js +158 -0
  39. package/dist/{platform-environment.d.ts → platform/environment.d.ts} +1 -1
  40. package/dist/{platform-environment.js → platform/environment.js} +12 -12
  41. package/dist/platform/http.d.ts +7 -0
  42. package/dist/platform/http.js +105 -0
  43. package/dist/{platform-operations.d.ts → platform/operations.d.ts} +1 -1
  44. package/dist/{platform-operations.js → platform/operations.js} +5 -5
  45. package/dist/platform/output.d.ts +2 -0
  46. package/dist/platform/output.js +79 -0
  47. package/dist/{platform-production.d.ts → platform/production.d.ts} +1 -1
  48. package/dist/{platform-production.js → platform/production.js} +4 -4
  49. package/dist/platform/projects.d.ts +12 -0
  50. package/dist/platform/projects.js +125 -0
  51. package/dist/{platform-source.js → platform/source.js} +7 -7
  52. package/dist/platform/state-schema.d.ts +25 -0
  53. package/dist/platform/state-schema.js +11 -0
  54. package/dist/{platform-state.d.ts → platform/state.d.ts} +1 -1
  55. package/dist/{platform-state.js → platform/state.js} +3 -4
  56. package/dist/platform/types.d.ts +26 -0
  57. package/dist/platform/upload.d.ts +2 -0
  58. package/dist/platform/upload.js +60 -0
  59. package/dist/process/runner.d.ts +1 -0
  60. package/dist/{command-runner.js → process/runner.js} +1 -1
  61. package/dist/registry/usage.d.ts +1 -0
  62. package/dist/{platforms → scaffold}/tanstack.d.ts +2 -2
  63. package/dist/{platforms → scaffold}/tanstack.js +2 -2
  64. package/dist/transactions/durable-files.d.ts +8 -0
  65. package/dist/transactions/durable-files.js +132 -0
  66. package/dist/transactions/journal.d.ts +4 -0
  67. package/dist/transactions/journal.js +141 -0
  68. package/dist/{transaction-lock.js → transactions/lock.js} +2 -2
  69. package/dist/transactions/model.d.ts +18 -0
  70. package/dist/transactions/model.js +4 -0
  71. package/dist/transactions/paths.d.ts +12 -0
  72. package/dist/transactions/paths.js +155 -0
  73. package/dist/transactions/recovery.d.ts +7 -0
  74. package/dist/transactions/recovery.js +132 -0
  75. package/dist/{transaction.d.ts → transactions/transaction.d.ts} +1 -2
  76. package/dist/transactions/transaction.js +179 -0
  77. package/dist/util.js +2 -2
  78. package/dist/version.d.ts +1 -1
  79. package/dist/version.js +1 -1
  80. package/docs/capabilities.md +8 -6
  81. package/docs/software-factory.md +36 -6
  82. package/package.json +22 -22
  83. package/dist/platform-command.js +0 -787
  84. package/dist/transaction.js +0 -716
  85. /package/dist/{capability-editor.d.ts → composition/editor.d.ts} +0 -0
  86. /package/dist/{capability-references.d.ts → composition/references.d.ts} +0 -0
  87. /package/dist/{credential-helper.d.ts → platform/credential-helper.d.ts} +0 -0
  88. /package/dist/{platform-source.d.ts → platform/source.d.ts} +0 -0
  89. /package/dist/{command-runner.d.ts → platform/types.js} +0 -0
  90. /package/dist/{command.d.ts → process/resolve-command.d.ts} +0 -0
  91. /package/dist/{command.js → process/resolve-command.js} +0 -0
  92. /package/dist/{transaction-lock.d.ts → transactions/lock.d.ts} +0 -0
@@ -76,65 +76,6 @@ export declare const deploymentManifestSchema: z.ZodObject<{
76
76
  }>;
77
77
  }, z.core.$strict>;
78
78
  }, z.core.$strict>;
79
- export declare const deploymentSourceSchema: z.ZodObject<{
80
- inventoryVersion: z.ZodLiteral<2>;
81
- inventoryProfile: z.ZodString;
82
- sourceDigest: z.ZodString;
83
- lockfileDigest: z.ZodString;
84
- manifestDigest: z.ZodString;
85
- }, z.core.$strict>;
86
- export declare const deploymentPlanSchema: z.ZodObject<{
87
- contractVersion: z.ZodLiteral<1>;
88
- requestId: z.ZodUUID;
89
- projectId: z.ZodUUID;
90
- manifest: z.ZodObject<{
91
- contractVersion: z.ZodLiteral<1>;
92
- foundation: z.ZodLiteral<"tanstack-start">;
93
- capabilities: z.ZodArray<z.ZodEnum<{
94
- hono: "hono";
95
- "database-auth": "database-auth";
96
- r2: "r2";
97
- stripe: "stripe";
98
- }>>;
99
- identity: z.ZodEnum<{
100
- none: "none";
101
- "better-auth-d1-v1": "better-auth-d1-v1";
102
- }>;
103
- cliArtifact: z.ZodObject<{
104
- version: z.ZodString;
105
- sourceRevision: z.ZodString;
106
- packageIntegrity: z.ZodString;
107
- }, z.core.$strict>;
108
- intent: z.ZodObject<{
109
- contractVersion: z.ZodLiteral<1>;
110
- runtimeProfile: z.ZodLiteral<"anhedral-stack">;
111
- environment: z.ZodEnum<{
112
- production: "production";
113
- preview: "preview";
114
- }>;
115
- visibility: z.ZodEnum<{
116
- protected: "protected";
117
- public: "public";
118
- }>;
119
- }, z.core.$strict>;
120
- }, z.core.$strict>;
121
- source: z.ZodObject<{
122
- inventoryVersion: z.ZodLiteral<2>;
123
- inventoryProfile: z.ZodString;
124
- sourceDigest: z.ZodString;
125
- lockfileDigest: z.ZodString;
126
- manifestDigest: z.ZodString;
127
- }, z.core.$strict>;
128
- policyDigest: z.ZodString;
129
- runtimeImage: z.ZodString;
130
- configurationRevision: z.ZodString;
131
- expectedGeneration: z.ZodNumber;
132
- migrationDigests: z.ZodArray<z.ZodString>;
133
- requiredAuthority: z.ZodEnum<{
134
- preview: "preview";
135
- "production-approval": "production-approval";
136
- }>;
137
- }, z.core.$strict>;
138
79
  export declare const deploymentErrorSchema: z.ZodObject<{
139
80
  code: z.ZodEnum<{
140
81
  INVALID_MANIFEST: "INVALID_MANIFEST";
@@ -156,13 +97,13 @@ export declare const deploymentEventSchema: z.ZodObject<{
156
97
  sequence: z.ZodNumber;
157
98
  state: z.ZodEnum<{
158
99
  queued: "queued";
159
- preparing: "preparing";
160
- ready: "ready";
161
- failed: "failed";
162
100
  uploading: "uploading";
163
101
  building: "building";
102
+ preparing: "preparing";
164
103
  verifying: "verifying";
165
104
  "awaiting-approval": "awaiting-approval";
105
+ ready: "ready";
106
+ failed: "failed";
166
107
  cancelled: "cancelled";
167
108
  }>;
168
109
  occurredAt: z.ZodISODateTime;
@@ -174,9 +115,9 @@ export declare const deploymentResultSchema: z.ZodDiscriminatedUnion<[z.ZodObjec
174
115
  status: z.ZodLiteral<"pending">;
175
116
  state: z.ZodEnum<{
176
117
  queued: "queued";
177
- preparing: "preparing";
178
118
  uploading: "uploading";
179
119
  building: "building";
120
+ preparing: "preparing";
180
121
  verifying: "verifying";
181
122
  "awaiting-approval": "awaiting-approval";
182
123
  }>;
@@ -223,8 +164,6 @@ export declare const deploymentResultSchema: z.ZodDiscriminatedUnion<[z.ZodObjec
223
164
  requestId: z.ZodUUID;
224
165
  }, z.core.$strict>], "status">;
225
166
  export type DeploymentManifest = z.infer<typeof deploymentManifestSchema>;
226
- export type DeploymentPlan = z.infer<typeof deploymentPlanSchema>;
227
- export type DeploymentSource = z.infer<typeof deploymentSourceSchema>;
228
167
  export type DeploymentIntent = z.infer<typeof deploymentIntentSchema>;
229
168
  export type DeploymentEvent = z.infer<typeof deploymentEventSchema>;
230
169
  export type DeploymentResult = z.infer<typeof deploymentResultSchema>;
@@ -73,35 +73,6 @@ export const deploymentManifestSchema = z
73
73
  message: `${id} requires ${parent}.`,
74
74
  });
75
75
  });
76
- export const deploymentSourceSchema = z
77
- .object({
78
- inventoryVersion: z.literal(2),
79
- inventoryProfile: z.string().min(1).max(100),
80
- sourceDigest: deploymentDigestSchema,
81
- lockfileDigest: deploymentDigestSchema,
82
- manifestDigest: deploymentDigestSchema,
83
- })
84
- .strict();
85
- const runtimeImageSchema = z
86
- .string()
87
- .regex(/^registry\.[a-z0-9.-]+\/[a-zA-Z0-9/_.-]+@sha256:[a-f0-9]{64}$/);
88
- export const deploymentPlanSchema = z
89
- .object({
90
- contractVersion: z.literal(1),
91
- requestId: z.uuid(),
92
- projectId: z.uuid(),
93
- manifest: deploymentManifestSchema,
94
- source: deploymentSourceSchema,
95
- policyDigest: deploymentDigestSchema,
96
- runtimeImage: runtimeImageSchema,
97
- configurationRevision: deploymentDigestSchema,
98
- expectedGeneration: z.number().int().nonnegative(),
99
- migrationDigests: z.array(deploymentDigestSchema).max(100),
100
- requiredAuthority: z.enum(["preview", "production-approval"]),
101
- })
102
- .strict()
103
- .refine((plan) => plan.requiredAuthority ===
104
- (plan.manifest.intent.environment === "production" ? "production-approval" : "preview"), "Production requires exact-candidate approval.");
105
76
  export const deploymentErrorSchema = z
106
77
  .object({
107
78
  code: z.enum([
@@ -1,3 +1,6 @@
1
+ export declare const ENVIRONMENT_FILE_MAX_BYTES = 65536;
2
+ export declare class EnvironmentFileError extends Error {
3
+ }
1
4
  /** Literal dotenv parsing only. Never evaluate a shell, interpolate variables,
2
5
  * or include input values in errors. The same parser serves browser and CLI. */
3
6
  export declare function parseEnvironmentFile(input: string): {
@@ -1,18 +1,21 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  import { environmentNameSchema } from "./environment-transport.js";
3
+ export const ENVIRONMENT_FILE_MAX_BYTES = 65536;
4
+ export class EnvironmentFileError extends Error {
5
+ }
3
6
  /** Literal dotenv parsing only. Never evaluate a shell, interpolate variables,
4
7
  * or include input values in errors. The same parser serves browser and CLI. */
5
8
  export function parseEnvironmentFile(input) {
6
9
  if (input.includes("\0"))
7
- throw new Error("Environment files cannot contain NUL bytes.");
8
- if (new TextEncoder().encode(input).length > 65536)
9
- throw new Error("Environment files support at most 64 KiB.");
10
+ throw new EnvironmentFileError("Environment files cannot contain NUL bytes.");
11
+ if (new TextEncoder().encode(input).length > ENVIRONMENT_FILE_MAX_BYTES)
12
+ throw new EnvironmentFileError("Environment files support at most 64 KiB.");
10
13
  const text = input.replace(/^\uFEFF/, "").replaceAll("\r\n", "\n");
11
14
  const entries = [];
12
15
  const names = new Set();
13
16
  let position = 0, line = 1;
14
17
  const fail = (message) => {
15
- throw new Error(`Line ${line}: ${message}`);
18
+ throw new EnvironmentFileError(`Line ${line}: ${message}`);
16
19
  };
17
20
  const space = () => {
18
21
  while (text[position] === " " || text[position] === "\t" || text[position] === "\r")
@@ -104,7 +107,7 @@ export function parseEnvironmentFile(input) {
104
107
  }
105
108
  }
106
109
  if (!entries.length)
107
- throw new Error("The environment file contains no variables.");
110
+ throw new EnvironmentFileError("The environment file contains no variables.");
108
111
  return entries;
109
112
  }
110
113
  export function inferredEnvironmentKind(name) {
@@ -32,9 +32,9 @@ export declare const productionDeploymentSchema: z.ZodObject<{
32
32
  queued: "queued";
33
33
  preparing: "preparing";
34
34
  ready: "ready";
35
- published: "published";
36
35
  failed: "failed";
37
36
  superseded: "superseded";
37
+ published: "published";
38
38
  }>;
39
39
  sourceRevision: z.ZodString;
40
40
  createdAt: z.ZodString;
@@ -57,9 +57,9 @@ export declare const productionStateSchema: z.ZodObject<{
57
57
  queued: "queued";
58
58
  preparing: "preparing";
59
59
  ready: "ready";
60
- published: "published";
61
60
  failed: "failed";
62
61
  superseded: "superseded";
62
+ published: "published";
63
63
  }>;
64
64
  sourceRevision: z.ZodString;
65
65
  createdAt: z.ZodString;
@@ -19,8 +19,8 @@ export declare const stagingDeploymentSchema: z.ZodObject<{
19
19
  preparing: "preparing";
20
20
  ready: "ready";
21
21
  failed: "failed";
22
- superseded: "superseded";
23
22
  deployed: "deployed";
23
+ superseded: "superseded";
24
24
  }>;
25
25
  summary: z.ZodNullable<z.ZodString>;
26
26
  sourceRevision: z.ZodString;
@@ -48,8 +48,8 @@ export declare const stagingStateSchema: z.ZodObject<{
48
48
  preparing: "preparing";
49
49
  ready: "ready";
50
50
  failed: "failed";
51
- superseded: "superseded";
52
51
  deployed: "deployed";
52
+ superseded: "superseded";
53
53
  }>;
54
54
  summary: z.ZodNullable<z.ZodString>;
55
55
  sourceRevision: z.ZodString;
@@ -26,7 +26,7 @@ export declare const STACK_DEPENDENCIES: {
26
26
  readonly '@types/node': "22.20.5";
27
27
  readonly eslint: "9.39.5";
28
28
  readonly 'drizzle-kit': "0.31.11";
29
- readonly hono: "4.13.13";
29
+ readonly hono: "4.13.18";
30
30
  readonly '@hono/zod-openapi': "1.6.3";
31
31
  readonly fallow: "3.34.0";
32
32
  readonly undici: "7.30.1";
@@ -75,7 +75,7 @@ export const STACK_DEPENDENCIES = {
75
75
  // renovate: datasource=npm depName=drizzle-kit
76
76
  'drizzle-kit': '0.31.11',
77
77
  // renovate: datasource=npm depName=hono
78
- hono: '4.13.13',
78
+ hono: '4.13.18',
79
79
  // renovate: datasource=npm depName=@hono/zod-openapi
80
80
  '@hono/zod-openapi': '1.6.3',
81
81
  // renovate: datasource=npm depName=fallow
package/dist/launch.js CHANGED
@@ -2,14 +2,14 @@ import { existsSync, lstatSync, mkdirSync, readdirSync, realpathSync, rmdirSync
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { spawnSync } from 'node:child_process';
4
4
  import path from 'node:path';
5
- import { scaffoldTanstack } from './platforms/tanstack.js';
5
+ import { scaffoldTanstack } from './scaffold/tanstack.js';
6
6
  import { bootstrapWorkspace, assertWorkspaceRuntime } from './scaffold/bootstrap.js';
7
7
  import { scaffoldStyling } from './scaffold/styling.js';
8
8
  import { json, put, sharedPackage } from './scaffold/files.js';
9
- import { CapabilityEditor } from './capability-editor.js';
10
- import { addCapabilityRecipe, composeCapabilities } from './capability-recipes.js';
11
- import { launchCompositionSchema } from './composition.js';
12
- import { runStagedTransaction } from './transaction.js';
9
+ import { CapabilityEditor } from './composition/editor.js';
10
+ import { addCapabilityRecipe, composeCapabilities } from './composition/recipes.js';
11
+ import { launchCompositionSchema } from './composition/composition.js';
12
+ import { runStagedTransaction } from './transactions/transaction.js';
13
13
  import { configureDependencyPatches, writeDependencyAudit } from './dependency-patches.js';
14
14
  import { setPnpmPolicy } from './pnpm-policy.js';
15
15
  import { GENERATOR_VERSION } from './version.js';
@@ -117,9 +117,9 @@ Keep LICENSE.shadcn with the copied starter components.
117
117
  ## Add services progressively
118
118
 
119
119
  Run anhedral add backend to add Hono, Drizzle/D1 and Better Auth together.
120
- Then run anhedral add r2 for private storage, or anhedral add stripe for payments.
120
+ Then run anhedral add storage for private storage, or anhedral add payment for payments.
121
121
  Missing prerequisites stop before writes; --with-dependencies opts into them.
122
- The public additions are backend, r2 and stripe; this application is web-only.
122
+ The public additions are backend, storage and payment; this application is web-only.
123
123
 
124
124
  After adding backend, copy apps/api/.dev.vars.example to apps/api/.dev.vars.
125
125
  Set PUBLIC_APP_URL=http://localhost:3000 and generate BETTER_AUTH_SECRET with
@@ -150,7 +150,7 @@ requires its separately reviewed Anhedral Stack runtime/artifact; generation is
150
150
  put(root, 'AGENTS.md', `# Anhedral Stack application
151
151
 
152
152
  Use the single Anhedral Stack, starting with TanStack Start and source-owned shadcn UI. Add backend for Hono,
153
- Drizzle/D1 and Better Auth together. Add r2 and stripe only when required. Mobile,
153
+ Drizzle/D1 and Better Auth together. Use the storage and payment additions only when required. Mobile,
154
154
  extensions and desktop are outside launch scope.
155
155
 
156
156
  Edit web product routes in apps/web/src/routes, API routes in apps/api/src/index.ts,
@@ -0,0 +1,14 @@
1
+ import { commandArguments } from '../cli-arguments.js';
2
+ import { createReporter } from '../cli-output.js';
3
+ import { type SecretStore } from './state.js';
4
+ type Request = (path: string, method: string, body?: unknown) => Promise<unknown>;
5
+ export declare function runLogin({ options, origin, reporter, store, readCredential, request, sleep, }: {
6
+ options: ReturnType<typeof commandArguments>;
7
+ origin: string;
8
+ reporter: ReturnType<typeof createReporter>;
9
+ store: SecretStore;
10
+ readCredential: () => Promise<unknown>;
11
+ request: Request;
12
+ sleep?: (ms: number) => Promise<void>;
13
+ }): Promise<void>;
14
+ export {};
@@ -0,0 +1,62 @@
1
+ import { z } from 'zod';
2
+ import { commandArgumentError, commandArguments } from '../cli-arguments.js';
3
+ import { createReporter } from '../cli-output.js';
4
+ import { cliDeviceSchema, cliLoginSchema } from '../contracts/cli-transport.js';
5
+ import { platformFailure } from './state.js';
6
+ const pending = z
7
+ .object({ origin: z.string(), device: cliDeviceSchema, expiresAt: z.number() })
8
+ .strict();
9
+ export async function runLogin({ options, origin, reporter, store, readCredential, request, sleep, }) {
10
+ const emit = (result) => reporter.result(result);
11
+ if (options.positional.length)
12
+ throw commandArgumentError('login', 'Login does not accept positional arguments.');
13
+ let state = pending.safeParse(await readCredential());
14
+ if (!options.has('--resume') ||
15
+ !state.success ||
16
+ state.data.origin !== origin ||
17
+ state.data.expiresAt <= Date.now()) {
18
+ const device = cliDeviceSchema.parse(await request('/auth/code', 'POST', {}));
19
+ if (new URL(device.verification_uri_complete).origin !== origin ||
20
+ new URL(device.verification_uri_complete).protocol !== new URL(origin).protocol)
21
+ throw platformFailure('Platform returned an unexpected verification origin.');
22
+ const saved = { origin, device, expiresAt: Date.now() + device.expires_in * 1000 };
23
+ await store.write(saved);
24
+ state = pending.safeParse(saved);
25
+ }
26
+ if (!state.success)
27
+ throw platformFailure('Login state is unavailable. Start login again.');
28
+ const saved = state.data;
29
+ if (options.has('--start') || (!reporter.canPrompt && !options.has('--resume'))) {
30
+ emit({
31
+ status: 'authorization_required',
32
+ verificationUrl: saved.device.verification_uri_complete,
33
+ userCode: saved.device.user_code,
34
+ expiresAt: new Date(saved.expiresAt).toISOString(),
35
+ nextAction: 'Approve in your browser, then run anhedral login --resume with the same API origin and credential store.',
36
+ });
37
+ return;
38
+ }
39
+ reporter.diagnostic(`Approve CLI access at ${saved.device.verification_uri_complete}\nConfirm code ${saved.device.user_code}.`);
40
+ let interval = saved.device.interval * 1000;
41
+ while (Date.now() < saved.expiresAt) {
42
+ await (sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(interval);
43
+ const result = await request('/auth/token', 'POST', {
44
+ device_code: saved.device.device_code,
45
+ });
46
+ const grant = cliLoginSchema.safeParse(result);
47
+ if (grant.success) {
48
+ await store.write({ ...grant.data, origin });
49
+ emit({ status: 'authenticated', origin, expiresAt: grant.data.expiresAt });
50
+ return;
51
+ }
52
+ const error = result.error;
53
+ if (error === 'slow_down')
54
+ interval += 5000;
55
+ else if (error !== 'authorization_pending') {
56
+ await store.clear();
57
+ throw platformFailure('Device approval was denied or expired. Start login again.');
58
+ }
59
+ }
60
+ await store.clear();
61
+ throw platformFailure('Device approval expired. Start login again.');
62
+ }
@@ -1,5 +1,5 @@
1
- import { type OutputOptions } from './cli-output.js';
2
- import { type SecretStore } from './platform-state.js';
1
+ import { type OutputOptions } from '../cli-output.js';
2
+ import { type SecretStore } from './state.js';
3
3
  interface PlatformDependencies {
4
4
  store?: SecretStore;
5
5
  fetch?: typeof fetch;
@@ -0,0 +1,279 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { unlink } from 'node:fs/promises';
3
+ import { join, resolve } from 'node:path';
4
+ import { z } from 'zod';
5
+ import { CliArgumentError, commandArgumentError, commandArguments } from '../cli-arguments.js';
6
+ import { CliFailure } from '../cli-errors.js';
7
+ import { createReporter } from '../cli-output.js';
8
+ import { cliLinkSchema, cliLoginSchema } from '../contracts/cli-transport.js';
9
+ import { runLogin } from './auth.js';
10
+ import { runDeploy } from './deploy.js';
11
+ import { runEnvironmentCommand, validateEnvironmentArguments } from './environment.js';
12
+ import { createPlatformRequest } from './http.js';
13
+ import { runLogsCommand, runStagingCommand, validateLogsArguments, validateStagingArguments, } from './operations.js';
14
+ import { formatPlatformResult } from './output.js';
15
+ import { runProductionCommand, validateProductionArguments } from './production.js';
16
+ import { runProjects, validateProjects } from './projects.js';
17
+ import { packageSource } from './source.js';
18
+ import { linkSchema } from './state-schema.js';
19
+ import { platformFailure as createPlatformFailure, platformOrigin, readPrivate, secretStore, withProjectLock, writePrivate, } from './state.js';
20
+ import { runSourceUpload } from './upload.js';
21
+ const credential = cliLoginSchema.extend({ origin: z.string() });
22
+ const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
23
+ export async function runPlatformCommand(command, args, output, dependencies = {}) {
24
+ try {
25
+ await runPlatformOperation(command, args, output, dependencies);
26
+ }
27
+ catch (error) {
28
+ if (error instanceof CliArgumentError || error instanceof CliFailure)
29
+ throw error;
30
+ if (error instanceof z.ZodError)
31
+ throw createPlatformFailure('Platform data or saved context does not match the supported protocol. Preserve saved state and verify the selected context before retrying.', `Run anhedral ${command} --help.`, 'context');
32
+ if (error instanceof SyntaxError)
33
+ throw createPlatformFailure('Selected local Platform input is not valid JSON. Preserve saved state and review the selected input before retrying.', `Run anhedral ${command} --help.`, 'context');
34
+ if (['ENOENT', 'ENOTDIR', 'EISDIR', 'EACCES', 'EPERM'].includes(error?.code ?? ''))
35
+ throw createPlatformFailure('A required local Platform file is missing or inaccessible. Review the selected working directory, manifest and credential store.', `Run anhedral ${command} --help.`, 'context');
36
+ throw error;
37
+ }
38
+ }
39
+ async function runPlatformOperation(command, args, output, dependencies) {
40
+ const reporter = createReporter(output, (result) => formatPlatformResult(command, result), true);
41
+ const platformFailure = (message, category = 'context', retryable = false, nextAction = `Run anhedral ${command} --help.`) => createPlatformFailure(message, nextAction, category, retryable);
42
+ const options = commandArguments(command, args), origin = platformOrigin(options.value('--api-url'));
43
+ if (command === 'env')
44
+ validateEnvironmentArguments(args);
45
+ if (command === 'staging')
46
+ validateStagingArguments(args);
47
+ if (command === 'production')
48
+ validateProductionArguments(args);
49
+ if (command === 'logs')
50
+ validateLogsArguments(args);
51
+ const emit = (result) => reporter.result(result);
52
+ if (['login', 'logout', 'whoami', 'link', 'unlink'].includes(command) &&
53
+ options.positional.length)
54
+ throw commandArgumentError(command, 'Unexpected positional arguments.');
55
+ if (command === 'login' && options.has('--start') && options.has('--resume'))
56
+ throw commandArgumentError(command, 'Choose --start or --resume.');
57
+ if (command === 'source' &&
58
+ (options.positional.length !== 1 || !['upload', 'status'].includes(options.positional[0])))
59
+ throw commandArgumentError(command, 'Use source upload or source status.');
60
+ if (command === 'deploy' &&
61
+ (options.positional.length !== 1 ||
62
+ !['plan', 'prepare', 'status'].includes(options.positional[0])))
63
+ throw commandArgumentError(command, 'Use deploy plan, deploy prepare or deploy status.');
64
+ if (command === 'deploy' &&
65
+ options.positional[0] !== 'plan' &&
66
+ (options.has('--manifest') || options.has('--new')))
67
+ throw commandArgumentError(command, 'Manifest and --new options apply to deploy plan only.');
68
+ if (command === 'link' &&
69
+ (!z.uuid().safeParse(options.value('--project')).success ||
70
+ !z.uuid().safeParse(options.value('--team')).success))
71
+ throw commandArgumentError(command, 'Supply existing project and team UUIDs with --project and --team.');
72
+ const projectInput = command === 'projects' ? validateProjects(options) : undefined;
73
+ if (command === 'projects' && projectInput && options.has('--dry-run')) {
74
+ emit({
75
+ status: 'dry_run',
76
+ ...projectInput,
77
+ teamId: options.value('--team') ?? null,
78
+ link: options.has('--link'),
79
+ initialization: 'source-upload',
80
+ });
81
+ return;
82
+ }
83
+ const root = process.cwd(), stateDir = join(root, '.anhedral', 'platform'), linkPath = join(stateDir, 'project.json'), uploadPath = join(stateDir, 'upload.json');
84
+ if (command === 'unlink') {
85
+ if ((await readPrivate(linkPath)) === null) {
86
+ emit({ status: 'unlinked' });
87
+ return;
88
+ }
89
+ await withProjectLock(stateDir, async () => {
90
+ await readPrivate(linkPath);
91
+ await unlink(linkPath).catch((e) => {
92
+ if (e.code !== 'ENOENT')
93
+ throw e;
94
+ });
95
+ });
96
+ emit({ status: 'unlinked' });
97
+ return;
98
+ }
99
+ if (command === 'env' && options.has('--dry-run'))
100
+ return runEnvironmentCommand(args, output);
101
+ if (command === 'source' && options.has('--dry-run')) {
102
+ if (options.positional[0] !== 'upload')
103
+ throw commandArgumentError(command, 'Use source upload --dry-run.');
104
+ const source = await packageSource(root), archiveDigest = hash(source.archive);
105
+ emit({
106
+ status: 'dry_run',
107
+ archiveDigest,
108
+ inventoryDigest: source.inventoryDigest,
109
+ files: source.files,
110
+ includedPaths: source.paths,
111
+ bytes: source.bytes,
112
+ archiveBytes: source.archive.length,
113
+ });
114
+ return;
115
+ }
116
+ const store = dependencies.store ??
117
+ secretStore(origin, options.value('--credential-file') ? resolve(options.value('--credential-file')) : undefined);
118
+ const readCredential = async () => {
119
+ try {
120
+ return await store.read();
121
+ }
122
+ catch (error) {
123
+ if (error instanceof SyntaxError)
124
+ throw platformFailure('Saved credential data is not valid JSON. Preserve it and reconcile the selected credential store.', 'auth', false, 'Run anhedral login --help.');
125
+ throw error;
126
+ }
127
+ };
128
+ const request = createPlatformRequest({
129
+ command,
130
+ operation: options.positional[0],
131
+ origin,
132
+ fetch: dependencies.fetch,
133
+ });
134
+ if (command === 'login')
135
+ return runLogin({
136
+ options,
137
+ origin,
138
+ reporter,
139
+ store,
140
+ readCredential,
141
+ request,
142
+ sleep: dependencies.sleep,
143
+ });
144
+ const saved = credential.safeParse(await readCredential());
145
+ if (!saved.success || saved.data.origin !== origin)
146
+ throw platformFailure('Log in to the selected API origin first.', 'auth', false, 'Run anhedral login with the same API origin and credential store.');
147
+ const token = saved.data.token;
148
+ if (command === 'logout') {
149
+ await request('/auth/logout', 'POST', {}, token);
150
+ try {
151
+ await store.clear();
152
+ }
153
+ catch {
154
+ throw platformFailure('Platform access was revoked, but the saved local credential could not be removed.', 'context', false, 'Remove the saved credential from the selected credential store before signing in again.');
155
+ }
156
+ emit({ status: 'logged_out', origin });
157
+ return;
158
+ }
159
+ const actor = z
160
+ .object({
161
+ protocol: z.literal(1),
162
+ principalId: z.uuid(),
163
+ name: z.string(),
164
+ teamId: z.uuid().nullable(),
165
+ })
166
+ .parse(await request('/actor', 'GET', undefined, token));
167
+ if (command === 'whoami') {
168
+ const identity = { ...actor, origin, expiresAt: saved.data.expiresAt };
169
+ if (!options.has('--context')) {
170
+ emit(identity);
171
+ return;
172
+ }
173
+ const savedLink = await readPrivate(linkPath);
174
+ const localLink = savedLink === null ? null : linkSchema.safeParse(savedLink);
175
+ if (localLink &&
176
+ (!localLink.success ||
177
+ localLink.data.origin !== origin ||
178
+ localLink.data.principalId !== actor.principalId))
179
+ throw platformFailure('The saved project link does not match the selected API origin and signed-in identity. Preserve it and explicitly link the intended project.', 'context', false, 'Run anhedral link --help.');
180
+ const file = options.value('--credential-file');
181
+ emit({
182
+ ...identity,
183
+ context: {
184
+ apiOrigin: { value: origin, source: options.has('--api-url') ? 'flag' : 'default' },
185
+ identityVerification: 'live-platform',
186
+ credential: {
187
+ source: file ? 'flag' : dependencies.store ? 'injected' : 'os-secret-store',
188
+ kind: file
189
+ ? 'owner-only-file'
190
+ : dependencies.store
191
+ ? 'injected'
192
+ : process.platform === 'darwin'
193
+ ? 'macos-keychain'
194
+ : process.platform === 'linux'
195
+ ? 'linux-secret-service'
196
+ : 'unsupported',
197
+ },
198
+ project: localLink && localLink.success
199
+ ? {
200
+ projectId: localLink.data.projectId,
201
+ teamId: localLink.data.teamId,
202
+ name: localLink.data.name,
203
+ source: '.anhedral/platform/project.json',
204
+ verification: 'saved-local-link',
205
+ access: 'not-verified',
206
+ }
207
+ : null,
208
+ },
209
+ });
210
+ return;
211
+ }
212
+ if (command === 'projects')
213
+ return runProjects({
214
+ options,
215
+ origin,
216
+ actor,
217
+ token,
218
+ stateDir,
219
+ linkPath,
220
+ request,
221
+ emit,
222
+ platformFailure,
223
+ projectInput,
224
+ });
225
+ if (command === 'link') {
226
+ await withProjectLock(stateDir, async () => {
227
+ const input = z
228
+ .object({ projectId: z.uuid(), teamId: z.uuid() })
229
+ .parse({ projectId: options.value('--project'), teamId: options.value('--team') });
230
+ if (options.positional.length)
231
+ throw commandArgumentError(command, 'Use --project and --team.');
232
+ const link = cliLinkSchema.parse(await request('/link', 'POST', input, token, input.teamId));
233
+ if (link.principalId !== actor.principalId ||
234
+ link.projectId !== input.projectId ||
235
+ link.teamId !== input.teamId)
236
+ throw platformFailure('Project link identity differs.');
237
+ await writePrivate(linkPath, { ...link, origin });
238
+ emit({ ...link, origin });
239
+ });
240
+ return;
241
+ }
242
+ if (['env', 'staging', 'production', 'logs'].includes(command)) {
243
+ const link = linkSchema.parse(await readPrivate(linkPath));
244
+ if (link.origin !== origin || link.principalId !== actor.principalId)
245
+ throw platformFailure('Link this project to the selected API origin and signed-in identity.');
246
+ const operation = command === 'env'
247
+ ? runEnvironmentCommand
248
+ : command === 'staging'
249
+ ? runStagingCommand
250
+ : command === 'production'
251
+ ? runProductionCommand
252
+ : runLogsCommand;
253
+ return operation(args, output, { origin, principalId: actor.principalId, projectId: link.projectId, teamId: link.teamId }, (path, method, body) => request(path, method, body, token, link.teamId));
254
+ }
255
+ if (!['source', 'deploy'].includes(command) ||
256
+ options.positional.length !== 1 ||
257
+ !(command === 'deploy' ? ['plan', 'prepare', 'status'] : ['upload', 'status']).includes(options.positional[0]))
258
+ throw commandArgumentError(command, 'Use source upload/status or deploy plan/prepare/status.');
259
+ const link = linkSchema.parse(await readPrivate(linkPath));
260
+ if (link.origin !== origin || link.principalId !== actor.principalId)
261
+ throw platformFailure('Link this project to the selected API origin and signed-in identity.');
262
+ const sourceOperation = {
263
+ options,
264
+ origin,
265
+ actor,
266
+ token,
267
+ stateDir,
268
+ linkPath,
269
+ link,
270
+ uploadPath,
271
+ root,
272
+ request,
273
+ emit,
274
+ platformFailure,
275
+ };
276
+ if (command === 'deploy')
277
+ return runDeploy(sourceOperation);
278
+ return runSourceUpload(sourceOperation);
279
+ }
@@ -1,6 +1,6 @@
1
1
  import { lstat, realpath } from 'node:fs/promises';
2
2
  import { dirname, isAbsolute, join, parse } from 'node:path';
3
- import { CliFailure } from './cli-errors.js';
3
+ import { CliFailure } from '../cli-errors.js';
4
4
  const unavailable = () => new CliFailure('A trusted Linux Secret Service helper is unavailable.', 'PLATFORM_ACCESS_FAILED', 'Install a system-owned secret-tool, explicitly select a trusted system helper with ANHEDRAL_CLI_SECRET_TOOL_PATH, or use --credential-file.', 'context', false);
5
5
  async function safePath(path, executable) {
6
6
  // Validate the original chain as well as the canonical chain: an untrusted