payload-live-preview 2.0.2 → 2.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.md +13 -8
  2. package/dist/adapters/astro/index.js +1 -1
  3. package/dist/adapters/astro/index.js.map +1 -1
  4. package/dist/adapters/astro/middleware-entry.js +1 -1
  5. package/dist/adapters/astro/middleware-entry.js.map +1 -1
  6. package/dist/adapters/nextjs/index.js +1 -1
  7. package/dist/adapters/nextjs/index.js.map +1 -1
  8. package/dist/adapters/nuxt/index.js +1 -1
  9. package/dist/adapters/nuxt/index.js.map +1 -1
  10. package/dist/adapters/sveltekit/index.js +1 -1
  11. package/dist/adapters/sveltekit/index.js.map +1 -1
  12. package/dist/client.cjs +1 -1
  13. package/dist/client.cjs.map +1 -1
  14. package/dist/client.d.cts +10 -3
  15. package/dist/client.d.ts +10 -3
  16. package/dist/client.js +1 -1
  17. package/dist/client.js.map +1 -1
  18. package/dist/codegen-astro.js.map +1 -1
  19. package/dist/codegen-cli.js.map +1 -1
  20. package/dist/codegen.cjs +1 -1
  21. package/dist/codegen.cjs.map +1 -1
  22. package/dist/codegen.d.cts +1 -16
  23. package/dist/codegen.d.ts +1 -16
  24. package/dist/codegen.js +1 -1
  25. package/dist/codegen.js.map +1 -1
  26. package/dist/core.cjs +1 -1
  27. package/dist/core.cjs.map +1 -1
  28. package/dist/core.d.cts +13 -5
  29. package/dist/core.d.ts +13 -5
  30. package/dist/core.js +1 -1
  31. package/dist/core.js.map +1 -1
  32. package/dist/doctor-cli.d.ts +1 -1
  33. package/dist/doctor-cli.js +1 -1
  34. package/dist/doctor-cli.js.map +1 -1
  35. package/dist/doctor.d.ts +2 -2
  36. package/dist/doctor.js +1 -1
  37. package/dist/doctor.js.map +1 -1
  38. package/dist/fragment.cjs +1 -1
  39. package/dist/fragment.cjs.map +1 -1
  40. package/dist/fragment.d.cts +5 -1
  41. package/dist/fragment.d.ts +5 -1
  42. package/dist/fragment.js +1 -1
  43. package/dist/fragment.js.map +1 -1
  44. package/dist/index.cjs +1 -1
  45. package/dist/index.cjs.map +1 -1
  46. package/dist/index.d.cts +13 -5
  47. package/dist/index.d.ts +13 -5
  48. package/dist/index.js +1 -1
  49. package/dist/index.js.map +1 -1
  50. package/dist/lean.cjs +1 -1
  51. package/dist/lean.cjs.map +1 -1
  52. package/dist/lean.js +1 -1
  53. package/dist/lean.js.map +1 -1
  54. package/dist/lexical.cjs +1 -1
  55. package/dist/lexical.cjs.map +1 -1
  56. package/dist/lexical.js +1 -1
  57. package/dist/lexical.js.map +1 -1
  58. package/dist/plugins.cjs +1 -1
  59. package/dist/plugins.cjs.map +1 -1
  60. package/dist/plugins.d.cts +5 -1
  61. package/dist/plugins.d.ts +5 -1
  62. package/dist/plugins.js +1 -1
  63. package/dist/plugins.js.map +1 -1
  64. package/dist/{probe-DqaItcwX.d.ts → probe-Bzm4fYFL.d.ts} +11 -1
  65. package/dist/server.cjs +1 -1
  66. package/dist/server.cjs.map +1 -1
  67. package/dist/server.js +1 -1
  68. package/dist/server.js.map +1 -1
  69. package/dist/structural.cjs +2 -2
  70. package/dist/structural.cjs.map +1 -1
  71. package/dist/structural.js +2 -2
  72. package/dist/structural.js.map +1 -1
  73. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { D as DoctorFetch } from './probe-DqaItcwX.js';
2
+ import { D as DoctorFetch } from './probe-Bzm4fYFL.js';
3
3
 
4
4
  /** @param fetchImpl Seam for tests; the bin shim never passes it. */
