chore: run eslint & prettier, adjust perfectionist sorting for package.json and tsconfig.json in eslint configs

This commit is contained in:
Alessio Gravili
2023-09-19 11:41:56 +02:00
parent 4f68b722dc
commit cdaa0acd61
332 changed files with 17301 additions and 3409 deletions

View File

@@ -11,6 +11,28 @@ module.exports = {
'perfectionist/sort-objects': 'off', 'perfectionist/sort-objects': 'off',
}, },
}, },
{
files: ['package.json', 'tsconfig.json'],
rules: {
'perfectionist/sort-array-includes': 'off',
'perfectionist/sort-astro-attributes': 'off',
'perfectionist/sort-classes': 'off',
'perfectionist/sort-enums': 'off',
'perfectionist/sort-exports': 'off',
'perfectionist/sort-imports': 'off',
'perfectionist/sort-interfaces': 'off',
'perfectionist/sort-jsx-props': 'off',
'perfectionist/sort-keys': 'off',
'perfectionist/sort-maps': 'off',
'perfectionist/sort-named-exports': 'off',
'perfectionist/sort-named-imports': 'off',
'perfectionist/sort-object-types': 'off',
'perfectionist/sort-objects': 'off',
'perfectionist/sort-svelte-attributes': 'off',
'perfectionist/sort-union-types': 'off',
'perfectionist/sort-vue-attributes': 'off',
},
},
], ],
root: true, root: true,
} }

View File

@@ -0,0 +1,10 @@
.tmp
**/.git
**/.hg
**/.pnp.*
**/.svn
**/.yarn/**
**/build
**/dist/**
**/node_modules
**/temp

View File

@@ -0,0 +1,43 @@
/** @type {import('prettier').Config} */
module.exports = {
extends: ['@payloadcms'],
overrides: [
{
extends: ['plugin:@typescript-eslint/disable-type-checked'],
files: ['*.js', '*.cjs', '*.json', '*.md', '*.yml', '*.yaml'],
},
{
files: ['**/*.ts'],
rules: {
'@typescript-eslint/no-redundant-type-constituents': 'off',
},
},
{
files: ['package.json', 'tsconfig.json'],
rules: {
'perfectionist/sort-array-includes': 'off',
'perfectionist/sort-astro-attributes': 'off',
'perfectionist/sort-classes': 'off',
'perfectionist/sort-enums': 'off',
'perfectionist/sort-exports': 'off',
'perfectionist/sort-imports': 'off',
'perfectionist/sort-interfaces': 'off',
'perfectionist/sort-jsx-props': 'off',
'perfectionist/sort-keys': 'off',
'perfectionist/sort-maps': 'off',
'perfectionist/sort-named-exports': 'off',
'perfectionist/sort-named-imports': 'off',
'perfectionist/sort-object-types': 'off',
'perfectionist/sort-objects': 'off',
'perfectionist/sort-svelte-attributes': 'off',
'perfectionist/sort-union-types': 'off',
'perfectionist/sort-vue-attributes': 'off',
},
},
],
parserOptions: {
project: ['./tsconfig.json'],
tsconfigRootDir: __dirname,
},
root: true,
}

View File

@@ -0,0 +1,10 @@
.tmp
**/.git
**/.hg
**/.pnp.*
**/.svn
**/.yarn/**
**/build
**/dist/**
**/node_modules
**/temp

View File

@@ -1,15 +1,16 @@
/* eslint-disable no-param-reassign */ /* eslint-disable no-param-reassign */
import path from 'path' import type { SanitizedConfig } from 'payload/config'
// @ts-expect-error // @ts-expect-error
import type { InlineConfig } from 'vite' import type { InlineConfig } from 'vite'
import viteCommonJS from 'vite-plugin-commonjs'
import virtual from 'vite-plugin-virtual'
import scss from 'rollup-plugin-scss'
import image from '@rollup/plugin-image'
import rollupCommonJS from '@rollup/plugin-commonjs' import rollupCommonJS from '@rollup/plugin-commonjs'
import image from '@rollup/plugin-image'
import react from '@vitejs/plugin-react' import react from '@vitejs/plugin-react'
import getPort from 'get-port' import getPort from 'get-port'
import type { SanitizedConfig } from 'payload/config' import path from 'path'
import scss from 'rollup-plugin-scss'
import viteCommonJS from 'vite-plugin-commonjs'
import virtual from 'vite-plugin-virtual'
const bundlerPath = path.resolve(__dirname, '../') const bundlerPath = path.resolve(__dirname, '../')
const mockModulePath = path.resolve(__dirname, '../mocks/emptyModule.js') const mockModulePath = path.resolve(__dirname, '../mocks/emptyModule.js')
@@ -18,7 +19,7 @@ const mockDotENVPath = path.resolve(__dirname, '../mocks/dotENV.js')
export const getViteConfig = async (payloadConfig: SanitizedConfig): Promise<InlineConfig> => { export const getViteConfig = async (payloadConfig: SanitizedConfig): Promise<InlineConfig> => {
const { createLogger } = await import('vite') const { createLogger } = await import('vite')
const logger = createLogger('warn', { prefix: '[VITE-WARNING]', allowClearScreen: false }) const logger = createLogger('warn', { allowClearScreen: false, prefix: '[VITE-WARNING]' })
const originalWarning = logger.warn const originalWarning = logger.warn
logger.warn = (msg, options) => { logger.warn = (msg, options) => {
// TODO: fix this? removed these warnings to make debugging easier // TODO: fix this? removed these warnings to make debugging easier
@@ -60,9 +61,46 @@ export const getViteConfig = async (payloadConfig: SanitizedConfig): Promise<Inl
} }
return { return {
root: path.resolve(__dirname, '../'),
base: payloadConfig.routes.admin, base: payloadConfig.routes.admin,
build: {
commonjsOptions: {
include: [/payload/],
transformMixedEsModules: true,
},
outDir: payloadConfig.admin.buildPath,
rollupOptions: {
// output: {
// manualChunks: {
// jsonWorker: ['monaco-editor/esm/vs/language/json/json.worker'],
// cssWorker: ['monaco-editor/esm/vs/language/css/css.worker'],
// htmlWorker: ['monaco-editor/esm/vs/language/html/html.worker'],
// tsWorker: ['monaco-editor/esm/vs/language/typescript/ts.worker'],
// editorWorker: ['monaco-editor/esm/vs/editor/editor.worker'],
// },
// },
input: {
main: path.resolve(__dirname, '../index.html'),
},
plugins: [
image(),
rollupCommonJS(),
scss({
output: path.resolve(payloadConfig.admin.buildPath, 'styles.css'),
outputStyle: 'compressed',
// include: [`${relativeAdminPath}/**/*.scss`],
}),
],
treeshake: true,
},
},
customLogger: logger, customLogger: logger,
define: {
__dirname: '""',
'module.hot': 'undefined',
'process.argv': '[]',
'process.cwd': '() => ""',
'process.env': '{}',
},
optimizeDeps: { optimizeDeps: {
exclude: [ exclude: [
// Dependencies that need aliases should be excluded // Dependencies that need aliases should be excluded
@@ -79,22 +117,6 @@ export const getViteConfig = async (payloadConfig: SanitizedConfig): Promise<Inl
// '@monaco-editor/react', // '@monaco-editor/react',
], ],
}, },
server: {
middlewareMode: true,
hmr: {
port: hmrPort,
},
},
resolve: {
alias,
},
define: {
__dirname: '""',
'module.hot': 'undefined',
'process.env': '{}',
'process.cwd': '() => ""',
'process.argv': '[]',
},
plugins: [ plugins: [
{ {
name: 'absolute-aliases', name: 'absolute-aliases',
@@ -119,8 +141,8 @@ export const getViteConfig = async (payloadConfig: SanitizedConfig): Promise<Inl
}, },
virtual({ virtual({
crypto: 'export default {}', crypto: 'export default {}',
https: 'export default {}',
http: 'export default {}', http: 'export default {}',
https: 'export default {}',
}), }),
react(), react(),
// viteCommonJS(), // viteCommonJS(),
@@ -138,36 +160,15 @@ export const getViteConfig = async (payloadConfig: SanitizedConfig): Promise<Inl
// }, // },
// }, // },
], ],
build: { resolve: {
outDir: payloadConfig.admin.buildPath, alias,
commonjsOptions: {
transformMixedEsModules: true,
include: [/payload/],
},
rollupOptions: {
// output: {
// manualChunks: {
// jsonWorker: ['monaco-editor/esm/vs/language/json/json.worker'],
// cssWorker: ['monaco-editor/esm/vs/language/css/css.worker'],
// htmlWorker: ['monaco-editor/esm/vs/language/html/html.worker'],
// tsWorker: ['monaco-editor/esm/vs/language/typescript/ts.worker'],
// editorWorker: ['monaco-editor/esm/vs/editor/editor.worker'],
// },
// },
plugins: [
image(),
rollupCommonJS(),
scss({
output: path.resolve(payloadConfig.admin.buildPath, 'styles.css'),
outputStyle: 'compressed',
// include: [`${relativeAdminPath}/**/*.scss`],
}),
],
treeshake: true,
input: {
main: path.resolve(__dirname, '../index.html'),
}, },
root: path.resolve(__dirname, '../'),
server: {
hmr: {
port: hmrPort,
}, },
middlewareMode: true,
}, },
} }
} }

View File

@@ -1,8 +1,8 @@
// eslint-disable-next-line @typescript-eslint/ban-ts-comment // eslint-disable-next-line @typescript-eslint/ban-ts-comment
import { Root } from 'payload/components/root'
// @ts-ignore - need to do this because this file doesn't actually exist // @ts-ignore - need to do this because this file doesn't actually exist
import React from 'react' import React from 'react'
import { createRoot } from 'react-dom/client' import { createRoot } from 'react-dom/client'
import { Root } from 'payload/components/root'
const container = document.getElementById('app') const container = document.getElementById('app')
const root = createRoot(container) // createRoot(container!) if you use TypeScript const root = createRoot(container) // createRoot(container!) if you use TypeScript

View File

@@ -1,12 +1,14 @@
// @ts-expect-error // @ts-expect-error
import type { InlineConfig } from 'vite' import type { InlineConfig } from 'vite'
import { PayloadBundler } from './types'
import { devAdmin } from './scripts/dev' import type { PayloadBundler } from './types'
import { buildAdmin } from './scripts/build' import { buildAdmin } from './scripts/build'
import { devAdmin } from './scripts/dev'
import { serveAdmin } from './scripts/serve' import { serveAdmin } from './scripts/serve'
export const viteBundler: (viteConfig?: InlineConfig) => PayloadBundler = (viteConfig) => ({ export const viteBundler: (viteConfig?: InlineConfig) => PayloadBundler = (viteConfig) => ({
dev: async (payload) => devAdmin({ payload, viteConfig }),
build: async (payloadConfig) => buildAdmin({ payloadConfig, viteConfig }), build: async (payloadConfig) => buildAdmin({ payloadConfig, viteConfig }),
dev: async (payload) => devAdmin({ payload, viteConfig }),
serve: async (payload) => serveAdmin({ payload }), serve: async (payload) => serveAdmin({ payload }),
}) })

View File

@@ -1 +1 @@
export default () => {}; export default () => {}

View File

@@ -1,3 +1,3 @@
export default { export default {
config: () => null, config: () => null,
}; }

View File

@@ -1 +1 @@
export default () => { }; export default () => {}

View File

@@ -1 +1 @@
export default 'file-stub'; export default 'file-stub'

View File

@@ -1,6 +1,6 @@
// @ts-expect-error import type { SanitizedConfig } from 'payload/config'
import type { InlineConfig } from 'vite' import type { InlineConfig } from 'vite'
import { SanitizedConfig } from 'payload/config'
import { getViteConfig } from '../configs/vite' import { getViteConfig } from '../configs/vite'
type BuildAdminType = (options: { type BuildAdminType = (options: {

View File

@@ -1,8 +1,10 @@
// @ts-expect-error
import type { InlineConfig } from 'vite'
import express from 'express'
import type { PayloadHandler } from 'payload/config' import type { PayloadHandler } from 'payload/config'
import { Payload } from '../../../payload' import type { InlineConfig } from 'vite'
import express from 'express'
import type { Payload } from '../../../payload'
import { getViteConfig } from '../configs/vite' import { getViteConfig } from '../configs/vite'
const router = express.Router() const router = express.Router()

View File

@@ -1,8 +1,9 @@
import express from 'express' import type { Payload } from 'payload'
import type { PayloadHandler } from 'payload/config'
import compression from 'compression' import compression from 'compression'
import history from 'connect-history-api-fallback' import history from 'connect-history-api-fallback'
import type { PayloadHandler } from 'payload/config' import express from 'express'
import type { Payload } from 'payload'
const router = express.Router() const router = express.Router()

View File

@@ -1,8 +1,8 @@
import type { PayloadHandler, SanitizedConfig } from 'payload/config'
import type { Payload } from 'payload' import type { Payload } from 'payload'
import type { PayloadHandler, SanitizedConfig } from 'payload/config'
export interface PayloadBundler { export interface PayloadBundler {
dev: (payload: Payload) => Promise<PayloadHandler> // this would be a typical Express middleware handler
build: (payloadConfig: SanitizedConfig) => Promise<void> // used in `payload build` build: (payloadConfig: SanitizedConfig) => Promise<void> // used in `payload build`
dev: (payload: Payload) => Promise<PayloadHandler> // this would be a typical Express middleware handler
serve: (payload: Payload) => Promise<PayloadHandler> // serve built files in production serve: (payload: Payload) => Promise<PayloadHandler> // serve built files in production
} }

View File

@@ -0,0 +1,10 @@
.tmp
**/.git
**/.hg
**/.pnp.*
**/.svn
**/.yarn/**
**/build
**/dist/**
**/node_modules
**/temp

View File

@@ -0,0 +1,43 @@
/** @type {import('prettier').Config} */
module.exports = {
extends: ['@payloadcms'],
overrides: [
{
extends: ['plugin:@typescript-eslint/disable-type-checked'],
files: ['*.js', '*.cjs', '*.json', '*.md', '*.yml', '*.yaml'],
},
{
files: ['**/*.ts'],
rules: {
'@typescript-eslint/no-redundant-type-constituents': 'off',
},
},
{
files: ['package.json', 'tsconfig.json'],
rules: {
'perfectionist/sort-array-includes': 'off',
'perfectionist/sort-astro-attributes': 'off',
'perfectionist/sort-classes': 'off',
'perfectionist/sort-enums': 'off',
'perfectionist/sort-exports': 'off',
'perfectionist/sort-imports': 'off',
'perfectionist/sort-interfaces': 'off',
'perfectionist/sort-jsx-props': 'off',
'perfectionist/sort-keys': 'off',
'perfectionist/sort-maps': 'off',
'perfectionist/sort-named-exports': 'off',
'perfectionist/sort-named-imports': 'off',
'perfectionist/sort-object-types': 'off',
'perfectionist/sort-objects': 'off',
'perfectionist/sort-svelte-attributes': 'off',
'perfectionist/sort-union-types': 'off',
'perfectionist/sort-vue-attributes': 'off',
},
},
],
parserOptions: {
project: ['./tsconfig.json'],
tsconfigRootDir: __dirname,
},
root: true,
}

View File

@@ -0,0 +1,10 @@
.tmp
**/.git
**/.hg
**/.pnp.*
**/.svn
**/.yarn/**
**/build
**/dist/**
**/node_modules
**/temp

View File

@@ -1,7 +1,9 @@
import path from 'path'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import webpack, { Configuration } from 'webpack'
import type { SanitizedConfig } from 'payload/config' import type { SanitizedConfig } from 'payload/config'
import type { Configuration } from 'webpack'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import path from 'path'
import webpack from 'webpack'
const mockModulePath = path.resolve(__dirname, '../mocks/emptyModule.js') const mockModulePath = path.resolve(__dirname, '../mocks/emptyModule.js')
const mockDotENVPath = path.resolve(__dirname, '../mocks/dotENV.js') const mockDotENVPath = path.resolve(__dirname, '../mocks/dotENV.js')
@@ -17,8 +19,8 @@ export const getBaseConfig = (payloadConfig: SanitizedConfig): Configuration =>
module: { module: {
rules: [ rules: [
{ {
test: /\.(t|j)sx?$/,
exclude: /\/node_modules\/(?!.+\.tsx?$).*$/, exclude: /\/node_modules\/(?!.+\.tsx?$).*$/,
test: /\.(t|j)sx?$/,
use: [ use: [
{ {
loader: require.resolve('swc-loader'), loader: require.resolve('swc-loader'),
@@ -43,23 +45,6 @@ export const getBaseConfig = (payloadConfig: SanitizedConfig): Configuration =>
}, },
], ],
}, },
resolve: {
fallback: {
crypto: false,
https: false,
http: false,
},
modules: ['node_modules', nodeModulesPath],
alias: {
path: require.resolve('path-browserify'),
'payload-config': payloadConfig.paths.rawConfig,
payload$: mockModulePath,
'payload-user-css': payloadConfig.admin.css,
dotenv: mockDotENVPath,
[bundlerPath]: mockModulePath,
},
extensions: ['.ts', '.tsx', '.js', '.json'],
},
plugins: [ plugins: [
new webpack.ProvidePlugin({ process: require.resolve('process/browser') }), new webpack.ProvidePlugin({ process: require.resolve('process/browser') }),
new webpack.DefinePlugin( new webpack.DefinePlugin(
@@ -75,9 +60,26 @@ export const getBaseConfig = (payloadConfig: SanitizedConfig): Configuration =>
}, {}), }, {}),
), ),
new HtmlWebpackPlugin({ new HtmlWebpackPlugin({
template: payloadConfig.admin.indexHTML,
filename: path.normalize('./index.html'), filename: path.normalize('./index.html'),
template: payloadConfig.admin.indexHTML,
}), }),
new webpack.HotModuleReplacementPlugin(), new webpack.HotModuleReplacementPlugin(),
], ],
resolve: {
alias: {
[bundlerPath]: mockModulePath,
dotenv: mockDotENVPath,
path: require.resolve('path-browserify'),
payload$: mockModulePath,
'payload-config': payloadConfig.paths.rawConfig,
'payload-user-css': payloadConfig.admin.css,
},
extensions: ['.ts', '.tsx', '.js', '.json'],
fallback: {
crypto: false,
http: false,
https: false,
},
modules: ['node_modules', nodeModulesPath],
},
}) })

View File

