payload-live-preview 2.2.1 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +21 -18
  2. package/dist/adapters/astro/PreviewBoundary.astro +17 -4
  3. package/dist/adapters/astro/RichText.astro +13 -2
  4. package/dist/adapters/astro/index.d.ts +7 -7
  5. package/dist/adapters/astro/index.js +1 -1
  6. package/dist/adapters/astro/index.js.map +1 -1
  7. package/dist/adapters/astro/middleware-entry.d.ts +3 -3
  8. package/dist/adapters/astro/middleware-entry.js +1 -1
  9. package/dist/adapters/astro/middleware-entry.js.map +1 -1
  10. package/dist/adapters/nextjs/index.d.ts +2 -2
  11. package/dist/adapters/nextjs/index.js +1 -1
  12. package/dist/adapters/nextjs/index.js.map +1 -1
  13. package/dist/adapters/nuxt/index.d.ts +4 -4
  14. package/dist/adapters/nuxt/index.js +1 -1
  15. package/dist/adapters/nuxt/index.js.map +1 -1
  16. package/dist/adapters/nuxt/module.d.ts +1 -1
  17. package/dist/adapters/react/index.d.ts +2 -2
  18. package/dist/adapters/react/index.js +1 -1
  19. package/dist/adapters/react/index.js.map +1 -1
  20. package/dist/adapters/sveltekit/index.d.ts +5 -5
  21. package/dist/adapters/sveltekit/index.js +1 -1
  22. package/dist/adapters/sveltekit/index.js.map +1 -1
  23. package/dist/adapters/vue/index.d.ts +2 -2
  24. package/dist/adapters/vue/index.js +1 -1
  25. package/dist/adapters/vue/index.js.map +1 -1
  26. package/dist/client.cjs +1 -1
  27. package/dist/client.cjs.map +1 -1
  28. package/dist/client.d.cts +15 -3
  29. package/dist/client.d.ts +15 -3
  30. package/dist/client.js +1 -1
  31. package/dist/client.js.map +1 -1
  32. package/dist/codegen-astro.js +1 -1
  33. package/dist/codegen-astro.js.map +1 -1
  34. package/dist/codegen-cli.js +1 -1
  35. package/dist/codegen-cli.js.map +1 -1
  36. package/dist/codegen.cjs +1 -1
  37. package/dist/codegen.cjs.map +1 -1
  38. package/dist/codegen.js +1 -1
  39. package/dist/codegen.js.map +1 -1
  40. package/dist/core.cjs +1 -1
  41. package/dist/core.cjs.map +1 -1
  42. package/dist/core.d.cts +141 -6
  43. package/dist/core.d.ts +141 -6
  44. package/dist/core.js +1 -1
  45. package/dist/core.js.map +1 -1
  46. package/dist/doctor-cli.d.ts +1 -1
  47. package/dist/doctor-cli.js +1 -1
  48. package/dist/doctor-cli.js.map +1 -1
  49. package/dist/doctor.d.ts +2 -2
  50. package/dist/doctor.js +1 -1
  51. package/dist/doctor.js.map +1 -1
  52. package/dist/{document-session-Bkd181PV.d.ts → document-session-BuYuO3ae.d.ts} +27 -2
  53. package/dist/{fragment-endpoint-DGGLIijM.d.ts → fragment-endpoint-CQE_7MKi.d.ts} +5 -3
  54. package/dist/fragment.cjs +1 -1
  55. package/dist/fragment.cjs.map +1 -1
  56. package/dist/fragment.d.cts +6 -2
  57. package/dist/fragment.d.ts +6 -2
  58. package/dist/fragment.js +1 -1
  59. package/dist/fragment.js.map +1 -1
  60. package/dist/index.cjs +1 -1
  61. package/dist/index.cjs.map +1 -1
  62. package/dist/index.d.cts +79 -16
  63. package/dist/index.d.ts +79 -16
  64. package/dist/index.js +1 -1
  65. package/dist/index.js.map +1 -1
  66. package/dist/lean.cjs +1 -1
  67. package/dist/lean.cjs.map +1 -1
  68. package/dist/lean.js +1 -1
  69. package/dist/lean.js.map +1 -1
  70. package/dist/lexical.cjs +1 -1
  71. package/dist/lexical.cjs.map +1 -1
  72. package/dist/lexical.d.cts +16 -4
  73. package/dist/lexical.d.ts +16 -4
  74. package/dist/lexical.js +1 -1
  75. package/dist/lexical.js.map +1 -1
  76. package/dist/{locals-zz2gi9dj.d.ts → locals-CyzDKfKU.d.ts} +7 -1
  77. package/dist/{middleware-CI-UTf6R.d.ts → middleware-Dnt6u4nF.d.ts} +2 -2
  78. package/dist/{options-CnYybG51.d.ts → options-DTzhFVJ4.d.ts} +13 -1
  79. package/dist/plugin.cjs +1 -1
  80. package/dist/plugin.cjs.map +1 -1
  81. package/dist/plugin.d.cts +15 -9
  82. package/dist/plugin.d.ts +15 -9
  83. package/dist/plugin.js +1 -1
  84. package/dist/plugin.js.map +1 -1
  85. package/dist/plugins.cjs +1 -1
  86. package/dist/plugins.cjs.map +1 -1
  87. package/dist/plugins.d.cts +8 -2
  88. package/dist/plugins.d.ts +8 -2
  89. package/dist/plugins.js +1 -1
  90. package/dist/plugins.js.map +1 -1
  91. package/dist/{probe-D-IHg9dF.d.ts → probe-afwdYebU.d.ts} +6 -2
  92. package/dist/server.cjs +1 -1
  93. package/dist/server.cjs.map +1 -1
  94. package/dist/server.d.cts +23 -3
  95. package/dist/server.d.ts +23 -3
  96. package/dist/server.js +1 -1
  97. package/dist/server.js.map +1 -1
  98. package/dist/structural.cjs +2 -2
  99. package/dist/structural.cjs.map +1 -1
  100. package/dist/structural.d.cts +2 -0
  101. package/dist/structural.d.ts +2 -0
  102. package/dist/structural.js +1 -1
  103. package/dist/structural.js.map +1 -1
  104. package/package.json +7 -4
