create-payload-app 3.0.0-beta.0 → 3.0.0-beta.1

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.
@@ -6,6 +6,7 @@ type InitNextArgs = Pick<CliArgs, '--debug'> & {
6
6
  projectDir: string;
7
7
  useDistFiles?: boolean;
8
8
  };
9
+ type NextConfigType = 'cjs' | 'esm';
9
10
  type InitNextResult = {
10
11
  isSrcDir: boolean;
11
12
  nextAppDir: string;
@@ -23,6 +24,7 @@ type NextAppDetails = {
23
24
  isSrcDir: boolean;
24
25
  nextAppDir?: string;
25
26
  nextConfigPath?: string;
27
+ nextConfigType?: NextConfigType;
26
28
  };
27
29
  export declare function getNextAppDetails(projectDir: string): Promise<NextAppDetails>;
28
30
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"init-next.d.ts","sourceRoot":"","sources":["../../src/lib/init-next.ts"],"names":[],"mappings":"AAkBA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAOlE,KAAK,YAAY,GAAG,IAAI,CAAC,OAAO,EAAE,SAAS,CAAC,GAAG;IAC7C,MAAM,EAAE,MAAM,CAAA;IACd,cAAc,CAAC,EAAE,cAAc,CAAA;IAC/B,cAAc,EAAE,cAAc,CAAA;IAC9B,UAAU,EAAE,MAAM,CAAA;IAClB,YAAY,CAAC,EAAE,OAAO,CAAA;CACvB,CAAA;AAED,KAAK,cAAc,GACf;IACE,QAAQ,EAAE,OAAO,CAAA;IACjB,UAAU,EAAE,MAAM,CAAA;IAClB,iBAAiB,EAAE,MAAM,CAAA;IACzB,OAAO,EAAE,IAAI,CAAA;CACd,GACD;IAAE,QAAQ,EAAE,OAAO,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,KAAK,CAAA;CAAE,CAAA;AAE9E,wBAAsB,QAAQ,CAAC,IAAI,EAA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AU,CAAC,EAAE,MAAM,CAAA;IACnB,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB,cAAc,CAAC,EAAE,cAAc,CAAA;CAChC,CAAA;AAED,wBAAsB,iBAAiB,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,CAAC,CAkCnF"}
@@ -2,6 +2,7 @@ import * as p from '@clack/prompts';
2
2
  import { parse, stringify } from 'comment-json';
3
3
  import execa from 'execa';
4
4
  import fs from 'fs';
5
+ import fse from 'fs-extra';
5
6
  import globby from 'globby';
6
7
  import path from 'path';
7
8
  import { promisify } from 'util';
