anhedral 0.11.0 → 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 (148) hide show
  1. package/README.md +73 -157
  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 +15 -11
  9. package/dist/capabilities.d.ts +4 -4
  10. package/dist/capabilities.js +6 -2
  11. package/dist/capability-contract.js +22 -5
  12. package/dist/catalog-model.d.ts +24 -0
  13. package/dist/catalog-model.js +1 -0
  14. package/dist/catalog-registration.d.ts +16 -0
  15. package/dist/catalog-registration.js +22 -0
  16. package/dist/catalog-snapshot.d.ts +5 -0
  17. package/dist/catalog-snapshot.js +97 -0
  18. package/dist/cli-arguments.js +1 -1
  19. package/dist/cli-output.js +27 -2
  20. package/dist/cloudflare.d.ts +7 -1
  21. package/dist/cloudflare.js +36 -6
  22. package/dist/command-schema.js +49 -5
  23. package/dist/delivery.d.ts +10 -3
  24. package/dist/delivery.js +154 -37
  25. package/dist/dependencies.d.ts +24 -0
  26. package/dist/dependencies.js +48 -0
  27. package/dist/dependency-patches.d.ts +7 -0
  28. package/dist/dependency-patches.js +125 -0
  29. package/dist/index.d.ts +3 -0
  30. package/dist/index.js +2 -0
  31. package/dist/inspector-model.d.ts +9 -1
  32. package/dist/integration-service-readers.d.ts +13 -0
  33. package/dist/integration-service-readers.js +173 -0
  34. package/dist/lifecycle.d.ts +0 -1
  35. package/dist/lifecycle.js +0 -1
  36. package/dist/neon-service-data.d.ts +8 -0
  37. package/dist/neon-service-data.js +117 -0
  38. package/dist/pnpm-policy.d.ts +2 -2
  39. package/dist/pnpm-policy.js +19 -45
  40. package/dist/project-catalog.d.ts +41 -0
  41. package/dist/project-catalog.js +288 -0
  42. package/dist/project-config.d.ts +14 -0
  43. package/dist/project-config.js +89 -0
  44. package/dist/project-inspector.js +73 -17
  45. package/dist/project-lifecycle.d.ts +25 -0
  46. package/dist/project-lifecycle.js +57 -0
  47. package/dist/project-state.d.ts +5 -1
  48. package/dist/project-state.js +122 -16
  49. package/dist/provider-auth.js +2 -3
  50. package/dist/provider-readiness.js +27 -10
  51. package/dist/providers/adapters.js +4 -1
  52. package/dist/providers/api.d.ts +1 -0
  53. package/dist/providers/api.js +1 -0
  54. package/dist/providers/config.js +6 -8
  55. package/dist/providers/provision.js +1 -1
  56. package/dist/providers/recovery.d.ts +1 -1
  57. package/dist/providers/runtime.d.ts +1 -1
  58. package/dist/providers/runtime.js +46 -23
  59. package/dist/providers/state.d.ts +1 -2
  60. package/dist/providers/state.js +14 -54
  61. package/dist/provision.d.ts +9 -0
  62. package/dist/provision.js +30 -1
  63. package/dist/r2-service-data.d.ts +2 -0
  64. package/dist/r2-service-data.js +136 -0
  65. package/dist/readiness.js +9 -13
  66. package/dist/registry/add.js +64 -21
  67. package/dist/registry/commands.js +7 -9
  68. package/dist/registry/options.d.ts +1 -1
  69. package/dist/registry/options.js +4 -4
  70. package/dist/registry/receipt.d.ts +1 -0
  71. package/dist/registry/receipt.js +19 -4
  72. package/dist/registry/resolve.js +5 -1
  73. package/dist/registry/usage.js +1 -5
  74. package/dist/render.d.ts +2 -0
  75. package/dist/render.js +6 -0
  76. package/dist/runtime-policy.d.ts +4 -0
  77. package/dist/runtime-policy.js +21 -0
  78. package/dist/scaffold/bootstrap.js +2 -2
  79. package/dist/scaffold/compose.js +9 -3
  80. package/dist/scaffold/database.js +107 -25
  81. package/dist/scaffold/documentation.js +18 -13
  82. package/dist/scaffold/lint.d.ts +4 -0
  83. package/dist/scaffold/lint.js +56 -0
  84. package/dist/scaffold/neon-realtime.d.ts +2 -0
  85. package/dist/scaffold/neon-realtime.js +97 -0
  86. package/dist/scaffold/stack-documentation.js +1 -1
  87. package/dist/scaffold/void.d.ts +4 -0
  88. package/dist/scaffold/void.js +256 -0
  89. package/dist/scaffold/web.js +7 -1
  90. package/dist/scaffold/workspace.js +120 -29
  91. package/dist/service-deletion.d.ts +29 -0
  92. package/dist/service-deletion.js +195 -0
  93. package/dist/service-descriptor.d.ts +10 -0
  94. package/dist/service-descriptor.js +78 -0
  95. package/dist/service-model.d.ts +49 -0
  96. package/dist/service-model.js +8 -0
  97. package/dist/service-operations.d.ts +29 -0
  98. package/dist/service-operations.js +78 -0
  99. package/dist/service-readers.d.ts +8 -0
  100. package/dist/service-readers.js +247 -0
  101. package/dist/services-command.d.ts +39 -0
  102. package/dist/services-command.js +100 -0
  103. package/dist/ship.d.ts +36 -8
  104. package/dist/ship.js +39 -13
  105. package/dist/stack-registry.d.ts +4 -2
  106. package/dist/stack-registry.js +41 -11
  107. package/dist/standard.js +23 -4
  108. package/dist/transaction.d.ts +2 -0
  109. package/dist/transaction.js +10 -0
  110. package/dist/util.js +17 -2
  111. package/dist/vercel.d.ts +2 -0
  112. package/dist/vercel.js +69 -13
  113. package/dist/version.d.ts +1 -1
  114. package/dist/version.js +1 -1
  115. package/dist/vinext.d.ts +1 -0
  116. package/dist/vinext.js +13 -1
  117. package/dist/void-execution.d.ts +10 -0
  118. package/dist/void-execution.js +94 -0
  119. package/dist/void-migrations.d.ts +6 -0
  120. package/dist/void-migrations.js +110 -0
  121. package/dist/void-state.d.ts +16 -0
  122. package/dist/void-state.js +65 -0
  123. package/dist/void.d.ts +3 -0
  124. package/dist/void.js +5 -0
  125. package/docs/cli-design.md +2 -2
  126. package/docs/delivery-workflow.md +8 -7
  127. package/docs/plugin-ui.md +51 -10
  128. package/docs/provider-configuration.md +10 -11
  129. package/docs/stack-standard.md +175 -0
  130. package/docs/void-verification.md +185 -0
  131. package/package.json +22 -20
  132. package/assets/anhedral-mark.svg +0 -4
  133. package/assets/anhedral-stack-technical.svg +0 -322
  134. package/assets/anhedral-stack.svg +0 -322
  135. package/assets/anhedral.svg +0 -4
  136. package/assets/favicon.ico +0 -0
  137. package/assets/security/LICENSES.txt +0 -63
  138. package/assets/security/audit-deps.mjs +0 -300
  139. package/assets/security/braces-regression.mjs +0 -102
  140. package/assets/security/braces@3.0.3.patch +0 -285
  141. package/assets/security/decode-uri-component@0.2.2.patch +0 -149
  142. package/assets/security/decoder-regression.mjs +0 -37
  143. package/assets/security/forge-regression.mjs +0 -46
  144. package/assets/security/manifest.json +0 -53
  145. package/assets/security/node-forge@1.4.0.patch +0 -26
  146. package/dist/security-backports.d.ts +0 -3
  147. package/dist/security-backports.js +0 -26
  148. package/docs/application-stack-standard.md +0 -75
