payload-live-preview 2.0.6 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +141 -38
  2. package/dist/adapters/astro/FragmentBridge.astro +25 -0
  3. package/dist/adapters/astro/PreviewBoundary.astro +2 -4
  4. package/dist/adapters/astro/RichText.astro +26 -5
  5. package/dist/adapters/astro/index.d.ts +41 -9
  6. package/dist/adapters/astro/index.js +1 -1
  7. package/dist/adapters/astro/index.js.map +1 -1
  8. package/dist/adapters/astro/middleware-entry.d.ts +3 -3
  9. package/dist/adapters/astro/middleware-entry.js +1 -1
  10. package/dist/adapters/astro/middleware-entry.js.map +1 -1
  11. package/dist/adapters/nextjs/index.d.ts +17 -12
  12. package/dist/adapters/nextjs/index.js +1 -1
  13. package/dist/adapters/nextjs/index.js.map +1 -1
  14. package/dist/adapters/nuxt/index.d.ts +11 -6
  15. package/dist/adapters/nuxt/index.js +1 -1
  16. package/dist/adapters/nuxt/index.js.map +1 -1
  17. package/dist/adapters/nuxt/module.d.ts +64 -13
  18. package/dist/adapters/nuxt/module.js +1 -1
  19. package/dist/adapters/nuxt/module.js.map +1 -1
  20. package/dist/adapters/react/index.d.ts +11 -7
  21. package/dist/adapters/react/index.js +1 -1
  22. package/dist/adapters/react/index.js.map +1 -1
  23. package/dist/adapters/sveltekit/index.d.ts +10 -5
  24. package/dist/adapters/sveltekit/index.js +1 -1
  25. package/dist/adapters/sveltekit/index.js.map +1 -1
  26. package/dist/adapters/vue/index.d.ts +10 -7
  27. package/dist/adapters/vue/index.js +1 -1
  28. package/dist/adapters/vue/index.js.map +1 -1
  29. package/dist/annotate.d.ts +15 -2
  30. package/dist/annotate.js.map +1 -1
  31. package/dist/client.cjs +1 -1
  32. package/dist/client.cjs.map +1 -1
  33. package/dist/client.d.cts +367 -266
  34. package/dist/client.d.ts +367 -266
  35. package/dist/client.js +1 -1
  36. package/dist/client.js.map +1 -1
  37. package/dist/codegen-cli.js.map +1 -1
  38. package/dist/codegen.cjs.map +1 -1
  39. package/dist/codegen.d.cts +7 -1
  40. package/dist/codegen.d.ts +7 -1
  41. package/dist/codegen.js.map +1 -1
  42. package/dist/core.cjs +1 -1
  43. package/dist/core.cjs.map +1 -1
  44. package/dist/core.d.cts +544 -392
  45. package/dist/core.d.ts +544 -392
  46. package/dist/core.js +1 -1
  47. package/dist/core.js.map +1 -1
  48. package/dist/doctor-cli.d.ts +1 -1
  49. package/dist/doctor-cli.js +1 -1
  50. package/dist/doctor-cli.js.map +1 -1
  51. package/dist/doctor.d.ts +2 -2
  52. package/dist/doctor.js +1 -1
  53. package/dist/doctor.js.map +1 -1
  54. package/dist/{document-session-BfBfLVpg.d.ts → document-session-DWi9H3Qk.d.ts} +7 -0
  55. package/dist/{fragment-endpoint-DATKU183.d.ts → fragment-endpoint-B2qcRw5T.d.ts} +22 -7
  56. package/dist/fragment.cjs +1 -1
  57. package/dist/fragment.cjs.map +1 -1
  58. package/dist/fragment.d.cts +37 -16
  59. package/dist/fragment.d.ts +37 -16
  60. package/dist/fragment.js +1 -1
  61. package/dist/fragment.js.map +1 -1
  62. package/dist/index.cjs +1 -1
  63. package/dist/index.cjs.map +1 -1
  64. package/dist/index.d.cts +598 -400
  65. package/dist/index.d.ts +598 -400
  66. package/dist/index.js +1 -1
  67. package/dist/index.js.map +1 -1
  68. package/dist/lean.cjs +1 -1
  69. package/dist/lean.cjs.map +1 -1
  70. package/dist/lean.d.cts +5 -2
  71. package/dist/lean.d.ts +5 -2
  72. package/dist/lean.js +1 -1
  73. package/dist/lean.js.map +1 -1
  74. package/dist/lexical.cjs +1 -1
  75. package/dist/lexical.cjs.map +1 -1
  76. package/dist/lexical.d.cts +32 -11
  77. package/dist/lexical.d.ts +32 -11
  78. package/dist/lexical.js +1 -1
  79. package/dist/lexical.js.map +1 -1
  80. package/dist/{locals-CNUGYbA_.d.ts → locals-B1mF3aTb.d.ts} +1 -1
  81. package/dist/{middleware-CWObDO37.d.ts → middleware-BGobLN9P.d.ts} +11 -5
  82. package/dist/migrate.js +1 -1
  83. package/dist/migrate.js.map +1 -1
  84. package/dist/{options-uHKrDM2U.d.ts → options-Cm8fC7dj.d.ts} +31 -1
  85. package/dist/payload.cjs +1 -1
  86. package/dist/payload.cjs.map +1 -1
  87. package/dist/payload.d.cts +18 -2
  88. package/dist/payload.d.ts +18 -2
  89. package/dist/payload.js +1 -1
  90. package/dist/payload.js.map +1 -1
  91. package/dist/plugin.cjs +2 -0
  92. package/dist/plugin.cjs.map +1 -0
  93. package/dist/plugin.d.cts +30 -0
  94. package/dist/plugin.d.ts +30 -0
  95. package/dist/plugin.js +2 -0
  96. package/dist/plugin.js.map +1 -0
  97. package/dist/plugins.cjs +1 -1
  98. package/dist/plugins.cjs.map +1 -1
  99. package/dist/plugins.d.cts +102 -29
  100. package/dist/plugins.d.ts +102 -29
  101. package/dist/plugins.js +1 -1
  102. package/dist/plugins.js.map +1 -1
  103. package/dist/{probe-Bzm4fYFL.d.ts → probe-DGPDsnbj.d.ts} +6 -2
  104. package/dist/server.cjs +1 -1
  105. package/dist/server.cjs.map +1 -1
  106. package/dist/server.d.cts +43 -4
  107. package/dist/server.d.ts +43 -4
  108. package/dist/server.js +1 -1
  109. package/dist/server.js.map +1 -1
  110. package/dist/structural.cjs +2 -2
  111. package/dist/structural.cjs.map +1 -1
  112. package/dist/structural.d.cts +61 -13
  113. package/dist/structural.d.ts +61 -13
  114. package/dist/structural.js +2 -2
  115. package/dist/structural.js.map +1 -1
  116. package/package.json +33 -4
