Merge branch 'beta' into feat/next-icons

This commit is contained in:
Jacob Fletcher
2024-05-14 09:30:01 -04:00
22 changed files with 586 additions and 855 deletions

View File

@@ -12,7 +12,8 @@ on:
- beta
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
# <workflow_name>-<branch_name>-<true || commit_sha if branch is protected>
group: ${{ github.workflow }}-${{ github.ref }}-${{ github.ref_protected && github.sha || ''}}
cancel-in-progress: true
env:
@@ -344,7 +345,7 @@ jobs:
- name: Cache Playwright Browsers for Playwright's Version
id: cache-playwright-browsers
uses: actions/cache@v3
uses: actions/cache@v4
with:
path: ~/.cache/ms-playwright
key: playwright-browsers-${{ env.PLAYWRIGHT_VERSION }}
@@ -423,7 +424,6 @@ jobs:
pnpm run build
tests-type-generation:
if: false # This should be replaced with gen on a real Payload project
runs-on: ubuntu-latest
needs: build

View File

@@ -55,6 +55,7 @@
"@types/esprima": "^4.0.6",
"@types/fs-extra": "^9.0.12",
"@types/jest": "^27.0.3",
"@types/node": "20.12.5"
"@types/node": "20.12.5",
"temp-dir": "2.0.0"
}
}

View File