@@ -1,2 +1,2 @@
1
- import{watch as e}from"fs";import{dirname as t,resolve as o,sep as n,extname as i,isAbsolute as s}from"path";import{fileURLToPath as r}from"url";import{mkdir as a,writeFile as l}from"fs/promises";import{createRequire as c}from"module";function u(e){return e.split(/[-_\s]+/u).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}var d,f=/^[A-Za-z_$][\w$]*$/u;function p(e,t){return`${e}${u(t)}`}function g(e,t,o,n){!0===n.markLocalizedAsDeprecated&&e.localized&&o.push(" /** @localized */");const i=e.required?"":"?";var s;o.push(` ${s=e.name,f.test(s)?s:`'${s.replace(/\\/gu,"\\\\").replace(/'/gu,"\\'")}'`}${i}: ${function(e,t){switch(e.kind){case"scalar":return!0===e.hasMany?`${e.typeRef}[]`:e.typeRef;case"array":return`${p(t,e.name)}[]`;case"blocks":return 0===e.blocks.length?"unknown[]":`(${e.blocks.map(o=>p(p(t,e.name),o.typeName)).join(" | ")})[]`;case"group":return p(t,e.name);case"relationship":{const t=`PayloadRelationship<${"string"==typeof e.target?`'${e.target}'`:e.target.map(e=>`'${e}'`).join(" | ")}>`;return e.hasMany?`${t}[]`:t}case"upload":return!0===e.hasMany?"PayloadMedia[]":"PayloadMedia";case"json":return"unknown";case"select":{if(0===e.options.length)return e.hasMany?"string[]":"string";const t=e.options.map(e=>`'${e}'`).join(" | ");return e.hasMany?`(${t})[]`:t}}}(e,t)};`)}function h(e,t,o,n){o.push(`export interface ${e} {`),o.push(` blockType: '${t.slug}';`);for(const i of t.fields)g(i,e,o,n);o.push("}","")}function m(e,t,o,n,i){for(const s of t){const t=p(e,s.name);if("array"===s.kind||"group"===s.kind){if(n.has(t))continue;n.add(t),m(t,s.fields,o,n,i),o.push(`export interface ${t} {`);for(const e of s.fields)g(e,t,o,i);o.push("}","")}else if("blocks"===s.kind)for(const e of s.blocks){const s=p(t,e.typeName);n.has(s)||(n.add(s),m(s,e.fields,o,n,i),h(s,e,o,i))}}}function v(e,t,o,n){m(e.typeName,e.fields,t,o,n),t.push(`export interface ${e.typeName} {`);for(const o of e.fields)g(o,e.typeName,t,n);t.push("}")}function y(e,t,o){if(0!==t.length){o.push(`export type ${e} = {`);for(const e of t)o.push(` '${e.slug}': ${e.typeName};`);o.push("};","")}}function b(e,t,o){for(const n of e){if("group"===n.kind&&"__structural"===n.name){b(n.fields,t,o);continue}const e=""===t?n.name:`${t}.${n.name}`;if(o.push({path:e,kind:n.kind,localized:n.localized,required:n.required}),"group"===n.kind)b(n.fields,e,o);else if("array"===n.kind)b(n.fields,`${e}.*`,o);else if("blocks"===n.kind)for(const t of n.blocks)b(t.fields,`${e}.*.${t.slug}`,o)}}function $(e){const t=[];return b(e.fields,"",t),{slug:e.slug,typeName:e.typeName,fields:t}}function k(){if(void 0===d)try{d=c(import.meta.url)("ts-morph")}catch(e){throw new Error("pll-codegen needs ts-morph: npm install --save-dev ts-morph",{cause:e})}return d}function w(){return k().Node}function x(e,t,o){e.diagnostics.push(`Skipped "${function(e){const t=e.getText().replace(/\s+/gu," ");return t.length>60?`${t.slice(0,57)}...`:t}(t)}" at ${function(e){return`${e.getSourceFile().getBaseName()}:${String(e.getStartLineNumber())}`}(t)}: ${o}.`)}function P(e){let t=e;for(;w().isParenthesizedExpression(t)||w().isAsExpression(t)||w().isSatisfiesExpression(t)||w().isNonNullExpression(t)||w().isTypeAssertion(t);)t=t.getExpression();return t}function S(e){if(!(w().isImportSpecifier(e)||w().isImportClause(e)||w().isNamespaceImport(e)||w().isExportSpecifier(e)))return[e];const t=e.getSymbol()?.getAliasedSymbol();return t?.getDeclarations()??[e]}function E(e){const t=e.getDefinitionNodes();return(t.length>0?t:e.getSymbol()?.getDeclarations()??[]).flatMap(S)}function N(e){return w().isVariableDeclaration(e)||w().isPropertyAssignment(e)?e.getInitializer():w().isExportAssignment(e)?e.getExpression():w().isShorthandPropertyAssignment(e)?e.getNameNode():void 0}function j(e,t){const o=e.getProperty(t);if(void 0!==o)return w().isPropertyAssignment(o)?o.getInitializer():w().isShorthandPropertyAssignment(o)?o.getNameNode():void 0}function A(e,t){return void 0!==e.getProperty(t)}function F(e,t=/* @__PURE__ */new Set){if(void 0===e||t.has(e))return;t.add(e);const o=P(e);if(w().isObjectLiteralExpression(o))return o;if(w().isCallExpression(o))return F(o.getArguments()[0],t);if(w().isIdentifier(o))for(const e of E(o)){const o=F(N(e),t);if(void 0!==o)return o}if(w().isPropertyAccessExpression(o)){const e=F(o.getExpression(),t);if(void 0!==e)return F(j(e,o.getName()),t)}}function C(e,t=/* @__PURE__ */new Set){if(void 0===e||t.has(e))return;t.add(e);const o=P(e);if(w().isArrayLiteralExpression(o))return o;if(w().isIdentifier(o))for(const e of E(o)){const o=C(N(e),t);if(void 0!==o)return o}if(w().isPropertyAccessExpression(o)){const e=F(o.getExpression(),t);if(void 0!==e)return C(j(e,o.getName()),t)}}function L(e,t){const o=[];for(const n of e.getElements()){if(!w().isSpreadElement(n)){o.push(n);continue}const e=C(n.getExpression());void 0!==e?o.push(...L(e,t)):x(t,n,"could not resolve the spread to an array literal, so its entries are missing")}return o}function M(e,t){const o=j(e,t);if(void 0===o)return;const n=P(o);return w().isStringLiteral(n)||w().isNoSubstitutionTemplateLiteral(n)?n.getLiteralValue():void 0}function z(e,t){const o=j(e,t);if(void 0===o)return;const n=P(o);return!!w().isTrueLiteral(n)||!w().isFalseLiteral(n)&&void 0}function T(e,t){return C(j(e,t))}function D(e){const t=j(e,"relationTo");if(void 0===t)return"unknown";const o=P(t);if(w().isStringLiteral(o))return o.getLiteralValue();const n=C(o);return void 0===n?"unknown":n.getElements().map(P).filter(e=>w().isStringLiteral(e)).map(e=>e.getLiteralValue())}var I="__structural",q=/* @__PURE__ */new Set(["tabs","row","collapsible"]),_={text:"string",textarea:"string",email:"string",richText:"unknown",number:"number",checkbox:"boolean",date:"string",code:"string",point:"[number, number]"},R=/* @__PURE__ */new Set(["text","number"]);function V(e,t){const o=[];for(const n of L(e,t)){const e=F(n);if(void 0===e){x(t,n,"could not resolve the field to an object literal");continue}const i=U(e,t);void 0!==i&&("group"===i.kind&&i.name===I?o.push(...i.fields):o.push(i))}return o}function O(e,t){const o=T(e,"fields");return void 0!==o?V(o,t):(x(t,e,A(e,"fields")?"its `fields` could not be resolved to an array literal":"it has no `fields`"),[])}function B(e,t){const o=T(e,"tabs");if(void 0===o)return x(t,e,"its `tabs` could not be resolved to an array literal"),[];const n=[];for(const e of L(o,t)){const o=F(e);if(void 0===o){x(t,e,"could not resolve the tab to an object literal");continue}const i=M(o,"name"),s=O(o,t);void 0===i?n.push(...s):n.push({kind:"group",name:i,required:!1,localized:!1,fields:s})}return n}function G(e,t){const o=T(e,"blocks");if(void 0===o)return x(t,e,"its `blocks` could not be resolved to an array literal"),[];const n=[];for(const e of L(o,t)){const o=F(e);if(void 0===o){x(t,e,"could not resolve the block to an object literal");continue}const i=M(o,"slug");void 0!==i?n.push({slug:i,typeName:u(i),fields:O(o,t)}):x(t,e,"a block needs a string `slug`")}return n}function K(e,t){const o=T(e,"options");if(void 0===o)return x(t,e,"its `options` could not be resolved to an array literal"),[];const n=[];for(const e of L(o,t)){if(w().isStringLiteral(e)){n.push(e.getLiteralValue());continue}const o=F(e),i=void 0===o?void 0:M(o,"value");void 0===i?x(t,e,"an option needs a string or a `value`"):n.push(i)}return n}function U(e,t){const o=M(e,"type");if(void 0===o)return void x(t,e,"it has no string `type`");if("ui"===o)return;const n=M(e,"name");if(void 0===n&&!q.has(o))return void x(t,e,`a ${o} field needs a string \`name\``);const i={name:n??I,required:z(e,"required")??!1,localized:z(e,"localized")??!1},s=z(e,"hasMany")??!1;switch(o){case"array":return{...i,kind:"array",fields:O(e,t)};case"group":case"row":case"collapsible":return{...i,kind:"group",fields:O(e,t)};case"tabs":return{...i,kind:"group",fields:B(e,t)};case"blocks":return{...i,kind:"blocks",blocks:G(e,t)};case"relationship":return{...i,kind:"relationship",target:D(e),hasMany:s};case"upload":{const t=D(e);return{...i,kind:"upload",target:("string"==typeof t?t:t[0])??"media",hasMany:s}}case"json":return{...i,kind:"json"};case"select":case"radio":return{...i,kind:"select",options:K(e,t),hasMany:"select"===o&&s};default:return{...i,kind:"scalar",typeRef:_[o]??"unknown",hasMany:R.has(o)&&s}}}function J(e){if(w().isExportAssignment(e))return e.getExpression()}function W(e,t,o){const n=j(e,t);if(void 0===n)return[];const i=C(n);if(void 0===i)return x(o,n,`could not resolve \`${t}\` to an array literal`),[];const s=[];for(const e of L(i,o)){const t=F(e);if(void 0===t){x(o,e,"could not resolve the config entry to an object literal");continue}const n=M(t,"slug");if(void 0===n){x(o,e,"the config entry has no string `slug`");continue}const i=T(t,"fields");void 0===i&&x(o,t,A(t,"fields")?`the \`fields\` of "${n}" could not be resolved to an array literal`:`"${n}" has no \`fields\``),s.push({slug:n,typeName:u(n),fields:void 0===i?[]:V(i,o)})}return s}async function Z(e,o){await a(t(e),{recursive:!0}),await l(e,o,"utf8")}async function H(e){const t=e.cwd??process.cwd(),n=e=>s(e)?e:o(t,e),i=function(e){const t=e.project??new(k().Project)(void 0!==e.tsConfigFilePath?{tsConfigFilePath:e.tsConfigFilePath}:{skipAddingFilesFromTsConfig:!0}),o=t.addSourceFileAtPathIfExists(e.configPath);if(void 0===o)return{globals:[],collections:[],diagnostics:[`Could not open ${e.configPath}`]};t.resolveSourceFileDependencies();const n={diagnostics:[]},i=function(e,t){const o=e.getDefaultExportSymbol();if(void 0!==o){for(const e of o.getDeclarations()){const t=F(J(e));if(void 0!==t)return t}for(const t of e.getDescendantsOfKind(k().SyntaxKind.CallExpression)){const e=t.getExpression();if(!w().isIdentifier(e)||"buildConfig"!==e.getText())continue;const o=F(t.getArguments()[0]);if(void 0!==o)return o}}else t.diagnostics.push("payload.config.ts has no default export.")}(o,n);return void 0===i?{globals:[],collections:[],diagnostics:[...n.diagnostics,"Could not locate a buildConfig({...}) call or `export default {...}` in the config file."]}:{globals:W(i,"globals",n),collections:W(i,"collections",n),diagnostics:n.diagnostics}}({configPath:n(e.configPath),...void 0!==e.project?{project:e.project}:{},...void 0!==e.tsConfigFilePath?{tsConfigFilePath:e.tsConfigFilePath}:{}}),r=function(e,t={}){const o=[t.header??"// Auto-generated by payload-live-preview/codegen.\n// Do not edit by hand — run `pll-codegen` to regenerate.\n/* eslint-disable */",""];o.push('import type { PayloadMedia, PayloadRelationship } from "payload-live-preview";',"");const n=/* @__PURE__ */new Set;for(const i of[...e.globals,...e.collections])v(i,o,n,t),o.push("");y("PayloadGlobals",e.globals,o),y("PayloadCollections",e.collections,o);const i=[];return e.globals.length>0&&i.push("keyof PayloadGlobals"),e.collections.length>0&&i.push("keyof PayloadCollections"),i.length>0&&o.push(`export type PayloadSlug = ${i.join(" | ")};`,""),o.join("\n").replace(/\n{3,}/gu,"\n\n")}(i,e),a=function(e){return{globals:e.globals.map($),collections:e.collections.map($)}}(i),l=[...i.diagnostics],c=void 0===e.outFile?void 0:n(e.outFile),u=void 0===e.inventoryFile?void 0:n(e.inventoryFile),d=[c,u].filter(e=>void 0!==e),f=i.globals.length+i.collections.length===0;return f&&d.length>0?l.push(`Nothing written: the schema is empty (0 globals, 0 collections), so ${d.join(" and ")} were left as they are.`):(void 0!==c&&await Z(c,r),void 0!==u&&await Z(u,`${JSON.stringify(a,null,2)}\n`)),{code:r,diagnostics:l,schema:i,inventory:a,...f||void 0===c?{}:{outFile:c},...f||void 0===u?{}:{inventoryFile:u}}}var Q=/* @__PURE__ */new Set([".ts",".mts",".cts",".js",".mjs",".cjs",".json"]);function X(s){const a=s.watch??!0;let l,c,u=process.cwd(),d=!1,f=!1;async function p(e){if(d)f=!0;else{d=!0;try{const t=await H({configPath:s.configPath,outFile:s.outPath,cwd:u});if(void 0===t.outFile)e?.error(`pll-codegen: nothing written — ${t.diagnostics.join(" ")}`);else if(!0!==s.quiet){e?.info(`pll-codegen: ${String(t.schema.globals.length)} globals, ${String(t.schema.collections.length)} collections → ${s.outPath}`);for(const o of t.diagnostics)e?.warn(`pll-codegen: ${o}`)}}catch(t){e?.error(`pll-codegen failed: ${t instanceof Error?t.message:String(t)}`)}finally{d=!1,f&&(f=!1,p(e))}}}return{name:"payload-live-preview:codegen",hooks:{"astro:config:setup":async({command:d,logger:f,config:g})=>{u=function(e){return void 0===e?process.cwd():e instanceof URL||e.startsWith("file:")?r(e):e}(g?.root),await p(f),a&&"dev"===d&&function(r){const a=t(o(u,s.configPath)),d=o(u,s.outPath);try{l=e(a,{recursive:!0},(e,t)=>{if(null===t)return;const s=o(a,t);s===d||s.includes(`${n}node_modules${n}`)||Q.has(i(s))&&(clearTimeout(c),c=setTimeout(()=>{p(r)},100))})}catch(e){r?.warn(`pll-codegen watcher unavailable: ${e instanceof Error?e.message:String(e)}`)}}(f)},"astro:server:start":()=>{},"astro:build:start":()=>{clearTimeout(c),l?.close(),l=void 0}}}}export{X as livePreviewCodegen};
1
+ import{watch as e}from"fs";import{dirname as t,resolve as o,sep as n,extname as i,isAbsolute as s}from"path";import{fileURLToPath as r}from"url";import{mkdir as a,writeFile as l}from"fs/promises";import{createRequire as c}from"module";function u(e){return e.split(/[-_\s]+/u).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}var d,f=/^[A-Za-z_$][\w$]*$/u;function p(e,t){return`${e}${u(t)}`}function g(e,t,o,n){!0===n.markLocalizedAsDeprecated&&e.localized&&o.push(" /** @localized */");const i=e.required?"":"?";var s;o.push(` ${s=e.name,f.test(s)?s:`'${s.replace(/\\/gu,"\\\\").replace(/'/gu,"\\'")}'`}${i}: ${function(e,t){switch(e.kind){case"scalar":return!0===e.hasMany?`${e.typeRef}[]`:e.typeRef;case"array":return`${p(t,e.name)}[]`;case"blocks":return 0===e.blocks.length?"unknown[]":`(${e.blocks.map(o=>p(p(t,e.name),o.typeName)).join(" | ")})[]`;case"group":return p(t,e.name);case"relationship":{const t=`PayloadRelationship<${"string"==typeof e.target?`'${e.target}'`:e.target.map(e=>`'${e}'`).join(" | ")}>`;return e.hasMany?`${t}[]`:t}case"upload":return!0===e.hasMany?"PayloadMedia[]":"PayloadMedia";case"json":return"unknown";case"select":{if(0===e.options.length)return e.hasMany?"string[]":"string";const t=e.options.map(e=>`'${e}'`).join(" | ");return e.hasMany?`(${t})[]`:t}}}(e,t)};`)}function h(e,t,o,n){o.push(`export interface ${e} {`),o.push(` blockType: '${t.slug}';`);for(const i of t.fields)g(i,e,o,n);o.push("}","")}function m(e,t,o,n,i){for(const s of t){const t=p(e,s.name);if("array"===s.kind||"group"===s.kind){if(n.has(t))continue;n.add(t),m(t,s.fields,o,n,i),o.push(`export interface ${t} {`);for(const e of s.fields)g(e,t,o,i);o.push("}","")}else if("blocks"===s.kind)for(const e of s.blocks){const s=p(t,e.typeName);n.has(s)||(n.add(s),m(s,e.fields,o,n,i),h(s,e,o,i))}}}function v(e,t,o,n){m(e.typeName,e.fields,t,o,n),t.push(`export interface ${e.typeName} {`);for(const o of e.fields)g(o,e.typeName,t,n);t.push("}")}function y(e,t,o){if(0!==t.length){o.push(`export type ${e} = {`);for(const e of t)o.push(` '${e.slug}': ${e.typeName};`);o.push("};","")}}function b(e,t,o){for(const n of e){if("group"===n.kind&&"__structural"===n.name){b(n.fields,t,o);continue}const e=""===t?n.name:`${t}.${n.name}`;if(o.push({path:e,kind:n.kind,localized:n.localized,required:n.required}),"group"===n.kind)b(n.fields,e,o);else if("array"===n.kind)b(n.fields,`${e}.*`,o);else if("blocks"===n.kind)for(const t of n.blocks)b(t.fields,`${e}.*.${t.slug}`,o)}}function $(e){const t=[];return b(e.fields,"",t),{slug:e.slug,typeName:e.typeName,fields:t}}function k(){if(void 0===d)try{d=c(import.meta.url)("ts-morph")}catch(e){throw new Error("pll-codegen needs ts-morph: npm install --save-dev ts-morph",{cause:e})}return d}function x(){return k().Node}function w(e,t,o){e.diagnostics.push(`Skipped "${function(e){const t=e.getText().replace(/\s+/gu," ");return t.length>60?`${t.slice(0,57)}...`:t}(t)}" at ${function(e){return`${e.getSourceFile().getBaseName()}:${String(e.getStartLineNumber())}`}(t)}: ${o}.`)}function P(e){let t=e;for(;x().isParenthesizedExpression(t)||x().isAsExpression(t)||x().isSatisfiesExpression(t)||x().isNonNullExpression(t)||x().isTypeAssertion(t);)t=t.getExpression();return t}function S(e){if(!(x().isImportSpecifier(e)||x().isImportClause(e)||x().isNamespaceImport(e)||x().isExportSpecifier(e)))return[e];const t=e.getSymbol()?.getAliasedSymbol();return t?.getDeclarations()??[e]}function E(e){const t=e.getDefinitionNodes();return(t.length>0?t:e.getSymbol()?.getDeclarations()??[]).flatMap(S)}function N(e){return x().isVariableDeclaration(e)||x().isPropertyAssignment(e)?e.getInitializer():x().isExportAssignment(e)?e.getExpression():x().isShorthandPropertyAssignment(e)?e.getNameNode():void 0}function j(e,t){const o=e.getProperty(t);if(void 0!==o)return x().isPropertyAssignment(o)?o.getInitializer():x().isShorthandPropertyAssignment(o)?o.getNameNode():void 0}function A(e,t){return void 0!==e.getProperty(t)}function F(e){const t=P(e.getExpression());if(x().isIdentifier(t))for(const e of E(t)){const t=x().isVariableDeclaration(e)?e.getInitializer():e;if(void 0===t||!(x().isFunctionDeclaration(t)||x().isArrowFunction(t)||x().isFunctionExpression(t)))continue;const o=t.getBody();if(void 0===o)continue;if(!x().isBlock(o))return o;const[n,...i]=o.getStatements();if(void 0!==n&&0===i.length&&x().isReturnStatement(n))return n.getExpression()}}function C(e,t=/* @__PURE__ */new Set){if(void 0===e||t.has(e))return;t.add(e);const o=P(e);if(x().isObjectLiteralExpression(o))return o;if(x().isCallExpression(o)){const e=C(F(o),t);return void 0===e||e.getProperties().some(x().isSpreadAssignment)?C(o.getArguments()[0],t):e}if(x().isIdentifier(o))for(const e of E(o)){const o=C(N(e),t);if(void 0!==o)return o}if(x().isPropertyAccessExpression(o)){const e=C(o.getExpression(),t);if(void 0!==e)return C(j(e,o.getName()),t)}}function L(e,t=/* @__PURE__ */new Set){if(void 0===e||t.has(e))return;t.add(e);const o=P(e);if(x().isArrayLiteralExpression(o))return o;if(x().isCallExpression(o)){const e=o.getExpression();return x().isPropertyAccessExpression(e)&&"map"===e.getName()?L(e.getExpression(),t):L(F(o),t)}if(x().isIdentifier(o))for(const e of E(o)){const o=L(N(e),t);if(void 0!==o)return o}if(x().isPropertyAccessExpression(o)){const e=C(o.getExpression(),t);if(void 0!==e)return L(j(e,o.getName()),t)}}function M(e,t){const o=[];for(const n of e.getElements()){if(!x().isSpreadElement(n)){o.push(n);continue}const e=L(n.getExpression());void 0!==e?o.push(...M(e,t)):w(t,n,"could not resolve the spread to an array literal, so its entries are missing")}return o}function z(e,t){const o=j(e,t);if(void 0===o)return;const n=P(o);return x().isStringLiteral(n)||x().isNoSubstitutionTemplateLiteral(n)?n.getLiteralValue():void 0}function D(e,t){const o=j(e,t);if(void 0===o)return;const n=P(o);return!!x().isTrueLiteral(n)||!x().isFalseLiteral(n)&&void 0}function T(e,t){return L(j(e,t))}function I(e){const t=j(e,"relationTo");if(void 0===t)return"unknown";const o=P(t);if(x().isStringLiteral(o))return o.getLiteralValue();const n=L(o);return void 0===n?"unknown":n.getElements().map(P).filter(e=>x().isStringLiteral(e)).map(e=>e.getLiteralValue())}var q="__structural",R=/* @__PURE__ */new Set(["tabs","row","collapsible"]),_={text:"string",textarea:"string",email:"string",richText:"unknown",number:"number",checkbox:"boolean",date:"string",code:"string",point:"[number, number]"},V=/* @__PURE__ */new Set(["text","number"]);function B(e,t){const o=[];for(const n of M(e,t)){const e=C(n);if(void 0===e){w(t,n,"could not resolve the field to an object literal");continue}const i=J(e,t);void 0!==i&&("group"===i.kind&&i.name===q?o.push(...i.fields):o.push(i))}return o}function O(e,t){const o=T(e,"fields");return void 0!==o?B(o,t):(w(t,e,A(e,"fields")?"its `fields` could not be resolved to an array literal":"it has no `fields`"),[])}function G(e,t){const o=T(e,"tabs");if(void 0===o)return w(t,e,"its `tabs` could not be resolved to an array literal"),[];const n=[];for(const e of M(o,t)){const o=C(e);if(void 0===o){w(t,e,"could not resolve the tab to an object literal");continue}const i=z(o,"name"),s=O(o,t);void 0===i?n.push(...s):n.push({kind:"group",name:i,required:!1,localized:!1,fields:s})}return n}function K(e,t){const o=T(e,"blocks");if(void 0===o)return w(t,e,"its `blocks` could not be resolved to an array literal"),[];const n=[];for(const e of M(o,t)){const o=C(e);if(void 0===o){w(t,e,"could not resolve the block to an object literal");continue}const i=z(o,"slug");void 0!==i?n.push({slug:i,typeName:u(i),fields:O(o,t)}):w(t,e,"a block needs a string `slug`")}return n}function U(e,t){const o=T(e,"options");if(void 0===o)return w(t,e,"its `options` could not be resolved to an array literal"),[];const n=[];for(const e of M(o,t)){if(x().isStringLiteral(e)){n.push(e.getLiteralValue());continue}const o=C(e),i=void 0===o?void 0:z(o,"value");void 0===i?w(t,e,"an option needs a string or a `value`"):n.push(i)}return n}function J(e,t){const o=z(e,"type");if(void 0===o)return void w(t,e,"it has no string `type`");if("ui"===o)return;const n=z(e,"name");if(void 0===n&&!R.has(o))return void w(t,e,`a ${o} field needs a string \`name\``);const i={name:n??q,required:D(e,"required")??!1,localized:D(e,"localized")??!1},s=D(e,"hasMany")??!1;switch(o){case"array":return{...i,kind:"array",fields:O(e,t)};case"group":case"row":case"collapsible":return{...i,kind:"group",fields:O(e,t)};case"tabs":return{...i,kind:"group",fields:G(e,t)};case"blocks":return{...i,kind:"blocks",blocks:K(e,t)};case"relationship":return{...i,kind:"relationship",target:I(e),hasMany:s};case"upload":{const t=I(e);return{...i,kind:"upload",target:("string"==typeof t?t:t[0])??"media",hasMany:s}}case"json":return{...i,kind:"json"};case"select":case"radio":return{...i,kind:"select",options:U(e,t),hasMany:"select"===o&&s};default:return{...i,kind:"scalar",typeRef:_[o]??"unknown",hasMany:V.has(o)&&s}}}function W(e){if(x().isExportAssignment(e))return e.getExpression()}function Z(e,t,o){const n=j(e,t);if(void 0===n)return[];const i=L(n);if(void 0===i)return w(o,n,`could not resolve \`${t}\` to an array literal`),[];const s=[];for(const e of M(i,o)){const t=C(e);if(void 0===t){w(o,e,"could not resolve the config entry to an object literal");continue}const n=z(t,"slug");if(void 0===n){w(o,e,"the config entry has no string `slug`");continue}const i=T(t,"fields");void 0===i&&w(o,t,A(t,"fields")?`the \`fields\` of "${n}" could not be resolved to an array literal`:`"${n}" has no \`fields\``),s.push({slug:n,typeName:u(n),fields:void 0===i?[]:B(i,o)})}return s}async function H(e,o){await a(t(e),{recursive:!0}),await l(e,o,"utf8")}async function Q(e){const t=e.cwd??process.cwd(),n=e=>s(e)?e:o(t,e),i=function(e){const t=e.project??new(k().Project)(void 0!==e.tsConfigFilePath?{tsConfigFilePath:e.tsConfigFilePath}:{skipAddingFilesFromTsConfig:!0}),o=t.addSourceFileAtPathIfExists(e.configPath);if(void 0===o)return{globals:[],collections:[],diagnostics:[`Could not open ${e.configPath}`]};t.resolveSourceFileDependencies();const n={diagnostics:[]},i=function(e,t){const o=e.getDefaultExportSymbol();if(void 0!==o){for(const e of o.getDeclarations()){const t=C(W(e));if(void 0!==t)return t}for(const t of e.getDescendantsOfKind(k().SyntaxKind.CallExpression)){const e=t.getExpression();if(!x().isIdentifier(e)||"buildConfig"!==e.getText())continue;const o=C(t.getArguments()[0]);if(void 0!==o)return o}}else t.diagnostics.push("payload.config.ts has no default export.")}(o,n);return void 0===i?{globals:[],collections:[],diagnostics:[...n.diagnostics,"Could not locate a buildConfig({...}) call or `export default {...}` in the config file."]}:{globals:Z(i,"globals",n),collections:Z(i,"collections",n),diagnostics:n.diagnostics}}({configPath:n(e.configPath),...void 0!==e.project?{project:e.project}:{},...void 0!==e.tsConfigFilePath?{tsConfigFilePath:e.tsConfigFilePath}:{}}),r=function(e,t={}){const o=[t.header??"// Auto-generated by payload-live-preview/codegen.\n// Do not edit by hand — run `pll-codegen` to regenerate.\n/* eslint-disable */",""];o.push('import type { PayloadMedia, PayloadRelationship } from "payload-live-preview";',"");const n=/* @__PURE__ */new Set;for(const i of[...e.globals,...e.collections])v(i,o,n,t),o.push("");y("PayloadGlobals",e.globals,o),y("PayloadCollections",e.collections,o);const i=[];return e.globals.length>0&&i.push("keyof PayloadGlobals"),e.collections.length>0&&i.push("keyof PayloadCollections"),i.length>0&&o.push(`export type PayloadSlug = ${i.join(" | ")};`,""),o.join("\n").replace(/\n{3,}/gu,"\n\n")}(i,e),a=function(e){return{globals:e.globals.map($),collections:e.collections.map($)}}(i),l=[...i.diagnostics],c=void 0===e.outFile?void 0:n(e.outFile),u=void 0===e.inventoryFile?void 0:n(e.inventoryFile),d=[c,u].filter(e=>void 0!==e),f=i.globals.length+i.collections.length===0;return f&&d.length>0?l.push(`Nothing written: the schema is empty (0 globals, 0 collections), so ${d.join(" and ")} were left as they are.`):(void 0!==c&&await H(c,r),void 0!==u&&await H(u,`${JSON.stringify(a,null,2)}\n`)),{code:r,diagnostics:l,schema:i,inventory:a,...f||void 0===c?{}:{outFile:c},...f||void 0===u?{}:{inventoryFile:u}}}var X=/* @__PURE__ */new Set([".ts",".mts",".cts",".js",".mjs",".cjs",".json"]);function Y(s){const a=s.watch??!0;let l,c,u=process.cwd(),d=!1,f=!1;async function p(e){if(d)f=!0;else{d=!0;try{const t=await Q({configPath:s.configPath,outFile:s.outPath,cwd:u});if(void 0===t.outFile)e?.error(`pll-codegen: nothing written — ${t.diagnostics.join(" ")}`);else if(!0!==s.quiet){e?.info(`pll-codegen: ${String(t.schema.globals.length)} globals, ${String(t.schema.collections.length)} collections → ${s.outPath}`);for(const o of t.diagnostics)e?.warn(`pll-codegen: ${o}`)}}catch(t){e?.error(`pll-codegen failed: ${t instanceof Error?t.message:String(t)}`)}finally{d=!1,f&&(f=!1,p(e))}}}return{name:"payload-live-preview:codegen",hooks:{"astro:config:setup":async({command:d,logger:f,config:g})=>{u=function(e){return void 0===e?process.cwd():e instanceof URL||e.startsWith("file:")?r(e):e}(g?.root),await p(f),a&&"dev"===d&&function(r){const a=t(o(u,s.configPath)),d=o(u,s.outPath);try{l=e(a,{recursive:!0},(e,t)=>{if(null===t)return;const s=o(a,t);s===d||s.includes(`${n}node_modules${n}`)||X.has(i(s))&&(clearTimeout(c),c=setTimeout(()=>{p(r)},100))})}catch(e){r?.warn(`pll-codegen watcher unavailable: ${e instanceof Error?e.message:String(e)}`)}}(f)},"astro:server:start":()=>{},"astro:build:start":()=>{clearTimeout(c),l?.close(),l=void 0}}}}export{Y as livePreviewCodegen};
2
2
  //# sourceMappingURL=codegen-astro.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"codegen-astro.js","names":["toPascalCase","slug","split","filter","Boolean","map","part","charAt","toUpperCase","slice","join","tsMorph","IDENTIFIER","nestedTypeName","parent","child","emitFieldMember","field","lines","options","markLocalizedAsDeprecated","localized","push","optional","required","name","test","replace","kind","hasMany","typeRef","blocks","length","block","typeName","base","target","literal","option","renderFieldType","emitBlockInterface","fields","emitAuxiliaries","prefix","seen","auxName","has","add","inner","blockTypeName","emitSlug","emitMap","slugs","collect","basePath","out","path","entry","loadTsMorph","createRequire","url","error","Error","cause","tsNode","Node","reportSkip","context","node","why","diagnostics","text","getText","snippet","getSourceFile","getBaseName","String","getStartLineNumber","where","unwrap","current","isParenthesizedExpression","isAsExpression","isSatisfiesExpression","isNonNullExpression","isTypeAssertion","getExpression","followAlias","declaration","isImportSpecifier","isImportClause","isNamespaceImport","isExportSpecifier","aliased","getSymbol","getAliasedSymbol","getDeclarations","definitionsOf","identifier","definitions","getDefinitionNodes","flatMap","valueOf","isVariableDeclaration","isPropertyAssignment","getInitializer","isExportAssignment","isShorthandPropertyAssignment","getNameNode","propertyValue","property","getProperty","hasProperty","resolveToObjectLiteral","Set","isObjectLiteralExpression","isCallExpression","getArguments","isIdentifier","resolved","isPropertyAccessExpression","owner","getName","resolveToArrayLiteral","isArrayLiteralExpression","expandElements","array","element","getElements","isSpreadElement","expanded","readStringProperty","value","isStringLiteral","isNoSubstitutionTemplateLiteral","getLiteralValue","readBooleanProperty","isTrueLiteral","isFalseLiteral","readArrayProperty","readRelationTarget","STRUCTURAL_SENTINEL","STRUCTURAL_TYPES","SCALAR_TYPE_MAP","textarea","email","richText","number","checkbox","date","code","point","HAS_MANY_SCALARS","extractFields","extractField","nestedFields","extractTabs","tabs","tab","extractBlocks","readOptions","type","declaredValue","extractSlugList","configLiteral","key","async","writeOut","content","mkdir","dirname","recursive","writeFile","generateTypes","cwd","process","absolute","isAbsolute","resolve","schema","project","Project","tsConfigFilePath","skipAddingFilesFromTsConfig","sourceFile","addSourceFileAtPathIfExists","configPath","globals","collections","resolveSourceFileDependencies","defaultExport","getDefaultExportSymbol","call","getDescendantsOfKind","SyntaxKind","CallExpression","callee","findConfigLiteral","extractSchema","header","slugAliases","emitTypes","inventory","buildPreviewInventory","outFile","inventoryFile","targets","empty","JSON","stringify","SOURCE_EXTENSIONS","livePreviewCodegen","watchEnabled","watch","watcher","timer","root","active","queued","regenerate","logger","result","outPath","quiet","info","diagnostic","warn","message","hooks","command","config","URL","startsWith","fileURLToPath","rootOf","directory","_event","file","changed","includes","sep","extname","clearTimeout","setTimeout","startWatching","close"],"sources":["../src/codegen/parser/names.ts","../src/codegen/emit/emit-types.ts","../src/codegen/parser/resolve.ts","../src/codegen/inventory.ts","../src/codegen/parser/extract-field.ts","../src/codegen/parser/extract-schema.ts","../src/codegen/index.ts","../src/codegen/astro-plugin.ts"],"sourcesContent":["/** Naming shared by the parser and the emitter. */\n\nexport function toPascalCase(slug: string): string {\n return slug\n .split(/[-_\\s]+/u)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join('');\n}\n","/**\n * Render an `ExtractedSchema` as one self-contained TypeScript file: an\n * interface per global and collection, nested interfaces for groups, arrays\n * and blocks, and the `PayloadGlobals`/`PayloadCollections`/`PayloadSlug` maps.\n */\nimport { toPascalCase } from '../parser/names';\nimport type {\n ExtractedBlock,\n ExtractedField,\n ExtractedSchema,\n ExtractedSlug,\n} from '../parser/types';\n\nexport interface EmitOptions {\n /** When true, localized fields carry a `@localized` JSDoc marker. */\n readonly markLocalizedAsDeprecated?: boolean;\n /** Header text at the top of the output. */\n readonly header?: string;\n}\n\nconst DEFAULT_HEADER =\n '// Auto-generated by payload-live-preview/codegen.\\n' +\n '// Do not edit by hand — run `pll-codegen` to regenerate.\\n' +\n '/* eslint-disable */';\nconst IDENTIFIER = /^[A-Za-z_$][\\w$]*$/u;\n\nfunction memberName(name: string): string {\n if (IDENTIFIER.test(name)) return name;\n return `'${name.replace(/\\\\/gu, '\\\\\\\\').replace(/'/gu, \"\\\\'\")}'`;\n}\n\nfunction nestedTypeName(parent: string, child: string): string {\n return `${parent}${toPascalCase(child)}`;\n}\n\nfunction renderFieldType(field: ExtractedField, parent: string): string {\n switch (field.kind) {\n case 'scalar':\n return field.hasMany === true ? `${field.typeRef}[]` : field.typeRef;\n case 'array':\n return `${nestedTypeName(parent, field.name)}[]`;\n case 'blocks': {\n if (field.blocks.length === 0) return 'unknown[]';\n const variants = field.blocks\n .map((block) => nestedTypeName(nestedTypeName(parent, field.name), block.typeName))\n .join(' | ');\n return `(${variants})[]`;\n }\n case 'group':\n return nestedTypeName(parent, field.name);\n case 'relationship': {\n const target =\n typeof field.target === 'string'\n ? `'${field.target}'`\n : field.target.map((slug) => `'${slug}'`).join(' | ');\n const base = `PayloadRelationship<${target}>`;\n return field.hasMany ? `${base}[]` : base;\n }\n case 'upload':\n return field.hasMany === true ? 'PayloadMedia[]' : 'PayloadMedia';\n case 'json':\n return 'unknown';\n case 'select': {\n if (field.options.length === 0) return field.hasMany ? 'string[]' : 'string';\n const literal = field.options.map((option) => `'${option}'`).join(' | ');\n return field.hasMany ? `(${literal})[]` : literal;\n }\n }\n}\n\nfunction emitFieldMember(\n field: ExtractedField,\n parent: string,\n lines: string[],\n options: EmitOptions,\n): void {\n if (options.markLocalizedAsDeprecated === true && field.localized) {\n lines.push(' /** @localized */');\n }\n const optional = field.required ? '' : '?';\n lines.push(` ${memberName(field.name)}${optional}: ${renderFieldType(field, parent)};`);\n}\n\nfunction emitBlockInterface(\n typeName: string,\n block: ExtractedBlock,\n lines: string[],\n options: EmitOptions,\n): void {\n lines.push(`export interface ${typeName} {`);\n lines.push(` blockType: '${block.slug}';`);\n for (const field of block.fields) emitFieldMember(field, typeName, lines, options);\n lines.push('}', '');\n}\n\nfunction emitAuxiliaries(\n prefix: string,\n fields: readonly ExtractedField[],\n lines: string[],\n seen: Set<string>,\n options: EmitOptions,\n): void {\n for (const field of fields) {\n const auxName = nestedTypeName(prefix, field.name);\n if (field.kind === 'array' || field.kind === 'group') {\n if (seen.has(auxName)) continue;\n seen.add(auxName);\n emitAuxiliaries(auxName, field.fields, lines, seen, options);\n lines.push(`export interface ${auxName} {`);\n for (const inner of field.fields) emitFieldMember(inner, auxName, lines, options);\n lines.push('}', '');\n } else if (field.kind === 'blocks') {\n for (const block of field.blocks) {\n const blockTypeName = nestedTypeName(auxName, block.typeName);\n if (seen.has(blockTypeName)) continue;\n seen.add(blockTypeName);\n emitAuxiliaries(blockTypeName, block.fields, lines, seen, options);\n emitBlockInterface(blockTypeName, block, lines, options);\n }\n }\n }\n}\n\nfunction emitSlug(\n slug: ExtractedSlug,\n lines: string[],\n seen: Set<string>,\n options: EmitOptions,\n): void {\n emitAuxiliaries(slug.typeName, slug.fields, lines, seen, options);\n lines.push(`export interface ${slug.typeName} {`);\n for (const field of slug.fields) emitFieldMember(field, slug.typeName, lines, options);\n lines.push('}');\n}\n\nfunction emitMap(name: string, slugs: readonly ExtractedSlug[], lines: string[]): void {\n if (slugs.length === 0) return;\n lines.push(`export type ${name} = {`);\n for (const slug of slugs) lines.push(` '${slug.slug}': ${slug.typeName};`);\n lines.push('};', '');\n}\n\n/** @internal */\nexport function emitTypes(schema: ExtractedSchema, options: EmitOptions = {}): string {\n const lines: string[] = [options.header ?? DEFAULT_HEADER, ''];\n lines.push('import type { PayloadMedia, PayloadRelationship } from \"payload-live-preview\";', '');\n const seen = new Set<string>();\n for (const slug of [...schema.globals, ...schema.collections]) {\n emitSlug(slug, lines, seen, options);\n lines.push('');\n }\n emitMap('PayloadGlobals', schema.globals, lines);\n emitMap('PayloadCollections', schema.collections, lines);\n const slugAliases: string[] = [];\n if (schema.globals.length > 0) slugAliases.push('keyof PayloadGlobals');\n if (schema.collections.length > 0) slugAliases.push('keyof PayloadCollections');\n if (slugAliases.length > 0) {\n lines.push(`export type PayloadSlug = ${slugAliases.join(' | ')};`, '');\n }\n return lines.join('\\n').replace(/\\n{3,}/gu, '\\n\\n');\n}\n","/**\n * Resolving the shapes a Payload config takes — literals, identifiers,\n * imports, wrappers, spreads — to the literals the extractors read. Every\n * shape that cannot be resolved becomes a diagnostic, never a silent gap.\n */\nimport { createRequire } from 'node:module';\nimport type * as TsMorphModule from 'ts-morph';\nimport type { ArrayLiteralExpression, Identifier, Node, ObjectLiteralExpression } from 'ts-morph';\n\nlet tsMorph: typeof TsMorphModule | undefined;\n\n/**\n * ts-morph on first use. It is an optional peer because it reads a Payload\n * config, and nothing else here needs a TypeScript compiler: an entry that only\n * prints its help, or refuses a usage error, must load without it. A static\n * import would not allow that — esbuild hoists an external import to the top of\n * the bundle even out of a dynamically imported module, so the binary would\n * resolve the peer before parsing its first flag. `pll migrate` loads it the\n * same way (src/migrate/ast.ts).\n */\nexport function loadTsMorph(): typeof TsMorphModule {\n if (tsMorph === undefined) {\n try {\n tsMorph = createRequire(import.meta.url)('ts-morph') as typeof TsMorphModule;\n } catch (error) {\n throw new Error('pll-codegen needs ts-morph: npm install --save-dev ts-morph', {\n cause: error,\n });\n }\n }\n return tsMorph;\n}\n\n/** The `Node` type guards, which every extractor reaches for. */\nexport function tsNode(): typeof TsMorphModule.Node {\n return loadTsMorph().Node;\n}\n\nexport interface ExtractContext {\n readonly diagnostics: string[];\n}\n\nfunction where(node: Node): string {\n return `${node.getSourceFile().getBaseName()}:${String(node.getStartLineNumber())}`;\n}\n\nfunction snippet(node: Node): string {\n const text = node.getText().replace(/\\s+/gu, ' ');\n return text.length > 60 ? `${text.slice(0, 57)}...` : text;\n}\n\nexport function reportSkip(context: ExtractContext, node: Node, why: string): void {\n context.diagnostics.push(`Skipped \"${snippet(node)}\" at ${where(node)}: ${why}.`);\n}\n\nfunction unwrap(node: Node): Node {\n let current = node;\n while (\n tsNode().isParenthesizedExpression(current) ||\n tsNode().isAsExpression(current) ||\n tsNode().isSatisfiesExpression(current) ||\n tsNode().isNonNullExpression(current) ||\n tsNode().isTypeAssertion(current)\n ) {\n current = current.getExpression();\n }\n return current;\n}\n\n/** An import or re-export binds a name but holds no value; the value is in the module it names. */\nfunction followAlias(declaration: Node): readonly Node[] {\n const isAlias =\n tsNode().isImportSpecifier(declaration) ||\n tsNode().isImportClause(declaration) ||\n tsNode().isNamespaceImport(declaration) ||\n tsNode().isExportSpecifier(declaration);\n if (!isAlias) return [declaration];\n const aliased = declaration.getSymbol()?.getAliasedSymbol();\n return aliased?.getDeclarations() ?? [declaration];\n}\n\n/** Follows imports through the language service; the binder is the fallback for what it cannot see. */\nfunction definitionsOf(identifier: Identifier): readonly Node[] {\n const definitions = identifier.getDefinitionNodes();\n const found =\n definitions.length > 0 ? definitions : (identifier.getSymbol()?.getDeclarations() ?? []);\n return found.flatMap(followAlias);\n}\n\nfunction valueOf(declaration: Node): Node | undefined {\n if (tsNode().isVariableDeclaration(declaration) || tsNode().isPropertyAssignment(declaration)) {\n return declaration.getInitializer();\n }\n if (tsNode().isExportAssignment(declaration)) return declaration.getExpression();\n if (tsNode().isShorthandPropertyAssignment(declaration)) return declaration.getNameNode();\n return undefined;\n}\n\n/** The value of a property, treating `{ fields }` shorthand as a reference to resolve. */\nexport function propertyValue(literal: ObjectLiteralExpression, name: string): Node | undefined {\n const property = literal.getProperty(name);\n if (property === undefined) return undefined;\n if (tsNode().isPropertyAssignment(property)) return property.getInitializer();\n if (tsNode().isShorthandPropertyAssignment(property)) return property.getNameNode();\n return undefined;\n}\n\nexport function hasProperty(literal: ObjectLiteralExpression, name: string): boolean {\n return literal.getProperty(name) !== undefined;\n}\n\nexport function resolveToObjectLiteral(\n node: Node | undefined,\n seen = new Set<Node>(),\n): ObjectLiteralExpression | undefined {\n if (node === undefined || seen.has(node)) return undefined;\n seen.add(node);\n const target = unwrap(node);\n if (tsNode().isObjectLiteralExpression(target)) return target;\n // `buildConfig({...})`, `defineConfig({...})`: the literal is the first argument.\n if (tsNode().isCallExpression(target)) {\n return resolveToObjectLiteral(target.getArguments()[0], seen);\n }\n if (tsNode().isIdentifier(target)) {\n for (const declaration of definitionsOf(target)) {\n const resolved = resolveToObjectLiteral(valueOf(declaration), seen);\n if (resolved !== undefined) return resolved;\n }\n }\n if (tsNode().isPropertyAccessExpression(target)) {\n const owner = resolveToObjectLiteral(target.getExpression(), seen);\n if (owner !== undefined) {\n return resolveToObjectLiteral(propertyValue(owner, target.getName()), seen);\n }\n }\n return undefined;\n}\n\nexport function resolveToArrayLiteral(\n node: Node | undefined,\n seen = new Set<Node>(),\n): ArrayLiteralExpression | undefined {\n if (node === undefined || seen.has(node)) return undefined;\n seen.add(node);\n const target = unwrap(node);\n if (tsNode().isArrayLiteralExpression(target)) return target;\n if (tsNode().isIdentifier(target)) {\n for (const declaration of definitionsOf(target)) {\n const resolved = resolveToArrayLiteral(valueOf(declaration), seen);\n if (resolved !== undefined) return resolved;\n }\n }\n if (tsNode().isPropertyAccessExpression(target)) {\n const owner = resolveToObjectLiteral(target.getExpression(), seen);\n if (owner !== undefined) {\n return resolveToArrayLiteral(propertyValue(owner, target.getName()), seen);\n }\n }\n return undefined;\n}\n\n/** The elements of an array with every spread expanded; a spread that cannot be resolved is reported and dropped. */\nexport function expandElements(array: ArrayLiteralExpression, context: ExtractContext): Node[] {\n const out: Node[] = [];\n for (const element of array.getElements()) {\n if (!tsNode().isSpreadElement(element)) {\n out.push(element);\n continue;\n }\n const expanded = resolveToArrayLiteral(element.getExpression());\n if (expanded === undefined) {\n reportSkip(\n context,\n element,\n 'could not resolve the spread to an array literal, so its entries are missing',\n );\n continue;\n }\n out.push(...expandElements(expanded, context));\n }\n return out;\n}\n\nexport function readStringProperty(\n literal: ObjectLiteralExpression,\n name: string,\n): string | undefined {\n const value = propertyValue(literal, name);\n if (value === undefined) return undefined;\n const target = unwrap(value);\n if (tsNode().isStringLiteral(target) || tsNode().isNoSubstitutionTemplateLiteral(target)) {\n return target.getLiteralValue();\n }\n return undefined;\n}\n\nexport function readBooleanProperty(\n literal: ObjectLiteralExpression,\n name: string,\n): boolean | undefined {\n const value = propertyValue(literal, name);\n if (value === undefined) return undefined;\n const target = unwrap(value);\n if (tsNode().isTrueLiteral(target)) return true;\n if (tsNode().isFalseLiteral(target)) return false;\n return undefined;\n}\n\nexport function readArrayProperty(\n literal: ObjectLiteralExpression,\n name: string,\n): ArrayLiteralExpression | undefined {\n return resolveToArrayLiteral(propertyValue(literal, name));\n}\n\n/** `relationTo`: one slug, several, or `'unknown'` when it is not a literal. */\nexport function readRelationTarget(literal: ObjectLiteralExpression): string | readonly string[] {\n const value = propertyValue(literal, 'relationTo');\n if (value === undefined) return 'unknown';\n const target = unwrap(value);\n if (tsNode().isStringLiteral(target)) return target.getLiteralValue();\n const array = resolveToArrayLiteral(target);\n if (array === undefined) return 'unknown';\n return array\n .getElements()\n .map(unwrap)\n .filter((element) => tsNode().isStringLiteral(element))\n .map((element) => element.getLiteralValue());\n}\n","/**\n * Which schema fields a binding can address, spelled the way the runtime\n * resolves them. Paths follow `@schema/walker` exactly — bindings are matched\n * against that rule at runtime, so any other spelling would be wrong here.\n */\n\nimport type { ExtractedField, ExtractedSchema, ExtractedSlug } from './parser/types';\n\n/** Sentinel the parser gives an unnamed structural container. */\nconst STRUCTURAL_SENTINEL = '__structural';\n\n/** One addressable field, spelled the way a binding must spell it. */\nexport interface PreviewInventoryField {\n /** Runtime binding path, e.g. `hero.title` or `slides.*.caption`. */\n readonly path: string;\n /** Extracted field kind: `scalar`, `array`, `blocks`, `group`, … */\n readonly kind: ExtractedField['kind'];\n readonly localized: boolean;\n readonly required: boolean;\n}\n\nexport interface PreviewInventoryEntry {\n readonly slug: string;\n readonly typeName: string;\n readonly fields: readonly PreviewInventoryField[];\n}\n\nexport interface PreviewInventory {\n readonly globals: readonly PreviewInventoryEntry[];\n readonly collections: readonly PreviewInventoryEntry[];\n}\n\nfunction collect(\n fields: readonly ExtractedField[],\n basePath: string,\n out: PreviewInventoryField[],\n): void {\n for (const field of fields) {\n // No segment, but its children still belong to the parent's surface.\n if (field.kind === 'group' && field.name === STRUCTURAL_SENTINEL) {\n collect(field.fields, basePath, out);\n continue;\n }\n const path = basePath === '' ? field.name : `${basePath}.${field.name}`;\n out.push({\n path,\n kind: field.kind,\n localized: field.localized,\n required: field.required,\n });\n if (field.kind === 'group') {\n collect(field.fields, path, out);\n } else if (field.kind === 'array') {\n collect(field.fields, `${path}.*`, out);\n } else if (field.kind === 'blocks') {\n for (const block of field.blocks) {\n collect(block.fields, `${path}.*.${block.slug}`, out);\n }\n }\n }\n}\n\nfunction entry(slug: ExtractedSlug): PreviewInventoryEntry {\n const fields: PreviewInventoryField[] = [];\n collect(slug.fields, '', fields);\n return { slug: slug.slug, typeName: slug.typeName, fields };\n}\n\n/** Flatten an extracted schema into every path a binding may address. @internal */\nexport function buildPreviewInventory(schema: ExtractedSchema): PreviewInventory {\n return {\n globals: schema.globals.map(entry),\n collections: schema.collections.map(entry),\n };\n}\n","/**\n * Field-level extraction: one Payload field literal → an `ExtractedField`,\n * recursing into groups, arrays, tabs and blocks.\n */\nimport type { ArrayLiteralExpression, ObjectLiteralExpression } from 'ts-morph';\nimport { toPascalCase } from './names';\nimport {\n expandElements,\n hasProperty,\n readArrayProperty,\n readBooleanProperty,\n readRelationTarget,\n readStringProperty,\n reportSkip,\n resolveToObjectLiteral,\n tsNode,\n type ExtractContext,\n} from './resolve';\nimport type { ExtractedBlock, ExtractedField, ExtractedScalarField } from './types';\n\n/** Name of an unnamed structural container; its fields flatten into the parent. */\nexport const STRUCTURAL_SENTINEL = '__structural';\nconst STRUCTURAL_TYPES = new Set(['tabs', 'row', 'collapsible']);\nconst SCALAR_TYPE_MAP: Readonly<Record<string, ExtractedScalarField['typeRef']>> = {\n text: 'string',\n textarea: 'string',\n email: 'string',\n richText: 'unknown',\n number: 'number',\n checkbox: 'boolean',\n date: 'string',\n code: 'string',\n point: '[number, number]',\n};\nconst HAS_MANY_SCALARS = new Set(['text', 'number']);\n\n/** Every field in `array`, spreads expanded and structural containers flattened. */\nexport function extractFields(\n array: ArrayLiteralExpression,\n context: ExtractContext,\n): ExtractedField[] {\n const out: ExtractedField[] = [];\n for (const element of expandElements(array, context)) {\n const literal = resolveToObjectLiteral(element);\n if (literal === undefined) {\n reportSkip(context, element, 'could not resolve the field to an object literal');\n continue;\n }\n const field = extractField(literal, context);\n if (field === undefined) continue;\n if (field.kind === 'group' && field.name === STRUCTURAL_SENTINEL) out.push(...field.fields);\n else out.push(field);\n }\n return out;\n}\n\nfunction nestedFields(literal: ObjectLiteralExpression, context: ExtractContext): ExtractedField[] {\n const array = readArrayProperty(literal, 'fields');\n if (array !== undefined) return extractFields(array, context);\n reportSkip(\n context,\n literal,\n hasProperty(literal, 'fields')\n ? 'its `fields` could not be resolved to an array literal'\n : 'it has no `fields`',\n );\n return [];\n}\n\nfunction extractTabs(literal: ObjectLiteralExpression, context: ExtractContext): ExtractedField[] {\n const tabs = readArrayProperty(literal, 'tabs');\n if (tabs === undefined) {\n reportSkip(context, literal, 'its `tabs` could not be resolved to an array literal');\n return [];\n }\n const out: ExtractedField[] = [];\n for (const element of expandElements(tabs, context)) {\n const tab = resolveToObjectLiteral(element);\n if (tab === undefined) {\n reportSkip(context, element, 'could not resolve the tab to an object literal');\n continue;\n }\n const name = readStringProperty(tab, 'name');\n const fields = nestedFields(tab, context);\n if (name === undefined) out.push(...fields);\n else out.push({ kind: 'group', name, required: false, localized: false, fields });\n }\n return out;\n}\n\nfunction extractBlocks(\n literal: ObjectLiteralExpression,\n context: ExtractContext,\n): ExtractedBlock[] {\n const blocks = readArrayProperty(literal, 'blocks');\n if (blocks === undefined) {\n reportSkip(context, literal, 'its `blocks` could not be resolved to an array literal');\n return [];\n }\n const out: ExtractedBlock[] = [];\n for (const element of expandElements(blocks, context)) {\n const block = resolveToObjectLiteral(element);\n if (block === undefined) {\n reportSkip(context, element, 'could not resolve the block to an object literal');\n continue;\n }\n const slug = readStringProperty(block, 'slug');\n if (slug === undefined) {\n reportSkip(context, element, 'a block needs a string `slug`');\n continue;\n }\n out.push({ slug, typeName: toPascalCase(slug), fields: nestedFields(block, context) });\n }\n return out;\n}\n\nfunction readOptions(literal: ObjectLiteralExpression, context: ExtractContext): string[] {\n const options = readArrayProperty(literal, 'options');\n if (options === undefined) {\n reportSkip(context, literal, 'its `options` could not be resolved to an array literal');\n return [];\n }\n const out: string[] = [];\n for (const element of expandElements(options, context)) {\n if (tsNode().isStringLiteral(element)) {\n out.push(element.getLiteralValue());\n continue;\n }\n const option = resolveToObjectLiteral(element);\n const value = option === undefined ? undefined : readStringProperty(option, 'value');\n if (value === undefined) reportSkip(context, element, 'an option needs a string or a `value`');\n else out.push(value);\n }\n return out;\n}\n\n/** One field, or `undefined` for a `ui` field (nothing to type) and for shapes reported as skipped. */\nexport function extractField(\n literal: ObjectLiteralExpression,\n context: ExtractContext,\n): ExtractedField | undefined {\n const type = readStringProperty(literal, 'type');\n if (type === undefined) {\n reportSkip(context, literal, 'it has no string `type`');\n return undefined;\n }\n if (type === 'ui') return undefined;\n const name = readStringProperty(literal, 'name');\n if (name === undefined && !STRUCTURAL_TYPES.has(type)) {\n reportSkip(context, literal, `a ${type} field needs a string \\`name\\``);\n return undefined;\n }\n const base = {\n name: name ?? STRUCTURAL_SENTINEL,\n required: readBooleanProperty(literal, 'required') ?? false,\n localized: readBooleanProperty(literal, 'localized') ?? false,\n };\n const hasMany = readBooleanProperty(literal, 'hasMany') ?? false;\n switch (type) {\n case 'array':\n return { ...base, kind: 'array', fields: nestedFields(literal, context) };\n case 'group':\n case 'row':\n case 'collapsible':\n return { ...base, kind: 'group', fields: nestedFields(literal, context) };\n case 'tabs':\n return { ...base, kind: 'group', fields: extractTabs(literal, context) };\n case 'blocks':\n return { ...base, kind: 'blocks', blocks: extractBlocks(literal, context) };\n case 'relationship':\n return { ...base, kind: 'relationship', target: readRelationTarget(literal), hasMany };\n case 'upload': {\n const target = readRelationTarget(literal);\n return {\n ...base,\n kind: 'upload',\n target: (typeof target === 'string' ? target : target[0]) ?? 'media',\n hasMany,\n };\n }\n case 'json':\n return { ...base, kind: 'json' };\n case 'select':\n case 'radio':\n return {\n ...base,\n kind: 'select',\n options: readOptions(literal, context),\n hasMany: type === 'select' && hasMany,\n };\n default:\n return {\n ...base,\n kind: 'scalar',\n typeRef: SCALAR_TYPE_MAP[type] ?? 'unknown',\n hasMany: HAS_MANY_SCALARS.has(type) && hasMany,\n };\n }\n}\n","/**\n * Schema-level extraction: open the config, find every collection and global,\n * walk into them. Lenient by design — a Payload config is a full TypeScript\n * program, so the common shapes are recognised and everything else becomes a\n * diagnostic rather than a silently empty type.\n */\nimport type { Node, ObjectLiteralExpression, Project, SourceFile } from 'ts-morph';\nimport { extractFields } from './extract-field';\nimport { toPascalCase } from './names';\nimport {\n expandElements,\n hasProperty,\n propertyValue,\n readArrayProperty,\n readStringProperty,\n reportSkip,\n resolveToArrayLiteral,\n resolveToObjectLiteral,\n loadTsMorph,\n tsNode,\n type ExtractContext,\n} from './resolve';\nimport type { ExtractedSchema, ExtractedSlug } from './types';\n\nexport interface ExtractSchemaOptions {\n /** Absolute or relative path to `payload.config.ts`. */\n readonly configPath: string;\n /** When provided, used instead of constructing a fresh ts-morph project. */\n readonly project?: Project;\n /** A `tsconfig.json` whose module resolution lets cross-file imports be followed. */\n readonly tsConfigFilePath?: string;\n}\n\n/**\n * What a default export declaration holds. TypeScript only ever declares the\n * `default` export as an export assignment, an export specifier, or a function\n * or class declaration — `export default config` keeps the variable's own\n * declaration out of it — so a variable declaration never arrives here.\n */\nfunction declaredValue(declaration: Node): Node | undefined {\n if (tsNode().isExportAssignment(declaration)) return declaration.getExpression();\n return undefined;\n}\n\nfunction findConfigLiteral(\n sourceFile: SourceFile,\n context: ExtractContext,\n): ObjectLiteralExpression | undefined {\n const defaultExport = sourceFile.getDefaultExportSymbol();\n if (defaultExport === undefined) {\n context.diagnostics.push('payload.config.ts has no default export.');\n return undefined;\n }\n for (const declaration of defaultExport.getDeclarations()) {\n const literal = resolveToObjectLiteral(declaredValue(declaration));\n if (literal !== undefined) return literal;\n }\n for (const call of sourceFile.getDescendantsOfKind(loadTsMorph().SyntaxKind.CallExpression)) {\n const callee = call.getExpression();\n if (!tsNode().isIdentifier(callee) || callee.getText() !== 'buildConfig') continue;\n const literal = resolveToObjectLiteral(call.getArguments()[0]);\n if (literal !== undefined) return literal;\n }\n return undefined;\n}\n\nfunction extractSlugList(\n configLiteral: ObjectLiteralExpression,\n key: 'globals' | 'collections',\n context: ExtractContext,\n): ExtractedSlug[] {\n const value = propertyValue(configLiteral, key);\n if (value === undefined) return [];\n const array = resolveToArrayLiteral(value);\n if (array === undefined) {\n reportSkip(context, value, `could not resolve \\`${key}\\` to an array literal`);\n return [];\n }\n const out: ExtractedSlug[] = [];\n for (const element of expandElements(array, context)) {\n const literal = resolveToObjectLiteral(element);\n if (literal === undefined) {\n reportSkip(context, element, 'could not resolve the config entry to an object literal');\n continue;\n }\n const slug = readStringProperty(literal, 'slug');\n if (slug === undefined) {\n reportSkip(context, element, 'the config entry has no string `slug`');\n continue;\n }\n const fields = readArrayProperty(literal, 'fields');\n if (fields === undefined) {\n reportSkip(\n context,\n literal,\n hasProperty(literal, 'fields')\n ? `the \\`fields\\` of \"${slug}\" could not be resolved to an array literal`\n : `\"${slug}\" has no \\`fields\\``,\n );\n }\n out.push({\n slug,\n typeName: toPascalCase(slug),\n fields: fields === undefined ? [] : extractFields(fields, context),\n });\n }\n return out;\n}\n\n/** @internal */\nexport function extractSchema(options: ExtractSchemaOptions): ExtractedSchema {\n const project =\n options.project ??\n new (loadTsMorph().Project)(\n options.tsConfigFilePath !== undefined\n ? { tsConfigFilePath: options.tsConfigFilePath }\n : { skipAddingFilesFromTsConfig: true },\n );\n const sourceFile = project.addSourceFileAtPathIfExists(options.configPath);\n if (sourceFile === undefined) {\n return { globals: [], collections: [], diagnostics: [`Could not open ${options.configPath}`] };\n }\n project.resolveSourceFileDependencies();\n const context: ExtractContext = { diagnostics: [] };\n const configLiteral = findConfigLiteral(sourceFile, context);\n if (configLiteral === undefined) {\n return {\n globals: [],\n collections: [],\n diagnostics: [\n ...context.diagnostics,\n 'Could not locate a buildConfig({...}) call or `export default {...}` in the config file.',\n ],\n };\n }\n const globals = extractSlugList(configLiteral, 'globals', context);\n const collections = extractSlugList(configLiteral, 'collections', context);\n return { globals, collections, diagnostics: context.diagnostics };\n}\n","/**\n * Programmatic codegen API: `generateTypes({ configPath, outFile })` parses a\n * Payload config and writes the TypeScript types and, optionally, the preview\n * inventory. Requires ts-morph.\n */\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, isAbsolute, resolve } from 'node:path';\nimport { emitTypes, type EmitOptions } from './emit/emit-types';\nimport { buildPreviewInventory, type PreviewInventory } from './inventory';\nimport { extractSchema, type ExtractSchemaOptions } from './parser/extract-schema';\nimport type { ExtractedSchema } from './parser/types';\n\nexport {\n annotateTemplates,\n annotatablePaths,\n formatAnnotateReport,\n ANNOTATABLE_EXTENSIONS,\n type AnnotateOptions,\n type AnnotateResult,\n type AnnotateFileResult,\n type AnnotationCandidate,\n type AnnotationRefusal,\n type AnnotatableSchema,\n} from './annotate/index';\n\nexport interface GenerateTypesOptions\n extends Pick<ExtractSchemaOptions, 'configPath' | 'project' | 'tsConfigFilePath'>, EmitOptions {\n /** Where to write the generated code; `code` is returned either way. */\n readonly outFile?: string;\n /** Resolves relative paths. Defaults to `process.cwd()`. */\n readonly cwd?: string;\n /** Where to write the preview inventory as JSON: every path a binding may address. */\n readonly inventoryFile?: string;\n}\n\nexport interface GenerateTypesResult {\n readonly code: string;\n /** Extraction diagnostics, plus a note when nothing was written. */\n readonly diagnostics: readonly string[];\n readonly schema: ExtractedSchema;\n /** The types file actually written; absent when writing was refused. */\n readonly outFile?: string;\n /** Always produced; written to disk only when `inventoryFile` is set. */\n readonly inventory: PreviewInventory;\n readonly inventoryFile?: string;\n}\n\nasync function writeOut(path: string, content: string): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, content, 'utf8');\n}\n\n/** Parse the config and write the types, never writing an empty schema over a consumer's file. */\nexport async function generateTypes(options: GenerateTypesOptions): Promise<GenerateTypesResult> {\n const cwd = options.cwd ?? process.cwd();\n const absolute = (path: string): string => (isAbsolute(path) ? path : resolve(cwd, path));\n const schema = extractSchema({\n configPath: absolute(options.configPath),\n ...(options.project !== undefined ? { project: options.project } : {}),\n ...(options.tsConfigFilePath !== undefined\n ? { tsConfigFilePath: options.tsConfigFilePath }\n : {}),\n });\n const code = emitTypes(schema, options);\n const inventory = buildPreviewInventory(schema);\n const diagnostics = [...schema.diagnostics];\n const outFile = options.outFile === undefined ? undefined : absolute(options.outFile);\n const inventoryFile =\n options.inventoryFile === undefined ? undefined : absolute(options.inventoryFile);\n const targets = [outFile, inventoryFile].filter((path): path is string => path !== undefined);\n const empty = schema.globals.length + schema.collections.length === 0;\n if (empty && targets.length > 0) {\n diagnostics.push(\n `Nothing written: the schema is empty (0 globals, 0 collections), so ${targets.join(' and ')} ` +\n 'were left as they are.',\n );\n } else {\n if (outFile !== undefined) await writeOut(outFile, code);\n // Stable key order and a trailing newline keep the inventory diffable.\n if (inventoryFile !== undefined) {\n await writeOut(inventoryFile, `${JSON.stringify(inventory, null, 2)}\\n`);\n }\n }\n return {\n code,\n diagnostics,\n schema,\n inventory,\n ...(!empty && outFile !== undefined ? { outFile } : {}),\n ...(!empty && inventoryFile !== undefined ? { inventoryFile } : {}),\n };\n}\n\nexport { buildPreviewInventory } from './inventory';\nexport type { PreviewInventory, PreviewInventoryEntry, PreviewInventoryField } from './inventory';\nexport { extractSchema } from './parser/extract-schema';\nexport { emitTypes } from './emit/emit-types';\nexport type { ExtractedSchema, ExtractedSlug, ExtractedField } from './parser/types';\n","/**\n * Astro integration: regenerate the types on startup and, during `astro dev`,\n * whenever a .ts, .mts, .cts, .js, .mjs, .cjs or .json file changes in the\n * Payload config's directory or below it, except under node_modules and the\n * output file itself. Paths are relative to Astro's root. Uses `fs.watch`; no\n * watcher dependency.\n */\nimport { watch, type FSWatcher } from 'node:fs';\nimport { dirname, extname, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { generateTypes } from './index';\n\nexport interface AstroCodegenOptions {\n /** Path to `payload.config.ts` (absolute or relative to Astro's root). */\n readonly configPath: string;\n /** Output path for generated types (absolute or relative to Astro's root). */\n readonly outPath: string;\n /**\n * Re-run during `astro dev` when a .ts, .mts, .cts, .js, .mjs, .cjs or .json\n * file in or below the config's directory changes. Default `true`.\n */\n readonly watch?: boolean;\n /** Only log errors. Default `false`. */\n readonly quiet?: boolean;\n}\n\ninterface AstroLogger {\n readonly info: (msg: string) => void;\n readonly warn: (msg: string) => void;\n readonly error: (msg: string) => void;\n}\n\ninterface AstroIntegration {\n readonly name: string;\n readonly hooks: Readonly<{\n readonly 'astro:config:setup'?: (params: {\n readonly command: string;\n readonly logger?: AstroLogger;\n readonly config?: { readonly root?: URL | string };\n }) => Promise<void> | void;\n readonly 'astro:server:start'?: () => void;\n readonly 'astro:build:start'?: () => Promise<void> | void;\n }>;\n}\n\nconst SOURCE_EXTENSIONS = new Set(['.ts', '.mts', '.cts', '.js', '.mjs', '.cjs', '.json']);\nconst DEBOUNCE_MS = 100;\n\nfunction rootOf(root: URL | string | undefined): string {\n if (root === undefined) return process.cwd();\n if (root instanceof URL) return fileURLToPath(root);\n return root.startsWith('file:') ? fileURLToPath(root) : root;\n}\n\nexport function livePreviewCodegen(options: AstroCodegenOptions): AstroIntegration {\n const watchEnabled = options.watch ?? true;\n let root = process.cwd();\n let watcher: FSWatcher | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let active = false;\n let queued = false;\n\n async function regenerate(logger: AstroLogger | undefined): Promise<void> {\n if (active) {\n queued = true;\n return;\n }\n active = true;\n try {\n const result = await generateTypes({\n configPath: options.configPath,\n outFile: options.outPath,\n cwd: root,\n });\n if (result.outFile === undefined) {\n logger?.error(`pll-codegen: nothing written — ${result.diagnostics.join(' ')}`);\n } else if (options.quiet !== true) {\n logger?.info(\n `pll-codegen: ${String(result.schema.globals.length)} globals, ${String(result.schema.collections.length)} collections → ${options.outPath}`,\n );\n for (const diagnostic of result.diagnostics) logger?.warn(`pll-codegen: ${diagnostic}`);\n }\n } catch (error) {\n logger?.error(\n `pll-codegen failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n } finally {\n active = false;\n if (queued) {\n queued = false;\n void regenerate(logger);\n }\n }\n }\n\n function startWatching(logger: AstroLogger | undefined): void {\n const directory = dirname(resolve(root, options.configPath));\n const outPath = resolve(root, options.outPath);\n try {\n // The output file may live under the watched directory; writing it must not retrigger.\n watcher = watch(directory, { recursive: true }, (_event, file) => {\n if (file === null) return;\n const changed = resolve(directory, file);\n if (changed === outPath || changed.includes(`${sep}node_modules${sep}`)) return;\n if (!SOURCE_EXTENSIONS.has(extname(changed))) return;\n clearTimeout(timer);\n timer = setTimeout(() => void regenerate(logger), DEBOUNCE_MS);\n });\n } catch (error) {\n logger?.warn(\n `pll-codegen watcher unavailable: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n return {\n name: 'payload-live-preview:codegen',\n hooks: {\n 'astro:config:setup': async ({ command, logger, config }) => {\n root = rootOf(config?.root);\n await regenerate(logger);\n if (watchEnabled && command === 'dev') startWatching(logger);\n },\n 'astro:server:start': () => undefined,\n 'astro:build:start': () => {\n clearTimeout(timer);\n watcher?.close();\n watcher = undefined;\n },\n },\n };\n}\n"],"mappings":"2OAEO,SAASA,EAAaC,GAC3B,OAAOA,EACJC,MAAM,YACNC,OAAOC,SACPC,IAAKC,GAASA,EAAKC,OAAO,GAAGC,cAAgBF,EAAKG,MAAM,IACxDC,KAAK,GACV,CCYA,ICXIC,EDeEC,EAAa,sBAOnB,SAASC,EAAeC,EAAgBC,GACtC,MAAO,GAAGD,IAASd,EAAae,IAClC,CAqCA,SAASC,EACPC,EACAH,EACAI,EACAC,IAE0C,IAAtCA,EAAQC,2BAAsCH,EAAMI,WACtDH,EAAMI,KAAK,uBAEb,MAAMC,EAAWN,EAAMO,SAAW,GAAK,IArDzC,IAAoBC,EAsDlBP,EAAMI,KAAK,KAtDOG,EAsDSR,EAAMQ,KArD7Bb,EAAWc,KAAKD,GAAcA,EAC3B,IAAIA,EAAKE,QAAQ,OAAQ,QAAQA,QAAQ,MAAO,YAoDdJ,MA7C3C,SAAyBN,EAAuBH,GAC9C,OAAQG,EAAMW,MACZ,IAAK,SACH,OAAyB,IAAlBX,EAAMY,QAAmB,GAAGZ,EAAMa,YAAcb,EAAMa,QAC/D,IAAK,QACH,MAAO,GAAGjB,EAAeC,EAAQG,EAAMQ,UACzC,IAAK,SACH,OAA4B,IAAxBR,EAAMc,OAAOC,OAAqB,YAI/B,IAHUf,EAAMc,OACpB1B,IAAK4B,GAAUpB,EAAeA,EAAeC,EAAQG,EAAMQ,MA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O,CACL,qBAAsB9D,OAAS+D,UAAST,SAAQU,aAC9Cd,EAvER,SAAgBA,GACd,YAAa,IAATA,EAA2BzC,QAAQD,MACnC0C,aAAgBe,KACbf,EAAKgB,WAAW,SADSC,EAAcjB,GACUA,CAC1D,CAmEekB,CAAOJ,GAAQd,YAChBG,EAAWC,GACbR,GAA4B,QAAZiB,GA1B1B,SAAuBT,GACrB,MAAMe,EAAYjE,EAAQQ,EAAQsC,EAAMrM,EAAQuK,aAC1CoC,EAAU5C,EAAQsC,EAAMrM,EAAQ2M,SACtC,IAEER,EAAUD,EAAMsB,EAAW,CAAEhE,WAAW,GAAQ,CAACiE,EAAQC,KACvD,GAAa,OAATA,EAAe,OACnB,MAAMC,EAAU5D,EAAQyD,EAAWE,GAC/BC,IAAYhB,GAAWgB,EAAQC,SAAS,GAAGC,gBAAkBA,MAC5D9B,EAAkBpK,IAAImM,EAAQH,MACnCI,aAAa3B,GACbA,EAAQ4B,WAAW,KAAWxB,EAAWC,IA5D7B,OA8DhB,OAAS/J,GACP+J,GAAQM,KACN,oCAAoCrK,aAAiBC,MAAQD,EAAMsK,QAAUvJ,OAAOf,KAExF,CACF,CAQ6CuL,CAAcxB,IAEvD,qBAAsB,OACtB,oBAAqB,KACnBsB,aAAa3B,GACbD,GAAS+B,QACT/B,OAAU,IAIlB,Q","ignoreList":[]}