@@ -1,20 +1,40 @@
import webpack, { Configuration } from 'webpack' import type { SanitizedConfig } from 'payload/config'
import type { Configuration } from 'webpack'
import md5 from 'md5' import md5 from 'md5'
import webpack from 'webpack'
import { getBaseConfig } from './base' import { getBaseConfig } from './base'
import { SanitizedConfig } from 'payload/config'
export const getDevConfig = (payloadConfig: SanitizedConfig): Configuration => { export const getDevConfig = (payloadConfig: SanitizedConfig): Configuration => {
const baseConfig = getBaseConfig(payloadConfig) as any const baseConfig = getBaseConfig(payloadConfig) as any
let webpackConfig: Configuration = { let webpackConfig: Configuration = {
...baseConfig, ...baseConfig,
cache: {
type: 'filesystem',
// version cache when there are changes to aliases
buildDependencies: {
config: [__filename],
},
version: md5(Object.entries(baseConfig.resolve.alias).join()),
},
devtool: 'inline-source-map',
entry: {
...baseConfig.entry,
main: [
`webpack-hot-middleware/client?path=${payloadConfig.routes.admin}/__webpack_hmr`,
...(baseConfig.entry.main as string[]),
],
},
mode: 'development',
module: { module: {
...baseConfig.module, ...baseConfig.module,
rules: [ rules: [
...baseConfig.module.rules, ...baseConfig.module.rules,
{ {
test: /\.(scss|css)$/,
sideEffects: true, sideEffects: true,
test: /\.(scss|css)$/,
/* /*
* The loaders here are run in reverse order. Here is how your loaders are being processed: * The loaders here are run in reverse order. Here is how your loaders are being processed:
* 1. sass-loader: This loader compiles your SCSS into CSS. * 1. sass-loader: This loader compiles your SCSS into CSS.
@@ -43,30 +63,13 @@ export const getDevConfig = (payloadConfig: SanitizedConfig): Configuration => {
}, },
], ],
}, },
cache: {
type: 'filesystem',
// version cache when there are changes to aliases
version: md5(Object.entries(baseConfig.resolve.alias).join()),
buildDependencies: {
config: [__filename],
},
},
entry: {
...baseConfig.entry,
main: [
`webpack-hot-middleware/client?path=${payloadConfig.routes.admin}/__webpack_hmr`,
...(baseConfig.entry.main as string[]),
],
},
output: { output: {
publicPath: `${payloadConfig.routes.admin}/`,
path: '/',
filename: '[name].js', filename: '[name].js',
path: '/',
publicPath: `${payloadConfig.routes.admin}/`,
}, },
devtool: 'inline-source-map',
mode: 'development',
stats: 'errors-warnings',
plugins: [...baseConfig.plugins, new webpack.HotModuleReplacementPlugin()], plugins: [...baseConfig.plugins, new webpack.HotModuleReplacementPlugin()],
stats: 'errors-warnings',
} }
if (payloadConfig.admin.webpack && typeof payloadConfig.admin.webpack === 'function') { if (payloadConfig.admin.webpack && typeof payloadConfig.admin.webpack === 'function') {

View File

@@ -1,22 +1,26 @@
import { Configuration, WebpackPluginInstance } from 'webpack' import type { SanitizedConfig } from 'payload/config'
import type { Configuration } from 'webpack'
import MiniCSSExtractPlugin from 'mini-css-extract-plugin' import MiniCSSExtractPlugin from 'mini-css-extract-plugin'
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer'
import { SwcMinifyWebpackPlugin } from 'swc-minify-webpack-plugin' import { SwcMinifyWebpackPlugin } from 'swc-minify-webpack-plugin'
import { WebpackPluginInstance } from 'webpack'
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer'
import { getBaseConfig } from './base' import { getBaseConfig } from './base'
import { SanitizedConfig } from 'payload/config'
export const getProdConfig = (payloadConfig: SanitizedConfig): Configuration => { export const getProdConfig = (payloadConfig: SanitizedConfig): Configuration => {
const baseConfig = getBaseConfig(payloadConfig) as any const baseConfig = getBaseConfig(payloadConfig) as any
let webpackConfig: Configuration = { let webpackConfig: Configuration = {
...baseConfig, ...baseConfig,
mode: 'production',
module: { module: {
...baseConfig.module, ...baseConfig.module,
rules: [ rules: [
...baseConfig.module.rules, ...baseConfig.module.rules,
{ {
test: /\.(scss|css)$/,
sideEffects: true, sideEffects: true,
test: /\.(scss|css)$/,
use: [ use: [
MiniCSSExtractPlugin.loader, MiniCSSExtractPlugin.loader,
{ {
@@ -38,27 +42,25 @@ export const getProdConfig = (payloadConfig: SanitizedConfig): Configuration =>
}, },
], ],
}, },
output: {
publicPath: `${payloadConfig.routes.admin}/`,
path: payloadConfig.admin.buildPath,
filename: '[name].[chunkhash].js',
chunkFilename: '[name].[chunkhash].js',
},
mode: 'production',
stats: 'errors-only',
optimization: { optimization: {
minimizer: [new SwcMinifyWebpackPlugin()], minimizer: [new SwcMinifyWebpackPlugin()],
splitChunks: { splitChunks: {
cacheGroups: { cacheGroups: {
styles: { styles: {
name: 'styles', name: 'styles',
test: /\.(sa|sc|c)ss$/,
chunks: 'all', chunks: 'all',
enforce: true, enforce: true,
test: /\.(sa|sc|c)ss$/,
}, },
}, },
}, },
}, },
output: {
chunkFilename: '[name].[chunkhash].js',
filename: '[name].[chunkhash].js',
path: payloadConfig.admin.buildPath,
publicPath: `${payloadConfig.routes.admin}/`,
},
plugins: [ plugins: [
...baseConfig.plugins, ...baseConfig.plugins,
new MiniCSSExtractPlugin({ new MiniCSSExtractPlugin({
@@ -67,6 +69,7 @@ export const getProdConfig = (payloadConfig: SanitizedConfig): Configuration =>
}), }),
...(process.env.PAYLOAD_ANALYZE_BUNDLE ? [new BundleAnalyzerPlugin()] : []), ...(process.env.PAYLOAD_ANALYZE_BUNDLE ? [new BundleAnalyzerPlugin()] : []),
], ],
stats: 'errors-only',
} }
if (payloadConfig.admin.webpack && typeof payloadConfig.admin.webpack === 'function') { if (payloadConfig.admin.webpack && typeof payloadConfig.admin.webpack === 'function') {

View File

@@ -1,11 +1,12 @@
/* eslint-disable @typescript-eslint/no-var-requires */ /* eslint-disable @typescript-eslint/no-var-requires */
import { PayloadBundler } from '../../payload/dist/bundlers/types' import type { PayloadBundler } from '../../payload/dist/bundlers/types'
import { devAdmin } from './scripts/dev'
import { buildAdmin } from './scripts/build' import { buildAdmin } from './scripts/build'
import { devAdmin } from './scripts/dev'
import { serveAdmin } from './scripts/serve' import { serveAdmin } from './scripts/serve'
export const webpackBundler: () => PayloadBundler = () => ({ export const webpackBundler: () => PayloadBundler = () => ({
dev: async (payload) => devAdmin({ payload }),
build: async (payloadConfig) => buildAdmin({ payloadConfig }), build: async (payloadConfig) => buildAdmin({ payloadConfig }),
dev: async (payload) => devAdmin({ payload }),
serve: async (payload) => serveAdmin({ payload }), serve: async (payload) => serveAdmin({ payload }),
}) })

View File

@@ -1,6 +1,8 @@
import type { SanitizedConfig } from 'payload/config'
import webpack from 'webpack' import webpack from 'webpack'
import { getProdConfig } from '../configs/prod' import { getProdConfig } from '../configs/prod'
import { SanitizedConfig } from 'payload/config'
type BuildAdminType = (options: { payloadConfig: SanitizedConfig }) => Promise<void> type BuildAdminType = (options: { payloadConfig: SanitizedConfig }) => Promise<void>
export const buildAdmin: BuildAdminType = async ({ payloadConfig }) => { export const buildAdmin: BuildAdminType = async ({ payloadConfig }) => {

View File

@@ -1,10 +1,12 @@
import webpack from 'webpack' import type { Payload } from 'payload'
import type { PayloadHandler } from 'payload/config'
import history from 'connect-history-api-fallback'
import express from 'express' import express from 'express'
import webpack from 'webpack'
import webpackDevMiddleware from 'webpack-dev-middleware' import webpackDevMiddleware from 'webpack-dev-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware' import webpackHotMiddleware from 'webpack-hot-middleware'
import history from 'connect-history-api-fallback'
import type { PayloadHandler } from 'payload/config'
import { Payload } from 'payload'
import { getDevConfig } from '../configs/dev' import { getDevConfig } from '../configs/dev'
const router = express.Router() const router = express.Router()

View File

@@ -1,8 +1,9 @@
import express from 'express' import type { Payload } from 'payload'
import type { PayloadHandler } from 'payload/config'
import compression from 'compression' import compression from 'compression'
import history from 'connect-history-api-fallback' import history from 'connect-history-api-fallback'
import type { PayloadHandler } from 'payload/config' import express from 'express'
import { Payload } from 'payload'
const router = express.Router() const router = express.Router()

View File

@@ -6,6 +6,28 @@ module.exports = {
extends: ['plugin:@typescript-eslint/disable-type-checked'], extends: ['plugin:@typescript-eslint/disable-type-checked'],
files: ['*.js', '*.cjs', '*.json', '*.md', '*.yml', '*.yaml'], files: ['*.js', '*.cjs', '*.json', '*.md', '*.yml', '*.yaml'],
}, },
{
files: ['package.json', 'tsconfig.json'],
rules: {
'perfectionist/sort-array-includes': 'off',
'perfectionist/sort-astro-attributes': 'off',
'perfectionist/sort-classes': 'off',
'perfectionist/sort-enums': 'off',
'perfectionist/sort-exports': 'off',
'perfectionist/sort-imports': 'off',
'perfectionist/sort-interfaces': 'off',
'perfectionist/sort-jsx-props': 'off',
'perfectionist/sort-keys': 'off',
'perfectionist/sort-maps': 'off',
'perfectionist/sort-named-exports': 'off',
'perfectionist/sort-named-imports': 'off',
'perfectionist/sort-object-types': 'off',
'perfectionist/sort-objects': 'off',
'perfectionist/sort-svelte-attributes': 'off',
'perfectionist/sort-union-types': 'off',
'perfectionist/sort-vue-attributes': 'off',
},
},
], ],
parserOptions: { parserOptions: {
project: ['./tsconfig.json'], project: ['./tsconfig.json'],

View File

@@ -24,9 +24,9 @@ export const createVersion: CreateVersion = async function createVersion(
const [doc] = await VersionModel.create( const [doc] = await VersionModel.create(
[ [
{ {
latest: true,
autosave, autosave,
createdAt, createdAt,
latest: true,
parent, parent,
updatedAt, updatedAt,
version: versionData, version: versionData,
@@ -36,7 +36,8 @@ export const createVersion: CreateVersion = async function createVersion(
req, req,
) )
await VersionModel.updateMany({ await VersionModel.updateMany(
{
$and: [ $and: [
{ {
_id: { _id: {
@@ -54,10 +55,12 @@ export const createVersion: CreateVersion = async function createVersion(
}, },
}, },
], ],
}, { $unset: { latest: 1 } }); },
{ $unset: { latest: 1 } },
)
const result: Document = JSON.parse(JSON.stringify(doc)); const result: Document = JSON.parse(JSON.stringify(doc))
const verificationToken = doc._verificationToken; const verificationToken = doc._verificationToken
// custom id type reset // custom id type reset
result.id = result._id result.id = result._id

View File

@@ -1,8 +1,7 @@
import type { Field, TabAsField } from 'payload/types'; import type { Field, TabAsField } from 'payload/types'
import mongoose from 'mongoose';
import { createArrayFromCommaDelineated } from 'payload/utilities';
import mongoose from 'mongoose'
import { createArrayFromCommaDelineated } from 'payload/utilities'
type SanitizeQueryValueArgs = { type SanitizeQueryValueArgs = {
field: Field | TabAsField field: Field | TabAsField

View File

@@ -2,7 +2,7 @@ import type { PaginateOptions } from 'mongoose'
import type { QueryDrafts } from 'payload/database' import type { QueryDrafts } from 'payload/database'
import type { PayloadRequest } from 'payload/types' import type { PayloadRequest } from 'payload/types'
import { flattenWhereToOperators, combineQueries } from 'payload/database' import { combineQueries, flattenWhereToOperators } from 'payload/database'
import type { MongooseAdapter } from '.' import type { MongooseAdapter } from '.'
@@ -18,8 +18,8 @@ export const queryDrafts: QueryDrafts = async function queryDrafts<T>(
const collectionConfig = this.payload.collections[collection].config const collectionConfig = this.payload.collections[collection].config
const options = withSession(this, req.transactionID) const options = withSession(this, req.transactionID)
let hasNearConstraint; let hasNearConstraint
let sort; let sort
if (where) { if (where) {
const constraints = flattenWhereToOperators(where) const constraints = flattenWhereToOperators(where)
@@ -36,33 +36,33 @@ export const queryDrafts: QueryDrafts = async function queryDrafts<T>(
}) })
} }
const combinedWhere = combineQueries({ latest: { equals: true } }, where); const combinedWhere = combineQueries({ latest: { equals: true } }, where)
const versionQuery = await VersionModel.buildQuery({ const versionQuery = await VersionModel.buildQuery({
where: combinedWhere,
locale, locale,
payload: this.payload, payload: this.payload,
}); where: combinedWhere,
})
const paginationOptions: PaginateOptions = { const paginationOptions: PaginateOptions = {
page, forceCountFn: hasNearConstraint,
sort,
lean: true, lean: true,
leanWithId: true, leanWithId: true,
useEstimatedCount: hasNearConstraint,
forceCountFn: hasNearConstraint,
pagination,
options, options,
}; page,
pagination,
if (limit > 0) { sort,
paginationOptions.limit = limit; useEstimatedCount: hasNearConstraint,
// limit must also be set here, it's ignored when pagination is false
paginationOptions.options.limit = limit;
} }
const result = await VersionModel.paginate(versionQuery, paginationOptions); if (limit > 0) {
const docs = JSON.parse(JSON.stringify(result.docs)); paginationOptions.limit = limit
// limit must also be set here, it's ignored when pagination is false
paginationOptions.options.limit = limit
}
const result = await VersionModel.paginate(versionQuery, paginationOptions)
const docs = JSON.parse(JSON.stringify(result.docs))
return { return {
...result, ...result,

View File

@@ -11,7 +11,7 @@ import { withSession } from './withSession'
export const updateOne: UpdateOne = async function updateOne( export const updateOne: UpdateOne = async function updateOne(
this: MongooseAdapter, this: MongooseAdapter,
{ collection, data, id, locale, req = {} as PayloadRequest, where: whereArg }, { id, collection, data, locale, req = {} as PayloadRequest, where: whereArg },
) { ) {
const where = id ? { id: { equals: id } } : whereArg const where = id ? { id: { equals: id } } : whereArg
const Model = this.collections[collection] const Model = this.collections[collection]

View File

@@ -12,6 +12,28 @@ module.exports = {
'@typescript-eslint/no-redundant-type-constituents': 'off', '@typescript-eslint/no-redundant-type-constituents': 'off',
}, },
}, },
{
files: ['package.json', 'tsconfig.json'],
rules: {
'perfectionist/sort-array-includes': 'off',
'perfectionist/sort-astro-attributes': 'off',
'perfectionist/sort-classes': 'off',
'perfectionist/sort-enums': 'off',
'perfectionist/sort-exports': 'off',
'perfectionist/sort-imports': 'off',
'perfectionist/sort-interfaces': 'off',
'perfectionist/sort-jsx-props': 'off',
'perfectionist/sort-keys': 'off',
'perfectionist/sort-maps': 'off',
'perfectionist/sort-named-exports': 'off',
'perfectionist/sort-named-imports': 'off',
'perfectionist/sort-object-types': 'off',
'perfectionist/sort-objects': 'off',
'perfectionist/sort-svelte-attributes': 'off',
'perfectionist/sort-union-types': 'off',
'perfectionist/sort-vue-attributes': 'off',
},
},
], ],
parserOptions: { parserOptions: {
project: ['./tsconfig.json'], project: ['./tsconfig.json'],

View File

@@ -1,149 +1,149 @@
import type { Connect } from 'payload/database'; import type { Connect } from 'payload/database'
import { generateDrizzleJson, pushSchema } from 'drizzle-kit/utils'; import { generateDrizzleJson, pushSchema } from 'drizzle-kit/utils'
import { eq, sql } from 'drizzle-orm'; import { eq, sql } from 'drizzle-orm'
import { drizzle } from 'drizzle-orm/node-postgres'; import { drizzle } from 'drizzle-orm/node-postgres'
import { jsonb, numeric, pgTable, varchar } from 'drizzle-orm/pg-core'; import { jsonb, numeric, pgTable, varchar } from 'drizzle-orm/pg-core'
import fs from 'fs'; import fs from 'fs'
import { configToJSONSchema } from 'payload/utilities'; import { configToJSONSchema } from 'payload/utilities'
import { Client, Pool } from 'pg'; import { Client, Pool } from 'pg'
import prompts from 'prompts'; import prompts from 'prompts'
import { v4 as uuid } from 'uuid'; import { v4 as uuid } from 'uuid'
import type { DrizzleDB, PostgresAdapter } from './types'; import type { DrizzleDB, PostgresAdapter } from './types'
// Migration table def in order to use query using drizzle // Migration table def in order to use query using drizzle
const migrationsSchema = pgTable('payload_migrations', { const migrationsSchema = pgTable('payload_migrations', {
batch: numeric('batch'),
name: varchar('name'), name: varchar('name'),
batch: numeric('batch'),
schema: jsonb('schema'), schema: jsonb('schema'),
}); })
export const connect: Connect = async function connect( export const connect: Connect = async function connect(this: PostgresAdapter, payload) {
this: PostgresAdapter, let db: DrizzleDB
payload,
) {
let db: DrizzleDB;
this.schema = { this.schema = {
...this.tables, ...this.tables,
...this.relations, ...this.relations,
...this.enums, ...this.enums,
}; }
try { try {
const sessionID = uuid(); const sessionID = uuid()
if ('pool' in this && this.pool !== false) { if ('pool' in this && this.pool !== false) {
const pool = new Pool(this.pool); const pool = new Pool(this.pool)
db = drizzle(pool, { schema: this.schema }); db = drizzle(pool, { schema: this.schema })
await pool.connect(); await pool.connect()
} }
if ('client' in this && this.client !== false) { if ('client' in this && this.client !== false) {
const client = new Client(this.client); const client = new Client(this.client)
db = drizzle(client, { schema: this.schema }); db = drizzle(client, { schema: this.schema })
await client.connect(); await client.connect()
} }
this.sessions[sessionID] = db; this.sessions[sessionID] = db
if (process.env.PAYLOAD_DROP_DATABASE === 'true') { if (process.env.PAYLOAD_DROP_DATABASE === 'true') {
this.payload.logger.info('---- DROPPING TABLES ----'); this.payload.logger.info('---- DROPPING TABLES ----')
await db.execute(sql`drop schema public cascade;\ncreate schema public;`); await db.execute(sql`drop schema public cascade;\ncreate schema public;`)
this.payload.logger.info('---- DROPPED TABLES ----'); this.payload.logger.info('---- DROPPED TABLES ----')
} }
} catch (err) { } catch (err) {
payload.logger.error( payload.logger.error(`Error: cannot connect to Postgres. Details: ${err.message}`, err)
`Error: cannot connect to Postgres. Details: ${err.message}`, process.exit(1)
err,
);
process.exit(1);
} }
this.payload.logger.info('Connected to Postgres successfully'); this.payload.logger.info('Connected to Postgres successfully')
this.db = db; this.db = db
// Only push schema if not in production // Only push schema if not in production
if (process.env.NODE_ENV === 'production') return; if (process.env.NODE_ENV === 'production') return
// This will prompt if clarifications are needed for Drizzle to push new schema // This will prompt if clarifications are needed for Drizzle to push new schema
const { apply, hasDataLoss, statementsToExecute, warnings } = await pushSchema(this.schema, this.db); const { apply, hasDataLoss, statementsToExecute, warnings } = await pushSchema(
this.schema,
this.db,
)
this.payload.logger.debug({ this.payload.logger.debug({
hasDataLoss, hasDataLoss,
msg: 'Schema push results', msg: 'Schema push results',
statementsToExecute, statementsToExecute,
warnings, warnings,
}); })
if (warnings.length) { if (warnings.length) {
this.payload.logger.warn({ this.payload.logger.warn({
msg: `Warnings detected during schema push: ${warnings.join('\n')}`, msg: `Warnings detected during schema push: ${warnings.join('\n')}`,
warnings, warnings,
}); })
if (hasDataLoss) { if (hasDataLoss) {
this.payload.logger.warn({ this.payload.logger.warn({
msg: 'DATA LOSS WARNING: Possible data loss detected if schema is pushed.', msg: 'DATA LOSS WARNING: Possible data loss detected if schema is pushed.',
}); })
} }
const { confirm: acceptWarnings } = await prompts( const { confirm: acceptWarnings } = await prompts(
{ {
name: 'confirm',
initial: false, initial: false,
message: 'Accept warnings and push schema to database?', message: 'Accept warnings and push schema to database?',
name: 'confirm',
type: 'confirm', type: 'confirm',
}, },
{ {
onCancel: () => { onCancel: () => {
process.exit(0); process.exit(0)
}, },
}, },
); )
// Exit if user does not accept warnings. // Exit if user does not accept warnings.
// Q: Is this the right type of exit for this interaction? // Q: Is this the right type of exit for this interaction?
if (!acceptWarnings) { if (!acceptWarnings) {
process.exit(0); process.exit(0)
} }
} }
this.migrationDir = '.migrations'; this.migrationDir = '.migrations'
// Create drizzle snapshot if it doesn't exist // Create drizzle snapshot if it doesn't exist
if (!fs.existsSync(`${this.migrationDir}/drizzle-snapshot.json`)) { if (!fs.existsSync(`${this.migrationDir}/drizzle-snapshot.json`)) {
// Ensure migration dir exists // Ensure migration dir exists
if (!fs.existsSync(this.migrationDir)) { if (!fs.existsSync(this.migrationDir)) {
fs.mkdirSync(this.migrationDir); fs.mkdirSync(this.migrationDir)
} }
const drizzleJSON = generateDrizzleJson(this.schema); const drizzleJSON = generateDrizzleJson(this.schema)
fs.writeFileSync(`${this.migrationDir}/drizzle-snapshot.json`, JSON.stringify(drizzleJSON, null, 2)); fs.writeFileSync(
`${this.migrationDir}/drizzle-snapshot.json`,
JSON.stringify(drizzleJSON, null, 2),
)
} }
const jsonSchema = configToJSONSchema(this.payload.config); const jsonSchema = configToJSONSchema(this.payload.config)
await apply(); await apply()
const devPush = await this.db const devPush = await this.db
.select() .select()
.from(migrationsSchema) .from(migrationsSchema)
.where(eq(migrationsSchema.batch, '-1')); .where(eq(migrationsSchema.batch, '-1'))
if (!devPush.length) { if (!devPush.length) {
await this.db.insert(migrationsSchema).values({ await this.db.insert(migrationsSchema).values({
batch: '-1',
name: 'dev', name: 'dev',
batch: '-1',
schema: JSON.stringify(jsonSchema), schema: JSON.stringify(jsonSchema),
}); })
} else { } else {
await this.db await this.db
.update(migrationsSchema) .update(migrationsSchema)
.set({ .set({
schema: JSON.stringify(jsonSchema), schema: JSON.stringify(jsonSchema),
}) })
.where(eq(migrationsSchema.batch, '-1')); .where(eq(migrationsSchema.batch, '-1'))
} }
}; }

View File

@@ -1,16 +1,12 @@
import type { Create } from 'payload/database'; import type { Create } from 'payload/database'
import toSnakeCase from 'to-snake-case'; import toSnakeCase from 'to-snake-case'
import { upsertRow } from '../upsertRow'; import { upsertRow } from '../upsertRow'
export const create: Create = async function create({ export const create: Create = async function create({ collection: collectionSlug, data, req }) {
collection: collectionSlug, const db = req.transactionID ? this.sessions[req.transactionID] : this.db
data, const collection = this.payload.collections[collectionSlug].config
req,
}) {
const db = req.transactionID ? this.sessions[req.transactionID] : this.db;
const collection = this.payload.collections[collectionSlug].config;
const result = await upsertRow({ const result = await upsertRow({
adapter: this, adapter: this,
@@ -19,7 +15,7 @@ export const create: Create = async function create({
fields: collection.fields, fields: collection.fields,
operation: 'create', operation: 'create',
tableName: toSnakeCase(collectionSlug), tableName: toSnakeCase(collectionSlug),
}); })
return result; return result
}; }

View File

@@ -1,18 +1,18 @@
import type { CreateGlobal } from 'payload/database'; import type { CreateGlobal } from 'payload/database'
import type { PayloadRequest } from 'payload/types'; import type { PayloadRequest } from 'payload/types'
import toSnakeCase from 'to-snake-case'; import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types'; import type { PostgresAdapter } from './types'
import { upsertRow } from './upsertRow'; import { upsertRow } from './upsertRow'
export const createGlobal: CreateGlobal = async function createGlobal( export const createGlobal: CreateGlobal = async function createGlobal(
this: PostgresAdapter, this: PostgresAdapter,
{ data, req = {} as PayloadRequest, slug }, { data, req = {} as PayloadRequest, slug },
) { ) {
const db = req.transactionID ? this.sessions[req.transactionID] : this.db; const db = req.transactionID ? this.sessions[req.transactionID] : this.db
const globalConfig = this.payload.globals.config.find((config) => config.slug === slug); const globalConfig = this.payload.globals.config.find((config) => config.slug === slug)
const result = await upsertRow({ const result = await upsertRow({
adapter: this, adapter: this,
@@ -21,7 +21,7 @@ export const createGlobal: CreateGlobal = async function createGlobal(
fields: globalConfig.fields, fields: globalConfig.fields,
operation: 'create', operation: 'create',
tableName: toSnakeCase(slug), tableName: toSnakeCase(slug),
}); })
return result; return result
}; }

View File

@@ -1,51 +1,48 @@
import type { DeleteMany } from 'payload/database'; import type { DeleteMany } from 'payload/database'
import type { PayloadRequest } from 'payload/types'; import type { PayloadRequest } from 'payload/types'
import toSnakeCase from 'to-snake-case'; import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types'; import type { PostgresAdapter } from './types'
import { buildFindManyArgs } from './find/buildFindManyArgs'; import { buildFindManyArgs } from './find/buildFindManyArgs'
import buildQuery from './queries/buildQuery'; import buildQuery from './queries/buildQuery'
import { transform } from './transform/read'; import { transform } from './transform/read'
export const deleteMany: DeleteMany = async function deleteMany(this: PostgresAdapter, export const deleteMany: DeleteMany = async function deleteMany(
{ this: PostgresAdapter,
collection, { collection, req = {} as PayloadRequest, where: incomingWhere },
req = {} as PayloadRequest, ) {
where: incomingWhere, const collectionConfig = this.payload.collections[collection].config
}) { const tableName = toSnakeCase(collection)
const collectionConfig = this.payload.collections[collection].config;
const tableName = toSnakeCase(collection);
const { where } = await buildQuery({ const { where } = await buildQuery({
adapter: this, adapter: this,
fields: collectionConfig.fields, fields: collectionConfig.fields,
tableName, tableName,
where: incomingWhere, where: incomingWhere,
}); })
const findManyArgs = buildFindManyArgs({ const findManyArgs = buildFindManyArgs({
adapter: this, adapter: this,
depth: 0, depth: 0,
fields: collectionConfig.fields, fields: collectionConfig.fields,
tableName, tableName,
}); })
findManyArgs.where = where; findManyArgs.where = where
const docsToDelete = await this.db.query[tableName].findMany(findManyArgs); const docsToDelete = await this.db.query[tableName].findMany(findManyArgs)
const result = docsToDelete.map((data) => { const result = docsToDelete.map((data) => {
return transform({ return transform({
config: this.payload.config, config: this.payload.config,
data, data,
fields: collectionConfig.fields, fields: collectionConfig.fields,
}); })
}); })
await this.db.delete(this.tables[tableName]) await this.db.delete(this.tables[tableName]).where(where)
.where(where);
return result; return result
}; }

View File

@@ -1,51 +1,46 @@
import type { DeleteOne } from 'payload/database'; import type { DeleteOne } from 'payload/database'
import type { PayloadRequest } from 'payload/types'; import type { PayloadRequest } from 'payload/types'
import toSnakeCase from 'to-snake-case'; import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types'; import type { PostgresAdapter } from './types'
import { buildFindManyArgs } from './find/buildFindManyArgs'; import { buildFindManyArgs } from './find/buildFindManyArgs'
import buildQuery from './queries/buildQuery'; import buildQuery from './queries/buildQuery'
import { transform } from './transform/read'; import { transform } from './transform/read'
export const deleteOne: DeleteOne = async function deleteOne( export const deleteOne: DeleteOne = async function deleteOne(
this: PostgresAdapter, this: PostgresAdapter,
{ { collection, req = {} as PayloadRequest, where: incomingWhere },
collection,
req = {} as PayloadRequest,
where: incomingWhere,
},
) { ) {
const collectionConfig = this.payload.collections[collection].config; const collectionConfig = this.payload.collections[collection].config
const tableName = toSnakeCase(collection); const tableName = toSnakeCase(collection)
const { where } = await buildQuery({ const { where } = await buildQuery({
adapter: this, adapter: this,
fields: collectionConfig.fields, fields: collectionConfig.fields,
tableName, tableName,
where: incomingWhere, where: incomingWhere,
}); })
const findManyArgs = buildFindManyArgs({ const findManyArgs = buildFindManyArgs({
adapter: this, adapter: this,
depth: 0, depth: 0,
fields: collectionConfig.fields, fields: collectionConfig.fields,
tableName, tableName,
}); })
findManyArgs.where = where; findManyArgs.where = where
const docToDelete = await this.db.query[tableName].findFirst(findManyArgs); const docToDelete = await this.db.query[tableName].findFirst(findManyArgs)
const result = transform({ const result = transform({
config: this.payload.config, config: this.payload.config,
data: docToDelete, data: docToDelete,
fields: collectionConfig.fields, fields: collectionConfig.fields,
}); })
await this.db.delete(this.tables[tableName]) await this.db.delete(this.tables[tableName]).where(where)
.where(where);
return result; return result
}; }

View File

@@ -1,16 +1,16 @@
import type { Find } from 'payload/database'; import type { Find } from 'payload/database'
import type { PayloadRequest, SanitizedCollectionConfig, TypeWithID } from 'payload/types'; import type { PayloadRequest, SanitizedCollectionConfig, TypeWithID } from 'payload/types'
import { asc, desc, inArray, sql } from 'drizzle-orm'; import { asc, desc, inArray, sql } from 'drizzle-orm'
import toSnakeCase from 'to-snake-case'; import toSnakeCase from 'to-snake-case'
import type { ChainedMethods } from './find/chainMethods'; import type { ChainedMethods } from './find/chainMethods'
import type { PostgresAdapter } from './types'; import type { PostgresAdapter } from './types'
import { buildFindManyArgs } from './find/buildFindManyArgs'; import { buildFindManyArgs } from './find/buildFindManyArgs'
import { chainMethods } from './find/chainMethods'; import { chainMethods } from './find/chainMethods'
import buildQuery from './queries/buildQuery'; import buildQuery from './queries/buildQuery'
import { transform } from './transform/read'; import { transform } from './transform/read'
export const find: Find = async function find( export const find: Find = async function find(
this: PostgresAdapter, this: PostgresAdapter,
@@ -48,7 +48,7 @@ export const find: Find = async function find(
const db = this.sessions?.[req.transactionID] || this.db const db = this.sessions?.[req.transactionID] || this.db
const orderedIDMap: Record<number | string, number> = {} const orderedIDMap: Record<number | string, number> = {}
const selectDistinctMethods: ChainedMethods = []; const selectDistinctMethods: ChainedMethods = []
if (orderBy?.order && orderBy?.column) { if (orderBy?.order && orderBy?.column) {
selectDistinctMethods.push({ selectDistinctMethods.push({
@@ -81,7 +81,10 @@ export const find: Find = async function find(
selectDistinctMethods.push({ args: [(page - 1) * limit], method: 'offset' }) selectDistinctMethods.push({ args: [(page - 1) * limit], method: 'offset' })
selectDistinctMethods.push({ args: [limit === 0 ? undefined : limit], method: 'limit' }) selectDistinctMethods.push({ args: [limit === 0 ? undefined : limit], method: 'limit' })
selectDistinctResult = await chainMethods({ methods: selectDistinctMethods, query: db.selectDistinct(selectFields).from(table)}) selectDistinctResult = await chainMethods({
methods: selectDistinctMethods,
query: db.selectDistinct(selectFields).from(table),
})
if (selectDistinctResult.length === 0) { if (selectDistinctResult.length === 0) {
return { return {
@@ -121,7 +124,7 @@ export const find: Find = async function find(
const findPromise = db.query[tableName].findMany(findManyArgs) const findPromise = db.query[tableName].findMany(findManyArgs)
if (pagination !== false || selectDistinctResult?.length > limit) { if (pagination !== false || selectDistinctResult?.length > limit) {
const selectCountMethods: ChainedMethods = []; const selectCountMethods: ChainedMethods = []
Object.entries(joins).forEach(([joinTable, condition]) => { Object.entries(joins).forEach(([joinTable, condition]) => {
if (joinTable) { if (joinTable) {
selectCountMethods.push({ selectCountMethods.push({
@@ -135,7 +138,7 @@ export const find: Find = async function find(
query: db query: db
.select({ count: sql<number>`count(*)` }) .select({ count: sql<number>`count(*)` })
.from(table) .from(table)
.where(where) .where(where),
}) })
totalDocs = Number(countResult[0].count) totalDocs = Number(countResult[0].count)
totalPages = typeof limit === 'number' ? Math.ceil(totalDocs / limit) : 1 totalPages = typeof limit === 'number' ? Math.ceil(totalDocs / limit) : 1

View File

@@ -1,9 +1,9 @@
import type { DBQueryConfig } from 'drizzle-orm'; import type { DBQueryConfig } from 'drizzle-orm'
import type { ArrayField, Block, Field } from 'payload/types'; import type { ArrayField, Block, Field } from 'payload/types'
import type { PostgresAdapter } from '../types'; import type { PostgresAdapter } from '../types'
import { traverseFields } from './traverseFields'; import { traverseFields } from './traverseFields'
type BuildFindQueryArgs = { type BuildFindQueryArgs = {
adapter: PostgresAdapter adapter: PostgresAdapter
@@ -24,14 +24,14 @@ export const buildFindManyArgs = ({
}: BuildFindQueryArgs): Record<string, unknown> => { }: BuildFindQueryArgs): Record<string, unknown> => {
const result: Result = { const result: Result = {
with: {}, with: {},
}; }
const _locales: Result = { const _locales: Result = {
columns: { columns: {
_parentID: false,
id: false, id: false,
_parentID: false,
}, },
}; }
if (adapter.tables[`${tableName}_relationships`]) { if (adapter.tables[`${tableName}_relationships`]) {
result.with._relationships = { result.with._relationships = {
@@ -40,15 +40,15 @@ export const buildFindManyArgs = ({
parent: false, parent: false,
}, },
orderBy: ({ order }, { asc: ASC }) => [ASC(order)], orderBy: ({ order }, { asc: ASC }) => [ASC(order)],
}; }
} }
if (adapter.tables[`${tableName}_locales`]) { if (adapter.tables[`${tableName}_locales`]) {
result.with._locales = _locales; result.with._locales = _locales
} }
const locatedBlocks: Block[] = []; const locatedBlocks: Block[] = []
const locatedArrays: { [path: string]: ArrayField } = {}; const locatedArrays: { [path: string]: ArrayField } = {}
traverseFields({ traverseFields({
_locales, _locales,
@@ -62,7 +62,7 @@ export const buildFindManyArgs = ({
path: '', path: '',
topLevelArgs: result, topLevelArgs: result,
topLevelTableName: tableName, topLevelTableName: tableName,
}); })
return result; return result
}; }

View File

@@ -1,4 +1,3 @@
export type ChainedMethods = { export type ChainedMethods = {
args: unknown[] args: unknown[]
method: string method: string
@@ -9,13 +8,10 @@ export type ChainedMethods = {
* @param methods * @param methods
* @param query * @param query
*/ */
const chainMethods = ({ const chainMethods = ({ methods, query }): Promise<unknown> => {
methods,
query,
}): Promise<unknown> => {
return methods.reduce((query, { args, method }) => { return methods.reduce((query, { args, method }) => {
return query[method](...args) return query[method](...args)
}, query) }, query)
} }
export { chainMethods } ; export { chainMethods }

View File

@@ -1,11 +1,11 @@
import type { FindOne } from 'payload/database'; import type { FindOne } from 'payload/database'
import type { PayloadRequest, SanitizedCollectionConfig } from 'payload/types'; import type { PayloadRequest, SanitizedCollectionConfig } from 'payload/types'
import toSnakeCase from 'to-snake-case'; import toSnakeCase from 'to-snake-case'
import { buildFindManyArgs } from './find/buildFindManyArgs'; import { buildFindManyArgs } from './find/buildFindManyArgs'
import buildQuery from './queries/buildQuery'; import buildQuery from './queries/buildQuery'
import { transform } from './transform/read'; import { transform } from './transform/read'
export const findOne: FindOne = async function findOne({ export const findOne: FindOne = async function findOne({
collection, collection,
@@ -13,9 +13,9 @@ export const findOne: FindOne = async function findOne({
req = {} as PayloadRequest, req = {} as PayloadRequest,
where: incomingWhere, where: incomingWhere,
}) { }) {
const db = req.transactionID ? this.sessions[req.transactionID] : this.db; const db = req.transactionID ? this.sessions[req.transactionID] : this.db
const collectionConfig: SanitizedCollectionConfig = this.payload.collections[collection].config; const collectionConfig: SanitizedCollectionConfig = this.payload.collections[collection].config
const tableName = toSnakeCase(collection); const tableName = toSnakeCase(collection)
const { where } = await buildQuery({ const { where } = await buildQuery({
adapter: this, adapter: this,
@@ -23,22 +23,22 @@ export const findOne: FindOne = async function findOne({
locale, locale,
tableName, tableName,
where: incomingWhere, where: incomingWhere,
}); })
const findManyArgs = buildFindManyArgs({ const findManyArgs = buildFindManyArgs({
adapter: this, adapter: this,
depth: 0, depth: 0,
fields: collectionConfig.fields, fields: collectionConfig.fields,
tableName, tableName,
}); })
findManyArgs.where = where; findManyArgs.where = where
const doc = await db.query[tableName].findFirst(findManyArgs); const doc = await db.query[tableName].findFirst(findManyArgs)
return transform({ return transform({
config: this.payload.config, config: this.payload.config,
data: doc, data: doc,
fields: collectionConfig.fields, fields: collectionConfig.fields,
}); })
}; }

View File

@@ -1,14 +1,14 @@
/* eslint-disable no-param-reassign */ /* eslint-disable no-param-reassign */
import type { Init } from 'payload/database'; import type { Init } from 'payload/database'
import type { SanitizedCollectionConfig } from 'payload/types'; import type { SanitizedCollectionConfig } from 'payload/types'
import { pgEnum } from 'drizzle-orm/pg-core'; import { pgEnum } from 'drizzle-orm/pg-core'
import { buildVersionCollectionFields, buildVersionGlobalFields } from 'payload/versions'; import { buildVersionCollectionFields, buildVersionGlobalFields } from 'payload/versions'
import toSnakeCase from 'to-snake-case'; import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types'; import type { PostgresAdapter } from './types'
import { buildTable } from './schema/build'; import { buildTable } from './schema/build'
export const init: Init = async function init(this: PostgresAdapter) { export const init: Init = async function init(this: PostgresAdapter) {
if (this.payload.config.localization) { if (this.payload.config.localization) {
@@ -16,12 +16,14 @@ export const init: Init = async function init(this: PostgresAdapter) {
'_locales', '_locales',
// TODO: types out of sync with core, monorepo please // TODO: types out of sync with core, monorepo please
// this.payload.config.localization.localeCodes, // this.payload.config.localization.localeCodes,
(this.payload.config.localization.locales as unknown as { code: string }[]).map(({ code }) => code) as [string, ...string[]], (this.payload.config.localization.locales as unknown as { code: string }[]).map(
); ({ code }) => code,
) as [string, ...string[]],
)
} }
this.payload.config.collections.forEach((collection: SanitizedCollectionConfig) => { this.payload.config.collections.forEach((collection: SanitizedCollectionConfig) => {
const tableName = toSnakeCase(collection.slug); const tableName = toSnakeCase(collection.slug)
buildTable({ buildTable({
adapter: this, adapter: this,
@@ -29,11 +31,11 @@ export const init: Init = async function init(this: PostgresAdapter) {
fields: collection.fields, fields: collection.fields,
tableName, tableName,
timestamps: collection.timestamps, timestamps: collection.timestamps,
}); })
if (collection.versions) { if (collection.versions) {
const versionsTableName = `_${tableName}_versions`; const versionsTableName = `_${tableName}_versions`
const versionFields = buildVersionCollectionFields(collection); const versionFields = buildVersionCollectionFields(collection)
buildTable({ buildTable({
adapter: this, adapter: this,
@@ -41,12 +43,12 @@ export const init: Init = async function init(this: PostgresAdapter) {
fields: versionFields, fields: versionFields,
tableName: versionsTableName, tableName: versionsTableName,
timestamps: true, timestamps: true,
}); })
} }
}); })
this.payload.config.globals.forEach((global) => { this.payload.config.globals.forEach((global) => {
const tableName = toSnakeCase(global.slug); const tableName = toSnakeCase(global.slug)
buildTable({ buildTable({
adapter: this, adapter: this,
@@ -54,11 +56,11 @@ export const init: Init = async function init(this: PostgresAdapter) {
fields: global.fields, fields: global.fields,
tableName, tableName,
timestamps: false, timestamps: false,
}); })
if (global.versions) { if (global.versions) {
const versionsTableName = `_${tableName}_versions`; const versionsTableName = `_${tableName}_versions`
const versionFields = buildVersionGlobalFields(global); const versionFields = buildVersionGlobalFields(global)
buildTable({ buildTable({
adapter: this, adapter: this,
@@ -66,7 +68,7 @@ export const init: Init = async function init(this: PostgresAdapter) {
fields: versionFields, fields: versionFields,
tableName: versionsTableName, tableName: versionsTableName,
timestamps: true, timestamps: true,
}); })
} }
}); })
}; }

View File

@@ -1,10 +1,10 @@
import type { SQL } from 'drizzle-orm'; import type { SQL } from 'drizzle-orm'
import type { Field, Where } from 'payload/types'; import type { Field, Where } from 'payload/types'
import type { GenericColumn, PostgresAdapter } from '../types'; import type { GenericColumn, PostgresAdapter } from '../types'
import type { BuildQueryJoins } from './buildQuery'; import type { BuildQueryJoins } from './buildQuery'
import { parseParams } from './parseParams'; import { parseParams } from './parseParams'
export async function buildAndOrConditions({ export async function buildAndOrConditions({
adapter, adapter,
@@ -16,16 +16,16 @@ export async function buildAndOrConditions({
where, where,
}: { }: {
adapter: PostgresAdapter adapter: PostgresAdapter
collectionSlug?: string, collectionSlug?: string
fields: Field[], fields: Field[]
globalSlug?: string, globalSlug?: string
joins: BuildQueryJoins, joins: BuildQueryJoins
locale?: string, locale?: string
selectFields: Record<string, GenericColumn> selectFields: Record<string, GenericColumn>
tableName: string, tableName: string
where: Where[], where: Where[]
}): Promise<SQL[]> { }): Promise<SQL[]> {
const completedConditions = []; const completedConditions = []
// Loop over all AND / OR operations and add them to the AND / OR query param // Loop over all AND / OR operations and add them to the AND / OR query param
// Operations should come through as an array // Operations should come through as an array
// eslint-disable-next-line no-restricted-syntax // eslint-disable-next-line no-restricted-syntax
@@ -41,11 +41,11 @@ export async function buildAndOrConditions({
selectFields, selectFields,
tableName, tableName,
where: condition, where: condition,
}); })
if (result && Object.keys(result).length > 0) { if (result && Object.keys(result).length > 0) {
completedConditions.push(result); completedConditions.push(result)
} }
} }
} }
return completedConditions; return completedConditions
} }

View File

@@ -1,12 +1,12 @@
import type { SQL } from 'drizzle-orm'; import type { SQL } from 'drizzle-orm'
import type { Field, Where } from 'payload/types'; import type { Field, Where } from 'payload/types'
import { asc, desc } from 'drizzle-orm'; import { asc, desc } from 'drizzle-orm'
import type { GenericColumn, PostgresAdapter } from '../types'; import type { GenericColumn, PostgresAdapter } from '../types'
import { getTableColumnFromPath } from './getTableColumnFromPath'; import { getTableColumnFromPath } from './getTableColumnFromPath'
import { parseParams } from './parseParams'; import { parseParams } from './parseParams'
export type BuildQueryJoins = Record<string, SQL> export type BuildQueryJoins = Record<string, SQL>
@@ -38,28 +38,25 @@ const buildQuery = async function buildQuery({
}: BuildQueryArgs): Promise<Result> { }: BuildQueryArgs): Promise<Result> {
const selectFields: Record<string, GenericColumn> = { const selectFields: Record<string, GenericColumn> = {
id: adapter.tables[tableName].id, id: adapter.tables[tableName].id,
}; }
const joins: BuildQueryJoins = {}; const joins: BuildQueryJoins = {}
const orderBy: Result['orderBy'] = { const orderBy: Result['orderBy'] = {
column: null, column: null,
order: null, order: null,
};
if (sort) {
let sortPath;
if (sort[0] === '-') {
sortPath = sort.substring(1);
orderBy.order = desc;
} else {
sortPath = sort;
orderBy.order = asc;
} }
const { if (sort) {
columnName: sortTableColumnName, let sortPath
table: sortTable,
} = getTableColumnFromPath({ if (sort[0] === '-') {
sortPath = sort.substring(1)
orderBy.order = desc
} else {
sortPath = sort
orderBy.order = asc
}
const { columnName: sortTableColumnName, table: sortTable } = getTableColumnFromPath({
adapter, adapter,
collectionPath: sortPath, collectionPath: sortPath,
fields, fields,
@@ -68,16 +65,16 @@ const buildQuery = async function buildQuery({
pathSegments: sortPath.replace(/__/g, '.').split('.'), pathSegments: sortPath.replace(/__/g, '.').split('.'),
selectFields, selectFields,
tableName, tableName,
}); })
orderBy.column = sortTable[sortTableColumnName]; orderBy.column = sortTable[sortTableColumnName]
if (orderBy.column) { if (orderBy.column) {
selectFields.sort = orderBy.column; selectFields.sort = orderBy.column
} }
} }
let where: SQL; let where: SQL
if (Object.keys(incomingWhere).length > 0) { if (Object.keys(incomingWhere).length > 0) {
where = await parseParams({ where = await parseParams({
@@ -88,7 +85,7 @@ const buildQuery = async function buildQuery({
selectFields, selectFields,
tableName, tableName,
where: incomingWhere, where: incomingWhere,
}); })
} }
return { return {
@@ -96,7 +93,7 @@ const buildQuery = async function buildQuery({
orderBy, orderBy,
selectFields, selectFields,
where, where,
}; }
}; }
export default buildQuery; export default buildQuery

View File

@@ -1,15 +1,15 @@
/* eslint-disable no-param-reassign */ /* eslint-disable no-param-reassign */
import type { SQL } from 'drizzle-orm'; import type { SQL } from 'drizzle-orm'
import type { Field, FieldAffectingData, TabAsField } from 'payload/types'; import type { Field, FieldAffectingData, TabAsField } from 'payload/types'
import { and, eq, sql } from 'drizzle-orm'; import { and, eq, sql } from 'drizzle-orm'
import { APIError } from 'payload/errors'; import { APIError } from 'payload/errors'
import { fieldAffectsData, tabHasName } from 'payload/types'; import { fieldAffectsData, tabHasName } from 'payload/types'
import { flattenTopLevelFields } from 'payload/utilities'; import { flattenTopLevelFields } from 'payload/utilities'
import toSnakeCase from 'to-snake-case'; import toSnakeCase from 'to-snake-case'
import type { GenericColumn, GenericTable, PostgresAdapter } from '../types'; import type { GenericColumn, GenericTable, PostgresAdapter } from '../types'
import type { BuildQueryJoins } from './buildQuery'; import type { BuildQueryJoins } from './buildQuery'
type Constraint = { type Constraint = {
columnName: string columnName: string
@@ -26,7 +26,7 @@ type TableColumn = {
} }
type Args = { type Args = {
adapter: PostgresAdapter, adapter: PostgresAdapter
collectionPath: string collectionPath: string
columnPrefix?: string columnPrefix?: string
constraints?: Constraint[] constraints?: Constraint[]
@@ -54,13 +54,14 @@ export const getTableColumnFromPath = ({
selectFields, selectFields,
tableName, tableName,
}: Args): TableColumn => { }: Args): TableColumn => {
const fieldPath = pathSegments[0]; const fieldPath = pathSegments[0]
const field = flattenTopLevelFields(fields as Field[]) const field = flattenTopLevelFields(fields as Field[]).find(
.find((fieldToFind) => fieldAffectsData(fieldToFind) && fieldToFind.name === fieldPath) as Field | TabAsField; (fieldToFind) => fieldAffectsData(fieldToFind) && fieldToFind.name === fieldPath,
let newTableName = tableName; ) as Field | TabAsField
let newTableName = tableName
if (!field && fieldPath === 'id') { if (!field && fieldPath === 'id') {
selectFields.id = adapter.tables[newTableName].id; selectFields.id = adapter.tables[newTableName].id
return { return {
columnName: 'id', columnName: 'id',
constraints, constraints,
@@ -69,7 +70,7 @@ export const getTableColumnFromPath = ({
type: 'number', type: 'number',
}, },
table: adapter.tables[newTableName], table: adapter.tables[newTableName],
}; }
} }
if (field) { if (field) {
@@ -89,7 +90,7 @@ export const getTableColumnFromPath = ({
pathSegments: pathSegments.slice(1), pathSegments: pathSegments.slice(1),
selectFields, selectFields,
tableName: newTableName, tableName: newTableName,
}); })
} }
case 'tab': { case 'tab': {
if (tabHasName(field)) { if (tabHasName(field)) {
@@ -98,38 +99,41 @@ export const getTableColumnFromPath = ({
collectionPath, collectionPath,
columnPrefix: `${columnPrefix}${field.name}_`, columnPrefix: `${columnPrefix}${field.name}_`,
constraints, constraints,
fields: field.fields , fields: field.fields,
joins, joins,
locale, locale,
pathSegments: pathSegments.slice(1), pathSegments: pathSegments.slice(1),
selectFields, selectFields,
tableName: newTableName, tableName: newTableName,
}); })
} }
return getTableColumnFromPath({ return getTableColumnFromPath({
adapter, adapter,
collectionPath, collectionPath,
columnPrefix, columnPrefix,
constraints, constraints,
fields: field.fields , fields: field.fields,
joins, joins,
locale, locale,
pathSegments: pathSegments.slice(1), pathSegments: pathSegments.slice(1),
selectFields, selectFields,
tableName: newTableName, tableName: newTableName,
}); })
} }
case 'group': { case 'group': {
if (locale && field.localized && adapter.payload.config.localization) { if (locale && field.localized && adapter.payload.config.localization) {
newTableName = `${tableName}_locales`; newTableName = `${tableName}_locales`
joins[tableName] = eq(adapter.tables[tableName].id, adapter.tables[newTableName]._parentID); joins[tableName] = eq(
adapter.tables[tableName].id,
adapter.tables[newTableName]._parentID,
)
if (locale !== 'all') { if (locale !== 'all') {
constraints.push({ constraints.push({
columnName: '_locale', columnName: '_locale',
table: adapter.tables[newTableName], table: adapter.tables[newTableName],
value: locale, value: locale,
}); })
} }
} }
return getTableColumnFromPath({ return getTableColumnFromPath({
@@ -137,31 +141,34 @@ export const getTableColumnFromPath = ({
collectionPath, collectionPath,
columnPrefix: `${columnPrefix}${field.name}_`, columnPrefix: `${columnPrefix}${field.name}_`,
constraints, constraints,
fields: field.fields , fields: field.fields,
joins, joins,
locale, locale,
pathSegments: pathSegments.slice(1), pathSegments: pathSegments.slice(1),
selectFields, selectFields,
tableName: newTableName, tableName: newTableName,
}); })
} }
case 'array': { case 'array': {
newTableName = `${tableName}_${toSnakeCase(field.name)}`; newTableName = `${tableName}_${toSnakeCase(field.name)}`
if (locale && field.localized && adapter.payload.config.localization) { if (locale && field.localized && adapter.payload.config.localization) {
joins[newTableName] = and( joins[newTableName] = and(
eq(adapter.tables[tableName].id, adapter.tables[newTableName]._parentID), eq(adapter.tables[tableName].id, adapter.tables[newTableName]._parentID),
eq(adapter.tables[newTableName]._locale, locale), eq(adapter.tables[newTableName]._locale, locale),
); )
if (locale !== 'all') { if (locale !== 'all') {
constraints.push({ constraints.push({
columnName: '_locale', columnName: '_locale',
table: adapter.tables[newTableName], table: adapter.tables[newTableName],
value: locale, value: locale,
}); })
} }
} else { } else {
joins[newTableName] = eq(adapter.tables[tableName].id, adapter.tables[newTableName]._parentID); joins[newTableName] = eq(
adapter.tables[tableName].id,
adapter.tables[newTableName]._parentID,
)
} }
return getTableColumnFromPath({ return getTableColumnFromPath({
adapter, adapter,
@@ -173,17 +180,17 @@ export const getTableColumnFromPath = ({
pathSegments: pathSegments.slice(1), pathSegments: pathSegments.slice(1),
selectFields, selectFields,
tableName: newTableName, tableName: newTableName,
}); })
} }
case 'blocks': { case 'blocks': {
let blockTableColumn: TableColumn; let blockTableColumn: TableColumn
let newTableName: string; let newTableName: string
const hasBlockField = field.blocks.some((block) => { const hasBlockField = field.blocks.some((block) => {
newTableName = `${tableName}_${toSnakeCase(block.slug)}`; newTableName = `${tableName}_${toSnakeCase(block.slug)}`
let result; let result
const blockConstraints = []; const blockConstraints = []
const blockSelectFields = {}; const blockSelectFields = {}
try { try {
result = getTableColumnFromPath({ result = getTableColumnFromPath({
adapter, adapter,
@@ -195,33 +202,36 @@ export const getTableColumnFromPath = ({
pathSegments: pathSegments.slice(1), pathSegments: pathSegments.slice(1),
selectFields: blockSelectFields, selectFields: blockSelectFields,
tableName: newTableName, tableName: newTableName,
}); })
} catch (error) { } catch (error) {
// this is fine, not every block will have the field // this is fine, not every block will have the field
} }
if (!result) { if (!result) {
return; return
} }
blockTableColumn = result; blockTableColumn = result
constraints = constraints.concat(blockConstraints); constraints = constraints.concat(blockConstraints)
selectFields = {...selectFields, ...blockSelectFields}; selectFields = { ...selectFields, ...blockSelectFields }
if (field.localized && adapter.payload.config.localization) { if (field.localized && adapter.payload.config.localization) {
joins[newTableName] = and( joins[newTableName] = and(
eq(adapter.tables[tableName].id, adapter.tables[newTableName]._parentID), eq(adapter.tables[tableName].id, adapter.tables[newTableName]._parentID),
eq(adapter.tables[newTableName]._locale, locale), eq(adapter.tables[newTableName]._locale, locale),
); )
if (locale) { if (locale) {
constraints.push({ constraints.push({
columnName: '_locale', columnName: '_locale',
table: adapter.tables[newTableName], table: adapter.tables[newTableName],
value: locale, value: locale,
}); })
} }
} else { } else {
joins[newTableName] = eq(adapter.tables[tableName].id, adapter.tables[newTableName]._parentID); joins[newTableName] = eq(
adapter.tables[tableName].id,
adapter.tables[newTableName]._parentID,
)
} }
return result; return result
}); })
if (hasBlockField) { if (hasBlockField) {
return { return {
columnName: blockTableColumn.columnName, columnName: blockTableColumn.columnName,
@@ -229,49 +239,57 @@ export const getTableColumnFromPath = ({
field: blockTableColumn.field, field: blockTableColumn.field,
rawColumn: blockTableColumn.rawColumn, rawColumn: blockTableColumn.rawColumn,
table: adapter.tables[newTableName], table: adapter.tables[newTableName],
};
} }
break; }
break
} }
case 'relationship': case 'relationship':
case 'upload': { case 'upload': {
let relationshipFields; let relationshipFields
const relationTableName = `${tableName}_relationships`; const relationTableName = `${tableName}_relationships`
const newCollectionPath = pathSegments.slice(1).join('.'); const newCollectionPath = pathSegments.slice(1).join('.')
// Join in the relationships table // Join in the relationships table
joins[relationTableName] = eq(adapter.tables[tableName].id, adapter.tables[relationTableName].parent); joins[relationTableName] = eq(
selectFields[`${relationTableName}.path`] = adapter.tables[relationTableName].path; adapter.tables[tableName].id,
adapter.tables[relationTableName].parent,
)
selectFields[`${relationTableName}.path`] = adapter.tables[relationTableName].path
constraints.push({ constraints.push({
columnName: 'path', columnName: 'path',
table: adapter.tables[relationTableName], table: adapter.tables[relationTableName],
value: field.name, value: field.name,
}); })
if (typeof field.relationTo === 'string') { if (typeof field.relationTo === 'string') {
newTableName = `${toSnakeCase(field.relationTo)}`; newTableName = `${toSnakeCase(field.relationTo)}`
// parent to relationship join table // parent to relationship join table
relationshipFields = adapter.payload.collections[field.relationTo].config.fields; relationshipFields = adapter.payload.collections[field.relationTo].config.fields
joins[newTableName] = eq(adapter.tables[newTableName].id, adapter.tables[`${tableName}_relationships`][`${field.relationTo}ID`]); joins[newTableName] = eq(
adapter.tables[newTableName].id,
adapter.tables[`${tableName}_relationships`][`${field.relationTo}ID`],
)
if (newCollectionPath === '') { if (newCollectionPath === '') {
return { return {
columnName: `${field.relationTo}ID`, columnName: `${field.relationTo}ID`,
constraints, constraints,
field, field,
table: adapter.tables[relationTableName], table: adapter.tables[relationTableName],
}; }
} }
} else if (newCollectionPath === 'value') { } else if (newCollectionPath === 'value') {
const tableColumnsNames = field.relationTo.map((relationTo) => `"${relationTableName}"."${toSnakeCase(relationTo)}_id"`); const tableColumnsNames = field.relationTo.map(
(relationTo) => `"${relationTableName}"."${toSnakeCase(relationTo)}_id"`,
)
return { return {
constraints, constraints,
field, field,
rawColumn: sql.raw(`COALESCE(${tableColumnsNames.join(', ')})`), rawColumn: sql.raw(`COALESCE(${tableColumnsNames.join(', ')})`),
table: adapter.tables[relationTableName], table: adapter.tables[relationTableName],
}; }
} else { } else {
throw new APIError('Not supported'); throw new APIError('Not supported')
} }
return getTableColumnFromPath({ return getTableColumnFromPath({
@@ -284,7 +302,7 @@ export const getTableColumnFromPath = ({
pathSegments: pathSegments.slice(1), pathSegments: pathSegments.slice(1),
selectFields, selectFields,
tableName: newTableName, tableName: newTableName,
}); })
} }
default: { default: {
@@ -302,28 +320,31 @@ export const getTableColumnFromPath = ({
// case 'point': // case 'point':
if (fieldAffectsData(field)) { if (fieldAffectsData(field)) {
if (field.localized && adapter.payload.config.localization) { if (field.localized && adapter.payload.config.localization) {
newTableName = `${tableName}_locales`; newTableName = `${tableName}_locales`
joins[newTableName] = eq(adapter.tables[tableName].id, adapter.tables[newTableName]._parentID); joins[newTableName] = eq(
adapter.tables[tableName].id,
adapter.tables[newTableName]._parentID,
)
if (locale !== 'all') { if (locale !== 'all') {
constraints.push({ constraints.push({
columnName: '_locale', columnName: '_locale',
table: adapter.tables[newTableName], table: adapter.tables[newTableName],
value: locale, value: locale,
}); })
} }
} }
selectFields[`${newTableName}.${field.name}`] = adapter.tables[newTableName][field.name]; selectFields[`${newTableName}.${field.name}`] = adapter.tables[newTableName][field.name]
return { return {
columnName: `${columnPrefix}${field.name}`, columnName: `${columnPrefix}${field.name}`,
constraints, constraints,
field, field,
table: adapter.tables[newTableName], table: adapter.tables[newTableName],
}; }
} }
} }
} }
} }
throw new APIError(`Cannot find field for path at ${fieldPath}`); throw new APIError(`Cannot find field for path at ${fieldPath}`)
}; }

View File

@@ -1,17 +1,17 @@
/* eslint-disable no-await-in-loop */ /* eslint-disable no-await-in-loop */
import type { SQL } from 'drizzle-orm'; import type { SQL } from 'drizzle-orm'
import type { Field, Operator, Where } from 'payload/types'; import type { Field, Operator, Where } from 'payload/types'
import { and } from 'drizzle-orm'; import { and } from 'drizzle-orm'
import { validOperators } from 'payload/types'; import { validOperators } from 'payload/types'
import type { GenericColumn, PostgresAdapter } from '../types'; import type { GenericColumn, PostgresAdapter } from '../types'
import type { BuildQueryJoins } from './buildQuery'; import type { BuildQueryJoins } from './buildQuery'
import { buildAndOrConditions } from './buildAndOrConditions'; import { buildAndOrConditions } from './buildAndOrConditions'
import { getTableColumnFromPath } from './getTableColumnFromPath'; import { getTableColumnFromPath } from './getTableColumnFromPath'
import { operatorMap } from './operatorMap'; import { operatorMap } from './operatorMap'
import { sanitizeQueryValue } from './sanitizeQueryValue'; import { sanitizeQueryValue } from './sanitizeQueryValue'
type Args = { type Args = {
adapter: PostgresAdapter adapter: PostgresAdapter

View File

@@ -1,13 +1,13 @@
import type { QueryDrafts } from 'payload/database'; import type { QueryDrafts } from 'payload/database'
import type { PayloadRequest, SanitizedCollectionConfig } from 'payload/types'; import type { PayloadRequest, SanitizedCollectionConfig } from 'payload/types'
import { sql } from 'drizzle-orm'; import { sql } from 'drizzle-orm'
import { buildVersionCollectionFields } from 'payload/versions'; import { buildVersionCollectionFields } from 'payload/versions'
import toSnakeCase from 'to-snake-case'; import toSnakeCase from 'to-snake-case'
import { buildFindManyArgs } from './find/buildFindManyArgs'; import { buildFindManyArgs } from './find/buildFindManyArgs'
import buildQuery from './queries/buildQuery'; import buildQuery from './queries/buildQuery'
import { transform } from './transform/read'; import { transform } from './transform/read'
export const queryDrafts: QueryDrafts = async function queryDrafts({ export const queryDrafts: QueryDrafts = async function queryDrafts({
collection, collection,
@@ -19,20 +19,21 @@ export const queryDrafts: QueryDrafts = async function queryDrafts({
sort: sortArg, sort: sortArg,
where: whereArg, where: whereArg,
}) { }) {
const db = req.transactionID ? this.sessions[req.transactionID] : this.db; const db = req.transactionID ? this.sessions[req.transactionID] : this.db
const collectionConfig: SanitizedCollectionConfig = this.payload.collections[collection].config; const collectionConfig: SanitizedCollectionConfig = this.payload.collections[collection].config
const tableName = toSnakeCase(collection); const tableName = toSnakeCase(collection)
const versionsTableName = `_${tableName}_versions`; const versionsTableName = `_${tableName}_versions`
const table = this.tables[versionsTableName]; const table = this.tables[versionsTableName]
const limit = typeof limitArg === 'number' ? limitArg : collectionConfig.admin.pagination.defaultLimit; const limit =
typeof limitArg === 'number' ? limitArg : collectionConfig.admin.pagination.defaultLimit
// TODO: use sort // TODO: use sort
const sort = typeof sortArg === 'string' ? sortArg : collectionConfig.defaultSort; const sort = typeof sortArg === 'string' ? sortArg : collectionConfig.defaultSort
let totalDocs; let totalDocs
let totalPages; let totalPages
let hasPrevPage; let hasPrevPage
let hasNextPage; let hasNextPage
let pagingCounter; let pagingCounter
const { where } = await buildQuery({ const { where } = await buildQuery({
adapter: this, adapter: this,
@@ -40,16 +41,19 @@ export const queryDrafts: QueryDrafts = async function queryDrafts({
locale, locale,
sort, sort,
tableName: versionsTableName, tableName: versionsTableName,
where: whereArg where: whereArg,
}); })
if (pagination !== false) { if (pagination !== false) {
const countResult = await db.select({ count: sql<number>`count(*)` }).from(table).where(where); const countResult = await db
totalDocs = Number(countResult[0].count); .select({ count: sql<number>`count(*)` })
totalPages = Math.ceil(totalDocs / limit); .from(table)
hasPrevPage = page > 1; .where(where)
hasNextPage = totalPages > page; totalDocs = Number(countResult[0].count)
pagingCounter = ((page - 1) * limit) + 1; totalPages = Math.ceil(totalDocs / limit)
hasPrevPage = page > 1
hasNextPage = totalPages > page
pagingCounter = (page - 1) * limit + 1
} }
const findManyArgs = buildFindManyArgs({ const findManyArgs = buildFindManyArgs({
@@ -57,21 +61,21 @@ export const queryDrafts: QueryDrafts = async function queryDrafts({
depth: 0, depth: 0,
fields: collectionConfig.fields, fields: collectionConfig.fields,
tableName, tableName,
}); })
findManyArgs.limit = limit === 0 ? undefined : limit; findManyArgs.limit = limit === 0 ? undefined : limit
findManyArgs.offset = (page - 1) * limit; findManyArgs.offset = (page - 1) * limit
findManyArgs.where = where; findManyArgs.where = where
const rawDocs = await db.query[tableName].findMany(findManyArgs); const rawDocs = await db.query[tableName].findMany(findManyArgs)
const docs = rawDocs.map((data) => { const docs = rawDocs.map((data) => {
return transform({ return transform({
config: this.payload.config, config: this.payload.config,
data, data,
fields: collectionConfig.fields, fields: collectionConfig.fields,
}); })
}); })
return { return {
docs, // : T[] docs, // : T[]
@@ -84,5 +88,5 @@ export const queryDrafts: QueryDrafts = async function queryDrafts({
prevPage: hasPrevPage ? page - 1 : null, // ?: number | null | undefined prevPage: hasPrevPage ? page - 1 : null, // ?: number | null | undefined
totalDocs, // : number totalDocs, // : number
totalPages, // : number totalPages, // : number
}; }
}; }

View File

@@ -1,21 +1,30 @@
/* eslint-disable no-param-reassign */ /* eslint-disable no-param-reassign */
import type { Relation } from 'drizzle-orm'; import type { Relation } from 'drizzle-orm'
import type { IndexBuilder, PgColumnBuilder, UniqueConstraintBuilder } from 'drizzle-orm/pg-core'; import type { IndexBuilder, PgColumnBuilder, UniqueConstraintBuilder } from 'drizzle-orm/pg-core'
import type { Field } from 'payload/types'; import type { Field } from 'payload/types'
import { relations } from 'drizzle-orm'; import { relations } from 'drizzle-orm'
import { index, integer, numeric, pgTable, serial, timestamp, unique, varchar, } from 'drizzle-orm/pg-core'; import {
import { fieldAffectsData } from 'payload/types'; index,
import toSnakeCase from 'to-snake-case'; integer,
numeric,
pgTable,
serial,
timestamp,
unique,
varchar,
} from 'drizzle-orm/pg-core'
import { fieldAffectsData } from 'payload/types'
import toSnakeCase from 'to-snake-case'
import type { GenericColumns, GenericTable, PostgresAdapter } from '../types'; import type { GenericColumns, GenericTable, PostgresAdapter } from '../types'
import { parentIDColumnMap } from './parentIDColumnMap'; import { parentIDColumnMap } from './parentIDColumnMap'
import { traverseFields } from './traverseFields'; import { traverseFields } from './traverseFields'
type Args = { type Args = {
adapter: PostgresAdapter adapter: PostgresAdapter
baseColumns?: Record<string, PgColumnBuilder>, baseColumns?: Record<string, PgColumnBuilder>
baseExtraConfig?: Record<string, (cols: GenericColumns) => IndexBuilder | UniqueConstraintBuilder> baseExtraConfig?: Record<string, (cols: GenericColumns) => IndexBuilder | UniqueConstraintBuilder>
buildRelationships?: boolean buildRelationships?: boolean
fields: Field[] fields: Field[]
@@ -36,38 +45,38 @@ export const buildTable = ({
tableName, tableName,
timestamps, timestamps,
}: Args): Result => { }: Args): Result => {
const columns: Record<string, PgColumnBuilder> = baseColumns; const columns: Record<string, PgColumnBuilder> = baseColumns
const indexes: Record<string, (cols: GenericColumns) => IndexBuilder> = {}; const indexes: Record<string, (cols: GenericColumns) => IndexBuilder> = {}
let hasLocalizedField = false; let hasLocalizedField = false
let hasLocalizedRelationshipField = false; let hasLocalizedRelationshipField = false
const localesColumns: Record<string, PgColumnBuilder> = {}; const localesColumns: Record<string, PgColumnBuilder> = {}
const localesIndexes: Record<string, (cols: GenericColumns) => IndexBuilder> = {}; const localesIndexes: Record<string, (cols: GenericColumns) => IndexBuilder> = {}
let localesTable: GenericTable; let localesTable: GenericTable
const relationships: Set<string> = new Set(); const relationships: Set<string> = new Set()
let relationshipsTable: GenericTable; let relationshipsTable: GenericTable
const arrayBlockRelations: Map<string, string> = new Map(); const arrayBlockRelations: Map<string, string> = new Map()
const idField = fields.find((field) => fieldAffectsData(field) && field.name === 'id'); const idField = fields.find((field) => fieldAffectsData(field) && field.name === 'id')
let idColType = 'integer'; let idColType = 'integer'
if (idField) { if (idField) {
if (idField.type === 'number') { if (idField.type === 'number') {
idColType = 'numeric'; idColType = 'numeric'
columns.id = numeric('id').primaryKey(); columns.id = numeric('id').primaryKey()
} }
if (idField.type === 'text') { if (idField.type === 'text') {
idColType = 'varchar'; idColType = 'varchar'
columns.id = varchar('id').primaryKey(); columns.id = varchar('id').primaryKey()
} }
} else { } else {
columns.id = serial('id').primaryKey(); columns.id = serial('id').primaryKey()
} }
({ hasLocalizedField, hasLocalizedRelationshipField } = traverseFields({ ;({ hasLocalizedField, hasLocalizedRelationshipField } = traverseFields({
adapter, adapter,
arrayBlockRelations, arrayBlockRelations,
buildRelationships, buildRelationships,
@@ -79,52 +88,57 @@ export const buildTable = ({
newTableName: tableName, newTableName: tableName,
parentTableName: tableName, parentTableName: tableName,
relationships, relationships,
})); }))
if (timestamps) { if (timestamps) {
columns.createdAt = timestamp('created_at').defaultNow().notNull(); columns.createdAt = timestamp('created_at').defaultNow().notNull()
columns.updatedAt = timestamp('updated_at').defaultNow().notNull(); columns.updatedAt = timestamp('updated_at').defaultNow().notNull()
} }
const table = pgTable(tableName, columns, (cols) => { const table = pgTable(tableName, columns, (cols) => {
const extraConfig = Object.entries(baseExtraConfig).reduce((config, [key, func]) => { const extraConfig = Object.entries(baseExtraConfig).reduce((config, [key, func]) => {
config[key] = func(cols); config[key] = func(cols)
return config; return config
}, {}); }, {})
return Object.entries(indexes).reduce((acc, [colName, func]) => { return Object.entries(indexes).reduce((acc, [colName, func]) => {
acc[colName] = func(cols); acc[colName] = func(cols)
return acc; return acc
}, extraConfig); }, extraConfig)
}); })
adapter.tables[tableName] = table; adapter.tables[tableName] = table
if (hasLocalizedField) { if (hasLocalizedField) {
const localeTableName = `${tableName}_locales`; const localeTableName = `${tableName}_locales`
localesColumns.id = serial('id').primaryKey(); localesColumns.id = serial('id').primaryKey()
localesColumns._locale = adapter.enums._locales('_locale').notNull(); localesColumns._locale = adapter.enums._locales('_locale').notNull()
localesColumns._parentID = parentIDColumnMap[idColType]('_parent_id').references(() => table.id, { onDelete: 'cascade' }).notNull(); localesColumns._parentID = parentIDColumnMap[idColType]('_parent_id')
.references(() => table.id, { onDelete: 'cascade' })
.notNull()
localesTable = pgTable(localeTableName, localesColumns, (cols) => { localesTable = pgTable(localeTableName, localesColumns, (cols) => {
return Object.entries(localesIndexes).reduce((acc, [colName, func]) => { return Object.entries(localesIndexes).reduce(
acc[colName] = func(cols); (acc, [colName, func]) => {
return acc; acc[colName] = func(cols)
}, { return acc
},
{
_localeParent: unique().on(cols._locale, cols._parentID), _localeParent: unique().on(cols._locale, cols._parentID),
}); },
}); )
})
adapter.tables[localeTableName] = localesTable; adapter.tables[localeTableName] = localesTable
const localesTableRelations = relations(localesTable, ({ one }) => ({ const localesTableRelations = relations(localesTable, ({ one }) => ({
_parentID: one(table, { _parentID: one(table, {
fields: [localesTable._parentID], fields: [localesTable._parentID],
references: [table.id], references: [table.id],
}), }),
})); }))
adapter.relations[`relations_${localeTableName}`] = localesTableRelations; adapter.relations[`relations_${localeTableName}`] = localesTableRelations
} }
if (buildRelationships) { if (buildRelationships) {
@@ -132,40 +146,51 @@ export const buildTable = ({
const relationshipColumns: Record<string, PgColumnBuilder> = { const relationshipColumns: Record<string, PgColumnBuilder> = {
id: serial('id').primaryKey(), id: serial('id').primaryKey(),
order: integer('order'), order: integer('order'),
parent: parentIDColumnMap[idColType]('parent_id').references(() => table.id, { onDelete: 'cascade' }).notNull(), parent: parentIDColumnMap[idColType]('parent_id')
.references(() => table.id, { onDelete: 'cascade' })
.notNull(),
path: varchar('path').notNull(), path: varchar('path').notNull(),
}; }
if (hasLocalizedRelationshipField) { if (hasLocalizedRelationshipField) {
relationshipColumns.locale = adapter.enums._locales('locale'); relationshipColumns.locale = adapter.enums._locales('locale')
} }
relationships.forEach((relationTo) => { relationships.forEach((relationTo) => {
const formattedRelationTo = toSnakeCase(relationTo); const formattedRelationTo = toSnakeCase(relationTo)
let colType = 'integer'; let colType = 'integer'
const relatedCollectionCustomID = adapter.payload.collections[relationTo].config.fields.find((field) => fieldAffectsData(field) && field.name === 'id'); const relatedCollectionCustomID = adapter.payload.collections[
if (relatedCollectionCustomID?.type === 'number') colType = 'numeric'; relationTo
if (relatedCollectionCustomID?.type === 'text') colType = 'varchar'; ].config.fields.find((field) => fieldAffectsData(field) && field.name === 'id')
if (relatedCollectionCustomID?.type === 'number') colType = 'numeric'
if (relatedCollectionCustomID?.type === 'text') colType = 'varchar'
relationshipColumns[`${relationTo}ID`] = parentIDColumnMap[colType](`${formattedRelationTo}_id`).references(() => adapter.tables[formattedRelationTo].id); relationshipColumns[`${relationTo}ID`] = parentIDColumnMap[colType](
}); `${formattedRelationTo}_id`,
).references(() => adapter.tables[formattedRelationTo].id)
})
const relationshipsTableName = `${tableName}_relationships`; const relationshipsTableName = `${tableName}_relationships`
relationshipsTable = pgTable(relationshipsTableName, relationshipColumns, (cols) => { relationshipsTable = pgTable(relationshipsTableName, relationshipColumns, (cols) => {
const result: Record<string, unknown> = {}; const result: Record<string, unknown> = {}
if (hasLocalizedRelationshipField) { if (hasLocalizedRelationshipField) {
result.localeIdx = index('locale_idx').on(cols.locale); result.localeIdx = index('locale_idx').on(cols.locale)
result.parentPathOrderLocale = unique().on(cols.parent, cols.path, cols.order, cols.locale); result.parentPathOrderLocale = unique().on(
cols.parent,
cols.path,
cols.order,
cols.locale,
)
} else { } else {
result.parentPathOrder = unique().on(cols.parent, cols.path, cols.order); result.parentPathOrder = unique().on(cols.parent, cols.path, cols.order)
} }
return result; return result
}); })
adapter.tables[relationshipsTableName] = relationshipsTable; adapter.tables[relationshipsTableName] = relationshipsTable
const relationshipsTableRelations = relations(relationshipsTable, ({ one }) => { const relationshipsTableRelations = relations(relationshipsTable, ({ one }) => {
const result: Record<string, Relation<string>> = { const result: Record<string, Relation<string>> = {
@@ -174,45 +199,45 @@ export const buildTable = ({
references: [table.id], references: [table.id],
relationName: '_relationships', relationName: '_relationships',
}), }),
}; }
relationships.forEach((relationTo) => { relationships.forEach((relationTo) => {
const relatedTableName = toSnakeCase(relationTo); const relatedTableName = toSnakeCase(relationTo)
const idColumnName = `${relationTo}ID`; const idColumnName = `${relationTo}ID`
result[idColumnName] = one(adapter.tables[relatedTableName], { result[idColumnName] = one(adapter.tables[relatedTableName], {
fields: [relationshipsTable[idColumnName]], fields: [relationshipsTable[idColumnName]],
references: [adapter.tables[relatedTableName].id], references: [adapter.tables[relatedTableName].id],
}); })
}); })
return result; return result
}); })
adapter.relations[`relations_${relationshipsTableName}`] = relationshipsTableRelations; adapter.relations[`relations_${relationshipsTableName}`] = relationshipsTableRelations
} }
} }
const tableRelations = relations(table, ({ many }) => { const tableRelations = relations(table, ({ many }) => {
const result: Record<string, Relation<string>> = {}; const result: Record<string, Relation<string>> = {}
arrayBlockRelations.forEach((val, key) => { arrayBlockRelations.forEach((val, key) => {
result[key] = many(adapter.tables[val]); result[key] = many(adapter.tables[val])
}); })
if (hasLocalizedField) { if (hasLocalizedField) {
result._locales = many(localesTable); result._locales = many(localesTable)
} }
if (relationships.size && relationshipsTable) { if (relationships.size && relationshipsTable) {
result._relationships = many(relationshipsTable, { result._relationships = many(relationshipsTable, {
relationName: '_relationships', relationName: '_relationships',
}); })
} }
return result; return result
}); })
adapter.relations[`relations_${tableName}`] = tableRelations; adapter.relations[`relations_${tableName}`] = tableRelations
return { arrayBlockRelations }; return { arrayBlockRelations }
}; }

View File

@@ -1,7 +1,7 @@
/* eslint-disable no-param-reassign */ /* eslint-disable no-param-reassign */
import { index, uniqueIndex } from 'drizzle-orm/pg-core'; import { index, uniqueIndex } from 'drizzle-orm/pg-core'
import type { GenericColumn } from '../types'; import type { GenericColumn } from '../types'
type CreateIndexArgs = { type CreateIndexArgs = {
columnName: string columnName: string
@@ -9,9 +9,9 @@ type CreateIndexArgs = {
unique?: boolean unique?: boolean
} }
export const createIndex = ({ columnName, name, unique }: CreateIndexArgs) => { export const createIndex = ({ name, columnName, unique }: CreateIndexArgs) => {
return (table: { [x: string]: GenericColumn }) => { return (table: { [x: string]: GenericColumn }) => {
if (unique) return uniqueIndex(`${columnName}_idx`).on(table[name]); if (unique) return uniqueIndex(`${columnName}_idx`).on(table[name])
return index(`${columnName}_idx`).on(table[name]); return index(`${columnName}_idx`).on(table[name])
}; }
}; }

View File

@@ -1,7 +1,7 @@
import { integer, numeric, varchar } from 'drizzle-orm/pg-core'; import { integer, numeric, varchar } from 'drizzle-orm/pg-core'
export const parentIDColumnMap = { export const parentIDColumnMap = {
integer, integer,
numeric, numeric,
varchar, varchar,
}; }

View File

@@ -1,9 +1,9 @@
/* eslint-disable no-param-reassign */ /* eslint-disable no-param-reassign */
import type { Relation } from 'drizzle-orm'; import type { Relation } from 'drizzle-orm'
import type { IndexBuilder, PgColumnBuilder, UniqueConstraintBuilder } from 'drizzle-orm/pg-core'; import type { IndexBuilder, PgColumnBuilder, UniqueConstraintBuilder } from 'drizzle-orm/pg-core'
import type { Field } from 'payload/types'; import type { Field } from 'payload/types'
import { relations } from 'drizzle-orm'; import { relations } from 'drizzle-orm'
import { import {
PgNumericBuilder, PgNumericBuilder,
PgVarcharBuilder, PgVarcharBuilder,
@@ -13,16 +13,16 @@ import {
text, text,
unique, unique,
varchar, varchar,
} from 'drizzle-orm/pg-core'; } from 'drizzle-orm/pg-core'
import { fieldAffectsData } from 'payload/types'; import { fieldAffectsData } from 'payload/types'
import toSnakeCase from 'to-snake-case'; import toSnakeCase from 'to-snake-case'
import type { GenericColumns, PostgresAdapter } from '../types'; import type { GenericColumns, PostgresAdapter } from '../types'
import { hasLocalesTable } from '../utilities/hasLocalesTable'; import { hasLocalesTable } from '../utilities/hasLocalesTable'
import { buildTable } from './build'; import { buildTable } from './build'
import { createIndex } from './createIndex'; import { createIndex } from './createIndex'
import { parentIDColumnMap } from './parentIDColumnMap'; import { parentIDColumnMap } from './parentIDColumnMap'
type Args = { type Args = {
adapter: PostgresAdapter adapter: PostgresAdapter
@@ -62,33 +62,40 @@ export const traverseFields = ({
parentTableName, parentTableName,
relationships, relationships,
}: Args): Result => { }: Args): Result => {
let hasLocalizedField = false; let hasLocalizedField = false
let hasLocalizedRelationshipField = false; let hasLocalizedRelationshipField = false
let parentIDColType = 'integer'; let parentIDColType = 'integer'
if (columns.id instanceof PgNumericBuilder) parentIDColType = 'numeric'; if (columns.id instanceof PgNumericBuilder) parentIDColType = 'numeric'
if (columns.id instanceof PgVarcharBuilder) parentIDColType = 'varchar'; if (columns.id instanceof PgVarcharBuilder) parentIDColType = 'varchar'
fields.forEach((field) => { fields.forEach((field) => {
if ('name' in field && field.name === 'id') return; if ('name' in field && field.name === 'id') return
let columnName: string; let columnName: string
let targetTable = columns; let targetTable = columns
let targetIndexes = indexes; let targetIndexes = indexes
if (fieldAffectsData(field)) { if (fieldAffectsData(field)) {
columnName = `${columnPrefix || ''}${toSnakeCase(field.name)}`; columnName = `${columnPrefix || ''}${toSnakeCase(field.name)}`
// If field is localized, // If field is localized,
// add the column to the locale table instead of main table // add the column to the locale table instead of main table
if (adapter.payload.config.localization && (field.localized || forceLocalized)) { if (adapter.payload.config.localization && (field.localized || forceLocalized)) {
hasLocalizedField = true; hasLocalizedField = true
targetTable = localesColumns; targetTable = localesColumns
targetIndexes = localesIndexes; targetIndexes = localesIndexes
} }
if ((field.unique || field.index) && !['array', 'blocks', 'group', 'relationship', 'upload'].includes(field.type)) { if (
targetIndexes[`${field.name}Idx`] = createIndex({ columnName, name: field.name, unique: field.unique }); (field.unique || field.index) &&
!['array', 'blocks', 'group', 'relationship', 'upload'].includes(field.type)
) {
targetIndexes[`${field.name}Idx`] = createIndex({
name: field.name,
columnName,
unique: field.unique,
})
} }
} }
@@ -99,55 +106,61 @@ export const traverseFields = ({
case 'textarea': { case 'textarea': {
// TODO: handle hasMany // TODO: handle hasMany
// TODO: handle min / max length // TODO: handle min / max length
targetTable[`${fieldPrefix || ''}${field.name}`] = varchar(columnName); targetTable[`${fieldPrefix || ''}${field.name}`] = varchar(columnName)
break; break
} }
case 'number': { case 'number': {
// TODO: handle hasMany // TODO: handle hasMany
// TODO: handle min / max // TODO: handle min / max
targetTable[`${fieldPrefix || ''}${field.name}`] = numeric(columnName); targetTable[`${fieldPrefix || ''}${field.name}`] = numeric(columnName)
break; break
} }
case 'richText': case 'richText':
case 'json': { case 'json': {
targetTable[`${fieldPrefix || ''}${field.name}`] = jsonb(columnName); targetTable[`${fieldPrefix || ''}${field.name}`] = jsonb(columnName)
break; break
} }
case 'date': { case 'date': {
break; break
} }
case 'point': { case 'point': {
break; break
} }
case 'radio': { case 'radio': {
break; break
} }
case 'select': { case 'select': {
break; break
} }
case 'array': { case 'array': {
const baseColumns: Record<string, PgColumnBuilder> = { const baseColumns: Record<string, PgColumnBuilder> = {
_order: integer('_order').notNull(), _order: integer('_order').notNull(),
_parentID: parentIDColumnMap[parentIDColType]('_parent_id').references(() => adapter.tables[parentTableName].id, { onDelete: 'cascade' }).notNull(), _parentID: parentIDColumnMap[parentIDColType]('_parent_id')
}; .references(() => adapter.tables[parentTableName].id, { onDelete: 'cascade' })
.notNull(),
const baseExtraConfig: Record<string, (cols: GenericColumns) => IndexBuilder | UniqueConstraintBuilder> = {};
if (field.localized && adapter.payload.config.localization) {
baseColumns._locale = adapter.enums._locales('_locale').notNull();
baseExtraConfig._parentOrderLocale = (cols) => unique().on(cols._parentID, cols._order, cols._locale);
} else {
baseExtraConfig._parentOrder = (cols) => unique().on(cols._parentID, cols._order);
} }
const arrayTableName = `${newTableName}_${toSnakeCase(field.name)}`; const baseExtraConfig: Record<
string,
(cols: GenericColumns) => IndexBuilder | UniqueConstraintBuilder
> = {}
if (field.localized && adapter.payload.config.localization) {
baseColumns._locale = adapter.enums._locales('_locale').notNull()
baseExtraConfig._parentOrderLocale = (cols) =>
unique().on(cols._parentID, cols._order, cols._locale)
} else {
baseExtraConfig._parentOrder = (cols) => unique().on(cols._parentID, cols._order)
}
const arrayTableName = `${newTableName}_${toSnakeCase(field.name)}`
const { arrayBlockRelations: subArrayBlockRelations } = buildTable({ const { arrayBlockRelations: subArrayBlockRelations } = buildTable({
adapter, adapter,
@@ -155,9 +168,9 @@ export const traverseFields = ({
baseExtraConfig, baseExtraConfig,
fields: field.fields, fields: field.fields,
tableName: arrayTableName, tableName: arrayTableName,
}); })
arrayBlockRelations.set(`${fieldPrefix || ''}${field.name}`, arrayTableName); arrayBlockRelations.set(`${fieldPrefix || ''}${field.name}`, arrayTableName)
const arrayTableRelations = relations(adapter.tables[arrayTableName], ({ many, one }) => { const arrayTableRelations = relations(adapter.tables[arrayTableName], ({ many, one }) => {
const result: Record<string, Relation<string>> = { const result: Record<string, Relation<string>> = {
@@ -165,41 +178,48 @@ export const traverseFields = ({
fields: [adapter.tables[arrayTableName]._parentID], fields: [adapter.tables[arrayTableName]._parentID],
references: [adapter.tables[parentTableName].id], references: [adapter.tables[parentTableName].id],
}), }),
}; }
if (hasLocalesTable(field.fields)) { if (hasLocalesTable(field.fields)) {
result._locales = many(adapter.tables[`${arrayTableName}_locales`]); result._locales = many(adapter.tables[`${arrayTableName}_locales`])
} }
subArrayBlockRelations.forEach((val, key) => { subArrayBlockRelations.forEach((val, key) => {
result[key] = many(adapter.tables[val]); result[key] = many(adapter.tables[val])
}); })
return result; return result
}); })
adapter.relations[`relations_${arrayTableName}`] = arrayTableRelations; adapter.relations[`relations_${arrayTableName}`] = arrayTableRelations
break; break
} }
case 'blocks': { case 'blocks': {
field.blocks.forEach((block) => { field.blocks.forEach((block) => {
const blockTableName = `${newTableName}_${toSnakeCase(block.slug)}`; const blockTableName = `${newTableName}_${toSnakeCase(block.slug)}`
if (!adapter.tables[blockTableName]) { if (!adapter.tables[blockTableName]) {
const baseColumns: Record<string, PgColumnBuilder> = { const baseColumns: Record<string, PgColumnBuilder> = {
_order: integer('_order').notNull(), _order: integer('_order').notNull(),
_parentID: parentIDColumnMap[parentIDColType]('_parent_id').references(() => adapter.tables[parentTableName].id, { onDelete: 'cascade' }).notNull(), _parentID: parentIDColumnMap[parentIDColType]('_parent_id')
.references(() => adapter.tables[parentTableName].id, { onDelete: 'cascade' })
.notNull(),
_path: text('_path').notNull(), _path: text('_path').notNull(),
}; }
const baseExtraConfig: Record<string, (cols: GenericColumns) => IndexBuilder | UniqueConstraintBuilder> = {}; const baseExtraConfig: Record<
string,
(cols: GenericColumns) => IndexBuilder | UniqueConstraintBuilder
> = {}
if (field.localized && adapter.payload.config.localization) { if (field.localized && adapter.payload.config.localization) {
baseColumns._locale = adapter.enums._locales('_locale').notNull(); baseColumns._locale = adapter.enums._locales('_locale').notNull()
baseExtraConfig._parentPathOrderLocale = (cols) => unique().on(cols._parentID, cols._path, cols._order, cols._locale); baseExtraConfig._parentPathOrderLocale = (cols) =>
unique().on(cols._parentID, cols._path, cols._order, cols._locale)
} else { } else {
baseExtraConfig._parentPathOrder = (cols) => unique().on(cols._parentID, cols._path, cols._order); baseExtraConfig._parentPathOrder = (cols) =>
unique().on(cols._parentID, cols._path, cols._order)
} }
const { arrayBlockRelations: subArrayBlockRelations } = buildTable({ const { arrayBlockRelations: subArrayBlockRelations } = buildTable({
@@ -208,34 +228,37 @@ export const traverseFields = ({
baseExtraConfig, baseExtraConfig,
fields: block.fields, fields: block.fields,
tableName: blockTableName, tableName: blockTableName,
}); })
const blockTableRelations = relations(adapter.tables[blockTableName], ({ many, one }) => { const blockTableRelations = relations(
adapter.tables[blockTableName],
({ many, one }) => {
const result: Record<string, Relation<string>> = { const result: Record<string, Relation<string>> = {
_parentID: one(adapter.tables[parentTableName], { _parentID: one(adapter.tables[parentTableName], {
fields: [adapter.tables[blockTableName]._parentID], fields: [adapter.tables[blockTableName]._parentID],
references: [adapter.tables[parentTableName].id], references: [adapter.tables[parentTableName].id],
}), }),
}; }
if (hasLocalesTable(block.fields)) { if (hasLocalesTable(block.fields)) {
result._locales = many(adapter.tables[`${blockTableName}_locales`]); result._locales = many(adapter.tables[`${blockTableName}_locales`])
} }
subArrayBlockRelations.forEach((val, key) => { subArrayBlockRelations.forEach((val, key) => {
result[key] = many(adapter.tables[val]); result[key] = many(adapter.tables[val])
}); })
return result; return result
}); },
)
adapter.relations[`relations_${blockTableName}`] = blockTableRelations; adapter.relations[`relations_${blockTableName}`] = blockTableRelations
} }
arrayBlockRelations.set(`_blocks_${block.slug}`, blockTableName); arrayBlockRelations.set(`_blocks_${block.slug}`, blockTableName)
}); })
break; break
} }
case 'group': { case 'group': {
@@ -257,11 +280,11 @@ export const traverseFields = ({
newTableName: `${parentTableName}_${toSnakeCase(field.name)}`, newTableName: `${parentTableName}_${toSnakeCase(field.name)}`,
parentTableName, parentTableName,
relationships, relationships,
}); })
if (groupHasLocalizedField) hasLocalizedField = true; if (groupHasLocalizedField) hasLocalizedField = true
if (groupHasLocalizedRelationshipField) hasLocalizedRelationshipField = true; if (groupHasLocalizedRelationshipField) hasLocalizedRelationshipField = true
break; break
} }
case 'tabs': { case 'tabs': {
@@ -284,15 +307,12 @@ export const traverseFields = ({
newTableName: `${parentTableName}_${toSnakeCase(tab.name)}`, newTableName: `${parentTableName}_${toSnakeCase(tab.name)}`,
parentTableName, parentTableName,
relationships, relationships,
}); })
if (tabHasLocalizedField) hasLocalizedField = true; if (tabHasLocalizedField) hasLocalizedField = true
if (tabHasLocalizedRelationshipField) hasLocalizedRelationshipField = true; if (tabHasLocalizedRelationshipField) hasLocalizedRelationshipField = true
} else { } else {
({ ;({ hasLocalizedField, hasLocalizedRelationshipField } = traverseFields({
hasLocalizedField,
hasLocalizedRelationshipField,
} = traverseFields({
adapter, adapter,
arrayBlockRelations, arrayBlockRelations,
buildRelationships, buildRelationships,
@@ -304,18 +324,15 @@ export const traverseFields = ({
newTableName: parentTableName, newTableName: parentTableName,
parentTableName, parentTableName,
relationships, relationships,
})); }))
} }
}); })
break; break
} }
case 'row': case 'row':
case 'collapsible': { case 'collapsible': {
({ ;({ hasLocalizedField, hasLocalizedRelationshipField } = traverseFields({
hasLocalizedField,
hasLocalizedRelationshipField,
} = traverseFields({
adapter, adapter,
arrayBlockRelations, arrayBlockRelations,
buildRelationships, buildRelationships,
@@ -327,27 +344,27 @@ export const traverseFields = ({
newTableName: parentTableName, newTableName: parentTableName,
parentTableName, parentTableName,
relationships, relationships,
})); }))
break; break
} }
case 'relationship': case 'relationship':
case 'upload': case 'upload':
if (Array.isArray(field.relationTo)) { if (Array.isArray(field.relationTo)) {
field.relationTo.forEach((relation) => relationships.add(relation)); field.relationTo.forEach((relation) => relationships.add(relation))
} else { } else {
relationships.add(field.relationTo); relationships.add(field.relationTo)
} }
if (field.localized && adapter.payload.config.localization) { if (field.localized && adapter.payload.config.localization) {
hasLocalizedRelationshipField = true; hasLocalizedRelationshipField = true
} }
break; break
default: default:
break; break
} }
}); })
return { hasLocalizedField, hasLocalizedRelationshipField }; return { hasLocalizedField, hasLocalizedRelationshipField }
}; }

View File

@@ -1,19 +1,18 @@
import type { CommitTransaction } from 'payload/database'; import type { CommitTransaction } from 'payload/database'
import { sql } from 'drizzle-orm';
import { sql } from 'drizzle-orm'
export const commitTransaction: CommitTransaction = async function commitTransaction(id) { export const commitTransaction: CommitTransaction = async function commitTransaction(id) {
if (!this.sessions[id]) { if (!this.sessions[id]) {
this.payload.logger.warn('commitTransaction called when no transaction exists'); this.payload.logger.warn('commitTransaction called when no transaction exists')
return; return
} }
try { try {
await this.sessions[id].execute(sql`COMMIT;`); await this.sessions[id].execute(sql`COMMIT;`)
} catch (err: unknown) { } catch (err: unknown) {
await this.sessions[id].execute(sql`ROLLBACK;`); await this.sessions[id].execute(sql`ROLLBACK;`)
} }
delete this.sessions[id]; delete this.sessions[id]
}; }

View File

@@ -1,13 +1,14 @@
import type { RollbackTransaction } from 'payload/database'; import type { RollbackTransaction } from 'payload/database'
import { sql } from 'drizzle-orm'; import { sql } from 'drizzle-orm'
export const rollbackTransaction: RollbackTransaction = async function rollbackTransaction(
export const rollbackTransaction: RollbackTransaction = async function rollbackTransaction(id = '') { id = '',
) {
if (!this.sessions[id]) { if (!this.sessions[id]) {
this.payload.logger.warn('rollbackTransaction called when no transaction exists'); this.payload.logger.warn('rollbackTransaction called when no transaction exists')
return; return
} }
await this.sessions[id].execute(sql`ROLLBACK;`); await this.sessions[id].execute(sql`ROLLBACK;`)
delete this.sessions[id]; delete this.sessions[id]
}; }

View File

@@ -1,10 +1,10 @@
/* eslint-disable no-param-reassign */ /* eslint-disable no-param-reassign */
import type { SanitizedConfig } from 'payload/config'; import type { SanitizedConfig } from 'payload/config'
import type { Field, TypeWithID } from 'payload/types'; import type { Field, TypeWithID } from 'payload/types'
import { createBlocksMap } from '../../utilities/createBlocksMap'; import { createBlocksMap } from '../../utilities/createBlocksMap'
import { createRelationshipMap } from '../../utilities/createRelationshipMap'; import { createRelationshipMap } from '../../utilities/createRelationshipMap'
import { traverseFields } from './traverseFields'; import { traverseFields } from './traverseFields'
type TransformArgs = { type TransformArgs = {
config: SanitizedConfig config: SanitizedConfig
@@ -16,19 +16,15 @@ type TransformArgs = {
// This is the entry point to transform Drizzle output data // This is the entry point to transform Drizzle output data
// into the shape Payload expects based on field schema // into the shape Payload expects based on field schema
export const transform = <T extends TypeWithID>({ export const transform = <T extends TypeWithID>({ config, data, fields }: TransformArgs): T => {
config, let relationships: Record<string, Record<string, unknown>[]> = {}
data,
fields,
}: TransformArgs): T => {
let relationships: Record<string, Record<string, unknown>[]> = {};
if ('_relationships' in data) { if ('_relationships' in data) {
relationships = createRelationshipMap(data._relationships); relationships = createRelationshipMap(data._relationships)
delete data._relationships; delete data._relationships
} }
const blocks = createBlocksMap(data); const blocks = createBlocksMap(data)
const result = traverseFields<T>({ const result = traverseFields<T>({
blocks, blocks,
@@ -39,11 +35,11 @@ export const transform = <T extends TypeWithID>({
relationships, relationships,
siblingData: data, siblingData: data,
table: data, table: data,
}); })
if ('_locales' in result) { if ('_locales' in result) {
delete result._locales; delete result._locales
} }
return result; return result
}; }

View File

@@ -1,5 +1,5 @@
/* eslint-disable no-param-reassign */ /* eslint-disable no-param-reassign */
import { RelationshipField } from 'payload/types'; import type { RelationshipField } from 'payload/types'
type Args = { type Args = {
field: RelationshipField field: RelationshipField
@@ -8,68 +8,67 @@ type Args = {
relations: Record<string, unknown>[] relations: Record<string, unknown>[]
} }
export const transformRelationship = ({ export const transformRelationship = ({ field, locale, ref, relations }: Args) => {
field, let result: unknown
locale,
ref,
relations,
}: Args) => {
let result: unknown;
if (!field.hasMany) { if (!field.hasMany) {
const relation = relations[0]; const relation = relations[0]
if (relation) { if (relation) {
// Handle hasOne Poly // Handle hasOne Poly
if (Array.isArray(field.relationTo)) { if (Array.isArray(field.relationTo)) {
const matchedRelation = Object.entries(relation).find(([key, val]) => val !== null && !['order', 'id', 'parent', 'locale'].includes(key)); const matchedRelation = Object.entries(relation).find(
([key, val]) => val !== null && !['id', 'locale', 'order', 'parent'].includes(key),
)
if (matchedRelation) { if (matchedRelation) {
const relationTo = matchedRelation[0].replace('ID', ''); const relationTo = matchedRelation[0].replace('ID', '')
result = { result = {
relationTo, relationTo,
value: matchedRelation[1], value: matchedRelation[1],
}; }
} }
} else { } else {
// Handle hasOne // Handle hasOne
const relatedData = relation[`${field.relationTo}ID`]; const relatedData = relation[`${field.relationTo}ID`]
result = relatedData; result = relatedData
} }
} }
} else { } else {
const transformedRelations = []; const transformedRelations = []
relations.forEach((relation) => { relations.forEach((relation) => {
// Handle hasMany // Handle hasMany
if (!Array.isArray(field.relationTo)) { if (!Array.isArray(field.relationTo)) {
const relatedData = relation[`${field.relationTo}ID`]; const relatedData = relation[`${field.relationTo}ID`]
if (relatedData) { if (relatedData) {
transformedRelations.push(relatedData); transformedRelations.push(relatedData)
} }
} else { } else {
// Handle hasMany Poly // Handle hasMany Poly
const matchedRelation = Object.entries(relation).find(([key, val]) => val !== null && !['order', 'parent', 'id', 'locale'].includes(key)); const matchedRelation = Object.entries(relation).find(
([key, val]) => val !== null && !['id', 'locale', 'order', 'parent'].includes(key),
)
if (matchedRelation) { if (matchedRelation) {
const relationTo = matchedRelation[0].replace('ID', ''); const relationTo = matchedRelation[0].replace('ID', '')
transformedRelations.push({ transformedRelations.push({
relationTo, relationTo,
value: matchedRelation[1], value: matchedRelation[1],
}); })
} }
} }
}); })
result = transformedRelations; result = transformedRelations
} }
if (locale) { if (locale) {
ref[field.name][locale] = result; ref[field.name][locale] = result
} else { } else {
ref[field.name] = result; ref[field.name] = result
} }
}; }

View File

@@ -1,12 +1,12 @@
/* eslint-disable no-param-reassign */ /* eslint-disable no-param-reassign */
import type { SanitizedConfig } from 'payload/config'; import type { SanitizedConfig } from 'payload/config'
import type { Field} from 'payload/types'; import type { Field } from 'payload/types'
import { fieldAffectsData } from 'payload/types'; import { fieldAffectsData } from 'payload/types'
import type { BlocksMap } from '../../utilities/createBlocksMap'; import type { BlocksMap } from '../../utilities/createBlocksMap'
import { transformRelationship } from './relationship'; import { transformRelationship } from './relationship'
type TraverseFieldsArgs = { type TraverseFieldsArgs = {
/** /**
@@ -58,18 +58,18 @@ export const traverseFields = <T extends Record<string, unknown>>({
siblingData, siblingData,
table, table,
}: TraverseFieldsArgs): T => { }: TraverseFieldsArgs): T => {
const sanitizedPath = path ? `${path}.` : path; const sanitizedPath = path ? `${path}.` : path
const formatted = fields.reduce((result, field) => { const formatted = fields.reduce((result, field) => {
if (fieldAffectsData(field)) { if (fieldAffectsData(field)) {
if (field.type === 'array') { if (field.type === 'array') {
const fieldData = result[field.name]; const fieldData = result[field.name]
if (Array.isArray(fieldData)) { if (Array.isArray(fieldData)) {
if (field.localized) { if (field.localized) {
result[field.name] = fieldData.reduce((arrayResult, row) => { result[field.name] = fieldData.reduce((arrayResult, row) => {
if (typeof row._locale === 'string') { if (typeof row._locale === 'string') {
if (!arrayResult[row._locale]) arrayResult[row._locale] = []; if (!arrayResult[row._locale]) arrayResult[row._locale] = []
const rowResult = traverseFields<T>({ const rowResult = traverseFields<T>({
blocks, blocks,
@@ -80,14 +80,14 @@ export const traverseFields = <T extends Record<string, unknown>>({
relationships, relationships,
siblingData: row, siblingData: row,
table: row, table: row,
}); })
arrayResult[row._locale].push(rowResult); arrayResult[row._locale].push(rowResult)
delete rowResult._locale; delete rowResult._locale
} }
return arrayResult; return arrayResult
}, {}); }, {})
} else { } else {
result[field.name] = fieldData.map((row, i) => { result[field.name] = fieldData.map((row, i) => {
return traverseFields<T>({ return traverseFields<T>({
@@ -99,32 +99,32 @@ export const traverseFields = <T extends Record<string, unknown>>({
relationships, relationships,
siblingData: row, siblingData: row,
table: row, table: row,
}); })
}); })
} }
} }
return result; return result
} }
if (field.type === 'blocks') { if (field.type === 'blocks') {
const blockFieldPath = `${sanitizedPath}${field.name}`; const blockFieldPath = `${sanitizedPath}${field.name}`
if (Array.isArray(blocks[blockFieldPath])) { if (Array.isArray(blocks[blockFieldPath])) {
if (field.localized) { if (field.localized) {
result[field.name] = {}; result[field.name] = {}
blocks[blockFieldPath].forEach((row) => { blocks[blockFieldPath].forEach((row) => {
if (typeof row._locale === 'string') { if (typeof row._locale === 'string') {
if (!result[field.name][row._locale]) result[field.name][row._locale] = []; if (!result[field.name][row._locale]) result[field.name][row._locale] = []
result[field.name][row._locale].push(row); result[field.name][row._locale].push(row)
delete row._locale; delete row._locale
} }
}); })
Object.entries(result[field.name]).forEach(([locale, localizedBlocks]) => { Object.entries(result[field.name]).forEach(([locale, localizedBlocks]) => {
result[field.name][locale] = localizedBlocks.map((row) => { result[field.name][locale] = localizedBlocks.map((row) => {
const block = field.blocks.find(({ slug }) => slug === row.blockType); const block = field.blocks.find(({ slug }) => slug === row.blockType)
if (block) { if (block) {
const blockResult = traverseFields<T>({ const blockResult = traverseFields<T>({
@@ -136,19 +136,19 @@ export const traverseFields = <T extends Record<string, unknown>>({
relationships, relationships,
siblingData: row, siblingData: row,
table: row, table: row,
}); })
delete blockResult._order; delete blockResult._order
return blockResult; return blockResult
} }
return {}; return {}
}); })
}); })
} else { } else {
result[field.name] = blocks[blockFieldPath].map((row, i) => { result[field.name] = blocks[blockFieldPath].map((row, i) => {
delete row._order; delete row._order
const block = field.blocks.find(({ slug }) => slug === row.blockType); const block = field.blocks.find(({ slug }) => slug === row.blockType)
if (block) { if (block) {
return traverseFields<T>({ return traverseFields<T>({
@@ -160,31 +160,31 @@ export const traverseFields = <T extends Record<string, unknown>>({
relationships, relationships,
siblingData: row, siblingData: row,
table: row, table: row,
}); })
} }
return {}; return {}
}); })
} }
} }
return result; return result
} }
if (field.type === 'relationship') { if (field.type === 'relationship') {
const relationPathMatch = relationships[`${sanitizedPath}${field.name}`]; const relationPathMatch = relationships[`${sanitizedPath}${field.name}`]
if (!relationPathMatch) return result; if (!relationPathMatch) return result
if (field.localized) { if (field.localized) {
result[field.name] = {}; result[field.name] = {}
const relationsByLocale: Record<string, Record<string, unknown>[]> = {}; const relationsByLocale: Record<string, Record<string, unknown>[]> = {}
relationPathMatch.forEach((row) => { relationPathMatch.forEach((row) => {
if (typeof row.locale === 'string') { if (typeof row.locale === 'string') {
if (!relationsByLocale[row.locale]) relationsByLocale[row.locale] = []; if (!relationsByLocale[row.locale]) relationsByLocale[row.locale] = []
relationsByLocale[row.locale].push(row); relationsByLocale[row.locale].push(row)
} }
}); })
Object.entries(relationsByLocale).forEach(([locale, relations]) => { Object.entries(relationsByLocale).forEach(([locale, relations]) => {
transformRelationship({ transformRelationship({
@@ -192,51 +192,56 @@ export const traverseFields = <T extends Record<string, unknown>>({
locale, locale,
ref: result, ref: result,
relations, relations,
}); })
}); })
} else { } else {
transformRelationship({ transformRelationship({
field, field,
ref: result, ref: result,
relations: relationPathMatch, relations: relationPathMatch,
}); })
} }
return result; return result
} }
const localizedFieldData = {}; const localizedFieldData = {}
const valuesToTransform: { localeRow: Record<string, unknown>, ref: Record<string, unknown> }[] = []; const valuesToTransform: {
localeRow: Record<string, unknown>
ref: Record<string, unknown>
}[] = []
if (field.localized && Array.isArray(table._locales)) { if (field.localized && Array.isArray(table._locales)) {
table._locales.forEach((localeRow) => { table._locales.forEach((localeRow) => {
valuesToTransform.push({ localeRow, ref: localizedFieldData }); valuesToTransform.push({ localeRow, ref: localizedFieldData })
}); })
} else { } else {
valuesToTransform.push({ localeRow: undefined, ref: result }); valuesToTransform.push({ localeRow: undefined, ref: result })
} }
valuesToTransform.forEach(({ localeRow, ref }) => { valuesToTransform.forEach(({ localeRow, ref }) => {
const fieldData = localeRow?.[field.name] || ref[field.name]; const fieldData = localeRow?.[field.name] || ref[field.name]
const locale = localeRow?._locale; const locale = localeRow?._locale
switch (field.type) { switch (field.type) {
case 'group': { case 'group': {
const groupData = {}; const groupData = {}
field.fields.forEach((subField) => { field.fields.forEach((subField) => {
if (fieldAffectsData(subField)) { if (fieldAffectsData(subField)) {
const subFieldKey = `${sanitizedPath.replace(/\./g, '_')}${field.name}_${subField.name}`; const subFieldKey = `${sanitizedPath.replace(/\./g, '_')}${field.name}_${
subField.name
}`
if (typeof locale === 'string') { if (typeof locale === 'string') {
if (!ref[locale]) ref[locale] = {}; if (!ref[locale]) ref[locale] = {}
ref[locale][subField.name] = localeRow[subFieldKey]; ref[locale][subField.name] = localeRow[subFieldKey]
} else { } else {
groupData[subField.name] = table[subFieldKey]; groupData[subField.name] = table[subFieldKey]
delete table[subFieldKey]; delete table[subFieldKey]
} }
} }
}); })
if (field.localized) { if (field.localized) {
Object.entries(ref).forEach(([groupLocale, groupLocaleData]) => { Object.entries(ref).forEach(([groupLocale, groupLocaleData]) => {
@@ -249,8 +254,8 @@ export const traverseFields = <T extends Record<string, unknown>>({
relationships, relationships,
siblingData: groupLocaleData as Record<string, unknown>, siblingData: groupLocaleData as Record<string, unknown>,
table, table,
}); })
}); })
} else { } else {
ref[field.name] = traverseFields<Record<string, unknown>>({ ref[field.name] = traverseFields<Record<string, unknown>>({
blocks, blocks,
@@ -261,63 +266,63 @@ export const traverseFields = <T extends Record<string, unknown>>({
relationships, relationships,
siblingData: groupData as Record<string, unknown>, siblingData: groupData as Record<string, unknown>,
table, table,
}); })
} }
break; break
} }
case 'number': { case 'number': {
let val = fieldData; let val = fieldData
// TODO: handle hasMany // TODO: handle hasMany
if (typeof fieldData === 'string') { if (typeof fieldData === 'string') {
val = Number.parseFloat(fieldData); val = Number.parseFloat(fieldData)
} }
if (typeof locale === 'string') { if (typeof locale === 'string') {
ref[locale] = val; ref[locale] = val
} else { } else {
result[field.name] = val; result[field.name] = val
} }
break; break
} }
case 'date': { case 'date': {
if (fieldData instanceof Date) { if (fieldData instanceof Date) {
const val = fieldData.toISOString(); const val = fieldData.toISOString()
if (typeof locale === 'string') { if (typeof locale === 'string') {
ref[locale] = val; ref[locale] = val
} else { } else {
result[field.name] = val; result[field.name] = val
} }
} }
break; break
} }
default: { default: {
if (typeof locale === 'string') { if (typeof locale === 'string') {
ref[locale] = fieldData; ref[locale] = fieldData
} else { } else {
result[field.name] = fieldData; result[field.name] = fieldData
} }
break; break
} }
} }
}); })
if (Object.keys(localizedFieldData).length > 0) { if (Object.keys(localizedFieldData).length > 0) {
result[field.name] = localizedFieldData; result[field.name] = localizedFieldData
} }
return result; return result
} }
return siblingData; return siblingData
}, siblingData); }, siblingData)
return formatted as T; return formatted as T
}; }

View File

@@ -1,10 +1,10 @@
/* eslint-disable no-param-reassign */ /* eslint-disable no-param-reassign */
import type { ArrayField } from 'payload/types'; import type { ArrayField } from 'payload/types'
import type { ArrayRowToInsert, BlockRowToInsert } from './types'; import type { ArrayRowToInsert, BlockRowToInsert } from './types'
import { isArrayOfRows } from '../../utilities/isArrayOfRows'; import { isArrayOfRows } from '../../utilities/isArrayOfRows'
import { traverseFields } from './traverseFields'; import { traverseFields } from './traverseFields'
type Args = { type Args = {
arrayTableName: string arrayTableName: string
@@ -29,7 +29,7 @@ export const transformArray = ({
path, path,
relationships, relationships,
}: Args) => { }: Args) => {
const newRows: ArrayRowToInsert[] = []; const newRows: ArrayRowToInsert[] = []
if (isArrayOfRows(data)) { if (isArrayOfRows(data)) {
data.forEach((arrayRow, i) => { data.forEach((arrayRow, i) => {
@@ -40,16 +40,16 @@ export const transformArray = ({
row: { row: {
_order: i + 1, _order: i + 1,
}, },
}; }
if (locale) { if (locale) {
newRow.locales[locale] = { newRow.locales[locale] = {
_locale: locale, _locale: locale,
}; }
} }
if (field.localized) { if (field.localized) {
newRow.row._locale = locale; newRow.row._locale = locale
} }
traverseFields({ traverseFields({
@@ -64,11 +64,11 @@ export const transformArray = ({
path: `${path || ''}${field.name}.${i}.`, path: `${path || ''}${field.name}.${i}.`,
relationships, relationships,
row: newRow.row, row: newRow.row,
}); })
newRows.push(newRow); newRows.push(newRow)
}); })
} }
return newRows; return newRows
}; }

View File

@@ -1,11 +1,11 @@
/* eslint-disable no-param-reassign */ /* eslint-disable no-param-reassign */
import type { BlockField } from 'payload/types'; import type { BlockField } from 'payload/types'
import toSnakeCase from 'to-snake-case'; import toSnakeCase from 'to-snake-case'
import type { BlockRowToInsert } from './types'; import type { BlockRowToInsert } from './types'
import { traverseFields } from './traverseFields'; import { traverseFields } from './traverseFields'
type Args = { type Args = {
blocks: { blocks: {
@@ -28,11 +28,11 @@ export const transformBlocks = ({
tableName, tableName,
}: Args) => { }: Args) => {
data.forEach((blockRow, i) => { data.forEach((blockRow, i) => {
if (typeof blockRow.blockType !== 'string') return; if (typeof blockRow.blockType !== 'string') return
const matchedBlock = field.blocks.find(({ slug }) => slug === blockRow.blockType); const matchedBlock = field.blocks.find(({ slug }) => slug === blockRow.blockType)
if (!matchedBlock) return; if (!matchedBlock) return
if (!blocks[blockRow.blockType]) blocks[blockRow.blockType] = []; if (!blocks[blockRow.blockType]) blocks[blockRow.blockType] = []
const newRow: BlockRowToInsert = { const newRow: BlockRowToInsert = {
arrays: {}, arrays: {},
@@ -41,11 +41,11 @@ export const transformBlocks = ({
_order: i + 1, _order: i + 1,
_path: `${path}${field.name}`, _path: `${path}${field.name}`,
}, },
}; }
if (field.localized && locale) newRow.row._locale = locale; if (field.localized && locale) newRow.row._locale = locale
const blockTableName = `${tableName}_${toSnakeCase(blockRow.blockType)}`; const blockTableName = `${tableName}_${toSnakeCase(blockRow.blockType)}`
traverseFields({ traverseFields({
arrays: newRow.arrays, arrays: newRow.arrays,
@@ -59,8 +59,8 @@ export const transformBlocks = ({
path: `${path || ''}${field.name}.${i}.`, path: `${path || ''}${field.name}.${i}.`,
relationships, relationships,
row: newRow.row, row: newRow.row,
}); })
blocks[blockRow.blockType].push(newRow); blocks[blockRow.blockType].push(newRow)
}); })
}; }

View File

@@ -1,10 +1,9 @@
/* eslint-disable no-param-reassign */ /* eslint-disable no-param-reassign */
import type { Field } from 'payload/types'; import type { Field } from 'payload/types'
import type { RowToInsert } from './types'; import type { RowToInsert } from './types'
import { traverseFields } from './traverseFields';
import { traverseFields } from './traverseFields'
type Args = { type Args = {
data: Record<string, unknown> data: Record<string, unknown>
@@ -13,12 +12,7 @@ type Args = {
tableName: string tableName: string
} }
export const transformForWrite = ({ export const transformForWrite = ({ data, fields, path = '', tableName }: Args): RowToInsert => {
data,
fields,
path = '',
tableName,
}: Args): RowToInsert => {
// Split out the incoming data into the corresponding: // Split out the incoming data into the corresponding:
// base row, locales, relationships, blocks, and arrays // base row, locales, relationships, blocks, and arrays
const rowToInsert: RowToInsert = { const rowToInsert: RowToInsert = {
@@ -27,7 +21,7 @@ export const transformForWrite = ({
locales: {}, locales: {},
relationships: [], relationships: [],
row: {}, row: {},
}; }
// This function is responsible for building up the // This function is responsible for building up the
// above rowToInsert // above rowToInsert
@@ -43,7 +37,7 @@ export const transformForWrite = ({
path, path,
relationships: rowToInsert.relationships, relationships: rowToInsert.relationships,
row: rowToInsert.row, row: rowToInsert.row,
}); })
return rowToInsert; return rowToInsert
}; }

View File

@@ -1,6 +1,6 @@
import type { RelationshipField, UploadField } from 'payload/types'; import type { RelationshipField, UploadField } from 'payload/types'
import { valueIsValueWithRelation } from 'payload/types'; import { valueIsValueWithRelation } from 'payload/types'
type Args = { type Args = {
baseRow: Record<string, unknown> baseRow: Record<string, unknown>
@@ -9,26 +9,21 @@ type Args = {
relationships: Record<string, unknown>[] relationships: Record<string, unknown>[]
} }
export const transformRelationship = ({ export const transformRelationship = ({ baseRow, data, field, relationships }: Args) => {
baseRow, const relations = Array.isArray(data) ? data : [data]
data,
field,
relationships,
}: Args) => {
const relations = Array.isArray(data) ? data : [data];
relations.forEach((relation, i) => { relations.forEach((relation, i) => {
if (relation) { if (relation) {
const relationRow = { ...baseRow }; const relationRow = { ...baseRow }
if ('hasMany' in field && field.hasMany) relationRow.order = i + 1; if ('hasMany' in field && field.hasMany) relationRow.order = i + 1
if (Array.isArray(field.relationTo) && valueIsValueWithRelation(relation)) { if (Array.isArray(field.relationTo) && valueIsValueWithRelation(relation)) {
relationRow[`${relation.relationTo}ID`] = relation.value; relationRow[`${relation.relationTo}ID`] = relation.value
relationships.push(relationRow); relationships.push(relationRow)
} else { } else {
relationRow[`${field.relationTo}ID`] = relation; relationRow[`${field.relationTo}ID`] = relation
if (relation) relationships.push(relationRow); if (relation) relationships.push(relationRow)
} }
} }
}); })
}; }

View File

@@ -1,15 +1,15 @@
/* eslint-disable no-param-reassign */ /* eslint-disable no-param-reassign */
import type { Field } from 'payload/types'; import type { Field } from 'payload/types'
import { fieldAffectsData } from 'payload/types'; import { fieldAffectsData } from 'payload/types'
import toSnakeCase from 'to-snake-case'; import toSnakeCase from 'to-snake-case'
import type { ArrayRowToInsert, BlockRowToInsert } from './types'; import type { ArrayRowToInsert, BlockRowToInsert } from './types'
import { isArrayOfRows } from '../../utilities/isArrayOfRows'; import { isArrayOfRows } from '../../utilities/isArrayOfRows'
import { transformArray } from './array'; import { transformArray } from './array'
import { transformBlocks } from './blocks'; import { transformBlocks } from './blocks'
import { transformRelationship } from './relationships'; import { transformRelationship } from './relationships'
type Args = { type Args = {
arrays: { arrays: {
@@ -49,17 +49,17 @@ export const traverseFields = ({
row, row,
}: Args) => { }: Args) => {
fields.forEach((field) => { fields.forEach((field) => {
let columnName = ''; let columnName = ''
let fieldData: unknown; let fieldData: unknown
if (fieldAffectsData(field)) { if (fieldAffectsData(field)) {
columnName = `${columnPrefix || ''}${field.name}`; columnName = `${columnPrefix || ''}${field.name}`
fieldData = data[field.name]; fieldData = data[field.name]
} }
if (field.type === 'array') { if (field.type === 'array') {
const arrayTableName = `${newTableName}_${toSnakeCase(field.name)}`; const arrayTableName = `${newTableName}_${toSnakeCase(field.name)}`
if (!arrays[arrayTableName]) arrays[arrayTableName] = []; if (!arrays[arrayTableName]) arrays[arrayTableName] = []
if (field.localized) { if (field.localized) {
if (typeof data[field.name] === 'object' && data[field.name] !== null) { if (typeof data[field.name] === 'object' && data[field.name] !== null) {
@@ -74,11 +74,11 @@ export const traverseFields = ({
locale: localeKey, locale: localeKey,
path, path,
relationships, relationships,
}); })
arrays[arrayTableName] = arrays[arrayTableName].concat(newRows); arrays[arrayTableName] = arrays[arrayTableName].concat(newRows)
} }
}); })
} }
} else { } else {
const newRows = transformArray({ const newRows = transformArray({
@@ -89,12 +89,12 @@ export const traverseFields = ({
field, field,
path, path,
relationships, relationships,
}); })
arrays[arrayTableName] = arrays[arrayTableName].concat(newRows); arrays[arrayTableName] = arrays[arrayTableName].concat(newRows)
} }
return; return
} }
if (field.type === 'blocks') { if (field.type === 'blocks') {
@@ -110,9 +110,9 @@ export const traverseFields = ({
path, path,
relationships, relationships,
tableName: newTableName, tableName: newTableName,
}); })
} }
}); })
} }
} else if (isArrayOfRows(fieldData)) { } else if (isArrayOfRows(fieldData)) {
transformBlocks({ transformBlocks({
@@ -122,10 +122,10 @@ export const traverseFields = ({
path, path,
relationships, relationships,
tableName: newTableName, tableName: newTableName,
}); })
} }
return; return
} }
if (field.type === 'group') { if (field.type === 'group') {
@@ -146,8 +146,8 @@ export const traverseFields = ({
path: `${path || ''}${field.name}.`, path: `${path || ''}${field.name}.`,
relationships, relationships,
row, row,
}); })
}); })
} else { } else {
traverseFields({ traverseFields({
arrays, arrays,
@@ -162,15 +162,15 @@ export const traverseFields = ({
path: `${path || ''}${field.name}.`, path: `${path || ''}${field.name}.`,
relationships, relationships,
row, row,
}); })
} }
} }
return; return
} }
if (field.type === 'relationship') { if (field.type === 'relationship') {
const relationshipPath = `${path || ''}${field.name}`; const relationshipPath = `${path || ''}${field.name}`
if (field.localized) { if (field.localized) {
if (typeof fieldData === 'object') { if (typeof fieldData === 'object') {
@@ -183,8 +183,8 @@ export const traverseFields = ({
data: localeData, data: localeData,
field, field,
relationships, relationships,
}); })
}); })
} }
} else { } else {
transformRelationship({ transformRelationship({
@@ -194,59 +194,59 @@ export const traverseFields = ({
data: fieldData, data: fieldData,
field, field,
relationships, relationships,
}); })
} }
return; return
} }
if (fieldAffectsData(field)) { if (fieldAffectsData(field)) {
const valuesToTransform: { localeKey?: string, ref: unknown, value: unknown }[] = []; const valuesToTransform: { localeKey?: string; ref: unknown; value: unknown }[] = []
if ((field.localized)) { if (field.localized) {
if (typeof fieldData === 'object' && fieldData !== null) { if (typeof fieldData === 'object' && fieldData !== null) {
Object.entries(fieldData).forEach(([localeKey, localeData]) => { Object.entries(fieldData).forEach(([localeKey, localeData]) => {
if (!locales[localeKey]) locales[localeKey] = {}; if (!locales[localeKey]) locales[localeKey] = {}
valuesToTransform.push({ valuesToTransform.push({
localeKey, localeKey,
ref: locales, ref: locales,
value: localeData, value: localeData,
}); })
}); })
} }
} else { } else {
let ref = row; let ref = row
if (forcedLocale) { if (forcedLocale) {
if (!locales[forcedLocale]) locales[forcedLocale] = {}; if (!locales[forcedLocale]) locales[forcedLocale] = {}
ref = locales[forcedLocale]; ref = locales[forcedLocale]
} }
valuesToTransform.push({ ref, value: fieldData }); valuesToTransform.push({ ref, value: fieldData })
} }
valuesToTransform.forEach(({ localeKey, ref, value }) => { valuesToTransform.forEach(({ localeKey, ref, value }) => {
if (typeof value !== 'undefined') { if (typeof value !== 'undefined') {
let formattedValue = value; let formattedValue = value
switch (field.type) { switch (field.type) {
case 'number': { case 'number': {
// TODO: handle hasMany // TODO: handle hasMany
break; break
} }
case 'select': { case 'select': {
break; break
} }
case 'date': { case 'date': {
if (typeof fieldData === 'string') { if (typeof fieldData === 'string') {
const parsedDate = new Date(fieldData); const parsedDate = new Date(fieldData)
formattedValue = parsedDate; formattedValue = parsedDate
} }
break; break
} }
// case 'tabs': { // case 'tabs': {
@@ -311,17 +311,17 @@ export const traverseFields = ({
// } // }
default: { default: {
break; break
} }
} }
if (localeKey) { if (localeKey) {
ref[localeKey][columnName] = formattedValue; ref[localeKey][columnName] = formattedValue
} else { } else {
ref[columnName] = formattedValue; ref[columnName] = formattedValue
} }
} }
}); })
} }
}); })
}; }

View File

@@ -6,7 +6,7 @@ export type ArrayRowToInsert = {
locales: { locales: {
[locale: string]: Record<string, unknown> [locale: string]: Record<string, unknown>
} }
row: Record<string, unknown>, row: Record<string, unknown>
} }
export type BlockRowToInsert = { export type BlockRowToInsert = {
@@ -16,7 +16,7 @@ export type BlockRowToInsert = {
locales: { locales: {
[locale: string]: Record<string, unknown> [locale: string]: Record<string, unknown>
} }
row: Record<string, unknown>, row: Record<string, unknown>
} }
export type RowToInsert = { export type RowToInsert = {
@@ -29,6 +29,6 @@ export type RowToInsert = {
locales: { locales: {
[locale: string]: Record<string, unknown> [locale: string]: Record<string, unknown>
} }
relationships: Record<string, unknown>[], relationships: Record<string, unknown>[]
row: Record<string, unknown>, row: Record<string, unknown>
} }

View File

@@ -1,14 +1,14 @@
import type { ColumnBaseConfig, ColumnDataType, Relation, Relations } from 'drizzle-orm'; import type { ColumnBaseConfig, ColumnDataType, Relation, Relations } from 'drizzle-orm'
import type { NodePgDatabase } from 'drizzle-orm/node-postgres'; import type { NodePgDatabase } from 'drizzle-orm/node-postgres'
import type { PgColumn, PgEnum, PgTableWithColumns } from 'drizzle-orm/pg-core'; import type { PgColumn, PgEnum, PgTableWithColumns } from 'drizzle-orm/pg-core'
import type { DatabaseAdapter, Payload } from 'payload'; import type { DatabaseAdapter, Payload } from 'payload'
import type { ClientConfig, PoolConfig } from 'pg'; import type { ClientConfig, PoolConfig } from 'pg'
export type DrizzleDB = NodePgDatabase<Record<string, never>> export type DrizzleDB = NodePgDatabase<Record<string, never>>
type BaseArgs = { type BaseArgs = {
migrationDir?: string; migrationDir?: string
migrationName?: string; migrationName?: string
} }
type ClientArgs = { type ClientArgs = {
@@ -23,27 +23,34 @@ type PoolArgs = {
export type Args = ClientArgs | PoolArgs export type Args = ClientArgs | PoolArgs
export type GenericColumn = PgColumn<ColumnBaseConfig<ColumnDataType, string>, Record<string, unknown>> export type GenericColumn = PgColumn<
ColumnBaseConfig<ColumnDataType, string>,
Record<string, unknown>
>
export type GenericColumns = { export type GenericColumns = {
[x: string]: GenericColumn [x: string]: GenericColumn
} }
export type GenericTable = PgTableWithColumns<{ export type GenericTable = PgTableWithColumns<{
columns: GenericColumns, dialect: string, name: string, schema: undefined columns: GenericColumns
dialect: string
name: string
schema: undefined
}> }>
export type GenericEnum = PgEnum<[string, ...string[]]> export type GenericEnum = PgEnum<[string, ...string[]]>
export type GenericRelation = Relations<string, Record<string, Relation<string>>> export type GenericRelation = Relations<string, Record<string, Relation<string>>>
export type PostgresAdapter = DatabaseAdapter & Args & { export type PostgresAdapter = DatabaseAdapter &
Args & {
db: DrizzleDB db: DrizzleDB
enums: Record<string, GenericEnum> enums: Record<string, GenericEnum>
relations: Record<string, GenericRelation> relations: Record<string, GenericRelation>
schema: Record<string, GenericEnum | GenericRelation | GenericTable> schema: Record<string, GenericEnum | GenericRelation | GenericTable>
sessions: Record<string, DrizzleDB> sessions: Record<string, DrizzleDB>
tables: Record<string, GenericTable> tables: Record<string, GenericTable>
} }
export type PostgresAdapterResult = (args: { payload: Payload }) => PostgresAdapter export type PostgresAdapterResult = (args: { payload: Payload }) => PostgresAdapter

View File

@@ -1,9 +1,9 @@
import type { UpdateOne } from 'payload/database'; import type { UpdateOne } from 'payload/database'
import toSnakeCase from 'to-snake-case'; import toSnakeCase from 'to-snake-case'
import buildQuery from '../queries/buildQuery'; import buildQuery from '../queries/buildQuery'
import { upsertRow } from '../upsertRow'; import { upsertRow } from '../upsertRow'
export const updateOne: UpdateOne = async function updateOne({ export const updateOne: UpdateOne = async function updateOne({
id, id,
@@ -14,18 +14,18 @@ export const updateOne: UpdateOne = async function updateOne({
req, req,
where: whereArg, where: whereArg,
}) { }) {
const db = req.transactionID ? this.sessions[req.transactionID] : this.db; const db = req.transactionID ? this.sessions[req.transactionID] : this.db
const collection = this.payload.collections[collectionSlug].config; const collection = this.payload.collections[collectionSlug].config
const tableName = toSnakeCase(collectionSlug); const tableName = toSnakeCase(collectionSlug)
const whereToUse = whereArg || { id: { equals: id } }; const whereToUse = whereArg || { id: { equals: id } }
const { where } = await buildQuery({ const { where } = await buildQuery({
adapter: this, adapter: this,
fields: collection.fields, fields: collection.fields,
locale, locale,
tableName, tableName,
where: whereToUse where: whereToUse,
}); })
const result = await upsertRow({ const result = await upsertRow({
id, id,
@@ -36,7 +36,7 @@ export const updateOne: UpdateOne = async function updateOne({
operation: 'update', operation: 'update',
tableName: toSnakeCase(collectionSlug), tableName: toSnakeCase(collectionSlug),
where, where,
}); })
return result; return result
}; }

View File

@@ -1,31 +1,31 @@
import type { UpdateGlobal } from 'payload/database'; import type { UpdateGlobal } from 'payload/database'
import type { PayloadRequest } from 'payload/types'; import type { PayloadRequest } from 'payload/types'
import toSnakeCase from 'to-snake-case'; import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types'; import type { PostgresAdapter } from './types'
import { upsertRow } from './upsertRow'; import { upsertRow } from './upsertRow'
export const updateGlobal: UpdateGlobal = async function updateGlobal( export const updateGlobal: UpdateGlobal = async function updateGlobal(
this: PostgresAdapter, this: PostgresAdapter,
{ data, req = {} as PayloadRequest, slug }, { data, req = {} as PayloadRequest, slug },
) { ) {
const db = req.transactionID ? this.sessions[req.transactionID] : this.db; const db = req.transactionID ? this.sessions[req.transactionID] : this.db
const globalConfig = this.payload.globals.config.find((config) => config.slug === slug); const globalConfig = this.payload.globals.config.find((config) => config.slug === slug)
const tableName = toSnakeCase(slug); const tableName = toSnakeCase(slug)
const existingGlobal = await this.db.query[tableName].findFirst({}); const existingGlobal = await this.db.query[tableName].findFirst({})
const result = await upsertRow({ const result = await upsertRow({
id: existingGlobal.id,
adapter: this, adapter: this,
data, data,
db, db,
fields: globalConfig.fields, fields: globalConfig.fields,
id: existingGlobal.id,
operation: 'update', operation: 'update',
tableName: toSnakeCase(slug), tableName: toSnakeCase(slug),
}); })
return result; return result
}; }

View File

@@ -1,5 +1,6 @@
import { and, eq } from 'drizzle-orm'; import { and, eq } from 'drizzle-orm'
import { PostgresAdapter } from '../types';
import type { PostgresAdapter } from '../types'
type Args = { type Args = {
adapter: PostgresAdapter adapter: PostgresAdapter
@@ -13,14 +14,9 @@ export const deleteExistingArrayRows = async ({
parentID, parentID,
tableName, tableName,
}: Args): Promise<void> => { }: Args): Promise<void> => {
const table = adapter.tables[tableName]; const table = adapter.tables[tableName]
const whereConstraints = [ const whereConstraints = [eq(table._parentID, parentID)]
eq(table._parentID, parentID),
];
await adapter.db.delete(table) await adapter.db.delete(table).where(and(...whereConstraints))
.where( }
and(...whereConstraints),
);
};

View File

@@ -1,64 +1,57 @@
import { and, eq, inArray } from 'drizzle-orm'; import { and, eq, inArray } from 'drizzle-orm'
import { PostgresAdapter } from '../types';
import type { PostgresAdapter } from '../types'
type Args = { type Args = {
adapter: PostgresAdapter adapter: PostgresAdapter
localeColumnName?: string localeColumnName?: string
newRows: Record<string, unknown>[]
parentColumnName?: string parentColumnName?: string
parentID: unknown parentID: unknown
pathColumnName?: string pathColumnName?: string
newRows: Record<string, unknown>[]
tableName: string tableName: string
} }
export const deleteExistingRowsByPath = async ({ export const deleteExistingRowsByPath = async ({
adapter, adapter,
localeColumnName = '_locale', localeColumnName = '_locale',
newRows,
parentColumnName = '_parentID', parentColumnName = '_parentID',
parentID, parentID,
pathColumnName = '_path', pathColumnName = '_path',
newRows,
tableName, tableName,
}: Args): Promise<void> => { }: Args): Promise<void> => {
const localizedPathsToDelete = new Set<string>(); const localizedPathsToDelete = new Set<string>()
const pathsToDelete = new Set<string>(); const pathsToDelete = new Set<string>()
const table = adapter.tables[tableName]; const table = adapter.tables[tableName]
newRows.forEach((row) => { newRows.forEach((row) => {
const path = row[pathColumnName]; const path = row[pathColumnName]
const localeData = row[localeColumnName]; const localeData = row[localeColumnName]
if (typeof path === 'string') { if (typeof path === 'string') {
if (typeof localeData === 'string') { if (typeof localeData === 'string') {
localizedPathsToDelete.add(path); localizedPathsToDelete.add(path)
} else { } else {
pathsToDelete.add(path); pathsToDelete.add(path)
} }
} }
}); })
if (localizedPathsToDelete.size > 0) { if (localizedPathsToDelete.size > 0) {
const whereConstraints = [ const whereConstraints = [eq(table[parentColumnName], parentID)]
eq(table[parentColumnName], parentID),
];
if (pathColumnName) whereConstraints.push(inArray(table[pathColumnName], Array.from(localizedPathsToDelete))); if (pathColumnName)
whereConstraints.push(inArray(table[pathColumnName], Array.from(localizedPathsToDelete)))
await adapter.db.delete(table) await adapter.db.delete(table).where(and(...whereConstraints))
.where(
and(...whereConstraints),
);
} }
if (pathsToDelete.size > 0) { if (pathsToDelete.size > 0) {
const whereConstraints = [ const whereConstraints = [eq(table[parentColumnName], parentID)]
eq(table[parentColumnName], parentID),
];
if (pathColumnName) whereConstraints.push(inArray(table[pathColumnName], Array.from(pathsToDelete))); if (pathColumnName)
whereConstraints.push(inArray(table[pathColumnName], Array.from(pathsToDelete)))
await adapter.db.delete(table) await adapter.db.delete(table).where(and(...whereConstraints))
.where(
and(...whereConstraints),
);
} }
}; }

View File

@@ -1,6 +1,6 @@
/* eslint-disable no-param-reassign */ /* eslint-disable no-param-reassign */
import { PostgresAdapter } from '../types'; import type { ArrayRowToInsert } from '../transform/write/types'
import { ArrayRowToInsert } from '../transform/write/types'; import type { PostgresAdapter } from '../types'
type Args = { type Args = {
adapter: PostgresAdapter adapter: PostgresAdapter
@@ -20,13 +20,9 @@ type RowsByTable = {
} }
} }
export const insertArrays = async ({ export const insertArrays = async ({ adapter, arrays, parentRows }: Args): Promise<void> => {
adapter,
arrays,
parentRows,
}: Args): Promise<void> => {
// Maintain a map of flattened rows by table // Maintain a map of flattened rows by table
const rowsByTable: RowsByTable = {}; const rowsByTable: RowsByTable = {}
arrays.forEach((arraysByTable, parentRowIndex) => { arrays.forEach((arraysByTable, parentRowIndex) => {
Object.entries(arraysByTable).forEach(([tableName, arrayRows]) => { Object.entries(arraysByTable).forEach(([tableName, arrayRows]) => {
@@ -36,43 +32,43 @@ export const insertArrays = async ({
arrays: [], arrays: [],
locales: [], locales: [],
rows: [], rows: [],
}; }
} }
const parentID = parentRows[parentRowIndex].id; const parentID = parentRows[parentRowIndex].id
// Add any sub arrays that need to be created // Add any sub arrays that need to be created
// We will call this recursively below // We will call this recursively below
arrayRows.forEach((arrayRow) => { arrayRows.forEach((arrayRow) => {
if (Object.keys(arrayRow.arrays).length > 0) { if (Object.keys(arrayRow.arrays).length > 0) {
rowsByTable[tableName].arrays.push(arrayRow.arrays); rowsByTable[tableName].arrays.push(arrayRow.arrays)
} }
// Set up parent IDs for both row and locale row // Set up parent IDs for both row and locale row
arrayRow.row._parentID = parentID; arrayRow.row._parentID = parentID
rowsByTable[tableName].rows.push(arrayRow.row); rowsByTable[tableName].rows.push(arrayRow.row)
Object.entries(arrayRow.locales).forEach(([arrayRowLocale, arrayRowLocaleData]) => { Object.entries(arrayRow.locales).forEach(([arrayRowLocale, arrayRowLocaleData]) => {
arrayRowLocaleData._parentID = arrayRow.row.id; arrayRowLocaleData._parentID = arrayRow.row.id
arrayRowLocaleData._locale = arrayRowLocale; arrayRowLocaleData._locale = arrayRowLocale
rowsByTable[tableName].locales.push(arrayRowLocaleData); rowsByTable[tableName].locales.push(arrayRowLocaleData)
}); })
}); })
}); })
}); })
// Insert all corresponding arrays in parallel // Insert all corresponding arrays in parallel
// (one insert per array table) // (one insert per array table)
await Promise.all(Object.entries(rowsByTable).map(async ( await Promise.all(
[tableName, row], Object.entries(rowsByTable).map(async ([tableName, row]) => {
) => { await adapter.db.insert(adapter.tables[tableName]).values(row.rows).returning()
await adapter.db.insert(adapter.tables[tableName])
.values(row.rows).returning();
// Insert locale rows // Insert locale rows
if (adapter.tables[`${tableName}_locales`]) { if (adapter.tables[`${tableName}_locales`]) {
await adapter.db.insert(adapter.tables[`${tableName}_locales`]) await adapter.db
.values(row.locales).returning(); .insert(adapter.tables[`${tableName}_locales`])
.values(row.locales)
.returning()
} }
// If there are sub arrays, call this function recursively // If there are sub arrays, call this function recursively
@@ -81,7 +77,8 @@ export const insertArrays = async ({
adapter, adapter,
arrays: row.arrays, arrays: row.arrays,
parentRows: row.rows, parentRows: row.rows,
}); })
} }
})); }),
}; )
}

View File

@@ -1,8 +1,8 @@
import type { SQL } from 'drizzle-orm'; import type { SQL } from 'drizzle-orm'
import type { Field } from 'payload/types'; import type { Field } from 'payload/types'
import type { GenericColumn, PostgresAdapter } from '../types'; import type { GenericColumn, PostgresAdapter } from '../types'
import type { DrizzleDB } from '../types'; import type { DrizzleDB } from '../types'
type BaseArgs = { type BaseArgs = {
adapter: PostgresAdapter adapter: PostgresAdapter

View File

@@ -4,38 +4,38 @@ export type BlocksMap = {
} }
export const createBlocksMap = (data: Record<string, unknown>): BlocksMap => { export const createBlocksMap = (data: Record<string, unknown>): BlocksMap => {
const blocksMap: BlocksMap = {}; const blocksMap: BlocksMap = {}
Object.entries(data).forEach(([key, rows]) => { Object.entries(data).forEach(([key, rows]) => {
if (key.startsWith('_blocks_') && Array.isArray(rows)) { if (key.startsWith('_blocks_') && Array.isArray(rows)) {
const blockType = key.replace('_blocks_', ''); const blockType = key.replace('_blocks_', '')
rows.forEach((row) => { rows.forEach((row) => {
if ('_path' in row) { if ('_path' in row) {
if (!(row._path in blocksMap)) blocksMap[row._path] = []; if (!(row._path in blocksMap)) blocksMap[row._path] = []
row.blockType = blockType; row.blockType = blockType
blocksMap[row._path].push(row); blocksMap[row._path].push(row)
delete row._path; delete row._path
} }
}); })
delete data[key]; delete data[key]
} }
}); })
Object.entries(blocksMap).reduce((sortedBlocksMap, [path, blocks]) => { Object.entries(blocksMap).reduce((sortedBlocksMap, [path, blocks]) => {
sortedBlocksMap[path] = blocks.sort((a, b) => { sortedBlocksMap[path] = blocks.sort((a, b) => {
if (typeof a._order === 'number' && typeof b._order === 'number') { if (typeof a._order === 'number' && typeof b._order === 'number') {
return a._order - b._order; return a._order - b._order
} }
return 0; return 0
}); })
return sortedBlocksMap; return sortedBlocksMap
}, {}); }, {})
return blocksMap; return blocksMap
}; }

View File

@@ -1,22 +1,24 @@
// Flatten relationships to object with path keys // Flatten relationships to object with path keys
// for easier retrieval // for easier retrieval
export const createRelationshipMap = (rawRelationships: unknown): Record<string, Record<string, unknown>[]> => { export const createRelationshipMap = (
let relationships = {}; rawRelationships: unknown,
): Record<string, Record<string, unknown>[]> => {
let relationships = {}
if (Array.isArray(rawRelationships)) { if (Array.isArray(rawRelationships)) {
relationships = rawRelationships.reduce((res, relation) => { relationships = rawRelationships.reduce((res, relation) => {
const formattedRelation = { const formattedRelation = {
...relation, ...relation,
};
delete formattedRelation.path;
if (!res[relation.path]) res[relation.path] = [];
res[relation.path].push(formattedRelation);
return res;
}, {});
} }
return relationships; delete formattedRelation.path
};
if (!res[relation.path]) res[relation.path] = []
res[relation.path].push(formattedRelation)
return res
}, {})
}
return relationships
}

View File

@@ -1,12 +1,12 @@
import type { Field} from 'payload/types'; import type { Field } from 'payload/types'
import { fieldAffectsData, fieldHasSubFields } from 'payload/types'; import { fieldAffectsData, fieldHasSubFields } from 'payload/types'
export const hasLocalesTable = (fields: Field[]): boolean => { export const hasLocalesTable = (fields: Field[]): boolean => {
return fields.some((field) => { return fields.some((field) => {
if (fieldAffectsData(field) && field.localized) return true; if (fieldAffectsData(field) && field.localized) return true
if (fieldHasSubFields(field) && field.type !== 'array') return hasLocalesTable(field.fields); if (fieldHasSubFields(field) && field.type !== 'array') return hasLocalesTable(field.fields)
if (field.type === 'tabs') return field.tabs.some((tab) => hasLocalesTable(tab.fields)); if (field.type === 'tabs') return field.tabs.some((tab) => hasLocalesTable(tab.fields))
return false; return false
}); })
}; }

View File

@@ -1,3 +1,3 @@
export function isArrayOfRows(data: unknown): data is Record<string, unknown>[] { export function isArrayOfRows(data: unknown): data is Record<string, unknown>[] {
return Array.isArray(data); return Array.isArray(data)
} }

View File

@@ -27,6 +27,28 @@ module.exports = {
'jest/expect-expect': 'off', 'jest/expect-expect': 'off',
}, },
}, },
{
files: ['package.json', 'tsconfig.json'],
rules: {
'perfectionist/sort-array-includes': 'off',
'perfectionist/sort-astro-attributes': 'off',
'perfectionist/sort-classes': 'off',
'perfectionist/sort-enums': 'off',
'perfectionist/sort-exports': 'off',
'perfectionist/sort-imports': 'off',
'perfectionist/sort-interfaces': 'off',
'perfectionist/sort-jsx-props': 'off',
'perfectionist/sort-keys': 'off',
'perfectionist/sort-maps': 'off',
'perfectionist/sort-named-exports': 'off',
'perfectionist/sort-named-imports': 'off',
'perfectionist/sort-object-types': 'off',
'perfectionist/sort-objects': 'off',
'perfectionist/sort-svelte-attributes': 'off',
'perfectionist/sort-union-types': 'off',
'perfectionist/sort-vue-attributes': 'off',
},
},
], ],
parserOptions: { parserOptions: {
project: ['./tsconfig.json'], project: ['./tsconfig.json'],

View File

@@ -1,2 +1,2 @@
export * from './dist/auth'; export * from './dist/auth'
//# sourceMappingURL=auth.d.ts.map //# sourceMappingURL=auth.d.ts.map

View File

@@ -1,20 +1,20 @@
"use strict"; 'use strict'
Object.defineProperty(exports, "__esModule", { Object.defineProperty(exports, '__esModule', {
value: true value: true,
}); })
_export_star(require("./dist/auth"), exports); _export_star(require('./dist/auth'), exports)
function _export_star(from, to) { function _export_star(from, to) {
Object.keys(from).forEach(function(k) { Object.keys(from).forEach(function (k) {
if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) { if (k !== 'default' && !Object.prototype.hasOwnProperty.call(to, k)) {
Object.defineProperty(to, k, { Object.defineProperty(to, k, {
enumerable: true, enumerable: true,
get: function() { get: function () {
return from[k]; return from[k]
},
})
} }
}); })
} return from
});
return from;
} }
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9leHBvcnRzL2F1dGgudHMiXSwic291cmNlc0NvbnRlbnQiOlsiZXhwb3J0ICogZnJvbSAnLi4vYXV0aCdcbiJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7O3FCQUFjIn0= //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9leHBvcnRzL2F1dGgudHMiXSwic291cmNlc0NvbnRlbnQiOlsiZXhwb3J0ICogZnJvbSAnLi4vYXV0aCdcbiJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7O3FCQUFjIn0=

View File

@@ -1,13 +1,13 @@
export { default as Banner } from './dist/admin/components/elements/Banner'; export { default as Banner } from './dist/admin/components/elements/Banner'
export { default as Button } from './dist/admin/components/elements/Button'; export { default as Button } from './dist/admin/components/elements/Button'
export { default as Pill } from './dist/admin/components/elements/Pill'; export { default as Pill } from './dist/admin/components/elements/Pill'
export { default as Popup } from './dist/admin/components/elements/Popup'; export { default as Popup } from './dist/admin/components/elements/Popup'
export { ShimmerEffect } from './dist/admin/components/elements/ShimmerEffect'; export { ShimmerEffect } from './dist/admin/components/elements/ShimmerEffect'
export { default as Tooltip } from './dist/admin/components/elements/Tooltip'; export { default as Tooltip } from './dist/admin/components/elements/Tooltip'
export { default as Check } from './dist/admin/components/icons/Check'; export { default as Check } from './dist/admin/components/icons/Check'
export { default as Chevron } from './dist/admin/components/icons/Chevron'; export { default as Chevron } from './dist/admin/components/icons/Chevron'
export { default as Menu } from './dist/admin/components/icons/Menu'; export { default as Menu } from './dist/admin/components/icons/Menu'
export { default as Search } from './dist/admin/components/icons/Search'; export { default as Search } from './dist/admin/components/icons/Search'
export { default as X } from './dist/admin/components/icons/X'; export { default as X } from './dist/admin/components/icons/X'
export { default as MinimalTemplate } from './dist/admin/components/templates/Minimal'; export { default as MinimalTemplate } from './dist/admin/components/templates/Minimal'
//# sourceMappingURL=components.d.ts.map //# sourceMappingURL=components.d.ts.map

View File

@@ -1,67 +1,88 @@
"use strict"; 'use strict'
Object.defineProperty(exports, "__esModule", { Object.defineProperty(exports, '__esModule', {
value: true value: true,
}); })
function _export(target, all) { function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, { for (var name in all)
Object.defineProperty(target, name, {
enumerable: true, enumerable: true,
get: all[name] get: all[name],
}); })
} }
_export(exports, { _export(exports, {
Banner: function() { Banner: function () {
return _Banner.default; return _Banner.default
}, },
Button: function() { Button: function () {
return _Button.default; return _Button.default
}, },
Pill: function() { Check: function () {
return _Pill.default; return _Check.default
}, },
Popup: function() { Chevron: function () {
return _Popup.default; return _Chevron.default
}, },
ShimmerEffect: function() { Menu: function () {
return _ShimmerEffect.ShimmerEffect; return _Menu.default
}, },
Tooltip: function() { MinimalTemplate: function () {
return _Tooltip.default; return _Minimal.default
}, },
Check: function() { Pill: function () {
return _Check.default; return _Pill.default
}, },
Chevron: function() { Popup: function () {
return _Chevron.default; return _Popup.default
}, },
Menu: function() { Search: function () {
return _Menu.default; return _Search.default
}, },
Search: function() { ShimmerEffect: function () {
return _Search.default; return _ShimmerEffect.ShimmerEffect
}, },
X: function() { Tooltip: function () {
return _X.default; return _Tooltip.default
}, },
MinimalTemplate: function() { X: function () {
return _Minimal.default; return _X.default
} },
}); })
const _Banner = /*#__PURE__*/ _interop_require_default(require("./dist/admin/components/elements/Banner")); const _Banner = /*#__PURE__*/ _interop_require_default(
const _Button = /*#__PURE__*/ _interop_require_default(require("./dist/admin/components/elements/Button")); require('./dist/admin/components/elements/Banner'),
const _Pill = /*#__PURE__*/ _interop_require_default(require("./dist/admin/components/elements/Pill")); )
const _Popup = /*#__PURE__*/ _interop_require_default(require("./dist/admin/components/elements/Popup")); const _Button = /*#__PURE__*/ _interop_require_default(
const _ShimmerEffect = require("./dist/admin/components/elements/ShimmerEffect"); require('./dist/admin/components/elements/Button'),
const _Tooltip = /*#__PURE__*/ _interop_require_default(require("./dist/admin/components/elements/Tooltip")); )
const _Check = /*#__PURE__*/ _interop_require_default(require("./dist/admin/components/icons/Check")); const _Pill = /*#__PURE__*/ _interop_require_default(
const _Chevron = /*#__PURE__*/ _interop_require_default(require("./dist/admin/components/icons/Chevron")); require('./dist/admin/components/elements/Pill'),
const _Menu = /*#__PURE__*/ _interop_require_default(require("./dist/admin/components/icons/Menu")); )
const _Search = /*#__PURE__*/ _interop_require_default(require("./dist/admin/components/icons/Search")); const _Popup = /*#__PURE__*/ _interop_require_default(
const _X = /*#__PURE__*/ _interop_require_default(require("./dist/admin/components/icons/X")); require('./dist/admin/components/elements/Popup'),
const _Minimal = /*#__PURE__*/ _interop_require_default(require("./dist/admin/components/templates/Minimal")); )
const _ShimmerEffect = require('./dist/admin/components/elements/ShimmerEffect')
const _Tooltip = /*#__PURE__*/ _interop_require_default(
require('./dist/admin/components/elements/Tooltip'),
)
const _Check = /*#__PURE__*/ _interop_require_default(
require('./dist/admin/components/icons/Check'),
)
const _Chevron = /*#__PURE__*/ _interop_require_default(
require('./dist/admin/components/icons/Chevron'),
)
const _Menu = /*#__PURE__*/ _interop_require_default(require('./dist/admin/components/icons/Menu'))
const _Search = /*#__PURE__*/ _interop_require_default(
require('./dist/admin/components/icons/Search'),
)
const _X = /*#__PURE__*/ _interop_require_default(require('./dist/admin/components/icons/X'))
const _Minimal = /*#__PURE__*/ _interop_require_default(
require('./dist/admin/components/templates/Minimal'),
)
function _interop_require_default(obj) { function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : { return obj && obj.__esModule
default: obj ? obj
}; : {
default: obj,
}
} }
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9leHBvcnRzL2NvbXBvbmVudHMudHMiXSwic291cmNlc0NvbnRlbnQiOlsiZXhwb3J0IHsgZGVmYXVsdCBhcyBCYW5uZXIgfSBmcm9tICcuLi9hZG1pbi9jb21wb25lbnRzL2VsZW1lbnRzL0Jhbm5lcidcbmV4cG9ydCB7IGRlZmF1bHQgYXMgQnV0dG9uIH0gZnJvbSAnLi4vYWRtaW4vY29tcG9uZW50cy9lbGVtZW50cy9CdXR0b24nXG5cbmV4cG9ydCB7IGRlZmF1bHQgYXMgUGlsbCB9IGZyb20gJy4uL2FkbWluL2NvbXBvbmVudHMvZWxlbWVudHMvUGlsbCdcblxuZXhwb3J0IHsgZGVmYXVsdCBhcyBQb3B1cCB9IGZyb20gJy4uL2FkbWluL2NvbXBvbmVudHMvZWxlbWVudHMvUG9wdXAnXG5cbmV4cG9ydCB7IFNoaW1tZXJFZmZlY3QgfSBmcm9tICcuLi9hZG1pbi9jb21wb25lbnRzL2VsZW1lbnRzL1NoaW1tZXJFZmZlY3QnXG5leHBvcnQgeyBkZWZhdWx0IGFzIFRvb2x0aXAgfSBmcm9tICcuLi9hZG1pbi9jb21wb25lbnRzL2VsZW1lbnRzL1Rvb2x0aXAnXG5leHBvcnQgeyBkZWZhdWx0IGFzIENoZWNrIH0gZnJvbSAnLi4vYWRtaW4vY29tcG9uZW50cy9pY29ucy9DaGVjaydcbmV4cG9ydCB7IGRlZmF1bHQgYXMgQ2hldnJvbiB9IGZyb20gJy4uL2FkbWluL2NvbXBvbmVudHMvaWNvbnMvQ2hldnJvbidcbmV4cG9ydCB7IGRlZmF1bHQgYXMgTWVudSB9IGZyb20gJy4uL2FkbWluL2NvbXBvbmVudHMvaWNvbnMvTWVudSdcbmV4cG9ydCB7IGRlZmF1bHQgYXMgU2VhcmNoIH0gZnJvbSAnLi4vYWRtaW4vY29tcG9uZW50cy9pY29ucy9TZWFyY2gnXG5leHBvcnQgeyBkZWZhdWx0IGFzIFggfSBmcm9tICcuLi9hZG1pbi9jb21wb25lbnRzL2ljb25zL1gnXG5leHBvcnQgeyBkZWZhdWx0IGFzIE1pbmltYWxUZW1wbGF0ZSB9IGZyb20gJy4uL2FkbWluL2NvbXBvbmVudHMvdGVtcGxhdGVzL01pbmltYWwnXG4iXSwibmFtZXMiOlsiQmFubmVyIiwiQnV0dG9uIiwiUGlsbCIsIlBvcHVwIiwiU2hpbW1lckVmZmVjdCIsIlRvb2x0aXAiLCJDaGVjayIsIkNoZXZyb24iLCJNZW51IiwiU2VhcmNoIiwiWCIsIk1pbmltYWxUZW1wbGF0ZSJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7SUFBb0JBLE1BQU07ZUFBTkEsZUFBTTs7SUFDTkMsTUFBTTtlQUFOQSxlQUFNOztJQUVOQyxJQUFJO2VBQUpBLGFBQUk7O0lBRUpDLEtBQUs7ZUFBTEEsY0FBSzs7SUFFaEJDLGFBQWE7ZUFBYkEsNEJBQWE7O0lBQ0ZDLE9BQU87ZUFBUEEsZ0JBQU87O0lBQ1BDLEtBQUs7ZUFBTEEsY0FBSzs7SUFDTEMsT0FBTztlQUFQQSxnQkFBTzs7SUFDUEMsSUFBSTtlQUFKQSxhQUFJOztJQUNKQyxNQUFNO2VBQU5BLGVBQU07O0lBQ05DLENBQUM7ZUFBREEsVUFBQzs7SUFDREMsZUFBZTtlQUFmQSxnQkFBZTs7OytEQWREOytEQUNBOzZEQUVGOzhEQUVDOytCQUVIO2dFQUNLOzhEQUNGO2dFQUNFOzZEQUNIOytEQUNFOzBEQUNMO2dFQUNjIn0= //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9leHBvcnRzL2NvbXBvbmVudHMudHMiXSwic291cmNlc0NvbnRlbnQiOlsiZXhwb3J0IHsgZGVmYXVsdCBhcyBCYW5uZXIgfSBmcm9tICcuLi9hZG1pbi9jb21wb25lbnRzL2VsZW1lbnRzL0Jhbm5lcidcbmV4cG9ydCB7IGRlZmF1bHQgYXMgQnV0dG9uIH0gZnJvbSAnLi4vYWRtaW4vY29tcG9uZW50cy9lbGVtZW50cy9CdXR0b24nXG5cbmV4cG9ydCB7IGRlZmF1bHQgYXMgUGlsbCB9IGZyb20gJy4uL2FkbWluL2NvbXBvbmVudHMvZWxlbWVudHMvUGlsbCdcblxuZXhwb3J0IHsgZGVmYXVsdCBhcyBQb3B1cCB9IGZyb20gJy4uL2FkbWluL2NvbXBvbmVudHMvZWxlbWVudHMvUG9wdXAnXG5cbmV4cG9ydCB7IFNoaW1tZXJFZmZlY3QgfSBmcm9tICcuLi9hZG1pbi9jb21wb25lbnRzL2VsZW1lbnRzL1NoaW1tZXJFZmZlY3QnXG5leHBvcnQgeyBkZWZhdWx0IGFzIFRvb2x0aXAgfSBmcm9tICcuLi9hZG1pbi9jb21wb25lbnRzL2VsZW1lbnRzL1Rvb2x0aXAnXG5leHBvcnQgeyBkZWZhdWx0IGFzIENoZWNrIH0gZnJvbSAnLi4vYWRtaW4vY29tcG9uZW50cy9pY29ucy9DaGVjaydcbmV4cG9ydCB7IGRlZmF1bHQgYXMgQ2hldnJvbiB9IGZyb20gJy4uL2FkbWluL2NvbXBvbmVudHMvaWNvbnMvQ2hldnJvbidcbmV4cG9ydCB7IGRlZmF1bHQgYXMgTWVudSB9IGZyb20gJy4uL2FkbWluL2NvbXBvbmVudHMvaWNvbnMvTWVudSdcbmV4cG9ydCB7IGRlZmF1bHQgYXMgU2VhcmNoIH0gZnJvbSAnLi4vYWRtaW4vY29tcG9uZW50cy9pY29ucy9TZWFyY2gnXG5leHBvcnQgeyBkZWZhdWx0IGFzIFggfSBmcm9tICcuLi9hZG1pbi9jb21wb25lbnRzL2ljb25zL1gnXG5leHBvcnQgeyBkZWZhdWx0IGFzIE1pbmltYWxUZW1wbGF0ZSB9IGZyb20gJy4uL2FkbWluL2NvbXBvbmVudHMvdGVtcGxhdGVzL01pbmltYWwnXG4iXSwibmFtZXMiOlsiQmFubmVyIiwiQnV0dG9uIiwiUGlsbCIsIlBvcHVwIiwiU2hpbW1lckVmZmVjdCIsIlRvb2x0aXAiLCJDaGVjayIsIkNoZXZyb24iLCJNZW51IiwiU2VhcmNoIiwiWCIsIk1pbmltYWxUZW1wbGF0ZSJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7SUFBb0JBLE1BQU07ZUFBTkEsZUFBTTs7SUFDTkMsTUFBTTtlQUFOQSxlQUFNOztJQUVOQyxJQUFJO2VBQUpBLGFBQUk7O0lBRUpDLEtBQUs7ZUFBTEEsY0FBSzs7SUFFaEJDLGFBQWE7ZUFBYkEsNEJBQWE7O0lBQ0ZDLE9BQU87ZUFBUEEsZ0JBQU87O0lBQ1BDLEtBQUs7ZUFBTEEsY0FBSzs7SUFDTEMsT0FBTztlQUFQQSxnQkFBTzs7SUFDUEMsSUFBSTtlQUFKQSxhQUFJOztJQUNKQyxNQUFNO2VBQU5BLGVBQU07O0lBQ05DLENBQUM7ZUFBREEsVUFBQzs7SUFDREMsZUFBZTtlQUFmQSxnQkFBZTs7OytEQWREOytEQUNBOzZEQUVGOzhEQUVDOytCQUVIO2dFQUNLOzhEQUNGO2dFQUNFOzZEQUNIOytEQUNFOzBEQUNMO2dFQUNjIn0=

View File

@@ -1,10 +1,21 @@
export { default as Button } from '../dist/admin/components/elements/Button'; export { default as Button } from '../dist/admin/components/elements/Button'
export { default as Card } from '../dist/admin/components/elements/Card'; export { default as Card } from '../dist/admin/components/elements/Card'
export { DocumentDrawer, DocumentDrawerToggler, baseClass as DocumentDrawerBaseClass, useDocumentDrawer, } from '../dist/admin/components/elements/DocumentDrawer'; export {
export { Drawer, DrawerToggler, formatDrawerSlug } from '../dist/admin/components/elements/Drawer'; DocumentDrawer,
export { useDrawerSlug } from '../dist/admin/components/elements/Drawer/useDrawerSlug'; DocumentDrawerToggler,
export { default as Eyebrow } from '../dist/admin/components/elements/Eyebrow'; baseClass as DocumentDrawerBaseClass,
export { Gutter } from '../dist/admin/components/elements/Gutter'; useDocumentDrawer,
export { ListDrawer, ListDrawerToggler, baseClass as ListDrawerBaseClass, formatListDrawerSlug, useListDrawer, } from '../dist/admin/components/elements/ListDrawer'; } from '../dist/admin/components/elements/DocumentDrawer'
export { default as Nav } from '../dist/admin/components/elements/Nav'; export { Drawer, DrawerToggler, formatDrawerSlug } from '../dist/admin/components/elements/Drawer'
export { useDrawerSlug } from '../dist/admin/components/elements/Drawer/useDrawerSlug'
export { default as Eyebrow } from '../dist/admin/components/elements/Eyebrow'
export { Gutter } from '../dist/admin/components/elements/Gutter'
export {
ListDrawer,
ListDrawerToggler,
baseClass as ListDrawerBaseClass,
formatListDrawerSlug,
useListDrawer,
} from '../dist/admin/components/elements/ListDrawer'
export { default as Nav } from '../dist/admin/components/elements/Nav'
//# sourceMappingURL=elements.d.ts.map //# sourceMappingURL=elements.d.ts.map

View File

@@ -1,82 +1,93 @@
"use strict"; 'use strict'
Object.defineProperty(exports, "__esModule", { Object.defineProperty(exports, '__esModule', {
value: true value: true,
}); })
function _export(target, all) { function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, { for (var name in all)
Object.defineProperty(target, name, {
enumerable: true, enumerable: true,
get: all[name] get: all[name],
}); })
} }
_export(exports, { _export(exports, {
Button: function() { Button: function () {
return _Button.default; return _Button.default
}, },
Card: function() { Card: function () {
return _Card.default; return _Card.default
}, },
DocumentDrawer: function() { DocumentDrawer: function () {
return _DocumentDrawer.DocumentDrawer; return _DocumentDrawer.DocumentDrawer
}, },
DocumentDrawerToggler: function() { DocumentDrawerBaseClass: function () {
return _DocumentDrawer.DocumentDrawerToggler; return _DocumentDrawer.baseClass
}, },
DocumentDrawerBaseClass: function() { DocumentDrawerToggler: function () {
return _DocumentDrawer.baseClass; return _DocumentDrawer.DocumentDrawerToggler
}, },
useDocumentDrawer: function() { Drawer: function () {
return _DocumentDrawer.useDocumentDrawer; return _Drawer.Drawer
}, },
Drawer: function() { DrawerToggler: function () {
return _Drawer.Drawer; return _Drawer.DrawerToggler
}, },
DrawerToggler: function() { Eyebrow: function () {
return _Drawer.DrawerToggler; return _Eyebrow.default
}, },
formatDrawerSlug: function() { Gutter: function () {
return _Drawer.formatDrawerSlug; return _Gutter.Gutter
}, },
useDrawerSlug: function() { ListDrawer: function () {
return _useDrawerSlug.useDrawerSlug; return _ListDrawer.ListDrawer
}, },
Eyebrow: function() { ListDrawerBaseClass: function () {
return _Eyebrow.default; return _ListDrawer.baseClass
}, },
Gutter: function() { ListDrawerToggler: function () {
return _Gutter.Gutter; return _ListDrawer.ListDrawerToggler
}, },
ListDrawer: function() { Nav: function () {
return _ListDrawer.ListDrawer; return _Nav.default
}, },
ListDrawerToggler: function() { formatDrawerSlug: function () {
return _ListDrawer.ListDrawerToggler; return _Drawer.formatDrawerSlug
}, },
ListDrawerBaseClass: function() { formatListDrawerSlug: function () {
return _ListDrawer.baseClass; return _ListDrawer.formatListDrawerSlug
}, },
formatListDrawerSlug: function() { useDocumentDrawer: function () {
return _ListDrawer.formatListDrawerSlug; return _DocumentDrawer.useDocumentDrawer
}, },
useListDrawer: function() { useDrawerSlug: function () {
return _ListDrawer.useListDrawer; return _useDrawerSlug.useDrawerSlug
}, },
Nav: function() { useListDrawer: function () {
return _Nav.default; return _ListDrawer.useListDrawer
} },
}); })
const _Button = /*#__PURE__*/ _interop_require_default(require("../dist/admin/components/elements/Button")); const _Button = /*#__PURE__*/ _interop_require_default(
const _Card = /*#__PURE__*/ _interop_require_default(require("../dist/admin/components/elements/Card")); require('../dist/admin/components/elements/Button'),
const _DocumentDrawer = require("../dist/admin/components/elements/DocumentDrawer"); )
const _Drawer = require("../dist/admin/components/elements/Drawer"); const _Card = /*#__PURE__*/ _interop_require_default(
const _useDrawerSlug = require("../dist/admin/components/elements/Drawer/useDrawerSlug"); require('../dist/admin/components/elements/Card'),
const _Eyebrow = /*#__PURE__*/ _interop_require_default(require("../dist/admin/components/elements/Eyebrow")); )
const _Gutter = require("../dist/admin/components/elements/Gutter"); const _DocumentDrawer = require('../dist/admin/components/elements/DocumentDrawer')
const _ListDrawer = require("../dist/admin/components/elements/ListDrawer"); const _Drawer = require('../dist/admin/components/elements/Drawer')
const _Nav = /*#__PURE__*/ _interop_require_default(require("../dist/admin/components/elements/Nav")); const _useDrawerSlug = require('../dist/admin/components/elements/Drawer/useDrawerSlug')
const _Eyebrow = /*#__PURE__*/ _interop_require_default(
require('../dist/admin/components/elements/Eyebrow'),
)
const _Gutter = require('../dist/admin/components/elements/Gutter')
const _ListDrawer = require('../dist/admin/components/elements/ListDrawer')
const _Nav = /*#__PURE__*/ _interop_require_default(
require('../dist/admin/components/elements/Nav'),
)
function _interop_require_default(obj) { function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : { return obj && obj.__esModule
default: obj ? obj
}; : {
default: obj,
}
} }
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9leHBvcnRzL2NvbXBvbmVudHMvZWxlbWVudHMudHMiXSwic291cmNlc0NvbnRlbnQiOlsiZXhwb3J0IHsgZGVmYXVsdCBhcyBCdXR0b24gfSBmcm9tICcuLi8uLi9hZG1pbi9jb21wb25lbnRzL2VsZW1lbnRzL0J1dHRvbidcbmV4cG9ydCB7IGRlZmF1bHQgYXMgQ2FyZCB9IGZyb20gJy4uLy4uL2FkbWluL2NvbXBvbmVudHMvZWxlbWVudHMvQ2FyZCdcbmV4cG9ydCB7XG4gIERvY3VtZW50RHJhd2VyLFxuICBEb2N1bWVudERyYXdlclRvZ2dsZXIsXG4gIGJhc2VDbGFzcyBhcyBEb2N1bWVudERyYXdlckJhc2VDbGFzcyxcbiAgdXNlRG9jdW1lbnREcmF3ZXIsXG59IGZyb20gJy4uLy4uL2FkbWluL2NvbXBvbmVudHMvZWxlbWVudHMvRG9jdW1lbnREcmF3ZXInXG5leHBvcnQgeyBEcmF3ZXIsIERyYXdlclRvZ2dsZXIsIGZvcm1hdERyYXdlclNsdWcgfSBmcm9tICcuLi8uLi9hZG1pbi9jb21wb25lbnRzL2VsZW1lbnRzL0RyYXdlcidcbmV4cG9ydCB7IHVzZURyYXdlclNsdWcgfSBmcm9tICcuLi8uLi9hZG1pbi9jb21wb25lbnRzL2VsZW1lbnRzL0RyYXdlci91c2VEcmF3ZXJTbHVnJ1xuXG5leHBvcnQgeyBkZWZhdWx0IGFzIEV5ZWJyb3cgfSBmcm9tICcuLi8uLi9hZG1pbi9jb21wb25lbnRzL2VsZW1lbnRzL0V5ZWJyb3cnXG5cbmV4cG9ydCB7IEd1dHRlciB9IGZyb20gJy4uLy4uL2FkbWluL2NvbXBvbmVudHMvZWxlbWVudHMvR3V0dGVyJ1xuZXhwb3J0IHtcbiAgTGlzdERyYXdlcixcbiAgTGlzdERyYXdlclRvZ2dsZXIsXG4gIGJhc2VDbGFzcyBhcyBMaXN0RHJhd2VyQmFzZUNsYXNzLFxuICBmb3JtYXRMaXN0RHJhd2VyU2x1ZyxcbiAgdXNlTGlzdERyYXdlcixcbn0gZnJvbSAnLi4vLi4vYWRtaW4vY29tcG9uZW50cy9lbGVtZW50cy9MaXN0RHJhd2VyJ1xuZXhwb3J0IHsgZGVmYXVsdCBhcyBOYXYgfSBmcm9tICcuLi8uLi9hZG1pbi9jb21wb25lbnRzL2VsZW1lbnRzL05hdidcbiJdLCJuYW1lcyI6WyJCdXR0b24iLCJDYXJkIiwiRG9jdW1lbnREcmF3ZXIiLCJEb2N1bWVudERyYXdlclRvZ2dsZXIiLCJEb2N1bWVudERyYXdlckJhc2VDbGFzcyIsImJhc2VDbGFzcyIsInVzZURvY3VtZW50RHJhd2VyIiwiRHJhd2VyIiwiRHJhd2VyVG9nZ2xlciIsImZvcm1hdERyYXdlclNsdWciLCJ1c2VEcmF3ZXJTbHVnIiwiRXllYnJvdyIsIkd1dHRlciIsIkxpc3REcmF3ZXIiLCJMaXN0RHJhd2VyVG9nZ2xlciIsIkxpc3REcmF3ZXJCYXNlQ2xhc3MiLCJmb3JtYXRMaXN0RHJhd2VyU2x1ZyIsInVzZUxpc3REcmF3ZXIiLCJOYXYiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7O0lBQW9CQSxNQUFNO2VBQU5BLGVBQU07O0lBQ05DLElBQUk7ZUFBSkEsYUFBSTs7SUFFdEJDLGNBQWM7ZUFBZEEsOEJBQWM7O0lBQ2RDLHFCQUFxQjtlQUFyQkEscUNBQXFCOztJQUNSQyx1QkFBdUI7ZUFBcENDLHlCQUFTOztJQUNUQyxpQkFBaUI7ZUFBakJBLGlDQUFpQjs7SUFFVkMsTUFBTTtlQUFOQSxjQUFNOztJQUFFQyxhQUFhO2VBQWJBLHFCQUFhOztJQUFFQyxnQkFBZ0I7ZUFBaEJBLHdCQUFnQjs7SUFDdkNDLGFBQWE7ZUFBYkEsNEJBQWE7O0lBRUZDLE9BQU87ZUFBUEEsZ0JBQU87O0lBRWxCQyxNQUFNO2VBQU5BLGNBQU07O0lBRWJDLFVBQVU7ZUFBVkEsc0JBQVU7O0lBQ1ZDLGlCQUFpQjtlQUFqQkEsNkJBQWlCOztJQUNKQyxtQkFBbUI7ZUFBaENWLHFCQUFTOztJQUNUVyxvQkFBb0I7ZUFBcEJBLGdDQUFvQjs7SUFDcEJDLGFBQWE7ZUFBYkEseUJBQWE7O0lBRUtDLEdBQUc7ZUFBSEEsWUFBRzs7OytEQXJCVzs2REFDRjtnQ0FNekI7d0JBQ2lEOytCQUMxQjtnRUFFSzt3QkFFWjs0QkFPaEI7NERBQ3dCIn0= //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9leHBvcnRzL2NvbXBvbmVudHMvZWxlbWVudHMudHMiXSwic291cmNlc0NvbnRlbnQiOlsiZXhwb3J0IHsgZGVmYXVsdCBhcyBCdXR0b24gfSBmcm9tICcuLi8uLi9hZG1pbi9jb21wb25lbnRzL2VsZW1lbnRzL0J1dHRvbidcbmV4cG9ydCB7IGRlZmF1bHQgYXMgQ2FyZCB9IGZyb20gJy4uLy4uL2FkbWluL2NvbXBvbmVudHMvZWxlbWVudHMvQ2FyZCdcbmV4cG9ydCB7XG4gIERvY3VtZW50RHJhd2VyLFxuICBEb2N1bWVudERyYXdlclRvZ2dsZXIsXG4gIGJhc2VDbGFzcyBhcyBEb2N1bWVudERyYXdlckJhc2VDbGFzcyxcbiAgdXNlRG9jdW1lbnREcmF3ZXIsXG59IGZyb20gJy4uLy4uL2FkbWluL2NvbXBvbmVudHMvZWxlbWVudHMvRG9jdW1lbnREcmF3ZXInXG5leHBvcnQgeyBEcmF3ZXIsIERyYXdlclRvZ2dsZXIsIGZvcm1hdERyYXdlclNsdWcgfSBmcm9tICcuLi8uLi9hZG1pbi9jb21wb25lbnRzL2VsZW1lbnRzL0RyYXdlcidcbmV4cG9ydCB7IHVzZURyYXdlclNsdWcgfSBmcm9tICcuLi8uLi9hZG1pbi9jb21wb25lbnRzL2VsZW1lbnRzL0RyYXdlci91c2VEcmF3ZXJTbHVnJ1xuXG5leHBvcnQgeyBkZWZhdWx0IGFzIEV5ZWJyb3cgfSBmcm9tICcuLi8uLi9hZG1pbi9jb21wb25lbnRzL2VsZW1lbnRzL0V5ZWJyb3cnXG5cbmV4cG9ydCB7IEd1dHRlciB9IGZyb20gJy4uLy4uL2FkbWluL2NvbXBvbmVudHMvZWxlbWVudHMvR3V0dGVyJ1xuZXhwb3J0IHtcbiAgTGlzdERyYXdlcixcbiAgTGlzdERyYXdlclRvZ2dsZXIsXG4gIGJhc2VDbGFzcyBhcyBMaXN0RHJhd2VyQmFzZUNsYXNzLFxuICBmb3JtYXRMaXN0RHJhd2VyU2x1ZyxcbiAgdXNlTGlzdERyYXdlcixcbn0gZnJvbSAnLi4vLi4vYWRtaW4vY29tcG9uZW50cy9lbGVtZW50cy9MaXN0RHJhd2VyJ1xuZXhwb3J0IHsgZGVmYXVsdCBhcyBOYXYgfSBmcm9tICcuLi8uLi9hZG1pbi9jb21wb25lbnRzL2VsZW1lbnRzL05hdidcbiJdLCJuYW1lcyI6WyJCdXR0b24iLCJDYXJkIiwiRG9jdW1lbnREcmF3ZXIiLCJEb2N1bWVudERyYXdlclRvZ2dsZXIiLCJEb2N1bWVudERyYXdlckJhc2VDbGFzcyIsImJhc2VDbGFzcyIsInVzZURvY3VtZW50RHJhd2VyIiwiRHJhd2VyIiwiRHJhd2VyVG9nZ2xlciIsImZvcm1hdERyYXdlclNsdWciLCJ1c2VEcmF3ZXJTbHVnIiwiRXllYnJvdyIsIkd1dHRlciIsIkxpc3REcmF3ZXIiLCJMaXN0RHJhd2VyVG9nZ2xlciIsIkxpc3REcmF3ZXJCYXNlQ2xhc3MiLCJmb3JtYXRMaXN0RHJhd2VyU2x1ZyIsInVzZUxpc3REcmF3ZXIiLCJOYXYiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7O0lBQW9CQSxNQUFNO2VBQU5BLGVBQU07O0lBQ05DLElBQUk7ZUFBSkEsYUFBSTs7SUFFdEJDLGNBQWM7ZUFBZEEsOEJBQWM7O0lBQ2RDLHFCQUFxQjtlQUFyQkEscUNBQXFCOztJQUNSQyx1QkFBdUI7ZUFBcENDLHlCQUFTOztJQUNUQyxpQkFBaUI7ZUFBakJBLGlDQUFpQjs7SUFFVkMsTUFBTTtlQUFOQSxjQUFNOztJQUFFQyxhQUFhO2VBQWJBLHFCQUFhOztJQUFFQyxnQkFBZ0I7ZUFBaEJBLHdCQUFnQjs7SUFDdkNDLGFBQWE7ZUFBYkEsNEJBQWE7O0lBRUZDLE9BQU87ZUFBUEEsZ0JBQU87O0lBRWxCQyxNQUFNO2VBQU5BLGNBQU07O0lBRWJDLFVBQVU7ZUFBVkEsc0JBQVU7O0lBQ1ZDLGlCQUFpQjtlQUFqQkEsNkJBQWlCOztJQUNKQyxtQkFBbUI7ZUFBaENWLHFCQUFTOztJQUNUVyxvQkFBb0I7ZUFBcEJBLGdDQUFvQjs7SUFDcEJDLGFBQWE7ZUFBYkEseUJBQWE7O0lBRUtDLEdBQUc7ZUFBSEEsWUFBRzs7OytEQXJCVzs2REFDRjtnQ0FNekI7d0JBQ2lEOytCQUMxQjtnRUFFSzt3QkFFWjs0QkFPaEI7NERBQ3dCIn0=

View File

@@ -1,2 +1,2 @@
export type { Props } from '../../dist/admin/components/forms/field-types/Array/types'; export type { Props } from '../../dist/admin/components/forms/field-types/Array/types'
//# sourceMappingURL=Array.d.ts.map //# sourceMappingURL=Array.d.ts.map

View File

@@ -1,6 +1,6 @@
"use strict"; 'use strict'
Object.defineProperty(exports, "__esModule", { Object.defineProperty(exports, '__esModule', {
value: true value: true,
}); })
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9 //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9

View File

@@ -1,2 +1,2 @@
export type { Props } from '../../dist/admin/components/forms/field-types/Blocks/types'; export type { Props } from '../../dist/admin/components/forms/field-types/Blocks/types'
//# sourceMappingURL=Blocks.d.ts.map //# sourceMappingURL=Blocks.d.ts.map

View File

@@ -1,6 +1,6 @@
"use strict"; 'use strict'
Object.defineProperty(exports, "__esModule", { Object.defineProperty(exports, '__esModule', {
value: true value: true,
}); })
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9 //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9

View File

@@ -1,2 +1,2 @@
export type { Props } from '../../dist/admin/components/views/collections/List/Cell/types'; export type { Props } from '../../dist/admin/components/views/collections/List/Cell/types'
//# sourceMappingURL=Cell.d.ts.map //# sourceMappingURL=Cell.d.ts.map

View File

@@ -1,6 +1,6 @@
"use strict"; 'use strict'
Object.defineProperty(exports, "__esModule", { Object.defineProperty(exports, '__esModule', {
value: true value: true,
}); })
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9 //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9

View File

@@ -1,2 +1,2 @@
export type { Props } from '../../dist/admin/components/forms/field-types/Checkbox/types'; export type { Props } from '../../dist/admin/components/forms/field-types/Checkbox/types'
//# sourceMappingURL=Checkbox.d.ts.map //# sourceMappingURL=Checkbox.d.ts.map

View File

@@ -1,6 +1,6 @@
"use strict"; 'use strict'
Object.defineProperty(exports, "__esModule", { Object.defineProperty(exports, '__esModule', {
value: true value: true,
}); })
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9 //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9

View File

@@ -1,2 +1,2 @@
export type { Props } from '../../dist/admin/components/forms/field-types/Code/types'; export type { Props } from '../../dist/admin/components/forms/field-types/Code/types'
//# sourceMappingURL=Code.d.ts.map //# sourceMappingURL=Code.d.ts.map

View File

@@ -1,6 +1,6 @@
"use strict"; 'use strict'
Object.defineProperty(exports, "__esModule", { Object.defineProperty(exports, '__esModule', {
value: true value: true,
}); })
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9 //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9

View File

@@ -1,2 +1,2 @@
export type { Props } from '../../dist/admin/components/forms/field-types/DateTime/types'; export type { Props } from '../../dist/admin/components/forms/field-types/DateTime/types'
//# sourceMappingURL=DateTime.d.ts.map //# sourceMappingURL=DateTime.d.ts.map

View File

@@ -1,6 +1,6 @@
"use strict"; 'use strict'
Object.defineProperty(exports, "__esModule", { Object.defineProperty(exports, '__esModule', {
value: true value: true,
}); })
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9 //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9

View File

@@ -1,2 +1,2 @@
export type { Props } from '../../dist/admin/components/forms/field-types/Email/types'; export type { Props } from '../../dist/admin/components/forms/field-types/Email/types'
//# sourceMappingURL=Email.d.ts.map //# sourceMappingURL=Email.d.ts.map

View File

@@ -1,6 +1,6 @@
"use strict"; 'use strict'
Object.defineProperty(exports, "__esModule", { Object.defineProperty(exports, '__esModule', {
value: true value: true,
}); })
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9 //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9

View File

@@ -1,2 +1,2 @@
export type { Props } from '../../dist/admin/components/forms/field-types/Group/types'; export type { Props } from '../../dist/admin/components/forms/field-types/Group/types'
//# sourceMappingURL=Group.d.ts.map //# sourceMappingURL=Group.d.ts.map

View File

@@ -1,6 +1,6 @@
"use strict"; 'use strict'
Object.defineProperty(exports, "__esModule", { Object.defineProperty(exports, '__esModule', {
value: true value: true,
}); })
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9 //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9

View File

@@ -1,2 +1,2 @@
export type { Props } from '../../dist/admin/components/forms/field-types/JSON/types'; export type { Props } from '../../dist/admin/components/forms/field-types/JSON/types'
//# sourceMappingURL=Json.d.ts.map //# sourceMappingURL=Json.d.ts.map

View File

@@ -1,6 +1,6 @@
"use strict"; 'use strict'
Object.defineProperty(exports, "__esModule", { Object.defineProperty(exports, '__esModule', {
value: true value: true,
}); })
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9 //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9

View File

@@ -1,2 +1,2 @@
export type { Props } from '../../dist/admin/components/forms/field-types/Number/types'; export type { Props } from '../../dist/admin/components/forms/field-types/Number/types'
//# sourceMappingURL=Number.d.ts.map //# sourceMappingURL=Number.d.ts.map

View File

@@ -1,6 +1,6 @@
"use strict"; 'use strict'
Object.defineProperty(exports, "__esModule", { Object.defineProperty(exports, '__esModule', {
value: true value: true,
}); })
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9 //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9

View File

@@ -1,2 +1,2 @@
export type { Props } from '../../dist/admin/components/forms/field-types/Password/types'; export type { Props } from '../../dist/admin/components/forms/field-types/Password/types'
//# sourceMappingURL=Password.d.ts.map //# sourceMappingURL=Password.d.ts.map

Some files were not shown because too many files have changed in this diff Show More