siteplane 0.2.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.
@@ -1 +1,2 @@
1
- function L(t){return _(t)?t.type==="siteplane:refresh"?{type:"siteplane:refresh"}:t.type==="siteplane:highlight"&&(t.fieldId===null||O(t.fieldId))?{type:"siteplane:highlight",fieldId:t.fieldId}:null:null}function _(t){return typeof t=="object"&&t!==null}function O(t){return typeof t=="string"&&t.length>0&&t.length<=256}var r="data-siteplane-field",f="data-siteplane-selected",A="2px solid #2563eb",H="2px dashed #2563eb";function b(t){let c=t.parent??(window.parent===window?null:window.parent);if(!c)return()=>{};let s=new Map,o=null,E="",d,g=e=>c.postMessage(e,t.editorOrigin);function a(e){let n=e===void 0?`[${r}]`:`[${r}=${CSS.escape(e)}]`;return[...document.querySelectorAll(n)]}function l(e,n){if(n===null){let i=s.get(e);if(!i)return;e.style.outline=i.outline,e.style.outlineOffset=i.outlineOffset,s.delete(e);return}s.has(e)||s.set(e,{outline:e.style.outline,outlineOffset:e.style.outlineOffset}),e.style.outline=n,e.style.outlineOffset="2px"}function p(){for(let e of document.querySelectorAll(`[${f}]`))e.removeAttribute(f),l(e,null);if(o!==null)for(let e of a(o))e.setAttribute(f,""),l(e,A)}function m(){let e=[...new Set(a().map(M=>M.getAttribute(r)??""))],n=t.path(),i=JSON.stringify([n,e]);i!==E&&(E=i,g({type:"siteplane:page",version:1,path:n,fields:e.filter(Boolean)}))}let y=e=>e instanceof Element?e.closest(`[${r}]`):null;function T(e){let i=y(e.target)?.getAttribute(r);i&&(e.preventDefault(),e.stopPropagation(),g({type:"siteplane:select",version:1,fieldId:i}))}function u(e){let n=y(e.target);!n||n.hasAttribute(f)||l(n,e.type==="mouseover"?H:null)}function h(e){if(e.origin!==t.editorOrigin||e.source!==c)return;let n=L(e.data);n?.type==="siteplane:refresh"&&t.refresh(),n?.type==="siteplane:highlight"&&(o=n.fieldId,p())}let I=new MutationObserver(()=>{clearTimeout(d),d=setTimeout(()=>{m(),o!==null&&p()},150)});return document.addEventListener("click",T,!0),document.addEventListener("mouseover",u),document.addEventListener("mouseout",u),window.addEventListener("message",h),I.observe(document.documentElement,{childList:!0,subtree:!0,attributeFilter:[r]}),m(),()=>{clearTimeout(d),I.disconnect(),document.removeEventListener("click",T,!0),document.removeEventListener("mouseover",u),document.removeEventListener("mouseout",u),window.removeEventListener("message",h),o=null,p();for(let e of[...s.keys()])l(e,null)}}export{b as startBridge};
1
+ /*! Contains the decoder of @vercel/stega 1.1.0 (source: https://www.npmjs.com/package/@vercel/stega), subject to the terms of the Mozilla Public License, v. 2.0. A copy of the licence is at https://mozilla.org/MPL/2.0/. */
2
+ var j=/^[A-Za-z][A-Za-z0-9_-]*/u,X=/^\[_key=="([a-z][a-z0-9]{7})"\]/u,B=/^\[(0|[1-9][0-9]{0,8})\]/u;function R(e){let n="";for(let t of e)"field"in t?n+=n===""?t.field:`.${t.field}`:"key"in t?n+=`[_key=="${t.key}"]`:n+=`[${t.index}]`;return n}function y(e){if(typeof e!="string"||e.length>512)return null;let n=[],t=e;for(;t.length>0;){if(t.startsWith("[")){let l=X.exec(t),i=l?null:B.exec(t);if(l)n.push({key:l[1]});else if(i)n.push({index:Number(i[1])});else return null;t=t.slice((l??i)[0].length);continue}if(n.length>0){if(!t.startsWith("."))return null;t=t.slice(1)}let o=j.exec(t);if(!o)return null;n.push({field:o[0]}),t=t.slice(o[0].length)}return n}var V="abcdefghijklmnopqrstuvwxyz",ie=`${V}0123456789`;function M(e){return J(e)?e.type==="siteplane:refresh"?{type:"siteplane:refresh"}:e.type==="siteplane:highlight"&&(e.fieldId===null||z(e.fieldId))?{type:"siteplane:highlight",fieldId:e.fieldId}:null:null}function J(e){return typeof e=="object"&&e!==null}function z(e){return typeof e=="string"&&e.length>0&&e.length<=512}var P={0:8203,1:8204,2:8205,3:8290,4:8291,5:8288,6:65279,7:8289,8:119155,9:119156,a:119157,b:119158,c:119159,d:119160,e:119161,f:119162},E={0:8203,1:8204,2:8205,3:65279},U={0:String.fromCodePoint(E[0]),1:String.fromCodePoint(E[1]),2:String.fromCodePoint(E[2]),3:String.fromCodePoint(E[3])},T=new Array(4).fill(String.fromCodePoint(E[0])).join(""),b="\0";var S=Object.fromEntries(Object.entries(U).map(e=>[e[1],+e[0]])),C=Object.fromEntries(Object.entries(P).map(e=>e.reverse())),K=`${Object.values(P).map(e=>`\\u{${e.toString(16)}}`).join("")}`,A=new RegExp(`[${K}]{4,}`,"gu");function D(e){let n=e.match(A);if(n)return Z(n[0],!0)[0]}function Z(e,n=!1){let t=Array.from(e),o=1/0,l=-1;for(let i=0;i<t.length;++i)t[i]===T[0]&&t[i+1]===T[1]&&t[i+2]===T[2]&&t[i+3]===T[3]&&(o=Math.min(o,i),l=Math.max(l,i));if(l===-1)return q(t,n);for(let i=o;i<=l;++i)if(!((t.length-i)%4))try{let p=t.slice(i+4),f=new Uint8Array(p.length/4);for(let u=0;u<f.length;u++)f[u]=S[p[u*4]]<<6|S[p[u*4+1]]<<4|S[p[u*4+2]]<<2|S[p[u*4+3]];let a=new TextDecoder().decode(f);if(n){let u=a.indexOf(b);return u===-1&&(u=a.length),[JSON.parse(a.slice(0,u))]}return a.split(b).filter(Boolean).map(u=>JSON.parse(u))}catch{}return[]}function q(e,n){var t;let o=[];for(let f=e.length*.5;f--;){let a=`${C[e[f*2].codePointAt(0)]}${C[e[f*2+1].codePointAt(0)]}`;o.unshift(String.fromCharCode(parseInt(a,16)))}let l=[],i=[o.join("")],p=10;for(;i.length;){let f=i.shift();try{if(l.push(JSON.parse(f)),n)return l}catch(a){if(!p--)throw a;let u=+((t=a.message.match(/\sposition\s(\d+)$/))==null?void 0:t[1]);if(!u)throw a;i.unshift(f.substring(0,u),f.substring(u))}}return l}var $="data-siteplane-field",_="data-siteplane-selected",Y="2px solid #2563eb",Q="2px dashed #2563eb",F="script, style, noscript, template",ee=256,te=500;function fe(e){let n=e.parent??(window.parent===window?null:window.parent);if(!n)return()=>{};let t=new Map,o=null,l="",i,p=r=>n.postMessage(r,e.editorOrigin);function f(r,s){if(s===null){let d=t.get(r);if(!d)return;r.style.outline=d.outline,r.style.outlineOffset=d.outlineOffset,t.delete(r);return}t.has(r)||t.set(r,{outline:r.style.outline,outlineOffset:r.style.outlineOffset}),r.style.outline=s,r.style.outlineOffset="2px"}function a(){for(let c of document.querySelectorAll(`[${_}]`))c.removeAttribute(_),f(c,null);if(o===null)return;let r=o,s=c=>c===r||c.startsWith(`${r}.`)||c.startsWith(`${r}[`),d=new Set;k({text:(c,g)=>{g.some(s)&&c.parentElement instanceof HTMLElement&&d.add(c.parentElement)},element:(c,g)=>{g.some(s)&&c instanceof HTMLElement&&d.add(c)}});for(let c of d)c.setAttribute(_,""),f(c,Y)}function u(){let r=new Set,s=v=>{for(let m of v){let N=re(m);N&&r.add(N)}};k({text:(v,m)=>s(m),element:(v,m)=>s(m)});let d=[...r].slice(0,te),c=e.path(),g=JSON.stringify([c,d]);g!==l&&(l=g,p({type:"siteplane:page",version:1,path:c,fields:d}))}function x(r){for(let s=r instanceof Element?r:null;s&&s!==document.documentElement;s=s.parentElement){let d=ne(s)??W(s);if(d)return{path:d,element:s}}return null}function O(r){let s=x(r.target);s&&(r.preventDefault(),r.stopPropagation(),p({type:"siteplane:select",version:1,fieldId:s.path}))}function h(r){let s=x(r.target)?.element;!(s instanceof HTMLElement)||s.hasAttribute(_)||f(s,r.type==="mouseover"?Q:null)}function w(r){if(r.origin!==e.editorOrigin||r.source!==n)return;let s=M(r.data);s?.type==="siteplane:refresh"&&e.refresh(),s?.type==="siteplane:highlight"&&(o=s.fieldId,a())}let L=new MutationObserver(()=>{clearTimeout(i),i=setTimeout(()=>{u(),o!==null&&a()},150)});return document.addEventListener("click",O,!0),document.addEventListener("mouseover",h),document.addEventListener("mouseout",h),window.addEventListener("message",w),L.observe(document.documentElement,{childList:!0,subtree:!0,characterData:!0,attributeFilter:["alt",$]}),u(),()=>{clearTimeout(i),L.disconnect(),document.removeEventListener("click",O,!0),document.removeEventListener("mouseover",h),document.removeEventListener("mouseout",h),window.removeEventListener("message",w),o=null,a();for(let r of[...t.keys()])f(r,null)}}function k(e){if(!document.body)return;let n=document.createTreeWalker(document.body,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,{acceptNode:t=>t instanceof Element&&t.matches(F)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT});for(let t=n.nextNode();t;t=n.nextNode()){if(t instanceof Text){let i=I(t.data);i.length>0&&e.text(t,i);continue}let o=t,l=[G(o),W(o)].filter(i=>i!==null);l.length>0&&e.element(o,l)}}function ne(e){let n=G(e);if(n)return n;if(e.closest(F))return null;for(let t of e.childNodes)if(t instanceof Text){let o=I(t.data)[0];if(o)return o}return null}function G(e){return e instanceof HTMLImageElement?I(e.getAttribute("alt")??"")[0]??null:null}function W(e){let n=e.getAttribute($);return n&&y(n)?n:null}function I(e){let n=e.match(new RegExp(A.source,"gu"));return n?n.flatMap(t=>{let o;try{o=D(t)}catch{return[]}return typeof o=="string"&&y(o)?[o]:[]}):[]}function re(e){let n=y(e)??[],t=n.findIndex(i=>!("field"in i)),o=t===-1?n:n.slice(0,t);if(o.length<2)return null;let l=R(o);return l.length<=ee?l:null}export{fe as startBridge};
@@ -0,0 +1,6 @@
1
+ // src/internal/empty.ts
2
+ var empty = null;
3
+ var empty_default = empty;
4
+ export {
5
+ empty_default as default
6
+ };
package/dist/next.cjs CHANGED
@@ -23,6 +23,7 @@ __export(next_exports, {
23
23
  withSiteplane: () => withSiteplane
24
24
  });
