chore: pre-builds in CI (#5690)

This commit is contained in:
James Mikrut
2024-04-06 14:10:25 -04:00
committed by GitHub
120 changed files with 505 additions and 345 deletions

View File

@@ -2,6 +2,7 @@ import type { I18n } from '@payloadcms/translations'
import type { Metadata } from 'next'
import type { SanitizedConfig } from 'payload/types'
import { getNextI18n } from '@payloadcms/next/utilities/getNextI18n.js'
import { HydrateClientUser } from '@payloadcms/ui/elements/HydrateClientUser'
import { DefaultTemplate } from '@payloadcms/ui/templates/Default'
import React, { Fragment } from 'react'
@@ -10,13 +11,18 @@ import { initPage } from '../../utilities/initPage.js'
import { NotFoundClient } from './index.client.js'
export const generatePageMetadata = async ({
i18n,
config: configPromise,
}: {
config: SanitizedConfig
i18n: I18n
config: Promise<SanitizedConfig> | SanitizedConfig
params?: { [key: string]: string | string[] }
//eslint-disable-next-line @typescript-eslint/require-await
}): Promise<Metadata> => {
const config = await configPromise
const i18n = getNextI18n({
config,
})
return {
title: i18n.t('general:notFound'),
}

View File

@@ -49,7 +49,7 @@ export const generatePageMetadata = async ({ config: configPromise, params }: Ar
const isGlobal = segmentOne === 'globals'
const isCollection = segmentOne === 'collections'
const i18n = await getNextI18n({
const i18n = getNextI18n({
config,
})

View File

@@ -12,7 +12,7 @@ if (process.env.DISABLE_SWC !== 'true') {
const dirname = path.dirname(filename)
const url = pathToFileURL(dirname).toString() + '/'
register('./dist/bin/register/index.js', url)
register('./dist/bin/loader/index.js', url)
}
bin()

View File

@@ -61,7 +61,6 @@
"nodemailer": "6.9.10",
"pino": "8.15.0",
"pino-pretty": "10.2.0",
"pirates": "^4.0.6",
"pluralize": "8.0.0",
"probe-image-size": "^7.2.3",
"sanitize-filename": "1.6.3",

View File

@@ -0,0 +1,40 @@
import type * as ts from 'typescript'
import { transform } from '@swc-node/core'
import { SourcemapMap } from '@swc-node/sourcemap-support'
import { tsCompilerOptionsToSwcConfig } from './read-default-tsconfig.js'
const injectInlineSourceMap = ({
code,
filename,
map,
}: {
code: string
filename: string
map: string | undefined
}): string => {
if (map) {
SourcemapMap.set(filename, map)
const base64Map = Buffer.from(map, 'utf8').toString('base64')
const sourceMapContent = `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${base64Map}`
return `${code}\n${sourceMapContent}`
}
return code
}
export async function compile(
sourcecode: string,
filename: string,
options: ts.CompilerOptions & { fallbackToTs?: (filename: string) => boolean },
): Promise<string> {
if (filename.endsWith('.d.ts')) {
return ''
}
const swcRegisterConfig = tsCompilerOptionsToSwcConfig(options, filename)
return transform(sourcecode, filename, swcRegisterConfig).then(({ code, map }) => {
return injectInlineSourceMap({ code, filename, map })
})
}

View File

@@ -5,7 +5,7 @@ import ts from 'typescript'
import { fileURLToPath, pathToFileURL } from 'url'
import { CLIENT_EXTENSIONS } from './clientExtensions.js'
import { compile } from './register.js'
import { compile } from './compile.js'
interface ResolveContext {
conditions: string[]
@@ -27,7 +27,13 @@ const locatedConfig = getTsconfig()
const tsconfig = locatedConfig.config.compilerOptions as unknown as ts.CompilerOptions
tsconfig.module = ts.ModuleKind.ESNext
tsconfig.moduleResolution = ts.ModuleResolutionKind.NodeNext
// Specify bundler resolution for Next.js compatibility.
// We will use TS to resolve file paths for most flexibility
tsconfig.moduleResolution = ts.ModuleResolutionKind.Bundler
// Don't resolve d.ts files, because we aren't type-checking
tsconfig.noDtsResolution = true
const moduleResolutionCache = ts.createModuleResolutionCache(
ts.sys.getCurrentDirectory(),
@@ -38,10 +44,15 @@ const host: ts.ModuleResolutionHost = {
fileExists: ts.sys.fileExists,
readFile: ts.sys.readFile,
}
const EXTENSIONS: string[] = [ts.Extension.Ts, ts.Extension.Tsx, ts.Extension.Dts, ts.Extension.Mts]
const TS_EXTENSIONS: string[] = [
ts.Extension.Ts,
ts.Extension.Tsx,
ts.Extension.Dts,
ts.Extension.Mts,
]
export const resolve: ResolveFn = async (specifier, context, nextResolve) => {
const isTS = EXTENSIONS.some((ext) => specifier.endsWith(ext))
const isTS = TS_EXTENSIONS.some((ext) => specifier.endsWith(ext))
const isClient = CLIENT_EXTENSIONS.some((ext) => specifier.endsWith(ext))
if (isClient) {
@@ -78,16 +89,21 @@ export const resolve: ResolveFn = async (specifier, context, nextResolve) => {
)
// import from local project to local project TS file
if (
resolvedModule &&
!resolvedModule.resolvedFileName.includes('/node_modules/') &&
EXTENSIONS.includes(resolvedModule.extension)
) {
return {
format: 'ts',
shortCircuit: true,
url: pathToFileURL(resolvedModule.resolvedFileName).href,
if (resolvedModule) {
const resolvedIsNodeModule = resolvedModule.resolvedFileName.includes('/node_modules/')
const resolvedIsTS = TS_EXTENSIONS.includes(resolvedModule.extension)
if (!resolvedIsNodeModule && resolvedIsTS) {
return {
format: 'ts',
shortCircuit: true,
url: pathToFileURL(resolvedModule.resolvedFileName).href,
}
}
// We want to use TS "Bundler" moduleResolution for just about all files
// so we pass the TS result here
return nextResolve(pathToFileURL(resolvedModule.resolvedFileName).href)
}
// import from local project to either:
@@ -140,7 +156,7 @@ export const load: LoadFn = async (url, context, nextLoad) => {
if (context.format === 'ts') {
const { source } = await nextLoad(url, context)
const code = typeof source === 'string' ? source : Buffer.from(source).toString()
const compiled = await compile(code, fileURLToPath(url), swcOptions, true)
const compiled = await compile(code, fileURLToPath(url), swcOptions)
return {
format: 'module',
shortCircuit: true,

View File

@@ -1,125 +0,0 @@
import type { Options } from '@swc-node/core'
import { transform, transformSync } from '@swc-node/core'
import { SourcemapMap, installSourceMapSupport } from '@swc-node/sourcemap-support'
import { getTsconfig } from 'get-tsconfig'
import { platform } from 'os'
import { resolve } from 'path'
import { addHook } from 'pirates'
import * as ts from 'typescript'
import { tsCompilerOptionsToSwcConfig } from './read-default-tsconfig.js'
const DEFAULT_EXTENSIONS = ['.js', '.jsx', '.es6', '.es', '.mjs', '.ts', '.tsx']
const PLATFORM = platform()
const injectInlineSourceMap = ({
code,
filename,
map,
}: {
code: string
filename: string
map: string | undefined
}): string => {
if (map) {
SourcemapMap.set(filename, map)
const base64Map = Buffer.from(map, 'utf8').toString('base64')
const sourceMapContent = `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${base64Map}`
return `${code}\n${sourceMapContent}`
}
return code
}
export function compile(
sourcecode: string,
filename: string,
options: ts.CompilerOptions & { fallbackToTs?: (filename: string) => boolean },
): string
export function compile(
sourcecode: string,
filename: string,
options: ts.CompilerOptions & { fallbackToTs?: (filename: string) => boolean },
async: false,
): string
export function compile(
sourcecode: string,
filename: string,
options: ts.CompilerOptions & { fallbackToTs?: (filename: string) => boolean },
async: true,
): Promise<string>
export function compile(
sourcecode: string,
filename: string,
options: ts.CompilerOptions & { fallbackToTs?: (filename: string) => boolean },
async: boolean,
): Promise<string> | string
export function compile(
sourcecode: string,
filename: string,
options: ts.CompilerOptions & { fallbackToTs?: (filename: string) => boolean },
async = false,
) {
if (filename.endsWith('.d.ts')) {
return ''
}
if (options.files && (options.files as string[]).length) {
if (
PLATFORM === 'win32' &&
(options.files as string[]).every((file) => filename !== resolve(process.cwd(), file))
) {
return sourcecode
}
if (
PLATFORM !== 'win32' &&
(options.files as string[]).every((file) => !filename.endsWith(file))
) {
return sourcecode
}
}
if (options && typeof options.fallbackToTs === 'function' && options.fallbackToTs(filename)) {
delete options.fallbackToTs
const { outputText, sourceMapText } = ts.transpileModule(sourcecode, {
compilerOptions: options,
fileName: filename,
})
return injectInlineSourceMap({ code: outputText, filename, map: sourceMapText })
}
let swcRegisterConfig: Options
if (process.env.SWCRC) {
// when SWCRC environment variable is set to true it will use swcrc file
swcRegisterConfig = {
swc: {
swcrc: true,
},
}
} else {
swcRegisterConfig = tsCompilerOptionsToSwcConfig(options, filename)
}
if (async) {
return transform(sourcecode, filename, swcRegisterConfig).then(({ code, map }) => {
return injectInlineSourceMap({ code, filename, map })
})
} else {
const { code, map } = transformSync(sourcecode, filename, swcRegisterConfig)
return injectInlineSourceMap({ code, filename, map })
}
}
export function register(options: Partial<ts.CompilerOptions> = {}, hookOpts = {}) {
const locatedConfig = getTsconfig()
const tsconfig = locatedConfig.config.compilerOptions as unknown as ts.CompilerOptions
options = tsconfig
// options.module = ts.ModuleKind.CommonJS
installSourceMapSupport()
return addHook((code, filename) => compile(code, filename, options), {
exts: DEFAULT_EXTENSIONS,
...hookOpts,
})
}

View File

@@ -1,44 +0,0 @@
import type pino from 'pino'
import { createRequire } from 'module'
import path from 'path'
import type { SanitizedConfig } from './types.js'
import { CLIENT_EXTENSIONS } from '../bin/register/clientExtensions.js'
import Logger from '../utilities/logger.js'
import { findConfig } from './find.js'
import { validateSchema } from './validate.js'
const require = createRequire(import.meta.url)
const loadConfig = async (logger?: pino.Logger): Promise<SanitizedConfig> => {
const localLogger = logger ?? Logger()
const configPath = findConfig()
CLIENT_EXTENSIONS.forEach((ext) => {
require.extensions[ext] = () => null
})
const configPromise = await import(configPath)
let config = await configPromise
if ('default' in config) config = await config.default
if (process.env.NODE_ENV !== 'production') {
config = validateSchema(config, localLogger)
}
return {
...config,
paths: {
config: configPath,
configDir: path.dirname(configPath),
rawConfig: configPath,
},
}
}
export default loadConfig

View File

@@ -1,7 +1,6 @@
'use client'
// TODO: abstract the `next/navigation` dependency out from this component
import { usePathname, useRouter } from 'next/navigation.js'
import queryString from 'qs'
import { useRouter } from 'next/navigation.js'
import React, { useCallback } from 'react'
export type SortColumnProps = {
@@ -22,9 +21,8 @@ const baseClass = 'sort-column'
export const SortColumn: React.FC<SortColumnProps> = (props) => {
const { name, Label, disable = false, label } = props
const { searchParams } = useSearchParams()
const { searchParams, stringifyParams } = useSearchParams()
const router = useRouter()
const pathname = usePathname()
const { t } = useTranslation()
const { sort } = searchParams
@@ -40,17 +38,16 @@ export const SortColumn: React.FC<SortColumnProps> = (props) => {
const setSort = useCallback(
(newSort) => {
const search = queryString.stringify(
{
...searchParams,
sort: newSort,
},
{ addQueryPrefix: true },
router.replace(
stringifyParams({
params: {
sort: newSort,
},
replace: true,
}),
)
router.replace(`${pathname}?${search}`)
},
[searchParams, pathname, router],
[router, stringifyParams],
)
return (