anhedral 0.11.2 → 0.13.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 (102) hide show
  1. package/README.md +171 -18
  2. package/dist/bin.js +48 -493
  3. package/dist/capabilities.d.ts +3 -3
  4. package/dist/capability-contract.js +16 -1
  5. package/dist/cli-arguments.d.ts +8 -0
  6. package/dist/cli-arguments.js +32 -0
  7. package/dist/cli-commands.d.ts +3 -0
  8. package/dist/cli-commands.js +114 -0
  9. package/dist/cli-delivery.d.ts +3 -0
  10. package/dist/cli-delivery.js +172 -0
  11. package/dist/cli-output.js +231 -205
  12. package/dist/command-schema.js +8 -2
  13. package/dist/command.js +9 -11
  14. package/dist/delivery-evidence.d.ts +62 -0
  15. package/dist/delivery-evidence.js +186 -0
  16. package/dist/delivery.d.ts +3 -40
  17. package/dist/delivery.js +7 -182
  18. package/dist/dependencies.d.ts +7 -1
  19. package/dist/dependencies.js +15 -1
  20. package/dist/index.d.ts +1 -0
  21. package/dist/index.js +1 -0
  22. package/dist/mobile-delivery.d.ts +21 -44
  23. package/dist/mobile-delivery.js +127 -80
  24. package/dist/platforms/mobile.d.ts +1 -1
  25. package/dist/platforms/mobile.js +44 -3
  26. package/dist/project-state.js +4 -1
  27. package/dist/provider-auth.js +9 -3
  28. package/dist/providers/adapters.js +9 -3
  29. package/dist/providers/runtime.js +11 -0
  30. package/dist/readiness.js +4 -2
  31. package/dist/registry/add.js +40 -7
  32. package/dist/registry/options.js +12 -0
  33. package/dist/registry/presets.d.ts +4 -0
  34. package/dist/registry/presets.js +41 -0
  35. package/dist/registry/resolve.d.ts +3 -1
  36. package/dist/registry/resolve.js +40 -14
  37. package/dist/registry/types.d.ts +1 -0
  38. package/dist/registry/usage.js +1 -1
  39. package/dist/runtime-policy.js +4 -1
  40. package/dist/scaffold/api.js +10 -2
  41. package/dist/scaffold/auth.d.ts +1 -1
  42. package/dist/scaffold/auth.js +22 -6
  43. package/dist/scaffold/backend.d.ts +6 -0
  44. package/dist/scaffold/backend.js +224 -0
  45. package/dist/scaffold/billing-config.d.ts +1 -0
  46. package/dist/scaffold/billing-config.js +73 -0
  47. package/dist/scaffold/billing-contracts.d.ts +2 -0
  48. package/dist/scaffold/billing-contracts.js +48 -0
  49. package/dist/scaffold/billing-providers.d.ts +1 -0
  50. package/dist/scaffold/billing-providers.js +249 -0
  51. package/dist/scaffold/billing-schema.d.ts +1 -0
  52. package/dist/scaffold/billing-schema.js +34 -0
  53. package/dist/scaffold/billing-security.d.ts +1 -0
  54. package/dist/scaffold/billing-security.js +46 -0
  55. package/dist/scaffold/billing-server.d.ts +1 -0
  56. package/dist/scaffold/billing-server.js +139 -0
  57. package/dist/scaffold/billing-store.d.ts +1 -0
  58. package/dist/scaffold/billing-store.js +72 -0
  59. package/dist/scaffold/billing.d.ts +2 -0
  60. package/dist/scaffold/billing.js +216 -0
  61. package/dist/scaffold/cloudflare-services.d.ts +8 -0
  62. package/dist/scaffold/cloudflare-services.js +198 -0
  63. package/dist/scaffold/compose.js +2 -0
  64. package/dist/scaffold/database.js +19 -2
  65. package/dist/scaffold/documentation.js +11 -6
  66. package/dist/scaffold/expo-auth.d.ts +3 -0
  67. package/dist/scaffold/expo-auth.js +192 -0
  68. package/dist/scaffold/expo-billing.d.ts +3 -0
  69. package/dist/scaffold/expo-billing.js +292 -0
  70. package/dist/scaffold/expo-runtime.d.ts +3 -0
  71. package/dist/scaffold/expo-runtime.js +134 -0
  72. package/dist/scaffold/integrations.d.ts +2 -1
  73. package/dist/scaffold/integrations.js +7 -2
  74. package/dist/scaffold/stream.d.ts +2 -0
  75. package/dist/scaffold/stream.js +114 -0
  76. package/dist/scaffold/void.js +13 -5
  77. package/dist/scaffold/web.js +2 -0
  78. package/dist/scaffold/workspace.js +6 -1
  79. package/dist/service-readers.js +1 -1
  80. package/dist/services-command.js +8 -6
  81. package/dist/ship.d.ts +15 -15
  82. package/dist/ship.js +3 -1
  83. package/dist/stack-registry.d.ts +13 -2
  84. package/dist/stack-registry.js +152 -16
  85. package/dist/transaction-lock.d.ts +15 -0
  86. package/dist/transaction-lock.js +227 -0
  87. package/dist/transaction.js +2 -208
  88. package/dist/vercel-project.d.ts +101 -0
  89. package/dist/vercel-project.js +305 -0
  90. package/dist/vercel.d.ts +3 -36
  91. package/dist/vercel.js +3 -300
  92. package/dist/version.d.ts +1 -1
  93. package/dist/version.js +1 -1
  94. package/docs/anhedral-stack.md +122 -0
  95. package/docs/software-factory.md +402 -7
  96. package/docs/stack-standard.md +226 -49
  97. package/docs/verification.md +557 -0
  98. package/package.json +7 -7
  99. package/docs/cli-design.md +0 -67
  100. package/docs/plugin-ui.md +0 -102
  101. package/docs/provider-configuration.md +0 -116
  102. package/docs/void-verification.md +0 -185
