@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,104 @@
1
+ /**
2
+ * Applying a pending migration.
3
+ *
4
+ * The one write path in the Supabase surface, and it goes over SQL rather than
5
+ * through `POST /v1/projects/{ref}/database/migrations`. Two reasons, in order
6
+ * of weight: the SQL path is the only one that also works for a `supabase start`
7
+ * stack, so there is one implementation instead of two; and it is exactly what
8
+ * `supabase db push` does — run the file, then record the version in the CLI's
9
+ * own bookkeeping table — so a migration applied from here is indistinguishable
10
+ * from one applied from the terminal.
11
+ *
12
+ * Everything happens in ONE transaction: Postgres rolls DDL back like anything
13
+ * else, so a migration that fails half way leaves nothing behind, and the
14
+ * version is only recorded if the SQL that earns it succeeded.
15
+ *
16
+ * The known limit is `CREATE INDEX CONCURRENTLY`, which Postgres refuses inside
17
+ * a transaction. The provider's own error says so plainly and is passed through
18
+ * rather than rewritten, because the fix — run that one statement by hand — is
19
+ * something only the user can decide on.
20
+ */
21
+
22
+ import type { DbClientDriverAdapter, DbClientTxContext } from '../../drivers/types';
23
+ import { debug } from '$shared/utils/logger';
24
+
25
+ const SCHEMA = 'supabase_migrations';
26
+ const TABLE = 'schema_migrations';
27
+
28
+ /**
29
+ * Make sure the CLI's bookkeeping table exists, in the shape the CLI uses.
30
+ *
31
+ * A project that has only ever been changed through the dashboard has no such
32
+ * table, and a project created by an older CLI has the table without its later
33
+ * columns — which is why each column is added separately and idempotently
34
+ * rather than the whole thing being created in one shot and assumed complete.
35
+ */
36
+ async function ensureBookkeeping(tx: DbClientTxContext): Promise<void> {
37
+ await tx.executeWrite(`CREATE SCHEMA IF NOT EXISTS ${SCHEMA}`);
38
+ await tx.executeWrite(`
39
+ CREATE TABLE IF NOT EXISTS ${SCHEMA}.${TABLE} (
40
+ version text NOT NULL PRIMARY KEY
41
+ )
42
+ `);
43
+ await tx.executeWrite(`ALTER TABLE ${SCHEMA}.${TABLE} ADD COLUMN IF NOT EXISTS statements text[]`);
44
+ await tx.executeWrite(`ALTER TABLE ${SCHEMA}.${TABLE} ADD COLUMN IF NOT EXISTS name text`);
45
+ }
46
+
47
+ export interface ApplyMigrationInput {
48
+ adapter: DbClientDriverAdapter;
49
+ version: string;
50
+ name: string | null;
51
+ sql: string;
52
+ }
53
+
54
+ export interface ApplyMigrationResult {
55
+ version: string;
56
+ /** Milliseconds the whole transaction took, for the report line. */
57
+ durationMs: number;
58
+ }
59
+
60
+ export async function applyMigration(input: ApplyMigrationInput): Promise<ApplyMigrationResult> {
61
+ const { adapter, version, name, sql } = input;
62
+
63
+ if (!adapter.withTransaction) {
64
+ throw new Error('This connection cannot run a transaction, so a migration cannot be applied safely from here');
65
+ }
66
+ if (!sql.trim()) {
67
+ throw new Error(`Migration ${version} is empty`);
68
+ }
69
+
70
+ const started = performance.now();
71
+
72
+ await adapter.withTransaction(async (tx) => {
73
+ await ensureBookkeeping(tx);
74
+
75
+ // Guard INSIDE the transaction. Checking before it opens would leave a gap
76
+ // where two people apply the same migration at once and both see it
77
+ // pending; the primary key would then reject the second write after its
78
+ // SQL had already run.
79
+ const existing = await tx.executeRead(
80
+ `SELECT version FROM ${SCHEMA}.${TABLE} WHERE version = '${version.replace(/'/g, "''")}'`
81
+ );
82
+ if (existing.rows.length > 0) {
83
+ throw new Error(`Migration ${version} is already recorded as applied`);
84
+ }
85
+
86
+ // The whole file as one statement. Bun's SQL sends a parameterless query
87
+ // over the simple protocol, which is what allows the several statements a
88
+ // migration normally contains; splitting it here would have to understand
89
+ // dollar-quoted function bodies, and getting that wrong truncates a
90
+ // function definition mid-way.
91
+ await tx.executeWrite(sql);
92
+
93
+ const escapedVersion = version.replace(/'/g, "''");
94
+ const escapedName = name ? `'${name.replace(/'/g, "''")}'` : 'NULL';
95
+ await tx.executeWrite(`
96
+ INSERT INTO ${SCHEMA}.${TABLE} (version, name)
97
+ VALUES ('${escapedVersion}', ${escapedName})
98
+ `);
99
+ });
100
+
101
+ const durationMs = Math.round(performance.now() - started);
102
+ debug.log('db-client', `Applied Supabase migration ${version} in ${durationMs}ms`);
103
+ return { version, durationMs };
104
+ }
@@ -0,0 +1,259 @@
1
+ /**
2
+ * A small Supabase Management API client — only what DB Client needs.
3
+ *
4
+ * No SDK, for the reason the Vercel and GitHub clients have none: this is a
5
+ * handful of plain JSON calls, and an SDK would add a dependency tree we then
6
+ * have to keep Bun-compatible for no capability we use.
7
+ *
8
+ * Every path in this file was read out of the published OpenAPI document at
9
+ * `https://api.supabase.com/api/v1-json` rather than inferred from a sibling.
10
+ * Two things there are worth knowing before changing anything:
11
+ *
12
+ * - `POST /v1/projects/{ref}/database/query` exists and is marked BETA. It is
13
+ * deliberately unused: everything inside the database is read through the
14
+ * Postgres connection DB Client already holds, which keeps a `supabase start`
15
+ * stack working without an access token and keeps us off a beta endpoint for
16
+ * queries we can make directly.
17
+ * - There is NO endpoint that reads a project's database password back.
18
+ * `/v1/projects/{ref}/database/password` is PATCH-only, by design. That single
19
+ * fact is why a link stores a password of its own.
20
+ */
21
+
22
+ const SUPABASE_API_BASE = 'https://api.supabase.com';
23
+
24
+ /**
25
+ * Two budgets, the same split the Vercel client settled on. A read answers
26
+ * quickly; generating TypeScript types for a large schema does not, and
27
+ * aborting it mid-flight reports a timeout for work the server completed.
28
+ */
29
+ const READ_TIMEOUT_MS = 20_000;
30
+ const SLOW_TIMEOUT_MS = 120_000;
31
+
32
+ export class SupabaseError extends Error {
33
+ constructor(
34
+ message: string,
35
+ readonly status: number,
36
+ readonly kind: 'auth' | 'config' | 'rate-limit' | 'error'
37
+ ) {
38
+ super(message);
39
+ this.name = 'SupabaseError';
40
+ }
41
+ }
42
+
43
+ export interface SupabaseCredentials {
44
+ accessToken: string;
45
+ }
46
+
47
+ /**
48
+ * Classic or scoped, read from the prefix.
49
+ *
50
+ * Supabase prefixes a scoped personal access token `sbp_fc` and a classic
51
+ * full-access one plain `sbp_`. That one character of information is worth a
52
+ * great deal, because a scoped token missing a permission fails with an
53
+ * undecorated "Forbidden" — the same undiagnosable shape GitHub's fine-grained
54
+ * tokens produced in `Task 2`, and answered the same way: read the prefix and
55
+ * name the likely cause rather than repeating the provider's word for it.
56
+ */
57
+ export function tokenKindOf(token: string): 'scoped' | 'classic' {
58
+ return token.startsWith('sbp_fc') ? 'scoped' : 'classic';
59
+ }
60
+
61
+ /** Which permission a 403 on a given path most likely needs. */
62
+ function missingScopeHint(path: string): string | null {
63
+ if (path.startsWith('/v1/organizations/')) return 'Organization Settings (Read)';
64
+ if (path === '/v1/organizations') return 'Organizations (Read)';
65
+ if (path === '/v1/projects') return 'Organization Projects (Read-write) to create, Projects (account-wide) Read to list';
66
+ if (path.includes('/types/typescript')) return 'Database (Read)';
67
+ if (path.includes('/functions')) return 'Edge Functions (Read)';
68
+ if (path.includes('/advisors/')) return 'Project Settings (Read)';
69
+ if (path.includes('/config/database/pooler')) return 'Project Settings (Read)';
70
+ return null;
71
+ }
72
+
73
+ /**
74
+ * Map a failed response onto something the hub and the panel can act on.
75
+ *
76
+ * Supabase's own message is kept: it is the most specific thing anyone will
77
+ * see. The classification is ours, because the hub's status strip understands
78
+ * four states and no more.
79
+ */
80
+ async function toError(
81
+ response: Response,
82
+ context: { path: string; token: string }
83
+ ): Promise<SupabaseError> {
84
+ let message = response.statusText || `HTTP ${response.status}`;
85
+ try {
86
+ const body = await response.json() as { message?: unknown; error?: unknown; msg?: unknown };
87
+ for (const candidate of [body.message, body.error, body.msg]) {
88
+ if (typeof candidate === 'string' && candidate.trim()) {
89
+ message = candidate;
90
+ break;
91
+ }
92
+ }
93
+ } catch {
94
+ // Non-JSON body — the status line is all we have.
95
+ }
96
+
97
+ if (response.status === 401) {
98
+ return new SupabaseError(
99
+ `${message}. The access token is invalid or was revoked — create a new one at supabase.com/dashboard/account/tokens.`,
100
+ 401,
101
+ 'auth'
102
+ );
103
+ }
104
+ if (response.status === 403) {
105
+ // The most common cause by far, and the one the provider never names.
106
+ // A classic token's 403 really is about membership; a scoped token's is
107
+ // almost always a permission that was not ticked when it was created.
108
+ const scope = missingScopeHint(context.path);
109
+ const detail = tokenKindOf(context.token) === 'scoped'
110
+ ? `This is a SCOPED token${scope ? `, and this call needs ${scope}` : ''}. Scoped tokens only carry the permissions picked when they were created — regenerate it with that permission, or use a classic token.`
111
+ : "This token's user does not have access here — a token belongs to one Supabase user, and organisation access follows that user's membership.";
112
+ return new SupabaseError(`${message}. ${detail}`, 403, 'config');
113
+ }
114
+ if (response.status === 404) {
115
+ return new SupabaseError(
116
+ `${message}. The project does not exist, or this token cannot see it.`,
117
+ 404,
118
+ 'config'
119
+ );
120
+ }
121
+ if (response.status === 429) {
122
+ return new SupabaseError('Supabase rate limit reached. Try again shortly.', 429, 'rate-limit');
123
+ }
124
+ return new SupabaseError(message, response.status, 'error');
125
+ }
126
+
127
+ /**
128
+ * What the Management API says about how much budget is left.
129
+ *
130
+ * Supabase does not document these, but every response carries them — verified
131
+ * against a live account: `x-ratelimit-limit: 120`, `x-ratelimit-remaining`,
132
+ * and `x-ratelimit-reset: 60`. The budget is per MINUTE, not per hour.
133
+ *
134
+ * `x-ratelimit-reset` is SECONDS FROM NOW, not an epoch timestamp. GitHub and
135
+ * Vercel both send an epoch there, and reading this one the same way dated
136
+ * every reset to January 1970 — the footer would have said "resets 07:01:00"
137
+ * and nobody would have known why.
138
+ *
139
+ * Absent means "not reported", never "none left", so a missing header shows
140
+ * nothing rather than an alarming zero.
141
+ */
142
+ export interface SupabaseRateLimit {
143
+ remaining: number;
144
+ limit: number;
145
+ resetAt: string | null;
146
+ }
147
+
148
+ /**
149
+ * Last reading PER TOKEN, not per process.
150
+ *
151
+ * The limit is counted per Supabase user, so two connected accounts have two
152
+ * separate budgets and one global figure would attribute one account's usage to
153
+ * the other. The token is used as the map key and nothing more — it never
154
+ * leaves this module, and it is already in memory on the object being passed.
155
+ */
156
+ const rateLimits = new Map<string, SupabaseRateLimit>();
157
+
158
+ /** The most recent rate-limit reading for one account, for the surface's footer. */
159
+ export function getSupabaseRateLimit(credentials: SupabaseCredentials): SupabaseRateLimit | null {
160
+ return rateLimits.get(credentials.accessToken) ?? null;
161
+ }
162
+
163
+ /**
164
+ * Take a reading if this account has never produced one.
165
+ *
166
+ * The footer is rendered from the connection context, and resolving that
167
+ * context touches no Management API at all — the default tab is pure SQL — so
168
+ * on a fresh server the quota had nothing to show and simply never appeared.
169
+ * One cheap request the first time an account is looked at fixes that for the
170
+ * process's lifetime; every later call refreshes the reading for free, because
171
+ * the headers ride on responses we were making anyway.
172
+ *
173
+ * Failure is ignored: this exists to populate a footer, and nothing depends on
174
+ * it succeeding.
175
+ */
176
+ export async function primeSupabaseRateLimit(
177
+ credentials: SupabaseCredentials,
178
+ ref: string
179
+ ): Promise<void> {
180
+ if (rateLimits.has(credentials.accessToken)) return;
181
+ try {
182
+ await supabaseRequest(credentials, `/v1/projects/${encodeURIComponent(ref)}`);
183
+ } catch {
184
+ // A token that cannot read the project still cannot report a budget.
185
+ }
186
+ }
187
+
188
+ function readRateLimit(token: string, headers: Headers): void {
189
+ const remaining = headers.get('x-ratelimit-remaining');
190
+ const limit = headers.get('x-ratelimit-limit');
191
+ if (remaining === null || limit === null) return;
192
+
193
+ const remainingValue = Number(remaining);
194
+ const limitValue = Number(limit);
195
+ if (!Number.isFinite(remainingValue) || !Number.isFinite(limitValue)) return;
196
+
197
+ const reset = headers.get('x-ratelimit-reset');
198
+ const resetValue = reset === null ? NaN : Number(reset);
199
+ rateLimits.set(token, {
200
+ remaining: remainingValue,
201
+ limit: limitValue,
202
+ // A DURATION in seconds, resolved against now. See the note above: reading
203
+ // it as an epoch is the mistake this comment exists to stop.
204
+ resetAt: Number.isFinite(resetValue) ? new Date(Date.now() + resetValue * 1000).toISOString() : null
205
+ });
206
+ }
207
+
208
+ export interface SupabaseRequestOptions {
209
+ method?: 'GET' | 'POST' | 'PATCH' | 'DELETE';
210
+ body?: unknown;
211
+ query?: Record<string, string | number | undefined | null>;
212
+ timeoutMs?: number;
213
+ }
214
+
215
+ function buildUrl(path: string, query?: SupabaseRequestOptions['query']): string {
216
+ const url = new URL(`${SUPABASE_API_BASE}${path}`);
217
+ for (const [key, value] of Object.entries(query ?? {})) {
218
+ if (value === undefined || value === null || value === '') continue;
219
+ url.searchParams.set(key, String(value));
220
+ }
221
+ return url.toString();
222
+ }
223
+
224
+ export async function supabaseRequest<T>(
225
+ credentials: SupabaseCredentials,
226
+ path: string,
227
+ options: SupabaseRequestOptions = {}
228
+ ): Promise<T> {
229
+ const method = options.method ?? 'GET';
230
+ const headers: Record<string, string> = {
231
+ Authorization: `Bearer ${credentials.accessToken}`,
232
+ 'User-Agent': 'clopen'
233
+ };
234
+ if (options.body !== undefined) headers['Content-Type'] = 'application/json';
235
+
236
+ let response: Response;
237
+ try {
238
+ response = await fetch(buildUrl(path, options.query), {
239
+ method,
240
+ headers,
241
+ ...(options.body !== undefined && { body: JSON.stringify(options.body) }),
242
+ signal: AbortSignal.timeout(options.timeoutMs ?? READ_TIMEOUT_MS)
243
+ });
244
+ } catch (error) {
245
+ const detail = error instanceof Error ? error.message : String(error);
246
+ throw new SupabaseError(`Could not reach Supabase: ${detail}`, 0, 'error');
247
+ }
248
+
249
+ // Read before the status check: a 429 is precisely when the remaining count
250
+ // is worth knowing.
251
+ readRateLimit(credentials.accessToken, response.headers);
252
+ if (!response.ok) throw await toError(response, { path, token: credentials.accessToken });
253
+
254
+ const text = await response.text();
255
+ return (text ? JSON.parse(text) : null) as T;
256
+ }
257
+
258
+ /** The budget for calls that do real work upstream, such as type generation. */
259
+ export const SUPABASE_SLOW_TIMEOUT_MS = SLOW_TIMEOUT_MS;