@myrialabs/clopen 0.4.38 → 0.4.40

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 (177) hide show
  1. package/backend/auth/permissions.ts +48 -0
  2. package/backend/chat/stream-manager.ts +1 -1
  3. package/backend/database/crypto/secret-columns.ts +9 -1
  4. package/backend/database/migrations/075_create_deploy_bindings.ts +54 -0
  5. package/backend/database/migrations/076_remove_memory_code_graph.ts +229 -0
  6. package/backend/database/migrations/077_create_integration_db_links.ts +150 -0
  7. package/backend/database/migrations/078_create_worktree_branch_tables.ts +158 -0
  8. package/backend/database/migrations/index.ts +28 -0
  9. package/backend/database/queries/db-client-connection-queries.ts +19 -0
  10. package/backend/database/queries/deploy-queries.ts +124 -0
  11. package/backend/database/queries/graph-queries.ts +291 -247
  12. package/backend/database/queries/index.ts +10 -0
  13. package/backend/database/queries/integration-db-link-queries.ts +168 -0
  14. package/backend/database/queries/integration-queries.ts +34 -6
  15. package/backend/database/queries/worktree-branch-queries.ts +331 -0
  16. package/backend/db-client/cloning.test.ts +161 -0
  17. package/backend/db-client/cloning.ts +672 -0
  18. package/backend/db-client/connection-url.test.ts +117 -0
  19. package/backend/db-client/connection-url.ts +126 -0
  20. package/backend/db-client/drivers/mongodb.ts +2 -14
  21. package/backend/db-client/drivers/mysql.ts +2 -8
  22. package/backend/db-client/drivers/postgres.ts +10 -13
  23. package/backend/db-client/drivers/redis.ts +2 -6
  24. package/backend/db-client/env/detect.ts +438 -0
  25. package/backend/db-client/env/diff.ts +94 -0
  26. package/backend/db-client/env/env.test.ts +574 -0
  27. package/backend/db-client/env/index.ts +15 -0
  28. package/backend/db-client/env/naming.ts +202 -0
  29. package/backend/db-client/env/service.ts +487 -0
  30. package/backend/db-client/integrations/index.ts +44 -0
  31. package/backend/db-client/integrations/links.ts +564 -0
  32. package/backend/db-client/integrations/projector.test.ts +280 -0
  33. package/backend/db-client/integrations/projector.ts +256 -0
  34. package/backend/db-client/integrations/supabase-service.ts +266 -0
  35. package/backend/db-client/providers/neon/adapter.ts +522 -0
  36. package/backend/db-client/providers/neon/api-types.ts +182 -0
  37. package/backend/db-client/providers/neon/client.ts +298 -0
  38. package/backend/db-client/providers/neon/endpoints.test.ts +201 -0
  39. package/backend/db-client/providers/neon/endpoints.ts +314 -0
  40. package/backend/db-client/providers/neon/list.test.ts +181 -0
  41. package/backend/db-client/providers/registry.ts +27 -0
  42. package/backend/db-client/providers/supabase/adapter.ts +523 -0
  43. package/backend/db-client/providers/supabase/api-types.ts +92 -0
  44. package/backend/db-client/providers/supabase/apply-migration.ts +104 -0
  45. package/backend/db-client/providers/supabase/client.ts +259 -0
  46. package/backend/db-client/providers/supabase/features.ts +502 -0
  47. package/backend/db-client/providers/supabase/local.test.ts +78 -0
  48. package/backend/db-client/providers/supabase/local.ts +137 -0
  49. package/backend/db-client/providers/types.ts +194 -0
  50. package/backend/deployments/bindings.test.ts +43 -0
  51. package/backend/deployments/bindings.ts +216 -0
  52. package/backend/deployments/index.ts +53 -0
  53. package/backend/deployments/log-streams.ts +214 -0
  54. package/backend/deployments/prompts.ts +70 -0
  55. package/backend/deployments/providers/vercel/adapter.ts +757 -0
  56. package/backend/deployments/providers/vercel/build-logs.test.ts +80 -0
  57. package/backend/deployments/providers/vercel/build-logs.ts +211 -0
  58. package/backend/deployments/providers/vercel/client.ts +203 -0
  59. package/backend/deployments/providers/vercel/list.test.ts +624 -0
  60. package/backend/deployments/providers/vercel/normalise.test.ts +115 -0
  61. package/backend/deployments/providers/vercel/normalise.ts +113 -0
  62. package/backend/deployments/providers/vercel/types.ts +104 -0
  63. package/backend/deployments/registry.ts +27 -0
  64. package/backend/deployments/service.ts +458 -0
  65. package/backend/deployments/types.ts +278 -0
  66. package/backend/env-files/discovery.ts +48 -0
  67. package/backend/env-files/edit.ts +213 -0
  68. package/backend/env-files/env-files.test.ts +515 -0
  69. package/backend/env-files/git.ts +27 -0
  70. package/backend/env-files/index.ts +44 -0
  71. package/backend/env-files/keys.ts +69 -0
  72. package/backend/env-files/parse.ts +157 -0
  73. package/backend/env-files/write.ts +229 -0
  74. package/backend/index.ts +4 -0
  75. package/backend/integrations/health.ts +18 -4
  76. package/backend/integrations/projections/index.ts +0 -0
  77. package/backend/integrations/projections/mcp-projector.ts +7 -3
  78. package/backend/integrations/projections/types.ts +28 -9
  79. package/backend/integrations/registry/index.ts +8 -1
  80. package/backend/integrations/registry/providers/context7.ts +1 -0
  81. package/backend/integrations/registry/providers/firecrawl.ts +1 -0
  82. package/backend/integrations/registry/providers/github.ts +1 -0
  83. package/backend/integrations/registry/providers/neon.ts +55 -0
  84. package/backend/integrations/registry/providers/supabase.ts +62 -0
  85. package/backend/integrations/registry/providers/vercel.ts +47 -0
  86. package/backend/integrations/registry/types.ts +2 -0
  87. package/backend/mcp/internal/servers/memory-graph/description.ts +3 -3
  88. package/backend/mcp/internal/servers/memory-graph/runner.ts +4 -9
  89. package/backend/mcp/internal/servers/memory-graph/schema.ts +0 -4
  90. package/backend/memory/README.md +57 -34
  91. package/backend/memory/compose.test.ts +3 -3
  92. package/backend/memory/compose.ts +6 -9
  93. package/backend/memory/config.ts +0 -5
  94. package/backend/memory/consolidate.ts +1 -2
  95. package/backend/memory/context.test.ts +8 -54
  96. package/backend/memory/context.ts +19 -25
  97. package/backend/memory/extract/episodic.ts +10 -12
  98. package/backend/memory/extract/index.ts +23 -52
  99. package/backend/memory/extract/scheduler.ts +3 -6
  100. package/backend/memory/index.ts +6 -5
  101. package/backend/memory/invalidate.ts +36 -48
  102. package/backend/memory/layout.ts +319 -130
  103. package/backend/memory/retention.ts +12 -42
  104. package/backend/memory/retrieval.eval.test.ts +2 -2
  105. package/backend/memory/retrieval.test.ts +228 -183
  106. package/backend/memory/retrieval.ts +22 -21
  107. package/backend/memory/revise.test.ts +62 -116
  108. package/backend/memory/revise.ts +0 -1
  109. package/backend/memory/view.ts +8 -5
  110. package/backend/snapshot/helpers.ts +35 -41
  111. package/backend/snapshot/snapshot-service.ts +90 -0
  112. package/backend/snapshot/turn-changes.test.ts +163 -0
  113. package/backend/snapshot/turn-changes.ts +131 -0
  114. package/backend/work/start-work.ts +4 -0
  115. package/backend/worktrees/branching/engine.ts +557 -0
  116. package/backend/worktrees/branching/index.ts +56 -0
  117. package/backend/worktrees/branching/naming.test.ts +118 -0
  118. package/backend/worktrees/branching/naming.ts +97 -0
  119. package/backend/worktrees/branching/projector.test.ts +229 -0
  120. package/backend/worktrees/branching/projector.ts +139 -0
  121. package/backend/worktrees/branching/providers/neon.ts +220 -0
  122. package/backend/worktrees/branching/registry.ts +27 -0
  123. package/backend/worktrees/branching/service.ts +620 -0
  124. package/backend/worktrees/branching/suggest.test.ts +154 -0
  125. package/backend/worktrees/branching/suggest.ts +202 -0
  126. package/backend/worktrees/branching/types.ts +88 -0
  127. package/backend/worktrees/index.ts +7 -0
  128. package/backend/worktrees/service.ts +48 -1
  129. package/backend/ws/db-client/accounts.ts +225 -0
  130. package/backend/ws/db-client/connections.ts +34 -3
  131. package/backend/ws/db-client/context.ts +37 -0
  132. package/backend/ws/db-client/env.ts +142 -0
  133. package/backend/ws/db-client/index.ts +22 -1
  134. package/backend/ws/db-client/supabase.ts +188 -0
  135. package/backend/ws/deployments/actions.ts +360 -0
  136. package/backend/ws/deployments/context.ts +43 -0
  137. package/backend/ws/deployments/crud.ts +152 -0
  138. package/backend/ws/deployments/index.ts +15 -0
  139. package/backend/ws/deployments/schemas.ts +183 -0
  140. package/backend/ws/index.ts +6 -2
  141. package/backend/ws/memory/crud.ts +4 -16
  142. package/backend/ws/projects/index.ts +6 -1
  143. package/backend/ws/projects/info.ts +70 -6
  144. package/backend/ws/projects/overview.test.ts +108 -0
  145. package/backend/ws/projects/overview.ts +300 -0
  146. package/backend/ws/snapshot/changes.ts +279 -0
  147. package/backend/ws/snapshot/index.ts +4 -3
  148. package/backend/ws/system/device-info.ts +307 -76
  149. package/backend/ws/worktrees/branching.ts +212 -0
  150. package/backend/ws/worktrees/crud.ts +33 -7
  151. package/backend/ws/worktrees/index.ts +14 -0
  152. package/dist/assets/{index-DSHIANSy.js → index-D4igjF6e.js} +1 -1
  153. package/dist/assets/{index-CyH7fSbR.js → index-DONNwiXm.js} +1 -1
  154. package/dist/assets/main-BrfXH1bL.js +1205 -0
  155. package/dist/assets/main-CT1PygsW.css +1 -0
  156. package/dist/index.html +2 -2
  157. package/package.json +1 -1
  158. package/shared/constants/tool-icons.ts +13 -0
  159. package/shared/types/db-client/connection.ts +6 -0
  160. package/shared/types/db-client/env.ts +192 -0
  161. package/shared/types/db-client/index.ts +3 -0
  162. package/shared/types/db-client/integrations.ts +204 -0
  163. package/shared/types/db-client/supabase.ts +131 -0
  164. package/shared/types/deployments.ts +382 -0
  165. package/shared/types/integrations.ts +9 -0
  166. package/shared/types/memory.ts +34 -51
  167. package/shared/types/ui/components.ts +1 -1
  168. package/shared/types/worktree-branching.ts +315 -0
  169. package/shared/utils/diff-calculator.test.ts +89 -0
  170. package/shared/utils/diff-calculator.ts +30 -65
  171. package/shared/utils/logger.ts +2 -0
  172. package/backend/memory/extract/languages.ts +0 -176
  173. package/backend/memory/extract/structural.test.ts +0 -215
  174. package/backend/memory/extract/structural.ts +0 -364
  175. package/backend/ws/snapshot/content.ts +0 -85
  176. package/dist/assets/main-D2IOjftb.css +0 -1
  177. package/dist/assets/main-DM-tHKbW.js +0 -1152