25
25
  module.exports = __toCommonJS(next_exports);
26
+ var import_node_crypto = require("crypto");
26
27
  var import_node_fs = require("fs");
27
28
  var import_promises = require("fs/promises");
28
29
  var import_node_module = require("module");
@@ -51,9 +52,41 @@ function isWebOrigin(value) {
51
52
  }
52
53
  }
53
54
 
55
+ // src/runtime/frame-ancestors.ts
56
+ var FRAME_ANCESTORS = /^frame-ancestors(?:\s|$)/iu;
57
+ function mergeFrameAncestors(policy, editorOrigins) {
58
+ const policies = (policy ?? "").split(",").map(
59
+ (text) => text.split(";").map((directive) => directive.trim()).filter(Boolean)
60
+ ).filter((directives) => directives.length > 0);
61
+ let extended = false;
62
+ const merged = policies.map((directives) => {
63
+ const index = directives.findIndex((directive) => FRAME_ANCESTORS.test(directive));
64
+ if (index === -1) return directives;
65
+ extended = true;
66
+ const sources = (directives[index] ?? "").split(/\s+/u).slice(1);
67
+ const allowed = sources.some((source) => source.toLowerCase() === "'none'") ? editorOrigins : [...sources, ...editorOrigins.filter((origin) => !sources.includes(origin))];
68
+ return [
69
+ ...directives.slice(0, index),
70
+ `frame-ancestors ${allowed.join(" ") || "'none'"}`,
71
+ // Browsers use the first directive of a name and ignore repeats.
72
+ ...directives.slice(index + 1).filter((directive) => !FRAME_ANCESTORS.test(directive))
73
+ ];
74
+ });
75
+ if (!extended) {
76
+ const own = `frame-ancestors ${["'self'", ...editorOrigins].join(" ")}`;
77
+ const last = merged.at(-1);
78
+ if (last) last.push(own);
79
+ else merged.push([own]);
80
+ }
81
+ return merged.map((directives) => directives.join("; ")).join(", ");
82
+ }
83
+
54
84
  // src/next.ts
