siteplane 0.2.1-rc.1 → 0.3.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.
@@ -0,0 +1,1772 @@
1
+ // src/astro/index.ts
2
+ import { existsSync, readFileSync } from "fs";
3
+ import { mkdir as mkdir3, writeFile as writeFile3 } from "fs/promises";
4
+ import { join } from "path";
5
+ import { fileURLToPath } from "url";
6
+
7
+ // ../shared/dist/safe-redirect.js
8
+ var UNSAFE_URL_CHARACTERS = /[\\\u0000-\u001f\u007f]/u;
9
+ var MAX_REDIRECT_PATH_LENGTH = 2048;
10
+ var INTERNAL_BASE = "https://siteplane.invalid";
11
+ function hasUnsafeUrlCharacters(value) {
12
+ return UNSAFE_URL_CHARACTERS.test(value);
13
+ }
14
+ function parseSafeRedirectPath(value) {
15
+ if (typeof value !== "string" || value.length > MAX_REDIRECT_PATH_LENGTH || !value.startsWith("/") || value.startsWith("//") || hasUnsafeUrlCharacters(value)) {
16
+ return null;
17
+ }
18
+ let url;
19
+ try {
20
+ url = new URL(value, INTERNAL_BASE);
21
+ } catch {
22
+ return null;
23
+ }
24
+ return url.origin === INTERNAL_BASE && !url.pathname.startsWith("//") ? `${url.pathname}${url.search}${url.hash}` : null;
25
+ }
26
+
27
+ // ../shared/dist/content-path.js
28
+ var ROW_KEY_PATTERN = /^[a-z][a-z0-9]{7}$/u;
29
+ function formatContentPath(steps) {
30
+ let path = "";
31
+ for (const step of steps) {
32
+ if ("field" in step)
33
+ path += path === "" ? step.field : `.${step.field}`;
34
+ else if ("key" in step)
35
+ path += `[_key=="${step.key}"]`;
36
+ else
37
+ path += `[${step.index}]`;
38
+ }
39
+ return path;
40
+ }
41
+ function isRowKey(value) {
42
+ return typeof value === "string" && ROW_KEY_PATTERN.test(value);
43
+ }
44
+ var letters = "abcdefghijklmnopqrstuvwxyz";
45
+ var lettersAndDigits = `${letters}0123456789`;
46
+
47
+ // ../shared/dist/field-values.js
48
+ var FIELD_VALUE_LIMITS = {
49
+ text: 256,
50
+ longText: 5e4,
51
+ linkLabel: 256,
52
+ linkHref: 2048,
53
+ imageSrc: 2048,
54
+ imageFile: 2048,
55
+ imageAlt: 300,
56
+ imageSize: 1e5
57
+ };
58
+ var FIELD_VALUE_PROBLEMS = [
59
+ "not_text",
60
+ "too_long",
61
+ "not_object",
62
+ "unknown_key",
63
+ "href_invalid",
64
+ "label_missing",
65
+ "label_too_long",
66
+ "asset_missing",
67
+ "src_invalid",
68
+ "alt_invalid",
69
+ "size_invalid",
70
+ "unknown_type"
71
+ ];
72
+ var FIELD_VALUE_PROBLEM_TEXT = {
73
+ not_text: "it must be a string",
74
+ too_long: "it is too long (short text 256, long text 50,000 characters)",
75
+ not_object: "it must be an object",
76
+ unknown_key: "it has keys the field type does not know",
77
+ href_invalid: "href must be a path such as /menu, an anchor such as #contact, or start with http(s)://, mailto: or tel:",
78
+ label_missing: "a link needs a visible label",
79
+ label_too_long: "the label is longer than 256 characters",
80
+ asset_missing: "the image needs an asset uploaded to this site",
81
+ src_invalid: 'src must be a path such as /hero.jpg or an http(s) address; in an Astro project it may also be an imported image (import hero from "../assets/hero.jpg")',
82
+ alt_invalid: "alt must be a string of at most 300 characters; it may be empty",
83
+ size_invalid: "width and height must be whole numbers from 1 to 100,000",
84
+ unknown_type: "this field type has no single value; a list is checked with its row type"
85
+ };
86
+ var linkKeys = ["href", "label"];
87
+ var fallbackImageKeys = ["src", "file", "alt", "width", "height"];
88
+ var contentImageKeys = ["assetId", "src", "alt", "width", "height"];
89
+ var controlCharacter = /[\u0000-\u001f\u007f-\u009f]/u;
90
+ var asciiBlank = /^[ \t\n\v\f\r]*$/u;
91
+ var uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
92
+ var webAddress = /^https?:\/\/[^/?#@]+(?:[/?#].*)?$/isu;
93
+ function fieldValueProblem(type, value, origin) {
94
+ switch (type) {
95
+ case "text":
96
+ case "longText":
97
+ if (typeof value !== "string")
98
+ return "not_text";
99
+ return codePoints(value) > FIELD_VALUE_LIMITS[type] ? "too_long" : null;
100
+ case "link":
101
+ return linkProblem(value);
102
+ case "image":
103
+ return imageProblem(value, origin);
104
+ case "array":
105
+ return "unknown_type";
106
+ }
107
+ }
108
+ var CONTENT_VALUE_LIMITS = { valueBytes: 256 * 1024, listDepth: 3, blurDataURL: 1024 };
109
+ var CONTENT_VALUE_PROBLEMS = [
110
+ ...FIELD_VALUE_PROBLEMS,
111
+ "required",
112
+ "not_list",
113
+ "key_missing",
114
+ "key_invalid",
115
+ "key_duplicate",
116
+ "too_few_rows",
117
+ "too_many_rows",
118
+ "too_deep",
119
+ "too_large",
120
+ "focus_invalid",
121
+ "blur_invalid"
122
+ ];
123
+ var CONTENT_VALUE_PROBLEM_TEXT = {
124
+ ...FIELD_VALUE_PROBLEM_TEXT,
125
+ unknown_key: "it has keys the field type or the row type does not know",
126
+ required: "it is required and cannot be empty",
127
+ not_list: "a list must be an array of rows",
128
+ key_missing: "the row has no _key; Siteplane gives a key to each row you add",
129
+ key_invalid: "the row's _key must be eight lowercase letters and digits starting with a letter, as Siteplane gives them; never write a key by hand",
130
+ key_duplicate: "another row of this list has the same _key; remove the _key from the row you added",
131
+ too_few_rows: "the list has fewer rows than its minRows",
132
+ too_many_rows: "the list has more rows than its maxRows",
133
+ too_deep: "lists stand in lists at most three levels deep",
134
+ too_large: "the value is larger than 256 KB",
135
+ focus_invalid: "focus must be { x, y } with numbers from 0 to 1",
136
+ blur_invalid: "blurDataURL must be a data address of an image of at most 1 KB; Siteplane sets it"
137
+ };
138
+ function linkProblem(value) {
139
+ if (!isRecord(value))
140
+ return "not_object";
141
+ if (hasUnknownKey(value, linkKeys))
142
+ return "unknown_key";
143
+ if (!isHref(value.href))
144
+ return "href_invalid";
145
+ if (typeof value.label !== "string" || asciiBlank.test(value.label))
146
+ return "label_missing";
147
+ return codePoints(value.label) > FIELD_VALUE_LIMITS.linkLabel ? "label_too_long" : null;
148
+ }
149
+ function imageProblem(value, origin) {
150
+ if (!isRecord(value))
151
+ return "not_object";
152
+ if (hasUnknownKey(value, origin === "content" ? contentImageKeys : fallbackImageKeys))
153
+ return "unknown_key";
154
+ if (origin === "content" && (typeof value.assetId !== "string" || !uuidPattern.test(value.assetId))) {
155
+ return "asset_missing";
156
+ }
157
+ const source = value.file === void 0 ? isImageSource(value.src) : value.src === void 0 && isImportPath(value.file);
158
+ if (!source)
159
+ return "src_invalid";
160
+ if (typeof value.alt !== "string" || codePoints(value.alt) > FIELD_VALUE_LIMITS.imageAlt)
161
+ return "alt_invalid";
162
+ const sizeRequired = origin === "content";
163
+ for (const size of [value.width, value.height]) {
164
+ if (size === void 0 ? sizeRequired : !isImageSize(size))
165
+ return "size_invalid";
166
+ }
167
+ return null;
168
+ }
169
+ function isHref(value) {
170
+ if (!isAddressText(value, FIELD_VALUE_LIMITS.linkHref))
171
+ return false;
172
+ return isSitePath(value) || value.startsWith("#") || webAddress.test(value) || /^mailto:.+$/isu.test(value) || /^tel:\+?[0-9][0-9().-]*$/iu.test(value);
173
+ }
174
+ function isImageSource(value) {
175
+ return isAddressText(value, FIELD_VALUE_LIMITS.imageSrc) && (isSitePath(value) || webAddress.test(value));
176
+ }
177
+ function isImportPath(value) {
178
+ return typeof value === "string" && value.length > 0 && codePoints(value) <= FIELD_VALUE_LIMITS.imageFile && !controlCharacter.test(value);
179
+ }
180
+ function isSitePath(value) {
181
+ return value.startsWith("/") && !value.startsWith("//");
182
+ }
183
+ function isAddressText(value, maxLength) {
184
+ if (typeof value !== "string" || value.length === 0 || codePoints(value) > maxLength)
185
+ return false;
186
+ for (const character of value) {
187
+ const code = character.codePointAt(0);
188
+ if (code <= 32 || code === 127 || character === "\\")
189
+ return false;
190
+ }
191
+ return true;
192
+ }
193
+ function isImageSize(value) {
194
+ return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= FIELD_VALUE_LIMITS.imageSize;
195
+ }
196
+ function hasUnknownKey(value, keys) {
197
+ return Object.keys(value).some((key) => !keys.includes(key));
198
+ }
199
+ function codePoints(value) {
200
+ return Array.from(value).length;
201
+ }
202
+ function isRecord(value) {
203
+ return typeof value === "object" && value !== null && !Array.isArray(value);
204
+ }
205
+
206
+ // ../shared/dist/website-status.js
207
+ function isRevision(value) {
208
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
209
+ }
210
+
211
+ // ../shared/dist/siteplane-config.js
212
+ var SITEPLANE_CONFIG_FILE = "siteplane.config.json";
213
+ var siteIdPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;
214
+ function readSiteplaneConfig(value) {
215
+ if (typeof value !== "object" || value === null)
216
+ return null;
217
+ const { siteId, apiOrigin, editorOrigins } = value;
218
+ if (typeof siteId !== "string" || !siteIdPattern.test(siteId) || !isWebOrigin(apiOrigin) || !Array.isArray(editorOrigins) || !editorOrigins.every(isWebOrigin)) {
219
+ return null;
220
+ }
221
+ return { siteId, apiOrigin, editorOrigins: [...editorOrigins] };
222
+ }
223
+ function isWebOrigin(value) {
224
+ if (typeof value !== "string")
225
+ return false;
226
+ try {
227
+ const url = new URL(value);
228
+ return (url.protocol === "https:" || url.protocol === "http:") && url.origin === value;
229
+ } catch {
230
+ return false;
231
+ }
232
+ }
233
+
234
+ // ../shared/dist/runtime-urls.js
235
+ function runtimeValuesUrl(apiOrigin, siteId) {
236
+ return `${siteUrl(apiOrigin, siteId)}/values`;
237
+ }
238
+ function siteUrl(apiOrigin, siteId) {
239
+ return `${runtimeApi(apiOrigin)}/sites/${encodeURIComponent(siteId)}`;
240
+ }
241
+ function runtimeApi(apiOrigin) {
242
+ return `${apiOrigin.replace(/\/+$/u, "")}/api/runtime/v1`;
243
+ }
244
+
245
+ // ../shared/dist/signing-keys.js
246
+ var pkcs8Ed25519Prefix = Uint8Array.from([
247
+ 48,
248
+ 46,
249
+ 2,
250
+ 1,
251
+ 0,
252
+ 48,
253
+ 5,
254
+ 6,
255
+ 3,
256
+ 43,
257
+ 101,
258
+ 112,
259
+ 4,
260
+ 34,
261
+ 4,
262
+ 32
263
+ ]);
264
+ var ed25519 = { name: "Ed25519" };
265
+ async function verifyWithSigningKey(publicKey, signature, data) {
266
+ const key = await crypto.subtle.importKey("raw", decodeKey(publicKey, "whpk_"), ed25519, false, ["verify"]);
267
+ return crypto.subtle.verify(ed25519, key, signature, data);
268
+ }
269
+ function decodeBase64(value) {
270
+ const standard = value.replace(/-/gu, "+").replace(/_/gu, "/");
271
+ return Uint8Array.from(atob(standard.padEnd(Math.ceil(standard.length / 4) * 4, "=")), (character) => character.charCodeAt(0));
272
+ }
273
+ function decodeKey(key, prefix) {
274
+ let bytes;
275
+ try {
276
+ if (key.startsWith(prefix))
277
+ bytes = decodeBase64(key.slice(prefix.length));
278
+ } catch {
279
+ bytes = void 0;
280
+ }
281
+ if (bytes?.length !== 32)
282
+ throw new Error("invalid_signing_key");
283
+ return bytes;
284
+ }
285
+
286
+ // ../shared/dist/preview-token.js
287
+ var PREVIEW_TOKEN_MAX_SECONDS = 60 * 60;
288
+ var header = encodeJson({ alg: "EdDSA", typ: "JWT" });
289
+ var clockSkewSeconds = 60;
290
+ async function verifyPreviewToken(input) {
291
+ const parts = input.token.split(".");
292
+ const nowSeconds = Math.floor((input.now ?? /* @__PURE__ */ new Date()).getTime() / 1e3);
293
+ let claims = null;
294
+ let signature = null;
295
+ if (parts.length === 3 && parts[0] === header) {
296
+ try {
297
+ claims = readClaims(JSON.parse(new TextDecoder().decode(decodeBase64(parts[1]))), nowSeconds);
298
+ signature = decodeBase64(parts[2]);
299
+ } catch {
300
+ claims = null;
301
+ }
302
+ }
303
+ if (!claims || !signature)
304
+ return { ok: false, reason: "malformed" };
305
+ const signingInput = new TextEncoder().encode(`${parts[0]}.${parts[1]}`);
306
+ let signed = false;
307
+ for (const publicKey of input.publicKeys) {
308
+ signed = await verifyWithSigningKey(publicKey, signature, signingInput);
309
+ if (signed)
310
+ break;
311
+ }
312
+ if (!signed)
313
+ return { ok: false, reason: "signature_invalid" };
314
+ if (claims.aud !== input.siteId)
315
+ return { ok: false, reason: "wrong_site" };
316
+ if (claims.exp <= nowSeconds)
317
+ return { ok: false, reason: "expired" };
318
+ return { ok: true, claims };
319
+ }
320
+ function readClaims(value, nowSeconds) {
321
+ if (typeof value !== "object" || value === null)
322
+ return null;
323
+ const claims = value;
324
+ const { aud, sub, scope, actor, editor_origin: editorOrigin, iat, exp, jti } = claims;
325
+ if (typeof aud !== "string" || !aud || typeof sub !== "string" || !sub || scope !== "drafts:read" || actor !== "workspace_member" && actor !== "site_member" || typeof editorOrigin !== "string" || !isOrigin(editorOrigin) || !Number.isSafeInteger(iat) || !Number.isSafeInteger(exp) || typeof iat !== "number" || typeof exp !== "number" || exp - iat > PREVIEW_TOKEN_MAX_SECONDS || iat > nowSeconds + clockSkewSeconds || typeof jti !== "string" || !jti) {
326
+ return null;
327
+ }
328
+ return { aud, sub, scope, actor, editor_origin: editorOrigin, iat, exp, jti };
329
+ }
330
+ function isOrigin(value) {
331
+ try {
332
+ return new URL(value).origin === value;
333
+ } catch {
334
+ return false;
335
+ }
336
+ }
337
+ function encodeJson(value) {
338
+ return toBase64Url(new TextEncoder().encode(JSON.stringify(value)));
339
+ }
340
+ function toBase64Url(bytes) {
341
+ let binary = "";
342
+ for (const byte of bytes)
343
+ binary += String.fromCharCode(byte);
344
+ return btoa(binary).replace(/\+/gu, "-").replace(/\//gu, "_").replace(/=+$/u, "");
345
+ }
346
+
347
+ // ../shared/dist/webhook-signature.js
348
+ var WEBHOOK_TOLERANCE_SECONDS = 5 * 60;
349
+ var encoder = new TextEncoder();
350
+ function webhookSignedContent(id, timestamp, payload) {
351
+ return `${id}.${timestamp}.${payload}`;
352
+ }
353
+ async function verifyWebhook(input) {
354
+ const read = (name) => input.headers instanceof Headers ? input.headers.get(name) : input.headers[name];
355
+ const id = read("webhook-id");
356
+ const timestamp = read("webhook-timestamp");
357
+ const signatureHeader = read("webhook-signature");
358
+ if (!id || !timestamp || !signatureHeader)
359
+ return { ok: false, reason: "missing_headers" };
360
+ const nowSeconds = Math.floor((input.now ?? /* @__PURE__ */ new Date()).getTime() / 1e3);
361
+ if (!/^\d{1,12}$/u.test(timestamp) || Math.abs(nowSeconds - Number(timestamp)) > WEBHOOK_TOLERANCE_SECONDS) {
362
+ return { ok: false, reason: "timestamp_out_of_window" };
363
+ }
364
+ const content = encoder.encode(webhookSignedContent(id, timestamp, input.payload));
365
+ const signatures = signatureHeader.split(" ").flatMap((entry) => {
366
+ const [version, signature] = entry.split(",");
367
+ if (version !== "v1a" || !signature)
368
+ return [];
369
+ try {
370
+ return [decodeBase64(signature)];
371
+ } catch {
372
+ return [];
373
+ }
374
+ });
375
+ for (const publicKey of input.publicKeys) {
376
+ for (const signature of signatures) {
377
+ if (await verifyWithSigningKey(publicKey, signature, content))
378
+ return { ok: true };
379
+ }
380
+ }
381
+ return { ok: false, reason: "no_matching_signature" };
382
+ }
383
+
384
+ // ../shared/dist/astro-page-cache.js
385
+ import ts from "typescript";
386
+ var ADAPTERS = [
387
+ {
388
+ cache: "vercel-isr",
389
+ option: "isr",
390
+ modules: ["@astrojs/vercel", "@astrojs/vercel/serverless", "@astrojs/vercel/static"]
391
+ },
392
+ {
393
+ cache: "netlify-on-demand",
394
+ option: "cacheOnDemandPages",
395
+ modules: ["@astrojs/netlify", "@astrojs/netlify/functions", "@astrojs/netlify/static"]
396
+ }
397
+ ];
398
+ var CONFIG_FILE = "/astro.config.ts";
399
+ var previewComparisons = /* @__PURE__ */ new WeakMap();
400
+ var previewBranches = /* @__PURE__ */ new WeakMap();
401
+ function detectAstroPageCache(configSource, options = {}) {
402
+ try {
403
+ const file = ts.createSourceFile(CONFIG_FILE, configSource, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
404
+ if (hasSyntaxErrors(file))
405
+ return "unknown";
406
+ const config = readConfig(file, options.preview === true);
407
+ const [vercel, netlify] = ADAPTERS.map(({ modules, option }) => adapterSwitch(config, modules, option));
408
+ const routeCache = routeCacheSwitch(config);
409
+ if (vercel === "on")
410
+ return "vercel-isr";
411
+ if (netlify === "on")
412
+ return "netlify-on-demand";
413
+ if (vercel === "unknown" || netlify === "unknown" || routeCache === "unknown")
414
+ return "unknown";
415
+ return routeCache === "on" ? "astro-route-cache" : "none";
416
+ } catch {
417
+ return "unknown";
418
+ }
419
+ }
420
+ function adapterSwitch(config, modules, option) {
421
+ const states = config.unfollowed.some((module) => modules.includes(module)) ? ["unknown"] : [];
422
+ const names = new Set(config.bindings.filter(({ module }) => modules.includes(module)).map(({ name }) => name));
423
+ for (const identifier of config.identifiers) {
424
+ if (!names.has(identifier.text) || !isValueReference(identifier))
425
+ continue;
426
+ const parent = identifier.parent;
427
+ states.push(ts.isCallExpression(parent) && parent.expression === identifier ? callSwitch(parent, option) : "unknown");
428
+ }
429
+ return strongest(states);
430
+ }
431
+ function callSwitch(call, option) {
432
+ const [first] = call.arguments;
433
+ if (!first)
434
+ return "off";
435
+ const options = unwrap(first);
436
+ if (!ts.isObjectLiteralExpression(options))
437
+ return truth(options) === false ? "off" : "unknown";
438
+ return optionSwitch(entries(null, options), option, (value) => toSwitch(truth(value)));
439
+ }
440
+ function routeCacheSwitch(config) {
441
+ const states = [];
442
+ for (const { left, right } of config.assignments) {
443
+ const name = assignedName(left);
444
+ if (name === "cache")
445
+ states.push(cacheSwitch(right));
446
+ if (name === "experimental")
447
+ states.push(experimentalSwitch(right));
448
+ }
449
+ let readable2 = config.roots.length > 0;
450
+ for (const root of config.roots) {
451
+ const object = resolveConfig(config, root);
452
+ if (!ts.isObjectLiteralExpression(object)) {
453
+ readable2 = false;
454
+ continue;
455
+ }
456
+ const items = entries(config, object);
457
+ states.push(optionSwitch(items, "cache", cacheSwitch), optionSwitch(items, "experimental", experimentalSwitch));
458
+ }
459
+ if (!readable2) {
460
+ for (const object of config.objects) {
461
+ for (const { name, value } of entries(null, object)) {
462
+ if (name === "cache")
463
+ states.push(value ? cacheSwitch(value) : "unknown");
464
+ if (name === "experimental")
465
+ states.push(value ? experimentalSwitch(value) : "unknown");
466
+ }
467
+ }
468
+ }
469
+ return strongest(states);
470
+ }
471
+ function experimentalSwitch(expression) {
472
+ const value = unwrap(expression);
473
+ if (ts.isObjectLiteralExpression(value))
474
+ return optionSwitch(entries(null, value), "cache", cacheSwitch);
475
+ return truth(value) === false ? "off" : "unknown";
476
+ }
477
+ function cacheSwitch(expression) {
478
+ const value = unwrap(expression);
479
+ if (ts.isObjectLiteralExpression(value))
480
+ return optionSwitch(entries(null, value), "provider", providerSwitch);
481
+ return truth(value) === false ? "off" : "unknown";
482
+ }
483
+ function providerSwitch(expression) {
484
+ const value = unwrap(expression);
485
+ if (truth(value) === false)
486
+ return "off";
487
+ return ts.isCallExpression(value) || ts.isNewExpression(value) || ts.isObjectLiteralExpression(value) ? "on" : "unknown";
488
+ }
489
+ function optionSwitch(items, option, valueSwitch) {
490
+ for (const { name, value } of [...items].reverse()) {
491
+ if (name === null)
492
+ return "unknown";
493
+ if (name === option)
494
+ return value ? valueSwitch(value) : "unknown";
495
+ }
496
+ return "off";
497
+ }
498
+ function truth(expression) {
499
+ const value = unwrap(expression);
500
+ const decided = previewComparisons.get(value);
501
+ if (decided !== void 0)
502
+ return decided;
503
+ if (value.kind === ts.SyntaxKind.TrueKeyword)
504
+ return true;
505
+ if (value.kind === ts.SyntaxKind.FalseKeyword || value.kind === ts.SyntaxKind.NullKeyword)
506
+ return false;
507
+ if (ts.isIdentifier(value) && value.text === "undefined" || ts.isVoidExpression(value))
508
+ return false;
509
+ if (ts.isNumericLiteral(value))
510
+ return Number(value.text) !== 0;
511
+ if (ts.isStringLiteralLike(value))
512
+ return value.text !== "";
513
+ if (ts.isObjectLiteralExpression(value) || ts.isArrayLiteralExpression(value))
514
+ return true;
515
+ if (ts.isPrefixUnaryExpression(value) && value.operator === ts.SyntaxKind.ExclamationToken) {
516
+ const inner = truth(value.operand);
517
+ return inner === void 0 ? void 0 : !inner;
518
+ }
519
+ return void 0;
520
+ }
521
+ function toSwitch(value) {
522
+ return value === void 0 ? "unknown" : value ? "on" : "off";
523
+ }
524
+ function strongest(states) {
525
+ if (states.includes("on"))
526
+ return "on";
527
+ return states.includes("unknown") ? "unknown" : "off";
528
+ }
529
+ function entries(config, object, depth = 0) {
530
+ return object.properties.flatMap((property) => {
531
+ if (ts.isSpreadAssignment(property)) {
532
+ const spread = config ? resolveConfig(config, property.expression) : unwrap(property.expression);
533
+ return ts.isObjectLiteralExpression(spread) && depth < 10 ? entries(config, spread, depth + 1) : [{ name: null, value: null }];
534
+ }
535
+ if (ts.isShorthandPropertyAssignment(property))
536
+ return [{ name: property.name.text, value: property.name }];
537
+ const name = propertyName(property.name);
538
+ if (ts.isPropertyAssignment(property))
539
+ return [{ name, value: name === null ? null : property.initializer }];
540
+ return [{ name, value: null }];
541
+ });
542
+ }
543
+ function propertyName(name) {
544
+ if (!name)
545
+ return null;
546
+ if (ts.isComputedPropertyName(name)) {
547
+ const key = unwrap(name.expression);
548
+ return ts.isStringLiteralLike(key) ? key.text : null;
549
+ }
550
+ return ts.isIdentifier(name) || ts.isStringLiteralLike(name) || ts.isNumericLiteral(name) ? name.text : null;
551
+ }
552
+ function assignedName(left) {
553
+ const target = unwrap(left);
554
+ if (ts.isPropertyAccessExpression(target))
555
+ return target.name.text;
556
+ if (ts.isElementAccessExpression(target)) {
557
+ const key = unwrap(target.argumentExpression);
558
+ return ts.isStringLiteralLike(key) ? key.text : null;
559
+ }
560
+ return null;
561
+ }
562
+ function resolveConfig(config, expression) {
563
+ let value = unwrap(expression);
564
+ for (let step = 0; step < 10; step += 1) {
565
+ if (ts.isIdentifier(value)) {
566
+ const initializer = config.constants.get(value.text);
567
+ if (!initializer)
568
+ return value;
569
+ value = unwrap(initializer);
570
+ } else if (ts.isCallExpression(value) && isDefineConfig(config, value.expression) && configArgument(value)) {
571
+ value = unwrap(configArgument(value) ?? value);
572
+ } else {
573
+ return value;
574
+ }
575
+ }
576
+ return value;
577
+ }
578
+ function unwrap(expression) {
579
+ let value = expression;
580
+ for (; ; ) {
581
+ if (ts.isParenthesizedExpression(value) || ts.isAsExpression(value) || ts.isSatisfiesExpression(value) || ts.isTypeAssertionExpression(value) || ts.isNonNullExpression(value)) {
582
+ value = value.expression;
583
+ continue;
584
+ }
585
+ const branch = previewBranches.get(value);
586
+ if (!branch)
587
+ return value;
588
+ value = branch;
589
+ }
590
+ }
591
+ function previewComparison(node, preview) {
592
+ if (!ts.isBinaryExpression(node))
593
+ return void 0;
594
+ const equals = node.operatorToken.kind === ts.SyntaxKind.EqualsEqualsEqualsToken;
595
+ if (!equals && node.operatorToken.kind !== ts.SyntaxKind.ExclamationEqualsEqualsToken)
596
+ return void 0;
597
+ const right = unwrap(node.right);
598
+ if (!isPreviewSwitch(unwrap(node.left)) || !ts.isStringLiteralLike(right) || right.text !== "1")
599
+ return void 0;
600
+ return equals === preview;
601
+ }
602
+ function isPreviewSwitch(expression) {
603
+ if (!ts.isPropertyAccessExpression(expression) || expression.name.text !== "SITEPLANE_PREVIEW")
604
+ return false;
605
+ const env = expression.expression;
606
+ return ts.isPropertyAccessExpression(env) && env.name.text === "env" && ts.isIdentifier(env.expression) && env.expression.text === "process";
607
+ }
608
+ function isDefineConfig(config, callee) {
609
+ if (ts.isIdentifier(callee))
610
+ return config.defineConfig.has(callee.text);
611
+ return ts.isPropertyAccessExpression(callee) && callee.name.text === "defineConfig";
612
+ }
613
+ function configArgument(call) {
614
+ const [first] = call.arguments;
615
+ return first && !ts.isSpreadElement(first) ? first : null;
616
+ }
617
+ function isValueReference(identifier) {
618
+ const parent = identifier.parent;
619
+ if (ts.isImportClause(parent) || ts.isImportSpecifier(parent) || ts.isNamespaceImport(parent))
620
+ return false;
621
+ if (ts.isQualifiedName(parent) || ts.isTypeReferenceNode(parent) || ts.isTypeQueryNode(parent))
622
+ return false;
623
+ if (ts.isBindingElement(parent) && parent.propertyName === identifier)
624
+ return false;
625
+ if ((ts.isVariableDeclaration(parent) || ts.isParameter(parent) || ts.isBindingElement(parent) || ts.isFunctionDeclaration(parent) || ts.isClassDeclaration(parent) || ts.isPropertyAccessExpression(parent) || ts.isPropertyAssignment(parent) || ts.isMethodDeclaration(parent) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent) || ts.isGetAccessorDeclaration(parent) || ts.isSetAccessorDeclaration(parent)) && parent.name === identifier) {
626
+ return false;
627
+ }
628
+ return true;
629
+ }
630
+ function readConfig(file, preview) {
631
+ const config = {
632
+ identifiers: [],
633
+ calls: [],
634
+ objects: [],
635
+ assignments: [],
636
+ roots: [],
637
+ bindings: [],
638
+ unfollowed: [],
639
+ constants: /* @__PURE__ */ new Map(),
640
+ defineConfig: /* @__PURE__ */ new Set(["defineConfig"])
641
+ };
642
+ const declared = /* @__PURE__ */ new Map();
643
+ const declare = (name, initializer) => {
644
+ if (!name || !ts.isIdentifier(name))
645
+ return;
646
+ const count = (declared.get(name.text) ?? 0) + 1;
647
+ declared.set(name.text, count);
648
+ config.constants.set(name.text, count === 1 && initializer ? initializer : null);
649
+ };
650
+ const visit = (node) => {
651
+ if (ts.isBinaryExpression(node)) {
652
+ const decided = previewComparison(node, preview);
653
+ if (decided !== void 0)
654
+ previewComparisons.set(node, decided);
655
+ }
656
+ if (ts.isConditionalExpression(node)) {
657
+ const decided = previewComparison(unwrap(node.condition), preview);
658
+ if (decided !== void 0) {
659
+ const branch = decided ? node.whenTrue : node.whenFalse;
660
+ previewBranches.set(node, branch);
661
+ visit(node.condition);
662
+ visit(branch);
663
+ return;
664
+ }
665
+ }
666
+ if (ts.isIdentifier(node))
667
+ config.identifiers.push(node);
668
+ else if (ts.isCallExpression(node))
669
+ config.calls.push(node);
670
+ else if (ts.isObjectLiteralExpression(node))
671
+ config.objects.push(node);
672
+ else if (ts.isExportAssignment(node))
673
+ config.roots.push(node.expression);
674
+ else if (ts.isImportDeclaration(node))
675
+ readImport(node, config);
676
+ else if (ts.isExportDeclaration(node) && node.moduleSpecifier && ts.isStringLiteralLike(node.moduleSpecifier)) {
677
+ config.unfollowed.push(node.moduleSpecifier.text);
678
+ } else if (ts.isBinaryExpression(node) && isAssignment(node.operatorToken.kind)) {
679
+ config.assignments.push(node);
680
+ if (ts.isPropertyAccessExpression(node.left) && node.left.getText(file) === "module.exports")
681
+ config.roots.push(node.right);
682
+ }
683
+ if (ts.isVariableDeclaration(node)) {
684
+ const constant = (ts.getCombinedNodeFlags(node) & ts.NodeFlags.Const) !== 0;
685
+ declare(node.name, constant ? node.initializer : void 0);
686
+ } else if (ts.isParameter(node) || ts.isBindingElement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isImportClause(node) || ts.isImportSpecifier(node) || ts.isNamespaceImport(node)) {
687
+ declare(node.name);
688
+ }
689
+ ts.forEachChild(node, visit);
690
+ };
691
+ visit(file);
692
+ for (const call of config.calls) {
693
+ if (isDefineConfig(config, call.expression)) {
694
+ const argument = configArgument(call);
695
+ if (argument)
696
+ config.roots.push(argument);
697
+ }
698
+ for (const argument of call.arguments) {
699
+ const specifier = ts.isStringLiteralLike(argument) ? argument.text : null;
700
+ if (!specifier || !isAdapterModule(specifier))
701
+ continue;
702
+ const name = requiredName(call);
703
+ if (name)
704
+ config.bindings.push({ module: specifier, name });
705
+ else
706
+ config.unfollowed.push(specifier);
707
+ }
708
+ }
709
+ return config;
710
+ }
711
+ function readImport(node, config) {
712
+ const specifier = ts.isStringLiteralLike(node.moduleSpecifier) ? node.moduleSpecifier.text : null;
713
+ const clause = node.importClause;
714
+ if (!specifier || !clause || clause.isTypeOnly)
715
+ return;
716
+ const named = clause.namedBindings;
717
+ if (specifier === "astro/config" && named && ts.isNamedImports(named)) {
718
+ for (const element of named.elements) {
719
+ if ((element.propertyName ?? element.name).text === "defineConfig")
720
+ config.defineConfig.add(element.name.text);
721
+ }
722
+ }
723
+ if (!isAdapterModule(specifier))
724
+ return;
725
+ if (clause.name)
726
+ config.bindings.push({ module: specifier, name: clause.name.text });
727
+ if (named && ts.isNamespaceImport(named))
728
+ config.unfollowed.push(specifier);
729
+ if (named && ts.isNamedImports(named)) {
730
+ for (const element of named.elements) {
731
+ if (!element.isTypeOnly && (element.propertyName ?? element.name).text === "default") {
732
+ config.bindings.push({ module: specifier, name: element.name.text });
733
+ }
734
+ }
735
+ }
736
+ }
737
+ function isAdapterModule(specifier) {
738
+ return ADAPTERS.some(({ modules }) => modules.includes(specifier));
739
+ }
740
+ function requiredName(call) {
741
+ if (!ts.isIdentifier(call.expression) || call.expression.text !== "require")
742
+ return null;
743
+ const parent = ts.isPropertyAccessExpression(call.parent) && call.parent.name.text === "default" ? call.parent.parent : call.parent;
744
+ return ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) ? parent.name.text : null;
745
+ }
746
+ function isAssignment(kind) {
747
+ return kind >= ts.SyntaxKind.FirstAssignment && kind <= ts.SyntaxKind.LastAssignment;
748
+ }
749
+ function hasSyntaxErrors(file) {
750
+ const host = {
751
+ fileExists: (name) => name === file.fileName,
752
+ getSourceFile: (name) => name === file.fileName ? file : void 0,
753
+ readFile: () => void 0,
754
+ writeFile: () => {
755
+ },
756
+ getDefaultLibFileName: () => "/lib.d.ts",
757
+ getCurrentDirectory: () => "/",
758
+ getCanonicalFileName: (name) => name,
759
+ useCaseSensitiveFileNames: () => true,
760
+ getNewLine: () => "\n"
761
+ };
762
+ return ts.createProgram([file.fileName], { noLib: true, noResolve: true }, host).getSyntacticDiagnostics(file).length > 0;
763
+ }
764
+
765
+ // src/runtime/fetch-json.ts
766
+ var SITEPLANE_DEADLINE_MS = 3e3;
767
+ var MAX_BODY_BYTES = 10 * 1024 * 1024;
768
+ async function readBoundedText(body, maxBytes) {
769
+ if (!body) return "";
770
+ const reader = body.getReader();
771
+ const chunks = [];
772
+ let bytes = 0;
773
+ for (; ; ) {
774
+ const chunk = await reader.read();
775
+ if (chunk.done) break;
776
+ bytes += chunk.value.byteLength;
777
+ if (bytes > maxBytes) {
778
+ await reader.cancel();
779
+ return null;
780
+ }
781
+ chunks.push(chunk.value);
782
+ }
783
+ const combined = new Uint8Array(bytes);
784
+ let offset = 0;
785
+ for (const chunk of chunks) {
786
+ combined.set(chunk, offset);
787
+ offset += chunk.byteLength;
788
+ }
789
+ return new TextDecoder().decode(combined);
790
+ }
791
+
792
+ // src/runtime/preview.ts
793
+ var COUNT_COOKIE = "siteplane-count";
794
+ async function verifySitePreviewToken(config, token, keys, now) {
795
+ const verify = async (reload) => verifyPreviewToken({
796
+ token,
797
+ siteId: config.siteId,
798
+ publicKeys: await keys(config, "preview", reload ? { reload } : {}),
799
+ now
800
+ });
801
+ let result = await verify(false);
802
+ if (!result.ok && result.reason === "signature_invalid") result = await verify(true);
803
+ return result.ok ? result.claims : null;
804
+ }
805
+ async function verifySiteRevalidation(config, request, keys, now) {
806
+ const verify = async (reload) => verifyWebhook({
807
+ headers: request.headers,
808
+ payload: request.payload,
809
+ publicKeys: await keys(config, "revalidation", reload ? { reload } : {}),
810
+ now
811
+ });
812
+ let result = await verify(false);
813
+ if (!result.ok && result.reason === "no_matching_signature") result = await verify(true);
814
+ return result.ok;
815
+ }
816
+
817
+ // src/runtime/values.ts
818
+ var BUILD_READ_LIMITS = { attempts: 3, budgetMs: 1e4, attemptMs: SITEPLANE_DEADLINE_MS, pausesMs: [500, 1e3] };
819
+ var MAX_VALUES_BYTES = 10 * 1024 * 1024;
820
+ var realTiming = {
821
+ now: () => performance.now(),
822
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms))
823
+ };
824
+ function siteCacheTag(siteId) {
825
+ return `siteplane:${siteId}`;
826
+ }
827
+ function buildFailedMessage(config, reason) {
828
+ const host = hostOf(config);
829
+ return `[Siteplane] The build could not read the content of this website from ${host} (${reason}; ${BUILD_READ_LIMITS.attempts} attempts within ${BUILD_READ_LIMITS.budgetMs / 1e3} s), and there is no content of an earlier build, so it stops here. The current version of the website stays online. Build again once ${host} answers.`;
830
+ }
831
+ function hostOf(config) {
832
+ try {
833
+ return new URL(config.apiOrigin).host;
834
+ } catch {
835
+ return "Siteplane";
836
+ }
837
+ }
838
+ async function readValuesForBuild(read, timing = realTiming, firstFailed) {
839
+ const started = timing.now();
840
+ const elapsed = () => timing.now() - started;
841
+ let first = null;
842
+ let attempts = 0;
843
+ while (attempts < BUILD_READ_LIMITS.attempts) {
844
+ const left = BUILD_READ_LIMITS.budgetMs - elapsed();
845
+ if (left <= 0) break;
846
+ attempts += 1;
847
+ const result = await read(Math.min(BUILD_READ_LIMITS.attemptMs, left));
848
+ if (result.ok) return { ...result, attempts, elapsedMs: elapsed() };
849
+ if (first === null) firstFailed?.(result.reason);
850
+ first ??= result.reason;
851
+ const pause = BUILD_READ_LIMITS.pausesMs[attempts - 1];
852
+ if (attempts < BUILD_READ_LIMITS.attempts && pause !== void 0 && elapsed() + pause < BUILD_READ_LIMITS.budgetMs) {
853
+ await timing.sleep(pause);
854
+ }
855
+ }
856
+ return { ok: false, reason: first ?? `no answer within ${BUILD_READ_LIMITS.budgetMs / 1e3} s`, attempts, elapsedMs: elapsed() };
857
+ }
858
+ async function readValues(fetchImpl, config, url, init, deadlineMs) {
859
+ const controller = new AbortController();
860
+ let timer;
861
+ const deadline2 = new Promise((resolve) => {
862
+ timer = setTimeout(() => {
863
+ controller.abort();
864
+ resolve({ ok: false, reason: `no answer within ${deadlineMs / 1e3} s` });
865
+ }, deadlineMs);
866
+ });
867
+ const attempt = (async () => {
868
+ let response;
869
+ try {
870
+ response = await fetchImpl(url, { ...init, signal: controller.signal });
871
+ } catch (error) {
872
+ return { ok: false, reason: networkReason(error) };
873
+ }
874
+ if (response.status !== 200) {
875
+ void response.body?.cancel().catch(() => {
876
+ });
877
+ return { ok: false, reason: `HTTP ${response.status}` };
878
+ }
879
+ let text;
880
+ try {
881
+ text = await readBoundedText(response.body, MAX_VALUES_BYTES);
882
+ } catch (error) {
883
+ return { ok: false, reason: networkReason(error) };
884
+ }
885
+ if (text === null) return { ok: false, reason: "an answer larger than 10 MB" };
886
+ let body;
887
+ try {
888
+ body = JSON.parse(text);
889
+ } catch {
890
+ return { ok: false, reason: "an answer that is not JSON" };
891
+ }
892
+ const { siteId, values, revision } = isRecord2(body) ? body : {};
893
+ if (siteId !== config.siteId) return { ok: false, reason: "an answer for another site" };
894
+ if (!isRecord2(values)) return { ok: false, reason: "an answer without content" };
895
+ return { ok: true, values, revision: isRevision(revision) ? revision : null };
896
+ })();
897
+ try {
898
+ return await Promise.race([attempt, deadline2]);
899
+ } finally {
900
+ clearTimeout(timer);
901
+ }
902
+ }
903
+ function networkReason(error) {
904
+ const code = errorCode(error);
905
+ if (code === "ECONNREFUSED") return "connection refused";
906
+ if (code === "ECONNRESET" || code === "UND_ERR_SOCKET" || code === "EPIPE" || code === "UND_ERR_CLOSED") return "connection closed";
907
+ if (code === "ENOTFOUND" || code === "EAI_AGAIN") return "host not found";
908
+ return "network error";
909
+ }
910
+ function errorCode(error) {
911
+ for (let current = error, depth = 0; isRecord2(current) && depth < 4; depth += 1) {
912
+ if (typeof current.code === "string") return current.code;
913
+ const first = Array.isArray(current.errors) ? current.errors[0] : void 0;
914
+ if (isRecord2(first) && typeof first.code === "string") return first.code;
915
+ current = current.cause;
916
+ }
917
+ return null;
918
+ }
919
+ function isRecord2(value) {
920
+ return typeof value === "object" && value !== null && !Array.isArray(value);
921
+ }
922
+
923
+ // src/route/handlers.ts
924
+ var MAX_REVALIDATION_BYTES = 16 * 1024;
925
+ var noStore = { "Cache-Control": "no-store" };
926
+ function createRouteHandlers(dependencies) {
927
+ async function GET(request) {
928
+ const route = routeName(request);
929
+ const config = dependencies.config();
930
+ if (!config || route !== "status" && route !== "draft") return notFound();
931
+ return route === "status" ? status(config) : draft(request, config);
932
+ }
933
+ async function POST(request) {
934
+ const config = dependencies.config();
935
+ if (!config || routeName(request) !== "revalidate") return notFound();
936
+ return revalidate(request, config);
937
+ }
938
+ function status(config) {
939
+ const { VERCEL_GIT_COMMIT_SHA: commit, VERCEL_ENV: environment } = dependencies.env;
940
+ const answer = {
941
+ siteId: config.siteId,
942
+ version: dependencies.version,
943
+ commit: commit || null,
944
+ environment: environment || null,
945
+ ...statusDetails(),
946
+ ...dependencies.devServer ? { devServer: true } : {}
947
+ };
948
+ return Response.json(answer, { headers: noStore });
949
+ }
950
+ function statusDetails() {
951
+ try {
952
+ return dependencies.statusDetails?.() ?? {};
953
+ } catch {
954
+ return {};
955
+ }
956
+ }
957
+ async function draft(request, config) {
958
+ const url = new URL(request.url);
959
+ const query = url.searchParams;
960
+ const count = query.has("count");
961
+ if (count && !dependencies.devServer) return notFound();
962
+ const path = parseSafeRedirectPath(query.get("path") ?? "/");
963
+ if (!path) return Response.json({ error: "invalid_path" }, { status: 400, headers: noStore });
964
+ if (count) {
965
+ return redirect(url, path, await dependencies.enableCount?.() ?? {});
966
+ }
967
+ const now = dependencies.now();
968
+ const token = query.get("token") ?? "";
969
+ const claims = token ? await verifySitePreviewToken(config, token, dependencies.keys, now) : null;
970
+ if (!claims) return Response.json({ error: "preview_token_invalid" }, { status: 401, headers: noStore });
971
+ await dependencies.enableDraftMode({ token, maxAgeSeconds: claims.exp - Math.floor(now.getTime() / 1e3) });
972
+ return redirect(url, path);
973
+ }
974
+ function redirect(url, path, headers = {}) {
975
+ const root = url.pathname.endsWith("/") ? "../../../" : "../../";
976
+ return new Response(null, { status: 307, headers: { ...noStore, ...headers, Location: `${root}${path.slice(1)}` } });
977
+ }
978
+ async function revalidate(request, config) {
979
+ const payload = await readBoundedText(request.body, MAX_REVALIDATION_BYTES);
980
+ if (payload === null) return Response.json({ error: "too_large" }, { status: 413, headers: noStore });
981
+ const now = dependencies.now();
982
+ if (!await verifySiteRevalidation(config, { headers: request.headers, payload }, dependencies.keys, now)) {
983
+ return Response.json({ error: "invalid_signature" }, { status: 401, headers: noStore });
984
+ }
985
+ if (readSiteId(payload) !== config.siteId) {
986
+ return Response.json({ error: "wrong_site" }, { status: 403, headers: noStore });
987
+ }
988
+ dependencies.revalidateTag(siteCacheTag(config.siteId));
989
+ return Response.json({ revalidated: true }, { headers: noStore });
990
+ }
991
+ return { GET, POST };
992
+ }
993
+ function routeName(request) {
994
+ return /\/api\/siteplane\/([a-z]+)\/?$/u.exec(new URL(request.url).pathname)?.[1] ?? null;
995
+ }
996
+ function notFound() {
997
+ return Response.json({ error: "not_found" }, { status: 404, headers: noStore });
998
+ }
999
+ function readSiteId(payload) {
1000
+ try {
1001
+ return JSON.parse(payload).data?.siteId;
1002
+ } catch {
1003
+ return void 0;
1004
+ }
1005
+ }
1006
+
1007
+ // src/version.ts
1008
+ var PACKAGE_VERSION = "0.3.0";
1009
+
1010
+ // src/astro/build-images.ts
1011
+ import { mkdir, readdir, readFile, rename, rm, writeFile } from "fs/promises";
1012
+ var BUILD_IMAGE_LIMITS = { answerMs: 3e3, imageMs: 1e4, totalMs: 3e4, concurrency: 6 };
1013
+ var CONTENT_TYPES = {
1014
+ jpg: "image/jpeg",
1015
+ png: "image/png",
1016
+ webp: "image/webp",
1017
+ avif: "image/avif"
1018
+ };
1019
+ var UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
1020
+ var SITE_IMAGE_PATH = new RegExp(`^(${UUID})/(${UUID})\\.(jpg|png|webp|avif)$`, "u");
1021
+ var IMMUTABLE = "public, max-age=31536000, immutable";
1022
+ var MAX_IMAGE_BYTES = 20 * 1024 * 1024;
1023
+ var NAMED_FIELDS = 5;
1024
+ var ImageMiss = class extends Error {
1025
+ constructor(reason, status) {
1026
+ super(reason);
1027
+ this.reason = reason;
1028
+ this.status = status;
1029
+ }
1030
+ reason;
1031
+ status;
1032
+ };
1033
+ async function prepareBuildImages(input) {
1034
+ const limits = { ...BUILD_IMAGE_LIMITS, ...input.limits };
1035
+ const folder = new URL("siteplane/images/", input.cacheDir);
1036
+ const images = siteImages(input.values, input.apiOrigin);
1037
+ const copies = /* @__PURE__ */ new Map();
1038
+ const unavailable = [];
1039
+ if (images.length === 0) return { values: input.values, copies, unavailable };
1040
+ const readMetadata = await metadataReader();
1041
+ const missing = [];
1042
+ for (const image of images) {
1043
+ const copy = await readCopy(folder, image, readMetadata);
1044
+ if (copy) copies.set(image.src, copy);
1045
+ else missing.push(image);
1046
+ }
1047
+ const total = totalDeadline(limits.totalMs);
1048
+ let stopped = null;
1049
+ const miss = (image, error) => {
1050
+ const { reason, status } = error instanceof ImageMiss ? error : new ImageMiss("unreachable");
1051
+ if (reason === "unreachable" || reason === "timeout") stopped ??= reason;
1052
+ unavailable.push({ src: image.src, fieldIds: image.fieldIds, reason, ...status === void 0 ? {} : { status } });
1053
+ };
1054
+ const queue = [...missing];
1055
+ async function worker() {
1056
+ for (let image = queue.shift(); image; image = queue.shift()) {
1057
+ if (total.expired) miss(image, new ImageMiss("total_timeout"));
1058
+ else if (stopped) miss(image, new ImageMiss(stopped));
1059
+ else {
1060
+ try {
1061
+ const { bytes, contentType } = await download(image, input.fetch, limits, total);
1062
+ if (contentType !== CONTENT_TYPES[image.extension] || !await readable(readMetadata, bytes, image.src)) {
1063
+ throw new ImageMiss("invalid");
1064
+ }
1065
+ copies.set(image.src, await writeCopy(folder, image, bytes, contentType));
1066
+ } catch (error) {
1067
+ miss(image, error);
1068
+ }
1069
+ }
1070
+ }
1071
+ }
1072
+ await Promise.all(Array.from({ length: Math.min(limits.concurrency, missing.length) }, worker));
1073
+ total.clear();
1074
+ const order = new Map(images.map(({ src }, index) => [src, index]));
1075
+ unavailable.sort((first, second) => (order.get(first.src) ?? 0) - (order.get(second.src) ?? 0));
1076
+ const lost = new Set(unavailable.map(({ src }) => src));
1077
+ const values = lost.size === 0 ? input.values : moveToSecondPath(input.values, lost, input.apiOrigin);
1078
+ return { values, copies, unavailable };
1079
+ }
1080
+ function answerImageDownloadsFromCopies(copies) {
1081
+ const previous = globalThis.fetch;
1082
+ const wrapper = async (input, init) => {
1083
+ const url = requestUrl(input);
1084
+ const method = (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();
1085
+ const copy = url && (method === "GET" || method === "HEAD") ? copies.get(url) : void 0;
1086
+ if (!copy) return previous(input, init);
1087
+ let bytes;
1088
+ try {
1089
+ bytes = copy.kind === "memory" ? copy.bytes : new Uint8Array(await readFile(copy.file));
1090
+ } catch {
1091
+ return previous(input, init);
1092
+ }
1093
+ const response = new Response(method === "HEAD" ? null : bytes, {
1094
+ status: 200,
1095
+ headers: { "content-type": copy.contentType, "content-length": String(bytes.byteLength), "cache-control": IMMUTABLE }
1096
+ });
1097
+ Object.defineProperty(response, "url", { value: url });
1098
+ return response;
1099
+ };
1100
+ globalThis.fetch = wrapper;
1101
+ return {
1102
+ restore() {
1103
+ if (globalThis.fetch === wrapper) globalThis.fetch = previous;
1104
+ }
1105
+ };
1106
+ }
1107
+ function directImageAddress(src, apiOrigin) {
1108
+ const path = siteImagePath(src, apiOrigin);
1109
+ return path ? `${apiOrigin.replace(/\/+$/u, "")}/site-images-direct/${path.file}` : null;
1110
+ }
1111
+ function siteImagePath(src, apiOrigin) {
1112
+ const prefix = `${apiOrigin.replace(/\/+$/u, "")}/site-images/`;
1113
+ if (!src.startsWith(prefix)) return null;
1114
+ const file = src.slice(prefix.length);
1115
+ const [, , assetId, extension] = SITE_IMAGE_PATH.exec(file) ?? [];
1116
+ return assetId && extension ? { file, assetId, extension } : null;
1117
+ }
1118
+ function warnAboutMissingImages(logger, unavailable) {
1119
+ const groups = /* @__PURE__ */ new Map();
1120
+ for (const miss of unavailable) {
1121
+ const key = miss.reason === "rejected" ? `rejected ${miss.status ?? ""}` : miss.reason;
1122
+ groups.set(key, [...groups.get(key) ?? [], miss]);
1123
+ }
1124
+ for (const misses of groups.values()) {
1125
+ const [first] = misses;
1126
+ if (!first) continue;
1127
+ const host = hostOf2(first.src);
1128
+ const fields = fieldList(misses.flatMap(({ fieldIds }) => fieldIds));
1129
+ const count = misses.length;
1130
+ const images = `${count} ${count === 1 ? "image" : "images"}`;
1131
+ const shown = count === 1 ? "it is shown" : "they are shown";
1132
+ const status = first.status;
1133
+ switch (first.reason) {
1134
+ case "unreachable":
1135
+ logger.warn(
1136
+ `${host} could not be reached, so ${images} ${count === 1 ? "is" : "are"} shown without resizing (${fields}). Build again once ${host} is reachable.`
1137
+ );
1138
+ break;
1139
+ case "timeout":
1140
+ logger.warn(
1141
+ `${host} did not deliver ${images} in time (answer within ${seconds(BUILD_IMAGE_LIMITS.answerMs)}, image within ${seconds(BUILD_IMAGE_LIMITS.imageMs)}); ${shown} without resizing (${fields}). Build again later.`
1142
+ );
1143
+ break;
1144
+ case "total_timeout":
1145
+ logger.warn(
1146
+ `Loading images from ${host} took longer than ${seconds(BUILD_IMAGE_LIMITS.totalMs)}; ${images} ${count === 1 ? "is" : "are"} shown without resizing (${fields}). Build again later.`
1147
+ );
1148
+ break;
1149
+ case "rejected":
1150
+ if (status === 400 || status === 404 || status === 410) {
1151
+ logger.warn(
1152
+ `${host} has no image for ${fields} (HTTP ${status}). Replace the image in Siteplane; building again does not change this.`
1153
+ );
1154
+ } else if (status !== void 0 && status >= 300 && status < 400) {
1155
+ logger.warn(
1156
+ `${host} answered the image for ${fields} with a redirect (HTTP ${status}), which Siteplane does not follow; ${shown} without resizing. If this repeats, contact Siteplane.`
1157
+ );
1158
+ } else {
1159
+ logger.warn(
1160
+ `${host} refused the image for ${fields} (HTTP ${status ?? "?"}); ${shown} without resizing. Build again later; if this repeats, contact Siteplane.`
1161
+ );
1162
+ }
1163
+ break;
1164
+ case "invalid":
1165
+ logger.warn(
1166
+ `${host} did not send a valid image for ${fields}; ${shown} without resizing. Build again; if this repeats, contact Siteplane.`
1167
+ );
1168
+ break;
1169
+ }
1170
+ }
1171
+ }
1172
+ async function removeUnusedImageCopies(cacheDir, copies) {
1173
+ const folder = new URL("siteplane/images/", cacheDir);
1174
+ const kept = /* @__PURE__ */ new Set();
1175
+ for (const copy of copies.values()) {
1176
+ if (copy.kind !== "file") continue;
1177
+ const name = decodeURIComponent(copy.file.pathname.split("/").at(-1) ?? "");
1178
+ kept.add(name).add(`${name}.json`);
1179
+ }
1180
+ try {
1181
+ await Promise.all(
1182
+ (await readdir(folder)).filter((name) => !kept.has(name)).map((name) => rm(new URL(name, folder), { force: true }))
1183
+ );
1184
+ } catch {
1185
+ }
1186
+ }
1187
+ var MAX_IMAGE_DEPTH = 64;
1188
+ function siteImages(values, apiOrigin) {
1189
+ const images = /* @__PURE__ */ new Map();
1190
+ const visit = (value, steps, depth) => {
1191
+ if (depth > MAX_IMAGE_DEPTH || typeof value !== "object" || value === null) return;
1192
+ if (Array.isArray(value)) {
1193
+ value.forEach((item, index) => {
1194
+ const key = isRecord3(item) && isRowKey(item._key) ? item._key : null;
1195
+ visit(item, [...steps, key === null ? { index } : { key }], depth + 1);
1196
+ });
1197
+ return;
1198
+ }
1199
+ const record = value;
1200
+ const path = isStoredImage(record) ? siteImagePath(record.src, apiOrigin) : null;
1201
+ if (path && typeof record.src === "string") {
1202
+ const place = formatContentPath(steps);
1203
+ const known = images.get(record.src);
1204
+ if (known) known.fieldIds.push(place);
1205
+ else images.set(record.src, { src: record.src, fieldIds: [place], assetId: path.assetId, extension: path.extension });
1206
+ return;
1207
+ }
1208
+ for (const [name, inner] of Object.entries(record)) visit(inner, [...steps, { field: name }], depth + 1);
1209
+ };
1210
+ for (const [fieldId, value] of Object.entries(values)) visit(value, [{ field: fieldId }], 0);
1211
+ return [...images.values()];
1212
+ }
1213
+ function isStoredImage(value) {
1214
+ const { assetId, src, alt, width, height } = value;
1215
+ return fieldValueProblem("image", { assetId, src, alt, width, height }, "content") === null;
1216
+ }
1217
+ function moveToSecondPath(value, lost, apiOrigin, depth = 0) {
1218
+ if (depth > MAX_IMAGE_DEPTH || typeof value !== "object" || value === null) return value;
1219
+ if (Array.isArray(value)) return value.map((item) => moveToSecondPath(item, lost, apiOrigin, depth + 1));
1220
+ const record = value;
1221
+ if (isStoredImage(record) && lost.has(record.src)) {
1222
+ const direct = directImageAddress(record.src, apiOrigin);
1223
+ return direct ? { ...record, src: direct } : record;
1224
+ }
1225
+ return Object.fromEntries(Object.entries(record).map(([name, inner]) => [name, moveToSecondPath(inner, lost, apiOrigin, depth + 1)]));
1226
+ }
1227
+ function isRecord3(value) {
1228
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1229
+ }
1230
+ async function download(image, fetchImpl, limits, total) {
1231
+ const controller = new AbortController();
1232
+ const stop = () => controller.abort();
1233
+ total.signal.addEventListener("abort", stop);
1234
+ const answer = deadline(limits.answerMs, "timeout");
1235
+ const whole = deadline(limits.imageMs, "timeout");
1236
+ try {
1237
+ const response = await Promise.race([
1238
+ fetchImpl(image.src, { method: "GET", redirect: "manual", signal: controller.signal }),
1239
+ answer.promise,
1240
+ whole.promise,
1241
+ total.promise
1242
+ ]);
1243
+ answer.clear();
1244
+ const { status } = response;
1245
+ if (status === 429 || status >= 500) throw new ImageMiss("unreachable", status);
1246
+ if (status >= 300 && status < 500) throw new ImageMiss("rejected", status);
1247
+ if (status !== 200) throw new ImageMiss("invalid", status);
1248
+ const declared = response.headers.get("content-length");
1249
+ const bytes = await Promise.race([readBody(response.body), whole.promise, total.promise]);
1250
+ if (!bytes || declared !== null && Number(declared) !== bytes.byteLength) throw new ImageMiss("invalid");
1251
+ return { bytes, contentType: (response.headers.get("content-type") ?? "").split(";")[0]?.trim().toLowerCase() ?? "" };
1252
+ } catch (error) {
1253
+ controller.abort();
1254
+ throw error instanceof ImageMiss ? error : new ImageMiss("unreachable");
1255
+ } finally {
1256
+ answer.clear();
1257
+ whole.clear();
1258
+ total.signal.removeEventListener("abort", stop);
1259
+ }
1260
+ }
1261
+ async function readBody(body) {
1262
+ if (!body) return new Uint8Array();
1263
+ const reader = body.getReader();
1264
+ const chunks = [];
1265
+ let length = 0;
1266
+ for (; ; ) {
1267
+ const chunk = await reader.read();
1268
+ if (chunk.done) break;
1269
+ length += chunk.value.byteLength;
1270
+ if (length > MAX_IMAGE_BYTES) {
1271
+ await reader.cancel().catch(() => {
1272
+ });
1273
+ return null;
1274
+ }
1275
+ chunks.push(chunk.value);
1276
+ }
1277
+ const bytes = new Uint8Array(length);
1278
+ let offset = 0;
1279
+ for (const chunk of chunks) {
1280
+ bytes.set(chunk, offset);
1281
+ offset += chunk.byteLength;
1282
+ }
1283
+ return bytes;
1284
+ }
1285
+ async function readCopy(folder, image, readMetadata) {
1286
+ const file = new URL(`${image.assetId}.${image.extension}`, folder);
1287
+ const sidecar = new URL(`${image.assetId}.${image.extension}.json`, folder);
1288
+ try {
1289
+ const [bytes, meta] = await Promise.all([readFile(file), readFile(sidecar, "utf8")]);
1290
+ const { contentType, length } = JSON.parse(meta);
1291
+ if (contentType === CONTENT_TYPES[image.extension] && length === bytes.byteLength && await readable(readMetadata, bytes, image.src)) {
1292
+ return { kind: "file", file, contentType, length };
1293
+ }
1294
+ } catch {
1295
+ }
1296
+ await Promise.all([rm(file, { force: true }), rm(sidecar, { force: true })]).catch(() => {
1297
+ });
1298
+ return null;
1299
+ }
1300
+ async function writeCopy(folder, image, bytes, contentType) {
1301
+ const file = new URL(`${image.assetId}.${image.extension}`, folder);
1302
+ try {
1303
+ await mkdir(folder, { recursive: true });
1304
+ await writeAtomically(file, bytes);
1305
+ await writeAtomically(new URL(`${image.assetId}.${image.extension}.json`, folder), JSON.stringify({ contentType, length: bytes.byteLength }));
1306
+ return { kind: "file", file, contentType, length: bytes.byteLength };
1307
+ } catch {
1308
+ return { kind: "memory", bytes, contentType };
1309
+ }
1310
+ }
1311
+ async function writeAtomically(target, content) {
1312
+ const temporary = new URL(`${target.href}.${process.pid}.${Date.now()}.tmp`);
1313
+ await writeFile(temporary, content);
1314
+ await rename(temporary, target);
1315
+ }
1316
+ async function metadataReader() {
1317
+ try {
1318
+ const { imageMetadata } = await import("astro/assets/utils");
1319
+ return imageMetadata;
1320
+ } catch {
1321
+ return null;
1322
+ }
1323
+ }
1324
+ async function readable(readMetadata, bytes, src) {
1325
+ if (!readMetadata) return false;
1326
+ try {
1327
+ await readMetadata(bytes, src);
1328
+ return true;
1329
+ } catch {
1330
+ return false;
1331
+ }
1332
+ }
1333
+ function totalDeadline(ms) {
1334
+ const controller = new AbortController();
1335
+ let expired = false;
1336
+ let timer;
1337
+ const promise = new Promise((_resolve, reject) => {
1338
+ timer = setTimeout(() => {
1339
+ expired = true;
1340
+ controller.abort();
1341
+ reject(new ImageMiss("total_timeout"));
1342
+ }, ms);
1343
+ });
1344
+ promise.catch(() => {
1345
+ });
1346
+ return {
1347
+ promise,
1348
+ signal: controller.signal,
1349
+ get expired() {
1350
+ return expired;
1351
+ },
1352
+ clear: () => clearTimeout(timer)
1353
+ };
1354
+ }
1355
+ function deadline(ms, reason) {
1356
+ let timer;
1357
+ const promise = new Promise((_resolve, reject) => {
1358
+ timer = setTimeout(() => reject(new ImageMiss(reason)), ms);
1359
+ });
1360
+ promise.catch(() => {
1361
+ });
1362
+ return { promise, clear: () => clearTimeout(timer) };
1363
+ }
1364
+ function requestUrl(input) {
1365
+ try {
1366
+ return new URL(input instanceof Request ? input.url : input).href;
1367
+ } catch {
1368
+ return null;
1369
+ }
1370
+ }
1371
+ function hostOf2(src) {
1372
+ try {
1373
+ return new URL(src).host;
1374
+ } catch {
1375
+ return "Siteplane";
1376
+ }
1377
+ }
1378
+ function fieldList(fieldIds) {
1379
+ const named = fieldIds.slice(0, NAMED_FIELDS).join(", ");
1380
+ return fieldIds.length > NAMED_FIELDS ? `${named} and ${fieldIds.length - NAMED_FIELDS} more` : named;
1381
+ }
1382
+ function seconds(ms) {
1383
+ return `${ms / 1e3} s`;
1384
+ }
1385
+
1386
+ // src/astro/build-info.ts
1387
+ var BUILD_INFO_MODULE = "virtual:siteplane/build";
1388
+
1389
+ // src/astro/build-snapshot.ts
1390
+ import { mkdir as mkdir2, readFile as readFile2, rename as rename2, writeFile as writeFile2 } from "fs/promises";
1391
+ var SNAPSHOT_FILE = "build-snapshot.json";
1392
+ var LAST_VALUES_FILE = "last-values.json";
1393
+ async function loadBuildSnapshot(input) {
1394
+ const builtAt = input.now().toISOString();
1395
+ const folder = new URL("siteplane/", input.cacheDir);
1396
+ const url = runtimeValuesUrl(input.config.apiOrigin, input.config.siteId);
1397
+ const read = await readValuesForBuild((deadlineMs) => readValues(input.fetch, input.config, url, {}, deadlineMs), input.timing);
1398
+ let stand;
1399
+ if (read.ok) {
1400
+ stand = { values: read.values, revision: read.revision, source: "fresh" };
1401
+ await store(folder, LAST_VALUES_FILE, { siteId: input.config.siteId, revision: read.revision, values: read.values });
1402
+ } else {
1403
+ const cached = await readLastValues(folder, input.config.siteId);
1404
+ if (!cached) throw new Error(buildFailedMessage(input.config, read.reason));
1405
+ stand = { ...cached, source: "build-cache", failure: { reason: read.reason, attempts: read.attempts, elapsedMs: read.elapsedMs } };
1406
+ }
1407
+ let values = stand.values;
1408
+ if (input.prepareValues) values = await input.prepareValues(values).catch(() => stand.values);
1409
+ const snapshot = { ...stand, values, builtAt };
1410
+ await store(folder, SNAPSHOT_FILE, {
1411
+ siteId: input.config.siteId,
1412
+ revision: snapshot.revision,
1413
+ builtAt,
1414
+ source: snapshot.source,
1415
+ values
1416
+ });
1417
+ return snapshot;
1418
+ }
1419
+ async function readLastValues(folder, siteId) {
1420
+ try {
1421
+ const stored = JSON.parse(await readFile2(new URL(LAST_VALUES_FILE, folder), "utf8"));
1422
+ const { values, revision } = stored;
1423
+ if (stored.siteId !== siteId || typeof values !== "object" || values === null || Array.isArray(values)) return null;
1424
+ if (revision !== null && !isRevision(revision)) return null;
1425
+ return { values, revision };
1426
+ } catch {
1427
+ return null;
1428
+ }
1429
+ }
1430
+ async function store(folder, name, content) {
1431
+ try {
1432
+ await mkdir2(folder, { recursive: true });
1433
+ const temporary = new URL(`${name}.${process.pid}.${Date.now()}.tmp`, folder);
1434
+ await writeFile2(temporary, JSON.stringify(content));
1435
+ await rename2(temporary, new URL(name, folder));
1436
+ } catch {
1437
+ }
1438
+ }
1439
+
1440
+ // src/astro/index.ts
1441
+ var SCHEMA_FILE = "siteplane.schema.ts";
1442
+ var SCHEMA_MODULE = "siteplane/schema-file";
1443
+ var EMPTY_SCHEMA = "\0siteplane:empty-schema";
1444
+ var ASTRO_CONFIG_FILES = [
1445
+ "astro.config.mjs",
1446
+ "astro.config.js",
1447
+ "astro.config.ts",
1448
+ "astro.config.mts",
1449
+ "astro.config.cjs",
1450
+ "astro.config.cts"
1451
+ ];
1452
+ var SAMPLE_ID = "00000000-0000-4000-8000-000000000000";
1453
+ var LOCALS_TYPES = `declare namespace App {
1454
+ interface Locals {
1455
+ siteplane: import("siteplane/astro").SiteplaneAstroReader;
1456
+ siteplanePreview: { editorOrigin: string } | null;
1457
+ }
1458
+ }
1459
+ `;
1460
+ var globalFetch = (input, init) => globalThis.fetch(input, init);
1461
+ function siteplane(options = {}) {
1462
+ let config = null;
1463
+ let dev = false;
1464
+ let preview = false;
1465
+ let adapter = false;
1466
+ let configuredPageCache = "unknown";
1467
+ let pageCache = "unknown";
1468
+ let drafts = false;
1469
+ let prerenderedPages = false;
1470
+ let cacheDir = null;
1471
+ let incrementalBuild = false;
1472
+ let snapshot = null;
1473
+ let images = null;
1474
+ let restoreFetch = null;
1475
+ const revision = () => incrementalBuild ? null : snapshot?.revision ?? null;
1476
+ const buildInfo = () => ({
1477
+ dev,
1478
+ preview,
1479
+ drafts,
1480
+ pageCache,
1481
+ prerenderedFields: prerenderedPages,
1482
+ builtAt: snapshot?.builtAt ?? null,
1483
+ revision: revision(),
1484
+ values: snapshot?.values ?? null,
1485
+ ...hostingDetails()
1486
+ });
1487
+ return {
1488
+ name: "siteplane",
1489
+ hooks: {
1490
+ "astro:config:setup": ({ config: astro, command, updateConfig, injectRoute, addMiddleware, logger }) => {
1491
+ addMiddleware({ entrypoint: "siteplane/astro/middleware", order: "pre" });
1492
+ dev = command === "dev";
1493
+ preview = process.env.SITEPLANE_PREVIEW === "1";
1494
+ adapter = Boolean(astro.adapter);
1495
+ const projectDir = options.projectDir ?? fileURLToPath(astro.root);
1496
+ config = readProjectConfig(projectDir, logger);
1497
+ const schemaPath = join(projectDir, SCHEMA_FILE);
1498
+ const schema = config && existsSync(schemaPath) ? schemaPath : null;
1499
+ if (config && !schema) {
1500
+ logger.warn(
1501
+ `${SCHEMA_FILE} is missing next to ${SITEPLANE_CONFIG_FILE}, so pages that read content cannot render. Describe the content there and run npx siteplane check.`
1502
+ );
1503
+ }
1504
+ const count = config && dev ? [devPlugin({ config, base: astro.base, status: () => devStatus(adapter, buildInfo()) })] : [];
1505
+ const vite = { plugins: [buildInfoPlugin(buildInfo), schemaPlugin(schema), clientPlugin(), ...count], ssr: { noExternal: ["siteplane"] } };
1506
+ if (!config) {
1507
+ updateConfig({ vite });
1508
+ return;
1509
+ }
1510
+ configuredPageCache = readConfiguredPageCache(fileURLToPath(astro.root), preview);
1511
+ updateConfig({
1512
+ vite: {
1513
+ ...vite,
1514
+ resolve: { alias: [{ find: /^siteplane\/config$/u, replacement: join(projectDir, SITEPLANE_CONFIG_FILE) }] }
1515
+ },
1516
+ image: { remotePatterns: [imagePattern(config.apiOrigin)] },
1517
+ ...preview && adapter ? { output: "server" } : {}
1518
+ });
1519
+ if (adapter) {
1520
+ injectRoute({ pattern: "/api/siteplane/[...siteplane]", entrypoint: "siteplane/astro/route", prerender: false });
1521
+ } else if (preview) {
1522
+ logger.warn(
1523
+ "SITEPLANE_PREVIEW=1 needs an adapter that renders pages on demand; this build stays static, so its preview shows no drafts."
1524
+ );
1525
+ }
1526
+ },
1527
+ "astro:config:done": async ({ config: astro, injectTypes, logger }) => {
1528
+ injectTypes({ filename: "types.d.ts", content: LOCALS_TYPES });
1529
+ cacheDir = astro.cacheDir;
1530
+ incrementalBuild = astro.experimental?.incrementalBuild === true;
1531
+ if (!config) return;
1532
+ pageCache = withRouteCache(configuredPageCache, astro);
1533
+ drafts = pageCache === "none" || preview && adapter && pageCache === "astro-route-cache";
1534
+ if (preview && adapter && !drafts) {
1535
+ logger.warn(
1536
+ `This preview build keeps a page cache (${pageCache}), so its preview shows no drafts. Turn the cache off only when SITEPLANE_PREVIEW=1 and keep the production value, for example vercel({ isr: process.env.SITEPLANE_PREVIEW === "1" ? false : true }).`
1537
+ );
1538
+ }
1539
+ await warnWhenTheSecondPathIsAllowed(astro, config.apiOrigin, logger);
1540
+ },
1541
+ "astro:route:setup": ({ route }) => {
1542
+ if (config && preview && adapter) route.prerender = false;
1543
+ },
1544
+ "astro:routes:resolved": ({ routes }) => {
1545
+ prerenderedPages = routes.some((route) => route.isPrerendered && route.type === "page" && route.origin !== "internal");
1546
+ },
1547
+ "astro:build:start": async ({ logger }) => {
1548
+ snapshot = null;
1549
+ images = null;
1550
+ if (!config || !cacheDir) return;
1551
+ const site = config;
1552
+ const folder = cacheDir;
1553
+ const step = {};
1554
+ snapshot = await loadBuildSnapshot({
1555
+ config: site,
1556
+ fetch: globalFetch,
1557
+ cacheDir: folder,
1558
+ now: () => /* @__PURE__ */ new Date(),
1559
+ // Only prerendered pages download images during the build.
1560
+ prepareValues: prerenderedPages ? async (values) => (step.images = await prepareBuildImages({ values, apiOrigin: site.apiOrigin, cacheDir: folder, fetch: globalFetch })).values : void 0
1561
+ });
1562
+ warnAboutValues(logger, snapshot, site);
1563
+ if (incrementalBuild) {
1564
+ logger.warn(
1565
+ "experimental.incrementalBuild can keep pages of an earlier build with older values, so this build reports no value revision and Siteplane cannot confirm that a publish is live. Build without it to have publishes confirmed."
1566
+ );
1567
+ }
1568
+ if (!step.images) return;
1569
+ images = step.images;
1570
+ restoreFetch = answerImageDownloadsFromCopies(images.copies).restore;
1571
+ warnAboutMissingImages(logger, images.unavailable);
1572
+ },
1573
+ "astro:build:done": async ({ dir, logger }) => {
1574
+ restoreFetch?.();
1575
+ restoreFetch = null;
1576
+ if (images && cacheDir) await removeUnusedImageCopies(cacheDir, images.copies);
1577
+ if (!config || adapter) return;
1578
+ const answer = {
1579
+ siteId: config.siteId,
1580
+ version: PACKAGE_VERSION,
1581
+ ...hostingDetails(),
1582
+ stack: "astro",
1583
+ rendering: "static",
1584
+ builtAt: snapshot?.builtAt ?? (/* @__PURE__ */ new Date()).toISOString(),
1585
+ revision: revision(),
1586
+ prerenderedFields: prerenderedPages,
1587
+ pageCache
1588
+ };
1589
+ await writeStatusFile(dir, answer, logger);
1590
+ }
1591
+ }
1592
+ };
1593
+ }
1594
+ function readProjectConfig(projectDir, logger) {
1595
+ const path = join(projectDir, SITEPLANE_CONFIG_FILE);
1596
+ if (!existsSync(path)) {
1597
+ logger.warn(
1598
+ `${SITEPLANE_CONFIG_FILE} is missing, so the pages cannot read their content from Siteplane. Run npx siteplane init to connect the website.`
1599
+ );
1600
+ return null;
1601
+ }
1602
+ try {
1603
+ const config = readSiteplaneConfig(JSON.parse(readFileSync(path, "utf8")));
1604
+ if (config) return config;
1605
+ } catch {
1606
+ }
1607
+ logger.warn(
1608
+ `${SITEPLANE_CONFIG_FILE} could not be read, so the pages cannot read their content from Siteplane. Run npx siteplane init to repair it.`
1609
+ );
1610
+ return null;
1611
+ }
1612
+ function readConfiguredPageCache(root, preview) {
1613
+ const named = configFlag(process.argv);
1614
+ const file = named === null ? ASTRO_CONFIG_FILES.map((name) => join(root, name)).find((path) => existsSync(path)) : join(root, named);
1615
+ if (!file || !existsSync(file)) return "unknown";
1616
+ try {
1617
+ return detectAstroPageCache(readFileSync(file, "utf8"), { preview });
1618
+ } catch {
1619
+ return "unknown";
1620
+ }
1621
+ }
1622
+ function configFlag(argv) {
1623
+ for (const [index, argument] of argv.entries()) {
1624
+ if (argument.startsWith("--config=")) return argument.slice("--config=".length) || null;
1625
+ const next = argv[index + 1];
1626
+ if (argument === "--config" && next && !next.startsWith("-")) return next;
1627
+ }
1628
+ return null;
1629
+ }
1630
+ function withRouteCache(configured, astro) {
1631
+ if (configured !== "none" && configured !== "astro-route-cache") return configured;
1632
+ const resolved = astro;
1633
+ return resolved.cache?.provider || resolved.experimental?.cache?.provider ? "astro-route-cache" : configured;
1634
+ }
1635
+ function imagePattern(apiOrigin) {
1636
+ const url = new URL(apiOrigin);
1637
+ return {
1638
+ protocol: url.protocol.slice(0, -1),
1639
+ hostname: url.hostname,
1640
+ ...url.port ? { port: url.port } : {},
1641
+ pathname: "/site-images/**"
1642
+ };
1643
+ }
1644
+ async function warnWhenTheSecondPathIsAllowed(astro, apiOrigin, logger) {
1645
+ try {
1646
+ const sample = directImageAddress(`${apiOrigin}/site-images/${SAMPLE_ID}/${SAMPLE_ID}.jpg`, apiOrigin);
1647
+ const { isRemoteAllowed } = await import("astro/assets/utils");
1648
+ const settings = {
1649
+ domains: astro.image.domains ?? [],
1650
+ remotePatterns: astro.image.remotePatterns ?? []
1651
+ };
1652
+ const host = new URL(apiOrigin).host;
1653
+ if (sample && isRemoteAllowed(sample, settings)) {
1654
+ logger.warn(
1655
+ `The image settings of this website also allow ${host}/site-images-direct/, so during an outage of ${host} the build would still try to download those images. Allow only the path /site-images/** of ${host}.`
1656
+ );
1657
+ }
1658
+ } catch {
1659
+ }
1660
+ }
1661
+ function warnAboutValues(logger, snapshot, config) {
1662
+ if (snapshot.source !== "build-cache" || !snapshot.failure) return;
1663
+ const { reason, attempts, elapsedMs } = snapshot.failure;
1664
+ const revision = snapshot.revision === null ? "" : ` (revision ${snapshot.revision})`;
1665
+ logger.warn(
1666
+ `${hostOf(config)} did not deliver the content (${reason}; ${attempts} ${attempts === 1 ? "attempt" : "attempts"} within 10 s, ${Math.round(elapsedMs)} ms), so this build uses the content of an earlier build${revision}. Build again once it answers.`
1667
+ );
1668
+ }
1669
+ async function writeStatusFile(dir, answer, logger) {
1670
+ try {
1671
+ const folder = new URL("api/siteplane/", dir.href.endsWith("/") ? dir : new URL(`${dir.href}/`));
1672
+ await mkdir3(folder, { recursive: true });
1673
+ await writeFile3(new URL("status", folder), JSON.stringify(answer));
1674
+ } catch (error) {
1675
+ logger.warn(
1676
+ `The status answer for Siteplane could not be written, so Siteplane cannot confirm this build: ${error instanceof Error ? error.message : String(error)}`
1677
+ );
1678
+ }
1679
+ }
1680
+ function hostingDetails() {
1681
+ return { commit: process.env.VERCEL_GIT_COMMIT_SHA || null, environment: process.env.VERCEL_ENV || null };
1682
+ }
1683
+ function schemaPlugin(schemaPath) {
1684
+ return {
1685
+ name: "siteplane:schema",
1686
+ enforce: "pre",
1687
+ resolveId(id, _importer, options) {
1688
+ if (id !== SCHEMA_MODULE) return void 0;
1689
+ return schemaPath && isServerEnvironment(this, options) ? schemaPath : EMPTY_SCHEMA;
1690
+ },
1691
+ load: (id) => id === EMPTY_SCHEMA ? "export default null;" : void 0
1692
+ };
1693
+ }
1694
+ function isServerEnvironment(context, options) {
1695
+ const consumer = context?.environment?.config?.consumer;
1696
+ return consumer === void 0 ? options?.ssr === true : consumer === "server";
1697
+ }
1698
+ function clientPlugin() {
1699
+ return {
1700
+ name: "siteplane:client",
1701
+ enforce: "pre",
1702
+ resolveId(id, importer, options) {
1703
+ if (id !== "siteplane/client") return void 0;
1704
+ return this.resolve("siteplane/astro/client", importer, { ...options, skipSelf: true });
1705
+ }
1706
+ };
1707
+ }
1708
+ function devStatus(adapter, build) {
1709
+ return {
1710
+ stack: "astro",
1711
+ rendering: adapter ? "server" : "static",
1712
+ builtAt: null,
1713
+ revision: null,
1714
+ prerenderedFields: build.prerenderedFields,
1715
+ pageCache: build.pageCache
1716
+ };
1717
+ }
1718
+ var COUNT_COOKIE_HEADER = `${COUNT_COOKIE}=1; Path=/; HttpOnly; SameSite=Lax`;
1719
+ var COUNT_COOKIE_SENT = new RegExp(`(?:^|;\\s*)${COUNT_COOKIE}=1(?:;|$)`, "u");
1720
+ var ASTRO_LOCALS = /* @__PURE__ */ Symbol.for("astro.locals");
1721
+ function devPlugin(dependencies) {
1722
+ const handlers = createRouteHandlers({
1723
+ config: () => dependencies.config,
1724
+ keys: async () => [],
1725
+ revalidateTag: () => {
1726
+ },
1727
+ enableDraftMode: async () => {
1728
+ },
1729
+ env: { VERCEL_GIT_COMMIT_SHA: process.env.VERCEL_GIT_COMMIT_SHA, VERCEL_ENV: process.env.VERCEL_ENV },
1730
+ version: PACKAGE_VERSION,
1731
+ now: () => /* @__PURE__ */ new Date(),
1732
+ statusDetails: dependencies.status,
1733
+ devServer: true,
1734
+ enableCount: async () => ({ "Set-Cookie": COUNT_COOKIE_HEADER })
1735
+ });
1736
+ const base = (dependencies.base ?? "/").replace(/\/+$/u, "").replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
1737
+ const route = new RegExp(`^(?:${base})?/api/siteplane/(status|draft)/?$`, "u");
1738
+ return {
1739
+ name: "siteplane:dev",
1740
+ apply: "serve",
1741
+ configureServer(server) {
1742
+ server.middlewares.use((request, response, next) => {
1743
+ const url = new URL(request.url ?? "/", "http://localhost");
1744
+ const name = route.exec(url.pathname)?.[1];
1745
+ if (request.method === "GET" && (name === "status" || name === "draft" && url.searchParams.has("count"))) {
1746
+ void handlers.GET(new Request(url)).then(async (answer) => {
1747
+ response.writeHead(answer.status, Object.fromEntries(answer.headers));
1748
+ response.end(new Uint8Array(await answer.arrayBuffer()));
1749
+ }, next);
1750
+ return;
1751
+ }
1752
+ if (COUNT_COOKIE_SENT.test(request.headers.cookie ?? "")) {
1753
+ const locals = Reflect.get(request, ASTRO_LOCALS) ?? {};
1754
+ locals.siteplaneCount = true;
1755
+ Reflect.set(request, ASTRO_LOCALS, locals);
1756
+ }
1757
+ next();
1758
+ });
1759
+ }
1760
+ };
1761
+ }
1762
+ function buildInfoPlugin(info) {
1763
+ const resolved = `\0${BUILD_INFO_MODULE}`;
1764
+ return {
1765
+ name: "siteplane:build",
1766
+ resolveId: (id) => id === BUILD_INFO_MODULE ? resolved : void 0,
1767
+ load: (id) => id === resolved ? `export default ${JSON.stringify(info())};` : void 0
1768
+ };
1769
+ }
1770
+ export {
1771
+ siteplane as default
1772
+ };