@plitzi/sdk-server 0.39.3 → 0.39.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +50 -8
  3. package/dist/adapters/cloudAdapters.d.ts +7 -0
  4. package/dist/adapters/space/index.d.ts +2 -0
  5. package/dist/adapters/space/resolvers.d.ts +14 -3
  6. package/dist/adapters/space/snapshotPreview.d.ts +45 -0
  7. package/dist/adapters/space/types.d.ts +4 -1
  8. package/dist/auth.d.ts +3 -2
  9. package/dist/auth.js +26 -107
  10. package/dist/cache.js +1 -1
  11. package/dist/chunks/{buildBody-W9D8ySNY.js → buildBody-Bm398uxH.js} +893 -114
  12. package/dist/chunks/{core-TlrWmT4B.js → core-CoKORAOg.js} +234 -26
  13. package/dist/chunks/{createServer-Bd_b7T3k.js → createServer-BSmQqzwb.js} +186 -639
  14. package/dist/chunks/{platform-DhdFYWm5.js → platform-BTssQQXp.js} +2 -2
  15. package/dist/chunks/sdkAssets-CXGoc_WE.js +60 -0
  16. package/dist/chunks/throttle-CRiZB6_A.js +330 -0
  17. package/dist/chunks/{token-B2uY9JzU.js → token-XEz1n4jp.js} +1 -1
  18. package/dist/chunks/views/template.ejs +12 -0
  19. package/dist/core/auth/api/context.d.ts +4 -4
  20. package/dist/core/auth/api/values.d.ts +6 -0
  21. package/dist/core/auth/createAuth.d.ts +1 -1
  22. package/dist/core/auth/throttle.d.ts +54 -4
  23. package/dist/core/createServer.d.ts +1 -1
  24. package/dist/core/platform.d.ts +1 -1
  25. package/dist/core/services/iconFaces.d.ts +3 -0
  26. package/dist/core/services/llmsTxt.d.ts +15 -0
  27. package/dist/core/services/robotsTxt.d.ts +5 -9
  28. package/dist/core/services/securityTxt.d.ts +10 -0
  29. package/dist/deploy/aws/s3.d.ts +51 -0
  30. package/dist/deploy/aws/sigv4.d.ts +33 -0
  31. package/dist/deploy/contentType.d.ts +2 -0
  32. package/dist/deploy/fingerprint.d.ts +18 -0
  33. package/dist/deploy/folder.d.ts +6 -0
  34. package/dist/deploy/ftp.d.ts +27 -0
  35. package/dist/deploy/sdkFiles.d.ts +11 -0
  36. package/dist/deploy/spaShell.d.ts +35 -0
  37. package/dist/deploy/staticSite.d.ts +44 -0
  38. package/dist/deploy/types.d.ts +58 -0
  39. package/dist/deploy/zip.d.ts +8 -0
  40. package/dist/deploy.d.ts +24 -0
  41. package/dist/deploy.js +938 -0
  42. package/dist/handlers.js +1 -1
  43. package/dist/helpers/documentParts.d.ts +10 -0
  44. package/dist/helpers/ownVersion.d.ts +1 -0
  45. package/dist/helpers/paintedCookie.d.ts +15 -1
  46. package/dist/index.d.ts +1 -1
  47. package/dist/index.js +3 -3
  48. package/dist/modules/icons/glyphs.d.ts +21 -0
  49. package/dist/modules/icons/handler.d.ts +11 -0
  50. package/dist/modules/icons/spaceIcons.d.ts +26 -0
  51. package/dist/modules/rsc/connectorRscData.d.ts +4 -2
  52. package/dist/modules/rsc/resolveRscData.d.ts +4 -1
  53. package/dist/modules/ssr/csrfHint.d.ts +12 -0
  54. package/dist/modules/ssr/defaultFavicon.d.ts +1 -1
  55. package/dist/modules/ssr/spaceDocument.d.ts +8 -1
  56. package/dist/oauth.js +1 -1
  57. package/dist/platform.d.ts +1 -1
  58. package/dist/platform.js +1 -1
  59. package/dist/project.js +3 -3
  60. package/dist/spaces.d.ts +2 -2
  61. package/dist/spaces.js +1 -1
  62. package/dist/ssr.d.ts +1 -1
  63. package/dist/ssr.js +1 -1
  64. package/dist/types/config.d.ts +24 -0
  65. package/dist/types/index.d.ts +1 -1
  66. package/package.json +17 -13
  67. package/skills/plitzi-authoring/recipes/accordion.ts +3 -1
  68. package/skills/plitzi-authoring/recipes/carousel.ts +68 -63
  69. package/skills/plitzi-authoring/recipes/detail-page.ts +43 -33
  70. package/skills/plitzi-authoring/recipes/embed-and-svg.ts +16 -11
  71. package/skills/plitzi-authoring/recipes/every-few-seconds.ts +52 -42
  72. package/skills/plitzi-authoring/recipes/feature-flag.ts +7 -2
  73. package/skills/plitzi-authoring/recipes/filter-a-list.ts +39 -31
  74. package/skills/plitzi-authoring/recipes/forms-and-modals.ts +34 -28
  75. package/skills/plitzi-authoring/recipes/from-tailwind.ts +11 -6
  76. package/skills/plitzi-authoring/recipes/link-to-a-section.ts +11 -6
  77. package/skills/plitzi-authoring/recipes/link-with-data.ts +21 -16
  78. package/skills/plitzi-authoring/recipes/marquee.ts +17 -12
  79. package/skills/plitzi-authoring/recipes/plugin.ts +16 -10
  80. package/skills/plitzi-authoring/recipes/scroll-a-row.ts +30 -25
  81. package/skills/plitzi-authoring/recipes/server-data.ts +15 -10
  82. package/skills/plitzi-authoring/recipes/show-data.ts +32 -24
  83. package/skills/plitzi-authoring/recipes/style-a-page.ts +9 -4
  84. package/skills/plitzi-authoring/recipes/typed-data.ts +26 -21
  85. package/skills/plitzi-authoring/recipes/usable-without-sight.ts +16 -11
  86. package/skills/plitzi-authoring/reference/authoring-errors.md +11 -4
  87. package/skills/plitzi-authoring/reference/efficiency.md +3 -1
  88. package/skills/plitzi-authoring/reference/layouts.md +2 -1
  89. package/dist/chunks/throttle-BH7JLIOF.js +0 -108
