chore: begins work to get playwright working with esm

This commit is contained in:
James
2024-03-07 16:26:36 -05:00
parent 7420dba0c9
commit fb7e671c26
14 changed files with 55 additions and 87 deletions

View File

@@ -3,6 +3,7 @@ import type { CreateMigration } from 'payload/database'
import fs from 'fs' import fs from 'fs'
import path from 'path' import path from 'path'
import { fileURLToPath } from 'url'
const migrationTemplate = (upSQL?: string, downSQL?: string) => `import { const migrationTemplate = (upSQL?: string, downSQL?: string) => `import {
MigrateUpArgs, MigrateUpArgs,
@@ -23,6 +24,9 @@ export const createMigration: CreateMigration = async function createMigration({
migrationName, migrationName,
payload, payload,
}) { }) {
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
const dir = payload.db.migrationDir const dir = payload.db.migrationDir
if (!fs.existsSync(dir)) { if (!fs.existsSync(dir)) {
fs.mkdirSync(dir) fs.mkdirSync(dir)
@@ -37,7 +41,7 @@ export const createMigration: CreateMigration = async function createMigration({
const predefinedMigrationName = file.replace('@payloadcms/db-mongodb/', '') const predefinedMigrationName = file.replace('@payloadcms/db-mongodb/', '')
migrationName = predefinedMigrationName migrationName = predefinedMigrationName
const cleanPath = path.join(__dirname, `../predefinedMigrations/${predefinedMigrationName}.js`) const cleanPath = path.join(dirname, `../predefinedMigrations/${predefinedMigrationName}.js`)
// Check if predefined migration exists // Check if predefined migration exists
if (fs.existsSync(cleanPath)) { if (fs.existsSync(cleanPath)) {

View File

@@ -60,7 +60,7 @@ export const createMigration: CreateMigration = async function createMigration(
fs.mkdirSync(dir) fs.mkdirSync(dir)
} }
const { generateDrizzleJson, generateMigration } = require('drizzle-kit/payload') const { generateDrizzleJson, generateMigration } = await import('drizzle-kit/payload')
const [yyymmdd, hhmmss] = new Date().toISOString().split('T') const [yyymmdd, hhmmss] = new Date().toISOString().split('T')
const formattedDate = yyymmdd.replace(/\D/g, '') const formattedDate = yyymmdd.replace(/\D/g, '')

View File

@@ -10,7 +10,7 @@ import type { PostgresAdapter } from './types.js'
import { buildTable } from './schema/build.js' import { buildTable } from './schema/build.js'
export const init: Init = async function init(this: PostgresAdapter) { export const init: Init = function init(this: PostgresAdapter) {
if (this.schemaName) { if (this.schemaName) {
this.pgSchema = pgSchema(this.schemaName) this.pgSchema = pgSchema(this.schemaName)
} else { } else {

View File

@@ -82,7 +82,7 @@ export async function migrate(this: PostgresAdapter): Promise<void> {
} }
async function runMigrationFile(payload: Payload, migration: Migration, batch: number) { async function runMigrationFile(payload: Payload, migration: Migration, batch: number) {
const { generateDrizzleJson } = require('drizzle-kit/payload') const { generateDrizzleJson } = await import('drizzle-kit/payload')
const start = Date.now() const start = Date.now()
const req = { payload } as PayloadRequest const req = { payload } as PayloadRequest

View File

@@ -3,6 +3,8 @@ import ConfImport from 'conf'
import { randomBytes } from 'crypto' import { randomBytes } from 'crypto'
import findUp from 'find-up' import findUp from 'find-up'
import fs from 'fs' import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'
import type { Payload } from '../../types/index.js' import type { Payload } from '../../types/index.js'
import type { AdminInitEvent } from './events/adminInit.js' import type { AdminInitEvent } from './events/adminInit.js'
@@ -99,7 +101,9 @@ const getGitID = (payload: Payload) => {
} }
const getPackageJSON = async (): Promise<PackageJSON> => { const getPackageJSON = async (): Promise<PackageJSON> => {
const packageJsonPath = await findUp('package.json', { cwd: __dirname }) const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
const packageJsonPath = await findUp('package.json', { cwd: dirname })
const jsonContent: PackageJSON = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8')) const jsonContent: PackageJSON = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'))
return jsonContent return jsonContent
} }

View File

@@ -4,8 +4,8 @@ import { fileURLToPath } from 'url'
import { ensureDirectoryExists } from './src/utilities/ensureDirExists.js' import { ensureDirectoryExists } from './src/utilities/ensureDirExists.js'
import { copyFile } from './src/utilities/copyFile.js' import { copyFile } from './src/utilities/copyFile.js'
const __filename = fileURLToPath(import.meta.url) const filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename) const dirname = path.dirname(filename)
const serverTranslationKeys = [ const serverTranslationKeys = [
'authentication:account', 'authentication:account',
@@ -422,7 +422,7 @@ function buildSchemaFile(type: 'client' | 'server') {
} }
const schemaFileContents = JSON.parse( const schemaFileContents = JSON.parse(
fs.readFileSync(path.resolve(__dirname, SOURCE_DIR, 'translation-schema.json'), 'utf8'), fs.readFileSync(path.resolve(dirname, SOURCE_DIR, 'translation-schema.json'), 'utf8'),
) )
for (const [group, selectors] of groupedProperties.entries()) { for (const [group, selectors] of groupedProperties.entries()) {
@@ -450,17 +450,17 @@ function buildSchemaFile(type: 'client' | 'server') {
schemaFileContents.required = Array.from(groupedProperties.keys()) schemaFileContents.required = Array.from(groupedProperties.keys())
fs.writeFileSync( fs.writeFileSync(
path.resolve(__dirname, DESTINATION_DIR, 'translation-schema.json'), path.resolve(dirname, DESTINATION_DIR, 'translation-schema.json'),
JSON.stringify(schemaFileContents, null, 2), JSON.stringify(schemaFileContents, null, 2),
{ flag: 'w+' }, { flag: 'w+' },
) )
} }
async function build() { async function build() {
ensureDirectoryExists(path.resolve(__dirname, `${DESTINATION_ROOT}/client`)) ensureDirectoryExists(path.resolve(dirname, `${DESTINATION_ROOT}/client`))
ensureDirectoryExists(path.resolve(__dirname, `${DESTINATION_ROOT}/api`)) ensureDirectoryExists(path.resolve(dirname, `${DESTINATION_ROOT}/api`))
const filenames = fs.readdirSync(path.resolve(__dirname, SOURCE_DIR)) const filenames = fs.readdirSync(path.resolve(dirname, SOURCE_DIR))
// build up the client and server translation files // build up the client and server translation files
for (const filename of filenames) { for (const filename of filenames) {
@@ -468,11 +468,9 @@ async function build() {
continue continue
} }
const source = JSON.parse( const source = JSON.parse(fs.readFileSync(path.resolve(dirname, SOURCE_DIR, filename), 'utf8'))
fs.readFileSync(path.resolve(__dirname, SOURCE_DIR, filename), 'utf8'),
)
const dest1 = path.resolve(__dirname, `${DESTINATION_ROOT}/client`, filename) const dest1 = path.resolve(dirname, `${DESTINATION_ROOT}/client`, filename)
const clientTranslations = sortObject(filterKeys(source, '', clientTranslationKeys)) const clientTranslations = sortObject(filterKeys(source, '', clientTranslationKeys))
fs.writeFileSync(dest1, JSON.stringify(clientTranslations, null, 2), { fs.writeFileSync(dest1, JSON.stringify(clientTranslations, null, 2), {
@@ -480,7 +478,7 @@ async function build() {
}) })
const serverTranslations = sortObject(filterKeys(source, '', serverTranslationKeys)) const serverTranslations = sortObject(filterKeys(source, '', serverTranslationKeys))
const dest2 = path.resolve(__dirname, `${DESTINATION_ROOT}/api`, filename) const dest2 = path.resolve(dirname, `${DESTINATION_ROOT}/api`, filename)
fs.writeFileSync(dest2, JSON.stringify(serverTranslations, null, 2), { fs.writeFileSync(dest2, JSON.stringify(serverTranslations, null, 2), {
flag: 'w+', flag: 'w+',
@@ -495,12 +493,12 @@ async function build() {
// copy barrel file to both client and api folders // copy barrel file to both client and api folders
copyFile( copyFile(
path.resolve(__dirname, `${SOURCE_DIR}/index.ts`), path.resolve(dirname, `${SOURCE_DIR}/index.ts`),
path.resolve(__dirname, `${DESTINATION_ROOT}/api/index.ts`), path.resolve(dirname, `${DESTINATION_ROOT}/api/index.ts`),
) )
copyFile( copyFile(
path.resolve(__dirname, `${SOURCE_DIR}/index.ts`), path.resolve(dirname, `${SOURCE_DIR}/index.ts`),
path.resolve(__dirname, `${DESTINATION_ROOT}/client/index.ts`), path.resolve(dirname, `${DESTINATION_ROOT}/client/index.ts`),
) )
} }

View File

@@ -14,5 +14,5 @@ export default defineConfig({
timeout: 45000, timeout: 45000,
}, },
workers: 16, workers: 16,
globalSetup: require.resolve('./playwright-global-setup'), globalSetup: './playwright-global-setup',
}) })

View File

@@ -1,11 +1,16 @@
import type { Page } from '@playwright/test' import type { Page } from '@playwright/test'
import { expect, test } from '@playwright/test' import { expect, test } from '@playwright/test'
import * as path from 'path'
import { fileURLToPath } from 'url'
import { initPageConsoleErrorCatch } from '../helpers' import { initPageConsoleErrorCatch } from '../helpers.js'
import { AdminUrlUtil } from '../helpers/adminUrlUtil' import { AdminUrlUtil } from '../helpers/adminUrlUtil.js'
import { initPayloadE2E } from '../helpers/configHelpers' import { initPayloadE2E } from '../helpers/configHelpers.js'
import config from './config' import config from './config.js'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
const { beforeAll, describe } = test const { beforeAll, describe } = test
@@ -14,7 +19,7 @@ describe('Admin Panel', () => {
let url: AdminUrlUtil let url: AdminUrlUtil
beforeAll(async ({ browser }) => { beforeAll(async ({ browser }) => {
const { serverURL } = await initPayloadE2E({ config, dirname: __dirname }) const { serverURL } = await initPayloadE2E({ config, dirname })
url = new AdminUrlUtil(serverURL, 'posts') url = new AdminUrlUtil(serverURL, 'posts')
const context = await browser.newContext() const context = await browser.newContext()

View File

@@ -3,6 +3,7 @@ import type { Payload } from '../../packages/payload/src/index.js'
import { getPayload } from '../../packages/payload/src/index.js' import { getPayload } from '../../packages/payload/src/index.js'
import { devUser } from '../credentials.js' import { devUser } from '../credentials.js'
import { NextRESTClient } from '../helpers/NextRESTClient.js' import { NextRESTClient } from '../helpers/NextRESTClient.js'
import { startMemoryDB } from '../startMemoryDB.js'
import { postsSlug } from './collections/Posts/index.js' import { postsSlug } from './collections/Posts/index.js'
import configPromise from './config.js' import configPromise from './config.js'
@@ -17,7 +18,8 @@ describe('_Community Tests', () => {
// Boilerplate test setup/teardown // Boilerplate test setup/teardown
// --__--__--__--__--__--__--__--__--__ // --__--__--__--__--__--__--__--__--__
beforeAll(async () => { beforeAll(async () => {
payload = await getPayload({ config: configPromise }) const config = await startMemoryDB(configPromise)
payload = await getPayload({ config })
restClient = new NextRESTClient(payload.config) restClient = new NextRESTClient(payload.config)
const data = await restClient const data = await restClient

View File

@@ -1,9 +1,9 @@
import type { Payload } from '../../packages/payload/src' import type { Payload } from '../../packages/payload/src/index.js'
import { getPayload } from '../../packages/payload/src' import { getPayload } from '../../packages/payload/src/index.js'
import { startMemoryDB } from '../startMemoryDB' import { startMemoryDB } from '../startMemoryDB.js'
import configPromise from './config' import configPromise from './config.js'
import { arraySlug } from './shared' import { arraySlug } from './shared.js'
let payload: Payload let payload: Payload

View File

@@ -1,4 +1,3 @@
import path from 'path'
import sharp from 'sharp' import sharp from 'sharp'
import type { Config, SanitizedConfig } from '../packages/payload/src/config/types.d.ts' import type { Config, SanitizedConfig } from '../packages/payload/src/config/types.d.ts'
@@ -30,7 +29,6 @@ import {
lexicalEditor, lexicalEditor,
} from '../packages/richtext-lexical/src/index.js' } from '../packages/richtext-lexical/src/index.js'
// import { slateEditor } from '../packages/richtext-slate/src/index.js' // import { slateEditor } from '../packages/richtext-slate/src/index.js'
import { CustomDashboard } from './CustomDashboard.js'
// process.env.PAYLOAD_DATABASE = 'postgres' // process.env.PAYLOAD_DATABASE = 'postgres'
@@ -67,13 +65,6 @@ export function buildConfigWithDefaults(testConfig?: Partial<Config>): Promise<S
const config: Config = { const config: Config = {
db: databaseAdapters[process.env.PAYLOAD_DATABASE || 'mongoose'], db: databaseAdapters[process.env.PAYLOAD_DATABASE || 'mongoose'],
secret: 'TEST_SECRET', secret: 'TEST_SECRET',
admin: {
components: {
views: {
Dashboard: CustomDashboard,
},
},
},
// editor: slateEditor({ // editor: slateEditor({
// admin: { // admin: {
// upload: { // upload: {
@@ -184,7 +175,6 @@ export function buildConfigWithDefaults(testConfig?: Partial<Config>): Promise<S
password: 'test', password: 'test',
}, },
...(config.admin || {}), ...(config.admin || {}),
buildPath: path.resolve(__dirname, '../build'),
} }
if (process.env.PAYLOAD_DISABLE_ADMIN === 'true') { if (process.env.PAYLOAD_DISABLE_ADMIN === 'true') {

View File

@@ -1,39 +0,0 @@
import { createServer } from 'http'
import next from 'next'
import { parse } from 'url'
type args = {
appDir: string
port?: number
}
export const bootAdminPanel = async ({ port = 3000, appDir }: args) => {
const serverURL = `http://localhost:${port}`
const app = next({
dev: true,
hostname: 'localhost',
port,
dir: appDir,
})
const handle = app.getRequestHandler()
await app.prepare()
createServer(async (req, res) => {
try {
const parsedUrl = parse(req.url, true)
console.log('Requested path: ', parsedUrl.path)
await handle(req, res, parsedUrl)
} catch (err) {
console.error('Error occurred handling', req.url, err)
res.statusCode = 500
res.end('internal server error')
}
})
.once('error', (err) => {
console.error(err)
process.exit(1)
})
.listen(port, () => {
console.log(`> Ready on ${serverURL}`)
})
}

View File

@@ -1,11 +1,11 @@
import getPort from 'get-port' import getPort from 'get-port'
import { nextDev } from 'next/dist/cli/next-dev.js'
import path from 'path' import path from 'path'
import type { Payload } from '../../packages/payload/src' import type { SanitizedConfig } from '../../packages/payload/src/config/types.js'
import type { SanitizedConfig } from '../../packages/payload/src/config/types' import type { Payload } from '../../packages/payload/src/index.js'
import { getPayload } from '../../packages/payload/src' import { getPayload } from '../../packages/payload/src/index.js'
import { bootAdminPanel } from './bootAdminPanel'
type InitializedPayload = { payload: Payload; serverURL: string } type InitializedPayload = { payload: Payload; serverURL: string }
@@ -18,6 +18,7 @@ export async function initPayloadE2E(args: {
// process.env.TURBOPACK = '1' // Not working due to turbopack pulling in mongoose, pg // process.env.TURBOPACK = '1' // Not working due to turbopack pulling in mongoose, pg
process.env.PAYLOAD_CONFIG_PATH = path.resolve(dirname, './config.ts') process.env.PAYLOAD_CONFIG_PATH = path.resolve(dirname, './config.ts')
process.env.PAYLOAD_DROP_DATABASE = 'true' process.env.PAYLOAD_DROP_DATABASE = 'true'
// @ts-expect-error
process.env.NODE_ENV = 'test' process.env.NODE_ENV = 'test'
const payload = await getPayload({ config }) const payload = await getPayload({ config })
@@ -27,7 +28,7 @@ export async function initPayloadE2E(args: {
process.env.APP_ENV = 'test' process.env.APP_ENV = 'test'
process.env.__NEXT_TEST_MODE = 'jest' process.env.__NEXT_TEST_MODE = 'jest'
await bootAdminPanel({ port, appDir: path.resolve(__dirname, '../../') }) nextDev({ _: [path.resolve(dirname, '../../')], port: process.env.PORT || 3000 })
return { serverURL, payload } return { serverURL, payload }
} }

View File

@@ -47,6 +47,9 @@
"@payloadcms/richtext-lexical": [ "@payloadcms/richtext-lexical": [
"./packages/richtext-lexical/src" "./packages/richtext-lexical/src"
], ],
"@payloadcms/richtext-slate": [
"./packages/richtext-slate/src"
],
"@payloadcms/plugin-cloud": [ "@payloadcms/plugin-cloud": [
"./packages/plugin-cloud/src" "./packages/plugin-cloud/src"
], ],