anhedral 0.10.1 → 0.11.1

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 (183) hide show
  1. package/README.md +79 -124
  2. package/assets/patches/LICENSE.braces +21 -0
  3. package/assets/patches/LICENSE.node-forge +50 -0
  4. package/assets/patches/audit-deps.mjs +167 -0
  5. package/assets/patches/braces@3.0.3.patch +127 -0
  6. package/assets/patches/node-forge@1.4.0.patch +41 -0
  7. package/dist/auth-schema.js +3 -3
  8. package/dist/bin.js +284 -163
  9. package/dist/capabilities.d.ts +4 -4
  10. package/dist/capabilities.js +6 -2
  11. package/dist/capability-contract.d.ts +47 -0
  12. package/dist/capability-contract.js +153 -0
  13. package/dist/catalog-model.d.ts +24 -0
  14. package/dist/catalog-model.js +1 -0
  15. package/dist/catalog-registration.d.ts +16 -0
  16. package/dist/catalog-registration.js +22 -0
  17. package/dist/catalog-snapshot.d.ts +5 -0
  18. package/dist/catalog-snapshot.js +97 -0
  19. package/dist/cli-arguments.d.ts +16 -0
  20. package/dist/cli-arguments.js +115 -0
  21. package/dist/cli-output.d.ts +8 -0
  22. package/dist/cli-output.js +236 -0
  23. package/dist/cloudflare.d.ts +14 -3
  24. package/dist/cloudflare.js +196 -36
  25. package/dist/command-schema.d.ts +21 -0
  26. package/dist/command-schema.js +418 -0
  27. package/dist/delivery.d.ts +12 -5
  28. package/dist/delivery.js +173 -39
  29. package/dist/dependencies.d.ts +24 -0
  30. package/dist/dependencies.js +48 -0
  31. package/dist/dependency-patches.d.ts +7 -0
  32. package/dist/dependency-patches.js +125 -0
  33. package/dist/index.d.ts +26 -1
  34. package/dist/index.js +17 -1
  35. package/dist/inspector-model.d.ts +123 -0
  36. package/dist/inspector-model.js +1 -0
  37. package/dist/integration-service-readers.d.ts +13 -0
  38. package/dist/integration-service-readers.js +173 -0
  39. package/dist/lifecycle-model.d.ts +15 -0
  40. package/dist/lifecycle-model.js +20 -0
  41. package/dist/lifecycle.d.ts +11 -0
  42. package/dist/lifecycle.js +91 -0
  43. package/dist/mobile-delivery.d.ts +100 -0
  44. package/dist/mobile-delivery.js +319 -0
  45. package/dist/neon-service-data.d.ts +8 -0
  46. package/dist/neon-service-data.js +117 -0
  47. package/dist/platforms/mobile.js +8 -5
  48. package/dist/pnpm-policy.d.ts +2 -2
  49. package/dist/pnpm-policy.js +19 -45
  50. package/dist/project-catalog.d.ts +41 -0
  51. package/dist/project-catalog.js +288 -0
  52. package/dist/project-config.d.ts +14 -0
  53. package/dist/project-config.js +89 -0
  54. package/dist/project-inspector.d.ts +4 -0
  55. package/dist/project-inspector.js +702 -0
  56. package/dist/project-lifecycle.d.ts +25 -0
  57. package/dist/project-lifecycle.js +57 -0
  58. package/dist/project-state.d.ts +22 -1
  59. package/dist/project-state.js +361 -27
  60. package/dist/provider-auth.d.ts +41 -0
  61. package/dist/provider-auth.js +209 -0
  62. package/dist/provider-readiness.js +27 -10
  63. package/dist/providers/adapters.d.ts +17 -0
  64. package/dist/providers/adapters.js +272 -0
  65. package/dist/providers/api.d.ts +29 -0
  66. package/dist/providers/api.js +253 -0
  67. package/dist/providers/config.d.ts +15 -0
  68. package/dist/providers/config.js +182 -0
  69. package/dist/providers/definitions.d.ts +318 -0
  70. package/dist/providers/definitions.js +127 -0
  71. package/dist/providers/provision.d.ts +24 -0
  72. package/dist/providers/provision.js +76 -0
  73. package/dist/providers/receipts.d.ts +20 -0
  74. package/dist/providers/receipts.js +66 -0
  75. package/dist/providers/recovery-verification.d.ts +7 -0
  76. package/dist/providers/recovery-verification.js +112 -0
  77. package/dist/providers/recovery.d.ts +30 -0
  78. package/dist/providers/recovery.js +34 -0
  79. package/dist/providers/runtime.d.ts +10 -0
  80. package/dist/providers/runtime.js +254 -0
  81. package/dist/providers/schema.d.ts +28 -0
  82. package/dist/providers/schema.js +49 -0
  83. package/dist/providers/state.d.ts +55 -0
  84. package/dist/providers/state.js +289 -0
  85. package/dist/provision.d.ts +10 -1
  86. package/dist/provision.js +91 -4
  87. package/dist/r2-service-data.d.ts +2 -0
  88. package/dist/r2-service-data.js +136 -0
  89. package/dist/readiness.js +9 -13
  90. package/dist/registry/add.d.ts +6 -0
  91. package/dist/registry/add.js +93 -22
  92. package/dist/registry/commands.d.ts +3 -2
  93. package/dist/registry/commands.js +52 -15
  94. package/dist/registry/options.d.ts +1 -1
  95. package/dist/registry/options.js +5 -4
  96. package/dist/registry/preview.d.ts +11 -0
  97. package/dist/registry/preview.js +91 -0
  98. package/dist/registry/receipt.d.ts +1 -0
  99. package/dist/registry/receipt.js +19 -4
  100. package/dist/registry/resolve.js +5 -1
  101. package/dist/registry/usage.d.ts +10 -0
  102. package/dist/registry/usage.js +18 -37
  103. package/dist/render.d.ts +2 -0
  104. package/dist/render.js +6 -0
  105. package/dist/runtime-policy.d.ts +4 -0
  106. package/dist/runtime-policy.js +21 -0
  107. package/dist/scaffold/auth.js +3 -19
  108. package/dist/scaffold/bootstrap.js +2 -2
  109. package/dist/scaffold/compose.js +9 -3
  110. package/dist/scaffold/database.js +107 -25
  111. package/dist/scaffold/documentation.js +18 -13
  112. package/dist/scaffold/lint.d.ts +4 -0
  113. package/dist/scaffold/lint.js +56 -0
  114. package/dist/scaffold/neon-realtime.d.ts +2 -0
  115. package/dist/scaffold/neon-realtime.js +97 -0
  116. package/dist/scaffold/stack-documentation.js +1 -1
  117. package/dist/scaffold/void.d.ts +4 -0
  118. package/dist/scaffold/void.js +256 -0
  119. package/dist/scaffold/web.js +7 -1
  120. package/dist/scaffold/workspace.js +127 -25
  121. package/dist/service-deletion.d.ts +29 -0
  122. package/dist/service-deletion.js +195 -0
  123. package/dist/service-descriptor.d.ts +10 -0
  124. package/dist/service-descriptor.js +78 -0
  125. package/dist/service-model.d.ts +49 -0
  126. package/dist/service-model.js +8 -0
  127. package/dist/service-operations.d.ts +29 -0
  128. package/dist/service-operations.js +78 -0
  129. package/dist/service-readers.d.ts +8 -0
  130. package/dist/service-readers.js +247 -0
  131. package/dist/services-command.d.ts +39 -0
  132. package/dist/services-command.js +100 -0
  133. package/dist/ship.d.ts +348 -0
  134. package/dist/ship.js +237 -0
  135. package/dist/stack-registry.d.ts +4 -2
  136. package/dist/stack-registry.js +48 -12
  137. package/dist/standard.d.ts +2 -1
  138. package/dist/standard.js +33 -14
  139. package/dist/transaction.d.ts +2 -0
  140. package/dist/transaction.js +10 -0
  141. package/dist/util.js +17 -2
  142. package/dist/vercel.d.ts +5 -3
  143. package/dist/vercel.js +96 -14
  144. package/dist/version.d.ts +1 -1
  145. package/dist/version.js +1 -1
  146. package/dist/vinext.d.ts +1 -0
  147. package/dist/vinext.js +13 -1
  148. package/dist/void-execution.d.ts +10 -0
  149. package/dist/void-execution.js +94 -0
  150. package/dist/void-migrations.d.ts +6 -0
  151. package/dist/void-migrations.js +110 -0
  152. package/dist/void-state.d.ts +16 -0
  153. package/dist/void-state.js +65 -0
  154. package/dist/void.d.ts +3 -0
  155. package/dist/void.js +5 -0
  156. package/docs/cli-design.md +67 -0
  157. package/docs/delivery-workflow.md +32 -17
  158. package/docs/plugin-ui.md +102 -0
  159. package/docs/provider-configuration.md +116 -0
  160. package/docs/stack-standard.md +175 -0
  161. package/docs/void-verification.md +185 -0
  162. package/package.json +29 -23
  163. package/assets/anhedral-cli-init-technical.svg +0 -322
  164. package/assets/anhedral-cli-init.svg +0 -322
  165. package/assets/anhedral-mark.svg +0 -4
  166. package/assets/anhedral.svg +0 -4
  167. package/assets/favicon.ico +0 -0
  168. package/assets/security/LICENSES.txt +0 -63
  169. package/assets/security/audit-deps.mjs +0 -300
  170. package/assets/security/braces-regression.mjs +0 -102
  171. package/assets/security/braces@3.0.3.patch +0 -285
  172. package/assets/security/decode-uri-component@0.2.2.patch +0 -149
  173. package/assets/security/decoder-regression.mjs +0 -37
  174. package/assets/security/forge-regression.mjs +0 -46
  175. package/assets/security/manifest.json +0 -53
  176. package/assets/security/node-forge@1.4.0.patch +0 -26
  177. package/dist/managed-hosting.d.ts +0 -49
  178. package/dist/managed-hosting.js +0 -373
  179. package/dist/security-backports.d.ts +0 -3
  180. package/dist/security-backports.js +0 -26
  181. package/docs/application-stack-standard.md +0 -104
  182. package/docs/managed-hosting-architecture.md +0 -87
  183. package/docs/sponsorships.md +0 -25