@@ -2,25 +2,22 @@ import fse from 'fs-extra'
import path from 'path'
import type { CliArgs, DbType, ProjectTemplate } from '../types.js'
import { createProject } from './create-project.js'
import { fileURLToPath } from 'node:url'
import { dbReplacements } from './packages.js'
import { getValidTemplates } from './templates.js'
import globby from 'globby'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
import tempDirectory from 'temp-dir'
const projectDir = path.resolve(dirname, './tmp')
describe('createProject', () => {
let projectDir: string
beforeAll(() => {
console.log = jest.fn()
})
beforeEach(() => {
if (fse.existsSync(projectDir)) {
fse.rmdirSync(projectDir, { recursive: true })
}
projectDir = `${tempDirectory}/${Math.random().toString(36).substring(7)}`
})
afterEach(() => {
if (fse.existsSync(projectDir)) {
fse.rmSync(projectDir, { recursive: true })
@@ -100,6 +97,9 @@ describe('createProject', () => {
const packageJsonPath = path.resolve(projectDir, 'package.json')
const packageJson = fse.readJsonSync(packageJsonPath)
// Verify git was initialized
expect(fse.existsSync(path.resolve(projectDir, '.git'))).toBe(true)
// Should only have one db adapter
expect(
Object.keys(packageJson.dependencies).filter((n) => n.startsWith('@payloadcms/db-')),

View File

@@ -8,6 +8,7 @@ import path from 'path'
import type { CliArgs, DbDetails, PackageManager, ProjectTemplate } from '../types.js'
import { tryInitRepoAndCommit } from '../utils/git.js'
import { debug, error, warning } from '../utils/log.js'
import { configurePayloadConfig } from './configure-payload-config.js'
@@ -108,6 +109,10 @@ export async function createProject(args: {
} else {
spinner.stop('Dependency installation skipped')
}
if (!cliArgs['--no-git']) {
tryInitRepoAndCommit({ cwd: projectDir })
}
}
export async function updatePackageJSON(args: {

View File

@@ -53,6 +53,9 @@ export class Main {
'--use-pnpm': Boolean,
'--use-yarn': Boolean,
// Other
'--no-git': Boolean,
// Flags
'--beta': Boolean,
'--debug': Boolean,

View File

@@ -12,6 +12,7 @@ export interface Args extends arg.Spec {
'--local-template': StringConstructor
'--name': StringConstructor
'--no-deps': BooleanConstructor
'--no-git': BooleanConstructor
'--secret': StringConstructor
'--template': StringConstructor
'--template-branch': StringConstructor

View File

@@ -0,0 +1,50 @@
import type { ExecSyncOptions } from 'child_process'
import { execSync } from 'child_process'
import { warning } from './log.js'
export function tryInitRepoAndCommit(args: { cwd: string }): void {
const execOpts: ExecSyncOptions = { cwd: args.cwd, stdio: 'ignore' }
try {
// Check if git is available
execSync('git -v', execOpts)
// Do nothing if already in a git repo
if (isGitRepo(execOpts)) {
return
}
// Initialize
execSync('git init', execOpts)
if (!ensureHasDefaultBranch(execOpts)) {
execSync('git checkout -b main', execOpts)
}
// Add and commit files
execSync('git add -A', execOpts)
execSync('git commit -m "feat: initial commit"', execOpts)
} catch (_) {
warning('Failed to initialize git repository.')
}
}
function isGitRepo(opts: ExecSyncOptions): boolean {
try {
execSync('git rev-parse --is-inside-work-tree', opts)
return true
} catch (_) {
// Ignore errors
}
return false
}
function ensureHasDefaultBranch(opts: ExecSyncOptions): boolean {
try {
execSync(`git config init.defaultBranch`, opts)
return true
} catch (_) {
// Ignore errros
}
return false
}

5
packages/graphql/bin.js Executable file
View File

@@ -0,0 +1,5 @@
#!/usr/bin/env node
import { bin } from './dist/bin/index.js'
bin()

View File

@@ -13,10 +13,18 @@
"import": "./src/index.ts",
"require": "./src/index.ts",
"types": "./src/index.ts"
},
"./*": {
"import": "./src/exports/*.ts",
"require": "./src/exports/*.ts",
"types": "./src/exports/*.ts"
}
},
"main": "./src/index.ts",
"types": "./src/index.d.ts",
"bin": {
"payload-graphql": "bin.js"
},
"files": [
"dist"
],
@@ -48,6 +56,11 @@
"import": "./dist/index.js",
"require": "./dist/index.js",
"types": "./dist/index.d.ts"
},
"./*": {
"import": "./dist/exports/*.js",
"require": "./dist/exports/*.js",
"types": "./dist/exports/*.d.ts"
}
},
"main": "./dist/index.js",

View File

@@ -0,0 +1,14 @@
/* eslint-disable @typescript-eslint/no-floating-promises */
import type { SanitizedConfig } from 'payload/types'
import fs from 'fs'
import { printSchema } from 'graphql'
import { configToSchema } from '../index.js'
export function generateSchema(config: SanitizedConfig): void {
const outputFile = process.env.PAYLOAD_GRAPHQL_SCHEMA_PATH || config.graphQL.schemaOutputFile
const { schema } = configToSchema(config)
fs.writeFileSync(outputFile, printSchema(schema))
}

View File

@@ -0,0 +1,21 @@
/* eslint-disable no-console */
import minimist from 'minimist'
import { findConfig, importConfig, loadEnv } from 'payload/node'
import { generateSchema } from './generateSchema.js'
export const bin = async () => {
loadEnv()
const configPath = findConfig()
const config = await importConfig(configPath)
const args = minimist(process.argv.slice(2))
const script = (typeof args._[0] === 'string' ? args._[0] : '').toLowerCase()
if (script === 'generate:schema') {
return generateSchema(config)
}
console.log(`Unknown script: "${script}".`)
process.exit(1)
}

View File

@@ -0,0 +1 @@
export { generateSchema } from '../bin/generateSchema.js'

View File

@@ -1,3 +1,29 @@
/**
*
* MIT License
*
* Copyright (c) 2020-present LongYinan
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
import type { Options } from '@swc-node/core'
import { resolve } from 'path'

View File

@@ -26,6 +26,7 @@ export const defaults: Omit<Config, 'db' | 'editor' | 'secret'> = {
graphQL: {
disablePlaygroundInProduction: true,
maxComplexity: 1000,
schemaOutputFile: `${typeof process?.cwd === 'function' ? process.cwd() : ''}/schema.graphql`,
},
hooks: {},
i18n: {},

View File

@@ -116,6 +116,7 @@ export default joi.object({
maxComplexity: joi.number(),
mutations: joi.function(),
queries: joi.function(),
schemaOutputFile: joi.string(),
}),
hooks: joi.object().keys({
afterError: joi.func(),

View File

@@ -566,6 +566,10 @@ export type Config = {
* @see https://payloadcms.com/docs/graphql/extending
*/
queries?: GraphQLExtension
/**
* Filepath to write the generated schema to
*/
schemaOutputFile?: string
}
/**
* Tap into Payload-wide hooks.

View File

@@ -3,4 +3,6 @@
*/
export { generateTypes } from '../bin/generateTypes.js'
export { loadEnv } from '../bin/loadEnv.js'
export { findConfig } from '../config/find.js'
export { importConfig, importWithoutClientFiles } from '../utilities/importWithoutClientFiles.js'

3
pnpm-lock.yaml generated
View File

@@ -328,6 +328,9 @@ importers:
'@types/node':
specifier: 20.12.5
version: 20.12.5
temp-dir:
specifier: 2.0.0
version: 2.0.0
packages/db-mongodb:
dependencies:

File diff suppressed because it is too large Load Diff

View File

@@ -1,31 +1,39 @@
// import fs from 'fs'
// import path from 'path'
import { generateSchema } from '@payloadcms/graphql/utilities'
import fs from 'fs'
import path from 'path'
// TODO: This should be ported to use configToSchema from @payloadcms/graphql
import { setTestEnvPaths } from './helpers/setTestEnvPaths.js'
// import { generateGraphQLSchema } from '../packages/payload/src/bin/generateGraphQLSchema.js'
// import { setTestEnvPaths } from './helpers/setTestEnvPaths.js'
const [testConfigDir] = process.argv.slice(2)
import { fileURLToPath } from 'url'
// const [testConfigDir] = process.argv.slice(2)
import { load } from './loader/load.js'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
// import { fileURLToPath } from 'url'
// const filename = fileURLToPath(import.meta.url)
// const dirname = path.dirname(filename)
const loadConfig = async (configPath: string) => {
const configPromise = await load(configPath)
return configPromise
}
// let testDir
// if (testConfigDir) {
// testDir = path.resolve(dirname, testConfigDir)
// setTestEnvPaths(testDir)
// generateGraphQLSchema()
// } else {
// // Generate graphql schema for entire directory
// testDir = dirname
let testDir
if (testConfigDir) {
testDir = path.resolve(dirname, testConfigDir)
const config = await loadConfig(path.resolve(testDir, 'config.ts'))
// fs.readdirSync(dirname, { withFileTypes: true })
// .filter((f) => f.isDirectory())
// .forEach((dir) => {
// const suiteDir = path.resolve(testDir, dir.name)
// const configFound = setTestEnvPaths(suiteDir)
// if (configFound) generateGraphQLSchema()
// })
// }
setTestEnvPaths(testDir)
generateSchema(config)
} else {
// Generate graphql schema for entire directory
testDir = dirname
const config = await loadConfig(path.resolve(testDir, 'config.ts'))
fs.readdirSync(dirname, { withFileTypes: true })
.filter((f) => f.isDirectory())
.forEach((dir) => {
const suiteDir = path.resolve(testDir, dir.name)
const configFound = setTestEnvPaths(suiteDir)
if (configFound) generateSchema(config)
})
}

View File

@@ -1,35 +1,21 @@
type Query {
Collection1(id: String!, draft: Boolean): Collection1
Collection1s(
draft: Boolean
where: Collection1_where
limit: Int
page: Int
sort: String
): Collection1s
Collection1s(draft: Boolean, where: Collection1_where, limit: Int, page: Int, sort: String): Collection1s
countCollection1s(draft: Boolean, where: Collection1_where): countCollection1s
docAccessCollection1(id: String!): collection1DocAccess
Collection2(id: String!, draft: Boolean): Collection2
Collection2s(
draft: Boolean
where: Collection2_where
limit: Int
page: Int
sort: String
): Collection2s
Collection2s(draft: Boolean, where: Collection2_where, limit: Int, page: Int, sort: String): Collection2s
countCollection2s(draft: Boolean, where: Collection2_where): countCollection2s
docAccessCollection2(id: String!): collection2DocAccess
User(id: String!, draft: Boolean): User
Users(draft: Boolean, where: User_where, limit: Int, page: Int, sort: String): Users
countUsers(draft: Boolean, where: User_where): countUsers
docAccessUser(id: String!): usersDocAccess
meUser: usersMe
initializedUser: Boolean
PayloadPreference(id: String!, draft: Boolean): PayloadPreference
PayloadPreferences(
draft: Boolean
where: PayloadPreference_where
limit: Int
page: Int
sort: String
): PayloadPreferences
PayloadPreferences(draft: Boolean, where: PayloadPreference_where, limit: Int, page: Int, sort: String): PayloadPreferences
countPayloadPreferences(draft: Boolean, where: PayloadPreference_where): countPayloadPreferences
docAccessPayloadPreference(id: String!): payload_preferencesDocAccess
Access: Access
}
@@ -212,6 +198,10 @@ input Collection1_where_or {
OR: [Collection1_where_or]
}
type countCollection1s {
totalDocs: Int
}
type collection1DocAccess {
fields: Collection1DocAccessFields
create: Collection1CreateDocAccess
@@ -451,7 +441,7 @@ type Collection1CreateDocAccess {
"""
The `JSONObject` scalar type represents JSON objects as specified by [ECMA-404](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf).
"""
scalar JSONObject
scalar JSONObject @specifiedBy(url: "http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf")
type Collection1ReadDocAccess {
permission: Boolean!
@@ -655,6 +645,10 @@ input Collection2_where_or {
OR: [Collection2_where_or]
}
type countCollection2s {
totalDocs: Int
}
type collection2DocAccess {
fields: Collection2DocAccessFields
create: Collection2CreateDocAccess
@@ -1031,8 +1025,7 @@ type User {
"""
A field whose value conforms to the standard internet email address format as specified in HTML Spec: https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address.
"""
scalar EmailAddress
@specifiedBy(url: "https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address")
scalar EmailAddress @specifiedBy(url: "https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address")
type Users {
docs: [User]
@@ -1118,6 +1111,10 @@ input User_where_or {
OR: [User_where_or]
}
type countUsers {
totalDocs: Int
}
type usersDocAccess {
fields: UsersDocAccessFields
create: UsersCreateDocAccess
@@ -1281,7 +1278,7 @@ union PayloadPreference_User = User
"""
The `JSON` scalar type represents JSON values as specified by [ECMA-404](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf).
"""
scalar JSON
scalar JSON @specifiedBy(url: "http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf")
type PayloadPreferences {
docs: [PayloadPreference]
@@ -1393,6 +1390,10 @@ input PayloadPreference_where_or {
OR: [PayloadPreference_where_or]
}
type countPayloadPreferences {
totalDocs: Int
}
type payload_preferencesDocAccess {
fields: PayloadPreferencesDocAccessFields
create: PayloadPreferencesCreateDocAccess
@@ -2448,21 +2449,13 @@ type PayloadPreferencesDeleteAccess {
type Mutation {
createCollection1(data: mutationCollection1Input!, draft: Boolean): Collection1
updateCollection1(
id: String!
autosave: Boolean
data: mutationCollection1UpdateInput!
draft: Boolean
): Collection1
updateCollection1(id: String!, autosave: Boolean, data: mutationCollection1UpdateInput!, draft: Boolean): Collection1
deleteCollection1(id: String!): Collection1
duplicateCollection1(id: String!): Collection1
createCollection2(data: mutationCollection2Input!, draft: Boolean): Collection2
updateCollection2(
id: String!
autosave: Boolean
data: mutationCollection2UpdateInput!
draft: Boolean
): Collection2
updateCollection2(id: String!, autosave: Boolean, data: mutationCollection2UpdateInput!, draft: Boolean): Collection2
deleteCollection2(id: String!): Collection2
duplicateCollection2(id: String!): Collection2
createUser(data: mutationUserInput!, draft: Boolean): User
updateUser(id: String!, autosave: Boolean, data: mutationUserUpdateInput!, draft: Boolean): User
deleteUser(id: String!): User
@@ -2474,13 +2467,9 @@ type Mutation {
resetPasswordUser(password: String, token: String): usersResetPassword
verifyEmailUser(token: String): Boolean
createPayloadPreference(data: mutationPayloadPreferenceInput!, draft: Boolean): PayloadPreference
updatePayloadPreference(
id: String!
autosave: Boolean
data: mutationPayloadPreferenceUpdateInput!
draft: Boolean
): PayloadPreference
updatePayloadPreference(id: String!, autosave: Boolean, data: mutationPayloadPreferenceUpdateInput!, draft: Boolean): PayloadPreference
deletePayloadPreference(id: String!): PayloadPreference
duplicatePayloadPreference(id: String!): PayloadPreference
}
input mutationCollection1Input {
@@ -2649,4 +2638,4 @@ input PayloadPreferenceUpdate_UserRelationshipInput {
enum PayloadPreferenceUpdate_UserRelationshipInputRelationTo {
users
}
}

View File

@@ -5,9 +5,11 @@ import path from 'path'
export function setTestEnvPaths(dir) {
const configPath = path.resolve(dir, 'config.ts')
const outputPath = path.resolve(dir, 'payload-types.ts')
const schemaPath = path.resolve(dir, 'schema.graphql')
if (fs.existsSync(configPath)) {
process.env.PAYLOAD_CONFIG_PATH = configPath
process.env.PAYLOAD_TS_OUTPUT_PATH = outputPath
process.env.PAYLOAD_GRAPHQL_SCHEMA_PATH = schemaPath
return true
}
return false