@myrialabs/clopen 0.4.38 → 0.4.39

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 (114) hide show
  1. package/backend/auth/permissions.ts +25 -0
  2. package/backend/chat/stream-manager.ts +1 -1
  3. package/backend/database/crypto/secret-columns.ts +5 -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/index.ts +21 -0
  8. package/backend/database/queries/db-client-connection-queries.ts +19 -0
  9. package/backend/database/queries/deploy-queries.ts +124 -0
  10. package/backend/database/queries/graph-queries.ts +291 -247
  11. package/backend/database/queries/index.ts +4 -0
  12. package/backend/database/queries/integration-db-link-queries.ts +168 -0
  13. package/backend/database/queries/integration-queries.ts +34 -6
  14. package/backend/db-client/integrations/index.ts +37 -0
  15. package/backend/db-client/integrations/links.ts +533 -0
  16. package/backend/db-client/integrations/projector.test.ts +280 -0
  17. package/backend/db-client/integrations/projector.ts +256 -0
  18. package/backend/db-client/integrations/supabase-service.ts +266 -0
  19. package/backend/db-client/providers/registry.ts +27 -0
  20. package/backend/db-client/providers/supabase/adapter.ts +500 -0
  21. package/backend/db-client/providers/supabase/api-types.ts +92 -0
  22. package/backend/db-client/providers/supabase/apply-migration.ts +104 -0
  23. package/backend/db-client/providers/supabase/client.ts +259 -0
  24. package/backend/db-client/providers/supabase/features.ts +502 -0
  25. package/backend/db-client/providers/supabase/local.test.ts +78 -0
  26. package/backend/db-client/providers/supabase/local.ts +137 -0
  27. package/backend/db-client/providers/types.ts +137 -0
  28. package/backend/deployments/bindings.test.ts +43 -0
  29. package/backend/deployments/bindings.ts +216 -0
  30. package/backend/deployments/index.ts +53 -0
  31. package/backend/deployments/log-streams.ts +214 -0
  32. package/backend/deployments/prompts.ts +70 -0
  33. package/backend/deployments/providers/vercel/adapter.ts +757 -0
  34. package/backend/deployments/providers/vercel/build-logs.test.ts +80 -0
  35. package/backend/deployments/providers/vercel/build-logs.ts +211 -0
  36. package/backend/deployments/providers/vercel/client.ts +203 -0
  37. package/backend/deployments/providers/vercel/list.test.ts +624 -0
  38. package/backend/deployments/providers/vercel/normalise.test.ts +115 -0
  39. package/backend/deployments/providers/vercel/normalise.ts +113 -0
  40. package/backend/deployments/providers/vercel/types.ts +104 -0
  41. package/backend/deployments/registry.ts +27 -0
  42. package/backend/deployments/service.ts +458 -0
  43. package/backend/deployments/types.ts +278 -0
  44. package/backend/index.ts +4 -0
  45. package/backend/integrations/projections/index.ts +0 -0
  46. package/backend/integrations/projections/mcp-projector.ts +7 -3
  47. package/backend/integrations/projections/types.ts +21 -9
  48. package/backend/integrations/registry/index.ts +5 -1
  49. package/backend/integrations/registry/providers/supabase.ts +61 -0
  50. package/backend/integrations/registry/providers/vercel.ts +46 -0
  51. package/backend/mcp/internal/servers/memory-graph/description.ts +3 -3
  52. package/backend/mcp/internal/servers/memory-graph/runner.ts +4 -9
  53. package/backend/mcp/internal/servers/memory-graph/schema.ts +0 -4
  54. package/backend/memory/README.md +57 -34
  55. package/backend/memory/compose.test.ts +3 -3
  56. package/backend/memory/compose.ts +6 -9
  57. package/backend/memory/config.ts +0 -5
  58. package/backend/memory/consolidate.ts +1 -2
  59. package/backend/memory/context.test.ts +8 -54
  60. package/backend/memory/context.ts +19 -25
  61. package/backend/memory/extract/episodic.ts +10 -12
  62. package/backend/memory/extract/index.ts +23 -52
  63. package/backend/memory/extract/scheduler.ts +3 -6
  64. package/backend/memory/index.ts +6 -5
  65. package/backend/memory/invalidate.ts +36 -48
  66. package/backend/memory/layout.ts +319 -130
  67. package/backend/memory/retention.ts +12 -42
  68. package/backend/memory/retrieval.eval.test.ts +2 -2
  69. package/backend/memory/retrieval.test.ts +228 -183
  70. package/backend/memory/retrieval.ts +22 -21
  71. package/backend/memory/revise.test.ts +62 -116
  72. package/backend/memory/revise.ts +0 -1
  73. package/backend/memory/view.ts +8 -5
  74. package/backend/snapshot/helpers.ts +35 -41
  75. package/backend/snapshot/snapshot-service.ts +90 -0
  76. package/backend/snapshot/turn-changes.test.ts +163 -0
  77. package/backend/snapshot/turn-changes.ts +131 -0
  78. package/backend/ws/db-client/accounts.ts +225 -0
  79. package/backend/ws/db-client/connections.ts +34 -3
  80. package/backend/ws/db-client/context.ts +37 -0
  81. package/backend/ws/db-client/index.ts +20 -1
  82. package/backend/ws/db-client/supabase.ts +188 -0
  83. package/backend/ws/deployments/actions.ts +360 -0
  84. package/backend/ws/deployments/context.ts +43 -0
  85. package/backend/ws/deployments/crud.ts +152 -0
  86. package/backend/ws/deployments/index.ts +15 -0
  87. package/backend/ws/deployments/schemas.ts +183 -0
  88. package/backend/ws/index.ts +6 -2
  89. package/backend/ws/memory/crud.ts +4 -16
  90. package/backend/ws/snapshot/changes.ts +279 -0
  91. package/backend/ws/snapshot/index.ts +4 -3
  92. package/dist/assets/{index-CyH7fSbR.js → index-BrF6nqld.js} +1 -1
  93. package/dist/assets/{index-DSHIANSy.js → index-C8Gi-b6U.js} +1 -1
  94. package/dist/assets/main-Bd3gb79F.css +1 -0
  95. package/dist/assets/main-Bo1hD7mt.js +1191 -0
  96. package/dist/index.html +2 -2
  97. package/package.json +1 -1
  98. package/shared/constants/tool-icons.ts +9 -0
  99. package/shared/types/db-client/connection.ts +6 -0
  100. package/shared/types/db-client/index.ts +2 -0
  101. package/shared/types/db-client/integrations.ts +174 -0
  102. package/shared/types/db-client/supabase.ts +131 -0
  103. package/shared/types/deployments.ts +382 -0
  104. package/shared/types/memory.ts +34 -51
  105. package/shared/types/ui/components.ts +1 -1
  106. package/shared/utils/diff-calculator.test.ts +89 -0
  107. package/shared/utils/diff-calculator.ts +30 -65
  108. package/shared/utils/logger.ts +1 -0
  109. package/backend/memory/extract/languages.ts +0 -176
  110. package/backend/memory/extract/structural.test.ts +0 -215
  111. package/backend/memory/extract/structural.ts +0 -364
  112. package/backend/ws/snapshot/content.ts +0 -85
  113. package/dist/assets/main-D2IOjftb.css +0 -1
  114. package/dist/assets/main-DM-tHKbW.js +0 -1152
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Keeping the tail of a build log.
3
+ *
4
+ * The direction is the whole point: a build log's head is dependency
5
+ * installation, so truncating from the front is the one way to produce an
6
+ * excerpt with no information about the failure in it.
7
+ */
8
+
9
+ import { describe, it, expect } from 'bun:test';
10
+
11
+ import { keepTail } from './build-logs';
12
+
13
+ describe('keepTail', () => {
14
+ it('leaves a log that already fits alone', () => {
15
+ const text = 'one\ntwo\nthree';
16
+ expect(keepTail(text, 1_000)).toEqual({ text, truncated: false });
17
+ });
18
+
19
+ it('keeps the END of a log that does not fit', () => {
20
+ const text = Array.from({ length: 200 }, (_, index) => `line ${index}`).join('\n');
21
+ const result = keepTail(text, 120);
22
+
23
+ expect(result.truncated).toBe(true);
24
+ expect(result.text).toContain('line 199');
25
+ expect(result.text).not.toContain('line 0\n');
26
+ });
27
+
28
+ it('cuts on a line boundary rather than mid-line', () => {
29
+ const text = 'aaaaaaaaaa\nbbbbbbbbbb\ncccccccccc';
30
+ const result = keepTail(text, 15);
31
+
32
+ // Every surviving line is whole — no leading fragment of a dropped one.
33
+ const body = result.text.split('\n').slice(1);
34
+ for (const line of body) {
35
+ expect(['aaaaaaaaaa', 'bbbbbbbbbb', 'cccccccccc']).toContain(line);
36
+ }
37
+ });
38
+
39
+ it('says how much it dropped, so the reader knows the log is partial', () => {
40
+ const text = Array.from({ length: 50 }, (_, index) => `line ${index}`).join('\n');
41
+ expect(keepTail(text, 60).text).toMatch(/^… \d+ earlier lines? omitted …\n/);
42
+ });
43
+ });
44
+
45
+ /**
46
+ * Reading the stage out of the event stream.
47
+ *
48
+ * A build prints nothing for long stretches — uploading, provisioning,
49
+ * assigning domains — and during those the log alone cannot be told apart from
50
+ * a stall. These events are the only thing that speaks, so they are forwarded
51
+ * as a phase rather than dropped with the rest of the non-output events.
52
+ */
53
+ import { phaseOf } from './build-logs';
54
+
55
+ describe('phaseOf', () => {
56
+ it('names the stage from a deployment-state event', () => {
57
+ expect(phaseOf({ type: 'deployment-state', info: { readyState: 'BUILDING' } } as never)).toBe('Building');
58
+ expect(phaseOf({ type: 'deployment-state', info: { readyState: 'UPLOADING' } } as never)).toBe('Uploading');
59
+ });
60
+
61
+ it('ignores events that are output rather than state', () => {
62
+ expect(phaseOf({ type: 'stdout', text: 'BUILDING something' })).toBeNull();
63
+ expect(phaseOf({ type: 'command', text: 'npm run build' })).toBeNull();
64
+ });
65
+
66
+ it('falls back to the build step when there is no ready state', () => {
67
+ // Still more useful than silence, so it is passed through as written.
68
+ expect(phaseOf({ type: 'deployment-state', info: { step: 'install' } } as never)).toBe('install');
69
+ });
70
+
71
+ it('reads the state from a payload-wrapped event too', () => {
72
+ expect(
73
+ phaseOf({ type: 'deployment-state', payload: { info: { readyState: 'READY' } } } as never)
74
+ ).toBe('Ready');
75
+ });
76
+
77
+ it('answers null when the event names no stage at all', () => {
78
+ expect(phaseOf({ type: 'deployment-state' })).toBeNull();
79
+ });
80
+ });
@@ -0,0 +1,211 @@
1
+ /**
2
+ * Build logs — the bundle a prompt carries, and the live follow.
3
+ *
4
+ * THE TAIL, NOT THE HEAD, for exactly the reason the Actions log reader keeps
5
+ * the tail: a build log's first hundreds of lines are dependency installation,
6
+ * and truncating from the front is the one way to produce an excerpt that
7
+ * contains no information about the failure.
8
+ *
9
+ * Only the lines a reader would care about survive. Vercel's event stream also
10
+ * carries `deployment-state`, `metric` and invocation records, which say
11
+ * nothing about why a build broke and would spend the budget saying it.
12
+ */
13
+
14
+ import type { BuildLogBundle } from '$shared/types/deployments';
15
+ import { vercelEventStream, vercelRequest, VercelError, type VercelCredentials } from './client';
16
+ import type { VercelEvent } from './types';
17
+ import type { LogStreamCallbacks, LogStreamHandle } from '../../types';
18
+ import { debug } from '$shared/utils/logger';
19
+
20
+ /** Log text handed to the model. Roughly the same budget the CI reader uses. */
21
+ const LOG_BUDGET = 24 * 1024;
22
+ const FETCH_TIMEOUT_MS = 30_000;
23
+
24
+ /** Event types that carry build output a human would read. */
25
+ const OUTPUT_TYPES = new Set(['stdout', 'stderr', 'command', 'fatal', 'exit']);
26
+
27
+ /**
28
+ * A human name for the stage a `deployment-state` event reports.
29
+ *
30
+ * These events are dropped from the log text — they are not output — but they
31
+ * are the only thing that speaks during the quiet parts of a build, so they are
32
+ * forwarded as a phase instead of discarded.
33
+ */
34
+ const PHASE_LABELS: Record<string, string> = {
35
+ QUEUED: 'Queued',
36
+ INITIALIZING: 'Initializing',
37
+ BUILDING: 'Building',
38
+ UPLOADING: 'Uploading',
39
+ DEPLOYING: 'Deploying',
40
+ ANALYZING: 'Analyzing',
41
+ READY: 'Ready',
42
+ ERROR: 'Failed',
43
+ CANCELED: 'Cancelled'
44
+ };
45
+
46
+ /** The stage this event reports, or null when it reports none. */
47
+ export function phaseOf(event: VercelEvent): string | null {
48
+ if (event.type !== 'deployment-state') return null;
49
+ const info = (event as { info?: { readyState?: string; step?: string; name?: string } }).info
50
+ ?? (event.payload as { info?: { readyState?: string; step?: string; name?: string } } | undefined)?.info;
51
+
52
+ const state = info?.readyState?.toUpperCase();
53
+ if (state && PHASE_LABELS[state]) return PHASE_LABELS[state];
54
+ // Some events name a build step instead of a state — still more useful than
55
+ // silence, so it is passed through as written.
56
+ return info?.step || null;
57
+ }
58
+
59
+ function textOf(event: VercelEvent): string | null {
60
+ if (!event.type || !OUTPUT_TYPES.has(event.type)) return null;
61
+ const text = event.text ?? event.payload?.text;
62
+ return typeof text === 'string' && text.length > 0 ? text : null;
63
+ }
64
+
65
+ /** Keep the last `limit` bytes, cut on a line boundary, and say what was dropped. */
66
+ export function keepTail(text: string, limit: number): { text: string; truncated: boolean } {
67
+ if (text.length <= limit) return { text, truncated: false };
68
+ const tail = text.slice(text.length - limit);
69
+ const firstNewline = tail.indexOf('\n');
70
+ const body = firstNewline >= 0 ? tail.slice(firstNewline + 1) : tail;
71
+ const droppedLines = text.slice(0, text.length - body.length).split('\n').length;
72
+ return {
73
+ text: `… ${droppedLines} earlier line${droppedLines === 1 ? '' : 's'} omitted …\n${body}`,
74
+ truncated: true
75
+ };
76
+ }
77
+
78
+ /**
79
+ * The whole log as one budgeted bundle.
80
+ *
81
+ * Without `follow` the same endpoint answers with a plain JSON array, which is
82
+ * what makes one reader serve both the chat prompt and a finished build's log
83
+ * view. `limit: -1` asks for everything, and the budget above is what actually
84
+ * bounds it.
85
+ */
86
+ export async function fetchBuildLogs(
87
+ credentials: VercelCredentials,
88
+ deploymentId: string,
89
+ teamId: string | null
90
+ ): Promise<BuildLogBundle> {
91
+ const response = await vercelRequest<VercelEvent[]>(
92
+ credentials,
93
+ `/v3/deployments/${encodeURIComponent(deploymentId)}/events`,
94
+ { query: { builds: 1, limit: -1, direction: 'forward', teamId: teamId ?? undefined } }
95
+ );
96
+
97
+ const lines: string[] = [];
98
+ for (const event of response.data ?? []) {
99
+ const text = textOf(event);
100
+ if (text !== null) lines.push(text.replace(/\n$/, ''));
101
+ }
102
+
103
+ if (lines.length === 0) {
104
+ return {
105
+ deploymentId,
106
+ // An empty log is a real state, not a failure: Vercel drops build
107
+ // events after a retention window, and a deployment that never began
108
+ // building never wrote any.
109
+ text: 'No build output is stored for this deployment. It may have been skipped, cancelled before the build started, or its logs may have aged out.',
110
+ truncated: false
111
+ };
112
+ }
113
+
114
+ const clipped = keepTail(lines.join('\n'), LOG_BUDGET);
115
+ return { deploymentId, text: clipped.text, truncated: clipped.truncated };
116
+ }
117
+
118
+ /**
119
+ * Follow a running build.
120
+ *
121
+ * The response body is newline-delimited JSON that never ends on its own, so
122
+ * the only way out is the abort signal — which is why the handle returned here
123
+ * is the stream manager's sole means of cleaning up. A partial line at the end
124
+ * of a chunk is held back rather than parsed, because network chunk boundaries
125
+ * fall wherever they like and half a JSON object parses as nothing.
126
+ */
127
+ export async function streamBuildLogs(
128
+ credentials: VercelCredentials,
129
+ deploymentId: string,
130
+ teamId: string | null,
131
+ callbacks: LogStreamCallbacks
132
+ ): Promise<LogStreamHandle> {
133
+ const controller = new AbortController();
134
+ const response = await vercelEventStream(credentials, deploymentId, {
135
+ teamId,
136
+ signal: controller.signal
137
+ });
138
+
139
+ const body = response.body;
140
+ if (!body) {
141
+ controller.abort();
142
+ throw new VercelError('Vercel returned no log stream', response.status, 'error');
143
+ }
144
+
145
+ void pump(body, callbacks, controller);
146
+ return { stop: () => controller.abort() };
147
+ }
148
+
149
+ async function pump(
150
+ body: ReadableStream<Uint8Array>,
151
+ callbacks: LogStreamCallbacks,
152
+ controller: AbortController
153
+ ): Promise<void> {
154
+ const reader = body.getReader();
155
+ const decoder = new TextDecoder();
156
+ let buffer = '';
157
+ let ended = false;
158
+ let lastPhase: string | null = null;
159
+
160
+ const end = (error: string | null): void => {
161
+ if (ended) return;
162
+ ended = true;
163
+ callbacks.onEnd(error);
164
+ };
165
+
166
+ try {
167
+ for (;;) {
168
+ const { done, value } = await reader.read();
169
+ if (done) break;
170
+ if (!value) continue;
171
+
172
+ buffer += decoder.decode(value, { stream: true });
173
+ const lines = buffer.split('\n');
174
+ // The last element is whatever came after the final newline: either an
175
+ // empty string or half an event. Either way it waits for more bytes.
176
+ buffer = lines.pop() ?? '';
177
+
178
+ const out: string[] = [];
179
+ for (const line of lines) {
180
+ if (!line.trim()) continue;
181
+ try {
182
+ const event = JSON.parse(line) as VercelEvent;
183
+
184
+ const phase = phaseOf(event);
185
+ // Only on a CHANGE: these repeat, and re-announcing the same stage
186
+ // would read as progress that is not happening.
187
+ if (phase && phase !== lastPhase) {
188
+ lastPhase = phase;
189
+ callbacks.onPhase?.(phase);
190
+ }
191
+
192
+ const text = textOf(event);
193
+ if (text !== null) out.push(text.replace(/\n$/, ''));
194
+ } catch {
195
+ // A line that is not JSON is not worth killing the stream over.
196
+ debug.log('deployments', 'Skipped an unparseable log line');
197
+ }
198
+ }
199
+ if (out.length > 0) callbacks.onChunk(`${out.join('\n')}\n`);
200
+ }
201
+ end(null);
202
+ } catch (error) {
203
+ // An abort is how this stream is meant to finish, so it is not an error.
204
+ if (controller.signal.aborted) end(null);
205
+ else end(error instanceof Error ? error.message : String(error));
206
+ } finally {
207
+ reader.releaseLock();
208
+ }
209
+ }
210
+
211
+ export { FETCH_TIMEOUT_MS };
@@ -0,0 +1,203 @@
1
+ /**
2
+ * A small Vercel REST client — only what the Deployments surface needs.
3
+ *
4
+ * No SDK, for the reason the GitHub client has none: this surface makes about a
5
+ * dozen plain JSON calls, and an SDK would add a dependency whose transitive
6
+ * tree we then have to keep Bun-compatible (see the typebox and bson incidents)
7
+ * for no capability we use.
8
+ *
9
+ * Vercel's API is versioned PER ENDPOINT, not globally, and the versions are
10
+ * not interchangeable — listing projects is `/v10/projects` while reading one
11
+ * is `/v9/projects/{id}`, and rollback and promote sit on `/v1` and `/v10`
12
+ * respectively. Every path in this file was checked against the published
13
+ * OpenAPI document rather than inferred from a sibling, because guessing the
14
+ * version yields a 404 that reads exactly like a permission problem.
15
+ *
16
+ * `teamId` travels on nearly every call. A token reaches several teams, and a
17
+ * request without the team simply does not see that team's projects — another
18
+ * failure that arrives as an empty list rather than an error.
19
+ */
20
+
21
+ import type { DeployRateLimit } from '$shared/types/deployments';
22
+
23
+ export const VERCEL_API_BASE = 'https://api.vercel.com';
24
+
25
+ /**
26
+ * Requests are capped so a hung API cannot wedge a handler.
27
+ *
28
+ * Two budgets, because the work behind these calls differs by an order of
29
+ * magnitude. A read answers in under a second. Linking a repository, creating a
30
+ * project or queueing a build makes Vercel talk to a git host and provision
31
+ * things, and 20 seconds is not unusual — the first version aborted those
32
+ * mid-flight and reported a timeout for an operation that then completed
33
+ * server-side, which is the worst of both: no result, and the change happened
34
+ * anyway.
35
+ */
36
+ const READ_TIMEOUT_MS = 20_000;
37
+ const MUTATION_TIMEOUT_MS = 120_000;
38
+
39
+ export class VercelError extends Error {
40
+ constructor(
41
+ message: string,
42
+ readonly status: number,
43
+ readonly kind: 'auth' | 'config' | 'rate-limit' | 'error'
44
+ ) {
45
+ super(message);
46
+ this.name = 'VercelError';
47
+ }
48
+ }
49
+
50
+ export interface VercelCredentials {
51
+ token: string;
52
+ }
53
+
54
+ function parseRateLimit(headers: Headers): DeployRateLimit | null {
55
+ const remaining = headers.get('x-ratelimit-remaining');
56
+ const limit = headers.get('x-ratelimit-limit');
57
+ if (remaining === null || limit === null) return null;
58
+
59
+ const reset = headers.get('x-ratelimit-reset');
60
+ return {
61
+ remaining: Number(remaining),
62
+ limit: Number(limit),
63
+ // Vercel reports the reset as epoch seconds, like GitHub does.
64
+ resetAt: reset ? new Date(Number(reset) * 1000).toISOString() : null
65
+ };
66
+ }
67
+
68
+ /**
69
+ * Map a failed response onto something the hub and the panel can act on.
70
+ *
71
+ * Vercel's own message is kept because it is the most specific thing anyone
72
+ * will see — "Not authorized to access this resource" names the problem better
73
+ * than any wording we could invent. The classification is ours, because the
74
+ * hub's status strip only understands four states.
75
+ */
76
+ async function toError(response: Response): Promise<VercelError> {
77
+ let message = response.statusText || `HTTP ${response.status}`;
78
+ try {
79
+ const body = await response.json() as { error?: { message?: unknown; code?: unknown } };
80
+ if (typeof body.error?.message === 'string' && body.error.message.trim()) {
81
+ message = body.error.message;
82
+ }
83
+ } catch {
84
+ // Non-JSON body — the status line is all we have.
85
+ }
86
+
87
+ if (response.status === 401) {
88
+ return new VercelError(`${message}. The token is invalid or was revoked.`, 401, 'auth');
89
+ }
90
+ if (response.status === 429) {
91
+ const reset = response.headers.get('x-ratelimit-reset');
92
+ const at = reset ? new Date(Number(reset) * 1000).toLocaleTimeString() : 'shortly';
93
+ return new VercelError(`Vercel rate limit reached. It resets at ${at}.`, 429, 'rate-limit');
94
+ }
95
+ if (response.status === 403) {
96
+ return new VercelError(`${message}. The token cannot reach this resource — check its scope, and whether the project belongs to a team.`, 403, 'config');
97
+ }
98
+ if (response.status === 404) {
99
+ // A token scoped to a personal account gets 404 for a team's project
100
+ // rather than 403, so "not found" has to name both possibilities.
101
+ return new VercelError(`${message}. The project does not exist, or this token cannot see it — a project owned by a team needs the team's id.`, 404, 'config');
102
+ }
103
+ return new VercelError(message, response.status, 'error');
104
+ }
105
+
106
+ export interface VercelResponse<T> {
107
+ data: T;
108
+ rateLimit: DeployRateLimit | null;
109
+ }
110
+
111
+ export interface VercelRequestOptions {
112
+ method?: 'GET' | 'POST' | 'PATCH' | 'DELETE';
113
+ body?: unknown;
114
+ /**
115
+ * Appended verbatim.
116
+ *
117
+ * `teamId` belongs here on nearly every call — but NOT on all of them:
118
+ * `/v1/integrations/git-namespaces` rejects it with a 400, because
119
+ * namespaces belong to the signed-in user rather than to a team.
120
+ */
121
+ query?: Record<string, string | number | undefined | null>;
122
+ /** Overrides the budget chosen from the method. */
123
+ timeoutMs?: number;
124
+ }
125
+
126
+ function buildUrl(path: string, query?: VercelRequestOptions['query']): string {
127
+ const url = new URL(path.startsWith('http') ? path : `${VERCEL_API_BASE}${path}`);
128
+ for (const [key, value] of Object.entries(query ?? {})) {
129
+ if (value === undefined || value === null || value === '') continue;
130
+ url.searchParams.set(key, String(value));
131
+ }
132
+ return url.toString();
133
+ }
134
+
135
+ export async function vercelRequest<T>(
136
+ credentials: VercelCredentials,
137
+ path: string,
138
+ options: VercelRequestOptions = {}
139
+ ): Promise<VercelResponse<T>> {
140
+ const method = options.method ?? 'GET';
141
+ const timeout = options.timeoutMs ?? (method === 'GET' ? READ_TIMEOUT_MS : MUTATION_TIMEOUT_MS);
142
+ const headers: Record<string, string> = {
143
+ Authorization: `Bearer ${credentials.token}`,
144
+ 'User-Agent': 'clopen'
145
+ };
146
+ if (options.body !== undefined) headers['Content-Type'] = 'application/json';
147
+
148
+ let response: Response;
149
+ try {
150
+ response = await fetch(buildUrl(path, options.query), {
151
+ method,
152
+ headers,
153
+ ...(options.body !== undefined && { body: JSON.stringify(options.body) }),
154
+ signal: AbortSignal.timeout(timeout)
155
+ });
156
+ } catch (error) {
157
+ const detail = error instanceof Error ? error.message : String(error);
158
+ throw new VercelError(`Could not reach Vercel: ${detail}`, 0, 'error');
159
+ }
160
+
161
+ const rateLimit = parseRateLimit(response.headers);
162
+ if (!response.ok) throw await toError(response);
163
+
164
+ // An empty body is a legitimate success on the action paths.
165
+ const text = await response.text();
166
+ return { data: (text ? JSON.parse(text) : null) as T, rateLimit };
167
+ }
168
+
169
+ /**
170
+ * Open the build-log stream.
171
+ *
172
+ * Returned raw rather than parsed because the caller pumps it: `follow=1` makes
173
+ * this response never end on its own, so it cannot go through `vercelRequest`,
174
+ * which reads the body to completion. The abort signal is the only way to close
175
+ * it, which is why it is required rather than optional.
176
+ */
177
+ export async function vercelEventStream(
178
+ credentials: VercelCredentials,
179
+ deploymentId: string,
180
+ options: { teamId: string | null; signal: AbortSignal }
181
+ ): Promise<Response> {
182
+ const url = buildUrl(`/v3/deployments/${encodeURIComponent(deploymentId)}/events`, {
183
+ follow: 1,
184
+ builds: 1,
185
+ limit: -1,
186
+ teamId: options.teamId ?? undefined
187
+ });
188
+
189
+ const response = await fetch(url, {
190
+ headers: {
191
+ Authorization: `Bearer ${credentials.token}`,
192
+ // The endpoint answers with a JSON array when it is not following and
193
+ // a newline-delimited stream when it is. Asking for the stream shape
194
+ // explicitly keeps the parser honest about which one arrived.
195
+ Accept: 'application/stream+json',
196
+ 'User-Agent': 'clopen'
197
+ },
198
+ signal: options.signal
199
+ });
200
+
201
+ if (!response.ok) throw await toError(response);
202
+ return response;
203
+ }