@@ -1,9 +1,8 @@
1
+ import { LOCK_FILE, acquireTransactionLock, releaseTransactionLock } from './transaction-lock.js';
1
2
  import { readBoundedFile } from './bounded-file.js';
2
- import { closeSync, cpSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmdirSync, rmSync, unlinkSync, writeFileSync, } from 'node:fs';
3
+ import { closeSync, cpSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmdirSync, rmSync, unlinkSync, writeFileSync, } from 'node:fs';
3
4
  import { createHash, randomUUID } from 'node:crypto';
4
- import os from 'node:os';
5
5
  import path from 'node:path';
6
- const LOCK_FILE = '.anhedral.lock';
7
6
  const JOURNAL_FILE = '.anhedral-journal.json';
8
7
  const TRANSACTION_DIRECTORY = '.anhedral-txn';
9
8
  const JOURNAL_VERSION = 2;
@@ -235,211 +234,6 @@ function removeEntryDurably(target) {
235
234
  if (pathEntryExists(parent))
236
235
  syncDirectory(parent);
237
236
  }
238
- function parseLockOwner(lockPath) {
239
- if (lstatSync(lockPath).isSymbolicLink()) {
240
- throw new Error(`Refusing symbolic-link transaction lock at ${lockPath}.`);
241
- }
242
- let value;
243
- try {
244
- value = JSON.parse(readBoundedFile(lockPath, 16 * 1024).toString('utf8'));
245
- }
246
- catch (error) {
247
- throw new Error(`Cannot read transaction lock owner at ${lockPath}; remove it only after confirming no Anhedral process is running.`, { cause: error });
248
- }
249
- if (!isRecord(value) ||
250
- value.version !== 1 ||
251
- !Number.isSafeInteger(value.pid) ||
252
- value.pid <= 0 ||
253
- typeof value.hostname !== 'string' ||
254
- typeof value.token !== 'string' ||
255
- typeof value.createdAt !== 'string') {
256
- throw new Error(`Invalid transaction lock owner at ${lockPath}; remove it only after confirming no Anhedral process is running.`);
257
- }
258
- return value;
259
- }
260
- function readLockOwnerIfPresent(lockPath) {
261
- try {
262
- return parseLockOwner(lockPath);
263
- }
264
- catch (error) {
265
- const candidate = error;
266
- if (candidate.code === 'ENOENT' || candidate.cause?.code === 'ENOENT')
267
- return null;
268
- throw error;
269
- }
270
- }
271
- function isProcessAlive(pid) {
272
- try {
273
- process.kill(pid, 0);
274
- return true;
275
- }
276
- catch (error) {
277
- const code = error.code;
278
- if (code === 'ESRCH')
279
- return false;
280
- if (code === 'EPERM')
281
- return true;
282
- throw error;
283
- }
284
- }
285
- function cleanupTemporaryLocks(root, owner, temporaryPath) {
286
- for (const entry of readdirSync(root)) {
287
- if (!entry.startsWith(`${LOCK_FILE}.`) || !entry.endsWith('.tmp'))
288
- continue;
289
- const staleTemporaryPath = path.join(root, entry);
290
- if (staleTemporaryPath === temporaryPath)
291
- continue;
292
- let temporaryOwner;
293
- try {
294
- temporaryOwner = parseLockOwner(staleTemporaryPath);
295
- }
296
- catch (error) {
297
- throw new Error(`Cannot safely classify transaction lock artifact at ${staleTemporaryPath}; inspect it manually before retrying.`, { cause: error });
298
- }
299
- if (temporaryOwner.hostname !== owner.hostname) {
300
- throw new Error(`Transaction lock artifact at ${staleTemporaryPath} belongs to another host; inspect it manually before retrying.`);
301
- }
302
- if (!isProcessAlive(temporaryOwner.pid)) {
303
- unlinkSync(staleTemporaryPath);
304
- }
305
- }
306
- }
307
- function claimReclamation(lockPath, reclaimPath, temporaryPath, owner) {
308
- try {
309
- linkSync(temporaryPath, reclaimPath);
310
- }
311
- catch (error) {
312
- if (error.code === 'EEXIST') {
313
- const reclaimer = readLockOwnerIfPresent(reclaimPath);
314
- if (!reclaimer) {
315
- return false;
316
- }
317
- if (reclaimer.hostname === owner.hostname && !isProcessAlive(reclaimer.pid)) {
318
- unlinkSync(reclaimPath);
319
- return false;
320
- }
321
- throw new Error(`A stale Anhedral lock is being recovered (${lockPath}, pid ${reclaimer.pid} on ${reclaimer.hostname}); retry the command.`);
322
- }
323
- throw error;
324
- }
325
- return true;
326
- }
327
- function reclaimTransactionLock(lockPath, reclaimPath, temporaryPath, owner) {
328
- const existing = readLockOwnerIfPresent(lockPath);
329
- if (!existing) {
330
- return 'retry';
331
- }
332
- if (existing.hostname !== owner.hostname || isProcessAlive(existing.pid)) {
333
- throw new Error(`Another Anhedral operation is already running (${lockPath}, pid ${existing.pid} on ${existing.hostname}).`);
334
- }
335
- if (!claimReclamation(lockPath, reclaimPath, temporaryPath, owner))
336
- return 'retry';
337
- try {
338
- if (!pathEntryExists(lockPath))
339
- return 'next';
340
- const current = parseLockOwner(lockPath);
341
- if (current.token !== existing.token)
342
- return 'next';
343
- if (current.hostname !== owner.hostname || isProcessAlive(current.pid)) {
344
- throw new Error(`Another Anhedral operation is already running (${lockPath}, pid ${current.pid} on ${current.hostname}).`);
345
- }
346
- unlinkSync(lockPath);
347
- }
348
- finally {
349
- if (pathEntryExists(reclaimPath)) {
350
- const reclaimer = parseLockOwner(reclaimPath);
351
- if (reclaimer.token === owner.token)
352
- unlinkSync(reclaimPath);
353
- }
354
- }
355
- return 'next';
356
- }
357
- function assertLockRoot(root) {
358
- const rootStat = lstatIfPresent(root);
359
- if (!rootStat)
360
- throw new Error(`Transaction root is not a directory: ${root}`);
361
- if (rootStat.isSymbolicLink()) {
362
- throw new Error(`Refusing transaction root that is a symbolic link: ${root}`);
363
- }
364
- if (!rootStat.isDirectory())
365
- throw new Error(`Transaction root is not a directory: ${root}`);
366
- }
367
- function clearDeadReclaimer(lockPath, reclaimPath, owner) {
368
- const activeReclaimer = readLockOwnerIfPresent(reclaimPath);
369
- if (activeReclaimer) {
370
- if (activeReclaimer.hostname === owner.hostname && !isProcessAlive(activeReclaimer.pid)) {
371
- try {
372
- unlinkSync(reclaimPath);
373
- }
374
- catch (error) {
375
- if (error.code !== 'ENOENT')
376
- throw error;
377
- }
378
- return true;
379
- }
380
- throw new Error(`An Anhedral lock is being recovered (${lockPath}, pid ${activeReclaimer.pid} on ${activeReclaimer.hostname}); retry the command.`);
381
- }
382
- return false;
383
- }
384
- function cleanupAcquiredLock(root, lockPath, owner, temporaryPath) {
385
- try {
386
- cleanupTemporaryLocks(root, owner, temporaryPath);
387
- }
388
- catch (error) {
389
- const current = readLockOwnerIfPresent(lockPath);
390
- if (current?.token === owner.token)
391
- unlinkSync(lockPath);
392
- throw error;
393
- }
394
- }
395
- function acquireTransactionLock(root) {
396
- assertLockRoot(root);
397
- const lockPath = path.join(root, LOCK_FILE);
398
- const reclaimPath = `${lockPath}.reclaim`;
399
- const owner = {
400
- version: 1,
401
- pid: process.pid,
402
- hostname: os.hostname(),
403
- token: `${process.pid}-${randomUUID()}`,
404
- createdAt: new Date().toISOString(),
405
- };
406
- const temporaryPath = `${lockPath}.${owner.token}.tmp`;
407
- writeFileSync(temporaryPath, JSON.stringify(owner) + '\n', {
408
- encoding: 'utf8',
409
- flag: 'wx',
410
- mode: 0o600,
411
- });
412
- try {
413
- for (let attempt = 0; attempt < 3; attempt += 1) {
414
- if (clearDeadReclaimer(lockPath, reclaimPath, owner)) {
415
- attempt -= 1;
416
- continue;
417
- }
418
- try {
419
- linkSync(temporaryPath, lockPath);
420
- cleanupAcquiredLock(root, lockPath, owner, temporaryPath);
421
- return { lockPath, owner };
422
- }
423
- catch (error) {
424
- if (error.code !== 'EEXIST')
425
- throw error;
426
- }
427
- if (reclaimTransactionLock(lockPath, reclaimPath, temporaryPath, owner) === 'retry')
428
- attempt -= 1;
429
- }
430
- }
431
- finally {
432
- rmSync(temporaryPath, { force: true });
433
- }
434
- throw new Error(`Could not acquire Anhedral transaction lock (${lockPath}).`);
435
- }
436
- function releaseTransactionLock(lock) {
437
- if (!pathEntryExists(lock.lockPath))
438
- return;
439
- const current = parseLockOwner(lock.lockPath);
440
- if (current.token === lock.owner.token)
441
- unlinkSync(lock.lockPath);
442
- }
443
237
  function assertExpectedTempRoot(root, candidate, kind) {
444
238
  const resolved = path.resolve(candidate);
445
239
  const tokenPattern = '(\\d+-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})';
@@ -0,0 +1,101 @@
1
+ import type { DeliveryRunner } from './project-state.js';
2
+ export declare const cli: string[];
3
+ export interface WebProject {
4
+ schemaVersion: 1;
5
+ id: string;
6
+ name: string;
7
+ ownership: 'customer';
8
+ provider: 'vercel';
9
+ directory: 'apps/web';
10
+ teamId: string | null;
11
+ projectId: string | null;
12
+ scope: string | null;
13
+ audience: 'unconfigured' | 'public' | 'private';
14
+ use: 'unconfigured' | 'personal' | 'commercial';
15
+ repository?: {
16
+ repoId: number;
17
+ nameWithOwner: string;
18
+ productionBranch?: string;
19
+ };
20
+ }
21
+ export interface WebRelease {
22
+ id: string;
23
+ commit: string;
24
+ operation: 'ship' | 'rollback' | 'adopt' | 'recover';
25
+ provenance?: 'cli' | 'git';
26
+ branch?: string;
27
+ state: 'running' | 'deployed' | 'failed';
28
+ startedAt: string;
29
+ deploymentId?: string;
30
+ url?: string;
31
+ deploymentUrl?: string;
32
+ restoredReleaseId?: string;
33
+ verification?: {
34
+ state: 'passed' | 'failed';
35
+ checkedAt: string;
36
+ };
37
+ }
38
+ export interface ProviderProject {
39
+ id: string;
40
+ name: string;
41
+ accountId: string;
42
+ framework: string;
43
+ rootDirectory: string;
44
+ sourceFilesOutsideRootDirectory?: boolean;
45
+ link?: {
46
+ type: string;
47
+ org?: string;
48
+ repo?: string;
49
+ repoId?: number;
50
+ productionBranch?: string;
51
+ };
52
+ ssoProtection?: {
53
+ deploymentType?: string;
54
+ };
55
+ passwordProtection?: unknown;
56
+ targets?: {
57
+ production?: {
58
+ id?: string;
59
+ };
60
+ };
61
+ }
62
+ export interface ProviderDeployment {
63
+ id: string;
64
+ projectId: string;
65
+ ownerId: string;
66
+ readyState: string;
67
+ target: string;
68
+ url: string;
69
+ alias?: string[];
70
+ meta?: Record<string, string>;
71
+ gitSource?: {
72
+ type?: string;
73
+ repoId?: number | string;
74
+ org?: string;
75
+ repo?: string;
76
+ sha?: string;
77
+ ref?: string;
78
+ prId?: number | null;
79
+ };
80
+ }
81
+ export declare function registerVercelApplication(root: string): WebProject;
82
+ export declare function readWeb(root: string): WebProject;
83
+ export declare function env(project?: WebProject): NodeJS.ProcessEnv;
84
+ export declare function context(root: string, project: WebProject): void;
85
+ export declare function api(root: string, run: DeliveryRunner, endpoint: string, scope?: string, body?: unknown, method?: string): Promise<any>;
86
+ export declare function paginated(root: string, run: DeliveryRunner, endpoint: string, key: string, scope?: string): Promise<any[]>;
87
+ export declare function validateProvider(project: WebProject, value: ProviderProject): void;
88
+ export declare function matchesRepository(link: ProviderProject['link'], repository: NonNullable<WebProject['repository']>): boolean;
89
+ export declare function inspect(root: string, project: WebProject, run: DeliveryRunner): Promise<ProviderProject>;
90
+ export declare function history(root: string, project: WebProject): {
91
+ schemaVersion: 1;
92
+ projectId: string;
93
+ releases: WebRelease[];
94
+ };
95
+ export declare function source(root: string, run: DeliveryRunner): Promise<string>;
96
+ export declare function https(value: string): string;
97
+ export declare function validBranch(branch: string): boolean;
98
+ export declare function deployment(project: WebProject, value: ProviderDeployment, commit: string, provenance?: 'cli' | 'git', branch?: string): void;
99
+ export declare function validateRelease(project: WebProject, value: ProviderDeployment, release: WebRelease): void;
100
+ export declare function committedManifest(root: string, project: WebProject, run: DeliveryRunner): Promise<string>;
101
+ export declare function remoteBranch(root: string, branch: string, commit: string, run: DeliveryRunner): Promise<void>;
@@ -0,0 +1,305 @@
1
+ import { hasProjectSection, readProjectSection, writeProjectSection } from './project-config.js';
2
+ import { githubRepository } from './repository.js';
3
+ import { providerProjectName } from './render.js';
4
+ import { existsSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
5
+ import { randomUUID } from 'node:crypto';
6
+ import path from 'node:path';
7
+ import { tmpdir } from 'node:os';
8
+ import { VERCEL_CLI_VERSION } from './dependencies.js';
9
+ // Keep provider commands reproducible independently of globally installed tooling.
10
+ export const cli = ['dlx', `vercel@${VERCEL_CLI_VERSION}`];
11
+ const manifest = 'anhedral.json';
12
+ function webDirectory(root) {
13
+ root = realpathSync(root);
14
+ const directory = realpathSync(path.join(root, 'apps/web'));
15
+ if (!directory.startsWith(root + path.sep))
16
+ throw new Error('Web directory escapes the application.');
17
+ return directory;
18
+ }
19
+ export function registerVercelApplication(root) {
20
+ root = realpathSync(root);
21
+ webDirectory(root);
22
+ if (hasProjectSection(root, 'vercel'))
23
+ return readWeb(root);
24
+ const setup = readProjectSection(root, 'setup');
25
+ if (setup.hosting !== 'vercel')
26
+ throw new Error('This application did not select Vercel web hosting.');
27
+ const packageName = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8')).name;
28
+ if (typeof packageName !== 'string' || !packageName)
29
+ throw new Error('A package name is required to register the Vercel project.');
30
+ const name = providerProjectName(packageName);
31
+ const project = {
32
+ schemaVersion: 1,
33
+ id: randomUUID(),
34
+ name,
35
+ ownership: 'customer',
36
+ provider: 'vercel',
37
+ directory: 'apps/web',
38
+ teamId: null,
39
+ projectId: null,
40
+ scope: null,
41
+ audience: 'unconfigured',
42
+ use: 'unconfigured',
43
+ };
44
+ const ignore = path.join(root, '.gitignore');
45
+ let source = existsSync(ignore) ? readFileSync(ignore, 'utf8') : '';
46
+ for (const entry of ['.anhedral/', '.vercel/'])
47
+ if (!source.split(/\r?\n/).includes(entry))
48
+ source += (source && !source.endsWith('\n') ? '\n' : '') + entry + '\n';
49
+ writeFileSync(ignore, source);
50
+ writeProjectSection(root, 'vercel', project);
51
+ return project;
52
+ }
53
+ export function readWeb(root) {
54
+ webDirectory(root);
55
+ const project = readProjectSection(root, 'vercel');
56
+ if (project.schemaVersion !== 1 ||
57
+ !/^[a-f0-9-]{36}$/.test(project.id) ||
58
+ project.provider !== 'vercel' ||
59
+ project.ownership !== 'customer' ||
60
+ project.directory !== 'apps/web' ||
61
+ !/^[a-z0-9][a-z0-9-]{0,62}$/.test(project.name) ||
62
+ !['unconfigured', 'public', 'private'].includes(project.audience) ||
63
+ !['unconfigured', 'personal', 'commercial'].includes(project.use) ||
64
+ !(project.teamId === null || /^team_[a-zA-Z0-9]+$/.test(project.teamId)) ||
65
+ !(project.projectId === null || /^prj_[a-zA-Z0-9]+$/.test(project.projectId)) ||
66
+ !(project.scope === null || /^[a-zA-Z0-9_-]+$/.test(project.scope)) ||
67
+ (project.repository !== undefined &&
68
+ (!Number.isSafeInteger(project.repository?.repoId) ||
69
+ project.repository.repoId <= 0 ||
70
+ !/^[a-zA-Z0-9-]+\/[a-zA-Z0-9_.-]+$/.test(project.repository.nameWithOwner) ||
71
+ (project.repository.productionBranch !== undefined &&
72
+ !validBranch(project.repository.productionBranch)))))
73
+ throw new Error('Invalid Vercel application manifest.');
74
+ return project;
75
+ }
76
+ export function env(project) {
77
+ if (project &&
78
+ ((process.env.VERCEL_PROJECT_ID && process.env.VERCEL_PROJECT_ID !== project.projectId) ||
79
+ (process.env.VERCEL_ORG_ID && process.env.VERCEL_ORG_ID !== project.teamId)))
80
+ throw new Error('Vercel environment selects a different project/account.');
81
+ return {
82
+ ...process.env,
83
+ CI: '1',
84
+ NO_COLOR: '1',
85
+ ...(project?.projectId
86
+ ? { VERCEL_PROJECT_ID: project.projectId, VERCEL_ORG_ID: project.teamId }
87
+ : {}),
88
+ };
89
+ }
90
+ export function context(root, project) {
91
+ const file = path.join(root, '.vercel/project.json');
92
+ if (existsSync(path.join(root, '.vercel/repo.json')))
93
+ throw new Error('Reconcile existing Vercel repository links explicitly before using automatic delivery.');
94
+ if (!existsSync(file))
95
+ throw new Error('Run anhedral connect to link the selected Vercel project.');
96
+ if (realpathSync(path.dirname(file)) !== path.join(realpathSync(root), '.vercel'))
97
+ throw new Error('Vercel link directory must not be a symbolic link.');
98
+ const link = JSON.parse(readFileSync(file, 'utf8'));
99
+ if (link.orgId !== project.teamId || link.projectId !== project.projectId)
100
+ throw new Error('Local Vercel link differs from the recorded customer account/project.');
101
+ }
102
+ export async function api(root, run, endpoint, scope, body, method = 'POST') {
103
+ if (!/^\/v\d+\//.test(endpoint) || endpoint.includes('..') || endpoint.includes('#'))
104
+ throw new Error('Invalid Vercel API path.');
105
+ const temporary = path.join(tmpdir(), `anhedral-vercel-${randomUUID()}.json`);
106
+ const args = [
107
+ ...cli,
108
+ 'api',
109
+ endpoint,
110
+ '--raw',
111
+ '--non-interactive',
112
+ ...(scope ? ['--scope', scope] : []),
113
+ ];
114
+ try {
115
+ if (body) {
116
+ writeFileSync(temporary, JSON.stringify(body), { mode: 0o600, flag: 'wx' });
117
+ args.push('-X', method, '--input', temporary);
118
+ }
119
+ const output = await run('pnpm', args, root, env());
120
+ let value;
121
+ try {
122
+ value = JSON.parse(output);
123
+ }
124
+ catch {
125
+ throw new Error('Vercel did not return valid provider JSON.');
126
+ }
127
+ if (!value || typeof value !== 'object' || value.error || value.status === 'error')
128
+ throw new Error('Vercel rejected the request; verify login, scope and project permissions.');
129
+ return value;
130
+ }
131
+ finally {
132
+ rmSync(temporary, { force: true });
133
+ }
134
+ }
135
+ export async function paginated(root, run, endpoint, key, scope) {
136
+ const result = [];
137
+ let cursor;
138
+ for (let page = 0; page < 1000; page++) {
139
+ const data = await api(root, run, `${endpoint}${endpoint.includes('?') ? '&' : '?'}limit=100${cursor ? `&until=${cursor}` : ''}`, scope);
140
+ if (!Array.isArray(data[key]))
141
+ throw new Error('Invalid Vercel provider listing.');
142
+ result.push(...data[key]);
143
+ if (data[key].length === 0)
144
+ return result;
145
+ const next = data.pagination?.next;
146
+ if (next === null || next === undefined)
147
+ return result;
148
+ if (typeof next !== 'number' || !Number.isFinite(next) || next === cursor)
149
+ throw new Error('Invalid Vercel pagination cursor.');
150
+ cursor = next;
151
+ }
152
+ throw new Error('Vercel listing exceeded pagination bounds.');
153
+ }
154
+ function protection(project, provider) {
155
+ const all = provider.ssoProtection?.deploymentType === 'all';
156
+ if (project.audience === 'private' && !all)
157
+ throw new Error('Private Vercel hosting requires verified protection for all deployments, including production. Configure Vercel Authentication for every deployment in the selected project; protection was not disabled or purchased.');
158
+ if (project.audience === 'public' && (all || provider.passwordProtection))
159
+ throw new Error('Provider production protection differs from the requested public audience. Reconcile it explicitly.');
160
+ }
161
+ export function validateProvider(project, value) {
162
+ if (value.id !== project.projectId ||
163
+ value.accountId !== project.teamId ||
164
+ value.name !== project.name ||
165
+ value.framework !== 'nextjs' ||
166
+ value.rootDirectory !== project.directory ||
167
+ value.sourceFilesOutsideRootDirectory !== true)
168
+ throw new Error('Vercel provider account, framework or monorepo root differs from the manifest.');
169
+ protection(project, value);
170
+ if (project.repository &&
171
+ (!matchesRepository(value.link, project.repository) ||
172
+ (project.repository.productionBranch !== undefined &&
173
+ value.link?.productionBranch !== project.repository.productionBranch)))
174
+ throw new Error('Vercel Git repository differs from the recorded source repository. Reconcile it explicitly.');
175
+ }
176
+ export function matchesRepository(link, repository) {
177
+ const [owner, name] = repository.nameWithOwner.split('/');
178
+ return (link?.type === 'github' &&
179
+ link.repoId === repository.repoId &&
180
+ link.org?.toLowerCase() === owner.toLowerCase() &&
181
+ link.repo?.toLowerCase() === name.toLowerCase());
182
+ }
183
+ export async function inspect(root, project, run) {
184
+ context(root, project);
185
+ env(project);
186
+ const team = await api(root, run, `/v2/teams/${project.teamId}`, project.teamId);
187
+ if (team.id !== project.teamId ||
188
+ !['hobby', 'pro', 'enterprise'].includes(team.billing?.plan) ||
189
+ (project.use === 'commercial' && team.billing.plan === 'hobby'))
190
+ throw new Error('Selected Vercel account plan no longer supports the recorded application use.');
191
+ const linked = JSON.parse(await run('pnpm', [...cli, 'project', 'inspect', '--json', '--non-interactive', '--scope', project.teamId], root, env(project)));
192
+ if (linked.id !== project.projectId || linked.owner?.slug !== project.scope)
193
+ throw new Error('Vercel CLI resolved a different project/account.');
194
+ const provider = await api(root, run, `/v9/projects/${project.projectId}?teamId=${project.teamId}`, project.teamId);
195
+ validateProvider(project, provider);
196
+ if (project.repository) {
197
+ const repository = await githubRepository(root, run);
198
+ if (repository.repoId !== project.repository.repoId ||
199
+ repository.nameWithOwner.toLowerCase() !== project.repository.nameWithOwner.toLowerCase())
200
+ throw new Error('GitHub origin differs from the recorded source repository. Reconcile it explicitly.');
201
+ }
202
+ return provider;
203
+ }
204
+ export function history(root, project) {
205
+ const file = path.join(root, '.anhedral/web-releases.json');
206
+ const value = existsSync(file)
207
+ ? JSON.parse(readFileSync(file, 'utf8'))
208
+ : { schemaVersion: 1, projectId: project.id, releases: [] };
209
+ if (value.schemaVersion !== 1 || value.projectId !== project.id || !Array.isArray(value.releases))
210
+ throw new Error('Vercel release history differs from project identity.');
211
+ return value;
212
+ }
213
+ export async function source(root, run) {
214
+ if (realpathSync((await run('git', ['rev-parse', '--show-toplevel'], root, env())).trim()) !==
215
+ root ||
216
+ (await run('git', ['status', '--porcelain'], root, env())).trim())
217
+ throw new Error('Commit the application and manifest in their own repository before delivery/verification.');
218
+ const commit = (await run('git', ['rev-parse', 'HEAD'], root, env())).trim();
219
+ if (!/^[a-f0-9]{40,64}$/.test(commit))
220
+ throw new Error('Invalid source commit.');
221
+ return commit;
222
+ }
223
+ export function https(value) {
224
+ const url = new URL(value.startsWith('https://') ? value : `https://${value}`);
225
+ if (url.protocol !== 'https:' ||
226
+ url.username ||
227
+ url.password ||
228
+ url.port ||
229
+ url.search ||
230
+ url.hash ||
231
+ url.pathname !== '/')
232
+ throw new Error('Invalid provider deployment URL.');
233
+ return url.origin;
234
+ }
235
+ export function validBranch(branch) {
236
+ return (typeof branch === 'string' &&
237
+ branch.length > 0 &&
238
+ branch.length < 256 &&
239
+ !branch.startsWith('-') &&
240
+ !branch.startsWith('/') &&
241
+ !branch.endsWith('/') &&
242
+ !branch.endsWith('.') &&
243
+ !branch.includes('..') &&
244
+ !branch.includes('@{') &&
245
+ !/[\x00-\x20\x7f~^:?*\\[\]]/.test(branch) &&
246
+ !branch.split('/').some((part) => !part || part.startsWith('.') || part.endsWith('.lock')));
247
+ }
248
+ export function deployment(project, value, commit, provenance = 'cli', branch) {
249
+ if (!/^[a-f0-9]{40,64}$/.test(commit) ||
250
+ !/^dpl_[a-zA-Z0-9]+$/.test(value.id) ||
251
+ value.projectId !== project.projectId ||
252
+ value.ownerId !== project.teamId ||
253
+ value.readyState !== 'READY' ||
254
+ value.target !== 'production')
255
+ throw new Error('Vercel deployment is not ready or differs from account/project/source provenance.');
256
+ if (provenance === 'git') {
257
+ const repository = project.repository;
258
+ const git = value.gitSource;
259
+ const identity = git?.repoId !== undefined && String(git.repoId) === String(repository?.repoId);
260
+ if (!repository ||
261
+ !branch ||
262
+ !validBranch(branch) ||
263
+ git?.type !== 'github' ||
264
+ !identity ||
265
+ git.sha !== commit ||
266
+ git.ref !== branch ||
267
+ git.prId != null)
268
+ throw new Error('Git deployment differs from the recorded repository, production branch or source commit.');
269
+ }
270
+ else if (value.meta?.anhedralProject !== project.id || value.meta?.anhedralCommit !== commit)
271
+ throw new Error('Vercel deployment differs from recorded CLI provenance.');
272
+ https(value.url);
273
+ }
274
+ export function validateRelease(project, value, release) {
275
+ deployment(project, value, release.commit, release.provenance ?? 'cli', release.branch);
276
+ if (value.id !== release.deploymentId ||
277
+ !release.deploymentUrl ||
278
+ https(value.url) !== https(release.deploymentUrl))
279
+ throw new Error('Recorded deployment identity or URL differs from provider evidence.');
280
+ }
281
+ export async function committedManifest(root, project, run) {
282
+ const commit = await source(root, run);
283
+ let recorded;
284
+ try {
285
+ const configuration = JSON.parse(await run('git', ['show', `HEAD:${manifest}`], root, env(project)));
286
+ if (configuration.schemaVersion !== 1)
287
+ throw new Error('Invalid committed project configuration.');
288
+ recorded = configuration.vercel;
289
+ }
290
+ catch {
291
+ throw new Error('Commit the Vercel identity manifest before adoption or recovery.');
292
+ }
293
+ if (JSON.stringify(recorded) !== JSON.stringify(project))
294
+ throw new Error('Committed Vercel identity differs from the application manifest.');
295
+ return commit;
296
+ }
297
+ export async function remoteBranch(root, branch, commit, run) {
298
+ if (!validBranch(branch))
299
+ throw new Error('Record an explicit valid production branch before Git adoption.');
300
+ const ref = `refs/heads/${branch}`;
301
+ const output = (await run('git', ['ls-remote', '--heads', 'origin', ref], root, env())).trim();
302
+ const rows = output.split(/\r?\n/).filter(Boolean);
303
+ if (rows.length !== 1 || rows[0] !== `${commit}\t${ref}`)
304
+ throw new Error('Remote production branch does not match the exact clean source commit.');
305
+ }
package/dist/vercel.d.ts CHANGED
@@ -1,40 +1,7 @@
1
+ import { type WebProject, type WebRelease } from './vercel-project.js';
2
+ export { registerVercelApplication } from './vercel-project.js';
3
+ export type { WebProject, WebRelease } from './vercel-project.js';
1
4
  import { type DeliveryRunner } from './project-state.js';
2
- export interface WebProject {
3
- schemaVersion: 1;
4
- id: string;
5
- name: string;
6
- ownership: 'customer';
7
- provider: 'vercel';
8
- directory: 'apps/web';
9
- teamId: string | null;
10
- projectId: string | null;
11
- scope: string | null;
12
- audience: 'unconfigured' | 'public' | 'private';
13
- use: 'unconfigured' | 'personal' | 'commercial';
14
- repository?: {
15
- repoId: number;
16
- nameWithOwner: string;
17
- productionBranch?: string;
18
- };
19
- }
20
- export interface WebRelease {
21
- id: string;
22
- commit: string;
23
- operation: 'ship' | 'rollback' | 'adopt' | 'recover';
24
- provenance?: 'cli' | 'git';
25
- branch?: string;
26
- state: 'running' | 'deployed' | 'failed';
27
- startedAt: string;
28
- deploymentId?: string;
29
- url?: string;
30
- deploymentUrl?: string;
31
- restoredReleaseId?: string;
32
- verification?: {
33
- state: 'passed' | 'failed';
34
- checkedAt: string;
35
- };
36
- }
37
- export declare function registerVercelApplication(root: string): WebProject;
38
5
  export declare function connectVercelApplication(root: string, options: {
39
6
  scope?: string;
40
7
  audience: 'public' | 'private';