@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,298 @@
1
+ /**
2
+ * A small Neon API client — the vendor's home in this codebase.
3
+ *
4
+ * No SDK, for the reason the Supabase, Vercel and GitHub clients have none:
5
+ * this is a handful of plain JSON calls, and an SDK would add a dependency tree
6
+ * we then have to keep Bun-compatible for no capability we use.
7
+ *
8
+ * NEON SERVES TWO SURFACES from one credential — DB Client (`database`) and the
9
+ * worktree manager (`worktree-branching`) — so this module lives here, with the
10
+ * database adapter, and `backend/worktrees/branching/providers/neon.ts` imports
11
+ * it rather than opening a second one. Two clients would mean two independent
12
+ * views of the same account's rate budget and two places to fix a 403, which is
13
+ * exactly the duplication the account layer exists to prevent.
14
+ *
15
+ * Every path below was read out of the published OpenAPI document at
16
+ * `https://dfv3qgd2ykmrx.cloudfront.net/api_spec/release/v2.json` rather than
17
+ * inferred from a sibling. Four things there are worth knowing before changing
18
+ * anything:
19
+ *
20
+ * - `POST /projects/{id}/branches` returns `connection_uris` OPTIONALLY. The
21
+ * document is explicit: "When creating a branch from a parent with more than
22
+ * one role or database, the response body does not include a connection
23
+ * URI." So the create path must fall back to `GET /connection_uri`, which is
24
+ * not an optimisation but a correctness requirement.
25
+ * - A branch created WITHOUT `endpoints` has no compute at all and refuses
26
+ * every connection. `endpoints: [{ type: 'read_write' }]` is mandatory here.
27
+ * - `GET /projects/{id}/branches/{bid}/roles/{role}/reveal_password` exists.
28
+ * Neon hands the password back, which is why linking a Neon database asks
29
+ * for no secret at all — the opposite of Supabase, whose
30
+ * `/database/password` is PATCH-only by design.
31
+ * - `expires_at` / branch TTL is EARLY ACCESS ONLY. It would be the perfect
32
+ * safety net for a leaked branch and it is deliberately unused: sending it
33
+ * would fail for every account outside that programme, so orphan detection
34
+ * is Clopen's own job (see `backend/worktrees/branching/service.ts`).
35
+ *
36
+ * There is NO `POST /organizations`. Neon organisations cannot be created
37
+ * through the API at all, so this adapter offers no `createGroup` — absent
38
+ * rather than faked, the rule `Task 4` settled on for Supabase organisations.
39
+ */
40
+
41
+ const NEON_API_BASE = 'https://console.neon.tech/api/v2';
42
+
43
+ /**
44
+ * Two budgets, the same split the Supabase and Vercel clients settled on. A
45
+ * read answers quickly; provisioning a project does not, and aborting it
46
+ * mid-flight reports a timeout for work the server completed.
47
+ */
48
+ const READ_TIMEOUT_MS = 20_000;
49
+ const SLOW_TIMEOUT_MS = 120_000;
50
+
51
+ export class NeonError extends Error {
52
+ constructor(
53
+ message: string,
54
+ readonly status: number,
55
+ readonly kind: 'auth' | 'config' | 'quota' | 'rate-limit' | 'error'
56
+ ) {
57
+ super(message);
58
+ this.name = 'NeonError';
59
+ }
60
+ }
61
+
62
+ export interface NeonCredentials {
63
+ apiKey: string;
64
+ }
65
+
66
+ /** Which permission or plan limit a refusal on a given path most likely means. */
67
+ function refusalHint(path: string, method: string): string | null {
68
+ if (method === 'POST' && path.endsWith('/branches')) {
69
+ return "Neon caps how many branches a project may have, and the cap is part of the plan. Delete a branch you no longer need, or check the project's branch limit.";
70
+ }
71
+ if (method === 'POST' && path === '/projects') {
72
+ return 'Neon caps how many projects an account may have. Delete one you no longer need, or pick an organisation with room.';
73
+ }
74
+ if (path.startsWith('/organizations/')) {
75
+ return 'An organisation-scoped API key only reaches its own organisation — check which one this key was created in.';
76
+ }
77
+ return null;
78
+ }
79
+
80
+ /**
81
+ * Whether a message is Neon's "you did not say which organisation".
82
+ *
83
+ * `/projects` is organisation-scoped and refuses a call that omits `org_id`.
84
+ * The adapter now always supplies one, so reaching this means the organisation
85
+ * lookup itself came back empty — which is a different problem from the one
86
+ * Neon's own wording describes, and pointing the user at their organisation
87
+ * settings page would send them somewhere that cannot help.
88
+ */
89
+ export function isMissingOrgError(error: unknown): boolean {
90
+ return error instanceof NeonError && /org_id is required/i.test(error.message);
91
+ }
92
+
93
+ /**
94
+ * Map a failed response onto something the hub and the manager can act on.
95
+ *
96
+ * Neon's own message is kept: it is the most specific thing anyone will see.
97
+ * The classification is ours, because the hub's status strip understands four
98
+ * states and no more.
99
+ */
100
+ async function toError(
101
+ response: Response,
102
+ context: { path: string; method: string }
103
+ ): Promise<NeonError> {
104
+ let message = response.statusText || `HTTP ${response.status}`;
105
+ try {
106
+ const body = await response.json() as { message?: unknown; error?: unknown; code?: unknown };
107
+ for (const candidate of [body.message, body.error]) {
108
+ if (typeof candidate === 'string' && candidate.trim()) {
109
+ message = candidate;
110
+ break;
111
+ }
112
+ }
113
+ } catch {
114
+ // Non-JSON body — the status line is all we have.
115
+ }
116
+
117
+ // A 400 here is Neon telling us a required parameter is missing or wrong —
118
+ // `org_id` on `/projects` is the one that actually happened. That is a
119
+ // CONFIGURATION problem, not a transient failure, so it must not land in the
120
+ // hub's status strip as a red "error" with no guidance: `needs_config` is
121
+ // what tells the user there is something to fix rather than to retry.
122
+ if (response.status === 400) {
123
+ return new NeonError(message, 400, 'config');
124
+ }
125
+ if (response.status === 401) {
126
+ return new NeonError(
127
+ `${message}. The API key is invalid or was revoked — create a new one at console.neon.tech/app/settings/api-keys.`,
128
+ 401,
129
+ 'auth'
130
+ );
131
+ }
132
+ if (response.status === 403) {
133
+ const hint = refusalHint(context.path, context.method);
134
+ return new NeonError(
135
+ `${message}.${hint ? ` ${hint}` : ' This key does not have access here.'}`,
136
+ 403,
137
+ 'config'
138
+ );
139
+ }
140
+ if (response.status === 404) {
141
+ return new NeonError(`${message}. It does not exist, or this key cannot see it.`, 404, 'config');
142
+ }
143
+ // 422 is what Neon answers when a limit is reached — a branch cap, a project
144
+ // cap — and it is a different problem from a permission, so it gets its own
145
+ // kind rather than being flattened into "config".
146
+ if (response.status === 422) {
147
+ const hint = refusalHint(context.path, context.method);
148
+ return new NeonError(`${message}.${hint ? ` ${hint}` : ''}`, 422, 'quota');
149
+ }
150
+ if (response.status === 429) {
151
+ return new NeonError('Neon rate limit reached. Try again shortly.', 429, 'rate-limit');
152
+ }
153
+ return new NeonError(message, response.status, 'error');
154
+ }
155
+
156
+ /**
157
+ * What Neon says about how much budget is left.
158
+ *
159
+ * Read defensively and reported as ABSENT when the headers are not there. Neon
160
+ * documents rate limits but not the headers that carry them, so unlike the
161
+ * Supabase client — where every header name was confirmed against a live
162
+ * account — nothing here is asserted. Absent means NOT REPORTED, never zero: a
163
+ * footer that invents a quota is worse than one that shows none.
164
+ */
165
+ export interface NeonRateLimit {
166
+ remaining: number;
167
+ limit: number;
168
+ resetAt: string | null;
169
+ }
170
+
171
+ /**
172
+ * Last reading PER KEY, not per process.
173
+ *
174
+ * Neon counts per API key, so two connected accounts have two budgets and one
175
+ * global figure would attribute one account's usage to the other — the same
176
+ * reason the Supabase client keys on its token.
177
+ */
178
+ const rateLimits = new Map<string, NeonRateLimit>();
179
+
180
+ export function getNeonRateLimit(credentials: NeonCredentials): NeonRateLimit | null {
181
+ return rateLimits.get(credentials.apiKey) ?? null;
182
+ }
183
+
184
+ function readRateLimit(key: string, headers: Headers): void {
185
+ const remaining = headers.get('x-ratelimit-remaining') ?? headers.get('ratelimit-remaining');
186
+ const limit = headers.get('x-ratelimit-limit') ?? headers.get('ratelimit-limit');
187
+ if (remaining === null || limit === null) return;
188
+
189
+ const remainingValue = Number(remaining);
190
+ const limitValue = Number(limit);
191
+ if (!Number.isFinite(remainingValue) || !Number.isFinite(limitValue)) return;
192
+
193
+ const reset = headers.get('x-ratelimit-reset') ?? headers.get('ratelimit-reset');
194
+ const resetValue = reset === null ? NaN : Number(reset);
195
+ // Read as a DURATION in seconds, the interpretation that is safe when it is
196
+ // wrong: a duration misread as an epoch dates the reset to 1970, which is the
197
+ // bug the Supabase footer shipped with. An epoch misread as a duration only
198
+ // pushes the label further into the future, which reads as "not soon".
199
+ rateLimits.set(key, {
200
+ remaining: remainingValue,
201
+ limit: limitValue,
202
+ resetAt: Number.isFinite(resetValue) ? new Date(Date.now() + resetValue * 1000).toISOString() : null
203
+ });
204
+ }
205
+
206
+ export interface NeonRequestOptions {
207
+ method?: 'GET' | 'POST' | 'PATCH' | 'DELETE';
208
+ body?: unknown;
209
+ query?: Record<string, string | number | boolean | undefined | null>;
210
+ timeoutMs?: number;
211
+ /**
212
+ * Try once more when the CONNECTION failed rather than the request.
213
+ *
214
+ * Defaults to true for GET and false for everything else, and the default is
215
+ * the whole point: a dropped socket says nothing about whether the server
216
+ * acted. Re-reading is free; re-sending a `POST /projects` would provision a
217
+ * second real database and bill for it.
218
+ */
219
+ retryOnTransport?: boolean;
220
+ }
221
+
222
+ /** True for a failure that happened before Neon answered at all. */
223
+ export function isTransportError(error: unknown): boolean {
224
+ return error instanceof NeonError && error.status === 0;
225
+ }
226
+
227
+ /**
228
+ * A network failure, said once and without the runtime's debugging aside.
229
+ *
230
+ * Bun appends "For more information, pass `verbose: true` in the second
231
+ * argument to fetch()" to a closed socket, which reached the user inside a
232
+ * dialog about creating a database and told them to edit Clopen's source.
233
+ */
234
+ function transportMessage(error: unknown): string {
235
+ const raw = error instanceof Error ? error.message : String(error);
236
+ const cleaned = raw.replace(/\s*For more information, pass[\s\S]*$/i, '').trim();
237
+ if (/timed? out|timeout|abort/i.test(cleaned)) {
238
+ return 'Neon did not answer in time — check the dashboard before trying again, in case it went through.';
239
+ }
240
+ return `Could not reach Neon: ${cleaned || 'the connection was closed'}.`;
241
+ }
242
+
243
+ function buildUrl(path: string, query?: NeonRequestOptions['query']): string {
244
+ const url = new URL(`${NEON_API_BASE}${path}`);
245
+ for (const [key, value] of Object.entries(query ?? {})) {
246
+ if (value === undefined || value === null || value === '') continue;
247
+ url.searchParams.set(key, String(value));
248
+ }
249
+ return url.toString();
250
+ }
251
+
252
+ export async function neonRequest<T>(
253
+ credentials: NeonCredentials,
254
+ path: string,
255
+ options: NeonRequestOptions = {}
256
+ ): Promise<T> {
257
+ const method = options.method ?? 'GET';
258
+ const headers: Record<string, string> = {
259
+ Authorization: `Bearer ${credentials.apiKey}`,
260
+ Accept: 'application/json',
261
+ 'User-Agent': 'clopen'
262
+ };
263
+ if (options.body !== undefined) headers['Content-Type'] = 'application/json';
264
+
265
+ const url = buildUrl(path, options.query);
266
+ const send = (): Promise<Response> =>
267
+ fetch(url, {
268
+ method,
269
+ headers,
270
+ ...(options.body !== undefined && { body: JSON.stringify(options.body) }),
271
+ signal: AbortSignal.timeout(options.timeoutMs ?? READ_TIMEOUT_MS)
272
+ });
273
+
274
+ const mayRetry = options.retryOnTransport ?? method === 'GET';
275
+
276
+ let response: Response;
277
+ try {
278
+ response = await send();
279
+ } catch (first) {
280
+ if (!mayRetry) throw new NeonError(transportMessage(first), 0, 'error');
281
+ try {
282
+ response = await send();
283
+ } catch (second) {
284
+ throw new NeonError(transportMessage(second), 0, 'error');
285
+ }
286
+ }
287
+
288
+ // Read before the status check: a 429 is precisely when the remaining count
289
+ // is worth knowing.
290
+ readRateLimit(credentials.apiKey, response.headers);
291
+ if (!response.ok) throw await toError(response, { path, method });
292
+
293
+ const text = await response.text();
294
+ return (text ? JSON.parse(text) : null) as T;
295
+ }
296
+
297
+ /** The budget for calls that do real work upstream — provisioning a project. */
298
+ export const NEON_SLOW_TIMEOUT_MS = SLOW_TIMEOUT_MS;
@@ -0,0 +1,201 @@
1
+ /**
2
+ * Resolving where a Neon branch answers.
3
+ *
4
+ * This file exists because two response shapes were conflated. Neon has both:
5
+ *
6
+ * ConnectionDetails `{ connection_uri, connection_parameters }` — inside
7
+ * the `connection_uris[]` array of a CREATE response
8
+ * ConnectionURIResponse `{ uri }` — what
9
+ * `GET /connection_uri` answers with, and nothing else
10
+ *
11
+ * Reading the second as though it were the first leaves every discrete field
12
+ * undefined, so linking any project failed with "Neon did not report a host for
13
+ * branch …". The tests below pin both shapes and the choice between them.
14
+ */
15
+
16
+ import { describe, it, expect, afterEach } from 'bun:test';
17
+
18
+ import {
19
+ connectionFromCreateResponse,
20
+ parseConnectionUri,
21
+ resolveBranchConnection
22
+ } from './endpoints';
23
+
24
+ const realFetch = globalThis.fetch;
25
+ afterEach(() => {
26
+ globalThis.fetch = realFetch;
27
+ });
28
+
29
+ const DIRECT_HOST = 'ep-morning-scene-a1b2c3.ap-southeast-1.aws.neon.tech';
30
+ const POOLER_HOST = 'ep-morning-scene-a1b2c3-pooler.ap-southeast-1.aws.neon.tech';
31
+ const DIRECT_URI = `postgresql://neondb_owner:npg_secret@${DIRECT_HOST}/neondb?sslmode=require`;
32
+ const POOLED_URI = `postgresql://neondb_owner:npg_secret@${POOLER_HOST}/neondb?sslmode=require`;
33
+
34
+ function json(body: unknown, status = 200): Response {
35
+ return new Response(JSON.stringify(body), {
36
+ status,
37
+ headers: { 'content-type': 'application/json' }
38
+ });
39
+ }
40
+
41
+ describe('parseConnectionUri', () => {
42
+ it('reads every part back out of the bare string', () => {
43
+ const parsed = parseConnectionUri(DIRECT_URI);
44
+
45
+ expect(parsed).not.toBeNull();
46
+ expect(parsed!.host).toBe(DIRECT_HOST);
47
+ expect(parsed!.port).toBe(5432);
48
+ expect(parsed!.username).toBe('neondb_owner');
49
+ expect(parsed!.password).toBe('npg_secret');
50
+ expect(parsed!.database).toBe('neondb');
51
+ expect(parsed!.sslMode).toBe('require');
52
+ });
53
+
54
+ it('keeps the URI verbatim, since Neon already applied the mode we asked for', () => {
55
+ // Rebuilding would drop options Neon chose to include and could disagree
56
+ // with the discrete fields; both come from this one string instead.
57
+ const withOptions = `${DIRECT_URI}&channel_binding=require`;
58
+ expect(parseConnectionUri(withOptions)!.uri).toBe(withOptions);
59
+ });
60
+
61
+ it('decodes an escaped password rather than storing the escaping', () => {
62
+ const parsed = parseConnectionUri(
63
+ `postgresql://user%40x:p%40ss%2Fword@${DIRECT_HOST}/db?sslmode=require`
64
+ );
65
+ expect(parsed!.username).toBe('user@x');
66
+ expect(parsed!.password).toBe('p@ss/word');
67
+ });
68
+
69
+ it('answers null for a URI that cannot log in', () => {
70
+ // Reported as unresolved rather than passed on: a connection with no
71
+ // password fails much later, inside a driver, saying "authentication
72
+ // failed" instead of naming the real problem.
73
+ expect(parseConnectionUri(`postgresql://neondb_owner@${DIRECT_HOST}/neondb`)).toBeNull();
74
+ expect(parseConnectionUri('not a uri')).toBeNull();
75
+ });
76
+ });
77
+
78
+ describe('connectionFromCreateResponse', () => {
79
+ it('prefers connection_parameters, which carries both hosts', () => {
80
+ const entries = [
81
+ {
82
+ connection_uri: DIRECT_URI,
83
+ connection_parameters: {
84
+ host: DIRECT_HOST,
85
+ pooler_host: POOLER_HOST,
86
+ role: 'neondb_owner',
87
+ database: 'neondb',
88
+ password: 'npg_secret'
89
+ }
90
+ }
91
+ ];
92
+
93
+ expect(connectionFromCreateResponse(entries, false)!.host).toBe(DIRECT_HOST);
94
+ expect(connectionFromCreateResponse(entries, true)!.host).toBe(POOLER_HOST);
95
+ });
96
+
97
+ it('falls back to parsing the string for a DIRECT request', () => {
98
+ expect(connectionFromCreateResponse([{ connection_uri: DIRECT_URI }], false)!.host).toBe(
99
+ DIRECT_HOST
100
+ );
101
+ });
102
+
103
+ it('refuses to answer a POOLED request from the string alone', () => {
104
+ // The string names the direct host, and deriving the pooler hostname would
105
+ // mean guessing a naming convention. Null sends the caller to
106
+ // `GET /connection_uri?pooled=true`, which answers authoritatively.
107
+ expect(connectionFromCreateResponse([{ connection_uri: DIRECT_URI }], true)).toBeNull();
108
+ });
109
+
110
+ it('answers null when the create response carried nothing', () => {
111
+ // The documented case: a branch cut from a parent with more than one role
112
+ // or database comes back without any connection URI at all.
113
+ expect(connectionFromCreateResponse(undefined, false)).toBeNull();
114
+ expect(connectionFromCreateResponse([], false)).toBeNull();
115
+ });
116
+ });
117
+
118
+ describe('resolveBranchConnection', () => {
119
+ /** Neon, answering `/connection_uri` in its real `{ uri }` shape. */
120
+ function mockNeon(options: { uri?: string; revealPassword?: string } = {}) {
121
+ const requested: string[] = [];
122
+
123
+ globalThis.fetch = (async (target: string | URL) => {
124
+ const url = new URL(String(target));
125
+ requested.push(url.pathname + url.search);
126
+
127
+ if (url.pathname.endsWith('/databases')) return json({ databases: [{ name: 'neondb' }] });
128
+ if (url.pathname.endsWith('/roles')) {
129
+ return json({ roles: [{ name: 'neon_superuser', protected: true }, { name: 'neondb_owner' }] });
130
+ }
131
+ if (url.pathname.endsWith('/reveal_password')) {
132
+ return json({ password: options.revealPassword });
133
+ }
134
+ if (url.pathname.endsWith('/connection_uri')) {
135
+ const pooled = url.searchParams.get('pooled') === 'true';
136
+ return json({ uri: options.uri ?? (pooled ? POOLED_URI : DIRECT_URI) });
137
+ }
138
+ throw new Error(`unexpected request: ${url}`);
139
+ }) as typeof fetch;
140
+
141
+ return requested;
142
+ }
143
+
144
+ it('resolves from the bare `{ uri }` shape the endpoint actually returns', async () => {
145
+ // The regression in one test: this shape used to produce "Neon did not
146
+ // report a host" for every project.
147
+ const requested = mockNeon();
148
+
149
+ const connection = await resolveBranchConnection(
150
+ { apiKey: 'napi_x' },
151
+ { projectId: 'proj-1', branchId: 'br-1', pooled: false }
152
+ );
153
+
154
+ expect(connection.host).toBe(DIRECT_HOST);
155
+ expect(connection.password).toBe('npg_secret');
156
+ expect(connection.database).toBe('neondb');
157
+ expect(requested.some((path) => path.includes('database_name=neondb'))).toBe(true);
158
+ expect(requested.some((path) => path.includes('role_name=neondb_owner'))).toBe(true);
159
+ });
160
+
161
+ it('asks for the pooled endpoint rather than deriving its hostname', async () => {
162
+ mockNeon();
163
+
164
+ const connection = await resolveBranchConnection(
165
+ { apiKey: 'napi_x' },
166
+ { projectId: 'proj-1', branchId: 'br-1', pooled: true }
167
+ );
168
+ expect(connection.host).toBe(POOLER_HOST);
169
+ });
170
+
171
+ it('skips a protected role, which cannot own a migration', async () => {
172
+ const requested = mockNeon();
173
+ await resolveBranchConnection(
174
+ { apiKey: 'napi_x' },
175
+ { projectId: 'proj-1', branchId: 'br-1', pooled: false }
176
+ );
177
+ expect(requested.some((path) => path.includes('role_name=neon_superuser'))).toBe(false);
178
+ });
179
+
180
+ it('reveals the password when the URI carries none', async () => {
181
+ mockNeon({
182
+ uri: `postgresql://neondb_owner@${DIRECT_HOST}/neondb`,
183
+ revealPassword: 'npg_revealed'
184
+ });
185
+
186
+ const connection = await resolveBranchConnection(
187
+ { apiKey: 'napi_x' },
188
+ { projectId: 'proj-1', branchId: 'br-1', pooled: false }
189
+ );
190
+ expect(connection.password).toBe('npg_revealed');
191
+ expect(connection.host).toBe(DIRECT_HOST);
192
+ });
193
+
194
+ it('names the real cause when the branch has no compute at all', async () => {
195
+ mockNeon({ uri: '' });
196
+
197
+ await expect(
198
+ resolveBranchConnection({ apiKey: 'napi_x' }, { projectId: 'proj-1', branchId: 'br-1', pooled: false })
199
+ ).rejects.toThrow(/compute endpoint/);
200
+ });
201
+ });