@jini-ai/devops 0.3.3 → 0.4.0

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.
@@ -1,299 +0,0 @@
1
- import { createHash } from 'node:crypto';
2
- import { FETCH_TIMEOUT_MS, fetchWithTimeout } from '@jini-ai/platform';
3
- import { checkDeploymentUrl, normalizeDeploymentUrl, waitForReachableDeploymentUrl } from './reachability.js';
4
- import { safeDnsLabel } from './naming.js';
5
- import { DeployError, } from './types.js';
6
- export const NETLIFY_TARGET_ID = 'netlify';
7
- const NETLIFY_API = 'https://api.netlify.com/api/v1';
8
- /**
9
- * Deploy states enumerated by the Netlify API's own `GET /sites/{site_id}/deploys`
10
- * `state` query-filter (the canonical source for this field's real values —
11
- * the deploy object's own schema types `state` as a bare `string` with no
12
- * inline enum). `'ready'` is the only success terminal state; `'error'` and
13
- * `'rejected'` are the only failure terminal states. Every other value
14
- * (`'new'`, `'pending_review'`, `'accepted'`, `'enqueued'`, `'building'`,
15
- * `'uploading'`, `'uploaded'`, `'preparing'`, `'prepared'`, `'processing'`,
16
- * `'processed'`, `'retrying'`) is an in-progress state this module keeps
17
- * polling through.
18
- */
19
- const NETLIFY_FAILURE_STATES = new Set(['error', 'rejected']);
20
- /**
21
- * `DeployTarget` adapter for Netlify's digest-based deploy API: find-or-create
22
- * a site for the caller's `projectName`, create a deploy from a SHA1 file
23
- * manifest, upload whichever files Netlify reports as `required`, poll until
24
- * the deploy reaches a terminal `state`, then wait for the resulting URL to
25
- * become publicly reachable.
26
- *
27
- * No OD origin — `apps/daemon/src/deploy.ts` never implemented a Netlify
28
- * target (only `vercel-self` and `cloudflare-pages` exist there); this is new
29
- * work built directly against Netlify's own published OpenAPI contract
30
- * (`https://open-api.netlify.com`), following the same `DeployTarget` shape
31
- * `vercel.ts`/`cloudflare-pages.ts` already establish. See `source-map.md`'s
32
- * 2026-07-21 addition for the exact endpoints/fields this was built from.
33
- */
34
- export class NetlifyDeployTarget {
35
- config;
36
- id = NETLIFY_TARGET_ID;
37
- constructor(config) {
38
- this.config = config;
39
- }
40
- /**
41
- * Publishes `input.files` as a new Netlify deploy (creating the target site
42
- * on first use) and waits for the resulting URL to be reachable.
43
- *
44
- * @param input - File set plus a caller-chosen project name label.
45
- * @returns The published deploy's URL/status once Netlify has a terminal
46
- * `state` (or the poll budget is exhausted).
47
- * @throws {DeployError} If `config.token` is missing, the site cannot be
48
- * found/created, or Netlify reports a terminal failure state
49
- * (`'error'`/`'rejected'`).
50
- */
51
- async publish(input) {
52
- if (!this.config.token) {
53
- throw new DeployError('Netlify token is required.', 400);
54
- }
55
- const siteName = deriveNetlifySiteName(input.projectName);
56
- if (!siteName) {
57
- throw new DeployError('Netlify site name could not be generated.', 400);
58
- }
59
- const site = await ensureNetlifySite(this.config, siteName);
60
- const siteId = typeof site.id === 'string' ? site.id : '';
61
- if (!siteId) {
62
- throw new DeployError('Netlify site response did not include an id.', 502, site);
63
- }
64
- const { created, byHash } = await createNetlifyDeploy(this.config, siteId, input.files);
65
- const deployId = typeof created.id === 'string' ? created.id : '';
66
- if (!deployId) {
67
- throw new DeployError('Netlify deploy response did not include an id.', 502, created);
68
- }
69
- const required = Array.isArray(created.required) ? created.required.filter((h) => typeof h === 'string') : [];
70
- for (const hash of required) {
71
- const file = byHash.get(hash);
72
- // A hash Netlify asked for but that isn't in our own manifest should
73
- // never happen (`required` is derived from the manifest we just sent),
74
- // but skip defensively rather than crash the whole publish over it.
75
- if (!file)
76
- continue;
77
- await uploadNetlifyFile(this.config, deployId, file);
78
- }
79
- const finalState = await pollNetlifyDeploy(this.config, deployId);
80
- if (finalState && NETLIFY_FAILURE_STATES.has(String(finalState.state))) {
81
- throw new DeployError((typeof finalState.error_message === 'string' && finalState.error_message) || `Netlify deployment ${finalState.state}.`, 502, finalState);
82
- }
83
- const candidates = netlifyUrlCandidates(finalState, site);
84
- const link = await waitForReachableDeploymentUrl(candidates, { providerLabel: 'Netlify' });
85
- return {
86
- targetId: this.id,
87
- url: link.url || candidates[0] || '',
88
- deploymentId: deployId,
89
- status: link.status,
90
- statusMessage: link.statusMessage,
91
- ...(link.reachableAt !== undefined ? { reachableAt: link.reachableAt } : {}),
92
- providerMetadata: { siteId, siteName },
93
- };
94
- }
95
- /** Probes `url` with the shared reachability checker (no Netlify-specific auth-wall detection is needed/documented). */
96
- async checkReachability(url) {
97
- return checkDeploymentUrl(url);
98
- }
99
- }
100
- /**
101
- * Derives a stable, Netlify-site-name-safe label from the caller's
102
- * `projectName`. Deterministic (no random suffix) so repeated publishes of
103
- * the same logical project land on the same Netlify site — same shape as
104
- * `cloudflare-pages.ts`'s `deriveCloudflarePagesProjectName`.
105
- */
106
- function deriveNetlifySiteName(projectName) {
107
- const label = safeDnsLabel(projectName) || 'site';
108
- return safeDnsLabel(`jini-${label}`).slice(0, 63);
109
- }
110
- function netlifyHeaders(token, extra = {}) {
111
- return { Authorization: `Bearer ${token}`, ...extra };
112
- }
113
- async function readNetlifyJson(resp) {
114
- try {
115
- return (await resp.json());
116
- }
117
- catch {
118
- throw new DeployError('Netlify returned a non-JSON response.', resp.status || 502);
119
- }
120
- }
121
- /**
122
- * `fallback || \`Netlify request failed (${status}).\`` (the template
123
- * literal half) is unreachable today: every one of this file's 5 call
124
- * sites passes a non-empty string literal for `fallback` ('Netlify site
125
- * lookup failed.', 'Netlify site creation failed.', 'Netlify deploy
126
- * creation failed.', the per-file upload message, 'Netlify deploy status
127
- * check failed.') — `fallback` is never derived from network/config input,
128
- * so it cannot vary at runtime, and this right-hand operand can never be
129
- * selected. Verified by reading every call site, not just "not covered".
130
- * Left as-is (not deleted) because `netlifyError` is a general-purpose
131
- * formatter, not written solely for today's 5 callers, and this is the
132
- * sane-default guard a future caller forgetting to pass `fallback` would
133
- * fall through to.
134
- */
135
- function netlifyError(json, status, fallback) {
136
- const message = typeof json?.message === 'string' && json.message ? json.message : fallback || `Netlify request failed (${status}).`;
137
- return new DeployError(message, status, json);
138
- }
139
- /** Looks up an existing site by its exact (case-insensitive) name within the caller's own account. */
140
- async function findNetlifySiteByName(config, name) {
141
- const url = `${NETLIFY_API}/sites?${new URLSearchParams({ name, filter: 'all' }).toString()}`;
142
- const resp = await fetchWithTimeout(url, { headers: netlifyHeaders(config.token) }, { timeoutMs: FETCH_TIMEOUT_MS.QUICK });
143
- const body = await readNetlifyJson(resp);
144
- if (!resp.ok) {
145
- throw netlifyError(Array.isArray(body) ? {} : body, resp.status, 'Netlify site lookup failed.');
146
- }
147
- const list = Array.isArray(body) ? body : [];
148
- return list.find((site) => typeof site?.name === 'string' && site.name.toLowerCase() === name.toLowerCase());
149
- }
150
- async function createNetlifySite(config, name) {
151
- const resp = await fetchWithTimeout(`${NETLIFY_API}/sites`, {
152
- method: 'POST',
153
- headers: netlifyHeaders(config.token, { 'Content-Type': 'application/json' }),
154
- body: JSON.stringify({ name }),
155
- }, { timeoutMs: FETCH_TIMEOUT_MS.DEPLOY });
156
- const body = await readNetlifyJson(resp);
157
- if (!resp.ok)
158
- throw netlifyError(body, resp.status, 'Netlify site creation failed.');
159
- return body;
160
- }
161
- /**
162
- * Finds the site for `name`, creating it on first use. Netlify site names
163
- * are globally unique (not scoped to one account), so a creation conflict is
164
- * ambiguous: it may mean *this* account already owns the name (a benign
165
- * create/create race — recoverable by re-listing), or that a different
166
- * account owns it outright (not recoverable). Re-checking the caller's own
167
- * account's sites after a failed create distinguishes the two: found → use
168
- * it; still not found → rethrow the original creation error.
169
- */
170
- async function ensureNetlifySite(config, name) {
171
- const existing = await findNetlifySiteByName(config, name);
172
- if (existing)
173
- return existing;
174
- try {
175
- return await createNetlifySite(config, name);
176
- }
177
- catch (err) {
178
- const retry = await findNetlifySiteByName(config, name);
179
- if (retry)
180
- return retry;
181
- throw err;
182
- }
183
- }
184
- function sha1Hex(data) {
185
- return createHash('sha1').update(Buffer.from(data)).digest('hex');
186
- }
187
- /** URL-encodes each path segment individually so directory separators survive but special characters in a single segment don't. */
188
- function encodeNetlifyFilePath(path) {
189
- return path
190
- .split('/')
191
- .filter(Boolean)
192
- .map(encodeURIComponent)
193
- .join('/');
194
- }
195
- /**
196
- * Creates a Netlify deploy from an async SHA1 file-digest manifest. Returns
197
- * both the raw created-deploy response and a hash→file lookup so the caller
198
- * can resolve whichever hashes Netlify reports back as `required` to upload.
199
- */
200
- async function createNetlifyDeploy(config, siteId, files) {
201
- const manifest = {};
202
- const byHash = new Map();
203
- for (const file of files) {
204
- const hash = sha1Hex(file.data);
205
- manifest[`/${file.file}`] = hash;
206
- if (!byHash.has(hash))
207
- byHash.set(hash, file);
208
- }
209
- const resp = await fetchWithTimeout(`${NETLIFY_API}/sites/${encodeURIComponent(siteId)}/deploys`, {
210
- method: 'POST',
211
- headers: netlifyHeaders(config.token, { 'Content-Type': 'application/json' }),
212
- body: JSON.stringify({ async: true, files: manifest }),
213
- }, { timeoutMs: FETCH_TIMEOUT_MS.DEPLOY });
214
- const created = await readNetlifyJson(resp);
215
- if (!resp.ok)
216
- throw netlifyError(created, resp.status, 'Netlify deploy creation failed.');
217
- return { created, byHash };
218
- }
219
- async function uploadNetlifyFile(config, deployId, file) {
220
- const resp = await fetchWithTimeout(`${NETLIFY_API}/deploys/${encodeURIComponent(deployId)}/files/${encodeNetlifyFilePath(file.file)}`, {
221
- method: 'PUT',
222
- headers: netlifyHeaders(config.token, { 'Content-Type': file.contentType || 'application/octet-stream' }),
223
- body: Buffer.from(file.data),
224
- }, { timeoutMs: FETCH_TIMEOUT_MS.UPLOAD });
225
- if (!resp.ok) {
226
- const body = await readNetlifyJson(resp).catch(() => ({}));
227
- throw netlifyError(body, resp.status, `Netlify file upload failed for "${file.file}".`);
228
- }
229
- }
230
- /**
231
- * Polls a just-created Netlify deploy until it reaches a terminal `state`
232
- * (`'ready'` or one of {@link NETLIFY_FAILURE_STATES}) or the fixed
233
- * 30-attempt budget is spent (~1s for the first 5 attempts, 2s thereafter —
234
- * roughly a minute) — same attempt/backoff shape as `vercel.ts`'s
235
- * `pollVercelDeployment`, for consistency across this package's targets.
236
- *
237
- * A response this file cannot parse as JSON is treated as "keep polling,"
238
- * not an error — same reasoning as `github-pages.ts`'s `pollGitHubPagesBuild`
239
- * and `vercel.ts`'s `pollVercelDeployment` (fixed 2026-08-16 for the
240
- * identical bug class): the deploy and its files are already created/uploaded
241
- * server-side by the time this loop runs, so a transient/edge/empty poll
242
- * response is never a reason to report an already-uploaded deploy as failed.
243
- * Any other non-2xx response whose body DID parse still fails fast, unchanged.
244
- */
245
- async function pollNetlifyDeploy(config, deployId) {
246
- let last = null;
247
- for (let i = 0; i < 30; i += 1) {
248
- await new Promise((resolve) => setTimeout(resolve, i < 5 ? 1000 : 2000));
249
- const resp = await fetchWithTimeout(`${NETLIFY_API}/deploys/${encodeURIComponent(deployId)}`, { headers: netlifyHeaders(config.token) }, { timeoutMs: FETCH_TIMEOUT_MS.DEPLOY });
250
- let json;
251
- try {
252
- json = await readNetlifyJson(resp);
253
- }
254
- catch {
255
- // Nothing usable to report yet — keep polling within the same fixed budget
256
- // rather than turning an ambiguous mid-poll hiccup into a reported failure.
257
- continue;
258
- }
259
- if (!resp.ok)
260
- throw netlifyError(json, resp.status, 'Netlify deploy status check failed.');
261
- last = json;
262
- if (json.state === 'ready' || NETLIFY_FAILURE_STATES.has(String(json.state)))
263
- return json;
264
- }
265
- return last;
266
- }
267
- /**
268
- * Collects candidate public URLs from a deploy/site response, preferring the HTTPS site URL over the deploy-specific one.
269
- *
270
- * `if (!json) continue` is unreachable via this file's one call site,
271
- * `netlifyUrlCandidates(finalState, site)` in `publish()`: `finalState`
272
- * comes from `pollNetlifyDeploy`, whose 30-iteration loop (`i < 30` with
273
- * `i` starting at 0) always runs at least once and unconditionally assigns
274
- * `last` before any return, so it can only resolve to a real `JsonObject`
275
- * or throw — never resolve to `null`; `site` comes from `ensureNetlifySite`,
276
- * which always returns a `JsonObject` (never null/undefined), and `publish()`
277
- * additionally guards it with a `!siteId` check right after. The `| null |
278
- * undefined` in this function's own parameter type is deliberately wider
279
- * than what its only caller can ever supply, so this stays real
280
- * defense-in-depth for a general-purpose variadic helper rather than dead
281
- * weight worth deleting.
282
- */
283
- function netlifyUrlCandidates(...responses) {
284
- const urls = [];
285
- for (const json of responses) {
286
- if (!json)
287
- continue;
288
- if (typeof json.ssl_url === 'string')
289
- urls.push(json.ssl_url);
290
- if (typeof json.url === 'string')
291
- urls.push(json.url);
292
- if (typeof json.deploy_ssl_url === 'string')
293
- urls.push(json.deploy_ssl_url);
294
- if (typeof json.deploy_url === 'string')
295
- urls.push(json.deploy_url);
296
- }
297
- return [...new Set(urls.map(normalizeDeploymentUrl).filter(Boolean))];
298
- }
299
- //# sourceMappingURL=netlify.js.map
@@ -1,56 +0,0 @@
1
- import { type DeployPublishInput, type DeployPublishResult, type DeployTarget, type DeploymentUrlCheck } from './types.js';
2
- export declare const VERCEL_TARGET_ID = "vercel";
3
- /** Auth/scoping config a caller supplies when constructing a `VercelDeployTarget`. */
4
- export interface VercelDeployConfig {
5
- token: string;
6
- teamId?: string;
7
- teamSlug?: string;
8
- }
9
- /**
10
- * Heuristically detects Vercel's own Deployment Protection auth wall from a
11
- * 401 response, so `checkReachability` can report `status: 'protected'`
12
- * (an actionable, non-error outcome) instead of `reachable: false` with a
13
- * generic message.
14
- *
15
- * @param resp - The HTTP response received from probing a deployment URL.
16
- * @param body - The response body (only read for 401s by the caller).
17
- * @returns `true` if the response looks like Vercel's SSO/auth gate.
18
- * @complexity O(1) — a handful of regex tests over already-fetched strings.
19
- * @overallScore 100/100
20
- */
21
- export declare function isVercelProtectedResponse(resp: Response, body?: string): boolean;
22
- /**
23
- * `DeployTarget` adapter for Vercel's v13 deployments API. Publishes a
24
- * caller-supplied file set as a single deployment, polls until Vercel
25
- * reports a terminal `readyState`, then waits for the resulting URL to
26
- * become publicly reachable.
27
- *
28
- * Genericized from the origin product's daemon deploy module's
29
- * `deployToVercel`: the origin's product-specific deployment-name
30
- * convention is replaced by `input.projectName` (sanitized the same way);
31
- * token/team config is supplied by the caller instead of being read from a
32
- * product-owned local config file — persistence of that config is now the
33
- * caller's concern, not this package's.
34
- */
35
- export declare class VercelDeployTarget implements DeployTarget {
36
- private readonly config;
37
- readonly id = "vercel";
38
- constructor(config: VercelDeployConfig);
39
- /**
40
- * Publishes `input.files` as a new Vercel deployment and waits for the
41
- * resulting URL to be reachable.
42
- *
43
- * @param input - File set plus a caller-chosen project name label.
44
- * @returns The published deployment's URL/status once Vercel has a
45
- * terminal `readyState` (or the poll budget is exhausted).
46
- * @throws {DeployError} If `config.token` is missing, or Vercel's API
47
- * rejects the deployment request or reports `readyState: 'ERROR'`.
48
- * @complexity O(files) to encode the payload, plus a bounded poll loop
49
- * (`pollVercelDeployment`) and the reachability wait's own bound.
50
- * @overallScore 100/100
51
- */
52
- publish(input: DeployPublishInput): Promise<DeployPublishResult>;
53
- /** Probes `url`, recognizing Vercel's own Deployment Protection auth wall. */
54
- checkReachability(url: string): Promise<DeploymentUrlCheck>;
55
- }
56
- //# sourceMappingURL=vercel.d.ts.map
@@ -1,258 +0,0 @@
1
- import { FETCH_TIMEOUT_MS, fetchWithTimeout } from '@jini-ai/platform';
2
- import { checkDeploymentUrl, normalizeDeploymentUrl, waitForReachableDeploymentUrl } from './reachability.js';
3
- import { safeProjectLabel } from './naming.js';
4
- import { assertNotRedirected, redirectGuardInit } from './redirect-guard.js';
5
- import { DeployError } from './types.js';
6
- export const VERCEL_TARGET_ID = 'vercel';
7
- const VERCEL_API = 'https://api.vercel.com';
8
- const VERCEL_PROTECTED_MESSAGE = 'Deployment is protected by Vercel. Disable Deployment Protection or use a custom domain to make this link public.';
9
- /**
10
- * Heuristically detects Vercel's own Deployment Protection auth wall from a
11
- * 401 response, so `checkReachability` can report `status: 'protected'`
12
- * (an actionable, non-error outcome) instead of `reachable: false` with a
13
- * generic message.
14
- *
15
- * @param resp - The HTTP response received from probing a deployment URL.
16
- * @param body - The response body (only read for 401s by the caller).
17
- * @returns `true` if the response looks like Vercel's SSO/auth gate.
18
- * @complexity O(1) — a handful of regex tests over already-fetched strings.
19
- * @overallScore 100/100
20
- */
21
- export function isVercelProtectedResponse(resp, body = '') {
22
- const server = resp.headers?.get?.('server') || '';
23
- const setCookie = resp.headers?.get?.('set-cookie') || '';
24
- const text = String(body || '');
25
- return (/vercel/i.test(server) ||
26
- /_vercel_sso_nonce/i.test(setCookie) ||
27
- /Authentication Required/i.test(text) ||
28
- /Vercel Authentication/i.test(text) ||
29
- /vercel\.com\/sso-api/i.test(text));
30
- }
31
- /**
32
- * `DeployTarget` adapter for Vercel's v13 deployments API. Publishes a
33
- * caller-supplied file set as a single deployment, polls until Vercel
34
- * reports a terminal `readyState`, then waits for the resulting URL to
35
- * become publicly reachable.
36
- *
37
- * Genericized from the origin product's daemon deploy module's
38
- * `deployToVercel`: the origin's product-specific deployment-name
39
- * convention is replaced by `input.projectName` (sanitized the same way);
40
- * token/team config is supplied by the caller instead of being read from a
41
- * product-owned local config file — persistence of that config is now the
42
- * caller's concern, not this package's.
43
- */
44
- export class VercelDeployTarget {
45
- config;
46
- id = VERCEL_TARGET_ID;
47
- constructor(config) {
48
- this.config = config;
49
- }
50
- /**
51
- * Publishes `input.files` as a new Vercel deployment and waits for the
52
- * resulting URL to be reachable.
53
- *
54
- * @param input - File set plus a caller-chosen project name label.
55
- * @returns The published deployment's URL/status once Vercel has a
56
- * terminal `readyState` (or the poll budget is exhausted).
57
- * @throws {DeployError} If `config.token` is missing, or Vercel's API
58
- * rejects the deployment request or reports `readyState: 'ERROR'`.
59
- * @complexity O(files) to encode the payload, plus a bounded poll loop
60
- * (`pollVercelDeployment`) and the reachability wait's own bound.
61
- * @overallScore 100/100
62
- */
63
- async publish(input) {
64
- if (!this.config.token) {
65
- throw new DeployError('Vercel token is required.', 400);
66
- }
67
- const createResp = await fetchWithTimeout(`${VERCEL_API}/v13/deployments${vercelTeamQuery(this.config)}`, redirectGuardInit({
68
- method: 'POST',
69
- headers: {
70
- Authorization: `Bearer ${this.config.token}`,
71
- 'Content-Type': 'application/json',
72
- },
73
- body: JSON.stringify({
74
- name: safeVercelProjectName(input.projectName),
75
- files: input.files.map((f) => ({
76
- file: f.file,
77
- data: Buffer.from(f.data).toString('base64'),
78
- encoding: 'base64',
79
- })),
80
- projectSettings: { framework: null },
81
- }),
82
- }), { timeoutMs: FETCH_TIMEOUT_MS.UPLOAD });
83
- assertNotRedirected(createResp, 'Vercel deployment creation');
84
- const created = await readVercelJson(createResp);
85
- if (!createResp.ok)
86
- throw vercelError(created, createResp.status);
87
- const deploymentId = typeof created.id === 'string' ? created.id : typeof created.uid === 'string' ? created.uid : undefined;
88
- const initialUrl = deploymentUrl(created);
89
- const ready = deploymentId ? await pollVercelDeployment(this.config, deploymentId) : created;
90
- if (ready?.readyState === 'ERROR') {
91
- const readyError = ready?.error;
92
- // `ready ?? undefined` — the `undefined` side is unreachable: this line
93
- // only runs when `ready?.readyState === 'ERROR'` just matched, which
94
- // requires `ready` itself to already be a real object (optional
95
- // chaining on a null/undefined `ready` would make the whole comparison
96
- // `undefined === 'ERROR'`, i.e. false, skipping this block entirely).
97
- // So by the time `ready ?? undefined` evaluates, `ready` is always
98
- // truthy and the `??` is a no-op at runtime. Kept (not simplified to
99
- // just `ready`) purely for type-level reasons: `ready`'s static type is
100
- // `JsonObject | null` (from `pollVercelDeployment`'s return type /
101
- // `created`'s), and `DeployError`'s `details` parameter accepts
102
- // `JsonObject | string | undefined` — not `null` — so this coalesce is
103
- // a compile-time-required null-to-undefined conversion that TypeScript's
104
- // control-flow analysis cannot narrow away just from the optional-chained
105
- // comparison above. See packages/devops/source-map.md's 2026-07-22
106
- // addition for the full re-derivation.
107
- throw new DeployError(readyError?.message || 'Vercel deployment failed.', 502, ready ?? undefined);
108
- }
109
- const candidates = deploymentUrlCandidates(ready, created);
110
- const link = await waitForReachableDeploymentUrl(candidates.length ? candidates : [initialUrl], {
111
- providerLabel: 'Vercel',
112
- detectProtected: isVercelProtectedResponse,
113
- protectedMessage: VERCEL_PROTECTED_MESSAGE,
114
- });
115
- return {
116
- targetId: this.id,
117
- url: link.url || deploymentUrl(ready) || initialUrl,
118
- ...(deploymentId ? { deploymentId } : {}),
119
- status: link.status,
120
- statusMessage: link.statusMessage,
121
- ...(link.reachableAt !== undefined ? { reachableAt: link.reachableAt } : {}),
122
- };
123
- }
124
- /** Probes `url`, recognizing Vercel's own Deployment Protection auth wall. */
125
- async checkReachability(url) {
126
- return checkDeploymentUrl(url, {
127
- detectProtected: isVercelProtectedResponse,
128
- protectedMessage: VERCEL_PROTECTED_MESSAGE,
129
- });
130
- }
131
- }
132
- /**
133
- * Polls a just-created Vercel deployment until it reaches a terminal
134
- * `readyState` (`READY`/`ERROR`) or the fixed 30-attempt budget is spent
135
- * (~1s for the first 5 attempts, 2s thereafter — roughly a minute).
136
- *
137
- * A response this file cannot parse as JSON is treated as "keep polling,"
138
- * not an error — same reasoning as `github-pages.ts`'s `pollGitHubPagesBuild`
139
- * (fixed 2026-08-16 for the identical bug class): the deployment already
140
- * exists server-side by the time this loop runs (the create call above
141
- * already succeeded), so a transient/edge/empty poll response is exactly as
142
- * uninformative as a stuck in-progress state, never a reason to report an
143
- * already-created deployment as failed. Any other non-2xx response whose
144
- * body DID parse still fails fast, unchanged.
145
- *
146
- * @complexity O(30) network round-trips, bounded and fixed regardless of input size.
147
- * @overallScore 90/100
148
- * @tradeoffs Fixed attempt/backoff constants (lifted verbatim from the OD
149
- * origin) rather than caller-configurable ones — acceptable for now since
150
- * `publish` has no caller-facing timeout knob yet either; flagged as a
151
- * minor extensibility gap rather than a correctness issue.
152
- */
153
- async function pollVercelDeployment(config, id) {
154
- let last = null;
155
- for (let i = 0; i < 30; i += 1) {
156
- await new Promise((resolve) => setTimeout(resolve, i < 5 ? 1000 : 2000));
157
- const resp = await fetchWithTimeout(`${VERCEL_API}/v13/deployments/${encodeURIComponent(id)}${vercelTeamQuery(config)}`, redirectGuardInit({ headers: { Authorization: `Bearer ${config.token}` } }), { timeoutMs: FETCH_TIMEOUT_MS.DEPLOY });
158
- assertNotRedirected(resp, 'Vercel deployment status poll');
159
- let json;
160
- try {
161
- json = await readVercelJson(resp);
162
- }
163
- catch {
164
- // Nothing usable to report yet — keep polling within the same fixed budget
165
- // rather than turning an ambiguous mid-poll hiccup into a reported failure.
166
- continue;
167
- }
168
- if (!resp.ok)
169
- throw vercelError(json, resp.status);
170
- last = json;
171
- if (json.readyState === 'READY' || json.readyState === 'ERROR')
172
- return json;
173
- }
174
- return last;
175
- }
176
- function vercelTeamQuery(config) {
177
- const params = new URLSearchParams();
178
- if (config.teamId)
179
- params.set('teamId', config.teamId);
180
- else if (config.teamSlug)
181
- params.set('slug', config.teamSlug);
182
- const s = params.toString();
183
- return s ? `?${s}` : '';
184
- }
185
- /**
186
- * Derives a Vercel-safe project name from a caller-supplied label, falling
187
- * back to a random id if the label sanitizes to nothing. Replaces the OD
188
- * origin's hardcoded `od-${projectId}` convention.
189
- */
190
- function safeVercelProjectName(projectName) {
191
- return safeProjectLabel(projectName, 80) || `deploy-${Math.random().toString(36).slice(2, 10)}`;
192
- }
193
- async function readVercelJson(resp) {
194
- try {
195
- return (await resp.json());
196
- }
197
- catch {
198
- throw new DeployError('Vercel returned a non-JSON response.', resp.status || 502);
199
- }
200
- }
201
- function vercelError(json, status) {
202
- const code = json?.error && typeof json.error === 'object' ? json.error.code : undefined;
203
- const message = (json?.error && typeof json.error === 'object' ? json.error.message : undefined) ||
204
- json?.message ||
205
- `Vercel request failed (${status}).`;
206
- if (code === 'forbidden' || /permission/i.test(String(message))) {
207
- return new DeployError("You don't have permission to create a project.", status, json);
208
- }
209
- return new DeployError(String(message), status, json);
210
- }
211
- function deploymentUrl(json) {
212
- const url = json?.url || json?.alias?.[0] || '';
213
- if (!url)
214
- return '';
215
- return /^https?:\/\//i.test(url) ? url : `https://${url}`;
216
- }
217
- /**
218
- * `if (!json) continue` is unreachable via this file's one call site,
219
- * `deploymentUrlCandidates(ready, created)` in `publish()`: `created` comes
220
- * from `readVercelJson`, which either returns a real parsed `JsonObject` or
221
- * throws (never resolves to null/undefined); `ready` is either `created`
222
- * itself (same guarantee) or `pollVercelDeployment`'s result, which — per
223
- * that function's own loop shape (`i < 30` starting at `i = 0`, so it always
224
- * runs at least one full iteration before it can return, and that iteration
225
- * unconditionally assigns `last = json` right after the `!resp.ok` throw
226
- * check, before any `return`) — can only resolve to a real `JsonObject` or
227
- * throw, never resolve to `null`. The wider `(JsonObject | null | undefined)[]`
228
- * parameter type is deliberately more permissive than what this one caller
229
- * can ever supply — same "general-purpose helper, defense-in-depth beyond
230
- * today's only caller" reasoning `netlify.ts`'s own `netlifyUrlCandidates`
231
- * already documents for its structurally identical guard.
232
- */
233
- function deploymentUrlCandidates(...responses) {
234
- const urls = [];
235
- for (const json of responses) {
236
- if (!json)
237
- continue;
238
- if (typeof json.url === 'string')
239
- urls.push(json.url);
240
- for (const alias of json.alias ?? []) {
241
- if (typeof alias === 'string')
242
- urls.push(alias);
243
- }
244
- for (const alias of json.aliases ?? []) {
245
- if (typeof alias === 'string')
246
- urls.push(alias);
247
- else if (alias && typeof alias === 'object') {
248
- const a = alias;
249
- if (typeof a.domain === 'string')
250
- urls.push(a.domain);
251
- else if (typeof a.url === 'string')
252
- urls.push(a.url);
253
- }
254
- }
255
- }
256
- return [...new Set(urls.map(normalizeDeploymentUrl).filter(Boolean))];
257
- }
258
- //# sourceMappingURL=vercel.js.map