@@ -1 +1 @@
1
- {"version":3,"file":"migrate.js","names":["tsMorph","project","PACKAGE_NAME","loadTsMorph","createRequire","url","error","Error","cause","parseScript","text","kind","morph","Project","useInMemoryFileSystem","skipLoadingLibFiles","skipFileDependencyResolution","compilerOptions","allowJs","noLib","createSourceFile","overwrite","isPackageSpecifier","specifier","startsWith","packageBindings","script","Node","SyntaxKind","out","declaration","getImportDeclarations","getModuleSpecifierValue","spec","getNamedImports","alias","getAliasNode","localNode","getNameNode","push","imported","getName","local","getText","importedNode","aliased","symbol","getSymbol","getDescendantsOfKind","VariableDeclaration","requiredSpecifier","getInitializer","pattern","isObjectBindingPattern","element","getElements","nameNode","isIdentifier","propertyName","getPropertyNameNode","literalName","initializer","call","isAwaitExpression","getExpression","isCallExpression","callee","getKind","ImportKeyword","argument","getArguments","isStringLiteral","getLiteralText","node","isNoSubstitutionTemplateLiteral","propertyKey","property","isSpreadAssignment","isComputedPropertyName","referencesTo","binding","target","compilerSymbol","checker","getProject","getTypeChecker","Identifier","isInside","parent","getParent","isShorthandPropertyAssignment","getShorthandAssignmentValueSymbol","isExportSpecifier","getLocalTargetSymbol","ancestor","getFirstAncestor","candidate","declaresName","name","except","bindsIdentifier","some","skip","isVariableDeclaration","isBindingElement","isFunctionDeclaration","isClassDeclaration","isParameterDeclaration","isEnumDeclaration","isImportSpecifier","isImportClause","getDefaultImport","isNamespaceImport","replaceNode","start","getStart","end","getEnd","applyTextEdits","edits","ordered","sort","left","right","output","floor","Number","POSITIVE_INFINITY","edit","slice","ID","SERVER_SPECIFIER","METHOD","fetchPreviewDocument","fetchPreviewGlobal","SERVER_OPTIONS","Set","DROPPED_OPTIONS","SHARED_READ_OPTIONS","READ_OPTIONS","conflict","line","reason","codemod","rewriteCall","options","server","read","dropped","keys","getProperties","key","add","has","accepted","unplaceable","filter","includes","typeArguments","getTypeArguments","map","generic","length","join","method","droppedNote","getStartLineNumber","notes","importLine","quote","names","moveFetchPreviewHelpers","id","summary","ledgerEntry","apply","bindings","conflicts","blocking","reference","isObjectLiteralExpression","rewritten","serverDeclaration","foreign","declarations","isImportDeclaration","serverImport","find","isTypeOnly","hasDefinePreview","serverLine","getModuleSpecifier","getQuoteKind","defaultImport","clauses","remaining","clause","typeOnly","kept","trailingNewline","getFullText","rewriteImports","plan","CALLEE","OLD_KEY","NEW_KEY","BY_HAND","renameAdminOriginsOption","properties","isPropertyAssignment","BOOLEAN_REFUSED","renameBindingsAuthorizedOption","value","isFalseLiteral","OLD_NAME","NEW_NAME","renameBinding","getParentOrThrow","renameIsPreviewRequest","notice","existing","isPropertyAccessExpression","memberAccesses","WHOLE_FILE","COMPONENT_EXTENSIONS","FRONTMATTER","SCRIPT_TAG","PACKAGE_REFERENCE","importsThisPackage","source","test","IMPLEMENTATIONS","CODEMODS","lineNumberAt","offset","index","lineEdits","before","after","firstLine","oldLines","split","newLines","prefix","suffix","oldMiddle","newMiddle","changed","Math","max","migrateSource","chosen","only","byCodemod","Map","cursor","block","fileName","extension","extname","toLowerCase","blocks","frontmatter","exec","indexOf","match","matchAll","body","trim","lastIndexOf","scriptBlocks","item","next","lines","get","set","count"],"sources":["../src/migrate/ast.ts","../src/migrate/codemods/move-fetch-preview-helpers.ts","../src/migrate/codemods/rename-admin-origins-option.ts","../src/migrate/codemods/rename-bindings-authorized-option.ts","../src/migrate/codemods/rename-is-preview-request.ts","../src/migrate/script-blocks.ts","../src/migrate/index.ts"],"sourcesContent":["/**\n * ts-morph access for the codemods: parsing, the package's bindings in a\n * script and the references those bindings have. ts-morph is loaded on first\n * use so the entry stays importable without the optional peer.\n */\nimport { createRequire } from 'node:module';\nimport type * as TsMorphModule from 'ts-morph';\nimport type {\n Identifier,\n Node,\n ObjectLiteralElementLike,\n Project,\n SourceFile,\n Symbol as TsSymbol,\n} from 'ts-morph';\nimport type { TextEdit } from './types';\n\ntype TsMorph = typeof TsMorphModule;\n\nexport type ScriptKind = 'ts' | 'tsx' | 'js' | 'jsx';\n\nexport const PACKAGE_NAME = 'payload-live-preview';\n\nlet tsMorph: TsMorph | undefined;\nlet project: Project | undefined;\n\nexport function loadTsMorph(): TsMorph {\n if (tsMorph === undefined) {\n try {\n tsMorph = createRequire(import.meta.url)('ts-morph') as TsMorph;\n } catch (error) {\n throw new Error('pll migrate needs ts-morph: npm install --save-dev ts-morph', {\n cause: error,\n });\n }\n }\n return tsMorph;\n}\n\n/** Parse one script into a throwaway in-memory project; the previous script is discarded. */\nexport function parseScript(text: string, kind: ScriptKind): SourceFile {\n const morph = loadTsMorph();\n project ??= new morph.Project({\n useInMemoryFileSystem: true,\n skipLoadingLibFiles: true,\n skipFileDependencyResolution: true,\n compilerOptions: { allowJs: true, noLib: true },\n });\n return project.createSourceFile(`/script.${kind}`, text, { overwrite: true });\n}\n\nexport function isPackageSpecifier(specifier: string): boolean {\n return specifier === PACKAGE_NAME || specifier.startsWith(`${PACKAGE_NAME}/`);\n}\n\n/** A name the script binds from the package, by `import` or by destructuring `require()`/`import()`. */\nexport interface PackageBinding {\n /** The exported name, as the package spells it. */\n readonly imported: string;\n /** The name the script uses; equals `imported` unless aliased. */\n readonly local: string;\n readonly specifier: string;\n readonly kind: 'import' | 'require';\n /** The node spelling the exported name; rewritten when the export is renamed. */\n readonly importedNode: Node;\n readonly aliased: boolean;\n readonly symbol: TsSymbol | undefined;\n /** The import declaration or variable declaration that binds it. */\n readonly declaration: Node;\n}\n\nexport function packageBindings(script: SourceFile): readonly PackageBinding[] {\n const { Node, SyntaxKind } = loadTsMorph();\n const out: PackageBinding[] = [];\n for (const declaration of script.getImportDeclarations()) {\n const specifier = declaration.getModuleSpecifierValue();\n if (!isPackageSpecifier(specifier)) continue;\n for (const spec of declaration.getNamedImports()) {\n const alias = spec.getAliasNode();\n const localNode = alias ?? spec.getNameNode();\n out.push({\n imported: spec.getName(),\n local: localNode.getText(),\n specifier,\n kind: 'import',\n importedNode: spec.getNameNode(),\n aliased: alias !== undefined,\n symbol: localNode.getSymbol(),\n declaration,\n });\n }\n }\n for (const declaration of script.getDescendantsOfKind(SyntaxKind.VariableDeclaration)) {\n const specifier = requiredSpecifier(declaration.getInitializer());\n const pattern = declaration.getNameNode();\n if (specifier === undefined || !isPackageSpecifier(specifier)) continue;\n if (!Node.isObjectBindingPattern(pattern)) continue;\n for (const element of pattern.getElements()) {\n const nameNode = element.getNameNode();\n if (!Node.isIdentifier(nameNode)) continue;\n const propertyName = element.getPropertyNameNode();\n out.push({\n imported: propertyName === undefined ? nameNode.getText() : literalName(propertyName),\n local: nameNode.getText(),\n specifier,\n kind: 'require',\n importedNode: propertyName ?? nameNode,\n aliased: propertyName !== undefined,\n symbol: nameNode.getSymbol(),\n declaration,\n });\n }\n }\n return out;\n}\n\nfunction requiredSpecifier(initializer: Node | undefined): string | undefined {\n const { Node, SyntaxKind } = loadTsMorph();\n const call =\n initializer !== undefined && Node.isAwaitExpression(initializer)\n ? initializer.getExpression()\n : initializer;\n if (call === undefined || !Node.isCallExpression(call)) return undefined;\n const callee = call.getExpression();\n const isRequire = Node.isIdentifier(callee) && callee.getText() === 'require';\n if (!isRequire && callee.getKind() !== SyntaxKind.ImportKeyword) return undefined;\n const [argument] = call.getArguments();\n return argument !== undefined && Node.isStringLiteral(argument)\n ? argument.getLiteralText()\n : undefined;\n}\n\nfunction literalName(node: Node): string {\n const { Node } = loadTsMorph();\n if (Node.isStringLiteral(node) || Node.isNoSubstitutionTemplateLiteral(node)) {\n return node.getLiteralText();\n }\n return node.getText();\n}\n\n/** The key of an object-literal member, or `undefined` when it is computed. */\nexport function propertyKey(property: ObjectLiteralElementLike): string | undefined {\n const { Node } = loadTsMorph();\n if (Node.isSpreadAssignment(property)) return undefined;\n const nameNode = property.getNameNode();\n if (Node.isComputedPropertyName(nameNode)) return undefined;\n return literalName(nameNode);\n}\n\nexport type ReferenceKind = 'reference' | 'shorthand' | 'export';\n\nexport interface BindingReference {\n readonly node: Identifier;\n /** `shorthand` is `{ name }`, `export` is `export { name }`; both keep the old key visible. */\n readonly kind: ReferenceKind;\n}\n\n/** Every use of the binding outside its own declaration, resolved by symbol so shadowing is respected. */\nexport function referencesTo(\n script: SourceFile,\n binding: PackageBinding,\n): readonly BindingReference[] {\n const { Node, SyntaxKind } = loadTsMorph();\n const target = binding.symbol?.compilerSymbol;\n if (target === undefined) return [];\n const checker = script.getProject().getTypeChecker();\n const out: BindingReference[] = [];\n for (const node of script.getDescendantsOfKind(SyntaxKind.Identifier)) {\n if (node.getText() !== binding.local || isInside(node, binding.declaration)) continue;\n const parent = node.getParent();\n if (Node.isShorthandPropertyAssignment(parent)) {\n if (checker.getShorthandAssignmentValueSymbol(parent)?.compilerSymbol === target) {\n out.push({ node, kind: 'shorthand' });\n }\n continue;\n }\n if (Node.isExportSpecifier(parent)) {\n if (\n parent.getNameNode() === node &&\n parent.getLocalTargetSymbol()?.compilerSymbol === target\n ) {\n out.push({ node, kind: 'export' });\n }\n continue;\n }\n if (node.getSymbol()?.compilerSymbol === target) out.push({ node, kind: 'reference' });\n }\n return out;\n}\n\nfunction isInside(node: Node, ancestor: Node): boolean {\n return node.getFirstAncestor((candidate) => candidate === ancestor) !== undefined;\n}\n\n/** The declaration that binds `name` anywhere in the script, ignoring those in `except`. */\nexport function declaresName(\n script: SourceFile,\n name: string,\n except: readonly Node[] = [],\n): Node | undefined {\n const { SyntaxKind } = loadTsMorph();\n for (const node of script.getDescendantsOfKind(SyntaxKind.Identifier)) {\n if (node.getText() !== name) continue;\n const parent = node.getParent();\n if (!bindsIdentifier(parent, node)) continue;\n if (except.some((skip) => skip === parent || isInside(parent, skip))) continue;\n return parent;\n }\n return undefined;\n}\n\nfunction bindsIdentifier(parent: Node, node: Identifier): boolean {\n const { Node } = loadTsMorph();\n if (\n Node.isVariableDeclaration(parent) ||\n Node.isBindingElement(parent) ||\n Node.isFunctionDeclaration(parent) ||\n Node.isClassDeclaration(parent) ||\n Node.isParameterDeclaration(parent) ||\n Node.isEnumDeclaration(parent)\n ) {\n return parent.getNameNode() === node;\n }\n if (Node.isImportSpecifier(parent)) {\n return (parent.getAliasNode() ?? parent.getNameNode()) === node;\n }\n if (Node.isImportClause(parent)) return parent.getDefaultImport() === node;\n if (Node.isNamespaceImport(parent)) return parent.getNameNode() === node;\n return false;\n}\n\n/** Identifiers spelled `name` that are member names (`x.name`), never the package's binding. */\nexport function memberAccesses(script: SourceFile, name: string): readonly Identifier[] {\n const { Node, SyntaxKind } = loadTsMorph();\n return script.getDescendantsOfKind(SyntaxKind.Identifier).filter((node) => {\n const parent = node.getParent();\n return (\n node.getText() === name &&\n Node.isPropertyAccessExpression(parent) &&\n parent.getNameNode() === node\n );\n });\n}\n\nexport function replaceNode(node: Node, text: string): TextEdit {\n return { start: node.getStart(), end: node.getEnd(), text };\n}\n\n/** Splice non-overlapping edits into `text`. */\nexport function applyTextEdits(text: string, edits: readonly TextEdit[]): string {\n const ordered = [...edits].sort((left, right) => right.start - left.start);\n let output = text;\n let floor = Number.POSITIVE_INFINITY;\n for (const edit of ordered) {\n if (edit.end > floor) throw new Error('overlapping codemod edits');\n output = `${output.slice(0, edit.start)}${edit.text}${output.slice(edit.end)}`;\n floor = edit.start;\n }\n return output;\n}\n","/**\n * Ledger entry 9: `fetchPreviewDocument()`/`fetchPreviewGlobal()` on the root\n * entry → `definePreview({ serverURL, depth }).fetchDocument()`/`.fetchGlobal()`\n * on `payload-live-preview/server`.\n */\nimport {\n PACKAGE_NAME,\n declaresName,\n loadTsMorph,\n packageBindings,\n propertyKey,\n referencesTo,\n type PackageBinding,\n} from '../ast';\nimport type { CodemodImplementation, CodemodConflict, CodemodPlan, TextEdit } from '../types';\nimport type {\n CallExpression,\n ImportDeclaration,\n ObjectLiteralExpression,\n SourceFile,\n} from 'ts-morph';\n\nconst ID = 'move-fetch-preview-helpers';\nconst SERVER_SPECIFIER = `${PACKAGE_NAME}/server`;\nconst METHOD: Readonly<Record<string, string>> = {\n fetchPreviewDocument: 'fetchDocument',\n fetchPreviewGlobal: 'fetchGlobal',\n};\nconst SERVER_OPTIONS = new Set(['serverURL', 'apiRoute', 'depth']);\nconst DROPPED_OPTIONS = new Set(['draft', 'fetchFn']);\n/**\n * What `ReadDocumentOptions`/`ReadGlobalOptions` accept (src/server/preview.ts).\n * 1.x spelled the target `collection` and `global` too, so there is no rename to\n * make here — a key that is in neither set is one this codemod cannot place, and\n * passing it through unannounced produces a file that does not compile.\n */\nconst SHARED_READ_OPTIONS = ['authorization', 'locale', 'headers', 'signal', 'errorMode'];\nconst READ_OPTIONS: Readonly<Record<string, readonly string[]>> = {\n fetchPreviewDocument: ['collection', 'where', ...SHARED_READ_OPTIONS],\n fetchPreviewGlobal: ['global', ...SHARED_READ_OPTIONS],\n};\nconst DEPTH_TODO =\n 'depth: 1 /* TODO(pll migrate): the 1.x default; match the runtime mergeDepth */';\nconst AUTHORIZATION_TODO =\n 'authorization: null /* TODO(pll migrate): pass the verdict from authorizePreviewRequest(); ' +\n 'null reads the published document */';\n\nfunction conflict(line: number, reason: string): CodemodConflict {\n return { codemod: ID, reason, line };\n}\n\ninterface RewrittenCall {\n readonly edit: TextEdit;\n readonly notes: readonly CodemodConflict[];\n}\n\nfunction rewriteCall(\n call: CallExpression,\n options: ObjectLiteralExpression,\n imported: string,\n): RewrittenCall {\n const server: string[] = [];\n const read: string[] = [];\n const dropped: string[] = [];\n const keys = new Set<string>();\n for (const property of options.getProperties()) {\n const key = propertyKey(property);\n if (key !== undefined) keys.add(key);\n if (key !== undefined && SERVER_OPTIONS.has(key)) server.push(property.getText());\n else if (key !== undefined && DROPPED_OPTIONS.has(key)) dropped.push(key);\n else read.push(property.getText());\n }\n if (!keys.has('depth')) server.push(DEPTH_TODO);\n if (!keys.has('authorization')) read.push(AUTHORIZATION_TODO);\n const accepted = READ_OPTIONS[imported] ?? [];\n const unplaceable = [...keys].filter(\n (key) => !SERVER_OPTIONS.has(key) && !DROPPED_OPTIONS.has(key) && !accepted.includes(key),\n );\n const typeArguments = call.getTypeArguments().map((argument) => argument.getText());\n const generic = typeArguments.length === 0 ? '' : `<${typeArguments.join(', ')}>`;\n const method = METHOD[imported] ?? imported;\n const text = `definePreview({ ${server.join(', ')} }).${method}${generic}({ ${read.join(', ')} })`;\n const droppedNote = dropped.length === 0 ? '' : `, and ${dropped.join('/')} was dropped`;\n const line = call.getStartLineNumber();\n const notes = [\n conflict(\n line,\n `${imported}() was rewritten onto definePreview().${method}(); it now returns a ` +\n `PreviewFetchResult (check ok/data) and needs a real authorization for drafts${droppedNote}`,\n ),\n ];\n if (unplaceable.length > 0) {\n notes.push(\n conflict(\n line,\n `${imported}() was passed ${unplaceable.map((key) => `\\`${key}\\``).join(', ')}, which ` +\n `.${method}() does not accept; it takes ${accepted.join(', ')}. The key was carried ` +\n 'over unchanged and will not compile — place it by hand',\n ),\n );\n }\n return { edit: { start: call.getStart(), end: call.getEnd(), text }, notes };\n}\n\nfunction importLine(quote: string, names: readonly string[], specifier: string): string {\n return `import { ${names.join(', ')} } from ${quote}${specifier}${quote};`;\n}\n\n/** Drop the moved names from their root imports and make sure `definePreview` is imported from the server entry. */\nfunction rewriteImports(script: SourceFile, bindings: readonly PackageBinding[]): TextEdit[] {\n const { Node } = loadTsMorph();\n const edits: TextEdit[] = [];\n const declarations = new Set<ImportDeclaration>();\n for (const binding of bindings) {\n if (Node.isImportDeclaration(binding.declaration)) declarations.add(binding.declaration);\n }\n const serverImport = script\n .getImportDeclarations()\n .find(\n (declaration) =>\n declaration.getModuleSpecifierValue() === SERVER_SPECIFIER && !declaration.isTypeOnly(),\n );\n const hasDefinePreview =\n serverImport?.getNamedImports().some((spec) => spec.getName() === 'definePreview') === true;\n let serverLine: string | undefined;\n if (serverImport !== undefined && !hasDefinePreview) {\n const quote = serverImport.getModuleSpecifier().getQuoteKind();\n const names = [\n ...serverImport.getNamedImports().map((spec) => spec.getText()),\n 'definePreview',\n ];\n const defaultImport = serverImport.getDefaultImport()?.getText();\n const clauses =\n defaultImport === undefined ? names.join(', ') : `${defaultImport}, { ${names.join(', ')} }`;\n const text =\n defaultImport === undefined\n ? importLine(quote, names, SERVER_SPECIFIER)\n : `import ${clauses} from ${quote}${SERVER_SPECIFIER}${quote};`;\n edits.push({ start: serverImport.getStart(), end: serverImport.getEnd(), text });\n }\n for (const declaration of declarations) {\n const quote = declaration.getModuleSpecifier().getQuoteKind();\n const remaining = declaration\n .getNamedImports()\n .filter((spec) => !(spec.getName() in METHOD))\n .map((spec) => spec.getText());\n const defaultImport = declaration.getDefaultImport()?.getText();\n const clauses = [\n defaultImport,\n remaining.length === 0 ? undefined : `{ ${remaining.join(', ')} }`,\n ].filter((clause): clause is string => clause !== undefined);\n const typeOnly = declaration.isTypeOnly() ? 'type ' : '';\n const kept =\n clauses.length === 0\n ? ''\n : `import ${typeOnly}${clauses.join(', ')} from ${quote}${PACKAGE_NAME}${quote};`;\n if (serverImport === undefined && serverLine === undefined) {\n serverLine = importLine(quote, ['definePreview'], SERVER_SPECIFIER);\n edits.push({\n start: declaration.getStart(),\n end: declaration.getEnd(),\n text: kept === '' ? serverLine : `${kept}\\n${serverLine}`,\n });\n } else {\n // A removed declaration takes its line break with it.\n const end = declaration.getEnd();\n const trailingNewline = kept === '' && script.getFullText()[end] === '\\n' ? 1 : 0;\n edits.push({ start: declaration.getStart(), end: end + trailingNewline, text: kept });\n }\n }\n return edits;\n}\n\nfunction plan(script: SourceFile, bindings: readonly PackageBinding[]): CodemodPlan {\n const { Node } = loadTsMorph();\n const blocking: CodemodConflict[] = [];\n const notes: CodemodConflict[] = [];\n const edits: TextEdit[] = [];\n for (const binding of bindings) {\n if (binding.kind === 'require') {\n blocking.push(\n conflict(\n binding.declaration.getStartLineNumber(),\n `${binding.imported} is bound with require(); rewrite it onto definePreview() from ` +\n `${SERVER_SPECIFIER} by hand`,\n ),\n );\n continue;\n }\n for (const reference of referencesTo(script, binding)) {\n const line = reference.node.getStartLineNumber();\n const call = reference.node.getParent();\n const isCall =\n reference.kind === 'reference' &&\n Node.isCallExpression(call) &&\n call.getExpression() === reference.node;\n if (!isCall) {\n blocking.push(\n conflict(\n line,\n `${binding.local} is used other than as a direct call; rewrite it onto definePreview() by hand`,\n ),\n );\n continue;\n }\n const [options] = call.getArguments();\n if (\n options === undefined ||\n !Node.isObjectLiteralExpression(options) ||\n options.getProperties().some((property) => Node.isSpreadAssignment(property))\n ) {\n blocking.push(\n conflict(\n line,\n `${binding.imported}() options are not a plain object literal, so serverURL/depth ` +\n 'cannot be split out; rewrite it onto definePreview() by hand',\n ),\n );\n continue;\n }\n const rewritten = rewriteCall(call, options, binding.imported);\n edits.push(rewritten.edit);\n notes.push(...rewritten.notes);\n }\n }\n const serverDeclaration = script\n .getImportDeclarations()\n .filter((declaration) => declaration.getModuleSpecifierValue() === SERVER_SPECIFIER);\n const foreign = declaresName(script, 'definePreview', serverDeclaration);\n if (foreign !== undefined) {\n blocking.push(\n conflict(\n foreign.getStartLineNumber(),\n `this module already binds a definePreview that is not ${SERVER_SPECIFIER}'s; rename it, ` +\n 'then move the fetch helpers by hand',\n ),\n );\n }\n if (blocking.length > 0) return { edits: [], conflicts: [...blocking, ...notes] };\n edits.push(...rewriteImports(script, bindings));\n return { edits, conflicts: notes };\n}\n\nexport const moveFetchPreviewHelpers: CodemodImplementation = {\n id: ID,\n summary:\n '`fetchPreviewDocument`/`fetchPreviewGlobal` from the root → `definePreview().fetchDocument`/`.fetchGlobal` (payload-live-preview/server)',\n ledgerEntry: 9,\n apply(script) {\n const bindings = packageBindings(script).filter(\n (binding) => binding.specifier === PACKAGE_NAME && binding.imported in METHOD,\n );\n if (bindings.length === 0) return { edits: [], conflicts: [] };\n return plan(script, bindings);\n },\n};\n","/** Ledger entry 13: `hasPreviewIntent(request, { adminOrigins })` → `{ allowedOrigins }`. */\nimport { loadTsMorph, packageBindings, propertyKey, referencesTo, replaceNode } from '../ast';\nimport type { CodemodImplementation, CodemodConflict, TextEdit } from '../types';\n\nconst ID = 'rename-admin-origins-option';\nconst CALLEE = 'hasPreviewIntent';\nconst OLD_KEY = 'adminOrigins';\nconst NEW_KEY = 'allowedOrigins';\nconst BY_HAND = `if they carry \\`${OLD_KEY}\\`, rename it to \\`${NEW_KEY}\\``;\n\nexport const renameAdminOriginsOption: CodemodImplementation = {\n id: ID,\n summary: '`hasPreviewIntent(request, { adminOrigins })` → `{ allowedOrigins }`',\n ledgerEntry: 13,\n apply(script) {\n const { Node } = loadTsMorph();\n const edits: TextEdit[] = [];\n const conflicts: CodemodConflict[] = [];\n const bindings = packageBindings(script).filter((binding) => binding.imported === CALLEE);\n for (const binding of bindings) {\n for (const reference of referencesTo(script, binding)) {\n const call = reference.node.getParent();\n if (reference.kind !== 'reference' || !Node.isCallExpression(call)) continue;\n if (call.getExpression() !== reference.node) continue;\n const options = call.getArguments()[1];\n if (options === undefined) continue;\n const line = options.getStartLineNumber();\n if (!Node.isObjectLiteralExpression(options)) {\n conflicts.push({\n codemod: ID,\n line,\n reason: `${CALLEE}() options are not a literal; ${BY_HAND}`,\n });\n continue;\n }\n const properties = options.getProperties();\n const keys = properties.map((property) => propertyKey(property));\n // With both names the package reads `allowedOrigins` and ignores the\n // alias; renamed, the later key would win instead.\n if (keys.includes(OLD_KEY) && keys.includes(NEW_KEY)) {\n conflicts.push({\n codemod: ID,\n line,\n reason: `${CALLEE}() is given both ${OLD_KEY} and ${NEW_KEY}; ${NEW_KEY} wins, drop ${OLD_KEY} by hand`,\n });\n continue;\n }\n for (const property of properties) {\n if (Node.isSpreadAssignment(property)) {\n conflicts.push({\n codemod: ID,\n line: property.getStartLineNumber(),\n reason: `${CALLEE}() spreads its options; ${BY_HAND}`,\n });\n } else if (propertyKey(property) !== OLD_KEY) {\n continue;\n } else if (Node.isShorthandPropertyAssignment(property)) {\n edits.push(replaceNode(property, `${NEW_KEY}: ${OLD_KEY}`));\n } else if (Node.isPropertyAssignment(property)) {\n edits.push(replaceNode(property.getNameNode(), NEW_KEY));\n }\n }\n }\n }\n return { edits, conflicts };\n },\n};\n","/** Ledger entry 7: `createPreviewBindings({ authorized })` → `{ authorization }`. */\nimport { loadTsMorph, packageBindings, propertyKey, referencesTo, replaceNode } from '../ast';\nimport type { CodemodImplementation, CodemodConflict, TextEdit } from '../types';\n\nconst ID = 'rename-bindings-authorized-option';\nconst OLD_KEY = 'authorized';\nconst NEW_KEY = 'authorization';\nconst BY_HAND =\n `if they carry \\`${OLD_KEY}\\`, rename it to \\`${NEW_KEY}\\` and pass the verdict from ` +\n 'authorizePreviewRequest()';\n/**\n * `false` has an exact equivalent — an unauthorized response suppresses every\n * binding, which is what `null` means — so it is rewritten. Nothing else does:\n * only a real context from `authorizePreviewRequest()` authorizes emission, and\n * a boolean left under the new name does not compile (TS2322).\n */\nconst BOOLEAN_REFUSED =\n `\\`${NEW_KEY}\\` takes the context from authorizePreviewRequest(); the boolean 1.x ` +\n 'accepted is not. The key was renamed and its value left as it stands — pass the ' +\n 'verdict, or `null` for a public response';\n\nexport const renameBindingsAuthorizedOption: CodemodImplementation = {\n id: ID,\n summary: '`createPreviewBindings({ authorized })` → `{ authorization }`',\n ledgerEntry: 7,\n apply(script) {\n const { Node } = loadTsMorph();\n const edits: TextEdit[] = [];\n const conflicts: CodemodConflict[] = [];\n const bindings = packageBindings(script).filter(\n (binding) => binding.imported === 'createPreviewBindings',\n );\n for (const binding of bindings) {\n for (const reference of referencesTo(script, binding)) {\n const call = reference.node.getParent();\n if (reference.kind !== 'reference' || !Node.isCallExpression(call)) continue;\n if (call.getExpression() !== reference.node) continue;\n const [options] = call.getArguments();\n if (options === undefined) continue;\n const line = options.getStartLineNumber();\n if (!Node.isObjectLiteralExpression(options)) {\n conflicts.push({\n codemod: ID,\n line,\n reason: `createPreviewBindings() options are not a literal; ${BY_HAND}`,\n });\n continue;\n }\n for (const property of options.getProperties()) {\n if (Node.isSpreadAssignment(property)) {\n conflicts.push({\n codemod: ID,\n line: property.getStartLineNumber(),\n reason: `createPreviewBindings() spreads its options; ${BY_HAND}`,\n });\n } else if (propertyKey(property) !== OLD_KEY) {\n continue;\n } else if (Node.isShorthandPropertyAssignment(property)) {\n edits.push(replaceNode(property, `${NEW_KEY}: ${OLD_KEY}`));\n conflicts.push({\n codemod: ID,\n line: property.getStartLineNumber(),\n reason: BOOLEAN_REFUSED,\n });\n } else if (Node.isPropertyAssignment(property)) {\n const value = property.getInitializer();\n if (value !== undefined && Node.isFalseLiteral(value)) {\n edits.push(replaceNode(property, `${NEW_KEY}: null`));\n continue;\n }\n edits.push(replaceNode(property.getNameNode(), NEW_KEY));\n conflicts.push({\n codemod: ID,\n line: property.getStartLineNumber(),\n reason: BOOLEAN_REFUSED,\n });\n }\n }\n }\n }\n return { edits, conflicts };\n },\n};\n","/** Ledger entry 1: `isPreviewRequest()` → `hasPreviewIntent()`, same signature. */\nimport {\n declaresName,\n memberAccesses,\n packageBindings,\n referencesTo,\n replaceNode,\n type PackageBinding,\n} from '../ast';\nimport type { CodemodImplementation, CodemodConflict, CodemodPlan, TextEdit } from '../types';\n\nconst ID = 'rename-is-preview-request';\nconst OLD_NAME = 'isPreviewRequest';\nconst NEW_NAME = 'hasPreviewIntent';\n\nfunction conflict(line: number, reason: string): CodemodConflict {\n return { codemod: ID, reason, line };\n}\n\nfunction renameBinding(binding: PackageBinding): TextEdit {\n // `import { isPreviewRequest as hasPreviewIntent }` collapses to the bare name.\n if (binding.aliased && binding.local === NEW_NAME) {\n return replaceNode(binding.importedNode.getParentOrThrow(), NEW_NAME);\n }\n return replaceNode(binding.importedNode, NEW_NAME);\n}\n\nfunction plan(\n bindings: readonly PackageBinding[],\n script: Parameters<CodemodImplementation['apply']>[0],\n): CodemodPlan {\n const blocking: CodemodConflict[] = [];\n const edits: TextEdit[] = [];\n const existing = declaresName(\n script,\n NEW_NAME,\n bindings.map((binding) => binding.declaration),\n );\n if (existing !== undefined) {\n blocking.push(\n conflict(\n existing.getStartLineNumber(),\n `this module already binds ${NEW_NAME}; rename it (or drop the wrapper and import the ` +\n `package's ${NEW_NAME} directly), then rename ${OLD_NAME} by hand`,\n ),\n );\n }\n for (const binding of bindings) {\n edits.push(renameBinding(binding));\n if (binding.aliased) continue;\n for (const reference of referencesTo(script, binding)) {\n if (reference.kind === 'reference') {\n edits.push(replaceNode(reference.node, NEW_NAME));\n } else if (reference.kind === 'shorthand') {\n blocking.push(\n conflict(\n reference.node.getStartLineNumber(),\n `{ ${OLD_NAME} } keeps the old key for whoever reads it; write ` +\n `{ ${OLD_NAME}: ${NEW_NAME} } or rename the key and its readers by hand`,\n ),\n );\n } else {\n blocking.push(\n conflict(\n reference.node.getStartLineNumber(),\n `${OLD_NAME} is re-exported under its old name; rename the export and its ` +\n `importers, or write export { ${NEW_NAME} as ${OLD_NAME} }`,\n ),\n );\n }\n }\n }\n const notes = memberAccesses(script, OLD_NAME).map((node) =>\n conflict(\n node.getStartLineNumber(),\n `.${OLD_NAME} is a member of this module's own object, not the package import, and was ` +\n 'left alone; check that it does not wrap the removed API',\n ),\n );\n if (blocking.length > 0) return { edits: [], conflicts: [...blocking, ...notes] };\n return { edits, conflicts: notes };\n}\n\nexport const renameIsPreviewRequest: CodemodImplementation = {\n id: ID,\n summary: '`isPreviewRequest()` → `hasPreviewIntent()` (same signature)',\n ledgerEntry: 1,\n // The rename keeps behaviour, and that is the part worth saying: the 2.0\n // adapters count only the query, and a renamed call silently does not.\n notice:\n 'hasPreviewIntent() takes the options isPreviewRequest() took and, without `signals`, counts ' +\n 'the same three: a preview query parameter, Sec-Fetch-Dest: iframe and an admin Referer. The ' +\n \"2.0 adapters count only the query; where a call should agree with them, pass { signals: ['query'] } \" +\n '(docs/migration.md).',\n apply(script) {\n const bindings = packageBindings(script).filter((binding) => binding.imported === OLD_NAME);\n if (bindings.length === 0) return { edits: [], conflicts: [] };\n return plan(bindings, script);\n },\n};\n","/** Where the script lives in a file: the whole file, or the script blocks of a component. */\nimport { extname } from 'node:path';\nimport type { ScriptKind } from './ast';\n\nexport interface ScriptBlock {\n readonly start: number;\n readonly end: number;\n readonly kind: ScriptKind;\n}\n\nconst WHOLE_FILE: Readonly<Record<string, ScriptKind>> = {\n '.ts': 'ts',\n '.mts': 'ts',\n '.cts': 'ts',\n '.tsx': 'tsx',\n '.js': 'js',\n '.mjs': 'js',\n '.cjs': 'js',\n '.jsx': 'jsx',\n};\nconst COMPONENT_EXTENSIONS = new Set(['.astro', '.vue', '.svelte']);\nconst FRONTMATTER = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---/u;\n// Browsers close a script on `</script` followed by anything up to `>`, so the\n// end tag must accept that too, or a stray `</script foo>` would swallow the\n// rest of the file into one block.\nconst SCRIPT_TAG = /<script(?:\\s[^>]*)?>([\\s\\S]*?)<\\/script\\b[^>]*>/giu;\n\nexport function scriptBlocks(source: string, fileName: string): readonly ScriptBlock[] {\n const extension = extname(fileName).toLowerCase();\n if (!COMPONENT_EXTENSIONS.has(extension)) {\n return [{ start: 0, end: source.length, kind: WHOLE_FILE[extension] ?? 'ts' }];\n }\n const blocks: ScriptBlock[] = [];\n const frontmatter = extension === '.astro' ? FRONTMATTER.exec(source) : null;\n if (frontmatter?.[1] !== undefined) {\n const start = frontmatter.index + frontmatter[0].indexOf('\\n') + 1;\n blocks.push({ start, end: start + frontmatter[1].length, kind: 'ts' });\n }\n for (const match of source.matchAll(SCRIPT_TAG)) {\n const body = match[1] ?? '';\n if (body.trim() === '') continue;\n const start = match.index + match[0].lastIndexOf(body);\n blocks.push({ start, end: start + body.length, kind: 'ts' });\n }\n return blocks;\n}\n","/**\n * `pll migrate`: the 1.x → 2.0 codemods and the driver that applies them to one\n * source string. Rewrites are planned on the AST (ts-morph) so only names the\n * package binds are touched; see ADR 0007.\n */\nimport { applyTextEdits, parseScript } from './ast';\nimport { moveFetchPreviewHelpers } from './codemods/move-fetch-preview-helpers';\nimport { renameAdminOriginsOption } from './codemods/rename-admin-origins-option';\nimport { renameBindingsAuthorizedOption } from './codemods/rename-bindings-authorized-option';\nimport { renameIsPreviewRequest } from './codemods/rename-is-preview-request';\nimport { scriptBlocks } from './script-blocks';\nimport type {\n Codemod,\n CodemodConflict,\n CodemodEdit,\n CodemodImplementation,\n CodemodLineEdit,\n} from './types';\n\nexport type {\n Codemod,\n CodemodConflict,\n CodemodEdit,\n CodemodLineEdit,\n CodemodPlan,\n TextEdit,\n} from './types';\n\nconst PACKAGE_REFERENCE =\n /(?:\\bfrom\\s*|\\bimport\\s*\\(?\\s*|\\brequire\\s*\\(\\s*)['\"]payload-live-preview(?:\\/[^'\"]*)?['\"]/u;\n\n/** Whether the source names the package in an `import`, `import()` or `require()`. @internal */\nexport function importsThisPackage(source: string): boolean {\n return PACKAGE_REFERENCE.test(source);\n}\n\n// The option rename follows the function rename so it sees the new binding.\nconst IMPLEMENTATIONS: readonly CodemodImplementation[] = [\n renameIsPreviewRequest,\n renameAdminOriginsOption,\n renameBindingsAuthorizedOption,\n moveFetchPreviewHelpers,\n];\n\n/**\n * The codemods in the order they run. Each is idempotent. Metadata only: the\n * rewrite is internal, so importing this entry's types does not require\n * `ts-morph`, which is needed only to run `pll migrate`.\n * @internal\n */\nexport const CODEMODS: readonly Codemod[] = IMPLEMENTATIONS;\n\nexport interface MigrateSourceOptions {\n /** Restrict to these codemod ids. */\n readonly only?: readonly string[];\n /**\n * Decides how the source is parsed: `.astro`, `.vue` and `.svelte` by script\n * block, JSX by extension. Defaults to a `.ts` module.\n */\n readonly fileName?: string;\n}\n\nexport interface MigrateSourceResult {\n readonly output: string;\n readonly edits: readonly CodemodEdit[];\n readonly conflicts: readonly CodemodConflict[];\n}\n\nfunction lineNumberAt(source: string, offset: number): number {\n let line = 1;\n for (let index = 0; index < offset; index += 1) if (source[index] === '\\n') line += 1;\n return line;\n}\n\n/** The changed lines between two versions, trimmed to the differing middle. */\nfunction lineEdits(before: string, after: string, firstLine: number): CodemodLineEdit[] {\n const oldLines = before.split('\\n');\n const newLines = after.split('\\n');\n let prefix = 0;\n while (\n prefix < oldLines.length &&\n prefix < newLines.length &&\n oldLines[prefix] === newLines[prefix]\n ) {\n prefix += 1;\n }\n let suffix = 0;\n while (\n suffix < oldLines.length - prefix &&\n suffix < newLines.length - prefix &&\n oldLines[oldLines.length - 1 - suffix] === newLines[newLines.length - 1 - suffix]\n ) {\n suffix += 1;\n }\n const oldMiddle = oldLines.slice(prefix, oldLines.length - suffix);\n const newMiddle = newLines.slice(prefix, newLines.length - suffix);\n const changed: CodemodLineEdit[] = [];\n for (let index = 0; index < Math.max(oldMiddle.length, newMiddle.length); index += 1) {\n const before = oldMiddle[index] ?? '';\n const after = newMiddle[index] ?? '';\n if (before !== after) changed.push({ line: firstLine + prefix + index, before, after });\n }\n return changed;\n}\n\n/** Apply every codemod (or the chosen subset) to one source string. */\nexport function migrateSource(\n source: string,\n options: MigrateSourceOptions = {},\n): MigrateSourceResult {\n const chosen =\n options.only === undefined\n ? IMPLEMENTATIONS\n : IMPLEMENTATIONS.filter((codemod) => options.only?.includes(codemod.id));\n if (chosen.length === 0 || !importsThisPackage(source)) {\n return { output: source, edits: [], conflicts: [] };\n }\n const byCodemod = new Map<string, CodemodLineEdit[]>();\n const conflicts: CodemodConflict[] = [];\n let output = '';\n let cursor = 0;\n for (const block of scriptBlocks(source, options.fileName ?? 'source.ts')) {\n output += source.slice(cursor, block.start);\n const firstLine = lineNumberAt(source, block.start);\n let text = source.slice(block.start, block.end);\n for (const codemod of chosen) {\n const plan = codemod.apply(parseScript(text, block.kind));\n for (const item of plan.conflicts) {\n conflicts.push(\n item.line === undefined ? item : { ...item, line: item.line + firstLine - 1 },\n );\n }\n if (plan.edits.length === 0) continue;\n const next = applyTextEdits(text, plan.edits);\n const lines = byCodemod.get(codemod.id) ?? [];\n lines.push(...lineEdits(text, next, firstLine));\n byCodemod.set(codemod.id, lines);\n text = next;\n }\n output += text;\n cursor = block.end;\n }\n output += source.slice(cursor);\n const edits = [...byCodemod].map(([codemod, lines]) => ({ codemod, count: lines.length, lines }));\n return { output, edits, conflicts };\n}\n"],"mappings":"sEAqBO,IAEHA,EACAC,EAHSC,EAAe,uBAKrB,SAASC,IACd,QAAgB,IAAZH,EACF,IACEA,EAAUI,cAA0BC,IAA1BD,CAA+B,WAC3C,OAASE,GACP,MAAM,IAAIC,MAAM,8DAA+D,CAC7EC,MAAOF,GAEX,CAEF,OAAON,CACT,CAGO,SAASS,EAAYC,EAAcC,GACxC,MAAMC,EAAQT,IAOd,OANAF,IAAY,IAAIW,EAAMC,QAAQ,CAC5BC,uBAAuB,EACvBC,qBAAqB,EACrBC,8BAA8B,EAC9BC,gBAAiB,CAAEC,SAAS,EAAMC,OAAO,KAEpClB,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C,OAAc,SAC7B,MAAM8G,EAAO1J,EAAe5G,EAAMgM,EAAKnF,OACjC0J,EAAQpB,EAAUqB,IAAInI,EAAQ6B,KAAO,GAC3CqG,EAAM1O,QAAQqM,GAAUlO,EAAMsQ,EAAMjC,IACpCc,EAAUsB,IAAIpI,EAAQ6B,GAAIqG,GAC1BvQ,EAAOsQ,CACT,CACApJ,GAAUlH,EACVqP,EAASC,EAAM5I,GACjB,CAGA,OAFAQ,GAAUyG,EAAOpG,MAAM8H,GAEhB,CAAEnI,SAAQL,MADH,IAAIsI,GAAW7F,IAAI,EAAEjB,EAASkI,MAAK,CAASlI,UAASqI,MAAOH,EAAM/G,OAAQ+G,WAChEhG,YAC1B,Q","ignoreList":[]}
1
+ {"version":3,"file":"migrate.js","names":["tsMorph","project","PACKAGE_NAME","loadTsMorph","createRequire","url","error","Error","cause","parseScript","text","kind","morph","Project","useInMemoryFileSystem","skipLoadingLibFiles","skipFileDependencyResolution","compilerOptions","allowJs","noLib","createSourceFile","overwrite","isPackageSpecifier","specifier","startsWith","packageReexports","script","out","declaration","getExportDeclarations","getModuleSpecifierValue","spec","getNamedExports","push","imported","getName","importedNode","getNameNode","alias","getAliasNode","getText","line","getStartLineNumber","packageBindings","Node","SyntaxKind","getImportDeclarations","getNamedImports","localNode","local","aliased","symbol","getSymbol","getDescendantsOfKind","VariableDeclaration","requiredSpecifier","getInitializer","pattern","isObjectBindingPattern","element","getElements","nameNode","isIdentifier","propertyName","getPropertyNameNode","literalName","initializer","call","isAwaitExpression","getExpression","isCallExpression","callee","getKind","ImportKeyword","argument","getArguments","isStringLiteral","getLiteralText","node","isNoSubstitutionTemplateLiteral","propertyKey","property","isSpreadAssignment","isComputedPropertyName","referencesTo","binding","target","compilerSymbol","checker","getProject","getTypeChecker","Identifier","isInside","parent","getParent","isShorthandPropertyAssignment","getShorthandAssignmentValueSymbol","isExportSpecifier","getLocalTargetSymbol","ancestor","getFirstAncestor","candidate","declaresName","name","except","bindsIdentifier","some","skip","isVariableDeclaration","isBindingElement","isFunctionDeclaration","isClassDeclaration","isParameterDeclaration","isEnumDeclaration","isImportSpecifier","isImportClause","getDefaultImport","isNamespaceImport","replaceNode","start","getStart","end","getEnd","applyTextEdits","edits","ordered","sort","left","right","output","floor","Number","POSITIVE_INFINITY","edit","slice","ADAPTER_ENTRIES","Set","map","entry","optionLiterals","found","Map","record","literal","use","uses","get","known","outer","at","set","visit","getProperties","forEach","shared","constLiteral","has","reference","isNewExpression","inner","unwrap","isObjectLiteralExpression","packageJsxAttributes","tags","JsxAttribute","filter","attribute","isJsxOpeningElement","isJsxSelfClosingElement","getTagNameNode","memberNamed","key","find","VariableDeclarationKind","getDeclarations","getVariableStatement","getDeclarationKind","Const","current","isParenthesizedExpression","isAsExpression","isSatisfiesExpression","isTypeAssertion","ID","KEY","RUNTIME_ROWS","q","ROWS","adapter","join","runtime","ROW_KEYS","BY_HAND","expandDefaultsV1","id","summary","ledgerEntry","notice","apply","conflicts","conflict","reason","codemod","value","isPropertyAssignment","refusal","refuse","expansion","charAt","size","properties","index","findIndex","member","overridden","quote","present","composed","part","opaque","rows","source","getSourceFile","getFullText","length","next","lineStart","lastIndexOf","lead","separator","test","SERVER_SPECIFIER","METHOD","fetchPreviewDocument","fetchPreviewGlobal","SERVER_OPTIONS","DROPPED_OPTIONS","SHARED_READ_OPTIONS","READ_OPTIONS","rewriteCall","options","server","read","dropped","keys","add","accepted","unplaceable","includes","typeArguments","getTypeArguments","generic","method","droppedNote","done","advice","importLine","names","moveFetchPreviewHelpers","bindings","reexports","reexport","blocking","notes","rewritten","serverDeclaration","foreign","declarations","isImportDeclaration","serverImport","isTypeOnly","hasDefinePreview","serverLine","getModuleSpecifier","getQuoteKind","defaultImport","clauses","remaining","clause","typeOnly","kept","trailingNewline","rewriteImports","plan","CALLEE","OLD_KEY","NEW_KEY","renameAdminOriginsOption","BOOLEAN_REFUSED","renameBindingsAuthorizedOption","isFalseLiteral","OLD_NAME","NEW_NAME","renameBinding","getParentOrThrow","renameIsPreviewRequest","existing","isPropertyAccessExpression","memberAccesses","RENAMED","route","ignore","renameOnUnboundChange","renamed","WHOLE_FILE","COMPONENT_EXTENSIONS","FRONTMATTER","SCRIPT_TAG","PACKAGE_REFERENCE","importsThisPackage","IMPLEMENTATIONS","CODEMODS","lineNumberAt","offset","lineEdits","before","after","firstLine","oldLines","split","newLines","prefix","suffix","oldMiddle","newMiddle","changed","Math","max","migrateSource","chosen","only","byCodemod","cursor","block","fileName","extension","extname","toLowerCase","blocks","frontmatter","exec","indexOf","match","matchAll","body","trim","scriptBlocks","item","lines","count"],"sources":["../src/migrate/ast.ts","../src/migrate/option-literals.ts","../src/migrate/codemods/expand-defaults-v1.ts","../src/migrate/codemods/move-fetch-preview-helpers.ts","../src/migrate/codemods/rename-admin-origins-option.ts","../src/migrate/codemods/rename-bindings-authorized-option.ts","../src/migrate/codemods/rename-is-preview-request.ts","../src/migrate/codemods/rename-on-unbound-change.ts","../src/migrate/script-blocks.ts","../src/migrate/index.ts"],"sourcesContent":["/**\n * ts-morph access for the codemods: parsing, the package's bindings in a\n * script and the references those bindings have. ts-morph is loaded on first\n * use so the entry stays importable without the optional peer.\n */\nimport { createRequire } from 'node:module';\nimport type * as TsMorphModule from 'ts-morph';\nimport type {\n Identifier,\n Node,\n ObjectLiteralElementLike,\n Project,\n SourceFile,\n Symbol as TsSymbol,\n} from 'ts-morph';\nimport type { TextEdit } from './types';\n\ntype TsMorph = typeof TsMorphModule;\n\nexport type ScriptKind = 'ts' | 'tsx' | 'js' | 'jsx';\n\nexport const PACKAGE_NAME = 'payload-live-preview';\n\nlet tsMorph: TsMorph | undefined;\nlet project: Project | undefined;\n\nexport function loadTsMorph(): TsMorph {\n if (tsMorph === undefined) {\n try {\n tsMorph = createRequire(import.meta.url)('ts-morph') as TsMorph;\n } catch (error) {\n throw new Error('pll migrate needs ts-morph: npm install --save-dev ts-morph', {\n cause: error,\n });\n }\n }\n return tsMorph;\n}\n\n/** Parse one script into a throwaway in-memory project; the previous script is discarded. */\nexport function parseScript(text: string, kind: ScriptKind): SourceFile {\n const morph = loadTsMorph();\n project ??= new morph.Project({\n useInMemoryFileSystem: true,\n skipLoadingLibFiles: true,\n skipFileDependencyResolution: true,\n compilerOptions: { allowJs: true, noLib: true },\n });\n return project.createSourceFile(`/script.${kind}`, text, { overwrite: true });\n}\n\nexport function isPackageSpecifier(specifier: string): boolean {\n return specifier === PACKAGE_NAME || specifier.startsWith(`${PACKAGE_NAME}/`);\n}\n\n/** A name the script binds from the package, by `import` or by destructuring `require()`/`import()`. */\nexport interface PackageBinding {\n /** The exported name, as the package spells it. */\n readonly imported: string;\n /** The name the script uses; equals `imported` unless aliased. */\n readonly local: string;\n readonly specifier: string;\n readonly kind: 'import' | 'require';\n /** The node spelling the exported name; rewritten when the export is renamed. */\n readonly importedNode: Node;\n readonly aliased: boolean;\n readonly symbol: TsSymbol | undefined;\n /** The import declaration or variable declaration that binds it. */\n readonly declaration: Node;\n}\n\n/** A name the script re-exports straight from the package: `export { name } from 'payload-live-preview'`. */\nexport interface PackageReexport {\n /** The exported name, as the package spells it. */\n readonly imported: string;\n readonly specifier: string;\n /** The node spelling the package's name; rewritten when the export is renamed. */\n readonly importedNode: Node;\n /** The name the module exports it under, when the specifier has `as`. */\n readonly alias: string | undefined;\n readonly line: number;\n}\n\n/** packageBindings() sees imports; a re-export from the package binds nothing locally and needs its own pass. */\nexport function packageReexports(script: SourceFile): readonly PackageReexport[] {\n const out: PackageReexport[] = [];\n for (const declaration of script.getExportDeclarations()) {\n const specifier = declaration.getModuleSpecifierValue();\n if (specifier === undefined || !isPackageSpecifier(specifier)) continue;\n for (const spec of declaration.getNamedExports()) {\n out.push({\n imported: spec.getName(),\n specifier,\n importedNode: spec.getNameNode(),\n alias: spec.getAliasNode()?.getText(),\n line: spec.getStartLineNumber(),\n });\n }\n }\n return out;\n}\n\nexport function packageBindings(script: SourceFile): readonly PackageBinding[] {\n const { Node, SyntaxKind } = loadTsMorph();\n const out: PackageBinding[] = [];\n for (const declaration of script.getImportDeclarations()) {\n const specifier = declaration.getModuleSpecifierValue();\n if (!isPackageSpecifier(specifier)) continue;\n for (const spec of declaration.getNamedImports()) {\n const alias = spec.getAliasNode();\n const localNode = alias ?? spec.getNameNode();\n out.push({\n imported: spec.getName(),\n local: localNode.getText(),\n specifier,\n kind: 'import',\n importedNode: spec.getNameNode(),\n aliased: alias !== undefined,\n symbol: localNode.getSymbol(),\n declaration,\n });\n }\n }\n for (const declaration of script.getDescendantsOfKind(SyntaxKind.VariableDeclaration)) {\n const specifier = requiredSpecifier(declaration.getInitializer());\n const pattern = declaration.getNameNode();\n if (specifier === undefined || !isPackageSpecifier(specifier)) continue;\n if (!Node.isObjectBindingPattern(pattern)) continue;\n for (const element of pattern.getElements()) {\n const nameNode = element.getNameNode();\n if (!Node.isIdentifier(nameNode)) continue;\n const propertyName = element.getPropertyNameNode();\n out.push({\n imported: propertyName === undefined ? nameNode.getText() : literalName(propertyName),\n local: nameNode.getText(),\n specifier,\n kind: 'require',\n importedNode: propertyName ?? nameNode,\n aliased: propertyName !== undefined,\n symbol: nameNode.getSymbol(),\n declaration,\n });\n }\n }\n return out;\n}\n\nfunction requiredSpecifier(initializer: Node | undefined): string | undefined {\n const { Node, SyntaxKind } = loadTsMorph();\n const call =\n initializer !== undefined && Node.isAwaitExpression(initializer)\n ? initializer.getExpression()\n : initializer;\n if (call === undefined || !Node.isCallExpression(call)) return undefined;\n const callee = call.getExpression();\n const isRequire = Node.isIdentifier(callee) && callee.getText() === 'require';\n if (!isRequire && callee.getKind() !== SyntaxKind.ImportKeyword) return undefined;\n const [argument] = call.getArguments();\n return argument !== undefined && Node.isStringLiteral(argument)\n ? argument.getLiteralText()\n : undefined;\n}\n\nfunction literalName(node: Node): string {\n const { Node } = loadTsMorph();\n if (Node.isStringLiteral(node) || Node.isNoSubstitutionTemplateLiteral(node)) {\n return node.getLiteralText();\n }\n return node.getText();\n}\n\n/** The key of an object-literal member, or `undefined` when it is computed. */\nexport function propertyKey(property: ObjectLiteralElementLike): string | undefined {\n const { Node } = loadTsMorph();\n if (Node.isSpreadAssignment(property)) return undefined;\n const nameNode = property.getNameNode();\n if (Node.isComputedPropertyName(nameNode)) return undefined;\n return literalName(nameNode);\n}\n\nexport type ReferenceKind = 'reference' | 'shorthand' | 'export';\n\nexport interface BindingReference {\n readonly node: Identifier;\n /** `shorthand` is `{ name }`, `export` is `export { name }`; both keep the old key visible. */\n readonly kind: ReferenceKind;\n}\n\n/** Every use of the binding outside its own declaration, resolved by symbol so shadowing is respected. */\nexport function referencesTo(\n script: SourceFile,\n binding: PackageBinding,\n): readonly BindingReference[] {\n const { Node, SyntaxKind } = loadTsMorph();\n const target = binding.symbol?.compilerSymbol;\n if (target === undefined) return [];\n const checker = script.getProject().getTypeChecker();\n const out: BindingReference[] = [];\n for (const node of script.getDescendantsOfKind(SyntaxKind.Identifier)) {\n if (node.getText() !== binding.local || isInside(node, binding.declaration)) continue;\n const parent = node.getParent();\n if (Node.isShorthandPropertyAssignment(parent)) {\n if (checker.getShorthandAssignmentValueSymbol(parent)?.compilerSymbol === target) {\n out.push({ node, kind: 'shorthand' });\n }\n continue;\n }\n if (Node.isExportSpecifier(parent)) {\n if (\n parent.getNameNode() === node &&\n parent.getLocalTargetSymbol()?.compilerSymbol === target\n ) {\n out.push({ node, kind: 'export' });\n }\n continue;\n }\n if (node.getSymbol()?.compilerSymbol === target) out.push({ node, kind: 'reference' });\n }\n return out;\n}\n\nfunction isInside(node: Node, ancestor: Node): boolean {\n return node.getFirstAncestor((candidate) => candidate === ancestor) !== undefined;\n}\n\n/** The declaration that binds `name` anywhere in the script, ignoring those in `except`. */\nexport function declaresName(\n script: SourceFile,\n name: string,\n except: readonly Node[] = [],\n): Node | undefined {\n const { SyntaxKind } = loadTsMorph();\n for (const node of script.getDescendantsOfKind(SyntaxKind.Identifier)) {\n if (node.getText() !== name) continue;\n const parent = node.getParent();\n if (!bindsIdentifier(parent, node)) continue;\n if (except.some((skip) => skip === parent || isInside(parent, skip))) continue;\n return parent;\n }\n return undefined;\n}\n\nfunction bindsIdentifier(parent: Node, node: Identifier): boolean {\n const { Node } = loadTsMorph();\n if (\n Node.isVariableDeclaration(parent) ||\n Node.isBindingElement(parent) ||\n Node.isFunctionDeclaration(parent) ||\n Node.isClassDeclaration(parent) ||\n Node.isParameterDeclaration(parent) ||\n Node.isEnumDeclaration(parent)\n ) {\n return parent.getNameNode() === node;\n }\n if (Node.isImportSpecifier(parent)) {\n return (parent.getAliasNode() ?? parent.getNameNode()) === node;\n }\n if (Node.isImportClause(parent)) return parent.getDefaultImport() === node;\n if (Node.isNamespaceImport(parent)) return parent.getNameNode() === node;\n return false;\n}\n\n/** Identifiers spelled `name` that are member names (`x.name`), never the package's binding. */\nexport function memberAccesses(script: SourceFile, name: string): readonly Identifier[] {\n const { Node, SyntaxKind } = loadTsMorph();\n return script.getDescendantsOfKind(SyntaxKind.Identifier).filter((node) => {\n const parent = node.getParent();\n return (\n node.getText() === name &&\n Node.isPropertyAccessExpression(parent) &&\n parent.getNameNode() === node\n );\n });\n}\n\nexport function replaceNode(node: Node, text: string): TextEdit {\n return { start: node.getStart(), end: node.getEnd(), text };\n}\n\n/** Splice non-overlapping edits into `text`. */\nexport function applyTextEdits(text: string, edits: readonly TextEdit[]): string {\n const ordered = [...edits].sort((left, right) => right.start - left.start);\n let output = text;\n let floor = Number.POSITIVE_INFINITY;\n for (const edit of ordered) {\n if (edit.end > floor) throw new Error('overlapping codemod edits');\n output = `${output.slice(0, edit.start)}${edit.text}${output.slice(edit.end)}`;\n floor = edit.start;\n }\n return output;\n}\n","/**\n * The options literals a script hands to the package: an object literal passed\n * to a function or class the script binds from it, and a `const` object literal\n * such a call takes by name or spreads into its own. The option codemods rename\n * or expand keys there (ADR 0026); anything else they cannot see is left to the\n * development warning the package gives at run time.\n */\nimport type { JsxAttribute, Node, ObjectLiteralExpression, SourceFile } from 'ts-morph';\nimport { loadTsMorph, packageBindings, propertyKey, referencesTo } from './ast';\n\n/** Adapter options carry the request rows too; the root, `/core` and `/client` take runtime options. */\nexport type OptionsKind = 'adapter' | 'runtime';\n\n/** @internal */\nexport const ADAPTER_ENTRIES: ReadonlySet<string> = new Set(\n ['astro', 'nextjs', 'sveltekit', 'nuxt', 'nuxt-module'].map(\n (entry) => `payload-live-preview/${entry}`,\n ),\n);\n\n/** One call that uses a literal: the literal the call passes, which spreads the shared one or is it. */\nexport interface OptionsUse {\n readonly kind: OptionsKind;\n readonly outer: ObjectLiteralExpression;\n /** The index of the spread in `outer` that brings the shared literal in; absent when `outer` is it. */\n readonly at?: number;\n}\n\n/** Every literal the package receives, with the calls that give it. */\nexport function optionLiterals(\n script: SourceFile,\n): ReadonlyMap<ObjectLiteralExpression, readonly OptionsUse[]> {\n const { Node } = loadTsMorph();\n const found = new Map<ObjectLiteralExpression, OptionsUse[]>();\n const record = (literal: ObjectLiteralExpression, use: OptionsUse): void => {\n const uses = found.get(literal) ?? [];\n if (\n !uses.some(\n (known) => known.outer === use.outer && known.at === use.at && known.kind === use.kind,\n )\n ) {\n uses.push(use);\n }\n found.set(literal, uses);\n };\n const visit = (literal: ObjectLiteralExpression, kind: OptionsKind): void => {\n record(literal, { kind, outer: literal });\n literal.getProperties().forEach((property, at) => {\n if (!Node.isSpreadAssignment(property)) return;\n const shared = constLiteral(property.getExpression());\n if (shared !== undefined) record(shared, { kind, outer: literal, at });\n });\n };\n for (const binding of packageBindings(script)) {\n const kind: OptionsKind = ADAPTER_ENTRIES.has(binding.specifier) ? 'adapter' : 'runtime';\n for (const reference of referencesTo(script, binding)) {\n const call = reference.node.getParent();\n if (reference.kind !== 'reference') continue;\n if (!Node.isCallExpression(call) && !Node.isNewExpression(call)) continue;\n if (call.getExpression() !== reference.node) continue;\n for (const argument of call.getArguments()) {\n const inner = unwrap(argument);\n const literal = Node.isObjectLiteralExpression(inner) ? inner : constLiteral(inner);\n if (literal !== undefined) visit(literal, kind);\n }\n }\n }\n return found;\n}\n\n/** `name=\"…\"` or `name={…}` on a JSX element whose tag the script binds from the package. */\nexport function packageJsxAttributes(script: SourceFile, name: string): readonly JsxAttribute[] {\n const { Node, SyntaxKind } = loadTsMorph();\n const tags = new Set(packageBindings(script).map((binding) => binding.local));\n return script.getDescendantsOfKind(SyntaxKind.JsxAttribute).filter((attribute) => {\n const element = attribute.getParent().getParent();\n const isTag = Node.isJsxOpeningElement(element) || Node.isJsxSelfClosingElement(element);\n return (\n isTag &&\n tags.has(element.getTagNameNode().getText()) &&\n attribute.getNameNode().getText() === name\n );\n });\n}\n\n/** The member spelled `key`, or `undefined`. */\nexport function memberNamed(literal: ObjectLiteralExpression, key: string): Node | undefined {\n return literal.getProperties().find((property) => propertyKey(property) === key);\n}\n\n/** The literal a `const` declares, seen through `as const`, `satisfies` and parentheses. */\nfunction constLiteral(node: Node): ObjectLiteralExpression | undefined {\n const { Node, VariableDeclarationKind } = loadTsMorph();\n const target = unwrap(node);\n if (!Node.isIdentifier(target)) return undefined;\n for (const declaration of target.getSymbol()?.getDeclarations() ?? []) {\n if (!Node.isVariableDeclaration(declaration)) continue;\n if (\n declaration.getVariableStatement()?.getDeclarationKind() !== VariableDeclarationKind.Const\n ) {\n continue;\n }\n const initializer = declaration.getInitializer();\n const literal = initializer === undefined ? undefined : unwrap(initializer);\n if (literal !== undefined && Node.isObjectLiteralExpression(literal)) return literal;\n }\n return undefined;\n}\n\nfunction unwrap(node: Node): Node {\n const { Node } = loadTsMorph();\n let current = node;\n while (\n Node.isParenthesizedExpression(current) ||\n Node.isAsExpression(current) ||\n Node.isSatisfiesExpression(current) ||\n Node.isTypeAssertion(current)\n ) {\n current = current.getExpression();\n }\n return current;\n}\n","/**\n * Ledger entry 21: `defaults: 'v1'` → the rows it stands for, as explicit\n * options. The rows keep every value the profile gave, so nothing changes at\n * run time; they only move into the source, where a reviewer and\n * `pll doctor --v2` see each one (ADR 0026).\n */\nimport type { Node, ObjectLiteralElementLike, ObjectLiteralExpression } from 'ts-morph';\nimport { loadTsMorph, propertyKey } from '../ast';\nimport {\n memberNamed,\n optionLiterals,\n packageJsxAttributes,\n type OptionsKind,\n type OptionsUse,\n} from '../option-literals';\nimport type { CodemodImplementation, CodemodConflict, TextEdit } from '../types';\n\nconst ID = 'expand-defaults-v1';\nconst KEY = 'defaults';\n\n/** The 1.x rows (`src/types/defaults-profile.ts`), in source form; `Q` is the file's quote. */\nconst REQUEST_ROWS: readonly (readonly [string, (q: string) => string])[] = [\n ['strict', () => 'false'],\n [\n 'previewSignals',\n (q) => `[${[`${q}query${q}`, `${q}fetch-dest${q}`, `${q}referer${q}`].join(', ')}]`,\n ],\n];\nconst RUNTIME_ROWS: readonly (readonly [string, (q: string) => string])[] = [\n ['disableReferrerDetection', () => 'false'],\n ['eventSourcePolicy', (q) => `${q}any${q}`],\n ['skipUnchanged', () => 'false'],\n ['sanitizerPolicy', (q) => `${q}compat${q}`],\n];\nconst ROWS: Readonly<Record<OptionsKind, readonly (readonly [string, (q: string) => string])[]>> = {\n adapter: [...REQUEST_ROWS, ...RUNTIME_ROWS],\n runtime: RUNTIME_ROWS,\n};\nconst ROW_KEYS: ReadonlySet<string> = new Set(ROWS.adapter.map(([key]) => key));\nconst BY_HAND = \"write the rows `defaults: 'v1'` stands for by hand (docs/migration.md)\";\n\nexport const expandDefaultsV1: CodemodImplementation = {\n id: ID,\n summary: \"`defaults: 'v1'` → the 1.x rows as explicit options\",\n ledgerEntry: 21,\n notice:\n \"The rows keep the 1.x values `defaults: 'v1'` gave; `pll doctor --v2` names each one to drop once the page is ready for 2.0's.\",\n apply(script) {\n const { Node } = loadTsMorph();\n const edits: TextEdit[] = [];\n const conflicts: CodemodConflict[] = [];\n for (const [literal, uses] of optionLiterals(script)) {\n const property = memberNamed(literal, KEY);\n if (property === undefined) continue;\n const line = property.getStartLineNumber();\n const conflict = (reason: string): void => {\n conflicts.push({ codemod: ID, line, reason: `${reason}; ${BY_HAND}` });\n };\n const value = Node.isPropertyAssignment(property) ? property.getInitializer() : undefined;\n if (value === undefined || !Node.isStringLiteral(value)) {\n conflict('`defaults` is not a literal');\n continue;\n }\n if (value.getLiteralText() !== 'v1') continue;\n const refusal = refuse(literal, property, uses);\n if (refusal !== undefined) {\n conflict(refusal);\n continue;\n }\n edits.push(expansion(literal, property, uses, value.getText().charAt(0)));\n }\n for (const attribute of packageJsxAttributes(script, KEY)) {\n conflicts.push({\n codemod: ID,\n line: attribute.getStartLineNumber(),\n reason: `a JSX attribute; ${BY_HAND} as attributes`,\n });\n }\n return { edits, conflicts };\n },\n};\n\n/** Why the rows cannot go where `defaults` was without changing what wins, if they cannot. */\nfunction refuse(\n literal: ObjectLiteralExpression,\n property: Node,\n uses: readonly OptionsUse[],\n): string | undefined {\n const { Node } = loadTsMorph();\n if (new Set(uses.map((use) => use.kind)).size > 1) {\n return 'the object is shared by an adapter and a client, which take different rows';\n }\n // A row is explicit once written, so whatever came before it no longer wins over it.\n const properties = literal.getProperties();\n const index = properties.findIndex((member) => member === property);\n if (properties.slice(0, index).some((member) => Node.isSpreadAssignment(member))) {\n return 'a spread before `defaults` may set a row the expansion would override';\n }\n for (const { outer, at } of uses) {\n if (at === undefined) continue;\n if (memberNamed(outer, KEY) !== undefined) {\n return 'a call that spreads it names its own defaults';\n }\n const before = outer.getProperties().slice(0, at);\n const overridden = (member: ObjectLiteralElementLike): boolean =>\n Node.isSpreadAssignment(member) || ROW_KEYS.has(propertyKey(member) ?? '');\n if (before.some(overridden)) {\n return 'a call sets a row before spreading the object, and the expansion would override it';\n }\n }\n return undefined;\n}\n\nfunction expansion(\n literal: ObjectLiteralExpression,\n property: Node,\n uses: readonly OptionsUse[],\n quote: string,\n): TextEdit {\n const { Node } = loadTsMorph();\n const kind = uses[0]?.kind ?? 'runtime';\n const present = new Set(literal.getProperties().map((member) => propertyKey(member)));\n const composed = [literal, ...uses.map((use) => use.outer)];\n const has = (key: string): boolean =>\n composed.some((part) => memberNamed(part, key) !== undefined);\n // A spread the codemod cannot see into may carry `serverURL`; the one that brings this object in is seen.\n const known = new Set(\n uses.map((use) => (use.at === undefined ? undefined : use.outer.getProperties()[use.at])),\n );\n const opaque = composed.some((part) =>\n part.getProperties().some((member) => Node.isSpreadAssignment(member) && !known.has(member)),\n );\n const rows = ROWS[kind]\n .filter(([key]) => !present.has(key))\n .map(([key, value]) => `${key}: ${value(quote)}`);\n // `'v1'` read an omitted depth as the 1.x default of 1; 2.0 asks for it with `serverURL`.\n if (!has('mergeDepth') && (has('serverURL') || opaque)) rows.push('mergeDepth: 1');\n const source = property.getSourceFile().getFullText();\n if (rows.length === 0) {\n // Every row is already explicit: only the key goes, with the separator after it.\n const next = literal.getProperties().find((member) => member.getStart() > property.getStart());\n return { start: property.getStart(), end: next?.getStart() ?? property.getEnd(), text: '' };\n }\n const lineStart = source.lastIndexOf('\\n', property.getStart()) + 1;\n const lead = source.slice(lineStart, property.getStart());\n const separator = /^\\s*$/u.test(lead) ? `,\\n${lead}` : ', ';\n return { start: property.getStart(), end: property.getEnd(), text: rows.join(separator) };\n}\n","/**\n * Ledger entry 9: `fetchPreviewDocument()`/`fetchPreviewGlobal()` on the root\n * entry → `definePreview({ serverURL, depth }).fetchDocument()`/`.fetchGlobal()`\n * on `payload-live-preview/server`.\n */\nimport {\n PACKAGE_NAME,\n declaresName,\n loadTsMorph,\n packageBindings,\n packageReexports,\n propertyKey,\n referencesTo,\n type PackageBinding,\n type PackageReexport,\n} from '../ast';\nimport type { CodemodImplementation, CodemodConflict, CodemodPlan, TextEdit } from '../types';\nimport type {\n CallExpression,\n ImportDeclaration,\n ObjectLiteralExpression,\n SourceFile,\n} from 'ts-morph';\n\nconst ID = 'move-fetch-preview-helpers';\nconst SERVER_SPECIFIER = `${PACKAGE_NAME}/server`;\nconst METHOD: Readonly<Record<string, string>> = {\n fetchPreviewDocument: 'fetchDocument',\n fetchPreviewGlobal: 'fetchGlobal',\n};\nconst SERVER_OPTIONS = new Set(['serverURL', 'apiRoute', 'depth']);\nconst DROPPED_OPTIONS = new Set(['draft', 'fetchFn']);\n/**\n * What `ReadDocumentOptions`/`ReadGlobalOptions` accept (src/server/preview.ts).\n * 1.x spelled the target `collection` and `global` too, so there is no rename to\n * make here — a key that is in neither set is one this codemod cannot place, and\n * passing it through unannounced produces a file that does not compile.\n */\nconst SHARED_READ_OPTIONS = ['authorization', 'locale', 'headers', 'signal', 'errorMode'];\nconst READ_OPTIONS: Readonly<Record<string, readonly string[]>> = {\n fetchPreviewDocument: ['collection', 'where', ...SHARED_READ_OPTIONS],\n fetchPreviewGlobal: ['global', ...SHARED_READ_OPTIONS],\n};\nconst DEPTH_TODO =\n 'depth: 1 /* TODO(pll migrate): the 1.x default; match the runtime mergeDepth */';\nconst AUTHORIZATION_TODO =\n 'authorization: null /* TODO(pll migrate): pass the verdict from authorizePreviewRequest(); ' +\n 'null reads the published document */';\n\nfunction conflict(line: number, reason: string): CodemodConflict {\n return { codemod: ID, reason, line };\n}\n\ninterface RewrittenCall {\n readonly edit: TextEdit;\n /** What the rewrite did; only true when the file is rewritten. */\n readonly done: CodemodConflict;\n /** What a reader has to place by hand, rewritten or not. */\n readonly advice: readonly CodemodConflict[];\n}\n\nfunction rewriteCall(\n call: CallExpression,\n options: ObjectLiteralExpression,\n imported: string,\n): RewrittenCall {\n const server: string[] = [];\n const read: string[] = [];\n const dropped: string[] = [];\n const keys = new Set<string>();\n for (const property of options.getProperties()) {\n const key = propertyKey(property);\n if (key !== undefined) keys.add(key);\n if (key !== undefined && SERVER_OPTIONS.has(key)) server.push(property.getText());\n else if (key !== undefined && DROPPED_OPTIONS.has(key)) dropped.push(key);\n else read.push(property.getText());\n }\n if (!keys.has('depth')) server.push(DEPTH_TODO);\n if (!keys.has('authorization')) read.push(AUTHORIZATION_TODO);\n const accepted = READ_OPTIONS[imported] ?? [];\n const unplaceable = [...keys].filter(\n (key) => !SERVER_OPTIONS.has(key) && !DROPPED_OPTIONS.has(key) && !accepted.includes(key),\n );\n const typeArguments = call.getTypeArguments().map((argument) => argument.getText());\n const generic = typeArguments.length === 0 ? '' : `<${typeArguments.join(', ')}>`;\n const method = METHOD[imported] ?? imported;\n const text = `definePreview({ ${server.join(', ')} }).${method}${generic}({ ${read.join(', ')} })`;\n const droppedNote = dropped.length === 0 ? '' : `, and ${dropped.join('/')} was dropped`;\n const line = call.getStartLineNumber();\n const done = conflict(\n line,\n `${imported}() was rewritten onto definePreview().${method}(); it now returns a ` +\n `PreviewFetchResult (check ok/data) and needs a real authorization for drafts${droppedNote}`,\n );\n const advice: CodemodConflict[] = [];\n if (unplaceable.length > 0) {\n advice.push(\n conflict(\n line,\n `${imported}() was passed ${unplaceable.map((key) => `\\`${key}\\``).join(', ')}, which ` +\n `.${method}() does not accept; it takes ${accepted.join(', ')}. The key was carried ` +\n 'over unchanged and will not compile — place it by hand',\n ),\n );\n }\n return { edit: { start: call.getStart(), end: call.getEnd(), text }, done, advice };\n}\n\nfunction importLine(quote: string, names: readonly string[], specifier: string): string {\n return `import { ${names.join(', ')} } from ${quote}${specifier}${quote};`;\n}\n\n/** Drop the moved names from their root imports and make sure `definePreview` is imported from the server entry. */\nfunction rewriteImports(script: SourceFile, bindings: readonly PackageBinding[]): TextEdit[] {\n const { Node } = loadTsMorph();\n const edits: TextEdit[] = [];\n const declarations = new Set<ImportDeclaration>();\n for (const binding of bindings) {\n if (Node.isImportDeclaration(binding.declaration)) declarations.add(binding.declaration);\n }\n const serverImport = script\n .getImportDeclarations()\n .find(\n (declaration) =>\n declaration.getModuleSpecifierValue() === SERVER_SPECIFIER && !declaration.isTypeOnly(),\n );\n const hasDefinePreview =\n serverImport?.getNamedImports().some((spec) => spec.getName() === 'definePreview') === true;\n let serverLine: string | undefined;\n if (serverImport !== undefined && !hasDefinePreview) {\n const quote = serverImport.getModuleSpecifier().getQuoteKind();\n const names = [\n ...serverImport.getNamedImports().map((spec) => spec.getText()),\n 'definePreview',\n ];\n const defaultImport = serverImport.getDefaultImport()?.getText();\n const clauses =\n defaultImport === undefined ? names.join(', ') : `${defaultImport}, { ${names.join(', ')} }`;\n const text =\n defaultImport === undefined\n ? importLine(quote, names, SERVER_SPECIFIER)\n : `import ${clauses} from ${quote}${SERVER_SPECIFIER}${quote};`;\n edits.push({ start: serverImport.getStart(), end: serverImport.getEnd(), text });\n }\n for (const declaration of declarations) {\n const quote = declaration.getModuleSpecifier().getQuoteKind();\n const remaining = declaration\n .getNamedImports()\n .filter((spec) => !(spec.getName() in METHOD))\n .map((spec) => spec.getText());\n const defaultImport = declaration.getDefaultImport()?.getText();\n const clauses = [\n defaultImport,\n remaining.length === 0 ? undefined : `{ ${remaining.join(', ')} }`,\n ].filter((clause): clause is string => clause !== undefined);\n const typeOnly = declaration.isTypeOnly() ? 'type ' : '';\n const kept =\n clauses.length === 0\n ? ''\n : `import ${typeOnly}${clauses.join(', ')} from ${quote}${PACKAGE_NAME}${quote};`;\n if (serverImport === undefined && serverLine === undefined) {\n serverLine = importLine(quote, ['definePreview'], SERVER_SPECIFIER);\n edits.push({\n start: declaration.getStart(),\n end: declaration.getEnd(),\n text: kept === '' ? serverLine : `${kept}\\n${serverLine}`,\n });\n } else {\n // A removed declaration takes its line break with it.\n const end = declaration.getEnd();\n const trailingNewline = kept === '' && script.getFullText()[end] === '\\n' ? 1 : 0;\n edits.push({ start: declaration.getStart(), end: end + trailingNewline, text: kept });\n }\n }\n return edits;\n}\n\nfunction plan(\n script: SourceFile,\n bindings: readonly PackageBinding[],\n reexports: readonly PackageReexport[],\n): CodemodPlan {\n const { Node } = loadTsMorph();\n const blocking: CodemodConflict[] = reexports.map((reexport) =>\n conflict(\n reexport.line,\n `${reexport.imported} is re-exported straight from the package; it became ` +\n `definePreview().${METHOD[reexport.imported] ?? reexport.imported}() on ${SERVER_SPECIFIER}, ` +\n 'so rewrite the re-export and its importers by hand',\n ),\n );\n const notes: CodemodConflict[] = [];\n const advice: CodemodConflict[] = [];\n const edits: TextEdit[] = [];\n for (const binding of bindings) {\n if (binding.kind === 'require') {\n blocking.push(\n conflict(\n binding.declaration.getStartLineNumber(),\n `${binding.imported} is bound with require(); rewrite it onto definePreview() from ` +\n `${SERVER_SPECIFIER} by hand`,\n ),\n );\n continue;\n }\n for (const reference of referencesTo(script, binding)) {\n const line = reference.node.getStartLineNumber();\n const call = reference.node.getParent();\n const isCall =\n reference.kind === 'reference' &&\n Node.isCallExpression(call) &&\n call.getExpression() === reference.node;\n if (!isCall) {\n blocking.push(\n conflict(\n line,\n `${binding.local} is used other than as a direct call; rewrite it onto definePreview() by hand`,\n ),\n );\n continue;\n }\n const [options] = call.getArguments();\n if (\n options === undefined ||\n !Node.isObjectLiteralExpression(options) ||\n options.getProperties().some((property) => Node.isSpreadAssignment(property))\n ) {\n blocking.push(\n conflict(\n line,\n `${binding.imported}() options are not a plain object literal, so serverURL/depth ` +\n 'cannot be split out; rewrite it onto definePreview() by hand',\n ),\n );\n continue;\n }\n const rewritten = rewriteCall(call, options, binding.imported);\n edits.push(rewritten.edit);\n notes.push(rewritten.done, ...rewritten.advice);\n advice.push(...rewritten.advice);\n }\n }\n const serverDeclaration = script\n .getImportDeclarations()\n .filter((declaration) => declaration.getModuleSpecifierValue() === SERVER_SPECIFIER);\n const foreign = declaresName(script, 'definePreview', serverDeclaration);\n if (foreign !== undefined) {\n blocking.push(\n conflict(\n foreign.getStartLineNumber(),\n `this module already binds a definePreview that is not ${SERVER_SPECIFIER}'s; rename it, ` +\n 'then move the fetch helpers by hand',\n ),\n );\n }\n // A held-back file was not rewritten, so \"was rewritten\" would say the opposite; the advice still holds.\n if (blocking.length > 0) return { edits: [], conflicts: [...blocking, ...advice] };\n edits.push(...rewriteImports(script, bindings));\n return { edits, conflicts: notes };\n}\n\nexport const moveFetchPreviewHelpers: CodemodImplementation = {\n id: ID,\n summary:\n '`fetchPreviewDocument`/`fetchPreviewGlobal` from the root → `definePreview().fetchDocument`/`.fetchGlobal` (payload-live-preview/server)',\n ledgerEntry: 9,\n apply(script) {\n const bindings = packageBindings(script).filter(\n (binding) => binding.specifier === PACKAGE_NAME && binding.imported in METHOD,\n );\n const reexports = packageReexports(script).filter(\n (reexport) => reexport.specifier === PACKAGE_NAME && reexport.imported in METHOD,\n );\n if (bindings.length === 0 && reexports.length === 0) return { edits: [], conflicts: [] };\n return plan(script, bindings, reexports);\n },\n};\n","/** Ledger entry 13: `hasPreviewIntent(request, { adminOrigins })` → `{ allowedOrigins }`. */\nimport { loadTsMorph, packageBindings, propertyKey, referencesTo, replaceNode } from '../ast';\nimport type { CodemodImplementation, CodemodConflict, TextEdit } from '../types';\n\nconst ID = 'rename-admin-origins-option';\nconst CALLEE = 'hasPreviewIntent';\nconst OLD_KEY = 'adminOrigins';\nconst NEW_KEY = 'allowedOrigins';\nconst BY_HAND = `if they carry \\`${OLD_KEY}\\`, rename it to \\`${NEW_KEY}\\``;\n\nexport const renameAdminOriginsOption: CodemodImplementation = {\n id: ID,\n summary: '`hasPreviewIntent(request, { adminOrigins })` → `{ allowedOrigins }`',\n ledgerEntry: 13,\n apply(script) {\n const { Node } = loadTsMorph();\n const edits: TextEdit[] = [];\n const conflicts: CodemodConflict[] = [];\n const bindings = packageBindings(script).filter((binding) => binding.imported === CALLEE);\n for (const binding of bindings) {\n for (const reference of referencesTo(script, binding)) {\n const call = reference.node.getParent();\n if (reference.kind !== 'reference' || !Node.isCallExpression(call)) continue;\n if (call.getExpression() !== reference.node) continue;\n const options = call.getArguments()[1];\n if (options === undefined) continue;\n const line = options.getStartLineNumber();\n if (!Node.isObjectLiteralExpression(options)) {\n conflicts.push({\n codemod: ID,\n line,\n reason: `${CALLEE}() options are not a literal; ${BY_HAND}`,\n });\n continue;\n }\n const properties = options.getProperties();\n const keys = properties.map((property) => propertyKey(property));\n // With both names the package reads `allowedOrigins` and ignores the\n // alias; renamed, the later key would win instead.\n if (keys.includes(OLD_KEY) && keys.includes(NEW_KEY)) {\n conflicts.push({\n codemod: ID,\n line,\n reason: `${CALLEE}() is given both ${OLD_KEY} and ${NEW_KEY}; ${NEW_KEY} wins, drop ${OLD_KEY} by hand`,\n });\n continue;\n }\n for (const property of properties) {\n if (Node.isSpreadAssignment(property)) {\n conflicts.push({\n codemod: ID,\n line: property.getStartLineNumber(),\n reason: `${CALLEE}() spreads its options; ${BY_HAND}`,\n });\n } else if (propertyKey(property) !== OLD_KEY) {\n continue;\n } else if (Node.isShorthandPropertyAssignment(property)) {\n edits.push(replaceNode(property, `${NEW_KEY}: ${OLD_KEY}`));\n } else if (Node.isPropertyAssignment(property)) {\n edits.push(replaceNode(property.getNameNode(), NEW_KEY));\n }\n }\n }\n }\n return { edits, conflicts };\n },\n};\n","/** Ledger entry 7: `createPreviewBindings({ authorized })` → `{ authorization }`. */\nimport { loadTsMorph, packageBindings, propertyKey, referencesTo, replaceNode } from '../ast';\nimport type { CodemodImplementation, CodemodConflict, TextEdit } from '../types';\n\nconst ID = 'rename-bindings-authorized-option';\nconst OLD_KEY = 'authorized';\nconst NEW_KEY = 'authorization';\nconst BY_HAND =\n `if they carry \\`${OLD_KEY}\\`, rename it to \\`${NEW_KEY}\\` and pass the verdict from ` +\n 'authorizePreviewRequest()';\n/**\n * `false` has an exact equivalent — an unauthorized response suppresses every\n * binding, which is what `null` means — so it is rewritten. Nothing else does:\n * only a real context from `authorizePreviewRequest()` authorizes emission, and\n * a boolean left under the new name does not compile (TS2322).\n */\nconst BOOLEAN_REFUSED =\n `\\`${NEW_KEY}\\` takes the context from authorizePreviewRequest(); the boolean 1.x ` +\n 'accepted is not. The key was renamed and its value left as it stands — pass the ' +\n 'verdict, or `null` for a public response';\n\nexport const renameBindingsAuthorizedOption: CodemodImplementation = {\n id: ID,\n summary: '`createPreviewBindings({ authorized })` → `{ authorization }`',\n ledgerEntry: 7,\n apply(script) {\n const { Node } = loadTsMorph();\n const edits: TextEdit[] = [];\n const conflicts: CodemodConflict[] = [];\n const bindings = packageBindings(script).filter(\n (binding) => binding.imported === 'createPreviewBindings',\n );\n for (const binding of bindings) {\n for (const reference of referencesTo(script, binding)) {\n const call = reference.node.getParent();\n if (reference.kind !== 'reference' || !Node.isCallExpression(call)) continue;\n if (call.getExpression() !== reference.node) continue;\n const [options] = call.getArguments();\n if (options === undefined) continue;\n const line = options.getStartLineNumber();\n if (!Node.isObjectLiteralExpression(options)) {\n conflicts.push({\n codemod: ID,\n line,\n reason: `createPreviewBindings() options are not a literal; ${BY_HAND}`,\n });\n continue;\n }\n for (const property of options.getProperties()) {\n if (Node.isSpreadAssignment(property)) {\n conflicts.push({\n codemod: ID,\n line: property.getStartLineNumber(),\n reason: `createPreviewBindings() spreads its options; ${BY_HAND}`,\n });\n } else if (propertyKey(property) !== OLD_KEY) {\n continue;\n } else if (Node.isShorthandPropertyAssignment(property)) {\n edits.push(replaceNode(property, `${NEW_KEY}: ${OLD_KEY}`));\n conflicts.push({\n codemod: ID,\n line: property.getStartLineNumber(),\n reason: BOOLEAN_REFUSED,\n });\n } else if (Node.isPropertyAssignment(property)) {\n const value = property.getInitializer();\n if (value !== undefined && Node.isFalseLiteral(value)) {\n edits.push(replaceNode(property, `${NEW_KEY}: null`));\n continue;\n }\n edits.push(replaceNode(property.getNameNode(), NEW_KEY));\n conflicts.push({\n codemod: ID,\n line: property.getStartLineNumber(),\n reason: BOOLEAN_REFUSED,\n });\n }\n }\n }\n }\n return { edits, conflicts };\n },\n};\n","/** Ledger entry 1: `isPreviewRequest()` → `hasPreviewIntent()`, same signature. */\nimport {\n declaresName,\n memberAccesses,\n packageBindings,\n packageReexports,\n referencesTo,\n replaceNode,\n type PackageBinding,\n type PackageReexport,\n} from '../ast';\nimport type { CodemodImplementation, CodemodConflict, CodemodPlan, TextEdit } from '../types';\n\nconst ID = 'rename-is-preview-request';\nconst OLD_NAME = 'isPreviewRequest';\nconst NEW_NAME = 'hasPreviewIntent';\n\nfunction conflict(line: number, reason: string): CodemodConflict {\n return { codemod: ID, reason, line };\n}\n\nfunction renameBinding(binding: PackageBinding): TextEdit {\n // `import { isPreviewRequest as hasPreviewIntent }` collapses to the bare name.\n if (binding.aliased && binding.local === NEW_NAME) {\n return replaceNode(binding.importedNode.getParentOrThrow(), NEW_NAME);\n }\n return replaceNode(binding.importedNode, NEW_NAME);\n}\n\nfunction plan(\n bindings: readonly PackageBinding[],\n reexports: readonly PackageReexport[],\n script: Parameters<CodemodImplementation['apply']>[0],\n): CodemodPlan {\n const blocking: CodemodConflict[] = [];\n const edits: TextEdit[] = [];\n for (const reexport of reexports) {\n if (reexport.alias === undefined) {\n // Renaming it would rename this module's export too; its importers decide.\n blocking.push(\n conflict(\n reexport.line,\n `${OLD_NAME} is re-exported straight from the package under its old name; write ` +\n `export { ${NEW_NAME} as ${OLD_NAME} } from '${reexport.specifier}', or rename it and its importers by hand`,\n ),\n );\n } else if (reexport.alias === NEW_NAME) {\n edits.push(replaceNode(reexport.importedNode.getParentOrThrow(), NEW_NAME));\n } else {\n edits.push(replaceNode(reexport.importedNode, NEW_NAME));\n }\n }\n const existing = declaresName(\n script,\n NEW_NAME,\n bindings.map((binding) => binding.declaration),\n );\n if (existing !== undefined) {\n blocking.push(\n conflict(\n existing.getStartLineNumber(),\n `this module already binds ${NEW_NAME}; rename it (or drop the wrapper and import the ` +\n `package's ${NEW_NAME} directly), then rename ${OLD_NAME} by hand`,\n ),\n );\n }\n for (const binding of bindings) {\n edits.push(renameBinding(binding));\n if (binding.aliased) continue;\n for (const reference of referencesTo(script, binding)) {\n if (reference.kind === 'reference') {\n edits.push(replaceNode(reference.node, NEW_NAME));\n } else if (reference.kind === 'shorthand') {\n blocking.push(\n conflict(\n reference.node.getStartLineNumber(),\n `{ ${OLD_NAME} } keeps the old key for whoever reads it; write ` +\n `{ ${OLD_NAME}: ${NEW_NAME} } or rename the key and its readers by hand`,\n ),\n );\n } else {\n blocking.push(\n conflict(\n reference.node.getStartLineNumber(),\n `${OLD_NAME} is re-exported under its old name; rename the export and its ` +\n `importers, or write export { ${NEW_NAME} as ${OLD_NAME} }`,\n ),\n );\n }\n }\n }\n const notes = memberAccesses(script, OLD_NAME).map((node) =>\n conflict(\n node.getStartLineNumber(),\n `.${OLD_NAME} is a member of this module's own object, not the package import, and was ` +\n 'left alone; check that it does not wrap the removed API',\n ),\n );\n if (blocking.length > 0) return { edits: [], conflicts: [...blocking, ...notes] };\n return { edits, conflicts: notes };\n}\n\nexport const renameIsPreviewRequest: CodemodImplementation = {\n id: ID,\n summary: '`isPreviewRequest()` → `hasPreviewIntent()` (same signature)',\n ledgerEntry: 1,\n // The rename keeps behaviour, and that is the part worth saying: the 2.0\n // adapters count only the query, and a renamed call silently does not.\n notice:\n 'hasPreviewIntent() takes the options isPreviewRequest() took and, without `signals`, counts ' +\n 'the same three: a preview query parameter, Sec-Fetch-Dest: iframe and an admin Referer. The ' +\n \"2.0 adapters count only the query; where a call should agree with them, pass { signals: ['query'] } \" +\n '(docs/migration.md).',\n apply(script) {\n const bindings = packageBindings(script).filter((binding) => binding.imported === OLD_NAME);\n const reexports = packageReexports(script).filter((reexport) => reexport.imported === OLD_NAME);\n if (bindings.length === 0 && reexports.length === 0) return { edits: [], conflicts: [] };\n return plan(bindings, reexports, script);\n },\n};\n","/** Ledger entry 19: `onUnboundChange: 'route' | 'ignore'` → `onUnfaithfulPatch: 'escalate' | 'ignore'`. */\nimport { loadTsMorph, replaceNode } from '../ast';\nimport { memberNamed, optionLiterals, packageJsxAttributes } from '../option-literals';\nimport type { CodemodImplementation, CodemodConflict, TextEdit } from '../types';\n\nconst ID = 'rename-on-unbound-change';\nconst OLD_KEY = 'onUnboundChange';\nconst NEW_KEY = 'onUnfaithfulPatch';\nconst RENAMED: Readonly<Record<string, string>> = { route: 'escalate', ignore: 'ignore' };\n\nexport const renameOnUnboundChange: CodemodImplementation = {\n id: ID,\n summary: \"`onUnboundChange: 'route'` → `onUnfaithfulPatch: 'escalate'`\",\n ledgerEntry: 19,\n apply(script) {\n const { Node } = loadTsMorph();\n const edits: TextEdit[] = [];\n const conflicts: CodemodConflict[] = [];\n for (const [literal, uses] of optionLiterals(script)) {\n const property = memberNamed(literal, OLD_KEY);\n if (property === undefined) continue;\n const line = property.getStartLineNumber();\n // The package reads the new name first; renamed, the later key would win instead.\n const both = [literal, ...uses.map((use) => use.outer)].some(\n (candidate) => memberNamed(candidate, NEW_KEY) !== undefined,\n );\n if (both) {\n conflicts.push({\n codemod: ID,\n line,\n reason: `both ${OLD_KEY} and ${NEW_KEY} are given; ${NEW_KEY} wins, drop ${OLD_KEY} by hand`,\n });\n continue;\n }\n const value = Node.isPropertyAssignment(property) ? property.getInitializer() : undefined;\n const text = value !== undefined && Node.isStringLiteral(value) ? value.getLiteralText() : '';\n const renamed = RENAMED[text];\n if (value === undefined || renamed === undefined) {\n conflicts.push({\n codemod: ID,\n line,\n reason: `${OLD_KEY} is not a literal 'route' or 'ignore'; rename it to ${NEW_KEY} by hand ('route' is 'escalate')`,\n });\n continue;\n }\n const quote = value.getText().charAt(0);\n edits.push(replaceNode(property, `${NEW_KEY}: ${quote}${renamed}${quote}`));\n }\n for (const attribute of packageJsxAttributes(script, OLD_KEY)) {\n conflicts.push({\n codemod: ID,\n line: attribute.getStartLineNumber(),\n reason: `a JSX attribute; rename ${OLD_KEY} to ${NEW_KEY} by hand ('route' is 'escalate')`,\n });\n }\n return { edits, conflicts };\n },\n};\n","/** Where the script lives in a file: the whole file, or the script blocks of a component. */\nimport { extname } from 'node:path';\nimport type { ScriptKind } from './ast';\n\nexport interface ScriptBlock {\n readonly start: number;\n readonly end: number;\n readonly kind: ScriptKind;\n}\n\nconst WHOLE_FILE: Readonly<Record<string, ScriptKind>> = {\n '.ts': 'ts',\n '.mts': 'ts',\n '.cts': 'ts',\n '.tsx': 'tsx',\n '.js': 'js',\n '.mjs': 'js',\n '.cjs': 'js',\n '.jsx': 'jsx',\n};\nconst COMPONENT_EXTENSIONS = new Set(['.astro', '.vue', '.svelte']);\nconst FRONTMATTER = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---/u;\n// Browsers close a script on `</script` followed by anything up to `>`, so the\n// end tag must accept that too, or a stray `</script foo>` would swallow the\n// rest of the file into one block.\nconst SCRIPT_TAG = /<script(?:\\s[^>]*)?>([\\s\\S]*?)<\\/script\\b[^>]*>/giu;\n\nexport function scriptBlocks(source: string, fileName: string): readonly ScriptBlock[] {\n const extension = extname(fileName).toLowerCase();\n if (!COMPONENT_EXTENSIONS.has(extension)) {\n return [{ start: 0, end: source.length, kind: WHOLE_FILE[extension] ?? 'ts' }];\n }\n const blocks: ScriptBlock[] = [];\n const frontmatter = extension === '.astro' ? FRONTMATTER.exec(source) : null;\n if (frontmatter?.[1] !== undefined) {\n const start = frontmatter.index + frontmatter[0].indexOf('\\n') + 1;\n blocks.push({ start, end: start + frontmatter[1].length, kind: 'ts' });\n }\n for (const match of source.matchAll(SCRIPT_TAG)) {\n const body = match[1] ?? '';\n if (body.trim() === '') continue;\n const start = match.index + match[0].lastIndexOf(body);\n blocks.push({ start, end: start + body.length, kind: 'ts' });\n }\n return blocks;\n}\n","/**\n * `pll migrate`: the 1.x → 2.0 codemods and the driver that applies them to one\n * source string. Rewrites are planned on the AST (ts-morph) so only names the\n * package binds are touched; see ADR 0007.\n */\nimport { applyTextEdits, parseScript } from './ast';\nimport { expandDefaultsV1 } from './codemods/expand-defaults-v1';\nimport { moveFetchPreviewHelpers } from './codemods/move-fetch-preview-helpers';\nimport { renameAdminOriginsOption } from './codemods/rename-admin-origins-option';\nimport { renameBindingsAuthorizedOption } from './codemods/rename-bindings-authorized-option';\nimport { renameIsPreviewRequest } from './codemods/rename-is-preview-request';\nimport { renameOnUnboundChange } from './codemods/rename-on-unbound-change';\nimport { scriptBlocks } from './script-blocks';\nimport type {\n Codemod,\n CodemodConflict,\n CodemodEdit,\n CodemodImplementation,\n CodemodLineEdit,\n} from './types';\n\nexport type {\n Codemod,\n CodemodConflict,\n CodemodEdit,\n CodemodLineEdit,\n CodemodPlan,\n TextEdit,\n} from './types';\n\nconst PACKAGE_REFERENCE =\n /(?:\\bfrom\\s*|\\bimport\\s*\\(?\\s*|\\brequire\\s*\\(\\s*)['\"]payload-live-preview(?:\\/[^'\"]*)?['\"]/u;\n\n/** Whether the source names the package in an `import`, `import()` or `require()`. @internal */\nexport function importsThisPackage(source: string): boolean {\n return PACKAGE_REFERENCE.test(source);\n}\n\n// The option rename follows the function rename so it sees the new binding.\nconst IMPLEMENTATIONS: readonly CodemodImplementation[] = [\n renameIsPreviewRequest,\n renameAdminOriginsOption,\n renameBindingsAuthorizedOption,\n moveFetchPreviewHelpers,\n renameOnUnboundChange,\n expandDefaultsV1,\n];\n\n/**\n * The codemods in the order they run. Each is idempotent. Metadata only: the\n * rewrite is internal, so importing this entry's types does not require\n * `ts-morph`, which is needed only to run `pll migrate`.\n * @internal\n */\nexport const CODEMODS: readonly Codemod[] = IMPLEMENTATIONS;\n\nexport interface MigrateSourceOptions {\n /** Restrict to these codemod ids. */\n readonly only?: readonly string[];\n /**\n * Decides how the source is parsed: `.astro`, `.vue` and `.svelte` by script\n * block, JSX by extension. Defaults to a `.ts` module.\n */\n readonly fileName?: string;\n}\n\nexport interface MigrateSourceResult {\n readonly output: string;\n readonly edits: readonly CodemodEdit[];\n readonly conflicts: readonly CodemodConflict[];\n}\n\nfunction lineNumberAt(source: string, offset: number): number {\n let line = 1;\n for (let index = 0; index < offset; index += 1) if (source[index] === '\\n') line += 1;\n return line;\n}\n\n/** The changed lines between two versions, trimmed to the differing middle. */\nfunction lineEdits(before: string, after: string, firstLine: number): CodemodLineEdit[] {\n const oldLines = before.split('\\n');\n const newLines = after.split('\\n');\n let prefix = 0;\n while (\n prefix < oldLines.length &&\n prefix < newLines.length &&\n oldLines[prefix] === newLines[prefix]\n ) {\n prefix += 1;\n }\n let suffix = 0;\n while (\n suffix < oldLines.length - prefix &&\n suffix < newLines.length - prefix &&\n oldLines[oldLines.length - 1 - suffix] === newLines[newLines.length - 1 - suffix]\n ) {\n suffix += 1;\n }\n const oldMiddle = oldLines.slice(prefix, oldLines.length - suffix);\n const newMiddle = newLines.slice(prefix, newLines.length - suffix);\n const changed: CodemodLineEdit[] = [];\n for (let index = 0; index < Math.max(oldMiddle.length, newMiddle.length); index += 1) {\n const before = oldMiddle[index] ?? '';\n const after = newMiddle[index] ?? '';\n if (before !== after) changed.push({ line: firstLine + prefix + index, before, after });\n }\n return changed;\n}\n\n/** Apply every codemod (or the chosen subset) to one source string. */\nexport function migrateSource(\n source: string,\n options: MigrateSourceOptions = {},\n): MigrateSourceResult {\n const chosen =\n options.only === undefined\n ? IMPLEMENTATIONS\n : IMPLEMENTATIONS.filter((codemod) => options.only?.includes(codemod.id));\n if (chosen.length === 0 || !importsThisPackage(source)) {\n return { output: source, edits: [], conflicts: [] };\n }\n const byCodemod = new Map<string, CodemodLineEdit[]>();\n const conflicts: CodemodConflict[] = [];\n let output = '';\n let cursor = 0;\n for (const block of scriptBlocks(source, options.fileName ?? 'source.ts')) {\n output += source.slice(cursor, block.start);\n const firstLine = lineNumberAt(source, block.start);\n let text = source.slice(block.start, block.end);\n for (const codemod of chosen) {\n const plan = codemod.apply(parseScript(text, block.kind));\n for (const item of plan.conflicts) {\n conflicts.push(\n item.line === undefined ? item : { ...item, line: item.line + firstLine - 1 },\n );\n }\n if (plan.edits.length === 0) continue;\n const next = applyTextEdits(text, plan.edits);\n const lines = byCodemod.get(codemod.id) ?? [];\n lines.push(...lineEdits(text, next, firstLine));\n byCodemod.set(codemod.id, lines);\n text = next;\n }\n output += text;\n cursor = block.end;\n }\n output += source.slice(cursor);\n const edits = [...byCodemod].map(([codemod, lines]) => ({ codemod, count: lines.length, lines }));\n return { output, edits, conflicts };\n}\n"],"mappings":"sEAqBO,IAEHA,EACAC,EAHSC,EAAe,uBAKrB,SAASC,IACd,QAAgB,IAAZH,EACF,IACEA,EAAUI,cAA0BC,IAA1BD,CAA+B,WAC3C,OAASE,GACP,MAAM,IAAIC,MAAM,8DAA+D,CAC7EC,MAAOF,GAEX,CAEF,OAAON,CACT,CAGO,SAASS,EAAYC,EAAcC,GACxC,MAAMC,EAAQT,IAOd,OANAF,IAAY,IAAIW,EAAMC,QAAQ,CAC5BC,uBAAuB,EACvBC,qBAAqB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O,EAAKxH,OAAQrN,KAAM,MACvD,CACA,OAAOuU,CACT,CCgFsBQ,CAAa7H,EAAQmB,EAAQ8F,UAAY,aAAc,CACzE7M,GAAU4F,EAAOvF,MAAMsM,EAAQC,EAAMtN,OACrC,MAAMsM,EAAYL,GAAa3F,EAAQgH,EAAMtN,OAC7C,IAAI7G,EAAOmN,EAAOvF,MAAMuM,EAAMtN,MAAOsN,EAAMpN,KAC3C,UAAWiF,KAAW+H,EAAQ,CAC5B,MAAM9C,EAAOjF,EAAQJ,MAAM7L,EAAYC,EAAMmU,EAAMlU,OACnD,UAAWgV,KAAQhE,EAAKpF,UACtBA,EAAUtK,UACM,IAAd0T,EAAKlT,KAAqBkT,EAAO,IAAKA,EAAMlT,KAAMkT,EAAKlT,KAAOoR,EAAY,IAG9E,GAA0B,IAAtBlC,EAAK/J,MAAMoG,OAAc,SAC7B,MAAMC,EAAOtG,EAAejH,EAAMiR,EAAK/J,OACjCgO,EAAQjB,EAAUzL,IAAIwD,EAAQR,KAAO,GAC3C0J,EAAM3T,QAAQyR,GAAUhT,EAAMuN,EAAM4F,IACpCc,EAAUrL,IAAIoD,EAAQR,GAAI0J,GAC1BlV,EAAOuN,CACT,CACAhG,GAAUvH,EACVkU,EAASC,EAAMpN,GACjB,CAGA,OAFAQ,GAAU4F,EAAOvF,MAAMsM,GAEhB,CAAE3M,SAAQL,MADH,IAAI+M,GAAWlM,IAAI,EAAEiE,EAASkJ,MAAK,CAASlJ,UAASmJ,MAAOD,EAAM5H,OAAQ4H,WAChErJ,YAC1B,Q","ignoreList":[]}
@@ -40,6 +40,25 @@ type EventSourcePolicy = 'any' | 'parent-or-opener';
40
40
  */