@@ -1,17 +1,20 @@
1
- import { schemaFromWire } from "@plitzi/sdk-shared/schema";
1
+ import { schemaForPage, schemaFromWire, splitSchema } from "@plitzi/sdk-shared/schema";
2
+ import path from "node:path";
2
3
  import { compressBody, frameAncestorsOf, requestAuthority, requestOrigin } from "@plitzi/sdk-kernel/http";
3
4
  import { serverLog } from "@plitzi/sdk-kernel/log";
4
5
  import { flagsCookieName } from "@plitzi/sdk-shared/flags";
5
6
  import { TRUSTED_TYPES_POLICIES, getKeyDecoded, isRecord } from "@plitzi/sdk-shared/helpers";
6
- import { paintedKeys, paintedStateCookieName, paintedStateFor } from "@plitzi/sdk-shared/state";
7
+ import { paintedKeys, paintedStateCookieName, paintedStateFor, pickPainted } from "@plitzi/sdk-shared/state";
7
8
  import { frameAncestors, sessionCookieParams, sessionHintCookieName } from "@plitzi/sdk-kernel/identity";
8
9
  import { TtlCache } from "@plitzi/sdk-kernel/cache";
9
10
  import { debugCookieName } from "@plitzi/sdk-shared/devTools";
10
11
  import { requestScheme, themeFromCookies } from "@plitzi/sdk-shared/theme/cookie";
11
12
  import { brotliDecompressSync, gunzipSync } from "node:zlib";
12
- import { createHash, randomBytes, randomUUID } from "node:crypto";
13
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
13
14
  import { styleSheetCss, styleSheetHref, styleSheetLinkable } from "@plitzi/sdk-shared/style";
15
+ import { fileURLToPath } from "node:url";
14
16
  import { readFileSync, statSync, writeFileSync } from "node:fs";
17
+ import { CLIENT_HEADER, CURRENT_HEADER, behindText, clientHeaderValue } from "@plitzi/sdk-shared/clients";
15
18
  // src/helpers/paintedCookie.ts