@@ -0,0 +1,25 @@
1
+ import type { ProjectInspection } from './inspector-model.js';
2
+ export interface ProjectLifecycle {
3
+ supportedConfiguration: boolean;
4
+ init: {
5
+ state: 'configured' | 'needs-attention' | 'unavailable';
6
+ message: string;
7
+ };
8
+ auth: {
9
+ state: 'not-checked';
10
+ providers: string[];
11
+ accounts: {
12
+ provider: string;
13
+ reference: string;
14
+ }[];
15
+ message: string;
16
+ };
17
+ ship: {
18
+ state: 'not-recorded' | 'recorded' | 'needs-attention';
19
+ successfulTargets: number;
20
+ totalTargets: number;
21
+ message: string;
22
+ };
23
+ }
24
+ /** Derive lifecycle evidence from the CLI inspector. Never infer authentication or live health. */
25
+ export declare function projectLifecycle(inspection: ProjectInspection): ProjectLifecycle;
@@ -0,0 +1,57 @@
1
+ /** Derive lifecycle evidence from the CLI inspector. Never infer authentication or live health. */
2
+ export function projectLifecycle(inspection) {
3
+ const supportedConfiguration = inspection.selection.state === 'available' &&
4
+ Boolean(inspection.selection.data.cliVersion) &&
5
+ inspection.selection.data.products.length > 0;
6
+ const targets = inspection.targets.state === 'available' ? inspection.targets.data : [];
7
+ const successfulTargets = targets.filter((target) => target.lastSuccessful).length;
8
+ const accounts = targets
9
+ .flatMap((target) => target.accountReference
10
+ ? [{ provider: target.provider, reference: target.accountReference }]
11
+ : [])
12
+ .filter((account, index, values) => values.findIndex((value) => value.provider === account.provider && value.reference === account.reference) === index);
13
+ const blocked = inspection.targets.state === 'unavailable' ||
14
+ inspection.serviceDeletions?.state === 'unavailable' ||
15
+ Boolean(inspection.serviceDeletions?.data.length) ||
16
+ inspection.operation.state === 'unavailable' ||
17
+ Boolean(inspection.operation.data && inspection.operation.data.state !== 'completed') ||
18
+ targets.some((target) => target.error ||
19
+ target.delivery === 'scaffold-only' ||
20
+ (target.latestAttempt && target.latestAttempt.id !== target.lastSuccessful?.id));
21
+ const shipState = blocked
22
+ ? 'needs-attention'
23
+ : targets.length && successfulTargets === targets.length
24
+ ? 'recorded'
25
+ : 'not-recorded';
26
+ return {
27
+ supportedConfiguration,
28
+ init: {
29
+ state: !supportedConfiguration
30
+ ? 'unavailable'
31
+ : inspection.readiness.state === 'available' && inspection.readiness.data.localReady
32
+ ? 'configured'
33
+ : 'needs-attention',
34
+ message: !supportedConfiguration
35
+ ? 'No supported Anhedral stack configuration found. Registering a folder does not adopt its application.'
36
+ : 'Anhedral stack configuration recorded. Local checks describe source structure, not feature completeness.',
37
+ },
38
+ auth: {
39
+ state: 'not-checked',
40
+ providers: inspection.setupProviders.state === 'available'
41
+ ? inspection.setupProviders.data.map((provider) => provider.id)
42
+ : [],
43
+ accounts,
44
+ message: 'Account references are recorded selections. Provider sessions, permissions and billing eligibility require an explicit access check.',
45
+ },
46
+ ship: {
47
+ state: shipState,
48
+ successfulTargets,
49
+ totalTargets: targets.length,
50
+ message: blocked
51
+ ? 'Review incomplete, conflicting or deletion evidence before shipping. Prior successes remain history.'
52
+ : shipState === 'recorded'
53
+ ? 'Success receipts exist for the recorded targets. Current source, live health and product behavior require separate verification.'
54
+ : 'No complete set of successful target receipts is recorded. Review the delivery plan before provisioning or deploying.',
55
+ },
56
+ };
57
+ }
@@ -9,6 +9,7 @@ export interface ApplicationProject {
9
9
  name: string;
10
10
  ownership: 'customer';
11
11
  provider: 'cloudflare';
12
+ deliveryEngine: 'void' | 'wrangler';
12
13
  accountId: string | null;
13
14
  audience: 'unconfigured' | 'public' | 'private';
14
15
  access?: {
@@ -16,8 +17,11 @@ export interface ApplicationProject {
16
17
  };
17
18
  targets: DeploymentTarget[];
18
19
  }
19
- export type DeliveryRunner = (command: string, args: string[], cwd: string, env: NodeJS.ProcessEnv) => Promise<string>;
20
+ export type DeliveryRunner = (command: string, args: string[], cwd: string, env: NodeJS.ProcessEnv, input?: string) => Promise<string>;
20
21
  export declare function atomicJson(file: string, value: unknown): void;
22
+ export declare function configurationFile(directory: string): string;
23
+ export declare function usesVoid(project: ApplicationProject): boolean;
24
+ export declare function resolveVoidCloudflareConfig(authored: Record<string, unknown>, lock: Record<string, unknown>): Record<string, unknown>;
21
25
  export declare function readConfig(directory: string): Record<string, unknown>;
22
26
  export declare function targetDirectory(root: string, target: DeploymentTarget): string;
23
27
  export declare function registerApplication(root: string, extendTargets?: boolean): ApplicationProject;
@@ -25,4 +29,21 @@ export declare function readApplication(root: string): ApplicationProject;
25
29
  export declare const defaultRunner: DeliveryRunner;
26
30
  export declare function environment(project: ApplicationProject): NodeJS.ProcessEnv;
27
31
  export declare function authenticate(root: string, project: ApplicationProject, run: DeliveryRunner): Promise<void>;
32
+ /** Explicit local cleanup only. A dead same-host PID is required; live, foreign,
33
+ * malformed and legacy locks remain intact. Provider operations are never replayed. */
34
+ export declare function recoverDeliveryLock(root: string): {
35
+ schemaVersion: number;
36
+ state: string;
37
+ recovered: boolean;
38
+ mutation: string;
39
+ providerReplay: boolean;
40
+ nextAction?: undefined;
41
+ } | {
42
+ schemaVersion: number;
43
+ state: string;
44
+ recovered: boolean;
45
+ mutation: string;
46
+ providerReplay: boolean;
47
+ nextAction: string;
48
+ };
28
49
  export declare function withApplicationLock<T>(root: string, operation: () => Promise<T>): Promise<T>;
@@ -1,10 +1,15 @@
1
+ import { hasProjectSection, readProjectSection, writeProjectSection } from './project-config.js';
2
+ import { isDeepStrictEqual } from 'node:util';
1
3
  import { randomUUID } from 'node:crypto';
2
- import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
4
+ import { AsyncLocalStorage } from 'node:async_hooks';
5
+ import { existsSync, lstatSync, fstatSync, openSync, closeSync, unlinkSync, rmdirSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
3
6
  import { spawn } from 'node:child_process';
4
7
  import path from 'node:path';
8
+ import { hostname } from 'node:os';
9
+ import { readBoundedFile } from './bounded-file.js';
10
+ import { validateSetupPlan } from './readiness.js';
5
11
  import { parse } from 'jsonc-parser';
6
12
  import { resolveCommand } from './command.js';
7
- const manifestName = 'anhedral.project.json';
8
13
  const stateDirectory = '.anhedral';
9
14
  const accountPattern = /^[a-f0-9]{32}$/i;
10
15
  const workerPattern = /^[a-z0-9][a-z0-9-]{0,62}$/;
@@ -18,11 +23,94 @@ export function atomicJson(file, value) {
18
23
  rmSync(temporary, { force: true });
19
24
  }
20
25
  }
26
+ export function configurationFile(directory) {
27
+ const canonical = path.join(directory, 'anhedral.cloudflare.json');
28
+ return existsSync(canonical) ? canonical : path.join(directory, 'wrangler.jsonc');
29
+ }
30
+ export function usesVoid(project) {
31
+ return project.deliveryEngine === 'void';
32
+ }
33
+ function mergeVoidConfig(previous, resolved, authored) {
34
+ if (isDeepStrictEqual(previous, authored))
35
+ return resolved;
36
+ if (Array.isArray(previous) && Array.isArray(resolved) && Array.isArray(authored)) {
37
+ const identity = (value) => {
38
+ if (value && typeof value === 'object')
39
+ for (const key of ['binding', 'name', 'tag', 'class_name', 'pattern', 'route']) {
40
+ const item = value[key];
41
+ if (typeof item === 'string')
42
+ return `${key}:${item}`;
43
+ }
44
+ return JSON.stringify(value);
45
+ };
46
+ return [
47
+ ...authored.map((item) => {
48
+ const before = previous.find((entry) => identity(entry) === identity(item));
49
+ const after = resolved.find((entry) => identity(entry) === identity(item));
50
+ return before !== undefined && after !== undefined
51
+ ? mergeVoidConfig(before, after, item)
52
+ : item;
53
+ }),
54
+ ...resolved.filter((item) => !previous.some((entry) => identity(entry) === identity(item)) &&
55
+ !authored.some((entry) => identity(entry) === identity(item))),
56
+ ];
57
+ }
58
+ const object = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
59
+ if (object(previous) && object(resolved) && object(authored)) {
60
+ const result = {};
61
+ for (const key of new Set([
62
+ ...Object.keys(previous),
63
+ ...Object.keys(resolved),
64
+ ...Object.keys(authored),
65
+ ])) {
66
+ if (key in authored)
67
+ Object.defineProperty(result, key, {
68
+ value: mergeVoidConfig(previous[key], resolved[key], authored[key]),
69
+ enumerable: true,
70
+ });
71
+ else if (!(key in previous) && key in resolved)
72
+ Object.defineProperty(result, key, { value: resolved[key], enumerable: true });
73
+ }
74
+ return result;
75
+ }
76
+ return authored;
77
+ }
78
+ export function resolveVoidCloudflareConfig(authored, lock) {
79
+ const value = structuredClone(authored);
80
+ if (lock.version !== 1 ||
81
+ !lock.source ||
82
+ typeof lock.source !== 'object' ||
83
+ Array.isArray(lock.source) ||
84
+ !lock.resolved ||
85
+ typeof lock.resolved !== 'object' ||
86
+ Array.isArray(lock.resolved) ||
87
+ typeof lock.text !== 'string')
88
+ throw new Error('Invalid pinned Void resource lock.');
89
+ // The generated Void configuration omits resource-ID scaffolding placeholders.
90
+ // Match that authored input when applying Void's resolved resource identities.
91
+ for (const [field, key] of [
92
+ ['d1_databases', 'database_id'],
93
+ ['kv_namespaces', 'id'],
94
+ ['pipelines', 'stream'],
95
+ ]) {
96
+ if (Array.isArray(value[field]))
97
+ for (const entry of value[field]) {
98
+ if (entry && typeof entry[key] === 'string' && entry[key].startsWith('REPLACE_WITH_'))
99
+ delete entry[key];
100
+ }
101
+ }
102
+ return mergeVoidConfig(lock.source, lock.resolved, value);
103
+ }
21
104
  export function readConfig(directory) {
22
105
  const errors = [];
23
- const value = parse(readFileSync(path.join(directory, 'wrangler.jsonc'), 'utf8'), errors);
106
+ const value = parse(readFileSync(configurationFile(directory), 'utf8'), errors);
24
107
  if (errors.length || !value || typeof value !== 'object' || Array.isArray(value))
25
108
  throw new Error('Invalid Wrangler JSONC configuration.');
109
+ const lockFile = path.join(directory, 'void.lock.json');
110
+ if (existsSync(path.join(directory, 'anhedral.cloudflare.json')) && existsSync(lockFile)) {
111
+ const lock = JSON.parse(readFileSync(lockFile, 'utf8'));
112
+ return resolveVoidCloudflareConfig(value, lock);
113
+ }
26
114
  return value;
27
115
  }
28
116
  export function targetDirectory(root, target) {
@@ -35,15 +123,14 @@ export function targetDirectory(root, target) {
35
123
  }
36
124
  export function registerApplication(root, extendTargets = false) {
37
125
  root = realpathSync(root);
38
- const existing = existsSync(path.join(root, manifestName)) ? readApplication(root) : undefined;
126
+ const existing = hasProjectSection(root, 'cloudflare') ? readApplication(root) : undefined;
39
127
  if (existing && !extendTargets)
40
128
  return existing;
41
- const setup = JSON.parse(readFileSync(path.join(root, 'anhedral.setup.json'), 'utf8'));
42
- if (!['cloudflare', 'vercel'].includes(setup.hosting))
43
- throw new Error('Automatic delivery currently supports Cloudflare projects.');
129
+ const setup = readProjectSection(root, 'setup');
130
+ validateSetupPlan(setup);
44
131
  const targets = readdirSync(path.join(root, 'apps'), { withFileTypes: true })
45
132
  .filter((entry) => entry.isDirectory())
46
- .filter((entry) => existsSync(path.join(root, 'apps', entry.name, 'wrangler.jsonc')))
133
+ .filter((entry) => existsSync(configurationFile(path.join(root, 'apps', entry.name))))
47
134
  .map((entry) => {
48
135
  const workerName = readConfig(path.join(root, 'apps', entry.name)).name;
49
136
  if (typeof workerName !== 'string' || !workerPattern.test(workerName))
@@ -51,13 +138,23 @@ export function registerApplication(root, extendTargets = false) {
51
138
  return { id: entry.name, directory: `apps/${entry.name}`, workerName };
52
139
  })
53
140
  .sort((a, b) => (a.id === 'web' ? 1 : b.id === 'web' ? -1 : a.id.localeCompare(b.id)));
141
+ const selectedEngine = targets.length &&
142
+ targets.every((target) => existsSync(path.join(root, target.directory, 'void.config.ts')))
143
+ ? 'void'
144
+ : 'wrangler';
54
145
  if (existing) {
55
146
  if (existing.targets.some((target) => !targets.some((candidate) => candidate.id === target.id &&
56
147
  candidate.directory === target.directory &&
57
148
  candidate.workerName === target.workerName)))
58
149
  throw new Error('Addition cannot replace existing delivery targets.');
59
- const extended = { ...existing, targets };
60
- atomicJson(path.join(root, manifestName), extended);
150
+ const extended = {
151
+ ...existing,
152
+ // A native-only registration has no Cloudflare runtime to preserve.
153
+ // Select the first actual targets' engine while keeping project identity.
154
+ deliveryEngine: existing.targets.length ? existing.deliveryEngine : selectedEngine,
155
+ targets,
156
+ };
157
+ writeProjectSection(root, 'cloudflare', extended);
61
158
  return extended;
62
159
  }
63
160
  const project = {
@@ -66,6 +163,7 @@ export function registerApplication(root, extendTargets = false) {
66
163
  name: JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8')).name ?? path.basename(root),
67
164
  ownership: 'customer',
68
165
  provider: 'cloudflare',
166
+ deliveryEngine: selectedEngine,
69
167
  accountId: null,
70
168
  audience: 'unconfigured',
71
169
  targets,
@@ -74,16 +172,17 @@ export function registerApplication(root, extendTargets = false) {
74
172
  const ignored = existsSync(ignoreFile) ? readFileSync(ignoreFile, 'utf8') : '';
75
173
  if (!ignored.split(/\r?\n/).includes('.anhedral/'))
76
174
  writeFileSync(ignoreFile, ignored + (ignored.endsWith('\n') || !ignored ? '' : '\n') + '.anhedral/\n');
77
- atomicJson(path.join(root, manifestName), project);
175
+ writeProjectSection(root, 'cloudflare', project);
78
176
  return project;
79
177
  }
80
178
  export function readApplication(root) {
81
- const project = JSON.parse(readFileSync(path.join(root, manifestName), 'utf8'));
179
+ const project = readProjectSection(root, 'cloudflare');
82
180
  if (project.schemaVersion !== 1 ||
83
181
  typeof project.id !== 'string' ||
84
182
  !/^[a-f0-9-]{36}$/i.test(project.id) ||
85
183
  project.ownership !== 'customer' ||
86
184
  project.provider !== 'cloudflare' ||
185
+ !['void', 'wrangler'].includes(project.deliveryEngine) ||
87
186
  !(project.accountId === null || accountPattern.test(project.accountId)) ||
88
187
  !['unconfigured', 'public', 'private'].includes(project.audience) ||
89
188
  !Array.isArray(project.targets))
@@ -111,14 +210,18 @@ export function readApplication(root) {
111
210
  }
112
211
  return project;
113
212
  }
114
- export const defaultRunner = (command, args, cwd, env) => new Promise((resolve, reject) => {
213
+ export const defaultRunner = (command, args, cwd, env, input) => new Promise((resolve, reject) => {
115
214
  const invocation = resolveCommand(command, args);
116
215
  const child = spawn(invocation.command, invocation.args, {
117
216
  cwd,
118
217
  env,
119
218
  detached: process.platform !== 'win32',
120
- stdio: ['ignore', 'pipe', 'pipe'],
219
+ stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'],
121
220
  });
221
+ if (input !== undefined) {
222
+ child.stdin?.on('error', () => { });
223
+ child.stdin?.end(input);
224
+ }
122
225
  let output = '';
123
226
  let oversized = false;
124
227
  let interrupted = false;
@@ -149,7 +252,7 @@ export const defaultRunner = (command, args, cwd, env) => new Promise((resolve,
149
252
  };
150
253
  process.once('SIGINT', interrupt);
151
254
  process.once('SIGTERM', interrupt);
152
- child.stdout.on('data', (chunk) => {
255
+ child.stdout?.on('data', (chunk) => {
153
256
  if (!oversized)
154
257
  output += chunk.toString();
155
258
  if (output.length > 8 * 1024 * 1024) {
@@ -158,11 +261,17 @@ export const defaultRunner = (command, args, cwd, env) => new Promise((resolve,
158
261
  }
159
262
  });
160
263
  // Do not persist raw build/provider output: it can contain credentials or customer data.
161
- child.stderr.resume();
264
+ child.stderr?.resume();
265
+ const requestedDeadline = Number(env.ANHEDRAL_COMMAND_TIMEOUT_MS);
266
+ const commandDeadline = Number.isInteger(requestedDeadline) &&
267
+ requestedDeadline >= 1 &&
268
+ requestedDeadline <= 20 * 60 * 1000
269
+ ? requestedDeadline
270
+ : 20 * 60 * 1000;
162
271
  const timer = setTimeout(() => {
163
272
  timedOut = true;
164
273
  stop();
165
- }, 20 * 60 * 1000);
274
+ }, commandDeadline);
166
275
  const clean = () => {
167
276
  clearTimeout(timer);
168
277
  if (forceTimer)
@@ -204,23 +313,248 @@ export async function authenticate(root, project, run) {
204
313
  !identity.accounts.some((account) => account.id === project.accountId))
205
314
  throw new Error('Wrangler cannot access the registered Cloudflare account. Run wrangler login or configure scoped credentials.');
206
315
  }
207
- export async function withApplicationLock(root, operation) {
208
- root = realpathSync(root);
316
+ const applicationLocks = new AsyncLocalStorage();
317
+ const lockBusy = () => new Error('Another delivery is running or was interrupted. Inspect provider status and use anhedral recover --lock only after reviewing the recorded operation.');
318
+ const ownerChanged = () => new Error('Delivery lock ownership changed or is invalid. Preserve the lock and inspect local operation evidence before retrying.');
319
+ function privateState(root) {
209
320
  const state = path.join(root, stateDirectory);
210
- mkdirSync(state, { recursive: true });
211
- if (realpathSync(state) !== path.join(root, stateDirectory))
212
- throw new Error('Delivery state directory must not be a symbolic link.');
213
- const lock = path.join(state, 'ship.lock');
214
321
  try {
215
- mkdirSync(lock);
322
+ mkdirSync(state, { recursive: true, mode: 0o700 });
323
+ const stat = lstatSync(state);
324
+ if (!stat.isDirectory() ||
325
+ stat.isSymbolicLink() ||
326
+ realpathSync(state) !== state ||
327
+ (process.platform !== 'win32' && stat.mode & 0o022))
328
+ throw new Error();
329
+ return state;
330
+ }
331
+ catch {
332
+ throw new Error('Delivery state must be a regular directory without shared write permissions.');
333
+ }
334
+ }
335
+ function lockOwner() {
336
+ return {
337
+ schemaVersion: 1,
338
+ pid: process.pid,
339
+ host: hostname(),
340
+ token: randomUUID(),
341
+ createdAt: new Date().toISOString(),
342
+ };
343
+ }
344
+ function privateOwner(file) {
345
+ try {
346
+ const stat = lstatSync(file);
347
+ if (!stat.isFile() ||
348
+ stat.isSymbolicLink() ||
349
+ (process.platform !== 'win32' && (stat.mode & 0o077 || stat.uid !== process.getuid?.())))
350
+ throw new Error();
351
+ const value = JSON.parse(readBoundedFile(file, 4096).toString('utf8'));
352
+ if (!value || typeof value !== 'object' || Array.isArray(value))
353
+ throw new Error();
354
+ const owner = value;
355
+ if (Object.keys(owner).some((key) => !['schemaVersion', 'pid', 'host', 'token', 'createdAt'].includes(key)) ||
356
+ owner.schemaVersion !== 1 ||
357
+ !Number.isSafeInteger(owner.pid) ||
358
+ owner.pid < 1 ||
359
+ owner.pid > 2147483647 ||
360
+ typeof owner.host !== 'string' ||
361
+ !owner.host ||
362
+ owner.host.length > 255 ||
363
+ /[\x00-\x1f\x7f]/.test(owner.host) ||
364
+ typeof owner.token !== 'string' ||
365
+ !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(owner.token) ||
366
+ typeof owner.createdAt !== 'string' ||
367
+ !/^\d{4}-\d{2}-\d{2}T/.test(owner.createdAt) ||
368
+ !Number.isFinite(Date.parse(owner.createdAt)))
369
+ throw new Error();
370
+ return owner;
371
+ }
372
+ catch {
373
+ throw ownerChanged();
374
+ }
375
+ }
376
+ function snapshotLock(lock) {
377
+ try {
378
+ const stat = lstatSync(lock);
379
+ if (!stat.isDirectory() ||
380
+ stat.isSymbolicLink() ||
381
+ (process.platform !== 'win32' && (stat.mode & 0o077 || stat.uid !== process.getuid?.())) ||
382
+ readdirSync(lock).join(',') !== 'owner.json')
383
+ throw new Error();
384
+ const file = path.join(lock, 'owner.json');
385
+ const owner = privateOwner(file);
386
+ const ownerStat = lstatSync(file);
387
+ return {
388
+ identity: {
389
+ device: stat.dev,
390
+ inode: stat.ino,
391
+ ownerDevice: ownerStat.dev,
392
+ ownerInode: ownerStat.ino,
393
+ owner,
394
+ },
395
+ owner,
396
+ };
397
+ }
398
+ catch {
399
+ throw ownerChanged();
400
+ }
401
+ }
402
+ function sameOwner(left, right) {
403
+ return (left.pid === right.pid &&
404
+ left.host === right.host &&
405
+ left.token === right.token &&
406
+ left.createdAt === right.createdAt);
407
+ }
408
+ function sameIdentity(left, right) {
409
+ return (left.device === right.device &&
410
+ left.inode === right.inode &&
411
+ left.ownerDevice === right.ownerDevice &&
412
+ left.ownerInode === right.ownerInode &&
413
+ sameOwner(left.owner, right.owner));
414
+ }
415
+ class DeliveryGuardBusyError extends Error {
416
+ constructor() {
417
+ super('Delivery lock acquisition or recovery is busy. Inspect .anhedral/ship.guard before retrying.');
418
+ }
419
+ }
420
+ /** This synchronous guard covers only filesystem transitions. An uncertain guard
421
+ * after process termination is preserved for operator inspection, never auto-unlinked. */
422
+ function withLockGuard(state, operation) {
423
+ try {
424
+ const stat = lstatSync(state);
425
+ if (!stat.isDirectory() ||
426
+ stat.isSymbolicLink() ||
427
+ realpathSync(state) !== state ||
428
+ (process.platform !== 'win32' && stat.mode & 0o022))
429
+ throw new Error();
216
430
  }
217
431
  catch {
218
- throw new Error('Another delivery is running or was interrupted. Inspect provider status and remove .anhedral/ship.lock only after confirming no delivery is active.');
432
+ throw ownerChanged();
219
433
  }
434
+ const file = path.join(state, 'ship.guard');
435
+ let descriptor;
436
+ try {
437
+ descriptor = openSync(file, 'wx', 0o600);
438
+ }
439
+ catch {
440
+ throw new DeliveryGuardBusyError();
441
+ }
442
+ const stat = fstatSync(descriptor);
443
+ const owner = lockOwner();
444
+ try {
445
+ writeFileSync(descriptor, JSON.stringify(owner) + '\n');
446
+ return operation();
447
+ }
448
+ finally {
449
+ closeSync(descriptor);
450
+ // Another process must never lose its guard because this invocation finishes.
451
+ let current;
452
+ try {
453
+ current = lstatSync(file);
454
+ }
455
+ catch {
456
+ throw ownerChanged();
457
+ }
458
+ if (current.isSymbolicLink() ||
459
+ current.dev !== stat.dev ||
460
+ current.ino !== stat.ino ||
461
+ !sameOwner(privateOwner(file), owner))
462
+ throw ownerChanged();
463
+ unlinkSync(file);
464
+ }
465
+ }
466
+ function removeOwnedLock(lock, identity) {
467
+ if (!sameIdentity(snapshotLock(lock).identity, identity))
468
+ throw ownerChanged();
469
+ // Never recursively remove a lock: unknown additional files are evidence.
470
+ unlinkSync(path.join(lock, 'owner.json'));
471
+ rmdirSync(lock);
472
+ }
473
+ async function releaseApplicationLock(state, lock, identity) {
474
+ // A simultaneous operator inspection may briefly hold the guard. Preserve our
475
+ // lock while waiting; never bypass a guard or reinterpret uncertain ownership.
476
+ for (let attempt = 0;; attempt++) {
477
+ try {
478
+ withLockGuard(state, () => removeOwnedLock(lock, identity));
479
+ return;
480
+ }
481
+ catch (error) {
482
+ if (!(error instanceof DeliveryGuardBusyError) || attempt >= 4)
483
+ throw error;
484
+ await new Promise((resolve) => setTimeout(resolve, 25));
485
+ }
486
+ }
487
+ }
488
+ /** Explicit local cleanup only. A dead same-host PID is required; live, foreign,
489
+ * malformed and legacy locks remain intact. Provider operations are never replayed. */
490
+ export function recoverDeliveryLock(root) {
491
+ root = realpathSync(root);
492
+ const state = privateState(root);
493
+ return withLockGuard(state, () => {
494
+ const lock = path.join(state, 'ship.lock');
495
+ if (!lstatSync(lock, { throwIfNoEntry: false }))
496
+ return {
497
+ schemaVersion: 1,
498
+ state: 'unlocked',
499
+ recovered: false,
500
+ mutation: 'local-lock-only',
501
+ providerReplay: false,
502
+ };
503
+ const snapshot = snapshotLock(lock);
504
+ if (snapshot.owner.host !== hostname())
505
+ throw new Error('Delivery lock belongs to another host; preserve it and inspect operation evidence.');
506
+ let dead = false;
507
+ try {
508
+ process.kill(snapshot.owner.pid, 0);
509
+ }
510
+ catch (error) {
511
+ if (error.code === 'ESRCH')
512
+ dead = true;
513
+ else
514
+ throw new Error('Cannot prove the delivery lock owner exited; preserve the lock.');
515
+ }
516
+ if (!dead)
517
+ throw new Error('Delivery lock owner is still running; no lock or provider state was changed.');
518
+ removeOwnedLock(lock, snapshot.identity);
519
+ return {
520
+ schemaVersion: 1,
521
+ state: 'lock-recovered',
522
+ recovered: true,
523
+ mutation: 'local-lock-only',
524
+ providerReplay: false,
525
+ nextAction: 'Inspect provider status and recorded receipts before retrying ship. No provider operation was replayed.',
526
+ };
527
+ });
528
+ }
529
+ export async function withApplicationLock(root, operation) {
530
+ root = realpathSync(root);
531
+ const held = applicationLocks.getStore();
532
+ const state = privateState(root);
533
+ const lock = path.join(state, 'ship.lock');
534
+ if (held?.active && held.root === root) {
535
+ if (!sameIdentity(snapshotLock(lock).identity, held.identity))
536
+ throw ownerChanged();
537
+ return operation();
538
+ }
539
+ const identity = withLockGuard(state, () => {
540
+ try {
541
+ mkdirSync(lock, { mode: 0o700 });
542
+ }
543
+ catch {
544
+ throw lockBusy();
545
+ }
546
+ writeFileSync(path.join(lock, 'owner.json'), JSON.stringify(lockOwner()) + '\n', {
547
+ flag: 'wx',
548
+ mode: 0o600,
549
+ });
550
+ return snapshotLock(lock).identity;
551
+ });
552
+ const context = { root, active: true, identity };
220
553
  try {
221
- return await operation();
554
+ return await applicationLocks.run(context, operation);
222
555
  }
223
556
  finally {
224
- rmSync(lock, { recursive: true, force: true });
557
+ context.active = false;
558
+ await releaseApplicationLock(state, lock, identity);
225
559
  }
226
560
  }
@@ -0,0 +1,41 @@
1
+ import type { StandardProduct } from './stack-registry.js';
2
+ import { type DeliveryRunner } from './project-state.js';
3
+ export interface ProviderAuth {
4
+ id: string;
5
+ products: readonly StandardProduct[];
6
+ login?: readonly string[];
7
+ identity?: readonly string[];
8
+ credential?: string;
9
+ endpoint?: string;
10
+ runtime?: {
11
+ credential: string;
12
+ endpoint: string;
13
+ };
14
+ regionalEndpoints?: Readonly<Record<string, string>>;
15
+ setup: string;
16
+ }
17
+ /** Deployment access is separate from application-user authentication. */
18
+ export declare const PROVIDER_AUTH: readonly ProviderAuth[];
19
+ export declare function requiredProviders(root: string): ProviderAuth[];
20
+ export type AuthState = 'verified' | 'missing' | 'insufficient-permissions' | 'unverified';
21
+ export interface AuthCheck {
22
+ provider: string;
23
+ state: AuthState;
24
+ evidence: 'cli-session' | 'api-access' | 'none';
25
+ access: 'session' | 'management' | 'runtime' | 'none';
26
+ nextAction: string;
27
+ }
28
+ export interface AuthOptions {
29
+ provider?: string;
30
+ status?: boolean;
31
+ interactive?: boolean;
32
+ }
33
+ export type LoginRunner = (command: readonly string[], root: string) => Promise<void>;
34
+ /** Never return provider output, tokens, user addresses or response bodies. */
35
+ export declare function authenticateProviders(root: string, options?: AuthOptions, run?: DeliveryRunner, send?: typeof fetch, startLogin?: LoginRunner, environment?: NodeJS.ProcessEnv): Promise<{
36
+ schemaVersion: number;
37
+ checks: AuthCheck[];
38
+ authenticated: boolean;
39
+ provisioningReady: boolean;
40
+ note: string;
41
+ }>;