1
+ {"version":3,"file":"codegen-astro.js","names":["toPascalCase","slug","split","filter","Boolean","map","part","charAt","toUpperCase","slice","join","tsMorph","IDENTIFIER","nestedTypeName","parent","child","emitFieldMember","field","lines","options","markLocalizedAsDeprecated","localized","push","optional","required","name","test","replace","kind","hasMany","typeRef","blocks","length","block","typeName","base","target","literal","option","renderFieldType","emitBlockInterface","fields","emitAuxiliaries","prefix","seen","auxName","has","add","inner","blockTypeName","emitSlug","emitMap","slugs","collect","basePath","out","path","entry","loadTsMorph","createRequire","url","error","Error","cause","tsNode","Node","reportSkip","context","node","why","diagnostics","text","getText","snippet","getSourceFile","getBaseName","String","getStartLineNumber","where","unwrap","current","isParenthesizedExpression","isAsExpression","isSatisfiesExpression","isNonNullExpression","isTypeAssertion","getExpression","followAlias","declaration","isImportSpecifier","isImportClause","isNamespaceImport","isExportSpecifier","aliased","getSymbol","getAliasedSymbol","getDeclarations","definitionsOf","identifier","definitions","getDefinitionNodes","flatMap","valueOf","isVariableDeclaration","isPropertyAssignment","getInitializer","isExportAssignment","isShorthandPropertyAssignment","getNameNode","propertyValue","property","getProperty","hasProperty","returnedBy","call","callee","isIdentifier","fn","isFunctionDeclaration","isArrowFunction","isFunctionExpression","body","getBody","isBlock","only","rest","getStatements","isReturnStatement","resolveToObjectLiteral","Set","isObjectLiteralExpression","isCallExpression","returned","getProperties","some","isSpreadAssignment","getArguments","resolved","isPropertyAccessExpression","owner","getName","resolveToArrayLiteral","isArrayLiteralExpression","expandElements","array","element","getElements","isSpreadElement","expanded","readStringProperty","value","isStringLiteral","isNoSubstitutionTemplateLiteral","getLiteralValue","readBooleanProperty","isTrueLiteral","isFalseLiteral","readArrayProperty","readRelationTarget","STRUCTURAL_SENTINEL","STRUCTURAL_TYPES","SCALAR_TYPE_MAP","textarea","email","richText","number","checkbox","date","code","point","HAS_MANY_SCALARS","extractFields","extractField","nestedFields","extractTabs","tabs","tab","extractBlocks","readOptions","type","declaredValue","extractSlugList","configLiteral","key","async","writeOut","content","mkdir","dirname","recursive","writeFile","generateTypes","cwd","process","absolute","isAbsolute","resolve","schema","project","Project","tsConfigFilePath","skipAddingFilesFromTsConfig","sourceFile","addSourceFileAtPathIfExists","configPath","globals","collections","resolveSourceFileDependencies","defaultExport","getDefaultExportSymbol","getDescendantsOfKind","SyntaxKind","CallExpression","findConfigLiteral","extractSchema","header","slugAliases","emitTypes","inventory","buildPreviewInventory","outFile","inventoryFile","targets","empty","JSON","stringify","SOURCE_EXTENSIONS","livePreviewCodegen","watchEnabled","watch","watcher","timer","root","active","queued","regenerate","logger","result","outPath","quiet","info","diagnostic","warn","message","hooks","command","config","URL","startsWith","fileURLToPath","rootOf","directory","_event","file","changed","includes","sep","extname","clearTimeout","setTimeout","startWatching","close"],"sources":["../src/codegen/parser/names.ts","../src/codegen/emit/emit-types.ts","../src/codegen/parser/resolve.ts","../src/codegen/inventory.ts","../src/codegen/parser/extract-field.ts","../src/codegen/parser/extract-schema.ts","../src/codegen/index.ts","../src/codegen/astro-plugin.ts"],"sourcesContent":["/** Naming shared by the parser and the emitter. */\n\nexport function toPascalCase(slug: string): string {\n return slug\n .split(/[-_\\s]+/u)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join('');\n}\n","/**\n * Render an `ExtractedSchema` as one self-contained TypeScript file: an\n * interface per global and collection, nested interfaces for groups, arrays\n * and blocks, and the `PayloadGlobals`/`PayloadCollections`/`PayloadSlug` maps.\n */\nimport { toPascalCase } from '../parser/names';\nimport type {\n ExtractedBlock,\n ExtractedField,\n ExtractedSchema,\n ExtractedSlug,\n} from '../parser/types';\n\nexport interface EmitOptions {\n /** When true, localized fields carry a `@localized` JSDoc marker. */\n readonly markLocalizedAsDeprecated?: boolean;\n /** Header text at the top of the output. */\n readonly header?: string;\n}\n\nconst DEFAULT_HEADER =\n '// Auto-generated by payload-live-preview/codegen.\\n' +\n '// Do not edit by hand — run `pll-codegen` to regenerate.\\n' +\n '/* eslint-disable */';\nconst IDENTIFIER = /^[A-Za-z_$][\\w$]*$/u;\n\nfunction memberName(name: string): string {\n if (IDENTIFIER.test(name)) return name;\n return `'${name.replace(/\\\\/gu, '\\\\\\\\').replace(/'/gu, \"\\\\'\")}'`;\n}\n\nfunction nestedTypeName(parent: string, child: string): string {\n return `${parent}${toPascalCase(child)}`;\n}\n\nfunction renderFieldType(field: ExtractedField, parent: string): string {\n switch (field.kind) {\n case 'scalar':\n return field.hasMany === true ? `${field.typeRef}[]` : field.typeRef;\n case 'array':\n return `${nestedTypeName(parent, field.name)}[]`;\n case 'blocks': {\n if (field.blocks.length === 0) return 'unknown[]';\n const variants = field.blocks\n .map((block) => nestedTypeName(nestedTypeName(parent, field.name), block.typeName))\n .join(' | ');\n return `(${variants})[]`;\n }\n case 'group':\n return nestedTypeName(parent, field.name);\n case 'relationship': {\n const target =\n typeof field.target === 'string'\n ? `'${field.target}'`\n : field.target.map((slug) => `'${slug}'`).join(' | ');\n const base = `PayloadRelationship<${target}>`;\n return field.hasMany ? `${base}[]` : base;\n }\n case 'upload':\n return field.hasMany === true ? 'PayloadMedia[]' : 'PayloadMedia';\n case 'json':\n return 'unknown';\n case 'select': {\n if (field.options.length === 0) return field.hasMany ? 'string[]' : 'string';\n const literal = field.options.map((option) => `'${option}'`).join(' | ');\n return field.hasMany ? `(${literal})[]` : literal;\n }\n }\n}\n\nfunction emitFieldMember(\n field: ExtractedField,\n parent: string,\n lines: string[],\n options: EmitOptions,\n): void {\n if (options.markLocalizedAsDeprecated === true && field.localized) {\n lines.push(' /** @localized */');\n }\n const optional = field.required ? '' : '?';\n lines.push(` ${memberName(field.name)}${optional}: ${renderFieldType(field, parent)};`);\n}\n\nfunction emitBlockInterface(\n typeName: string,\n block: ExtractedBlock,\n lines: string[],\n options: EmitOptions,\n): void {\n lines.push(`export interface ${typeName} {`);\n lines.push(` blockType: '${block.slug}';`);\n for (const field of block.fields) emitFieldMember(field, typeName, lines, options);\n lines.push('}', '');\n}\n\nfunction emitAuxiliaries(\n prefix: string,\n fields: readonly ExtractedField[],\n lines: string[],\n seen: Set<string>,\n options: EmitOptions,\n): void {\n for (const field of fields) {\n const auxName = nestedTypeName(prefix, field.name);\n if (field.kind === 'array' || field.kind === 'group') {\n if (seen.has(auxName)) continue;\n seen.add(auxName);\n emitAuxiliaries(auxName, field.fields, lines, seen, options);\n lines.push(`export interface ${auxName} {`);\n for (const inner of field.fields) emitFieldMember(inner, auxName, lines, options);\n lines.push('}', '');\n } else if (field.kind === 'blocks') {\n for (const block of field.blocks) {\n const blockTypeName = nestedTypeName(auxName, block.typeName);\n if (seen.has(blockTypeName)) continue;\n seen.add(blockTypeName);\n emitAuxiliaries(blockTypeName, block.fields, lines, seen, options);\n emitBlockInterface(blockTypeName, block, lines, options);\n }\n }\n }\n}\n\nfunction emitSlug(\n slug: ExtractedSlug,\n lines: string[],\n seen: Set<string>,\n options: EmitOptions,\n): void {\n emitAuxiliaries(slug.typeName, slug.fields, lines, seen, options);\n lines.push(`export interface ${slug.typeName} {`);\n for (const field of slug.fields) emitFieldMember(field, slug.typeName, lines, options);\n lines.push('}');\n}\n\nfunction emitMap(name: string, slugs: readonly ExtractedSlug[], lines: string[]): void {\n if (slugs.length === 0) return;\n lines.push(`export type ${name} = {`);\n for (const slug of slugs) lines.push(` '${slug.slug}': ${slug.typeName};`);\n lines.push('};', '');\n}\n\n/** @internal */\nexport function emitTypes(schema: ExtractedSchema, options: EmitOptions = {}): string {\n const lines: string[] = [options.header ?? DEFAULT_HEADER, ''];\n lines.push('import type { PayloadMedia, PayloadRelationship } from \"payload-live-preview\";', '');\n const seen = new Set<string>();\n for (const slug of [...schema.globals, ...schema.collections]) {\n emitSlug(slug, lines, seen, options);\n lines.push('');\n }\n emitMap('PayloadGlobals', schema.globals, lines);\n emitMap('PayloadCollections', schema.collections, lines);\n const slugAliases: string[] = [];\n if (schema.globals.length > 0) slugAliases.push('keyof PayloadGlobals');\n if (schema.collections.length > 0) slugAliases.push('keyof PayloadCollections');\n if (slugAliases.length > 0) {\n lines.push(`export type PayloadSlug = ${slugAliases.join(' | ')};`, '');\n }\n return lines.join('\\n').replace(/\\n{3,}/gu, '\\n\\n');\n}\n","/**\n * Resolving the shapes a Payload config takes — literals, identifiers,\n * imports, wrappers, spreads — to the literals the extractors read. Every\n * shape that cannot be resolved becomes a diagnostic, never a silent gap.\n */\nimport { createRequire } from 'node:module';\nimport type * as TsMorphModule from 'ts-morph';\nimport type {\n ArrayLiteralExpression,\n CallExpression,\n Identifier,\n Node,\n ObjectLiteralExpression,\n} from 'ts-morph';\n\nlet tsMorph: typeof TsMorphModule | undefined;\n\n/**\n * ts-morph on first use. It is an optional peer because it reads a Payload\n * config, and nothing else here needs a TypeScript compiler: an entry that only\n * prints its help, or refuses a usage error, must load without it. A static\n * import would not allow that — esbuild hoists an external import to the top of\n * the bundle even out of a dynamically imported module, so the binary would\n * resolve the peer before parsing its first flag. `pll migrate` loads it the\n * same way (src/migrate/ast.ts).\n */\nexport function loadTsMorph(): typeof TsMorphModule {\n if (tsMorph === undefined) {\n try {\n tsMorph = createRequire(import.meta.url)('ts-morph') as typeof TsMorphModule;\n } catch (error) {\n throw new Error('pll-codegen needs ts-morph: npm install --save-dev ts-morph', {\n cause: error,\n });\n }\n }\n return tsMorph;\n}\n\n/** The `Node` type guards, which every extractor reaches for. */\nexport function tsNode(): typeof TsMorphModule.Node {\n return loadTsMorph().Node;\n}\n\nexport interface ExtractContext {\n readonly diagnostics: string[];\n}\n\nfunction where(node: Node): string {\n return `${node.getSourceFile().getBaseName()}:${String(node.getStartLineNumber())}`;\n}\n\nfunction snippet(node: Node): string {\n const text = node.getText().replace(/\\s+/gu, ' ');\n return text.length > 60 ? `${text.slice(0, 57)}...` : text;\n}\n\nexport function reportSkip(context: ExtractContext, node: Node, why: string): void {\n context.diagnostics.push(`Skipped \"${snippet(node)}\" at ${where(node)}: ${why}.`);\n}\n\nfunction unwrap(node: Node): Node {\n let current = node;\n while (\n tsNode().isParenthesizedExpression(current) ||\n tsNode().isAsExpression(current) ||\n tsNode().isSatisfiesExpression(current) ||\n tsNode().isNonNullExpression(current) ||\n tsNode().isTypeAssertion(current)\n ) {\n current = current.getExpression();\n }\n return current;\n}\n\n/** An import or re-export binds a name but holds no value; the value is in the module it names. */\nfunction followAlias(declaration: Node): readonly Node[] {\n const isAlias =\n tsNode().isImportSpecifier(declaration) ||\n tsNode().isImportClause(declaration) ||\n tsNode().isNamespaceImport(declaration) ||\n tsNode().isExportSpecifier(declaration);\n if (!isAlias) return [declaration];\n const aliased = declaration.getSymbol()?.getAliasedSymbol();\n return aliased?.getDeclarations() ?? [declaration];\n}\n\n/** Follows imports through the language service; the binder is the fallback for what it cannot see. */\nfunction definitionsOf(identifier: Identifier): readonly Node[] {\n const definitions = identifier.getDefinitionNodes();\n const found =\n definitions.length > 0 ? definitions : (identifier.getSymbol()?.getDeclarations() ?? []);\n return found.flatMap(followAlias);\n}\n\nfunction valueOf(declaration: Node): Node | undefined {\n if (tsNode().isVariableDeclaration(declaration) || tsNode().isPropertyAssignment(declaration)) {\n return declaration.getInitializer();\n }\n if (tsNode().isExportAssignment(declaration)) return declaration.getExpression();\n if (tsNode().isShorthandPropertyAssignment(declaration)) return declaration.getNameNode();\n return undefined;\n}\n\n/** The value of a property, treating `{ fields }` shorthand as a reference to resolve. */\nexport function propertyValue(literal: ObjectLiteralExpression, name: string): Node | undefined {\n const property = literal.getProperty(name);\n if (property === undefined) return undefined;\n if (tsNode().isPropertyAssignment(property)) return property.getInitializer();\n if (tsNode().isShorthandPropertyAssignment(property)) return property.getNameNode();\n return undefined;\n}\n\nexport function hasProperty(literal: ObjectLiteralExpression, name: string): boolean {\n return literal.getProperty(name) !== undefined;\n}\n\n/**\n * What a function in this project hands back: an arrow's expression, or the\n * `return` of a body with nothing else in it. A body that decides is left alone,\n * since the schema would then be a guess, and the caller reports the entry.\n */\nfunction returnedBy(call: CallExpression): Node | undefined {\n const callee = unwrap(call.getExpression());\n if (!tsNode().isIdentifier(callee)) return undefined;\n for (const declaration of definitionsOf(callee)) {\n const fn = tsNode().isVariableDeclaration(declaration)\n ? declaration.getInitializer()\n : declaration;\n if (\n fn === undefined ||\n !(\n tsNode().isFunctionDeclaration(fn) ||\n tsNode().isArrowFunction(fn) ||\n tsNode().isFunctionExpression(fn)\n )\n ) {\n continue;\n }\n const body = fn.getBody();\n if (body === undefined) continue;\n if (!tsNode().isBlock(body)) return body;\n const [only, ...rest] = body.getStatements();\n if (only !== undefined && rest.length === 0 && tsNode().isReturnStatement(only)) {\n return only.getExpression();\n }\n }\n return undefined;\n}\n\nexport function resolveToObjectLiteral(\n node: Node | undefined,\n seen = new Set<Node>(),\n): ObjectLiteralExpression | undefined {\n if (node === undefined || seen.has(node)) return undefined;\n seen.add(node);\n const target = unwrap(node);\n if (tsNode().isObjectLiteralExpression(target)) return target;\n if (tsNode().isCallExpression(target)) {\n // A local field factory. One that spreads its argument over the result is a\n // wrapper, and the field is the argument, as below.\n const returned = resolveToObjectLiteral(returnedBy(target), seen);\n if (returned !== undefined && !returned.getProperties().some(tsNode().isSpreadAssignment)) {\n return returned;\n }\n // `buildConfig({...})`, `defineConfig({...})`: the literal is the first argument.\n return resolveToObjectLiteral(target.getArguments()[0], seen);\n }\n if (tsNode().isIdentifier(target)) {\n for (const declaration of definitionsOf(target)) {\n const resolved = resolveToObjectLiteral(valueOf(declaration), seen);\n if (resolved !== undefined) return resolved;\n }\n }\n if (tsNode().isPropertyAccessExpression(target)) {\n const owner = resolveToObjectLiteral(target.getExpression(), seen);\n if (owner !== undefined) {\n return resolveToObjectLiteral(propertyValue(owner, target.getName()), seen);\n }\n }\n return undefined;\n}\n\nexport function resolveToArrayLiteral(\n node: Node | undefined,\n seen = new Set<Node>(),\n): ArrayLiteralExpression | undefined {\n if (node === undefined || seen.has(node)) return undefined;\n seen.add(node);\n const target = unwrap(node);\n if (tsNode().isArrayLiteralExpression(target)) return target;\n if (tsNode().isCallExpression(target)) {\n const callee = target.getExpression();\n // `fields.map(wrapper)`: a wrapper keeps each field's name and type.\n return tsNode().isPropertyAccessExpression(callee) && callee.getName() === 'map'\n ? resolveToArrayLiteral(callee.getExpression(), seen)\n : resolveToArrayLiteral(returnedBy(target), seen);\n }\n if (tsNode().isIdentifier(target)) {\n for (const declaration of definitionsOf(target)) {\n const resolved = resolveToArrayLiteral(valueOf(declaration), seen);\n if (resolved !== undefined) return resolved;\n }\n }\n if (tsNode().isPropertyAccessExpression(target)) {\n const owner = resolveToObjectLiteral(target.getExpression(), seen);\n if (owner !== undefined) {\n return resolveToArrayLiteral(propertyValue(owner, target.getName()), seen);\n }\n }\n return undefined;\n}\n\n/** The elements of an array with every spread expanded; a spread that cannot be resolved is reported and dropped. */\nexport function expandElements(array: ArrayLiteralExpression, context: ExtractContext): Node[] {\n const out: Node[] = [];\n for (const element of array.getElements()) {\n if (!tsNode().isSpreadElement(element)) {\n out.push(element);\n continue;\n }\n const expanded = resolveToArrayLiteral(element.getExpression());\n if (expanded === undefined) {\n reportSkip(\n context,\n element,\n 'could not resolve the spread to an array literal, so its entries are missing',\n );\n continue;\n }\n out.push(...expandElements(expanded, context));\n }\n return out;\n}\n\nexport function readStringProperty(\n literal: ObjectLiteralExpression,\n name: string,\n): string | undefined {\n const value = propertyValue(literal, name);\n if (value === undefined) return undefined;\n const target = unwrap(value);\n if (tsNode().isStringLiteral(target) || tsNode().isNoSubstitutionTemplateLiteral(target)) {\n return target.getLiteralValue();\n }\n return undefined;\n}\n\nexport function readBooleanProperty(\n literal: ObjectLiteralExpression,\n name: string,\n): boolean | undefined {\n const value = propertyValue(literal, name);\n if (value === undefined) return undefined;\n const target = unwrap(value);\n if (tsNode().isTrueLiteral(target)) return true;\n if (tsNode().isFalseLiteral(target)) return false;\n return undefined;\n}\n\nexport function readArrayProperty(\n literal: ObjectLiteralExpression,\n name: string,\n): ArrayLiteralExpression | undefined {\n return resolveToArrayLiteral(propertyValue(literal, name));\n}\n\n/** `relationTo`: one slug, several, or `'unknown'` when it is not a literal. */\nexport function readRelationTarget(literal: ObjectLiteralExpression): string | readonly string[] {\n const value = propertyValue(literal, 'relationTo');\n if (value === undefined) return 'unknown';\n const target = unwrap(value);\n if (tsNode().isStringLiteral(target)) return target.getLiteralValue();\n const array = resolveToArrayLiteral(target);\n if (array === undefined) return 'unknown';\n return array\n .getElements()\n .map(unwrap)\n .filter((element) => tsNode().isStringLiteral(element))\n .map((element) => element.getLiteralValue());\n}\n","/**\n * Which schema fields a binding can address, spelled the way the runtime\n * resolves them. Paths follow `@schema/walker` exactly — bindings are matched\n * against that rule at runtime, so any other spelling would be wrong here.\n */\n\nimport type { ExtractedField, ExtractedSchema, ExtractedSlug } from './parser/types';\n\n/** Sentinel the parser gives an unnamed structural container. */\nconst STRUCTURAL_SENTINEL = '__structural';\n\n/** One addressable field, spelled the way a binding must spell it. */\nexport interface PreviewInventoryField {\n /** Runtime binding path, e.g. `hero.title` or `slides.*.caption`. */\n readonly path: string;\n /** Extracted field kind: `scalar`, `array`, `blocks`, `group`, … */\n readonly kind: ExtractedField['kind'];\n readonly localized: boolean;\n readonly required: boolean;\n}\n\nexport interface PreviewInventoryEntry {\n readonly slug: string;\n readonly typeName: string;\n readonly fields: readonly PreviewInventoryField[];\n}\n\nexport interface PreviewInventory {\n readonly globals: readonly PreviewInventoryEntry[];\n readonly collections: readonly PreviewInventoryEntry[];\n}\n\nfunction collect(\n fields: readonly ExtractedField[],\n basePath: string,\n out: PreviewInventoryField[],\n): void {\n for (const field of fields) {\n // No segment, but its children still belong to the parent's surface.\n if (field.kind === 'group' && field.name === STRUCTURAL_SENTINEL) {\n collect(field.fields, basePath, out);\n continue;\n }\n const path = basePath === '' ? field.name : `${basePath}.${field.name}`;\n out.push({\n path,\n kind: field.kind,\n localized: field.localized,\n required: field.required,\n });\n if (field.kind === 'group') {\n collect(field.fields, path, out);\n } else if (field.kind === 'array') {\n collect(field.fields, `${path}.*`, out);\n } else if (field.kind === 'blocks') {\n for (const block of field.blocks) {\n collect(block.fields, `${path}.*.${block.slug}`, out);\n }\n }\n }\n}\n\nfunction entry(slug: ExtractedSlug): PreviewInventoryEntry {\n const fields: PreviewInventoryField[] = [];\n collect(slug.fields, '', fields);\n return { slug: slug.slug, typeName: slug.typeName, fields };\n}\n\n/** Flatten an extracted schema into every path a binding may address. @internal */\nexport function buildPreviewInventory(schema: ExtractedSchema): PreviewInventory {\n return {\n globals: schema.globals.map(entry),\n collections: schema.collections.map(entry),\n };\n}\n","/**\n * Field-level extraction: one Payload field literal → an `ExtractedField`,\n * recursing into groups, arrays, tabs and blocks.\n */\nimport type { ArrayLiteralExpression, ObjectLiteralExpression } from 'ts-morph';\nimport { toPascalCase } from './names';\nimport {\n expandElements,\n hasProperty,\n readArrayProperty,\n readBooleanProperty,\n readRelationTarget,\n readStringProperty,\n reportSkip,\n resolveToObjectLiteral,\n tsNode,\n type ExtractContext,\n} from './resolve';\nimport type { ExtractedBlock, ExtractedField, ExtractedScalarField } from './types';\n\n/** Name of an unnamed structural container; its fields flatten into the parent. */\nexport const STRUCTURAL_SENTINEL = '__structural';\nconst STRUCTURAL_TYPES = new Set(['tabs', 'row', 'collapsible']);\nconst SCALAR_TYPE_MAP: Readonly<Record<string, ExtractedScalarField['typeRef']>> = {\n text: 'string',\n textarea: 'string',\n email: 'string',\n richText: 'unknown',\n number: 'number',\n checkbox: 'boolean',\n date: 'string',\n code: 'string',\n point: '[number, number]',\n};\nconst HAS_MANY_SCALARS = new Set(['text', 'number']);\n\n/** Every field in `array`, spreads expanded and structural containers flattened. */\nexport function extractFields(\n array: ArrayLiteralExpression,\n context: ExtractContext,\n): ExtractedField[] {\n const out: ExtractedField[] = [];\n for (const element of expandElements(array, context)) {\n const literal = resolveToObjectLiteral(element);\n if (literal === undefined) {\n reportSkip(context, element, 'could not resolve the field to an object literal');\n continue;\n }\n const field = extractField(literal, context);\n if (field === undefined) continue;\n if (field.kind === 'group' && field.name === STRUCTURAL_SENTINEL) out.push(...field.fields);\n else out.push(field);\n }\n return out;\n}\n\nfunction nestedFields(literal: ObjectLiteralExpression, context: ExtractContext): ExtractedField[] {\n const array = readArrayProperty(literal, 'fields');\n if (array !== undefined) return extractFields(array, context);\n reportSkip(\n context,\n literal,\n hasProperty(literal, 'fields')\n ? 'its `fields` could not be resolved to an array literal'\n : 'it has no `fields`',\n );\n return [];\n}\n\nfunction extractTabs(literal: ObjectLiteralExpression, context: ExtractContext): ExtractedField[] {\n const tabs = readArrayProperty(literal, 'tabs');\n if (tabs === undefined) {\n reportSkip(context, literal, 'its `tabs` could not be resolved to an array literal');\n return [];\n }\n const out: ExtractedField[] = [];\n for (const element of expandElements(tabs, context)) {\n const tab = resolveToObjectLiteral(element);\n if (tab === undefined) {\n reportSkip(context, element, 'could not resolve the tab to an object literal');\n continue;\n }\n const name = readStringProperty(tab, 'name');\n const fields = nestedFields(tab, context);\n if (name === undefined) out.push(...fields);\n else out.push({ kind: 'group', name, required: false, localized: false, fields });\n }\n return out;\n}\n\nfunction extractBlocks(\n literal: ObjectLiteralExpression,\n context: ExtractContext,\n): ExtractedBlock[] {\n const blocks = readArrayProperty(literal, 'blocks');\n if (blocks === undefined) {\n reportSkip(context, literal, 'its `blocks` could not be resolved to an array literal');\n return [];\n }\n const out: ExtractedBlock[] = [];\n for (const element of expandElements(blocks, context)) {\n const block = resolveToObjectLiteral(element);\n if (block === undefined) {\n reportSkip(context, element, 'could not resolve the block to an object literal');\n continue;\n }\n const slug = readStringProperty(block, 'slug');\n if (slug === undefined) {\n reportSkip(context, element, 'a block needs a string `slug`');\n continue;\n }\n out.push({ slug, typeName: toPascalCase(slug), fields: nestedFields(block, context) });\n }\n return out;\n}\n\nfunction readOptions(literal: ObjectLiteralExpression, context: ExtractContext): string[] {\n const options = readArrayProperty(literal, 'options');\n if (options === undefined) {\n reportSkip(context, literal, 'its `options` could not be resolved to an array literal');\n return [];\n }\n const out: string[] = [];\n for (const element of expandElements(options, context)) {\n if (tsNode().isStringLiteral(element)) {\n out.push(element.getLiteralValue());\n continue;\n }\n const option = resolveToObjectLiteral(element);\n const value = option === undefined ? undefined : readStringProperty(option, 'value');\n if (value === undefined) reportSkip(context, element, 'an option needs a string or a `value`');\n else out.push(value);\n }\n return out;\n}\n\n/** One field, or `undefined` for a `ui` field (nothing to type) and for shapes reported as skipped. */\nexport function extractField(\n literal: ObjectLiteralExpression,\n context: ExtractContext,\n): ExtractedField | undefined {\n const type = readStringProperty(literal, 'type');\n if (type === undefined) {\n reportSkip(context, literal, 'it has no string `type`');\n return undefined;\n }\n if (type === 'ui') return undefined;\n const name = readStringProperty(literal, 'name');\n if (name === undefined && !STRUCTURAL_TYPES.has(type)) {\n reportSkip(context, literal, `a ${type} field needs a string \\`name\\``);\n return undefined;\n }\n const base = {\n name: name ?? STRUCTURAL_SENTINEL,\n required: readBooleanProperty(literal, 'required') ?? false,\n localized: readBooleanProperty(literal, 'localized') ?? false,\n };\n const hasMany = readBooleanProperty(literal, 'hasMany') ?? false;\n switch (type) {\n case 'array':\n return { ...base, kind: 'array', fields: nestedFields(literal, context) };\n case 'group':\n case 'row':\n case 'collapsible':\n return { ...base, kind: 'group', fields: nestedFields(literal, context) };\n case 'tabs':\n return { ...base, kind: 'group', fields: extractTabs(literal, context) };\n case 'blocks':\n return { ...base, kind: 'blocks', blocks: extractBlocks(literal, context) };\n case 'relationship':\n return { ...base, kind: 'relationship', target: readRelationTarget(literal), hasMany };\n case 'upload': {\n const target = readRelationTarget(literal);\n return {\n ...base,\n kind: 'upload',\n target: (typeof target === 'string' ? target : target[0]) ?? 'media',\n hasMany,\n };\n }\n case 'json':\n return { ...base, kind: 'json' };\n case 'select':\n case 'radio':\n return {\n ...base,\n kind: 'select',\n options: readOptions(literal, context),\n hasMany: type === 'select' && hasMany,\n };\n default:\n return {\n ...base,\n kind: 'scalar',\n typeRef: SCALAR_TYPE_MAP[type] ?? 'unknown',\n hasMany: HAS_MANY_SCALARS.has(type) && hasMany,\n };\n }\n}\n","/**\n * Schema-level extraction: open the config, find every collection and global,\n * walk into them. Lenient by design — a Payload config is a full TypeScript\n * program, so the common shapes are recognised and everything else becomes a\n * diagnostic rather than a silently empty type.\n */\nimport type { Node, ObjectLiteralExpression, Project, SourceFile } from 'ts-morph';\nimport { extractFields } from './extract-field';\nimport { toPascalCase } from './names';\nimport {\n expandElements,\n hasProperty,\n propertyValue,\n readArrayProperty,\n readStringProperty,\n reportSkip,\n resolveToArrayLiteral,\n resolveToObjectLiteral,\n loadTsMorph,\n tsNode,\n type ExtractContext,\n} from './resolve';\nimport type { ExtractedSchema, ExtractedSlug } from './types';\n\nexport interface ExtractSchemaOptions {\n /** Absolute or relative path to `payload.config.ts`. */\n readonly configPath: string;\n /** When provided, used instead of constructing a fresh ts-morph project. */\n readonly project?: Project;\n /** A `tsconfig.json` whose module resolution lets cross-file imports be followed. */\n readonly tsConfigFilePath?: string;\n}\n\n/**\n * What a default export declaration holds. TypeScript only ever declares the\n * `default` export as an export assignment, an export specifier, or a function\n * or class declaration — `export default config` keeps the variable's own\n * declaration out of it — so a variable declaration never arrives here.\n */\nfunction declaredValue(declaration: Node): Node | undefined {\n if (tsNode().isExportAssignment(declaration)) return declaration.getExpression();\n return undefined;\n}\n\nfunction findConfigLiteral(\n sourceFile: SourceFile,\n context: ExtractContext,\n): ObjectLiteralExpression | undefined {\n const defaultExport = sourceFile.getDefaultExportSymbol();\n if (defaultExport === undefined) {\n context.diagnostics.push('payload.config.ts has no default export.');\n return undefined;\n }\n for (const declaration of defaultExport.getDeclarations()) {\n const literal = resolveToObjectLiteral(declaredValue(declaration));\n if (literal !== undefined) return literal;\n }\n for (const call of sourceFile.getDescendantsOfKind(loadTsMorph().SyntaxKind.CallExpression)) {\n const callee = call.getExpression();\n if (!tsNode().isIdentifier(callee) || callee.getText() !== 'buildConfig') continue;\n const literal = resolveToObjectLiteral(call.getArguments()[0]);\n if (literal !== undefined) return literal;\n }\n return undefined;\n}\n\nfunction extractSlugList(\n configLiteral: ObjectLiteralExpression,\n key: 'globals' | 'collections',\n context: ExtractContext,\n): ExtractedSlug[] {\n const value = propertyValue(configLiteral, key);\n if (value === undefined) return [];\n const array = resolveToArrayLiteral(value);\n if (array === undefined) {\n reportSkip(context, value, `could not resolve \\`${key}\\` to an array literal`);\n return [];\n }\n const out: ExtractedSlug[] = [];\n for (const element of expandElements(array, context)) {\n const literal = resolveToObjectLiteral(element);\n if (literal === undefined) {\n reportSkip(context, element, 'could not resolve the config entry to an object literal');\n continue;\n }\n const slug = readStringProperty(literal, 'slug');\n if (slug === undefined) {\n reportSkip(context, element, 'the config entry has no string `slug`');\n continue;\n }\n const fields = readArrayProperty(literal, 'fields');\n if (fields === undefined) {\n reportSkip(\n context,\n literal,\n hasProperty(literal, 'fields')\n ? `the \\`fields\\` of \"${slug}\" could not be resolved to an array literal`\n : `\"${slug}\" has no \\`fields\\``,\n );\n }\n out.push({\n slug,\n typeName: toPascalCase(slug),\n fields: fields === undefined ? [] : extractFields(fields, context),\n });\n }\n return out;\n}\n\n/** @internal */\nexport function extractSchema(options: ExtractSchemaOptions): ExtractedSchema {\n const project =\n options.project ??\n new (loadTsMorph().Project)(\n options.tsConfigFilePath !== undefined\n ? { tsConfigFilePath: options.tsConfigFilePath }\n : { skipAddingFilesFromTsConfig: true },\n );\n const sourceFile = project.addSourceFileAtPathIfExists(options.configPath);\n if (sourceFile === undefined) {\n return { globals: [], collections: [], diagnostics: [`Could not open ${options.configPath}`] };\n }\n project.resolveSourceFileDependencies();\n const context: ExtractContext = { diagnostics: [] };\n const configLiteral = findConfigLiteral(sourceFile, context);\n if (configLiteral === undefined) {\n return {\n globals: [],\n collections: [],\n diagnostics: [\n ...context.diagnostics,\n 'Could not locate a buildConfig({...}) call or `export default {...}` in the config file.',\n ],\n };\n }\n const globals = extractSlugList(configLiteral, 'globals', context);\n const collections = extractSlugList(configLiteral, 'collections', context);\n return { globals, collections, diagnostics: context.diagnostics };\n}\n","/**\n * Programmatic codegen API: `generateTypes({ configPath, outFile })` parses a\n * Payload config and writes the TypeScript types and, optionally, the preview\n * inventory. Requires ts-morph.\n */\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, isAbsolute, resolve } from 'node:path';\nimport { emitTypes, type EmitOptions } from './emit/emit-types';\nimport { buildPreviewInventory, type PreviewInventory } from './inventory';\nimport { extractSchema, type ExtractSchemaOptions } from './parser/extract-schema';\nimport type { ExtractedSchema } from './parser/types';\n\nexport {\n annotateTemplates,\n annotatablePaths,\n formatAnnotateReport,\n ANNOTATABLE_EXTENSIONS,\n type AnnotateOptions,\n type AnnotateResult,\n type AnnotateFileResult,\n type AnnotationCandidate,\n type AnnotationRefusal,\n type AnnotatableSchema,\n} from './annotate/index';\n\nexport interface GenerateTypesOptions\n extends Pick<ExtractSchemaOptions, 'configPath' | 'project' | 'tsConfigFilePath'>, EmitOptions {\n /** Where to write the generated code; `code` is returned either way. */\n readonly outFile?: string;\n /** Resolves relative paths. Defaults to `process.cwd()`. */\n readonly cwd?: string;\n /** Where to write the preview inventory as JSON: every path a binding may address. */\n readonly inventoryFile?: string;\n}\n\nexport interface GenerateTypesResult {\n readonly code: string;\n /** Extraction diagnostics, plus a note when nothing was written. */\n readonly diagnostics: readonly string[];\n readonly schema: ExtractedSchema;\n /** The types file actually written; absent when writing was refused. */\n readonly outFile?: string;\n /** Always produced; written to disk only when `inventoryFile` is set. */\n readonly inventory: PreviewInventory;\n readonly inventoryFile?: string;\n}\n\nasync function writeOut(path: string, content: string): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, content, 'utf8');\n}\n\n/** Parse the config and write the types, never writing an empty schema over a consumer's file. */\nexport async function generateTypes(options: GenerateTypesOptions): Promise<GenerateTypesResult> {\n const cwd = options.cwd ?? process.cwd();\n const absolute = (path: string): string => (isAbsolute(path) ? path : resolve(cwd, path));\n const schema = extractSchema({\n configPath: absolute(options.configPath),\n ...(options.project !== undefined ? { project: options.project } : {}),\n ...(options.tsConfigFilePath !== undefined\n ? { tsConfigFilePath: options.tsConfigFilePath }\n : {}),\n });\n const code = emitTypes(schema, options);\n const inventory = buildPreviewInventory(schema);\n const diagnostics = [...schema.diagnostics];\n const outFile = options.outFile === undefined ? undefined : absolute(options.outFile);\n const inventoryFile =\n options.inventoryFile === undefined ? undefined : absolute(options.inventoryFile);\n const targets = [outFile, inventoryFile].filter((path): path is string => path !== undefined);\n const empty = schema.globals.length + schema.collections.length === 0;\n if (empty && targets.length > 0) {\n diagnostics.push(\n `Nothing written: the schema is empty (0 globals, 0 collections), so ${targets.join(' and ')} ` +\n 'were left as they are.',\n );\n } else {\n if (outFile !== undefined) await writeOut(outFile, code);\n // Stable key order and a trailing newline keep the inventory diffable.\n if (inventoryFile !== undefined) {\n await writeOut(inventoryFile, `${JSON.stringify(inventory, null, 2)}\\n`);\n }\n }\n return {\n code,\n diagnostics,\n schema,\n inventory,\n ...(!empty && outFile !== undefined ? { outFile } : {}),\n ...(!empty && inventoryFile !== undefined ? { inventoryFile } : {}),\n };\n}\n\nexport { buildPreviewInventory } from './inventory';\nexport type { PreviewInventory, PreviewInventoryEntry, PreviewInventoryField } from './inventory';\nexport { extractSchema } from './parser/extract-schema';\nexport { emitTypes } from './emit/emit-types';\nexport type { ExtractedSchema, ExtractedSlug, ExtractedField } from './parser/types';\n","/**\n * Astro integration: regenerate the types on startup and, during `astro dev`,\n * whenever a .ts, .mts, .cts, .js, .mjs, .cjs or .json file changes in the\n * Payload config's directory or below it, except under node_modules and the\n * output file itself. Paths are relative to Astro's root. Uses `fs.watch`; no\n * watcher dependency.\n */\nimport { watch, type FSWatcher } from 'node:fs';\nimport { dirname, extname, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { generateTypes } from './index';\n\nexport interface AstroCodegenOptions {\n /** Path to `payload.config.ts` (absolute or relative to Astro's root). */\n readonly configPath: string;\n /** Output path for generated types (absolute or relative to Astro's root). */\n readonly outPath: string;\n /**\n * Re-run during `astro dev` when a .ts, .mts, .cts, .js, .mjs, .cjs or .json\n * file in or below the config's directory changes. Default `true`.\n */\n readonly watch?: boolean;\n /** Only log errors. Default `false`. */\n readonly quiet?: boolean;\n}\n\ninterface AstroLogger {\n readonly info: (msg: string) => void;\n readonly warn: (msg: string) => void;\n readonly error: (msg: string) => void;\n}\n\ninterface AstroIntegration {\n readonly name: string;\n readonly hooks: Readonly<{\n readonly 'astro:config:setup'?: (params: {\n readonly command: string;\n readonly logger?: AstroLogger;\n readonly config?: { readonly root?: URL | string };\n }) => Promise<void> | void;\n readonly 'astro:server:start'?: () => void;\n readonly 'astro:build:start'?: () => Promise<void> | void;\n }>;\n}\n\nconst SOURCE_EXTENSIONS = new Set(['.ts', '.mts', '.cts', '.js', '.mjs', '.cjs', '.json']);\nconst DEBOUNCE_MS = 100;\n\nfunction rootOf(root: URL | string | undefined): string {\n if (root === undefined) return process.cwd();\n if (root instanceof URL) return fileURLToPath(root);\n return root.startsWith('file:') ? fileURLToPath(root) : root;\n}\n\nexport function livePreviewCodegen(options: AstroCodegenOptions): AstroIntegration {\n const watchEnabled = options.watch ?? true;\n let root = process.cwd();\n let watcher: FSWatcher | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let active = false;\n let queued = false;\n\n async function regenerate(logger: AstroLogger | undefined): Promise<void> {\n if (active) {\n queued = true;\n return;\n }\n active = true;\n try {\n const result = await generateTypes({\n configPath: options.configPath,\n outFile: options.outPath,\n cwd: root,\n });\n if (result.outFile === undefined) {\n logger?.error(`pll-codegen: nothing written — ${result.diagnostics.join(' ')}`);\n } else if (options.quiet !== true) {\n logger?.info(\n `pll-codegen: ${String(result.schema.globals.length)} globals, ${String(result.schema.collections.length)} collections → ${options.outPath}`,\n );\n for (const diagnostic of result.diagnostics) logger?.warn(`pll-codegen: ${diagnostic}`);\n }\n } catch (error) {\n logger?.error(\n `pll-codegen failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n } finally {\n active = false;\n if (queued) {\n queued = false;\n void regenerate(logger);\n }\n }\n }\n\n function startWatching(logger: AstroLogger | undefined): void {\n const directory = dirname(resolve(root, options.configPath));\n const outPath = resolve(root, options.outPath);\n try {\n // The output file may live under the watched directory; writing it must not retrigger.\n watcher = watch(directory, { recursive: true }, (_event, file) => {\n if (file === null) return;\n const changed = resolve(directory, file);\n if (changed === outPath || changed.includes(`${sep}node_modules${sep}`)) return;\n if (!SOURCE_EXTENSIONS.has(extname(changed))) return;\n clearTimeout(timer);\n timer = setTimeout(() => void regenerate(logger), DEBOUNCE_MS);\n });\n } catch (error) {\n logger?.warn(\n `pll-codegen watcher unavailable: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n return {\n name: 'payload-live-preview:codegen',\n hooks: {\n 'astro:config:setup': async ({ command, logger, config }) => {\n root = rootOf(config?.root);\n await regenerate(logger);\n if (watchEnabled && command === 'dev') startWatching(logger);\n },\n 'astro:server:start': () => undefined,\n 'astro:build:start': () => {\n clearTimeout(timer);\n watcher?.close();\n watcher = undefined;\n },\n },\n };\n}\n"],"mappings":"2OAEO,SAASA,EAAaC,GAC3B,OAAOA,EACJC,MAAM,YACNC,OAAOC,SACPC,IAAKC,GAASA,EAAKC,OAAO,GAAGC,cAAgBF,EAAKG,MAAM,IACxDC,KAAK,GACV,CCYA,ICLIC,EDSEC,EAAa,sBAOnB,SAASC,EAAeC,EAAgBC,GACtC,MAAO,GAAGD,IAASd,EAAae,IAClC,CAqCA,SAASC,EACPC,EACAH,EACAI,EACAC,IAE0C,IAAtCA,EAAQC,2BAAsCH,EAAMI,WACtDH,EAAMI,KAAK,uBAEb,MAAMC,EAAWN,EAAMO,SAAW,GAAK,IArDzC,IAAoBC,EAsDlBP,EAAMI,KAAK,KAtDOG,EAsDSR,EAAMQ,KArD7Bb,EAAWc,KAAKD,GAAcA,EAC3B,IAAIA,EAAKE,QAAQ,OAAQ,QAAQA,QAAQ,MAAO,YAoDdJ,MA7C3C,SAAyBN,EAAuBH,GAC9C,OAAQG,EAAMW,MACZ,IAAK,SACH,OAAyB,IAAlBX,EAAMY,QAAmB,GAAGZ,EAAMa,YAAcb,EAAMa,QAC/D,IAAK,QACH,MAAO,GAAGjB,EAAeC,EAAQG,EAAMQ,UACzC,IAAK,SACH,OAA4B,IAAxBR,EAAMc,OAAOC,OAAqB,YAI/B,IAHUf,EAAMc,OACpB1B,IAAK4B,GAAUpB,EAAeA,EAAeC,EAAQG,EAAMQ,MAAOQ,EAAMC,WACxExB,KAAK,YAGV,IAAK,QACH,OAAOG,EAAeC,EAAQG,EAAMQ,MACtC,IAAK,eAAgB,CACnB,MAIMU,EAAO,uBAHa,iBAAjBlB,EAAMmB,OACT,IAAInB,EAAMmB,UACVnB,EAAMmB,OAAO/B,IAAKJ,GAAS,IAAIA,MAASS,KAAK,UA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H,MACnCI,aAAa3B,GACbA,EAAQ4B,WAAW,KAAWxB,EAAWC,IA5D7B,OA8DhB,OAAS/K,GACP+K,GAAQM,KACN,oCAAoCrL,aAAiBC,MAAQD,EAAMsL,QAAUvK,OAAOf,KAExF,CACF,CAQ6CuM,CAAcxB,IAEvD,qBAAsB,OACtB,oBAAqB,KACnBsB,aAAa3B,GACbD,GAAS+B,QACT/B,OAAU,IAIlB,Q","ignoreList":[]}
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{stat as e,readFile as t,writeFile as n,mkdir as o,readdir as i}from"fs/promises";import{resolve as s,extname as r,relative as a,isAbsolute as l,dirname as c,join as d}from"path";import{createRequire as u}from"module";function f(e){return e.split(/[-_\s]+/u).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}var p,h=/^[A-Za-z_$][\w$]*$/u;function g(e,t){return`${e}${f(t)}`}function y(e,t,n,o){!0===o.markLocalizedAsDeprecated&&e.localized&&n.push(" /** @localized */");const i=e.required?"":"?";var s;n.push(` ${s=e.name,h.test(s)?s:`'${s.replace(/\\/gu,"\\\\").replace(/'/gu,"\\'")}'`}${i}: ${function(e,t){switch(e.kind){case"scalar":return!0===e.hasMany?`${e.typeRef}[]`:e.typeRef;case"array":return`${g(t,e.name)}[]`;case"blocks":return 0===e.blocks.length?"unknown[]":`(${e.blocks.map(n=>g(g(t,e.name),n.typeName)).join(" | ")})[]`;case"group":return g(t,e.name);case"relationship":{const t=`PayloadRelationship<${"string"==typeof e.target?`'${e.target}'`:e.target.map(e=>`'${e}'`).join(" | ")}>`;return e.hasMany?`${t}[]`:t}case"upload":return!0===e.hasMany?"PayloadMedia[]":"PayloadMedia";case"json":return"unknown";case"select":{if(0===e.options.length)return e.hasMany?"string[]":"string";const t=e.options.map(e=>`'${e}'`).join(" | ");return e.hasMany?`(${t})[]`:t}}}(e,t)};`)}function m(e,t,n,o){n.push(`export interface ${e} {`),n.push(` blockType: '${t.slug}';`);for(const i of t.fields)y(i,e,n,o);n.push("}","")}function v(e,t,n,o,i){for(const s of t){const t=g(e,s.name);if("array"===s.kind||"group"===s.kind){if(o.has(t))continue;o.add(t),v(t,s.fields,n,o,i),n.push(`export interface ${t} {`);for(const e of s.fields)y(e,t,n,i);n.push("}","")}else if("blocks"===s.kind)for(const e of s.blocks){const s=g(t,e.typeName);o.has(s)||(o.add(s),v(s,e.fields,n,o,i),m(s,e,n,i))}}}function w(e,t,n,o){v(e.typeName,e.fields,t,n,o),t.push(`export interface ${e.typeName} {`);for(const n of e.fields)y(n,e.typeName,t,o);t.push("}")}function b(e,t,n){if(0!==t.length){n.push(`export type ${e} = {`);for(const e of t)n.push(` '${e.slug}': ${e.typeName};`);n.push("};","")}}function $(e,t,n){for(const o of e){if("group"===o.kind&&"__structural"===o.name){$(o.fields,t,n);continue}const e=""===t?o.name:`${t}.${o.name}`;if(n.push({path:e,kind:o.kind,localized:o.localized,required:o.required}),"group"===o.kind)$(o.fields,e,n);else if("array"===o.kind)$(o.fields,`${e}.*`,n);else if("blocks"===o.kind)for(const t of o.blocks)$(t.fields,`${e}.*.${t.slug}`,n)}}function x(e){const t=[];return $(e.fields,"",t),{slug:e.slug,typeName:e.typeName,fields:t}}function k(){if(void 0===p)try{p=u(import.meta.url)("ts-morph")}catch(e){throw new Error("pll-codegen needs ts-morph: npm install --save-dev ts-morph",{cause:e})}return p}function S(){return k().Node}function P(e,t,n){e.diagnostics.push(`Skipped "${function(e){const t=e.getText().replace(/\s+/gu," ");return t.length>60?`${t.slice(0,57)}...`:t}(t)}" at ${function(e){return`${e.getSourceFile().getBaseName()}:${String(e.getStartLineNumber())}`}(t)}: ${n}.`)}function F(e){let t=e;for(;S().isParenthesizedExpression(t)||S().isAsExpression(t)||S().isSatisfiesExpression(t)||S().isNonNullExpression(t)||S().isTypeAssertion(t);)t=t.getExpression();return t}function A(e){if(!(S().isImportSpecifier(e)||S().isImportClause(e)||S().isNamespaceImport(e)||S().isExportSpecifier(e)))return[e];const t=e.getSymbol()?.getAliasedSymbol();return t?.getDeclarations()??[e]}function E(e){const t=e.getDefinitionNodes();return(t.length>0?t:e.getSymbol()?.getDeclarations()??[]).flatMap(A)}function C(e){return S().isVariableDeclaration(e)||S().isPropertyAssignment(e)?e.getInitializer():S().isExportAssignment(e)?e.getExpression():S().isShorthandPropertyAssignment(e)?e.getNameNode():void 0}function N(e,t){const n=e.getProperty(t);if(void 0!==n)return S().isPropertyAssignment(n)?n.getInitializer():S().isShorthandPropertyAssignment(n)?n.getNameNode():void 0}function j(e,t){return void 0!==e.getProperty(t)}function q(e,t=/* @__PURE__ */new Set){if(void 0===e||t.has(e))return;t.add(e);const n=F(e);if(S().isObjectLiteralExpression(n))return n;if(S().isCallExpression(n))return q(n.getArguments()[0],t);if(S().isIdentifier(n))for(const e of E(n)){const n=q(C(e),t);if(void 0!==n)return n}if(S().isPropertyAccessExpression(n)){const e=q(n.getExpression(),t);if(void 0!==e)return q(N(e,n.getName()),t)}}function z(e,t=/* @__PURE__ */new Set){if(void 0===e||t.has(e))return;t.add(e);const n=F(e);if(S().isArrayLiteralExpression(n))return n;if(S().isIdentifier(n))for(const e of E(n)){const n=z(C(e),t);if(void 0!==n)return n}if(S().isPropertyAccessExpression(n)){const e=q(n.getExpression(),t);if(void 0!==e)return z(N(e,n.getName()),t)}}function M(e,t){const n=[];for(const o of e.getElements()){if(!S().isSpreadElement(o)){n.push(o);continue}const e=z(o.getExpression());void 0!==e?n.push(...M(e,t)):P(t,o,"could not resolve the spread to an array literal, so its entries are missing")}return n}function L(e,t){const n=N(e,t);if(void 0===n)return;const o=F(n);return S().isStringLiteral(o)||S().isNoSubstitutionTemplateLiteral(o)?o.getLiteralValue():void 0}function O(e,t){const n=N(e,t);if(void 0===n)return;const o=F(n);return!!S().isTrueLiteral(o)||!S().isFalseLiteral(o)&&void 0}function T(e,t){return z(N(e,t))}function D(e){const t=N(e,"relationTo");if(void 0===t)return"unknown";const n=F(t);if(S().isStringLiteral(n))return n.getLiteralValue();const o=z(n);return void 0===o?"unknown":o.getElements().map(F).filter(e=>S().isStringLiteral(e)).map(e=>e.getLiteralValue())}var _="__structural",W=/* @__PURE__ */new Set(["tabs","row","collapsible"]),I={text:"string",textarea:"string",email:"string",richText:"unknown",number:"number",checkbox:"boolean",date:"string",code:"string",point:"[number, number]"},R=/* @__PURE__ */new Set(["text","number"]);function Z(e,t){const n=[];for(const o of M(e,t)){const e=q(o);if(void 0===e){P(t,o,"could not resolve the field to an object literal");continue}const i=J(e,t);void 0!==i&&("group"===i.kind&&i.name===_?n.push(...i.fields):n.push(i))}return n}function H(e,t){const n=T(e,"fields");return void 0!==n?Z(n,t):(P(t,e,j(e,"fields")?"its `fields` could not be resolved to an array literal":"it has no `fields`"),[])}function V(e,t){const n=T(e,"tabs");if(void 0===n)return P(t,e,"its `tabs` could not be resolved to an array literal"),[];const o=[];for(const e of M(n,t)){const n=q(e);if(void 0===n){P(t,e,"could not resolve the tab to an object literal");continue}const i=L(n,"name"),s=H(n,t);void 0===i?o.push(...s):o.push({kind:"group",name:i,required:!1,localized:!1,fields:s})}return o}function U(e,t){const n=T(e,"blocks");if(void 0===n)return P(t,e,"its `blocks` could not be resolved to an array literal"),[];const o=[];for(const e of M(n,t)){const n=q(e);if(void 0===n){P(t,e,"could not resolve the block to an object literal");continue}const i=L(n,"slug");void 0!==i?o.push({slug:i,typeName:f(i),fields:H(n,t)}):P(t,e,"a block needs a string `slug`")}return o}function B(e,t){const n=T(e,"options");if(void 0===n)return P(t,e,"its `options` could not be resolved to an array literal"),[];const o=[];for(const e of M(n,t)){if(S().isStringLiteral(e)){o.push(e.getLiteralValue());continue}const n=q(e),i=void 0===n?void 0:L(n,"value");void 0===i?P(t,e,"an option needs a string or a `value`"):o.push(i)}return o}function J(e,t){const n=L(e,"type");if(void 0===n)return void P(t,e,"it has no string `type`");if("ui"===n)return;const o=L(e,"name");if(void 0===o&&!W.has(n))return void P(t,e,`a ${n} field needs a string \`name\``);const i={name:o??_,required:O(e,"required")??!1,localized:O(e,"localized")??!1},s=O(e,"hasMany")??!1;switch(n){case"array":return{...i,kind:"array",fields:H(e,t)};case"group":case"row":case"collapsible":return{...i,kind:"group",fields:H(e,t)};case"tabs":return{...i,kind:"group",fields:V(e,t)};case"blocks":return{...i,kind:"blocks",blocks:U(e,t)};case"relationship":return{...i,kind:"relationship",target:D(e),hasMany:s};case"upload":{const t=D(e);return{...i,kind:"upload",target:("string"==typeof t?t:t[0])??"media",hasMany:s}}case"json":return{...i,kind:"json"};case"select":case"radio":return{...i,kind:"select",options:B(e,t),hasMany:"select"===n&&s};default:return{...i,kind:"scalar",typeRef:I[n]??"unknown",hasMany:R.has(n)&&s}}}function G(e){if(S().isExportAssignment(e))return e.getExpression()}function K(e,t,n){const o=N(e,t);if(void 0===o)return[];const i=z(o);if(void 0===i)return P(n,o,`could not resolve \`${t}\` to an array literal`),[];const s=[];for(const e of M(i,n)){const t=q(e);if(void 0===t){P(n,e,"could not resolve the config entry to an object literal");continue}const o=L(t,"slug");if(void 0===o){P(n,e,"the config entry has no string `slug`");continue}const i=T(t,"fields");void 0===i&&P(n,t,j(t,"fields")?`the \`fields\` of "${o}" could not be resolved to an array literal`:`"${o}" has no \`fields\``),s.push({slug:o,typeName:f(o),fields:void 0===i?[]:Z(i,n)})}return s}var X=/<([a-z][a-z0-9-]*)((?:"[^"]*"|'[^']*'|\{(?:[^{}]|\{[^{}]*\})*\}|[^>"'{])*)>([^<]*)<\/\1\s*>/gu,Q=/<script\b[^>]*>[\s\S]*?<\/script\b[^>]*>|<style\b[^>]*>[\s\S]*?<\/style\b[^>]*>|<!--[\s\S]*?-->/giu,Y=/^\s*\{([^{}]*)\}\s*$/u,ee=/\{([^{}]*)\}/u,te=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/u,ne="data-payload-field",oe=/\bdata-payload-field\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*(["'`])([^"'`]*)\3\s*\})/u,ie=/\{\s*\.\.\.\s*(?:[\w$]+\s*\.\s*)*(?:bind|bindByPath)\s*(?:<[^>]*>)?\s*\(\s*(?:(["'`])([^"'`]*)\1)?/u,se=/\{\s*\.\.\./u,re=[/\.(?: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 ae(e){return e.replace(/[^\n]/gu," ")}function le(e){const{bodyOffset:t}=function(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}}(e),n=e.slice(t).replace(Q,ae);return`${ae(e.slice(0,t))}${n}`}function ce(e,t){let n=1;for(let o=0;o<t;o+=1)10===e.charCodeAt(o)&&(n+=1);return n}function de(e){return e.slice(e.indexOf(".")+1)}function ue(e){return e.slice(0,e.indexOf("."))}function fe(e){const t=e.replace(/\s+/gu," ").trim();return t.length>60?`${t.slice(0,57)}…`:t}function pe(e){if(e.includes(ne)){const t=oe.exec(e);return{path:t?.[1]??t?.[2]??t?.[4]}}const t=ie.exec(e);return null===t?null:{path:t[2]}}function he(e,t){const n=e.trim();if(0===n.length)return"the element is empty";if(!te.test(n))return"not a plain field access — a call, an operator or an index cannot be traced to one field";const o=de(n),i=ue(n);if(t.items.has(i))return`\`${i}\` is a loop item — a binding names a field of the document, and \`${o}\` there is a different value, or none`;if(!t.known.has(o))return`the schema has no field \`${o}\`; the binding would name something that never arrives`;const s=t.anchors.get(i);if(void 0===s)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 r=[...s,o];return t.entities.some(e=>r.every(t=>e.has(t)))?void 0:`no single collection or global has \`${o}\` and what this file binds on \`${i}\` (${[...s].map(e=>`\`${e}\``).join(", ")}) — one variable holds one document`}function ge(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':se.test(t)?"the element spreads attributes the scan cannot read, and one of them may already bind it":void 0}function ye(e,t){const n=/* @__PURE__ */new Map;for(const[,,o="",i=""]of e){const e=pe(o)?.path,s=Y.exec(i)?.[1]?.trim();if(void 0===e||void 0===s||!te.test(s))continue;const r=ue(s);if(de(s)!==e||t.has(r))continue;const a=n.get(r)??/* @__PURE__ */new Set;a.add(e),n.set(r,a)}return n}function me(e,t){const n=[],o=[],i=function(e){const t=/* @__PURE__ */new Set;for(const n of re)for(const o of e.matchAll(n))void 0!==o[1]&&t.add(o[1]);return t}(e),s=[...le(e).matchAll(X)],r={known:new Set(t.entities.flatMap(e=>[...e])),entities:t.entities,items:i,anchors:ye(s,i)};for(const t of s){const[,i="",s="",a=""]=t,l=ce(e,t.index);if(null!==pe(s))continue;if(null===ee.exec(a))continue;const c=ge(i,s);if(void 0!==c){o.push({line:l,reason:c,expression:fe(a)});continue}const d=Y.exec(a);if(null===d){o.push({line:l,reason:"the value is printed beside other content — a binding replaces the whole text, so the markup has to be split first",expression:fe(a)});continue}const u=d[1]??"",f=he(u,r);void 0===f?n.push({insertAt:t.index+1+i.length,path:de(u.trim()),line:l,tag:i}):o.push({line:l,reason:f,expression:fe(u)})}return{candidates:n,refusals:o}}function ve(e){return`${ne}="${e.path}"`}function we(e,t,n=ve){let o=e;for(const e of[...t].sort((e,t)=>t.insertAt-e.insertAt))o=`${o.slice(0,e.insertAt)} ${n(e)}${o.slice(e.insertAt)}`;return o}var be=[".astro",".jsx",".tsx",".svelte"];async function $e(e,t){await o(c(e),{recursive:!0}),await n(e,t,"utf8")}async function xe(e){const t=e.cwd??process.cwd(),n=e=>l(e)?e:s(t,e),o=function(e){const t=e.project??new(k().Project)(void 0!==e.tsConfigFilePath?{tsConfigFilePath:e.tsConfigFilePath}:{skipAddingFilesFromTsConfig:!0}),n=t.addSourceFileAtPathIfExists(e.configPath);if(void 0===n)return{globals:[],collections:[],diagnostics:[`Could not open ${e.configPath}`]};t.resolveSourceFileDependencies();const o={diagnostics:[]},i=function(e,t){const n=e.getDefaultExportSymbol();if(void 0!==n){for(const e of n.getDeclarations()){const t=q(G(e));if(void 0!==t)return t}for(const t of e.getDescendantsOfKind(k().SyntaxKind.CallExpression)){const e=t.getExpression();if(!S().isIdentifier(e)||"buildConfig"!==e.getText())continue;const n=q(t.getArguments()[0]);if(void 0!==n)return n}}else t.diagnostics.push("payload.config.ts has no default export.")}(n,o);return void 0===i?{globals:[],collections:[],diagnostics:[...o.diagnostics,"Could not locate a buildConfig({...}) call or `export default {...}` in the config file."]}:{globals:K(i,"globals",o),collections:K(i,"collections",o),diagnostics:o.diagnostics}}({configPath:n(e.configPath),...void 0!==e.project?{project:e.project}:{},...void 0!==e.tsConfigFilePath?{tsConfigFilePath:e.tsConfigFilePath}:{}}),i=function(e,t={}){const n=[t.header??"// Auto-generated by payload-live-preview/codegen.\n// Do not edit by hand — run `pll-codegen` to regenerate.\n/* eslint-disable */",""];n.push('import type { PayloadMedia, PayloadRelationship } from "payload-live-preview";',"");const o=/* @__PURE__ */new Set;for(const i of[...e.globals,...e.collections])w(i,n,o,t),n.push("");b("PayloadGlobals",e.globals,n),b("PayloadCollections",e.collections,n);const i=[];return e.globals.length>0&&i.push("keyof PayloadGlobals"),e.collections.length>0&&i.push("keyof PayloadCollections"),i.length>0&&n.push(`export type PayloadSlug = ${i.join(" | ")};`,""),n.join("\n").replace(/\n{3,}/gu,"\n\n")}(o,e),r=function(e){return{globals:e.globals.map(x),collections:e.collections.map(x)}}(o),a=[...o.diagnostics],c=void 0===e.outFile?void 0:n(e.outFile),d=void 0===e.inventoryFile?void 0:n(e.inventoryFile),u=[c,d].filter(e=>void 0!==e),f=o.globals.length+o.collections.length===0;return f&&u.length>0?a.push(`Nothing written: the schema is empty (0 globals, 0 collections), so ${u.join(" and ")} were left as they are.`):(void 0!==c&&await $e(c,i),void 0!==d&&await $e(d,`${JSON.stringify(r,null,2)}\n`)),{code:i,diagnostics:a,schema:o,inventory:r,...f||void 0===c?{}:{outFile:c},...f||void 0===d?{}:{inventoryFile:d}}}var ke=/* @__PURE__ */new Set(["node_modules","dist",".git",".astro",".svelte-kit",".next",".nuxt","coverage"]);async function Se(e){const t=[];for(const n of await i(e,{withFileTypes:!0}))if(n.isDirectory()){if(ke.has(n.name))continue;t.push(...await Se(d(e,n.name)))}else be.includes(r(n.name))&&t.push(d(e,n.name));return t}async function Pe(o,i){const l=function(e){const t=[];let n,o=!1,i=!1;for(let s=0;s<e.length;s+=1){const r=e[s];void 0!==r&&("-h"===r||"--help"===r?i=!0:"--write"===r?o=!0:"--config"===r||"-c"===r?(n=e[s+1],s+=1):r.startsWith("--config=")?n=r.slice(9):r.startsWith("-")||t.push(r))}return{paths:t,configPath:n,write:o,showHelp:i}}(o);if(l.showHelp)return i.out("pll-codegen annotate — add data-payload-field where a template prints a field\n\nUsage:\n pll-codegen annotate <path...> --config <payload.config.ts> [--write]\n\nRequires ts-morph to read the config: npm install --save-dev ts-morph\n\nOptions:\n -c, --config <path> Path to payload.config.ts (required): the schema decides\n which paths exist\n --write Write the annotated files; without it nothing is touched\n -h, --help Show this help\n\nWhat it annotates:\n An element whose entire content is one field access, <p>{page.subtitle}</p>,\n on a variable the same file already binds a field of by hand:\n <h1 data-payload-field=\"title\">{page.title}</h1> or {...preview.bind('title')}.\n That binding is what says page holds the document being previewed, and the\n path must be in the collection or global that has the hand-bound fields.\n Astro, JSX and Svelte templates.\n\nWhat it refuses, with a reason per line:\n a value printed beside other text, a call or an operator, a field printed\n from a loop item, a path the schema does not know, a variable the file binds\n no field of, a link (<a>), a <title>, and an element that spreads attributes\n it cannot read. An element already bound by data-payload-field or by a\n bind() spread is left as it is, without a line; <script>, <style>, comments\n and Astro frontmatter are not read.\n\nExit codes:\n 0 nothing left to do, or the files were written\n 1 fatal error\n 2 no globals or collections found in the config; nothing was scanned\n 3 a dry run found work; re-run with --write\n"),0;if(void 0===l.configPath||0===l.paths.length)return i.err("pll-codegen annotate: --config and at least one path are required.\n"),1;try{const{inventory:o,schema:c,diagnostics:d}=await xe({configPath:l.configPath});for(const e of d)i.err(` warning: ${e}\n`);if(c.globals.length+c.collections.length===0)return i.err("pll-codegen annotate: the schema is empty (0 globals, 0 collections), so nothing was scanned: every field would have been refused as unknown. The warnings above name what could not be read. Imports through a path alias (@/...) are not followed, so a config that reaches its collections or globals that way reads as empty here.\n"),2;const u=await async function(t){const n=[];for(const o of t){const t=s(o);(await e(t)).isDirectory()?n.push(...await Se(t)):be.includes(r(t))&&n.push(t)}return n.sort()}(l.paths);if(0===u.length)return i.err(`pll-codegen annotate: no ${be.join(", ")} files found.\n`),1;const f=await async function(e){const o=e.io?.read??(e=>t(e,"utf8")),i=e.io?.write??((e,t)=>n(e,t,"utf8")),s=e.cwd??process.cwd(),r=[...(l=e.inventory).globals,...l.collections].map(e=>new Set(e.fields.map(e=>e.path).filter(e=>!e.includes("*"))));var l;const c=[];for(const t of e.files){const n=await o(t),{candidates:l,refusals:d}=me(n,{entities:r}),u=0===l.length?n:we(n,l),f=u!==n;f&&!0===e.write&&await i(t,u),c.push({file:a(s,t)||t,code:u,annotations:l,refusals:d,changed:f})}return{files:c,annotationCount:c.reduce((e,t)=>e+t.annotations.length,0),refusalCount:c.reduce((e,t)=>e+t.refusals.length,0),written:!0===e.write}}({files:u,inventory:o,write:l.write});return i.out(function(e){const t=[];for(const n of e.files)if(0!==n.annotations.length||0!==n.refusals.length){t.push(n.file);for(const e of n.annotations)t.push(` ${String(e.line)}: <${e.tag}> → ${e.path}`);for(const e of n.refusals)t.push(` ${String(e.line)}: left alone — ${e.reason} (${e.expression})`)}const n=e.written?"annotated":"would annotate";return t.push(`${n} ${String(e.annotationCount)} element(s); ${String(e.refusalCount)} left for a human`),`${t.join("\n")}\n`}(f)),!l.write&&f.annotationCount>0?3:0}catch(e){return i.err(`pll-codegen annotate: ${e instanceof Error?e.message:String(e)}\n`),1}}async function Fe(e){if("annotate"===e[0])return Pe(e.slice(1),{out:e=>process.stdout.write(e),err:e=>process.stderr.write(e)});const t=function(e){const t={configPath:void 0,outFile:void 0,inventoryFile:void 0,tsConfigFilePath:void 0,showHelp:!1,quiet:!1};for(let n=0;n<e.length;n+=1){const o=e[n];void 0!==o&&("-h"===o||"--help"===o?t.showHelp=!0:"-q"===o||"--quiet"===o?t.quiet=!0:"--config"===o||"-c"===o?(t.configPath=e[n+1],n+=1):"--out"===o||"-o"===o?(t.outFile=e[n+1],n+=1):"--inventory"===o?(t.inventoryFile=e[n+1],n+=1):"--tsconfig"===o?(t.tsConfigFilePath=e[n+1],n+=1):o.startsWith("--config=")?t.configPath=o.slice(9):o.startsWith("--out=")?t.outFile=o.slice(6):o.startsWith("--inventory=")?t.inventoryFile=o.slice(12):o.startsWith("--tsconfig=")&&(t.tsConfigFilePath=o.slice(11)))}return t}(e);if(t.showHelp)return process.stdout.write('pll-codegen — generate TypeScript types from a Payload config\n\nUsage:\n pll-codegen --config <path> --out <path> [--inventory <path>] [--tsconfig <path>] [--quiet]\n pll-codegen annotate <path...> --config <path> [--write]\n\nRequires ts-morph to read the config: npm install --save-dev ts-morph\n\nOptions:\n -c, --config <path> Path to payload.config.ts (required)\n -o, --out <path> Output file for generated types (required)\n --inventory <path> Also write the preview inventory (JSON) here\n --tsconfig <path> Use this tsconfig for cross-file import resolution\n -q, --quiet Suppress non-error logging\n -h, --help Show this help\n\nExit codes:\n 0 types written (warnings, if any, on stderr)\n 1 fatal error\n 2 no globals or collections found; nothing was written\n\nSubcommands:\n annotate Add data-payload-field where a template already prints a\n field, and report every place it will not guess at.\n Run "pll-codegen annotate --help" for its options.\n\nExamples:\n pll-codegen --config backend/src/payload.config.ts --out frontend/src/payload-types.ts\n pll-codegen -c ./payload.config.ts -o ./generated.ts\n'),0;if(void 0===t.configPath||void 0===t.outFile)return process.stderr.write("pll-codegen: --config and --out are required. Try `pll-codegen --help`.\n"),1;try{const e=await xe({configPath:t.configPath,outFile:t.outFile,...void 0!==t.inventoryFile?{inventoryFile:t.inventoryFile}:{},...void 0!==t.tsConfigFilePath?{tsConfigFilePath:t.tsConfigFilePath}:{}}),{globals:n,collections:o}=e.schema,i=n.length+o.length;if(t.quiet||void 0===e.outFile||process.stdout.write(`pll-codegen: wrote ${e.outFile} (${String(n.length)} globals, ${String(o.length)} collections)\n`),!t.quiet&&void 0!==e.inventoryFile){const t=[...e.inventory.globals,...e.inventory.collections].reduce((e,t)=>e+t.fields.length,0);process.stdout.write(`pll-codegen: wrote ${e.inventoryFile} (${String(t)} addressable fields)\n`)}if(!t.quiet||0===i)for(const t of e.diagnostics)process.stderr.write(` warning: ${t}\n`);return 0===i?(process.stderr.write("pll-codegen: no globals or collections found; nothing was written. Check that the config path is correct.\n"),2):0}catch(e){return process.stderr.write(`pll-codegen: ${e instanceof Error?e.message:String(e)}\n`),1}}function Ae(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-codegen"===n||"pll-codegen.cmd"===n||n.startsWith("codegen-cli")}Ae()&&Fe(process.argv.slice(2)).then(e=>{process.exit(e)});export{Ae as isCliInvocation,Fe as run};
2
+ import{stat as e,readFile as t,writeFile as n,mkdir as o,readdir as i}from"fs/promises";import{resolve as s,extname as r,relative as a,isAbsolute as l,dirname as c,join as d}from"path";import{createRequire as u}from"module";function f(e){return e.split(/[-_\s]+/u).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}var p,h=/^[A-Za-z_$][\w$]*$/u;function g(e,t){return`${e}${f(t)}`}function y(e,t,n,o){!0===o.markLocalizedAsDeprecated&&e.localized&&n.push(" /** @localized */");const i=e.required?"":"?";var s;n.push(` ${s=e.name,h.test(s)?s:`'${s.replace(/\\/gu,"\\\\").replace(/'/gu,"\\'")}'`}${i}: ${function(e,t){switch(e.kind){case"scalar":return!0===e.hasMany?`${e.typeRef}[]`:e.typeRef;case"array":return`${g(t,e.name)}[]`;case"blocks":return 0===e.blocks.length?"unknown[]":`(${e.blocks.map(n=>g(g(t,e.name),n.typeName)).join(" | ")})[]`;case"group":return g(t,e.name);case"relationship":{const t=`PayloadRelationship<${"string"==typeof e.target?`'${e.target}'`:e.target.map(e=>`'${e}'`).join(" | ")}>`;return e.hasMany?`${t}[]`:t}case"upload":return!0===e.hasMany?"PayloadMedia[]":"PayloadMedia";case"json":return"unknown";case"select":{if(0===e.options.length)return e.hasMany?"string[]":"string";const t=e.options.map(e=>`'${e}'`).join(" | ");return e.hasMany?`(${t})[]`:t}}}(e,t)};`)}function m(e,t,n,o){n.push(`export interface ${e} {`),n.push(` blockType: '${t.slug}';`);for(const i of t.fields)y(i,e,n,o);n.push("}","")}function v(e,t,n,o,i){for(const s of t){const t=g(e,s.name);if("array"===s.kind||"group"===s.kind){if(o.has(t))continue;o.add(t),v(t,s.fields,n,o,i),n.push(`export interface ${t} {`);for(const e of s.fields)y(e,t,n,i);n.push("}","")}else if("blocks"===s.kind)for(const e of s.blocks){const s=g(t,e.typeName);o.has(s)||(o.add(s),v(s,e.fields,n,o,i),m(s,e,n,i))}}}function w(e,t,n,o){v(e.typeName,e.fields,t,n,o),t.push(`export interface ${e.typeName} {`);for(const n of e.fields)y(n,e.typeName,t,o);t.push("}")}function b(e,t,n){if(0!==t.length){n.push(`export type ${e} = {`);for(const e of t)n.push(` '${e.slug}': ${e.typeName};`);n.push("};","")}}function $(e,t,n){for(const o of e){if("group"===o.kind&&"__structural"===o.name){$(o.fields,t,n);continue}const e=""===t?o.name:`${t}.${o.name}`;if(n.push({path:e,kind:o.kind,localized:o.localized,required:o.required}),"group"===o.kind)$(o.fields,e,n);else if("array"===o.kind)$(o.fields,`${e}.*`,n);else if("blocks"===o.kind)for(const t of o.blocks)$(t.fields,`${e}.*.${t.slug}`,n)}}function x(e){const t=[];return $(e.fields,"",t),{slug:e.slug,typeName:e.typeName,fields:t}}function k(){if(void 0===p)try{p=u(import.meta.url)("ts-morph")}catch(e){throw new Error("pll-codegen needs ts-morph: npm install --save-dev ts-morph",{cause:e})}return p}function S(){return k().Node}function P(e,t,n){e.diagnostics.push(`Skipped "${function(e){const t=e.getText().replace(/\s+/gu," ");return t.length>60?`${t.slice(0,57)}...`:t}(t)}" at ${function(e){return`${e.getSourceFile().getBaseName()}:${String(e.getStartLineNumber())}`}(t)}: ${n}.`)}function F(e){let t=e;for(;S().isParenthesizedExpression(t)||S().isAsExpression(t)||S().isSatisfiesExpression(t)||S().isNonNullExpression(t)||S().isTypeAssertion(t);)t=t.getExpression();return t}function A(e){if(!(S().isImportSpecifier(e)||S().isImportClause(e)||S().isNamespaceImport(e)||S().isExportSpecifier(e)))return[e];const t=e.getSymbol()?.getAliasedSymbol();return t?.getDeclarations()??[e]}function E(e){const t=e.getDefinitionNodes();return(t.length>0?t:e.getSymbol()?.getDeclarations()??[]).flatMap(A)}function C(e){return S().isVariableDeclaration(e)||S().isPropertyAssignment(e)?e.getInitializer():S().isExportAssignment(e)?e.getExpression():S().isShorthandPropertyAssignment(e)?e.getNameNode():void 0}function N(e,t){const n=e.getProperty(t);if(void 0!==n)return S().isPropertyAssignment(n)?n.getInitializer():S().isShorthandPropertyAssignment(n)?n.getNameNode():void 0}function j(e,t){return void 0!==e.getProperty(t)}function q(e){const t=F(e.getExpression());if(S().isIdentifier(t))for(const e of E(t)){const t=S().isVariableDeclaration(e)?e.getInitializer():e;if(void 0===t||!(S().isFunctionDeclaration(t)||S().isArrowFunction(t)||S().isFunctionExpression(t)))continue;const n=t.getBody();if(void 0===n)continue;if(!S().isBlock(n))return n;const[o,...i]=n.getStatements();if(void 0!==o&&0===i.length&&S().isReturnStatement(o))return o.getExpression()}}function z(e,t=/* @__PURE__ */new Set){if(void 0===e||t.has(e))return;t.add(e);const n=F(e);if(S().isObjectLiteralExpression(n))return n;if(S().isCallExpression(n)){const e=z(q(n),t);return void 0===e||e.getProperties().some(S().isSpreadAssignment)?z(n.getArguments()[0],t):e}if(S().isIdentifier(n))for(const e of E(n)){const n=z(C(e),t);if(void 0!==n)return n}if(S().isPropertyAccessExpression(n)){const e=z(n.getExpression(),t);if(void 0!==e)return z(N(e,n.getName()),t)}}function M(e,t=/* @__PURE__ */new Set){if(void 0===e||t.has(e))return;t.add(e);const n=F(e);if(S().isArrayLiteralExpression(n))return n;if(S().isCallExpression(n)){const e=n.getExpression();return S().isPropertyAccessExpression(e)&&"map"===e.getName()?M(e.getExpression(),t):M(q(n),t)}if(S().isIdentifier(n))for(const e of E(n)){const n=M(C(e),t);if(void 0!==n)return n}if(S().isPropertyAccessExpression(n)){const e=z(n.getExpression(),t);if(void 0!==e)return M(N(e,n.getName()),t)}}function L(e,t){const n=[];for(const o of e.getElements()){if(!S().isSpreadElement(o)){n.push(o);continue}const e=M(o.getExpression());void 0!==e?n.push(...L(e,t)):P(t,o,"could not resolve the spread to an array literal, so its entries are missing")}return n}function D(e,t){const n=N(e,t);if(void 0===n)return;const o=F(n);return S().isStringLiteral(o)||S().isNoSubstitutionTemplateLiteral(o)?o.getLiteralValue():void 0}function O(e,t){const n=N(e,t);if(void 0===n)return;const o=F(n);return!!S().isTrueLiteral(o)||!S().isFalseLiteral(o)&&void 0}function T(e,t){return M(N(e,t))}function I(e){const t=N(e,"relationTo");if(void 0===t)return"unknown";const n=F(t);if(S().isStringLiteral(n))return n.getLiteralValue();const o=M(n);return void 0===o?"unknown":o.getElements().map(F).filter(e=>S().isStringLiteral(e)).map(e=>e.getLiteralValue())}var _="__structural",W=/* @__PURE__ */new Set(["tabs","row","collapsible"]),R={text:"string",textarea:"string",email:"string",richText:"unknown",number:"number",checkbox:"boolean",date:"string",code:"string",point:"[number, number]"},V=/* @__PURE__ */new Set(["text","number"]);function Z(e,t){const n=[];for(const o of L(e,t)){const e=z(o);if(void 0===e){P(t,o,"could not resolve the field to an object literal");continue}const i=G(e,t);void 0!==i&&("group"===i.kind&&i.name===_?n.push(...i.fields):n.push(i))}return n}function B(e,t){const n=T(e,"fields");return void 0!==n?Z(n,t):(P(t,e,j(e,"fields")?"its `fields` could not be resolved to an array literal":"it has no `fields`"),[])}function H(e,t){const n=T(e,"tabs");if(void 0===n)return P(t,e,"its `tabs` could not be resolved to an array literal"),[];const o=[];for(const e of L(n,t)){const n=z(e);if(void 0===n){P(t,e,"could not resolve the tab to an object literal");continue}const i=D(n,"name"),s=B(n,t);void 0===i?o.push(...s):o.push({kind:"group",name:i,required:!1,localized:!1,fields:s})}return o}function U(e,t){const n=T(e,"blocks");if(void 0===n)return P(t,e,"its `blocks` could not be resolved to an array literal"),[];const o=[];for(const e of L(n,t)){const n=z(e);if(void 0===n){P(t,e,"could not resolve the block to an object literal");continue}const i=D(n,"slug");void 0!==i?o.push({slug:i,typeName:f(i),fields:B(n,t)}):P(t,e,"a block needs a string `slug`")}return o}function J(e,t){const n=T(e,"options");if(void 0===n)return P(t,e,"its `options` could not be resolved to an array literal"),[];const o=[];for(const e of L(n,t)){if(S().isStringLiteral(e)){o.push(e.getLiteralValue());continue}const n=z(e),i=void 0===n?void 0:D(n,"value");void 0===i?P(t,e,"an option needs a string or a `value`"):o.push(i)}return o}function G(e,t){const n=D(e,"type");if(void 0===n)return void P(t,e,"it has no string `type`");if("ui"===n)return;const o=D(e,"name");if(void 0===o&&!W.has(n))return void P(t,e,`a ${n} field needs a string \`name\``);const i={name:o??_,required:O(e,"required")??!1,localized:O(e,"localized")??!1},s=O(e,"hasMany")??!1;switch(n){case"array":return{...i,kind:"array",fields:B(e,t)};case"group":case"row":case"collapsible":return{...i,kind:"group",fields:B(e,t)};case"tabs":return{...i,kind:"group",fields:H(e,t)};case"blocks":return{...i,kind:"blocks",blocks:U(e,t)};case"relationship":return{...i,kind:"relationship",target:I(e),hasMany:s};case"upload":{const t=I(e);return{...i,kind:"upload",target:("string"==typeof t?t:t[0])??"media",hasMany:s}}case"json":return{...i,kind:"json"};case"select":case"radio":return{...i,kind:"select",options:J(e,t),hasMany:"select"===n&&s};default:return{...i,kind:"scalar",typeRef:R[n]??"unknown",hasMany:V.has(n)&&s}}}function K(e){if(S().isExportAssignment(e))return e.getExpression()}function X(e,t,n){const o=N(e,t);if(void 0===o)return[];const i=M(o);if(void 0===i)return P(n,o,`could not resolve \`${t}\` to an array literal`),[];const s=[];for(const e of L(i,n)){const t=z(e);if(void 0===t){P(n,e,"could not resolve the config entry to an object literal");continue}const o=D(t,"slug");if(void 0===o){P(n,e,"the config entry has no string `slug`");continue}const i=T(t,"fields");void 0===i&&P(n,t,j(t,"fields")?`the \`fields\` of "${o}" could not be resolved to an array literal`:`"${o}" has no \`fields\``),s.push({slug:o,typeName:f(o),fields:void 0===i?[]:Z(i,n)})}return s}var Q=/<([a-z][a-z0-9-]*)((?:"[^"]*"|'[^']*'|\{(?:[^{}]|\{[^{}]*\})*\}|[^>"'{])*)>([^<]*)<\/\1\s*>/gu,Y=/<script\b[^>]*>[\s\S]*?<\/script\b[^>]*>|<style\b[^>]*>[\s\S]*?<\/style\b[^>]*>|<!--[\s\S]*?-->/giu,ee=/^\s*\{([^{}]*)\}\s*$/u,te=/\{([^{}]*)\}/u,ne=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/u,oe="data-payload-field",ie=/\bdata-payload-field\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*(["'`])([^"'`]*)\3\s*\})/u,se=/\{\s*\.\.\.\s*(?:[\w$]+\s*\.\s*)*(?:bind|bindByPath)\s*(?:<[^>]*>)?\s*\(\s*(?:(["'`])([^"'`]*)\1)?/u,re=/\{\s*\.\.\./u,ae=[/\.(?: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 le(e){return e.replace(/[^\n]/gu," ")}function ce(e){const{bodyOffset:t}=function(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}}(e),n=e.slice(t).replace(Y,le);return`${le(e.slice(0,t))}${n}`}function de(e,t){let n=1;for(let o=0;o<t;o+=1)10===e.charCodeAt(o)&&(n+=1);return n}function ue(e){return e.slice(e.indexOf(".")+1)}function fe(e){return e.slice(0,e.indexOf("."))}function pe(e){const t=e.replace(/\s+/gu," ").trim();return t.length>60?`${t.slice(0,57)}…`:t}function he(e){if(e.includes(oe)){const t=ie.exec(e);return{path:t?.[1]??t?.[2]??t?.[4]}}const t=se.exec(e);return null===t?null:{path:t[2]}}function ge(e,t){const n=e.trim();if(0===n.length)return"the element is empty";if(!ne.test(n))return"not a plain field access — a call, an operator or an index cannot be traced to one field";const o=ue(n),i=fe(n);if(t.items.has(i))return`\`${i}\` is a loop item — a binding names a field of the document, and \`${o}\` there is a different value, or none`;if(!t.known.has(o))return`the schema has no field \`${o}\`; the binding would name something that never arrives`;const s=t.anchors.get(i);if(void 0===s)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 r=[...s,o];return t.entities.some(e=>r.every(t=>e.has(t)))?void 0:`no single collection or global has \`${o}\` and what this file binds on \`${i}\` (${[...s].map(e=>`\`${e}\``).join(", ")}) — one variable holds one document`}function ye(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':re.test(t)?"the element spreads attributes the scan cannot read, and one of them may already bind it":void 0}function me(e,t){const n=/* @__PURE__ */new Map;for(const[,,o="",i=""]of e){const e=he(o)?.path,s=ee.exec(i)?.[1]?.trim();if(void 0===e||void 0===s||!ne.test(s))continue;const r=fe(s);if(ue(s)!==e||t.has(r))continue;const a=n.get(r)??/* @__PURE__ */new Set;a.add(e),n.set(r,a)}return n}function ve(e,t){const n=[],o=[],i=function(e){const t=/* @__PURE__ */new Set;for(const n of ae)for(const o of e.matchAll(n))void 0!==o[1]&&t.add(o[1]);return t}(e),s=[...ce(e).matchAll(Q)],r={known:new Set(t.entities.flatMap(e=>[...e])),entities:t.entities,items:i,anchors:me(s,i)};for(const t of s){const[,i="",s="",a=""]=t,l=de(e,t.index);if(null!==he(s))continue;if(null===te.exec(a))continue;const c=ye(i,s);if(void 0!==c){o.push({line:l,reason:c,expression:pe(a)});continue}const d=ee.exec(a);if(null===d){o.push({line:l,reason:"the value is printed beside other content — a binding replaces the whole text, so the markup has to be split first",expression:pe(a)});continue}const u=d[1]??"",f=ge(u,r);void 0===f?n.push({insertAt:t.index+1+i.length,path:ue(u.trim()),line:l,tag:i}):o.push({line:l,reason:f,expression:pe(u)})}return{candidates:n,refusals:o}}function we(e){return`${oe}="${e.path}"`}function be(e,t,n=we){let o=e;for(const e of[...t].sort((e,t)=>t.insertAt-e.insertAt))o=`${o.slice(0,e.insertAt)} ${n(e)}${o.slice(e.insertAt)}`;return o}var $e=[".astro",".jsx",".tsx",".svelte"];async function xe(e,t){await o(c(e),{recursive:!0}),await n(e,t,"utf8")}async function ke(e){const t=e.cwd??process.cwd(),n=e=>l(e)?e:s(t,e),o=function(e){const t=e.project??new(k().Project)(void 0!==e.tsConfigFilePath?{tsConfigFilePath:e.tsConfigFilePath}:{skipAddingFilesFromTsConfig:!0}),n=t.addSourceFileAtPathIfExists(e.configPath);if(void 0===n)return{globals:[],collections:[],diagnostics:[`Could not open ${e.configPath}`]};t.resolveSourceFileDependencies();const o={diagnostics:[]},i=function(e,t){const n=e.getDefaultExportSymbol();if(void 0!==n){for(const e of n.getDeclarations()){const t=z(K(e));if(void 0!==t)return t}for(const t of e.getDescendantsOfKind(k().SyntaxKind.CallExpression)){const e=t.getExpression();if(!S().isIdentifier(e)||"buildConfig"!==e.getText())continue;const n=z(t.getArguments()[0]);if(void 0!==n)return n}}else t.diagnostics.push("payload.config.ts has no default export.")}(n,o);return void 0===i?{globals:[],collections:[],diagnostics:[...o.diagnostics,"Could not locate a buildConfig({...}) call or `export default {...}` in the config file."]}:{globals:X(i,"globals",o),collections:X(i,"collections",o),diagnostics:o.diagnostics}}({configPath:n(e.configPath),...void 0!==e.project?{project:e.project}:{},...void 0!==e.tsConfigFilePath?{tsConfigFilePath:e.tsConfigFilePath}:{}}),i=function(e,t={}){const n=[t.header??"// Auto-generated by payload-live-preview/codegen.\n// Do not edit by hand — run `pll-codegen` to regenerate.\n/* eslint-disable */",""];n.push('import type { PayloadMedia, PayloadRelationship } from "payload-live-preview";',"");const o=/* @__PURE__ */new Set;for(const i of[...e.globals,...e.collections])w(i,n,o,t),n.push("");b("PayloadGlobals",e.globals,n),b("PayloadCollections",e.collections,n);const i=[];return e.globals.length>0&&i.push("keyof PayloadGlobals"),e.collections.length>0&&i.push("keyof PayloadCollections"),i.length>0&&n.push(`export type PayloadSlug = ${i.join(" | ")};`,""),n.join("\n").replace(/\n{3,}/gu,"\n\n")}(o,e),r=function(e){return{globals:e.globals.map(x),collections:e.collections.map(x)}}(o),a=[...o.diagnostics],c=void 0===e.outFile?void 0:n(e.outFile),d=void 0===e.inventoryFile?void 0:n(e.inventoryFile),u=[c,d].filter(e=>void 0!==e),f=o.globals.length+o.collections.length===0;return f&&u.length>0?a.push(`Nothing written: the schema is empty (0 globals, 0 collections), so ${u.join(" and ")} were left as they are.`):(void 0!==c&&await xe(c,i),void 0!==d&&await xe(d,`${JSON.stringify(r,null,2)}\n`)),{code:i,diagnostics:a,schema:o,inventory:r,...f||void 0===c?{}:{outFile:c},...f||void 0===d?{}:{inventoryFile:d}}}var Se=/* @__PURE__ */new Set(["node_modules","dist",".git",".astro",".svelte-kit",".next",".nuxt","coverage"]);async function Pe(e){const t=[];for(const n of await i(e,{withFileTypes:!0}))if(n.isDirectory()){if(Se.has(n.name))continue;t.push(...await Pe(d(e,n.name)))}else $e.includes(r(n.name))&&t.push(d(e,n.name));return t}async function Fe(o,i){const l=function(e){const t=[];let n,o=!1,i=!1;for(let s=0;s<e.length;s+=1){const r=e[s];void 0!==r&&("-h"===r||"--help"===r?i=!0:"--write"===r?o=!0:"--config"===r||"-c"===r?(n=e[s+1],s+=1):r.startsWith("--config=")?n=r.slice(9):r.startsWith("-")||t.push(r))}return{paths:t,configPath:n,write:o,showHelp:i}}(o);if(l.showHelp)return i.out("pll-codegen annotate — add data-payload-field where a template prints a field\n\nUsage:\n pll-codegen annotate <path...> --config <payload.config.ts> [--write]\n\nRequires ts-morph to read the config: npm install --save-dev ts-morph\n\nOptions:\n -c, --config <path> Path to payload.config.ts (required): the schema decides\n which paths exist\n --write Write the annotated files; without it nothing is touched\n -h, --help Show this help\n\nWhat it annotates:\n An element whose entire content is one field access, <p>{page.subtitle}</p>,\n on a variable the same file already binds a field of by hand:\n <h1 data-payload-field=\"title\">{page.title}</h1> or {...preview.bind('title')}.\n That binding is what says page holds the document being previewed, and the\n path must be in the collection or global that has the hand-bound fields.\n Astro, JSX and Svelte templates.\n\nWhat it refuses, with a reason per line:\n a value printed beside other text, a call or an operator, a field printed\n from a loop item, a path the schema does not know, a variable the file binds\n no field of, a link (<a>), a <title>, and an element that spreads attributes\n it cannot read. An element already bound by data-payload-field or by a\n bind() spread is left as it is, without a line; <script>, <style>, comments\n and Astro frontmatter are not read.\n\nExit codes:\n 0 nothing left to do, or the files were written\n 1 fatal error\n 2 no globals or collections found in the config; nothing was scanned\n 3 a dry run found work; re-run with --write\n"),0;if(void 0===l.configPath||0===l.paths.length)return i.err("pll-codegen annotate: --config and at least one path are required.\n"),1;try{const{inventory:o,schema:c,diagnostics:d}=await ke({configPath:l.configPath});for(const e of d)i.err(` warning: ${e}\n`);if(c.globals.length+c.collections.length===0)return i.err("pll-codegen annotate: the schema is empty (0 globals, 0 collections), so nothing was scanned: every field would have been refused as unknown. The warnings above name what could not be read. Imports through a path alias (@/...) are not followed, so a config that reaches its collections or globals that way reads as empty here.\n"),2;const u=await async function(t){const n=[];for(const o of t){const t=s(o);(await e(t)).isDirectory()?n.push(...await Pe(t)):$e.includes(r(t))&&n.push(t)}return n.sort()}(l.paths);if(0===u.length)return i.err(`pll-codegen annotate: no ${$e.join(", ")} files found.\n`),1;const f=await async function(e){const o=e.io?.read??(e=>t(e,"utf8")),i=e.io?.write??((e,t)=>n(e,t,"utf8")),s=e.cwd??process.cwd(),r=[...(l=e.inventory).globals,...l.collections].map(e=>new Set(e.fields.map(e=>e.path).filter(e=>!e.includes("*"))));var l;const c=[];for(const t of e.files){const n=await o(t),{candidates:l,refusals:d}=ve(n,{entities:r}),u=0===l.length?n:be(n,l),f=u!==n;f&&!0===e.write&&await i(t,u),c.push({file:a(s,t)||t,code:u,annotations:l,refusals:d,changed:f})}return{files:c,annotationCount:c.reduce((e,t)=>e+t.annotations.length,0),refusalCount:c.reduce((e,t)=>e+t.refusals.length,0),written:!0===e.write}}({files:u,inventory:o,write:l.write});return i.out(function(e){const t=[];for(const n of e.files)if(0!==n.annotations.length||0!==n.refusals.length){t.push(n.file);for(const e of n.annotations)t.push(` ${String(e.line)}: <${e.tag}> → ${e.path}`);for(const e of n.refusals)t.push(` ${String(e.line)}: left alone — ${e.reason} (${e.expression})`)}const n=e.written?"annotated":"would annotate";return t.push(`${n} ${String(e.annotationCount)} element(s); ${String(e.refusalCount)} left for a human`),`${t.join("\n")}\n`}(f)),!l.write&&f.annotationCount>0?3:0}catch(e){return i.err(`pll-codegen annotate: ${e instanceof Error?e.message:String(e)}\n`),1}}async function Ae(e){if("annotate"===e[0])return Fe(e.slice(1),{out:e=>process.stdout.write(e),err:e=>process.stderr.write(e)});const t=function(e){const t={configPath:void 0,outFile:void 0,inventoryFile:void 0,tsConfigFilePath:void 0,showHelp:!1,quiet:!1};for(let n=0;n<e.length;n+=1){const o=e[n];void 0!==o&&("-h"===o||"--help"===o?t.showHelp=!0:"-q"===o||"--quiet"===o?t.quiet=!0:"--config"===o||"-c"===o?(t.configPath=e[n+1],n+=1):"--out"===o||"-o"===o?(t.outFile=e[n+1],n+=1):"--inventory"===o?(t.inventoryFile=e[n+1],n+=1):"--tsconfig"===o?(t.tsConfigFilePath=e[n+1],n+=1):o.startsWith("--config=")?t.configPath=o.slice(9):o.startsWith("--out=")?t.outFile=o.slice(6):o.startsWith("--inventory=")?t.inventoryFile=o.slice(12):o.startsWith("--tsconfig=")&&(t.tsConfigFilePath=o.slice(11)))}return t}(e);if(t.showHelp)return process.stdout.write('pll-codegen — generate TypeScript types from a Payload config\n\nUsage:\n pll-codegen --config <path> --out <path> [--inventory <path>] [--tsconfig <path>] [--quiet]\n pll-codegen annotate <path...> --config <path> [--write]\n\nRequires ts-morph to read the config: npm install --save-dev ts-morph\n\nOptions:\n -c, --config <path> Path to payload.config.ts (required)\n -o, --out <path> Output file for generated types (required)\n --inventory <path> Also write the preview inventory (JSON) here\n --tsconfig <path> Use this tsconfig for cross-file import resolution\n -q, --quiet Suppress non-error logging\n -h, --help Show this help\n\nExit codes:\n 0 types written (warnings, if any, on stderr)\n 1 fatal error\n 2 no globals or collections found; nothing was written\n\nSubcommands:\n annotate Add data-payload-field where a template already prints a\n field, and report every place it will not guess at.\n Run "pll-codegen annotate --help" for its options.\n\nExamples:\n pll-codegen --config backend/src/payload.config.ts --out frontend/src/payload-types.ts\n pll-codegen -c ./payload.config.ts -o ./generated.ts\n'),0;if(void 0===t.configPath||void 0===t.outFile)return process.stderr.write("pll-codegen: --config and --out are required. Try `pll-codegen --help`.\n"),1;try{const e=await ke({configPath:t.configPath,outFile:t.outFile,...void 0!==t.inventoryFile?{inventoryFile:t.inventoryFile}:{},...void 0!==t.tsConfigFilePath?{tsConfigFilePath:t.tsConfigFilePath}:{}}),{globals:n,collections:o}=e.schema,i=n.length+o.length;if(t.quiet||void 0===e.outFile||process.stdout.write(`pll-codegen: wrote ${e.outFile} (${String(n.length)} globals, ${String(o.length)} collections)\n`),!t.quiet&&void 0!==e.inventoryFile){const t=[...e.inventory.globals,...e.inventory.collections].reduce((e,t)=>e+t.fields.length,0);process.stdout.write(`pll-codegen: wrote ${e.inventoryFile} (${String(t)} addressable fields)\n`)}if(!t.quiet||0===i)for(const t of e.diagnostics)process.stderr.write(` warning: ${t}\n`);return 0===i?(process.stderr.write("pll-codegen: no globals or collections found; nothing was written. Check that the config path is correct.\n"),2):0}catch(e){return process.stderr.write(`pll-codegen: ${e instanceof Error?e.message:String(e)}\n`),1}}function Ee(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-codegen"===n||"pll-codegen.cmd"===n||n.startsWith("codegen-cli")}Ee()&&Ae(process.argv.slice(2)).then(e=>{process.exit(e)});export{Ee as isCliInvocation,Ae as run};
3
3
  //# sourceMappingURL=codegen-cli.js.map