16
19
  /**
17
20
  * The name the painted state of a server-rendered page is kept under, for this request's host.
@@ -38,6 +41,44 @@ var requestPaintedState = (req, settings, account) => {
38
41
  state: paintedStateFor(req.headers.cookie, ssrPaintedCookieName(requestAuthority(req)), settings, account)
39
42
  };
40
43
  };
44
+ /** One answer a request: the render and its server providers read the same, and the deployment is asked once. */
45
+ var resolved = /* @__PURE__ */ new WeakMap();
46
+ /**
47
+ * `requestPaintedState` with the deployment's defaults (`paintedDefaults`) for the keys the cookie holds none of — for
48
+ * an account the request proved, never a guest: a guest's page is cached for every guest, and a default is an
49
+ * account's. Another account's entry holds nothing for this one (`paintedStateFor`), so after a change of account the
50
+ * defaults are this account's. A deployment that fails to answer is said in the log, and the page is drawn without.
51
+ */
52
+ var requestPaintedStateWithDefaults = (req, settings, scope, defaults) => {
53
+ const known = resolved.get(req);
54
+ if (known) return known;
55
+ const { account } = scope;
56
+ const painted = requestPaintedState(req, settings, account);
57
+ const missing = [...painted.keys].filter((key) => painted.state?.[key] === void 0);
58
+ const answer = !defaults || account === void 0 || missing.length === 0 ? Promise.resolve(painted) : (async () => {
59
+ try {
60
+ const given = await defaults({
61
+ spaceId: scope.spaceId,
62
+ environment: scope.environment,
63
+ account,
64
+ keys: missing
65
+ });
66
+ const added = pickPainted(given, new Set(missing));
67
+ return Object.keys(added).length > 0 ? {
68
+ keys: painted.keys,
69
+ state: {
70
+ ...painted.state,
71
+ ...added
72
+ }
73
+ } : painted;
74
+ } catch (error) {
75
+ serverLog.error("SSR", `paintedDefaults did not answer for ${missing.join(", ")}: drawn without`, error);
76
+ return painted;
77
+ }
78
+ })();
79
+ resolved.set(req, answer);
80
+ return answer;
81
+ };
41
82
  // src/helpers/cache/defaults.ts