55
85
  var DRAFT_MODE_COOKIE = { type: "cookie", key: "__prerender_bypass" };
56
86
  var siteIdPattern2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
87
+ var SCHEMA_FILE = "siteplane.schema.ts";
88
+ var EMPTY_MODULE = "siteplane/internal/empty";
89
+ var BUILD_PHASE = "phase-production-build";
57
90
  function withSiteplane(nextConfig, options = {}) {
58
91
  return async (phase, context) => {
59
92
  const base = await (typeof nextConfig === "function" ? nextConfig(phase, context) : nextConfig);
@@ -61,10 +94,10 @@ function withSiteplane(nextConfig, options = {}) {
61
94
  let config = base;
62
95
  try {
63
96
  const project = readProjectConfig(projectDir);
64
- if (project) config = withEditor(config, project, { projectDir, admin: options.admin === true });
97
+ if (project) config = withEditor(config, project, { projectDir, admin: options.admin === true, phase });
65
98
  } catch (error) {
66
99
  console.warn(
67
- `[Siteplane] ${SITEPLANE_CONFIG_FILE} could not be read, so the website builds without Siteplane content: ${error instanceof Error ? error.message : String(error)}`
100
+ `[Siteplane] ${SITEPLANE_CONFIG_FILE} could not be read, so pages that read content cannot render: ${error instanceof Error ? error.message : String(error)}`
68
101
  );
69
102
  }
70
103
  return options.booking ? await withBooking(config, options.booking.site, projectDir) : config;
@@ -79,21 +112,40 @@ function readProjectConfig(projectDir) {
79
112
  }
80
113
  function withEditor(config, project, options) {
81
114
  const configPath = (0, import_node_path.join)(options.projectDir, SITEPLANE_CONFIG_FILE);
82
- const next = { ...config, ...moduleAlias(config, options.projectDir) };
115
+ const schemaPath = (0, import_node_path.join)(options.projectDir, SCHEMA_FILE);
116
+ const schema = (0, import_node_fs.existsSync)(schemaPath) ? schemaPath : null;
117
+ if (!schema) {
118
+ console.warn(
119
+ `[Siteplane] ${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.`
120
+ );
121
+ }
122
+ const next = { ...config, ...moduleAlias(config, options.projectDir, schema !== null) };
123
+ if (options.phase === BUILD_PHASE) next.env = { ...config.env, SITEPLANE_BUILD_STAMP: `siteplane-mark-${(0, import_node_crypto.randomUUID)()}` };
83
124
  next.webpack = (webpackConfig, context) => {
84
125
  webpackConfig.resolve ??= {};
126
+ const server = context?.isServer === true;
85
127
  const alias = webpackConfig.resolve.alias;
86
- if (Array.isArray(alias)) alias.push({ name: "siteplane/config", alias: configPath, onlyModule: true });
87
- else webpackConfig.resolve.alias = Object.assign(alias ?? {}, { "siteplane/config$": configPath });
128
+ if (Array.isArray(alias)) {
129
+ alias.push({ name: "siteplane/config", alias: configPath, onlyModule: true });
130
+ if (schema && server) alias.push({ name: "siteplane/schema-file", alias: schema, onlyModule: true });
131
+ } else {
132
+ webpackConfig.resolve.alias = Object.assign(alias ?? {}, {
133
+ "siteplane/config$": configPath,
134
+ ...schema && server ? { "siteplane/schema-file$": schema } : {}
135
+ });
136
+ }
88
137
  return config.webpack ? config.webpack(webpackConfig, context) : webpackConfig;
89
138
  };
90
139
  const api = new URL(project.apiOrigin);
91
- if (api.protocol === "https:") {
92
- const pattern = { protocol: "https", hostname: api.hostname, pathname: "/**" };
93
- const patterns = config.images?.remotePatterns ?? [];
94
- const known = patterns.some((entry) => JSON.stringify(entry) === JSON.stringify(pattern));
95
- next.images = { ...config.images, remotePatterns: known ? patterns : [...patterns, pattern] };
96
- }
140
+ const pattern = {
141
+ protocol: api.protocol.slice(0, -1),
142
+ hostname: api.hostname,
143
+ ...api.port ? { port: api.port } : {},
144
+ pathname: "/site-images/**"
145
+ };
146
+ const patterns = config.images?.remotePatterns ?? [];
147
+ const known = patterns.some((entry) => JSON.stringify(entry) === JSON.stringify(pattern));
148
+ next.images = { ...config.images, remotePatterns: known ? patterns : [...patterns, pattern] };
97
149
  const websiteHeaders = config.headers;
98
150
  if (websiteHeaders) {
99
151
  next.headers = async () => {
@@ -112,8 +164,11 @@ function withEditor(config, project, options) {
112
164
  }
113
165
  return next;
114
166
  }
115
- function moduleAlias(config, projectDir) {
116
- const alias = { "siteplane/config": `./${SITEPLANE_CONFIG_FILE}` };
167
+ function moduleAlias(config, projectDir, schema) {
168
+ const alias = {
169
+ "siteplane/config": `./${SITEPLANE_CONFIG_FILE}`,
170
+ ...schema ? { "siteplane/schema-file": { browser: EMPTY_MODULE, default: `./${SCHEMA_FILE}` } } : {}
171
+ };
117
172
  if (usesExperimentalTurbo(projectDir)) {
118
173
  const turbo = config.experimental?.turbo;
119
174
  return {
@@ -141,10 +196,7 @@ function draftFrameRules(rules, editorOrigins) {
141
196
  headers
142
197
  });
143
198
  const optionsOnly = rules.filter((rule) => rule.headers.some((header) => isXfo(header.key)) && !rule.headers.some((header) => isCsp(header.key))).map(
144
- (rule) => draftRule(rule, [
145
- ...rule.headers,
146
- { key: "Content-Security-Policy", value: `frame-ancestors 'self' ${editorOrigins.join(" ")}` }
147
- ])
199
+ (rule) => draftRule(rule, [...rule.headers, { key: "Content-Security-Policy", value: mergeFrameAncestors(null, editorOrigins) }])
148
200
  );
149
201
  const policies = rules.filter(
150
202
  (rule) => rule.headers.some((header) => isCsp(header.key) && (hasFrameOptions || /frame-ancestors/iu.test(header.value)))
@@ -152,21 +204,12 @@ function draftFrameRules(rules, editorOrigins) {
152
204
  (rule) => draftRule(
153
205
  rule,
154
206
  rule.headers.map(
155
- (header) => isCsp(header.key) ? { ...header, value: allowEditorFrames(header.value, editorOrigins) } : header
207
+ (header) => isCsp(header.key) ? { ...header, value: mergeFrameAncestors(header.value, editorOrigins) } : header
156
208
  )
157
209
  )
158
210
  );
159
211
  return [...optionsOnly, ...policies];
160
212
  }
161
- function allowEditorFrames(policy, editorOrigins) {
162
- const directives = policy.split(";").map((directive) => directive.trim()).filter(Boolean);
163
- const index = directives.findIndex((directive) => /^frame-ancestors(\s|$)/iu.test(directive));
164
- if (index === -1) return [...directives, `frame-ancestors 'self' ${editorOrigins.join(" ")}`].join("; ");
165
- const sources = (directives[index] ?? "").split(/\s+/u).slice(1);
166
- const allowed = sources.includes("'none'") ? editorOrigins : [...sources, ...editorOrigins.filter((origin) => !sources.includes(origin))];
167
- directives[index] = `frame-ancestors ${allowed.join(" ")}`;
168
- return directives.join("; ");
169
- }
170
213
  function prependRewrites(rewrites, rules) {
171
214
  return async () => {
172
215
  const existing = await rewrites?.() ?? [];
package/dist/next.d.ts CHANGED
@@ -15,13 +15,16 @@ type SiteplaneNextOptions = {
15
15
  projectDir?: string;
16
16
  };
17
17
  /**
18
- * `next.config` wrapper (Vertrag 54 §6.5). With `siteplane.config.json` it adds
19
- * only Siteplane's image host for `next/image`, Draft Mode variants of the
20
- * website's own frame headers for the editor origins, the `siteplane/config`
21
- * module for the runtime and, on request, `/admin`. A `basePath` needs nothing
22
- * here: the website URL in Siteplane carries it, and the routes of this package
23
- * live below it. The editor connection never scans code, sets no build
24
- * variables and never stops a build; only an invalid `booking.site` is an error.
18
+ * `next.config` wrapper (Vertrag 54 §6.5, Dokument 68 4 and 5.1). With
19
+ * `siteplane.config.json` it adds only Siteplane's image path for
20
+ * `next/image`, Draft Mode variants of the website's own frame headers for the
21
+ * editor origins, the `siteplane/config` module, the description
22
+ * `siteplane.schema.ts` as `siteplane/schema-file` for the server only, a mark
23
+ * of each build (`SITEPLANE_BUILD_STAMP`, so Next's cache of an earlier build
24
+ * never answers it) and, on request, `/admin`. A `basePath` needs nothing here:
25
+ * the website URL in Siteplane carries it, and the routes of this package live
26
+ * below it. It never scans code, writes no file of the project and never stops
27
+ * a build; only an invalid `booking.site` is an error.
25
28
  */
26
29
  declare function withSiteplane(nextConfig: NextConfig | Promise<NextConfig> | NextConfigFunction, options?: SiteplaneNextOptions): (phase: string, context: {
27
30
  defaultConfig: NextConfig;
package/dist/next.js CHANGED
@@ -4,12 +4,47 @@ import {
4
4
  } from "./chunk-KZ3AQ6OA.js";
5
5
 
6
6
  // src/next.ts
7
+ import { randomUUID } from "crypto";
7
8
  import { existsSync, readFileSync } from "fs";
8
9
  import { access } from "fs/promises";
9
10
  import { createRequire } from "module";
10
11
  import { join } from "path";
12
+
13
+ // src/runtime/frame-ancestors.ts
14
+ var FRAME_ANCESTORS = /^frame-ancestors(?:\s|$)/iu;
15
+ function mergeFrameAncestors(policy, editorOrigins) {
16
+ const policies = (policy ?? "").split(",").map(
17
+ (text) => text.split(";").map((directive) => directive.trim()).filter(Boolean)
18
+ ).filter((directives) => directives.length > 0);
19
+ let extended = false;
20
+ const merged = policies.map((directives) => {
21
+ const index = directives.findIndex((directive) => FRAME_ANCESTORS.test(directive));
22
+ if (index === -1) return directives;
23
+ extended = true;
24
+ const sources = (directives[index] ?? "").split(/\s+/u).slice(1);
25
+ const allowed = sources.some((source) => source.toLowerCase() === "'none'") ? editorOrigins : [...sources, ...editorOrigins.filter((origin) => !sources.includes(origin))];
26
+ return [
27
+ ...directives.slice(0, index),
28
+ `frame-ancestors ${allowed.join(" ") || "'none'"}`,
29
+ // Browsers use the first directive of a name and ignore repeats.
30
+ ...directives.slice(index + 1).filter((directive) => !FRAME_ANCESTORS.test(directive))
31
+ ];
32
+ });
33
+ if (!extended) {
34
+ const own = `frame-ancestors ${["'self'", ...editorOrigins].join(" ")}`;
35
+ const last = merged.at(-1);
36
+ if (last) last.push(own);
37
+ else merged.push([own]);
38
+ }
39
+ return merged.map((directives) => directives.join("; ")).join(", ");
40
+ }
41
+
42
+ // src/next.ts
11
43
  var DRAFT_MODE_COOKIE = { type: "cookie", key: "__prerender_bypass" };
12
44
  var siteIdPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
45
+ var SCHEMA_FILE = "siteplane.schema.ts";
46
+ var EMPTY_MODULE = "siteplane/internal/empty";
47
+ var BUILD_PHASE = "phase-production-build";
13
48
  function withSiteplane(nextConfig, options = {}) {
14
49
  return async (phase, context) => {
15
50
  const base = await (typeof nextConfig === "function" ? nextConfig(phase, context) : nextConfig);
@@ -17,10 +52,10 @@ function withSiteplane(nextConfig, options = {}) {
17
52
  let config = base;
18
53
  try {
19
54
  const project = readProjectConfig(projectDir);
20
- if (project) config = withEditor(config, project, { projectDir, admin: options.admin === true });
55
+ if (project) config = withEditor(config, project, { projectDir, admin: options.admin === true, phase });
21
56
  } catch (error) {
22
57
  console.warn(
23
- `[Siteplane] ${SITEPLANE_CONFIG_FILE} could not be read, so the website builds without Siteplane content: ${error instanceof Error ? error.message : String(error)}`
58
+ `[Siteplane] ${SITEPLANE_CONFIG_FILE} could not be read, so pages that read content cannot render: ${error instanceof Error ? error.message : String(error)}`
24
59
  );
25
60
  }
26
61
  return options.booking ? await withBooking(config, options.booking.site, projectDir) : config;
@@ -35,21 +70,40 @@ function readProjectConfig(projectDir) {
35
70
  }
36
71
  function withEditor(config, project, options) {
37
72
  const configPath = join(options.projectDir, SITEPLANE_CONFIG_FILE);
38
- const next = { ...config, ...moduleAlias(config, options.projectDir) };
73
+ const schemaPath = join(options.projectDir, SCHEMA_FILE);
74
+ const schema = existsSync(schemaPath) ? schemaPath : null;
75
+ if (!schema) {
76
+ console.warn(
77
+ `[Siteplane] ${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.`
78
+ );
79
+ }
80
+ const next = { ...config, ...moduleAlias(config, options.projectDir, schema !== null) };
81
+ if (options.phase === BUILD_PHASE) next.env = { ...config.env, SITEPLANE_BUILD_STAMP: `siteplane-mark-${randomUUID()}` };
39
82
  next.webpack = (webpackConfig, context) => {
40
83
  webpackConfig.resolve ??= {};
84
+ const server = context?.isServer === true;
41
85
  const alias = webpackConfig.resolve.alias;
42
- if (Array.isArray(alias)) alias.push({ name: "siteplane/config", alias: configPath, onlyModule: true });
43
- else webpackConfig.resolve.alias = Object.assign(alias ?? {}, { "siteplane/config$": configPath });
86
+ if (Array.isArray(alias)) {
87
+ alias.push({ name: "siteplane/config", alias: configPath, onlyModule: true });
88
+ if (schema && server) alias.push({ name: "siteplane/schema-file", alias: schema, onlyModule: true });
89
+ } else {
90
+ webpackConfig.resolve.alias = Object.assign(alias ?? {}, {
91
+ "siteplane/config$": configPath,
92
+ ...schema && server ? { "siteplane/schema-file$": schema } : {}
93
+ });
94
+ }
44
95
  return config.webpack ? config.webpack(webpackConfig, context) : webpackConfig;
45
96
  };
46
97
  const api = new URL(project.apiOrigin);
47
- if (api.protocol === "https:") {
48
- const pattern = { protocol: "https", hostname: api.hostname, pathname: "/**" };
49
- const patterns = config.images?.remotePatterns ?? [];
50
- const known = patterns.some((entry) => JSON.stringify(entry) === JSON.stringify(pattern));
51
- next.images = { ...config.images, remotePatterns: known ? patterns : [...patterns, pattern] };
52
- }
98
+ const pattern = {
99
+ protocol: api.protocol.slice(0, -1),
100
+ hostname: api.hostname,
101
+ ...api.port ? { port: api.port } : {},
102
+ pathname: "/site-images/**"
103
+ };
104
+ const patterns = config.images?.remotePatterns ?? [];
105
+ const known = patterns.some((entry) => JSON.stringify(entry) === JSON.stringify(pattern));
106
+ next.images = { ...config.images, remotePatterns: known ? patterns : [...patterns, pattern] };
53
107
  const websiteHeaders = config.headers;
54
108
  if (websiteHeaders) {
55
109
  next.headers = async () => {
@@ -68,8 +122,11 @@ function withEditor(config, project, options) {
68
122
  }
69
123
  return next;
70
124
  }
71
- function moduleAlias(config, projectDir) {
72
- const alias = { "siteplane/config": `./${SITEPLANE_CONFIG_FILE}` };
125
+ function moduleAlias(config, projectDir, schema) {
126
+ const alias = {
127
+ "siteplane/config": `./${SITEPLANE_CONFIG_FILE}`,
128
+ ...schema ? { "siteplane/schema-file": { browser: EMPTY_MODULE, default: `./${SCHEMA_FILE}` } } : {}
129
+ };
73
130
  if (usesExperimentalTurbo(projectDir)) {
74
131
  const turbo = config.experimental?.turbo;
75
132
  return {
@@ -97,10 +154,7 @@ function draftFrameRules(rules, editorOrigins) {
97
154
  headers
98
155
  });
99
156
  const optionsOnly = rules.filter((rule) => rule.headers.some((header) => isXfo(header.key)) && !rule.headers.some((header) => isCsp(header.key))).map(
100
- (rule) => draftRule(rule, [
101
- ...rule.headers,
102
- { key: "Content-Security-Policy", value: `frame-ancestors 'self' ${editorOrigins.join(" ")}` }
103
- ])
157
+ (rule) => draftRule(rule, [...rule.headers, { key: "Content-Security-Policy", value: mergeFrameAncestors(null, editorOrigins) }])
104
158
  );
105
159
  const policies = rules.filter(
106
160
  (rule) => rule.headers.some((header) => isCsp(header.key) && (hasFrameOptions || /frame-ancestors/iu.test(header.value)))
@@ -108,21 +162,12 @@ function draftFrameRules(rules, editorOrigins) {
108
162
  (rule) => draftRule(
109
163
  rule,
110
164
  rule.headers.map(
111
- (header) => isCsp(header.key) ? { ...header, value: allowEditorFrames(header.value, editorOrigins) } : header
165
+ (header) => isCsp(header.key) ? { ...header, value: mergeFrameAncestors(header.value, editorOrigins) } : header
112
166
  )
113
167
  )
114
168
  );
115
169
  return [...optionsOnly, ...policies];
116
170
  }
117
- function allowEditorFrames(policy, editorOrigins) {
118
- const directives = policy.split(";").map((directive) => directive.trim()).filter(Boolean);
119
- const index = directives.findIndex((directive) => /^frame-ancestors(\s|$)/iu.test(directive));
120
- if (index === -1) return [...directives, `frame-ancestors 'self' ${editorOrigins.join(" ")}`].join("; ");
121
- const sources = (directives[index] ?? "").split(/\s+/u).slice(1);
122
- const allowed = sources.includes("'none'") ? editorOrigins : [...sources, ...editorOrigins.filter((origin) => !sources.includes(origin))];
123
- directives[index] = `frame-ancestors ${allowed.join(" ")}`;
124
- return directives.join("; ");
125
- }
126
171
  function prependRewrites(rewrites, rules) {
127
172
  return async () => {
128
173
  const existing = await rewrites?.() ?? [];
package/dist/route.d.ts CHANGED
@@ -5,7 +5,8 @@
5
5
  * export { GET, POST } from "siteplane/route";
6
6
  * ```
7
7
  *
8
- * GET serves `draft` (Draft Mode for the editor) and `status`, POST `revalidate`.
8
+ * GET serves `draft` (Draft Mode for the editor, and on the dev server the
9
+ * count request of the CLI) and `status`, POST `revalidate`.
9
10
  */
10
11
  declare const GET: (request: Request) => Promise<Response>;
11
12
  declare const POST: (request: Request) => Promise<Response>;
package/dist/route.js CHANGED
@@ -1,11 +1,12 @@
1
1
  import {
2
2
  PREVIEW_COOKIE,
3
+ readBoundedText,
3
4
  signingKeys,
4
5
  siteCacheTag,
5
6
  siteConfig,
6
7
  verifySitePreviewToken,
7
8
  verifySiteRevalidation
8
- } from "./chunk-BLJCWIYD.js";
9
+ } from "./chunk-IOFM5PE3.js";
9
10
  import "./chunk-KZ3AQ6OA.js";
10
11
 
11
12
  // src/route.ts
@@ -49,26 +50,46 @@ function createRouteHandlers(dependencies) {
49
50
  }
50
51
  function status(config) {
51
52
  const { VERCEL_GIT_COMMIT_SHA: commit, VERCEL_ENV: environment } = dependencies.env;
52
- return Response.json(
53
- { siteId: config.siteId, version: dependencies.version, commit: commit || null, environment: environment || null },
54
- { headers: noStore }
55
- );
53
+ const answer = {
54
+ siteId: config.siteId,
55
+ version: dependencies.version,
56
+ commit: commit || null,
57
+ environment: environment || null,
58
+ ...statusDetails(),
59
+ ...dependencies.devServer ? { devServer: true } : {}
60
+ };
61
+ return Response.json(answer, { headers: noStore });
62
+ }
63
+ function statusDetails() {
64
+ try {
65
+ return dependencies.statusDetails?.() ?? {};
66
+ } catch {
67
+ return {};
68
+ }
56
69
  }
57
70
  async function draft(request, config) {
58
71
  const url = new URL(request.url);
59
72
  const query = url.searchParams;
73
+ const count = query.has("count");
74
+ if (count && !dependencies.devServer) return notFound();
60
75
  const path = parseSafeRedirectPath(query.get("path") ?? "/");
61
76
  if (!path) return Response.json({ error: "invalid_path" }, { status: 400, headers: noStore });
77
+ if (count) {
78
+ return redirect(url, path, await dependencies.enableCount?.() ?? {});
79
+ }
62
80
  const now = dependencies.now();
63
81
  const token = query.get("token") ?? "";
64
82
  const claims = token ? await verifySitePreviewToken(config, token, dependencies.keys, now) : null;
65
83
  if (!claims) return Response.json({ error: "preview_token_invalid" }, { status: 401, headers: noStore });
66
84
  await dependencies.enableDraftMode({ token, maxAgeSeconds: claims.exp - Math.floor(now.getTime() / 1e3) });
85
+ return redirect(url, path);
86
+ }
87
+ function redirect(url, path, headers = {}) {
67
88
  const root = url.pathname.endsWith("/") ? "../../../" : "../../";
68
- return new Response(null, { status: 307, headers: { ...noStore, Location: `${root}${path.slice(1)}` } });
89
+ return new Response(null, { status: 307, headers: { ...noStore, ...headers, Location: `${root}${path.slice(1)}` } });
69
90
  }
70
91
  async function revalidate(request, config) {
71
- const payload = await readBoundedText(request);
92
+ const payload = await readBoundedText(request.body, MAX_REVALIDATION_BYTES);
72
93
  if (payload === null) return Response.json({ error: "too_large" }, { status: 413, headers: noStore });
73
94
  const now = dependencies.now();
74
95
  if (!await verifySiteRevalidation(config, { headers: request.headers, payload }, dependencies.keys, now)) {
@@ -95,26 +116,9 @@ function readSiteId(payload) {
95
116
  return void 0;
96
117
  }
97
118
  }
98
- async function readBoundedText(request) {
99
- if (!request.body) return "";
100
- const reader = request.body.getReader();
101
- const chunks = [];
102
- let bytes = 0;
103
- for (; ; ) {
104
- const chunk = await reader.read();
105
- if (chunk.done) break;
106
- bytes += chunk.value.byteLength;
107
- if (bytes > MAX_REVALIDATION_BYTES) {
108
- await reader.cancel();
109
- return null;
110
- }
111
- chunks.push(chunk.value);
112
- }
113
- return new TextDecoder().decode(Buffer.concat(chunks));
114
- }
115
119
 
116
120
  // src/version.ts
117
- var PACKAGE_VERSION = "0.2.1";
121
+ var PACKAGE_VERSION = "0.3.0";
118
122
 
119
123
  // src/route.ts
120
124
  var embeddable = { httpOnly: true, secure: true, sameSite: "none", partitioned: true, path: "/" };
@@ -134,7 +138,16 @@ var handlers = createRouteHandlers({
134
138
  },
135
139
  env: process.env,
136
140
  version: PACKAGE_VERSION,
137
- now: () => /* @__PURE__ */ new Date()
141
+ now: () => /* @__PURE__ */ new Date(),
142
+ // Plan 69 S3b (Nachweis 2, Teil c): exactly this expression, which Next fixes when it builds, so no production
143
+ // build has the count request, also when started with NODE_ENV=development; never read through `env` at run time.
144
+ devServer: process.env.NODE_ENV === "development",
145
+ // The count is Draft Mode alone, which every page sees, also one with `force-static` or one that reads in
146
+ // "use cache"; Next sends its cookie with the answer (Korrekturrunde 1 of S3b).
147
+ enableCount: async () => {
148
+ (await draftMode()).enable();
149
+ return {};
150
+ }
138
151
  });
139
152
  var GET = handlers.GET;
140
153
  var POST = handlers.POST;
@@ -0,0 +1,11 @@
1
+ import { SiteplaneSchema } from './schema.js';
2
+
3
+ /**
4
+ * `siteplane/schema-file`: `withSiteplane` and the Astro integration point this
5
+ * module at the project's `siteplane.schema.ts`, on the server only (Nachweis
6
+ * 1, Teil a). In the browser and without the description it stays empty, so the
7
+ * description never reaches a bundle for the browser.
8
+ */
9
+ declare const schema: SiteplaneSchema | null;
10
+
11
+ export { schema as default };
@@ -0,0 +1,6 @@
1
+ // src/schema-file.ts
2
+ var schema = null;
3
+ var schema_file_default = schema;
4
+ export {
5
+ schema_file_default as default
6
+ };
@@ -0,0 +1,64 @@
1
+ /** The types of a field in the description, in Payload's notation (Dokument 68, 4.1). */
2
+ type SchemaFieldType = "text" | "textarea" | "link" | "image" | "group" | "array" | "json";
3
+ /** A field of the description: a value, a group of fields or a list of rows. */
4
+ type SchemaField = {
5
+ name: string;
6
+ type: SchemaFieldType;
7
+ label?: string;
8
+ required?: boolean;
9
+ /** Only in list rows: the value a new row starts with. */
10
+ defaultValue?: unknown;
11
+ admin?: {
12
+ description?: string;
13
+ hidden?: boolean;
14
+ rowLabel?: string;
15
+ };
16
+ /** group, array */
17
+ fields?: SchemaField[];
18
+ /** array */
19
+ labels?: {
20
+ singular: string;
21
+ plural: string;
22
+ };
23
+ /** array */
24
+ minRows?: number;
25
+ maxRows?: number;
26
+ };
27
+ /** Why a page is left out of the count (Dokument 68, 7.2). */
28
+ type IgnoreReason = "decoration" | "generated" | "third-party" | "code" | "a11y" | "legal" | "collection" | "owner-wish" | "unused";
29
+ /** A page left out of the count; a path ending in `/*` means every page below it. */
30
+ type IgnoreRule = {
31
+ path: string;
32
+ reason: IgnoreReason;
33
+ };
34
+ /** The description of the website's content: its globals and the pages the count leaves out. */
35
+ type SiteplaneSchema = {
36
+ globals: Array<{
37
+ slug: string;
38
+ label?: string;
39
+ fields: SchemaField[];
40
+ }>;
41
+ ignore?: IgnoreRule[];
42
+ };
43
+ /**
44
+ * `siteplane/schema` (Dokument 68, 4.1): the description of the website's
45
+ * content in `siteplane.schema.ts`, in Payload's notation.
46
+ *
47
+ * ```ts
48
+ * import { defineSchema } from "siteplane/schema";
49
+ *
50
+ * export default defineSchema({
51
+ * globals: [{ slug: "home", label: "Home", fields: [{ name: "title", type: "text", required: true }] }],
52
+ * });
53
+ * ```
54
+ *
55
+ * It returns the description unchanged; `npx siteplane check` checks it, and
56
+ * the website reads it on its server through `siteplane/schema-file`. It has
57
+ * no dependencies, so the CLI and every bundler load it as it is. Fields kept
58
+ * in a variable of their own need the type, e.g.
59
+ * `const preisZeile: SchemaField[] = [ … ]`; TypeScript otherwise widens
60
+ * `type: "text"` to a string.
61
+ */
62
+ declare function defineSchema(schema: SiteplaneSchema): SiteplaneSchema;
63
+
64
+ export { type IgnoreReason, type IgnoreRule, type SchemaField, type SchemaFieldType, type SiteplaneSchema, defineSchema };
package/dist/schema.js ADDED
@@ -0,0 +1,7 @@
1
+ // src/schema.ts
2
+ function defineSchema(schema) {
3
+ return schema;
4
+ }
5
+ export {
6
+ defineSchema
7
+ };