payload-live-preview 2.2.0 → 2.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -21
- package/dist/adapters/astro/index.d.ts +2 -2
- package/dist/adapters/astro/index.js +1 -1
- package/dist/adapters/astro/index.js.map +1 -1
- package/dist/adapters/astro/middleware-entry.js +1 -1
- package/dist/adapters/astro/middleware-entry.js.map +1 -1
- package/dist/adapters/nextjs/index.d.ts +1 -1
- package/dist/adapters/nextjs/index.js +1 -1
- package/dist/adapters/nextjs/index.js.map +1 -1
- package/dist/adapters/nuxt/index.d.ts +2 -2
- package/dist/adapters/nuxt/index.js +1 -1
- package/dist/adapters/nuxt/index.js.map +1 -1
- package/dist/adapters/react/index.d.ts +2 -2
- package/dist/adapters/react/index.js +1 -1
- package/dist/adapters/react/index.js.map +1 -1
- package/dist/adapters/sveltekit/index.d.ts +2 -2
- package/dist/adapters/sveltekit/index.js +1 -1
- package/dist/adapters/sveltekit/index.js.map +1 -1
- package/dist/adapters/vue/index.d.ts +2 -2
- package/dist/adapters/vue/index.js +1 -1
- package/dist/adapters/vue/index.js.map +1 -1
- package/dist/annotate.d.ts +22 -15
- package/dist/annotate.js +1 -1
- package/dist/annotate.js.map +1 -1
- package/dist/client.cjs +1 -1
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +112 -112
- package/dist/client.d.ts +112 -112
- package/dist/client.js +1 -1
- package/dist/client.js.map +1 -1
- package/dist/codegen-cli.js +1 -1
- package/dist/codegen-cli.js.map +1 -1
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.cjs.map +1 -1
- package/dist/codegen.d.cts +14 -16
- package/dist/codegen.d.ts +14 -16
- package/dist/codegen.js +1 -1
- package/dist/codegen.js.map +1 -1
- package/dist/core.cjs +1 -1
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +176 -170
- package/dist/core.d.ts +176 -170
- package/dist/core.js +1 -1
- package/dist/core.js.map +1 -1
- package/dist/doctor-cli.d.ts +1 -1
- package/dist/doctor-cli.js +1 -1
- package/dist/doctor-cli.js.map +1 -1
- package/dist/doctor.d.ts +2 -2
- package/dist/doctor.js +1 -1
- package/dist/doctor.js.map +1 -1
- package/dist/{document-session-DWi9H3Qk.d.ts → document-session-Bkd181PV.d.ts} +3 -2
- package/dist/{fragment-endpoint-DGGLIijM.d.ts → fragment-endpoint-CLRpNQ3n.d.ts} +4 -2
- package/dist/fragment.cjs.map +1 -1
- package/dist/fragment.d.cts +1 -1
- package/dist/fragment.d.ts +1 -1
- package/dist/fragment.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +185 -177
- package/dist/index.d.ts +185 -177
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/lean.cjs +1 -1
- package/dist/lean.cjs.map +1 -1
- package/dist/lean.js +1 -1
- package/dist/lean.js.map +1 -1
- package/dist/lexical.cjs +1 -1
- package/dist/lexical.cjs.map +1 -1
- package/dist/lexical.js +1 -1
- package/dist/lexical.js.map +1 -1
- package/dist/plugins.cjs +1 -1
- package/dist/plugins.cjs.map +1 -1
- package/dist/plugins.d.cts +1 -1
- package/dist/plugins.d.ts +1 -1
- package/dist/plugins.js +1 -1
- package/dist/plugins.js.map +1 -1
- package/dist/{probe-DpMZ4fOS.d.ts → probe-D-IHg9dF.d.ts} +1 -1
- package/dist/server.cjs +1 -1
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +4 -2
- package/dist/server.d.ts +4 -2
- package/dist/server.js +1 -1
- package/dist/server.js.map +1 -1
- package/dist/structural.cjs +2 -2
- package/dist/structural.cjs.map +1 -1
- package/dist/structural.d.cts +27 -27
- package/dist/structural.d.ts +27 -27
- package/dist/structural.js +2 -2
- package/dist/structural.js.map +1 -1
- package/package.json +12 -9
package/dist/annotate.d.ts
CHANGED
|
@@ -6,15 +6,21 @@
|
|
|
6
6
|
* template language the package adapts:
|
|
7
7
|
*
|
|
8
8
|
* ```
|
|
9
|
-
* <h1>{page.title}</h1>
|
|
9
|
+
* <h1 data-payload-field="title">{page.title}</h1> bound by hand
|
|
10
|
+
* <p>{page.subtitle}</p> → subtitle
|
|
10
11
|
* ```
|
|
11
12
|
*
|
|
12
|
-
* An element whose entire content is one member expression, rooted at
|
|
13
|
-
* variable
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
13
|
+
* An element whose entire content is one member expression, rooted at a
|
|
14
|
+
* variable the file already binds a field of by hand, whose remaining path a
|
|
15
|
+
* collection or global has together with those hand-bound fields. The hand
|
|
16
|
+
* binding is the only thing in a template that says which variable holds the
|
|
17
|
+
* previewed document: `post` in a card, `settings` in a footer and `page` in a
|
|
18
|
+
* route look alike, and on four sites 16 of the 17 bindings proposed without
|
|
19
|
+
* it were wrong, most of them a field of some other document. Everything
|
|
20
|
+
* else — an interpolation next to text, a call, a path the schema does not
|
|
21
|
+
* know, a link, a component instead of an element — is reported instead, with
|
|
22
|
+
* the reason. A wrong `data-payload-field` is worse than a missing one: it
|
|
23
|
+
* makes the runtime write a value into markup that was never meant for it.
|
|
18
24
|
*
|
|
19
25
|
* Markup rather than an AST on purpose. Astro and Svelte templates are not
|
|
20
26
|
* TypeScript, so ts-morph would only cover the JSX third of the problem, and
|
|
@@ -42,6 +48,11 @@ interface AnnotationRefusal {
|
|
|
42
48
|
/** The source of the interpolation, trimmed, for the report. */
|
|
43
49
|
readonly expression: string;
|
|
44
50
|
}
|
|
51
|
+
/** Everything before the second `---`, and where the template starts. @internal */
|
|
52
|
+
declare function splitFrontmatter(code: string): {
|
|
53
|
+
readonly frontmatter: string;
|
|
54
|
+
readonly bodyOffset: number;
|
|
55
|
+
};
|
|
45
56
|
|
|
46
57
|
/**
|
|
47
58
|
* `pll-codegen annotate`: put `data-payload-field` where a template already
|
|
@@ -79,14 +90,15 @@ interface AnnotatableSchema {
|
|
|
79
90
|
|
|
80
91
|
/**
|
|
81
92
|
* `livePreviewAnnotate()` — the annotator as a build step, so a template needs
|
|
82
|
-
*
|
|
93
|
+
* one binding written by hand per document it prints rather than one per field.
|
|
83
94
|
*
|
|
84
95
|
* It rewrites the same shape `pll-codegen annotate` rewrites, decided by the
|
|
85
96
|
* same scanner (`./scan`), into a call rather than a fixed attribute:
|
|
86
97
|
*
|
|
87
98
|
* ```astro
|
|
88
|
-
* <h1>{page.title}</h1>
|
|
89
|
-
*
|
|
99
|
+
* <h1 {...preview.bind('title')}>{page.title}</h1> bound by hand
|
|
100
|
+
* <p>{page.subtitle}</p>
|
|
101
|
+
* → <p {...__lpPreview.bind('subtitle')}>{page.subtitle}</p>
|
|
90
102
|
* ```
|
|
91
103
|
*
|
|
92
104
|
* The difference is who may see it. A fixed attribute is in the HTML of every
|
|
@@ -147,11 +159,6 @@ interface AnnotateVitePlugin {
|
|
|
147
159
|
map: null;
|
|
148
160
|
} | null;
|
|
149
161
|
}
|
|
150
|
-
/** Everything before the second `---`, and where the template starts. @internal */
|
|
151
|
-
declare function splitFrontmatter(code: string): {
|
|
152
|
-
readonly frontmatter: string;
|
|
153
|
-
readonly bodyOffset: number;
|
|
154
|
-
};
|
|
155
162
|
/**
|
|
156
163
|
* The transform on its own, so a test can call it without a bundler and a
|
|
157
164
|
* caller can see exactly what a file becomes.
|
package/dist/annotate.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readFileSync as e}from"fs";import"fs/promises";import"path";var t=/<([a-z][a-z0-9-]*)((?:"[^"]*"|'[^']*'|[^>"'])*)>([^<]*)<\/\1\s*>/gu,n=/^\s*\{([^{}]*)\}\s*$/u,
|
|
1
|
+
import{readFileSync as e}from"fs";import"fs/promises";import"path";var t=/<([a-z][a-z0-9-]*)((?:"[^"]*"|'[^']*'|\{(?:[^{}]|\{[^{}]*\})*\}|[^>"'{])*)>([^<]*)<\/\1\s*>/gu,n=/<script\b[^>]*>[\s\S]*?<\/script\b[^>]*>|<style\b[^>]*>[\s\S]*?<\/style\b[^>]*>|<!--[\s\S]*?-->/giu,s=/^\s*\{([^{}]*)\}\s*$/u,i=/\{([^{}]*)\}/u,o=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/u,r="data-payload-field",a=/\bdata-payload-field\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*(["'`])([^"'`]*)\3\s*\})/u,l=/\{\s*\.\.\.\s*(?:[\w$]+\s*\.\s*)*(?:bind|bindByPath)\s*(?:<[^>]*>)?\s*\(\s*(?:(["'`])([^"'`]*)\1)?/u,c=/\{\s*\.\.\./u,u=[/\.(?:map|flatMap|forEach)\(\s*(?:async\s+)?\(?\s*([A-Za-z_$][\w$]*)/gu,/\bfor\s*\(\s*(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s+of\b/gu,/\{#each\s[^}]*?\sas\s+([A-Za-z_$][\w$]*)/gu];function f(e){if(!e.startsWith("---"))return{frontmatter:"",bodyOffset:0};const t=e.indexOf("\n---",3);if(-1===t)return{frontmatter:"",bodyOffset:0};const n=t+1+3;return{frontmatter:e.slice(3,t),bodyOffset:n}}function d(e){return e.replace(/[^\n]/gu," ")}function h(e){const{bodyOffset:t}=f(e),s=e.slice(t).replace(n,d);return`${d(e.slice(0,t))}${s}`}function p(e,t){let n=1;for(let s=0;s<t;s+=1)10===e.charCodeAt(s)&&(n+=1);return n}function m(e){return e.slice(e.indexOf(".")+1)}function $(e){return e.slice(0,e.indexOf("."))}function b(e){const t=e.replace(/\s+/gu," ").trim();return t.length>60?`${t.slice(0,57)}…`:t}function v(e){if(e.includes(r)){const t=a.exec(e);return{path:t?.[1]??t?.[2]??t?.[4]}}const t=l.exec(e);return null===t?null:{path:t[2]}}function g(e,t){const n=e.trim();if(0===n.length)return"the element is empty";if(!o.test(n))return"not a plain field access — a call, an operator or an index cannot be traced to one field";const s=m(n),i=$(n);if(t.items.has(i))return`\`${i}\` is a loop item — a binding names a field of the document, and \`${s}\` there is a different value, or none`;if(!t.known.has(s))return`the schema has no field \`${s}\`; the binding would name something that never arrives`;const r=t.anchors.get(i);if(void 0===r)return`this file binds no field of \`${i}\` by hand, so nothing says it holds the previewed document rather than another one — bind one of its fields and the rest can follow`;const a=[...r,s];return t.entities.some(e=>a.every(t=>e.has(t)))?void 0:`no single collection or global has \`${s}\` and what this file binds on \`${i}\` (${[...r].map(e=>`\`${e}\``).join(", ")}) — one variable holds one document`}function w(e,t){return"title"===e?"`<title>` belongs to the document head, which only a route refresh updates, and usually carries more than the field":"a"===e?'an `<a>` binding writes the value into `href` as well as the text — bind the label on an element inside the link, or set data-payload-type="text" by hand':c.test(t)?"the element spreads attributes the scan cannot read, and one of them may already bind it":void 0}function y(e,t){const n=/* @__PURE__ */new Map;for(const[,,i="",r=""]of e){const e=v(i)?.path,a=s.exec(r)?.[1]?.trim();if(void 0===e||void 0===a||!o.test(a))continue;const l=$(a);if(m(a)!==e||t.has(l))continue;const c=n.get(l)??/* @__PURE__ */new Set;c.add(e),n.set(l,c)}return n}function x(e){return`${r}="${e.path}"`}var A="__lpPreview",_="__lpPreviewBindingsFromLocals",O=`import { previewBindingsFromLocals as ${_} } from 'payload-live-preview/server';`,z=`const ${A} = ${_}(Astro.locals);`,S="---";function Z(e,t){const n=`${O}\n${z}\n`;return 0===t?`${S}\n${n}${S}\n${e}`:`${S}\n${n}${e.slice(3,t)}${e.slice(t)}`}var k=e=>!e.startsWith("\0")&&!e.includes("?")&&e.endsWith(".astro");function B(e,n){const{candidates:o,refusals:r}=function(e,n){const o=[],r=[],a=function(e){const t=/* @__PURE__ */new Set;for(const n of u)for(const s of e.matchAll(n))void 0!==s[1]&&t.add(s[1]);return t}(e),l=[...h(e).matchAll(t)],c={known:new Set(n.entities.flatMap(e=>[...e])),entities:n.entities,items:a,anchors:y(l,a)};for(const t of l){const[,n="",a="",l=""]=t,u=p(e,t.index);if(null!==v(a))continue;if(null===i.exec(l))continue;const f=w(n,a);if(void 0!==f){r.push({line:u,reason:f,expression:b(l)});continue}const d=s.exec(l);if(null===d){r.push({line:u,reason:"the value is printed beside other content — a binding replaces the whole text, so the markup has to be split first",expression:b(l)});continue}const h=d[1]??"",$=g(h,c);void 0===$?o.push({insertAt:t.index+1+n.length,path:m(h.trim()),line:u,tag:n}):r.push({line:u,reason:$,expression:b(h)})}return{candidates:o,refusals:r}}(e,{entities:(a=n.inventory,[...a.globals,...a.collections].map(e=>new Set(e.fields.map(e=>e.path).filter(e=>!e.includes("*")))))});var a;if(0===o.length)return{code:e,refusals:r};const{bodyOffset:l}=f(e),c=!0!==n.allowPublicBindings,d=function(e,t,n=x){let s=e;for(const e of[...t].sort((e,t)=>t.insertAt-e.insertAt))s=`${s.slice(0,e.insertAt)} ${n(e)}${s.slice(e.insertAt)}`;return s}(e,o,e=>c?`{...${A}.bind('${e.path}')}`:x(e));return{code:c?Z(d,l):d,refusals:r}}function P(t){const n=t.include??k,s=t.readFile??(t=>e(t,"utf8"));return{name:"payload-live-preview:annotate",enforce:"pre",load(e){if(!n(e))return null;const i=s(e),{code:o,refusals:r}=B(i,t);return r.length>0&&t.onRefusals?.(e,r),{code:o,map:null}}}}export{B as annotateSource,P as livePreviewAnnotate,f as splitFrontmatter};
|
|
2
2
|
//# sourceMappingURL=annotate.js.map
|
package/dist/annotate.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"annotate.js","names":["ELEMENT","ONLY_INTERPOLATION","ANY_INTERPOLATION","MEMBER_CHAIN","FIELD_ATTRIBUTE","LOOP_VARIABLES","lineAt","source","index","line","position","charCodeAt","pathOf","chain","slice","indexOf","describe","expression","flat","replace","trim","length","refusalReason","paths","items","trimmed","test","path","root","has","fieldAttribute","candidate","HELPER","IMPORT_ALIAS","IMPORT_LINE","HELPER_LINE","FENCE","splitFrontmatter","code","startsWith","frontmatter","bodyOffset","end","withHelper","lines","isAstro","id","includes","endsWith","annotateSource","options","inventory","Set","entry","globals","collections","field","fields","add","annotatablePaths","body","candidates","refusals","names","pattern","match","matchAll","loopVariables","tag","attributes","content","only","exec","push","reason","insertAt","scanTemplate","shifted","map","gated","allowPublicBindings","rewritten","render","out","sort","a","b","applyAnnotations","livePreviewAnnotate","include","read","readFile","readFileSync","name","enforce","load","onRefusals"],"sources":["../src/codegen/annotate/scan.ts","../src/codegen/annotate/vite-plugin.ts","../src/codegen/annotate/index.ts"],"sourcesContent":["/**\n * Find the places in a template where a field value is printed on its own, and\n * decide — never guess — which of them can carry a binding.\n *\n * The shape this recognises is deliberately narrow, and it is the same in every\n * template language the package adapts:\n *\n * ```\n * <h1>{page.title}</h1> Astro, JSX, Svelte\n * ```\n *\n * An element whose entire content is one member expression, rooted at some\n * variable, whose remaining path is a field the schema actually has. Everything\n * else — an interpolation next to text, a call, a ternary, a path the schema\n * does not know, a component instead of an element — is reported instead, with\n * the reason. A wrong `data-payload-field` is worse than a missing one: it makes\n * the runtime write a value into markup that was never meant for it.\n *\n * Markup rather than an AST on purpose. Astro and Svelte templates are not\n * TypeScript, so ts-morph would only cover the JSX third of the problem, and\n * three parsers would be three chances to disagree about which shape is safe.\n * The shape above is unambiguous enough to scan for.\n */\n\n/** A place that can carry a binding, with the attribute it should get. @internal */\nexport interface AnnotationCandidate {\n /** Offset where the attribute is inserted, inside the opening tag. */\n readonly insertAt: number;\n /** The binding path, as `data-payload-field` must spell it. */\n readonly path: string;\n /** 1-based line, for the report. */\n readonly line: number;\n readonly tag: string;\n}\n\n/**\n * A place that looks like an output but was left alone, and why.\n *\n * @beta\n */\nexport interface AnnotationRefusal {\n readonly line: number;\n readonly reason: string;\n /** The source of the interpolation, trimmed, for the report. */\n readonly expression: string;\n}\n\nexport interface ScanResult {\n readonly candidates: readonly AnnotationCandidate[];\n readonly refusals: readonly AnnotationRefusal[];\n}\n\nexport interface ScanOptions {\n /** Field paths the schema has, exactly as a binding must spell them. */\n readonly paths: ReadonlySet<string>;\n}\n\n/**\n * `<tag attrs>content</tag>` with no element inside it, the closing tag\n * repeating the name. Only lowercase tags: an uppercase one is a component,\n * whose children are its own business.\n */\nconst ELEMENT = /<([a-z][a-z0-9-]*)((?:\"[^\"]*\"|'[^']*'|[^>\"'])*)>([^<]*)<\\/\\1\\s*>/gu;\n\n/** The whole content is one interpolation, and nothing else. */\nconst ONLY_INTERPOLATION = /^\\s*\\{([^{}]*)\\}\\s*$/u;\n\n/** An interpolation somewhere in the content, which is a different case. */\nconst ANY_INTERPOLATION = /\\{([^{}]*)\\}/u;\n\n/** A plain member chain: `page.title`, `data.hero.eyebrow`. Nothing callable, nothing indexed. */\nconst MEMBER_CHAIN = /^[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)+$/u;\n\nconst FIELD_ATTRIBUTE = 'data-payload-field';\n\n/**\n * Where a template names one array item at a time: a `.map`, `.flatMap` or\n * `.forEach` callback's first parameter, a `for … of` variable, a Svelte\n * `{#each … as item}`. A chain rooted at such a name prints an item, and the\n * item's `title` is not the document's `title`, however alike the paths look.\n * A name bound this way anywhere in the file is treated as an item everywhere:\n * refusing one real field access costs a line in the report, binding an item\n * costs the preview.\n */\nconst LOOP_VARIABLES: readonly RegExp[] = [\n /\\.(?:map|flatMap|forEach)\\(\\s*(?:async\\s+)?\\(?\\s*([A-Za-z_$][\\w$]*)/gu,\n /\\bfor\\s*\\(\\s*(?:const|let|var)\\s+([A-Za-z_$][\\w$]*)\\s+of\\b/gu,\n /\\{#each\\s[^}]*?\\sas\\s+([A-Za-z_$][\\w$]*)/gu,\n];\n\nfunction loopVariables(source: string): ReadonlySet<string> {\n const names = new Set<string>();\n for (const pattern of LOOP_VARIABLES) {\n for (const match of source.matchAll(pattern)) {\n if (match[1] !== undefined) names.add(match[1]);\n }\n }\n return names;\n}\n\nfunction lineAt(source: string, index: number): number {\n let line = 1;\n for (let position = 0; position < index; position += 1) {\n if (source.charCodeAt(position) === 10) line += 1;\n }\n return line;\n}\n\n/**\n * The binding path a chain would address: everything after the root variable.\n * `page.hero.title` → `hero.title`, and a lone `title` is not a chain at all —\n * a bare identifier says nothing about which document it came from.\n */\nfunction pathOf(chain: string): string {\n return chain.slice(chain.indexOf('.') + 1);\n}\n\nfunction describe(expression: string): string {\n const flat = expression.replace(/\\s+/gu, ' ').trim();\n return flat.length > 60 ? `${flat.slice(0, 57)}…` : flat;\n}\n\n/** Why this interpolation cannot become a binding, in the words of the report. */\nfunction refusalReason(\n expression: string,\n paths: ReadonlySet<string>,\n items: ReadonlySet<string>,\n): string | undefined {\n const trimmed = expression.trim();\n if (trimmed.length === 0) return 'the element is empty';\n if (!MEMBER_CHAIN.test(trimmed)) {\n return 'not a plain field access — a call, an operator or an index cannot be traced to one field';\n }\n const path = pathOf(trimmed);\n const root = trimmed.slice(0, trimmed.indexOf('.'));\n if (items.has(root)) {\n return `\\`${root}\\` is a loop item — a binding names a field of the document, and \\`${path}\\` there is a different value, or none`;\n }\n if (!paths.has(path)) {\n return `the schema has no field \\`${path}\\`; the binding would name something that never arrives`;\n }\n return undefined;\n}\n\nexport function scanTemplate(source: string, options: ScanOptions): ScanResult {\n const candidates: AnnotationCandidate[] = [];\n const refusals: AnnotationRefusal[] = [];\n const items = loopVariables(source);\n for (const match of source.matchAll(ELEMENT)) {\n const [, tag = '', attributes = '', content = ''] = match;\n const line = lineAt(source, match.index);\n if (attributes.includes(FIELD_ATTRIBUTE)) continue;\n const only = ONLY_INTERPOLATION.exec(content);\n if (only === null) {\n // A value printed beside a label — `Published {page.publishedAt}`. The\n // runtime writes an element's whole text, so a binding here would eat the\n // label; splitting the markup is a decision for whoever wrote it.\n const beside = ANY_INTERPOLATION.exec(content);\n if (beside !== null) {\n refusals.push({\n line,\n reason:\n 'the value is printed beside other content — a binding replaces the whole text, so the markup has to be split first',\n expression: describe(content),\n });\n }\n continue;\n }\n const expression = only[1] ?? '';\n const reason = refusalReason(expression, options.paths, items);\n if (reason !== undefined) {\n refusals.push({ line, reason, expression: describe(expression) });\n continue;\n }\n candidates.push({\n // After `<tag`, before whatever the element already carries.\n insertAt: match.index + 1 + tag.length,\n path: pathOf(expression.trim()),\n line,\n tag,\n });\n }\n return { candidates, refusals };\n}\n\n/** The attribute a candidate becomes: what `pll-codegen annotate` writes into a file. */\nexport function fieldAttribute(candidate: AnnotationCandidate): string {\n return `${FIELD_ATTRIBUTE}=\"${candidate.path}\"`;\n}\n\n/**\n * Apply the candidates back-to-front, so every earlier offset still holds.\n *\n * `render` decides what a candidate becomes, because the two callers write\n * different things from the same decision: the codemod writes the attribute\n * into the file a person reads, and the build-time annotator writes a call to\n * the authorization-bound helper. What may be annotated at all is decided in\n * one place — above — and never here.\n */\nexport function applyAnnotations(\n source: string,\n candidates: readonly AnnotationCandidate[],\n render: (candidate: AnnotationCandidate) => string = fieldAttribute,\n): string {\n let out = source;\n for (const candidate of [...candidates].sort((a, b) => b.insertAt - a.insertAt)) {\n out = `${out.slice(0, candidate.insertAt)} ${render(candidate)}${out.slice(candidate.insertAt)}`;\n }\n return out;\n}\n","/**\n * `livePreviewAnnotate()` — the annotator as a build step, so a template needs\n * no binding attributes written into it by hand.\n *\n * It rewrites the same shape `pll-codegen annotate` rewrites, decided by the\n * same scanner (`./scan`), into a call rather than a fixed attribute:\n *\n * ```astro\n * <h1>{page.title}</h1>\n * → <h1 {...__lpPreview.bind('title')}>{page.title}</h1>\n * ```\n *\n * The difference is who may see it. A fixed attribute is in the HTML of every\n * visitor and describes the content model to all of them; the call resolves per\n * request against the authorization the adapter published, so an unauthorized\n * response carries no `data-payload-*` at all (ADR 0006). A static build has no\n * request to resolve against and therefore emits nothing — `allowPublicBindings`\n * is how you say you want the attribute anyway, out loud.\n *\n * Astro only, for a reason rather than a lack of time: the rewrite needs a\n * template whose own scope can reach the request context, which frontmatter and\n * `Astro.locals` give and a Svelte or Vue component does not — there the value\n * would have to travel through `load` or a payload, where a function cannot go.\n *\n * Vite compatibility is a recorded fact, not a guess: `name`, `enforce` and\n * `load(id)` are the whole surface used here, and all three have been stable\n * since Vite 5. The majors that matter are in `quality/compat-matrix.json`,\n * which is what the tests read.\n *\n * `load` rather than `transform`, which is where a source rewrite would\n * normally go. Astro compiles `.astro` in a `transform` of its own, registered\n * `enforce: 'pre'` and ahead of anything a config contributes, so by the time\n * any user transform runs the markup is gone — measured, not assumed: a probe\n * plugin at `pre` received compiled output importing from Astro's own compiler\n * runtime, not the template. Every `load` runs before every `transform`, so\n * that is where the file is still a template. Reading it is what Rollup's\n * default loader would have done anyway.\n */\n\nimport { readFileSync } from 'node:fs';\nimport { annotatablePaths, type AnnotatableSchema } from './index';\nimport { applyAnnotations, fieldAttribute, scanTemplate, type AnnotationRefusal } from './scan';\n\n/** The helper the rewritten markup calls, and the import that defines it. */\nconst HELPER = '__lpPreview';\nconst IMPORT_ALIAS = '__lpPreviewBindingsFromLocals';\nconst IMPORT_LINE = `import { previewBindingsFromLocals as ${IMPORT_ALIAS} } from 'payload-live-preview/server';`;\nconst HELPER_LINE = `const ${HELPER} = ${IMPORT_ALIAS}(Astro.locals);`;\nconst FENCE = '---';\n\n/** @beta */\nexport interface AnnotatePluginOptions {\n /** The schema, from `generateTypes().inventory` or the `--inventory` file. */\n readonly inventory: AnnotatableSchema;\n /**\n * Write the plain `data-payload-field` attribute instead of the gated call.\n * A statically built site has no request to authorize, so this is the only\n * way it can carry bindings — and it publishes the field names to everyone.\n * Default `false`.\n */\n readonly allowPublicBindings?: boolean;\n /** Which modules to transform. Default: every `.astro` file. */\n readonly include?: (id: string) => boolean;\n /** Called once per file with what the scanner would not annotate. */\n readonly onRefusals?: (file: string, refusals: readonly AnnotationRefusal[]) => void;\n /** Reads a template. Defaults to the file system; injected by tests. */\n readonly readFile?: (path: string) => string;\n}\n\n/**\n * The slice of Vite's plugin shape this uses; three hooks, stable since Vite 5.\n *\n * @beta\n */\nexport interface AnnotateVitePlugin {\n readonly name: string;\n readonly enforce: 'pre';\n load(id: string): { code: string; map: null } | null;\n}\n\n/** Everything before the second `---`, and where the template starts. @internal */\nexport function splitFrontmatter(code: string): {\n readonly frontmatter: string;\n readonly bodyOffset: number;\n} {\n if (!code.startsWith(FENCE)) return { frontmatter: '', bodyOffset: 0 };\n const end = code.indexOf(`\\n${FENCE}`, FENCE.length);\n if (end === -1) return { frontmatter: '', bodyOffset: 0 };\n const bodyOffset = end + 1 + FENCE.length;\n return { frontmatter: code.slice(FENCE.length, end), bodyOffset };\n}\n\n/** The frontmatter with the helper in it, whether or not the file had one. */\nfunction withHelper(code: string, bodyOffset: number): string {\n const lines = `${IMPORT_LINE}\\n${HELPER_LINE}\\n`;\n if (bodyOffset === 0) return `${FENCE}\\n${lines}${FENCE}\\n${code}`;\n return `${FENCE}\\n${lines}${code.slice(FENCE.length, bodyOffset)}${code.slice(bodyOffset)}`;\n}\n\n/**\n * A plain `.astro` path. Not a sub-request (`?astro&type=style`), not a virtual\n * module (`\\0…`): those are Astro's own, and loading them is not this plugin's\n * business.\n */\nconst isAstro = (id: string): boolean =>\n !id.startsWith('\\0') && !id.includes('?') && id.endsWith('.astro');\n\n/**\n * The transform on its own, so a test can call it without a bundler and a\n * caller can see exactly what a file becomes.\n * @internal\n */\nexport function annotateSource(\n code: string,\n options: AnnotatePluginOptions,\n): { readonly code: string; readonly refusals: readonly AnnotationRefusal[] } {\n const paths = annotatablePaths(options.inventory);\n const { bodyOffset } = splitFrontmatter(code);\n // Frontmatter is TypeScript, not markup: scanning it would match a template\n // written inside a string, and annotate something no browser ever sees.\n const body = code.slice(bodyOffset);\n const { candidates, refusals } = scanTemplate(body, { paths });\n if (candidates.length === 0) return { code, refusals };\n\n const shifted = candidates.map((candidate) => ({\n ...candidate,\n insertAt: candidate.insertAt + bodyOffset,\n }));\n const gated = options.allowPublicBindings !== true;\n const rewritten = applyAnnotations(code, shifted, (candidate) =>\n gated ? `{...${HELPER}.bind('${candidate.path}')}` : fieldAttribute(candidate),\n );\n return {\n code: gated ? withHelper(rewritten, bodyOffset) : rewritten,\n refusals,\n };\n}\n\n/**\n * ```js\n * // astro.config.mjs\n * vite: { plugins: [livePreviewAnnotate({ inventory })] }\n * ```\n *\n * @beta\n */\nexport function livePreviewAnnotate(options: AnnotatePluginOptions): AnnotateVitePlugin {\n const include = options.include ?? isAstro;\n const read = options.readFile ?? ((path: string) => readFileSync(path, 'utf8'));\n return {\n name: 'payload-live-preview:annotate',\n enforce: 'pre',\n load(id) {\n if (!include(id)) return null;\n const source = read(id);\n const { code, refusals } = annotateSource(source, options);\n if (refusals.length > 0) options.onRefusals?.(id, refusals);\n // The unannotated source is still returned: this loader replaces the\n // default one, so declining would leave the module empty.\n return { code, map: null };\n },\n };\n}\n","/**\n * `pll-codegen annotate`: put `data-payload-field` where a template already\n * prints a field, and report every place it would have had to guess.\n *\n * The schema decides what exists — the same inventory `--inventory` writes, so\n * an annotation and a runtime binding spell a path the same way. What the tool\n * cannot attribute is listed, never invented: an unbound field costs an editor\n * one invisible edit, a wrongly bound one writes a value into the wrong element\n * on every keystroke.\n */\n\nimport { readFile, writeFile } from 'node:fs/promises';\nimport { relative } from 'node:path';\nimport type { PreviewInventory } from '../inventory';\nimport {\n applyAnnotations,\n scanTemplate,\n type AnnotationCandidate,\n type AnnotationRefusal,\n} from './scan';\n\nexport type { AnnotationCandidate, AnnotationRefusal } from './scan';\n\n/** Templates this scanner understands; a `.vue` template uses `{{ … }}` and is not one yet. @internal */\nexport const ANNOTATABLE_EXTENSIONS: readonly string[] = ['.astro', '.jsx', '.tsx', '.svelte'];\n\n/** @internal */\nexport interface AnnotateFileResult {\n readonly file: string;\n /** The annotated source; identical to the input when nothing was added. */\n readonly code: string;\n readonly annotations: readonly AnnotationCandidate[];\n readonly refusals: readonly AnnotationRefusal[];\n readonly changed: boolean;\n}\n\n/** @internal */\nexport interface AnnotateResult {\n readonly files: readonly AnnotateFileResult[];\n readonly annotationCount: number;\n readonly refusalCount: number;\n /** Whether the files were written; `false` is a dry run. */\n readonly written: boolean;\n}\n\n/** @internal */\nexport interface AnnotateOptions {\n /** Template files to read. */\n readonly files: readonly string[];\n /** The schema's addressable paths, from `generateTypes().inventory`. */\n readonly inventory: PreviewInventory;\n /** Write the annotated sources back. Without it nothing is touched. */\n readonly write?: boolean;\n /** Resolves the paths in the report. Defaults to `process.cwd()`. */\n readonly cwd?: string;\n /** Reader/writer injection for tests. */\n readonly io?: {\n readonly read: (path: string) => Promise<string>;\n readonly write: (path: string, content: string) => Promise<void>;\n };\n}\n\n/**\n * The part of an inventory the annotator reads: the paths, and nothing else.\n *\n * `PreviewInventory` from `generateTypes()` satisfies it, and so does an object\n * a project writes by hand. Naming the minimum keeps the build plugin's public\n * surface free of the extracted-field union behind the full inventory — a dozen\n * types a consumer of a Vite plugin has no reason to meet.\n *\n * @beta\n */\nexport interface AnnotatableSchema {\n readonly globals: readonly { readonly fields: readonly { readonly path: string }[] }[];\n readonly collections: readonly { readonly fields: readonly { readonly path: string }[] }[];\n}\n\n/**\n * Every path the schema can address, in one set.\n *\n * An array's items are spelled `slides.*.caption` in the inventory because that\n * is how the runtime resolves them; a template writes `slide.caption` inside a\n * loop, where nothing connects `slide` to `slides`. Those paths are therefore\n * kept out: the scanner would otherwise match a name that only looks right.\n * @internal\n */\nexport function annotatablePaths(inventory: AnnotatableSchema): ReadonlySet<string> {\n const paths = new Set<string>();\n for (const entry of [...inventory.globals, ...inventory.collections]) {\n for (const field of entry.fields) {\n if (!field.path.includes('*')) paths.add(field.path);\n }\n }\n return paths;\n}\n\n/** @internal */\nexport async function annotateTemplates(options: AnnotateOptions): Promise<AnnotateResult> {\n const read = options.io?.read ?? ((path: string) => readFile(path, 'utf8'));\n const write =\n options.io?.write ?? ((path: string, content: string) => writeFile(path, content, 'utf8'));\n const root = options.cwd ?? process.cwd();\n const paths = annotatablePaths(options.inventory);\n const files: AnnotateFileResult[] = [];\n\n for (const file of options.files) {\n const source = await read(file);\n const { candidates, refusals } = scanTemplate(source, { paths });\n const code = candidates.length === 0 ? source : applyAnnotations(source, candidates);\n const changed = code !== source;\n if (changed && options.write === true) await write(file, code);\n files.push({\n file: relative(root, file) || file,\n code,\n annotations: candidates,\n refusals,\n changed,\n });\n }\n\n return {\n files,\n annotationCount: files.reduce((total, file) => total + file.annotations.length, 0),\n refusalCount: files.reduce((total, file) => total + file.refusals.length, 0),\n written: options.write === true,\n };\n}\n\n/** The report, one line per annotation and per refusal, in file order. @internal */\nexport function formatAnnotateReport(result: AnnotateResult): string {\n const lines: string[] = [];\n for (const file of result.files) {\n if (file.annotations.length === 0 && file.refusals.length === 0) continue;\n lines.push(file.file);\n for (const annotation of file.annotations) {\n lines.push(` ${String(annotation.line)}: <${annotation.tag}> → ${annotation.path}`);\n }\n for (const refusal of file.refusals) {\n lines.push(\n ` ${String(refusal.line)}: left alone — ${refusal.reason} (${refusal.expression})`,\n );\n }\n }\n const verb = result.written ? 'annotated' : 'would annotate';\n lines.push(\n `${verb} ${String(result.annotationCount)} element(s); ` +\n `${String(result.refusalCount)} left for a human`,\n );\n return `${lines.join('\\n')}\\n`;\n}\n"],"mappings":"mEA8DA,IAAMA,EAAU,qEAGVC,EAAqB,wBAGrBC,EAAoB,gBAGpBC,EAAe,6CAEfC,EAAkB,qBAWlBC,EAAoC,CACxC,wEACA,+DACA,8CAaF,SAASC,EAAOC,EAAgBC,GAC9B,IAAIC,EAAO,EACX,QAASC,EAAW,EAAGA,EAAWF,EAAOE,GAAY,EACf,KAAhCH,EAAOI,WAAWD,KAAkBD,GAAQ,GAElD,OAAOA,CACT,CAOA,SAASG,EAAOC,GACd,OAAOA,EAAMC,MAAMD,EAAME,QAAQ,KAAO,EAC1C,CAEA,SAASC,EAASC,GAChB,MAAMC,EAAOD,EAAWE,QAAQ,QAAS,KAAKC,OAC9C,OAAOF,EAAKG,OAAS,GAAK,GAAGH,EAAKJ,MAAM,EAAG,OAASI,CACtD,CAGA,SAASI,EACPL,EACAM,EACAC,GAEA,MAAMC,EAAUR,EAAWG,OAC3B,GAAuB,IAAnBK,EAAQJ,OAAc,MAAO,uBACjC,IAAKlB,EAAauB,KAAKD,GACrB,MAAO,2FAET,MAAME,EAAOf,EAAOa,GACdG,EAAOH,EAAQX,MAAM,EAAGW,EAAQ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K,CAACC,EAAGC,IAAMA,EAAEX,SAAWU,EAAEV,UACpEQ,EAAM,GAAGA,EAAIrE,MAAM,EAAGiB,EAAU4C,aAAaO,EAAOnD,KAAaoD,EAAIrE,MAAMiB,EAAU4C,YAEvF,OAAOQ,CACT,CChFoBI,CAAiBjD,EAAMuC,EAAU9C,GACjDgD,EAAQ,OAAO/C,WAAgBD,EAAUJ,UAAYG,EAAeC,IAEtE,MAAO,CACLO,KAAMyC,EAAQpC,EAAWsC,EAAWxC,GAAcwC,EAClDnB,WAEJ,CAUO,SAAS0B,EAAoBtC,GAClC,MAAMuC,EAAUvC,EAAQuC,SAAW5C,EAC7B6C,EAAOxC,EAAQyC,UAAA,CAAchE,GAAiBiE,EAAajE,EAAM,SACvE,MAAO,CACLkE,KAAM,gCACNC,QAAS,MACT,IAAAC,CAAKjD,GACH,IAAK2C,EAAQ3C,GAAK,OAAO,KACzB,MAAMvC,EAASmF,EAAK5C,IACdR,KAAEA,EAAAwB,SAAMA,GAAab,EAAe1C,EAAQ2C,GAIlD,OAHIY,EAASzC,OAAS,GAAG6B,EAAQ8C,aAAalD,EAAIgB,GAG3C,CAAExB,OAAMwC,IAAK,KACtB,EAEJ,Q","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"annotate.js","names":["ELEMENT","NOT_TEMPLATE","ONLY_INTERPOLATION","ANY_INTERPOLATION","MEMBER_CHAIN","FIELD_ATTRIBUTE","FIELD_LITERAL","BINDING_SPREAD","ANY_SPREAD","LOOP_VARIABLES","splitFrontmatter","code","startsWith","frontmatter","bodyOffset","end","indexOf","FENCE","slice","blank","text","replace","templateOnly","source","body","lineAt","index","line","position","charCodeAt","pathOf","chain","rootOf","describe","expression","flat","trim","length","bindingOf","attributes","includes","literal","exec","path","spread","refusalReason","file","trimmed","test","root","items","has","known","anchored","anchors","get","together","entities","some","entity","every","each","map","join","elementRefusal","tag","anchorsOf","elements","Map","content","paths","Set","add","set","fieldAttribute","candidate","HELPER","IMPORT_ALIAS","IMPORT_LINE","HELPER_LINE","withHelper","lines","isAstro","id","endsWith","annotateSource","options","candidates","refusals","names","pattern","match","matchAll","loopVariables","flatMap","refusedElement","push","reason","only","insertAt","scanTemplate","inventory","globals","collections","entry","fields","field","filter","gated","allowPublicBindings","rewritten","render","out","sort","a","b","applyAnnotations","livePreviewAnnotate","include","read","readFile","readFileSync","name","enforce","load","onRefusals"],"sources":["../src/codegen/annotate/scan.ts","../src/codegen/annotate/vite-plugin.ts","../src/codegen/annotate/index.ts"],"sourcesContent":["/**\n * Find the places in a template where a field value is printed on its own, and\n * decide — never guess — which of them can carry a binding.\n *\n * The shape this recognises is deliberately narrow, and it is the same in every\n * template language the package adapts:\n *\n * ```\n * <h1 data-payload-field=\"title\">{page.title}</h1> bound by hand\n * <p>{page.subtitle}</p> → subtitle\n * ```\n *\n * An element whose entire content is one member expression, rooted at a\n * variable the file already binds a field of by hand, whose remaining path a\n * collection or global has together with those hand-bound fields. The hand\n * binding is the only thing in a template that says which variable holds the\n * previewed document: `post` in a card, `settings` in a footer and `page` in a\n * route look alike, and on four sites 16 of the 17 bindings proposed without\n * it were wrong, most of them a field of some other document. Everything\n * else — an interpolation next to text, a call, a path the schema does not\n * know, a link, a component instead of an element — is reported instead, with\n * the reason. A wrong `data-payload-field` is worse than a missing one: it\n * makes the runtime write a value into markup that was never meant for it.\n *\n * Markup rather than an AST on purpose. Astro and Svelte templates are not\n * TypeScript, so ts-morph would only cover the JSX third of the problem, and\n * three parsers would be three chances to disagree about which shape is safe.\n * The shape above is unambiguous enough to scan for.\n */\n\n/** A place that can carry a binding, with the attribute it should get. @internal */\nexport interface AnnotationCandidate {\n /** Offset where the attribute is inserted, inside the opening tag. */\n readonly insertAt: number;\n /** The binding path, as `data-payload-field` must spell it. */\n readonly path: string;\n /** 1-based line, for the report. */\n readonly line: number;\n readonly tag: string;\n}\n\n/**\n * A place that looks like an output but was left alone, and why.\n *\n * @beta\n */\nexport interface AnnotationRefusal {\n readonly line: number;\n readonly reason: string;\n /** The source of the interpolation, trimmed, for the report. */\n readonly expression: string;\n}\n\nexport interface ScanResult {\n readonly candidates: readonly AnnotationCandidate[];\n readonly refusals: readonly AnnotationRefusal[];\n}\n\nexport interface ScanOptions {\n /**\n * The paths of each collection and global, one set per entity, exactly as a\n * binding must spell them. Kept apart because one variable holds one\n * document: a path is only bindable on a variable whose hand-bound fields\n * the same entity has.\n */\n readonly entities: readonly ReadonlySet<string>[];\n}\n\n/**\n * `<tag attrs>content</tag>` with no element inside it, the closing tag\n * repeating the name. Only lowercase tags: an uppercase one is a component,\n * whose children are its own business. An attribute in braces is read as one\n * unit, two levels deep, so the `>` of `bind<Page>(…)` or of an arrow function\n * does not end the tag.\n */\nconst ELEMENT =\n /<([a-z][a-z0-9-]*)((?:\"[^\"]*\"|'[^']*'|\\{(?:[^{}]|\\{[^{}]*\\})*\\}|[^>\"'{])*)>([^<]*)<\\/\\1\\s*>/gu;\n\n/**\n * Code inside a template: a script, a style sheet and a comment. Their braces\n * are JavaScript and CSS, and markup in them is a string, so the element scan\n * never reads them — the same three the doctor strips before it counts.\n */\nconst NOT_TEMPLATE =\n /<script\\b[^>]*>[\\s\\S]*?<\\/script\\b[^>]*>|<style\\b[^>]*>[\\s\\S]*?<\\/style\\b[^>]*>|<!--[\\s\\S]*?-->/giu;\n\n/** The whole content is one interpolation, and nothing else. */\nconst ONLY_INTERPOLATION = /^\\s*\\{([^{}]*)\\}\\s*$/u;\n\n/** An interpolation somewhere in the content, which is a different case. */\nconst ANY_INTERPOLATION = /\\{([^{}]*)\\}/u;\n\n/** A plain member chain: `page.title`, `data.hero.eyebrow`. Nothing callable, nothing indexed. */\nconst MEMBER_CHAIN = /^[A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)+$/u;\n\nconst FIELD_ATTRIBUTE = 'data-payload-field';\n\n/** The path a hand-written attribute names: `=\"title\"`, `='title'` or `={'title'}`. */\nconst FIELD_LITERAL =\n /\\bdata-payload-field\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|\\{\\s*([\"'`])([^\"'`]*)\\3\\s*\\})/u;\n\n/**\n * A spread of a binding helper: `{...preview.bind('title')}`,\n * `{...bind<Page>(\"title\")}`, `{...bindByPath((d) => d.title)}`. The path is\n * captured when it is a string literal.\n */\nconst BINDING_SPREAD =\n /\\{\\s*\\.\\.\\.\\s*(?:[\\w$]+\\s*\\.\\s*)*(?:bind|bindByPath)\\s*(?:<[^>]*>)?\\s*\\(\\s*(?:([\"'`])([^\"'`]*)\\1)?/u;\n\n/** Any other spread: attributes the scan cannot see, a binding among them or not. */\nconst ANY_SPREAD = /\\{\\s*\\.\\.\\./u;\n\n/**\n * Where a template names one array item at a time: a `.map`, `.flatMap` or\n * `.forEach` callback's first parameter, a `for … of` variable, a Svelte\n * `{#each … as item}`. A chain rooted at such a name prints an item, and the\n * item's `title` is not the document's `title`, however alike the paths look.\n * A name bound this way anywhere in the file is treated as an item everywhere:\n * refusing one real field access costs a line in the report, binding an item\n * costs the preview.\n */\nconst LOOP_VARIABLES: readonly RegExp[] = [\n /\\.(?:map|flatMap|forEach)\\(\\s*(?:async\\s+)?\\(?\\s*([A-Za-z_$][\\w$]*)/gu,\n /\\bfor\\s*\\(\\s*(?:const|let|var)\\s+([A-Za-z_$][\\w$]*)\\s+of\\b/gu,\n /\\{#each\\s[^}]*?\\sas\\s+([A-Za-z_$][\\w$]*)/gu,\n];\n\nconst FENCE = '---';\n\n/** Everything before the second `---`, and where the template starts. @internal */\nexport function splitFrontmatter(code: string): {\n readonly frontmatter: string;\n readonly bodyOffset: number;\n} {\n if (!code.startsWith(FENCE)) return { frontmatter: '', bodyOffset: 0 };\n const end = code.indexOf(`\\n${FENCE}`, FENCE.length);\n if (end === -1) return { frontmatter: '', bodyOffset: 0 };\n const bodyOffset = end + 1 + FENCE.length;\n return { frontmatter: code.slice(FENCE.length, end), bodyOffset };\n}\n\n/** Every character but a line break as a space, so offsets and lines stay the file's own. */\nfunction blank(text: string): string {\n return text.replace(/[^\\n]/gu, ' ');\n}\n\n/**\n * The source as the element scan reads it: Astro's frontmatter — TypeScript,\n * where a template in a string is not the document — and the code blocks\n * blanked out. A source that does not open with a fence has none, so this\n * holds for every template language.\n */\nfunction templateOnly(source: string): string {\n const { bodyOffset } = splitFrontmatter(source);\n const body = source.slice(bodyOffset).replace(NOT_TEMPLATE, blank);\n return `${blank(source.slice(0, bodyOffset))}${body}`;\n}\n\nfunction loopVariables(source: string): ReadonlySet<string> {\n const names = new Set<string>();\n for (const pattern of LOOP_VARIABLES) {\n for (const match of source.matchAll(pattern)) {\n if (match[1] !== undefined) names.add(match[1]);\n }\n }\n return names;\n}\n\nfunction lineAt(source: string, index: number): number {\n let line = 1;\n for (let position = 0; position < index; position += 1) {\n if (source.charCodeAt(position) === 10) line += 1;\n }\n return line;\n}\n\n/**\n * The binding path a chain would address: everything after the root variable.\n * `page.hero.title` → `hero.title`, and a lone `title` is not a chain at all —\n * a bare identifier says nothing about which document it came from.\n */\nfunction pathOf(chain: string): string {\n return chain.slice(chain.indexOf('.') + 1);\n}\n\nfunction rootOf(chain: string): string {\n return chain.slice(0, chain.indexOf('.'));\n}\n\nfunction describe(expression: string): string {\n const flat = expression.replace(/\\s+/gu, ' ').trim();\n return flat.length > 60 ? `${flat.slice(0, 57)}…` : flat;\n}\n\n/**\n * How an element is bound already, or `null`. `path` is the field when the\n * binding spells it as a literal, which is what lets it name its variable.\n */\nfunction bindingOf(attributes: string): { readonly path: string | undefined } | null {\n if (attributes.includes(FIELD_ATTRIBUTE)) {\n const literal = FIELD_LITERAL.exec(attributes);\n return { path: literal?.[1] ?? literal?.[2] ?? literal?.[4] };\n }\n const spread = BINDING_SPREAD.exec(attributes);\n return spread === null ? null : { path: spread[2] };\n}\n\n/** What a file says about its variables, read from the bindings written by hand. */\ninterface FileContext {\n /** Every path the schema has, whichever entity. */\n readonly known: ReadonlySet<string>;\n readonly entities: readonly ReadonlySet<string>[];\n readonly items: ReadonlySet<string>;\n /** A variable whose field is bound by hand, with the paths bound on it. */\n readonly anchors: ReadonlyMap<string, ReadonlySet<string>>;\n}\n\n/** Why this interpolation cannot become a binding, in the words of the report. */\nfunction refusalReason(expression: string, file: FileContext): string | undefined {\n const trimmed = expression.trim();\n if (trimmed.length === 0) return 'the element is empty';\n if (!MEMBER_CHAIN.test(trimmed)) {\n return 'not a plain field access — a call, an operator or an index cannot be traced to one field';\n }\n const path = pathOf(trimmed);\n const root = rootOf(trimmed);\n if (file.items.has(root)) {\n return `\\`${root}\\` is a loop item — a binding names a field of the document, and \\`${path}\\` there is a different value, or none`;\n }\n if (!file.known.has(path)) {\n return `the schema has no field \\`${path}\\`; the binding would name something that never arrives`;\n }\n const anchored = file.anchors.get(root);\n if (anchored === undefined) {\n return `this file binds no field of \\`${root}\\` by hand, so nothing says it holds the previewed document rather than another one — bind one of its fields and the rest can follow`;\n }\n const together = [...anchored, path];\n if (!file.entities.some((entity) => together.every((each) => entity.has(each)))) {\n const bound = [...anchored].map((each) => `\\`${each}\\``).join(', ');\n return `no single collection or global has \\`${path}\\` and what this file binds on \\`${root}\\` (${bound}) — one variable holds one document`;\n }\n return undefined;\n}\n\n/**\n * Why this element cannot carry a binding whatever it prints: its tag or its\n * attributes decide, before the content is read.\n */\nfunction elementRefusal(tag: string, attributes: string): string | undefined {\n if (tag === 'title') {\n return '`<title>` belongs to the document head, which only a route refresh updates, and usually carries more than the field';\n }\n if (tag === 'a') {\n return 'an `<a>` binding writes the value into `href` as well as the text — bind the label on an element inside the link, or set data-payload-type=\"text\" by hand';\n }\n if (ANY_SPREAD.test(attributes)) {\n return 'the element spreads attributes the scan cannot read, and one of them may already bind it';\n }\n return undefined;\n}\n\n/**\n * The variables a file binds by hand: an element bound to `P` whose content\n * is `{v.P}` says that `v` holds the document. A loop item never does — its\n * binding names the field of one item, which is a different statement.\n */\nfunction anchorsOf(\n elements: readonly RegExpMatchArray[],\n items: ReadonlySet<string>,\n): ReadonlyMap<string, ReadonlySet<string>> {\n const anchors = new Map<string, Set<string>>();\n for (const [, , attributes = '', content = ''] of elements) {\n const path = bindingOf(attributes)?.path;\n const chain = ONLY_INTERPOLATION.exec(content)?.[1]?.trim();\n if (path === undefined || chain === undefined || !MEMBER_CHAIN.test(chain)) continue;\n const root = rootOf(chain);\n if (pathOf(chain) !== path || items.has(root)) continue;\n const paths = anchors.get(root) ?? new Set<string>();\n paths.add(path);\n anchors.set(root, paths);\n }\n return anchors;\n}\n\nexport function scanTemplate(source: string, options: ScanOptions): ScanResult {\n const candidates: AnnotationCandidate[] = [];\n const refusals: AnnotationRefusal[] = [];\n const items = loopVariables(source);\n const elements = [...templateOnly(source).matchAll(ELEMENT)];\n const file: FileContext = {\n known: new Set(options.entities.flatMap((entity) => [...entity])),\n entities: options.entities,\n items,\n anchors: anchorsOf(elements, items),\n };\n for (const match of elements) {\n const [, tag = '', attributes = '', content = ''] = match;\n const line = lineAt(source, match.index);\n // Bound already, by an attribute or a helper's spread: yours wins, always.\n if (bindingOf(attributes) !== null) continue;\n if (ANY_INTERPOLATION.exec(content) === null) continue;\n const refusedElement = elementRefusal(tag, attributes);\n if (refusedElement !== undefined) {\n refusals.push({ line, reason: refusedElement, expression: describe(content) });\n continue;\n }\n const only = ONLY_INTERPOLATION.exec(content);\n if (only === null) {\n // A value printed beside a label — `Published {page.publishedAt}`. The\n // runtime writes an element's whole text, so a binding here would eat the\n // label; splitting the markup is a decision for whoever wrote it.\n refusals.push({\n line,\n reason:\n 'the value is printed beside other content — a binding replaces the whole text, so the markup has to be split first',\n expression: describe(content),\n });\n continue;\n }\n const expression = only[1] ?? '';\n const reason = refusalReason(expression, file);\n if (reason !== undefined) {\n refusals.push({ line, reason, expression: describe(expression) });\n continue;\n }\n candidates.push({\n // After `<tag`, before whatever the element already carries.\n insertAt: match.index + 1 + tag.length,\n path: pathOf(expression.trim()),\n line,\n tag,\n });\n }\n return { candidates, refusals };\n}\n\n/** The attribute a candidate becomes: what `pll-codegen annotate` writes into a file. */\nexport function fieldAttribute(candidate: AnnotationCandidate): string {\n return `${FIELD_ATTRIBUTE}=\"${candidate.path}\"`;\n}\n\n/**\n * Apply the candidates back-to-front, so every earlier offset still holds.\n *\n * `render` decides what a candidate becomes, because the two callers write\n * different things from the same decision: the codemod writes the attribute\n * into the file a person reads, and the build-time annotator writes a call to\n * the authorization-bound helper. What may be annotated at all is decided in\n * one place — above — and never here.\n */\nexport function applyAnnotations(\n source: string,\n candidates: readonly AnnotationCandidate[],\n render: (candidate: AnnotationCandidate) => string = fieldAttribute,\n): string {\n let out = source;\n for (const candidate of [...candidates].sort((a, b) => b.insertAt - a.insertAt)) {\n out = `${out.slice(0, candidate.insertAt)} ${render(candidate)}${out.slice(candidate.insertAt)}`;\n }\n return out;\n}\n","/**\n * `livePreviewAnnotate()` — the annotator as a build step, so a template needs\n * one binding written by hand per document it prints rather than one per field.\n *\n * It rewrites the same shape `pll-codegen annotate` rewrites, decided by the\n * same scanner (`./scan`), into a call rather than a fixed attribute:\n *\n * ```astro\n * <h1 {...preview.bind('title')}>{page.title}</h1> bound by hand\n * <p>{page.subtitle}</p>\n * → <p {...__lpPreview.bind('subtitle')}>{page.subtitle}</p>\n * ```\n *\n * The difference is who may see it. A fixed attribute is in the HTML of every\n * visitor and describes the content model to all of them; the call resolves per\n * request against the authorization the adapter published, so an unauthorized\n * response carries no `data-payload-*` at all (ADR 0006). A static build has no\n * request to resolve against and therefore emits nothing — `allowPublicBindings`\n * is how you say you want the attribute anyway, out loud.\n *\n * Astro only, for a reason rather than a lack of time: the rewrite needs a\n * template whose own scope can reach the request context, which frontmatter and\n * `Astro.locals` give and a Svelte or Vue component does not — there the value\n * would have to travel through `load` or a payload, where a function cannot go.\n *\n * Vite compatibility is a recorded fact, not a guess: `name`, `enforce` and\n * `load(id)` are the whole surface used here, and all three have been stable\n * since Vite 5. The majors that matter are in `quality/compat-matrix.json`,\n * which is what the tests read.\n *\n * `load` rather than `transform`, which is where a source rewrite would\n * normally go. Astro compiles `.astro` in a `transform` of its own, registered\n * `enforce: 'pre'` and ahead of anything a config contributes, so by the time\n * any user transform runs the markup is gone — measured, not assumed: a probe\n * plugin at `pre` received compiled output importing from Astro's own compiler\n * runtime, not the template. Every `load` runs before every `transform`, so\n * that is where the file is still a template. Reading it is what Rollup's\n * default loader would have done anyway.\n */\n\nimport { readFileSync } from 'node:fs';\nimport { annotatableEntities, type AnnotatableSchema } from './index';\nimport {\n applyAnnotations,\n fieldAttribute,\n scanTemplate,\n splitFrontmatter,\n type AnnotationRefusal,\n} from './scan';\n\nexport { splitFrontmatter } from './scan';\n\n/** The helper the rewritten markup calls, and the import that defines it. */\nconst HELPER = '__lpPreview';\nconst IMPORT_ALIAS = '__lpPreviewBindingsFromLocals';\nconst IMPORT_LINE = `import { previewBindingsFromLocals as ${IMPORT_ALIAS} } from 'payload-live-preview/server';`;\nconst HELPER_LINE = `const ${HELPER} = ${IMPORT_ALIAS}(Astro.locals);`;\nconst FENCE = '---';\n\n/** @beta */\nexport interface AnnotatePluginOptions {\n /** The schema, from `generateTypes().inventory` or the `--inventory` file. */\n readonly inventory: AnnotatableSchema;\n /**\n * Write the plain `data-payload-field` attribute instead of the gated call.\n * A statically built site has no request to authorize, so this is the only\n * way it can carry bindings — and it publishes the field names to everyone.\n * Default `false`.\n */\n readonly allowPublicBindings?: boolean;\n /** Which modules to transform. Default: every `.astro` file. */\n readonly include?: (id: string) => boolean;\n /** Called once per file with what the scanner would not annotate. */\n readonly onRefusals?: (file: string, refusals: readonly AnnotationRefusal[]) => void;\n /** Reads a template. Defaults to the file system; injected by tests. */\n readonly readFile?: (path: string) => string;\n}\n\n/**\n * The slice of Vite's plugin shape this uses; three hooks, stable since Vite 5.\n *\n * @beta\n */\nexport interface AnnotateVitePlugin {\n readonly name: string;\n readonly enforce: 'pre';\n load(id: string): { code: string; map: null } | null;\n}\n\n/** The frontmatter with the helper in it, whether or not the file had one. */\nfunction withHelper(code: string, bodyOffset: number): string {\n const lines = `${IMPORT_LINE}\\n${HELPER_LINE}\\n`;\n if (bodyOffset === 0) return `${FENCE}\\n${lines}${FENCE}\\n${code}`;\n return `${FENCE}\\n${lines}${code.slice(FENCE.length, bodyOffset)}${code.slice(bodyOffset)}`;\n}\n\n/**\n * A plain `.astro` path. Not a sub-request (`?astro&type=style`), not a virtual\n * module (`\\0…`): those are Astro's own, and loading them is not this plugin's\n * business.\n */\nconst isAstro = (id: string): boolean =>\n !id.startsWith('\\0') && !id.includes('?') && id.endsWith('.astro');\n\n/**\n * The transform on its own, so a test can call it without a bundler and a\n * caller can see exactly what a file becomes.\n * @internal\n */\nexport function annotateSource(\n code: string,\n options: AnnotatePluginOptions,\n): { readonly code: string; readonly refusals: readonly AnnotationRefusal[] } {\n // The scanner never reads the frontmatter, so every candidate lies in the\n // template and the fence stays where the helper goes.\n const { candidates, refusals } = scanTemplate(code, {\n entities: annotatableEntities(options.inventory),\n });\n if (candidates.length === 0) return { code, refusals };\n\n const { bodyOffset } = splitFrontmatter(code);\n const gated = options.allowPublicBindings !== true;\n const rewritten = applyAnnotations(code, candidates, (candidate) =>\n gated ? `{...${HELPER}.bind('${candidate.path}')}` : fieldAttribute(candidate),\n );\n return {\n code: gated ? withHelper(rewritten, bodyOffset) : rewritten,\n refusals,\n };\n}\n\n/**\n * ```js\n * // astro.config.mjs\n * vite: { plugins: [livePreviewAnnotate({ inventory })] }\n * ```\n *\n * @beta\n */\nexport function livePreviewAnnotate(options: AnnotatePluginOptions): AnnotateVitePlugin {\n const include = options.include ?? isAstro;\n const read = options.readFile ?? ((path: string) => readFileSync(path, 'utf8'));\n return {\n name: 'payload-live-preview:annotate',\n enforce: 'pre',\n load(id) {\n if (!include(id)) return null;\n const source = read(id);\n const { code, refusals } = annotateSource(source, options);\n if (refusals.length > 0) options.onRefusals?.(id, refusals);\n // The unannotated source is still returned: this loader replaces the\n // default one, so declining would leave the module empty.\n return { code, map: null };\n },\n };\n}\n","/**\n * `pll-codegen annotate`: put `data-payload-field` where a template already\n * prints a field, and report every place it would have had to guess.\n *\n * The schema decides what exists — the same inventory `--inventory` writes, so\n * an annotation and a runtime binding spell a path the same way. What the tool\n * cannot attribute is listed, never invented: an unbound field costs an editor\n * one invisible edit, a wrongly bound one writes a value into the wrong element\n * on every keystroke.\n */\n\nimport { readFile, writeFile } from 'node:fs/promises';\nimport { relative } from 'node:path';\nimport type { PreviewInventory } from '../inventory';\nimport {\n applyAnnotations,\n scanTemplate,\n type AnnotationCandidate,\n type AnnotationRefusal,\n} from './scan';\n\nexport type { AnnotationCandidate, AnnotationRefusal } from './scan';\n\n/** Templates this scanner understands; a `.vue` template uses `{{ … }}` and is not one yet. @internal */\nexport const ANNOTATABLE_EXTENSIONS: readonly string[] = ['.astro', '.jsx', '.tsx', '.svelte'];\n\n/** @internal */\nexport interface AnnotateFileResult {\n readonly file: string;\n /** The annotated source; identical to the input when nothing was added. */\n readonly code: string;\n readonly annotations: readonly AnnotationCandidate[];\n readonly refusals: readonly AnnotationRefusal[];\n readonly changed: boolean;\n}\n\n/** @internal */\nexport interface AnnotateResult {\n readonly files: readonly AnnotateFileResult[];\n readonly annotationCount: number;\n readonly refusalCount: number;\n /** Whether the files were written; `false` is a dry run. */\n readonly written: boolean;\n}\n\n/** @internal */\nexport interface AnnotateOptions {\n /** Template files to read. */\n readonly files: readonly string[];\n /** The schema's addressable paths, from `generateTypes().inventory`. */\n readonly inventory: PreviewInventory;\n /** Write the annotated sources back. Without it nothing is touched. */\n readonly write?: boolean;\n /** Resolves the paths in the report. Defaults to `process.cwd()`. */\n readonly cwd?: string;\n /** Reader/writer injection for tests. */\n readonly io?: {\n readonly read: (path: string) => Promise<string>;\n readonly write: (path: string, content: string) => Promise<void>;\n };\n}\n\n/**\n * The part of an inventory the annotator reads: the paths, and nothing else.\n *\n * `PreviewInventory` from `generateTypes()` satisfies it, and so does an object\n * a project writes by hand. Naming the minimum keeps the build plugin's public\n * surface free of the extracted-field union behind the full inventory — a dozen\n * types a consumer of a Vite plugin has no reason to meet.\n *\n * @beta\n */\nexport interface AnnotatableSchema {\n readonly globals: readonly { readonly fields: readonly { readonly path: string }[] }[];\n readonly collections: readonly { readonly fields: readonly { readonly path: string }[] }[];\n}\n\n/**\n * The paths each collection and global can address, one set per entity.\n *\n * An array's items are spelled `slides.*.caption` in the inventory because that\n * is how the runtime resolves them; a template writes `slide.caption` inside a\n * loop, where nothing connects `slide` to `slides`. Those paths are therefore\n * kept out: the scanner would otherwise match a name that only looks right.\n * The sets stay apart because one template variable holds one document, so a\n * path is only bindable together with the fields bound by hand on the same\n * variable.\n * @internal\n */\nexport function annotatableEntities(inventory: AnnotatableSchema): readonly ReadonlySet<string>[] {\n return [...inventory.globals, ...inventory.collections].map(\n (entry) =>\n new Set(entry.fields.map((field) => field.path).filter((path) => !path.includes('*'))),\n );\n}\n\n/** Every path of every collection and global, in one set: the same paths, not kept apart. @internal */\nexport function annotatablePaths(inventory: AnnotatableSchema): ReadonlySet<string> {\n return new Set(annotatableEntities(inventory).flatMap((paths) => [...paths]));\n}\n\n/** @internal */\nexport async function annotateTemplates(options: AnnotateOptions): Promise<AnnotateResult> {\n const read = options.io?.read ?? ((path: string) => readFile(path, 'utf8'));\n const write =\n options.io?.write ?? ((path: string, content: string) => writeFile(path, content, 'utf8'));\n const root = options.cwd ?? process.cwd();\n const entities = annotatableEntities(options.inventory);\n const files: AnnotateFileResult[] = [];\n\n for (const file of options.files) {\n const source = await read(file);\n const { candidates, refusals } = scanTemplate(source, { entities });\n const code = candidates.length === 0 ? source : applyAnnotations(source, candidates);\n const changed = code !== source;\n if (changed && options.write === true) await write(file, code);\n files.push({\n file: relative(root, file) || file,\n code,\n annotations: candidates,\n refusals,\n changed,\n });\n }\n\n return {\n files,\n annotationCount: files.reduce((total, file) => total + file.annotations.length, 0),\n refusalCount: files.reduce((total, file) => total + file.refusals.length, 0),\n written: options.write === true,\n };\n}\n\n/** The report, one line per annotation and per refusal, in file order. @internal */\nexport function formatAnnotateReport(result: AnnotateResult): string {\n const lines: string[] = [];\n for (const file of result.files) {\n if (file.annotations.length === 0 && file.refusals.length === 0) continue;\n lines.push(file.file);\n for (const annotation of file.annotations) {\n lines.push(` ${String(annotation.line)}: <${annotation.tag}> → ${annotation.path}`);\n }\n for (const refusal of file.refusals) {\n lines.push(\n ` ${String(refusal.line)}: left alone — ${refusal.reason} (${refusal.expression})`,\n );\n }\n }\n const verb = result.written ? 'annotated' : 'would annotate';\n lines.push(\n `${verb} ${String(result.annotationCount)} element(s); ` +\n `${String(result.refusalCount)} left for a human`,\n );\n return `${lines.join('\\n')}\\n`;\n}\n"],"mappings":"mEA2EA,IAAMA,EACJ,gGAOIC,EACJ,qGAGIC,EAAqB,wBAGrBC,EAAoB,gBAGpBC,EAAe,6CAEfC,EAAkB,qBAGlBC,EACJ,mFAOIC,EACJ,sGAGIC,EAAa,eAWbC,EAAoC,CACxC,wEACA,+DACA,8CAMK,SAASC,EAAiBC,GAI/B,IAAKA,EAAKC,WAPE,OAOc,MAAU,CAAEC,YAAa,GAAIC,WAAY,GACnE,MAAMC,EAAMJ,EAAKK,QAAQ,QAAcC,GACvC,IAAY,IAARF,EAAY,MAAO,CAAEF,YAAa,GAAIC,WAAY,GACtD,MAAMA,EAAaC,EAAM,EAAIE,EAC7B,MAAO,CAAEJ,YAAaF,EAAKO,MAAMD,EAAcF,GAAMD,aACvD,CAGA,SAASK,EAAMC,GACb,OAAOA,EAAKC,QAAQ,UAAW,IACjC,CAQA,SAASC,EAAaC,GACpB,MAAMT,WAAEA,GAAeJ,EAAiBa,GAClCC,EAAOD,EAAOL,MAAMJ,GAAYO,QAAQpB,EAAckB,GAC5D,MAAO,GAAGA,EAAMI,EAAOL,MAAM,EAAGJ,MAAeU,GACjD,CAYA,SAASC,EAAOF,EAAgBG,GAC9B,IAAIC,EAAO,EACX,QAASC,EAAW,EAAGA,EAAWF,EAAOE,GAAY,EACf,KAAhCL,EAAOM,WAAWD,KAAkBD,GAAQ,GAElD,OAAOA,CACT,CAOA,SAASG,EAAOC,GACd,OAAOA,EAAMb,MAAMa,EAAM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