42
83
  var DEFAULT_TTL_MS = {
43
84
  html: 3e5,
@@ -501,7 +542,7 @@ var styleSheetOf = (offlineData) => {
501
542
  sheets.set(offlineData.style, null);
502
543
  return;
503
544
  }
504
- const css = styleSheetCss(offlineData.style.cache);
545
+ const css = styleSheetCss(offlineData.style.cache, offlineData.schema.settings.customCss);
505
546
  const hash = digest(css);
506
547
  const sheet = {
507
548
  css,
@@ -535,6 +576,13 @@ var spaceDocument = (offlineData, { linkStyle = true } = {}) => {
535
576
  const sheet = linkStyle ? styleSheetOf(offlineData) : void 0;
536
577
  const data = sheet ? {
537
578
  ...offlineData,
579
+ schema: {
580
+ ...offlineData.schema,
581
+ settings: {
582
+ ...offlineData.schema.settings,
583
+ customCss: ""
584
+ }
585
+ },
538
586
  style: {
539
587
  ...offlineData.style,
540
588
  cache: "",
@@ -592,7 +640,7 @@ var destroyServerCaches = ({ html, rsc, offlineData, rendering }) => {
592
640
  // src/helpers/cache/sharedCache.ts
593
641
  /** The topic the processes of a deployment tell each other what their pages no longer hold on. */
594
642
  var CACHE_TOPIC = "ssr.cache";
595
- var LABEL = "SSR cache";
643
+ var LABEL$1 = "SSR cache";
596
644
  /** A filter as it travelled: only the fields a filter has, of the types it has them. */
597
645
  var cacheFilterOf = (value) => {
598
646
  if (!isRecord(value)) return {};
@@ -650,13 +698,13 @@ var shareCache = (cache, sharing) => {
650
698
  const from = randomUUID();
651
699
  const invalidator = createCacheInvalidator(sharing, from);
652
700
  const told = (what) => (error) => {
653
- serverLog.warn(LABEL, `${what} reached only this process: the other replicas keep those pages until their TTL`, error);
701
+ serverLog.warn(LABEL$1, `${what} reached only this process: the other replicas keep those pages until their TTL`, error);
654
702
  };
655
703
  let unsubscribe;
656
704
  const ready = sharing.bus ? sharing.bus.subscribe(CACHE_TOPIC, (raw) => {
657
705
  const message = messageOf(raw);
658
706
  if (!message) {
659
- serverLog.warn(LABEL, `A message on ${CACHE_TOPIC} was ignored: it is not one this server sends`);
707
+ serverLog.warn(LABEL$1, `A message on ${CACHE_TOPIC} was ignored: it is not one this server sends`);
660
708
  return;
661
709
  }
662
710
  if (message.from === from) return;
@@ -665,7 +713,7 @@ var shareCache = (cache, sharing) => {
665
713
  }).then((stop) => {
666
714
  unsubscribe = stop;
667
715
  }).catch((error) => {
668
- serverLog.warn(LABEL, `Not subscribed to ${CACHE_TOPIC}: what other replicas invalidate is kept here until its TTL`, error);
716
+ serverLog.warn(LABEL$1, `Not subscribed to ${CACHE_TOPIC}: what other replicas invalidate is kept here until its TTL`, error);
669
717
  }) : Promise.resolve();
670
718
  return {
671
719
  cache: {
@@ -761,6 +809,43 @@ var createOfflineDataLoader = (read) => {
761
809
  let pending;
762
810
  return () => pending ??= read();
763
811
  };
812
+ // src/helpers/documentParts.ts
813
+ var served = /* @__PURE__ */ new WeakMap();
814
+ /** A part as it is fetched: its root and its elements, escaped as the document is. */
815
+ var textOf = (part) => escapeJson(JSON.stringify(part));
816
+ var servedOf = (schema, withheld) => {
817
+ const known = served.get(schema);
818
+ if (known) return known;
819
+ const texts = /* @__PURE__ */ new Map();
820
+ const parts = {
821
+ split: splitSchema(schema, (part) => {
822
+ const text = textOf(part);
823
+ const name = digest(text);
824
+ texts.set(name, text);
825
+ return name;
826
+ }, withheld),
827
+ texts,
828
+ pages: /* @__PURE__ */ new Map()
829
+ };
830
+ served.set(schema, parts);
831
+ return parts;
832
+ };
833
+ /**
834
+ * Whether this space is sent in parts: unless it asks for the whole (`settings.wholeDocument`), or has a single page —
835
+ * nothing to fetch later, so the shell would only be split for nothing.
836
+ */
837
+ var sentInParts = (schema) => schema.settings.wholeDocument !== true && schema.pages.length > 1;
838
+ /** The schema a page is sent with: the shell, that page's part and its layouts' — the same object for every visit. */
839
+ var pageSchemaOf = (schema, withheld, pageId) => {
840
+ const parts = servedOf(schema, withheld);
841
+ const known = parts.pages.get(pageId);
842
+ if (known) return known;
843
+ const page = schemaForPage(parts.split, pageId);
844
+ parts.pages.set(pageId, page);
845
+ return page;
846
+ };
847
+ /** A part's text by its name, for this group of visitors; none for a name their shell does not give. */
848
+ var partTextOf = (schema, withheld, name) => servedOf(schema, withheld).texts.get(name);
764
849
  // src/modules/ssr/scriptPolicy.ts
765
850
  /** Where a browser reports what the page's script policy would have refused (`cspReportStage`). */
766
851
  var CSP_REPORT_PATH = "/_plitzi/csp-report";
@@ -1222,6 +1307,25 @@ var RequestMetrics = class {
1222
1307
  serverLog.debug("SSR", `${label} — ${parts} | total=${total}ms`);
1223
1308
  }
1224
1309
  };
1310
+ // src/helpers/ownVersion.ts
1311
+ /**
1312
+ * The version of `@plitzi/sdk-server` this code is, read from its own `package.json` — found from where this module is,
1313
+ * as source or built, and whoever compiles it: a build-time constant is only there when this package's own build
1314
+ * defines it, and a package that bundles its source (the MCP) would read nothing. Once a process.
1315
+ */
1316
+ var read;
1317
+ var ownVersion = () => {
1318
+ if (read !== void 0) return read;
1319
+ read = "unknown";
1320
+ for (let dir = path.dirname(fileURLToPath(import.meta.url)); dir !== path.dirname(dir); dir = path.dirname(dir)) try {
1321
+ const manifest = JSON.parse(readFileSync(path.join(dir, "package.json"), "utf8"));
1322
+ if (manifest !== null && typeof manifest === "object" && "name" in manifest && manifest.name === "@plitzi/sdk-server" && "version" in manifest && typeof manifest.version === "string") {
1323
+ read = manifest.version;
1324
+ break;
1325
+ }
1326
+ } catch {}
1327
+ return read;
1328
+ };
1225
1329
  // src/adapters/cloudAdapters.ts
1226
1330
  /**
1227
1331
  * A space fetched from Plitzi, for a server that is not Plitzi's.
@@ -1269,8 +1373,8 @@ var SPACE_QUERY = `query InitQuery($environment: String!, $revision: Int) {
1269
1373
  * magnitude cheaper — for this deployment and for Plitzi — than pulling a whole space down to discover it did not
1270
1374
  * change. The space itself is fetched only when this answer moves.
1271
1375
  */
1272
- var LATEST_REVISION_QUERY = `query SpaceLatestRevisionQuery($environment: String!) {
1273
- SpaceLatestRevision(environment: $environment) {
1376
+ var LATEST_REVISION_QUERY = `query SpaceLatestRevisionQuery($environment: String!, $domain: String) {
1377
+ SpaceLatestRevision(environment: $environment, domain: $domain) {
1274
1378
  snapshot { revision }
1275
1379
  flagsHash
1276
1380
  }
@@ -1321,7 +1425,8 @@ var assertHostKey = (webKey) => {
1321
1425
  throw new Error(`createCloudAdapters needs a space host key; this one is scoped "${scope}".`);
1322
1426
  };
1323
1427
  var createCloudAdapters = (config) => {
1324
- const { serverUrl = PLITZI_SERVER_URL, webKey, environment = "main", revision, cacheSeconds = 60, cache, spaceId = 1, deployment, fetchImpl = fetch } = config;
1428
+ const { serverUrl = PLITZI_SERVER_URL, webKey, environment = "main", revision, cacheSeconds = 60, cache, spaceId = 1, deployment, domain, fetchImpl = fetch } = config;
1429
+ let toldBehind = false;
1325
1430
  assertHostKey(webKey);
1326
1431
  /** `main` is the document somebody is editing right now. Nothing about it is worth remembering for a minute. */
1327
1432
  const isLive = (env) => env === "main";
@@ -1333,15 +1438,22 @@ var createCloudAdapters = (config) => {
1333
1438
  method: "POST",
1334
1439
  headers: {
1335
1440
  "Content-Type": "application/json",
1336
- authorization: `Bearer ${webKey}`
1441
+ authorization: `Bearer ${webKey}`,
1442
+ [CLIENT_HEADER]: clientHeaderValue("sdkServer", ownVersion())
1337
1443
  },
1338
1444
  body: JSON.stringify({
1339
1445
  query,
1340
1446
  variables
1341
1447
  })
1342
1448
  });
1449
+ const current = response.headers.get(CURRENT_HEADER);
1450
+ if (current && !toldBehind) {
1451
+ toldBehind = true;
1452
+ serverLog.warn("CloudAdapters", behindText("sdkServer", ownVersion(), current));
1453
+ }
1343
1454
  if (!response.ok) {
1344
- serverLog.error("CloudAdapters", `${what} answered ${response.status}`);
1455
+ const said = await response.json().catch(() => void 0);
1456
+ serverLog.error("CloudAdapters", `${what} answered ${String(response.status)}${isRecord(said) && typeof said.error === "string" ? `: ${said.error}` : ""}`);
1345
1457
  return;
1346
1458
  }
1347
1459
  const payload = await response.json();
@@ -1369,7 +1481,10 @@ var createCloudAdapters = (config) => {
1369
1481
  };
1370
1482
  /** Which revision is current, and what the flags are at — one small question for both halves of a served space. */
1371
1483
  const probe = async (env) => {
1372
- const answer = (await post(LATEST_REVISION_QUERY, { environment: env }, `latest revision of ${env}`))?.SpaceLatestRevision;
1484
+ const answer = (await post(LATEST_REVISION_QUERY, {
1485
+ environment: env,
1486
+ domain: domain ?? null
1487
+ }, `latest revision of ${env}`))?.SpaceLatestRevision;
1373
1488
  return {
1374
1489
  revision: answer?.snapshot?.revision,
1375
1490
  flagsHash: answer?.flagsHash ?? void 0
@@ -1738,7 +1853,7 @@ var verifiedDomain = (find) => {
1738
1853
  spaceId,
1739
1854
  ...environment ? { environment } : {},
1740
1855
  revision: row.revision ?? 0,
1741
- ...credential ? { credential } : {},
1856
+ ...credential ? { credentials: [credential] } : {},
1742
1857
  ...security ? { security } : {}
1743
1858
  };
1744
1859
  };
@@ -1757,10 +1872,13 @@ var wildcardSubdomain = ({ suffix, find }) => {
1757
1872
  const slug = req.hostname.slice(0, -dotted.length);
1758
1873
  if (!slug || slug.includes(".")) return;
1759
1874
  const space = await find(slug);
1760
- return space ? {
1761
- ...space,
1762
- revision: 0
1763
- } : void 0;
1875
+ if (!space) return;
1876
+ const { credential, ...found } = space;
1877
+ return {
1878
+ ...found,
1879
+ revision: 0,
1880
+ ...credential ? { credentials: [credential] } : {}
1881
+ };
1764
1882
  };
1765
1883
  };
1766
1884
  /**
@@ -1800,6 +1918,15 @@ var ENVIRONMENTS = [
1800
1918
  "development"
1801
1919
  ];
1802
1920
  var isEnvironment = (value) => value !== void 0 && ENVIRONMENTS.includes(value);
1921
+ var originHostOf = (req) => {
1922
+ const origin = req.headers.origin;
1923
+ if (typeof origin !== "string") return;
1924
+ try {
1925
+ return new URL(origin).hostname;
1926
+ } catch {
1927
+ return;
1928
+ }
1929
+ };
1803
1930
  /**
1804
1931
  * A page that renders the space itself — a site published as files, an embed, the desktop app — asking for it with the
1805
1932
  * space's public `render` credential, from wherever it is served.
@@ -1808,9 +1935,9 @@ var isEnvironment = (value) => value !== void 0 && ENVIRONMENTS.includes(value);
1808
1935
  * credential in `Authorization`, which a page's `fetch` sends: one in the address (`?access-token`) is a page opened
1809
1936
  * by a tool — a screenshot, a journey — and stays what it was. The grant is checked with the page's `Origin` and the
1810
1937
  * host it was presented on, as every browser credential is; it names the space, and the request the environment and
1811
- * revision — the live one when it names none, which is what a published site asks for.
1938
+ * revision — when it names none, the one its page's domain is published at (`served`), or the live one.
1812
1939
  */
1813
- var renderGrant = ({ resolveGrant, find }) => {
1940
+ var renderGrant = ({ resolveGrant, find, served }) => {
1814
1941
  return async (req) => {
1815
1942
  if (!req.headers.authorization) return;
1816
1943
  const result = await resolveGrant(req, { host: req.hostname });
@@ -1819,11 +1946,14 @@ var renderGrant = ({ resolveGrant, find }) => {
1819
1946
  if (!space) return refuse(404, "Space not found");
1820
1947
  const asked = req.query.environment;
1821
1948
  if (asked && !isEnvironment(asked)) return refuse(400, `No environment "${asked}": ask for one of ${ENVIRONMENTS.join(", ")}, or none for the live one`);
1822
- const revision = Number(req.query.revision);
1949
+ const environment = isEnvironment(asked) ? asked : space.environment ?? "main";
1950
+ const named = Number(req.query.revision);
1951
+ const originHost = originHostOf(req);
1952
+ const revision = Number.isInteger(named) && named > 0 ? named : served && originHost && environment !== "main" ? await served(space.spaceId, originHost, environment) ?? 0 : 0;
1823
1953
  return {
1824
1954
  spaceId: space.spaceId,
1825
- environment: isEnvironment(asked) ? asked : space.environment ?? "main",
1826
- revision: Number.isInteger(revision) && revision > 0 ? revision : 0,
1955
+ environment,
1956
+ revision,
1827
1957
  grantOrigins: result.grant.origins
1828
1958
  };
1829
1959
  };
@@ -1832,8 +1962,86 @@ var renderGrant = ({ resolveGrant, find }) => {
1832
1962
  var fixedSpace = (resolution) => {
1833
1963
  return () => Promise.resolve(resolution);
1834
1964
  };
1965
+ // src/adapters/space/snapshotPreview.ts
1966
+ /**
1967
+ * A snapshot's own address: `<name>--r12-production-<space>-<key>.<suffix>` serves `production r12` of one space, so it
1968
+ * can be looked at — and shown to whoever should see it — before any domain serves it.
1969
+ *
1970
+ * The address is a capability: its `key` is the deployment's secret for that one snapshot (an HMAC of it, say), so
1971
+ * nobody reaches a snapshot whose address they were not given, and nothing guessable names one. `name` is for the
1972
+ * person reading it — the space's sub-domain, cut to fit — and decides nothing: the space is the id the label carries.
1973
+ * A preview is never for search (`noindex`) and is served, and counted, as any page of the space is.
1974
+ */
1975
+ /** The environments a snapshot is taken of: the draft has no revisions, so it has no preview address. */
1976
+ var SNAPSHOT_ENVIRONMENTS = [
1977
+ "development",
1978
+ "staging",
1979
+ "production"
1980
+ ];
1981
+ /** RFC 1035: a label is at most 63 characters. */
1982
+ var MAX_LABEL = 63;
1983
+ /** How long a key is, in the label: the characters of [a-z0-9] the deployment's `keyOf` answers. */
1984
+ var PREVIEW_KEY_LENGTH = 12;
1985
+ var LABEL = new RegExp(`^(?:[a-z0-9-]*?--)?r(\\d{1,9})-(${SNAPSHOT_ENVIRONMENTS.join("|")})-([0-9a-z]{1,11})-([a-z0-9]{${String(12)}})$`);
1986
+ var sameKey = (presented, expected) => {
1987
+ const a = Buffer.from(presented);
1988
+ const b = Buffer.from(expected);
1989
+ return a.length === b.length && timingSafeEqual(a, b);
1990
+ };
1991
+ /**
1992
+ * The label of a snapshot's preview address, for a deployment that serves them with {@link snapshotPreview}: the
1993
+ * snapshot, the space's id and its key — and `name` before them, cut to what the label leaves room for (or left out).
1994
+ */
1995
+ var previewLabel = (name, address, key) => {
1996
+ const tail = `r${String(address.revision)}-${address.environment}-${address.spaceId.toString(36)}-${key}`;
1997
+ const room = MAX_LABEL - tail.length - 2;
1998
+ const cut = name.toLowerCase().replace(/[^a-z0-9-]/g, "").slice(0, Math.max(room, 0)).replace(/-+$/, "");
1999
+ if (!cut || cut.length === 2) return tail;
2000
+ return `${cut}--${tail}`;
2001
+ };
2002
+ /** The snapshot a label names, when it is a preview label at all. */
2003
+ var parsePreviewLabel = (label) => {
2004
+ const match = LABEL.exec(label);
2005
+ if (!match) return;
2006
+ const [, revision, environment, space, key] = match;
2007
+ const spaceId = parseInt(space, 36);
2008
+ const found = SNAPSHOT_ENVIRONMENTS.find((known) => known === environment);
2009
+ if (!found || !Number.isSafeInteger(spaceId) || spaceId <= 0) return;
2010
+ return {
2011
+ spaceId,
2012
+ environment: found,
2013
+ revision: Number(revision),
2014
+ key
2015
+ };
2016
+ };
2017
+ /**
2018
+ * Serves a snapshot at its preview address. Put it before `wildcardSubdomain`, whose sub-domains it shares: a label that
2019
+ * is not a preview's goes on to it, and one that is a preview's with the wrong key ends the chain as a 404 — the same
2020
+ * answer as a space that does not exist, so an address says nothing about which spaces do.
2021
+ */
2022
+ var snapshotPreview = ({ suffix, keyOf, find }) => {
2023
+ const dotted = suffix.startsWith(".") ? suffix : `.${suffix}`;
2024
+ return async (req) => {
2025
+ if (!req.hostname.endsWith(dotted)) return;
2026
+ const label = req.hostname.slice(0, -dotted.length);
2027
+ const asked = label.includes(".") ? void 0 : parsePreviewLabel(label);
2028
+ if (!asked) return;
2029
+ const { key, ...address } = asked;
2030
+ if (!sameKey(key, keyOf(address))) return refuse(404, "Space not found");
2031
+ const space = await find(address.spaceId);
2032
+ if (!space) return refuse(404, "Space not found");
2033
+ return {
2034
+ spaceId: space.spaceId,
2035
+ environment: address.environment,
2036
+ revision: address.revision,
2037
+ noindex: true,
2038
+ ...space.security ? { security: space.security } : {},
2039
+ ...space.credentials && space.credentials.length > 0 ? { credentials: space.credentials } : {}
2040
+ };
2041
+ };
2042
+ };
1835
2043
  // src/adapters/space/index.ts
1836
- var RESOLUTION_PREFIX = "space:resolution:";
2044
+ var RESOLUTION_PREFIX = "space:resolution:v2:";
1837
2045
  var DOMAINS_PREFIX = "space:domains:";
1838
2046
  /**
1839
2047
  * `getSpaceDeployment`, assembled.
@@ -2115,4 +2323,4 @@ var createRedisPageStore = (client, { prefix = "plitzi:{pages}:", maxBytes = byt
2115
2323
  return typeof count === "number" ? count : 0;
2116
2324
  }
2117
2325
  });
2118
- export { visitorScheme as $, shareCache as A, renderLimitOf as B, createOfflineDataLoader as C, cacheLimitsOf as D, normalizePlugins as E, offlineDataWith as F, buildCacheManager as G, keepPage as H, spaceDocument as I, keepsVersion as J, buildHtmlCacheKey as K, styleSheetOf as L, destroyServerCaches as M, digest as N, cacheFilterOf as O, hydrationPayload as P, SCHEME_HINT_HEADER as Q, DEFAULT_RENDER_WAIT_MS as R, sendScriptPolicy as S, normalizePluginSource as T, pageHtml as U, fromSharedPage as V, toSharedPage as W, ignoredQueryParamsOf as X, offlineDataCacheKeyOf as Y, renderedQuery as Z, buildServerInfo as _, presentsCredential as a, CSP_REPORT_PATH as b, wildcardSubdomain as c, createAuthAdapters as d, readCookie as et, createJsonAdapters as f, resolveDebugMode as g, escapeHtml as h, fixedSpace as i, requestPaintedState as it, createServerCaches as j, createCacheInvalidator as k, createMemoryCache as l, RequestMetrics as m, createSpaceAdapters as n, DEFAULT_IGNORED_QUERY_PARAMS as nt, renderGrant as o, createCloudAdapters as p, buildRscCacheKey as q, authoringPreview as r, DEFAULT_TTL_MS as rt, verifiedDomain as s, createRedisPageStore as t, DEFAULT_CACHE_BYTES as tt, refuse as u, googleFontsStage as v, reportReactBuild as w, scriptTemplateParams as x, googleFontsUrlOf as y, renderLimitFor as z };
2326
+ export { toSharedPage as $, sentInParts as A, destroyServerCaches as B, googleFontsStage as C, sendScriptPolicy as D, scriptTemplateParams as E, cacheLimitsOf as F, styleSheetOf as G, hydrationPayload as H, cacheFilterOf as I, renderLimitFor as J, escapeJson as K, createCacheInvalidator as L, reportReactBuild as M, normalizePluginSource as N, pageSchemaOf as O, normalizePlugins as P, pageHtml as Q, shareCache as R, buildServerInfo as S, CSP_REPORT_PATH as T, offlineDataWith as U, digest as V, spaceDocument as W, fromSharedPage as X, renderLimitOf as Y, keepPage as Z, createCloudAdapters as _, previewLabel as a, ignoredQueryParamsOf as at, escapeHtml as b, fixedSpace as c, visitorScheme as ct, verifiedDomain as d, DEFAULT_IGNORED_QUERY_PARAMS as dt, buildCacheManager as et, wildcardSubdomain as f, DEFAULT_TTL_MS as ft, createJsonAdapters as g, createAuthAdapters as h, parsePreviewLabel as i, offlineDataCacheKeyOf as it, createOfflineDataLoader as j, partTextOf as k, presentsCredential as l, readCookie as lt, refuse as m, createSpaceAdapters as n, buildRscCacheKey as nt, snapshotPreview as o, renderedQuery as ot, createMemoryCache as p, requestPaintedStateWithDefaults as pt, DEFAULT_RENDER_WAIT_MS as q, PREVIEW_KEY_LENGTH as r, keepsVersion as rt, authoringPreview as s, SCHEME_HINT_HEADER as st, createRedisPageStore as t, buildHtmlCacheKey as tt, renderGrant as u, DEFAULT_CACHE_BYTES as ut, ownVersion as v, googleFontsUrlOf as w, resolveDebugMode as x, RequestMetrics as y, createServerCaches as z };