@@ -60,11 +60,13 @@ export interface ResourceEvidence {
60
60
  name: string;
61
61
  id: string;
62
62
  reused: boolean | null;
63
+ createdByProject?: boolean | null;
63
64
  recordedAt: string | null;
64
65
  }
65
66
  /** Browser-safe projection. Read time never substitutes for provider evidence time. */
66
67
  export interface ProjectInspection {
67
68
  schemaVersion: 1;
69
+ lifecycle?: import('./project-lifecycle.js').ProjectLifecycle;
68
70
  name: string;
69
71
  inspectedAt: string;
70
72
  authentication: {
@@ -102,6 +104,13 @@ export interface ProjectInspection {
102
104
  targets: InspectionSection<TargetEvidence[]>;
103
105
  integrations: InspectionSection<IntegrationEvidence[]>;
104
106
  cloudflareResources: InspectionSection<ResourceEvidence[]>;
107
+ serviceDeletions?: InspectionSection<{
108
+ resourceId: string;
109
+ kind: string;
110
+ name: string;
111
+ state: 'pending' | 'deleted' | 'uncertain';
112
+ recordedAt: string | null;
113
+ }[]>;
105
114
  readiness: InspectionSection<{
106
115
  localReady: boolean;
107
116
  checks: {
@@ -112,4 +121,3 @@ export interface ProjectInspection {
112
121
  }>;
113
122
  operation: InspectionSection<LifecycleOperation | null>;
114
123
  }
115
- export type ApplicationInspection = ProjectInspection;
@@ -0,0 +1,13 @@
1
+ import { type IntegrationProvider, type ProviderSettings } from './providers/config.js';
2
+ import { type ApiRequest } from './providers/api.js';
3
+ import type { ServiceMetrics, ServiceObservation } from './service-model.js';
4
+ export interface IntegrationService {
5
+ provider: IntegrationProvider;
6
+ settings: ProviderSettings;
7
+ resources: Record<string, string>;
8
+ }
9
+ export declare function resolveIntegrationService(root: string, key: string): IntegrationService;
10
+ export declare function integrationRequest(service: IntegrationService, env?: NodeJS.ProcessEnv, send?: typeof fetch): ApiRequest;
11
+ export declare function inspectIntegrationResource(service: IntegrationService, api: ApiRequest): Promise<Record<string, unknown>>;
12
+ export declare function observeIntegrationService(service: IntegrationService, api: ApiRequest): Promise<ServiceObservation>;
13
+ export declare function posthogServiceMetrics(service: IntegrationService, api: ApiRequest, hours?: number): Promise<ServiceMetrics>;
@@ -0,0 +1,173 @@
1
+ import { inspectApplication } from './project-inspector.js';
2
+ import { providerConfiguration, setting, } from './providers/config.js';
3
+ import { INTEGRATION_PROVIDERS } from './providers/definitions.js';
4
+ import { providerApi, ProviderRequestError, resourceId } from './providers/api.js';
5
+ import { record } from './service-readers.js';
6
+ export function resolveIntegrationService(root, key) {
7
+ const inspection = inspectApplication(root);
8
+ const match = key.match(/^(provider|integration):([a-z]+)(?::(.+))?$/);
9
+ if (!match ||
10
+ !INTEGRATION_PROVIDERS.includes(match[2]) ||
11
+ !inspection.setupProviders.data.some((provider) => provider.id === match[2]))
12
+ throw new Error('Choose a selected integration service.');
13
+ const provider = match[2];
14
+ let resources = {};
15
+ if (match[1] === 'integration') {
16
+ const operation = inspection.integrations.data
17
+ .find((entry) => entry.provider === provider)
18
+ ?.operations.find((entry) => entry.operation === match[3]);
19
+ if (!operation || operation.status !== 'complete')
20
+ throw new Error('The integration operation is not complete.');
21
+ resources = operation.resources;
22
+ }
23
+ const settings = providerConfiguration(root).providers[provider];
24
+ if (!settings)
25
+ throw new Error('Complete the selected provider configuration.');
26
+ return { provider, settings, resources };
27
+ }
28
+ export function integrationRequest(service, env = process.env, send = fetch) {
29
+ return providerApi(service.provider, service.settings, env, send, {
30
+ maxAttempts: 1,
31
+ totalTimeoutMs: 10000,
32
+ attemptTimeoutMs: 10000,
33
+ });
34
+ }
35
+ function selected(service, field, receipt) {
36
+ const configured = setting(service.settings, field);
37
+ const recorded = service.resources[receipt];
38
+ if (configured && recorded && configured !== recorded)
39
+ throw new Error('Configured and recorded integration identities differ.');
40
+ return resourceId(configured || recorded);
41
+ }
42
+ export async function inspectIntegrationResource(service, api) {
43
+ const { provider, settings } = service;
44
+ let value;
45
+ let expected;
46
+ let returned;
47
+ if (provider === 'neon') {
48
+ expected = selected(service, 'projectId', 'project');
49
+ value = record(record(await api(`/api/v2/projects/${expected}`)).project);
50
+ returned = value.id;
51
+ if (value.org_id !== setting(settings, 'organizationId'))
52
+ throw new Error('Neon organization differs.');
53
+ }
54
+ else if (provider === 'clerk') {
55
+ if (record(await api('/v1/platform/me')).subject !== setting(settings, 'workspaceId'))
56
+ throw new Error('Clerk workspace differs.');
57
+ expected = selected(service, 'applicationId', 'application');
58
+ value = record(await api(`/v1/platform/applications/${expected}?include_secret_keys=false`));
59
+ returned = value.application_id;
60
+ }
61
+ else if (provider === 'resend') {
62
+ expected = selected(service, 'domainId', 'domain');
63
+ value = record(await api(`/domains/${expected}`));
64
+ returned = value.id;
65
+ if (value.name !== setting(settings, 'domain'))
66
+ throw new Error('Resend domain differs.');
67
+ }
68
+ else if (provider === 'stripe') {
69
+ if (record(await api('/v1/account')).id !== setting(settings, 'accountId'))
70
+ throw new Error('Stripe account differs.');
71
+ expected = resourceId(service.resources.webhook);
72
+ value = record(await api(`/v1/webhook_endpoints/${expected}`));
73
+ returned = value.id;
74
+ if (value.livemode !== (setting(settings, 'mode') === 'live') ||
75
+ value.url !== setting(settings, 'webhookUrl'))
76
+ throw new Error('Stripe environment or webhook differs.');
77
+ }
78
+ else if (provider === 'revenuecat') {
79
+ expected = selected(service, 'projectId', 'project');
80
+ value = record(await api(`/v2/projects/${expected}`));
81
+ returned = value.id;
82
+ }
83
+ else if (provider === 'sentry') {
84
+ const organization = resourceId(setting(settings, 'organization'));
85
+ const slug = resourceId(setting(settings, 'project'));
86
+ value = record(await api(`/api/0/projects/${organization}/${slug}/`));
87
+ expected = resourceId(service.resources.project ?? value.id);
88
+ returned = value.id;
89
+ if (record(value.organization).slug !== organization || value.slug !== slug)
90
+ throw new Error('Sentry organization or project differs.');
91
+ }
92
+ else if (provider === 'posthog') {
93
+ expected = selected(service, 'projectId', 'project');
94
+ const organization = resourceId(setting(settings, 'organizationId'));
95
+ value = record(await api(`/api/organizations/${organization}/projects/${expected}/`));
96
+ returned = String(value.id);
97
+ if (value.organization !== organization)
98
+ throw new Error('PostHog organization differs.');
99
+ }
100
+ else {
101
+ expected = selected(service, 'projectId', 'project');
102
+ value = record(await api(`/v1/organization/projects/${expected}`));
103
+ returned = value.id;
104
+ }
105
+ if (String(returned) !== expected)
106
+ throw new Error('Provider resource identity differs.');
107
+ return value;
108
+ }
109
+ export async function observeIntegrationService(service, api) {
110
+ const fetchedAt = new Date().toISOString();
111
+ try {
112
+ const value = await inspectIntegrationResource(service, api);
113
+ const name = typeof value.name === 'string' && value.name.length <= 256 ? value.name : undefined;
114
+ return {
115
+ state: 'available',
116
+ fetchedAt,
117
+ ...(name ? { name } : {}),
118
+ message: 'Provider confirmed the selected resource and account context. Application health is separate.',
119
+ };
120
+ }
121
+ catch (error) {
122
+ const status = error instanceof ProviderRequestError ? error.status : undefined;
123
+ return {
124
+ state: status === 404
125
+ ? 'not-found'
126
+ : status === 401 || status === 403
127
+ ? 'permission-required'
128
+ : 'unavailable',
129
+ fetchedAt,
130
+ message: 'Selected integration could not be verified. Check account configuration, identity and scoped permissions.',
131
+ };
132
+ }
133
+ }
134
+ export async function posthogServiceMetrics(service, api, hours = 24) {
135
+ if (service.provider !== 'posthog' || ![1, 24, 168].includes(hours))
136
+ throw new Error('Unsupported analytics selection.');
137
+ await inspectIntegrationResource(service, api);
138
+ const end = new Date().toISOString();
139
+ const start = new Date(Date.parse(end) - hours * 3600000).toISOString();
140
+ const id = selected(service, 'projectId', 'project');
141
+ const date = (value) => value.slice(0, 19).replace('T', ' ');
142
+ const value = record(await api(`/api/projects/${id}/query/`, 'POST', {
143
+ query: {
144
+ kind: 'HogQLQuery',
145
+ query: `SELECT formatDateTime(timestamp, '%Y-%m-%dT%H:00:00Z', 'UTC') AS time, count() AS events, uniqExact(distinct_id) AS visitors FROM events WHERE timestamp >= toDateTime('${date(start)}', 'UTC') AND timestamp < toDateTime('${date(end)}', 'UTC') GROUP BY time ORDER BY time LIMIT 1000`,
146
+ },
147
+ name: 'Anhedral selected-project hourly analytics',
148
+ async: false,
149
+ }));
150
+ if (!Array.isArray(value.results) || value.results.length >= 1000)
151
+ throw new Error('Analytics is pending, truncated or unavailable.');
152
+ const points = value.results.map((row) => {
153
+ if (!Array.isArray(row) ||
154
+ row.length !== 3 ||
155
+ typeof row[0] !== 'string' ||
156
+ !Number.isFinite(Date.parse(row[0])) ||
157
+ row
158
+ .slice(1)
159
+ .some((count) => typeof count !== 'number' || !Number.isFinite(count) || count < 0))
160
+ throw new Error('Unsupported analytics output.');
161
+ return { time: row[0], values: { events: row[1], visitors: row[2] } };
162
+ });
163
+ return {
164
+ start,
165
+ end,
166
+ fetchedAt: new Date().toISOString(),
167
+ source: 'PostHog hourly product analytics',
168
+ timezone: 'UTC',
169
+ sampled: false,
170
+ points,
171
+ units: { events: 'count', visitors: 'hourly bucket count' },
172
+ };
173
+ }
@@ -1,7 +1,6 @@
1
1
  import { type DeliveryRunner } from './project-state.js';
2
2
  import { type LifecycleOperation } from './lifecycle-model.js';
3
3
  export type { LifecycleOperation, OperationState, PhaseState } from './lifecycle-model.js';
4
- export { isLifecycleOperation } from './lifecycle-model.js';
5
4
  export interface LifecycleSession {
6
5
  phase<T>(name: string, action: () => Promise<T>): Promise<T>;
7
6
  }
package/dist/lifecycle.js CHANGED
@@ -4,7 +4,6 @@ import { randomUUID } from 'node:crypto';
4
4
  import { readBoundedFile, MAX_PROJECT_JSON_BYTES } from './bounded-file.js';
5
5
  import { atomicJson, withApplicationLock } from './project-state.js';
6
6
  import { isLifecycleOperation } from './lifecycle-model.js';
7
- export { isLifecycleOperation } from './lifecycle-model.js';
8
7
  /** A nonsecret record of execution; a completed phase is not product acceptance. */
9
8
  export function readLifecycleOperation(root) {
10
9
  root = realpathSync(root);
@@ -0,0 +1,8 @@
1
+ import { neon } from '@neondatabase/serverless';
2
+ import type { ApiRequest } from './providers/api.js';
3
+ import { type IntegrationService } from './integration-service-readers.js';
4
+ import type { ServiceData } from './service-model.js';
5
+ export type NeonRead = (query: string, params?: unknown[]) => Promise<Record<string, unknown>[]>;
6
+ export declare function neonReadConnection(service: IntegrationService, api: ApiRequest, env?: NodeJS.ProcessEnv, createClient?: typeof neon): Promise<NeonRead>;
7
+ export declare function listNeonTables(read: NeonRead): Promise<string[]>;
8
+ export declare function browseNeonData(read: NeonRead, table: string, offset?: number): Promise<ServiceData>;
@@ -0,0 +1,117 @@
1
+ import { neon } from '@neondatabase/serverless';
2
+ import { setting } from './providers/config.js';
3
+ import { record } from './service-readers.js';
4
+ import { inspectIntegrationResource, } from './integration-service-readers.js';
5
+ const identifier = (value) => {
6
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]{0,127}$/.test(value))
7
+ throw new Error('Unsupported database identifier.');
8
+ return `"${value}"`;
9
+ };
10
+ const sensitive = /password|secret|token|email|phone|address|authorization|cookie|session|private|credential/i;
11
+ export async function neonReadConnection(service, api, env = process.env, createClient = neon) {
12
+ if (service.provider !== 'neon')
13
+ throw new Error('Choose the selected Neon project.');
14
+ const project = await inspectIntegrationResource(service, api);
15
+ const connection = env[`ANHEDRAL_NEON_READONLY_URL_${String(project.id)
16
+ .replace(/[^a-zA-Z0-9]/g, '_')
17
+ .toUpperCase()}`] ?? env.ANHEDRAL_NEON_READONLY_URL;
18
+ if (!connection)
19
+ throw new Error('Provide ANHEDRAL_NEON_READONLY_URL for a restricted read-only role.');
20
+ let url;
21
+ try {
22
+ url = new URL(connection);
23
+ }
24
+ catch {
25
+ throw new Error('Invalid read-only database connection.');
26
+ }
27
+ if (!['postgres:', 'postgresql:'].includes(url.protocol) ||
28
+ !url.hostname.endsWith('.neon.tech') ||
29
+ !url.username ||
30
+ !url.password ||
31
+ (url.port && url.port !== '5432') ||
32
+ decodeURIComponent(url.pathname.slice(1)) !== setting(service.settings, 'database'))
33
+ throw new Error('Read-only database connection does not match selected configuration.');
34
+ const endpoints = record(await api(`/api/v2/projects/${project.id}/endpoints`)).endpoints;
35
+ if (!Array.isArray(endpoints) ||
36
+ endpoints.length > 100 ||
37
+ !endpoints.some((endpoint) => record(endpoint).host === url.hostname.replace(/-pooler\./, '.')))
38
+ throw new Error('Database endpoint does not belong to the selected Neon project.');
39
+ const sql = createClient(connection);
40
+ return async (query, params = []) => {
41
+ try {
42
+ const result = await sql.transaction([
43
+ sql.query("SELECT set_config('statement_timeout','5000',true)"),
44
+ sql.query("SELECT current_setting('transaction_read_only') = 'on' AS read_only, (SELECT rolsuper OR rolcreatedb OR rolcreaterole FROM pg_roles WHERE rolname = current_user) AS privileged, EXISTS(SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='public' AND c.relkind IN ('r','p') AND has_table_privilege(current_user,c.oid,'INSERT,UPDATE,DELETE,TRUNCATE')) AS writable"),
45
+ sql.query(query, params),
46
+ ], {
47
+ readOnly: true,
48
+ isolationLevel: 'RepeatableRead',
49
+ fetchOptions: { signal: AbortSignal.timeout(10000), redirect: 'error' },
50
+ });
51
+ const role = result[1]?.[0];
52
+ if (role?.read_only !== true || role.privileged !== false || role.writable !== false)
53
+ throw new Error('Restricted read-only role required.');
54
+ if (!Array.isArray(result[2]) || result[2].length > 1001)
55
+ throw new Error('Database response exceeded limits.');
56
+ return result[2].map(record);
57
+ }
58
+ catch {
59
+ throw new Error('Neon read failed. Check the selected endpoint, restricted role, read permissions and query limits.');
60
+ }
61
+ };
62
+ }
63
+ export async function listNeonTables(read) {
64
+ const rows = await read("SELECT table_name AS name FROM information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE' ORDER BY table_name LIMIT 1001");
65
+ if (rows.length > 1000)
66
+ throw new Error('Database schema exceeds its table limit.');
67
+ return rows.map((row) => {
68
+ if (typeof row.name !== 'string')
69
+ throw new Error('Invalid database table.');
70
+ identifier(row.name);
71
+ return row.name;
72
+ });
73
+ }
74
+ export async function browseNeonData(read, table, offset = 0) {
75
+ identifier(table);
76
+ if (!Number.isSafeInteger(offset) ||
77
+ offset < 0 ||
78
+ offset > 10000 ||
79
+ !(await listNeonTables(read)).includes(table))
80
+ throw new Error('Choose a bounded existing table page.');
81
+ const fields = await read("SELECT column_name AS name FROM information_schema.columns WHERE table_schema='public' AND table_name=$1 ORDER BY ordinal_position LIMIT 51", [table]);
82
+ if (fields.length > 50 || !fields.length)
83
+ throw new Error('Table exceeds its supported column limit.');
84
+ const columns = fields.map((row) => {
85
+ if (typeof row.name !== 'string')
86
+ throw new Error('Invalid database column.');
87
+ identifier(row.name);
88
+ return row.name;
89
+ });
90
+ const projection = columns
91
+ .map((column) => sensitive.test(column)
92
+ ? `'[masked]'::text AS ${identifier(column)}`
93
+ : `left(${identifier(column)}::text,1000) AS ${identifier(column)}`)
94
+ .join(', ');
95
+ const rows = await read(`SELECT ${projection} FROM public.${identifier(table)} ORDER BY ${columns.map((_, index) => index + 1).join(', ')} LIMIT $1 OFFSET $2`, [26, offset]);
96
+ let masked = columns.some((column) => sensitive.test(column));
97
+ const outputRows = rows.slice(0, 25).map((row) => columns.map((column) => {
98
+ const value = row[column];
99
+ if (value === null)
100
+ return null;
101
+ if (typeof value !== 'string')
102
+ throw new Error('Unsupported database value.');
103
+ if (/^(?:sk[-_]|rk[-_]|whsec[-_]|Bearer )/i.test(value)) {
104
+ masked = true;
105
+ return '[masked]';
106
+ }
107
+ return value.slice(0, 1000);
108
+ }));
109
+ return {
110
+ fetchedAt: new Date().toISOString(),
111
+ columns,
112
+ rows: outputRows,
113
+ offset,
114
+ hasMore: rows.length > 25,
115
+ masked,
116
+ };
117
+ }
@@ -1,4 +1,4 @@
1
1
  /** Preserve unrelated starter YAML while replacing the settings this initializer owns. */
2
2
  export declare function setPnpmPolicy(root: string, policy: Record<string, unknown>): void;
3
- /** Merge reviewed patches without deleting starter-maintained mappings. */
4
- export declare function mergePnpmPatches(root: string, patches: Record<string, string>): void;
3
+ /** Extend a pnpm patch map without replacing unrelated patches or YAML comments. */
4
+ export declare function pnpmPatchPolicy(source: string, coordinate: string, patch: string): string;
@@ -1,6 +1,7 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { writeFile } from './util.js';
4
+ import { isMap, parseDocument } from 'yaml';
4
5
  function policyBlock(key) {
5
6
  const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
6
7
  return new RegExp(`^(?:${escaped}|"${escaped}"|'${escaped}')[ \\t]*:.*(?:\\r?\\n|$)(?:[ \\t]+[^\\n]*(?:\\n|$)|#[^\\n]*(?:\\n|$)|[ \\t]*\\n)*`, 'gm');
@@ -17,50 +18,23 @@ export function setPnpmPolicy(root, policy) {
17
18
  }
18
19
  writeFile(file, source);
19
20
  }
20
- /** Merge reviewed patches without deleting starter-maintained mappings. */
21
- export function mergePnpmPatches(root, patches) {
22
- const file = path.join(root, 'pnpm-workspace.yaml');
23
- const source = existsSync(file) ? readFileSync(file, 'utf8') : '';
24
- const blocks = [...source.matchAll(policyBlock('patchedDependencies'))];
25
- if (blocks.length > 1)
26
- throw new Error('Duplicate patchedDependencies configuration');
27
- const block = blocks[0]?.[0] ?? '';
28
- const existing = patchRows(block, patches);
29
- const replacement = 'patchedDependencies:\n' +
30
- existing +
31
- Object.entries(patches)
32
- .map(([key, value]) => ` ${JSON.stringify(key)}: ${JSON.stringify(value)}\n`)
33
- .join('');
34
- const remaining = source.replace(policyBlock('patchedDependencies'), '');
35
- writeFile(file, remaining + `${remaining.endsWith('\n') || !remaining ? '' : '\n'}${replacement}`);
36
- }
37
- function patchRows(block, patches) {
38
- if (!block)
39
- return '';
40
- const [header, ...rows] = block.split(/\r?\n/);
41
- const value = header.slice(header.indexOf(':') + 1).trim();
42
- if (value && !value.startsWith('#')) {
43
- const object = JSON.parse(value);
44
- if (!object ||
45
- Array.isArray(object) ||
46
- typeof object !== 'object' ||
47
- Object.values(object).some((entry) => typeof entry !== 'string'))
48
- throw new Error('Unsupported patchedDependencies mapping');
49
- return Object.entries(object)
50
- .filter(([key]) => !Object.hasOwn(patches, key))
51
- .map(([key, entry]) => ` ${JSON.stringify(key)}: ${JSON.stringify(entry)}\n`)
52
- .join('');
21
+ /** Extend a pnpm patch map without replacing unrelated patches or YAML comments. */
22
+ export function pnpmPatchPolicy(source, coordinate, patch) {
23
+ const document = parseDocument(source);
24
+ if (document.errors.length || !isMap(document.contents))
25
+ throw new Error('Invalid pnpm workspace YAML; preserve and review its patch configuration.');
26
+ let mapping = document.get('patchedDependencies', true);
27
+ if (mapping === undefined) {
28
+ document.set('patchedDependencies', document.createNode({}));
29
+ mapping = document.get('patchedDependencies', true);
53
30
  }
54
- return rows
55
- .filter((row) => {
56
- if (!row.trim() || row.trimStart().startsWith('#'))
57
- return true;
58
- const match = row.match(/^ (?:"([^"\\]+)"|'([^']+)'|([^\s:'"]+)):\s*(?:"[^"\\]+"|'[^']+'|[^\s{}[\]&*!|>]+)(?:\s+#.*)?\s*$/);
59
- if (!match)
60
- throw new Error('Unsupported patchedDependencies mapping');
61
- return !Object.hasOwn(patches, match[1] ?? match[2] ?? match[3]);
62
- })
63
- .filter((row, index, rows) => row || index < rows.length - 1)
64
- .map((row) => `${row}\n`)
65
- .join('');
31
+ if (!isMap(mapping))
32
+ throw new Error('patchedDependencies must be an explicit YAML mapping.');
33
+ const previous = mapping.get(coordinate);
34
+ if (previous !== undefined && previous !== patch)
35
+ throw new Error(`A different customer patch is already configured for ${coordinate}.`);
36
+ if (previous === patch)
37
+ return source;
38
+ mapping.set(coordinate, patch);
39
+ return document.toString({ lineWidth: 0 });
66
40
  }
@@ -0,0 +1,41 @@
1
+ import { z } from 'zod';
2
+ import type { Dashboard, DashboardTool, ToolArguments } from './catalog-model.js';
3
+ export type CatalogErrorCode = 'CATALOG_BUSY' | 'CATALOG_INVALID' | 'PROJECT_NOT_FOUND' | 'PROJECT_UNAVAILABLE' | 'INVALID_INPUT' | 'CATALOG_FAILURE';
4
+ export declare class CatalogError extends Error {
5
+ readonly code: CatalogErrorCode;
6
+ constructor(code: CatalogErrorCode);
7
+ }
8
+ export declare function catalogFailure(error: unknown): {
9
+ message: string;
10
+ nextAction: string;
11
+ code: CatalogErrorCode;
12
+ };
13
+ declare const entrySchema: z.ZodObject<{
14
+ id: z.ZodString;
15
+ root: z.ZodString;
16
+ name: z.ZodString;
17
+ updatedAt: z.ZodString;
18
+ sourceIdentity: z.ZodOptional<z.ZodString>;
19
+ }, z.core.$strict>;
20
+ export type ProjectEntry = z.infer<typeof entrySchema>;
21
+ export declare class ProjectStore {
22
+ readonly directory: string;
23
+ readonly file: string;
24
+ constructor(directory: string);
25
+ private read;
26
+ private write;
27
+ register(root: string, displayName?: string): string;
28
+ private mutate;
29
+ /** Explicit local operator recovery only; uncertain ownership never removes a lock. */
30
+ recoverCatalogLock(): {
31
+ recovered: boolean;
32
+ };
33
+ context(id: string): {
34
+ id: string;
35
+ name: string;
36
+ directory: string;
37
+ };
38
+ snapshot(selectedId?: string | null): Dashboard;
39
+ call(tool: DashboardTool, raw: ToolArguments): Dashboard;
40
+ }
41
+ export {};