payload-live-preview 2.0.0-beta.0 → 2.0.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.
- package/README.md +60 -775
- package/dist/adapters/astro/PreviewBoundary.astro +2 -2
- package/dist/adapters/astro/index.d.ts +28 -154
- package/dist/adapters/astro/index.js +1 -1
- package/dist/adapters/astro/index.js.map +1 -1
- package/dist/adapters/astro/middleware-entry.d.ts +3 -2
- package/dist/adapters/astro/middleware-entry.js +1 -1
- package/dist/adapters/astro/middleware-entry.js.map +1 -1
- package/dist/adapters/nextjs/index.d.ts +247 -6
- package/dist/adapters/nextjs/index.js +1 -1
- package/dist/adapters/nextjs/index.js.map +1 -1
- package/dist/adapters/nuxt/index.d.ts +58 -3
- package/dist/adapters/nuxt/index.js +1 -1
- package/dist/adapters/nuxt/index.js.map +1 -1
- package/dist/adapters/nuxt/module.d.ts +82 -0
- package/dist/adapters/nuxt/module.js +2 -0
- package/dist/adapters/nuxt/module.js.map +1 -0
- package/dist/adapters/react/index.d.ts +110 -0
- package/dist/adapters/react/index.js +3 -0
- package/dist/adapters/react/index.js.map +1 -0
- package/dist/adapters/sveltekit/index.d.ts +65 -7
- package/dist/adapters/sveltekit/index.js +1 -1
- package/dist/adapters/sveltekit/index.js.map +1 -1
- package/dist/adapters/vue/index.d.ts +56 -0
- package/dist/adapters/vue/index.js +2 -0
- package/dist/adapters/vue/index.js.map +1 -0
- package/dist/annotate.d.ts +161 -0
- package/dist/annotate.js +2 -0
- package/dist/annotate.js.map +1 -0
- package/dist/client.cjs +1 -1
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +182 -9
- package/dist/client.d.ts +182 -9
- package/dist/client.js +1 -1
- package/dist/client.js.map +1 -1
- package/dist/codegen-astro.js +1 -1
- package/dist/codegen-astro.js.map +1 -1
- package/dist/codegen-cli.js +1 -1
- package/dist/codegen-cli.js.map +1 -1
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.cjs.map +1 -1
- package/dist/codegen.d.cts +129 -4
- package/dist/codegen.d.ts +129 -4
- package/dist/codegen.js +1 -1
- package/dist/codegen.js.map +1 -1
- package/dist/core.cjs +1 -1
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +264 -73
- package/dist/core.d.ts +264 -73
- package/dist/core.js +1 -1
- package/dist/core.js.map +1 -1
- package/dist/doctor-cli.d.ts +1 -1
- package/dist/doctor-cli.js +1 -1
- package/dist/doctor-cli.js.map +1 -1
- package/dist/doctor.d.ts +7 -6
- package/dist/doctor.js +1 -1
- package/dist/doctor.js.map +1 -1
- package/dist/document-session-BfBfLVpg.d.ts +53 -0
- package/dist/fragment-endpoint-3Mlz7GDz.d.ts +189 -0
- package/dist/fragment.cjs +1 -1
- package/dist/fragment.cjs.map +1 -1
- package/dist/fragment.d.cts +64 -18
- package/dist/fragment.d.ts +64 -18
- package/dist/fragment.js +1 -1
- package/dist/fragment.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +422 -83
- package/dist/index.d.ts +422 -83
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/lean.cjs +2 -0
- package/dist/lean.cjs.map +1 -0
- package/dist/lean.d.cts +44 -0
- package/dist/lean.d.ts +44 -0
- package/dist/lean.js +2 -0
- package/dist/lean.js.map +1 -0
- package/dist/lexical.cjs +1 -1
- package/dist/lexical.cjs.map +1 -1
- package/dist/lexical.d.cts +19 -1
- package/dist/lexical.d.ts +19 -1
- package/dist/lexical.js +1 -1
- package/dist/lexical.js.map +1 -1
- package/dist/locals-DBXDMxOA.d.ts +45 -0
- package/dist/{middleware-CEPsY1P7.d.ts → middleware-Bx9I7PXW.d.ts} +14 -14
- package/dist/migrate.d.ts +4 -3
- package/dist/migrate.js +1 -1
- package/dist/migrate.js.map +1 -1
- package/dist/{options-CEzzfHJu.d.ts → options-BW1eqXvc.d.ts} +90 -2
- package/dist/plugins.cjs +1 -1
- package/dist/plugins.cjs.map +1 -1
- package/dist/plugins.d.cts +111 -6
- package/dist/plugins.d.ts +111 -6
- package/dist/plugins.js +1 -1
- package/dist/plugins.js.map +1 -1
- package/dist/{probe-CYtvj_Lm.d.ts → probe-CELeUciC.d.ts} +26 -4
- package/dist/server.cjs +1 -1
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +67 -13
- package/dist/server.d.ts +67 -13
- package/dist/server.js +1 -1
- package/dist/server.js.map +1 -1
- package/dist/structural.cjs +2 -2
- package/dist/structural.cjs.map +1 -1
- package/dist/structural.d.cts +47 -4
- package/dist/structural.d.ts +47 -4
- package/dist/structural.js +2 -2
- package/dist/structural.js.map +1 -1
- package/package.json +77 -9
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { A as AuthorizedPreviewContext, d as PreviewAuthorizationOutcome } from './options-BW1eqXvc.js';
|
|
2
|
+
|
|
3
|
+
/** What a decision publishes for templates on `locals` (Astro, SvelteKit) or `event.context` (Nuxt). */
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The keys the adapters publish on the request-scoped context — `Astro.locals`,
|
|
7
|
+
* SvelteKit's `event.locals`, Nuxt's `event.context`. Extend the framework's
|
|
8
|
+
* `App.Locals` with it and templates read them typed. Every key is optional:
|
|
9
|
+
* a refused preview withholds them all, and Next.js has no locals at all.
|
|
10
|
+
*/
|
|
11
|
+
interface LivePreviewLocals {
|
|
12
|
+
/**
|
|
13
|
+
* The request-scoped CSP nonce, for templates that nonce their own scripts.
|
|
14
|
+
* Set by the Astro middleware (prerendered pages included), the SvelteKit
|
|
15
|
+
* handle and the Nuxt server handler or plugin on every request — except a
|
|
16
|
+
* preview the `authorizePreview` hook refused, which gets no preview artefact.
|
|
17
|
+
*/
|
|
18
|
+
readonly livePreviewNonce?: string;
|
|
19
|
+
/** The verified `AuthorizedPreviewContext`. Set only when `authorizePreview` authorized an intent-bearing request. */
|
|
20
|
+
readonly livePreviewAuthorization?: AuthorizedPreviewContext;
|
|
21
|
+
/** The hook's `PreviewAuthorizationOutcome`, refusals included. Set whenever the hook ran: on intent, with `authorizePreview` configured. */
|
|
22
|
+
readonly livePreviewAuthorizationOutcome?: PreviewAuthorizationOutcome;
|
|
23
|
+
}
|
|
24
|
+
/** The request-scoped nonce, for templates that nonce their own scripts. @internal */
|
|
25
|
+
declare const NONCE_LOCALS_KEY = "livePreviewNonce";
|
|
26
|
+
/** The verified `AuthorizedPreviewContext`; absent unless `authorizePreview` authorized. @internal */
|
|
27
|
+
declare const AUTHORIZATION_LOCALS_KEY = "livePreviewAuthorization";
|
|
28
|
+
/** The hook's `PreviewAuthorizationOutcome`; absent when no hook ran. @internal */
|
|
29
|
+
declare const AUTHORIZATION_OUTCOME_LOCALS_KEY = "livePreviewAuthorizationOutcome";
|
|
30
|
+
/**
|
|
31
|
+
* What an adapter needs of a framework's request context: the three keys it
|
|
32
|
+
* writes, and nothing else.
|
|
33
|
+
*
|
|
34
|
+
* This is what the adapters' event types declare rather than
|
|
35
|
+
* `Record<string, unknown>`. A framework's own `App.Locals` is an interface
|
|
36
|
+
* without an index signature, so it is not assignable to a record — which made
|
|
37
|
+
* composing our handle with SvelteKit's `Handle` type fail to compile, even
|
|
38
|
+
* though the values matched. The adapters assign through the interface's own
|
|
39
|
+
* keys, so the published type cannot drift from what the code writes either.
|
|
40
|
+
*/
|
|
41
|
+
type LivePreviewLocalsSink = {
|
|
42
|
+
-readonly [K in keyof LivePreviewLocals]: LivePreviewLocals[K];
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
export { AUTHORIZATION_LOCALS_KEY as A, type LivePreviewLocals as L, NONCE_LOCALS_KEY as N, AUTHORIZATION_OUTCOME_LOCALS_KEY as a, type LivePreviewLocalsSink as b };
|
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
import { b as
|
|
1
|
+
import { b as LivePreviewLocalsSink } from './locals-DBXDMxOA.js';
|
|
2
|
+
import { P as PreviewAdapterOptions } from './options-BW1eqXvc.js';
|
|
2
3
|
|
|
3
4
|
/** Public types for the Astro adapter. */
|
|
4
5
|
|
|
5
6
|
interface LivePreviewAstroOptions extends PreviewAdapterOptions {
|
|
6
7
|
/**
|
|
7
|
-
* How the integration
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
* `
|
|
14
|
-
*
|
|
8
|
+
* How the integration registers. `'inline'` (default) bakes the runtime into
|
|
9
|
+
* every page and `'loader'` publishes it as a hashed asset and injects a
|
|
10
|
+
* bootstrap — Astro emits and serves that asset itself, through a Vite
|
|
11
|
+
* plugin, which is why this is a mode here and the `delivery` option
|
|
12
|
+
* elsewhere: there is no route to mount.
|
|
13
|
+
*
|
|
14
|
+
* `'middleware'` registers the request-time middleware. It serializes its
|
|
15
|
+
* options into the build, so `authorizePreview` and `shouldInject` cannot
|
|
16
|
+
* travel and the strict default refuses it — register
|
|
17
|
+
* `createLivePreviewMiddleware()` in `src/middleware.ts` instead, or pass
|
|
18
|
+
* `strict: false` for intent-only delivery.
|
|
15
19
|
*/
|
|
16
20
|
readonly mode?: 'inline' | 'loader' | 'middleware';
|
|
17
|
-
/** Same-origin path of the route exporting `createFragmentEndpoint()`; the runtime then renders every boundary through it (ADR 0011). */
|
|
18
|
-
readonly fragments?: {
|
|
19
|
-
readonly endpoint: string;
|
|
20
|
-
};
|
|
21
21
|
}
|
|
22
22
|
|
|
23
23
|
/**
|
|
@@ -29,7 +29,7 @@ interface LivePreviewAstroOptions extends PreviewAdapterOptions {
|
|
|
29
29
|
type MiddlewareNext = () => Promise<Response>;
|
|
30
30
|
interface MiddlewareContext {
|
|
31
31
|
readonly request: Request;
|
|
32
|
-
readonly locals:
|
|
32
|
+
readonly locals: LivePreviewLocalsSink;
|
|
33
33
|
/** Astro ≥ 5: `true` while prerendering at build time. */
|
|
34
34
|
readonly isPrerendered?: boolean;
|
|
35
35
|
}
|
package/dist/migrate.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/** Shapes shared by the codemods, the driver and the runner. Types only. */
|
|
2
2
|
|
|
3
|
-
/** One splice into a script, in source offsets. */
|
|
3
|
+
/** One splice into a script, in source offsets. @internal */
|
|
4
4
|
interface TextEdit {
|
|
5
5
|
readonly start: number;
|
|
6
6
|
readonly end: number;
|
|
@@ -13,7 +13,7 @@ interface CodemodConflict {
|
|
|
13
13
|
/** 1-based line in the file, when the conflict has one. */
|
|
14
14
|
readonly line?: number;
|
|
15
15
|
}
|
|
16
|
-
/** What a codemod wants done to one script. */
|
|
16
|
+
/** What a codemod wants done to one script. @internal */
|
|
17
17
|
interface CodemodPlan {
|
|
18
18
|
readonly edits: readonly TextEdit[];
|
|
19
19
|
readonly conflicts: readonly CodemodConflict[];
|
|
@@ -45,12 +45,13 @@ interface CodemodEdit {
|
|
|
45
45
|
readonly lines: readonly CodemodLineEdit[];
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
-
/** Whether the source names the package in an `import`, `import()` or `require()`. */
|
|
48
|
+
/** Whether the source names the package in an `import`, `import()` or `require()`. @internal */
|
|
49
49
|
declare function importsThisPackage(source: string): boolean;
|
|
50
50
|
/**
|
|
51
51
|
* The codemods in the order they run. Each is idempotent. Metadata only: the
|
|
52
52
|
* rewrite is internal, so importing this entry's types does not require
|
|
53
53
|
* `ts-morph`, which is needed only to run `pll migrate`.
|
|
54
|
+
* @internal
|
|
54
55
|
*/
|
|
55
56
|
declare const CODEMODS: readonly Codemod[];
|
|
56
57
|
interface MigrateSourceOptions {
|
package/dist/migrate.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as e}from"module";import{extname as t}from"path";var n,o,i="payload-live-preview";function r(){if(void 0===n)try{n=e(import.meta.url)("ts-morph")}catch(e){throw new Error("pll migrate needs ts-morph: npm install --save-dev ts-morph",{cause:e})}return n}function s(e,t){const n=r();return o??=new n.Project({useInMemoryFileSystem:!0,skipLoadingLibFiles:!0,skipFileDependencyResolution:!0,compilerOptions:{allowJs:!0,noLib:!0}}),o.createSourceFile(`/script.${t}`,e,{overwrite:!0})}function a(e){return e===i||e.startsWith(`${i}/`)}function d(e){const{Node:t,SyntaxKind:n}=r(),o=[];for(const t of e.getImportDeclarations()){const e=t.getModuleSpecifierValue();if(a(e))for(const n of t.getNamedImports()){const i=n.getAliasNode(),r=i??n.getNameNode();o.push({imported:n.getName(),local:r.getText(),specifier:e,kind:"import",importedNode:n.getNameNode(),aliased:void 0!==i,symbol:r.getSymbol(),declaration:t})}}for(const i of e.getDescendantsOfKind(n.VariableDeclaration)){const e=c(i.getInitializer()),n=i.getNameNode();if(void 0!==e&&a(e)&&t.isObjectBindingPattern(n))for(const r of n.getElements()){const n=r.getNameNode();if(!t.isIdentifier(n))continue;const s=r.getPropertyNameNode();o.push({imported:void 0===s?n.getText():l(s),local:n.getText(),specifier:e,kind:"require",importedNode:s??n,aliased:void 0!==s,symbol:n.getSymbol(),declaration:i})}}return o}function c(e){const{Node:t,SyntaxKind:n}=r(),o=void 0!==e&&t.isAwaitExpression(e)?e.getExpression():e;if(void 0===o||!t.isCallExpression(o))return;const i=o.getExpression();if((!t.isIdentifier(i)||"require"!==i.getText())&&i.getKind()!==n.ImportKeyword)return;const[s]=o.getArguments();return void 0!==s&&t.isStringLiteral(s)?s.getLiteralText():void 0}function l(e){const{Node:t}=r();return t.isStringLiteral(e)||t.isNoSubstitutionTemplateLiteral(e)?e.getLiteralText():e.getText()}function u(e){const{Node:t}=r();if(t.isSpreadAssignment(e))return;const n=e.getNameNode();return t.isComputedPropertyName(n)?void 0:l(n)}function p(e,t){const{Node:n,SyntaxKind:o}=r(),i=t.symbol?.compilerSymbol;if(void 0===i)return[];const s=e.getProject().getTypeChecker(),a=[];for(const r of e.getDescendantsOfKind(o.Identifier)){if(r.getText()!==t.local||f(r,t.declaration))continue;const e=r.getParent();n.isShorthandPropertyAssignment(e)?s.getShorthandAssignmentValueSymbol(e)?.compilerSymbol===i&&a.push({node:r,kind:"shorthand"}):n.isExportSpecifier(e)?e.getNameNode()===r&&e.getLocalTargetSymbol()?.compilerSymbol===i&&a.push({node:r,kind:"export"}):r.getSymbol()?.compilerSymbol===i&&a.push({node:r,kind:"reference"})}return a}function f(e,t){return void 0!==e.getFirstAncestor(e=>e===t)}function m(e,t,n=[]){const{SyntaxKind:o}=r();for(const i of e.getDescendantsOfKind(o.Identifier)){if(i.getText()!==t)continue;const e=i.getParent();if(g(e,i)&&!n.some(t=>t===e||f(e,t)))return e}}function g(e,t){const{Node:n}=r();return n.isVariableDeclaration(e)||n.isBindingElement(e)||n.isFunctionDeclaration(e)||n.isClassDeclaration(e)||n.isParameterDeclaration(e)||n.isEnumDeclaration(e)?e.getNameNode()===t:n.isImportSpecifier(e)?(e.getAliasNode()??e.getNameNode())===t:n.isImportClause(e)?e.getDefaultImport()===t:!!n.isNamespaceImport(e)&&e.getNameNode()===t}function h(e,t){return{start:e.getStart(),end:e.getEnd(),text:t}}function v(e,t){const n=[...t].sort((e,t)=>t.start-e.start);let o=e,i=Number.POSITIVE_INFINITY;for(const e of n){if(e.end>i)throw new Error("overlapping codemod edits");o=`${o.slice(0,e.start)}${e.text}${o.slice(e.end)}`,i=e.start}return o}var N="move-fetch-preview-helpers",w=`${i}/server`,y={fetchPreviewDocument:"fetchDocument",fetchPreviewGlobal:"fetchGlobal"},x=/* @__PURE__ */new Set(["serverURL","apiRoute","depth"]),b=/* @__PURE__ */new Set(["draft","fetchFn"]);function S(e,t){return{codemod:N,reason:t,line:e}}function $(e,t,n){const o=[],i=[],r=[],s=/* @__PURE__ */new Set;for(const e of t.getProperties()){const t=u(e);void 0!==t&&s.add(t),void 0!==t&&x.has(t)?o.push(e.getText()):void 0!==t&&b.has(t)?r.push(t):i.push(e.getText())}s.has("depth")||o.push("depth: 1 /* TODO(pll migrate): the 1.x default; match the runtime mergeDepth */"),s.has("authorization")||i.push("authorization: null /* TODO(pll migrate): pass the verdict from authorizePreviewRequest(); null reads the published document */");const a=e.getTypeArguments().map(e=>e.getText()),d=0===a.length?"":`<${a.join(", ")}>`,c=y[n]??n,l=`definePreview({ ${o.join(", ")} }).${c}${d}({ ${i.join(", ")} })`,p=0===r.length?"":`, and ${r.join("/")} was dropped`;return{edit:{start:e.getStart(),end:e.getEnd(),text:l},note:S(e.getStartLineNumber(),`${n}() was rewritten onto definePreview().${c}(); it now returns a PreviewFetchResult (check ok/data) and needs a real authorization for drafts${p}`)}}function P(e,t,n){return`import { ${t.join(", ")} } from ${e}${n}${e};`}var I={id:N,summary:"`fetchPreviewDocument`/`fetchPreviewGlobal` from the root → `definePreview().fetchDocument`/`.fetchGlobal` (payload-live-preview/server)",ledgerEntry:9,apply(e){const t=d(e).filter(e=>e.specifier===i&&e.imported in y);return 0===t.length?{edits:[],conflicts:[]}:function(e,t){const{Node:n}=r(),o=[],s=[],a=[];for(const i of t)if("require"!==i.kind)for(const t of p(e,i)){const e=t.node.getStartLineNumber(),r=t.node.getParent();if("reference"!==t.kind||!n.isCallExpression(r)||r.getExpression()!==t.node){o.push(S(e,`${i.local} is used other than as a direct call; rewrite it onto definePreview() by hand`));continue}const[d]=r.getArguments();if(void 0===d||!n.isObjectLiteralExpression(d)||d.getProperties().some(e=>n.isSpreadAssignment(e))){o.push(S(e,`${i.imported}() options are not a plain object literal, so serverURL/depth cannot be split out; rewrite it onto definePreview() by hand`));continue}const c=$(r,d,i.imported);a.push(c.edit),s.push(c.note)}else o.push(S(i.declaration.getStartLineNumber(),`${i.imported} is bound with require(); rewrite it onto definePreview() from ${w} by hand`));const d=e.getImportDeclarations().filter(e=>e.getModuleSpecifierValue()===w),c=m(e,"definePreview",d);return void 0!==c&&o.push(S(c.getStartLineNumber(),`this module already binds a definePreview that is not ${w}'s; rename it, then move the fetch helpers by hand`)),o.length>0?{edits:[],conflicts:[...o,...s]}:(a.push(...function(e,t){const{Node:n}=r(),o=[],s=/* @__PURE__ */new Set;for(const e of t)n.isImportDeclaration(e.declaration)&&s.add(e.declaration);const a=e.getImportDeclarations().find(e=>e.getModuleSpecifierValue()===w&&!e.isTypeOnly()),d=!0===a?.getNamedImports().some(e=>"definePreview"===e.getName());let c;if(void 0!==a&&!d){const e=a.getModuleSpecifier().getQuoteKind(),t=[...a.getNamedImports().map(e=>e.getText()),"definePreview"],n=a.getDefaultImport()?.getText(),i=void 0===n?t.join(", "):`${n}, { ${t.join(", ")} }`,r=void 0===n?P(e,t,w):`import ${i} from ${e}${w}${e};`;o.push({start:a.getStart(),end:a.getEnd(),text:r})}for(const t of s){const n=t.getModuleSpecifier().getQuoteKind(),r=t.getNamedImports().filter(e=>!(e.getName()in y)).map(e=>e.getText()),s=t.getDefaultImport()?.getText(),d=[s,0===r.length?void 0:`{ ${r.join(", ")} }`].filter(e=>void 0!==e),l=t.isTypeOnly()?"type ":"",u=0===d.length?"":`import ${l}${d.join(", ")} from ${n}${i}${n};`;if(void 0===a&&void 0===c)c=P(n,["definePreview"],w),o.push({start:t.getStart(),end:t.getEnd(),text:""===u?c:`${u}\n${c}`});else{const n=t.getEnd(),i=""===u&&"\n"===e.getFullText()[n]?1:0;o.push({start:t.getStart(),end:n+i,text:u})}}return o}(e,t)),{edits:a,conflicts:s})}(e,t)}},T="rename-bindings-authorized-option",E="authorized",k="authorization",D=`if they carry \`${E}\`, rename it to \`${k}\` and pass the verdict from authorizePreviewRequest()`,j={id:T,summary:"`createPreviewBindings({ authorized })` → `{ authorization }`",ledgerEntry:7,apply(e){const{Node:t}=r(),n=[],o=[],i=d(e).filter(e=>"createPreviewBindings"===e.imported);for(const r of i)for(const i of p(e,r)){const e=i.node.getParent();if("reference"!==i.kind||!t.isCallExpression(e))continue;if(e.getExpression()!==i.node)continue;const[r]=e.getArguments();if(void 0===r)continue;const s=r.getStartLineNumber();if(t.isObjectLiteralExpression(r))for(const e of r.getProperties())if(t.isSpreadAssignment(e))o.push({codemod:T,line:e.getStartLineNumber(),reason:`createPreviewBindings() spreads its options; ${D}`});else{if(u(e)!==E)continue;t.isShorthandPropertyAssignment(e)?n.push(h(e,`${k}: ${E}`)):t.isPropertyAssignment(e)&&n.push(h(e.getNameNode(),k))}else o.push({codemod:T,line:s,reason:`createPreviewBindings() options are not a literal; ${D}`})}return{edits:n,conflicts:o}}},L="rename-is-preview-request",A="isPreviewRequest",O="hasPreviewIntent";function K(e,t){return{codemod:L,reason:t,line:e}}function z(e){return e.aliased&&e.local===O?h(e.importedNode.getParentOrThrow(),O):h(e.importedNode,O)}var q={id:L,summary:"`isPreviewRequest()` → `hasPreviewIntent()` (same signature)",ledgerEntry:1,apply(e){const t=d(e).filter(e=>e.imported===A);return 0===t.length?{edits:[],conflicts:[]}:function(e,t){const n=[],o=[],i=m(t,O,e.map(e=>e.declaration));void 0!==i&&n.push(K(i.getStartLineNumber(),`this module already binds ${O}; rename it (or drop the wrapper and import the package's ${O} directly), then rename ${A} by hand`));for(const i of e)if(o.push(z(i)),!i.aliased)for(const e of p(t,i))"reference"===e.kind?o.push(h(e.node,O)):"shorthand"===e.kind?n.push(K(e.node.getStartLineNumber(),`{ ${A} } keeps the old key for whoever reads it; write { ${A}: ${O} } or rename the key and its readers by hand`)):n.push(K(e.node.getStartLineNumber(),`${A} is re-exported under its old name; rename the export and its importers, or write export { ${O} as ${A} }`));const s=function(e,t){const{Node:n,SyntaxKind:o}=r();return e.getDescendantsOfKind(o.Identifier).filter(e=>{const o=e.getParent();return e.getText()===t&&n.isPropertyAccessExpression(o)&&o.getNameNode()===e})}(t,A).map(e=>K(e.getStartLineNumber(),`.${A} is a member of this module's own object, not the package import, and was left alone; check that it does not wrap the removed API`));return n.length>0?{edits:[],conflicts:[...n,...s]}:{edits:o,conflicts:s}}(t,e)}},F={".ts":"ts",".mts":"ts",".cts":"ts",".tsx":"tsx",".js":"js",".mjs":"js",".cjs":"js",".jsx":"jsx"},R=/* @__PURE__ */new Set([".astro",".vue",".svelte"]),C=/^---\r?\n([\s\S]*?)\r?\n---/u,M=/<script(?:\s[^>]*)?>([\s\S]*?)<\/script\b[^>]*>/giu,V=/(?:\bfrom\s*|\bimport\s*\(?\s*|\brequire\s*\(\s*)['"]payload-live-preview(?:\/[^'"]*)?['"]/u;function B(e){return V.test(e)}var G=[q,j,I],Q=G;function U(e,t){let n=1;for(let o=0;o<t;o+=1)"\n"===e[o]&&(n+=1);return n}function J(e,t,n){const o=e.split("\n"),i=t.split("\n");let r=0;for(;r<o.length&&r<i.length&&o[r]===i[r];)r+=1;let s=0;for(;s<o.length-r&&s<i.length-r&&o[o.length-1-s]===i[i.length-1-s];)s+=1;const a=o.slice(r,o.length-s),d=i.slice(r,i.length-s),c=[];for(let e=0;e<Math.max(a.length,d.length);e+=1){const t=a[e]??"",o=d[e]??"";t!==o&&c.push({line:n+r+e,before:t,after:o})}return c}function W(e,n={}){const o=void 0===n.only?G:G.filter(e=>n.only?.includes(e.id));if(0===o.length||!B(e))return{output:e,edits:[],conflicts:[]};const i=/* @__PURE__ */new Map,r=[];let a="",d=0;for(const c of function(e,n){const o=t(n).toLowerCase();if(!R.has(o))return[{start:0,end:e.length,kind:F[o]??"ts"}];const i=[],r=".astro"===o?C.exec(e):null;if(void 0!==r?.[1]){const e=r.index+r[0].indexOf("\n")+1;i.push({start:e,end:e+r[1].length,kind:"ts"})}for(const t of e.matchAll(M)){const e=t[1]??"";if(""===e.trim())continue;const n=t.index+t[0].lastIndexOf(e);i.push({start:n,end:n+e.length,kind:"ts"})}return i}(e,n.fileName??"source.ts")){a+=e.slice(d,c.start);const t=U(e,c.start);let n=e.slice(c.start,c.end);for(const e of o){const o=e.apply(s(n,c.kind));for(const e of o.conflicts)r.push(void 0===e.line?e:{...e,line:e.line+t-1});if(0===o.edits.length)continue;const a=v(n,o.edits),d=i.get(e.id)??[];d.push(...J(n,a,t)),i.set(e.id,d),n=a}a+=n,d=c.end}return a+=e.slice(d),{output:a,edits:[...i].map(([e,t])=>({codemod:e,count:t.length,lines:t})),conflicts:r}}export{Q as CODEMODS,B as importsThisPackage,W as migrateSource};
|
|
1
|
+
import{createRequire as e}from"module";import{extname as t}from"path";var n,i,o="payload-live-preview";function r(){if(void 0===n)try{n=e(import.meta.url)("ts-morph")}catch(e){throw new Error("pll migrate needs ts-morph: npm install --save-dev ts-morph",{cause:e})}return n}function s(e,t){const n=r();return i??=new n.Project({useInMemoryFileSystem:!0,skipLoadingLibFiles:!0,skipFileDependencyResolution:!0,compilerOptions:{allowJs:!0,noLib:!0}}),i.createSourceFile(`/script.${t}`,e,{overwrite:!0})}function a(e){return e===o||e.startsWith(`${o}/`)}function d(e){const{Node:t,SyntaxKind:n}=r(),i=[];for(const t of e.getImportDeclarations()){const e=t.getModuleSpecifierValue();if(a(e))for(const n of t.getNamedImports()){const o=n.getAliasNode(),r=o??n.getNameNode();i.push({imported:n.getName(),local:r.getText(),specifier:e,kind:"import",importedNode:n.getNameNode(),aliased:void 0!==o,symbol:r.getSymbol(),declaration:t})}}for(const o of e.getDescendantsOfKind(n.VariableDeclaration)){const e=c(o.getInitializer()),n=o.getNameNode();if(void 0!==e&&a(e)&&t.isObjectBindingPattern(n))for(const r of n.getElements()){const n=r.getNameNode();if(!t.isIdentifier(n))continue;const s=r.getPropertyNameNode();i.push({imported:void 0===s?n.getText():l(s),local:n.getText(),specifier:e,kind:"require",importedNode:s??n,aliased:void 0!==s,symbol:n.getSymbol(),declaration:o})}}return i}function c(e){const{Node:t,SyntaxKind:n}=r(),i=void 0!==e&&t.isAwaitExpression(e)?e.getExpression():e;if(void 0===i||!t.isCallExpression(i))return;const o=i.getExpression();if((!t.isIdentifier(o)||"require"!==o.getText())&&o.getKind()!==n.ImportKeyword)return;const[s]=i.getArguments();return void 0!==s&&t.isStringLiteral(s)?s.getLiteralText():void 0}function l(e){const{Node:t}=r();return t.isStringLiteral(e)||t.isNoSubstitutionTemplateLiteral(e)?e.getLiteralText():e.getText()}function u(e){const{Node:t}=r();if(t.isSpreadAssignment(e))return;const n=e.getNameNode();return t.isComputedPropertyName(n)?void 0:l(n)}function p(e,t){const{Node:n,SyntaxKind:i}=r(),o=t.symbol?.compilerSymbol;if(void 0===o)return[];const s=e.getProject().getTypeChecker(),a=[];for(const r of e.getDescendantsOfKind(i.Identifier)){if(r.getText()!==t.local||f(r,t.declaration))continue;const e=r.getParent();n.isShorthandPropertyAssignment(e)?s.getShorthandAssignmentValueSymbol(e)?.compilerSymbol===o&&a.push({node:r,kind:"shorthand"}):n.isExportSpecifier(e)?e.getNameNode()===r&&e.getLocalTargetSymbol()?.compilerSymbol===o&&a.push({node:r,kind:"export"}):r.getSymbol()?.compilerSymbol===o&&a.push({node:r,kind:"reference"})}return a}function f(e,t){return void 0!==e.getFirstAncestor(e=>e===t)}function m(e,t,n=[]){const{SyntaxKind:i}=r();for(const o of e.getDescendantsOfKind(i.Identifier)){if(o.getText()!==t)continue;const e=o.getParent();if(g(e,o)&&!n.some(t=>t===e||f(e,t)))return e}}function g(e,t){const{Node:n}=r();return n.isVariableDeclaration(e)||n.isBindingElement(e)||n.isFunctionDeclaration(e)||n.isClassDeclaration(e)||n.isParameterDeclaration(e)||n.isEnumDeclaration(e)?e.getNameNode()===t:n.isImportSpecifier(e)?(e.getAliasNode()??e.getNameNode())===t:n.isImportClause(e)?e.getDefaultImport()===t:!!n.isNamespaceImport(e)&&e.getNameNode()===t}function h(e,t){return{start:e.getStart(),end:e.getEnd(),text:t}}function v(e,t){const n=[...t].sort((e,t)=>t.start-e.start);let i=e,o=Number.POSITIVE_INFINITY;for(const e of n){if(e.end>o)throw new Error("overlapping codemod edits");i=`${i.slice(0,e.start)}${e.text}${i.slice(e.end)}`,o=e.start}return i}var w="move-fetch-preview-helpers",y=`${o}/server`,$={fetchPreviewDocument:"fetchDocument",fetchPreviewGlobal:"fetchGlobal"},N=/* @__PURE__ */new Set(["serverURL","apiRoute","depth"]),b=/* @__PURE__ */new Set(["draft","fetchFn"]),x=["authorization","locale","headers","signal","errorMode"],S={fetchPreviewDocument:["collection","where",...x],fetchPreviewGlobal:["global",...x]};function P(e,t){return{codemod:w,reason:t,line:e}}function I(e,t,n){const i=[],o=[],r=[],s=/* @__PURE__ */new Set;for(const e of t.getProperties()){const t=u(e);void 0!==t&&s.add(t),void 0!==t&&N.has(t)?i.push(e.getText()):void 0!==t&&b.has(t)?r.push(t):o.push(e.getText())}s.has("depth")||i.push("depth: 1 /* TODO(pll migrate): the 1.x default; match the runtime mergeDepth */"),s.has("authorization")||o.push("authorization: null /* TODO(pll migrate): pass the verdict from authorizePreviewRequest(); null reads the published document */");const a=S[n]??[],d=[...s].filter(e=>!N.has(e)&&!b.has(e)&&!a.includes(e)),c=e.getTypeArguments().map(e=>e.getText()),l=0===c.length?"":`<${c.join(", ")}>`,p=$[n]??n,f=`definePreview({ ${i.join(", ")} }).${p}${l}({ ${o.join(", ")} })`,m=0===r.length?"":`, and ${r.join("/")} was dropped`,g=e.getStartLineNumber(),h=[P(g,`${n}() was rewritten onto definePreview().${p}(); it now returns a PreviewFetchResult (check ok/data) and needs a real authorization for drafts${m}`)];return d.length>0&&h.push(P(g,`${n}() was passed ${d.map(e=>`\`${e}\``).join(", ")}, which .${p}() does not accept; it takes ${a.join(", ")}. The key was carried over unchanged and will not compile — place it by hand`)),{edit:{start:e.getStart(),end:e.getEnd(),text:f},notes:h}}function T(e,t,n){return`import { ${t.join(", ")} } from ${e}${n}${e};`}var k={id:w,summary:"`fetchPreviewDocument`/`fetchPreviewGlobal` from the root → `definePreview().fetchDocument`/`.fetchGlobal` (payload-live-preview/server)",ledgerEntry:9,apply(e){const t=d(e).filter(e=>e.specifier===o&&e.imported in $);return 0===t.length?{edits:[],conflicts:[]}:function(e,t){const{Node:n}=r(),i=[],s=[],a=[];for(const o of t)if("require"!==o.kind)for(const t of p(e,o)){const e=t.node.getStartLineNumber(),r=t.node.getParent();if("reference"!==t.kind||!n.isCallExpression(r)||r.getExpression()!==t.node){i.push(P(e,`${o.local} is used other than as a direct call; rewrite it onto definePreview() by hand`));continue}const[d]=r.getArguments();if(void 0===d||!n.isObjectLiteralExpression(d)||d.getProperties().some(e=>n.isSpreadAssignment(e))){i.push(P(e,`${o.imported}() options are not a plain object literal, so serverURL/depth cannot be split out; rewrite it onto definePreview() by hand`));continue}const c=I(r,d,o.imported);a.push(c.edit),s.push(...c.notes)}else i.push(P(o.declaration.getStartLineNumber(),`${o.imported} is bound with require(); rewrite it onto definePreview() from ${y} by hand`));const d=e.getImportDeclarations().filter(e=>e.getModuleSpecifierValue()===y),c=m(e,"definePreview",d);return void 0!==c&&i.push(P(c.getStartLineNumber(),`this module already binds a definePreview that is not ${y}'s; rename it, then move the fetch helpers by hand`)),i.length>0?{edits:[],conflicts:[...i,...s]}:(a.push(...function(e,t){const{Node:n}=r(),i=[],s=/* @__PURE__ */new Set;for(const e of t)n.isImportDeclaration(e.declaration)&&s.add(e.declaration);const a=e.getImportDeclarations().find(e=>e.getModuleSpecifierValue()===y&&!e.isTypeOnly()),d=!0===a?.getNamedImports().some(e=>"definePreview"===e.getName());let c;if(void 0!==a&&!d){const e=a.getModuleSpecifier().getQuoteKind(),t=[...a.getNamedImports().map(e=>e.getText()),"definePreview"],n=a.getDefaultImport()?.getText(),o=void 0===n?t.join(", "):`${n}, { ${t.join(", ")} }`,r=void 0===n?T(e,t,y):`import ${o} from ${e}${y}${e};`;i.push({start:a.getStart(),end:a.getEnd(),text:r})}for(const t of s){const n=t.getModuleSpecifier().getQuoteKind(),r=t.getNamedImports().filter(e=>!(e.getName()in $)).map(e=>e.getText()),s=t.getDefaultImport()?.getText(),d=[s,0===r.length?void 0:`{ ${r.join(", ")} }`].filter(e=>void 0!==e),l=t.isTypeOnly()?"type ":"",u=0===d.length?"":`import ${l}${d.join(", ")} from ${n}${o}${n};`;if(void 0===a&&void 0===c)c=T(n,["definePreview"],y),i.push({start:t.getStart(),end:t.getEnd(),text:""===u?c:`${u}\n${c}`});else{const n=t.getEnd(),o=""===u&&"\n"===e.getFullText()[n]?1:0;i.push({start:t.getStart(),end:n+o,text:u})}}return i}(e,t)),{edits:a,conflicts:s})}(e,t)}},E="rename-admin-origins-option",L="hasPreviewIntent",j="adminOrigins",D="allowedOrigins",O=`if they carry \`${j}\`, rename it to \`${D}\``,A={id:E,summary:"`hasPreviewIntent(request, { adminOrigins })` → `{ allowedOrigins }`",ledgerEntry:13,apply(e){const{Node:t}=r(),n=[],i=[],o=d(e).filter(e=>e.imported===L);for(const r of o)for(const o of p(e,r)){const e=o.node.getParent();if("reference"!==o.kind||!t.isCallExpression(e))continue;if(e.getExpression()!==o.node)continue;const r=e.getArguments()[1];if(void 0===r)continue;const s=r.getStartLineNumber();if(!t.isObjectLiteralExpression(r)){i.push({codemod:E,line:s,reason:`${L}() options are not a literal; ${O}`});continue}const a=r.getProperties(),d=a.map(e=>u(e));if(d.includes(j)&&d.includes(D))i.push({codemod:E,line:s,reason:`${L}() is given both ${j} and ${D}; ${D} wins, drop ${j} by hand`});else for(const e of a)if(t.isSpreadAssignment(e))i.push({codemod:E,line:e.getStartLineNumber(),reason:`${L}() spreads its options; ${O}`});else{if(u(e)!==j)continue;t.isShorthandPropertyAssignment(e)?n.push(h(e,`${D}: ${j}`)):t.isPropertyAssignment(e)&&n.push(h(e.getNameNode(),D))}}return{edits:n,conflicts:i}}},z="rename-bindings-authorized-option",K="authorized",q="authorization",F=`if they carry \`${K}\`, rename it to \`${q}\` and pass the verdict from authorizePreviewRequest()`,R=`\`${q}\` takes the context from authorizePreviewRequest(); the boolean 1.x accepted is not. The key was renamed and its value left as it stands — pass the verdict, or \`null\` for a public response`,C={id:z,summary:"`createPreviewBindings({ authorized })` → `{ authorization }`",ledgerEntry:7,apply(e){const{Node:t}=r(),n=[],i=[],o=d(e).filter(e=>"createPreviewBindings"===e.imported);for(const r of o)for(const o of p(e,r)){const e=o.node.getParent();if("reference"!==o.kind||!t.isCallExpression(e))continue;if(e.getExpression()!==o.node)continue;const[r]=e.getArguments();if(void 0===r)continue;const s=r.getStartLineNumber();if(t.isObjectLiteralExpression(r))for(const e of r.getProperties())if(t.isSpreadAssignment(e))i.push({codemod:z,line:e.getStartLineNumber(),reason:`createPreviewBindings() spreads its options; ${F}`});else{if(u(e)!==K)continue;if(t.isShorthandPropertyAssignment(e))n.push(h(e,`${q}: ${K}`)),i.push({codemod:z,line:e.getStartLineNumber(),reason:R});else if(t.isPropertyAssignment(e)){const o=e.getInitializer();if(void 0!==o&&t.isFalseLiteral(o)){n.push(h(e,`${q}: null`));continue}n.push(h(e.getNameNode(),q)),i.push({codemod:z,line:e.getStartLineNumber(),reason:R})}}else i.push({codemod:z,line:s,reason:`createPreviewBindings() options are not a literal; ${F}`})}return{edits:n,conflicts:i}}},M="rename-is-preview-request",V="isPreviewRequest",B="hasPreviewIntent";function G(e,t){return{codemod:M,reason:t,line:e}}function Q(e){return e.aliased&&e.local===B?h(e.importedNode.getParentOrThrow(),B):h(e.importedNode,B)}var U={id:M,summary:"`isPreviewRequest()` → `hasPreviewIntent()` (same signature)",ledgerEntry:1,apply(e){const t=d(e).filter(e=>e.imported===V);return 0===t.length?{edits:[],conflicts:[]}:function(e,t){const n=[],i=[],o=m(t,B,e.map(e=>e.declaration));void 0!==o&&n.push(G(o.getStartLineNumber(),`this module already binds ${B}; rename it (or drop the wrapper and import the package's ${B} directly), then rename ${V} by hand`));for(const o of e)if(i.push(Q(o)),!o.aliased)for(const e of p(t,o))"reference"===e.kind?i.push(h(e.node,B)):"shorthand"===e.kind?n.push(G(e.node.getStartLineNumber(),`{ ${V} } keeps the old key for whoever reads it; write { ${V}: ${B} } or rename the key and its readers by hand`)):n.push(G(e.node.getStartLineNumber(),`${V} is re-exported under its old name; rename the export and its importers, or write export { ${B} as ${V} }`));const s=function(e,t){const{Node:n,SyntaxKind:i}=r();return e.getDescendantsOfKind(i.Identifier).filter(e=>{const i=e.getParent();return e.getText()===t&&n.isPropertyAccessExpression(i)&&i.getNameNode()===e})}(t,V).map(e=>G(e.getStartLineNumber(),`.${V} is a member of this module's own object, not the package import, and was left alone; check that it does not wrap the removed API`));return n.length>0?{edits:[],conflicts:[...n,...s]}:{edits:i,conflicts:s}}(t,e)}},J={".ts":"ts",".mts":"ts",".cts":"ts",".tsx":"tsx",".js":"js",".mjs":"js",".cjs":"js",".jsx":"jsx"},W=/* @__PURE__ */new Set([".astro",".vue",".svelte"]),Y=/^---\r?\n([\s\S]*?)\r?\n---/u,_=/<script(?:\s[^>]*)?>([\s\S]*?)<\/script\b[^>]*>/giu,H=/(?:\bfrom\s*|\bimport\s*\(?\s*|\brequire\s*\(\s*)['"]payload-live-preview(?:\/[^'"]*)?['"]/u;function X(e){return H.test(e)}var Z=[U,A,C,k],ee=Z;function te(e,t){let n=1;for(let i=0;i<t;i+=1)"\n"===e[i]&&(n+=1);return n}function ne(e,t,n){const i=e.split("\n"),o=t.split("\n");let r=0;for(;r<i.length&&r<o.length&&i[r]===o[r];)r+=1;let s=0;for(;s<i.length-r&&s<o.length-r&&i[i.length-1-s]===o[o.length-1-s];)s+=1;const a=i.slice(r,i.length-s),d=o.slice(r,o.length-s),c=[];for(let e=0;e<Math.max(a.length,d.length);e+=1){const t=a[e]??"",i=d[e]??"";t!==i&&c.push({line:n+r+e,before:t,after:i})}return c}function ie(e,n={}){const i=void 0===n.only?Z:Z.filter(e=>n.only?.includes(e.id));if(0===i.length||!X(e))return{output:e,edits:[],conflicts:[]};const o=/* @__PURE__ */new Map,r=[];let a="",d=0;for(const c of function(e,n){const i=t(n).toLowerCase();if(!W.has(i))return[{start:0,end:e.length,kind:J[i]??"ts"}];const o=[],r=".astro"===i?Y.exec(e):null;if(void 0!==r?.[1]){const e=r.index+r[0].indexOf("\n")+1;o.push({start:e,end:e+r[1].length,kind:"ts"})}for(const t of e.matchAll(_)){const e=t[1]??"";if(""===e.trim())continue;const n=t.index+t[0].lastIndexOf(e);o.push({start:n,end:n+e.length,kind:"ts"})}return o}(e,n.fileName??"source.ts")){a+=e.slice(d,c.start);const t=te(e,c.start);let n=e.slice(c.start,c.end);for(const e of i){const i=e.apply(s(n,c.kind));for(const e of i.conflicts)r.push(void 0===e.line?e:{...e,line:e.line+t-1});if(0===i.edits.length)continue;const a=v(n,i.edits),d=o.get(e.id)??[];d.push(...ne(n,a,t)),o.set(e.id,d),n=a}a+=n,d=c.end}return a+=e.slice(d),{output:a,edits:[...o].map(([e,t])=>({codemod:e,count:t.length,lines:t})),conflicts:r}}export{ee as CODEMODS,X as importsThisPackage,ie as migrateSource};
|
|
2
2
|
//# sourceMappingURL=migrate.js.map
|
package/dist/migrate.js.map
CHANGED
|
@@ -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","conflict","line","reason","codemod","rewriteCall","options","server","read","dropped","keys","getProperties","key","add","has","typeArguments","getTypeArguments","map","generic","length","join","method","droppedNote","note","getStartLineNumber","importLine","quote","names","moveFetchPreviewHelpers","id","summary","ledgerEntry","apply","bindings","filter","conflicts","blocking","notes","reference","isObjectLiteralExpression","rewritten","serverDeclaration","foreign","declarations","isImportDeclaration","serverImport","find","isTypeOnly","hasDefinePreview","serverLine","getModuleSpecifier","getQuoteKind","defaultImport","clauses","remaining","clause","typeOnly","kept","trailingNewline","getFullText","rewriteImports","plan","OLD_KEY","NEW_KEY","BY_HAND","renameBindingsAuthorizedOption","isPropertyAssignment","OLD_NAME","NEW_NAME","renameBinding","getParentOrThrow","renameIsPreviewRequest","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","includes","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-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']);\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 note: 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 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 return {\n edit: { start: call.getStart(), end: call.getEnd(), text },\n note: conflict(\n call.getStartLineNumber(),\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}\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.note);\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 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\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 } 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 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 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 { 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()`. */\nexport function importsThisPackage(source: string): boolean {\n return PACKAGE_REFERENCE.test(source);\n}\n\nconst IMPLEMENTATIONS: readonly CodemodImplementation[] = [\n renameIsPreviewRequest,\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 */\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,EAAQmB,iBAAiB,WAAWT,IAAQD,EAAM,CAAEW,WAAW,GACxE,CAEO,SAASC,EAA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hK,EAAYC,EAAM4O,EAAM3O,OACnD,UAAW0P,KAAQ/D,EAAK1B,UACtBA,EAAUrI,UACM,IAAd8N,EAAK1H,KAAqB0H,EAAO,IAAKA,EAAM1H,KAAM0H,EAAK1H,KAAOyF,EAAY,IAG9E,GAA0B,IAAtB9B,EAAK/E,MAAMqC,OAAc,SAC7B,MAAM0G,EAAOhJ,EAAe5G,EAAM4L,EAAK/E,OACjCgJ,EAAQpB,EAAUqB,IAAI3H,EAAQyB,KAAO,GAC3CiG,EAAMhO,QAAQ0L,EAAUvN,EAAM4P,EAAMlC,IACpCe,EAAUsB,IAAI5H,EAAQyB,GAAIiG,GAC1B7P,EAAO4P,CACT,CACA1I,GAAUlH,EACV2O,EAASC,EAAMlI,GACjB,CAGA,OAFAQ,GAAU8F,EAAOzF,MAAMoH,GAEhB,CAAEzH,SAAQL,MADH,IAAI4H,GAAWzF,IAAI,EAAEb,EAAS0H,MAAK,CAAS1H,UAAS6H,MAAOH,EAAM3G,OAAQ2G,WAChE3F,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","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","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 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,EAAQmB,iBAAiB,WAAWT,IAAQD,EAAM,CAAEW,WAAW,GACxE,CAEO,SAASC,EAAmBC,GACjC,OAAOA,IAAcrB,GAAgBqB,EAAUC,WAAW,GAAGtB,KAC/D,CAkBO,SAASuB,EAAgBC,GAC9B,MAAMC,KAAEA,EAAAC,WAAMA,GAAezB,IACvB0B,EAAwB,GAC9B,UAAWC,KAAeJ,EAAOK,wBAAyB,CACxD,MAAMR,EAAYO,EAAYE,0BAC9B,GAAKV,EAAmBC,GACxB,UAAWU,KAAQH,EAAYI,kBAAmB,CAChD,MAAMC,EAAQF,EAAKG,eACbC,EAAYF,GAASF,EAAKK,cAChCT,EAAIU,KAAK,CACPC,SAAUP,EAAKQ,UACfC,MAAOL,EAAUM,UACjBpB,YACAZ,KAAM,SACNiC,aAAcX,EAAKK,cACnBO,aAAmB,IAAVV,EACTW,OAAQT,EAAUU,YAClBjB,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B,KAAhBE,EAAKC,OAAe,SACxB,MAAMzJ,EAAQsJ,EAAM9B,MAAQ8B,EAAM,GAAGI,YAAYF,GACjDN,EAAO7N,KAAK,CAAE2E,QAAOE,IAAKF,EAAQwJ,EAAKxG,OAAQvJ,KAAM,MACvD,CACA,OAAOyP,CACT,CC4EsBS,CAAazC,EAAQnF,EAAQ+G,UAAY,aAAc,CACzEpI,GAAUwG,EAAOnG,MAAM6H,EAAQC,EAAM7I,OACrC,MAAM4H,EAAYN,GAAaJ,EAAQ2B,EAAM7I,OAC7C,IAAIxG,EAAO0N,EAAOnG,MAAM8H,EAAM7I,MAAO6I,EAAM3I,KAC3C,UAAW2B,KAAW2G,EAAQ,CAC5B,MAAMhD,EAAO3D,EAAQgC,MAAMtK,EAAYC,EAAMqP,EAAMpP,OACnD,UAAWmQ,KAAQpE,EAAKzB,UACtBA,EAAU1I,UACM,IAAduO,EAAKjI,KAAqBiI,EAAO,IAAKA,EAAMjI,KAAMiI,EAAKjI,KAAOiG,EAAY,IAG9E,GAA0B,IAAtBpC,EAAKnF,MAAM2C,OAAc,SAC7B,MAAM6G,EAAOzJ,EAAe5G,EAAMgM,EAAKnF,OACjCyJ,EAAQpB,EAAUqB,IAAIlI,EAAQ6B,KAAO,GAC3CoG,EAAMzO,QAAQoM,GAAUjO,EAAMqQ,EAAMjC,IACpCc,EAAUsB,IAAInI,EAAQ6B,GAAIoG,GAC1BtQ,EAAOqQ,CACT,CACAnJ,GAAUlH,EACVoP,EAASC,EAAM3I,GACjB,CAGA,OAFAQ,GAAUwG,EAAOnG,MAAM6H,GAEhB,CAAElI,SAAQL,MADH,IAAIqI,GAAW5F,IAAI,EAAEjB,EAASiI,MAAK,CAASjI,UAASoI,MAAOH,EAAM9G,OAAQ8G,WAChE/F,YAC1B,Q","ignoreList":[]}
|
|
@@ -4,6 +4,10 @@
|
|
|
4
4
|
* one side — the adapter's request decision or the browser runtime — and a
|
|
5
5
|
* test asserts the profile assigns every readiness row that has an option, so
|
|
6
6
|
* a row added later cannot be forgotten. See ADR 0007.
|
|
7
|
+
*
|
|
8
|
+
* It lives in the leaf `types` domain, like `merge-depth.ts`, because the
|
|
9
|
+
* inline generator resolves the profile too, and the generator is server-side
|
|
10
|
+
* code that may not reach the browser runtime in `core`.
|
|
7
11
|
*/
|
|
8
12
|
/** `'v2'` is the 2.0 default; `'v1'` is the 1.x table. */
|
|
9
13
|
type DefaultsProfile = 'v1' | 'v2';
|
|
@@ -97,7 +101,9 @@ interface PreviewRequestOptions {
|
|
|
97
101
|
readonly signals?: readonly PreviewSignal[];
|
|
98
102
|
/** Query parameters (value `true` or `1`) that signal intent. Default `['preview', 'draft', 'livePreview']`. */
|
|
99
103
|
readonly queryParams?: readonly string[];
|
|
100
|
-
/** Admin origins whose Referer signals intent, e.g. `['https://cms.example.com']
|
|
104
|
+
/** Admin origins whose Referer signals intent, e.g. `['https://cms.example.com']` — the adapters' option of the same name. */
|
|
105
|
+
readonly allowedOrigins?: readonly string[];
|
|
106
|
+
/** @deprecated Use `allowedOrigins`; removed in 3.0. Ignored when `allowedOrigins` is given. */
|
|
101
107
|
readonly adminOrigins?: readonly string[];
|
|
102
108
|
}
|
|
103
109
|
/** The request surface the predicate reads; `Request` satisfies it, Nitro/H3 events need a shim. */
|
|
@@ -110,6 +116,27 @@ interface PreviewRequestLike {
|
|
|
110
116
|
/** Whether `request` carries live-preview intent. Intent, not authorization. */
|
|
111
117
|
declare function hasPreviewIntent(request: PreviewRequestLike, options?: PreviewRequestOptions): boolean;
|
|
112
118
|
|
|
119
|
+
/**
|
|
120
|
+
* The inline script's configuration and its positional wire order: the
|
|
121
|
+
* generator writes the tuple, `src/core/runtime.ts` destructures it, and
|
|
122
|
+
* `INLINE_CONFIG_KEYS` is where they agree. Append only, never reorder.
|
|
123
|
+
*/
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* A runtime build this package produces. `source` is the IIFE the page runs;
|
|
127
|
+
* the two digests describe the same bytes as a servable asset, so asset
|
|
128
|
+
* delivery can hash-name and SRI-verify whichever artifact was chosen without
|
|
129
|
+
* hashing anything at request time.
|
|
130
|
+
*/
|
|
131
|
+
interface RuntimeArtifact {
|
|
132
|
+
readonly profile: 'lean';
|
|
133
|
+
readonly source: string;
|
|
134
|
+
/** Short content hash, for the asset's file name. */
|
|
135
|
+
readonly contentHash: string;
|
|
136
|
+
/** `sha384-…`, for the bootstrap's `integrity` attribute. */
|
|
137
|
+
readonly integrity: string;
|
|
138
|
+
}
|
|
139
|
+
|
|
113
140
|
/**
|
|
114
141
|
* The options every framework adapter shares. Each adapter's public interface
|
|
115
142
|
* extends this with its request type, so the JSDoc lives here once. Defaults
|
|
@@ -170,6 +197,67 @@ interface PreviewAdapterOptions<Req = Request> {
|
|
|
170
197
|
readonly skipUnchanged?: boolean;
|
|
171
198
|
/** Scroll the preview to the field being edited. Default `false`. */
|
|
172
199
|
readonly revealEditedField?: boolean;
|
|
200
|
+
/**
|
|
201
|
+
* How the runtime reaches the page. `'inline'` (default) puts it in the
|
|
202
|
+
* response: nothing to mount, nothing to cache. `'asset'` injects a few
|
|
203
|
+
* hundred bytes of bootstrap instead, which fetches the runtime as a
|
|
204
|
+
* content-hashed, SRI-verified file — `immutable` for a year, so every
|
|
205
|
+
* further preview page pays nothing for it. It needs the asset route
|
|
206
|
+
* mounted; each adapter's page says where. (Astro publishes that file from
|
|
207
|
+
* its own build instead: `mode: 'loader'` there.)
|
|
208
|
+
*/
|
|
209
|
+
readonly delivery?: 'inline' | 'asset';
|
|
210
|
+
/**
|
|
211
|
+
* Where that asset route is mounted, as an absolute path. Default
|
|
212
|
+
* `/payload-live-preview`. Set it when the app is not served from the site
|
|
213
|
+
* root, so the bootstrap requests the path the framework actually routes.
|
|
214
|
+
*/
|
|
215
|
+
readonly assetPath?: string;
|
|
216
|
+
/**
|
|
217
|
+
* A runtime artifact to inject instead of the full one — `LEAN_RUNTIME` from
|
|
218
|
+
* `payload-live-preview/lean`, which is about 5.5 KB gzip smaller and reports
|
|
219
|
+
* LP0104 when a page needs a feature it left out (docs/options.md). Importing
|
|
220
|
+
* it is what puts those bytes in your build; the default costs nothing.
|
|
221
|
+
*/
|
|
222
|
+
readonly runtime?: RuntimeArtifact;
|
|
223
|
+
/**
|
|
224
|
+
* Server-rendered fragment boundaries (ADR 0011): the same-origin path of
|
|
225
|
+
* the route exporting `createFragmentEndpoint()`. The runtime then renders
|
|
226
|
+
* every `data-payload-fragment` boundary through it, and its prelude carries
|
|
227
|
+
* the route strategy as well. Default: none, and boundaries are patched.
|
|
228
|
+
*/
|
|
229
|
+
readonly fragments?: {
|
|
230
|
+
readonly endpoint: string;
|
|
231
|
+
};
|
|
232
|
+
/**
|
|
233
|
+
* Carry the route strategy: a binding in `<head>` or one marked
|
|
234
|
+
* `data-payload-strategy="route"` then refreshes the route. Implied by
|
|
235
|
+
* `fragments`, whose prelude already contains it. Default `false`.
|
|
236
|
+
*/
|
|
237
|
+
readonly routeStrategy?: boolean;
|
|
238
|
+
/**
|
|
239
|
+
* The 2.0 name for `onUnfaithfulPatch`, kept until 3.0. `'route'` means
|
|
240
|
+
* `'escalate'`, `'ignore'` means `'ignore'`.
|
|
241
|
+
*
|
|
242
|
+
* @deprecated Renamed to `onUnfaithfulPatch`.
|
|
243
|
+
*/
|
|
244
|
+
readonly onUnboundChange?: 'ignore' | 'route';
|
|
245
|
+
/**
|
|
246
|
+
* What to do when the runtime knows a patch cannot reach what the server
|
|
247
|
+
* would have drawn — a value no renderer can represent, a Lexical block whose
|
|
248
|
+
* markup the write drops, a changed field with no binding at all.
|
|
249
|
+
* `'escalate'` (the default) has a server draw the region instead, so it
|
|
250
|
+
* needs `routeStrategy` or `fragments` to do anything. `'warn'` reports
|
|
251
|
+
* LP0411 and keeps the patch; `'ignore'` keeps it silently.
|
|
252
|
+
*/
|
|
253
|
+
readonly onUnfaithfulPatch?: 'ignore' | 'warn' | 'escalate';
|
|
254
|
+
/**
|
|
255
|
+
* Find bindings by value on the connection's first message (ADR 0014): a
|
|
256
|
+
* scalar whose value is the whole content of exactly one element is bound
|
|
257
|
+
* to it as if `data-payload-field` stood there; a declared attribute always
|
|
258
|
+
* wins and `data-payload-no-bind` keeps a subtree out. Default `'off'`.
|
|
259
|
+
*/
|
|
260
|
+
readonly autoBind?: 'off' | 'unique';
|
|
173
261
|
/** Patch only the bindings of the document an update names (`data-payload-owner`). Default `false`. */
|
|
174
262
|
readonly scopeBindingsByOwner?: boolean;
|
|
175
263
|
/** Sanitizer for rich text and HTML writes. Default `'strict'`; `defaults: 'v1'` restores `'compat'`. */
|
|
@@ -194,4 +282,4 @@ interface PreviewAdapterOptions<Req = Request> {
|
|
|
194
282
|
readonly defaults?: DefaultsProfile;
|
|
195
283
|
}
|
|
196
284
|
|
|
197
|
-
export { type
|
|
285
|
+
export { type AuthorizedPreviewContext as A, type PreviewAdapterOptions as P, type PreviewRequestLike as a, type PreviewRequestOptions as b, type PreviewSignal as c, type PreviewAuthorizationOutcome as d, type PreviewAuthorizationRequest as e, type AuthorizedPreviewScope as f, hasPreviewIntent as h };
|