@@ -0,0 +1,522 @@
1
+ /**
2
+ * Neon as a database provider.
3
+ *
4
+ * Four facts about Neon shape everything below, and all four were checked
5
+ * against the published OpenAPI document rather than assumed:
6
+ *
7
+ * 0. **`/projects` IS ORGANISATION-SCOPED.** The document calls it "a list of
8
+ * projects for the specified organization", and a personal key that omits
9
+ * `org_id` is refused with a 400. This was got WRONG first time — the
10
+ * adapter shipped sending no `org_id` at all, on the reading that a personal
11
+ * key answers with its user's projects — and every read path failed against
12
+ * a real key. `GET /users/me/organizations` is the fix and the only endpoint
13
+ * that answers for both key kinds: given an organisation- or project-scoped
14
+ * key, which is tied to no user, it returns the organisation that owns it.
15
+ * 1. **The password CAN be read back.** `GET /branches/{id}/roles/{role}/reveal_password`
16
+ * exists, and `/connection_uri` returns the password inline. So this adapter
17
+ * declares NO secret fields at all — linking a Neon project asks for
18
+ * nothing. That is the opposite of Supabase, whose `/database/password` is
19
+ * PATCH-only by design and forces a link to store one.
20
+ * 2. **A project's organisation arrives with the list.** `ProjectListItem`
21
+ * carries `org_name`, so naming which organisation will be billed costs no
22
+ * second request and no extra permission — where Supabase needed both.
23
+ * 3. **Organisations cannot be created through the API.** There is no
24
+ * `POST /organizations`, so `createGroup` is ABSENT rather than faked —
25
+ * the rule `Task 4` settled on for the Supabase organisation delete it
26
+ * could not offer.
27
+ *
28
+ * What DB Client links is a project's DEFAULT BRANCH. Neon has no
29
+ * `default_branch_id` on the project — the flag lives on the branch — so it is
30
+ * resolved at link time and stored on the link, the same split `resolveEndpoint`
31
+ * exists for everywhere else: asking the provider where something answers is a
32
+ * network call, and projecting a row is not.
33
+ */
34
+
35
+ import type {
36
+ DbProviderAdapter,
37
+ DbProviderContext,
38
+ DbProviderEndpoint,
39
+ DbProviderEnvHints
40
+ } from '../types';
41
+ import type {
42
+ DbProviderCreateOptions,
43
+ DbProviderInfo,
44
+ DbRemoteDatabase
45
+ } from '$shared/types/db-client';
46
+ import type { IntegrationStatus } from '$shared/types/integrations';
47
+ import type {
48
+ NeonApiCreatedProject,
49
+ NeonApiOrganization,
50
+ NeonApiOrganizationsResponse,
51
+ NeonApiProject,
52
+ NeonApiProjectsResponse,
53
+ NeonApiRegionsResponse
54
+ } from './api-types';
55
+ import {
56
+ isMissingOrgError,
57
+ isTransportError,
58
+ NEON_SLOW_TIMEOUT_MS,
59
+ NeonError,
60
+ neonRequest,
61
+ type NeonCredentials
62
+ } from './client';
63
+ import { defaultBranchOf, resolveBranchConnection } from './endpoints';
64
+ import { debug } from '$shared/utils/logger';
65
+
66
+ export const NEON_PROVIDER_ID = 'neon';
67
+
68
+ /** Connection modes, in the order the dialog offers them. */
69
+ export const NEON_MODES = {
70
+ direct: 'direct',
71
+ pooled: 'pooled'
72
+ } as const;
73
+
74
+ export function neonCredentialsOf(context: DbProviderContext): NeonCredentials {
75
+ const apiKey = (context.credentials.apiKey ?? '').trim();
76
+ if (!apiKey) {
77
+ throw new NeonError(
78
+ 'This Neon account has no API key. Reconnect it in Settings → Integrations.',
79
+ 401,
80
+ 'auth'
81
+ );
82
+ }
83
+ return { apiKey };
84
+ }
85
+
86
+ /**
87
+ * Organisations this key can act in.
88
+ *
89
+ * `GET /users/me/organizations` is the ONE endpoint that answers for both kinds
90
+ * of Neon key, and the document is explicit about why: called with an
91
+ * organisation- or project-scoped key, which is not tied to a user at all, it
92
+ * returns the single organisation that owns the key. Everything else that
93
+ * identifies a key is user-shaped and 4xxs for the scoped ones.
94
+ *
95
+ * Memoised briefly per key. `listNeonProjects` sits on the readiness poll's
96
+ * path, which runs every five seconds for up to three minutes, and without this
97
+ * each tick would cost two requests instead of one for an answer that cannot
98
+ * change without a visit to Neon's console. A minute bounds the staleness for
99
+ * the one case that does change it — being added to an organisation elsewhere.
100
+ */
101
+ const ORGANIZATION_TTL_MS = 60_000;
102
+ const organizationCache = new Map<string, { at: number; organizations: NeonApiOrganization[] }>();
103
+
104
+ export async function listNeonOrganizations(
105
+ credentials: NeonCredentials
106
+ ): Promise<NeonApiOrganization[]> {
107
+ const cached = organizationCache.get(credentials.apiKey);
108
+ if (cached && Date.now() - cached.at < ORGANIZATION_TTL_MS) return cached.organizations;
109
+
110
+ const response = await neonRequest<NeonApiOrganizationsResponse>(
111
+ credentials,
112
+ '/users/me/organizations'
113
+ );
114
+ const organizations = (response?.organizations ?? []).filter((entry) => entry?.id);
115
+ organizationCache.set(credentials.apiKey, { at: Date.now(), organizations });
116
+ return organizations;
117
+ }
118
+
119
+ async function projectsOf(
120
+ credentials: NeonCredentials,
121
+ orgId: string | undefined
122
+ ): Promise<NeonApiProject[]> {
123
+ const response = await neonRequest<NeonApiProjectsResponse>(credentials, '/projects', {
124
+ query: { limit: 400, org_id: orgId }
125
+ });
126
+ // A soft-deleted project sits in a recovery window and still appears. It
127
+ // cannot be connected to, and offering it would be offering a dead end.
128
+ return (response?.projects ?? []).filter((project) => !project.deleted_at);
129
+ }
130
+
131
+ /**
132
+ * Every project this key can reach, asked for ONE ORGANISATION AT A TIME.
133
+ *
134
+ * `/projects` is organisation-scoped — the document calls it "a list of projects
135
+ * for the specified organization" — and a personal key that omits `org_id` is
136
+ * refused outright with "org_id is required, you can find it on your
137
+ * organization settings page". A bare call is therefore not the general case;
138
+ * it is the legacy fallback for an account that reports no organisation at all.
139
+ *
140
+ * Fanning out over every organisation also fixes a quieter bug than the 400: a
141
+ * key belonging to two organisations would only ever have seen one of them.
142
+ *
143
+ * A partial failure is TOLERATED but never silent. Dropping one organisation's
144
+ * projects and rendering the rest as the whole list is the "an absent signal is
145
+ * not a negative one" mistake `Task 3` recorded twice; so the failures are
146
+ * logged, and when nothing at all came back the first error is rethrown rather
147
+ * than answering with an empty list the caller would read as "no projects".
148
+ */
149
+ export async function listNeonProjects(credentials: NeonCredentials): Promise<NeonApiProject[]> {
150
+ const organizations = await listNeonOrganizations(credentials);
151
+ const scopes: (string | undefined)[] =
152
+ organizations.length > 0 ? organizations.map((entry) => entry.id) : [undefined];
153
+
154
+ const failures: unknown[] = [];
155
+ const collected = new Map<string, NeonApiProject>();
156
+
157
+ const pages = await Promise.all(
158
+ scopes.map(async (orgId) => {
159
+ try {
160
+ return await projectsOf(credentials, orgId);
161
+ } catch (error) {
162
+ failures.push(error);
163
+ debug.warn('db-client', `Could not list Neon projects for org ${orgId ?? '(none)'}:`, error);
164
+ return [] as NeonApiProject[];
165
+ }
166
+ })
167
+ );
168
+
169
+ for (const page of pages) {
170
+ for (const project of page) collected.set(project.id, project);
171
+ }
172
+
173
+ if (collected.size === 0 && failures.length > 0) {
174
+ // Rewritten rather than repeated. Neon's own wording — "org_id is required,
175
+ // you can find it on your organization settings page" — describes a call
176
+ // the user cannot make and sends them to a page that cannot help, because
177
+ // by here it is OUR organisation lookup that came back empty. The same
178
+ // trick `Task 2` used on GitHub's 404 and `Task 4` on Supabase's 403: the
179
+ // provider's word for it is undiagnosable, so name the real cause.
180
+ if (isMissingOrgError(failures[0]) && organizations.length === 0) {
181
+ throw new NeonError(
182
+ 'This API key reaches no Neon organisation — create the key again from the account that owns your projects.',
183
+ 400,
184
+ 'config'
185
+ );
186
+ }
187
+ throw failures[0];
188
+ }
189
+ return [...collected.values()];
190
+ }
191
+
192
+ function detailOf(project: NeonApiProject): string {
193
+ const parts = [project.region_id];
194
+ if (project.pg_version) parts.push(`Postgres ${project.pg_version}`);
195
+ return parts.filter(Boolean).join(' · ');
196
+ }
197
+
198
+
199
+ function messageOf(error: unknown): string {
200
+ return error instanceof Error ? error.message : String(error);
201
+ }
202
+
203
+ /** How far back a project can have been created and still be the one we asked for. */
204
+ const RECONCILE_WINDOW_MS = 10 * 60 * 1000;
205
+
206
+ /**
207
+ * Find the project a dropped `POST /projects` may still have created.
208
+ *
209
+ * Matching is by NAME within a recent window, and the newest match wins. Neon
210
+ * allows duplicate project names, so this can in principle pick a project the
211
+ * user created themselves moments earlier — but the alternatives are worse in
212
+ * both directions: retrying the POST provisions and bills for a second real
213
+ * database, and reporting a failure abandons one that exists.
214
+ *
215
+ * The list itself is retried once by the client, since a GET is safe to repeat.
216
+ * Coming back empty means the create genuinely did not land, and that is
217
+ * reported as itself rather than as the socket error the user cannot act on.
218
+ */
219
+ async function findJustCreatedProject(
220
+ credentials: NeonCredentials,
221
+ input: { name: string; group: string },
222
+ cause: unknown
223
+ ): Promise<string> {
224
+ let projects: NeonApiProject[];
225
+ try {
226
+ projects = await listNeonProjects(credentials);
227
+ } catch {
228
+ throw new NeonError(
229
+ `${messageOf(cause)} Check the Neon console before trying again, in case the project was created.`,
230
+ 0,
231
+ 'error'
232
+ );
233
+ }
234
+
235
+ const cutoff = Date.now() - RECONCILE_WINDOW_MS;
236
+ const match = projects
237
+ .filter((project) => (project.name ?? '') === input.name)
238
+ .filter((project) => !input.group || project.org_id === input.group)
239
+ .filter((project) => {
240
+ const at = project.created_at ? Date.parse(project.created_at) : NaN;
241
+ return !Number.isFinite(at) || at >= cutoff;
242
+ })
243
+ .sort((a, b) => Date.parse(b.created_at ?? '') - Date.parse(a.created_at ?? ''))[0];
244
+
245
+ if (!match) {
246
+ throw new NeonError(
247
+ `${messageOf(cause)} Nothing was created, so try again.`,
248
+ 0,
249
+ 'error'
250
+ );
251
+ }
252
+
253
+ debug.log('db-client', `Reconciled the dropped Neon create onto project ${match.id}`);
254
+ return match.id;
255
+ }
256
+
257
+ export const neonDbAdapter: DbProviderAdapter = {
258
+ provider: NEON_PROVIDER_ID,
259
+ driver: 'postgres',
260
+
261
+ info(): DbProviderInfo {
262
+ return {
263
+ id: NEON_PROVIDER_ID,
264
+ name: 'Neon',
265
+ driver: 'postgres',
266
+ description: "Pick a Neon project. Its default branch becomes the connection — nothing to type, Neon hands the password back.",
267
+ // Direct is the silent default and pooled is the escape hatch, which is
268
+ // the reverse of Supabase and for a concrete reason: Neon's pooled
269
+ // endpoint runs PgBouncer in TRANSACTION mode, which breaks the prepared
270
+ // statements `Bun.sql` uses. Neon's direct host is reachable over IPv4,
271
+ // so the trade Supabase faced — pooler or unreachable — does not arise.
272
+ modes: [
273
+ {
274
+ id: NEON_MODES.direct,
275
+ label: 'Direct',
276
+ help: 'The right choice for this client.',
277
+ isDefault: true
278
+ },
279
+ {
280
+ id: NEON_MODES.pooled,
281
+ label: 'Pooled',
282
+ help: 'Transaction mode, which breaks prepared statements.',
283
+ isAdvanced: true
284
+ }
285
+ ],
286
+ // EMPTY, and that is the feature. Neon can reveal a role's password, so
287
+ // there is nothing for the user to fetch from a dashboard and paste.
288
+ secretFields: []
289
+ };
290
+ },
291
+
292
+ /**
293
+ * Neon's own snippet names the pair `DATABASE_URL` and
294
+ * `DATABASE_URL_UNPOOLED`, so that is the preset, and the unpooled half is
295
+ * the DIRECT endpoint — the one a migration has to run on, because Neon's
296
+ * pooler is PgBouncer in transaction mode.
297
+ */
298
+ envHints(): DbProviderEnvHints {
299
+ return {
300
+ urlPrefix: 'DATABASE',
301
+ altKeySuffix: '_UNPOOLED',
302
+ directMode: NEON_MODES.direct,
303
+ pooledModes: [NEON_MODES.pooled]
304
+ };
305
+ },
306
+
307
+ async listDatabases(context: DbProviderContext): Promise<DbRemoteDatabase[]> {
308
+ const credentials = neonCredentialsOf(context);
309
+ const [projects, organizations] = await Promise.all([
310
+ listNeonProjects(credentials),
311
+ // Already memoised, and already fetched by `listNeonProjects` itself —
312
+ // so naming the owner costs nothing.
313
+ listNeonOrganizations(credentials).catch(() => [] as NeonApiOrganization[])
314
+ ]);
315
+ const names = new Map(organizations.map((entry) => [entry.id, entry.name || entry.handle || entry.id]));
316
+
317
+ return projects.map((project) => ({
318
+ ref: project.id,
319
+ name: project.name || project.id,
320
+ detail: detailOf(project),
321
+ // The NAME of the organisation, or nothing. An earlier version fell back
322
+ // to the literal word "Organisation", which rendered on every row and
323
+ // made two projects in different organisations indistinguishable — the
324
+ // exact question this field exists to answer.
325
+ group: project.org_name ?? (project.org_id ? names.get(project.org_id) ?? null : null),
326
+ status: null,
327
+ // A Neon project has no state of its own — its branches do, and a
328
+ // suspended compute wakes on connection. So every listed project is
329
+ // connectable, and claiming otherwise would disable rows that work.
330
+ isReady: true,
331
+ isLinked: false
332
+ }));
333
+ },
334
+
335
+ async resolveEndpoint(
336
+ context: DbProviderContext,
337
+ target: { remoteRef: string; mode: string }
338
+ ): Promise<DbProviderEndpoint> {
339
+ const credentials = neonCredentialsOf(context);
340
+ const branch = await defaultBranchOf(credentials, target.remoteRef);
341
+ const connection = await resolveBranchConnection(credentials, {
342
+ projectId: target.remoteRef,
343
+ branchId: branch.id,
344
+ pooled: target.mode === NEON_MODES.pooled
345
+ });
346
+
347
+ return {
348
+ host: connection.host,
349
+ port: connection.port,
350
+ username: connection.username,
351
+ database: connection.database,
352
+ sslMode: connection.sslMode,
353
+ options: {
354
+ neon: {
355
+ projectId: target.remoteRef,
356
+ branchId: branch.id,
357
+ mode: target.mode
358
+ }
359
+ },
360
+ /**
361
+ * The password, resolved rather than asked for.
362
+ *
363
+ * This is the whole reason `secretFields` is empty: Neon reveals a
364
+ * role's password, so the one awkward step of linking a managed Postgres
365
+ * — finding a password in a dashboard and pasting it — does not exist
366
+ * here. `links.ts` PEELS this off before storing the endpoint, because
367
+ * an endpoint lives in `config_json` and that column is not sealed.
368
+ */
369
+ secrets: { password: connection.password }
370
+ };
371
+ },
372
+
373
+ async createOptions(context: DbProviderContext): Promise<DbProviderCreateOptions> {
374
+ const credentials = neonCredentialsOf(context);
375
+
376
+ // The SAME organisation read every other call here makes, so the answer is
377
+ // already memoised and the two views cannot disagree about what this key
378
+ // can reach. Both are tolerated failing: a form that refuses to render
379
+ // because the region list timed out removes a capability that works.
380
+ const [organizations, regions] = await Promise.all([
381
+ listNeonOrganizations(credentials).catch((error) => {
382
+ debug.warn('db-client', 'Could not list Neon organizations:', error);
383
+ return [] as NeonApiOrganization[];
384
+ }),
385
+ neonRequest<NeonApiRegionsResponse>(credentials, '/regions').catch((error) => {
386
+ debug.warn('db-client', 'Could not list Neon regions:', error);
387
+ return null;
388
+ })
389
+ ]);
390
+
391
+ const groups = organizations.map((organization) => ({
392
+ value: organization.id,
393
+ label: organization.name || organization.handle || organization.id,
394
+ detail: organization.plan ?? null
395
+ }));
396
+
397
+ // NO synthetic "personal account" entry. An earlier version offered one
398
+ // with an empty `org_id`, on the reading that a personal key creates
399
+ // projects under its user — but `/projects` is organisation-scoped, and a
400
+ // project created without an owner is one this adapter then cannot list.
401
+ // Neon reports a personal account as an organisation of its own, so the
402
+ // real entry is always in the list above when there is one at all.
403
+ //
404
+ // The empty case is left empty on purpose rather than back-filled with a
405
+ // placeholder: `emptyGroupsNotice` is shown instead of the form, which is
406
+ // the honest outcome for a key that can reach nowhere to create anything.
407
+
408
+ // Live, not hard-coded. `GET /regions` is a documented, non-beta endpoint
409
+ // that needs no organisation — the three things that forced `Task 4` to
410
+ // hard-code Supabase's list are all absent here.
411
+ const regionList = (regions?.regions ?? [])
412
+ .filter((region) => region?.region_id)
413
+ .map((region) => ({ value: region.region_id, label: region.name || region.region_id }));
414
+
415
+ return {
416
+ groupLabel: 'Organisation',
417
+ groups,
418
+ regionLabel: 'Region',
419
+ regions: regionList.length > 0
420
+ ? regionList
421
+ : [{ value: 'aws-us-east-2', label: 'AWS US East (Ohio)' }],
422
+ notice:
423
+ "This provisions a real Postgres project on Neon. It counts against the owner's project quota and its plan decides what it costs.",
424
+ // Reachable, and one sentence with one instruction: a key that reports
425
+ // no organisation cannot create a project anywhere, and the only fix is
426
+ // a different key.
427
+ emptyGroupsNotice:
428
+ 'This API key reaches no organisation — create the key again from the Neon account that owns your projects.',
429
+ canCreateGroup: false,
430
+ createGroupNotice: '',
431
+ // Neon has no organisation endpoints at all — no POST, no PATCH, no
432
+ // DELETE — so all three buttons are absent rather than faked, and this
433
+ // says so once instead of leaving three holes to interpret.
434
+ groupManagementNotice: "Organisations are created and managed in Neon's console."
435
+ };
436
+ },
437
+
438
+ async createDatabase(
439
+ context: DbProviderContext,
440
+ input: { name: string; group: string; region: string }
441
+ ): Promise<{ ref: string; secrets: Record<string, string> }> {
442
+ const credentials = neonCredentialsOf(context);
443
+
444
+ let created: NeonApiCreatedProject | null;
445
+ try {
446
+ created = await neonRequest<NeonApiCreatedProject>(credentials, '/projects', {
447
+ method: 'POST',
448
+ body: {
449
+ project: {
450
+ name: input.name,
451
+ region_id: input.region,
452
+ // Sending an empty string would ask Neon to create the project
453
+ // inside an organisation called "". The form no longer offers a
454
+ // blank owner, so this guard is the backstop rather than the path.
455
+ ...(input.group ? { org_id: input.group } : {})
456
+ }
457
+ },
458
+ timeoutMs: NEON_SLOW_TIMEOUT_MS
459
+ });
460
+ } catch (error) {
461
+ // A DROPPED CONNECTION is not a failed create. Provisioning takes long
462
+ // enough that the socket closes while Neon is still working, and the
463
+ // project appears anyway — so retrying the POST would bill for a second
464
+ // one, and reporting a failure would leave a real database nobody
465
+ // linked. Ask what actually exists instead.
466
+ if (!isTransportError(error)) throw error;
467
+ debug.warn('db-client', `Neon create dropped the connection, reconciling: ${messageOf(error)}`);
468
+ return { ref: await findJustCreatedProject(credentials, input, error), secrets: {} };
469
+ }
470
+
471
+ const ref = created?.project?.id;
472
+ if (!ref) {
473
+ throw new NeonError(
474
+ 'Neon accepted the project but did not report its id, so it cannot be linked automatically. It will be in the list once it finishes provisioning.',
475
+ 502,
476
+ 'error'
477
+ );
478
+ }
479
+ // No secret to carry. Neon reveals the password on demand, so a link holds
480
+ // nothing and `resolveEndpoint` fetches it — which also means a password
481
+ // reset at Neon is picked up by re-resolving rather than by re-typing.
482
+ return { ref, secrets: {} };
483
+ },
484
+
485
+ async deleteDatabase(context: DbProviderContext, remoteRef: string): Promise<void> {
486
+ await neonRequest(
487
+ neonCredentialsOf(context),
488
+ `/projects/${encodeURIComponent(remoteRef)}`,
489
+ { method: 'DELETE', timeoutMs: NEON_SLOW_TIMEOUT_MS }
490
+ );
491
+ },
492
+
493
+ async renameDatabase(context: DbProviderContext, remoteRef: string, name: string): Promise<void> {
494
+ await neonRequest(
495
+ neonCredentialsOf(context),
496
+ `/projects/${encodeURIComponent(remoteRef)}`,
497
+ { method: 'PATCH', body: { project: { name } } }
498
+ );
499
+ },
500
+
501
+ async probe(context: DbProviderContext): Promise<{ status: IntegrationStatus; detail: string | null }> {
502
+ try {
503
+ const projects = await listNeonProjects(neonCredentialsOf(context));
504
+ if (projects.length === 0) {
505
+ return {
506
+ status: 'needs_config',
507
+ detail: 'The key works but reaches no projects — check which Neon account or organisation it belongs to.'
508
+ };
509
+ }
510
+ const plural = projects.length === 1 ? 'project' : 'projects';
511
+ return { status: 'ok', detail: `${projects.length} ${plural} reachable` };
512
+ } catch (error) {
513
+ if (error instanceof NeonError) {
514
+ const status: IntegrationStatus = error.kind === 'auth'
515
+ ? 'needs_auth'
516
+ : error.kind === 'config' || error.kind === 'quota' ? 'needs_config' : 'error';
517
+ return { status, detail: error.message };
518
+ }
519
+ return { status: 'error', detail: error instanceof Error ? error.message : String(error) };
520
+ }
521
+ }
522
+ };
@@ -0,0 +1,182 @@
1
+ /**
2
+ * The parts of Neon's API shapes this codebase reads.
3
+ *
4
+ * Transcribed from the published OpenAPI document, and deliberately NOT
5
+ * complete: a `Branch` there carries thirty fields, most of them billing
6
+ * counters. Only what is actually read is declared, so a field appearing here
7
+ * is evidence something depends on it.
8
+ *
9
+ * Everything optional is optional HERE even when the document marks it
10
+ * required, with two exceptions kept required because nothing can proceed
11
+ * without them (`id` on a project, `id`/`name` on a branch). A response that
12
+ * omits a "required" field is a real possibility across API versions, and a
13
+ * type that promises otherwise turns it into a `TypeError` inside a list
14
+ * render rather than a handled absence.
15
+ */
16
+
17
+ /** `GET /projects` → `{ projects: [...] }`, and `GET /projects/{id}` → `{ project }`. */
18
+ export interface NeonApiProject {
19
+ id: string;
20
+ name?: string;
21
+ region_id?: string;
22
+ pg_version?: number;
23
+ /** Present on projects owned by an organisation rather than by a user. */
24
+ org_id?: string;
25
+ /**
26
+ * The organisation's display name, carried on the LIST ITEM itself.
27
+ *
28
+ * Worth noting because it makes Neon cheaper to list than Supabase: there,
29
+ * naming the organisation of each project needs a second endpoint and a
30
+ * permission the token may not have. Here it arrives with the list.
31
+ */
32
+ org_name?: string;
33
+ created_at?: string;
34
+ /** False when the project was created with password storage disabled. */
35
+ store_passwords?: boolean;
36
+ /** Set on a soft-deleted project inside its recovery window. */
37
+ deleted_at?: string | null;
38
+ }
39
+
40
+ export interface NeonApiProjectsResponse {
41
+ projects?: NeonApiProject[];
42
+ }
43
+
44
+ export interface NeonApiProjectResponse {
45
+ project?: NeonApiProject;
46
+ }
47
+
48
+ /**
49
+ * `current_state` is a free-form string in the document, not an enum, so it is
50
+ * typed as one. `ready` is the only value that means connectable — `init` and
51
+ * `resetting` refuse queries, and `archived` answers them very slowly.
52
+ */
53
+ export interface NeonApiBranch {
54
+ id: string;
55
+ name: string;
56
+ project_id?: string;
57
+ parent_id?: string;
58
+ current_state?: string;
59
+ /** The project's default branch. Never ours, and never offered for deletion. */
60
+ default?: boolean;
61
+ /** A protected branch cannot be deleted, which is worth saying before trying. */
62
+ protected?: boolean;
63
+ logical_size?: number;
64
+ created_at?: string;
65
+ }
66
+
67
+ export interface NeonApiBranchesResponse {
68
+ branches?: NeonApiBranch[];
69
+ }
70
+
71
+ /** The discrete half of a connection URI, which is what the projector needs. */
72
+ export interface NeonApiConnectionParameters {
73
+ database?: string;
74
+ password?: string;
75
+ role?: string;
76
+ host?: string;
77
+ /**
78
+ * The pooled host, carried ALONGSIDE the direct one.
79
+ *
80
+ * This is why asking for a pooled endpoint costs no extra request: both
81
+ * hosts arrive together, so the mode is a choice about which field to read
82
+ * rather than a second round trip.
83
+ */
84
+ pooler_host?: string;
85
+ }
86
+
87
+ /**
88
+ * One entry of a `connection_uris[]` array — Neon's `ConnectionDetails`.
89
+ *
90
+ * NOT what `GET /connection_uri` answers with. That endpoint returns
91
+ * `NeonApiConnectionUriResponse` below, a bare `{ uri }`, and reading one as
92
+ * the other leaves every discrete field undefined — which is how linking a
93
+ * project failed with "Neon did not report a host". The two are declared
94
+ * separately here so the next reader cannot repeat it.
95
+ */
96
+ export interface NeonApiConnectionUri {
97
+ connection_uri?: string;
98
+ connection_parameters?: NeonApiConnectionParameters;
99
+ }
100
+
101
+ /**
102
+ * What `GET /projects/{id}/connection_uri` answers with — `ConnectionURIResponse`.
103
+ *
104
+ * One string. The document marks `uri` as the only property and the only
105
+ * required one, so there is no host, role or database field to read: the parts
106
+ * come from parsing it.
107
+ */
108
+ export interface NeonApiConnectionUriResponse {
109
+ uri?: string;
110
+ }
111
+
112
+ /**
113
+ * What `POST /projects/{id}/branches` answers with.
114
+ *
115
+ * `connection_uris` IS OPTIONAL, and that is the single most important fact in
116
+ * this file. The document states it plainly: a branch cut from a parent with
117
+ * more than one role or database comes back without one. Treating it as
118
+ * guaranteed would work on every simple project and fail on exactly the
119
+ * established ones this feature is most useful for.
120
+ */
121
+ export interface NeonApiCreatedBranch {
122
+ branch?: NeonApiBranch;
123
+ endpoints?: NeonApiEndpoint[];
124
+ roles?: NeonApiRole[];
125
+ databases?: NeonApiDatabase[];
126
+ connection_uris?: NeonApiConnectionUri[];
127
+ }
128
+
129
+ export interface NeonApiEndpoint {
130
+ id?: string;
131
+ host?: string;
132
+ branch_id?: string;
133
+ type?: string;
134
+ current_state?: string;
135
+ }
136
+
137
+ export interface NeonApiRole {
138
+ name?: string;
139
+ branch_id?: string;
140
+ /** Only present when the project stores passwords; read back separately if not. */
141
+ password?: string;
142
+ protected?: boolean;
143
+ }
144
+
145
+ export interface NeonApiDatabase {
146
+ name?: string;
147
+ branch_id?: string;
148
+ owner_name?: string;
149
+ }
150
+
151
+ export interface NeonApiRolePassword {
152
+ password?: string;
153
+ }
154
+
155
+ export interface NeonApiOrganization {
156
+ id: string;
157
+ name?: string;
158
+ handle?: string;
159
+ plan?: string;
160
+ }
161
+
162
+ export interface NeonApiOrganizationsResponse {
163
+ organizations?: NeonApiOrganization[];
164
+ }
165
+
166
+ export interface NeonApiRegion {
167
+ region_id: string;
168
+ name?: string;
169
+ default?: boolean;
170
+ }
171
+
172
+ export interface NeonApiRegionsResponse {
173
+ regions?: NeonApiRegion[];
174
+ }
175
+
176
+ /** `POST /projects` answers with the project plus its first connection URI. */
177
+ export interface NeonApiCreatedProject {
178
+ project?: NeonApiProject;
179
+ connection_uris?: NeonApiConnectionUri[];
180
+ roles?: NeonApiRole[];
181
+ databases?: NeonApiDatabase[];
182
+ }