41
41
  declare const AUTHORIZED_PREVIEW_BRAND_KEY = "payload-live-preview.authorized-preview-context";
42
42
  type PreviewAuthorizationStrategyName = 'payload-session' | 'signed-token' | 'verifier';
43
+ /** One server-authorized Payload document, not a query selected by the browser. */
44
+ type AuthorizedPreviewDocument = {
45
+ readonly kind: 'collection';
46
+ readonly slug: string;
47
+ readonly id: string | number;
48
+ } | {
49
+ readonly kind: 'global';
50
+ readonly slug: string;
51
+ };
52
+ /** Opt-in data capability, enforced by the fragment endpoint and `definePreview`. */
53
+ interface AuthorizedPreviewPayloadScope {
54
+ /** Payload base URL, distinct from the preview site's audience. */
55
+ readonly serverURL: string;
56
+ /** REST prefix, default `/api`. */
57
+ readonly apiRoute?: string;
58
+ readonly document: AuthorizedPreviewDocument;
59
+ /** Maximum requested population depth, not a field-level ACL. */
60
+ readonly maxDepth: number;
61
+ }
43
62
  /** What a context is bound to; every field is optional because every strategy binds differently. */
44
63
  interface AuthorizedPreviewScope {
45
64
  /** The site origin the credential was issued for. */
@@ -47,6 +66,8 @@ interface AuthorizedPreviewScope {
47
66
  /** The request pathname the credential is valid for. */
48
67
  readonly path?: string;
49
68
  readonly locale?: string;
69
+ /** Requires a finite context expiry. Unscoped contexts keep their existing behavior. */
70
+ readonly payload?: AuthorizedPreviewPayloadScope;
50
71
  }
51
72
  /** The verdict of a successful `authorizePreviewRequest()`: frozen, branded, produced only there. Carry it, do not rebuild it. */
52
73
  interface AuthorizedPreviewContext {
@@ -87,6 +108,8 @@ interface PreviewAuthorizationRequest {
87
108
  readonly headers: {
88
109
  get(name: string): string | null;
89
110
  };
111
+ /** Request lifetime, when supplied by the caller. Session fetches follow it. */
112
+ readonly signal?: AbortSignal;
90
113
  }
91
114
 
92
115
  /**
@@ -261,6 +284,13 @@ interface PreviewAdapterOptions<Req = Request> {
261
284
  readonly autoBind?: 'off' | 'unique';
262
285
  /** Patch only the bindings of the document an update names (`data-payload-owner`). Default `false`. */
263
286
  readonly scopeBindingsByOwner?: boolean;
287
+ /**
288
+ * How a group counts as covered (ADR 0022). `'descendant'` (default): one
289
+ * bound path inside it covers all of it. `'declared'`: each changed path
290
+ * inside such a group needs its own binding or a `data-payload-covers`
291
+ * declaration; an uncovered one is an unbound change.
292
+ */
293
+ readonly subfieldCoverage?: 'descendant' | 'declared';
264
294
  /** Sanitizer for rich text and HTML writes. Default `'strict'`; `defaults: 'v1'` restores `'compat'`. */
265
295
  readonly sanitizerPolicy?: 'compat' | 'strict';
266
296
  /** Which windows may post updates. Default `'parent-or-opener'`; `defaults: 'v1'` restores `'any'`. */
@@ -277,7 +307,7 @@ interface PreviewAdapterOptions<Req = Request> {
277
307
  * See ADR 0006.
278
308
  */
279
309
  readonly authorizePreview?: (request: Req) => PreviewAuthorizationHookResult | Promise<PreviewAuthorizationHookResult>;
280
- /** Refuse insecure configuration at startup: `authorizePreview`, https `allowedOrigins`, no referrer trust. Default `true`; `defaults: 'v1'` restores `false`. */
310
+ /** Refuse insecure configuration at startup: `authorizePreview`, non-empty `allowedOrigins` (`https:` in production), no `'referer'` signal. Default `true`; `defaults: 'v1'` restores `false`. */
281
311
  readonly strict?: boolean;
282
312
  /** `'v2'` (default) is the 2.0 table, `'v1'` stages a migration on the 1.x one; explicit options win. See ADR 0007. */
283
313
  readonly defaults?: DefaultsProfile;
package/dist/payload.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";exports.buildLivePreviewUrl=function(e){const l=e.baseUrl.replace(/\/+$/,""),n=void 0===e.fallback?"/":e.fallback,t=void 0===e.previewParam?"preview":e.previewParam;return o=>{const i=function(e){return void 0===e?void 0:"string"==typeof e?e.length>0?e:void 0:e.code.length>0?e.code:void 0}(o.locale),c={data:o.data,locale:i},r=function(e,l){const n=l.collectionConfig?.slug;if(void 0!==n&&void 0!==e.collections&&Object.hasOwn(e.collections,n))return e.collections[n];const t=l.globalConfig?.slug;return void 0!==t&&void 0!==e.globals&&Object.hasOwn(e.globals,t)?e.globals[t]:void 0}(e,o);let s=n;if(void 0!==r){const e="function"==typeof r?r(c):r;if(null===e)return null;e.length>0&&(s=e)}return null===s?null:(s.startsWith("/")||(s=`/${s}`),`${l}${null===t?s:function(e,l){const n=e.indexOf("#"),t=-1===n?"":e.slice(n),o=-1===n?e:e.slice(0,n),i=o.indexOf("?"),c=-1===i?"":o.slice(i+1);if("true"===new URLSearchParams(c).get(l))return e;return`${o}${-1===i?"?":0===c.length||c.endsWith("&")?"":"&"}${l}=true${t}`}(s,t)}`)}};
1
+ "use strict";function o(o,l,e){return void 0!==l&&void 0!==o.collections&&Object.hasOwn(o.collections,l)?o.collections[l]:void 0!==e&&void 0!==o.globals&&Object.hasOwn(o.globals,e)?o.globals[e]:void 0}exports.buildLivePreviewUrl=function(l){const e=l.baseUrl.replace(/\/+$/,""),n=void 0===l.fallback?"/":l.fallback,t=void 0===l.previewParam?"preview":l.previewParam;return i=>{const c=function(o){return void 0===o?void 0:"string"==typeof o?o.length>0?o:void 0:"string"==typeof o.code&&o.code.length>0?o.code:void 0}(i.locale),r={data:i.data,locale:c},s=function(l,e){return void 0!==e.collectionConfig||void 0!==e.globalConfig?o(l,e.collectionConfig?.slug,e.globalConfig?.slug):o(l,e.documentInfo?.collection?.slug,e.documentInfo?.global?.slug)}(l,i);let u=n;if(void 0!==s){const o="function"==typeof s?s(r):s;if(null===o)return null;o.length>0&&(u=o)}return null===u?null:(u.startsWith("/")||(u=`/${u}`),`${e}${null===t?u:function(o,l){const e=o.indexOf("#"),n=-1===e?"":o.slice(e),t=-1===e?o:o.slice(0,e),i=t.indexOf("?"),c=-1===i?"":t.slice(i+1),r=new URLSearchParams(c).getAll(l);if("true"===r[r.length-1])return o;return`${t}${-1===i?"?":0===c.length||c.endsWith("&")?"":"&"}${encodeURIComponent(l)}=true${n}`}(u,t)}`)}};
2
2
  //# sourceMappingURL=payload.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"payload.cjs","names":["options","base","baseUrl","replace","fallback","previewParam","args","locale","length","code","normaliseLocale","context","data","entry","collectionSlug","collectionConfig","slug","collections","Object","hasOwn","globalSlug","globalConfig","globals","findResolver","path","resolved","startsWith","name","hashAt","indexOf","hash","slice","beforeHash","queryAt","query","URLSearchParams","get","endsWith","withPreviewParam"],"sources":["../src/payload/index.ts"],"sourcesContent":["/**\n * `payload-live-preview/payload` — helpers for `payload.config.ts`. It never\n * imports `payload`, only produces the callback `admin.livePreview.url` expects.\n */\n\n/** Arguments Payload passes to `admin.livePreview.url`. */\nexport interface LivePreviewUrlArgs {\n readonly data: Record<string, unknown>;\n readonly locale?: string | { readonly code: string };\n readonly collectionConfig?: { readonly slug: string };\n readonly globalConfig?: { readonly slug: string };\n readonly [extra: string]: unknown;\n}\n\n/** Context handed to per-slug path resolvers. */\nexport interface PathResolverContext {\n readonly data: Record<string, unknown>;\n /** Normalised locale code, or `undefined`. */\n readonly locale: string | undefined;\n}\n\nexport type PathResolver = string | ((context: PathResolverContext) => string);\n\n/** A resolver that may decline a document: `null` means no preview target; `''` falls back. */\nexport type NullablePathResolver =\n string | null | ((context: PathResolverContext) => string | null);\n\nexport interface BuildLivePreviewUrlOptions {\n /** Frontend origin, e.g. `https://site.example`. */\n readonly baseUrl: string;\n /** Per-collection path resolvers keyed by collection slug. */\n readonly collections?: Readonly<Record<string, PathResolver>>;\n /** Per-global path resolvers keyed by global slug. */\n readonly globals?: Readonly<Record<string, PathResolver>>;\n /** Path when no resolver matches or one returns `''` (a draft without a slug). Default `/`. */\n readonly fallback?: string;\n /** Query parameter signalling preview intent; client-controlled, so it authorizes nothing. Default `'preview'`, `null` disables it. */\n readonly previewParam?: string | null;\n}\n\n/**\n * Like {@link BuildLivePreviewUrlOptions} with nullable resolvers: the callback\n * may return `null`, and no iframe beats one pointing at a public page.\n */\nexport interface BuildLivePreviewUrlNullableOptions {\n readonly baseUrl: string;\n readonly collections?: Readonly<Record<string, NullablePathResolver>>;\n readonly globals?: Readonly<Record<string, NullablePathResolver>>;\n /** `null` declines every unmapped document. Default `/`. */\n readonly fallback?: string | null;\n /** See {@link BuildLivePreviewUrlOptions.previewParam}. */\n readonly previewParam?: string | null;\n}\n\n/** Build an `admin.livePreview.url` callback from slug → path mappings. */\nexport function buildLivePreviewUrl(\n options: BuildLivePreviewUrlOptions,\n): (args: LivePreviewUrlArgs) => string;\nexport function buildLivePreviewUrl(\n options: BuildLivePreviewUrlNullableOptions,\n): (args: LivePreviewUrlArgs) => string | null;\nexport function buildLivePreviewUrl(\n options: BuildLivePreviewUrlNullableOptions,\n): (args: LivePreviewUrlArgs) => string | null {\n const base = options.baseUrl.replace(/\\/+$/, '');\n // `??` would swallow an explicit `null`, which is the whole point of the nullable form.\n const fallback = options.fallback === undefined ? '/' : options.fallback;\n const previewParam = options.previewParam === undefined ? 'preview' : options.previewParam;\n\n return (args) => {\n const locale = normaliseLocale(args.locale);\n const context: PathResolverContext = { data: args.data, locale };\n const entry = findResolver(options, args);\n\n let path: string | null = fallback;\n if (entry !== undefined) {\n const resolved = typeof entry === 'function' ? entry(context) : entry;\n if (resolved === null) return null;\n if (resolved.length > 0) path = resolved;\n }\n if (path === null) return null;\n if (!path.startsWith('/')) path = `/${path}`;\n return `${base}${previewParam === null ? path : withPreviewParam(path, previewParam)}`;\n };\n}\n\n/** `path` with `<name>=true` in its query — ahead of any `#fragment`, and not twice. */\nfunction withPreviewParam(path: string, name: string): string {\n const hashAt = path.indexOf('#');\n const hash = hashAt === -1 ? '' : path.slice(hashAt);\n const beforeHash = hashAt === -1 ? path : path.slice(0, hashAt);\n const queryAt = beforeHash.indexOf('?');\n const query = queryAt === -1 ? '' : beforeHash.slice(queryAt + 1);\n if (new URLSearchParams(query).get(name) === 'true') return path;\n const separator = queryAt === -1 ? '?' : query.length === 0 || query.endsWith('&') ? '' : '&';\n return `${beforeHash}${separator}${name}=true${hash}`;\n}\n\n/** The mapped resolver, or `undefined` when the slug is not mapped; a mapped `null` is a resolver in its own right. */\nfunction findResolver(\n options: BuildLivePreviewUrlNullableOptions,\n args: LivePreviewUrlArgs,\n): NullablePathResolver | undefined {\n const collectionSlug = args.collectionConfig?.slug;\n if (\n collectionSlug !== undefined &&\n options.collections !== undefined &&\n Object.hasOwn(options.collections, collectionSlug)\n ) {\n return options.collections[collectionSlug];\n }\n const globalSlug = args.globalConfig?.slug;\n if (\n globalSlug !== undefined &&\n options.globals !== undefined &&\n Object.hasOwn(options.globals, globalSlug)\n ) {\n return options.globals[globalSlug];\n }\n return undefined;\n}\n\nfunction normaliseLocale(locale: LivePreviewUrlArgs['locale']): string | undefined {\n if (locale === undefined) return undefined;\n if (typeof locale === 'string') return locale.length > 0 ? locale : undefined;\n return locale.code.length > 0 ? locale.code : undefined;\n}\n"],"mappings":"yCA6DO,SACLA,GAEA,MAAMC,EAAOD,EAAQE,QAAQC,QAAQ,OAAQ,IAEvCC,OAAgC,IAArBJ,EAAQI,SAAyB,IAAMJ,EAAQI,SAC1DC,OAAwC,IAAzBL,EAAQK,aAA6B,UAAYL,EAAQK,aAE9E,OAAQC,IACN,MAAMC,EAoDV,SAAyBA,GACvB,YAAe,IAAXA,OAAsB,EACJ,iBAAXA,EAA4BA,EAAOC,OAAS,EAAID,OAAS,EAC7DA,EAAOE,KAAKD,OAAS,EAAID,EAAOE,UAAO,CAChD,CAxDmBC,CAAgBJ,EAAKC,QAC9BI,EAA+B,CAAEC,KAAMN,EAAKM,KAAML,UAClDM,EA2BV,SACEb,EACAM,GAEA,MAAMQ,EAAiBR,EAAKS,kBAAkBC,KAC9C,QACqB,IAAnBF,QACwB,IAAxBd,EAAQiB,aACRC,OAAOC,OAAOnB,EAAQiB,YAAaH,GAEnC,OAAOd,EAAQiB,YAAYH,GAE7B,MAAMM,EAAad,EAAKe,cAAcL,KACtC,YACiB,IAAfI,QACoB,IAApBpB,EAAQsB,SACRJ,OAAOC,OAAOnB,EAAQsB,QAASF,GAExBpB,EAAQsB,QAAQF,QALzB,CAQF,CAhDkBG,CAAavB,EAASM,GAEpC,IAAIkB,EAAsBpB,EAC1B,QAAc,IAAVS,EAAqB,CACvB,MAAMY,EAA4B,mBAAVZ,EAAuBA,EAAMF,GAAWE,EAChE,GAAiB,OAAbY,EAAmB,OAAO,KAC1BA,EAASjB,OAAS,IAAGgB,EAAOC,EAClC,CACA,OAAa,OAATD,EAAsB,MACrBA,EAAKE,WAAW,OAAMF,EAAO,IAAIA,KAC/B,GAAGvB,IAAwB,OAAjBI,EAAwBmB,EAK7C,SAA0BA,EAAcG,GACtC,MAAMC,EAASJ,EAAKK,QAAQ,KACtBC,GAAkB,IAAXF,EAAgB,GAAKJ,EAAKO,MAAMH,GACvCI,GAAwB,IAAXJ,EAAgBJ,EAAOA,EAAKO,MAAM,EAAGH,GAClDK,EAAUD,EAAWH,QAAQ,KAC7BK,GAAoB,IAAZD,EAAiB,GAAKD,EAAWD,MAAME,EAAU,GAC/D,GAA6C,SAAzC,IAAIE,gBAAgBD,GAAOE,IAAIT,GAAkB,OAAOH,EAE5D,MAAO,GAAGQ,KADoB,IAAZC,EAAiB,IAAuB,IAAjBC,EAAM1B,QAAgB0B,EAAMG,SAAS,KAAO,GAAK,MACvDV,SAAYG,GACjD,CAdoDQ,CAAiBd,EAAMnB,MAE3E","ignoreList":[]}
1
+ {"version":3,"file":"payload.cjs","names":["findResolverBySlug","options","collectionSlug","globalSlug","collections","Object","hasOwn","globals","base","baseUrl","replace","fallback","previewParam","args","locale","length","code","normaliseLocale","context","data","entry","collectionConfig","globalConfig","slug","documentInfo","collection","global","findResolver","path","resolved","startsWith","name","hashAt","indexOf","hash","slice","beforeHash","queryAt","query","values","URLSearchParams","getAll","endsWith","encodeURIComponent","withPreviewParam"],"sources":["../src/payload/index.ts"],"sourcesContent":["/**\n * `payload-live-preview/payload` — helpers for `payload.config.ts`. It never\n * imports `payload`, only produces the callback `admin.livePreview.url` expects.\n */\n\n/** Arguments Payload passes to `admin.livePreview.url`. */\nexport interface LivePreviewUrlArgs {\n readonly data: Record<string, unknown>;\n readonly locale?: string | { readonly code?: string | null; readonly [extra: string]: unknown };\n readonly collectionConfig?: { readonly slug: string };\n readonly globalConfig?: { readonly slug: string };\n /** Payload 2 identifies the edited entity here instead of through the top-level configs. */\n readonly documentInfo?: {\n readonly collection?: {\n /** Payload 2 inherits this runtime value through a mapped config type. */\n readonly slug?: string;\n /** Structural anchor for Payload 2's published sanitized config type. */\n readonly fields?: unknown;\n };\n readonly global?: {\n /** Payload 2 inherits this runtime value through a mapped config type. */\n readonly slug?: string;\n /** Structural anchor for Payload 2's published sanitized config type. */\n readonly fields?: unknown;\n };\n };\n readonly [extra: string]: unknown;\n}\n\n/** Context handed to per-slug path resolvers. */\nexport interface PathResolverContext {\n readonly data: Record<string, unknown>;\n /** Normalised locale code, or `undefined`. */\n readonly locale: string | undefined;\n}\n\nexport type PathResolver = string | ((context: PathResolverContext) => string);\n\n/** A resolver that may decline a document: `null` means no preview target; `''` falls back. */\nexport type NullablePathResolver =\n string | null | ((context: PathResolverContext) => string | null);\n\nexport interface BuildLivePreviewUrlOptions {\n /** Frontend origin, e.g. `https://site.example`. */\n readonly baseUrl: string;\n /** Per-collection path resolvers keyed by collection slug. */\n readonly collections?: Readonly<Record<string, PathResolver>>;\n /** Per-global path resolvers keyed by global slug. */\n readonly globals?: Readonly<Record<string, PathResolver>>;\n /** Path when no resolver matches or one returns `''` (a draft without a slug). Default `/`. */\n readonly fallback?: string;\n /** Query parameter signalling preview intent; keep it in the adapter's `previewQueryParams`. Client-controlled, so it authorizes nothing. Default `'preview'`, `null` disables it. */\n readonly previewParam?: string | null;\n}\n\n/**\n * Like {@link BuildLivePreviewUrlOptions} with nullable resolvers: the callback\n * may return `null`, and no iframe beats one pointing at a public page.\n */\nexport interface BuildLivePreviewUrlNullableOptions {\n readonly baseUrl: string;\n readonly collections?: Readonly<Record<string, NullablePathResolver>>;\n readonly globals?: Readonly<Record<string, NullablePathResolver>>;\n /** `null` declines every unmapped document. Default `/`. */\n readonly fallback?: string | null;\n /** See {@link BuildLivePreviewUrlOptions.previewParam}. */\n readonly previewParam?: string | null;\n}\n\n/** Build an `admin.livePreview.url` callback from slug → path mappings. */\nexport function buildLivePreviewUrl(\n options: BuildLivePreviewUrlOptions,\n): (args: LivePreviewUrlArgs) => string;\nexport function buildLivePreviewUrl(\n options: BuildLivePreviewUrlNullableOptions,\n): (args: LivePreviewUrlArgs) => string | null;\nexport function buildLivePreviewUrl(\n options: BuildLivePreviewUrlNullableOptions,\n): (args: LivePreviewUrlArgs) => string | null {\n const base = options.baseUrl.replace(/\\/+$/, '');\n // `??` would swallow an explicit `null`, which is the whole point of the nullable form.\n const fallback = options.fallback === undefined ? '/' : options.fallback;\n const previewParam = options.previewParam === undefined ? 'preview' : options.previewParam;\n\n return (args) => {\n const locale = normaliseLocale(args.locale);\n const context: PathResolverContext = { data: args.data, locale };\n const entry = findResolver(options, args);\n\n let path: string | null = fallback;\n if (entry !== undefined) {\n const resolved = typeof entry === 'function' ? entry(context) : entry;\n if (resolved === null) return null;\n if (resolved.length > 0) path = resolved;\n }\n if (path === null) return null;\n if (!path.startsWith('/')) path = `/${path}`;\n return `${base}${previewParam === null ? path : withPreviewParam(path, previewParam)}`;\n };\n}\n\n/** `path` with `<name>=true` in its query — ahead of any `#fragment`, and not twice. */\nfunction withPreviewParam(path: string, name: string): string {\n const hashAt = path.indexOf('#');\n const hash = hashAt === -1 ? '' : path.slice(hashAt);\n const beforeHash = hashAt === -1 ? path : path.slice(0, hashAt);\n const queryAt = beforeHash.indexOf('?');\n const query = queryAt === -1 ? '' : beforeHash.slice(queryAt + 1);\n const values = new URLSearchParams(query).getAll(name);\n if (values[values.length - 1] === 'true') return path;\n const separator = queryAt === -1 ? '?' : query.length === 0 || query.endsWith('&') ? '' : '&';\n return `${beforeHash}${separator}${encodeURIComponent(name)}=true${hash}`;\n}\n\n/** The mapped resolver, or `undefined` when the slug is not mapped; a mapped `null` is a resolver in its own right. */\nfunction findResolver(\n options: BuildLivePreviewUrlNullableOptions,\n args: LivePreviewUrlArgs,\n): NullablePathResolver | undefined {\n // Payload 3's explicit callback arguments win as a pair. Looking through a\n // stale `documentInfo` when either is present could select the wrong entity.\n if (args.collectionConfig !== undefined || args.globalConfig !== undefined) {\n return findResolverBySlug(options, args.collectionConfig?.slug, args.globalConfig?.slug);\n }\n return findResolverBySlug(\n options,\n args.documentInfo?.collection?.slug,\n args.documentInfo?.global?.slug,\n );\n}\n\nfunction findResolverBySlug(\n options: BuildLivePreviewUrlNullableOptions,\n collectionSlug: string | undefined,\n globalSlug: string | undefined,\n): NullablePathResolver | undefined {\n if (\n collectionSlug !== undefined &&\n options.collections !== undefined &&\n Object.hasOwn(options.collections, collectionSlug)\n ) {\n return options.collections[collectionSlug];\n }\n if (\n globalSlug !== undefined &&\n options.globals !== undefined &&\n Object.hasOwn(options.globals, globalSlug)\n ) {\n return options.globals[globalSlug];\n }\n return undefined;\n}\n\nfunction normaliseLocale(locale: LivePreviewUrlArgs['locale']): string | undefined {\n if (locale === undefined) return undefined;\n if (typeof locale === 'string') return locale.length > 0 ? locale : undefined;\n return typeof locale.code === 'string' && locale.code.length > 0 ? locale.code : undefined;\n}\n"],"mappings":"aAmIA,SAASA,EACPC,EACAC,EACAC,GAEA,YACqB,IAAnBD,QACwB,IAAxBD,EAAQG,aACRC,OAAOC,OAAOL,EAAQG,YAAaF,GAE5BD,EAAQG,YAAYF,QAGZ,IAAfC,QACoB,IAApBF,EAAQM,SACRF,OAAOC,OAAOL,EAAQM,QAASJ,GAExBF,EAAQM,QAAQJ,QALzB,CAQF,C,4BA3EO,SACLF,GAEA,MAAMO,EAAOP,EAAQQ,QAAQC,QAAQ,OAAQ,IAEvCC,OAAgC,IAArBV,EAAQU,SAAyB,IAAMV,EAAQU,SAC1DC,OAAwC,IAAzBX,EAAQW,aAA6B,UAAYX,EAAQW,aAE9E,OAAQC,IACN,MAAMC,EAoEV,SAAyBA,GACvB,YAAe,IAAXA,OAAsB,EACJ,iBAAXA,EAA4BA,EAAOC,OAAS,EAAID,OAAS,EACtC,iBAAhBA,EAAOE,MAAqBF,EAAOE,KAAKD,OAAS,EAAID,EAAOE,UAAO,CACnF,CAxEmBC,CAAgBJ,EAAKC,QAC9BI,EAA+B,CAAEC,KAAMN,EAAKM,KAAML,UAClDM,EA4BV,SACEnB,EACAY,GAIA,YAA8B,IAA1BA,EAAKQ,uBAAwD,IAAtBR,EAAKS,aACvCtB,EAAmBC,EAASY,EAAKQ,kBAAkBE,KAAMV,EAAKS,cAAcC,MAE9EvB,EACLC,EACAY,EAAKW,cAAcC,YAAYF,KAC/BV,EAAKW,cAAcE,QAAQH,KAE/B,CA1CkBI,CAAa1B,EAASY,GAEpC,IAAIe,EAAsBjB,EAC1B,QAAc,IAAVS,EAAqB,CACvB,MAAMS,EAA4B,mBAAVT,EAAuBA,EAAMF,GAAWE,EAChE,GAAiB,OAAbS,EAAmB,OAAO,KAC1BA,EAASd,OAAS,IAAGa,EAAOC,EAClC,CACA,OAAa,OAATD,EAAsB,MACrBA,EAAKE,WAAW,OAAMF,EAAO,IAAIA,KAC/B,GAAGpB,IAAwB,OAAjBI,EAAwBgB,EAK7C,SAA0BA,EAAcG,GACtC,MAAMC,EAASJ,EAAKK,QAAQ,KACtBC,GAAkB,IAAXF,EAAgB,GAAKJ,EAAKO,MAAMH,GACvCI,GAAwB,IAAXJ,EAAgBJ,EAAOA,EAAKO,MAAM,EAAGH,GAClDK,EAAUD,EAAWH,QAAQ,KAC7BK,GAAoB,IAAZD,EAAiB,GAAKD,EAAWD,MAAME,EAAU,GACzDE,EAAS,IAAIC,gBAAgBF,GAAOG,OAAOV,GACjD,GAAkC,SAA9BQ,EAAOA,EAAOxB,OAAS,GAAe,OAAOa,EAEjD,MAAO,GAAGQ,KADoB,IAAZC,EAAiB,IAAuB,IAAjBC,EAAMvB,QAAgBuB,EAAMI,SAAS,KAAO,GAAK,MACvDC,mBAAmBZ,UAAaG,GACrE,CAfoDU,CAAiBhB,EAAMhB,MAE3E","ignoreList":[]}
@@ -6,7 +6,8 @@
6
6
  interface LivePreviewUrlArgs {
7
7
  readonly data: Record<string, unknown>;
8
8
  readonly locale?: string | {
9
- readonly code: string;
9
+ readonly code?: string | null;
10
+ readonly [extra: string]: unknown;
10
11
  };
11
12
  readonly collectionConfig?: {
12
13
  readonly slug: string;
@@ -14,6 +15,21 @@ interface LivePreviewUrlArgs {
14
15
  readonly globalConfig?: {
15
16
  readonly slug: string;
16
17
  };
18
+ /** Payload 2 identifies the edited entity here instead of through the top-level configs. */
19
+ readonly documentInfo?: {
20
+ readonly collection?: {
21
+ /** Payload 2 inherits this runtime value through a mapped config type. */
22
+ readonly slug?: string;
23
+ /** Structural anchor for Payload 2's published sanitized config type. */
24
+ readonly fields?: unknown;
25
+ };
26
+ readonly global?: {
27
+ /** Payload 2 inherits this runtime value through a mapped config type. */
28
+ readonly slug?: string;
29
+ /** Structural anchor for Payload 2's published sanitized config type. */
30
+ readonly fields?: unknown;
31
+ };
32
+ };
17
33
  readonly [extra: string]: unknown;
18
34
  }
19
35
  /** Context handed to per-slug path resolvers. */
@@ -34,7 +50,7 @@ interface BuildLivePreviewUrlOptions {
34
50
  readonly globals?: Readonly<Record<string, PathResolver>>;
35
51
  /** Path when no resolver matches or one returns `''` (a draft without a slug). Default `/`. */
36
52
  readonly fallback?: string;
37
- /** Query parameter signalling preview intent; client-controlled, so it authorizes nothing. Default `'preview'`, `null` disables it. */
53
+ /** Query parameter signalling preview intent; keep it in the adapter's `previewQueryParams`. Client-controlled, so it authorizes nothing. Default `'preview'`, `null` disables it. */
38
54
  readonly previewParam?: string | null;
39
55
  }
40
56
  /**
package/dist/payload.d.ts CHANGED
@@ -6,7 +6,8 @@
6
6
  interface LivePreviewUrlArgs {
7
7
  readonly data: Record<string, unknown>;
8
8
  readonly locale?: string | {
9
- readonly code: string;
9
+ readonly code?: string | null;
10
+ readonly [extra: string]: unknown;
10
11
  };
11
12
  readonly collectionConfig?: {
12
13
  readonly slug: string;
@@ -14,6 +15,21 @@ interface LivePreviewUrlArgs {
14
15
  readonly globalConfig?: {
15
16
  readonly slug: string;
16
17
  };
18
+ /** Payload 2 identifies the edited entity here instead of through the top-level configs. */
19
+ readonly documentInfo?: {
20
+ readonly collection?: {
21
+ /** Payload 2 inherits this runtime value through a mapped config type. */
22
+ readonly slug?: string;
23
+ /** Structural anchor for Payload 2's published sanitized config type. */
24
+ readonly fields?: unknown;
25
+ };
26
+ readonly global?: {
27
+ /** Payload 2 inherits this runtime value through a mapped config type. */
28
+ readonly slug?: string;
29
+ /** Structural anchor for Payload 2's published sanitized config type. */
30
+ readonly fields?: unknown;
31
+ };
32
+ };
17
33
  readonly [extra: string]: unknown;
18
34
  }
19
35
  /** Context handed to per-slug path resolvers. */
@@ -34,7 +50,7 @@ interface BuildLivePreviewUrlOptions {
34
50
  readonly globals?: Readonly<Record<string, PathResolver>>;
35
51
  /** Path when no resolver matches or one returns `''` (a draft without a slug). Default `/`. */
36
52
  readonly fallback?: string;
37
- /** Query parameter signalling preview intent; client-controlled, so it authorizes nothing. Default `'preview'`, `null` disables it. */
53
+ /** Query parameter signalling preview intent; keep it in the adapter's `previewQueryParams`. Client-controlled, so it authorizes nothing. Default `'preview'`, `null` disables it. */
38
54
  readonly previewParam?: string | null;
39
55
  }
40
56
  /**
package/dist/payload.js CHANGED
@@ -1,2 +1,2 @@
1
- function e(e){const l=e.baseUrl.replace(/\/+$/,""),n=void 0===e.fallback?"/":e.fallback,o=void 0===e.previewParam?"preview":e.previewParam;return t=>{const i=function(e){return void 0===e?void 0:"string"==typeof e?e.length>0?e:void 0:e.code.length>0?e.code:void 0}(t.locale),c={data:t.data,locale:i},r=function(e,l){const n=l.collectionConfig?.slug;if(void 0!==n&&void 0!==e.collections&&Object.hasOwn(e.collections,n))return e.collections[n];const o=l.globalConfig?.slug;return void 0!==o&&void 0!==e.globals&&Object.hasOwn(e.globals,o)?e.globals[o]:void 0}(e,t);let a=n;if(void 0!==r){const e="function"==typeof r?r(c):r;if(null===e)return null;e.length>0&&(a=e)}return null===a?null:(a.startsWith("/")||(a=`/${a}`),`${l}${null===o?a:function(e,l){const n=e.indexOf("#"),o=-1===n?"":e.slice(n),t=-1===n?e:e.slice(0,n),i=t.indexOf("?"),c=-1===i?"":t.slice(i+1);if("true"===new URLSearchParams(c).get(l))return e;return`${t}${-1===i?"?":0===c.length||c.endsWith("&")?"":"&"}${l}=true${o}`}(a,o)}`)}}export{e as buildLivePreviewUrl};
1
+ function o(o){const n=o.baseUrl.replace(/\/+$/,""),e=void 0===o.fallback?"/":o.fallback,t=void 0===o.previewParam?"preview":o.previewParam;return i=>{const c=function(o){return void 0===o?void 0:"string"==typeof o?o.length>0?o:void 0:"string"==typeof o.code&&o.code.length>0?o.code:void 0}(i.locale),r={data:i.data,locale:c},a=function(o,n){return void 0!==n.collectionConfig||void 0!==n.globalConfig?l(o,n.collectionConfig?.slug,n.globalConfig?.slug):l(o,n.documentInfo?.collection?.slug,n.documentInfo?.global?.slug)}(o,i);let u=e;if(void 0!==a){const o="function"==typeof a?a(r):a;if(null===o)return null;o.length>0&&(u=o)}return null===u?null:(u.startsWith("/")||(u=`/${u}`),`${n}${null===t?u:function(o,l){const n=o.indexOf("#"),e=-1===n?"":o.slice(n),t=-1===n?o:o.slice(0,n),i=t.indexOf("?"),c=-1===i?"":t.slice(i+1),r=new URLSearchParams(c).getAll(l);if("true"===r[r.length-1])return o;return`${t}${-1===i?"?":0===c.length||c.endsWith("&")?"":"&"}${encodeURIComponent(l)}=true${e}`}(u,t)}`)}}function l(o,l,n){return void 0!==l&&void 0!==o.collections&&Object.hasOwn(o.collections,l)?o.collections[l]:void 0!==n&&void 0!==o.globals&&Object.hasOwn(o.globals,n)?o.globals[n]:void 0}export{o as buildLivePreviewUrl};
2
2
  //# sourceMappingURL=payload.js.map