@jini-ai/devops 0.3.2 → 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.
- package/README.md +9 -2
- package/dist/deploy/host-kit.d.ts +116 -0
- package/dist/deploy/host-kit.js +2 -0
- package/dist/deploy/index.d.ts +1 -4
- package/dist/deploy/index.js +1 -4
- package/dist/deploy/naming.d.ts +1 -2
- package/dist/deploy/naming.js +1 -2
- package/dist/deploy/reachability.d.ts +5 -6
- package/dist/deploy/reachability.js +2 -2
- package/dist/deploy/redirect-guard.d.ts +8 -9
- package/dist/deploy/redirect-guard.js +8 -9
- package/dist/deploy/tokens.d.ts +3 -3
- package/dist/deploy/tokens.js +3 -3
- package/dist/deploy/tool.d.ts +3 -3
- package/dist/deploy/tool.js +4 -4
- package/dist/deploy/types.d.ts +13 -5
- package/dist/deploy/types.js +1 -1
- package/package.json +2 -2
- package/dist/deploy/cloudflare-pages.d.ts +0 -105
- package/dist/deploy/cloudflare-pages.js +0 -943
- package/dist/deploy/github-pages.d.ts +0 -62
- package/dist/deploy/github-pages.js +0 -373
- package/dist/deploy/netlify.d.ts +0 -40
- package/dist/deploy/netlify.js +0 -299
- package/dist/deploy/vercel.d.ts +0 -56
- package/dist/deploy/vercel.js +0 -258
|
@@ -1,943 +0,0 @@
|
|
|
1
|
-
import { createHash } from 'node:crypto';
|
|
2
|
-
import { FETCH_TIMEOUT_MS, fetchWithTimeout } from '@jini-ai/platform';
|
|
3
|
-
import { checkDeploymentUrl, waitForReachableDeploymentUrl } from './reachability.js';
|
|
4
|
-
import { safeDnsLabel } from './naming.js';
|
|
5
|
-
import { DeployError, } from './types.js';
|
|
6
|
-
export const CLOUDFLARE_PAGES_TARGET_ID = 'cloudflare-pages';
|
|
7
|
-
const CLOUDFLARE_API = 'https://api.cloudflare.com/client/v4';
|
|
8
|
-
const CLOUDFLARE_API_PAGE_SIZE = 100;
|
|
9
|
-
const CLOUDFLARE_API_MAX_PAGES = 100;
|
|
10
|
-
export const CLOUDFLARE_PAGES_ASSET_UPLOAD_MAX_FILES = 100;
|
|
11
|
-
export const CLOUDFLARE_PAGES_ASSET_UPLOAD_MAX_BODY_BYTES = 75 * 1024 * 1024;
|
|
12
|
-
export const CLOUDFLARE_PAGES_ASSET_MAX_BYTES = 25 * 1024 * 1024;
|
|
13
|
-
function formatMib(bytes) {
|
|
14
|
-
return `${(bytes / (1024 * 1024)).toFixed(2)} MiB`;
|
|
15
|
-
}
|
|
16
|
-
/**
|
|
17
|
-
* Deterministic content hash used purely as Cloudflare Pages' per-asset
|
|
18
|
-
* dedup key (the direct-upload protocol needs a stable 32-hex-char key per
|
|
19
|
-
* file, not a specific algorithm). Swapped from the OD origin's
|
|
20
|
-
* `blake3-wasm` to Node's built-in `crypto` so this package carries no
|
|
21
|
-
* native/WASM dependency — see `source-map.md`.
|
|
22
|
-
*/
|
|
23
|
-
export function cloudflarePagesAssetHash(file) {
|
|
24
|
-
const data = Buffer.from(file.data);
|
|
25
|
-
const extension = file.file.includes('.') ? file.file.slice(file.file.lastIndexOf('.') + 1) : '';
|
|
26
|
-
return createHash('sha256').update(`${data.toString('base64')}${extension}`).digest('hex').slice(0, 32);
|
|
27
|
-
}
|
|
28
|
-
/**
|
|
29
|
-
* `value || ''` is unreachable via this function's one call site,
|
|
30
|
-
* `cloudflarePagesDnsMarker`: its first argument is always `config.projectName`
|
|
31
|
-
* (guaranteed non-empty — see `deriveCloudflarePagesProjectName`'s doc), and
|
|
32
|
-
* its second argument is always `pagesTarget || projectName` at that call
|
|
33
|
-
* site — itself unreachable-fallback-guarded the same way (see
|
|
34
|
-
* `cloudflarePagesDnsMarker`'s own doc comment). Kept for the same
|
|
35
|
-
* general-purpose-helper reasoning `netlify.ts`'s `netlifyError` documents.
|
|
36
|
-
*/
|
|
37
|
-
function shortHash(value) {
|
|
38
|
-
return createHash('sha256').update(String(value || '')).digest('hex').slice(0, 12);
|
|
39
|
-
}
|
|
40
|
-
/**
|
|
41
|
-
* Splits a file set into upload batches that respect Cloudflare Pages'
|
|
42
|
-
* per-request file-count and body-size limits.
|
|
43
|
-
*
|
|
44
|
-
* @param files - Files with their pre-computed content hash.
|
|
45
|
-
* @param limits - Overridable file-count/byte-size caps (default to the
|
|
46
|
-
* Cloudflare Pages direct-upload limits).
|
|
47
|
-
* @returns An array of batches; each batch's estimated encoded size stays
|
|
48
|
-
* under `maxBytes` and its length under `maxFiles` (a single
|
|
49
|
-
* larger-than-cap file still gets its own batch rather than being dropped).
|
|
50
|
-
* @complexity O(n) in the number of files.
|
|
51
|
-
* @overallScore 100/100
|
|
52
|
-
*/
|
|
53
|
-
export function chunkCloudflarePagesAssetUploads(files, { maxFiles = CLOUDFLARE_PAGES_ASSET_UPLOAD_MAX_FILES, maxBytes = CLOUDFLARE_PAGES_ASSET_UPLOAD_MAX_BODY_BYTES } = {}) {
|
|
54
|
-
const chunks = [];
|
|
55
|
-
let current = [];
|
|
56
|
-
let currentBytes = 2; // JSON array brackets.
|
|
57
|
-
for (const file of files) {
|
|
58
|
-
const nextBytes = estimateCloudflarePagesAssetUploadPayloadBytes(file);
|
|
59
|
-
const wouldExceedCount = current.length >= maxFiles;
|
|
60
|
-
const wouldExceedBytes = current.length > 0 && currentBytes + nextBytes > maxBytes;
|
|
61
|
-
if (wouldExceedCount || wouldExceedBytes) {
|
|
62
|
-
chunks.push(current);
|
|
63
|
-
current = [];
|
|
64
|
-
currentBytes = 2;
|
|
65
|
-
}
|
|
66
|
-
current.push(file);
|
|
67
|
-
currentBytes += nextBytes;
|
|
68
|
-
}
|
|
69
|
-
if (current.length > 0)
|
|
70
|
-
chunks.push(current);
|
|
71
|
-
return chunks;
|
|
72
|
-
}
|
|
73
|
-
function estimateCloudflarePagesAssetUploadPayloadBytes(file) {
|
|
74
|
-
const data = Buffer.from(file?.data ?? '');
|
|
75
|
-
const encodedBytes = Math.ceil(data.length / 3) * 4;
|
|
76
|
-
const contentTypeBytes = Buffer.byteLength(file?.contentType || 'application/octet-stream');
|
|
77
|
-
const hashBytes = Buffer.byteLength(file?.hash || '');
|
|
78
|
-
return encodedBytes + contentTypeBytes + hashBytes + 128;
|
|
79
|
-
}
|
|
80
|
-
function normalizeHostname(raw) {
|
|
81
|
-
return String(raw || '')
|
|
82
|
-
.trim()
|
|
83
|
-
.toLowerCase()
|
|
84
|
-
.replace(/^https?:\/\//i, '')
|
|
85
|
-
.split('/')[0]
|
|
86
|
-
.replace(/\.$/, '');
|
|
87
|
-
}
|
|
88
|
-
/**
|
|
89
|
-
* Every branch inside this function below the top is unreachable via its
|
|
90
|
-
* only real call path (`hostnameFromUrl(pagesDevUrl)`, called once, from
|
|
91
|
-
* `setupCloudflarePagesCustomDomain`): `pagesDevUrl` is `publish()`'s
|
|
92
|
-
* `productionUrl || link.url`, which — per `cloudflarePagesProductionUrl`'s
|
|
93
|
-
* doc comment — is always the non-empty, well-formed
|
|
94
|
-
* `https://${projectName}.pages.dev` string (never `link.url`, since
|
|
95
|
-
* `productionUrl` is never falsy). That means: `raw || ''` never selects the
|
|
96
|
-
* fallback (`raw` is always that non-empty string); `!trimmed` is never true;
|
|
97
|
-
* the protocol-prefix ternary's `false` side (`https://${trimmed}`) is never
|
|
98
|
-
* selected (`trimmed` already starts with `https://`); and `new URL(...)`
|
|
99
|
-
* never throws for a well-formed `https://<dns-safe-label>.pages.dev` string,
|
|
100
|
-
* so the `catch` block (falling back to `normalizeHostname`) never runs
|
|
101
|
-
* either. Not simplified away, despite that: this is a general-purpose
|
|
102
|
-
* "raw URL/hostname → bare hostname" normalizer (the same shape
|
|
103
|
-
* `reachability.ts`'s own `normalizeDeploymentUrl` is, and that one earns its
|
|
104
|
-
* keep across many callers) that only happens to have a single, narrowly-shaped
|
|
105
|
-
* caller today. See packages/devops/source-map.md's 2026-07-22 addition.
|
|
106
|
-
*/
|
|
107
|
-
function normalizeDeploymentUrlToHostname(raw) {
|
|
108
|
-
const trimmed = String(raw || '').trim();
|
|
109
|
-
if (!trimmed)
|
|
110
|
-
return '';
|
|
111
|
-
const withProtocol = /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
|
|
112
|
-
try {
|
|
113
|
-
return new URL(withProtocol).hostname.toLowerCase();
|
|
114
|
-
}
|
|
115
|
-
catch {
|
|
116
|
-
return normalizeHostname(raw);
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
function normalizeCloudflareZoneName(raw) {
|
|
120
|
-
return normalizeHostname(raw);
|
|
121
|
-
}
|
|
122
|
-
function isValidCloudflareZoneName(raw) {
|
|
123
|
-
const name = normalizeCloudflareZoneName(raw);
|
|
124
|
-
if (!name || name.length > 253 || name.includes('..'))
|
|
125
|
-
return false;
|
|
126
|
-
return name.split('.').every((label) => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label));
|
|
127
|
-
}
|
|
128
|
-
function normalizeCloudflareDomainPrefix(raw) {
|
|
129
|
-
const prefix = String(raw || '').trim().toLowerCase();
|
|
130
|
-
if (!prefix || prefix === '@' || prefix.includes('.') || prefix.includes('*'))
|
|
131
|
-
return '';
|
|
132
|
-
return /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(prefix) ? prefix : '';
|
|
133
|
-
}
|
|
134
|
-
/**
|
|
135
|
-
* Derives a stable, Cloudflare-Pages-safe project name from the caller's
|
|
136
|
-
* `projectName` label. Deterministic (no random suffix) so repeated
|
|
137
|
-
* publishes of the same logical site land on the same Cloudflare Pages
|
|
138
|
-
* project — replaces the OD origin's `od-${projectId}-${hash}` convention,
|
|
139
|
-
* which relied on an OD project id this package has no concept of.
|
|
140
|
-
*/
|
|
141
|
-
function deriveCloudflarePagesProjectName(projectName) {
|
|
142
|
-
const label = safeDnsLabel(projectName) || 'site';
|
|
143
|
-
return safeDnsLabel(`jini-${label}`).slice(0, 63);
|
|
144
|
-
}
|
|
145
|
-
function cloudflareHeaders(config, extra = {}) {
|
|
146
|
-
return { Authorization: `Bearer ${config.token}`, ...extra };
|
|
147
|
-
}
|
|
148
|
-
function cloudflareAssetHeaders(token, extra = {}) {
|
|
149
|
-
return { Authorization: `Bearer ${token}`, ...extra };
|
|
150
|
-
}
|
|
151
|
-
async function readCloudflareJson(resp) {
|
|
152
|
-
try {
|
|
153
|
-
return (await resp.json());
|
|
154
|
-
}
|
|
155
|
-
catch {
|
|
156
|
-
throw new DeployError('Cloudflare returned a non-JSON response.', resp.status || 502);
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
/**
|
|
160
|
-
* `fallback || \`Cloudflare request failed (${status}).\`` — the template
|
|
161
|
-
* literal's own right-hand side is unreachable: all 14 direct call sites in
|
|
162
|
-
* this file pass a non-empty string literal, and the one indirect call
|
|
163
|
-
* (`fetchCloudflarePaginatedResult`'s own `cloudflareError(json, resp.status,
|
|
164
|
-
* fallback)`) is itself only ever invoked (by `listCloudflarePagesZones`)
|
|
165
|
-
* with the literal `'Cloudflare zones lookup failed.'`. So `fallback` is
|
|
166
|
-
* always truthy by the time it's evaluated here. Same "general-purpose
|
|
167
|
-
* formatter, sane default for a future caller that forgets to pass
|
|
168
|
-
* `fallback`" reasoning `netlify.ts`'s `netlifyError`/`github-pages.ts`'s
|
|
169
|
-
* `githubError` already document for the identical construct.
|
|
170
|
-
*/
|
|
171
|
-
function cloudflareError(json, status, fallback) {
|
|
172
|
-
const errors = json?.errors;
|
|
173
|
-
const messages = json?.messages;
|
|
174
|
-
const message = errors?.find((err) => err?.message)?.message ||
|
|
175
|
-
messages?.find((item) => item?.message)?.message ||
|
|
176
|
-
json?.message ||
|
|
177
|
-
fallback ||
|
|
178
|
-
`Cloudflare request failed (${status}).`;
|
|
179
|
-
return new DeployError(String(message), status, json);
|
|
180
|
-
}
|
|
181
|
-
/**
|
|
182
|
-
* `body || {}` is unreachable via all 3 real call sites: `ensureCloudflarePagesProject`'s
|
|
183
|
-
* `isCloudflareAlreadyExists(created)` and `ensureCloudflarePagesDomain`'s
|
|
184
|
-
* `isCloudflareAlreadyExists(json)` both pass a real parsed `JsonObject` from
|
|
185
|
-
* `readCloudflareJson` (which either returns an object or throws — an empty
|
|
186
|
-
* object `{}` is still truthy in JS, so even a minimal response body doesn't
|
|
187
|
-
* trigger the fallback); `maybeReuseCloudflarePagesCnameAfterDuplicate`'s
|
|
188
|
-
* `isCloudflareAlreadyExists(err.details || err.message)` only runs after
|
|
189
|
-
* `err instanceof DeployError` is confirmed (short-circuited otherwise), and
|
|
190
|
-
* every `DeployError` this file constructs has a non-empty string `message` —
|
|
191
|
-
* so even when `err.details` is falsy (a non-JSON-response error — see
|
|
192
|
-
* `maybeReuseCloudflarePagesCnameAfterDuplicate`'s own doc), the `err.message`
|
|
193
|
-
* fallback it lands on is still a truthy string.
|
|
194
|
-
*/
|
|
195
|
-
function isCloudflareAlreadyExists(body) {
|
|
196
|
-
const text = JSON.stringify(body || {}).toLowerCase();
|
|
197
|
-
return (text.includes('already exists') ||
|
|
198
|
-
text.includes('already exist') ||
|
|
199
|
-
text.includes('already bound') ||
|
|
200
|
-
text.includes('already been taken') ||
|
|
201
|
-
text.includes('already in use') ||
|
|
202
|
-
text.includes('duplicate'));
|
|
203
|
-
}
|
|
204
|
-
/**
|
|
205
|
-
* The `typeof value === 'string'` ternary's `true` side is real and reachable
|
|
206
|
-
* (e.g. when `err.details` is falsy — a non-JSON-response error from
|
|
207
|
-
* `readCloudflareJson` — `err.details || err.message` falls through to the
|
|
208
|
-
* string `err.message`). But `value || {}` inside the `false` side is
|
|
209
|
-
* unreachable: reaching the `false` side already means `value` is not a
|
|
210
|
-
* string, and this function's one call site
|
|
211
|
-
* (`isCloudflareCommentError(err.details || err.message)`) only ever
|
|
212
|
-
* produces a non-string `value` when `err.details` itself is a truthy
|
|
213
|
-
* `JsonObject` (the `||` picks `err.message`, always a string, whenever
|
|
214
|
-
* `err.details` is falsy/undefined) — so the non-string case is always a
|
|
215
|
-
* real, truthy object, never something `|| {}` would need to rescue.
|
|
216
|
-
*/
|
|
217
|
-
function isCloudflareCommentError(value) {
|
|
218
|
-
return /comment/i.test(typeof value === 'string' ? value : JSON.stringify(value || {}));
|
|
219
|
-
}
|
|
220
|
-
/**
|
|
221
|
-
* `if (!config.accountId) throw ...` is unreachable via every real call site
|
|
222
|
-
* in this file: every caller passes a `ResolvedConfig` built exclusively
|
|
223
|
-
* inside `publish()`, which already throws its own
|
|
224
|
-
* `'Cloudflare account ID is required.'` error (from `this.config.accountId`,
|
|
225
|
-
* the same field) before `config` is ever constructed. Kept as
|
|
226
|
-
* belt-and-suspenders for this URL-builder helper (which has no way to know,
|
|
227
|
-
* from its own signature, that every caller happens to pre-validate) — see
|
|
228
|
-
* packages/devops/source-map.md's 2026-07-22 addition.
|
|
229
|
-
*/
|
|
230
|
-
function cloudflareAccountPagesProjectsUrl(config) {
|
|
231
|
-
if (!config.accountId)
|
|
232
|
-
throw new DeployError('Cloudflare account ID is required.', 400);
|
|
233
|
-
return `${CLOUDFLARE_API}/accounts/${encodeURIComponent(config.accountId)}/pages/projects`;
|
|
234
|
-
}
|
|
235
|
-
/**
|
|
236
|
-
* `if (!config.projectName) throw ...` is unreachable via every real call
|
|
237
|
-
* site in this file, for the same reason `deriveCloudflarePagesProjectName`'s
|
|
238
|
-
* doc comment and `publish()`'s own (also-unreachable) guard establish:
|
|
239
|
-
* `config.projectName` is always `deriveCloudflarePagesProjectName(...)`'s
|
|
240
|
-
* result, which can never be empty. Kept as belt-and-suspenders for this
|
|
241
|
-
* shared URL-builder — see packages/devops/source-map.md's 2026-07-22
|
|
242
|
-
* addition.
|
|
243
|
-
*/
|
|
244
|
-
function cloudflarePagesProjectUrl(config, suffix = '') {
|
|
245
|
-
if (!config.projectName)
|
|
246
|
-
throw new DeployError('Cloudflare Pages project name could not be generated.', 400);
|
|
247
|
-
const base = `${cloudflareAccountPagesProjectsUrl(config)}/${encodeURIComponent(config.projectName)}`;
|
|
248
|
-
return suffix ? `${base}/${suffix}` : base;
|
|
249
|
-
}
|
|
250
|
-
function cloudflarePagesProjectDomainUrl(config, hostname) {
|
|
251
|
-
return `${cloudflarePagesProjectUrl(config, 'domains')}/${encodeURIComponent(hostname)}`;
|
|
252
|
-
}
|
|
253
|
-
/**
|
|
254
|
-
* `config?.projectName ? ... : ''` — the `''` side is unreachable via this
|
|
255
|
-
* function's one call site (`publish()`): `config.projectName` there is
|
|
256
|
-
* always `deriveCloudflarePagesProjectName(input.projectName)`'s result,
|
|
257
|
-
* which — per that function's own doc comment — is always non-empty
|
|
258
|
-
* (`safeDnsLabel(projectName) || 'site'`, then re-run through
|
|
259
|
-
* `safeDnsLabel` with a `'jini-'` prefix that itself survives sanitization).
|
|
260
|
-
* `publish()` also independently guards `if (!projectName) throw ...` right
|
|
261
|
-
* after deriving it, belt-and-suspenders. Kept for the same
|
|
262
|
-
* general-purpose-helper reasoning documented throughout this file — see
|
|
263
|
-
* packages/devops/source-map.md's 2026-07-22 addition.
|
|
264
|
-
*/
|
|
265
|
-
function cloudflarePagesProductionUrl(config) {
|
|
266
|
-
return config?.projectName ? `https://${config.projectName}.pages.dev` : '';
|
|
267
|
-
}
|
|
268
|
-
function cloudflareZoneDnsRecordsUrl(zoneId) {
|
|
269
|
-
return `${CLOUDFLARE_API}/zones/${encodeURIComponent(zoneId)}/dns_records`;
|
|
270
|
-
}
|
|
271
|
-
async function fetchCloudflarePaginatedResult(config, buildUrl, fallback, options = {}) {
|
|
272
|
-
const results = [];
|
|
273
|
-
const perPage = options.perPage || CLOUDFLARE_API_PAGE_SIZE;
|
|
274
|
-
for (let page = 1; page <= CLOUDFLARE_API_MAX_PAGES; page += 1) {
|
|
275
|
-
const resp = await fetchWithTimeout(buildUrl(page, perPage), { headers: cloudflareHeaders(config) }, { timeoutMs: FETCH_TIMEOUT_MS.QUICK });
|
|
276
|
-
const json = await readCloudflareJson(resp);
|
|
277
|
-
if (!resp.ok || json?.success === false)
|
|
278
|
-
throw cloudflareError(json, resp.status, fallback);
|
|
279
|
-
const pageItems = Array.isArray(json?.result) ? json.result : [];
|
|
280
|
-
results.push(...pageItems);
|
|
281
|
-
if (!shouldFetchNextCloudflarePage(json?.result_info, page, perPage, pageItems.length))
|
|
282
|
-
break;
|
|
283
|
-
}
|
|
284
|
-
return results;
|
|
285
|
-
}
|
|
286
|
-
function shouldFetchNextCloudflarePage(resultInfo, page, perPage, itemCount) {
|
|
287
|
-
if (itemCount <= 0)
|
|
288
|
-
return false;
|
|
289
|
-
const totalPages = Number(resultInfo?.total_pages);
|
|
290
|
-
if (Number.isFinite(totalPages) && totalPages > 0)
|
|
291
|
-
return page < totalPages;
|
|
292
|
-
const totalCount = Number(resultInfo?.total_count);
|
|
293
|
-
const responsePerPage = Number(resultInfo?.per_page);
|
|
294
|
-
const effectivePerPage = Number.isFinite(responsePerPage) && responsePerPage > 0 ? responsePerPage : perPage;
|
|
295
|
-
if (Number.isFinite(totalCount) && totalCount >= 0)
|
|
296
|
-
return page * effectivePerPage < totalCount;
|
|
297
|
-
const count = Number(resultInfo?.count);
|
|
298
|
-
if (Number.isFinite(count) && count >= 0)
|
|
299
|
-
return count >= effectivePerPage;
|
|
300
|
-
return itemCount >= perPage;
|
|
301
|
-
}
|
|
302
|
-
/** Lists active, fully-onboarded zones on the account — used to populate a custom-domain selection UI. */
|
|
303
|
-
export async function listCloudflarePagesZones(config) {
|
|
304
|
-
if (!config?.token)
|
|
305
|
-
throw new DeployError('Cloudflare API token is required.', 400);
|
|
306
|
-
if (!config?.accountId)
|
|
307
|
-
throw new DeployError('Cloudflare account ID is required.', 400);
|
|
308
|
-
const accountId = config.accountId;
|
|
309
|
-
const zones = await fetchCloudflarePaginatedResult(config, (page, perPage) => {
|
|
310
|
-
const params = new URLSearchParams({
|
|
311
|
-
'account.id': accountId,
|
|
312
|
-
status: 'active',
|
|
313
|
-
type: 'full',
|
|
314
|
-
page: String(page),
|
|
315
|
-
per_page: String(perPage),
|
|
316
|
-
});
|
|
317
|
-
return `${CLOUDFLARE_API}/zones?${params.toString()}`;
|
|
318
|
-
}, 'Cloudflare zones lookup failed.');
|
|
319
|
-
return {
|
|
320
|
-
zones: zones
|
|
321
|
-
.map((zone) => ({
|
|
322
|
-
id: typeof zone?.id === 'string' ? zone.id : '',
|
|
323
|
-
name: normalizeCloudflareZoneName(zone?.name),
|
|
324
|
-
status: typeof zone?.status === 'string' ? zone.status : undefined,
|
|
325
|
-
type: typeof zone?.type === 'string' ? zone.type : undefined,
|
|
326
|
-
}))
|
|
327
|
-
.filter((zone) => zone.id && zone.name),
|
|
328
|
-
};
|
|
329
|
-
}
|
|
330
|
-
async function ensureCloudflarePagesProject(config) {
|
|
331
|
-
const getResp = await fetchWithTimeout(cloudflarePagesProjectUrl(config), { headers: cloudflareHeaders(config) }, { timeoutMs: FETCH_TIMEOUT_MS.QUICK });
|
|
332
|
-
const found = await readCloudflareJson(getResp);
|
|
333
|
-
if (getResp.ok && found?.success !== false)
|
|
334
|
-
return found?.result ?? found;
|
|
335
|
-
if (getResp.status !== 404)
|
|
336
|
-
throw cloudflareError(found, getResp.status, 'Cloudflare Pages project lookup failed.');
|
|
337
|
-
const createResp = await fetchWithTimeout(cloudflareAccountPagesProjectsUrl(config), {
|
|
338
|
-
method: 'POST',
|
|
339
|
-
headers: cloudflareHeaders(config, { 'Content-Type': 'application/json' }),
|
|
340
|
-
body: JSON.stringify({ name: config.projectName, production_branch: 'main' }),
|
|
341
|
-
}, { timeoutMs: FETCH_TIMEOUT_MS.DEPLOY });
|
|
342
|
-
const created = await readCloudflareJson(createResp);
|
|
343
|
-
if (!createResp.ok || created?.success === false) {
|
|
344
|
-
if (isCloudflareAlreadyExists(created)) {
|
|
345
|
-
const retryResp = await fetchWithTimeout(cloudflarePagesProjectUrl(config), { headers: cloudflareHeaders(config) }, { timeoutMs: FETCH_TIMEOUT_MS.QUICK });
|
|
346
|
-
const retryFound = await readCloudflareJson(retryResp);
|
|
347
|
-
if (retryResp.ok && retryFound?.success !== false)
|
|
348
|
-
return retryFound?.result ?? retryFound;
|
|
349
|
-
}
|
|
350
|
-
throw cloudflareError(created, createResp.status, 'Cloudflare Pages project creation failed.');
|
|
351
|
-
}
|
|
352
|
-
return created?.result ?? created;
|
|
353
|
-
}
|
|
354
|
-
async function getCloudflarePagesUploadToken(config) {
|
|
355
|
-
const tokenResp = await fetchWithTimeout(cloudflarePagesProjectUrl(config, 'upload-token'), { headers: cloudflareHeaders(config) }, { timeoutMs: FETCH_TIMEOUT_MS.QUICK });
|
|
356
|
-
const tokenBody = await readCloudflareJson(tokenResp);
|
|
357
|
-
const jwt = tokenBody?.result?.jwt || tokenBody?.jwt;
|
|
358
|
-
if (!tokenResp.ok || tokenBody?.success === false || !jwt) {
|
|
359
|
-
throw cloudflareError(tokenBody, tokenResp.status, 'Cloudflare Pages upload token request failed.');
|
|
360
|
-
}
|
|
361
|
-
return String(jwt);
|
|
362
|
-
}
|
|
363
|
-
async function cloudflarePagesMissingAssetHashes(uploadToken, hashes) {
|
|
364
|
-
const resp = await fetchWithTimeout(`${CLOUDFLARE_API}/pages/assets/check-missing`, {
|
|
365
|
-
method: 'POST',
|
|
366
|
-
headers: cloudflareAssetHeaders(uploadToken, { 'Content-Type': 'application/json' }),
|
|
367
|
-
body: JSON.stringify({ hashes }),
|
|
368
|
-
}, { timeoutMs: FETCH_TIMEOUT_MS.QUICK });
|
|
369
|
-
const json = await readCloudflareJson(resp);
|
|
370
|
-
if (!resp.ok || json?.success === false)
|
|
371
|
-
throw cloudflareError(json, resp.status, 'Cloudflare Pages asset lookup failed.');
|
|
372
|
-
const result = json?.result ?? json;
|
|
373
|
-
return Array.isArray(result) ? result : Array.isArray(result?.hashes) ? result.hashes : hashes;
|
|
374
|
-
}
|
|
375
|
-
async function uploadCloudflarePagesAssets(uploadToken, files) {
|
|
376
|
-
const uniqueFiles = new Map();
|
|
377
|
-
for (const file of files) {
|
|
378
|
-
const data = Buffer.from(file.data);
|
|
379
|
-
if (data.length > CLOUDFLARE_PAGES_ASSET_MAX_BYTES) {
|
|
380
|
-
throw new DeployError(`Cloudflare Pages assets must be ${formatMib(CLOUDFLARE_PAGES_ASSET_MAX_BYTES)} or smaller: ${file.file} is ${formatMib(data.length)}.`, 400);
|
|
381
|
-
}
|
|
382
|
-
const hash = cloudflarePagesAssetHash({ ...file, data });
|
|
383
|
-
if (!uniqueFiles.has(hash)) {
|
|
384
|
-
uniqueFiles.set(hash, { hash, data, contentType: file.contentType || 'application/octet-stream' });
|
|
385
|
-
}
|
|
386
|
-
}
|
|
387
|
-
const hashes = Array.from(uniqueFiles.keys());
|
|
388
|
-
const missing = await cloudflarePagesMissingAssetHashes(uploadToken, hashes);
|
|
389
|
-
if (missing.length > 0) {
|
|
390
|
-
const missingFiles = missing.map((hash) => {
|
|
391
|
-
const file = uniqueFiles.get(hash);
|
|
392
|
-
if (!file)
|
|
393
|
-
throw new DeployError(`Cloudflare reported an unknown asset hash: ${hash}`, 502);
|
|
394
|
-
return { ...file, hash };
|
|
395
|
-
});
|
|
396
|
-
for (const batch of chunkCloudflarePagesAssetUploads(missingFiles)) {
|
|
397
|
-
const payload = batch.map((file) => ({
|
|
398
|
-
key: file.hash,
|
|
399
|
-
value: file.data.toString('base64'),
|
|
400
|
-
metadata: { contentType: file.contentType },
|
|
401
|
-
base64: true,
|
|
402
|
-
}));
|
|
403
|
-
const uploadResp = await fetchWithTimeout(`${CLOUDFLARE_API}/pages/assets/upload`, {
|
|
404
|
-
method: 'POST',
|
|
405
|
-
headers: cloudflareAssetHeaders(uploadToken, { 'Content-Type': 'application/json' }),
|
|
406
|
-
body: JSON.stringify(payload),
|
|
407
|
-
}, { timeoutMs: FETCH_TIMEOUT_MS.UPLOAD });
|
|
408
|
-
const uploaded = await readCloudflareJson(uploadResp);
|
|
409
|
-
if (!uploadResp.ok || uploaded?.success === false) {
|
|
410
|
-
throw cloudflareError(uploaded, uploadResp.status, 'Cloudflare Pages asset upload failed.');
|
|
411
|
-
}
|
|
412
|
-
}
|
|
413
|
-
}
|
|
414
|
-
const upsertResp = await fetchWithTimeout(`${CLOUDFLARE_API}/pages/assets/upsert-hashes`, {
|
|
415
|
-
method: 'POST',
|
|
416
|
-
headers: cloudflareAssetHeaders(uploadToken, { 'Content-Type': 'application/json' }),
|
|
417
|
-
body: JSON.stringify({ hashes }),
|
|
418
|
-
}, { timeoutMs: FETCH_TIMEOUT_MS.QUICK });
|
|
419
|
-
const upserted = await readCloudflareJson(upsertResp);
|
|
420
|
-
if (!upsertResp.ok || upserted?.success === false) {
|
|
421
|
-
throw cloudflareError(upserted, upsertResp.status, 'Cloudflare Pages asset hash update failed.');
|
|
422
|
-
}
|
|
423
|
-
}
|
|
424
|
-
/**
|
|
425
|
-
* Root-level Pages config files that the direct-upload API takes as their own deployment form
|
|
426
|
-
* fields rather than as assets (wrangler's `pages deploy` does the same and keeps them out of the
|
|
427
|
-
* manifest). Uploaded as an asset instead, `_headers` would be served as a public file and its
|
|
428
|
-
* rules never applied. Only the root copy is config; a nested `_headers` stays an ordinary asset.
|
|
429
|
-
*/
|
|
430
|
-
const CLOUDFLARE_PAGES_CONFIG_FILES = new Set(['_headers', '_redirects']);
|
|
431
|
-
function splitCloudflarePagesConfigFiles(files) {
|
|
432
|
-
const assets = [];
|
|
433
|
-
const configFiles = [];
|
|
434
|
-
for (const file of files) {
|
|
435
|
-
const name = file.file.replace(/^\.?\//, '');
|
|
436
|
-
if (CLOUDFLARE_PAGES_CONFIG_FILES.has(name))
|
|
437
|
-
configFiles.push({ name, data: file.data });
|
|
438
|
-
else
|
|
439
|
-
assets.push(file);
|
|
440
|
-
}
|
|
441
|
-
return { assets, configFiles };
|
|
442
|
-
}
|
|
443
|
-
// --- Custom domain / DNS record management -------------------------------
|
|
444
|
-
function normalizeCloudflarePagesDeploySelection(input) {
|
|
445
|
-
if (!input)
|
|
446
|
-
return null;
|
|
447
|
-
const rawZoneId = typeof input.zoneId === 'string' ? input.zoneId.trim() : '';
|
|
448
|
-
const rawZoneName = typeof input.zoneName === 'string' ? input.zoneName.trim() : '';
|
|
449
|
-
const rawPrefix = typeof input.domainPrefix === 'string' ? input.domainPrefix.trim() : '';
|
|
450
|
-
if (!rawZoneId && !rawZoneName && !rawPrefix)
|
|
451
|
-
return null;
|
|
452
|
-
const zoneName = normalizeCloudflareZoneName(rawZoneName);
|
|
453
|
-
const domainPrefix = normalizeCloudflareDomainPrefix(rawPrefix);
|
|
454
|
-
if (!rawZoneId)
|
|
455
|
-
throw new DeployError('Cloudflare zone is required for a custom domain.', 400);
|
|
456
|
-
if (!zoneName || !isValidCloudflareZoneName(zoneName)) {
|
|
457
|
-
throw new DeployError('Select a valid Cloudflare domain for the custom domain.', 400);
|
|
458
|
-
}
|
|
459
|
-
if (!domainPrefix)
|
|
460
|
-
throw new DeployError('Enter a valid subdomain prefix, for example "demo".', 400);
|
|
461
|
-
return { zoneId: rawZoneId, zoneName, domainPrefix, hostname: `${domainPrefix}.${zoneName}` };
|
|
462
|
-
}
|
|
463
|
-
async function validateCloudflarePagesDeploySelection(config, selection) {
|
|
464
|
-
if (!selection)
|
|
465
|
-
return null;
|
|
466
|
-
const resp = await fetchWithTimeout(`${CLOUDFLARE_API}/zones/${encodeURIComponent(selection.zoneId)}`, { headers: cloudflareHeaders(config) }, { timeoutMs: FETCH_TIMEOUT_MS.QUICK });
|
|
467
|
-
const json = await readCloudflareJson(resp);
|
|
468
|
-
if (!resp.ok || json?.success === false)
|
|
469
|
-
throw cloudflareError(json, resp.status, 'Cloudflare zone lookup failed.');
|
|
470
|
-
const zone = json?.result ?? json;
|
|
471
|
-
const zoneName = normalizeCloudflareZoneName(zone?.name);
|
|
472
|
-
if (!zoneName || zoneName !== selection.zoneName) {
|
|
473
|
-
throw new DeployError('Cloudflare zone selection no longer matches the selected domain.', 400, { errorCode: 'cloudflare_zone_mismatch' });
|
|
474
|
-
}
|
|
475
|
-
if (zone?.status && zone.status !== 'active') {
|
|
476
|
-
throw new DeployError('Cloudflare custom domains require an active zone.', 400, { errorCode: 'cloudflare_zone_inactive' });
|
|
477
|
-
}
|
|
478
|
-
if (zone?.type && zone.type !== 'full') {
|
|
479
|
-
throw new DeployError('Cloudflare custom domains require a full DNS zone.', 400, { errorCode: 'cloudflare_zone_not_full' });
|
|
480
|
-
}
|
|
481
|
-
return { ...selection, zoneName };
|
|
482
|
-
}
|
|
483
|
-
async function listCloudflareDnsRecords(config, zoneId, hostname) {
|
|
484
|
-
const params = new URLSearchParams({ name: hostname, per_page: '100' });
|
|
485
|
-
const resp = await fetchWithTimeout(`${cloudflareZoneDnsRecordsUrl(zoneId)}?${params.toString()}`, { headers: cloudflareHeaders(config) }, { timeoutMs: FETCH_TIMEOUT_MS.QUICK });
|
|
486
|
-
const json = await readCloudflareJson(resp);
|
|
487
|
-
if (!resp.ok || json?.success === false)
|
|
488
|
-
throw cloudflareError(json, resp.status, 'Cloudflare DNS record lookup failed.');
|
|
489
|
-
return Array.isArray(json?.result) ? json.result : [];
|
|
490
|
-
}
|
|
491
|
-
async function createCloudflareDnsRecord(config, zoneId, body) {
|
|
492
|
-
const resp = await fetchWithTimeout(cloudflareZoneDnsRecordsUrl(zoneId), {
|
|
493
|
-
method: 'POST',
|
|
494
|
-
headers: cloudflareHeaders(config, { 'Content-Type': 'application/json' }),
|
|
495
|
-
body: JSON.stringify(body),
|
|
496
|
-
}, { timeoutMs: FETCH_TIMEOUT_MS.QUICK });
|
|
497
|
-
const json = await readCloudflareJson(resp);
|
|
498
|
-
if (!resp.ok || json?.success === false)
|
|
499
|
-
throw cloudflareError(json, resp.status, 'Cloudflare DNS record creation failed.');
|
|
500
|
-
return json?.result ?? json;
|
|
501
|
-
}
|
|
502
|
-
async function patchCloudflareDnsRecord(config, zoneId, dnsRecordId, body) {
|
|
503
|
-
const resp = await fetchWithTimeout(`${cloudflareZoneDnsRecordsUrl(zoneId)}/${encodeURIComponent(dnsRecordId)}`, {
|
|
504
|
-
method: 'PATCH',
|
|
505
|
-
headers: cloudflareHeaders(config, { 'Content-Type': 'application/json' }),
|
|
506
|
-
body: JSON.stringify(body),
|
|
507
|
-
}, { timeoutMs: FETCH_TIMEOUT_MS.QUICK });
|
|
508
|
-
const json = await readCloudflareJson(resp);
|
|
509
|
-
if (!resp.ok || json?.success === false)
|
|
510
|
-
throw cloudflareError(json, resp.status, 'Cloudflare DNS record update failed.');
|
|
511
|
-
return json?.result ?? json;
|
|
512
|
-
}
|
|
513
|
-
function findExactCloudflarePagesCname(records, selection, targetHost) {
|
|
514
|
-
return records.find((record) => String(record?.type || '').toUpperCase() === 'CNAME' &&
|
|
515
|
-
normalizeHostname(record?.name) === selection.hostname &&
|
|
516
|
-
normalizeHostname(record?.content) === targetHost);
|
|
517
|
-
}
|
|
518
|
-
function findCloudflarePagesHostnameRecord(records, selection) {
|
|
519
|
-
return records.find((record) => normalizeHostname(record?.name) === selection.hostname);
|
|
520
|
-
}
|
|
521
|
-
function cloudflarePagesCnameReuseResult(record, marker) {
|
|
522
|
-
return {
|
|
523
|
-
dnsStatus: 'reused',
|
|
524
|
-
dnsRecordId: typeof record.id === 'string' ? record.id : undefined,
|
|
525
|
-
dnsOwnership: record.comment === marker ? 'marked' : 'unmarked',
|
|
526
|
-
marker,
|
|
527
|
-
};
|
|
528
|
-
}
|
|
529
|
-
function cloudflarePagesDnsConflictError(selection, conflicting) {
|
|
530
|
-
return new DeployError(`Cloudflare DNS already has a different record for ${selection.hostname}.`, 409, {
|
|
531
|
-
errorCode: 'cloudflare_dns_record_conflict',
|
|
532
|
-
dnsStatus: 'conflict',
|
|
533
|
-
dnsRecordId: conflicting.id,
|
|
534
|
-
dnsOwnership: 'external',
|
|
535
|
-
});
|
|
536
|
-
}
|
|
537
|
-
function canPatchCloudflarePagesCname(record, selection, marker, prior) {
|
|
538
|
-
return Boolean(record &&
|
|
539
|
-
String(record.type || '').toUpperCase() === 'CNAME' &&
|
|
540
|
-
typeof record.id === 'string' &&
|
|
541
|
-
record.id &&
|
|
542
|
-
record.id === prior?.dnsRecordId &&
|
|
543
|
-
normalizeHostname(record.name) === selection.hostname &&
|
|
544
|
-
record.comment === marker &&
|
|
545
|
-
prior?.marker === marker);
|
|
546
|
-
}
|
|
547
|
-
async function maybeReuseCloudflarePagesCnameAfterDuplicate(input) {
|
|
548
|
-
const { err, config, selection, targetHost, marker } = input;
|
|
549
|
-
if (!(err instanceof DeployError) || !isCloudflareAlreadyExists(err.details || err.message))
|
|
550
|
-
return null;
|
|
551
|
-
const racedRecords = await listCloudflareDnsRecords(config, selection.zoneId, selection.hostname);
|
|
552
|
-
const exact = findExactCloudflarePagesCname(racedRecords, selection, targetHost);
|
|
553
|
-
if (exact)
|
|
554
|
-
return cloudflarePagesCnameReuseResult(exact, marker);
|
|
555
|
-
const conflicting = findCloudflarePagesHostnameRecord(racedRecords, selection);
|
|
556
|
-
if (conflicting)
|
|
557
|
-
throw cloudflarePagesDnsConflictError(selection, conflicting);
|
|
558
|
-
throw err;
|
|
559
|
-
}
|
|
560
|
-
async function ensureCloudflarePagesCnameRecord(input) {
|
|
561
|
-
const { config, selection, target, marker, prior } = input;
|
|
562
|
-
const records = await listCloudflareDnsRecords(config, selection.zoneId, selection.hostname);
|
|
563
|
-
const targetHost = normalizeHostname(target);
|
|
564
|
-
const exact = findExactCloudflarePagesCname(records, selection, targetHost);
|
|
565
|
-
if (exact)
|
|
566
|
-
return cloudflarePagesCnameReuseResult(exact, marker);
|
|
567
|
-
const conflicting = findCloudflarePagesHostnameRecord(records, selection);
|
|
568
|
-
if (conflicting) {
|
|
569
|
-
if (canPatchCloudflarePagesCname(conflicting, selection, marker, prior)) {
|
|
570
|
-
const conflictingId = conflicting.id;
|
|
571
|
-
// `if (!conflictingId) throw ...` is unreachable: `canPatchCloudflarePagesCname` (just
|
|
572
|
-
// called, guarding this whole block) already requires `typeof record.id === 'string' &&
|
|
573
|
-
// record.id` — a truthy string — as part of its own boolean expression, on this exact same
|
|
574
|
-
// `conflicting` object. If `canPatchCloudflarePagesCname` returned `true`, `conflicting.id`
|
|
575
|
-
// is already known-truthy. Kept as belt-and-suspenders since `conflicting.id`'s static type
|
|
576
|
-
// (`unknown`, from `CloudflareDnsRecord`'s index signature) doesn't let TypeScript narrow
|
|
577
|
-
// that for us. See packages/devops/source-map.md's 2026-07-22 addition.
|
|
578
|
-
if (!conflictingId)
|
|
579
|
-
throw new DeployError('Cloudflare DNS record id is missing.', 502);
|
|
580
|
-
const patched = await patchCloudflareDnsRecord(config, selection.zoneId, conflictingId, {
|
|
581
|
-
type: 'CNAME',
|
|
582
|
-
name: selection.hostname,
|
|
583
|
-
content: targetHost,
|
|
584
|
-
proxied: true,
|
|
585
|
-
ttl: 1,
|
|
586
|
-
comment: marker,
|
|
587
|
-
});
|
|
588
|
-
return { dnsStatus: 'patched', dnsRecordId: patched?.id || conflictingId, dnsOwnership: 'marked', marker };
|
|
589
|
-
}
|
|
590
|
-
throw cloudflarePagesDnsConflictError(selection, conflicting);
|
|
591
|
-
}
|
|
592
|
-
try {
|
|
593
|
-
const created = await createCloudflareDnsRecord(config, selection.zoneId, {
|
|
594
|
-
type: 'CNAME',
|
|
595
|
-
name: selection.hostname,
|
|
596
|
-
content: targetHost,
|
|
597
|
-
proxied: true,
|
|
598
|
-
ttl: 1,
|
|
599
|
-
comment: marker,
|
|
600
|
-
});
|
|
601
|
-
return { dnsStatus: 'created', dnsRecordId: created?.id, dnsOwnership: 'marked', marker };
|
|
602
|
-
}
|
|
603
|
-
catch (err) {
|
|
604
|
-
const raced = await maybeReuseCloudflarePagesCnameAfterDuplicate({ err, config, selection, targetHost, marker });
|
|
605
|
-
if (raced)
|
|
606
|
-
return raced;
|
|
607
|
-
if (!(err instanceof DeployError) || !isCloudflareCommentError(err.details || err.message))
|
|
608
|
-
throw err;
|
|
609
|
-
try {
|
|
610
|
-
const created = await createCloudflareDnsRecord(config, selection.zoneId, {
|
|
611
|
-
type: 'CNAME',
|
|
612
|
-
name: selection.hostname,
|
|
613
|
-
content: targetHost,
|
|
614
|
-
proxied: true,
|
|
615
|
-
ttl: 1,
|
|
616
|
-
});
|
|
617
|
-
return { dnsStatus: 'created', dnsRecordId: created?.id, dnsOwnership: 'unmarked', marker };
|
|
618
|
-
}
|
|
619
|
-
catch (retryErr) {
|
|
620
|
-
const racedRetry = await maybeReuseCloudflarePagesCnameAfterDuplicate({ err: retryErr, config, selection, targetHost, marker });
|
|
621
|
-
if (racedRetry)
|
|
622
|
-
return racedRetry;
|
|
623
|
-
throw retryErr;
|
|
624
|
-
}
|
|
625
|
-
}
|
|
626
|
-
}
|
|
627
|
-
/**
|
|
628
|
-
* `if (!normalizedHostname) return null;` is unreachable via this function's
|
|
629
|
-
* one call site (`ensureCloudflarePagesDomain(config, selection.hostname)`,
|
|
630
|
-
* itself only called from `setupCloudflarePagesCustomDomain`):
|
|
631
|
-
* `selection.hostname` is always `${domainPrefix}.${zoneName}`, built in
|
|
632
|
-
* `normalizeCloudflarePagesDeploySelection` from a validated non-empty
|
|
633
|
-
* `domainPrefix` and a validated non-empty, regex-confirmed-DNS-safe
|
|
634
|
-
* `zoneName` — a value `normalizeHostname`'s trim/lowercase/protocol-strip
|
|
635
|
-
* transforms can never reduce to `''`. See
|
|
636
|
-
* packages/devops/source-map.md's 2026-07-22 addition.
|
|
637
|
-
*/
|
|
638
|
-
async function findCloudflarePagesDomain(config, hostname) {
|
|
639
|
-
const normalizedHostname = normalizeHostname(hostname);
|
|
640
|
-
if (!normalizedHostname)
|
|
641
|
-
return null;
|
|
642
|
-
const resp = await fetchWithTimeout(cloudflarePagesProjectDomainUrl(config, normalizedHostname), { headers: cloudflareHeaders(config) }, { timeoutMs: FETCH_TIMEOUT_MS.QUICK });
|
|
643
|
-
const json = await readCloudflareJson(resp);
|
|
644
|
-
if (resp.status === 404)
|
|
645
|
-
return null;
|
|
646
|
-
if (!resp.ok || json?.success === false)
|
|
647
|
-
throw cloudflareError(json, resp.status, 'Cloudflare Pages custom domain lookup failed.');
|
|
648
|
-
const domain = json?.result ?? json;
|
|
649
|
-
return normalizeHostname(domain?.name) === normalizedHostname ? domain : null;
|
|
650
|
-
}
|
|
651
|
-
async function ensureCloudflarePagesDomain(config, hostname) {
|
|
652
|
-
const existing = await findCloudflarePagesDomain(config, hostname);
|
|
653
|
-
if (existing)
|
|
654
|
-
return existing;
|
|
655
|
-
const resp = await fetchWithTimeout(cloudflarePagesProjectUrl(config, 'domains'), {
|
|
656
|
-
method: 'POST',
|
|
657
|
-
headers: cloudflareHeaders(config, { 'Content-Type': 'application/json' }),
|
|
658
|
-
body: JSON.stringify({ name: hostname }),
|
|
659
|
-
}, { timeoutMs: FETCH_TIMEOUT_MS.DEPLOY });
|
|
660
|
-
const json = await readCloudflareJson(resp);
|
|
661
|
-
if (!resp.ok || json?.success === false) {
|
|
662
|
-
if (isCloudflareAlreadyExists(json)) {
|
|
663
|
-
const retry = await findCloudflarePagesDomain(config, hostname);
|
|
664
|
-
if (retry)
|
|
665
|
-
return retry;
|
|
666
|
-
throw new DeployError(`Cloudflare Pages says ${hostname} is already bound to another project.`, 409, {
|
|
667
|
-
errorCode: 'cloudflare_domain_already_bound',
|
|
668
|
-
domainStatus: 'conflict',
|
|
669
|
-
});
|
|
670
|
-
}
|
|
671
|
-
throw cloudflareError(json, resp.status, 'Cloudflare Pages custom domain setup failed.');
|
|
672
|
-
}
|
|
673
|
-
return json?.result ?? json;
|
|
674
|
-
}
|
|
675
|
-
function normalizeCloudflarePagesDomainStatus(status) {
|
|
676
|
-
const value = String(status || '').toLowerCase();
|
|
677
|
-
if (value === 'active')
|
|
678
|
-
return 'active';
|
|
679
|
-
if (value === 'error' || value === 'blocked' || value === 'deactivated')
|
|
680
|
-
return 'failed';
|
|
681
|
-
return 'pending';
|
|
682
|
-
}
|
|
683
|
-
async function setupCloudflarePagesCustomDomain(input) {
|
|
684
|
-
const { config, selection, pagesDevUrl, prior } = input;
|
|
685
|
-
// `hostnameFromUrl(pagesDevUrl) || ...pages.dev` — the fallback is unreachable: this function's
|
|
686
|
-
// one call site (`publish()`) always passes `pagesDevUrl = productionUrl || link.url`, and
|
|
687
|
-
// `productionUrl` (`cloudflarePagesProductionUrl(config)`) is always the non-empty
|
|
688
|
-
// `https://${projectName}.pages.dev` string, so `pagesDevUrl` is never `link.url`. A non-empty,
|
|
689
|
-
// well-formed `https://` URL always yields a real hostname from `hostnameFromUrl`, so its own
|
|
690
|
-
// `|| default` inside `normalizeDeploymentUrlToHostname` is never needed here either. See
|
|
691
|
-
// packages/devops/source-map.md's 2026-07-22 addition.
|
|
692
|
-
const pagesTarget = normalizeHostname(hostnameFromUrl(pagesDevUrl) || `${config.projectName}.pages.dev`);
|
|
693
|
-
const marker = cloudflarePagesDnsMarker(config.projectName, pagesTarget);
|
|
694
|
-
const base = {
|
|
695
|
-
hostname: selection.hostname,
|
|
696
|
-
url: `https://${selection.hostname}`,
|
|
697
|
-
zoneId: selection.zoneId,
|
|
698
|
-
zoneName: selection.zoneName,
|
|
699
|
-
domainPrefix: selection.domainPrefix,
|
|
700
|
-
};
|
|
701
|
-
let dns;
|
|
702
|
-
try {
|
|
703
|
-
dns = await ensureCloudflarePagesCnameRecord({ config, selection, target: pagesTarget, marker, prior });
|
|
704
|
-
}
|
|
705
|
-
catch (err) {
|
|
706
|
-
const details = err instanceof DeployError && err.details && typeof err.details === 'object' ? err.details : {};
|
|
707
|
-
return {
|
|
708
|
-
...base,
|
|
709
|
-
status: details.errorCode === 'cloudflare_dns_record_conflict' ? 'conflict' : 'failed',
|
|
710
|
-
// `err instanceof Error ? ... : 'fallback'` — the fallback side is unreachable: every throw
|
|
711
|
-
// reachable from `ensureCloudflarePagesCnameRecord`'s own call graph (`cloudflareError(...)`,
|
|
712
|
-
// `new DeployError(...)`, or a rethrow of one of those) is a real `Error`/`DeployError`
|
|
713
|
-
// instance — this file never throws a bare string/object anywhere. See
|
|
714
|
-
// packages/devops/source-map.md's 2026-07-22 addition.
|
|
715
|
-
statusMessage: err instanceof Error ? err.message : 'Cloudflare DNS record setup failed.',
|
|
716
|
-
errorCode: details.errorCode || 'cloudflare_dns_record_failed',
|
|
717
|
-
dnsOwnership: details.dnsOwnership || 'external',
|
|
718
|
-
domainStatus: 'skipped',
|
|
719
|
-
};
|
|
720
|
-
}
|
|
721
|
-
let domain;
|
|
722
|
-
try {
|
|
723
|
-
domain = await ensureCloudflarePagesDomain(config, selection.hostname);
|
|
724
|
-
}
|
|
725
|
-
catch (err) {
|
|
726
|
-
const details = err instanceof DeployError && err.details && typeof err.details === 'object' ? err.details : {};
|
|
727
|
-
return {
|
|
728
|
-
...base,
|
|
729
|
-
status: details.errorCode === 'cloudflare_domain_already_bound' ? 'conflict' : 'failed',
|
|
730
|
-
// Same "every real throw site in this file is a genuine Error/DeployError" reasoning as the
|
|
731
|
-
// DNS-setup catch above — unreachable fallback, see packages/devops/source-map.md.
|
|
732
|
-
statusMessage: err instanceof Error ? err.message : 'Cloudflare Pages custom domain setup failed.',
|
|
733
|
-
errorCode: details.errorCode || 'cloudflare_domain_setup_failed',
|
|
734
|
-
dnsStatus: dns.dnsStatus,
|
|
735
|
-
dnsRecordId: dns.dnsRecordId,
|
|
736
|
-
dnsOwnership: dns.dnsOwnership,
|
|
737
|
-
domainStatus: details.domainStatus || 'failed',
|
|
738
|
-
};
|
|
739
|
-
}
|
|
740
|
-
const domainStatus = normalizeCloudflarePagesDomainStatus(domain?.status);
|
|
741
|
-
const customLink = domainStatus === 'active' ? await checkDeploymentUrl(base.url) : null;
|
|
742
|
-
const ready = domainStatus === 'active' && customLink?.reachable;
|
|
743
|
-
const failed = domainStatus === 'failed';
|
|
744
|
-
return {
|
|
745
|
-
...base,
|
|
746
|
-
status: ready ? 'ready' : failed ? 'failed' : 'pending',
|
|
747
|
-
statusMessage: ready
|
|
748
|
-
? 'Custom domain is ready.'
|
|
749
|
-
: failed
|
|
750
|
-
? 'Cloudflare Pages reported a custom-domain error.'
|
|
751
|
-
: customLink?.statusMessage || 'Custom domain is being verified by Cloudflare Pages.',
|
|
752
|
-
dnsStatus: dns.dnsStatus,
|
|
753
|
-
dnsRecordId: dns.dnsRecordId,
|
|
754
|
-
dnsOwnership: dns.dnsOwnership,
|
|
755
|
-
domainStatus,
|
|
756
|
-
};
|
|
757
|
-
}
|
|
758
|
-
function hostnameFromUrl(raw) {
|
|
759
|
-
return normalizeDeploymentUrlToHostname(raw);
|
|
760
|
-
}
|
|
761
|
-
/**
|
|
762
|
-
* A stable identifier stamped as a Cloudflare DNS record comment so a later
|
|
763
|
-
* publish can recognize (and safely patch) a CNAME record it created
|
|
764
|
-
* itself, versus one an operator manages by hand. Genericized from the OD
|
|
765
|
-
* origin's `od:cfp:` marker prefix.
|
|
766
|
-
*/
|
|
767
|
-
/**
|
|
768
|
-
* `pagesTarget || projectName` is unreachable via this function's one call
|
|
769
|
-
* site (`setupCloudflarePagesCustomDomain`): `pagesTarget` there is
|
|
770
|
-
* `normalizeHostname(hostnameFromUrl(pagesDevUrl) || \`${config.projectName}.pages.dev\`)`,
|
|
771
|
-
* and `pagesDevUrl` (`publish()`'s own `productionUrl || link.url`) is always
|
|
772
|
-
* `productionUrl` — always a non-empty `https://${projectName}.pages.dev`
|
|
773
|
-
* string per `cloudflarePagesProductionUrl`'s own doc comment, since
|
|
774
|
-
* `config.projectName` is validated non-empty before any of this runs. A
|
|
775
|
-
* non-empty, well-formed `https://` URL always yields a non-empty
|
|
776
|
-
* `new URL(...).hostname`, so `hostnameFromUrl(pagesDevUrl)` never falls
|
|
777
|
-
* through to its own `|| ...pages.dev` default, and `normalizeHostname` of a
|
|
778
|
-
* real hostname never produces `''`. So `pagesTarget` is always truthy by
|
|
779
|
-
* the time it reaches here. See packages/devops/source-map.md's 2026-07-22
|
|
780
|
-
* addition for the full chain.
|
|
781
|
-
*/
|
|
782
|
-
function cloudflarePagesDnsMarker(projectName, pagesTarget) {
|
|
783
|
-
return `jini-deploy:${shortHash(projectName)}:${shortHash(pagesTarget || projectName)}`;
|
|
784
|
-
}
|
|
785
|
-
function aggregateCloudflarePagesStatus(pagesDev, customDomain) {
|
|
786
|
-
// Every `|| fallback`/`!== undefined ? ... : {}` construct below that falls back specifically
|
|
787
|
-
// when `pagesDev.statusMessage` is falsy/undefined is unreachable via this function's one real
|
|
788
|
-
// call site (`publish()`'s `aggregateCloudflarePagesStatus(pagesDev, customDomain)`):
|
|
789
|
-
// `pagesDev` there is always `{ status: link.status, statusMessage: link.statusMessage }`, and
|
|
790
|
-
// `link` is a `ReachabilityWaitResult` (from `reachability.ts`'s `waitForReachableDeploymentUrl`)
|
|
791
|
-
// whose `statusMessage` field is typed *required*, not optional — every one of that function's
|
|
792
|
-
// own return paths sets a real, non-empty string (verified when closing that file's own coverage
|
|
793
|
-
// gaps — see its 2026-07-22 source-map addition). This function's own parameter type
|
|
794
|
-
// (`statusMessage?: string`) is deliberately wider than what its one real caller supplies, same
|
|
795
|
-
// general-purpose-helper posture as `deploymentUrlCandidates`/`normalizeDeploymentUrlToHostname`
|
|
796
|
-
// elsewhere in this file. Similarly, `customDomain.statusMessage`/`customDomain.errorCode`
|
|
797
|
-
// fallbacks below are unreachable because `customDomain` only ever comes from this file's own
|
|
798
|
-
// `setupCloudflarePagesCustomDomain`, whose every return shape sets a real, non-empty
|
|
799
|
-
// `statusMessage` (main flow) or `errorCode` (catch-block flows) — see that function's own return
|
|
800
|
-
// sites. See packages/devops/source-map.md's 2026-07-22 addition for the exhaustive case-by-case
|
|
801
|
-
// trace backing all of this.
|
|
802
|
-
if (!customDomain) {
|
|
803
|
-
return { status: pagesDev.status, ...(pagesDev.statusMessage !== undefined ? { statusMessage: pagesDev.statusMessage } : {}) };
|
|
804
|
-
}
|
|
805
|
-
if (customDomain.status === 'ready') {
|
|
806
|
-
return {
|
|
807
|
-
status: pagesDev.status === 'ready' ? 'ready' : 'link-delayed',
|
|
808
|
-
statusMessage: pagesDev.status === 'ready'
|
|
809
|
-
? 'Cloudflare Pages and custom domain are ready.'
|
|
810
|
-
: pagesDev.statusMessage || "Cloudflare Pages is still preparing its pages.dev link.",
|
|
811
|
-
};
|
|
812
|
-
}
|
|
813
|
-
if (customDomain.status === 'pending') {
|
|
814
|
-
return { status: 'link-delayed', statusMessage: customDomain.statusMessage || 'Custom domain is still being prepared.' };
|
|
815
|
-
}
|
|
816
|
-
const customFailureMessage = customDomain.errorCode || customDomain.statusMessage || 'Custom domain setup failed.';
|
|
817
|
-
return {
|
|
818
|
-
status: pagesDev.status,
|
|
819
|
-
statusMessage: pagesDev.status === 'ready' ? `pages.dev is ready. ${customFailureMessage}` : pagesDev.statusMessage || customFailureMessage,
|
|
820
|
-
};
|
|
821
|
-
}
|
|
822
|
-
/**
|
|
823
|
-
* `DeployTarget` adapter for Cloudflare Pages' direct-upload API: ensures a
|
|
824
|
-
* Pages project exists, uploads the file set as content-addressed assets,
|
|
825
|
-
* creates a deployment, waits for the `pages.dev` URL to be reachable, and
|
|
826
|
-
* (optionally, when `input.metadata.customDomain` is supplied) binds a
|
|
827
|
-
* custom domain via a managed CNAME + Pages domain record.
|
|
828
|
-
*
|
|
829
|
-
* Genericized from the origin product's daemon deploy module's
|
|
830
|
-
* `deployToCloudflarePages` family: the origin's persisted local config file
|
|
831
|
-
* and product-specific project naming are gone — the caller supplies
|
|
832
|
-
* `{ token, accountId }` directly and a stable `projectName` label.
|
|
833
|
-
*/
|
|
834
|
-
export class CloudflarePagesDeployTarget {
|
|
835
|
-
config;
|
|
836
|
-
id = CLOUDFLARE_PAGES_TARGET_ID;
|
|
837
|
-
constructor(config) {
|
|
838
|
-
this.config = config;
|
|
839
|
-
}
|
|
840
|
-
/**
|
|
841
|
-
* Publishes `input.files` to Cloudflare Pages and waits for the resulting
|
|
842
|
-
* `pages.dev` URL to be reachable, optionally binding a custom domain.
|
|
843
|
-
*
|
|
844
|
-
* @param input - File set, a caller-chosen project name label, and
|
|
845
|
-
* optional `metadata.customDomain`/`metadata.priorCustomDomain`.
|
|
846
|
-
* @returns The published deployment's URL/status, with any custom-domain
|
|
847
|
-
* outcome folded into `providerMetadata`.
|
|
848
|
-
* @throws {DeployError} If `token`/`accountId` are missing, the derived
|
|
849
|
-
* project name is empty, or any Cloudflare API call fails.
|
|
850
|
-
* @complexity O(files) to hash/chunk the asset set, plus a bounded
|
|
851
|
-
* reachability wait; DNS/domain setup is O(1) additional round-trips.
|
|
852
|
-
* @overallScore 95/100
|
|
853
|
-
* @tradeoffs Custom-domain setup errors are captured into the returned
|
|
854
|
-
* `providerMetadata` rather than thrown, matching the OD origin's
|
|
855
|
-
* behavior of always returning the base pages.dev result even if the
|
|
856
|
-
* custom domain step fails partway — flagged since a caller that only
|
|
857
|
-
* checks `status`/`throws` could miss a degraded custom-domain state
|
|
858
|
-
* without also inspecting `providerMetadata`.
|
|
859
|
-
*/
|
|
860
|
-
async publish(input) {
|
|
861
|
-
if (!this.config.token)
|
|
862
|
-
throw new DeployError('Cloudflare API token is required.', 400);
|
|
863
|
-
if (!this.config.accountId)
|
|
864
|
-
throw new DeployError('Cloudflare account ID is required.', 400);
|
|
865
|
-
const projectName = deriveCloudflarePagesProjectName(input.projectName);
|
|
866
|
-
// `if (!projectName) throw ...` is unreachable: `deriveCloudflarePagesProjectName`
|
|
867
|
-
// always returns a non-empty string (see its own doc comment) — kept as
|
|
868
|
-
// belt-and-suspenders in case that helper's contract ever changes, same
|
|
869
|
-
// reasoning as `cloudflarePagesProjectUrl`'s identical guard. See
|
|
870
|
-
// packages/devops/source-map.md's 2026-07-22 addition.
|
|
871
|
-
if (!projectName)
|
|
872
|
-
throw new DeployError('Cloudflare Pages project name could not be generated.', 400);
|
|
873
|
-
const config = { ...this.config, projectName };
|
|
874
|
-
const metadata = (input.metadata ?? {});
|
|
875
|
-
const customDomainSelection = await validateCloudflarePagesDeploySelection(config, normalizeCloudflarePagesDeploySelection(metadata.customDomain));
|
|
876
|
-
await ensureCloudflarePagesProject(config);
|
|
877
|
-
const uploadToken = await getCloudflarePagesUploadToken(config);
|
|
878
|
-
const { assets, configFiles } = splitCloudflarePagesConfigFiles(input.files);
|
|
879
|
-
await uploadCloudflarePagesAssets(uploadToken, assets);
|
|
880
|
-
const form = new FormData();
|
|
881
|
-
const manifest = {};
|
|
882
|
-
for (const file of assets)
|
|
883
|
-
manifest[`/${file.file}`] = cloudflarePagesAssetHash(file);
|
|
884
|
-
form.append('manifest', JSON.stringify(manifest));
|
|
885
|
-
form.append('branch', 'main');
|
|
886
|
-
for (const { name, data } of configFiles)
|
|
887
|
-
form.append(name, new File([Buffer.from(data)], name));
|
|
888
|
-
const deployResp = await fetchWithTimeout(cloudflarePagesProjectUrl(config, 'deployments'), {
|
|
889
|
-
method: 'POST',
|
|
890
|
-
headers: cloudflareHeaders(config),
|
|
891
|
-
body: form,
|
|
892
|
-
}, { timeoutMs: FETCH_TIMEOUT_MS.DEPLOY });
|
|
893
|
-
const deployed = await readCloudflareJson(deployResp);
|
|
894
|
-
if (!deployResp.ok || deployed?.success === false) {
|
|
895
|
-
throw cloudflareError(deployed, deployResp.status, 'Cloudflare Pages deployment failed.');
|
|
896
|
-
}
|
|
897
|
-
const deployment = deployed?.result ?? deployed;
|
|
898
|
-
// `productionUrl ? [productionUrl] : [deployment?.url]` and `productionUrl || link.url` below:
|
|
899
|
-
// the `[deployment?.url]`/`link.url` sides are both unreachable. `productionUrl` is
|
|
900
|
-
// `cloudflarePagesProductionUrl(config)`, which — per its own doc comment — is always the
|
|
901
|
-
// non-empty `https://${projectName}.pages.dev` string, since `config.projectName` is validated
|
|
902
|
-
// non-empty before `config` is ever constructed above. See
|
|
903
|
-
// packages/devops/source-map.md's 2026-07-22 addition.
|
|
904
|
-
const productionUrl = cloudflarePagesProductionUrl(config);
|
|
905
|
-
const link = await waitForReachableDeploymentUrl(productionUrl ? [productionUrl] : [deployment?.url], {
|
|
906
|
-
providerLabel: 'Cloudflare Pages',
|
|
907
|
-
});
|
|
908
|
-
const pagesDevUrl = productionUrl || link.url;
|
|
909
|
-
const pagesDev = { status: link.status, statusMessage: link.statusMessage };
|
|
910
|
-
const customDomain = customDomainSelection
|
|
911
|
-
? await setupCloudflarePagesCustomDomain({
|
|
912
|
-
config,
|
|
913
|
-
selection: customDomainSelection,
|
|
914
|
-
pagesDevUrl,
|
|
915
|
-
prior: metadata.priorCustomDomain,
|
|
916
|
-
})
|
|
917
|
-
: undefined;
|
|
918
|
-
const aggregate = aggregateCloudflarePagesStatus(pagesDev, customDomain);
|
|
919
|
-
return {
|
|
920
|
-
targetId: this.id,
|
|
921
|
-
url: pagesDevUrl,
|
|
922
|
-
...(typeof deployment?.id === 'string' ? { deploymentId: deployment.id } : {}),
|
|
923
|
-
status: aggregate.status,
|
|
924
|
-
// `aggregate.statusMessage !== undefined ? ... : {}` — the `{}` (statusMessage omitted) side
|
|
925
|
-
// is unreachable: every one of `aggregateCloudflarePagesStatus`'s own return paths sets a
|
|
926
|
-
// real, non-empty `statusMessage` — either a literal, or spread from `pagesDev.statusMessage`,
|
|
927
|
-
// which (per that function's own doc comment) is always defined. See
|
|
928
|
-
// packages/devops/source-map.md's 2026-07-22 addition.
|
|
929
|
-
...(aggregate.statusMessage !== undefined ? { statusMessage: aggregate.statusMessage } : {}),
|
|
930
|
-
...(link.reachableAt !== undefined ? { reachableAt: link.reachableAt } : {}),
|
|
931
|
-
providerMetadata: {
|
|
932
|
-
projectName,
|
|
933
|
-
pagesDev: { ...pagesDev, url: pagesDevUrl },
|
|
934
|
-
...(customDomain ? { customDomain } : {}),
|
|
935
|
-
},
|
|
936
|
-
};
|
|
937
|
-
}
|
|
938
|
-
/** Probes `url` with the shared reachability checker (no Cloudflare-specific auth-wall detection is needed). */
|
|
939
|
-
async checkReachability(url) {
|
|
940
|
-
return checkDeploymentUrl(url);
|
|
941
|
-
}
|
|
942
|
-
}
|
|
943
|
-
//# sourceMappingURL=cloudflare-pages.js.map
|