5
5
  declare function run(argv: readonly string[], fetchImpl?: DoctorFetch): Promise<number>;
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as e}from"module";import{relative as t,join as n,extname as r}from"path";import{writeFile as i,readFile as o,stat as s,readdir as a}from"fs/promises";var d,l,c="payload-live-preview";function u(){if(void 0===d)try{d=e(import.meta.url)("ts-morph")}catch(e){throw new Error("pll migrate needs ts-morph: npm install --save-dev ts-morph",{cause:e})}return d}function h(e,t){const n=u();return l??=new n.Project({useInMemoryFileSystem:!0,skipLoadingLibFiles:!0,skipFileDependencyResolution:!0,compilerOptions:{allowJs:!0,noLib:!0}}),l.createSourceFile(`/script.${t}`,e,{overwrite:!0})}function p(e){return e===c||e.startsWith(`${c}/`)}function f(e){const{Node:t,SyntaxKind:n}=u(),r=[];for(const t of e.getImportDeclarations()){const e=t.getModuleSpecifierValue();if(p(e))for(const n of t.getNamedImports()){const i=n.getAliasNode(),o=i??n.getNameNode();r.push({imported:n.getName(),local:o.getText(),specifier:e,kind:"import",importedNode:n.getNameNode(),aliased:void 0!==i,symbol:o.getSymbol(),declaration:t})}}for(const i of e.getDescendantsOfKind(n.VariableDeclaration)){const e=m(i.getInitializer()),n=i.getNameNode();if(void 0!==e&&p(e)&&t.isObjectBindingPattern(n))for(const o of n.getElements()){const n=o.getNameNode();if(!t.isIdentifier(n))continue;const s=o.getPropertyNameNode();r.push({imported:void 0===s?n.getText():g(s),local:n.getText(),specifier:e,kind:"require",importedNode:s??n,aliased:void 0!==s,symbol:n.getSymbol(),declaration:i})}}return r}function m(e){const{Node:t,SyntaxKind:n}=u(),r=void 0!==e&&t.isAwaitExpression(e)?e.getExpression():e;if(void 0===r||!t.isCallExpression(r))return;const i=r.getExpression();if((!t.isIdentifier(i)||"require"!==i.getText())&&i.getKind()!==n.ImportKeyword)return;const[o]=r.getArguments();return void 0!==o&&t.isStringLiteral(o)?o.getLiteralText():void 0}function g(e){const{Node:t}=u();return t.isStringLiteral(e)||t.isNoSubstitutionTemplateLiteral(e)?e.getLiteralText():e.getText()}function w(e){const{Node:t}=u();if(t.isSpreadAssignment(e))return;const n=e.getNameNode();return t.isComputedPropertyName(n)?void 0:g(n)}function v(e,t){const{Node:n,SyntaxKind:r}=u(),i=t.symbol?.compilerSymbol;if(void 0===i)return[];const o=e.getProject().getTypeChecker(),s=[];for(const a of e.getDescendantsOfKind(r.Identifier)){if(a.getText()!==t.local||y(a,t.declaration))continue;const e=a.getParent();n.isShorthandPropertyAssignment(e)?o.getShorthandAssignmentValueSymbol(e)?.compilerSymbol===i&&s.push({node:a,kind:"shorthand"}):n.isExportSpecifier(e)?e.getNameNode()===a&&e.getLocalTargetSymbol()?.compilerSymbol===i&&s.push({node:a,kind:"export"}):a.getSymbol()?.compilerSymbol===i&&s.push({node:a,kind:"reference"})}return s}function y(e,t){return void 0!==e.getFirstAncestor(e=>e===t)}function b(e,t,n=[]){const{SyntaxKind:r}=u();for(const i of e.getDescendantsOfKind(r.Identifier)){if(i.getText()!==t)continue;const e=i.getParent();if(P(e,i)&&!n.some(t=>t===e||y(e,t)))return e}}function P(e,t){const{Node:n}=u();return n.isVariableDeclaration(e)||n.isBindingElement(e)||n.isFunctionDeclaration(e)||n.isClassDeclaration(e)||n.isParameterDeclaration(e)||n.isEnumDeclaration(e)?e.getNameNode()===t:n.isImportSpecifier(e)?(e.getAliasNode()??e.getNameNode())===t:n.isImportClause(e)?e.getDefaultImport()===t:!!n.isNamespaceImport(e)&&e.getNameNode()===t}function $(e,t){return{start:e.getStart(),end:e.getEnd(),text:t}}function L(e,t){const n=[...t].sort((e,t)=>t.start-e.start);let r=e,i=Number.POSITIVE_INFINITY;for(const e of n){if(e.end>i)throw new Error("overlapping codemod edits");r=`${r.slice(0,e.start)}${e.text}${r.slice(e.end)}`,i=e.start}return r}var x="move-fetch-preview-helpers",S=`${c}/server`,k={fetchPreviewDocument:"fetchDocument",fetchPreviewGlobal:"fetchGlobal"},N=/* @__PURE__ */new Set(["serverURL","apiRoute","depth"]),T=/* @__PURE__ */new Set(["draft","fetchFn"]),O=["authorization","locale","headers","signal","errorMode"],R={fetchPreviewDocument:["collection","where",...O],fetchPreviewGlobal:["global",...O]};function E(e,t){return{codemod:x,reason:t,line:e}}function A(e,t,n){const r=[],i=[],o=[],s=/* @__PURE__ */new Set;for(const e of t.getProperties()){const t=w(e);void 0!==t&&s.add(t),void 0!==t&&N.has(t)?r.push(e.getText()):void 0!==t&&T.has(t)?o.push(t):i.push(e.getText())}s.has("depth")||r.push("depth: 1 /* TODO(pll migrate): the 1.x default; match the runtime mergeDepth */"),s.has("authorization")||i.push("authorization: null /* TODO(pll migrate): pass the verdict from authorizePreviewRequest(); null reads the published document */");const a=R[n]??[],d=[...s].filter(e=>!N.has(e)&&!T.has(e)&&!a.includes(e)),l=e.getTypeArguments().map(e=>e.getText()),c=0===l.length?"":`<${l.join(", ")}>`,u=k[n]??n,h=`definePreview({ ${r.join(", ")} }).${u}${c}({ ${i.join(", ")} })`,p=0===o.length?"":`, and ${o.join("/")} was dropped`,f=e.getStartLineNumber(),m=[E(f,`${n}() was rewritten onto definePreview().${u}(); it now returns a PreviewFetchResult (check ok/data) and needs a real authorization for drafts${p}`)];return d.length>0&&m.push(E(f,`${n}() was passed ${d.map(e=>`\`${e}\``).join(", ")}, which .${u}() does not accept; it takes ${a.join(", ")}. The key was carried over unchanged and will not compile — place it by hand`)),{edit:{start:e.getStart(),end:e.getEnd(),text:h},notes:m}}function j(e,t,n){return`import { ${t.join(", ")} } from ${e}${n}${e};`}var I={id:x,summary:"`fetchPreviewDocument`/`fetchPreviewGlobal` from the root → `definePreview().fetchDocument`/`.fetchGlobal` (payload-live-preview/server)",ledgerEntry:9,apply(e){const t=f(e).filter(e=>e.specifier===c&&e.imported in k);return 0===t.length?{edits:[],conflicts:[]}:function(e,t){const{Node:n}=u(),r=[],i=[],o=[];for(const s of t)if("require"!==s.kind)for(const t of v(e,s)){const e=t.node.getStartLineNumber(),a=t.node.getParent();if("reference"!==t.kind||!n.isCallExpression(a)||a.getExpression()!==t.node){r.push(E(e,`${s.local} is used other than as a direct call; rewrite it onto definePreview() by hand`));continue}const[d]=a.getArguments();if(void 0===d||!n.isObjectLiteralExpression(d)||d.getProperties().some(e=>n.isSpreadAssignment(e))){r.push(E(e,`${s.imported}() options are not a plain object literal, so serverURL/depth cannot be split out; rewrite it onto definePreview() by hand`));continue}const l=A(a,d,s.imported);o.push(l.edit),i.push(...l.notes)}else r.push(E(s.declaration.getStartLineNumber(),`${s.imported} is bound with require(); rewrite it onto definePreview() from ${S} by hand`));const s=e.getImportDeclarations().filter(e=>e.getModuleSpecifierValue()===S),a=b(e,"definePreview",s);return void 0!==a&&r.push(E(a.getStartLineNumber(),`this module already binds a definePreview that is not ${S}'s; rename it, then move the fetch helpers by hand`)),r.length>0?{edits:[],conflicts:[...r,...i]}:(o.push(...function(e,t){const{Node:n}=u(),r=[],i=/* @__PURE__ */new Set;for(const e of t)n.isImportDeclaration(e.declaration)&&i.add(e.declaration);const o=e.getImportDeclarations().find(e=>e.getModuleSpecifierValue()===S&&!e.isTypeOnly()),s=!0===o?.getNamedImports().some(e=>"definePreview"===e.getName());let a;if(void 0!==o&&!s){const e=o.getModuleSpecifier().getQuoteKind(),t=[...o.getNamedImports().map(e=>e.getText()),"definePreview"],n=o.getDefaultImport()?.getText(),i=void 0===n?t.join(", "):`${n}, { ${t.join(", ")} }`,s=void 0===n?j(e,t,S):`import ${i} from ${e}${S}${e};`;r.push({start:o.getStart(),end:o.getEnd(),text:s})}for(const t of i){const n=t.getModuleSpecifier().getQuoteKind(),i=t.getNamedImports().filter(e=>!(e.getName()in k)).map(e=>e.getText()),s=t.getDefaultImport()?.getText(),d=[s,0===i.length?void 0:`{ ${i.join(", ")} }`].filter(e=>void 0!==e),l=t.isTypeOnly()?"type ":"",u=0===d.length?"":`import ${l}${d.join(", ")} from ${n}${c}${n};`;if(void 0===o&&void 0===a)a=j(n,["definePreview"],S),r.push({start:t.getStart(),end:t.getEnd(),text:""===u?a:`${u}\n${a}`});else{const n=t.getEnd(),i=""===u&&"\n"===e.getFullText()[n]?1:0;r.push({start:t.getStart(),end:n+i,text:u})}}return r}(e,t)),{edits:o,conflicts:i})}(e,t)}},C="rename-admin-origins-option",U="hasPreviewIntent",q="adminOrigins",D="allowedOrigins",F=`if they carry \`${q}\`, rename it to \`${D}\``,z={id:C,summary:"`hasPreviewIntent(request, { adminOrigins })` → `{ allowedOrigins }`",ledgerEntry:13,apply(e){const{Node:t}=u(),n=[],r=[],i=f(e).filter(e=>e.imported===U);for(const o of i)for(const i of v(e,o)){const e=i.node.getParent();if("reference"!==i.kind||!t.isCallExpression(e))continue;if(e.getExpression()!==i.node)continue;const o=e.getArguments()[1];if(void 0===o)continue;const s=o.getStartLineNumber();if(!t.isObjectLiteralExpression(o)){r.push({codemod:C,line:s,reason:`${U}() options are not a literal; ${F}`});continue}const a=o.getProperties(),d=a.map(e=>w(e));if(d.includes(q)&&d.includes(D))r.push({codemod:C,line:s,reason:`${U}() is given both ${q} and ${D}; ${D} wins, drop ${q} by hand`});else for(const e of a)if(t.isSpreadAssignment(e))r.push({codemod:C,line:e.getStartLineNumber(),reason:`${U}() spreads its options; ${F}`});else{if(w(e)!==q)continue;t.isShorthandPropertyAssignment(e)?n.push($(e,`${D}: ${q}`)):t.isPropertyAssignment(e)&&n.push($(e.getNameNode(),D))}}return{edits:n,conflicts:r}}},M="rename-bindings-authorized-option",B="authorized",W="authorization",_=`if they carry \`${B}\`, rename it to \`${W}\` and pass the verdict from authorizePreviewRequest()`,G=`\`${W}\` takes the context from authorizePreviewRequest(); the boolean 1.x accepted is not. The key was renamed and its value left as it stands — pass the verdict, or \`null\` for a public response`,K={id:M,summary:"`createPreviewBindings({ authorized })` → `{ authorization }`",ledgerEntry:7,apply(e){const{Node:t}=u(),n=[],r=[],i=f(e).filter(e=>"createPreviewBindings"===e.imported);for(const o of i)for(const i of v(e,o)){const e=i.node.getParent();if("reference"!==i.kind||!t.isCallExpression(e))continue;if(e.getExpression()!==i.node)continue;const[o]=e.getArguments();if(void 0===o)continue;const s=o.getStartLineNumber();if(t.isObjectLiteralExpression(o))for(const e of o.getProperties())if(t.isSpreadAssignment(e))r.push({codemod:M,line:e.getStartLineNumber(),reason:`createPreviewBindings() spreads its options; ${_}`});else{if(w(e)!==B)continue;if(t.isShorthandPropertyAssignment(e))n.push($(e,`${W}: ${B}`)),r.push({codemod:M,line:e.getStartLineNumber(),reason:G});else if(t.isPropertyAssignment(e)){const i=e.getInitializer();if(void 0!==i&&t.isFalseLiteral(i)){n.push($(e,`${W}: null`));continue}n.push($(e.getNameNode(),W)),r.push({codemod:M,line:e.getStartLineNumber(),reason:G})}}else r.push({codemod:M,line:s,reason:`createPreviewBindings() options are not a literal; ${_}`})}return{edits:n,conflicts:r}}},V="rename-is-preview-request",H="isPreviewRequest",J="hasPreviewIntent";function Q(e,t){return{codemod:V,reason:t,line:e}}function X(e){return e.aliased&&e.local===J?$(e.importedNode.getParentOrThrow(),J):$(e.importedNode,J)}var Y={id:V,summary:"`isPreviewRequest()` → `hasPreviewIntent()` (same signature)",ledgerEntry:1,notice:"hasPreviewIntent() takes the options isPreviewRequest() took and, without `signals`, counts the same three: a preview query parameter, Sec-Fetch-Dest: iframe and an admin Referer. The 2.0 adapters count only the query; where a call should agree with them, pass { signals: ['query'] } (docs/migration.md).",apply(e){const t=f(e).filter(e=>e.imported===H);return 0===t.length?{edits:[],conflicts:[]}:function(e,t){const n=[],r=[],i=b(t,J,e.map(e=>e.declaration));void 0!==i&&n.push(Q(i.getStartLineNumber(),`this module already binds ${J}; rename it (or drop the wrapper and import the package's ${J} directly), then rename ${H} by hand`));for(const i of e)if(r.push(X(i)),!i.aliased)for(const e of v(t,i))"reference"===e.kind?r.push($(e.node,J)):"shorthand"===e.kind?n.push(Q(e.node.getStartLineNumber(),`{ ${H} } keeps the old key for whoever reads it; write { ${H}: ${J} } or rename the key and its readers by hand`)):n.push(Q(e.node.getStartLineNumber(),`${H} is re-exported under its old name; rename the export and its importers, or write export { ${J} as ${H} }`));const o=function(e,t){const{Node:n,SyntaxKind:r}=u();return e.getDescendantsOfKind(r.Identifier).filter(e=>{const r=e.getParent();return e.getText()===t&&n.isPropertyAccessExpression(r)&&r.getNameNode()===e})}(t,H).map(e=>Q(e.getStartLineNumber(),`.${H} is a member of this module's own object, not the package import, and was left alone; check that it does not wrap the removed API`));return n.length>0?{edits:[],conflicts:[...n,...o]}:{edits:r,conflicts:o}}(t,e)}},Z={".ts":"ts",".mts":"ts",".cts":"ts",".tsx":"tsx",".js":"js",".mjs":"js",".cjs":"js",".jsx":"jsx"},ee=/* @__PURE__ */new Set([".astro",".vue",".svelte"]),te=/^---\r?\n([\s\S]*?)\r?\n---/u,ne=/<script(?:\s[^>]*)?>([\s\S]*?)<\/script\b[^>]*>/giu,re=/(?:\bfrom\s*|\bimport\s*\(?\s*|\brequire\s*\(\s*)['"]payload-live-preview(?:\/[^'"]*)?['"]/u,ie=[Y,z,K,I],oe=ie;function se(e,t){let n=1;for(let r=0;r<t;r+=1)"\n"===e[r]&&(n+=1);return n}function ae(e,t,n){const r=e.split("\n"),i=t.split("\n");let o=0;for(;o<r.length&&o<i.length&&r[o]===i[o];)o+=1;let s=0;for(;s<r.length-o&&s<i.length-o&&r[r.length-1-s]===i[i.length-1-s];)s+=1;const a=r.slice(o,r.length-s),d=i.slice(o,i.length-s),l=[];for(let e=0;e<Math.max(a.length,d.length);e+=1){const t=a[e]??"",r=d[e]??"";t!==r&&l.push({line:n+o+e,before:t,after:r})}return l}function de(e,t={}){const n=void 0===t.only?ie:ie.filter(e=>t.only?.includes(e.id));if(0===n.length||!function(e){return re.test(e)}(e))return{output:e,edits:[],conflicts:[]};const i=/* @__PURE__ */new Map,o=[];let s="",a=0;for(const d of function(e,t){const n=r(t).toLowerCase();if(!ee.has(n))return[{start:0,end:e.length,kind:Z[n]??"ts"}];const i=[],o=".astro"===n?te.exec(e):null;if(void 0!==o?.[1]){const e=o.index+o[0].indexOf("\n")+1;i.push({start:e,end:e+o[1].length,kind:"ts"})}for(const t of e.matchAll(ne)){const e=t[1]??"";if(""===e.trim())continue;const n=t.index+t[0].lastIndexOf(e);i.push({start:n,end:n+e.length,kind:"ts"})}return i}(e,t.fileName??"source.ts")){s+=e.slice(a,d.start);const t=se(e,d.start);let r=e.slice(d.start,d.end);for(const e of n){const n=e.apply(h(r,d.kind));for(const e of n.conflicts)o.push(void 0===e.line?e:{...e,line:e.line+t-1});if(0===n.edits.length)continue;const s=L(r,n.edits),a=i.get(e.id)??[];a.push(...ae(r,s,t)),i.set(e.id,a),r=s}s+=r,a=d.end}return s+=e.slice(a),{output:s,edits:[...i].map(([e,t])=>({codemod:e,count:t.length,lines:t})),conflicts:o}}var le=/* @__PURE__ */new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".astro",".svelte",".vue"]),ce=/\.d\.[cm]?ts$/u,ue=/* @__PURE__ */new Set(["node_modules","dist",".git",".astro",".svelte-kit",".next",".nuxt","coverage"]);function he(e){return le.has(r(e))&&!ce.test(e)}async function pe(e){const t=[];return(await s(e)).isDirectory()?await async function e(r){for(const i of await a(r,{withFileTypes:!0})){const o=n(r,i.name);i.isDirectory()?ue.has(i.name)||await e(o):he(i.name)&&t.push(o)}}(e):he(e)&&t.push(e),t.sort()}function fe(e,n){const r=t(e,n);return 0===r.length?n:r}function me(e){return e.edits.map(e=>`${e.codemod}: ${String(e.count)} line(s)`).join(", ")}var ge={error:"ERROR",warning:"WARN ",info:"INFO "},we=Object.freeze({NoTrustedOrigin:"LP0101",ReferrerOnlyTrust:"LP0102",PluginIncompatible:"LP0103",ProfileFeatureOmitted:"LP0104",OrphanField:"LP0201",UnattributableUpdate:"LP0202",VisibilityGateDeferred:"LP0301",UnsafeAttributeWrite:"LP0401",TextTargetHasChildren:"LP0402",MissingArrayTemplate:"LP0403",StructuralItemUnkeyed:"LP0404",StructuralDuplicateKey:"LP0405",StructuralUnstableKeys:"LP0406",UnsupportedStrategy:"LP0407",UnknownValueFormat:"LP0408",SanitizerDroppedAttribute:"LP0409",UnrenderedBlockKept:"LP0410",UnfaithfulPatch:"LP0411",ServerFormatReplaced:"LP0412",UnrenderedBlockLost:"LP0413",MessageRejected:"LP0501",TokenRejected:"LP0502",ProtocolShapeUnknown:"LP0503",HandlerThrew:"LP0601",TransformThrew:"LP0602",RendererThrew:"LP0603",StartupFailed:"LP0605",ReadyFailed:"LP0606",HydrationWaitTimedOut:"LP0607",AuditRuntimeMissing:"LP0701",AuditNoFrameAncestors:"LP0702",AuditFrameOptionsBlocks:"LP0703",AuditBindingsExposed:"LP0704",AuditGateThresholdExceeded:"LP0705",AuditUnownedBindings:"LP0706",AuditNoBindings:"LP0707",AuditNotAPage:"LP0708",FragmentRequestFailed:"LP0801",FragmentResponseInvalid:"LP0802",FragmentUnauthorized:"LP0803",FragmentSuperseded:"LP0804",RouteRefreshLoop:"LP0805",FragmentStrategyUnavailable:"LP0806",UnboundChangeRefresh:"LP0807",V2ReadinessGap:"LP0709",RuntimeOnPublicPage:"LP0710"}),ve={http:"80",https:"443",ws:"80",wss:"443"},ye=/^([a-z][a-z0-9+.-]*):$/u,be=/^(?:([a-z][a-z0-9+.-]*):\/\/)?(\*|(?:\*\.)?[a-z0-9-]+(?:\.[a-z0-9-]+)*\.?)(?::(\*|\d+))?(?:\/.*)?$/u;function Pe(e){return e.protocol.slice(0,-1).toLowerCase()}function $e(e){return""===e.port?ve[Pe(e)]??"":e.port}function Le(e,t){return e===t||"http"===e&&"https"===t||"ws"===e&&"wss"===t}function xe(e,t){if(e.hostname!==t.hostname)return!1;const n=Pe(e),r=Pe(t);return(n===r||"http"===r&&"https"===n)&&($e(e)===$e(t)||""===e.port&&""===t.port)}function Se(e,t,n){const r=ye.exec(e);if(void 0!==r?.[1])return Le(r[1],Pe(t));const i=be.exec(e);if(null===i)return!1;const o=i[1],s=i[2]??"",a=i[3];return!!Le(o??Pe(n),Pe(t))&&!!function(e,t){if("*"===e)return!0;const n=e.replace(/\.$/u,""),r=t.replace(/\.$/u,"");return n.startsWith("*.")?r.endsWith(n.slice(1))&&r.length>n.length-1:n===r}(s,t.hostname)&&(void 0===a?""===t.port:"*"===a||a===$e(t))}var ke=["allowedOrigins","serverURL","apiRoute","mergeDepth","debug","debounceMs","enableA11y","heartbeatMs","disableVisibilityGate","visibilityGateThreshold","intersectionRootMargin","disableReferrerDetection","disableLocalhostMatching","scopeBindingsByOwner","skipUnchanged","eventSourcePolicy","sanitizerPolicy","fragmentEndpoint","revealEditedField","routeStrategy","onUnboundChange","onUnfaithfulPatch","autoBind","hydration","defaults"],Ne=Object.freeze({disableReferrerDetection:!0,eventSourcePolicy:"parent-or-opener",skipUnchanged:!0,sanitizerPolicy:"strict"}),Te=Object.freeze({disableReferrerDetection:!1,eventSourcePolicy:"any",skipUnchanged:!1,sanitizerPolicy:"compat"}),Oe=ke.indexOf("defaults"),Re=[{key:"disableReferrerDetection",title:"Referrer trust is still on",effect:"the runtime accepts the admin referer as a preview signal.",condition:"no preview flow relies on the admin referer alone"},{key:"eventSourcePolicy",title:"Messages are accepted from any window",effect:"any window that passes the origin check may post updates.",condition:"no window but the parent or opener posts updates"},{key:"sanitizerPolicy",title:"Sanitizer is in compat mode",effect:"id and every data-* pass.",condition:"rich text no longer relies on `id` or `data-*`"},{key:"skipUnchanged",title:"Unchanged bindings are re-applied every message",effect:"every binding is written again on every message.",condition:"no renderer relies on running again for a value that did not change"}],Ee={profile:"The script was generated with `defaults: 'v1'`.",explicit:"The script sets it explicitly.",unmarked:"The script names no defaults, so its empty slot is read as the 1.x value."},Ae={code:"LP0709",level:"info",title:"Could not read the inline configuration for a v2 readiness check",detail:"The preview response carried no readable `__LIVE_PREVIEW_CONFIG__` inline script.",remedy:"Run this against a page with the inline runtime (not loader mode without a preview context). A preview behind authorizePreview serves it only to a request with credentials: pass them with --header, or a signed token as ?previewToken=… in the URL."},je={code:"LP0709",level:"info",title:"The inline configuration does not say which defaults it was generated against",detail:"Scripts carry a `defaults` marker from 2.0.0-rc.1 on; this one has none, so a 1.x or 2.0.0-beta.0 generator wrote it. An empty slot is read as its 1.x value, which is what a 1.x runtime runs.",remedy:"On 1.x the warnings stand as written. On 2.0.0-beta.0 an empty slot already runs its 2.0 value, so a warning about one does not apply there; upgrade and run `pll doctor --v2` again to read the marker."};function Ie(e){return"string"==typeof e?`'${e}'`:JSON.stringify(e)}function Ce(e,t,n){const r=`\`${t.key}: ${Ie(Ne[t.key])}\``;switch(e){case"profile":return`Set ${r} or drop \`defaults: 'v1'\` once ${t.condition}.`;case"explicit":return`Drop the explicit \`${t.key}: ${Ie(n)}\` once ${t.condition}; 2.0 defaults to ${r}.`;case"unmarked":return`Upgrading to 2.0 sets ${r}; check first that ${t.condition}.`}}function Ue(e,t,n){return{code:"LP0709",level:"warning",title:e.title,detail:`${e.key} is ${Ie(t)}: ${e.effect} ${Ee[n]}`,remedy:Ce(n,e,t)}}function qe(e){return{code:"LP0709",level:"info",title:"The inline configuration names defaults this doctor does not know",detail:`Its \`defaults\` marker is ${JSON.stringify(e)}; this version reads 'v1' and 'v2', so no row was judged.`,remedy:"Run the `pll doctor` of the package version that generated the page."}}var De="__LIVE_PREVIEW_CONFIG__",Fe=/\bdata-payload-field\s*=/gu,ze=/\bdata-payload-owner\s*=/gu,Me={error:0,warning:1,info:2},Be=/<script\b[^>]*>[\s\S]*?<\/script\b[^>]*>|<style\b[^>]*>[\s\S]*?<\/style\b[^>]*>|<!--[\s\S]*?-->/giu;function We(e){let t=e;for(;;){const e=t.replace(Be,"");if(e===t)return t;t=e}}function _e(e,t){return e.match(t)?.length??0}function Ge(e){if(void 0!==e)try{return new URL(e)}catch{return}}function Ke(e,t){const{publicResponse:n,previewResponse:r}=e,i=function(e){if(e.status>=300&&e.status<=399){const t=e.headers.location;return{code:"LP0708",level:"error",title:`The preview request was redirected (${String(e.status)})${void 0===t?"":` to ${t}`}`,detail:"The audit does not follow redirects: the page at the end of one is a different resource, usually a login or a canonical host, and judging it would say nothing about this URL.",remedy:"The request carried the intent parameter (?preview=true, or the --param name), the way the admin's iframe loads the page, so a rule that redirects on that query redirects the iframe too. A redirect to a login means the route needs authentication that a plain probe cannot supply: pass an editor's credentials with --header, or a signed token as ?previewToken=… in the URL. Probe the final URL directly only when the redirect has nothing to do with either."}}if(e.status<200||e.status>299)return{code:"LP0708",level:"error",title:`The preview request returned ${String(e.status)}, not a page`,detail:"Nothing below this can be judged: a status outside 2xx means the body is an error page or empty.",remedy:"Check the URL."};if(""===e.body.trim())return{code:"LP0708",level:"error",title:`The preview request returned ${String(e.status)} with an empty body`,detail:"A 2xx status with nothing in it — 204 and 205 are defined that way — is not a page, so its missing runtime and missing bindings say nothing.",remedy:"Point the audit at a route that renders a document."};const t=e.headers["content-type"];return void 0===t||t.toLowerCase().includes("html")?void 0:{code:"LP0708",level:"error",title:`The preview request returned ${t}, not HTML`,detail:"The audit reads a rendered page. A non-HTML response has no runtime and no bindings by definition, so reporting their absence would say nothing.",remedy:"Point the audit at a page route rather than an API or an asset."}}(r);if(void 0!==i)return{url:t.url,findings:[i],errors:1,warnings:0};const o=r.body.includes(De),s=[];return o||s.push(!0===t.credentials?{code:"LP0701",level:"warning",title:"No inline runtime in the preview response",detail:`The preview request returned ${String(r.status)} without the inline runtime, although it carried credentials (--header, or ?previewToken= in the URL). Three readings: those credentials were not accepted — expired, issued for another page, or not what authorizePreview reads — an adapter that did not recognise the request as a preview, or a consumer that starts LivePreviewClient itself.`,remedy:"Check that the credentials are current and are the ones authorizePreview reads; if you use an adapter, check its inject mode and previewSignals. If you start the client yourself, this line is expected."}:{code:"LP0701",level:"warning",title:"No inline runtime in the preview response",detail:`The preview request returned ${String(r.status)} without the inline runtime. Three readings, and this audit cannot tell them apart from the response alone: a preview behind authorizePreview — the strict 2.0 default — which answers a request without credentials exactly like this, an adapter that did not recognise the request as a preview, or a consumer that starts LivePreviewClient itself.`,remedy:"To audit a gated preview, send what an editor's browser sends: --header 'Cookie: payload-token=…' for a Payload session; for a signed token, the URL with ?previewToken=… (the default transport, dropped from the visitor request), or --header 'x-preview-token: …' where the strategy sets transport: { kind: 'header' }. Otherwise check the adapter's inject mode and previewSignals; if you start the client yourself, this line is expected."}),s.push(...function(e,t,n){const r=[],i=Ge(n.url),o=Ge(n.adminOrigin),s=void 0!==o&&i?.origin===o.origin,a=function(e){if(void 0!==e)for(const t of e.split(";")){const e=t.trim();if(/^frame-ancestors(?:\s|$)/iu.test(e))return e}}(e.headers["content-security-policy"]);if(t&&void 0===a)r.push({code:"LP0702",level:"warning",title:"Preview response declares no frame-ancestors",detail:"The runtime is injected but the response carries no frame-ancestors directive, so nothing states which origins may embed this page.",remedy:"Let the adapter manage CSP, or set frame-ancestors yourself to the admin origin. Without it you are relying on the absence of a policy."});else if(void 0!==a&&void 0!==n.adminOrigin){const e=void 0!==o&&void 0!==i&&function(e,t,n){const r=e.split(/\s+/u).slice(1).filter(e=>e.length>0).map(e=>e.toLowerCase());if(0===r.length||1===r.length&&"'none'"===r[0])return!1;for(const e of r)if("'self'"===e){if(xe(t,n))return!0}else{if("*"===e)return!0;if(!e.startsWith("'")&&Se(e,t,n))return!0}return!1}(a,o,i);e||r.push({code:"LP0702",level:"error",title:"frame-ancestors does not admit the admin origin",detail:void 0===o?`"${n.adminOrigin}" is not an absolute URL, so no source expression can admit it.`:`Served: "${a}". Expected it to allow ${o.origin}.`,remedy:"Add the admin origin to allowedOrigins so the adapter merges it into frame-ancestors, or add it to your own policy."})}const d=e.headers["x-frame-options"];if(void 0!==d&&(/deny/iu.test(d)||/sameorigin/iu.test(d)&&!s)){const e=void 0!==o||/deny/iu.test(d);r.push(e?{code:"LP0703",level:"error",title:`X-Frame-Options: ${d} blocks the preview iframe`,detail:"This header is older than CSP and browsers honour it independently. No frame-ancestors directive can override it.",remedy:"Remove X-Frame-Options for preview responses. It is usually set by a proxy or a security middleware rather than by the app."}:{code:"LP0703",level:"warning",title:`X-Frame-Options: ${d} blocks every frame from another origin`,detail:"This header is older than CSP and browsers honour it independently, and no frame-ancestors directive can override it. SAMEORIGIN refuses a frame from another origin only, and no admin origin was given: whether it blocks this preview depends on where the admin is served, which this probe cannot see.",remedy:"Re-run with --admin <origin> to have it judged. If the admin is on another origin, remove X-Frame-Options for preview responses; a proxy or a security middleware usually sets it."})}return r}(r,o,t)),s.push(...function(e,t,n){const r=[],i=_e(e,Fe),o=_e(t,Fe),s=_e(e,ze);o>0&&r.push({code:"LP0704",level:"warning",title:`${String(o)} binding attribute(s) served to anonymous visitors`,detail:"A request with no preview intent received data-payload-field attributes. These disclose the CMS field taxonomy, and any CSS keyed on them changes public layout the moment emission is gated.",remedy:"Gate binding emission on an authorized preview context — see createPreviewBindings(), whose suppressed form emits nothing at all."}),i>50&&r.push({code:"LP0705",level:"warning",title:`${String(i)} bindings exceed the default visibility gate`,detail:`Above visibilityGateThreshold (${String(50)}) the scheduler stops writing offscreen elements and buffers them until they scroll into view. On a page nobody scrolls, that is never.`,remedy:"Raise visibilityGateThreshold if the whole page must stay live, or confirm that deferring below the fold is acceptable here."}),n&&0===i&&r.push({code:"LP0707",level:"error",title:"Preview response carries no bindings",detail:"The runtime is present but there is not one data-payload-field element for it to write into, so no edit can ever be visible on this page.",remedy:"Add binding attributes to the markup. pll-codegen --inventory lists every field the schema makes addressable."});const a=function(e){const t=e.search(/\bdata-payload-owner\s*=/u);return-1===t?0:_e(e.slice(0,t),Fe)}(e);return s>0&&a>0&&r.push({code:"LP0706",level:"warning",title:`${String(a)} binding(s) outside every owner marker`,detail:`The page declares ${String(s)} owner marker(s), so owner scoping is in use. Bindings that belong to no owner receive nothing once scopeBindingsByOwner is on — they fail closed.`,remedy:"Give every binding an owning ancestor, or leave scopeBindingsByOwner off until they all have one. Counted before the first owner marker only, so the real number may be higher."}),r}(We(r.body),We(n.body),o)),n.body.includes(De)&&s.push({code:we.RuntimeOnPublicPage,level:"info",title:"Runtime is also served to anonymous visitors",detail:"A request with no preview intent received the inline runtime. That is correct for inject: 'always' and unintended for 'preview-only'.",remedy:""}),!0===t.v2&&s.push(...function(e){const t=function(e){const t=e.indexOf("var __LIVE_PREVIEW_CONFIG__=");if(-1===t)return;const n=t+28;if("["!==e[n])return;let r=0,i=!1,o="",s="";for(let t=n;t<e.length;t+=1){const n=e[t]??"";if(i)s+=n,"\\"===n?(s+=e[t+1]??"",t+=1):'"'===n&&(i=!1,o='"');else if('"'!==n){if(!/\s/u.test(n)&&((","===n&&(","===o||"["===o)||"]"===n&&","===o)&&(s+="null"),s+=n,o=n,"["===n&&(r+=1),"]"===n&&(r-=1,0===r)))break}else i=!0,s+=n}if(0===r)try{const e=JSON.parse(s);return Array.isArray(e)?e:void 0}catch{return}}(e.previewResponse.body);if(void 0===t)return[Ae];const n=t[Oe]??void 0;if(void 0!==n&&"v1"!==n&&"v2"!==n)return[qe(n)];const r=n,i="v2"===r?Ne:Te,o=Re.flatMap(e=>{const n=t[ke.indexOf(e.key)]??void 0,o=n??i[e.key];return o===Ne[e.key]?[]:[Ue(e,o,"v1"===r?"profile":void 0===n?"unmarked":"explicit")]});return void 0===r?[...o,je]:o}(e)),s.sort((e,t)=>Me[e.level]-Me[t.level]),{url:t.url,findings:s,errors:s.filter(e=>"error"===e.level).length,warnings:s.filter(e=>"warning"===e.level).length}}var Ve=["preview","draft","livePreview"];function He(e){const t=e.indexOf("#"),n=-1===t?"":e.slice(t),r=-1===t?e:e.slice(0,t),i=r.indexOf("?");return-1===i?{base:r,parts:[],hash:n}:{base:r.slice(0,i),parts:r.slice(i+1).split("&"),hash:n}}function Je(e){const t=e.indexOf("="),n=e=>{try{return decodeURIComponent(e.replace(/\+/gu," "))}catch{return e}};return-1===t?[n(e),""]:[n(e.slice(0,t)),n(e.slice(t+1))]}var Qe="previewToken";function Xe(e){const{base:t,parts:n,hash:r}=He(e),i=n.map(e=>{const t=e.indexOf("=");return-1===t||Je(e)[0]!==Qe?e:`${e.slice(0,t)}=…`});return i.some((e,t)=>e!==n[t])?`${t}?${i.join("&")}${r}`:e}function Ye(e){const t={};return e.forEach((e,n)=>{t[n.toLowerCase()]=e}),t}async function Ze(e,t){const n=e.body?.getReader();if(void 0===n)return e.text();const r=new TextDecoder;let i=0,o="";for(;;){const{done:e,value:s}=await n.read();if(e)break;if(i+=s.byteLength,i>t)throw await n.cancel(),new Error(`the response body exceeds ${String(t)} bytes, which is not a page the audit can judge`);o+=r.decode(s,{stream:!0})}return o+r.decode()}function et(e){try{return new URL(e).href}catch{return`${e.replace(/\/+$/u,"")}/`}}var tt=/^[^\s&=#?-][^\s&=#]*$/u,nt=/^([!#$%&'*+.^_`|~0-9A-Za-z-]+):[ \t]*(.*)$/u;function rt(e,t){const n=void 0===t||t.startsWith("-")||st(t)?null:nt.exec(t),r=n?.[1],i=n?.[2];void 0!==r&&void 0!==i?Object.keys(e.headers).some(e=>e.toLowerCase()===r.toLowerCase())?e.usageError??=`pll doctor: --header "${r}" is given twice; join the values into one header`:e.headers[r]=i:e.usageError??='pll doctor: --header takes "Name: value", such as --header "Cookie: payload-token=…"'}function it(e,t){void 0!==t&&tt.test(t)?e.params.push(t):e.usageError??="pll doctor: --param takes a query parameter name, such as --param draft"}var ot='pll doctor — audit what a live-preview deployment actually serves\npll migrate — rewrite 1.x APIs to their 2.0 names and homes\n\nUsage:\n pll doctor <url> [--admin <origin>] [--header <name: value>]... [--param <name>]... [--json] [--v2]\n pll migrate <path> [--write] [--only <id,id>]\n\nThe URL is fetched twice: once as an ordinary visitor, without any intent\nparameter, and once the way the Payload admin\'s iframe loads it, with\n?preview=true and the iframe\'s headers.\nMost findings come from the difference between the two responses. Redirects\nare reported, not followed.\n\nOptions of pll doctor:\n -a, --admin <origin> Admin origin the preview is embedded from. Enables the\n frame-ancestors check to verify the origin is admitted,\n not merely that a policy exists.\n -H, --header <h> A header for the preview request only, as "Name: value";\n repeat it for more. A preview behind authorizePreview\n needs an editor\'s credentials: a Payload session Cookie,\n or an x-preview-token where the token strategy sets\n transport: { kind: \'header\' }. A signed token travels in\n the URL by default, as ?previewToken=…, which the visitor\n request drops. The visitor request stays anonymous and\n values are never printed, but a shell keeps them in its\n history, so prefer a short-lived token.\n --param <name> A query parameter the deployment reads as preview intent,\n for an adapter whose previewQueryParams replaces the\n default preview, draft and livePreview; repeat it for\n more. The first one is what the preview request carries\n as <name>=true; none of them reaches the visitor request.\n --json Emit the report as JSON instead of text\n --v2 Also check the page against the 2.0 readiness table\n -h, --help Show this help\n\nExit codes of pll doctor:\n 0 no error-level findings\n 1 usage error, or the URL could not be fetched\n 2 at least one error-level finding\n\npll migrate has its own options and exit codes: pll migrate --help\n\nExamples:\n pll doctor https://example.com/\n pll doctor https://example.com/blog/hello --admin https://cms.example.com\n pll doctor "https://example.com/?previewToken=$PREVIEW_TOKEN" --v2\n pll doctor https://example.com/ --header "Cookie: payload-token=$PAYLOAD_TOKEN"\n';function st(e){try{return"null"!==new URL(e).origin}catch{return!1}}async function at(e,t){const[n,...r]=e;if(void 0===n||"-h"===n||"--help"===n)return process.stdout.write(ot),void 0===n?1:0;if("migrate"===n)return async function(e){const t=function(e){let t,n,r,i=!1,o=!1;const s=e=>e.split(",").filter(e=>e.length>0);for(let a=0;a<e.length;a+=1){const d=e[a];void 0!==d&&("-h"===d||"--help"===d?o=!0:"--write"===d?i=!0:"--only"===d?(n=s(e[a+1]??""),a+=1):d.startsWith("--only=")?n=s(d.slice(7)):d.startsWith("-")?r??=d:t??=d)}return{target:t,write:i,only:n,help:o,unknown:r}}(e);if(t.help)return process.stdout.write("pll migrate — rewrite 1.x APIs to their 2.0 names and homes (ADR 0007)\n\nUsage:\n pll migrate <path> [--write] [--only <id,id>]\n\nWithout --write the run only reports what it would change. Codemods touch\nonly names bound from payload-live-preview; anything they cannot rewrite\nsafely is listed as needing manual attention. Requires ts-morph.\n\nOptions:\n --write Apply the changes (otherwise dry-run)\n --only <ids> Run only these codemods (comma-separated); an id not\n listed below runs nothing\n -h, --help Show this help\n\nCodemods, in the order they run:\n rename-is-preview-request\n rename-admin-origins-option\n rename-bindings-authorized-option\n move-fetch-preview-helpers\n\nExit codes:\n 0 nothing needs a human (changes applied, or would be with --write)\n 1 usage error, unreadable path, or ts-morph is not installed\n 3 at least one file needs manual attention\n"),0;if(void 0!==t.unknown)return process.stderr.write(`pll migrate: unknown option ${t.unknown}\n`),1;if(void 0===t.target)return process.stderr.write("pll migrate: a path is required. Try `pll migrate --help`.\n"),1;let n;try{n=await async function(e,t={}){const n=t.io??{read:e=>o(e,"utf8"),write:(e,t)=>i(e,t,"utf8"),list:pe},r=[],s={};for(const i of await n.list(e)){const o=await n.read(i),{output:a,edits:d,conflicts:l}=de(o,{fileName:i,...void 0===t.only?{}:{only:t.only}}),c=a!==o;if(c&&!0===t.write&&await n.write(i,a),c)for(const e of d)s[e.codemod]=(s[e.codemod]??0)+1;r.push({file:fe(e,i),edits:d,changed:c,conflicts:l})}return{files:r,changedCount:r.filter(e=>e.changed).length,byCodemod:s,conflictCount:r.filter(e=>e.conflicts.length>0).length}}(t.target,{write:t.write,...void 0===t.only?{}:{only:t.only}})}catch(e){return process.stderr.write(`pll migrate: ${e instanceof Error?e.message:String(e)}\n`),1}for(const e of n.files)e.changed&&process.stdout.write(`${t.write?"migrated":"would migrate"} ${e.file} (${me(e)})\n`);process.stdout.write(`\n${t.write?"Migrated":"Would migrate"} ${String(n.changedCount)} file(s).${t.write?"":" Re-run with --write to apply."}\n`);for(const{id:e,notice:t}of oe)void 0!==t&&(n.byCodemod[e]??0)>0&&process.stdout.write(`\nNote (${e}): ${t}\n`);const r=n.files.filter(e=>e.conflicts.length>0);if(0===r.length)return 0;process.stdout.write(`\n${String(r.length)} file(s) need manual attention:\n`);for(const e of r)for(const t of e.conflicts){const n=void 0===t.line?e.file:`${e.file}:${String(t.line)}`;process.stdout.write(` ${n}: ${t.reason}\n`)}return 3}(r);if("doctor"!==n)return process.stderr.write(`pll: unknown command "${n}". Try \`pll --help\`.\n`),1;const s=function(e){const t={url:void 0,adminOrigin:void 0,json:!1,v2:!1,showHelp:!1,unknown:[],headers:{},usageError:void 0,params:[]};for(let n=0;n<e.length;n+=1){const r=e[n];void 0!==r&&("-h"===r||"--help"===r?t.showHelp=!0:"--json"===r?t.json=!0:"--v2"===r?t.v2=!0:"--admin"===r||"-a"===r?(t.adminOrigin=e[n+1],n+=1):r.startsWith("--admin=")?t.adminOrigin=r.slice(8):"--header"===r||"-H"===r?(rt(t,e[n+1]),n+=1):r.startsWith("--header=")?rt(t,r.slice(9)):"--param"===r?(it(t,e[n+1]),n+=1):r.startsWith("--param=")?it(t,r.slice(8)):r.startsWith("-")?t.unknown.push(r):t.url??=r)}return t}(r);if(s.showHelp)return process.stdout.write(ot),0;if(s.unknown.length>0)return process.stderr.write(`pll doctor: unknown option ${s.unknown.join(", ")}\n`),1;if(void 0===s.url)return process.stderr.write("pll doctor: a URL is required. Try `pll doctor --help`.\n"),1;if(void 0!==s.usageError)return process.stderr.write(`${s.usageError}\n`),1;if(void 0!==s.adminOrigin&&!st(s.adminOrigin))return process.stderr.write(`pll doctor: --admin must be an absolute URL such as https://cms.example.com (got "${s.adminOrigin}")\n`),1;let a;try{a=await async function(e){const t=e.fetchImpl??function(e={}){const t=e.timeoutMs??15e3,n=e.maxBodyBytes??10485760;return async(r,i)=>{const o=e.fetchFn??globalThis.fetch;let s;try{s=await o(r,{headers:i.headers,redirect:"manual",signal:AbortSignal.timeout(t)})}catch(e){if(e instanceof Error&&"TimeoutError"===e.name)throw new Error(`no response within ${String(t/1e3)} s`,{cause:e});throw e}return{status:s.status,headers:Ye(s.headers),body:await Ze(s,n)}}}(),n=void 0===e.previewQueryParams||0===e.previewQueryParams.length?Ve:e.previewQueryParams,r=await t(function(e,t){const{base:n,parts:r,hash:i}=He(e),o=/* @__PURE__ */new Set([...t,Qe]),s=r.filter(e=>!o.has(Je(e)[0]));return s.length===r.length?e:`${n}${0===s.length?"":`?${s.join("&")}`}${i}`}(e.url,n),{headers:{Accept:"text/html","Sec-Fetch-Dest":"document","Sec-Fetch-Mode":"navigate"}}),i={Accept:"text/html","Sec-Fetch-Dest":"iframe","Sec-Fetch-Mode":"navigate",...void 0===e.adminOrigin?{}:{Referer:et(e.adminOrigin)}},o=function(e,t){const n=new Set(Object.keys(t).map(e=>e.toLowerCase()));return Object.fromEntries(Object.entries(e??{}).filter(([e])=>!n.has(e.toLowerCase())))}(e.previewHeaders,i),s=await t(function(e,t){const{base:n,parts:r,hash:i}=He(e);if(r.some(e=>{const[n,r]=Je(e);return t.includes(n)&&function(e){return"true"===e||"1"===e}(r)}))return e;const o=r.join("&"),s=""===o?"?":o.endsWith("&")?"":"&",a=`${encodeURIComponent(t[0]??"preview")}=true`;return`${n}${0===r.length?"?":`?${o}${s}`}${a}${i}`}(e.url,n),{headers:{...o,...i}});return Ke({publicResponse:r,previewResponse:s},{url:Xe(e.url),adminOrigin:e.adminOrigin,...!0===e.v2?{v2:!0}:{},...Object.keys(o).length>0||(a=e.url,He(a).parts.some(e=>{const[t,n]=Je(e);return t===Qe&&""!==n}))?{credentials:!0}:{}});var a}({url:s.url,...void 0!==s.adminOrigin?{adminOrigin:s.adminOrigin}:{},...s.v2?{v2:!0}:{},...Object.keys(s.headers).length>0?{previewHeaders:s.headers}:{},...s.params.length>0?{previewQueryParams:s.params}:{},...void 0!==t?{fetchImpl:t}:{}})}catch(e){const t=function(e){if(!(e instanceof Error))return String(e);const t=e.cause;return t instanceof Error&&""!==t.message&&!e.message.includes(t.message)?`${e.message} (${t.message})`:e.message}(e),n=Xe(s.url);return s.json?process.stdout.write(`${JSON.stringify({url:n,error:t},void 0,2)}\n`):process.stderr.write(`pll doctor: could not probe ${n}: ${t}\n`),1}return process.stdout.write(s.json?`${JSON.stringify(a,void 0,2)}\n`:function(e){const t=[`pll doctor — ${e.url}`,""];if(0===e.findings.length)return t.push("No findings. The preview response carries the runtime, a frame-ancestors"),t.push("policy, and bindings; the public response carries none of them.",""),t.join("\n");for(const n of e.findings)t.push(`${ge[n.level]} ${n.code} ${n.title}`),t.push(` ${n.detail}`),""!==n.remedy&&t.push(` → ${n.remedy}`),t.push("");return t.push(`${String(e.errors)} error(s), ${String(e.warnings)} warning(s).`,""),t.join("\n")}(a)),a.errors>0?2:0}function dt(e=process.argv){if("undefined"==typeof process)return!1;const t=e[1];if(void 0===t||""===t)return!1;const n=t.split(/[\\/]/u).pop()??"";return"pll"===n||"pll.cmd"===n||n.startsWith("doctor-cli")}dt()&&at(process.argv.slice(2)).then(e=>{process.exit(e)});export{dt as isCliInvocation,at as run};
2
+ import{createRequire as e}from"module";import{relative as t,join as n,extname as r}from"path";import{writeFile as i,readFile as o,stat as s,readdir as a}from"fs/promises";var d,l,c="payload-live-preview";function u(){if(void 0===d)try{d=e(import.meta.url)("ts-morph")}catch(e){throw new Error("pll migrate needs ts-morph: npm install --save-dev ts-morph",{cause:e})}return d}function h(e,t){const n=u();return l??=new n.Project({useInMemoryFileSystem:!0,skipLoadingLibFiles:!0,skipFileDependencyResolution:!0,compilerOptions:{allowJs:!0,noLib:!0}}),l.createSourceFile(`/script.${t}`,e,{overwrite:!0})}function p(e){return e===c||e.startsWith(`${c}/`)}function f(e){const{Node:t,SyntaxKind:n}=u(),r=[];for(const t of e.getImportDeclarations()){const e=t.getModuleSpecifierValue();if(p(e))for(const n of t.getNamedImports()){const i=n.getAliasNode(),o=i??n.getNameNode();r.push({imported:n.getName(),local:o.getText(),specifier:e,kind:"import",importedNode:n.getNameNode(),aliased:void 0!==i,symbol:o.getSymbol(),declaration:t})}}for(const i of e.getDescendantsOfKind(n.VariableDeclaration)){const e=m(i.getInitializer()),n=i.getNameNode();if(void 0!==e&&p(e)&&t.isObjectBindingPattern(n))for(const o of n.getElements()){const n=o.getNameNode();if(!t.isIdentifier(n))continue;const s=o.getPropertyNameNode();r.push({imported:void 0===s?n.getText():g(s),local:n.getText(),specifier:e,kind:"require",importedNode:s??n,aliased:void 0!==s,symbol:n.getSymbol(),declaration:i})}}return r}function m(e){const{Node:t,SyntaxKind:n}=u(),r=void 0!==e&&t.isAwaitExpression(e)?e.getExpression():e;if(void 0===r||!t.isCallExpression(r))return;const i=r.getExpression();if((!t.isIdentifier(i)||"require"!==i.getText())&&i.getKind()!==n.ImportKeyword)return;const[o]=r.getArguments();return void 0!==o&&t.isStringLiteral(o)?o.getLiteralText():void 0}function g(e){const{Node:t}=u();return t.isStringLiteral(e)||t.isNoSubstitutionTemplateLiteral(e)?e.getLiteralText():e.getText()}function w(e){const{Node:t}=u();if(t.isSpreadAssignment(e))return;const n=e.getNameNode();return t.isComputedPropertyName(n)?void 0:g(n)}function v(e,t){const{Node:n,SyntaxKind:r}=u(),i=t.symbol?.compilerSymbol;if(void 0===i)return[];const o=e.getProject().getTypeChecker(),s=[];for(const a of e.getDescendantsOfKind(r.Identifier)){if(a.getText()!==t.local||y(a,t.declaration))continue;const e=a.getParent();n.isShorthandPropertyAssignment(e)?o.getShorthandAssignmentValueSymbol(e)?.compilerSymbol===i&&s.push({node:a,kind:"shorthand"}):n.isExportSpecifier(e)?e.getNameNode()===a&&e.getLocalTargetSymbol()?.compilerSymbol===i&&s.push({node:a,kind:"export"}):a.getSymbol()?.compilerSymbol===i&&s.push({node:a,kind:"reference"})}return s}function y(e,t){return void 0!==e.getFirstAncestor(e=>e===t)}function b(e,t,n=[]){const{SyntaxKind:r}=u();for(const i of e.getDescendantsOfKind(r.Identifier)){if(i.getText()!==t)continue;const e=i.getParent();if(P(e,i)&&!n.some(t=>t===e||y(e,t)))return e}}function P(e,t){const{Node:n}=u();return n.isVariableDeclaration(e)||n.isBindingElement(e)||n.isFunctionDeclaration(e)||n.isClassDeclaration(e)||n.isParameterDeclaration(e)||n.isEnumDeclaration(e)?e.getNameNode()===t:n.isImportSpecifier(e)?(e.getAliasNode()??e.getNameNode())===t:n.isImportClause(e)?e.getDefaultImport()===t:!!n.isNamespaceImport(e)&&e.getNameNode()===t}function $(e,t){return{start:e.getStart(),end:e.getEnd(),text:t}}function k(e,t){const n=[...t].sort((e,t)=>t.start-e.start);let r=e,i=Number.POSITIVE_INFINITY;for(const e of n){if(e.end>i)throw new Error("overlapping codemod edits");r=`${r.slice(0,e.start)}${e.text}${r.slice(e.end)}`,i=e.start}return r}var L="move-fetch-preview-helpers",x=`${c}/server`,S={fetchPreviewDocument:"fetchDocument",fetchPreviewGlobal:"fetchGlobal"},N=/* @__PURE__ */new Set(["serverURL","apiRoute","depth"]),T=/* @__PURE__ */new Set(["draft","fetchFn"]),O=["authorization","locale","headers","signal","errorMode"],R={fetchPreviewDocument:["collection","where",...O],fetchPreviewGlobal:["global",...O]};function E(e,t){return{codemod:L,reason:t,line:e}}function A(e,t,n){const r=[],i=[],o=[],s=/* @__PURE__ */new Set;for(const e of t.getProperties()){const t=w(e);void 0!==t&&s.add(t),void 0!==t&&N.has(t)?r.push(e.getText()):void 0!==t&&T.has(t)?o.push(t):i.push(e.getText())}s.has("depth")||r.push("depth: 1 /* TODO(pll migrate): the 1.x default; match the runtime mergeDepth */"),s.has("authorization")||i.push("authorization: null /* TODO(pll migrate): pass the verdict from authorizePreviewRequest(); null reads the published document */");const a=R[n]??[],d=[...s].filter(e=>!N.has(e)&&!T.has(e)&&!a.includes(e)),l=e.getTypeArguments().map(e=>e.getText()),c=0===l.length?"":`<${l.join(", ")}>`,u=S[n]??n,h=`definePreview({ ${r.join(", ")} }).${u}${c}({ ${i.join(", ")} })`,p=0===o.length?"":`, and ${o.join("/")} was dropped`,f=e.getStartLineNumber(),m=[E(f,`${n}() was rewritten onto definePreview().${u}(); it now returns a PreviewFetchResult (check ok/data) and needs a real authorization for drafts${p}`)];return d.length>0&&m.push(E(f,`${n}() was passed ${d.map(e=>`\`${e}\``).join(", ")}, which .${u}() does not accept; it takes ${a.join(", ")}. The key was carried over unchanged and will not compile — place it by hand`)),{edit:{start:e.getStart(),end:e.getEnd(),text:h},notes:m}}function j(e,t,n){return`import { ${t.join(", ")} } from ${e}${n}${e};`}var I={id:L,summary:"`fetchPreviewDocument`/`fetchPreviewGlobal` from the root → `definePreview().fetchDocument`/`.fetchGlobal` (payload-live-preview/server)",ledgerEntry:9,apply(e){const t=f(e).filter(e=>e.specifier===c&&e.imported in S);return 0===t.length?{edits:[],conflicts:[]}:function(e,t){const{Node:n}=u(),r=[],i=[],o=[];for(const s of t)if("require"!==s.kind)for(const t of v(e,s)){const e=t.node.getStartLineNumber(),a=t.node.getParent();if("reference"!==t.kind||!n.isCallExpression(a)||a.getExpression()!==t.node){r.push(E(e,`${s.local} is used other than as a direct call; rewrite it onto definePreview() by hand`));continue}const[d]=a.getArguments();if(void 0===d||!n.isObjectLiteralExpression(d)||d.getProperties().some(e=>n.isSpreadAssignment(e))){r.push(E(e,`${s.imported}() options are not a plain object literal, so serverURL/depth cannot be split out; rewrite it onto definePreview() by hand`));continue}const l=A(a,d,s.imported);o.push(l.edit),i.push(...l.notes)}else r.push(E(s.declaration.getStartLineNumber(),`${s.imported} is bound with require(); rewrite it onto definePreview() from ${x} by hand`));const s=e.getImportDeclarations().filter(e=>e.getModuleSpecifierValue()===x),a=b(e,"definePreview",s);return void 0!==a&&r.push(E(a.getStartLineNumber(),`this module already binds a definePreview that is not ${x}'s; rename it, then move the fetch helpers by hand`)),r.length>0?{edits:[],conflicts:[...r,...i]}:(o.push(...function(e,t){const{Node:n}=u(),r=[],i=/* @__PURE__ */new Set;for(const e of t)n.isImportDeclaration(e.declaration)&&i.add(e.declaration);const o=e.getImportDeclarations().find(e=>e.getModuleSpecifierValue()===x&&!e.isTypeOnly()),s=!0===o?.getNamedImports().some(e=>"definePreview"===e.getName());let a;if(void 0!==o&&!s){const e=o.getModuleSpecifier().getQuoteKind(),t=[...o.getNamedImports().map(e=>e.getText()),"definePreview"],n=o.getDefaultImport()?.getText(),i=void 0===n?t.join(", "):`${n}, { ${t.join(", ")} }`,s=void 0===n?j(e,t,x):`import ${i} from ${e}${x}${e};`;r.push({start:o.getStart(),end:o.getEnd(),text:s})}for(const t of i){const n=t.getModuleSpecifier().getQuoteKind(),i=t.getNamedImports().filter(e=>!(e.getName()in S)).map(e=>e.getText()),s=t.getDefaultImport()?.getText(),d=[s,0===i.length?void 0:`{ ${i.join(", ")} }`].filter(e=>void 0!==e),l=t.isTypeOnly()?"type ":"",u=0===d.length?"":`import ${l}${d.join(", ")} from ${n}${c}${n};`;if(void 0===o&&void 0===a)a=j(n,["definePreview"],x),r.push({start:t.getStart(),end:t.getEnd(),text:""===u?a:`${u}\n${a}`});else{const n=t.getEnd(),i=""===u&&"\n"===e.getFullText()[n]?1:0;r.push({start:t.getStart(),end:n+i,text:u})}}return r}(e,t)),{edits:o,conflicts:i})}(e,t)}},U="rename-admin-origins-option",C="hasPreviewIntent",q="adminOrigins",D="allowedOrigins",F=`if they carry \`${q}\`, rename it to \`${D}\``,z={id:U,summary:"`hasPreviewIntent(request, { adminOrigins })` → `{ allowedOrigins }`",ledgerEntry:13,apply(e){const{Node:t}=u(),n=[],r=[],i=f(e).filter(e=>e.imported===C);for(const o of i)for(const i of v(e,o)){const e=i.node.getParent();if("reference"!==i.kind||!t.isCallExpression(e))continue;if(e.getExpression()!==i.node)continue;const o=e.getArguments()[1];if(void 0===o)continue;const s=o.getStartLineNumber();if(!t.isObjectLiteralExpression(o)){r.push({codemod:U,line:s,reason:`${C}() options are not a literal; ${F}`});continue}const a=o.getProperties(),d=a.map(e=>w(e));if(d.includes(q)&&d.includes(D))r.push({codemod:U,line:s,reason:`${C}() is given both ${q} and ${D}; ${D} wins, drop ${q} by hand`});else for(const e of a)if(t.isSpreadAssignment(e))r.push({codemod:U,line:e.getStartLineNumber(),reason:`${C}() spreads its options; ${F}`});else{if(w(e)!==q)continue;t.isShorthandPropertyAssignment(e)?n.push($(e,`${D}: ${q}`)):t.isPropertyAssignment(e)&&n.push($(e.getNameNode(),D))}}return{edits:n,conflicts:r}}},M="rename-bindings-authorized-option",W="authorized",B="authorization",_=`if they carry \`${W}\`, rename it to \`${B}\` and pass the verdict from authorizePreviewRequest()`,G=`\`${B}\` takes the context from authorizePreviewRequest(); the boolean 1.x accepted is not. The key was renamed and its value left as it stands — pass the verdict, or \`null\` for a public response`,K={id:M,summary:"`createPreviewBindings({ authorized })` → `{ authorization }`",ledgerEntry:7,apply(e){const{Node:t}=u(),n=[],r=[],i=f(e).filter(e=>"createPreviewBindings"===e.imported);for(const o of i)for(const i of v(e,o)){const e=i.node.getParent();if("reference"!==i.kind||!t.isCallExpression(e))continue;if(e.getExpression()!==i.node)continue;const[o]=e.getArguments();if(void 0===o)continue;const s=o.getStartLineNumber();if(t.isObjectLiteralExpression(o))for(const e of o.getProperties())if(t.isSpreadAssignment(e))r.push({codemod:M,line:e.getStartLineNumber(),reason:`createPreviewBindings() spreads its options; ${_}`});else{if(w(e)!==W)continue;if(t.isShorthandPropertyAssignment(e))n.push($(e,`${B}: ${W}`)),r.push({codemod:M,line:e.getStartLineNumber(),reason:G});else if(t.isPropertyAssignment(e)){const i=e.getInitializer();if(void 0!==i&&t.isFalseLiteral(i)){n.push($(e,`${B}: null`));continue}n.push($(e.getNameNode(),B)),r.push({codemod:M,line:e.getStartLineNumber(),reason:G})}}else r.push({codemod:M,line:s,reason:`createPreviewBindings() options are not a literal; ${_}`})}return{edits:n,conflicts:r}}},V="rename-is-preview-request",H="isPreviewRequest",Q="hasPreviewIntent";function J(e,t){return{codemod:V,reason:t,line:e}}function X(e){return e.aliased&&e.local===Q?$(e.importedNode.getParentOrThrow(),Q):$(e.importedNode,Q)}var Y={id:V,summary:"`isPreviewRequest()` → `hasPreviewIntent()` (same signature)",ledgerEntry:1,notice:"hasPreviewIntent() takes the options isPreviewRequest() took and, without `signals`, counts the same three: a preview query parameter, Sec-Fetch-Dest: iframe and an admin Referer. The 2.0 adapters count only the query; where a call should agree with them, pass { signals: ['query'] } (docs/migration.md).",apply(e){const t=f(e).filter(e=>e.imported===H);return 0===t.length?{edits:[],conflicts:[]}:function(e,t){const n=[],r=[],i=b(t,Q,e.map(e=>e.declaration));void 0!==i&&n.push(J(i.getStartLineNumber(),`this module already binds ${Q}; rename it (or drop the wrapper and import the package's ${Q} directly), then rename ${H} by hand`));for(const i of e)if(r.push(X(i)),!i.aliased)for(const e of v(t,i))"reference"===e.kind?r.push($(e.node,Q)):"shorthand"===e.kind?n.push(J(e.node.getStartLineNumber(),`{ ${H} } keeps the old key for whoever reads it; write { ${H}: ${Q} } or rename the key and its readers by hand`)):n.push(J(e.node.getStartLineNumber(),`${H} is re-exported under its old name; rename the export and its importers, or write export { ${Q} as ${H} }`));const o=function(e,t){const{Node:n,SyntaxKind:r}=u();return e.getDescendantsOfKind(r.Identifier).filter(e=>{const r=e.getParent();return e.getText()===t&&n.isPropertyAccessExpression(r)&&r.getNameNode()===e})}(t,H).map(e=>J(e.getStartLineNumber(),`.${H} is a member of this module's own object, not the package import, and was left alone; check that it does not wrap the removed API`));return n.length>0?{edits:[],conflicts:[...n,...o]}:{edits:r,conflicts:o}}(t,e)}},Z={".ts":"ts",".mts":"ts",".cts":"ts",".tsx":"tsx",".js":"js",".mjs":"js",".cjs":"js",".jsx":"jsx"},ee=/* @__PURE__ */new Set([".astro",".vue",".svelte"]),te=/^---\r?\n([\s\S]*?)\r?\n---/u,ne=/<script(?:\s[^>]*)?>([\s\S]*?)<\/script\b[^>]*>/giu,re=/(?:\bfrom\s*|\bimport\s*\(?\s*|\brequire\s*\(\s*)['"]payload-live-preview(?:\/[^'"]*)?['"]/u,ie=[Y,z,K,I],oe=ie;function se(e,t){let n=1;for(let r=0;r<t;r+=1)"\n"===e[r]&&(n+=1);return n}function ae(e,t,n){const r=e.split("\n"),i=t.split("\n");let o=0;for(;o<r.length&&o<i.length&&r[o]===i[o];)o+=1;let s=0;for(;s<r.length-o&&s<i.length-o&&r[r.length-1-s]===i[i.length-1-s];)s+=1;const a=r.slice(o,r.length-s),d=i.slice(o,i.length-s),l=[];for(let e=0;e<Math.max(a.length,d.length);e+=1){const t=a[e]??"",r=d[e]??"";t!==r&&l.push({line:n+o+e,before:t,after:r})}return l}function de(e,t={}){const n=void 0===t.only?ie:ie.filter(e=>t.only?.includes(e.id));if(0===n.length||!function(e){return re.test(e)}(e))return{output:e,edits:[],conflicts:[]};const i=/* @__PURE__ */new Map,o=[];let s="",a=0;for(const d of function(e,t){const n=r(t).toLowerCase();if(!ee.has(n))return[{start:0,end:e.length,kind:Z[n]??"ts"}];const i=[],o=".astro"===n?te.exec(e):null;if(void 0!==o?.[1]){const e=o.index+o[0].indexOf("\n")+1;i.push({start:e,end:e+o[1].length,kind:"ts"})}for(const t of e.matchAll(ne)){const e=t[1]??"";if(""===e.trim())continue;const n=t.index+t[0].lastIndexOf(e);i.push({start:n,end:n+e.length,kind:"ts"})}return i}(e,t.fileName??"source.ts")){s+=e.slice(a,d.start);const t=se(e,d.start);let r=e.slice(d.start,d.end);for(const e of n){const n=e.apply(h(r,d.kind));for(const e of n.conflicts)o.push(void 0===e.line?e:{...e,line:e.line+t-1});if(0===n.edits.length)continue;const s=k(r,n.edits),a=i.get(e.id)??[];a.push(...ae(r,s,t)),i.set(e.id,a),r=s}s+=r,a=d.end}return s+=e.slice(a),{output:s,edits:[...i].map(([e,t])=>({codemod:e,count:t.length,lines:t})),conflicts:o}}var le=/* @__PURE__ */new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".astro",".svelte",".vue"]),ce=/\.d\.[cm]?ts$/u,ue=/* @__PURE__ */new Set(["node_modules","dist",".git",".astro",".svelte-kit",".next",".nuxt","coverage"]);function he(e){return le.has(r(e))&&!ce.test(e)}async function pe(e){const t=[];return(await s(e)).isDirectory()?await async function e(r){for(const i of await a(r,{withFileTypes:!0})){const o=n(r,i.name);i.isDirectory()?ue.has(i.name)||await e(o):he(i.name)&&t.push(o)}}(e):he(e)&&t.push(e),t.sort()}function fe(e,n){const r=t(e,n);return 0===r.length?n:r}function me(e){return e.edits.map(e=>`${e.codemod}: ${String(e.count)} line(s)`).join(", ")}var ge={error:"ERROR",warning:"WARN ",info:"INFO "},we=Object.freeze({NoTrustedOrigin:"LP0101",ReferrerOnlyTrust:"LP0102",PluginIncompatible:"LP0103",ProfileFeatureOmitted:"LP0104",OrphanField:"LP0201",UnattributableUpdate:"LP0202",UnboundField:"LP0203",VisibilityGateDeferred:"LP0301",UnsafeAttributeWrite:"LP0401",TextTargetHasChildren:"LP0402",MissingArrayTemplate:"LP0403",StructuralItemUnkeyed:"LP0404",StructuralDuplicateKey:"LP0405",StructuralUnstableKeys:"LP0406",UnsupportedStrategy:"LP0407",UnknownValueFormat:"LP0408",SanitizerDroppedAttribute:"LP0409",UnrenderedBlockKept:"LP0410",UnfaithfulPatch:"LP0411",ServerFormatReplaced:"LP0412",UnrenderedBlockLost:"LP0413",MessageRejected:"LP0501",TokenRejected:"LP0502",ProtocolShapeUnknown:"LP0503",HandlerThrew:"LP0601",TransformThrew:"LP0602",RendererThrew:"LP0603",StartupFailed:"LP0605",ReadyFailed:"LP0606",HydrationWaitTimedOut:"LP0607",AuditRuntimeMissing:"LP0701",AuditNoFrameAncestors:"LP0702",AuditFrameOptionsBlocks:"LP0703",AuditBindingsExposed:"LP0704",AuditGateThresholdExceeded:"LP0705",AuditUnownedBindings:"LP0706",AuditNoBindings:"LP0707",AuditNotAPage:"LP0708",FragmentRequestFailed:"LP0801",FragmentResponseInvalid:"LP0802",FragmentUnauthorized:"LP0803",FragmentSuperseded:"LP0804",RouteRefreshLoop:"LP0805",FragmentStrategyUnavailable:"LP0806",UnboundChangeRefresh:"LP0807",EscalationUnavailable:"LP0808",V2ReadinessGap:"LP0709",RuntimeOnPublicPage:"LP0710"}),ve={http:"80",https:"443",ws:"80",wss:"443"},ye=/^([a-z][a-z0-9+.-]*):$/u,be=/^(?:([a-z][a-z0-9+.-]*):\/\/)?(\*|(?:\*\.)?[a-z0-9-]+(?:\.[a-z0-9-]+)*\.?)(?::(\*|\d+))?(?:\/.*)?$/u;function Pe(e){return e.protocol.slice(0,-1).toLowerCase()}function $e(e){return""===e.port?ve[Pe(e)]??"":e.port}function ke(e,t){return e===t||"http"===e&&"https"===t||"ws"===e&&"wss"===t}function Le(e,t){if(e.hostname!==t.hostname)return!1;const n=Pe(e),r=Pe(t);return(n===r||"http"===r&&"https"===n)&&($e(e)===$e(t)||""===e.port&&""===t.port)}function xe(e,t,n){const r=ye.exec(e);if(void 0!==r?.[1])return ke(r[1],Pe(t));const i=be.exec(e);if(null===i)return!1;const o=i[1],s=i[2]??"",a=i[3];return!!ke(o??Pe(n),Pe(t))&&!!function(e,t){if("*"===e)return!0;const n=e.replace(/\.$/u,""),r=t.replace(/\.$/u,"");return n.startsWith("*.")?r.endsWith(n.slice(1))&&r.length>n.length-1:n===r}(s,t.hostname)&&(void 0===a?""===t.port:"*"===a||a===$e(t))}var Se=["allowedOrigins","serverURL","apiRoute","mergeDepth","debug","debounceMs","enableA11y","heartbeatMs","disableVisibilityGate","visibilityGateThreshold","intersectionRootMargin","disableReferrerDetection","disableLocalhostMatching","scopeBindingsByOwner","skipUnchanged","eventSourcePolicy","sanitizerPolicy","fragmentEndpoint","revealEditedField","routeStrategy","onUnboundChange","onUnfaithfulPatch","autoBind","hydration","defaults"],Ne=Object.freeze({disableReferrerDetection:!0,eventSourcePolicy:"parent-or-opener",skipUnchanged:!0,sanitizerPolicy:"strict"}),Te=Object.freeze({disableReferrerDetection:!1,eventSourcePolicy:"any",skipUnchanged:!1,sanitizerPolicy:"compat"}),Oe=Se.indexOf("defaults"),Re=[{key:"disableReferrerDetection",title:"Referrer trust is still on",effect:"the runtime accepts the admin referer as a preview signal.",condition:"no preview flow relies on the admin referer alone"},{key:"eventSourcePolicy",title:"Messages are accepted from any window",effect:"any window that passes the origin check may post updates.",condition:"no window but the parent or opener posts updates"},{key:"sanitizerPolicy",title:"Sanitizer is in compat mode",effect:"id and every data-* pass.",condition:"rich text no longer relies on `id` or `data-*`"},{key:"skipUnchanged",title:"Unchanged bindings are re-applied every message",effect:"every binding is written again on every message.",condition:"no renderer relies on running again for a value that did not change"}],Ee={profile:"The script was generated with `defaults: 'v1'`.",explicit:"The script sets it explicitly.",unmarked:"The script names no defaults, so its empty slot is read as the 1.x value."},Ae={code:"LP0709",level:"info",title:"Could not read the inline configuration for a v2 readiness check",detail:"The preview response carried no readable `__LIVE_PREVIEW_CONFIG__` inline script.",remedy:"Run this against a page with the inline runtime (not loader mode without a preview context). A preview behind authorizePreview serves it only to a request with credentials: pass them with --header, or a signed token as ?previewToken=… in the URL."},je={code:"LP0709",level:"info",title:"The inline configuration does not say which defaults it was generated against",detail:"Scripts carry a `defaults` marker from 2.0.0-rc.1 on; this one has none, so a 1.x or 2.0.0-beta.0 generator wrote it. An empty slot is read as its 1.x value, which is what a 1.x runtime runs.",remedy:"On 1.x the warnings stand as written. On 2.0.0-beta.0 an empty slot already runs its 2.0 value, so a warning about one does not apply there; upgrade and run `pll doctor --v2` again to read the marker."};function Ie(e){return"string"==typeof e?`'${e}'`:JSON.stringify(e)}function Ue(e,t,n){const r=`\`${t.key}: ${Ie(Ne[t.key])}\``;switch(e){case"profile":return`Set ${r} or drop \`defaults: 'v1'\` once ${t.condition}.`;case"explicit":return`Drop the explicit \`${t.key}: ${Ie(n)}\` once ${t.condition}; 2.0 defaults to ${r}.`;case"unmarked":return`Upgrading to 2.0 sets ${r}; check first that ${t.condition}.`}}function Ce(e,t,n){return{code:"LP0709",level:"warning",title:e.title,detail:`${e.key} is ${Ie(t)}: ${e.effect} ${Ee[n]}`,remedy:Ue(n,e,t)}}function qe(e){return{code:"LP0709",level:"info",title:"The inline configuration names defaults this doctor does not know",detail:`Its \`defaults\` marker is ${JSON.stringify(e)}; this version reads 'v1' and 'v2', so no row was judged.`,remedy:"Run the `pll doctor` of the package version that generated the page."}}var De="__LIVE_PREVIEW_CONFIG__",Fe=/\bdata-payload-field\s*=/gu,ze=/\bdata-payload-owner\s*=/gu,Me={error:0,warning:1,info:2},We=/<script\b[^>]*>[\s\S]*?<\/script\b[^>]*>|<style\b[^>]*>[\s\S]*?<\/style\b[^>]*>|<!--[\s\S]*?-->/giu;function Be(e){let t=e;for(;;){const e=t.replace(We,"");if(e===t)return t;t=e}}function _e(e,t){return e.match(t)?.length??0}function Ge(e){if(void 0!==e)try{return new URL(e)}catch{return}}function Ke(e,t){const{publicResponse:n,previewResponse:r}=e,i=function(e){if(e.status>=300&&e.status<=399){const t=e.headers.location;return{code:"LP0708",level:"error",title:`The preview request was redirected (${String(e.status)})${void 0===t?"":` to ${t}`}`,detail:"The audit does not follow redirects: the page at the end of one is a different resource, usually a login or a canonical host, and judging it would say nothing about this URL.",remedy:"The request carried the intent parameter (?preview=true, or the --param name), the way the admin's iframe loads the page, so a rule that redirects on that query redirects the iframe too. A redirect to a login means the route needs authentication that a plain probe cannot supply: pass an editor's credentials with --header, or a signed token as ?previewToken=… in the URL. Probe the final URL directly only when the redirect has nothing to do with either."}}if(e.status<200||e.status>299)return{code:"LP0708",level:"error",title:`The preview request returned ${String(e.status)}, not a page`,detail:"Nothing below this can be judged: a status outside 2xx means the body is an error page or empty.",remedy:"Check the URL."};if(""===e.body.trim())return{code:"LP0708",level:"error",title:`The preview request returned ${String(e.status)} with an empty body`,detail:"A 2xx status with nothing in it — 204 and 205 are defined that way — is not a page, so its missing runtime and missing bindings say nothing.",remedy:"Point the audit at a route that renders a document."};const t=e.headers["content-type"];return void 0===t||t.toLowerCase().includes("html")?void 0:{code:"LP0708",level:"error",title:`The preview request returned ${t}, not HTML`,detail:"The audit reads a rendered page. A non-HTML response has no runtime and no bindings by definition, so reporting their absence would say nothing.",remedy:"Point the audit at a page route rather than an API or an asset."}}(r);if(void 0!==i)return{url:t.url,findings:[i],errors:1,warnings:0};const o=r.body.includes(De),s=[];return o||s.push(!0===t.credentials?{code:"LP0701",level:"warning",title:"No inline runtime in the preview response",detail:`The preview request returned ${String(r.status)} without the inline runtime, although it carried credentials (--header, or ?previewToken= in the URL). Three readings: those credentials were not accepted — expired, issued for another page, or not what authorizePreview reads — an adapter that did not recognise the request as a preview, or a consumer that starts LivePreviewClient itself.`,remedy:"Check that the credentials are current and are the ones authorizePreview reads; if you use an adapter, check its inject mode and previewSignals. If you start the client yourself, this line is expected."}:{code:"LP0701",level:"warning",title:"No inline runtime in the preview response",detail:`The preview request returned ${String(r.status)} without the inline runtime. Three readings, and this audit cannot tell them apart from the response alone: a preview behind authorizePreview — the strict 2.0 default — which answers a request without credentials exactly like this, an adapter that did not recognise the request as a preview, or a consumer that starts LivePreviewClient itself.`,remedy:"To audit a gated preview, send what an editor's browser sends: --header 'Cookie: payload-token=…' for a Payload session; for a signed token, the URL with ?previewToken=… (the default transport, dropped from the visitor request), or --header 'x-preview-token: …' where the strategy sets transport: { kind: 'header' }. Otherwise check the adapter's inject mode and previewSignals; if you start the client yourself, this line is expected."}),s.push(...function(e,t,n){const r=[],i=Ge(n.url),o=Ge(n.adminOrigin),s=void 0!==o&&i?.origin===o.origin,a=function(e){if(void 0!==e)for(const t of e.split(";")){const e=t.trim();if(/^frame-ancestors(?:\s|$)/iu.test(e))return e}}(e.headers["content-security-policy"]);if(t&&void 0===a)r.push({code:"LP0702",level:"warning",title:"Preview response declares no frame-ancestors",detail:"The runtime is injected but the response carries no frame-ancestors directive, so nothing states which origins may embed this page.",remedy:"Let the adapter manage CSP, or set frame-ancestors yourself to the admin origin. Without it you are relying on the absence of a policy."});else if(void 0!==a&&void 0!==n.adminOrigin){const e=void 0!==o&&void 0!==i&&function(e,t,n){const r=e.split(/\s+/u).slice(1).filter(e=>e.length>0).map(e=>e.toLowerCase());if(0===r.length||1===r.length&&"'none'"===r[0])return!1;for(const e of r)if("'self'"===e){if(Le(t,n))return!0}else{if("*"===e)return!0;if(!e.startsWith("'")&&xe(e,t,n))return!0}return!1}(a,o,i);e||r.push({code:"LP0702",level:"error",title:"frame-ancestors does not admit the admin origin",detail:void 0===o?`"${n.adminOrigin}" is not an absolute URL, so no source expression can admit it.`:`Served: "${a}". Expected it to allow ${o.origin}.`,remedy:"Add the admin origin to allowedOrigins so the adapter merges it into frame-ancestors, or add it to your own policy."})}const d=e.headers["x-frame-options"];if(void 0!==d&&(/deny/iu.test(d)||/sameorigin/iu.test(d)&&!s)){const e=void 0!==o||/deny/iu.test(d);r.push(e?{code:"LP0703",level:"error",title:`X-Frame-Options: ${d} blocks the preview iframe`,detail:"This header is older than CSP and browsers honour it independently. No frame-ancestors directive can override it.",remedy:"Remove X-Frame-Options for preview responses. It is usually set by a proxy or a security middleware rather than by the app."}:{code:"LP0703",level:"warning",title:`X-Frame-Options: ${d} blocks every frame from another origin`,detail:"This header is older than CSP and browsers honour it independently, and no frame-ancestors directive can override it. SAMEORIGIN refuses a frame from another origin only, and no admin origin was given: whether it blocks this preview depends on where the admin is served, which this probe cannot see.",remedy:"Re-run with --admin <origin> to have it judged. If the admin is on another origin, remove X-Frame-Options for preview responses; a proxy or a security middleware usually sets it."})}return r}(r,o,t)),s.push(...function(e,t,n){const r=[],i=_e(e,Fe),o=_e(t,Fe),s=_e(e,ze);o>0&&r.push({code:"LP0704",level:"warning",title:`${String(o)} binding attribute(s) served to anonymous visitors`,detail:"A request with no preview intent received data-payload-field attributes. These disclose the CMS field taxonomy, and any CSS keyed on them changes public layout the moment emission is gated.",remedy:"Gate binding emission on an authorized preview context — see createPreviewBindings(), whose suppressed form emits nothing at all."}),i>50&&r.push({code:"LP0705",level:"warning",title:`${String(i)} bindings exceed the default visibility gate`,detail:`Above visibilityGateThreshold (${String(50)}) the scheduler stops writing offscreen elements and buffers them until they scroll into view. On a page nobody scrolls, that is never.`,remedy:"Raise visibilityGateThreshold if the whole page must stay live, or confirm that deferring below the fold is acceptable here."}),n&&0===i&&r.push({code:"LP0707",level:"error",title:"Preview response carries no bindings",detail:"The runtime is present but there is not one data-payload-field element for it to write into, so no edit can ever be visible on this page.",remedy:"Add binding attributes to the markup. pll-codegen --inventory lists every field the schema makes addressable."});const a=function(e){const t=e.search(/\bdata-payload-owner\s*=/u);return-1===t?0:_e(e.slice(0,t),Fe)}(e);return s>0&&a>0&&r.push({code:"LP0706",level:"warning",title:`${String(a)} binding(s) outside every owner marker`,detail:`The page declares ${String(s)} owner marker(s), so owner scoping is in use. Bindings that belong to no owner receive nothing once scopeBindingsByOwner is on — they fail closed.`,remedy:"Give every binding an owning ancestor, or leave scopeBindingsByOwner off until they all have one. Counted before the first owner marker only, so the real number may be higher."}),r}(Be(r.body),Be(n.body),o)),n.body.includes(De)&&s.push({code:we.RuntimeOnPublicPage,level:"info",title:"Runtime is also served to anonymous visitors",detail:"A request with no preview intent received the inline runtime. That is correct for inject: 'always' and unintended for 'preview-only'.",remedy:""}),!0===t.v2&&s.push(...function(e){const t=function(e){const t=e.indexOf("var __LIVE_PREVIEW_CONFIG__=");if(-1===t)return;const n=t+28;if("["!==e[n])return;let r=0,i=!1,o="",s="";for(let t=n;t<e.length;t+=1){const n=e[t]??"";if(i)s+=n,"\\"===n?(s+=e[t+1]??"",t+=1):'"'===n&&(i=!1,o='"');else if('"'!==n){if(!/\s/u.test(n)&&((","===n&&(","===o||"["===o)||"]"===n&&","===o)&&(s+="null"),s+=n,o=n,"["===n&&(r+=1),"]"===n&&(r-=1,0===r)))break}else i=!0,s+=n}if(0===r)try{const e=JSON.parse(s);return Array.isArray(e)?e:void 0}catch{return}}(e.previewResponse.body);if(void 0===t)return[Ae];const n=t[Oe]??void 0;if(void 0!==n&&"v1"!==n&&"v2"!==n)return[qe(n)];const r=n,i="v2"===r?Ne:Te,o=Re.flatMap(e=>{const n=t[Se.indexOf(e.key)]??void 0,o=n??i[e.key];return o===Ne[e.key]?[]:[Ce(e,o,"v1"===r?"profile":void 0===n?"unmarked":"explicit")]});return void 0===r?[...o,je]:o}(e)),s.sort((e,t)=>Me[e.level]-Me[t.level]),{url:t.url,findings:s,errors:s.filter(e=>"error"===e.level).length,warnings:s.filter(e=>"warning"===e.level).length}}var Ve=["preview","draft","livePreview"];function He(e){const t=e.indexOf("#"),n=-1===t?"":e.slice(t),r=-1===t?e:e.slice(0,t),i=r.indexOf("?");return-1===i?{base:r,parts:[],hash:n}:{base:r.slice(0,i),parts:r.slice(i+1).split("&"),hash:n}}function Qe(e){const t=e.indexOf("="),n=e=>{try{return decodeURIComponent(e.replace(/\+/gu," "))}catch{return e}};return-1===t?[n(e),""]:[n(e.slice(0,t)),n(e.slice(t+1))]}var Je="previewToken";function Xe(e,t=Je){const{base:n,parts:r,hash:i}=He(e),o=r.map(e=>{const n=e.indexOf("=");return-1===n||Qe(e)[0]!==t?e:`${e.slice(0,n)}=…`});return o.some((e,t)=>e!==r[t])?`${n}?${o.join("&")}${i}`:e}function Ye(e,t){return He(e).parts.some(e=>{const[n,r]=Qe(e);return n===t&&""!==r})}function Ze(e){const t={};return e.forEach((e,n)=>{t[n.toLowerCase()]=e}),t}async function et(e,t){const n=e.body?.getReader();if(void 0===n)return e.text();const r=new TextDecoder;let i=0,o="";for(;;){const{done:e,value:s}=await n.read();if(e)break;if(i+=s.byteLength,i>t)throw await n.cancel(),new Error(`the response body exceeds ${String(t)} bytes, which is not a page the audit can judge`);o+=r.decode(s,{stream:!0})}return o+r.decode()}function tt(e){try{return new URL(e).href}catch{return`${e.replace(/\/+$/u,"")}/`}}var nt=/^[^\s&=#?-][^\s&=#]*$/u,rt=/^([!#$%&'*+.^_`|~0-9A-Za-z-]+):[ \t]*(.*)$/u;function it(e,t){const n=void 0===t||t.startsWith("-")||dt(t)?null:rt.exec(t),r=n?.[1],i=n?.[2];void 0!==r&&void 0!==i?Object.keys(e.headers).some(e=>e.toLowerCase()===r.toLowerCase())?e.usageError??=`pll doctor: --header "${r}" is given twice; join the values into one header`:e.headers[r]=i:e.usageError??='pll doctor: --header takes "Name: value", such as --header "Cookie: payload-token=…"'}function ot(e,t){void 0!==t&&nt.test(t)?e.params.push(t):e.usageError??="pll doctor: --param takes a query parameter name, such as --param draft"}function st(e,t){void 0!==t&&nt.test(t)?e.tokenParam=t:e.usageError??="pll doctor: --token-param takes a query parameter name, such as --token-param lpt"}var at='pll doctor — audit what a live-preview deployment actually serves\npll migrate — rewrite 1.x APIs to their 2.0 names and homes\n\nUsage:\n pll doctor <url> [--admin <origin>] [--header <name: value>]... [--param <name>]...\n [--token-param <name>] [--json] [--v2]\n pll migrate <path> [--write] [--only <id,id>]\n\nThe URL is fetched twice: once as an ordinary visitor, without any intent\nparameter, and once the way the Payload admin\'s iframe loads it, with\n?preview=true and the iframe\'s headers.\nMost findings come from the difference between the two responses. Redirects\nare reported, not followed.\n\nOptions of pll doctor:\n -a, --admin <origin> Admin origin the preview is embedded from. Enables the\n frame-ancestors check to verify the origin is admitted,\n not merely that a policy exists.\n -H, --header <h> A header for the preview request only, as "Name: value";\n repeat it for more. A preview behind authorizePreview\n needs an editor\'s credentials: a Payload session Cookie,\n or an x-preview-token where the token strategy sets\n transport: { kind: \'header\' }. A signed token travels in\n the URL by default, as ?previewToken=…, which the visitor\n request drops. The visitor request stays anonymous and\n values are never printed, but a shell keeps them in its\n history, so prefer a short-lived token.\n --param <name> A query parameter the deployment reads as preview intent,\n for an adapter whose previewQueryParams replaces the\n default preview, draft and livePreview; repeat it for\n more. The first one is what the preview request carries\n as <name>=true; none of them reaches the visitor request.\n --token-param <n> The query parameter the signed-token strategy reads,\n where its transport names one other than previewToken.\n Treated like previewToken: dropped from the visitor\n request, counted as the credential, never printed.\n --json Emit the report as JSON instead of text\n --v2 Also check the page against the 2.0 readiness table\n -h, --help Show this help\n\nExit codes of pll doctor:\n 0 no error-level findings\n 1 usage error, or the URL could not be fetched\n 2 at least one error-level finding\n\npll migrate has its own options and exit codes: pll migrate --help\n\nExamples:\n pll doctor https://example.com/\n pll doctor https://example.com/blog/hello --admin https://cms.example.com\n pll doctor "https://example.com/?previewToken=$PREVIEW_TOKEN" --v2\n pll doctor https://example.com/ --header "Cookie: payload-token=$PAYLOAD_TOKEN"\n';function dt(e){try{return"null"!==new URL(e).origin}catch{return!1}}async function lt(e,t){const[n,...r]=e;if(void 0===n||"-h"===n||"--help"===n)return process.stdout.write(at),void 0===n?1:0;if("migrate"===n)return async function(e){const t=function(e){let t,n,r,i=!1,o=!1;const s=e=>e.split(",").filter(e=>e.length>0);for(let a=0;a<e.length;a+=1){const d=e[a];void 0!==d&&("-h"===d||"--help"===d?o=!0:"--write"===d?i=!0:"--only"===d?(n=s(e[a+1]??""),a+=1):d.startsWith("--only=")?n=s(d.slice(7)):d.startsWith("-")?r??=d:t??=d)}return{target:t,write:i,only:n,help:o,unknown:r}}(e);if(t.help)return process.stdout.write("pll migrate — rewrite 1.x APIs to their 2.0 names and homes (ADR 0007)\n\nUsage:\n pll migrate <path> [--write] [--only <id,id>]\n\nWithout --write the run only reports what it would change. Codemods touch\nonly names bound from payload-live-preview; anything they cannot rewrite\nsafely is listed as needing manual attention. Requires ts-morph.\n\nOptions:\n --write Apply the changes (otherwise dry-run)\n --only <ids> Run only these codemods (comma-separated); an id not\n listed below runs nothing\n -h, --help Show this help\n\nCodemods, in the order they run:\n rename-is-preview-request\n rename-admin-origins-option\n rename-bindings-authorized-option\n move-fetch-preview-helpers\n\nExit codes:\n 0 nothing needs a human (changes applied, or would be with --write)\n 1 usage error, unreadable path, or ts-morph is not installed\n 3 at least one file needs manual attention\n"),0;if(void 0!==t.unknown)return process.stderr.write(`pll migrate: unknown option ${t.unknown}\n`),1;if(void 0===t.target)return process.stderr.write("pll migrate: a path is required. Try `pll migrate --help`.\n"),1;let n;try{n=await async function(e,t={}){const n=t.io??{read:e=>o(e,"utf8"),write:(e,t)=>i(e,t,"utf8"),list:pe},r=[],s={};for(const i of await n.list(e)){const o=await n.read(i),{output:a,edits:d,conflicts:l}=de(o,{fileName:i,...void 0===t.only?{}:{only:t.only}}),c=a!==o;if(c&&!0===t.write&&await n.write(i,a),c)for(const e of d)s[e.codemod]=(s[e.codemod]??0)+1;r.push({file:fe(e,i),edits:d,changed:c,conflicts:l})}return{files:r,changedCount:r.filter(e=>e.changed).length,byCodemod:s,conflictCount:r.filter(e=>e.conflicts.length>0).length}}(t.target,{write:t.write,...void 0===t.only?{}:{only:t.only}})}catch(e){return process.stderr.write(`pll migrate: ${e instanceof Error?e.message:String(e)}\n`),1}for(const e of n.files)e.changed&&process.stdout.write(`${t.write?"migrated":"would migrate"} ${e.file} (${me(e)})\n`);process.stdout.write(`\n${t.write?"Migrated":"Would migrate"} ${String(n.changedCount)} file(s).${t.write?"":" Re-run with --write to apply."}\n`);for(const{id:e,notice:t}of oe)void 0!==t&&(n.byCodemod[e]??0)>0&&process.stdout.write(`\nNote (${e}): ${t}\n`);const r=n.files.filter(e=>e.conflicts.length>0);if(0===r.length)return 0;process.stdout.write(`\n${String(r.length)} file(s) need manual attention:\n`);for(const e of r)for(const t of e.conflicts){const n=void 0===t.line?e.file:`${e.file}:${String(t.line)}`;process.stdout.write(` ${n}: ${t.reason}\n`)}return 3}(r);if("doctor"!==n)return process.stderr.write(`pll: unknown command "${n}". Try \`pll --help\`.\n`),1;const s=function(e){const t={url:void 0,adminOrigin:void 0,json:!1,v2:!1,showHelp:!1,unknown:[],headers:{},usageError:void 0,params:[],tokenParam:void 0};for(let n=0;n<e.length;n+=1){const r=e[n];void 0!==r&&("-h"===r||"--help"===r?t.showHelp=!0:"--json"===r?t.json=!0:"--v2"===r?t.v2=!0:"--admin"===r||"-a"===r?(t.adminOrigin=e[n+1],n+=1):r.startsWith("--admin=")?t.adminOrigin=r.slice(8):"--header"===r||"-H"===r?(it(t,e[n+1]),n+=1):r.startsWith("--header=")?it(t,r.slice(9)):"--param"===r?(ot(t,e[n+1]),n+=1):r.startsWith("--param=")?ot(t,r.slice(8)):"--token-param"===r?(st(t,e[n+1]),n+=1):r.startsWith("--token-param=")?st(t,r.slice(14)):r.startsWith("-")?t.unknown.push(r):t.url??=r)}return t}(r);if(s.showHelp)return process.stdout.write(at),0;if(s.unknown.length>0)return process.stderr.write(`pll doctor: unknown option ${s.unknown.join(", ")}\n`),1;if(void 0===s.url)return process.stderr.write("pll doctor: a URL is required. Try `pll doctor --help`.\n"),1;if(void 0!==s.usageError)return process.stderr.write(`${s.usageError}\n`),1;if(void 0!==s.adminOrigin&&!dt(s.adminOrigin))return process.stderr.write(`pll doctor: --admin must be an absolute URL such as https://cms.example.com (got "${s.adminOrigin}")\n`),1;let a;try{a=await async function(e){const t=e.fetchImpl??function(e={}){const t=e.timeoutMs??15e3,n=e.maxBodyBytes??10485760;return async(r,i)=>{const o=e.fetchFn??globalThis.fetch;let s;try{s=await o(r,{headers:i.headers,redirect:"manual",signal:AbortSignal.timeout(t)})}catch(e){if(e instanceof Error&&"TimeoutError"===e.name)throw new Error(`no response within ${String(t/1e3)} s`,{cause:e});throw e}return{status:s.status,headers:Ze(s.headers),body:await et(s,n)}}}(),n=void 0===e.previewQueryParams||0===e.previewQueryParams.length?Ve:e.previewQueryParams,r=e.tokenQueryParam??Je,i=await t(function(e,t,n){const{base:r,parts:i,hash:o}=He(e),s=/* @__PURE__ */new Set([...t,n]),a=i.filter(e=>!s.has(Qe(e)[0]));return a.length===i.length?e:`${r}${0===a.length?"":`?${a.join("&")}`}${o}`}(e.url,n,r),{headers:{Accept:"text/html","Sec-Fetch-Dest":"document","Sec-Fetch-Mode":"navigate"}}),o={Accept:"text/html","Sec-Fetch-Dest":"iframe","Sec-Fetch-Mode":"navigate",...void 0===e.adminOrigin?{}:{Referer:tt(e.adminOrigin)}},s=function(e,t){const n=new Set(Object.keys(t).map(e=>e.toLowerCase()));return Object.fromEntries(Object.entries(e??{}).filter(([e])=>!n.has(e.toLowerCase())))}(e.previewHeaders,o),a=await t(function(e,t){const{base:n,parts:r,hash:i}=He(e);if(r.some(e=>{const[n,r]=Qe(e);return t.includes(n)&&function(e){return"true"===e||"1"===e}(r)}))return e;const o=r.join("&"),s=""===o?"?":o.endsWith("&")?"":"&",a=`${encodeURIComponent(t[0]??"preview")}=true`;return`${n}${0===r.length?"?":`?${o}${s}`}${a}${i}`}(e.url,n),{headers:{...s,...o}});return Ke({publicResponse:i,previewResponse:a},{url:Xe(e.url,r),adminOrigin:e.adminOrigin,...!0===e.v2?{v2:!0}:{},...Object.keys(s).length>0||Ye(e.url,r)?{credentials:!0}:{}})}({url:s.url,...void 0!==s.adminOrigin?{adminOrigin:s.adminOrigin}:{},...s.v2?{v2:!0}:{},...Object.keys(s.headers).length>0?{previewHeaders:s.headers}:{},...s.params.length>0?{previewQueryParams:s.params}:{},...void 0===s.tokenParam?{}:{tokenQueryParam:s.tokenParam},...void 0!==t?{fetchImpl:t}:{}})}catch(e){const t=function(e){if(!(e instanceof Error))return String(e);const t=e.cause;return t instanceof Error&&""!==t.message&&!e.message.includes(t.message)?`${e.message} (${t.message})`:e.message}(e),n=Xe(s.url,s.tokenParam);return s.json?process.stdout.write(`${JSON.stringify({url:n,error:t},void 0,2)}\n`):process.stderr.write(`pll doctor: could not probe ${n}: ${t}\n`),1}return process.stdout.write(s.json?`${JSON.stringify(a,void 0,2)}\n`:function(e){const t=[`pll doctor — ${e.url}`,""];if(0===e.findings.length)return t.push("No findings. The preview response carries the runtime, a frame-ancestors"),t.push("policy, and bindings; the public response carries none of them.",""),t.join("\n");for(const n of e.findings)t.push(`${ge[n.level]} ${n.code} ${n.title}`),t.push(` ${n.detail}`),""!==n.remedy&&t.push(` → ${n.remedy}`),t.push("");return t.push(`${String(e.errors)} error(s), ${String(e.warnings)} warning(s).`,""),t.join("\n")}(a)),a.errors>0?2:0}function ct(e=process.argv){if("undefined"==typeof process)return!1;const t=e[1];if(void 0===t||""===t)return!1;const n=t.split(/[\\/]/u).pop()??"";return"pll"===n||"pll.cmd"===n||n.startsWith("doctor-cli")}ct()&&lt(process.argv.slice(2)).then(e=>{process.exit(e)});export{ct as isCliInvocation,lt as run};
3
3
  //# sourceMappingURL=doctor-cli.js.map