@@ -17,11 +18,20 @@ import { wrapNextConfig } from './wrap-next-config.js';
17
18
  export async function initNext(args) {
18
19
  const { dbType: dbType, packageManager, projectDir } = args;
19
20
  const nextAppDetails = args.nextAppDetails || await getNextAppDetails(projectDir);
20
- const { hasTopLevelLayout, isSrcDir, nextAppDir } = nextAppDetails || await getNextAppDetails(projectDir);
21
- if (!nextAppDir) {
21
+ if (!nextAppDetails.nextAppDir) {
22
+ warning(`Could not find app directory in ${projectDir}, creating...`);
23
+ const createdAppDir = path.resolve(projectDir, nextAppDetails.isSrcDir ? 'src/app' : 'app');
24
+ fse.mkdirSync(createdAppDir, {
25
+ recursive: true
26
+ });
27
+ nextAppDetails.nextAppDir = createdAppDir;
28
+ }
29
+ const { hasTopLevelLayout, isSrcDir, nextAppDir, nextConfigType } = nextAppDetails;
30
+ if (!nextConfigType) {
22
31
  return {
23
32
  isSrcDir,
24
- reason: `Could not find app directory in ${projectDir}`,
33
+ nextAppDir,
34
+ reason: `Could not determine Next Config type in ${projectDir}. Possibly try renaming next.config.js to next.config.cjs or next.config.mjs.`,
25
35
  success: false
26
36
  };
27
37
  }
@@ -43,6 +53,7 @@ export async function initNext(args) {
43
53
  const configurationResult = installAndConfigurePayload({
44
54
  ...args,
45
55
  nextAppDetails,
56
+ nextConfigType,
46
57
  useDistFiles: true
47
58
  });
48
59
  if (configurationResult.success === false) {
@@ -75,6 +86,11 @@ export async function initNext(args) {
75
86
  }
76
87
  async function addPayloadConfigToTsConfig(projectDir, isSrcDir) {
77
88
  const tsConfigPath = path.resolve(projectDir, 'tsconfig.json');
89
+ // Check if tsconfig.json exists
90
+ if (!fs.existsSync(tsConfigPath)) {
91
+ warning(`Could not find tsconfig.json to add @payload-config path.`);
92
+ return;
93
+ }
78
94
  const userTsConfigContent = await readFile(tsConfigPath, {
79
95
  encoding: 'utf8'
80
96
  });
@@ -95,7 +111,7 @@ async function addPayloadConfigToTsConfig(projectDir, isSrcDir) {
95
111
  }
96
112
  }
97
113
  function installAndConfigurePayload(args) {
98
- const { '--debug': debug, nextAppDetails: { isSrcDir, nextAppDir, nextConfigPath } = {}, projectDir, useDistFiles } = args;
114
+ const { '--debug': debug, nextAppDetails: { isSrcDir, nextAppDir, nextConfigPath } = {}, nextConfigType, projectDir, useDistFiles } = args;
99
115
  if (!nextAppDir || !nextConfigPath) {
100
116
  return {
101
117
  reason: 'Could not find app directory or next.config.js',
@@ -127,12 +143,14 @@ function installAndConfigurePayload(args) {
127
143
  logDebug(`nextAppDir: ${nextAppDir}`);
128
144
  logDebug(`projectDir: ${projectDir}`);
129
145
  logDebug(`nextConfigPath: ${nextConfigPath}`);
146
+ logDebug(`payloadConfigPath: ${path.resolve(projectDir, 'payload.config.ts')}`);
130
147
  logDebug(`isSrcDir: ${isSrcDir}. source: ${templateSrcDir}. dest: ${path.dirname(nextConfigPath)}`);
131
148
  // This is a little clunky and needs to account for isSrcDir
132
149
  copyRecursiveSync(templateSrcDir, path.dirname(nextConfigPath), debug);
133
150
  // Wrap next.config.js with withPayload
134
151
  wrapNextConfig({
135
- nextConfigPath
152
+ nextConfigPath,
153
+ nextConfigType
136
154
  });
137
155
  return {
138
156
  payloadConfigPath: path.resolve(nextAppDir, '../payload.config.ts'),
@@ -144,8 +162,8 @@ async function installDeps(projectDir, packageManager, dbType) {
144
162
  'payload',
145
163
  '@payloadcms/next',
146
164
  '@payloadcms/richtext-lexical'
147
- ].map((pkg)=>`${pkg}@alpha`);
148
- packagesToInstall.push(`@payloadcms/db-${dbType}@alpha`);
165
+ ].map((pkg)=>`${pkg}@beta`);
166
+ packagesToInstall.push(`@payloadcms/db-${dbType}@beta`);
149
167
  let exitCode = 0;
150
168
  switch(packageManager){
151
169
  case 'npm':
@@ -204,18 +222,40 @@ export async function getNextAppDetails(projectDir) {
204
222
  ], {
205
223
  absolute: true,
206
224
  cwd: projectDir,
225
+ ignore: [
226
+ '**/node_modules/**'
227
+ ],
207
228
  onlyDirectories: true
208
229
  }))?.[0];
209
230
  if (!nextAppDir || nextAppDir.length === 0) {
210
231
  nextAppDir = undefined;
211
232
  }
233
+ const configType = await getProjectType(projectDir, nextConfigPath);
212
234
  const hasTopLevelLayout = nextAppDir ? fs.existsSync(path.resolve(nextAppDir, 'layout.tsx')) : false;
213
235
  return {
214
236
  hasTopLevelLayout,
215
237
  isSrcDir,
216
238
  nextAppDir,
217
- nextConfigPath
239
+ nextConfigPath,
240
+ nextConfigType: configType
218
241
  };
219
242
  }
243
+ async function getProjectType(projectDir, nextConfigPath) {
244
+ if (nextConfigPath.endsWith('.mjs')) {
245
+ return 'esm';
246
+ }
247
+ if (nextConfigPath.endsWith('.cjs')) {
248
+ return 'cjs';
249
+ }
250
+ const packageObj = await fse.readJson(path.resolve(projectDir, 'package.json'));
251
+ const packageJsonType = packageObj.type;
252
+ if (packageJsonType === 'module') {
253
+ return 'esm';
254
+ }
255
+ if (packageJsonType === 'commonjs') {
256
+ return 'cjs';
257
+ }
258
+ return 'cjs';
259
+ }
220
260
 
221
261
  //# sourceMappingURL=init-next.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/lib/init-next.ts"],"sourcesContent":["import type { CompilerOptions } from 'typescript'\n\nimport * as p from '@clack/prompts'\nimport { parse, stringify } from 'comment-json'\nimport execa from 'execa'\nimport fs from 'fs'\nimport globby from 'globby'\nimport path from 'path'\nimport { promisify } from 'util'\n\nconst readFile = promisify(fs.readFile)\nconst writeFile = promisify(fs.writeFile)\n\nconst filename = fileURLToPath(import.meta.url)\nconst dirname = path.dirname(filename)\n\nimport { fileURLToPath } from 'node:url'\n\nimport type { CliArgs, DbType, PackageManager } from '../types.js'\n\nimport { copyRecursiveSync } from '../utils/copy-recursive-sync.js'\nimport { debug as origDebug, warning } from '../utils/log.js'\nimport { moveMessage } from '../utils/messages.js'\nimport { wrapNextConfig } from './wrap-next-config.js'\n\ntype InitNextArgs = Pick<CliArgs, '--debug'> & {\n dbType: DbType\n nextAppDetails?: NextAppDetails\n packageManager: PackageManager\n projectDir: string\n useDistFiles?: boolean\n}\n\ntype InitNextResult =\n | {\n isSrcDir: boolean\n nextAppDir: string\n payloadConfigPath: string\n success: true\n }\n | { isSrcDir: boolean; nextAppDir?: string; reason: string; success: false }\n\nexport async function initNext(args: InitNextArgs): Promise<InitNextResult> {\n const { dbType: dbType, packageManager, projectDir } = args\n\n const nextAppDetails = args.nextAppDetails || (await getNextAppDetails(projectDir))\n\n const { hasTopLevelLayout, isSrcDir, nextAppDir } =\n nextAppDetails || (await getNextAppDetails(projectDir))\n\n if (!nextAppDir) {\n return { isSrcDir, reason: `Could not find app directory in ${projectDir}`, success: false }\n }\n\n if (hasTopLevelLayout) {\n // Output directions for user to move all files from app to top-level directory named `(app)`\n p.log.warn(moveMessage({ nextAppDir, projectDir }))\n return {\n isSrcDir,\n nextAppDir,\n reason: 'Found existing layout.tsx in app directory',\n success: false,\n }\n }\n\n const installSpinner = p.spinner()\n installSpinner.start('Installing Payload and dependencies...')\n\n const configurationResult = installAndConfigurePayload({\n ...args,\n nextAppDetails,\n useDistFiles: true, // Requires running 'pnpm pack-template-files' in cpa\n })\n\n if (configurationResult.success === false) {\n installSpinner.stop(configurationResult.reason, 1)\n return { ...configurationResult, isSrcDir, success: false }\n }\n\n const { success: installSuccess } = await installDeps(projectDir, packageManager, dbType)\n if (!installSuccess) {\n installSpinner.stop('Failed to install dependencies', 1)\n return {\n ...configurationResult,\n isSrcDir,\n reason: 'Failed to install dependencies',\n success: false,\n }\n }\n\n // Add `@payload-config` to tsconfig.json `paths`\n await addPayloadConfigToTsConfig(projectDir, isSrcDir)\n installSpinner.stop('Successfully installed Payload and dependencies')\n return { ...configurationResult, isSrcDir, nextAppDir, success: true }\n}\n\nasync function addPayloadConfigToTsConfig(projectDir: string, isSrcDir: boolean) {\n const tsConfigPath = path.resolve(projectDir, 'tsconfig.json')\n const userTsConfigContent = await readFile(tsConfigPath, {\n encoding: 'utf8',\n })\n const userTsConfig = parse(userTsConfigContent) as {\n compilerOptions?: CompilerOptions\n }\n if (!userTsConfig.compilerOptions && !('extends' in userTsConfig)) {\n userTsConfig.compilerOptions = {}\n }\n\n if (\n !userTsConfig.compilerOptions?.paths?.['@payload-config'] &&\n userTsConfig.compilerOptions?.paths\n ) {\n userTsConfig.compilerOptions.paths = {\n ...(userTsConfig.compilerOptions.paths || {}),\n '@payload-config': [`./${isSrcDir ? 'src/' : ''}payload.config.ts`],\n }\n await writeFile(tsConfigPath, stringify(userTsConfig, null, 2), { encoding: 'utf8' })\n }\n}\n\nfunction installAndConfigurePayload(\n args: InitNextArgs & { nextAppDetails: NextAppDetails; useDistFiles?: boolean },\n):\n | { payloadConfigPath: string; success: true }\n | { payloadConfigPath?: string; reason: string; success: false } {\n const {\n '--debug': debug,\n nextAppDetails: { isSrcDir, nextAppDir, nextConfigPath } = {},\n projectDir,\n useDistFiles,\n } = args\n\n if (!nextAppDir || !nextConfigPath) {\n return {\n reason: 'Could not find app directory or next.config.js',\n success: false,\n }\n }\n\n const logDebug = (message: string) => {\n if (debug) origDebug(message)\n }\n\n if (!fs.existsSync(projectDir)) {\n return {\n reason: `Could not find specified project directory at ${projectDir}`,\n success: false,\n }\n }\n\n const templateFilesPath =\n dirname.endsWith('dist') || useDistFiles\n ? path.resolve(dirname, '../..', 'dist/template')\n : path.resolve(dirname, '../../../../templates/blank-3.0')\n\n logDebug(`Using template files from: ${templateFilesPath}`)\n\n if (!fs.existsSync(templateFilesPath)) {\n return {\n reason: `Could not find template source files from ${templateFilesPath}`,\n success: false,\n }\n } else {\n logDebug('Found template source files')\n }\n\n logDebug(`Copying template files from ${templateFilesPath} to ${nextAppDir}`)\n\n const templateSrcDir = path.resolve(templateFilesPath, isSrcDir ? '' : 'src')\n\n logDebug(`templateSrcDir: ${templateSrcDir}`)\n logDebug(`nextAppDir: ${nextAppDir}`)\n logDebug(`projectDir: ${projectDir}`)\n logDebug(`nextConfigPath: ${nextConfigPath}`)\n\n logDebug(\n `isSrcDir: ${isSrcDir}. source: ${templateSrcDir}. dest: ${path.dirname(nextConfigPath)}`,\n )\n\n // This is a little clunky and needs to account for isSrcDir\n copyRecursiveSync(templateSrcDir, path.dirname(nextConfigPath), debug)\n\n // Wrap next.config.js with withPayload\n wrapNextConfig({ nextConfigPath })\n\n return {\n payloadConfigPath: path.resolve(nextAppDir, '../payload.config.ts'),\n success: true,\n }\n}\n\nasync function installDeps(projectDir: string, packageManager: PackageManager, dbType: DbType) {\n const packagesToInstall = ['payload', '@payloadcms/next', '@payloadcms/richtext-lexical'].map(\n (pkg) => `${pkg}@alpha`,\n )\n\n packagesToInstall.push(`@payloadcms/db-${dbType}@alpha`)\n\n let exitCode = 0\n switch (packageManager) {\n case 'npm': {\n ;({ exitCode } = await execa('npm', ['install', '--save', ...packagesToInstall], {\n cwd: projectDir,\n }))\n break\n }\n case 'yarn':\n case 'pnpm': {\n ;({ exitCode } = await execa(packageManager, ['add', ...packagesToInstall], {\n cwd: projectDir,\n }))\n break\n }\n case 'bun': {\n warning('Bun support is untested.')\n ;({ exitCode } = await execa('bun', ['add', ...packagesToInstall], { cwd: projectDir }))\n break\n }\n }\n\n return { success: exitCode === 0 }\n}\n\ntype NextAppDetails = {\n hasTopLevelLayout: boolean\n isSrcDir: boolean\n nextAppDir?: string\n nextConfigPath?: string\n}\n\nexport async function getNextAppDetails(projectDir: string): Promise<NextAppDetails> {\n const isSrcDir = fs.existsSync(path.resolve(projectDir, 'src'))\n\n const nextConfigPath: string | undefined = (\n await globby('next.config.*js', { absolute: true, cwd: projectDir })\n )?.[0]\n if (!nextConfigPath || nextConfigPath.length === 0) {\n return {\n hasTopLevelLayout: false,\n isSrcDir,\n nextConfigPath: undefined,\n }\n }\n\n let nextAppDir: string | undefined = (\n await globby(['**/app'], {\n absolute: true,\n cwd: projectDir,\n onlyDirectories: true,\n })\n )?.[0]\n\n if (!nextAppDir || nextAppDir.length === 0) {\n nextAppDir = undefined\n }\n\n const hasTopLevelLayout = nextAppDir\n ? fs.existsSync(path.resolve(nextAppDir, 'layout.tsx'))\n : false\n\n return { hasTopLevelLayout, isSrcDir, nextAppDir, nextConfigPath }\n}\n"],"names":["p","parse","stringify","execa","fs","globby","path","promisify","readFile","writeFile","filename","fileURLToPath","url","dirname","copyRecursiveSync","debug","origDebug","warning","moveMessage","wrapNextConfig","initNext","args","dbType","packageManager","projectDir","nextAppDetails","getNextAppDetails","hasTopLevelLayout","isSrcDir","nextAppDir","reason","success","log","warn","installSpinner","spinner","start","configurationResult","installAndConfigurePayload","useDistFiles","stop","installSuccess","installDeps","addPayloadConfigToTsConfig","tsConfigPath","resolve","userTsConfigContent","encoding","userTsConfig","compilerOptions","paths","nextConfigPath","logDebug","message","existsSync","templateFilesPath","endsWith","templateSrcDir","payloadConfigPath","packagesToInstall","map","pkg","push","exitCode","cwd","absolute","length","undefined","onlyDirectories"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAEA,YAAYA,OAAO,iBAAgB;AACnC,SAASC,KAAK,EAAEC,SAAS,QAAQ,eAAc;AAC/C,OAAOC,WAAW,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IAEA,IAAItC,aACF,CAAA,MAAMxB,OAAO;QAAC;KAAS,EAAE;QACvB4D,UAAU;QACVD,KAAKxC;QACL4C,iBAAiB;IACnB,EAAC,GACA,CAAC,EAAE;IAEN,IAAI,CAACvC,cAAcA,WAAWqC,MAAM,KAAK,GAAG;QAC1CrC,aAAasC;IACf;IAEA,MAAMxC,oBAAoBE,aACtBzB,GAAGkD,UAAU,CAAChD,KAAKuC,OAAO,CAAChB,YAAY,iBACvC;IAEJ,OAAO;QAAEF;QAAmBC;QAAUC;QAAYsB;IAAe;AACnE"}
1
+ {"version":3,"sources":["../../src/lib/init-next.ts"],"sourcesContent":["import type { CompilerOptions } from 'typescript'\n\nimport * as p from '@clack/prompts'\nimport { parse, stringify } from 'comment-json'\nimport execa from 'execa'\nimport fs from 'fs'\nimport fse from 'fs-extra'\nimport globby from 'globby'\nimport path from 'path'\nimport { promisify } from 'util'\n\nconst readFile = promisify(fs.readFile)\nconst writeFile = promisify(fs.writeFile)\n\nconst filename = fileURLToPath(import.meta.url)\nconst dirname = path.dirname(filename)\n\nimport { fileURLToPath } from 'node:url'\n\nimport type { CliArgs, DbType, PackageManager } from '../types.js'\n\nimport { copyRecursiveSync } from '../utils/copy-recursive-sync.js'\nimport { debug as origDebug, warning } from '../utils/log.js'\nimport { moveMessage } from '../utils/messages.js'\nimport { wrapNextConfig } from './wrap-next-config.js'\n\ntype InitNextArgs = Pick<CliArgs, '--debug'> & {\n dbType: DbType\n nextAppDetails?: NextAppDetails\n packageManager: PackageManager\n projectDir: string\n useDistFiles?: boolean\n}\n\ntype NextConfigType = 'cjs' | 'esm'\n\ntype InitNextResult =\n | {\n isSrcDir: boolean\n nextAppDir: string\n payloadConfigPath: string\n success: true\n }\n | { isSrcDir: boolean; nextAppDir?: string; reason: string; success: false }\n\nexport async function initNext(args: InitNextArgs): Promise<InitNextResult> {\n const { dbType: dbType, packageManager, projectDir } = args\n\n const nextAppDetails = args.nextAppDetails || (await getNextAppDetails(projectDir))\n\n if (!nextAppDetails.nextAppDir) {\n warning(`Could not find app directory in ${projectDir}, creating...`)\n const createdAppDir = path.resolve(projectDir, nextAppDetails.isSrcDir ? 'src/app' : 'app')\n fse.mkdirSync(createdAppDir, { recursive: true })\n nextAppDetails.nextAppDir = createdAppDir\n }\n\n const { hasTopLevelLayout, isSrcDir, nextAppDir, nextConfigType } = nextAppDetails\n\n if (!nextConfigType) {\n return {\n isSrcDir,\n nextAppDir,\n reason: `Could not determine Next Config type in ${projectDir}. Possibly try renaming next.config.js to next.config.cjs or next.config.mjs.`,\n success: false,\n }\n }\n\n if (hasTopLevelLayout) {\n // Output directions for user to move all files from app to top-level directory named `(app)`\n p.log.warn(moveMessage({ nextAppDir, projectDir }))\n return {\n isSrcDir,\n nextAppDir,\n reason: 'Found existing layout.tsx in app directory',\n success: false,\n }\n }\n\n const installSpinner = p.spinner()\n installSpinner.start('Installing Payload and dependencies...')\n\n const configurationResult = installAndConfigurePayload({\n ...args,\n nextAppDetails,\n nextConfigType,\n useDistFiles: true, // Requires running 'pnpm pack-template-files' in cpa\n })\n\n if (configurationResult.success === false) {\n installSpinner.stop(configurationResult.reason, 1)\n return { ...configurationResult, isSrcDir, success: false }\n }\n\n const { success: installSuccess } = await installDeps(projectDir, packageManager, dbType)\n if (!installSuccess) {\n installSpinner.stop('Failed to install dependencies', 1)\n return {\n ...configurationResult,\n isSrcDir,\n reason: 'Failed to install dependencies',\n success: false,\n }\n }\n\n // Add `@payload-config` to tsconfig.json `paths`\n await addPayloadConfigToTsConfig(projectDir, isSrcDir)\n installSpinner.stop('Successfully installed Payload and dependencies')\n return { ...configurationResult, isSrcDir, nextAppDir, success: true }\n}\n\nasync function addPayloadConfigToTsConfig(projectDir: string, isSrcDir: boolean) {\n const tsConfigPath = path.resolve(projectDir, 'tsconfig.json')\n\n // Check if tsconfig.json exists\n if (!fs.existsSync(tsConfigPath)) {\n warning(`Could not find tsconfig.json to add @payload-config path.`)\n return\n }\n\n const userTsConfigContent = await readFile(tsConfigPath, {\n encoding: 'utf8',\n })\n const userTsConfig = parse(userTsConfigContent) as {\n compilerOptions?: CompilerOptions\n }\n if (!userTsConfig.compilerOptions && !('extends' in userTsConfig)) {\n userTsConfig.compilerOptions = {}\n }\n\n if (\n !userTsConfig.compilerOptions?.paths?.['@payload-config'] &&\n userTsConfig.compilerOptions?.paths\n ) {\n userTsConfig.compilerOptions.paths = {\n ...(userTsConfig.compilerOptions.paths || {}),\n '@payload-config': [`./${isSrcDir ? 'src/' : ''}payload.config.ts`],\n }\n await writeFile(tsConfigPath, stringify(userTsConfig, null, 2), { encoding: 'utf8' })\n }\n}\n\nfunction installAndConfigurePayload(\n args: InitNextArgs & {\n nextAppDetails: NextAppDetails\n nextConfigType: NextConfigType\n useDistFiles?: boolean\n },\n):\n | { payloadConfigPath: string; success: true }\n | { payloadConfigPath?: string; reason: string; success: false } {\n const {\n '--debug': debug,\n nextAppDetails: { isSrcDir, nextAppDir, nextConfigPath } = {},\n nextConfigType,\n projectDir,\n useDistFiles,\n } = args\n\n if (!nextAppDir || !nextConfigPath) {\n return {\n reason: 'Could not find app directory or next.config.js',\n success: false,\n }\n }\n\n const logDebug = (message: string) => {\n if (debug) origDebug(message)\n }\n\n if (!fs.existsSync(projectDir)) {\n return {\n reason: `Could not find specified project directory at ${projectDir}`,\n success: false,\n }\n }\n\n const templateFilesPath =\n dirname.endsWith('dist') || useDistFiles\n ? path.resolve(dirname, '../..', 'dist/template')\n : path.resolve(dirname, '../../../../templates/blank-3.0')\n\n logDebug(`Using template files from: ${templateFilesPath}`)\n\n if (!fs.existsSync(templateFilesPath)) {\n return {\n reason: `Could not find template source files from ${templateFilesPath}`,\n success: false,\n }\n } else {\n logDebug('Found template source files')\n }\n\n logDebug(`Copying template files from ${templateFilesPath} to ${nextAppDir}`)\n\n const templateSrcDir = path.resolve(templateFilesPath, isSrcDir ? '' : 'src')\n\n logDebug(`templateSrcDir: ${templateSrcDir}`)\n logDebug(`nextAppDir: ${nextAppDir}`)\n logDebug(`projectDir: ${projectDir}`)\n logDebug(`nextConfigPath: ${nextConfigPath}`)\n logDebug(`payloadConfigPath: ${path.resolve(projectDir, 'payload.config.ts')}`)\n\n logDebug(\n `isSrcDir: ${isSrcDir}. source: ${templateSrcDir}. dest: ${path.dirname(nextConfigPath)}`,\n )\n\n // This is a little clunky and needs to account for isSrcDir\n copyRecursiveSync(templateSrcDir, path.dirname(nextConfigPath), debug)\n\n // Wrap next.config.js with withPayload\n wrapNextConfig({ nextConfigPath, nextConfigType })\n\n return {\n payloadConfigPath: path.resolve(nextAppDir, '../payload.config.ts'),\n success: true,\n }\n}\n\nasync function installDeps(projectDir: string, packageManager: PackageManager, dbType: DbType) {\n const packagesToInstall = ['payload', '@payloadcms/next', '@payloadcms/richtext-lexical'].map(\n (pkg) => `${pkg}@beta`,\n )\n\n packagesToInstall.push(`@payloadcms/db-${dbType}@beta`)\n\n let exitCode = 0\n switch (packageManager) {\n case 'npm': {\n ;({ exitCode } = await execa('npm', ['install', '--save', ...packagesToInstall], {\n cwd: projectDir,\n }))\n break\n }\n case 'yarn':\n case 'pnpm': {\n ;({ exitCode } = await execa(packageManager, ['add', ...packagesToInstall], {\n cwd: projectDir,\n }))\n break\n }\n case 'bun': {\n warning('Bun support is untested.')\n ;({ exitCode } = await execa('bun', ['add', ...packagesToInstall], { cwd: projectDir }))\n break\n }\n }\n\n return { success: exitCode === 0 }\n}\n\ntype NextAppDetails = {\n hasTopLevelLayout: boolean\n isSrcDir: boolean\n nextAppDir?: string\n nextConfigPath?: string\n nextConfigType?: NextConfigType\n}\n\nexport async function getNextAppDetails(projectDir: string): Promise<NextAppDetails> {\n const isSrcDir = fs.existsSync(path.resolve(projectDir, 'src'))\n\n const nextConfigPath: string | undefined = (\n await globby('next.config.*js', { absolute: true, cwd: projectDir })\n )?.[0]\n if (!nextConfigPath || nextConfigPath.length === 0) {\n return {\n hasTopLevelLayout: false,\n isSrcDir,\n nextConfigPath: undefined,\n }\n }\n\n let nextAppDir: string | undefined = (\n await globby(['**/app'], {\n absolute: true,\n cwd: projectDir,\n ignore: ['**/node_modules/**'],\n onlyDirectories: true,\n })\n )?.[0]\n\n if (!nextAppDir || nextAppDir.length === 0) {\n nextAppDir = undefined\n }\n\n const configType = await getProjectType(projectDir, nextConfigPath)\n\n const hasTopLevelLayout = nextAppDir\n ? fs.existsSync(path.resolve(nextAppDir, 'layout.tsx'))\n : false\n\n return { hasTopLevelLayout, isSrcDir, nextAppDir, nextConfigPath, nextConfigType: configType }\n}\n\nasync function getProjectType(projectDir: string, nextConfigPath: string): Promise<'cjs' | 'esm'> {\n if (nextConfigPath.endsWith('.mjs')) {\n return 'esm'\n }\n if (nextConfigPath.endsWith('.cjs')) {\n return 'cjs'\n }\n\n const packageObj = await fse.readJson(path.resolve(projectDir, 'package.json'))\n const packageJsonType = packageObj.type\n if (packageJsonType === 'module') {\n return 'esm'\n }\n if (packageJsonType === 'commonjs') {\n return 'cjs'\n }\n\n return 'cjs'\n}\n"],"names":["p","parse","stringify","execa","fs","fse","globby","path","promisify","readFile","writeFile","filename","fileURLToPath","url","dirname","copyRecursiveSync","debug","origDebug","warning","moveMessage","wrapNextConfig","initNext","args","dbType","packageManager","projectDir","nextAppDetails","getNextAppDetails","nextAppDir","createdAppDir","resolve","isSrcDir","mkdirSync","recursive","hasTopLevelLayout","nextConfigType","reason","success","log","warn","installSpinner","spinner","start","configurationResult","installAndConfigurePayload","useDistFiles","stop","installSuccess","installDeps","addPayloadConfigToTsConfig","tsConfigPath","existsSync","userTsConfigContent","encoding","userTsConfig","compilerOptions","paths","nextConfigPath","logDebug","message","templateFilesPath","endsWith","templateSrcDir","payloadConfigPath","packagesToInstall","map","pkg","push","exitCode","cwd","absolute","length","undefined","ignore","onlyDirectories","configType","getProjectType","packageObj","readJson","packageJsonType","type"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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6B;QAAgBtB,gBAAgBwC;IAAW;AAC/F;AAEA,eAAeC,eAAenD,UAAkB,EAAEgC,cAAsB;IACtE,IAAIA,eAAeI,QAAQ,CAAC,SAAS;QACnC,OAAO;IACT;IACA,IAAIJ,eAAeI,QAAQ,CAAC,SAAS;QACnC,OAAO;IACT;IAEA,MAAMgB,aAAa,MAAMxE,IAAIyE,QAAQ,CAACvE,KAAKuB,OAAO,CAACL,YAAY;IAC/D,MAAMsD,kBAAkBF,WAAWG,IAAI;IACvC,IAAID,oBAAoB,UAAU;QAChC,OAAO;IACT;IACA,IAAIA,oBAAoB,YAAY;QAClC,OAAO;IACT;IAEA,OAAO;AACT"}
@@ -1,12 +1,18 @@
1
- export declare const withPayloadImportStatement = "import { withPayload } from '@payloadcms/next'\n";
1
+ export declare const withPayloadStatement: {
2
+ cjs: string;
3
+ esm: string;
4
+ };
5
+ type NextConfigType = 'cjs' | 'esm';
2
6
  export declare const wrapNextConfig: (args: {
3
7
  nextConfigPath: string;
8
+ nextConfigType: NextConfigType;
4
9
  }) => void;
5
10
  /**
6
11
  * Parses config content with AST and wraps it with withPayload function
7
12
  */
8
- export declare function parseAndModifyConfigContent(content: string): {
13
+ export declare function parseAndModifyConfigContent(content: string, configType: NextConfigType): {
9
14
  modifiedConfigContent: string;
10
15
  success: boolean;
11
16
  };
17
+ export {};
12
18
  //# sourceMappingURL=wrap-next-config.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"wrap-next-config.d.ts","sourceRoot":"","sources":["../../src/lib/wrap-next-config.ts"],"names":[],"mappings":"AAOA,eAAO,MAAM,0BAA0B,qDAAqD,CAAA;AAE5F,eAAO,MAAM,cAAc,SAAU;IAAE,cAAc,EAAE,MAAM,CAAA;CAAE,SAU9D,CAAA;AAED;;GAEG;AACH,wBAAgB,2BAA2B,CAAC,OAAO,EAAE,MAAM,GAAG;IAC5D,qBAAqB,EAAE,MAAM,CAAA;IAC7B,OAAO,EAAE,OAAO,CAAA;CACjB,CAgDA"}
1
+ {"version":3,"file":"wrap-next-config.d.ts","sourceRoot":"","sources":["../../src/lib/wrap-next-config.ts"],"names":[],"mappings":"AAOA,eAAO,MAAM,oBAAoB;;;CAGhC,CAAA;AAED,KAAK,cAAc,GAAG,KAAK,GAAG,KAAK,CAAA;AAEnC,eAAO,MAAM,cAAc,SAAU;IACnC,cAAc,EAAE,MAAM,CAAA;IACtB,cAAc,EAAE,cAAc,CAAA;CAC/B,SAaA,CAAA;AAED;;GAEG;AACH,wBAAgB,2BAA2B,CACzC,OAAO,EAAE,MAAM,EACf,UAAU,EAAE,cAAc,GACzB;IAAE,qBAAqB,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,OAAO,CAAA;CAAE,CAsFrD"}
@@ -3,11 +3,14 @@ import { parseModule } from 'esprima';
3
3
  import fs from 'fs';
4
4
  import { warning } from '../utils/log.js';
5
5
  import { log } from '../utils/log.js';
6
- export const withPayloadImportStatement = `import { withPayload } from '@payloadcms/next'\n`;
6
+ export const withPayloadStatement = {
7
+ cjs: `const { withPayload } = require('@payloadcms/next/withPayload')\n`,
8
+ esm: `import { withPayload } from '@payloadcms/next/withPayload'\n`
9
+ };
7
10
  export const wrapNextConfig = (args)=>{
8
- const { nextConfigPath } = args;
11
+ const { nextConfigPath, nextConfigType: configType } = args;
9
12
  const configContent = fs.readFileSync(nextConfigPath, 'utf8');
10
- const { modifiedConfigContent: newConfig, success } = parseAndModifyConfigContent(configContent);
13
+ const { modifiedConfigContent: newConfig, success } = parseAndModifyConfigContent(configContent, configType);
11
14
  if (!success) {
12
15
  return;
13
16
  }
@@ -15,59 +18,81 @@ export const wrapNextConfig = (args)=>{
15
18
  };
16
19
  /**
17
20
  * Parses config content with AST and wraps it with withPayload function
18
- */ export function parseAndModifyConfigContent(content) {
19
- content = withPayloadImportStatement + content;
21
+ */ export function parseAndModifyConfigContent(content, configType) {
22
+ content = withPayloadStatement[configType] + content;
20
23
  const ast = parseModule(content, {
21
24
  loc: true
22
25
  });
23
- const exportDefaultDeclaration = ast.body.find((p)=>p.type === 'ExportDefaultDeclaration');
24
- const exportNamedDeclaration = ast.body.find((p)=>p.type === 'ExportNamedDeclaration');
25
- if (!exportDefaultDeclaration && !exportNamedDeclaration) {
26
- throw new Error('Could not find ExportDefaultDeclaration in next.config.js');
27
- }
28
- if (exportDefaultDeclaration && exportDefaultDeclaration.declaration?.loc) {
29
- const modifiedConfigContent = insertBeforeAndAfter(content, exportDefaultDeclaration.declaration.loc);
26
+ if (configType === 'esm') {
27
+ const exportDefaultDeclaration = ast.body.find((p)=>p.type === 'ExportDefaultDeclaration');
28
+ const exportNamedDeclaration = ast.body.find((p)=>p.type === 'ExportNamedDeclaration');
29
+ if (!exportDefaultDeclaration && !exportNamedDeclaration) {
30
+ throw new Error('Could not find ExportDefaultDeclaration in next.config.js');
31
+ }
32
+ if (exportDefaultDeclaration && exportDefaultDeclaration.declaration?.loc) {
33
+ const modifiedConfigContent = insertBeforeAndAfter(content, exportDefaultDeclaration.declaration.loc, configType);
34
+ return {
35
+ modifiedConfigContent,
36
+ success: true
37
+ };
38
+ } else if (exportNamedDeclaration) {
39
+ const exportSpecifier = exportNamedDeclaration.specifiers.find((s)=>s.type === 'ExportSpecifier' && s.exported?.name === 'default' && s.local?.type === 'Identifier' && s.local?.name);
40
+ if (exportSpecifier) {
41
+ warning('Could not automatically wrap next.config.js with withPayload.');
42
+ warning('Automatic wrapping of named exports as default not supported yet.');
43
+ warnUserWrapNotSuccessful(configType);
44
+ return {
45
+ modifiedConfigContent: content,
46
+ success: false
47
+ };
48
+ }
49
+ }
50
+ warning('Could not automatically wrap Next config with withPayload.');
51
+ warnUserWrapNotSuccessful(configType);
30
52
  return {
31
- modifiedConfigContent,
32
- success: true
53
+ modifiedConfigContent: content,
54
+ success: false
33
55
  };
34
- } else if (exportNamedDeclaration) {
35
- const exportSpecifier = exportNamedDeclaration.specifiers.find((s)=>s.type === 'ExportSpecifier' && s.exported?.name === 'default' && s.local?.type === 'Identifier' && s.local?.name);
36
- if (exportSpecifier) {
37
- warning('Could not automatically wrap next.config.js with withPayload.');
38
- warning('Automatic wrapping of named exports as default not supported yet.');
39
- warnUserWrapNotSuccessful();
56
+ } else if (configType === 'cjs') {
57
+ // Find `module.exports = X`
58
+ const moduleExports = ast.body.find((p)=>p.type === 'ExpressionStatement' && p.expression?.type === 'AssignmentExpression' && p.expression.left?.type === 'MemberExpression' && p.expression.left.object?.type === 'Identifier' && p.expression.left.object.name === 'module' && p.expression.left.property?.type === 'Identifier' && p.expression.left.property.name === 'exports');
59
+ if (moduleExports && moduleExports.expression.right?.loc) {
60
+ const modifiedConfigContent = insertBeforeAndAfter(content, moduleExports.expression.right.loc, configType);
40
61
  return {
41
- modifiedConfigContent: content,
42
- success: false
62
+ modifiedConfigContent,
63
+ success: true
43
64
  };
44
65
  }
66
+ return {
67
+ modifiedConfigContent: content,
68
+ success: false
69
+ };
45
70
  }
46
- warning('Could not automatically wrap next.config.js with withPayload.');
47
- warnUserWrapNotSuccessful();
71
+ warning('Could not automatically wrap Next config with withPayload.');
72
+ warnUserWrapNotSuccessful(configType);
48
73
  return {
49
74
  modifiedConfigContent: content,
50
75
  success: false
51
76
  };
52
77
  }
53
- function warnUserWrapNotSuccessful() {
78
+ function warnUserWrapNotSuccessful(configType) {
54
79
  // Output directions for user to update next.config.js
55
80
  const withPayloadMessage = `
56
81
 
57
82
  ${chalk.bold(`Please manually wrap your existing next.config.js with the withPayload function. Here is an example:`)}
58
83
 
59
- import withPayload from '@payloadcms/next/withPayload'
84
+ ${withPayloadStatement[configType]}
60
85
 
61
86
  const nextConfig = {
62
87
  // Your Next.js config here
63
88
  }
64
89
 
65
- export default withPayload(nextConfig)
90
+ ${configType === 'esm' ? 'export default withPayload(nextConfig)' : 'module.exports = withPayload(nextConfig)'}
66
91
 
67
92
  `;
68
93
  log(withPayloadMessage);
69
94
  }
70
- function insertBeforeAndAfter(content, loc) {
95
+ function insertBeforeAndAfter(content, loc, configType) {
71
96
  const { end, start } = loc;
72
97
  const lines = content.split('\n');
73
98
  const insert = (line, column, text)=>{
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/lib/wrap-next-config.ts"],"sourcesContent":["import chalk from 'chalk'\nimport { parseModule } from 'esprima'\nimport fs from 'fs'\n\nimport { warning } from '../utils/log.js'\nimport { log } from '../utils/log.js'\n\nexport const withPayloadImportStatement = `import { withPayload } from '@payloadcms/next'\\n`\n\nexport const wrapNextConfig = (args: { nextConfigPath: string }) => {\n const { nextConfigPath } = args\n const configContent = fs.readFileSync(nextConfigPath, 'utf8')\n const { modifiedConfigContent: newConfig, success } = parseAndModifyConfigContent(configContent)\n\n if (!success) {\n return\n }\n\n fs.writeFileSync(nextConfigPath, newConfig)\n}\n\n/**\n * Parses config content with AST and wraps it with withPayload function\n */\nexport function parseAndModifyConfigContent(content: string): {\n modifiedConfigContent: string\n success: boolean\n} {\n content = withPayloadImportStatement + content\n const ast = parseModule(content, { loc: true })\n const exportDefaultDeclaration = ast.body.find((p) => p.type === 'ExportDefaultDeclaration') as\n | Directive\n | undefined\n\n const exportNamedDeclaration = ast.body.find((p) => p.type === 'ExportNamedDeclaration') as\n | ExportNamedDeclaration\n | undefined\n\n if (!exportDefaultDeclaration && !exportNamedDeclaration) {\n throw new Error('Could not find ExportDefaultDeclaration in next.config.js')\n }\n\n if (exportDefaultDeclaration && exportDefaultDeclaration.declaration?.loc) {\n const modifiedConfigContent = insertBeforeAndAfter(\n content,\n exportDefaultDeclaration.declaration.loc,\n )\n return { modifiedConfigContent, success: true }\n } else if (exportNamedDeclaration) {\n const exportSpecifier = exportNamedDeclaration.specifiers.find(\n (s) =>\n s.type === 'ExportSpecifier' &&\n s.exported?.name === 'default' &&\n s.local?.type === 'Identifier' &&\n s.local?.name,\n )\n\n if (exportSpecifier) {\n warning('Could not automatically wrap next.config.js with withPayload.')\n warning('Automatic wrapping of named exports as default not supported yet.')\n\n warnUserWrapNotSuccessful()\n return {\n modifiedConfigContent: content,\n success: false,\n }\n }\n }\n\n warning('Could not automatically wrap next.config.js with withPayload.')\n warnUserWrapNotSuccessful()\n return {\n modifiedConfigContent: content,\n success: false,\n }\n}\n\nfunction warnUserWrapNotSuccessful() {\n // Output directions for user to update next.config.js\n const withPayloadMessage = `\n\n ${chalk.bold(`Please manually wrap your existing next.config.js with the withPayload function. Here is an example:`)}\n\n import withPayload from '@payloadcms/next/withPayload'\n\n const nextConfig = {\n // Your Next.js config here\n }\n\n export default withPayload(nextConfig)\n\n`\n\n log(withPayloadMessage)\n}\n\ntype Directive = {\n declaration?: {\n loc: Loc\n }\n}\n\ntype ExportNamedDeclaration = {\n declaration: null\n loc: Loc\n specifiers: {\n exported: {\n loc: Loc\n name: string\n type: string\n }\n loc: Loc\n local: {\n loc: Loc\n name: string\n type: string\n }\n type: string\n }[]\n type: string\n}\n\ntype Loc = {\n end: { column: number; line: number }\n start: { column: number; line: number }\n}\n\nfunction insertBeforeAndAfter(content: string, loc: Loc) {\n const { end, start } = loc\n const lines = content.split('\\n')\n\n const insert = (line: string, column: number, text: string) => {\n return line.slice(0, column) + text + line.slice(column)\n }\n\n // insert ) after end\n lines[end.line - 1] = insert(lines[end.line - 1], end.column, ')')\n // insert withPayload before start\n if (start.line === end.line) {\n lines[end.line - 1] = insert(lines[end.line - 1], start.column, 'withPayload(')\n } else {\n lines[start.line - 1] = insert(lines[start.line - 1], start.column, 'withPayload(')\n }\n\n return lines.join('\\n')\n}\n"],"names":["chalk","parseModule","fs","warning","log","withPayloadImportStatement","wrapNextConfig","args","nextConfigPath","configContent","readFileSync","modifiedConfigContent","newConfig","success","parseAndModifyConfigContent","writeFileSync","content","ast","loc","exportDefaultDeclaration","body","find","p","type","exportNamedDeclaration","Error","declaration","insertBeforeAndAfter","exportSpecifier","specifiers","s","exported","name","local","warnUserWrapNotSuccessful","withPayloadMessage","bold","end","start","lines","split","insert","line","column","text","slice","join"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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alk'\nimport { parseModule } from 'esprima'\nimport fs from 'fs'\n\nimport { warning } from '../utils/log.js'\nimport { log } from '../utils/log.js'\n\nexport const withPayloadStatement = {\n cjs: `const { withPayload } = require('@payloadcms/next/withPayload')\\n`,\n esm: `import { withPayload } from '@payloadcms/next/withPayload'\\n`,\n}\n\ntype NextConfigType = 'cjs' | 'esm'\n\nexport const wrapNextConfig = (args: {\n nextConfigPath: string\n nextConfigType: NextConfigType\n}) => {\n const { nextConfigPath, nextConfigType: configType } = args\n const configContent = fs.readFileSync(nextConfigPath, 'utf8')\n const { modifiedConfigContent: newConfig, success } = parseAndModifyConfigContent(\n configContent,\n configType,\n )\n\n if (!success) {\n return\n }\n\n fs.writeFileSync(nextConfigPath, newConfig)\n}\n\n/**\n * Parses config content with AST and wraps it with withPayload function\n */\nexport function parseAndModifyConfigContent(\n content: string,\n configType: NextConfigType,\n): { modifiedConfigContent: string; success: boolean } {\n content = withPayloadStatement[configType] + content\n const ast = parseModule(content, { loc: true })\n\n if (configType === 'esm') {\n const exportDefaultDeclaration = ast.body.find((p) => p.type === 'ExportDefaultDeclaration') as\n | Directive\n | undefined\n\n const exportNamedDeclaration = ast.body.find((p) => p.type === 'ExportNamedDeclaration') as\n | ExportNamedDeclaration\n | undefined\n\n if (!exportDefaultDeclaration && !exportNamedDeclaration) {\n throw new Error('Could not find ExportDefaultDeclaration in next.config.js')\n }\n\n if (exportDefaultDeclaration && exportDefaultDeclaration.declaration?.loc) {\n const modifiedConfigContent = insertBeforeAndAfter(\n content,\n exportDefaultDeclaration.declaration.loc,\n configType,\n )\n return { modifiedConfigContent, success: true }\n } else if (exportNamedDeclaration) {\n const exportSpecifier = exportNamedDeclaration.specifiers.find(\n (s) =>\n s.type === 'ExportSpecifier' &&\n s.exported?.name === 'default' &&\n s.local?.type === 'Identifier' &&\n s.local?.name,\n )\n\n if (exportSpecifier) {\n warning('Could not automatically wrap next.config.js with withPayload.')\n warning('Automatic wrapping of named exports as default not supported yet.')\n\n warnUserWrapNotSuccessful(configType)\n return {\n modifiedConfigContent: content,\n success: false,\n }\n }\n }\n\n warning('Could not automatically wrap Next config with withPayload.')\n warnUserWrapNotSuccessful(configType)\n return {\n modifiedConfigContent: content,\n success: false,\n }\n } else if (configType === 'cjs') {\n // Find `module.exports = X`\n const moduleExports = ast.body.find(\n (p) =>\n p.type === 'ExpressionStatement' &&\n p.expression?.type === 'AssignmentExpression' &&\n p.expression.left?.type === 'MemberExpression' &&\n p.expression.left.object?.type === 'Identifier' &&\n p.expression.left.object.name === 'module' &&\n p.expression.left.property?.type === 'Identifier' &&\n p.expression.left.property.name === 'exports',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ) as any\n\n if (moduleExports && moduleExports.expression.right?.loc) {\n const modifiedConfigContent = insertBeforeAndAfter(\n content,\n moduleExports.expression.right.loc,\n configType,\n )\n return { modifiedConfigContent, success: true }\n }\n\n return {\n modifiedConfigContent: content,\n success: false,\n }\n }\n\n warning('Could not automatically wrap Next config with withPayload.')\n warnUserWrapNotSuccessful(configType)\n return {\n modifiedConfigContent: content,\n success: false,\n }\n}\n\nfunction warnUserWrapNotSuccessful(configType: NextConfigType) {\n // Output directions for user to update next.config.js\n const withPayloadMessage = `\n\n ${chalk.bold(`Please manually wrap your existing next.config.js with the withPayload function. Here is an example:`)}\n\n ${withPayloadStatement[configType]}\n\n const nextConfig = {\n // Your Next.js config here\n }\n\n ${configType === 'esm' ? 'export default withPayload(nextConfig)' : 'module.exports = withPayload(nextConfig)'}\n\n`\n\n log(withPayloadMessage)\n}\n\ntype Directive = {\n declaration?: {\n loc: Loc\n }\n}\n\ntype ExportNamedDeclaration = {\n declaration: null\n loc: Loc\n specifiers: {\n exported: {\n loc: Loc\n name: string\n type: string\n }\n loc: Loc\n local: {\n loc: Loc\n name: string\n type: string\n }\n type: string\n }[]\n type: string\n}\n\ntype Loc = {\n end: { column: number; line: number }\n start: { column: number; line: number }\n}\n\nfunction insertBeforeAndAfter(content: string, loc: Loc, configType: NextConfigType) {\n const { end, start } = loc\n const lines = content.split('\\n')\n\n const insert = (line: string, column: number, text: string) => {\n return line.slice(0, column) + text + line.slice(column)\n }\n\n // insert ) after end\n lines[end.line - 1] = insert(lines[end.line - 1], end.column, ')')\n // insert withPayload before start\n if (start.line === end.line) {\n lines[end.line - 1] = insert(lines[end.line - 1], start.column, 'withPayload(')\n } else {\n lines[start.line - 1] = insert(lines[start.line - 1], start.column, 'withPayload(')\n }\n\n return lines.join('\\n')\n}\n"],"names":["chalk","parseModule","fs","warning","log","withPayloadStatement","cjs","esm","wrapNextConfig","args","nextConfigPath","nextConfigType","configType","configContent","readFileSync","modifiedConfigContent","newConfig","success","parseAndModifyConfigContent","writeFileSync","content","ast","loc","exportDefaultDeclaration","body","find","p","type","exportNamedDeclaration","Error","declaration","insertBeforeAndAfter","exportSpecifier","specifiers","s","exported","name","local","warnUserWrapNotSuccessful","moduleExports","expression","left","object","property","right","withPayloadMessage","bold","end","start","lines","split","insert","line","column","text","slice","join"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA,OAAOA,WAAW,QAAO;AACzB,SAASC,WAAW,QAAQ,UAAS;AACrC,OAAOC,QAAQ,KAAI;AAEnB,SAASC,OAAO,QAAQ,kBAAiB;AACzC,SAASC,GAAG,QAAQ,kBAAiB;AAErC,OAAO,MAAMC,uBAAuB;IAClCC,KAAK,CAAC,iEAAiE,CAAC;IACxEC,KAAK,CAAC,4DAA4D,CAAC;AACrE,EAAC;AAID,OAAO,MAAMC,iBAAiB,CAACC;IAI7B,MAAM,EAAEC,cAAc,EAAEC,gBAAgBC,UAAU,EAAE,GAAGH;IACvD,MAAMI,gBAAgBX,GAAGY,YAAY,CAACJ,gBAAgB;IACtD,MAAM,EAAEK,uBAAuBC,SAAS,EAAEC,OAAO,EAAE,GAAGC,4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IACnD;IAEA,qBAAqB;IACrBJ,KAAK,CAACF,IAAIK,IAAI,GAAG,EAAE,GAAGD,OAAOF,KAAK,CAACF,IAAIK,IAAI,GAAG,EAAE,EAAEL,IAAIM,MAAM,EAAE;IAC9D,kCAAkC;IAClC,IAAIL,MAAMI,IAAI,KAAKL,IAAIK,IAAI,EAAE;QAC3BH,KAAK,CAACF,IAAIK,IAAI,GAAG,EAAE,GAAGD,OAAOF,KAAK,CAACF,IAAIK,IAAI,GAAG,EAAE,EAAEJ,MAAMK,MAAM,EAAE;IAClE,OAAO;QACLJ,KAAK,CAACD,MAAMI,IAAI,GAAG,EAAE,GAAGD,OAAOF,KAAK,CAACD,MAAMI,IAAI,GAAG,EAAE,EAAEJ,MAAMK,MAAM,EAAE;IACtE;IAEA,OAAOJ,MAAMO,IAAI,CAAC;AACpB"}
@@ -1,52 +1,97 @@
1
- import { parseAndModifyConfigContent, withPayloadImportStatement } from './wrap-next-config.js';
1
+ import { parseAndModifyConfigContent, withPayloadStatement } from './wrap-next-config.js';
2
2
  import * as p from '@clack/prompts';
3
- const defaultNextConfig = `/** @type {import('next').NextConfig} */
3
+ const esmConfigs = {
4
+ defaultNextConfig: `/** @type {import('next').NextConfig} */
4
5
  const nextConfig = {};
5
-
6
6
  export default nextConfig;
7
- `;
8
- const nextConfigWithFunc = `const nextConfig = {
9
- // Your Next.js config here
10
- }
11
-
12
- export default someFunc(nextConfig)
13
- `;
14
- const nextConfigWithFuncMultiline = `const nextConfig = {
15
- // Your Next.js config here
16
- }
17
-
7
+ `,
8
+ nextConfigWithFunc: `const nextConfig = {};
9
+ export default someFunc(nextConfig);
10
+ `,
11
+ nextConfigWithFuncMultiline: `const nextConfig = {};;
18
12
  export default someFunc(
19
13
  nextConfig
20
- )
21
- `;
22
- const nextConfigExportNamedDefault = `const nextConfig = {
23
- // Your Next.js config here
24
- }
25
- const wrapped = someFunc(asdf)
26
- export { wrapped as default }
27
- `;
14
+ );
15
+ `,
16
+ nextConfigExportNamedDefault: `const nextConfig = {};
17
+ const wrapped = someFunc(asdf);
18
+ export { wrapped as default };
19
+ `
20
+ };
21
+ const cjsConfigs = {
22
+ defaultNextConfig: `
23
+ /** @type {import('next').NextConfig} */
24
+ const nextConfig = {};
25
+ module.exports = nextConfig;
26
+ `,
27
+ anonConfig: `module.exports = {};`,
28
+ nextConfigWithFunc: `const nextConfig = {};
29
+ module.exports = someFunc(nextConfig);
30
+ `,
31
+ nextConfigWithFuncMultiline: `const nextConfig = {};
32
+ module.exports = someFunc(
33
+ nextConfig
34
+ );
35
+ `,
36
+ nextConfigExportNamedDefault: `const nextConfig = {};
37
+ const wrapped = someFunc(asdf);
38
+ module.exports = wrapped;
39
+ `
40
+ };
28
41
  describe('parseAndInsertWithPayload', ()=>{
29
- it('should parse the default next config', ()=>{
30
- const { modifiedConfigContent } = parseAndModifyConfigContent(defaultNextConfig);
31
- expect(modifiedConfigContent).toContain(withPayloadImportStatement);
32
- expect(modifiedConfigContent).toContain('withPayload(nextConfig)');
33
- });
34
- it('should parse the config with a function', ()=>{
35
- const { modifiedConfigContent } = parseAndModifyConfigContent(nextConfigWithFunc);
36
- expect(modifiedConfigContent).toContain('withPayload(someFunc(nextConfig))');
37
- });
38
- it('should parse the config with a function on a new line', ()=>{
39
- const { modifiedConfigContent } = parseAndModifyConfigContent(nextConfigWithFuncMultiline);
40
- expect(modifiedConfigContent).toContain(withPayloadImportStatement);
41
- expect(modifiedConfigContent).toMatch(/withPayload\(someFunc\(\n nextConfig\n\)\)/);
42
+ describe('esm', ()=>{
43
+ const configType = 'esm';
44
+ const importStatement = withPayloadStatement[configType];
45
+ it('should parse the default next config', ()=>{
46
+ const { modifiedConfigContent } = parseAndModifyConfigContent(esmConfigs.defaultNextConfig, configType);
47
+ expect(modifiedConfigContent).toContain(importStatement);
48
+ expect(modifiedConfigContent).toContain('withPayload(nextConfig)');
49
+ });
50
+ it('should parse the config with a function', ()=>{
51
+ const { modifiedConfigContent } = parseAndModifyConfigContent(esmConfigs.nextConfigWithFunc, configType);
52
+ expect(modifiedConfigContent).toContain('withPayload(someFunc(nextConfig))');
53
+ });
54
+ it('should parse the config with a function on a new line', ()=>{
55
+ const { modifiedConfigContent } = parseAndModifyConfigContent(esmConfigs.nextConfigWithFuncMultiline, configType);
56
+ expect(modifiedConfigContent).toContain(importStatement);
57
+ expect(modifiedConfigContent).toMatch(/withPayload\(someFunc\(\n nextConfig\n\)\)/);
58
+ });
59
+ // Unsupported: export { wrapped as default }
60
+ it('should give warning with a named export as default', ()=>{
61
+ const warnLogSpy = jest.spyOn(p.log, 'warn').mockImplementation(()=>{});
62
+ const { modifiedConfigContent, success } = parseAndModifyConfigContent(esmConfigs.nextConfigExportNamedDefault, configType);
63
+ expect(modifiedConfigContent).toContain(importStatement);
64
+ expect(success).toBe(false);
65
+ expect(warnLogSpy).toHaveBeenCalledWith(expect.stringContaining('Could not automatically wrap'));
66
+ });
42
67
  });
43
- // Unsupported: export { wrapped as default }
44
- it('should give warning with a named export as default', ()=>{
45
- const warnLogSpy = jest.spyOn(p.log, 'warn').mockImplementation(()=>{});
46
- const { modifiedConfigContent, success } = parseAndModifyConfigContent(nextConfigExportNamedDefault);
47
- expect(modifiedConfigContent).toContain(withPayloadImportStatement);
48
- expect(success).toBe(false);
49
- expect(warnLogSpy).toHaveBeenCalledWith(expect.stringContaining('Could not automatically wrap'));
68
+ describe('cjs', ()=>{
69
+ const configType = 'cjs';
70
+ const requireStatement = withPayloadStatement[configType];
71
+ it('should parse the default next config', ()=>{
72
+ const { modifiedConfigContent } = parseAndModifyConfigContent(cjsConfigs.defaultNextConfig, configType);
73
+ expect(modifiedConfigContent).toContain(requireStatement);
74
+ expect(modifiedConfigContent).toContain('withPayload(nextConfig)');
75
+ });
76
+ it('should parse anonymous default config', ()=>{
77
+ const { modifiedConfigContent } = parseAndModifyConfigContent(cjsConfigs.anonConfig, configType);
78
+ expect(modifiedConfigContent).toContain(requireStatement);
79
+ expect(modifiedConfigContent).toContain('withPayload({})');
80
+ });
81
+ it('should parse the config with a function', ()=>{
82
+ const { modifiedConfigContent } = parseAndModifyConfigContent(cjsConfigs.nextConfigWithFunc, configType);
83
+ expect(modifiedConfigContent).toContain('withPayload(someFunc(nextConfig))');
84
+ });
85
+ it('should parse the config with a function on a new line', ()=>{
86
+ const { modifiedConfigContent } = parseAndModifyConfigContent(cjsConfigs.nextConfigWithFuncMultiline, configType);
87
+ expect(modifiedConfigContent).toContain(requireStatement);
88
+ expect(modifiedConfigContent).toMatch(/withPayload\(someFunc\(\n nextConfig\n\)\)/);
89
+ });
90
+ it('should parse the config with a named export as default', ()=>{
91
+ const { modifiedConfigContent } = parseAndModifyConfigContent(cjsConfigs.nextConfigExportNamedDefault, configType);
92
+ expect(modifiedConfigContent).toContain(requireStatement);
93
+ expect(modifiedConfigContent).toContain('withPayload(wrapped)');
94
+ });
50
95
  });
51
96
  });
52
97
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/lib/wrap-next-config.spec.ts"],"sourcesContent":["import { parseAndModifyConfigContent, withPayloadImportStatement } from './wrap-next-config.js'\nimport * as p from '@clack/prompts'\n\nconst defaultNextConfig = `/** @type {import('next').NextConfig} */\nconst nextConfig = {};\n\nexport default nextConfig;\n`\n\nconst nextConfigWithFunc = `const nextConfig = {\n // Your Next.js config here\n}\n\nexport default someFunc(nextConfig)\n`\nconst nextConfigWithFuncMultiline = `const nextConfig = {\n // Your Next.js config here\n}\n\nexport default someFunc(\n nextConfig\n)\n`\n\nconst nextConfigExportNamedDefault = `const nextConfig = {\n // Your Next.js config here\n}\nconst wrapped = someFunc(asdf)\nexport { wrapped as default }\n`\n\ndescribe('parseAndInsertWithPayload', () => {\n it('should parse the default next config', () => {\n const { modifiedConfigContent } = parseAndModifyConfigContent(defaultNextConfig)\n expect(modifiedConfigContent).toContain(withPayloadImportStatement)\n expect(modifiedConfigContent).toContain('withPayload(nextConfig)')\n })\n it('should parse the config with a function', () => {\n const { modifiedConfigContent } = parseAndModifyConfigContent(nextConfigWithFunc)\n expect(modifiedConfigContent).toContain('withPayload(someFunc(nextConfig))')\n })\n\n it('should parse the config with a function on a new line', () => {\n const { modifiedConfigContent } = parseAndModifyConfigContent(nextConfigWithFuncMultiline)\n expect(modifiedConfigContent).toContain(withPayloadImportStatement)\n expect(modifiedConfigContent).toMatch(/withPayload\\(someFunc\\(\\n nextConfig\\n\\)\\)/)\n })\n\n // Unsupported: export { wrapped as default }\n it('should give warning with a named export as default', () => {\n const warnLogSpy = jest.spyOn(p.log, 'warn').mockImplementation(() => {})\n\n const { modifiedConfigContent, success } = parseAndModifyConfigContent(\n nextConfigExportNamedDefault,\n )\n expect(modifiedConfigContent).toContain(withPayloadImportStatement)\n expect(success).toBe(false)\n\n expect(warnLogSpy).toHaveBeenCalledWith(expect.stringContaining('Could not automatically wrap'))\n })\n})\n"],"names":["parseAndModifyConfigContent","withPayloadImportStatement","p","defaultNextConfig","nextConfigWithFunc","nextConfigWithFuncMultiline","nextConfigExportNamedDefault","describe","it","modifiedConfigContent","expect","toContain","toMatch","warnLogSpy","jest","spyOn","log","mockImplementation","success","toBe","toHaveBeenCalledWith","stringContaining"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA,SAASA,2BAA2B,EAAEC,0BAA0B,QAAQ,wBAAuB;AAC/F,YAAYC,OAAO,iBAAgB;AAEnC,MAAMC,oBAAoB,CAAC;;;;AAI3B,CAAC;AAED,MAAMC,qBAAqB,CAAC;;;;;AAK5B,CAAC;AACD,MAAMC,8BAA8B,CAAC;;;;;;;AAOrC,CAAC;AAED,MAAMC,+BAA+B,CAAC;;;;;AAKtC,CAAC;AAEDC,SAAS,6BAA6B;IACpCC,GAAG,wCAAwC;QACzC,MAAM,EAAEC,qBAAqB,EAAE,GAAGT,4BAA4BG;QAC9DO,OAAOD,uBAAuBE,SAAS,CAACV;QACxCS,OAAOD,uBAAuBE,SAAS,CAAC;IAC1C;IACAH,GAAG,2CAA2C;QAC5C,MAAM,EAAEC,qBAAqB,EAAE,GAAGT,4BAA4BI;QAC9DM,OAAOD,uBAAuBE,SAAS,CAAC;IAC1C;IAEAH,GAAG,yDAAyD;QAC1D,MAAM,EAAEC,qBAAqB,EAAE,GAAGT,4BAA4BK;QAC9DK,OAAOD,uBAAuBE,SAAS,CAACV;QACxCS,OAAOD,uBAAuBG,OAAO,CAAC;IACxC;IAEA,6CAA6C;IAC7CJ,GAAG,sDAAsD;QACvD,MAAMK,aAAaC,KAAKC,KAAK,CAACb,EAAEc,GAAG,EAAE,QAAQC,kBAAkB,CAAC,KAAO;QAEvE,MAAM,EAAER,qBAAqB,EAAES,OAAO,EAAE,GAAGlB,4BACzCM;QAEFI,OAAOD,uBAAuBE,SAAS,CAACV;QACxCS,OAAOQ,SAASC,IAAI,CAAC;QAErBT,OAAOG,YAAYO,oBAAoB,CAACV,OAAOW,gBAAgB,CAAC;IAClE;AACF"}
1
+ {"version":3,"sources":["../../src/lib/wrap-next-config.spec.ts"],"sourcesContent":["import { parseAndModifyConfigContent, withPayloadStatement } from './wrap-next-config.js'\nimport * as p from '@clack/prompts'\n\nconst esmConfigs = {\n defaultNextConfig: `/** @type {import('next').NextConfig} */\nconst nextConfig = {};\nexport default nextConfig;\n`,\n nextConfigWithFunc: `const nextConfig = {};\nexport default someFunc(nextConfig);\n`,\n nextConfigWithFuncMultiline: `const nextConfig = {};;\nexport default someFunc(\n nextConfig\n);\n`,\n nextConfigExportNamedDefault: `const nextConfig = {};\nconst wrapped = someFunc(asdf);\nexport { wrapped as default };\n`,\n}\n\nconst cjsConfigs = {\n defaultNextConfig: `\n /** @type {import('next').NextConfig} */\nconst nextConfig = {};\nmodule.exports = nextConfig;\n`,\n anonConfig: `module.exports = {};`,\n nextConfigWithFunc: `const nextConfig = {};\nmodule.exports = someFunc(nextConfig);\n`,\n nextConfigWithFuncMultiline: `const nextConfig = {};\nmodule.exports = someFunc(\n nextConfig\n);\n`,\n nextConfigExportNamedDefault: `const nextConfig = {};\nconst wrapped = someFunc(asdf);\nmodule.exports = wrapped;\n`,\n}\n\ndescribe('parseAndInsertWithPayload', () => {\n describe('esm', () => {\n const configType = 'esm'\n const importStatement = withPayloadStatement[configType]\n it('should parse the default next config', () => {\n const { modifiedConfigContent } = parseAndModifyConfigContent(\n esmConfigs.defaultNextConfig,\n configType,\n )\n expect(modifiedConfigContent).toContain(importStatement)\n expect(modifiedConfigContent).toContain('withPayload(nextConfig)')\n })\n it('should parse the config with a function', () => {\n const { modifiedConfigContent } = parseAndModifyConfigContent(\n esmConfigs.nextConfigWithFunc,\n configType,\n )\n expect(modifiedConfigContent).toContain('withPayload(someFunc(nextConfig))')\n })\n\n it('should parse the config with a function on a new line', () => {\n const { modifiedConfigContent } = parseAndModifyConfigContent(\n esmConfigs.nextConfigWithFuncMultiline,\n configType,\n )\n expect(modifiedConfigContent).toContain(importStatement)\n expect(modifiedConfigContent).toMatch(/withPayload\\(someFunc\\(\\n nextConfig\\n\\)\\)/)\n })\n\n // Unsupported: export { wrapped as default }\n it('should give warning with a named export as default', () => {\n const warnLogSpy = jest.spyOn(p.log, 'warn').mockImplementation(() => {})\n\n const { modifiedConfigContent, success } = parseAndModifyConfigContent(\n esmConfigs.nextConfigExportNamedDefault,\n configType,\n )\n expect(modifiedConfigContent).toContain(importStatement)\n expect(success).toBe(false)\n\n expect(warnLogSpy).toHaveBeenCalledWith(\n expect.stringContaining('Could not automatically wrap'),\n )\n })\n })\n\n describe('cjs', () => {\n const configType = 'cjs'\n const requireStatement = withPayloadStatement[configType]\n it('should parse the default next config', () => {\n const { modifiedConfigContent } = parseAndModifyConfigContent(\n cjsConfigs.defaultNextConfig,\n configType,\n )\n expect(modifiedConfigContent).toContain(requireStatement)\n expect(modifiedConfigContent).toContain('withPayload(nextConfig)')\n })\n it('should parse anonymous default config', () => {\n const { modifiedConfigContent } = parseAndModifyConfigContent(\n cjsConfigs.anonConfig,\n configType,\n )\n expect(modifiedConfigContent).toContain(requireStatement)\n expect(modifiedConfigContent).toContain('withPayload({})')\n })\n it('should parse the config with a function', () => {\n const { modifiedConfigContent } = parseAndModifyConfigContent(\n cjsConfigs.nextConfigWithFunc,\n configType,\n )\n expect(modifiedConfigContent).toContain('withPayload(someFunc(nextConfig))')\n })\n it('should parse the config with a function on a new line', () => {\n const { modifiedConfigContent } = parseAndModifyConfigContent(\n cjsConfigs.nextConfigWithFuncMultiline,\n configType,\n )\n expect(modifiedConfigContent).toContain(requireStatement)\n expect(modifiedConfigContent).toMatch(/withPayload\\(someFunc\\(\\n nextConfig\\n\\)\\)/)\n })\n it('should parse the config with a named export as default', () => {\n const { modifiedConfigContent } = parseAndModifyConfigContent(\n cjsConfigs.nextConfigExportNamedDefault,\n configType,\n )\n expect(modifiedConfigContent).toContain(requireStatement)\n expect(modifiedConfigContent).toContain('withPayload(wrapped)')\n })\n })\n})\n"],"names":["parseAndModifyConfigContent","withPayloadStatement","p","esmConfigs","defaultNextConfig","nextConfigWithFunc","nextConfigWithFuncMultiline","nextConfigExportNamedDefault","cjsConfigs","anonConfig","describe","configType","importStatement","it","modifiedConfigContent","expect","toContain","toMatch","warnLogSpy","jest","spyOn","log","mockImplementation","success","toBe","toHaveBeenCalledWith","stringContaining","requireStatement"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA,SAASA,2BAA2B,EAAEC,oBAAoB,QAAQ,wBAAuB;AACzF,YAAYC,OAAO,iBAAgB;AAEnC,MAAMC,aAAa;IACjBC,mBAAmB,CAAC;;;AAGtB,CAAC;IACCC,oBAAoB,CAAC;;AAEvB,CAAC;IACCC,6BAA6B,CAAC;;;;AAIhC,CAAC;IACCC,8BAA8B,CAAC;;;AAGjC,CAAC;AACD;AAEA,MAAMC,aAAa;IACjBJ,mBAAmB,CAAC;;;;AAItB,CAAC;IACCK,YAAY,CAAC,oBAAoB,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iBAAiB,EAC5BO;YAEFI,OAAOD,uBAAuBE,SAAS,CAACW;YACxCZ,OAAOD,uBAAuBE,SAAS,CAAC;QAC1C;QACAH,GAAG,yCAAyC;YAC1C,MAAM,EAAEC,qBAAqB,EAAE,GAAGd,4BAChCQ,WAAWC,UAAU,EACrBE;YAEFI,OAAOD,uBAAuBE,SAAS,CAACW;YACxCZ,OAAOD,uBAAuBE,SAAS,CAAC;QAC1C;QACAH,GAAG,2CAA2C;YAC5C,MAAM,EAAEC,qBAAqB,EAAE,GAAGd,4BAChCQ,WAAWH,kBAAkB,EAC7BM;YAEFI,OAAOD,uBAAuBE,SAAS,CAAC;QAC1C;QACAH,GAAG,yDAAyD;YAC1D,MAAM,EAAEC,qBAAqB,EAAE,GAAGd,4BAChCQ,WAAWF,2BAA2B,EACtCK;YAEFI,OAAOD,uBAAuBE,SAAS,CAACW;YACxCZ,OAAOD,uBAAuBG,OAAO,CAAC;QACxC;QACAJ,GAAG,0DAA0D;YAC3D,MAAM,EAAEC,qBAAqB,EAAE,GAAGd,4BAChCQ,WAAWD,4BAA4B,EACvCI;YAEFI,OAAOD,uBAAuBE,SAAS,CAACW;YACxCZ,OAAOD,uBAAuBE,SAAS,CAAC;QAC1C;IACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-payload-app",
3
- "version": "3.0.0-beta.0",
3
+ "version": "3.0.0-beta.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "homepage": "https://payloadcms.com",