payload-live-preview 2.0.0 → 2.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +41 -34
- package/dist/adapters/astro/RichText.astro +1 -1
- package/dist/adapters/astro/index.d.ts +8 -8
- package/dist/adapters/astro/index.js +1 -1
- package/dist/adapters/astro/index.js.map +1 -1
- package/dist/adapters/astro/middleware-entry.d.ts +3 -3
- package/dist/adapters/astro/middleware-entry.js +1 -1
- package/dist/adapters/astro/middleware-entry.js.map +1 -1
- package/dist/adapters/nextjs/index.d.ts +2 -2
- package/dist/adapters/nextjs/index.js +1 -1
- package/dist/adapters/nextjs/index.js.map +1 -1
- package/dist/adapters/nuxt/index.d.ts +4 -4
- package/dist/adapters/nuxt/index.js +1 -1
- package/dist/adapters/nuxt/index.js.map +1 -1
- package/dist/adapters/nuxt/module.d.ts +13 -5
- package/dist/adapters/nuxt/module.js.map +1 -1
- package/dist/adapters/react/index.d.ts +8 -6
- package/dist/adapters/react/index.js.map +1 -1
- package/dist/adapters/sveltekit/index.d.ts +5 -5
- package/dist/adapters/sveltekit/index.js +1 -1
- package/dist/adapters/sveltekit/index.js.map +1 -1
- package/dist/adapters/vue/index.d.ts +3 -3
- package/dist/adapters/vue/index.js.map +1 -1
- package/dist/annotate.js +1 -1
- package/dist/annotate.js.map +1 -1
- package/dist/client.cjs +1 -1
- package/dist/client.cjs.map +1 -1
- package/dist/client.js +1 -1
- package/dist/client.js.map +1 -1
- package/dist/codegen-astro.d.ts +4 -1
- package/dist/codegen-astro.js.map +1 -1
- package/dist/codegen-cli.js +1 -1
- package/dist/codegen-cli.js.map +1 -1
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.cjs.map +1 -1
- package/dist/codegen.js +1 -1
- package/dist/codegen.js.map +1 -1
- package/dist/core.cjs +1 -1
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +1 -1
- package/dist/core.d.ts +1 -1
- package/dist/core.js +1 -1
- package/dist/core.js.map +1 -1
- package/dist/doctor-cli.d.ts +1 -1
- package/dist/doctor-cli.js +1 -1
- package/dist/doctor-cli.js.map +1 -1
- package/dist/doctor.d.ts +4 -2
- package/dist/doctor.js +1 -1
- package/dist/doctor.js.map +1 -1
- package/dist/{fragment-endpoint-3Mlz7GDz.d.ts → fragment-endpoint-DATKU183.d.ts} +2 -2
- package/dist/fragment.cjs.map +1 -1
- package/dist/fragment.d.cts +6 -3
- package/dist/fragment.d.ts +6 -3
- package/dist/fragment.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +10 -10
- package/dist/index.d.ts +10 -10
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/lean.cjs +1 -1
- package/dist/lean.cjs.map +1 -1
- package/dist/lean.d.cts +3 -3
- package/dist/lean.d.ts +3 -3
- package/dist/lean.js +1 -1
- package/dist/lean.js.map +1 -1
- package/dist/lexical.cjs +1 -1
- package/dist/lexical.cjs.map +1 -1
- package/dist/lexical.d.cts +11 -1
- package/dist/lexical.d.ts +11 -1
- package/dist/lexical.js +1 -1
- package/dist/lexical.js.map +1 -1
- package/dist/{locals-DBXDMxOA.d.ts → locals-CNUGYbA_.d.ts} +1 -1
- package/dist/{middleware-Bx9I7PXW.d.ts → middleware-CWObDO37.d.ts} +2 -2
- package/dist/migrate.d.ts +6 -0
- package/dist/migrate.js +1 -1
- package/dist/migrate.js.map +1 -1
- package/dist/{options-BW1eqXvc.d.ts → options-uHKrDM2U.d.ts} +2 -1
- package/dist/plugins.cjs +1 -1
- package/dist/plugins.cjs.map +1 -1
- package/dist/plugins.js +1 -1
- package/dist/plugins.js.map +1 -1
- package/dist/{probe-CELeUciC.d.ts → probe-DqaItcwX.d.ts} +15 -0
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +1 -1
- package/dist/server.d.ts +1 -1
- package/dist/server.js.map +1 -1
- package/dist/structural.cjs +2 -2
- package/dist/structural.cjs.map +1 -1
- package/dist/structural.js +2 -2
- package/dist/structural.js.map +1 -1
- package/package.json +6 -4
package/dist/codegen-astro.d.ts
CHANGED
|
@@ -3,7 +3,10 @@ interface AstroCodegenOptions {
|
|
|
3
3
|
readonly configPath: string;
|
|
4
4
|
/** Output path for generated types (absolute or relative to Astro's root). */
|
|
5
5
|
readonly outPath: string;
|
|
6
|
-
/**
|
|
6
|
+
/**
|
|
7
|
+
* Re-run during `astro dev` when a .ts, .mts, .cts, .js, .mjs, .cjs or .json
|
|
8
|
+
* file in or below the config's directory changes. Default `true`.
|
|
9
|
+
*/
|
|
7
10
|
readonly watch?: boolean;
|
|
8
11
|
/** Only log errors. Default `false`. */
|
|
9
12
|
readonly quiet?: boolean;
|
|
@@ -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/** A binding found in consumer markup, however that consumer found it. @internal */\nexport interface PreviewBindingReference {\n readonly kind: 'global' | 'collection';\n readonly slug: string;\n readonly path: string;\n /** Free-form origin for the diagnostic, e.g. `Hero.astro:42`. */\n readonly source?: string;\n}\n\n/** @internal */\nexport interface PreviewCoverageOptions {\n /** Also report schema fields no binding addresses; off, since a page may render a subset. */\n readonly reportUnbound?: boolean;\n}\n\n/** Cross-check bindings the consumer extracted against the inventory. @internal */\nexport function checkPreviewBindings(\n inventory: PreviewInventory,\n bindings: readonly PreviewBindingReference[],\n options: PreviewCoverageOptions = {},\n): readonly string[] {\n const diagnostics: string[] = [];\n const byKey = new Map<string, ReadonlySet<string>>();\n for (const [kind, entries] of [\n ['global', inventory.globals],\n ['collection', inventory.collections],\n ] as const) {\n for (const item of entries) {\n byKey.set(`${kind}:${item.slug}`, new Set(item.fields.map((f) => f.path)));\n }\n }\n\n const seen = new Map<string, Set<string>>();\n for (const binding of bindings) {\n const key = `${binding.kind}:${binding.slug}`;\n const where = binding.source === undefined ? '' : ` (${binding.source})`;\n const paths = byKey.get(key);\n if (paths === undefined) {\n diagnostics.push(`unknown ${binding.kind} \"${binding.slug}\"${where}`);\n continue;\n }\n if (!paths.has(binding.path)) {\n diagnostics.push(`${key} has no field \"${binding.path}\"${where}`);\n continue;\n }\n let bound = seen.get(key);\n if (bound === undefined) {\n bound = new Set<string>();\n seen.set(key, bound);\n }\n bound.add(binding.path);\n }\n\n if (options.reportUnbound === true) {\n for (const [key, paths] of byKey) {\n const bound = seen.get(key) ?? new Set<string>();\n for (const path of paths) {\n if (!bound.has(path)) diagnostics.push(`${key} field \"${path}\" is never bound`);\n }\n }\n }\n\n return diagnostics;\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, checkPreviewBindings } from './inventory';\nexport type {\n PreviewBindingReference,\n PreviewCoverageOptions,\n PreviewInventory,\n PreviewInventoryEntry,\n PreviewInventoryField,\n} 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 anything next to the Payload config changes. Paths are relative to\n * Astro's root. Uses `fs.watch`; no 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 /** Re-run when the config or anything beside it changes during `astro dev`. Default `true`. */\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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,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","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/** A binding found in consumer markup, however that consumer found it. @internal */\nexport interface PreviewBindingReference {\n readonly kind: 'global' | 'collection';\n readonly slug: string;\n readonly path: string;\n /** Free-form origin for the diagnostic, e.g. `Hero.astro:42`. */\n readonly source?: string;\n}\n\n/** @internal */\nexport interface PreviewCoverageOptions {\n /** Also report schema fields no binding addresses; off, since a page may render a subset. */\n readonly reportUnbound?: boolean;\n}\n\n/** Cross-check bindings the consumer extracted against the inventory. @internal */\nexport function checkPreviewBindings(\n inventory: PreviewInventory,\n bindings: readonly PreviewBindingReference[],\n options: PreviewCoverageOptions = {},\n): readonly string[] {\n const diagnostics: string[] = [];\n const byKey = new Map<string, ReadonlySet<string>>();\n for (const [kind, entries] of [\n ['global', inventory.globals],\n ['collection', inventory.collections],\n ] as const) {\n for (const item of entries) {\n byKey.set(`${kind}:${item.slug}`, new Set(item.fields.map((f) => f.path)));\n }\n }\n\n const seen = new Map<string, Set<string>>();\n for (const binding of bindings) {\n const key = `${binding.kind}:${binding.slug}`;\n const where = binding.source === undefined ? '' : ` (${binding.source})`;\n const paths = byKey.get(key);\n if (paths === undefined) {\n diagnostics.push(`unknown ${binding.kind} \"${binding.slug}\"${where}`);\n continue;\n }\n if (!paths.has(binding.path)) {\n diagnostics.push(`${key} has no field \"${binding.path}\"${where}`);\n continue;\n }\n let bound = seen.get(key);\n if (bound === undefined) {\n bound = new Set<string>();\n seen.set(key, bound);\n }\n bound.add(binding.path);\n }\n\n if (options.reportUnbound === true) {\n for (const [key, paths] of byKey) {\n const bound = seen.get(key) ?? new Set<string>();\n for (const path of paths) {\n if (!bound.has(path)) diagnostics.push(`${key} field \"${path}\" is never bound`);\n }\n }\n }\n\n return diagnostics;\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, checkPreviewBindings } from './inventory';\nexport type {\n PreviewBindingReference,\n PreviewCoverageOptions,\n PreviewInventory,\n PreviewInventoryEntry,\n PreviewInventoryField,\n} 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,IAE0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oCrK,aAAiBC,MAAQD,EAAMsK,QAAUvJ,OAAOf,KAExF,CACF,CAQ6CuL,CAAcxB,IAEvD,qBAAsB,OACtB,oBAAqB,KACnBsB,aAAa3B,GACbD,GAAS+B,QACT/B,OAAU,IAIlB,Q","ignoreList":[]}
|
package/dist/codegen-cli.js
CHANGED
|
@@ -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 u}from"path";import{createRequire as d}from"module";function f(e){return e.split(/[-_\s]+/u).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}var p,g=/^[A-Za-z_$][\w$]*$/u;function h(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,g.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`${h(t,e.name)}[]`;case"blocks":return 0===e.blocks.length?"unknown[]":`(${e.blocks.map(n=>h(h(t,e.name),n.typeName)).join(" | ")})[]`;case"group":return h(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 v(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 m(e,t,n,o,i){for(const s of t){const t=h(e,s.name);if("array"===s.kind||"group"===s.kind){if(o.has(t))continue;o.add(t),m(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=h(t,e.typeName);o.has(s)||(o.add(s),m(s,e.fields,n,o,i),v(s,e,n,i))}}}function w(e,t,n,o){m(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=d(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 P(){return k().Node}function S(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(;P().isParenthesizedExpression(t)||P().isAsExpression(t)||P().isSatisfiesExpression(t)||P().isNonNullExpression(t)||P().isTypeAssertion(t);)t=t.getExpression();return t}function A(e){if(!(P().isImportSpecifier(e)||P().isImportClause(e)||P().isNamespaceImport(e)||P().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 P().isVariableDeclaration(e)||P().isPropertyAssignment(e)?e.getInitializer():P().isExportAssignment(e)?e.getExpression():P().isShorthandPropertyAssignment(e)?e.getNameNode():void 0}function N(e,t){const n=e.getProperty(t);if(void 0!==n)return P().isPropertyAssignment(n)?n.getInitializer():P().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(P().isObjectLiteralExpression(n))return n;if(P().isCallExpression(n))return q(n.getArguments()[0],t);if(P().isIdentifier(n))for(const e of E(n)){const n=q(C(e),t);if(void 0!==n)return n}if(P().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(P().isArrayLiteralExpression(n))return n;if(P().isIdentifier(n))for(const e of E(n)){const n=z(C(e),t);if(void 0!==n)return n}if(P().isPropertyAccessExpression(n)){const e=q(n.getExpression(),t);if(void 0!==e)return z(N(e,n.getName()),t)}}function L(e,t){const n=[];for(const o of e.getElements()){if(!P().isSpreadElement(o)){n.push(o);continue}const e=z(o.getExpression());void 0!==e?n.push(...L(e,t)):S(t,o,"could not resolve the spread to an array literal, so its entries are missing")}return n}function M(e,t){const n=N(e,t);if(void 0===n)return;const o=F(n);return P().isStringLiteral(o)||P().isNoSubstitutionTemplateLiteral(o)?o.getLiteralValue():void 0}function D(e,t){const n=N(e,t);if(void 0===n)return;const o=F(n);return!!P().isTrueLiteral(o)||!P().isFalseLiteral(o)&&void 0}function T(e,t){return z(N(e,t))}function W(e){const t=N(e,"relationTo");if(void 0===t)return"unknown";const n=F(t);if(P().isStringLiteral(n))return n.getLiteralValue();const o=z(n);return void 0===o?"unknown":o.getElements().map(F).filter(e=>P().isStringLiteral(e)).map(e=>e.getLiteralValue())}var I="__structural",_=/* @__PURE__ */new Set(["tabs","row","collapsible"]),O={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 H(e,t){const n=[];for(const o of L(e,t)){const e=q(o);if(void 0===e){S(t,o,"could not resolve the field to an object literal");continue}const i=B(e,t);void 0!==i&&("group"===i.kind&&i.name===I?n.push(...i.fields):n.push(i))}return n}function V(e,t){const n=T(e,"fields");return void 0!==n?H(n,t):(S(t,e,j(e,"fields")?"its `fields` could not be resolved to an array literal":"it has no `fields`"),[])}function U(e,t){const n=T(e,"tabs");if(void 0===n)return S(t,e,"its `tabs` could not be resolved to an array literal"),[];const o=[];for(const e of L(n,t)){const n=q(e);if(void 0===n){S(t,e,"could not resolve the tab to an object literal");continue}const i=M(n,"name"),s=V(n,t);void 0===i?o.push(...s):o.push({kind:"group",name:i,required:!1,localized:!1,fields:s})}return o}function J(e,t){const n=T(e,"blocks");if(void 0===n)return S(t,e,"its `blocks` could not be resolved to an array literal"),[];const o=[];for(const e of L(n,t)){const n=q(e);if(void 0===n){S(t,e,"could not resolve the block to an object literal");continue}const i=M(n,"slug");void 0!==i?o.push({slug:i,typeName:f(i),fields:V(n,t)}):S(t,e,"a block needs a string `slug`")}return o}function Z(e,t){const n=T(e,"options");if(void 0===n)return S(t,e,"its `options` could not be resolved to an array literal"),[];const o=[];for(const e of L(n,t)){if(P().isStringLiteral(e)){o.push(e.getLiteralValue());continue}const n=q(e),i=void 0===n?void 0:M(n,"value");void 0===i?S(t,e,"an option needs a string or a `value`"):o.push(i)}return o}function B(e,t){const n=M(e,"type");if(void 0===n)return void S(t,e,"it has no string `type`");if("ui"===n)return;const o=M(e,"name");if(void 0===o&&!_.has(n))return void S(t,e,`a ${n} field needs a string \`name\``);const i={name:o??I,required:D(e,"required")??!1,localized:D(e,"localized")??!1},s=D(e,"hasMany")??!1;switch(n){case"array":return{...i,kind:"array",fields:V(e,t)};case"group":case"row":case"collapsible":return{...i,kind:"group",fields:V(e,t)};case"tabs":return{...i,kind:"group",fields:U(e,t)};case"blocks":return{...i,kind:"blocks",blocks:J(e,t)};case"relationship":return{...i,kind:"relationship",target:W(e),hasMany:s};case"upload":{const t=W(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:Z(e,t),hasMany:"select"===n&&s};default:return{...i,kind:"scalar",typeRef:O[n]??"unknown",hasMany:R.has(n)&&s}}}function G(e){if(P().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 S(n,o,`could not resolve \`${t}\` to an array literal`),[];const s=[];for(const e of L(i,n)){const t=q(e);if(void 0===t){S(n,e,"could not resolve the config entry to an object literal");continue}const o=M(t,"slug");if(void 0===o){S(n,e,"the config entry has no string `slug`");continue}const i=T(t,"fields");void 0===i&&S(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?[]:H(i,n)})}return s}var X=/<([a-z][a-z0-9-]*)((?:"[^"]*"|'[^']*'|[^>"'])*)>([^<]*)<\/\1\s*>/gu,Q=/^\s*\{([^{}]*)\}\s*$/u,Y=/\{([^{}]*)\}/u,ee=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/u,te="data-payload-field";function ne(e,t){let n=1;for(let o=0;o<t;o+=1)10===e.charCodeAt(o)&&(n+=1);return n}function oe(e){return e.slice(e.indexOf(".")+1)}function ie(e){const t=e.replace(/\s+/gu," ").trim();return t.length>60?`${t.slice(0,57)}…`:t}function se(e,t){const n=e.trim();if(0===n.length)return"the element is empty";if(!ee.test(n))return"not a plain field access — a call, an operator or an index cannot be traced to one field";const o=oe(n);return t.has(o)?void 0:`the schema has no field \`${o}\`; the binding would name something that never arrives`}function re(e,t){const n=[],o=[];for(const i of e.matchAll(X)){const[,s="",r="",a=""]=i,l=ne(e,i.index);if(r.includes(te))continue;const c=Q.exec(a);if(null===c){null!==Y.exec(a)&&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:ie(a)});continue}const u=c[1]??"",d=se(u,t.paths);void 0===d?n.push({insertAt:i.index+1+s.length,path:oe(u.trim()),line:l,tag:s}):o.push({line:l,reason:d,expression:ie(u)})}return{candidates:n,refusals:o}}function ae(e){return`${te}="${e.path}"`}function le(e,t,n=ae){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 ce=[".astro",".jsx",".tsx",".svelte"];async function ue(e,t){await o(c(e),{recursive:!0}),await n(e,t,"utf8")}async function de(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(!P().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),u=void 0===e.inventoryFile?void 0:n(e.inventoryFile),d=[c,u].filter(e=>void 0!==e),f=o.globals.length+o.collections.length===0;return f&&d.length>0?a.push(`Nothing written: the schema is empty (0 globals, 0 collections), so ${d.join(" and ")} were left as they are.`):(void 0!==c&&await ue(c,i),void 0!==u&&await ue(u,`${JSON.stringify(r,null,2)}\n`)),{code:i,diagnostics:a,schema:o,inventory:r,...f||void 0===c?{}:{outFile:c},...f||void 0===u?{}:{inventoryFile:u}}}var fe=/* @__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(fe.has(n.name))continue;t.push(...await pe(u(e,n.name)))}else ce.includes(r(n.name))&&t.push(u(e,n.name));return t}async function ge(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\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 — <h1>{page.title}</h1> —\n and whose path the schema has. 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 path the schema\n does not know, an array item inside a loop, and anything already annotated.\n\nExit codes:\n 0 nothing left to do, or the files were written\n 1 fatal error\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}=await de({configPath:l.configPath}),c=await async function(t){const n=[];for(const o of t){const t=s(o);(await e(t)).isDirectory()?n.push(...await pe(t)):ce.includes(r(t))&&n.push(t)}return n.sort()}(l.paths);if(0===c.length)return i.err(`pll-codegen annotate: no ${ce.join(", ")} files found.\n`),1;const u=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=function(e){const t=/* @__PURE__ */new Set;for(const n of[...e.globals,...e.collections])for(const e of n.fields)e.path.includes("*")||t.add(e.path);return t}(e.inventory),l=[];for(const t of e.files){const n=await o(t),{candidates:c,refusals:u}=re(n,{paths:r}),d=0===c.length?n:le(n,c),f=d!==n;f&&!0===e.write&&await i(t,d),l.push({file:a(s,t)||t,code:d,annotations:c,refusals:u,changed:f})}return{files:l,annotationCount:l.reduce((e,t)=>e+t.annotations.length,0),refusalCount:l.reduce((e,t)=>e+t.refusals.length,0),written:!0===e.write}}({files:c,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`}(u)),!l.write&&u.annotationCount>0?3:0}catch(e){return i.err(`pll-codegen annotate: ${e instanceof Error?e.message:String(e)}\n`),1}}async function he(e){if("annotate"===e[0])return ge(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>] [--quiet]\n pll-codegen annotate <path...> --config <path> [--write]\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 de({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 ye(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")}ye()&&he(process.argv.slice(2)).then(e=>{process.exit(e)});export{ye as isCliInvocation,he 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 u}from"path";import{createRequire as d}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 v(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 y(e,t,n,o){n.push(`export interface ${e} {`),n.push(` blockType: '${t.slug}';`);for(const i of t.fields)v(i,e,n,o);n.push("}","")}function m(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),m(t,s.fields,n,o,i),n.push(`export interface ${t} {`);for(const e of s.fields)v(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),m(s,e.fields,n,o,i),y(s,e,n,i))}}}function w(e,t,n,o){m(e.typeName,e.fields,t,n,o),t.push(`export interface ${e.typeName} {`);for(const n of e.fields)v(n,e.typeName,t,o);t.push("}")}function $(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 b(e,t,n){for(const o of e){if("group"===o.kind&&"__structural"===o.name){b(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)b(o.fields,e,n);else if("array"===o.kind)b(o.fields,`${e}.*`,n);else if("blocks"===o.kind)for(const t of o.blocks)b(t.fields,`${e}.*.${t.slug}`,n)}}function x(e){const t=[];return b(e.fields,"",t),{slug:e.slug,typeName:e.typeName,fields:t}}function k(){if(void 0===p)try{p=d(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 P(){return k().Node}function S(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(;P().isParenthesizedExpression(t)||P().isAsExpression(t)||P().isSatisfiesExpression(t)||P().isNonNullExpression(t)||P().isTypeAssertion(t);)t=t.getExpression();return t}function A(e){if(!(P().isImportSpecifier(e)||P().isImportClause(e)||P().isNamespaceImport(e)||P().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 P().isVariableDeclaration(e)||P().isPropertyAssignment(e)?e.getInitializer():P().isExportAssignment(e)?e.getExpression():P().isShorthandPropertyAssignment(e)?e.getNameNode():void 0}function N(e,t){const n=e.getProperty(t);if(void 0!==n)return P().isPropertyAssignment(n)?n.getInitializer():P().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(P().isObjectLiteralExpression(n))return n;if(P().isCallExpression(n))return q(n.getArguments()[0],t);if(P().isIdentifier(n))for(const e of E(n)){const n=q(C(e),t);if(void 0!==n)return n}if(P().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(P().isArrayLiteralExpression(n))return n;if(P().isIdentifier(n))for(const e of E(n)){const n=z(C(e),t);if(void 0!==n)return n}if(P().isPropertyAccessExpression(n)){const e=q(n.getExpression(),t);if(void 0!==e)return z(N(e,n.getName()),t)}}function L(e,t){const n=[];for(const o of e.getElements()){if(!P().isSpreadElement(o)){n.push(o);continue}const e=z(o.getExpression());void 0!==e?n.push(...L(e,t)):S(t,o,"could not resolve the spread to an array literal, so its entries are missing")}return n}function M(e,t){const n=N(e,t);if(void 0===n)return;const o=F(n);return P().isStringLiteral(o)||P().isNoSubstitutionTemplateLiteral(o)?o.getLiteralValue():void 0}function D(e,t){const n=N(e,t);if(void 0===n)return;const o=F(n);return!!P().isTrueLiteral(o)||!P().isFalseLiteral(o)&&void 0}function T(e,t){return z(N(e,t))}function _(e){const t=N(e,"relationTo");if(void 0===t)return"unknown";const n=F(t);if(P().isStringLiteral(n))return n.getLiteralValue();const o=z(n);return void 0===o?"unknown":o.getElements().map(F).filter(e=>P().isStringLiteral(e)).map(e=>e.getLiteralValue())}var W="__structural",I=/* @__PURE__ */new Set(["tabs","row","collapsible"]),O={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 L(e,t)){const e=q(o);if(void 0===e){S(t,o,"could not resolve the field to an object literal");continue}const i=B(e,t);void 0!==i&&("group"===i.kind&&i.name===W?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):(S(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 S(t,e,"its `tabs` could not be resolved to an array literal"),[];const o=[];for(const e of L(n,t)){const n=q(e);if(void 0===n){S(t,e,"could not resolve the tab to an object literal");continue}const i=M(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 S(t,e,"its `blocks` could not be resolved to an array literal"),[];const o=[];for(const e of L(n,t)){const n=q(e);if(void 0===n){S(t,e,"could not resolve the block to an object literal");continue}const i=M(n,"slug");void 0!==i?o.push({slug:i,typeName:f(i),fields:H(n,t)}):S(t,e,"a block needs a string `slug`")}return o}function J(e,t){const n=T(e,"options");if(void 0===n)return S(t,e,"its `options` could not be resolved to an array literal"),[];const o=[];for(const e of L(n,t)){if(P().isStringLiteral(e)){o.push(e.getLiteralValue());continue}const n=q(e),i=void 0===n?void 0:M(n,"value");void 0===i?S(t,e,"an option needs a string or a `value`"):o.push(i)}return o}function B(e,t){const n=M(e,"type");if(void 0===n)return void S(t,e,"it has no string `type`");if("ui"===n)return;const o=M(e,"name");if(void 0===o&&!I.has(n))return void S(t,e,`a ${n} field needs a string \`name\``);const i={name:o??W,required:D(e,"required")??!1,localized:D(e,"localized")??!1},s=D(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:_(e),hasMany:s};case"upload":{const t=_(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:O[n]??"unknown",hasMany:R.has(n)&&s}}}function G(e){if(P().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 S(n,o,`could not resolve \`${t}\` to an array literal`),[];const s=[];for(const e of L(i,n)){const t=q(e);if(void 0===t){S(n,e,"could not resolve the config entry to an object literal");continue}const o=M(t,"slug");if(void 0===o){S(n,e,"the config entry has no string `slug`");continue}const i=T(t,"fields");void 0===i&&S(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=/^\s*\{([^{}]*)\}\s*$/u,Y=/\{([^{}]*)\}/u,ee=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/u,te="data-payload-field",ne=[/\.(?: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 oe(e,t){let n=1;for(let o=0;o<t;o+=1)10===e.charCodeAt(o)&&(n+=1);return n}function ie(e){return e.slice(e.indexOf(".")+1)}function se(e){const t=e.replace(/\s+/gu," ").trim();return t.length>60?`${t.slice(0,57)}…`:t}function re(e,t,n){const o=e.trim();if(0===o.length)return"the element is empty";if(!ee.test(o))return"not a plain field access — a call, an operator or an index cannot be traced to one field";const i=ie(o),s=o.slice(0,o.indexOf("."));return n.has(s)?`\`${s}\` is a loop item — a binding names a field of the document, and \`${i}\` there is a different value, or none`:t.has(i)?void 0:`the schema has no field \`${i}\`; the binding would name something that never arrives`}function ae(e,t){const n=[],o=[],i=function(e){const t=/* @__PURE__ */new Set;for(const n of ne)for(const o of e.matchAll(n))void 0!==o[1]&&t.add(o[1]);return t}(e);for(const s of e.matchAll(X)){const[,r="",a="",l=""]=s,c=oe(e,s.index);if(a.includes(te))continue;const u=Q.exec(l);if(null===u){null!==Y.exec(l)&&o.push({line:c,reason:"the value is printed beside other content — a binding replaces the whole text, so the markup has to be split first",expression:se(l)});continue}const d=u[1]??"",f=re(d,t.paths,i);void 0===f?n.push({insertAt:s.index+1+r.length,path:ie(d.trim()),line:c,tag:r}):o.push({line:c,reason:f,expression:se(d)})}return{candidates:n,refusals:o}}function le(e){return`${te}="${e.path}"`}function ce(e,t,n=le){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 ue=[".astro",".jsx",".tsx",".svelte"];async function de(e,t){await o(c(e),{recursive:!0}),await n(e,t,"utf8")}async function fe(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(!P().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("");$("PayloadGlobals",e.globals,n),$("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),u=void 0===e.inventoryFile?void 0:n(e.inventoryFile),d=[c,u].filter(e=>void 0!==e),f=o.globals.length+o.collections.length===0;return f&&d.length>0?a.push(`Nothing written: the schema is empty (0 globals, 0 collections), so ${d.join(" and ")} were left as they are.`):(void 0!==c&&await de(c,i),void 0!==u&&await de(u,`${JSON.stringify(r,null,2)}\n`)),{code:i,diagnostics:a,schema:o,inventory:r,...f||void 0===c?{}:{outFile:c},...f||void 0===u?{}:{inventoryFile:u}}}var pe=/* @__PURE__ */new Set(["node_modules","dist",".git",".astro",".svelte-kit",".next",".nuxt","coverage"]);async function he(e){const t=[];for(const n of await i(e,{withFileTypes:!0}))if(n.isDirectory()){if(pe.has(n.name))continue;t.push(...await he(u(e,n.name)))}else ue.includes(r(n.name))&&t.push(u(e,n.name));return t}async function ge(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 — <h1>{page.title}</h1> —\n and whose path the schema has. 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 path the schema\n does not know, and a field printed from a loop item. An element that already\n carries data-payload-field is left as it is, without a line.\n\nExit codes:\n 0 nothing left to do, or the files were written\n 1 fatal error\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}=await fe({configPath:l.configPath}),c=await async function(t){const n=[];for(const o of t){const t=s(o);(await e(t)).isDirectory()?n.push(...await he(t)):ue.includes(r(t))&&n.push(t)}return n.sort()}(l.paths);if(0===c.length)return i.err(`pll-codegen annotate: no ${ue.join(", ")} files found.\n`),1;const u=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=function(e){const t=/* @__PURE__ */new Set;for(const n of[...e.globals,...e.collections])for(const e of n.fields)e.path.includes("*")||t.add(e.path);return t}(e.inventory),l=[];for(const t of e.files){const n=await o(t),{candidates:c,refusals:u}=ae(n,{paths:r}),d=0===c.length?n:ce(n,c),f=d!==n;f&&!0===e.write&&await i(t,d),l.push({file:a(s,t)||t,code:d,annotations:c,refusals:u,changed:f})}return{files:l,annotationCount:l.reduce((e,t)=>e+t.annotations.length,0),refusalCount:l.reduce((e,t)=>e+t.refusals.length,0),written:!0===e.write}}({files:c,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`}(u)),!l.write&&u.annotationCount>0?3:0}catch(e){return i.err(`pll-codegen annotate: ${e instanceof Error?e.message:String(e)}\n`),1}}async function ve(e){if("annotate"===e[0])return ge(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 fe({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 ye(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")}ye()&&ve(process.argv.slice(2)).then(e=>{process.exit(e)});export{ye as isCliInvocation,ve as run};
|
|
3
3
|
//# sourceMappingURL=codegen-cli.js.map
|