payload 3.0.0-beta.122 → 3.0.0-beta.124
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/collections/operations/find.d.ts.map +1 -1
- package/dist/collections/operations/find.js +1 -0
- package/dist/collections/operations/find.js.map +1 -1
- package/dist/collections/operations/findByID.d.ts.map +1 -1
- package/dist/collections/operations/findByID.js +1 -0
- package/dist/collections/operations/findByID.js.map +1 -1
- package/dist/database/queryValidation/validateSearchParams.d.ts.map +1 -1
- package/dist/database/queryValidation/validateSearchParams.js +7 -0
- package/dist/database/queryValidation/validateSearchParams.js.map +1 -1
- package/dist/globals/operations/findOne.d.ts.map +1 -1
- package/dist/globals/operations/findOne.js +18 -4
- package/dist/globals/operations/findOne.js.map +1 -1
- package/dist/types/index.d.ts +1 -1
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/utilities/addSelectGenericsToGeneratedTyoes.spec.js +4 -4
- package/dist/utilities/addSelectGenericsToGeneratedTyoes.spec.js.map +1 -1
- package/dist/utilities/addSelectGenericsToGeneretedTypes.js +1 -1
- package/dist/utilities/addSelectGenericsToGeneretedTypes.js.map +1 -1
- package/dist/utilities/configToJSONSchema.d.ts.map +1 -1
- package/dist/utilities/configToJSONSchema.js +2 -0
- package/dist/utilities/configToJSONSchema.js.map +1 -1
- package/dist/utilities/telemetry/index.d.ts +1 -0
- package/dist/utilities/telemetry/index.d.ts.map +1 -1
- package/dist/utilities/telemetry/index.js +29 -3
- package/dist/utilities/telemetry/index.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"find.d.ts","sourceRoot":"","sources":["../../../src/collections/operations/find.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAA;AAC5D,OAAO,KAAK,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAC/D,OA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A6B,EAC7B,KAAK,EACN,MAAM,sBAAsB,CAAA;AAC7B,OAAO,KAAK,EACV,UAAU,EAEV,wBAAwB,EACzB,MAAM,oBAAoB,CAAA;AAa3B,MAAM,MAAM,SAAS,GAAG;IACtB,UAAU,EAAE,UAAU,CAAA;IACtB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,aAAa,CAAC,EAAE,OAAO,CAAA;IACvB,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,iBAAiB,CAAC,EAAE,OAAO,CAAA;IAC3B,KAAK,CAAC,EAAE,SAAS,CAAA;IACjB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,GAAG,CAAC,EAAE,cAAc,CAAA;IACpB,MAAM,CAAC,EAAE,UAAU,CAAA;IACnB,gBAAgB,CAAC,EAAE,OAAO,CAAA;IAC1B,IAAI,CAAC,EAAE,IAAI,CAAA;IACX,KAAK,CAAC,EAAE,KAAK,CAAA;CACd,CAAA;AAED,eAAO,MAAM,aAAa,GACxB,KAAK,SAAS,cAAc,EAC5B,OAAO,SAAS,wBAAwB,CAAC,KAAK,CAAC,gBAEjC,SAAS,KACtB,OAAO,CAAC,aAAa,CAAC,6BAA6B,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAsStE,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/collections/operations/find.ts"],"sourcesContent":["import type { AccessResult } from '../../config/types.js'\nimport type { PaginatedDocs } from '../../database/types.js'\nimport type { CollectionSlug, JoinQuery } from '../../index.js'\nimport type {\n PayloadRequest,\n SelectType,\n Sort,\n TransformCollectionWithSelect,\n Where,\n} from '../../types/index.js'\nimport type {\n Collection,\n DataFromCollectionSlug,\n SelectFromCollectionSlug,\n} from '../config/types.js'\n\nimport executeAccess from '../../auth/executeAccess.js'\nimport { combineQueries } from '../../database/combineQueries.js'\nimport { validateQueryPaths } from '../../database/queryValidation/validateQueryPaths.js'\nimport { afterRead } from '../../fields/hooks/afterRead/index.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { buildVersionCollectionFields } from '../../versions/buildCollectionFields.js'\nimport { appendVersionToQueryKey } from '../../versions/drafts/appendVersionToQueryKey.js'\nimport { getQueryDraftsSelect } from '../../versions/drafts/getQueryDraftsSelect.js'\nimport { getQueryDraftsSort } from '../../versions/drafts/getQueryDraftsSort.js'\nimport { buildAfterOperation } from './utils.js'\n\nexport type Arguments = {\n collection: Collection\n currentDepth?: number\n depth?: number\n disableErrors?: boolean\n draft?: boolean\n includeLockStatus?: boolean\n joins?: JoinQuery\n limit?: number\n overrideAccess?: boolean\n page?: number\n pagination?: boolean\n req?: PayloadRequest\n select?: SelectType\n showHiddenFields?: boolean\n sort?: Sort\n where?: Where\n}\n\nexport const findOperation = async <\n TSlug extends CollectionSlug,\n TSelect extends SelectFromCollectionSlug<TSlug>,\n>(\n incomingArgs: Arguments,\n): Promise<PaginatedDocs<TransformCollectionWithSelect<TSlug, TSelect>>> => {\n let args = incomingArgs\n\n try {\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n await args.collection.config.hooks.beforeOperation.reduce(async (priorHook, hook) => {\n await priorHook\n\n args =\n (await hook({\n args,\n collection: args.collection.config,\n context: args.req.context,\n operation: 'read',\n req: args.req,\n })) || args\n }, Promise.resolve())\n\n const {\n collection: { config: collectionConfig },\n collection,\n currentDepth,\n depth,\n disableErrors,\n draft: draftsEnabled,\n includeLockStatus,\n joins,\n limit,\n overrideAccess,\n page,\n pagination = true,\n req: { fallbackLocale, locale, payload },\n req,\n select,\n showHiddenFields,\n sort,\n where,\n } = args\n\n // /////////////////////////////////////\n // Access\n // /////////////////////////////////////\n\n let accessResult: AccessResult\n\n if (!overrideAccess) {\n accessResult = await executeAccess({ disableErrors, req }, collectionConfig.access.read)\n\n // If errors are disabled, and access returns false, return empty results\n if (accessResult === false) {\n return {\n docs: [],\n hasNextPage: false,\n hasPrevPage: false,\n limit,\n nextPage: null,\n page: 1,\n pagingCounter: 1,\n prevPage: null,\n totalDocs: 0,\n totalPages: 1,\n }\n }\n }\n\n // /////////////////////////////////////\n // Find\n // /////////////////////////////////////\n\n const usePagination = pagination && limit !== 0\n const sanitizedLimit = limit ?? (usePagination ? 10 : 0)\n const sanitizedPage = page || 1\n\n let result: PaginatedDocs<DataFromCollectionSlug<TSlug>>\n\n let fullWhere = combineQueries(where, accessResult)\n\n if (collectionConfig.versions?.drafts && draftsEnabled) {\n fullWhere = appendVersionToQueryKey(fullWhere)\n\n await validateQueryPaths({\n collectionConfig: collection.config,\n overrideAccess,\n req,\n versionFields: buildVersionCollectionFields(payload.config, collection.config),\n where: fullWhere,\n })\n\n result = await payload.db.queryDrafts<DataFromCollectionSlug<TSlug>>({\n collection: collectionConfig.slug,\n joins: req.payloadAPI === 'GraphQL' ? false : joins,\n limit: sanitizedLimit,\n locale,\n page: sanitizedPage,\n pagination: usePagination,\n req,\n select: getQueryDraftsSelect({ select }),\n sort: getQueryDraftsSort({ collectionConfig, sort }),\n where: fullWhere,\n })\n } else {\n await validateQueryPaths({\n collectionConfig,\n overrideAccess,\n req,\n where,\n })\n\n result = await payload.db.find<DataFromCollectionSlug<TSlug>>({\n collection: collectionConfig.slug,\n joins: req.payloadAPI === 'GraphQL' ? false : joins,\n limit: sanitizedLimit,\n locale,\n page: sanitizedPage,\n pagination,\n req,\n select,\n sort,\n where: fullWhere,\n })\n }\n\n if (includeLockStatus) {\n try {\n const lockDocumentsProp = collectionConfig?.lockDocuments\n\n const lockDurationDefault = 300 // Default 5 minutes in seconds\n const lockDuration =\n typeof lockDocumentsProp === 'object' ? lockDocumentsProp.duration : lockDurationDefault\n const lockDurationInMilliseconds = lockDuration * 1000\n\n const lockedDocuments = await payload.find({\n collection: 'payload-locked-documents',\n depth: 1,\n limit: sanitizedLimit,\n pagination: false,\n req,\n where: {\n and: [\n {\n 'document.relationTo': {\n equals: collectionConfig.slug,\n },\n },\n {\n 'document.value': {\n in: result.docs.map((doc) => doc.id),\n },\n },\n // Query where the lock is newer than the current time minus lock time\n {\n updatedAt: {\n greater_than: new Date(new Date().getTime() - lockDurationInMilliseconds),\n },\n },\n ],\n },\n })\n\n const now = new Date().getTime()\n const lockedDocs = Array.isArray(lockedDocuments?.docs) ? lockedDocuments.docs : []\n\n // Filter out stale locks\n const validLockedDocs = lockedDocs.filter((lock) => {\n const lastEditedAt = new Date(lock?.updatedAt).getTime()\n return lastEditedAt + lockDurationInMilliseconds > now\n })\n\n result.docs = result.docs.map((doc) => {\n const lockedDoc = validLockedDocs.find((lock) => lock?.document?.value === doc.id)\n return {\n ...doc,\n _isLocked: !!lockedDoc,\n _userEditing: lockedDoc ? lockedDoc?.user?.value : null,\n }\n })\n } catch (error) {\n result.docs = result.docs.map((doc) => ({\n ...doc,\n _isLocked: false,\n _userEditing: null,\n }))\n }\n }\n\n // /////////////////////////////////////\n // beforeRead - Collection\n // /////////////////////////////////////\n\n result = {\n ...result,\n docs: await Promise.all(\n result.docs.map(async (doc) => {\n let docRef = doc\n\n await collectionConfig.hooks.beforeRead.reduce(async (priorHook, hook) => {\n await priorHook\n\n docRef =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: docRef,\n query: fullWhere,\n req,\n })) || docRef\n }, Promise.resolve())\n\n return docRef\n }),\n ),\n }\n\n // /////////////////////////////////////\n // afterRead - Fields\n // /////////////////////////////////////\n\n result = {\n ...result,\n docs: await Promise.all(\n result.docs.map(async (doc) =>\n afterRead<DataFromCollectionSlug<TSlug>>({\n collection: collectionConfig,\n context: req.context,\n currentDepth,\n depth,\n doc,\n draft: draftsEnabled,\n fallbackLocale,\n findMany: true,\n global: null,\n locale,\n overrideAccess,\n req,\n select,\n showHiddenFields,\n }),\n ),\n ),\n }\n\n // /////////////////////////////////////\n // afterRead - Collection\n // /////////////////////////////////////\n\n result = {\n ...result,\n docs: await Promise.all(\n result.docs.map(async (doc) => {\n let docRef = doc\n\n await collectionConfig.hooks.afterRead.reduce(async (priorHook, hook) => {\n await priorHook\n\n docRef =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: docRef,\n findMany: true,\n query: fullWhere,\n req,\n })) || doc\n }, Promise.resolve())\n\n return docRef\n }),\n ),\n }\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: collectionConfig,\n operation: 'find',\n result,\n })\n\n // /////////////////////////////////////\n // Return results\n // /////////////////////////////////////\n\n return result as PaginatedDocs<TransformCollectionWithSelect<TSlug, TSelect>>\n } catch (error: unknown) {\n await killTransaction(args.req)\n throw error\n }\n}\n"],"names":["executeAccess","combineQueries","validateQueryPaths","afterRead","killTransaction","buildVersionCollectionFields","appendVersionToQueryKey","getQueryDraftsSelect","getQueryDraftsSort","buildAfterOperation","findOperation","incomingArgs","args","collection","config","hooks","beforeOperation","reduce","priorHook","hook","context","req","operation","Promise","resolve","collectionConfig","currentDepth","depth","disableErrors","draft","draftsEnabled","includeLockStatus","joins","limit","overrideAccess","page","pagination","fallbackLocale","locale","payload","select","showHiddenFields","sort","where","accessResult","access","read","docs","hasNextPage","hasPrevPage","nextPage","pagingCounter","prevPage","totalDocs","totalPages","usePagination","sanitizedLimit","sanitizedPage","result","fullWhere","versions","drafts","versionFields","db","queryDrafts","slug","payloadAPI","find","lockDocumentsProp","lockDocuments","lockDurationDefault","lockDuration","duration","lockDurationInMilliseconds","lockedDocuments","and","equals","in","map","doc","id","updatedAt","greater_than","Date","getTime","now","lockedDocs","Array","isArray","validLockedDocs","filter","lock","lastEditedAt","lockedDoc","document","value","_isLocked","_userEditing","user","error","all","docRef","beforeRead","query","findMany","global"],"mappings":"AAgBA,OAAOA,mBAAmB,8BAA6B;AACvD,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,kBAAkB,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AAiBV,KAAK,CAACZ,SAAS,CAACc,MAAM,CAAC,OAAOC,WAAWC;oBAC9D,MAAMD;oBAENmF,SACE,AAAC,MAAMlF,KAAK;wBACVN,YAAYY;wBACZL,SAASC,IAAID,OAAO;wBACpB2D,KAAKsB;wBACLG,UAAU;wBACVD,OAAO5C;wBACPtC;oBACF,MAAO0D;gBACX,GAAGxD,QAAQC,OAAO;gBAElB,OAAO6E;YACT;QAEJ;QAEA,wCAAwC;QACxC,8BAA8B;QAC9B,wCAAwC;QAExC3C,SAAS,MAAMjD,oBAAoB;YACjCG;YACAC,YAAYY;YACZH,WAAW;YACXoC;QACF;QAEA,wCAAwC;QACxC,iBAAiB;QACjB,wCAAwC;QAExC,OAAOA;IACT,EAAE,OAAOyC,OAAgB;QACvB,MAAM/F,gBAAgBQ,KAAKS,GAAG;QAC9B,MAAM8E;IACR;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/collections/operations/find.ts"],"sourcesContent":["import type { AccessResult } from '../../config/types.js'\nimport type { PaginatedDocs } from '../../database/types.js'\nimport type { CollectionSlug, JoinQuery } from '../../index.js'\nimport type {\n PayloadRequest,\n SelectType,\n Sort,\n TransformCollectionWithSelect,\n Where,\n} from '../../types/index.js'\nimport type {\n Collection,\n DataFromCollectionSlug,\n SelectFromCollectionSlug,\n} from '../config/types.js'\n\nimport executeAccess from '../../auth/executeAccess.js'\nimport { combineQueries } from '../../database/combineQueries.js'\nimport { validateQueryPaths } from '../../database/queryValidation/validateQueryPaths.js'\nimport { afterRead } from '../../fields/hooks/afterRead/index.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { buildVersionCollectionFields } from '../../versions/buildCollectionFields.js'\nimport { appendVersionToQueryKey } from '../../versions/drafts/appendVersionToQueryKey.js'\nimport { getQueryDraftsSelect } from '../../versions/drafts/getQueryDraftsSelect.js'\nimport { getQueryDraftsSort } from '../../versions/drafts/getQueryDraftsSort.js'\nimport { buildAfterOperation } from './utils.js'\n\nexport type Arguments = {\n collection: Collection\n currentDepth?: number\n depth?: number\n disableErrors?: boolean\n draft?: boolean\n includeLockStatus?: boolean\n joins?: JoinQuery\n limit?: number\n overrideAccess?: boolean\n page?: number\n pagination?: boolean\n req?: PayloadRequest\n select?: SelectType\n showHiddenFields?: boolean\n sort?: Sort\n where?: Where\n}\n\nexport const findOperation = async <\n TSlug extends CollectionSlug,\n TSelect extends SelectFromCollectionSlug<TSlug>,\n>(\n incomingArgs: Arguments,\n): Promise<PaginatedDocs<TransformCollectionWithSelect<TSlug, TSelect>>> => {\n let args = incomingArgs\n\n try {\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n await args.collection.config.hooks.beforeOperation.reduce(async (priorHook, hook) => {\n await priorHook\n\n args =\n (await hook({\n args,\n collection: args.collection.config,\n context: args.req.context,\n operation: 'read',\n req: args.req,\n })) || args\n }, Promise.resolve())\n\n const {\n collection: { config: collectionConfig },\n collection,\n currentDepth,\n depth,\n disableErrors,\n draft: draftsEnabled,\n includeLockStatus,\n joins,\n limit,\n overrideAccess,\n page,\n pagination = true,\n req: { fallbackLocale, locale, payload },\n req,\n select,\n showHiddenFields,\n sort,\n where,\n } = args\n\n // /////////////////////////////////////\n // Access\n // /////////////////////////////////////\n\n let accessResult: AccessResult\n\n if (!overrideAccess) {\n accessResult = await executeAccess({ disableErrors, req }, collectionConfig.access.read)\n\n // If errors are disabled, and access returns false, return empty results\n if (accessResult === false) {\n return {\n docs: [],\n hasNextPage: false,\n hasPrevPage: false,\n limit,\n nextPage: null,\n page: 1,\n pagingCounter: 1,\n prevPage: null,\n totalDocs: 0,\n totalPages: 1,\n }\n }\n }\n\n // /////////////////////////////////////\n // Find\n // /////////////////////////////////////\n\n const usePagination = pagination && limit !== 0\n const sanitizedLimit = limit ?? (usePagination ? 10 : 0)\n const sanitizedPage = page || 1\n\n let result: PaginatedDocs<DataFromCollectionSlug<TSlug>>\n\n let fullWhere = combineQueries(where, accessResult)\n\n if (collectionConfig.versions?.drafts && draftsEnabled) {\n fullWhere = appendVersionToQueryKey(fullWhere)\n\n await validateQueryPaths({\n collectionConfig: collection.config,\n overrideAccess,\n req,\n versionFields: buildVersionCollectionFields(payload.config, collection.config),\n where: fullWhere,\n })\n\n result = await payload.db.queryDrafts<DataFromCollectionSlug<TSlug>>({\n collection: collectionConfig.slug,\n joins: req.payloadAPI === 'GraphQL' ? false : joins,\n limit: sanitizedLimit,\n locale,\n page: sanitizedPage,\n pagination: usePagination,\n req,\n select: getQueryDraftsSelect({ select }),\n sort: getQueryDraftsSort({ collectionConfig, sort }),\n where: fullWhere,\n })\n } else {\n await validateQueryPaths({\n collectionConfig,\n overrideAccess,\n req,\n where,\n })\n\n result = await payload.db.find<DataFromCollectionSlug<TSlug>>({\n collection: collectionConfig.slug,\n joins: req.payloadAPI === 'GraphQL' ? false : joins,\n limit: sanitizedLimit,\n locale,\n page: sanitizedPage,\n pagination,\n req,\n select,\n sort,\n where: fullWhere,\n })\n }\n\n if (includeLockStatus) {\n try {\n const lockDocumentsProp = collectionConfig?.lockDocuments\n\n const lockDurationDefault = 300 // Default 5 minutes in seconds\n const lockDuration =\n typeof lockDocumentsProp === 'object' ? lockDocumentsProp.duration : lockDurationDefault\n const lockDurationInMilliseconds = lockDuration * 1000\n\n const lockedDocuments = await payload.find({\n collection: 'payload-locked-documents',\n depth: 1,\n limit: sanitizedLimit,\n overrideAccess: false,\n pagination: false,\n req,\n where: {\n and: [\n {\n 'document.relationTo': {\n equals: collectionConfig.slug,\n },\n },\n {\n 'document.value': {\n in: result.docs.map((doc) => doc.id),\n },\n },\n // Query where the lock is newer than the current time minus lock time\n {\n updatedAt: {\n greater_than: new Date(new Date().getTime() - lockDurationInMilliseconds),\n },\n },\n ],\n },\n })\n\n const now = new Date().getTime()\n const lockedDocs = Array.isArray(lockedDocuments?.docs) ? lockedDocuments.docs : []\n\n // Filter out stale locks\n const validLockedDocs = lockedDocs.filter((lock) => {\n const lastEditedAt = new Date(lock?.updatedAt).getTime()\n return lastEditedAt + lockDurationInMilliseconds > now\n })\n\n result.docs = result.docs.map((doc) => {\n const lockedDoc = validLockedDocs.find((lock) => lock?.document?.value === doc.id)\n return {\n ...doc,\n _isLocked: !!lockedDoc,\n _userEditing: lockedDoc ? lockedDoc?.user?.value : null,\n }\n })\n } catch (error) {\n result.docs = result.docs.map((doc) => ({\n ...doc,\n _isLocked: false,\n _userEditing: null,\n }))\n }\n }\n\n // /////////////////////////////////////\n // beforeRead - Collection\n // /////////////////////////////////////\n\n result = {\n ...result,\n docs: await Promise.all(\n result.docs.map(async (doc) => {\n let docRef = doc\n\n await collectionConfig.hooks.beforeRead.reduce(async (priorHook, hook) => {\n await priorHook\n\n docRef =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: docRef,\n query: fullWhere,\n req,\n })) || docRef\n }, Promise.resolve())\n\n return docRef\n }),\n ),\n }\n\n // /////////////////////////////////////\n // afterRead - Fields\n // /////////////////////////////////////\n\n result = {\n ...result,\n docs: await Promise.all(\n result.docs.map(async (doc) =>\n afterRead<DataFromCollectionSlug<TSlug>>({\n collection: collectionConfig,\n context: req.context,\n currentDepth,\n depth,\n doc,\n draft: draftsEnabled,\n fallbackLocale,\n findMany: true,\n global: null,\n locale,\n overrideAccess,\n req,\n select,\n showHiddenFields,\n }),\n ),\n ),\n }\n\n // /////////////////////////////////////\n // afterRead - Collection\n // /////////////////////////////////////\n\n result = {\n ...result,\n docs: await Promise.all(\n result.docs.map(async (doc) => {\n let docRef = doc\n\n await collectionConfig.hooks.afterRead.reduce(async (priorHook, hook) => {\n await priorHook\n\n docRef =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: docRef,\n findMany: true,\n query: fullWhere,\n req,\n })) || doc\n }, Promise.resolve())\n\n return docRef\n }),\n ),\n }\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: collectionConfig,\n operation: 'find',\n result,\n })\n\n // /////////////////////////////////////\n // Return results\n // /////////////////////////////////////\n\n return result as PaginatedDocs<TransformCollectionWithSelect<TSlug, TSelect>>\n } catch (error: unknown) {\n await killTransaction(args.req)\n throw error\n }\n}\n"],"names":["executeAccess","combineQueries","validateQueryPaths","afterRead","killTransaction","buildVersionCollectionFields","appendVersionToQueryKey","getQueryDraftsSelect","getQueryDraftsSort","buildAfterOperation","findOperation","incomingArgs","args","collection","config","hooks","beforeOperation","reduce","priorHook","hook","context","req","operation","Promise","resolve","collectionConfig","currentDepth","depth","disableErrors","draft","draftsEnabled","includeLockStatus","joins","limit","overrideAccess","page","pagination","fallbackLocale","locale","payload","select","showHiddenFields","sort","where","accessResult","access","read","docs","hasNextPage","hasPrevPage","nextPage","pagingCounter","prevPage","totalDocs","totalPages","usePagination","sanitizedLimit","sanitizedPage","result","fullWhere","versions","drafts","versionFields","db","queryDrafts","slug","payloadAPI","find","lockDocumentsProp","lockDocuments","lockDurationDefault","lockDuration","duration","lockDurationInMilliseconds","lockedDocuments","and","equals","in","map","doc","id","updatedAt","greater_than","Date","getTime","now","lockedDocs","Array","isArray","validLockedDocs","filter","lock","lastEditedAt","lockedDoc","document","value","_isLocked","_userEditing","user","error","all","docRef","beforeRead","query","findMany","global"],"mappings":"AAgBA,OAAOA,mBAAmB,8BAA6B;AACvD,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,kBAAkB,QAAQ,uDAAsD;AACzF,SAASC,SAAS,QAAQ,wCAAuC;AACjE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,4BAA4B,QAAQ,0CAAyC;AACtF,SAASC,uBAAuB,QAAQ,mDAAkD;AAC1F,SAASC,oBAAoB,QAAQ,gDAA+C;AACpF,SAASC,kBAAkB,QAAQ,8CAA6C;AAChF,SAASC,mBAAmB,QAAQ,aAAY;AAqBhD,OAAO,MAAMC,gBAAgB,OAI3BC;IAEA,IAAIC,OAAOD;IAEX,IAAI;QACF,wCAAwC;QACxC,+BAA+B;QAC/B,wCAAwC;QAExC,MAA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YACZH,WAAW;YACXoC;QACF;QAEA,wCAAwC;QACxC,iBAAiB;QACjB,wCAAwC;QAExC,OAAOA;IACT,EAAE,OAAOyC,OAAgB;QACvB,MAAM/F,gBAAgBQ,KAAKS,GAAG;QAC9B,MAAM8E;IACR;AACF,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"findByID.d.ts","sourceRoot":"","sources":["../../../src/collections/operations/findByID.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAC/D,OAAO,KAAK,EACV,kBAAkB,EAClB,cAAc,EACd,UAAU,EACV,6BAA6B,EAC9B,MAAM,sBAAsB,CAAA;AAC7B,OAAO,KAAK,EACV,UAAU,EAEV,wBAAwB,EACzB,MAAM,oBAAoB,CAAA;AAU3B,MAAM,MAAM,SAAS,GAAG;IACtB,UAAU,EAAE,UAAU,CAAA;IACtB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,aAAa,CAAC,EAAE,OAAO,CAAA;IACvB,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,EAAE,EAAE,MAAM,GAAG,MAAM,CAAA;IACnB,iBAAiB,CAAC,EAAE,OAAO,CAAA;IAC3B,KAAK,CAAC,EAAE,SAAS,CAAA;IACjB,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB,GAAG,EAAE,cAAc,CAAA;IACnB,MAAM,CAAC,EAAE,UAAU,CAAA;IACnB,gBAAgB,CAAC,EAAE,OAAO,CAAA;CAC3B,CAAA;AAED,eAAO,MAAM,iBAAiB,GAC5B,KAAK,SAAS,cAAc,EAC5B,cAAc,SAAS,OAAO,EAC9B,OAAO,SAAS,wBAAwB,CAAC,KAAK,CAAC,gBAEjC,SAAS,KACtB,OAAO,CAAC,kBAAkB,CAAC,6BAA6B,CAAC,KAAK,EAAE,OAAO,CAAC,EAAE,cAAc,CAAC,
|
|
1
|
+
{"version":3,"file":"findByID.d.ts","sourceRoot":"","sources":["../../../src/collections/operations/findByID.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAC/D,OAAO,KAAK,EACV,kBAAkB,EAClB,cAAc,EACd,UAAU,EACV,6BAA6B,EAC9B,MAAM,sBAAsB,CAAA;AAC7B,OAAO,KAAK,EACV,UAAU,EAEV,wBAAwB,EACzB,MAAM,oBAAoB,CAAA;AAU3B,MAAM,MAAM,SAAS,GAAG;IACtB,UAAU,EAAE,UAAU,CAAA;IACtB,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,aAAa,CAAC,EAAE,OAAO,CAAA;IACvB,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,EAAE,EAAE,MAAM,GAAG,MAAM,CAAA;IACnB,iBAAiB,CAAC,EAAE,OAAO,CAAA;IAC3B,KAAK,CAAC,EAAE,SAAS,CAAA;IACjB,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB,GAAG,EAAE,cAAc,CAAA;IACnB,MAAM,CAAC,EAAE,UAAU,CAAA;IACnB,gBAAgB,CAAC,EAAE,OAAO,CAAA;CAC3B,CAAA;AAED,eAAO,MAAM,iBAAiB,GAC5B,KAAK,SAAS,cAAc,EAC5B,cAAc,SAAS,OAAO,EAC9B,OAAO,SAAS,wBAAwB,CAAC,KAAK,CAAC,gBAEjC,SAAS,KACtB,OAAO,CAAC,kBAAkB,CAAC,6BAA6B,CAAC,KAAK,EAAE,OAAO,CAAC,EAAE,cAAc,CAAC,CAmO3F,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/collections/operations/findByID.ts"],"sourcesContent":["import type { FindOneArgs } from '../../database/types.js'\nimport type { CollectionSlug, JoinQuery } from '../../index.js'\nimport type {\n ApplyDisableErrors,\n PayloadRequest,\n SelectType,\n TransformCollectionWithSelect,\n} from '../../types/index.js'\nimport type {\n Collection,\n DataFromCollectionSlug,\n SelectFromCollectionSlug,\n} from '../config/types.js'\n\nimport executeAccess from '../../auth/executeAccess.js'\nimport { combineQueries } from '../../database/combineQueries.js'\nimport { NotFound } from '../../errors/index.js'\nimport { afterRead } from '../../fields/hooks/afterRead/index.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport replaceWithDraftIfAvailable from '../../versions/drafts/replaceWithDraftIfAvailable.js'\nimport { buildAfterOperation } from './utils.js'\n\nexport type Arguments = {\n collection: Collection\n currentDepth?: number\n depth?: number\n disableErrors?: boolean\n draft?: boolean\n id: number | string\n includeLockStatus?: boolean\n joins?: JoinQuery\n overrideAccess?: boolean\n req: PayloadRequest\n select?: SelectType\n showHiddenFields?: boolean\n}\n\nexport const findByIDOperation = async <\n TSlug extends CollectionSlug,\n TDisableErrors extends boolean,\n TSelect extends SelectFromCollectionSlug<TSlug>,\n>(\n incomingArgs: Arguments,\n): Promise<ApplyDisableErrors<TransformCollectionWithSelect<TSlug, TSelect>, TDisableErrors>> => {\n let args = incomingArgs\n\n try {\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n await args.collection.config.hooks.beforeOperation.reduce(async (priorHook, hook) => {\n await priorHook\n\n args =\n (await hook({\n args,\n collection: args.collection.config,\n context: args.req.context,\n operation: 'read',\n req: args.req,\n })) || args\n }, Promise.resolve())\n\n const {\n id,\n collection: { config: collectionConfig },\n currentDepth,\n depth,\n disableErrors,\n draft: draftEnabled = false,\n includeLockStatus,\n joins,\n overrideAccess = false,\n req: { fallbackLocale, locale, t },\n req,\n select,\n showHiddenFields,\n } = args\n\n // /////////////////////////////////////\n // Access\n // /////////////////////////////////////\n\n const accessResult = !overrideAccess\n ? await executeAccess({ id, disableErrors, req }, collectionConfig.access.read)\n : true\n\n // If errors are disabled, and access returns false, return null\n if (accessResult === false) {\n return null\n }\n\n const findOneArgs: FindOneArgs = {\n collection: collectionConfig.slug,\n joins: req.payloadAPI === 'GraphQL' ? false : joins,\n locale,\n req: {\n transactionID: req.transactionID,\n } as PayloadRequest,\n select,\n where: combineQueries({ id: { equals: id } }, accessResult),\n }\n\n // /////////////////////////////////////\n // Find by ID\n // /////////////////////////////////////\n\n if (!findOneArgs.where.and[0].id) {\n throw new NotFound(t)\n }\n\n let result: DataFromCollectionSlug<TSlug> = await req.payload.db.findOne(findOneArgs)\n\n if (!result) {\n if (!disableErrors) {\n throw new NotFound(req.t)\n }\n\n return null\n }\n\n // /////////////////////////////////////\n // Include Lock Status if required\n // /////////////////////////////////////\n\n if (includeLockStatus && id) {\n let lockStatus = null\n\n try {\n const lockDocumentsProp = collectionConfig?.lockDocuments\n\n const lockDurationDefault = 300 // Default 5 minutes in seconds\n const lockDuration =\n typeof lockDocumentsProp === 'object' ? lockDocumentsProp.duration : lockDurationDefault\n const lockDurationInMilliseconds = lockDuration * 1000\n\n const lockedDocument = await req.payload.find({\n collection: 'payload-locked-documents',\n depth: 1,\n limit: 1,\n pagination: false,\n req,\n where: {\n and: [\n {\n 'document.relationTo': {\n equals: collectionConfig.slug,\n },\n },\n {\n 'document.value': {\n equals: id,\n },\n },\n // Query where the lock is newer than the current time minus lock time\n {\n updatedAt: {\n greater_than: new Date(new Date().getTime() - lockDurationInMilliseconds),\n },\n },\n ],\n },\n })\n\n if (lockedDocument && lockedDocument.docs.length > 0) {\n lockStatus = lockedDocument.docs[0]\n }\n } catch {\n // swallow error\n }\n\n result._isLocked = !!lockStatus\n result._userEditing = lockStatus?.user?.value ?? null\n }\n\n // /////////////////////////////////////\n // Replace document with draft if available\n // /////////////////////////////////////\n\n if (collectionConfig.versions?.drafts && draftEnabled) {\n result = await replaceWithDraftIfAvailable({\n accessResult,\n doc: result,\n entity: collectionConfig,\n entityType: 'collection',\n overrideAccess,\n req,\n select,\n })\n }\n\n // /////////////////////////////////////\n // beforeRead - Collection\n // /////////////////////////////////////\n\n await collectionConfig.hooks.beforeRead.reduce(async (priorHook, hook) => {\n await priorHook\n\n result =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: result,\n query: findOneArgs.where,\n req,\n })) || result\n }, Promise.resolve())\n\n // /////////////////////////////////////\n // afterRead - Fields\n // /////////////////////////////////////\n\n result = await afterRead({\n collection: collectionConfig,\n context: req.context,\n currentDepth,\n depth,\n doc: result,\n draft: draftEnabled,\n fallbackLocale,\n global: null,\n locale,\n overrideAccess,\n req,\n select,\n showHiddenFields,\n })\n\n // /////////////////////////////////////\n // afterRead - Collection\n // /////////////////////////////////////\n\n await collectionConfig.hooks.afterRead.reduce(async (priorHook, hook) => {\n await priorHook\n\n result =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: result,\n query: findOneArgs.where,\n req,\n })) || result\n }, Promise.resolve())\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: collectionConfig,\n operation: 'findByID',\n result,\n })\n\n // /////////////////////////////////////\n // Return results\n // /////////////////////////////////////\n\n return result as ApplyDisableErrors<\n TransformCollectionWithSelect<TSlug, TSelect>,\n TDisableErrors\n >\n } catch (error: unknown) {\n await killTransaction(args.req)\n throw error\n }\n}\n"],"names":["executeAccess","combineQueries","NotFound","afterRead","killTransaction","replaceWithDraftIfAvailable","buildAfterOperation","findByIDOperation","incomingArgs","args","collection","config","hooks","beforeOperation","reduce","priorHook","hook","context","req","operation","Promise","resolve","id","collectionConfig","currentDepth","depth","disableErrors","draft","draftEnabled","includeLockStatus","joins","overrideAccess","fallbackLocale","locale","t","select","showHiddenFields","accessResult","access","read","findOneArgs","slug","payloadAPI","transactionID","where","equals","and","result","payload","db","findOne","lockStatus","lockDocumentsProp","lockDocuments","lockDurationDefault","lockDuration","duration","lockDurationInMilliseconds","lockedDocument","find","limit","pagination","updatedAt","greater_than","Date","getTime","docs","length","_isLocked","_userEditing","user","value","versions","drafts","doc","entity","entityType","beforeRead","query","global","error"],"mappings":"AAcA,OAAOA,mBAAmB,8BAA6B;AACv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AwC;QACxC,8BAA8B;QAC9B,wCAAwC;QAExC0B,SAAS,MAAMzC,oBAAoB;YACjCG;YACAC,YAAYa;YACZJ,WAAW;YACX4B;QACF;QAEA,wCAAwC;QACxC,iBAAiB;QACjB,wCAAwC;QAExC,OAAOA;IAIT,EAAE,OAAOiC,OAAgB;QACvB,MAAM5E,gBAAgBK,KAAKS,GAAG;QAC9B,MAAM8D;IACR;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/collections/operations/findByID.ts"],"sourcesContent":["import type { FindOneArgs } from '../../database/types.js'\nimport type { CollectionSlug, JoinQuery } from '../../index.js'\nimport type {\n ApplyDisableErrors,\n PayloadRequest,\n SelectType,\n TransformCollectionWithSelect,\n} from '../../types/index.js'\nimport type {\n Collection,\n DataFromCollectionSlug,\n SelectFromCollectionSlug,\n} from '../config/types.js'\n\nimport executeAccess from '../../auth/executeAccess.js'\nimport { combineQueries } from '../../database/combineQueries.js'\nimport { NotFound } from '../../errors/index.js'\nimport { afterRead } from '../../fields/hooks/afterRead/index.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport replaceWithDraftIfAvailable from '../../versions/drafts/replaceWithDraftIfAvailable.js'\nimport { buildAfterOperation } from './utils.js'\n\nexport type Arguments = {\n collection: Collection\n currentDepth?: number\n depth?: number\n disableErrors?: boolean\n draft?: boolean\n id: number | string\n includeLockStatus?: boolean\n joins?: JoinQuery\n overrideAccess?: boolean\n req: PayloadRequest\n select?: SelectType\n showHiddenFields?: boolean\n}\n\nexport const findByIDOperation = async <\n TSlug extends CollectionSlug,\n TDisableErrors extends boolean,\n TSelect extends SelectFromCollectionSlug<TSlug>,\n>(\n incomingArgs: Arguments,\n): Promise<ApplyDisableErrors<TransformCollectionWithSelect<TSlug, TSelect>, TDisableErrors>> => {\n let args = incomingArgs\n\n try {\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n await args.collection.config.hooks.beforeOperation.reduce(async (priorHook, hook) => {\n await priorHook\n\n args =\n (await hook({\n args,\n collection: args.collection.config,\n context: args.req.context,\n operation: 'read',\n req: args.req,\n })) || args\n }, Promise.resolve())\n\n const {\n id,\n collection: { config: collectionConfig },\n currentDepth,\n depth,\n disableErrors,\n draft: draftEnabled = false,\n includeLockStatus,\n joins,\n overrideAccess = false,\n req: { fallbackLocale, locale, t },\n req,\n select,\n showHiddenFields,\n } = args\n\n // /////////////////////////////////////\n // Access\n // /////////////////////////////////////\n\n const accessResult = !overrideAccess\n ? await executeAccess({ id, disableErrors, req }, collectionConfig.access.read)\n : true\n\n // If errors are disabled, and access returns false, return null\n if (accessResult === false) {\n return null\n }\n\n const findOneArgs: FindOneArgs = {\n collection: collectionConfig.slug,\n joins: req.payloadAPI === 'GraphQL' ? false : joins,\n locale,\n req: {\n transactionID: req.transactionID,\n } as PayloadRequest,\n select,\n where: combineQueries({ id: { equals: id } }, accessResult),\n }\n\n // /////////////////////////////////////\n // Find by ID\n // /////////////////////////////////////\n\n if (!findOneArgs.where.and[0].id) {\n throw new NotFound(t)\n }\n\n let result: DataFromCollectionSlug<TSlug> = await req.payload.db.findOne(findOneArgs)\n\n if (!result) {\n if (!disableErrors) {\n throw new NotFound(req.t)\n }\n\n return null\n }\n\n // /////////////////////////////////////\n // Include Lock Status if required\n // /////////////////////////////////////\n\n if (includeLockStatus && id) {\n let lockStatus = null\n\n try {\n const lockDocumentsProp = collectionConfig?.lockDocuments\n\n const lockDurationDefault = 300 // Default 5 minutes in seconds\n const lockDuration =\n typeof lockDocumentsProp === 'object' ? lockDocumentsProp.duration : lockDurationDefault\n const lockDurationInMilliseconds = lockDuration * 1000\n\n const lockedDocument = await req.payload.find({\n collection: 'payload-locked-documents',\n depth: 1,\n limit: 1,\n overrideAccess: false,\n pagination: false,\n req,\n where: {\n and: [\n {\n 'document.relationTo': {\n equals: collectionConfig.slug,\n },\n },\n {\n 'document.value': {\n equals: id,\n },\n },\n // Query where the lock is newer than the current time minus lock time\n {\n updatedAt: {\n greater_than: new Date(new Date().getTime() - lockDurationInMilliseconds),\n },\n },\n ],\n },\n })\n\n if (lockedDocument && lockedDocument.docs.length > 0) {\n lockStatus = lockedDocument.docs[0]\n }\n } catch {\n // swallow error\n }\n\n result._isLocked = !!lockStatus\n result._userEditing = lockStatus?.user?.value ?? null\n }\n\n // /////////////////////////////////////\n // Replace document with draft if available\n // /////////////////////////////////////\n\n if (collectionConfig.versions?.drafts && draftEnabled) {\n result = await replaceWithDraftIfAvailable({\n accessResult,\n doc: result,\n entity: collectionConfig,\n entityType: 'collection',\n overrideAccess,\n req,\n select,\n })\n }\n\n // /////////////////////////////////////\n // beforeRead - Collection\n // /////////////////////////////////////\n\n await collectionConfig.hooks.beforeRead.reduce(async (priorHook, hook) => {\n await priorHook\n\n result =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: result,\n query: findOneArgs.where,\n req,\n })) || result\n }, Promise.resolve())\n\n // /////////////////////////////////////\n // afterRead - Fields\n // /////////////////////////////////////\n\n result = await afterRead({\n collection: collectionConfig,\n context: req.context,\n currentDepth,\n depth,\n doc: result,\n draft: draftEnabled,\n fallbackLocale,\n global: null,\n locale,\n overrideAccess,\n req,\n select,\n showHiddenFields,\n })\n\n // /////////////////////////////////////\n // afterRead - Collection\n // /////////////////////////////////////\n\n await collectionConfig.hooks.afterRead.reduce(async (priorHook, hook) => {\n await priorHook\n\n result =\n (await hook({\n collection: collectionConfig,\n context: req.context,\n doc: result,\n query: findOneArgs.where,\n req,\n })) || result\n }, Promise.resolve())\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: collectionConfig,\n operation: 'findByID',\n result,\n })\n\n // /////////////////////////////////////\n // Return results\n // /////////////////////////////////////\n\n return result as ApplyDisableErrors<\n TransformCollectionWithSelect<TSlug, TSelect>,\n TDisableErrors\n >\n } catch (error: unknown) {\n await killTransaction(args.req)\n throw error\n }\n}\n"],"names":["executeAccess","combineQueries","NotFound","afterRead","killTransaction","replaceWithDraftIfAvailable","buildAfterOperation","findByIDOperation","incomingArgs","args","collection","config","hooks","beforeOperation","reduce","priorHook","hook","context","req","operation","Promise","resolve","id","collectionConfig","currentDepth","depth","disableErrors","draft","draftEnabled","includeLockStatus","joins","overrideAccess","fallbackLocale","locale","t","select","showHiddenFields","accessResult","access","read","findOneArgs","slug","payloadAPI","transactionID","where","equals","and","result","payload","db","findOne","lockStatus","lockDocumentsProp","lockDocuments","lockDurationDefault","lockDuration","duration","lockDurationInMilliseconds","lockedDocument","find","limit","pagination","updatedAt","greater_than","Date","getTime","docs","length","_isLocked","_userEditing","user","value","versions","drafts","doc","entity","entityType","beforeRead","query","global","error"],"mappings":"AAcA,OAAOA,mBAAmB,8BAA6B;AACvD,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,QAAQ,QAAQ,wBAAuB;AAChD,SAASC,SAAS,QAAQ,wCAAuC;AACjE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,OAAOC,iCAAiC,uDAAsD;AAC9F,SAASC,mBAAmB,QAAQ,aAAY;AAiBhD,OAAO,MAAMC,oBAAoB,OAK/BC;IAEA,IAAIC,OAAOD;IAEX,IAAI;QACF,wCAAwC;QACxC,+BAA+B;QAC/B,wCAAwC;QAExC,MAAMC,KAAKC,UAAU,CAACC,MAAM,CAACC,KAAK,CAACC,eAAe,CAACC,MAAM,CAAC,OAAOC,WAAWC;YAC1E,MAAMD;YAENN,OACE,AAAC,MAAMO,KAAK;gBACVP;gBACAC,YAAYD,KAAKC,UAAU,CAACC,MAAM;gBAClCM,SAASR,KAAKS,GAAG,CAACD,OAAO;gBACzBE,WAAW;gBACXD,KAAKT,KAAKS,GAAG;YACf,MAAOT;QACX,GAAGW,QAAQC,OAAO;QAElB,MAAM,EACJC,EAAE,EACFZ,YAAY,EAAEC,QAAQY,gBAAgB,EAAE,EACxCC,YAAY,EACZC,KAAK,EACLC,aAAa,EACbC,OAAOC,eAAe,KAAK,EAC3BC,iBAAiB,EACjBC,K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C;QAExC0B,SAAS,MAAM5C,UAAU;YACvBO,YAAYa;YACZN,SAASC,IAAID,OAAO;YACpBO;YACAC;YACAiD,KAAK3B;YACLpB,OAAOC;YACPI;YACA+C,QAAQ;YACR9C;YACAF;YACAb;YACAiB;YACAC;QACF;QAEA,wCAAwC;QACxC,yBAAyB;QACzB,wCAAwC;QAExC,MAAMb,iBAAiBX,KAAK,CAACT,SAAS,CAACW,MAAM,CAAC,OAAOC,WAAWC;YAC9D,MAAMD;YAENgC,SACE,AAAC,MAAM/B,KAAK;gBACVN,YAAYa;gBACZN,SAASC,IAAID,OAAO;gBACpByD,KAAK3B;gBACL+B,OAAOtC,YAAYI,KAAK;gBACxB1B;YACF,MAAO6B;QACX,GAAG3B,QAAQC,OAAO;QAElB,wCAAwC;QACxC,8BAA8B;QAC9B,wCAAwC;QAExC0B,SAAS,MAAMzC,oBAAoB;YACjCG;YACAC,YAAYa;YACZJ,WAAW;YACX4B;QACF;QAEA,wCAAwC;QACxC,iBAAiB;QACjB,wCAAwC;QAExC,OAAOA;IAIT,EAAE,OAAOiC,OAAgB;QACvB,MAAM5E,gBAAgBK,KAAKS,GAAG;QAC9B,MAAM8D;IACR;AACF,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validateSearchParams.d.ts","sourceRoot":"","sources":["../../../src/database/queryValidation/validateSearchParams.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAA;AAClF,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,8BAA8B,CAAA;AACzD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAA;AAC1E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AAC1D,OAAO,KAAK,EAAE,cAAc,EAAe,MAAM,YAAY,CAAA;AAQ7D,KAAK,IAAI,GAAG;IACV,gBAAgB,CAAC,EAAE,yBAAyB,CAAA;IAC5C,MAAM,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,EAAE,CAAA;IAC1B,MAAM,EAAE,KAAK,EAAE,CAAA;IACf,YAAY,CAAC,EAAE,qBAAqB,CAAA;IACpC,QAAQ,EAAE,MAAM,CAAA;IAChB,cAAc,EAAE,OAAO,CAAA;IACvB,IAAI,EAAE,MAAM,CAAA;IACZ,QAAQ,EAAE,cAAc,CAAA;IACxB,GAAG,EAAE,cAAc,CAAA;IACnB,GAAG,EAAE,OAAO,CAAA;IACZ,aAAa,CAAC,EAAE,KAAK,EAAE,CAAA;CACxB,CAAA;AAED;;GAEG;AACH,wBAAsB,mBAAmB,CAAC,EACxC,gBAAgB,EAChB,MAAM,EACN,MAAM,EACN,YAAY,EACZ,QAAQ,EACR,cAAc,EACd,IAAI,EAAE,YAAY,EAClB,QAAQ,EACR,GAAG,EACH,GAAG,EACH,aAAa,GACd,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,
|
|
1
|
+
{"version":3,"file":"validateSearchParams.d.ts","sourceRoot":"","sources":["../../../src/database/queryValidation/validateSearchParams.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAA;AAClF,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,8BAA8B,CAAA;AACzD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAA;AAC1E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AAC1D,OAAO,KAAK,EAAE,cAAc,EAAe,MAAM,YAAY,CAAA;AAQ7D,KAAK,IAAI,GAAG;IACV,gBAAgB,CAAC,EAAE,yBAAyB,CAAA;IAC5C,MAAM,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,EAAE,CAAA;IAC1B,MAAM,EAAE,KAAK,EAAE,CAAA;IACf,YAAY,CAAC,EAAE,qBAAqB,CAAA;IACpC,QAAQ,EAAE,MAAM,CAAA;IAChB,cAAc,EAAE,OAAO,CAAA;IACvB,IAAI,EAAE,MAAM,CAAA;IACZ,QAAQ,EAAE,cAAc,CAAA;IACxB,GAAG,EAAE,cAAc,CAAA;IACnB,GAAG,EAAE,OAAO,CAAA;IACZ,aAAa,CAAC,EAAE,KAAK,EAAE,CAAA;CACxB,CAAA;AAED;;GAEG;AACH,wBAAsB,mBAAmB,CAAC,EACxC,gBAAgB,EAChB,MAAM,EACN,MAAM,EACN,YAAY,EACZ,QAAQ,EACR,cAAc,EACd,IAAI,EAAE,YAAY,EAClB,QAAQ,EACR,GAAG,EACH,GAAG,EACH,aAAa,GACd,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAyJtB"}
|
|
@@ -38,6 +38,13 @@ import { validateQueryPaths } from './validateQueryPaths.js';
|
|
|
38
38
|
});
|
|
39
39
|
}
|
|
40
40
|
const promises = [];
|
|
41
|
+
// Sanitize relation.otherRelation.id to relation.otherRelation
|
|
42
|
+
if (paths.at(-1)?.path === 'id') {
|
|
43
|
+
const previousField = paths.at(-2)?.field;
|
|
44
|
+
if (previousField && (previousField.type === 'relationship' || previousField.type === 'upload') && typeof previousField.relationTo === 'string') {
|
|
45
|
+
paths.pop();
|
|
46
|
+
}
|
|
47
|
+
}
|
|
41
48
|
promises.push(...paths.map(async ({ collectionSlug, field, invalid, path }, i)=>{
|
|
42
49
|
if (invalid) {
|
|
43
50
|
errors.push({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/database/queryValidation/validateSearchParams.ts"],"sourcesContent":["import type { SanitizedCollectionConfig } from '../../collections/config/types.js'\nimport type { Field } from '../../fields/config/types.js'\nimport type { SanitizedGlobalConfig } from '../../globals/config/types.js'\nimport type { PayloadRequest } from '../../types/index.js'\nimport type { EntityPolicies, PathToQuery } from './types.js'\n\nimport { fieldAffectsData, fieldIsVirtual } from '../../fields/config/types.js'\nimport { getEntityPolicies } from '../../utilities/getEntityPolicies.js'\nimport isolateObjectProperty from '../../utilities/isolateObjectProperty.js'\nimport { getLocalizedPaths } from '../getLocalizedPaths.js'\nimport { validateQueryPaths } from './validateQueryPaths.js'\n\ntype Args = {\n collectionConfig?: SanitizedCollectionConfig\n errors: { path: string }[]\n fields: Field[]\n globalConfig?: SanitizedGlobalConfig\n operator: string\n overrideAccess: boolean\n path: string\n policies: EntityPolicies\n req: PayloadRequest\n val: unknown\n versionFields?: Field[]\n}\n\n/**\n * Validate the Payload key / value / operator\n */\nexport async function validateSearchParam({\n collectionConfig,\n errors,\n fields,\n globalConfig,\n operator,\n overrideAccess,\n path: incomingPath,\n policies,\n req,\n val,\n versionFields,\n}: Args): Promise<void> {\n // Replace GraphQL nested field double underscore formatting\n let sanitizedPath\n if (incomingPath === '_id') {\n sanitizedPath = 'id'\n } else {\n sanitizedPath = incomingPath.replace(/__/g, '.')\n }\n let paths: PathToQuery[] = []\n const { slug } = collectionConfig || globalConfig\n\n if (globalConfig && !policies.globals[slug]) {\n globalConfig.fields = fields\n\n policies.globals[slug] = await getEntityPolicies({\n type: 'global',\n entity: globalConfig,\n operations: ['read'],\n req,\n })\n }\n\n if (sanitizedPath !== 'id') {\n paths = await getLocalizedPaths({\n collectionSlug: collectionConfig?.slug,\n fields,\n globalSlug: globalConfig?.slug,\n incomingPath: sanitizedPath,\n locale: req.locale,\n overrideAccess,\n payload: req.payload,\n })\n }\n const promises = []\n promises.push(\n ...paths.map(async ({ collectionSlug, field, invalid, path }, i) => {\n if (invalid) {\n errors.push({ path })\n return\n }\n\n if (fieldIsVirtual(field)) {\n errors.push({ path })\n }\n\n if (!overrideAccess && fieldAffectsData(field)) {\n if (collectionSlug) {\n if (!policies.collections[collectionSlug]) {\n policies.collections[collectionSlug] = await getEntityPolicies({\n type: 'collection',\n entity: req.payload.collections[collectionSlug].config,\n operations: ['read'],\n req: isolateObjectProperty(req, 'transactionID'),\n })\n }\n\n if (\n ['hash', 'salt'].includes(incomingPath) &&\n collectionConfig.auth &&\n !collectionConfig.auth?.disableLocalStrategy\n ) {\n errors.push({ path: incomingPath })\n }\n }\n let fieldPath = path\n // remove locale from end of path\n if (path.endsWith(`.${req.locale}`)) {\n fieldPath = path.slice(0, -(req.locale.length + 1))\n }\n // remove \".value\" from ends of polymorphic relationship paths\n if (\n (field.type === 'relationship' || field.type === 'upload') &&\n Array.isArray(field.relationTo)\n ) {\n fieldPath = fieldPath.replace('.value', '')\n }\n const entityType: 'collections' | 'globals' = globalConfig ? 'globals' : 'collections'\n const entitySlug = collectionSlug || globalConfig.slug\n const segments = fieldPath.split('.')\n\n let fieldAccess\n if (versionFields) {\n fieldAccess = policies[entityType][entitySlug]\n if (segments[0] === 'parent' || segments[0] === 'version') {\n segments.shift()\n }\n } else {\n fieldAccess = policies[entityType][entitySlug].fields\n }\n\n segments.forEach((segment) => {\n if (fieldAccess[segment]) {\n if ('fields' in fieldAccess[segment]) {\n fieldAccess = fieldAccess[segment].fields\n } else if ('blocks' in fieldAccess[segment]) {\n fieldAccess = fieldAccess[segment]\n } else {\n fieldAccess = fieldAccess[segment]\n }\n }\n })\n\n if (!fieldAccess?.read?.permission) {\n errors.push({ path: fieldPath })\n }\n }\n\n if (i > 1) {\n // Remove top collection and reverse array\n // to work backwards from top\n const pathsToQuery = paths.slice(1).reverse()\n\n pathsToQuery.forEach(\n ({ collectionSlug: pathCollectionSlug, path: subPath }, pathToQueryIndex) => {\n // On the \"deepest\" collection,\n // validate query of the relationship\n if (pathToQueryIndex === 0) {\n promises.push(\n validateQueryPaths({\n collectionConfig: req.payload.collections[pathCollectionSlug].config,\n errors,\n globalConfig: undefined,\n overrideAccess,\n policies,\n req,\n where: {\n [subPath]: {\n [operator]: val,\n },\n },\n }),\n )\n }\n },\n )\n }\n }),\n )\n await Promise.all(promises)\n}\n"],"names":["fieldAffectsData","fieldIsVirtual","getEntityPolicies","isolateObjectProperty","getLocalizedPaths","validateQueryPaths","validateSearchParam","collectionConfig","errors","fields","globalConfig","operator","overrideAccess","path","incomingPath","policies","req","val","versionFields","sanitizedPath","replace","paths","slug","globals","type","entity","operations","collectionSlug","globalSlug","locale","payload","promises","push","map","field","invalid","i","collections","config","includes","auth","disableLocalStrategy","fieldPath","endsWith","slice","length","Array","isArray","relationTo","entityType","entitySlug","segments","split","fieldAccess","shift","forEach","segment","read","permission","pathsToQuery","reverse","pathCollectionSlug","subPath","pathToQueryIndex","undefined","where","Promise","all"],"mappings":"AAMA,SAASA,gBAAgB,EAAEC,cAAc,QAAQ,+BAA8B;AAC/E,SAASC,iBAAiB,QAAQ,uCAAsC;AACxE,OAAOC,2BAA2B,2CAA0C;AAC5E,SAASC,iBAAiB,QAAQ,0BAAyB;AAC3D,SAASC,kBAAkB,QAAQ,0BAAyB;AAgB5D;;CAEC,GACD,OAAO,eAAeC,oBAAoB,EACxCC,gBAAgB,EAChBC,MAAM,EACNC,MAAM,EACNC,YAAY,EACZC,QAAQ,EACRC,cAAc,EACdC,MAAMC,YAAY,EAClBC,QAAQ,EACRC,GAAG,EACHC,GAAG,EACHC,aAAa,EACR;IACL,4DAA4D;IAC5D,IAAIC;IACJ,IAAIL,iBAAiB,OAAO;QAC1BK,gBAAgB;IAClB,OAAO;QACLA,gBAAgBL,aAAaM,OAAO,CAAC,OAAO;IAC9C;IACA,IAAIC,QAAuB,EAAE;IAC7B,MAAM,EAAEC,IAAI,EAAE,GAAGf,oBAAoBG;IAErC,IAAIA,gBAAgB,CAACK,SAASQ,OAAO,CAACD,KAAK,EAAE;QAC3CZ,aAAaD,MAAM,GAAGA;QAEtBM,SAASQ,OAAO,CAACD,KAAK,GAAG,MAAMpB,kBAAkB;YAC/CsB,MAAM;YACNC,QAAQf;YACRgB,YAAY;gBAAC;aAAO;YACpBV;QACF;IACF;IAEA,IAAIG,kBAAkB,MAAM;QAC1BE,QAAQ,MAAMjB,kBAAkB;YAC9BuB,gBAAgBpB,kBAAkBe;YAClCb;YACAmB,YAAYlB,cAAcY;YAC1BR,cAAcK;YACdU,QAAQb,IAAIa,MAAM;YAClBjB;YACAkB,SAASd,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9B;wBACAE,cAAcsD;wBACdpD;wBACAG;wBACAC;wBACAiD,OAAO;4BACL,CAACH,QAAQ,EAAE;gCACT,CAACnD,SAAS,EAAEM;4BACd;wBACF;oBACF;gBAEJ;YACF;QAEJ;IACF;IAEF,MAAMiD,QAAQC,GAAG,CAACpC;AACpB"}
|
|
1
|
+
{"version":3,"sources":["../../../src/database/queryValidation/validateSearchParams.ts"],"sourcesContent":["import type { SanitizedCollectionConfig } from '../../collections/config/types.js'\nimport type { Field } from '../../fields/config/types.js'\nimport type { SanitizedGlobalConfig } from '../../globals/config/types.js'\nimport type { PayloadRequest } from '../../types/index.js'\nimport type { EntityPolicies, PathToQuery } from './types.js'\n\nimport { fieldAffectsData, fieldIsVirtual } from '../../fields/config/types.js'\nimport { getEntityPolicies } from '../../utilities/getEntityPolicies.js'\nimport isolateObjectProperty from '../../utilities/isolateObjectProperty.js'\nimport { getLocalizedPaths } from '../getLocalizedPaths.js'\nimport { validateQueryPaths } from './validateQueryPaths.js'\n\ntype Args = {\n collectionConfig?: SanitizedCollectionConfig\n errors: { path: string }[]\n fields: Field[]\n globalConfig?: SanitizedGlobalConfig\n operator: string\n overrideAccess: boolean\n path: string\n policies: EntityPolicies\n req: PayloadRequest\n val: unknown\n versionFields?: Field[]\n}\n\n/**\n * Validate the Payload key / value / operator\n */\nexport async function validateSearchParam({\n collectionConfig,\n errors,\n fields,\n globalConfig,\n operator,\n overrideAccess,\n path: incomingPath,\n policies,\n req,\n val,\n versionFields,\n}: Args): Promise<void> {\n // Replace GraphQL nested field double underscore formatting\n let sanitizedPath\n if (incomingPath === '_id') {\n sanitizedPath = 'id'\n } else {\n sanitizedPath = incomingPath.replace(/__/g, '.')\n }\n let paths: PathToQuery[] = []\n const { slug } = collectionConfig || globalConfig\n\n if (globalConfig && !policies.globals[slug]) {\n globalConfig.fields = fields\n\n policies.globals[slug] = await getEntityPolicies({\n type: 'global',\n entity: globalConfig,\n operations: ['read'],\n req,\n })\n }\n\n if (sanitizedPath !== 'id') {\n paths = await getLocalizedPaths({\n collectionSlug: collectionConfig?.slug,\n fields,\n globalSlug: globalConfig?.slug,\n incomingPath: sanitizedPath,\n locale: req.locale,\n overrideAccess,\n payload: req.payload,\n })\n }\n const promises = []\n\n // Sanitize relation.otherRelation.id to relation.otherRelation\n if (paths.at(-1)?.path === 'id') {\n const previousField = paths.at(-2)?.field\n if (\n previousField &&\n (previousField.type === 'relationship' || previousField.type === 'upload') &&\n typeof previousField.relationTo === 'string'\n ) {\n paths.pop()\n }\n }\n\n promises.push(\n ...paths.map(async ({ collectionSlug, field, invalid, path }, i) => {\n if (invalid) {\n errors.push({ path })\n return\n }\n\n if (fieldIsVirtual(field)) {\n errors.push({ path })\n }\n\n if (!overrideAccess && fieldAffectsData(field)) {\n if (collectionSlug) {\n if (!policies.collections[collectionSlug]) {\n policies.collections[collectionSlug] = await getEntityPolicies({\n type: 'collection',\n entity: req.payload.collections[collectionSlug].config,\n operations: ['read'],\n req: isolateObjectProperty(req, 'transactionID'),\n })\n }\n\n if (\n ['hash', 'salt'].includes(incomingPath) &&\n collectionConfig.auth &&\n !collectionConfig.auth?.disableLocalStrategy\n ) {\n errors.push({ path: incomingPath })\n }\n }\n let fieldPath = path\n // remove locale from end of path\n if (path.endsWith(`.${req.locale}`)) {\n fieldPath = path.slice(0, -(req.locale.length + 1))\n }\n // remove \".value\" from ends of polymorphic relationship paths\n if (\n (field.type === 'relationship' || field.type === 'upload') &&\n Array.isArray(field.relationTo)\n ) {\n fieldPath = fieldPath.replace('.value', '')\n }\n\n const entityType: 'collections' | 'globals' = globalConfig ? 'globals' : 'collections'\n const entitySlug = collectionSlug || globalConfig.slug\n const segments = fieldPath.split('.')\n\n let fieldAccess\n if (versionFields) {\n fieldAccess = policies[entityType][entitySlug]\n if (segments[0] === 'parent' || segments[0] === 'version') {\n segments.shift()\n }\n } else {\n fieldAccess = policies[entityType][entitySlug].fields\n }\n\n segments.forEach((segment) => {\n if (fieldAccess[segment]) {\n if ('fields' in fieldAccess[segment]) {\n fieldAccess = fieldAccess[segment].fields\n } else if ('blocks' in fieldAccess[segment]) {\n fieldAccess = fieldAccess[segment]\n } else {\n fieldAccess = fieldAccess[segment]\n }\n }\n })\n\n if (!fieldAccess?.read?.permission) {\n errors.push({ path: fieldPath })\n }\n }\n\n if (i > 1) {\n // Remove top collection and reverse array\n // to work backwards from top\n const pathsToQuery = paths.slice(1).reverse()\n\n pathsToQuery.forEach(\n ({ collectionSlug: pathCollectionSlug, path: subPath }, pathToQueryIndex) => {\n // On the \"deepest\" collection,\n // validate query of the relationship\n if (pathToQueryIndex === 0) {\n promises.push(\n validateQueryPaths({\n collectionConfig: req.payload.collections[pathCollectionSlug].config,\n errors,\n globalConfig: undefined,\n overrideAccess,\n policies,\n req,\n where: {\n [subPath]: {\n [operator]: val,\n },\n },\n }),\n )\n }\n },\n )\n }\n }),\n )\n await Promise.all(promises)\n}\n"],"names":["fieldAffectsData","fieldIsVirtual","getEntityPolicies","isolateObjectProperty","getLocalizedPaths","validateQueryPaths","validateSearchParam","collectionConfig","errors","fields","globalConfig","operator","overrideAccess","path","incomingPath","policies","req","val","versionFields","sanitizedPath","replace","paths","slug","globals","type","entity","operations","collectionSlug","globalSlug","locale","payload","promises","at","previousField","field","relationTo","pop","push","map","invalid","i","collections","config","includes","auth","disableLocalStrategy","fieldPath","endsWith","slice","length","Array","isArray","entityType","entitySlug","segments","split","fieldAccess","shift","forEach","segment","read","permission","pathsToQuery","reverse","pathCollectionSlug","subPath","pathToQueryIndex","undefined","where","Promise","all"],"mappings":"AAMA,SAASA,gBAAgB,EAAEC,cAAc,QAAQ,+BAA8B;AAC/E,SAASC,iBAAiB,QAAQ,uCAAsC;AACxE,OAAOC,2BAA2B,2CAA0C;AAC5E,SAASC,iBAAiB,QAAQ,0BAAyB;AAC3D,SAASC,kBAAkB,QAAQ,0BAAyB;AAgB5D;;CAEC,GACD,OAAO,eAAeC,oBAAoB,EACxCC,gBAAgB,EAChBC,MAAM,EACNC,MAA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1
|
-
{"version":3,"file":"findOne.d.ts","sourceRoot":"","sources":["../../../src/globals/operations/findOne.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,UAAU,EAAS,MAAM,sBAAsB,CAAA;AAC7E,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAA;AAQ/D,KAAK,IAAI,GAAG;IACV,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,YAAY,EAAE,qBAAqB,CAAA;IACnC,iBAAiB,CAAC,EAAE,OAAO,CAAA;IAC3B,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB,GAAG,EAAE,cAAc,CAAA;IACnB,MAAM,CAAC,EAAE,UAAU,CAAA;IACnB,gBAAgB,CAAC,EAAE,OAAO,CAAA;IAC1B,IAAI,EAAE,MAAM,CAAA;CACb,CAAA;AAED,eAAO,MAAM,gBAAgB,GAAU,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,QAChE,IAAI,KACT,OAAO,CAAC,CAAC,
|
|
1
|
+
{"version":3,"file":"findOne.d.ts","sourceRoot":"","sources":["../../../src/globals/operations/findOne.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,UAAU,EAAS,MAAM,sBAAsB,CAAA;AAC7E,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAA;AAQ/D,KAAK,IAAI,GAAG;IACV,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,YAAY,EAAE,qBAAqB,CAAA;IACnC,iBAAiB,CAAC,EAAE,OAAO,CAAA;IAC3B,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB,GAAG,EAAE,cAAc,CAAA;IACnB,MAAM,CAAC,EAAE,UAAU,CAAA;IACnB,gBAAgB,CAAC,EAAE,OAAO,CAAA;IAC1B,IAAI,EAAE,MAAM,CAAA;CACb,CAAA;AAED,eAAO,MAAM,gBAAgB,GAAU,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,QAChE,IAAI,KACT,OAAO,CAAC,CAAC,CAiLX,CAAA"}
|
|
@@ -34,16 +34,31 @@ export const findOneOperation = async (args)=>{
|
|
|
34
34
|
if (includeLockStatus && slug) {
|
|
35
35
|
let lockStatus = null;
|
|
36
36
|
try {
|
|
37
|
+
const lockDocumentsProp = globalConfig?.lockDocuments;
|
|
38
|
+
const lockDurationDefault = 300 // Default 5 minutes in seconds
|
|
39
|
+
;
|
|
40
|
+
const lockDuration = typeof lockDocumentsProp === 'object' ? lockDocumentsProp.duration : lockDurationDefault;
|
|
41
|
+
const lockDurationInMilliseconds = lockDuration * 1000;
|
|
37
42
|
const lockedDocument = await req.payload.find({
|
|
38
43
|
collection: 'payload-locked-documents',
|
|
39
44
|
depth: 1,
|
|
40
45
|
limit: 1,
|
|
46
|
+
overrideAccess: false,
|
|
41
47
|
pagination: false,
|
|
42
48
|
req,
|
|
43
49
|
where: {
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
50
|
+
and: [
|
|
51
|
+
{
|
|
52
|
+
globalSlug: {
|
|
53
|
+
equals: slug
|
|
54
|
+
}
|
|
55
|
+
},
|
|
56
|
+
{
|
|
57
|
+
updatedAt: {
|
|
58
|
+
greater_than: new Date(new Date().getTime() - lockDurationInMilliseconds)
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
]
|
|
47
62
|
}
|
|
48
63
|
});
|
|
49
64
|
if (lockedDocument && lockedDocument.docs.length > 0) {
|
|
@@ -53,7 +68,6 @@ export const findOneOperation = async (args)=>{
|
|
|
53
68
|
// swallow error
|
|
54
69
|
}
|
|
55
70
|
doc._isLocked = !!lockStatus;
|
|
56
|
-
doc._lastEditedAt = lockStatus?.updatedAt ?? null;
|
|
57
71
|
doc._userEditing = lockStatus?.user?.value ?? null;
|
|
58
72
|
}
|
|
59
73
|
// /////////////////////////////////////
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/globals/operations/findOne.ts"],"sourcesContent":["import type { AccessResult } from '../../config/types.js'\nimport type { PayloadRequest, SelectType, Where } from '../../types/index.js'\nimport type { SanitizedGlobalConfig } from '../config/types.js'\n\nimport executeAccess from '../../auth/executeAccess.js'\nimport { afterRead } from '../../fields/hooks/afterRead/index.js'\nimport { getSelectMode } from '../../utilities/getSelectMode.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport replaceWithDraftIfAvailable from '../../versions/drafts/replaceWithDraftIfAvailable.js'\n\ntype Args = {\n depth?: number\n draft?: boolean\n globalConfig: SanitizedGlobalConfig\n includeLockStatus?: boolean\n overrideAccess?: boolean\n req: PayloadRequest\n select?: SelectType\n showHiddenFields?: boolean\n slug: string\n}\n\nexport const findOneOperation = async <T extends Record<string, unknown>>(\n args: Args,\n): Promise<T> => {\n const {\n slug,\n depth,\n draft: draftEnabled = false,\n globalConfig,\n includeLockStatus,\n overrideAccess = false,\n req: { fallbackLocale, locale },\n req,\n select,\n showHiddenFields,\n } = args\n\n try {\n // /////////////////////////////////////\n // Retrieve and execute access\n // /////////////////////////////////////\n\n let accessResult: AccessResult\n\n if (!overrideAccess) {\n accessResult = await executeAccess({ req }, globalConfig.access.read)\n }\n\n // /////////////////////////////////////\n // Perform database operation\n // /////////////////////////////////////\n\n let doc = await req.payload.db.findGlobal({\n slug,\n locale,\n req,\n select,\n where: overrideAccess ? undefined : (accessResult as Where),\n })\n if (!doc) {\n doc = {}\n }\n\n // /////////////////////////////////////\n // Include Lock Status if required\n // /////////////////////////////////////\n
|
|
1
|
+
{"version":3,"sources":["../../../src/globals/operations/findOne.ts"],"sourcesContent":["import type { AccessResult } from '../../config/types.js'\nimport type { PayloadRequest, SelectType, Where } from '../../types/index.js'\nimport type { SanitizedGlobalConfig } from '../config/types.js'\n\nimport executeAccess from '../../auth/executeAccess.js'\nimport { afterRead } from '../../fields/hooks/afterRead/index.js'\nimport { getSelectMode } from '../../utilities/getSelectMode.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport replaceWithDraftIfAvailable from '../../versions/drafts/replaceWithDraftIfAvailable.js'\n\ntype Args = {\n depth?: number\n draft?: boolean\n globalConfig: SanitizedGlobalConfig\n includeLockStatus?: boolean\n overrideAccess?: boolean\n req: PayloadRequest\n select?: SelectType\n showHiddenFields?: boolean\n slug: string\n}\n\nexport const findOneOperation = async <T extends Record<string, unknown>>(\n args: Args,\n): Promise<T> => {\n const {\n slug,\n depth,\n draft: draftEnabled = false,\n globalConfig,\n includeLockStatus,\n overrideAccess = false,\n req: { fallbackLocale, locale },\n req,\n select,\n showHiddenFields,\n } = args\n\n try {\n // /////////////////////////////////////\n // Retrieve and execute access\n // /////////////////////////////////////\n\n let accessResult: AccessResult\n\n if (!overrideAccess) {\n accessResult = await executeAccess({ req }, globalConfig.access.read)\n }\n\n // /////////////////////////////////////\n // Perform database operation\n // /////////////////////////////////////\n\n let doc = await req.payload.db.findGlobal({\n slug,\n locale,\n req,\n select,\n where: overrideAccess ? undefined : (accessResult as Where),\n })\n if (!doc) {\n doc = {}\n }\n\n // /////////////////////////////////////\n // Include Lock Status if required\n // /////////////////////////////////////\n if (includeLockStatus && slug) {\n let lockStatus = null\n\n try {\n const lockDocumentsProp = globalConfig?.lockDocuments\n\n const lockDurationDefault = 300 // Default 5 minutes in seconds\n const lockDuration =\n typeof lockDocumentsProp === 'object' ? lockDocumentsProp.duration : lockDurationDefault\n const lockDurationInMilliseconds = lockDuration * 1000\n\n const lockedDocument = await req.payload.find({\n collection: 'payload-locked-documents',\n depth: 1,\n limit: 1,\n overrideAccess: false,\n pagination: false,\n req,\n where: {\n and: [\n {\n globalSlug: {\n equals: slug,\n },\n },\n {\n updatedAt: {\n greater_than: new Date(new Date().getTime() - lockDurationInMilliseconds),\n },\n },\n ],\n },\n })\n\n if (lockedDocument && lockedDocument.docs.length > 0) {\n lockStatus = lockedDocument.docs[0]\n }\n } catch {\n // swallow error\n }\n\n doc._isLocked = !!lockStatus\n doc._userEditing = lockStatus?.user?.value ?? null\n }\n\n // /////////////////////////////////////\n // Replace document with draft if available\n // /////////////////////////////////////\n\n if (globalConfig.versions?.drafts && draftEnabled) {\n doc = await replaceWithDraftIfAvailable({\n accessResult,\n doc,\n entity: globalConfig,\n entityType: 'global',\n overrideAccess,\n req,\n select,\n })\n }\n\n // /////////////////////////////////////\n // Execute before global hook\n // /////////////////////////////////////\n\n await globalConfig.hooks.beforeRead.reduce(async (priorHook, hook) => {\n await priorHook\n\n doc =\n (await hook({\n context: req.context,\n doc,\n global: globalConfig,\n req,\n })) || doc\n }, Promise.resolve())\n\n // /////////////////////////////////////\n // Execute globalType field if not selected\n // /////////////////////////////////////\n if (select && doc.globalType) {\n const selectMode = getSelectMode(select)\n if (\n (selectMode === 'include' && !select['globalType']) ||\n (selectMode === 'exclude' && select['globalType'] === false)\n ) {\n delete doc['globalType']\n }\n }\n\n // /////////////////////////////////////\n // Execute field-level hooks and access\n // /////////////////////////////////////\n\n doc = await afterRead({\n collection: null,\n context: req.context,\n depth,\n doc,\n draft: draftEnabled,\n fallbackLocale,\n global: globalConfig,\n locale,\n overrideAccess,\n req,\n select,\n showHiddenFields,\n })\n\n // /////////////////////////////////////\n // Execute after global hook\n // /////////////////////////////////////\n\n await globalConfig.hooks.afterRead.reduce(async (priorHook, hook) => {\n await priorHook\n\n doc =\n (await hook({\n context: req.context,\n doc,\n global: globalConfig,\n req,\n })) || doc\n }, Promise.resolve())\n\n // /////////////////////////////////////\n // Return results\n // /////////////////////////////////////\n\n return doc\n } catch (error: unknown) {\n await killTransaction(req)\n throw error\n }\n}\n"],"names":["executeAccess","afterRead","getSelectMode","killTransaction","replaceWithDraftIfAvailable","findOneOperation","args","slug","depth","draft","draftEnabled","globalConfig","includeLockStatus","overrideAccess","req","fallbackLocale","locale","select","showHiddenFields","accessResult","access","read","doc","payload","db","findGlobal","where","undefined","lockStatus","lockDocumentsProp","lockDocuments","lockDurationDefault","lockDuration","duration","lockDurationInMilliseconds","lockedDocument","find","collection","limit","pagination","and","globalSlug","equals","updatedAt","greater_than","Date","getTime","docs","length","_isLocked","_userEditing","user","value","versions","drafts","entity","entityType","hooks","beforeRead","reduce","priorHook","hook","context","global","Promise","resolve","globalType","selectMode","error"],"mappings":"AAIA,OAAOA,mBAAmB,8BAA6B;AACvD,SAASC,SAAS,QAAQ,wCAAuC;AACjE,SAASC,aAAa,QAAQ,mCAAkC;AAChE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,OAAOC,iCAAiC,uDAAsD;AAc9F,OAAO,MAAMC,mBAAmB,OAC9BC;IAEA,MAAM,EACJC,IAAI,EACJC,KAAK,EACLC,OAAOC,eAAe,KAAK,EAC3BC,YAAY,EACZC,iBAAiB,EACjBC,iBAAiB,KAAK,EACtBC,KAAK,EAAEC,cAAc,EAAEC,MAAM,EAAE,EAC/BF,GAAG,EACHG,MAAM,EACNC,gBAAgB,EACjB,GAAGZ;IAEJ,IAAI;QACF,wCAAwC;QACxC,8BAA8B;QAC9B,wCAAwC;QAExC,IAAIa;QAEJ,IAAI,CAACN,gBAAgB;YACnBM,eAAe,MAAMnB,cAAc;gBAAEc;YAAI,GAAGH,aAAaS,MAAM,CAACC,IAAI;QACtE;QAEA,wCAAwC;QACxC,6BAA6B;QAC7B,wCAAwC;QAExC,IAAIC,MAAM,MAAMR,IAAIS,OAAO,CAACC,EAAE,CAACC,UAAU,CAAC;YACxClB;YACAS;YACAF;YACAG;YACAS,OAAOb,iBAAiBc,YAAaR;QACvC;QACA,IAAI,CAACG,KAAK;YACRA,MAAM,CAAC;QACT;QAEA,wCAAwC;QACxC,kCAAkC;QAClC,wCAAwC;QACxC,IAAIV,qBAAqBL,MAAM;YAC7B,IAAIqB,aAAa;YAEjB,IAAI;gBACF,MAAMC,oBAAoBlB,cAAcmB;gBAExC,MAAMC,sBAAsB,IAAI,+BAA+B;;gBAC/D,MAAMC,eACJ,OAAOH,sBAAsB,WAAWA,kBA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,eAAe,aAAa,CAAClD,MAAM,CAAC,aAAa,IACjDkD,eAAe,aAAalD,MAAM,CAAC,aAAa,KAAK,OACtD;gBACA,OAAOK,GAAG,CAAC,aAAa;YAC1B;QACF;QAEA,wCAAwC;QACxC,uCAAuC;QACvC,wCAAwC;QAExCA,MAAM,MAAMrB,UAAU;YACpBoC,YAAY;YACZyB,SAAShD,IAAIgD,OAAO;YACpBtD;YACAc;YACAb,OAAOC;YACPK;YACAgD,QAAQpD;YACRK;YACAH;YACAC;YACAG;YACAC;QACF;QAEA,wCAAwC;QACxC,4BAA4B;QAC5B,wCAAwC;QAExC,MAAMP,aAAa8C,KAAK,CAACxD,SAAS,CAAC0D,MAAM,CAAC,OAAOC,WAAWC;YAC1D,MAAMD;YAENtC,MACE,AAAC,MAAMuC,KAAK;gBACVC,SAAShD,IAAIgD,OAAO;gBACpBxC;gBACAyC,QAAQpD;gBACRG;YACF,MAAOQ;QACX,GAAG0C,QAAQC,OAAO;QAElB,wCAAwC;QACxC,iBAAiB;QACjB,wCAAwC;QAExC,OAAO3C;IACT,EAAE,OAAO8C,OAAgB;QACvB,MAAMjE,gBAAgBW;QACtB,MAAMsD;IACR;AACF,EAAC"}
|
package/dist/types/index.d.ts
CHANGED
|
@@ -120,7 +120,7 @@ export type SelectExcludeType = {
|
|
|
120
120
|
};
|
|
121
121
|
export type SelectMode = 'exclude' | 'include';
|
|
122
122
|
export type SelectType = SelectExcludeType | SelectIncludeType;
|
|
123
|
-
export type ApplyDisableErrors<T, DisableErrors
|
|
123
|
+
export type ApplyDisableErrors<T, DisableErrors = false> = false extends DisableErrors ? T : null | T;
|
|
124
124
|
export type TransformDataWithSelect<Data extends Record<string, any>, Select extends SelectType> = Select extends never ? Data : string extends keyof Select ? Data : string extends keyof Omit<Data, 'id'> ? Select extends SelectIncludeType ? {
|
|
125
125
|
[K in Data extends TypeWithID ? 'id' | keyof Select : keyof Select]: K extends 'id' ? number | string : unknown;
|
|
126
126
|
} : Data : Select extends SelectInc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AI,GAIJ,MAAM,SAAS,MAAM,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,GACnC,MAAM,SAAS,iBAAiB,GAC9B;KACG,CAAC,IAAI,IAAI,SAAS,UAAU,GAAG,IAAI,GAAG,MAAM,MAAM,GAAG,MAAM,MAAM,GAAG,CAAC,SAAS,IAAI,GAC/E,MAAM,GAAG,MAAM,GACf,OAAO;CACZ,GACD,IAAI,GAGN,MAAM,SAAS,iBAAiB,GAC9B;KACG,CAAC,IAAI,MAAM,IAAI,IAAI,CAAC,SAAS,MAAM,MAAM,GACtC,MAAM,CAAC,CAAC,CAAC,SAAS,MAAM,GAAG,IAAI,GAC7B,CAAC,GACD,KAAK,GAEP,CAAC,SAAS,IAAI,GACZ,CAAC,GACD,KAAK,GAAG,IAAI,CAAC,CAAC,CAAC;CACtB,GAED;KACG,CAAC,IAAI,MAAM,IAAI,IAAI,CAAC,SAAS,MAAM,MAAM,GACtC,MAAM,CAAC,CAAC,CAAC,SAAS,MAAM,GAAG,SAAS,GAClC,CAAC,GACD,KAAK,GACP,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;CAChB,CAAA;AAEX,MAAM,MAAM,6BAA6B,CACvC,KAAK,SAAS,cAAc,EAC5B,OAAO,SAAS,UAAU,IACxB,OAAO,SAAS,UAAU,GAC1B,uBAAuB,CAAC,sBAAsB,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC,GAC/D,sBAAsB,CAAC,KAAK,CAAC,CAAA;AAEjC,MAAM,MAAM,yBAAyB,CACnC,KAAK,SAAS,UAAU,EACxB,OAAO,SAAS,UAAU,IACxB,OAAO,SAAS,UAAU,GAC1B,uBAAuB,CAAC,kBAAkB,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC,GAC3D,kBAAkB,CAAC,KAAK,CAAC,CAAA"}
|
package/dist/types/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/types/index.ts"],"sourcesContent":["import type { I18n, TFunction } from '@payloadcms/translations'\nimport type DataLoader from 'dataloader'\nimport type { URL } from 'url'\n\nimport type {\n DataFromCollectionSlug,\n TypeWithID,\n TypeWithTimestamps,\n} from '../collections/config/types.js'\nimport type payload from '../index.js'\nimport type {\n CollectionSlug,\n DataFromGlobalSlug,\n GlobalSlug,\n TypedLocale,\n TypedUser,\n} from '../index.js'\nimport type { validOperators } from './constants.js'\nexport type { Payload as Payload } from '../index.js'\n\nexport type CustomPayloadRequestProperties = {\n context: RequestContext\n /** The locale that should be used for a field when it is not translated to the requested locale */\n fallbackLocale?: string\n i18n: I18n\n /**\n * The requested locale if specified\n * Only available for localized collections\n */\n locale?: TypedLocale\n /**\n * The payload object\n */\n payload: typeof payload\n /**\n * The context in which the request is being made\n */\n payloadAPI: 'GraphQL' | 'local' | 'REST'\n /** Optimized document loader */\n payloadDataLoader?: DataLoader<string, TypeWithID>\n /** Resized versions of the image that was uploaded during this request */\n payloadUploadSizes?: Record<string, Buffer>\n /** Query params on the request */\n query: Record<string, unknown>\n /** Any response headers that are required to be set when a response is sent */\n responseHeaders?: Headers\n /** The route parameters\n * @example\n * /:collection/:id -> /posts/123\n * { collection: 'posts', id: '123' }\n */\n routeParams?: Record<string, unknown>\n /** Translate function - duplicate of i18n.t */\n t: TFunction\n /**\n * Identifier for the database transaction for interactions in a single, all-or-nothing operation.\n * Can also be used to ensure consistency when multiple operations try to create a transaction concurrently on the same request.\n */\n transactionID?: number | Promise<number | string> | string\n /**\n * Used to ensure consistency when multiple operations try to create a transaction concurrently on the same request\n */\n transactionIDPromise?: Promise<void>\n /** The signed-in user */\n user: null | TypedUser\n} & Pick<\n URL,\n 'hash' | 'host' | 'href' | 'origin' | 'pathname' | 'port' | 'protocol' | 'search' | 'searchParams'\n>\ntype PayloadRequestData = {\n /**\n * Data from the request body\n *\n * Within Payload operations, i.e. hooks, data will be there\n * BUT in custom endpoints it will not be, you will need to\n * use either:\n * 1. `const data = await req.json()`\n *\n * 2. import { addDataAndFileToRequest } from '@payloadcms/next/utilities'\n * `await addDataAndFileToRequest(req)`\n * */\n data?: JsonObject\n /** The file on the request, same rules apply as the `data` property */\n file?: {\n data: Buffer\n mimetype: string\n name: string\n size: number\n tempFilePath?: string\n }\n}\nexport type PayloadRequest = CustomPayloadRequestProperties &\n Partial<Request> &\n PayloadRequestData &\n Required<Pick<Request, 'headers'>>\n\nexport interface RequestContext {\n [key: string]: unknown\n}\n\nexport type Operator = (typeof validOperators)[number]\n\n// Makes it so things like passing new Date() will error\nexport type JsonValue = JsonArray | JsonObject | unknown //Date | JsonArray | JsonObject | boolean | null | number | string // TODO: Evaluate proper, strong type for this\n\nexport type JsonArray = Array<JsonValue>\n\nexport interface JsonObject {\n [key: string]: any\n}\n\nexport type WhereField = {\n // any json-serializable value\n [key in Operator]?: JsonValue\n}\n\nexport type Where = {\n [key: string]: Where[] | WhereField\n and?: Where[]\n or?: Where[]\n}\n\nexport type Sort = Array<string> | string\n\n/**\n * Applies pagination for join fields for including collection relationships\n */\nexport type JoinQuery =\n | {\n [schemaPath: string]: {\n limit?: number\n sort?: string\n where?: Where\n }\n }\n | false\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type Document = any\n\nexport type Operation = 'create' | 'delete' | 'read' | 'update'\nexport type VersionOperations = 'readVersions'\nexport type AuthOperations = 'unlock'\nexport type AllOperations = AuthOperations | Operation | VersionOperations\n\nexport function docHasTimestamps(doc: any): doc is TypeWithTimestamps {\n return doc?.createdAt && doc?.updatedAt\n}\n\nexport type IfAny<T, Y, N> = 0 extends 1 & T ? Y : N // This is a commonly used trick to detect 'any'\nexport type IsAny<T> = IfAny<T, true, false>\nexport type ReplaceAny<T, DefaultType> = IsAny<T> extends true ? DefaultType : T\n\nexport type SelectIncludeType = {\n [k: string]: SelectIncludeType | true\n}\n\nexport type SelectExcludeType = {\n [k: string]: false | SelectExcludeType\n}\n\nexport type SelectMode = 'exclude' | 'include'\n\nexport type SelectType = SelectExcludeType | SelectIncludeType\n\nexport type ApplyDisableErrors<T, DisableErrors
|
|
1
|
+
{"version":3,"sources":["../../src/types/index.ts"],"sourcesContent":["import type { I18n, TFunction } from '@payloadcms/translations'\nimport type DataLoader from 'dataloader'\nimport type { URL } from 'url'\n\nimport type {\n DataFromCollectionSlug,\n TypeWithID,\n TypeWithTimestamps,\n} from '../collections/config/types.js'\nimport type payload from '../index.js'\nimport type {\n CollectionSlug,\n DataFromGlobalSlug,\n GlobalSlug,\n TypedLocale,\n TypedUser,\n} from '../index.js'\nimport type { validOperators } from './constants.js'\nexport type { Payload as Payload } from '../index.js'\n\nexport type CustomPayloadRequestProperties = {\n context: RequestContext\n /** The locale that should be used for a field when it is not translated to the requested locale */\n fallbackLocale?: string\n i18n: I18n\n /**\n * The requested locale if specified\n * Only available for localized collections\n */\n locale?: TypedLocale\n /**\n * The payload object\n */\n payload: typeof payload\n /**\n * The context in which the request is being made\n */\n payloadAPI: 'GraphQL' | 'local' | 'REST'\n /** Optimized document loader */\n payloadDataLoader?: DataLoader<string, TypeWithID>\n /** Resized versions of the image that was uploaded during this request */\n payloadUploadSizes?: Record<string, Buffer>\n /** Query params on the request */\n query: Record<string, unknown>\n /** Any response headers that are required to be set when a response is sent */\n responseHeaders?: Headers\n /** The route parameters\n * @example\n * /:collection/:id -> /posts/123\n * { collection: 'posts', id: '123' }\n */\n routeParams?: Record<string, unknown>\n /** Translate function - duplicate of i18n.t */\n t: TFunction\n /**\n * Identifier for the database transaction for interactions in a single, all-or-nothing operation.\n * Can also be used to ensure consistency when multiple operations try to create a transaction concurrently on the same request.\n */\n transactionID?: number | Promise<number | string> | string\n /**\n * Used to ensure consistency when multiple operations try to create a transaction concurrently on the same request\n */\n transactionIDPromise?: Promise<void>\n /** The signed-in user */\n user: null | TypedUser\n} & Pick<\n URL,\n 'hash' | 'host' | 'href' | 'origin' | 'pathname' | 'port' | 'protocol' | 'search' | 'searchParams'\n>\ntype PayloadRequestData = {\n /**\n * Data from the request body\n *\n * Within Payload operations, i.e. hooks, data will be there\n * BUT in custom endpoints it will not be, you will need to\n * use either:\n * 1. `const data = await req.json()`\n *\n * 2. import { addDataAndFileToRequest } from '@payloadcms/next/utilities'\n * `await addDataAndFileToRequest(req)`\n * */\n data?: JsonObject\n /** The file on the request, same rules apply as the `data` property */\n file?: {\n data: Buffer\n mimetype: string\n name: string\n size: number\n tempFilePath?: string\n }\n}\nexport type PayloadRequest = CustomPayloadRequestProperties &\n Partial<Request> &\n PayloadRequestData &\n Required<Pick<Request, 'headers'>>\n\nexport interface RequestContext {\n [key: string]: unknown\n}\n\nexport type Operator = (typeof validOperators)[number]\n\n// Makes it so things like passing new Date() will error\nexport type JsonValue = JsonArray | JsonObject | unknown //Date | JsonArray | JsonObject | boolean | null | number | string // TODO: Evaluate proper, strong type for this\n\nexport type JsonArray = Array<JsonValue>\n\nexport interface JsonObject {\n [key: string]: any\n}\n\nexport type WhereField = {\n // any json-serializable value\n [key in Operator]?: JsonValue\n}\n\nexport type Where = {\n [key: string]: Where[] | WhereField\n and?: Where[]\n or?: Where[]\n}\n\nexport type Sort = Array<string> | string\n\n/**\n * Applies pagination for join fields for including collection relationships\n */\nexport type JoinQuery =\n | {\n [schemaPath: string]: {\n limit?: number\n sort?: string\n where?: Where\n }\n }\n | false\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type Document = any\n\nexport type Operation = 'create' | 'delete' | 'read' | 'update'\nexport type VersionOperations = 'readVersions'\nexport type AuthOperations = 'unlock'\nexport type AllOperations = AuthOperations | Operation | VersionOperations\n\nexport function docHasTimestamps(doc: any): doc is TypeWithTimestamps {\n return doc?.createdAt && doc?.updatedAt\n}\n\nexport type IfAny<T, Y, N> = 0 extends 1 & T ? Y : N // This is a commonly used trick to detect 'any'\nexport type IsAny<T> = IfAny<T, true, false>\nexport type ReplaceAny<T, DefaultType> = IsAny<T> extends true ? DefaultType : T\n\nexport type SelectIncludeType = {\n [k: string]: SelectIncludeType | true\n}\n\nexport type SelectExcludeType = {\n [k: string]: false | SelectExcludeType\n}\n\nexport type SelectMode = 'exclude' | 'include'\n\nexport type SelectType = SelectExcludeType | SelectIncludeType\n\nexport type ApplyDisableErrors<T, DisableErrors = false> = false extends DisableErrors\n ? T\n : null | T\n\nexport type TransformDataWithSelect<\n Data extends Record<string, any>,\n Select extends SelectType,\n> = Select extends never\n ? Data\n : string extends keyof Select\n ? Data\n : // START Handle types when they aren't generated\n // For example in any package in this repository outside of tests / plugins\n // This stil gives us autocomplete when using include select mode, i.e select: {title :true} returns type {title: any, id: string | number}\n string extends keyof Omit<Data, 'id'>\n ? Select extends SelectIncludeType\n ? {\n [K in Data extends TypeWithID ? 'id' | keyof Select : keyof Select]: K extends 'id'\n ? number | string\n : unknown\n }\n : Data\n : // END Handle types when they aren't generated\n // Handle include mode\n Select extends SelectIncludeType\n ? {\n [K in keyof Data as K extends keyof Select\n ? Select[K] extends object | true\n ? K\n : never\n : // select 'id' always\n K extends 'id'\n ? K\n : never]: Data[K]\n }\n : // Handle exclude mode\n {\n [K in keyof Data as K extends keyof Select\n ? Select[K] extends object | undefined\n ? K\n : never\n : K]: Data[K]\n }\n\nexport type TransformCollectionWithSelect<\n TSlug extends CollectionSlug,\n TSelect extends SelectType,\n> = TSelect extends SelectType\n ? TransformDataWithSelect<DataFromCollectionSlug<TSlug>, TSelect>\n : DataFromCollectionSlug<TSlug>\n\nexport type TransformGlobalWithSelect<\n TSlug extends GlobalSlug,\n TSelect extends SelectType,\n> = TSelect extends SelectType\n ? TransformDataWithSelect<DataFromGlobalSlug<TSlug>, TSelect>\n : DataFromGlobalSlug<TSlug>\n"],"names":["docHasTimestamps","doc","createdAt","updatedAt"],"mappings":"AAiJA,OAAO,SAASA,iBAAiBC,GAAQ;IACvC,OAAOA,KAAKC,aAAaD,KAAKE;AAChC"}
|
|
@@ -21,7 +21,7 @@ export interface Config {
|
|
|
21
21
|
'payload-preferences': PayloadPreference;
|
|
22
22
|
'payload-migrations': PayloadMigration;
|
|
23
23
|
};
|
|
24
|
-
collectionsSelect
|
|
24
|
+
collectionsSelect: {
|
|
25
25
|
posts: PostsSelect;
|
|
26
26
|
users: UsersSelect;
|
|
27
27
|
'payload-locked-documents': PayloadLockedDocumentsSelect;
|
|
@@ -32,7 +32,7 @@ export interface Config {
|
|
|
32
32
|
defaultIDType: string;
|
|
33
33
|
};
|
|
34
34
|
globals: {};
|
|
35
|
-
globalsSelect
|
|
35
|
+
globalsSelect: {};
|
|
36
36
|
locale: null;
|
|
37
37
|
user: User & {
|
|
38
38
|
collection: 'users';
|
|
@@ -294,7 +294,7 @@ export interface Config {
|
|
|
294
294
|
'payload-preferences': PayloadPreference;
|
|
295
295
|
'payload-migrations': PayloadMigration;
|
|
296
296
|
};
|
|
297
|
-
collectionsSelect
|
|
297
|
+
collectionsSelect: {
|
|
298
298
|
posts: PostsSelect<false> | PostsSelect<true>;
|
|
299
299
|
users: UsersSelect<false> | UsersSelect<true>;
|
|
300
300
|
'payload-locked-documents': PayloadLockedDocumentsSelect<false> | PayloadLockedDocumentsSelect<true>;
|
|
@@ -305,7 +305,7 @@ export interface Config {
|
|
|
305
305
|
defaultIDType: string;
|
|
306
306
|
};
|
|
307
307
|
globals: {};
|
|
308
|
-
globalsSelect
|
|
308
|
+
globalsSelect: {};
|
|
309
309
|
locale: null;
|
|
310
310
|
user: User & {
|
|
311
311
|
collection: 'users';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utilities/addSelectGenericsToGeneratedTyoes.spec.ts"],"sourcesContent":["import { addSelectGenericsToGeneratedTypes } from './addSelectGenericsToGeneretedTypes.js'\n\nconst INPUT_AND_OUTPUT = [\n {\n input: `\n/* tslint:disable */\n/* eslint-disable */\n/**\n * This file was automatically generated by Payload.\n * DO NOT MODIFY IT BY HAND. Instead, modify your source Payload config,\n * and re-run \\`payload generate:types\\` to regenerate this file.\n */\n\nexport interface Config {\n auth: {\n users: UserAuthOperations;\n };\n collections: {\n posts: Post;\n users: User;\n 'payload-locked-documents': PayloadLockedDocument;\n 'payload-preferences': PayloadPreference;\n 'payload-migrations': PayloadMigration;\n };\n collectionsSelect?: {\n posts: PostsSelect;\n users: UsersSelect;\n 'payload-locked-documents': PayloadLockedDocumentsSelect;\n 'payload-preferences': PayloadPreferencesSelect;\n 'payload-migrations': PayloadMigrationsSelect;\n };\n db: {\n defaultIDType: string;\n };\n globals: {};\n globalsSelect?: {};\n locale: null;\n user: User & {\n collection: 'users';\n };\n}\nexport interface UserAuthOperations {\n forgotPassword: {\n email: string;\n password: string;\n };\n login: {\n email: string;\n password: string;\n };\n registerFirstUser: {\n email: string;\n password: string;\n };\n unlock: {\n email: string;\n password: string;\n };\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"posts\".\n */\nexport interface Post {\n id: string;\n text?: string | null;\n number?: number | null;\n group?: {\n text?: string | null;\n number?: number | null;\n };\n array?:\n | {\n text?: string | null;\n number?: number | null;\n id?: string | null;\n }[]\n | null;\n blocks?:\n | (\n | {\n text?: string | null;\n introText?: string | null;\n id?: string | null;\n blockName?: string | null;\n blockType: 'intro';\n }\n | {\n text?: string | null;\n ctaText?: string | null;\n id?: string | null;\n blockName?: string | null;\n blockType: 'cta';\n }\n )[]\n | null;\n updatedAt: string;\n createdAt: string;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"users\".\n */\nexport interface User {\n id: string;\n updatedAt: string;\n createdAt: string;\n email: string;\n resetPasswordToken?: string | null;\n resetPasswordExpiration?: string | null;\n salt?: string | null;\n hash?: string | null;\n loginAttempts?: number | null;\n lockUntil?: string | null;\n password?: string | null;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"payload-locked-documents\".\n */\nexport interface PayloadLockedDocument {\n id: string;\n document?:\n | ({\n relationTo: 'posts';\n value: string | Post;\n } | null)\n | ({\n relationTo: 'users';\n value: string | User;\n } | null);\n globalSlug?: string | null;\n user: {\n relationTo: 'users';\n value: string | User;\n };\n updatedAt: string;\n createdAt: string;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"payload-preferences\".\n */\nexport interface PayloadPreference {\n id: string;\n user: {\n relationTo: 'users';\n value: string | User;\n };\n key?: string | null;\n value?:\n | {\n [k: string]: unknown;\n }\n | unknown[]\n | string\n | number\n | boolean\n | null;\n updatedAt: string;\n createdAt: string;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"payload-migrations\".\n */\nexport interface PayloadMigration {\n id: string;\n name?: string | null;\n batch?: number | null;\n updatedAt: string;\n createdAt: string;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"posts_select\".\n */\nexport interface PostsSelect {\n text?: boolean;\n number?: boolean;\n group?:\n | boolean\n | {\n text?: boolean;\n number?: boolean;\n };\n array?:\n | boolean\n | {\n text?: boolean;\n number?: boolean;\n id?: boolean;\n };\n blocks?:\n | boolean\n | {\n intro?:\n | boolean\n | {\n text?: boolean;\n introText?: boolean;\n id?: boolean;\n blockName?: boolean;\n };\n cta?:\n | boolean\n | {\n text?: boolean;\n ctaText?: boolean;\n id?: boolean;\n blockName?: boolean;\n };\n };\n updatedAt?: boolean;\n createdAt?: boolean;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"users_select\".\n */\nexport interface UsersSelect {\n updatedAt?: boolean;\n createdAt?: boolean;\n email?: boolean;\n resetPasswordToken?: boolean;\n resetPasswordExpiration?: boolean;\n salt?: boolean;\n hash?: boolean;\n loginAttempts?: boolean;\n lockUntil?: boolean;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"payload-locked-documents_select\".\n */\nexport interface PayloadLockedDocumentsSelect {\n document?: boolean;\n globalSlug?: boolean;\n user?: boolean;\n updatedAt?: boolean;\n createdAt?: boolean;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"payload-preferences_select\".\n */\nexport interface PayloadPreferencesSelect {\n user?: boolean;\n key?: boolean;\n value?: boolean;\n updatedAt?: boolean;\n createdAt?: boolean;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"payload-migrations_select\".\n */\nexport interface PayloadMigrationsSelect {\n name?: boolean;\n batch?: boolean;\n updatedAt?: boolean;\n createdAt?: boolean;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"auth\".\n */\nexport interface Auth {\n [k: string]: unknown;\n}\n\n\ndeclare module 'payload' {\n // @ts-ignore \n export interface GeneratedTypes extends Config {}\n}\n`,\n output: `\n/* tslint:disable */\n/* eslint-disable */\n/**\n * This file was automatically generated by Payload.\n * DO NOT MODIFY IT BY HAND. Instead, modify your source Payload config,\n * and re-run \\`payload generate:types\\` to regenerate this file.\n */\n\nexport interface Config {\n auth: {\n users: UserAuthOperations;\n };\n collections: {\n posts: Post;\n users: User;\n 'payload-locked-documents': PayloadLockedDocument;\n 'payload-preferences': PayloadPreference;\n 'payload-migrations': PayloadMigration;\n };\n collectionsSelect?: {\n posts: PostsSelect<false> | PostsSelect<true>;\n users: UsersSelect<false> | UsersSelect<true>;\n 'payload-locked-documents': PayloadLockedDocumentsSelect<false> | PayloadLockedDocumentsSelect<true>;\n 'payload-preferences': PayloadPreferencesSelect<false> | PayloadPreferencesSelect<true>;\n 'payload-migrations': PayloadMigrationsSelect<false> | PayloadMigrationsSelect<true>;\n };\n db: {\n defaultIDType: string;\n };\n globals: {};\n globalsSelect?: {};\n locale: null;\n user: User & {\n collection: 'users';\n };\n}\nexport interface UserAuthOperations {\n forgotPassword: {\n email: string;\n password: string;\n };\n login: {\n email: string;\n password: string;\n };\n registerFirstUser: {\n email: string;\n password: string;\n };\n unlock: {\n email: string;\n password: string;\n };\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"posts\".\n */\nexport interface Post {\n id: string;\n text?: string | null;\n number?: number | null;\n group?: {\n text?: string | null;\n number?: number | null;\n };\n array?:\n | {\n text?: string | null;\n number?: number | null;\n id?: string | null;\n }[]\n | null;\n blocks?:\n | (\n | {\n text?: string | null;\n introText?: string | null;\n id?: string | null;\n blockName?: string | null;\n blockType: 'intro';\n }\n | {\n text?: string | null;\n ctaText?: string | null;\n id?: string | null;\n blockName?: string | null;\n blockType: 'cta';\n }\n )[]\n | null;\n updatedAt: string;\n createdAt: string;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"users\".\n */\nexport interface User {\n id: string;\n updatedAt: string;\n createdAt: string;\n email: string;\n resetPasswordToken?: string | null;\n resetPasswordExpiration?: string | null;\n salt?: string | null;\n hash?: string | null;\n loginAttempts?: number | null;\n lockUntil?: string | null;\n password?: string | null;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"payload-locked-documents\".\n */\nexport interface PayloadLockedDocument {\n id: string;\n document?:\n | ({\n relationTo: 'posts';\n value: string | Post;\n } | null)\n | ({\n relationTo: 'users';\n value: string | User;\n } | null);\n globalSlug?: string | null;\n user: {\n relationTo: 'users';\n value: string | User;\n };\n updatedAt: string;\n createdAt: string;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"payload-preferences\".\n */\nexport interface PayloadPreference {\n id: string;\n user: {\n relationTo: 'users';\n value: string | User;\n };\n key?: string | null;\n value?:\n | {\n [k: string]: unknown;\n }\n | unknown[]\n | string\n | number\n | boolean\n | null;\n updatedAt: string;\n createdAt: string;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"payload-migrations\".\n */\nexport interface PayloadMigration {\n id: string;\n name?: string | null;\n batch?: number | null;\n updatedAt: string;\n createdAt: string;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"posts_select\".\n */\nexport interface PostsSelect<T extends boolean = true> {\n text?: T;\n number?: T;\n group?:\n | T\n | {\n text?: T;\n number?: T;\n };\n array?:\n | T\n | {\n text?: T;\n number?: T;\n id?: T;\n };\n blocks?:\n | T\n | {\n intro?:\n | T\n | {\n text?: T;\n introText?: T;\n id?: T;\n blockName?: T;\n };\n cta?:\n | T\n | {\n text?: T;\n ctaText?: T;\n id?: T;\n blockName?: T;\n };\n };\n updatedAt?: T;\n createdAt?: T;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"users_select\".\n */\nexport interface UsersSelect<T extends boolean = true> {\n updatedAt?: T;\n createdAt?: T;\n email?: T;\n resetPasswordToken?: T;\n resetPasswordExpiration?: T;\n salt?: T;\n hash?: T;\n loginAttempts?: T;\n lockUntil?: T;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"payload-locked-documents_select\".\n */\nexport interface PayloadLockedDocumentsSelect<T extends boolean = true> {\n document?: T;\n globalSlug?: T;\n user?: T;\n updatedAt?: T;\n createdAt?: T;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"payload-preferences_select\".\n */\nexport interface PayloadPreferencesSelect<T extends boolean = true> {\n user?: T;\n key?: T;\n value?: T;\n updatedAt?: T;\n createdAt?: T;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"payload-migrations_select\".\n */\nexport interface PayloadMigrationsSelect<T extends boolean = true> {\n name?: T;\n batch?: T;\n updatedAt?: T;\n createdAt?: T;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"auth\".\n */\nexport interface Auth {\n [k: string]: unknown;\n}\n\n\ndeclare module 'payload' {\n // @ts-ignore \n export interface GeneratedTypes extends Config {}\n}\n`,\n },\n]\n\ndescribe('addSelectGenericsToGeneratedTypes', () => {\n it('should match return of given input with output', () => {\n for (const { input, output } of INPUT_AND_OUTPUT) {\n expect(\n addSelectGenericsToGeneratedTypes({\n compiledGeneratedTypes: input,\n }),\n ).toStrictEqual(output)\n }\n })\n})\n"],"names":["addSelectGenericsToGeneratedTypes","INPUT_AND_OUTPUT","input","output","describe","it","expect","compiledGeneratedTypes","toStrictEqual"],"mappings":"AAAA,SAASA,iCAAiC,QAAQ,yCAAwC;AAE1F,MAAMC,mBAAmB;IACvB;QACEC,OAAO,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgRZ,CAAC;QACGC,QAAQ,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgRb,CAAC;IACC;CACD;AAEDC,SAAS,qCAAqC;IAC5CC,GAAG,kDAAkD;QACnD,KAAK,MAAM,EAAEH,KAAK,EAAEC,MAAM,EAAE,IAAIF,iBAAkB;YAChDK,OACEN,kCAAkC;gBAChCO,wBAAwBL;YAC1B,IACAM,aAAa,CAACL;QAClB;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/addSelectGenericsToGeneratedTyoes.spec.ts"],"sourcesContent":["import { addSelectGenericsToGeneratedTypes } from './addSelectGenericsToGeneretedTypes.js'\n\nconst INPUT_AND_OUTPUT = [\n {\n input: `\n/* tslint:disable */\n/* eslint-disable */\n/**\n * This file was automatically generated by Payload.\n * DO NOT MODIFY IT BY HAND. Instead, modify your source Payload config,\n * and re-run \\`payload generate:types\\` to regenerate this file.\n */\n\nexport interface Config {\n auth: {\n users: UserAuthOperations;\n };\n collections: {\n posts: Post;\n users: User;\n 'payload-locked-documents': PayloadLockedDocument;\n 'payload-preferences': PayloadPreference;\n 'payload-migrations': PayloadMigration;\n };\n collectionsSelect: {\n posts: PostsSelect;\n users: UsersSelect;\n 'payload-locked-documents': PayloadLockedDocumentsSelect;\n 'payload-preferences': PayloadPreferencesSelect;\n 'payload-migrations': PayloadMigrationsSelect;\n };\n db: {\n defaultIDType: string;\n };\n globals: {};\n globalsSelect: {};\n locale: null;\n user: User & {\n collection: 'users';\n };\n}\nexport interface UserAuthOperations {\n forgotPassword: {\n email: string;\n password: string;\n };\n login: {\n email: string;\n password: string;\n };\n registerFirstUser: {\n email: string;\n password: string;\n };\n unlock: {\n email: string;\n password: string;\n };\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"posts\".\n */\nexport interface Post {\n id: string;\n text?: string | null;\n number?: number | null;\n group?: {\n text?: string | null;\n number?: number | null;\n };\n array?:\n | {\n text?: string | null;\n number?: number | null;\n id?: string | null;\n }[]\n | null;\n blocks?:\n | (\n | {\n text?: string | null;\n introText?: string | null;\n id?: string | null;\n blockName?: string | null;\n blockType: 'intro';\n }\n | {\n text?: string | null;\n ctaText?: string | null;\n id?: string | null;\n blockName?: string | null;\n blockType: 'cta';\n }\n )[]\n | null;\n updatedAt: string;\n createdAt: string;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"users\".\n */\nexport interface User {\n id: string;\n updatedAt: string;\n createdAt: string;\n email: string;\n resetPasswordToken?: string | null;\n resetPasswordExpiration?: string | null;\n salt?: string | null;\n hash?: string | null;\n loginAttempts?: number | null;\n lockUntil?: string | null;\n password?: string | null;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"payload-locked-documents\".\n */\nexport interface PayloadLockedDocument {\n id: string;\n document?:\n | ({\n relationTo: 'posts';\n value: string | Post;\n } | null)\n | ({\n relationTo: 'users';\n value: string | User;\n } | null);\n globalSlug?: string | null;\n user: {\n relationTo: 'users';\n value: string | User;\n };\n updatedAt: string;\n createdAt: string;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"payload-preferences\".\n */\nexport interface PayloadPreference {\n id: string;\n user: {\n relationTo: 'users';\n value: string | User;\n };\n key?: string | null;\n value?:\n | {\n [k: string]: unknown;\n }\n | unknown[]\n | string\n | number\n | boolean\n | null;\n updatedAt: string;\n createdAt: string;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"payload-migrations\".\n */\nexport interface PayloadMigration {\n id: string;\n name?: string | null;\n batch?: number | null;\n updatedAt: string;\n createdAt: string;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"posts_select\".\n */\nexport interface PostsSelect {\n text?: boolean;\n number?: boolean;\n group?:\n | boolean\n | {\n text?: boolean;\n number?: boolean;\n };\n array?:\n | boolean\n | {\n text?: boolean;\n number?: boolean;\n id?: boolean;\n };\n blocks?:\n | boolean\n | {\n intro?:\n | boolean\n | {\n text?: boolean;\n introText?: boolean;\n id?: boolean;\n blockName?: boolean;\n };\n cta?:\n | boolean\n | {\n text?: boolean;\n ctaText?: boolean;\n id?: boolean;\n blockName?: boolean;\n };\n };\n updatedAt?: boolean;\n createdAt?: boolean;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"users_select\".\n */\nexport interface UsersSelect {\n updatedAt?: boolean;\n createdAt?: boolean;\n email?: boolean;\n resetPasswordToken?: boolean;\n resetPasswordExpiration?: boolean;\n salt?: boolean;\n hash?: boolean;\n loginAttempts?: boolean;\n lockUntil?: boolean;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"payload-locked-documents_select\".\n */\nexport interface PayloadLockedDocumentsSelect {\n document?: boolean;\n globalSlug?: boolean;\n user?: boolean;\n updatedAt?: boolean;\n createdAt?: boolean;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"payload-preferences_select\".\n */\nexport interface PayloadPreferencesSelect {\n user?: boolean;\n key?: boolean;\n value?: boolean;\n updatedAt?: boolean;\n createdAt?: boolean;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"payload-migrations_select\".\n */\nexport interface PayloadMigrationsSelect {\n name?: boolean;\n batch?: boolean;\n updatedAt?: boolean;\n createdAt?: boolean;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"auth\".\n */\nexport interface Auth {\n [k: string]: unknown;\n}\n\n\ndeclare module 'payload' {\n // @ts-ignore \n export interface GeneratedTypes extends Config {}\n}\n`,\n output: `\n/* tslint:disable */\n/* eslint-disable */\n/**\n * This file was automatically generated by Payload.\n * DO NOT MODIFY IT BY HAND. Instead, modify your source Payload config,\n * and re-run \\`payload generate:types\\` to regenerate this file.\n */\n\nexport interface Config {\n auth: {\n users: UserAuthOperations;\n };\n collections: {\n posts: Post;\n users: User;\n 'payload-locked-documents': PayloadLockedDocument;\n 'payload-preferences': PayloadPreference;\n 'payload-migrations': PayloadMigration;\n };\n collectionsSelect: {\n posts: PostsSelect<false> | PostsSelect<true>;\n users: UsersSelect<false> | UsersSelect<true>;\n 'payload-locked-documents': PayloadLockedDocumentsSelect<false> | PayloadLockedDocumentsSelect<true>;\n 'payload-preferences': PayloadPreferencesSelect<false> | PayloadPreferencesSelect<true>;\n 'payload-migrations': PayloadMigrationsSelect<false> | PayloadMigrationsSelect<true>;\n };\n db: {\n defaultIDType: string;\n };\n globals: {};\n globalsSelect: {};\n locale: null;\n user: User & {\n collection: 'users';\n };\n}\nexport interface UserAuthOperations {\n forgotPassword: {\n email: string;\n password: string;\n };\n login: {\n email: string;\n password: string;\n };\n registerFirstUser: {\n email: string;\n password: string;\n };\n unlock: {\n email: string;\n password: string;\n };\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"posts\".\n */\nexport interface Post {\n id: string;\n text?: string | null;\n number?: number | null;\n group?: {\n text?: string | null;\n number?: number | null;\n };\n array?:\n | {\n text?: string | null;\n number?: number | null;\n id?: string | null;\n }[]\n | null;\n blocks?:\n | (\n | {\n text?: string | null;\n introText?: string | null;\n id?: string | null;\n blockName?: string | null;\n blockType: 'intro';\n }\n | {\n text?: string | null;\n ctaText?: string | null;\n id?: string | null;\n blockName?: string | null;\n blockType: 'cta';\n }\n )[]\n | null;\n updatedAt: string;\n createdAt: string;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"users\".\n */\nexport interface User {\n id: string;\n updatedAt: string;\n createdAt: string;\n email: string;\n resetPasswordToken?: string | null;\n resetPasswordExpiration?: string | null;\n salt?: string | null;\n hash?: string | null;\n loginAttempts?: number | null;\n lockUntil?: string | null;\n password?: string | null;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"payload-locked-documents\".\n */\nexport interface PayloadLockedDocument {\n id: string;\n document?:\n | ({\n relationTo: 'posts';\n value: string | Post;\n } | null)\n | ({\n relationTo: 'users';\n value: string | User;\n } | null);\n globalSlug?: string | null;\n user: {\n relationTo: 'users';\n value: string | User;\n };\n updatedAt: string;\n createdAt: string;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"payload-preferences\".\n */\nexport interface PayloadPreference {\n id: string;\n user: {\n relationTo: 'users';\n value: string | User;\n };\n key?: string | null;\n value?:\n | {\n [k: string]: unknown;\n }\n | unknown[]\n | string\n | number\n | boolean\n | null;\n updatedAt: string;\n createdAt: string;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"payload-migrations\".\n */\nexport interface PayloadMigration {\n id: string;\n name?: string | null;\n batch?: number | null;\n updatedAt: string;\n createdAt: string;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"posts_select\".\n */\nexport interface PostsSelect<T extends boolean = true> {\n text?: T;\n number?: T;\n group?:\n | T\n | {\n text?: T;\n number?: T;\n };\n array?:\n | T\n | {\n text?: T;\n number?: T;\n id?: T;\n };\n blocks?:\n | T\n | {\n intro?:\n | T\n | {\n text?: T;\n introText?: T;\n id?: T;\n blockName?: T;\n };\n cta?:\n | T\n | {\n text?: T;\n ctaText?: T;\n id?: T;\n blockName?: T;\n };\n };\n updatedAt?: T;\n createdAt?: T;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"users_select\".\n */\nexport interface UsersSelect<T extends boolean = true> {\n updatedAt?: T;\n createdAt?: T;\n email?: T;\n resetPasswordToken?: T;\n resetPasswordExpiration?: T;\n salt?: T;\n hash?: T;\n loginAttempts?: T;\n lockUntil?: T;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"payload-locked-documents_select\".\n */\nexport interface PayloadLockedDocumentsSelect<T extends boolean = true> {\n document?: T;\n globalSlug?: T;\n user?: T;\n updatedAt?: T;\n createdAt?: T;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"payload-preferences_select\".\n */\nexport interface PayloadPreferencesSelect<T extends boolean = true> {\n user?: T;\n key?: T;\n value?: T;\n updatedAt?: T;\n createdAt?: T;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"payload-migrations_select\".\n */\nexport interface PayloadMigrationsSelect<T extends boolean = true> {\n name?: T;\n batch?: T;\n updatedAt?: T;\n createdAt?: T;\n}\n/**\n * This interface was referenced by \\`Config\\`'s JSON-Schema\n * via the \\`definition\\` \"auth\".\n */\nexport interface Auth {\n [k: string]: unknown;\n}\n\n\ndeclare module 'payload' {\n // @ts-ignore \n export interface GeneratedTypes extends Config {}\n}\n`,\n },\n]\n\ndescribe('addSelectGenericsToGeneratedTypes', () => {\n it('should match return of given input with output', () => {\n for (const { input, output } of INPUT_AND_OUTPUT) {\n expect(\n addSelectGenericsToGeneratedTypes({\n compiledGeneratedTypes: input,\n }),\n ).toStrictEqual(output)\n }\n })\n})\n"],"names":["addSelectGenericsToGeneratedTypes","INPUT_AND_OUTPUT","input","output","describe","it","expect","compiledGeneratedTypes","toStrictEqual"],"mappings":"AAAA,SAASA,iCAAiC,QAAQ,yCAAwC;AAE1F,MAAMC,mBAAmB;IACvB;QACEC,OAAO,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgRZ,CAAC;QACGC,QAAQ,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgRb,CAAC;IACC;CACD;AAEDC,SAAS,qCAAqC;IAC5CC,GAAG,kDAAkD;QACnD,KAAK,MAAM,EAAEH,KAAK,EAAEC,MAAM,EAAE,IAAIF,iBAAkB;YAChDK,OACEN,kCAAkC;gBAChCO,wBAAwBL;YAC1B,IACAM,aAAa,CAACL;QAClB;IACF;AACF"}
|
|
@@ -4,7 +4,7 @@ export const addSelectGenericsToGeneratedTypes = ({ compiledGeneratedTypes })=>{
|
|
|
4
4
|
let isSelectTypeToken = false;
|
|
5
5
|
for (const line of compiledGeneratedTypes.split('\n')){
|
|
6
6
|
let newLine = line;
|
|
7
|
-
if (line === ` collectionsSelect
|
|
7
|
+
if (line === ` collectionsSelect: {` || line === ` globalsSelect: {`) {
|
|
8
8
|
isCollectionsSelectToken = true;
|
|
9
9
|
}
|
|
10
10
|
if (isCollectionsSelectToken) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utilities/addSelectGenericsToGeneretedTypes.ts"],"sourcesContent":["export const addSelectGenericsToGeneratedTypes = ({\n compiledGeneratedTypes,\n}: {\n compiledGeneratedTypes: string\n}) => {\n const modifiedLines = []\n\n let isCollectionsSelectToken = false\n let isSelectTypeToken = false\n\n for (const line of compiledGeneratedTypes.split('\\n')) {\n let newLine = line\n if (line === ` collectionsSelect
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/addSelectGenericsToGeneretedTypes.ts"],"sourcesContent":["export const addSelectGenericsToGeneratedTypes = ({\n compiledGeneratedTypes,\n}: {\n compiledGeneratedTypes: string\n}) => {\n const modifiedLines = []\n\n let isCollectionsSelectToken = false\n let isSelectTypeToken = false\n\n for (const line of compiledGeneratedTypes.split('\\n')) {\n let newLine = line\n if (line === ` collectionsSelect: {` || line === ` globalsSelect: {`) {\n isCollectionsSelectToken = true\n }\n\n if (isCollectionsSelectToken) {\n if (line === ' };') {\n isCollectionsSelectToken = false\n } else {\n // replace <posts: PostsSelect;> with <posts: PostsSelect<true> | PostsSelect<false;>\n newLine = line.replace(/(['\"]?\\w+['\"]?):\\s*(\\w+);/g, (_, variable, type) => {\n return `${variable}: ${type}<false> | ${type}<true>;`\n })\n }\n }\n\n // eslint-disable-next-line regexp/no-unused-capturing-group\n if (line.match(/via the `definition` \"([\\w-]+_select)\"/g)) {\n isSelectTypeToken = true\n }\n\n if (isSelectTypeToken) {\n if (line.startsWith('export interface')) {\n // add generic to the interface\n newLine = line.replace(/(export interface\\s+\\w+)(\\s*\\{)/g, '$1<T extends boolean = true>$2')\n } else {\n // replace booleans with T on the line\n newLine = line.replace(/(?<!\\?)\\bboolean\\b/g, 'T')\n\n if (line === '}') {\n isSelectTypeToken = false\n }\n }\n }\n\n modifiedLines.push(newLine)\n }\n\n return modifiedLines.join('\\n')\n}\n"],"names":["addSelectGenericsToGeneratedTypes","compiledGeneratedTypes","modifiedLines","isCollectionsSelectToken","isSelectTypeToken","line","split","newLine","replace","_","variable","type","match","startsWith","push","join"],"mappings":"AAAA,OAAO,MAAMA,oCAAoC,CAAC,EAChDC,sBAAsB,EAGvB;IACC,MAAMC,gBAAgB,EAAE;IAExB,IAAIC,2BAA2B;IAC/B,IAAIC,oBAAoB;IAExB,KAAK,MAAMC,QAAQJ,uBAAuBK,KAAK,CAAC,MAAO;QACrD,IAAIC,UAAUF;QACd,IAAIA,SAAS,CAAC,sBAAsB,CAAC,IAAIA,SAAS,CAAC,kBAAkB,CAAC,EAAE;YACtEF,2BAA2B;QAC7B;QAEA,IAAIA,0BAA0B;YAC5B,IAAIE,SAAS,QAAQ;gBACnBF,2BAA2B;YAC7B,OAAO;gBACL,qFAAqF;gBACrFI,UAAUF,KAAKG,OAAO,CAAC,8BAA8B,CAACC,GAAGC,UAAUC;oBACjE,OAAO,CAAC,EAAED,SAAS,EAAE,EAAEC,KAAK,UAAU,EAAEA,KAAK,OAAO,CAAC;gBACvD;YACF;QACF;QAEA,4DAA4D;QA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AAED,wBAAgB,kBAAkB;AAChC;;;;GAIG;AACH,sBAAsB,EAAE;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,QAAQ,GAAG,QAAQ,CAAA;CAAE,EAC9D,MAAM,EAAE,KAAK,EAAE;AACf;;GAEG;AACH,wBAAwB,EAAE,GAAG,CAAC,MAAM,EAAE,WAAW,CAAC,EAClD,MAAM,CAAC,EAAE,eAAe,GACvB;IACD,UAAU,EAAE;QACV,CAAC,CAAC,EAAE,MAAM,GAAG,WAAW,CAAA;KACzB,CAAA;IACD,QAAQ,EAAE,MAAM,EAAE,CAAA;CACnB,CA6ZA;AAGD,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,eAAe,EACvB,cAAc,EAAE,yBAAyB,GAAG,qBAAqB,EACjE,wBAAwB,EAAE,GAAG,CAAC,MAAM,EAAE,WAAW,CAAC,EAClD,aAAa,EAAE,QAAQ,GAAG,MAAM,EAChC,sBAAsB,CAAC,EAAE;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,QAAQ,GAAG,QAAQ,CAAA;CAAE,GAC9D,WAAW,CA8Cb;AAED,wBAAgB,wBAAwB,CAAC,EAAE,MAAM,EAAE,EAAE;IAAE,MAAM,EAAE,KAAK,EAAE,CAAA;CAAE,GAAG,WAAW,CA0FrF;AAgHD,wBAAgB,oCAAoC,CAClD,MAAM,EAAE,yBAAyB,GAChC,WAAW,CA0Bb;AAoBD;;GAEG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,eAAe,EACvB,aAAa,CAAC,EAAE,QAAQ,GAAG,MAAM,GAChC,WAAW,CAmHb"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utilities/configToJSONSchema.ts"],"sourcesContent":["import type { JSONSchema4, JSONSchema4TypeName } from 'json-schema'\n\nimport pluralize from 'pluralize'\nconst { singular } = pluralize\n\nimport type { Auth } from '../auth/types.js'\nimport type { SanitizedCollectionConfig } from '../collections/config/types.js'\nimport type { SanitizedConfig } from '../config/types.js'\nimport type { Field, FieldAffectingData, Option } from '../fields/config/types.js'\nimport type { SanitizedGlobalConfig } from '../globals/config/types.js'\n\nimport { MissingEditorProp } from '../errors/MissingEditorProp.js'\nimport { fieldAffectsData, tabHasName } from '../fields/config/types.js'\nimport { generateJobsJSONSchemas } from '../queues/config/generateJobsJSONSchemas.js'\nimport { deepCopyObject } from './deepCopyObject.js'\nimport { toWords } from './formatLabels.js'\nimport { getCollectionIDFieldTypes } from './getCollectionIDFieldTypes.js'\n\nconst fieldIsRequired = (field: Field) => {\n const isConditional = Boolean(field?.admin && field?.admin?.condition)\n if (isConditional) {\n return false\n }\n\n const isMarkedRequired = 'required' in field && field.required === true\n if (fieldAffectsData(field) && isMarkedRequired) {\n return true\n }\n\n // if any subfields are required, this field is required\n if ('fields' in field && field.type !== 'array') {\n return field.fields.some((subField) => fieldIsRequired(subField))\n }\n\n // if any tab subfields have required fields, this field is required\n if (field.type === 'tabs') {\n return field.tabs.some((tab) => {\n if ('name' in tab) {\n return tab.fields.some((subField) => fieldIsRequired(subField))\n }\n return false\n })\n }\n\n return false\n}\n\nfunction buildOptionEnums(options: Option[]): string[] {\n return options.map((option) => {\n if (typeof option === 'object' && 'value' in option) {\n return option.value\n }\n\n return option\n })\n}\n\nfunction generateEntitySchemas(\n entities: (SanitizedCollectionConfig | SanitizedGlobalConfig)[],\n): JSONSchema4 {\n const properties = [...entities].reduce((acc, { slug }) => {\n acc[slug] = {\n $ref: `#/definitions/${slug}`,\n }\n\n return acc\n }, {})\n\n return {\n type: 'object',\n additionalProperties: false,\n properties,\n required: Object.keys(properties),\n }\n}\n\nfunction generateEntitySelectSchemas(\n entities: (SanitizedCollectionConfig | SanitizedGlobalConfig)[],\n): JSONSchema4 {\n const properties = [...entities].reduce((acc, { slug }) => {\n acc[slug] = {\n $ref: `#/definitions/${slug}_select`,\n }\n\n return acc\n }, {})\n\n return {\n type: 'object',\n additionalProperties: false,\n properties,\n required: Object.keys(properties),\n }\n}\n\nfunction generateLocaleEntitySchemas(localization: SanitizedConfig['localization']): JSONSchema4 {\n if (localization && 'locales' in localization && localization?.locales) {\n const localesFromConfig = localization?.locales\n\n const locales = [...localesFromConfig].map((locale) => {\n return locale.code\n }, [])\n\n return {\n type: 'string',\n enum: locales,\n }\n }\n\n return {\n type: 'null',\n }\n}\n\nfunction generateAuthEntitySchemas(entities: SanitizedCollectionConfig[]): JSONSchema4 {\n const properties: JSONSchema4[] = [...entities]\n .filter(({ auth }) => Boolean(auth))\n .map(({ slug }) => {\n return {\n allOf: [\n { $ref: `#/definitions/${slug}` },\n {\n type: 'object',\n additionalProperties: false,\n properties: {\n collection: { type: 'string', enum: [slug] },\n },\n required: ['collection'],\n },\n ],\n }\n }, {})\n\n return {\n oneOf: properties,\n }\n}\n\n/**\n * Generates the JSON Schema for database configuration\n *\n * @example { db: idType: string }\n */\nfunction generateDbEntitySchema(config: SanitizedConfig): JSONSchema4 {\n const defaultIDType: JSONSchema4 =\n config.db?.defaultIDType === 'number' ? { type: 'number' } : { type: 'string' }\n\n return {\n type: 'object',\n additionalProperties: false,\n properties: {\n defaultIDType,\n },\n required: ['defaultIDType'],\n }\n}\n\n/**\n * Returns a JSON Schema Type with 'null' added if the field is not required.\n */\nexport function withNullableJSONSchemaType(\n fieldType: JSONSchema4TypeName,\n isRequired: boolean,\n): JSONSchema4TypeName | JSONSchema4TypeName[] {\n const fieldTypes = [fieldType]\n if (isRequired) {\n return fieldType\n }\n fieldTypes.push('null')\n return fieldTypes\n}\n\nexport function fieldsToJSONSchema(\n /**\n * Used for relationship fields, to determine whether to use a string or number type for the ID.\n * While there is a default ID field type set by the db adapter, they can differ on a collection-level\n * if they have custom ID fields.\n */\n collectionIDFieldTypes: { [key: string]: 'number' | 'string' },\n fields: Field[],\n /**\n * Allows you to define new top-level interfaces that can be re-used in the output schema.\n */\n interfaceNameDefinitions: Map<string, JSONSchema4>,\n config?: SanitizedConfig,\n): {\n properties: {\n [k: string]: JSONSchema4\n }\n required: string[]\n} {\n const requiredFieldNames = new Set<string>()\n\n return {\n properties: Object.fromEntries(\n fields.reduce((fieldSchemas, field) => {\n const isRequired = fieldAffectsData(field) && fieldIsRequired(field)\n if (isRequired) {\n requiredFieldNames.add(field.name)\n }\n\n let fieldSchema: JSONSchema4\n\n switch (field.type) {\n case 'text':\n if (field.hasMany === true) {\n fieldSchema = {\n type: withNullableJSONSchemaType('array', isRequired),\n items: { type: 'string' },\n }\n } else {\n fieldSchema = { type: withNullableJSONSchemaType('string', isRequired) }\n }\n break\n case 'textarea':\n case 'code':\n case 'email':\n case 'date': {\n fieldSchema = { type: withNullableJSONSchemaType('string', isRequired) }\n break\n }\n\n case 'number': {\n if (field.hasMany === true) {\n fieldSchema = {\n type: withNullableJSONSchemaType('array', isRequired),\n items: { type: 'number' },\n }\n } else {\n fieldSchema = { type: withNullableJSONSchemaType('number', isRequired) }\n }\n break\n }\n\n case 'checkbox': {\n fieldSchema = { type: withNullableJSONSchemaType('boolean', isRequired) }\n break\n }\n\n case 'json': {\n fieldSchema = field.jsonSchema?.schema || {\n type: ['object', 'array', 'string', 'number', 'boolean', 'null'],\n }\n break\n }\n\n case 'richText': {\n if (!field?.editor) {\n throw new MissingEditorProp(field) // while we allow disabling editor functionality, you should not have any richText fields defined if you do not have an editor\n }\n if (typeof field.editor === 'function') {\n throw new Error('Attempted to access unsanitized rich text editor.')\n }\n if (field.editor.outputSchema) {\n fieldSchema = field.editor.outputSchema({\n collectionIDFieldTypes,\n config,\n field,\n interfaceNameDefinitions,\n isRequired,\n })\n } else {\n // Maintain backwards compatibility with existing rich text editors\n fieldSchema = {\n type: withNullableJSONSchemaType('array', isRequired),\n items: {\n type: 'object',\n },\n }\n }\n\n break\n }\n\n case 'radio': {\n fieldSchema = {\n type: withNullableJSONSchemaType('string', isRequired),\n enum: buildOptionEnums(field.options),\n }\n\n break\n }\n\n case 'select': {\n const optionEnums = buildOptionEnums(field.options)\n\n if (field.hasMany) {\n fieldSchema = {\n type: withNullableJSONSchemaType('array', isRequired),\n items: {\n type: 'string',\n },\n }\n if (optionEnums?.length) {\n ;(fieldSchema.items as JSONSchema4).enum = optionEnums\n }\n } else {\n fieldSchema = {\n type: withNullableJSONSchemaType('string', isRequired),\n }\n if (optionEnums?.length) {\n fieldSchema.enum = optionEnums\n }\n }\n\n break\n }\n\n case 'point': {\n fieldSchema = {\n type: withNullableJSONSchemaType('array', isRequired),\n items: [\n {\n type: 'number',\n },\n {\n type: 'number',\n },\n ],\n maxItems: 2,\n minItems: 2,\n }\n break\n }\n\n case 'join': {\n fieldSchema = {\n type: withNullableJSONSchemaType('object', false),\n additionalProperties: false,\n properties: {\n docs: {\n type: withNullableJSONSchemaType('array', false),\n items: {\n oneOf: [\n {\n type: collectionIDFieldTypes[field.collection],\n },\n {\n $ref: `#/definitions/${field.collection}`,\n },\n ],\n },\n },\n hasNextPage: { type: withNullableJSONSchemaType('boolean', false) },\n },\n }\n break\n }\n\n case 'upload':\n case 'relationship': {\n if (Array.isArray(field.relationTo)) {\n if (field.hasMany) {\n fieldSchema = {\n type: withNullableJSONSchemaType('array', isRequired),\n items: {\n oneOf: field.relationTo.map((relation) => {\n return {\n type: 'object',\n additionalProperties: false,\n properties: {\n relationTo: {\n const: relation,\n },\n value: {\n oneOf: [\n {\n type: collectionIDFieldTypes[relation],\n },\n {\n $ref: `#/definitions/${relation}`,\n },\n ],\n },\n },\n required: ['value', 'relationTo'],\n }\n }),\n },\n }\n } else {\n fieldSchema = {\n oneOf: field.relationTo.map((relation) => {\n return {\n type: withNullableJSONSchemaType('object', isRequired),\n additionalProperties: false,\n properties: {\n relationTo: {\n const: relation,\n },\n value: {\n oneOf: [\n {\n type: collectionIDFieldTypes[relation],\n },\n {\n $ref: `#/definitions/${relation}`,\n },\n ],\n },\n },\n required: ['value', 'relationTo'],\n }\n }),\n }\n }\n } else if (field.hasMany) {\n fieldSchema = {\n type: withNullableJSONSchemaType('array', isRequired),\n items: {\n oneOf: [\n {\n type: collectionIDFieldTypes[field.relationTo],\n },\n {\n $ref: `#/definitions/${field.relationTo}`,\n },\n ],\n },\n }\n } else {\n fieldSchema = {\n oneOf: [\n {\n type: withNullableJSONSchemaType(\n collectionIDFieldTypes[field.relationTo],\n isRequired,\n ),\n },\n {\n $ref: `#/definitions/${field.relationTo}`,\n },\n ],\n }\n }\n\n break\n }\n\n case 'blocks': {\n // Check for a case where no blocks are provided.\n // We need to generate an empty array for this case, note that JSON schema 4 doesn't support empty arrays\n // so the best we can get is `unknown[]`\n const hasBlocks = Boolean(field.blocks.length)\n\n fieldSchema = {\n type: withNullableJSONSchemaType('array', isRequired),\n items: hasBlocks\n ? {\n oneOf: field.blocks.map((block) => {\n const blockFieldSchemas = fieldsToJSONSchema(\n collectionIDFieldTypes,\n block.fields,\n interfaceNameDefinitions,\n config,\n )\n\n const blockSchema: JSONSchema4 = {\n type: 'object',\n additionalProperties: false,\n properties: {\n ...blockFieldSchemas.properties,\n blockType: {\n const: block.slug,\n },\n },\n required: ['blockType', ...blockFieldSchemas.required],\n }\n\n if (block.interfaceName) {\n interfaceNameDefinitions.set(block.interfaceName, blockSchema)\n\n return {\n $ref: `#/definitions/${block.interfaceName}`,\n }\n }\n\n return blockSchema\n }),\n }\n : {},\n }\n break\n }\n\n case 'array': {\n fieldSchema = {\n type: withNullableJSONSchemaType('array', isRequired),\n items: {\n type: 'object',\n additionalProperties: false,\n ...fieldsToJSONSchema(\n collectionIDFieldTypes,\n field.fields,\n interfaceNameDefinitions,\n config,\n ),\n },\n }\n\n if (field.interfaceName) {\n interfaceNameDefinitions.set(field.interfaceName, fieldSchema)\n\n fieldSchema = {\n $ref: `#/definitions/${field.interfaceName}`,\n }\n }\n break\n }\n\n case 'row':\n case 'collapsible': {\n const childSchema = fieldsToJSONSchema(\n collectionIDFieldTypes,\n field.fields,\n interfaceNameDefinitions,\n config,\n )\n Object.entries(childSchema.properties).forEach(([propName, propSchema]) => {\n fieldSchemas.set(propName, propSchema)\n })\n childSchema.required.forEach((propName) => {\n requiredFieldNames.add(propName)\n })\n break\n }\n\n case 'tabs': {\n field.tabs.forEach((tab) => {\n const childSchema = fieldsToJSONSchema(\n collectionIDFieldTypes,\n tab.fields,\n interfaceNameDefinitions,\n config,\n )\n if (tabHasName(tab)) {\n // could have interface\n fieldSchemas.set(tab.name, {\n type: 'object',\n additionalProperties: false,\n ...childSchema,\n })\n\n // If the named tab has any required fields then we mark this as required otherwise it should be optional\n const hasRequiredFields = tab.fields.some((subField) => fieldIsRequired(subField))\n\n if (hasRequiredFields) {\n requiredFieldNames.add(tab.name)\n }\n } else {\n Object.entries(childSchema.properties).forEach(([propName, propSchema]) => {\n fieldSchemas.set(propName, propSchema)\n })\n childSchema.required.forEach((propName) => {\n requiredFieldNames.add(propName)\n })\n }\n })\n break\n }\n\n case 'group': {\n fieldSchema = {\n type: 'object',\n additionalProperties: false,\n ...fieldsToJSONSchema(\n collectionIDFieldTypes,\n field.fields,\n interfaceNameDefinitions,\n config,\n ),\n }\n\n if (field.interfaceName) {\n interfaceNameDefinitions.set(field.interfaceName, fieldSchema)\n\n fieldSchema = {\n $ref: `#/definitions/${field.interfaceName}`,\n }\n }\n break\n }\n\n default: {\n break\n }\n }\n\n if ('typescriptSchema' in field && field?.typescriptSchema?.length) {\n for (const schema of field.typescriptSchema) {\n fieldSchema = schema({ jsonSchema: fieldSchema })\n }\n }\n\n if (fieldSchema && fieldAffectsData(field)) {\n fieldSchemas.set(field.name, fieldSchema)\n }\n\n return fieldSchemas\n }, new Map<string, JSONSchema4>()),\n ),\n required: Array.from(requiredFieldNames),\n }\n}\n\n// This function is part of the public API and is exported through payload/utilities\nexport function entityToJSONSchema(\n config: SanitizedConfig,\n incomingEntity: SanitizedCollectionConfig | SanitizedGlobalConfig,\n interfaceNameDefinitions: Map<string, JSONSchema4>,\n defaultIDType: 'number' | 'text',\n collectionIDFieldTypes?: { [key: string]: 'number' | 'string' },\n): JSONSchema4 {\n if (!collectionIDFieldTypes) {\n collectionIDFieldTypes = getCollectionIDFieldTypes({ config, defaultIDType })\n }\n const entity: SanitizedCollectionConfig | SanitizedGlobalConfig = deepCopyObject(incomingEntity)\n const title = entity.typescript?.interface\n ? entity.typescript.interface\n : singular(toWords(entity.slug, true))\n\n const idField: FieldAffectingData = { name: 'id', type: defaultIDType as 'text', required: true }\n const customIdField = entity.fields.find(\n (field) => fieldAffectsData(field) && field.name === 'id',\n ) as FieldAffectingData\n\n if (customIdField && customIdField.type !== 'group' && customIdField.type !== 'tab') {\n customIdField.required = true\n } else {\n entity.fields.unshift(idField)\n }\n\n // mark timestamp fields required\n if ('timestamps' in entity && entity.timestamps !== false) {\n entity.fields = entity.fields.map((field) => {\n if (fieldAffectsData(field) && (field.name === 'createdAt' || field.name === 'updatedAt')) {\n return {\n ...field,\n required: true,\n }\n }\n return field\n })\n }\n\n if ('auth' in entity && entity.auth && !entity.auth?.disableLocalStrategy) {\n entity.fields.push({\n name: 'password',\n type: 'text',\n })\n }\n\n return {\n type: 'object',\n additionalProperties: false,\n title,\n ...fieldsToJSONSchema(collectionIDFieldTypes, entity.fields, interfaceNameDefinitions, config),\n }\n}\n\nexport function fieldsToSelectJSONSchema({ fields }: { fields: Field[] }): JSONSchema4 {\n const schema: JSONSchema4 = {\n type: 'object',\n additionalProperties: false,\n properties: {},\n }\n\n for (const field of fields) {\n switch (field.type) {\n case 'row':\n case 'collapsible':\n schema.properties = {\n ...schema.properties,\n ...fieldsToSelectJSONSchema({ fields: field.fields }).properties,\n }\n\n break\n\n case 'array':\n case 'group':\n schema.properties[field.name] = {\n oneOf: [\n {\n type: 'boolean',\n },\n fieldsToSelectJSONSchema({ fields: field.fields }),\n ],\n }\n break\n\n case 'tabs':\n for (const tab of field.tabs) {\n if (tabHasName(tab)) {\n schema.properties[tab.name] = {\n oneOf: [\n {\n type: 'boolean',\n },\n fieldsToSelectJSONSchema({ fields: tab.fields }),\n ],\n }\n continue\n }\n\n schema.properties = {\n ...schema.properties,\n ...fieldsToSelectJSONSchema({ fields: tab.fields }).properties,\n }\n }\n break\n\n case 'blocks': {\n const blocksSchema: JSONSchema4 = {\n type: 'object',\n additionalProperties: false,\n properties: {},\n }\n\n for (const block of field.blocks) {\n blocksSchema.properties[block.slug] = {\n oneOf: [\n {\n type: 'boolean',\n },\n fieldsToSelectJSONSchema({ fields: block.fields }),\n ],\n }\n }\n\n schema.properties[field.name] = {\n oneOf: [\n {\n type: 'boolean',\n },\n blocksSchema,\n ],\n }\n\n break\n }\n\n default:\n schema.properties[field.name] = {\n type: 'boolean',\n }\n break\n }\n }\n\n return schema\n}\n\nconst fieldType: JSONSchema4 = {\n type: 'string',\n required: false,\n}\nconst generateAuthFieldTypes = ({\n type,\n loginWithUsername,\n}: {\n loginWithUsername: Auth['loginWithUsername']\n type: 'forgotOrUnlock' | 'login' | 'register'\n}): JSONSchema4 => {\n if (loginWithUsername) {\n switch (type) {\n case 'login': {\n if (loginWithUsername.allowEmailLogin) {\n // allow username or email and require password for login\n return {\n additionalProperties: false,\n oneOf: [\n {\n additionalProperties: false,\n properties: { email: fieldType, password: fieldType },\n required: ['email', 'password'],\n },\n {\n additionalProperties: false,\n properties: { password: fieldType, username: fieldType },\n required: ['username', 'password'],\n },\n ],\n }\n } else {\n // allow only username and password for login\n return {\n additionalProperties: false,\n properties: {\n password: fieldType,\n username: fieldType,\n },\n required: ['username', 'password'],\n }\n }\n }\n\n case 'register': {\n const requiredFields: ('email' | 'password' | 'username')[] = ['password']\n const properties: {\n email?: JSONSchema4['properties']\n password?: JSONSchema4['properties']\n username?: JSONSchema4['properties']\n } = {\n password: fieldType,\n username: fieldType,\n }\n\n if (loginWithUsername.requireEmail) {\n requiredFields.push('email')\n }\n if (loginWithUsername.requireUsername) {\n requiredFields.push('username')\n }\n if (loginWithUsername.requireEmail || loginWithUsername.allowEmailLogin) {\n properties.email = fieldType\n }\n\n return {\n additionalProperties: false,\n properties,\n required: requiredFields,\n }\n }\n\n case 'forgotOrUnlock': {\n if (loginWithUsername.allowEmailLogin) {\n // allow email or username for unlock/forgot-password\n return {\n additionalProperties: false,\n oneOf: [\n {\n additionalProperties: false,\n properties: { email: fieldType },\n required: ['email'],\n },\n {\n additionalProperties: false,\n properties: { username: fieldType },\n required: ['username'],\n },\n ],\n }\n } else {\n // allow only username for unlock/forgot-password\n return {\n additionalProperties: false,\n properties: { username: fieldType },\n required: ['username'],\n }\n }\n }\n }\n }\n\n // default email (and password for login/register)\n return {\n additionalProperties: false,\n properties: { email: fieldType, password: fieldType },\n required: ['email', 'password'],\n }\n}\n\nexport function authCollectionToOperationsJSONSchema(\n config: SanitizedCollectionConfig,\n): JSONSchema4 {\n const loginWithUsername = config.auth?.loginWithUsername\n const loginUserFields: JSONSchema4 = generateAuthFieldTypes({ type: 'login', loginWithUsername })\n const forgotOrUnlockUserFields: JSONSchema4 = generateAuthFieldTypes({\n type: 'forgotOrUnlock',\n loginWithUsername,\n })\n const registerUserFields: JSONSchema4 = generateAuthFieldTypes({\n type: 'register',\n loginWithUsername,\n })\n\n const properties: JSONSchema4['properties'] = {\n forgotPassword: forgotOrUnlockUserFields,\n login: loginUserFields,\n registerFirstUser: registerUserFields,\n unlock: forgotOrUnlockUserFields,\n }\n\n return {\n type: 'object',\n additionalProperties: false,\n properties,\n required: Object.keys(properties),\n title: `${singular(toWords(`${config.slug}`, true))}AuthOperations`,\n }\n}\n\nfunction generateAuthOperationSchemas(collections: SanitizedCollectionConfig[]): JSONSchema4 {\n const properties = collections.reduce((acc, collection) => {\n if (collection.auth) {\n acc[collection.slug] = {\n $ref: `#/definitions/auth/${collection.slug}`,\n }\n }\n return acc\n }, {})\n\n return {\n type: 'object',\n additionalProperties: false,\n properties,\n required: Object.keys(properties),\n }\n}\n\n/**\n * This is used for generating the TypeScript types (payload-types.ts) with the payload generate:types command.\n */\nexport function configToJSONSchema(\n config: SanitizedConfig,\n defaultIDType?: 'number' | 'text',\n): JSONSchema4 {\n // a mutable Map to store custom top-level `interfaceName` types. Fields with an `interfaceName` property will be moved to the top-level definitions here\n const interfaceNameDefinitions: Map<string, JSONSchema4> = new Map()\n\n // Used for relationship fields, to determine whether to use a string or number type for the ID.\n const collectionIDFieldTypes = getCollectionIDFieldTypes({ config, defaultIDType })\n\n // Collections and Globals have to be moved to the top-level definitions as well. Reason: The top-level type will be the `Config` type - we don't want all collection and global\n // types to be inlined inside the `Config` type\n\n const entities: {\n entity: SanitizedCollectionConfig | SanitizedGlobalConfig\n type: 'collection' | 'global'\n }[] = [\n ...config.globals.map((global) => ({ type: 'global' as const, entity: global })),\n ...config.collections.map((collection) => ({\n type: 'collection' as const,\n entity: collection,\n })),\n ]\n\n const entityDefinitions: { [k: string]: JSONSchema4 } = entities.reduce(\n (acc, { type, entity }) => {\n acc[entity.slug] = entityToJSONSchema(\n config,\n entity,\n interfaceNameDefinitions,\n defaultIDType,\n collectionIDFieldTypes,\n )\n const select = fieldsToSelectJSONSchema({ fields: entity.fields })\n\n if (type === 'global') {\n select.properties.globalType = {\n type: 'boolean',\n }\n }\n\n acc[`${entity.slug}_select`] = {\n type: 'object',\n additionalProperties: false,\n ...select,\n }\n\n return acc\n },\n {},\n )\n\n const authOperationDefinitions = [...config.collections]\n .filter(({ auth }) => Boolean(auth))\n .reduce(\n (acc, authCollection) => {\n acc.auth[authCollection.slug] = authCollectionToOperationsJSONSchema(authCollection)\n return acc\n },\n { auth: {} },\n )\n\n const jobsSchemas = config.jobs\n ? generateJobsJSONSchemas(config, config.jobs, interfaceNameDefinitions, collectionIDFieldTypes)\n : {}\n\n let jsonSchema: JSONSchema4 = {\n additionalProperties: false,\n definitions: {\n ...entityDefinitions,\n ...Object.fromEntries(interfaceNameDefinitions),\n ...authOperationDefinitions,\n },\n // These properties here will be very simple, as all the complexity is in the definitions. These are just the properties for the top-level `Config` type\n type: 'object',\n properties: {\n auth: generateAuthOperationSchemas(config.collections),\n collections: generateEntitySchemas(config.collections || []),\n collectionsSelect: generateEntitySelectSchemas(config.collections || []),\n db: generateDbEntitySchema(config),\n globals: generateEntitySchemas(config.globals || []),\n globalsSelect: generateEntitySelectSchemas(config.globals || []),\n locale: generateLocaleEntitySchemas(config.localization),\n user: generateAuthEntitySchemas(config.collections),\n },\n required: ['user', 'locale', 'collections', 'globals', 'auth', 'db'],\n title: 'Config',\n }\n if (jobsSchemas.definitions?.size) {\n for (const [key, value] of jobsSchemas.definitions) {\n jsonSchema.definitions[key] = value\n }\n }\n if (jobsSchemas.properties) {\n jsonSchema.properties.jobs = {\n type: 'object',\n additionalProperties: false,\n properties: jobsSchemas.properties,\n required: ['tasks'],\n }\n }\n\n if (config?.typescript?.schema?.length) {\n for (const schema of config.typescript.schema) {\n jsonSchema = schema({ jsonSchema })\n }\n }\n\n return jsonSchema\n}\n"],"names":["pluralize","singular","MissingEditorProp","fieldAffectsData","tabHasName","generateJobsJSONSchemas","deepCopyObject","toWords","getCollectionIDFieldTypes","fieldIsRequired","field","isConditional","Boolean","admin","condition","isMarkedRequired","required","type","fields","some","subField","tabs","tab","buildOptionEnums","options","map","option","value","generateEntitySchemas","entities","properties","reduce","acc","slug","$ref","additionalProperties","Object","keys","generateEntitySelectSchemas","generateLocaleEntitySchemas","localization","locales","localesFromConfig","locale","code","enum","generateAuthEntitySchemas","filter","auth","allOf","collection","oneOf","generateDbEntitySchema","config","defaultIDType","db","withNullableJSONSchemaType","fieldType","isRequired","fieldTypes","push","fieldsToJSONSchema","collectionIDFieldTypes","interfaceNameDefinitions","requiredFieldNames","Set","fromEntries","fieldSchemas","add","name","fieldSchema","hasMany","items","jsonSchema","schema","editor","Error","outputSchema","optionEnums","length","maxItems","minItems","docs","hasNextPage","Array","isArray","relationTo","relation","const","hasBlocks","blocks","block","blockFieldSchemas","blockSchema","blockType","interfaceName","set","childSchema","entries","forEach","propName","propSchema","hasRequiredFields","typescriptSchema","Map","from","entityToJSONSchema","incomingEntity","entity","title","typescript","interface","idField","customIdField","find","unshift","timestamps","disableLocalStrategy","fieldsToSelectJSONSchema","blocksSchema","generateAuthFieldTypes","loginWithUsername","allowEmailLogin","email","password","username","requiredFields","requireEmail","requireUsername","authCollectionToOperationsJSONSchema","loginUserFields","forgotOrUnlockUserFields","registerUserFields","forgotPassword","login","registerFirstUser","unlock","generateAuthOperationSchemas","collections","configToJSONSchema","globals","global","entityDefinitions","select","globalType","authOperationDefinitions","authCollection","jobsSchemas","jobs","definitions","collectionsSelect","globalsSelect","user","size","key"],"mappings":"AAEA,OAAOA,eAAe,YAAW;AACjC,MAAM,EAAEC,QAAQ,EAAE,GAAGD;AAQrB,SAASE,iBAAiB,QAAQ,iCAAgC;AAClE,SAASC,gBAAgB,EAAEC,UAAU,QAAQ,4BAA2B;AACxE,SAASC,uBAAuB,QAAQ,8CAA6C;AACrF,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,OAAO,QAAQ,oBAAmB;AAC3C,SAASC,yBAAyB,QAAQ,iCAAgC;AAE1E,MAAMC,kBAAkB,CAACC;IACvB,MAAMC,gBAAgBC,QAAQF,OAAOG,SAASH,OAAOG,OAAOC;IAC5D,IAAIH,eAAe;QACjB,OAAO;IACT;IAEA,MAAMI,mBAAmB,cAAcL,SAASA,MAAMM,QAAQ,KAAK;IACnE,IAAIb,iBAAiBO,UAAUK,kBAAkB;QAC/C,OAAO;IACT;IAEA,wDAAwD;IACxD,IAAI,YAAYL,SAASA,MAAMO,IAAI,KAAK,SAAS;QAC/C,OAAOP,MAAMQ,MAAM,CAACC,IAAI,CAAC,CAACC,WAAaX,gBAAgBW;IACzD;IAEA,oEAAoE;IACpE,IAAIV,MAAMO,IAAI,KAAK,QAAQ;QACzB,OAAOP,MAAMW,IAAI,CAACF,IAAI,CAAC,CAACG;YACtB,IAAI,UAAUA,KAAK;gBACjB,OAAOA,IAAIJ,MAAM,CAACC,IAAI,CAAC,CAACC,WAAaX,gBAAgBW;YACvD;YACA,OAAO;QACT;IACF;IAEA,OAAO;AACT;AAEA,SAASG,iBAAiBC,OAAiB;IACzC,OAAOA,QAAQC,GAAG,CAAC,CAACC;QAClB,IAAI,OAAOA,WAAW,YAAY,W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JSONSchema.ts"],"sourcesContent":["import type { JSONSchema4, JSONSchema4TypeName } from 'json-schema'\n\nimport pluralize from 'pluralize'\nconst { singular } = pluralize\n\nimport type { Auth } from '../auth/types.js'\nimport type { SanitizedCollectionConfig } from '../collections/config/types.js'\nimport type { SanitizedConfig } from '../config/types.js'\nimport type { Field, FieldAffectingData, Option } from '../fields/config/types.js'\nimport type { SanitizedGlobalConfig } from '../globals/config/types.js'\n\nimport { MissingEditorProp } from '../errors/MissingEditorProp.js'\nimport { fieldAffectsData, tabHasName } from '../fields/config/types.js'\nimport { generateJobsJSONSchemas } from '../queues/config/generateJobsJSONSchemas.js'\nimport { deepCopyObject } from './deepCopyObject.js'\nimport { toWords } from './formatLabels.js'\nimport { getCollectionIDFieldTypes } from './getCollectionIDFieldTypes.js'\n\nconst fieldIsRequired = (field: Field) => {\n const isConditional = Boolean(field?.admin && field?.admin?.condition)\n if (isConditional) {\n return false\n }\n\n const isMarkedRequired = 'required' in field && field.required === true\n if (fieldAffectsData(field) && isMarkedRequired) {\n return true\n }\n\n // if any subfields are required, this field is required\n if ('fields' in field && field.type !== 'array') {\n return field.fields.some((subField) => fieldIsRequired(subField))\n }\n\n // if any tab subfields have required fields, this field is required\n if (field.type === 'tabs') {\n return field.tabs.some((tab) => {\n if ('name' in tab) {\n return tab.fields.some((subField) => fieldIsRequired(subField))\n }\n return false\n })\n }\n\n return false\n}\n\nfunction buildOptionEnums(options: Option[]): string[] {\n return options.map((option) => {\n if (typeof option === 'object' && 'value' in option) {\n return option.value\n }\n\n return option\n })\n}\n\nfunction generateEntitySchemas(\n entities: (SanitizedCollectionConfig | SanitizedGlobalConfig)[],\n): JSONSchema4 {\n const properties = [...entities].reduce((acc, { slug }) => {\n acc[slug] = {\n $ref: `#/definitions/${slug}`,\n }\n\n return acc\n }, {})\n\n return {\n type: 'object',\n additionalProperties: false,\n properties,\n required: Object.keys(properties),\n }\n}\n\nfunction generateEntitySelectSchemas(\n entities: (SanitizedCollectionConfig | SanitizedGlobalConfig)[],\n): JSONSchema4 {\n const properties = [...entities].reduce((acc, { slug }) => {\n acc[slug] = {\n $ref: `#/definitions/${slug}_select`,\n }\n\n return acc\n }, {})\n\n return {\n type: 'object',\n additionalProperties: false,\n properties,\n required: Object.keys(properties),\n }\n}\n\nfunction generateLocaleEntitySchemas(localization: SanitizedConfig['localization']): JSONSchema4 {\n if (localization && 'locales' in localization && localization?.locales) {\n const localesFromConfig = localization?.locales\n\n const locales = [...localesFromConfig].map((locale) => {\n return locale.code\n }, [])\n\n return {\n type: 'string',\n enum: locales,\n }\n }\n\n return {\n type: 'null',\n }\n}\n\nfunction generateAuthEntitySchemas(entities: SanitizedCollectionConfig[]): JSONSchema4 {\n const properties: JSONSchema4[] = [...entities]\n .filter(({ auth }) => Boolean(auth))\n .map(({ slug }) => {\n return {\n allOf: [\n { $ref: `#/definitions/${slug}` },\n {\n type: 'object',\n additionalProperties: false,\n properties: {\n collection: { type: 'string', enum: [slug] },\n },\n required: ['collection'],\n },\n ],\n }\n }, {})\n\n return {\n oneOf: properties,\n }\n}\n\n/**\n * Generates the JSON Schema for database configuration\n *\n * @example { db: idType: string }\n */\nfunction generateDbEntitySchema(config: SanitizedConfig): JSONSchema4 {\n const defaultIDType: JSONSchema4 =\n config.db?.defaultIDType === 'number' ? { type: 'number' } : { type: 'string' }\n\n return {\n type: 'object',\n additionalProperties: false,\n properties: {\n defaultIDType,\n },\n required: ['defaultIDType'],\n }\n}\n\n/**\n * Returns a JSON Schema Type with 'null' added if the field is not required.\n */\nexport function withNullableJSONSchemaType(\n fieldType: JSONSchema4TypeName,\n isRequired: boolean,\n): JSONSchema4TypeName | JSONSchema4TypeName[] {\n const fieldTypes = [fieldType]\n if (isRequired) {\n return fieldType\n }\n fieldTypes.push('null')\n return fieldTypes\n}\n\nexport function fieldsToJSONSchema(\n /**\n * Used for relationship fields, to determine whether to use a string or number type for the ID.\n * While there is a default ID field type set by the db adapter, they can differ on a collection-level\n * if they have custom ID fields.\n */\n collectionIDFieldTypes: { [key: string]: 'number' | 'string' },\n fields: Field[],\n /**\n * Allows you to define new top-level interfaces that can be re-used in the output schema.\n */\n interfaceNameDefinitions: Map<string, JSONSchema4>,\n config?: SanitizedConfig,\n): {\n properties: {\n [k: string]: JSONSchema4\n }\n required: string[]\n} {\n const requiredFieldNames = new Set<string>()\n\n return {\n properties: Object.fromEntries(\n fields.reduce((fieldSchemas, field) => {\n const isRequired = fieldAffectsData(field) && fieldIsRequired(field)\n if (isRequired) {\n requiredFieldNames.add(field.name)\n }\n\n let fieldSchema: JSONSchema4\n\n switch (field.type) {\n case 'text':\n if (field.hasMany === true) {\n fieldSchema = {\n type: withNullableJSONSchemaType('array', isRequired),\n items: { type: 'string' },\n }\n } else {\n fieldSchema = { type: withNullableJSONSchemaType('string', isRequired) }\n }\n break\n case 'textarea':\n case 'code':\n case 'email':\n case 'date': {\n fieldSchema = { type: withNullableJSONSchemaType('string', isRequired) }\n break\n }\n\n case 'number': {\n if (field.hasMany === true) {\n fieldSchema = {\n type: withNullableJSONSchemaType('array', isRequired),\n items: { type: 'number' },\n }\n } else {\n fieldSchema = { type: withNullableJSONSchemaType('number', isRequired) }\n }\n break\n }\n\n case 'checkbox': {\n fieldSchema = { type: withNullableJSONSchemaType('boolean', isRequired) }\n break\n }\n\n case 'json': {\n fieldSchema = field.jsonSchema?.schema || {\n type: ['object', 'array', 'string', 'number', 'boolean', 'null'],\n }\n break\n }\n\n case 'richText': {\n if (!field?.editor) {\n throw new MissingEditorProp(field) // while we allow disabling editor functionality, you should not have any richText fields defined if you do not have an editor\n }\n if (typeof field.editor === 'function') {\n throw new Error('Attempted to access unsanitized rich text editor.')\n }\n if (field.editor.outputSchema) {\n fieldSchema = field.editor.outputSchema({\n collectionIDFieldTypes,\n config,\n field,\n interfaceNameDefinitions,\n isRequired,\n })\n } else {\n // Maintain backwards compatibility with existing rich text editors\n fieldSchema = {\n type: withNullableJSONSchemaType('array', isRequired),\n items: {\n type: 'object',\n },\n }\n }\n\n break\n }\n\n case 'radio': {\n fieldSchema = {\n type: withNullableJSONSchemaType('string', isRequired),\n enum: buildOptionEnums(field.options),\n }\n\n break\n }\n\n case 'select': {\n const optionEnums = buildOptionEnums(field.options)\n\n if (field.hasMany) {\n fieldSchema = {\n type: withNullableJSONSchemaType('array', isRequired),\n items: {\n type: 'string',\n },\n }\n if (optionEnums?.length) {\n ;(fieldSchema.items as JSONSchema4).enum = optionEnums\n }\n } else {\n fieldSchema = {\n type: withNullableJSONSchemaType('string', isRequired),\n }\n if (optionEnums?.length) {\n fieldSchema.enum = optionEnums\n }\n }\n\n break\n }\n\n case 'point': {\n fieldSchema = {\n type: withNullableJSONSchemaType('array', isRequired),\n items: [\n {\n type: 'number',\n },\n {\n type: 'number',\n },\n ],\n maxItems: 2,\n minItems: 2,\n }\n break\n }\n\n case 'join': {\n fieldSchema = {\n type: withNullableJSONSchemaType('object', false),\n additionalProperties: false,\n properties: {\n docs: {\n type: withNullableJSONSchemaType('array', false),\n items: {\n oneOf: [\n {\n type: collectionIDFieldTypes[field.collection],\n },\n {\n $ref: `#/definitions/${field.collection}`,\n },\n ],\n },\n },\n hasNextPage: { type: withNullableJSONSchemaType('boolean', false) },\n },\n }\n break\n }\n\n case 'upload':\n case 'relationship': {\n if (Array.isArray(field.relationTo)) {\n if (field.hasMany) {\n fieldSchema = {\n type: withNullableJSONSchemaType('array', isRequired),\n items: {\n oneOf: field.relationTo.map((relation) => {\n return {\n type: 'object',\n additionalProperties: false,\n properties: {\n relationTo: {\n const: relation,\n },\n value: {\n oneOf: [\n {\n type: collectionIDFieldTypes[relation],\n },\n {\n $ref: `#/definitions/${relation}`,\n },\n ],\n },\n },\n required: ['value', 'relationTo'],\n }\n }),\n },\n }\n } else {\n fieldSchema = {\n oneOf: field.relationTo.map((relation) => {\n return {\n type: withNullableJSONSchemaType('object', isRequired),\n additionalProperties: false,\n properties: {\n relationTo: {\n const: relation,\n },\n value: {\n oneOf: [\n {\n type: collectionIDFieldTypes[relation],\n },\n {\n $ref: `#/definitions/${relation}`,\n },\n ],\n },\n },\n required: ['value', 'relationTo'],\n }\n }),\n }\n }\n } else if (field.hasMany) {\n fieldSchema = {\n type: withNullableJSONSchemaType('array', isRequired),\n items: {\n oneOf: [\n {\n type: collectionIDFieldTypes[field.relationTo],\n },\n {\n $ref: `#/definitions/${field.relationTo}`,\n },\n ],\n },\n }\n } else {\n fieldSchema = {\n oneOf: [\n {\n type: withNullableJSONSchemaType(\n collectionIDFieldTypes[field.relationTo],\n isRequired,\n ),\n },\n {\n $ref: `#/definitions/${field.relationTo}`,\n },\n ],\n }\n }\n\n break\n }\n\n case 'blocks': {\n // Check for a case where no blocks are provided.\n // We need to generate an empty array for this case, note that JSON schema 4 doesn't support empty arrays\n // so the best we can get is `unknown[]`\n const hasBlocks = Boolean(field.blocks.length)\n\n fieldSchema = {\n type: withNullableJSONSchemaType('array', isRequired),\n items: hasBlocks\n ? {\n oneOf: field.blocks.map((block) => {\n const blockFieldSchemas = fieldsToJSONSchema(\n collectionIDFieldTypes,\n block.fields,\n interfaceNameDefinitions,\n config,\n )\n\n const blockSchema: JSONSchema4 = {\n type: 'object',\n additionalProperties: false,\n properties: {\n ...blockFieldSchemas.properties,\n blockType: {\n const: block.slug,\n },\n },\n required: ['blockType', ...blockFieldSchemas.required],\n }\n\n if (block.interfaceName) {\n interfaceNameDefinitions.set(block.interfaceName, blockSchema)\n\n return {\n $ref: `#/definitions/${block.interfaceName}`,\n }\n }\n\n return blockSchema\n }),\n }\n : {},\n }\n break\n }\n\n case 'array': {\n fieldSchema = {\n type: withNullableJSONSchemaType('array', isRequired),\n items: {\n type: 'object',\n additionalProperties: false,\n ...fieldsToJSONSchema(\n collectionIDFieldTypes,\n field.fields,\n interfaceNameDefinitions,\n config,\n ),\n },\n }\n\n if (field.interfaceName) {\n interfaceNameDefinitions.set(field.interfaceName, fieldSchema)\n\n fieldSchema = {\n $ref: `#/definitions/${field.interfaceName}`,\n }\n }\n break\n }\n\n case 'row':\n case 'collapsible': {\n const childSchema = fieldsToJSONSchema(\n collectionIDFieldTypes,\n field.fields,\n interfaceNameDefinitions,\n config,\n )\n Object.entries(childSchema.properties).forEach(([propName, propSchema]) => {\n fieldSchemas.set(propName, propSchema)\n })\n childSchema.required.forEach((propName) => {\n requiredFieldNames.add(propName)\n })\n break\n }\n\n case 'tabs': {\n field.tabs.forEach((tab) => {\n const childSchema = fieldsToJSONSchema(\n collectionIDFieldTypes,\n tab.fields,\n interfaceNameDefinitions,\n config,\n )\n if (tabHasName(tab)) {\n // could have interface\n fieldSchemas.set(tab.name, {\n type: 'object',\n additionalProperties: false,\n ...childSchema,\n })\n\n // If the named tab has any required fields then we mark this as required otherwise it should be optional\n const hasRequiredFields = tab.fields.some((subField) => fieldIsRequired(subField))\n\n if (hasRequiredFields) {\n requiredFieldNames.add(tab.name)\n }\n } else {\n Object.entries(childSchema.properties).forEach(([propName, propSchema]) => {\n fieldSchemas.set(propName, propSchema)\n })\n childSchema.required.forEach((propName) => {\n requiredFieldNames.add(propName)\n })\n }\n })\n break\n }\n\n case 'group': {\n fieldSchema = {\n type: 'object',\n additionalProperties: false,\n ...fieldsToJSONSchema(\n collectionIDFieldTypes,\n field.fields,\n interfaceNameDefinitions,\n config,\n ),\n }\n\n if (field.interfaceName) {\n interfaceNameDefinitions.set(field.interfaceName, fieldSchema)\n\n fieldSchema = {\n $ref: `#/definitions/${field.interfaceName}`,\n }\n }\n break\n }\n\n default: {\n break\n }\n }\n\n if ('typescriptSchema' in field && field?.typescriptSchema?.length) {\n for (const schema of field.typescriptSchema) {\n fieldSchema = schema({ jsonSchema: fieldSchema })\n }\n }\n\n if (fieldSchema && fieldAffectsData(field)) {\n fieldSchemas.set(field.name, fieldSchema)\n }\n\n return fieldSchemas\n }, new Map<string, JSONSchema4>()),\n ),\n required: Array.from(requiredFieldNames),\n }\n}\n\n// This function is part of the public API and is exported through payload/utilities\nexport function entityToJSONSchema(\n config: SanitizedConfig,\n incomingEntity: SanitizedCollectionConfig | SanitizedGlobalConfig,\n interfaceNameDefinitions: Map<string, JSONSchema4>,\n defaultIDType: 'number' | 'text',\n collectionIDFieldTypes?: { [key: string]: 'number' | 'string' },\n): JSONSchema4 {\n if (!collectionIDFieldTypes) {\n collectionIDFieldTypes = getCollectionIDFieldTypes({ config, defaultIDType })\n }\n const entity: SanitizedCollectionConfig | SanitizedGlobalConfig = deepCopyObject(incomingEntity)\n const title = entity.typescript?.interface\n ? entity.typescript.interface\n : singular(toWords(entity.slug, true))\n\n const idField: FieldAffectingData = { name: 'id', type: defaultIDType as 'text', required: true }\n const customIdField = entity.fields.find(\n (field) => fieldAffectsData(field) && field.name === 'id',\n ) as FieldAffectingData\n\n if (customIdField && customIdField.type !== 'group' && customIdField.type !== 'tab') {\n customIdField.required = true\n } else {\n entity.fields.unshift(idField)\n }\n\n // mark timestamp fields required\n if ('timestamps' in entity && entity.timestamps !== false) {\n entity.fields = entity.fields.map((field) => {\n if (fieldAffectsData(field) && (field.name === 'createdAt' || field.name === 'updatedAt')) {\n return {\n ...field,\n required: true,\n }\n }\n return field\n })\n }\n\n if ('auth' in entity && entity.auth && !entity.auth?.disableLocalStrategy) {\n entity.fields.push({\n name: 'password',\n type: 'text',\n })\n }\n\n return {\n type: 'object',\n additionalProperties: false,\n title,\n ...fieldsToJSONSchema(collectionIDFieldTypes, entity.fields, interfaceNameDefinitions, config),\n }\n}\n\nexport function fieldsToSelectJSONSchema({ fields }: { fields: Field[] }): JSONSchema4 {\n const schema: JSONSchema4 = {\n type: 'object',\n additionalProperties: false,\n properties: {},\n }\n\n for (const field of fields) {\n switch (field.type) {\n case 'row':\n case 'collapsible':\n schema.properties = {\n ...schema.properties,\n ...fieldsToSelectJSONSchema({ fields: field.fields }).properties,\n }\n\n break\n\n case 'array':\n case 'group':\n schema.properties[field.name] = {\n oneOf: [\n {\n type: 'boolean',\n },\n fieldsToSelectJSONSchema({ fields: field.fields }),\n ],\n }\n break\n\n case 'tabs':\n for (const tab of field.tabs) {\n if (tabHasName(tab)) {\n schema.properties[tab.name] = {\n oneOf: [\n {\n type: 'boolean',\n },\n fieldsToSelectJSONSchema({ fields: tab.fields }),\n ],\n }\n continue\n }\n\n schema.properties = {\n ...schema.properties,\n ...fieldsToSelectJSONSchema({ fields: tab.fields }).properties,\n }\n }\n break\n\n case 'blocks': {\n const blocksSchema: JSONSchema4 = {\n type: 'object',\n additionalProperties: false,\n properties: {},\n }\n\n for (const block of field.blocks) {\n blocksSchema.properties[block.slug] = {\n oneOf: [\n {\n type: 'boolean',\n },\n fieldsToSelectJSONSchema({ fields: block.fields }),\n ],\n }\n }\n\n schema.properties[field.name] = {\n oneOf: [\n {\n type: 'boolean',\n },\n blocksSchema,\n ],\n }\n\n break\n }\n\n default:\n schema.properties[field.name] = {\n type: 'boolean',\n }\n break\n }\n }\n\n return schema\n}\n\nconst fieldType: JSONSchema4 = {\n type: 'string',\n required: false,\n}\nconst generateAuthFieldTypes = ({\n type,\n loginWithUsername,\n}: {\n loginWithUsername: Auth['loginWithUsername']\n type: 'forgotOrUnlock' | 'login' | 'register'\n}): JSONSchema4 => {\n if (loginWithUsername) {\n switch (type) {\n case 'login': {\n if (loginWithUsername.allowEmailLogin) {\n // allow username or email and require password for login\n return {\n additionalProperties: false,\n oneOf: [\n {\n additionalProperties: false,\n properties: { email: fieldType, password: fieldType },\n required: ['email', 'password'],\n },\n {\n additionalProperties: false,\n properties: { password: fieldType, username: fieldType },\n required: ['username', 'password'],\n },\n ],\n }\n } else {\n // allow only username and password for login\n return {\n additionalProperties: false,\n properties: {\n password: fieldType,\n username: fieldType,\n },\n required: ['username', 'password'],\n }\n }\n }\n\n case 'register': {\n const requiredFields: ('email' | 'password' | 'username')[] = ['password']\n const properties: {\n email?: JSONSchema4['properties']\n password?: JSONSchema4['properties']\n username?: JSONSchema4['properties']\n } = {\n password: fieldType,\n username: fieldType,\n }\n\n if (loginWithUsername.requireEmail) {\n requiredFields.push('email')\n }\n if (loginWithUsername.requireUsername) {\n requiredFields.push('username')\n }\n if (loginWithUsername.requireEmail || loginWithUsername.allowEmailLogin) {\n properties.email = fieldType\n }\n\n return {\n additionalProperties: false,\n properties,\n required: requiredFields,\n }\n }\n\n case 'forgotOrUnlock': {\n if (loginWithUsername.allowEmailLogin) {\n // allow email or username for unlock/forgot-password\n return {\n additionalProperties: false,\n oneOf: [\n {\n additionalProperties: false,\n properties: { email: fieldType },\n required: ['email'],\n },\n {\n additionalProperties: false,\n properties: { username: fieldType },\n required: ['username'],\n },\n ],\n }\n } else {\n // allow only username for unlock/forgot-password\n return {\n additionalProperties: false,\n properties: { username: fieldType },\n required: ['username'],\n }\n }\n }\n }\n }\n\n // default email (and password for login/register)\n return {\n additionalProperties: false,\n properties: { email: fieldType, password: fieldType },\n required: ['email', 'password'],\n }\n}\n\nexport function authCollectionToOperationsJSONSchema(\n config: SanitizedCollectionConfig,\n): JSONSchema4 {\n const loginWithUsername = config.auth?.loginWithUsername\n const loginUserFields: JSONSchema4 = generateAuthFieldTypes({ type: 'login', loginWithUsername })\n const forgotOrUnlockUserFields: JSONSchema4 = generateAuthFieldTypes({\n type: 'forgotOrUnlock',\n loginWithUsername,\n })\n const registerUserFields: JSONSchema4 = generateAuthFieldTypes({\n type: 'register',\n loginWithUsername,\n })\n\n const properties: JSONSchema4['properties'] = {\n forgotPassword: forgotOrUnlockUserFields,\n login: loginUserFields,\n registerFirstUser: registerUserFields,\n unlock: forgotOrUnlockUserFields,\n }\n\n return {\n type: 'object',\n additionalProperties: false,\n properties,\n required: Object.keys(properties),\n title: `${singular(toWords(`${config.slug}`, true))}AuthOperations`,\n }\n}\n\nfunction generateAuthOperationSchemas(collections: SanitizedCollectionConfig[]): JSONSchema4 {\n const properties = collections.reduce((acc, collection) => {\n if (collection.auth) {\n acc[collection.slug] = {\n $ref: `#/definitions/auth/${collection.slug}`,\n }\n }\n return acc\n }, {})\n\n return {\n type: 'object',\n additionalProperties: false,\n properties,\n required: Object.keys(properties),\n }\n}\n\n/**\n * This is used for generating the TypeScript types (payload-types.ts) with the payload generate:types command.\n */\nexport function configToJSONSchema(\n config: SanitizedConfig,\n defaultIDType?: 'number' | 'text',\n): JSONSchema4 {\n // a mutable Map to store custom top-level `interfaceName` types. Fields with an `interfaceName` property will be moved to the top-level definitions here\n const interfaceNameDefinitions: Map<string, JSONSchema4> = new Map()\n\n // Used for relationship fields, to determine whether to use a string or number type for the ID.\n const collectionIDFieldTypes = getCollectionIDFieldTypes({ config, defaultIDType })\n\n // Collections and Globals have to be moved to the top-level definitions as well. Reason: The top-level type will be the `Config` type - we don't want all collection and global\n // types to be inlined inside the `Config` type\n\n const entities: {\n entity: SanitizedCollectionConfig | SanitizedGlobalConfig\n type: 'collection' | 'global'\n }[] = [\n ...config.globals.map((global) => ({ type: 'global' as const, entity: global })),\n ...config.collections.map((collection) => ({\n type: 'collection' as const,\n entity: collection,\n })),\n ]\n\n const entityDefinitions: { [k: string]: JSONSchema4 } = entities.reduce(\n (acc, { type, entity }) => {\n acc[entity.slug] = entityToJSONSchema(\n config,\n entity,\n interfaceNameDefinitions,\n defaultIDType,\n collectionIDFieldTypes,\n )\n const select = fieldsToSelectJSONSchema({ fields: entity.fields })\n\n if (type === 'global') {\n select.properties.globalType = {\n type: 'boolean',\n }\n }\n\n acc[`${entity.slug}_select`] = {\n type: 'object',\n additionalProperties: false,\n ...select,\n }\n\n return acc\n },\n {},\n )\n\n const authOperationDefinitions = [...config.collections]\n .filter(({ auth }) => Boolean(auth))\n .reduce(\n (acc, authCollection) => {\n acc.auth[authCollection.slug] = authCollectionToOperationsJSONSchema(authCollection)\n return acc\n },\n { auth: {} },\n )\n\n const jobsSchemas = config.jobs\n ? generateJobsJSONSchemas(config, config.jobs, interfaceNameDefinitions, collectionIDFieldTypes)\n : {}\n\n let jsonSchema: JSONSchema4 = {\n additionalProperties: false,\n definitions: {\n ...entityDefinitions,\n ...Object.fromEntries(interfaceNameDefinitions),\n ...authOperationDefinitions,\n },\n // These properties here will be very simple, as all the complexity is in the definitions. These are just the properties for the top-level `Config` type\n type: 'object',\n properties: {\n auth: generateAuthOperationSchemas(config.collections),\n collections: generateEntitySchemas(config.collections || []),\n collectionsSelect: generateEntitySelectSchemas(config.collections || []),\n db: generateDbEntitySchema(config),\n globals: generateEntitySchemas(config.globals || []),\n globalsSelect: generateEntitySelectSchemas(config.globals || []),\n locale: generateLocaleEntitySchemas(config.localization),\n user: generateAuthEntitySchemas(config.collections),\n },\n required: [\n 'user',\n 'locale',\n 'collections',\n 'collectionsSelect',\n 'globalsSelect',\n 'globals',\n 'auth',\n 'db',\n ],\n title: 'Config',\n }\n if (jobsSchemas.definitions?.size) {\n for (const [key, value] of jobsSchemas.definitions) {\n jsonSchema.definitions[key] = value\n }\n }\n if (jobsSchemas.properties) {\n jsonSchema.properties.jobs = {\n type: 'object',\n additionalProperties: false,\n properties: jobsSchemas.properties,\n required: ['tasks'],\n }\n }\n\n if (config?.typescript?.schema?.length) {\n for (const schema of config.typescript.schema) {\n jsonSchema = schema({ jsonSchema })\n }\n }\n\n return jsonSchema\n}\n"],"names":["pluralize","singular","MissingEditorProp","fieldAffectsData","tabHasName","generateJobsJSONSchemas","deepCopyObject","toWords","getCollectionIDFieldTypes","fieldIsRequired","field","isConditional","Boolean","admin","condition","isMarkedRequired","required","type","fields","some","subField","tabs","tab","buildOptionEnums","options","map","option","value","generateEntitySchemas","entities","properties","reduce","acc","slug","$ref","additionalProperties","Object","keys","generateEntitySelectSchemas","generateLocaleEntitySchemas","localization","locales","localesFromConfig","locale","code","enum","generateAuthEntitySchemas","filter","auth","allOf","collection","oneOf","generateDbEntitySchema","config","defaultIDType","db","withNullableJSONSchemaType","fieldType","isRequired","fieldTypes","push","fieldsToJSONSchema","collectionIDFieldTypes","interfaceNameDefinitions","requiredFieldNames","Set","fromEntries","fieldSchemas","add","name","fieldSchema","hasMany","items","jsonSchema","schema","editor","Error","outputSchema","optionEnums","length","maxItems","minItems","docs","hasNextPage","Array","isArray","relationTo","relation","const","hasBlocks","blocks","block","blockFieldSchemas","blockSchema","blockType","interfaceName","set","childSchema","entries","forEach","propName","propSchema","hasRequiredFields","typescriptSchema","Map","from","entityToJSONSchema","incomingEntity","entity","title","typescript","interface","idField","customIdField","find","unshift","timestamps","disableLocalStrategy","fieldsToSelectJSONSchema","blocksSchema","generateAuthFieldTypes","loginWithUsername","allowEmailLogin","email","password","username","requiredFields","requireEmail","requireUsername","authCollectionToOperationsJSONSchema","loginUserFields","forgotOrUnlockUserFields","registerUserFields","forgotPassword","login","registerFirstUser","unlock","generateAuthOperationSchemas","collections","configToJSONSchema","globals","global","entityDefinitions","select","globalType","authOperationDefinitions","authCollection","jobsSchemas","jobs","definitions","collectionsSelect","globalsSelect","user","size","key"],"mappings":"AAEA,OAAOA,eAAe,YAAW;AACjC,MAAM,EAAEC,QAAQ,EAAE,GAAGD;AAQrB,SAASE,iBAAiB,QAAQ,iCAAgC;AAClE,SAASC,gBAAgB,EAAEC,UAAU,QAAQ,4BAA2B;AACxE,SAASC,uBAAuB,QAAQ,8CAA6C;AACrF,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,OAAO,QAAQ,oBAAmB;AAC3C,SAASC,yBAAyB,QAAQ,iCAAgC;AAE1E,MAAMC,kBAAkB,CAACC;IACvB,MAAMC,gBAAgBC,QAAQF,OAAOG,SAASH,OAAOG,OAAOC;IAC5D,IAAIH,eAAe;QACjB,OAAO;IACT;IAEA,MAAMI,mBAAmB,cAAcL,SAASA,MAAMM,QAAQ,KAAK;IACnE,IAAIb,iBAAiBO,UAAUK,kBAAkB;QAC/C,OAAO;IACT;IAEA,wDAAwD;IACxD,IAAI,YAAYL,SAASA,MAAMO,IAAI,KAAK,SAAS;QAC/C,OAAOP,MAAMQ,MAAM,CAACC,IAAI,CAAC,CAACC,WAAaX,gBAAgBW;IACzD;IAEA,oEAAoE;IACpE,IAAIV,MAAMO,IAAI,KAAK,QAAQ;QACzB,OAAOP,MAAMW,IAAI,CAACF,IAAI,CAAC,CAACG;YACtB,IAAI,U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AAO,MAAM,iBAAiB,gBAAiB,WAAW,KAAG,MAE5D,CAAA;AAED,eAAO,MAAM,mBAAmB,YACrB,OAAO,KACf,IAAI,CAAC,SAAS,EAAE,SAAS,GAAG,2BAA2B,GAAG,qBAAqB,CAcjF,CAAA"}
|
|
@@ -13,6 +13,7 @@ export const sendEvent = async ({ event, payload })=>{
|
|
|
13
13
|
const { packageJSON, packageJSONPath } = await getPackageJSON();
|
|
14
14
|
// Only generate the base event once
|
|
15
15
|
if (!baseEvent) {
|
|
16
|
+
const { projectID, source: projectIDSource } = getProjectID(payload, packageJSON);
|
|
16
17
|
baseEvent = {
|
|
17
18
|
ciName: ciInfo.isCI ? ciInfo.name : null,
|
|
18
19
|
envID: getEnvID(),
|
|
@@ -20,7 +21,8 @@ export const sendEvent = async ({ event, payload })=>{
|
|
|
20
21
|
nodeEnv: process.env.NODE_ENV || 'development',
|
|
21
22
|
nodeVersion: process.version,
|
|
22
23
|
payloadVersion: getPayloadVersion(packageJSON),
|
|
23
|
-
projectID
|
|
24
|
+
projectID,
|
|
25
|
+
projectIDSource,
|
|
24
26
|
...getLocalizationInfo(payload),
|
|
25
27
|
dbAdapter: payload.db.name,
|
|
26
28
|
emailAdapter: payload.email?.name || null,
|
|
@@ -69,8 +71,32 @@ export const sendEvent = async ({ event, payload })=>{
|
|
|
69
71
|
return generated;
|
|
70
72
|
};
|
|
71
73
|
const getProjectID = (payload, packageJSON)=>{
|
|
72
|
-
const
|
|
73
|
-
|
|
74
|
+
const gitID = getGitID(payload);
|
|
75
|
+
if (gitID) {
|
|
76
|
+
return {
|
|
77
|
+
projectID: oneWayHash(gitID, payload.secret),
|
|
78
|
+
source: 'git'
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
const packageJSONID = getPackageJSONID(payload, packageJSON);
|
|
82
|
+
if (packageJSONID) {
|
|
83
|
+
return {
|
|
84
|
+
projectID: oneWayHash(packageJSONID, payload.secret),
|
|
85
|
+
source: 'packageJSON'
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
const serverURL = payload.config.serverURL;
|
|
89
|
+
if (serverURL) {
|
|
90
|
+
return {
|
|
91
|
+
projectID: oneWayHash(serverURL, payload.secret),
|
|
92
|
+
source: 'serverURL'
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
const cwd = process.cwd();
|
|
96
|
+
return {
|
|
97
|
+
projectID: oneWayHash(cwd, payload.secret),
|
|
98
|
+
source: 'cwd'
|
|
99
|
+
};
|
|
74
100
|
};
|
|
75
101
|
const getGitID = (payload)=>{
|
|
76
102
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/utilities/telemetry/index.ts"],"sourcesContent":["import { execSync } from 'child_process'\nimport ciInfo from 'ci-info'\nimport { randomBytes } from 'crypto'\nimport fs from 'fs'\nimport path from 'path'\nimport { fileURLToPath } from 'url'\n\nimport type { Payload } from '../../types/index.js'\nimport type { AdminInitEvent } from './events/adminInit.js'\nimport type { ServerInitEvent } from './events/serverInit.js'\n\nimport { findUp } from '../findUp.js'\nimport { Conf } from './conf/index.js'\nimport { oneWayHash } from './oneWayHash.js'\n\nexport type BaseEvent = {\n ciName: null | string\n dbAdapter: string\n emailAdapter: null | string\n envID: string\n isCI: boolean\n locales: string[]\n localizationDefaultLocale: null | string\n localizationEnabled: boolean\n nodeEnv: string\n nodeVersion: string\n payloadVersion: string\n projectID: string\n uploadAdapters: string[]\n}\n\ntype PackageJSON = {\n dependencies: Record<string, string | undefined>\n name: string\n}\n\ntype TelemetryEvent = AdminInitEvent | ServerInitEvent\n\ntype Args = {\n event: TelemetryEvent\n payload: Payload\n}\n\nlet baseEvent: BaseEvent | null = null\n\nexport const sendEvent = async ({ event, payload }: Args): Promise<void> => {\n try {\n const { packageJSON, packageJSONPath } = await getPackageJSON()\n\n // Only generate the base event once\n if (!baseEvent) {\n baseEvent = {\n ciName: ciInfo.isCI ? ciInfo.name : null,\n envID: getEnvID(),\n isCI: ciInfo.isCI,\n nodeEnv: process.env.NODE_ENV || 'development',\n nodeVersion: process.version,\n payloadVersion: getPayloadVersion(packageJSON),\n projectID
|
|
1
|
+
{"version":3,"sources":["../../../src/utilities/telemetry/index.ts"],"sourcesContent":["import { execSync } from 'child_process'\nimport ciInfo from 'ci-info'\nimport { randomBytes } from 'crypto'\nimport fs from 'fs'\nimport path from 'path'\nimport { fileURLToPath } from 'url'\n\nimport type { Payload } from '../../types/index.js'\nimport type { AdminInitEvent } from './events/adminInit.js'\nimport type { ServerInitEvent } from './events/serverInit.js'\n\nimport { findUp } from '../findUp.js'\nimport { Conf } from './conf/index.js'\nimport { oneWayHash } from './oneWayHash.js'\n\nexport type BaseEvent = {\n ciName: null | string\n dbAdapter: string\n emailAdapter: null | string\n envID: string\n isCI: boolean\n locales: string[]\n localizationDefaultLocale: null | string\n localizationEnabled: boolean\n nodeEnv: string\n nodeVersion: string\n payloadVersion: string\n projectID: string\n projectIDSource: 'cwd' | 'git' | 'packageJSON' | 'serverURL'\n uploadAdapters: string[]\n}\n\ntype PackageJSON = {\n dependencies: Record<string, string | undefined>\n name: string\n}\n\ntype TelemetryEvent = AdminInitEvent | ServerInitEvent\n\ntype Args = {\n event: TelemetryEvent\n payload: Payload\n}\n\nlet baseEvent: BaseEvent | null = null\n\nexport const sendEvent = async ({ event, payload }: Args): Promise<void> => {\n try {\n const { packageJSON, packageJSONPath } = await getPackageJSON()\n\n // Only generate the base event once\n if (!baseEvent) {\n const { projectID, source: projectIDSource } = getProjectID(payload, packageJSON)\n baseEvent = {\n ciName: ciInfo.isCI ? ciInfo.name : null,\n envID: getEnvID(),\n isCI: ciInfo.isCI,\n nodeEnv: process.env.NODE_ENV || 'development',\n nodeVersion: process.version,\n payloadVersion: getPayloadVersion(packageJSON),\n projectID,\n projectIDSource,\n ...getLocalizationInfo(payload),\n dbAdapter: payload.db.name,\n emailAdapter: payload.email?.name || null,\n uploadAdapters: payload.config.upload.adapters,\n }\n }\n\n if (process.env.PAYLOAD_TELEMETRY_DEBUG) {\n payload.logger.info({\n event: { ...baseEvent, ...event, packageJSONPath },\n msg: 'Telemetry Event',\n })\n return\n }\n\n if (payload.config.telemetry !== false) {\n await fetch('https://telemetry.payloadcms.com/events', {\n body: JSON.stringify({ ...baseEvent, ...event }),\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'post',\n })\n }\n } catch (_) {\n // Eat any errors in sending telemetry event\n }\n}\n\n/**\n * This is a quasi-persistent identifier used to dedupe recurring events. It's\n * generated from random data and completely anonymous.\n */\nconst getEnvID = (): string => {\n const conf = new Conf()\n const ENV_ID = 'envID'\n\n const val = conf.get(ENV_ID)\n if (val) {\n return val as string\n }\n\n const generated = randomBytes(32).toString('hex')\n conf.set(ENV_ID, generated)\n return generated\n}\n\nconst getProjectID = (\n payload: Payload,\n packageJSON: PackageJSON,\n): { projectID: string; source: BaseEvent['projectIDSource'] } => {\n const gitID = getGitID(payload)\n if (gitID) {\n return { projectID: oneWayHash(gitID, payload.secret), source: 'git' }\n }\n\n const packageJSONID = getPackageJSONID(payload, packageJSON)\n if (packageJSONID) {\n return { projectID: oneWayHash(packageJSONID, payload.secret), source: 'packageJSON' }\n }\n\n const serverURL = payload.config.serverURL\n if (serverURL) {\n return { projectID: oneWayHash(serverURL, payload.secret), source: 'serverURL' }\n }\n\n const cwd = process.cwd()\n return { projectID: oneWayHash(cwd, payload.secret), source: 'cwd' }\n}\n\nconst getGitID = (payload: Payload) => {\n try {\n const originBuffer = execSync('git config --local --get remote.origin.url', {\n stdio: 'pipe',\n timeout: 1000,\n })\n\n return oneWayHash(String(originBuffer).trim(), payload.secret)\n } catch (_) {\n return null\n }\n}\n\nconst getPackageJSON = async (): Promise<{\n packageJSON?: PackageJSON\n packageJSONPath: string\n}> => {\n let packageJSONPath = path.resolve(process.cwd(), 'package.json')\n\n if (!fs.existsSync(packageJSONPath)) {\n // Old logic\n const filename = fileURLToPath(import.meta.url)\n const dirname = path.dirname(filename)\n packageJSONPath = await findUp({\n dir: dirname,\n fileNames: ['package.json'],\n })\n }\n\n const jsonContentString = await fs.promises.readFile(packageJSONPath, 'utf-8')\n const jsonContent: PackageJSON = JSON.parse(jsonContentString)\n return { packageJSON: jsonContent, packageJSONPath }\n}\n\nconst getPackageJSONID = (payload: Payload, packageJSON: PackageJSON): string => {\n return oneWayHash(packageJSON.name, payload.secret)\n}\n\nexport const getPayloadVersion = (packageJSON: PackageJSON): string => {\n return packageJSON?.dependencies?.payload ?? ''\n}\n\nexport const getLocalizationInfo = (\n payload: Payload,\n): Pick<BaseEvent, 'locales' | 'localizationDefaultLocale' | 'localizationEnabled'> => {\n if (!payload.config.localization) {\n return {\n locales: [],\n localizationDefaultLocale: null,\n localizationEnabled: false,\n }\n }\n\n return {\n locales: payload.config.localization.localeCodes,\n localizationDefaultLocale: payload.config.localization.defaultLocale,\n localizationEnabled: true,\n }\n}\n"],"names":["execSync","ciInfo","randomBytes","fs","path","fileURLToPath","findUp","Conf","oneWayHash","baseEvent","sendEvent","event","payload","packageJSON","packageJSONPath","getPackageJSON","projectID","source","projectIDSource","getProjectID","ciName","isCI","name","envID","getEnvID","nodeEnv","process","env","NODE_ENV","nodeVersion","version","payloadVersion","getPayloadVersion","getLocalizationInfo","dbAdapter","db","emailAdapter","email","uploadAdapters","config","upload","adapters","PAYLOAD_TELEMETRY_DEBUG","logger","info","msg","telemetry","fetch","body","JSON","stringify","headers","method","_","conf","ENV_ID","val","get","generated","toString","set","gitID","getGitID","secret","packageJSONID","getPackageJSONID","serverURL","cwd","originBuffer","stdio","timeout","String","trim","resolve","existsSync","filename","url","dirname","dir","fileNames","jsonContentString","promises","readFile","jsonContent","parse","dependencies","localization","locales","localizationDefaultLocale","localizationEnabled","localeCodes","defaultLocale"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,gBAAe;AACxC,OAAOC,YAAY,UAAS;AAC5B,SAASC,WAAW,QAAQ,SAAQ;AACpC,OAAOC,QAAQ,KAAI;AACnB,OAAOC,UAAU,OAAM;AACvB,SAASC,aAAa,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AAI,CAAChE,GAAGuE,UAAU,CAAC5D,kBAAkB;QACnC,YAAY;QACZ,MAAM6D,WAAWtE,cAAc,YAAYuE,GAAG;QAC9C,MAAMC,UAAUzE,KAAKyE,OAAO,CAACF;QAC7B7D,kBAAkB,MAAMR,OAAO;YAC7BwE,KAAKD;YACLE,WAAW;gBAAC;aAAe;QAC7B;IACF;IAEA,MAAMC,oBAAoB,MAAM7E,GAAG8E,QAAQ,CAACC,QAAQ,CAACpE,iBAAiB;IACtE,MAAMqE,cAA2BlC,KAAKmC,KAAK,CAACJ;IAC5C,OAAO;QAAEnE,aAAasE;QAAarE;IAAgB;AACrD;AAEA,MAAMmD,mBAAmB,CAACrD,SAAkBC;IAC1C,OAAOL,WAAWK,YAAYS,IAAI,EAAEV,QAAQmD,MAAM;AACpD;AAEA,OAAO,MAAM/B,oBAAoB,CAACnB;IAChC,OAAOA,aAAawE,cAAczE,WAAW;AAC/C,EAAC;AAED,OAAO,MAAMqB,sBAAsB,CACjCrB;IAEA,IAAI,CAACA,QAAQ2B,MAAM,CAAC+C,YAAY,EAAE;QAChC,OAAO;YACLC,SAAS,EAAE;YACXC,2BAA2B;YAC3BC,qBAAqB;QACvB;IACF;IAEA,OAAO;QACLF,SAAS3E,QAAQ2B,MAAM,CAAC+C,YAAY,CAACI,WAAW;QAChDF,2BAA2B5E,QAAQ2B,MAAM,CAAC+C,YAAY,CAACK,aAAa;QACpEF,qBAAqB;IACvB;AACF,EAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "payload",
|
|
3
|
-
"version": "3.0.0-beta.
|
|
3
|
+
"version": "3.0.0-beta.124",
|
|
4
4
|
"description": "Node, React, Headless CMS and Application Framework built on Next.js",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"admin panel",
|
|
@@ -96,7 +96,7 @@
|
|
|
96
96
|
"ts-essentials": "10.0.2",
|
|
97
97
|
"tsx": "4.19.1",
|
|
98
98
|
"uuid": "10.0.0",
|
|
99
|
-
"@payloadcms/translations": "3.0.0-beta.
|
|
99
|
+
"@payloadcms/translations": "3.0.0-beta.124"
|
|
100
100
|
},
|
|
101
101
|
"devDependencies": {
|
|
102
102
|
"@hyrious/esbuild-plugin-commonjs": "^0.2.4",
|