@payloadcms/plugin-mcp 4.0.0-internal.532221d → 4.0.0-internal.567a487
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/mcp/builtin/collections/createTool.js +2 -1
- package/dist/mcp/builtin/collections/createTool.js.map +1 -1
- package/dist/mcp/builtin/collections/duplicateTool.js +2 -1
- package/dist/mcp/builtin/collections/duplicateTool.js.map +1 -1
- package/dist/mcp/builtin/collections/formatCollectionError.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/formatCollectionError.js +1 -1
- package/dist/mcp/builtin/collections/formatCollectionError.js.map +1 -1
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.d.ts.map +1 -1
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.js +2 -1
- package/dist/mcp/builtin/collections/getCollectionSchemaTool.js.map +1 -1
- package/dist/mcp/builtin/collections/updateTool.js +3 -1
- package/dist/mcp/builtin/collections/updateTool.js.map +1 -1
- package/dist/mcp/builtin/globals/getGlobalSchemaTool.d.ts.map +1 -1
- package/dist/mcp/builtin/globals/getGlobalSchemaTool.js +2 -1
- package/dist/mcp/builtin/globals/getGlobalSchemaTool.js.map +1 -1
- package/dist/mcp/builtin/globals/updateTool.js +2 -1
- package/dist/mcp/builtin/globals/updateTool.js.map +1 -1
- package/dist/mcp/builtin/validateEntityData.d.ts.map +1 -1
- package/dist/mcp/builtin/validateEntityData.js +1 -1
- package/dist/mcp/builtin/validateEntityData.js.map +1 -1
- package/dist/utils/getVirtualFieldNames.d.ts +14 -0
- package/dist/utils/getVirtualFieldNames.d.ts.map +1 -0
- package/dist/utils/getVirtualFieldNames.js +35 -0
- package/dist/utils/getVirtualFieldNames.js.map +1 -0
- package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts +28 -0
- package/dist/utils/schemaConversion/filterFieldsByAccess.d.ts.map +1 -0
- package/dist/utils/schemaConversion/filterFieldsByAccess.js +71 -0
- package/dist/utils/schemaConversion/filterFieldsByAccess.js.map +1 -0
- package/dist/utils/schemaConversion/getEntityInputSchema.d.ts +13 -0
- package/dist/utils/schemaConversion/getEntityInputSchema.d.ts.map +1 -0
- package/dist/utils/schemaConversion/getEntityInputSchema.js +66 -0
- package/dist/utils/schemaConversion/getEntityInputSchema.js.map +1 -0
- package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts +10 -0
- package/dist/utils/schemaConversion/sanitizeEntitySchema.d.ts.map +1 -0
- package/dist/utils/schemaConversion/sanitizeEntitySchema.js +384 -0
- package/dist/utils/schemaConversion/sanitizeEntitySchema.js.map +1 -0
- package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js +133 -0
- package/dist/utils/schemaConversion/sanitizeEntitySchema.spec.js.map +1 -0
- package/dist/utils/transformPointDataToPayload.d.ts +7 -0
- package/dist/utils/transformPointDataToPayload.d.ts.map +1 -0
- package/dist/utils/transformPointDataToPayload.js +28 -0
- package/dist/utils/transformPointDataToPayload.js.map +1 -0
- package/package.json +3 -3
- package/src/mcp/builtin/collections/createTool.ts +5 -5
- package/src/mcp/builtin/collections/duplicateTool.ts +5 -5
- package/src/mcp/builtin/collections/formatCollectionError.ts +2 -2
- package/src/mcp/builtin/collections/getCollectionSchemaTool.ts +2 -1
- package/src/mcp/builtin/collections/updateTool.ts +6 -6
- package/src/mcp/builtin/globals/getGlobalSchemaTool.ts +2 -1
- package/src/mcp/builtin/globals/updateTool.ts +5 -5
- package/src/mcp/builtin/validateEntityData.ts +7 -3
- package/src/utils/getVirtualFieldNames.ts +53 -0
- package/src/utils/schemaConversion/filterFieldsByAccess.ts +123 -0
- package/src/utils/schemaConversion/getEntityInputSchema.ts +96 -0
- package/src/utils/schemaConversion/sanitizeEntitySchema.spec.ts +96 -0
- package/src/utils/schemaConversion/sanitizeEntitySchema.ts +432 -0
- package/src/utils/transformPointDataToPayload.ts +40 -0
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { getCollectionVirtualFieldNames, stripVirtualFields, transformPointDataToPayload } from 'payload';
|
|
2
1
|
import { z } from 'zod';
|
|
3
2
|
import { defaultAccess } from '../../../defaultAccess.js';
|
|
4
3
|
import { defineCollectionTool } from '../../../defineTool.js';
|
|
5
4
|
import { getLogger } from '../../../utils/getLogger.js';
|
|
5
|
+
import { getCollectionVirtualFieldNames, stripVirtualFields } from '../../../utils/getVirtualFieldNames.js';
|
|
6
|
+
import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js';
|
|
6
7
|
import { validateCollectionData } from '../validateEntityData.js';
|
|
7
8
|
import { fileInputSchema, resolveFile } from './fileInput.js';
|
|
8
9
|
import { formatCollectionError } from './formatCollectionError.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/mcp/builtin/collections/createTool.ts"],"sourcesContent":["import type { SelectType } from 'payload'\n\nimport {\n getCollectionVirtualFieldNames,\n stripVirtualFields,\n transformPointDataToPayload,\n} from 'payload'\nimport { z } from 'zod'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport { validateCollectionData } from '../validateEntityData.js'\nimport { fileInputSchema, resolveFile } from './fileInput.js'\nimport { formatCollectionError } from './formatCollectionError.js'\n\nconst DEFAULT_DESCRIPTION =\n 'Create one or more documents. Each can have different data or a file. Prefer uploadReference after upload, externalURL for URLs, or base64 for small local files.'\n\nexport const createDocumentsTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.create),\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Create Documents',\n },\n description: DEFAULT_DESCRIPTION,\n input: z.object({\n depth: z\n .number()\n .int()\n .min(0)\n .max(10)\n .describe('How many levels deep to populate relationships in response')\n .optional()\n .default(0),\n documents: z\n .array(\n z.object({\n data: z\n .record(z.string(), z.unknown())\n .describe(\n 'The document fields to create. Only include fields permitted by the schema returned by getCollectionSchema.',\n ),\n file: fileInputSchema.optional(),\n }),\n )\n .min(1)\n .describe('The documents to create, in order'),\n draft: z\n .boolean()\n .describe(\n 'Only if getCollectionSchema includes _status; otherwise _status does not exist. true forces data._status to \"draft\"; with false, data._status controls draft or published.',\n )\n .optional()\n .default(false),\n fallbackLocale: z\n .string()\n .describe('Optional: fallback locale code to use when requested locale is not available')\n .optional(),\n locale: z\n .string()\n .describe(\n 'Optional: locale code to create the documents in (e.g., \"en\", \"es\"). Defaults to the default locale',\n )\n .optional(),\n select: z\n .record(z.string(), z.unknown())\n .describe(\n 'Optional: define exactly which fields you\\'d like to return, e.g., {\"title\": true}',\n )\n .optional(),\n }),\n}).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n const { depth, documents, draft, fallbackLocale, locale, select } = input\n\n logger.info(`Creating ${documents.length} documents in collection: ${collectionSlug}`)\n\n try {\n const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug)\n const docs: Array<{ doc: Record<string, unknown>; index: number }> = []\n const errors: Array<{ index: number; message: string }> = []\n let validationSchema: Record<string, unknown> | undefined\n\n for (const [index, document] of documents.entries()) {\n try {\n const inputData = stripVirtualFields(document.data, virtualFieldNames)\n const validationError = validateCollectionData({ collectionSlug, data: inputData, req })\n\n if (validationError) {\n const firstContent = validationError.content[0]\n const validationContent = validationError.structuredContent as\n | Record<string, unknown>\n | undefined\n const schema = validationContent?.schema\n\n if (!validationSchema && schema && typeof schema === 'object') {\n validationSchema = schema as Record<string, unknown>\n }\n\n errors.push({\n index,\n message:\n firstContent?.type === 'text'\n ? (firstContent.text.split('\\n\\nUse this schema')[0] ?? 'Invalid document data')\n : 'Invalid document data',\n })\n continue\n }\n\n const parsedData = transformPointDataToPayload(inputData)\n const file = await resolveFile({ collectionSlug, input: document.file, req })\n const result = await payload.create({\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n ...(file ? { file } : {}),\n ...(locale ? { locale } : {}),\n ...(fallbackLocale ? { fallbackLocale } : {}),\n ...(select ? { select: select as SelectType } : {}),\n })\n\n docs.push({ doc: result as Record<string, unknown>, index })\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error'\n\n logger.error(`Error creating document at index ${index} in ${collectionSlug}: ${message}`)\n errors.push({ index, message })\n }\n }\n\n const batchResult = { docs, errors }\n const retryMessage = errors.length > 0 ? '\\nRetry failed indexes only.' : ''\n const schemaMessage = validationSchema\n ? `\\n\\nUse this schema for data:\\n\\`\\`\\`json\\n${JSON.stringify(validationSchema)}\\n\\`\\`\\``\n : ''\n const structuredContent = validationSchema\n ? { ...batchResult, schema: validationSchema }\n : batchResult\n\n logger.info(`Created ${docs.length} of ${documents.length} documents in ${collectionSlug}`)\n\n return {\n content: [\n {\n type: 'text',\n text: `Created ${docs.length} of ${documents.length} documents in collection \"${collectionSlug}\".${retryMessage}\\nResults:\\n\\`\\`\\`json\\n${JSON.stringify(batchResult)}\\n\\`\\`\\`${schemaMessage}`,\n },\n ],\n doc: structuredContent as unknown as Record<string, unknown>,\n isError: docs.length === 0 && errors.length > 0,\n structuredContent,\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error'\n\n logger.error(`Error creating documents in ${collectionSlug}: ${message}`)\n return formatCollectionError({ action: 'creating', collectionSlug, error, req })\n }\n})\n"],"names":["getCollectionVirtualFieldNames","stripVirtualFields","transformPointDataToPayload","z","defaultAccess","defineCollectionTool","getLogger","validateCollectionData","fileInputSchema","resolveFile","formatCollectionError","DEFAULT_DESCRIPTION","createDocumentsTool","access","args","Boolean","permissions","collections","collectionSlug","create","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","object","depth","number","int","min","max","describe","optional","default","documents","array","data","record","string","unknown","file","draft","boolean","fallbackLocale","locale","select","handler","authorizedMCP","req","payload","logger","info","length","virtualFieldNames","config","docs","errors","validationSchema","index","document","entries","inputData","validationError","firstContent","content","validationContent","structuredContent","schema","push","message","type","text","split","parsedData","result","collection","overrideAccess","doc","error","Error","batchResult","retryMessage","schemaMessage","JSON","stringify","isError","action"],"mappings":"AAEA,SACEA,8BAA8B,EAC9BC,kBAAkB,EAClBC,2BAA2B,QACtB,UAAS;AAChB,SAASC,CAAC,QAAQ,MAAK;AAEvB,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SAASC,sBAAsB,QAAQ,2BAA0B;AACjE,SAASC,eAAe,EAAEC,WAAW,QAAQ,iBAAgB;AAC7D,SAASC,qBAAqB,QAAQ,6BAA4B;AAElE,MAAMC,sBACJ;AAEF,OAAO,MAAMC,sBAAsBP,qBAAqB;IACtDQ,QAAQ,CAACC,OACPV,cAAcU,SAASC,QAAQD,KAAKE,WAAW,EAAEC,aAAa,CAACH,KAAKI,cAAc,CAAC,EAAEC;IACvFC,aAAa;QACXC,iBAAiB;QACjBC,gBAAgB;QAChBC,eAAe;QACfC,cAAc;QACdC,OAAO;IACT;IACAC,aAAaf;IACbgB,OAAOxB,EAAEyB,MAAM,CAAC;QACdC,OAAO1B,EACJ2B,MAAM,GACNC,GAAG,GACHC,GAAG,CAAC,GACJC,GAAG,CAAC,IACJC,QAAQ,CAAC,8DACTC,QAAQ,GACRC,OAAO,CAAC;QACXC,WAAWlC,EACRmC,KAAK,CACJnC,EAAEyB,MAAM,CAAC;YACPW,MAAMpC,EACHqC,MAAM,CAACrC,EAAEsC,MAAM,IAAItC,EAAEuC,OAAO,IAC5BR,QAAQ,CACP;YAEJS,MAAMnC,gBAAgB2B,QAAQ;QAChC,IAEDH,GAAG,CAAC,GACJE,QAAQ,CAAC;QACZU,OAAOzC,EACJ0C,OAAO,GACPX,QAAQ,CACP,8KAEDC,QAAQ,GACRC,OAAO,CAAC;QACXU,gBAAgB3C,EACbsC,MAAM,GACNP,QAAQ,CAAC,gFACTC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ElB,UAAUkB,MAAM,CAAC,cAAc,EAAErC,gBAAgB;QAE1F,OAAO;YACLiD,SAAS;gBACP;oBACEM,MAAM;oBACNC,MAAM,CAAC,QAAQ,EAAEhB,KAAKH,MAAM,CAAC,IAAI,EAAElB,UAAUkB,MAAM,CAAC,0BAA0B,EAAErC,eAAe,EAAE,EAAEkE,aAAa,wBAAwB,EAAEE,KAAKC,SAAS,CAACJ,aAAa,QAAQ,EAAEE,eAAe;gBACjM;aACD;YACDL,KAAKX;YACLmB,SAAS9B,KAAKH,MAAM,KAAK,KAAKI,OAAOJ,MAAM,GAAG;YAC9Cc;QACF;IACF,EAAE,OAAOY,OAAO;QACd,MAAMT,UAAUS,iBAAiBC,QAAQD,MAAMT,OAAO,GAAG;QAEzDnB,OAAO4B,KAAK,CAAC,CAAC,4BAA4B,EAAE/D,eAAe,EAAE,EAAEsD,SAAS;QACxE,OAAO9D,sBAAsB;YAAE+E,QAAQ;YAAYvE;YAAgB+D;YAAO9B;QAAI;IAChF;AACF,GAAE"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/mcp/builtin/collections/createTool.ts"],"sourcesContent":["import type { SelectType } from 'payload'\n\nimport { z } from 'zod'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport {\n getCollectionVirtualFieldNames,\n stripVirtualFields,\n} from '../../../utils/getVirtualFieldNames.js'\nimport { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'\nimport { validateCollectionData } from '../validateEntityData.js'\nimport { fileInputSchema, resolveFile } from './fileInput.js'\nimport { formatCollectionError } from './formatCollectionError.js'\n\nconst DEFAULT_DESCRIPTION =\n 'Create one or more documents. Each can have different data or a file. Prefer uploadReference after upload, externalURL for URLs, or base64 for small local files.'\n\nexport const createDocumentsTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.create),\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Create Documents',\n },\n description: DEFAULT_DESCRIPTION,\n input: z.object({\n depth: z\n .number()\n .int()\n .min(0)\n .max(10)\n .describe('How many levels deep to populate relationships in response')\n .optional()\n .default(0),\n documents: z\n .array(\n z.object({\n data: z\n .record(z.string(), z.unknown())\n .describe(\n 'The document fields to create. Only include fields permitted by the schema returned by getCollectionSchema.',\n ),\n file: fileInputSchema.optional(),\n }),\n )\n .min(1)\n .describe('The documents to create, in order'),\n draft: z\n .boolean()\n .describe(\n 'Only if getCollectionSchema includes _status; otherwise _status does not exist. true forces data._status to \"draft\"; with false, data._status controls draft or published.',\n )\n .optional()\n .default(false),\n fallbackLocale: z\n .string()\n .describe('Optional: fallback locale code to use when requested locale is not available')\n .optional(),\n locale: z\n .string()\n .describe(\n 'Optional: locale code to create the documents in (e.g., \"en\", \"es\"). Defaults to the default locale',\n )\n .optional(),\n select: z\n .record(z.string(), z.unknown())\n .describe(\n 'Optional: define exactly which fields you\\'d like to return, e.g., {\"title\": true}',\n )\n .optional(),\n }),\n}).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n const { depth, documents, draft, fallbackLocale, locale, select } = input\n\n logger.info(`Creating ${documents.length} documents in collection: ${collectionSlug}`)\n\n try {\n const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug)\n const docs: Array<{ doc: Record<string, unknown>; index: number }> = []\n const errors: Array<{ index: number; message: string }> = []\n let validationSchema: Record<string, unknown> | undefined\n\n for (const [index, document] of documents.entries()) {\n try {\n const inputData = stripVirtualFields(document.data, virtualFieldNames)\n const validationError = validateCollectionData({ collectionSlug, data: inputData, req })\n\n if (validationError) {\n const firstContent = validationError.content[0]\n const validationContent = validationError.structuredContent as\n | Record<string, unknown>\n | undefined\n const schema = validationContent?.schema\n\n if (!validationSchema && schema && typeof schema === 'object') {\n validationSchema = schema as Record<string, unknown>\n }\n\n errors.push({\n index,\n message:\n firstContent?.type === 'text'\n ? (firstContent.text.split('\\n\\nUse this schema')[0] ?? 'Invalid document data')\n : 'Invalid document data',\n })\n continue\n }\n\n const parsedData = transformPointDataToPayload(inputData)\n const file = await resolveFile({ collectionSlug, input: document.file, req })\n const result = await payload.create({\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n ...(file ? { file } : {}),\n ...(locale ? { locale } : {}),\n ...(fallbackLocale ? { fallbackLocale } : {}),\n ...(select ? { select: select as SelectType } : {}),\n })\n\n docs.push({ doc: result as Record<string, unknown>, index })\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error'\n\n logger.error(`Error creating document at index ${index} in ${collectionSlug}: ${message}`)\n errors.push({ index, message })\n }\n }\n\n const batchResult = { docs, errors }\n const retryMessage = errors.length > 0 ? '\\nRetry failed indexes only.' : ''\n const schemaMessage = validationSchema\n ? `\\n\\nUse this schema for data:\\n\\`\\`\\`json\\n${JSON.stringify(validationSchema)}\\n\\`\\`\\``\n : ''\n const structuredContent = validationSchema\n ? { ...batchResult, schema: validationSchema }\n : batchResult\n\n logger.info(`Created ${docs.length} of ${documents.length} documents in ${collectionSlug}`)\n\n return {\n content: [\n {\n type: 'text',\n text: `Created ${docs.length} of ${documents.length} documents in collection \"${collectionSlug}\".${retryMessage}\\nResults:\\n\\`\\`\\`json\\n${JSON.stringify(batchResult)}\\n\\`\\`\\`${schemaMessage}`,\n },\n ],\n doc: structuredContent as unknown as Record<string, unknown>,\n isError: docs.length === 0 && errors.length > 0,\n structuredContent,\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error'\n\n logger.error(`Error creating documents in ${collectionSlug}: ${message}`)\n return formatCollectionError({ action: 'creating', collectionSlug, error, req })\n }\n})\n"],"names":["z","defaultAccess","defineCollectionTool","getLogger","getCollectionVirtualFieldNames","stripVirtualFields","transformPointDataToPayload","validateCollectionData","fileInputSchema","resolveFile","formatCollectionError","DEFAULT_DESCRIPTION","createDocumentsTool","access","args","Boolean","permissions","collections","collectionSlug","create","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","object","depth","number","int","min","max","describe","optional","default","documents","array","data","record","string","unknown","file","draft","boolean","fallbackLocale","locale","select","handler","authorizedMCP","req","payload","logger","info","length","virtualFieldNames","config","docs","errors","validationSchema","index","document","entries","inputData","validationError","firstContent","content","validationContent","structuredContent","schema","push","message","type","text","split","parsedData","result","collection","overrideAccess","doc","error","Error","batchResult","retryMessage","schemaMessage","JSON","stringify","isError","action"],"mappings":"AAEA,SAASA,CAAC,QAAQ,MAAK;AAEvB,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SACEC,8BAA8B,EAC9BC,kBAAkB,QACb,yCAAwC;AAC/C,SAASC,2BAA2B,QAAQ,gDAA+C;AAC3F,SAASC,sBAAsB,QAAQ,2BAA0B;AACjE,SAASC,eAAe,EAAEC,WAAW,QAAQ,iBAAgB;AAC7D,SAASC,qBAAqB,QAAQ,6BAA4B;AAElE,MAAMC,sBACJ;AAEF,OAAO,MAAMC,sBAAsBV,qBAAqB;IACtDW,QAAQ,CAACC,OACPb,cAAca,SAASC,QAAQD,KAAKE,WAAW,EAAEC,aAAa,CAACH,KAAKI,cAAc,CAAC,EAAEC;IACvFC,aAAa;QACXC,iBAAiB;QACjBC,gBAAgB;QAChBC,eAAe;QACfC,cAAc;QACdC,OAAO;IACT;IACAC,aAAaf;IACbgB,OAAO3B,EAAE4B,MAAM,CAAC;QACdC,OAAO7B,EACJ8B,MAAM,GACNC,GAAG,GACHC,GAAG,CAAC,GACJC,GAAG,CAAC,IACJC,QAAQ,CAAC,8DACTC,QAAQ,GACRC,OAAO,CAAC;QACXC,WAAWrC,EACRsC,KAAK,CACJtC,EAAE4B,MAAM,CAAC;YACPW,MAAMvC,EACHwC,MAAM,C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iCAAiC;QAC1E,MAAM8B,gBAAgBzB,mBAClB,CAAC,2CAA2C,EAAE0B,KAAKC,SAAS,CAAC3B,kBAAkB,QAAQ,CAAC,GACxF;QACJ,MAAMS,oBAAoBT,mBACtB;YAAE,GAAGuB,WAAW;YAAEb,QAAQV;QAAiB,IAC3CuB;QAEJ9B,OAAOC,IAAI,CAAC,CAAC,QAAQ,EAAEI,KAAKH,MAAM,CAAC,IAAI,EAAElB,UAAUkB,MAAM,CAAC,cAAc,EAAErC,gBAAgB;QAE1F,OAAO;YACLiD,SAAS;gBACP;oBACEM,MAAM;oBACNC,MAAM,CAAC,QAAQ,EAAEhB,KAAKH,MAAM,CAAC,IAAI,EAAElB,UAAUkB,MAAM,CAAC,0BAA0B,EAAErC,eAAe,EAAE,EAAEkE,aAAa,wBAAwB,EAAEE,KAAKC,SAAS,CAACJ,aAAa,QAAQ,EAAEE,eAAe;gBACjM;aACD;YACDL,KAAKX;YACLmB,SAAS9B,KAAKH,MAAM,KAAK,KAAKI,OAAOJ,MAAM,GAAG;YAC9Cc;QACF;IACF,EAAE,OAAOY,OAAO;QACd,MAAMT,UAAUS,iBAAiBC,QAAQD,MAAMT,OAAO,GAAG;QAEzDnB,OAAO4B,KAAK,CAAC,CAAC,4BAA4B,EAAE/D,eAAe,EAAE,EAAEsD,SAAS;QACxE,OAAO9D,sBAAsB;YAAE+E,QAAQ;YAAYvE;YAAgB+D;YAAO9B;QAAI;IAChF;AACF,GAAE"}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { getCollectionVirtualFieldNames, stripVirtualFields, transformPointDataToPayload } from 'payload';
|
|
2
1
|
import { z } from 'zod';
|
|
3
2
|
import { defaultAccess } from '../../../defaultAccess.js';
|
|
4
3
|
import { defineCollectionTool } from '../../../defineTool.js';
|
|
5
4
|
import { getLogger } from '../../../utils/getLogger.js';
|
|
5
|
+
import { getCollectionVirtualFieldNames, stripVirtualFields } from '../../../utils/getVirtualFieldNames.js';
|
|
6
|
+
import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js';
|
|
6
7
|
import { formatCollectionError } from './formatCollectionError.js';
|
|
7
8
|
const DEFAULT_DESCRIPTION = 'Duplicate a document in any collection by passing the collection slug and source document ID.';
|
|
8
9
|
export const duplicateDocumentTool = defineCollectionTool({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/mcp/builtin/collections/duplicateTool.ts"],"sourcesContent":["import type { PopulateType, SelectType } from 'payload'\n\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../../src/mcp/builtin/collections/duplicateTool.ts"],"sourcesContent":["import type { PopulateType, SelectType } from 'payload'\n\nimport { z } from 'zod'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport {\n getCollectionVirtualFieldNames,\n stripVirtualFields,\n} from '../../../utils/getVirtualFieldNames.js'\nimport { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'\nimport { formatCollectionError } from './formatCollectionError.js'\n\nconst DEFAULT_DESCRIPTION =\n 'Duplicate a document in any collection by passing the collection slug and source document ID.'\n\nexport const duplicateDocumentTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.create),\n annotations: {\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Duplicate Document',\n },\n description: DEFAULT_DESCRIPTION,\n input: z.object({\n id: z.union([z.string(), z.number()]).describe('The ID of the document to duplicate'),\n data: z\n .record(z.string(), z.unknown())\n .describe('Optional: fields to override on the duplicated document')\n .optional(),\n depth: z\n .number()\n .int()\n .min(0)\n .max(10)\n .describe('How many levels deep to populate relationships in response')\n .optional()\n .default(0),\n draft: z\n .boolean()\n .describe('Whether to create the duplicate as a draft')\n .optional()\n .default(false),\n fallbackLocale: z\n .string()\n .describe('Optional: fallback locale code to use when requested locale is not available')\n .optional(),\n locale: z\n .string()\n .describe(\n 'Optional: locale code to duplicate in (e.g., \"en\", \"es\"). Defaults to the default locale',\n )\n .optional(),\n populate: z\n .record(z.string(), z.unknown())\n .describe(\n 'Optional: control which fields to include from populated relationship or upload documents.',\n )\n .optional(),\n select: z\n .record(z.string(), z.unknown())\n .describe(\n 'Optional: define exactly which fields you\\'d like to return in the response, e.g., {\"title\": true}',\n )\n .optional(),\n selectedLocales: z\n .array(z.string())\n .describe('Optional: localized field locales to include in the duplicated document')\n .optional(),\n showHiddenFields: z\n .boolean()\n .describe('Optional: include hidden fields in the duplicated document response')\n .optional(),\n }),\n}).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n const {\n id,\n data,\n depth,\n draft,\n fallbackLocale,\n locale,\n populate,\n select,\n selectedLocales,\n showHiddenFields,\n } = input\n\n logger.info(`Duplicating document in collection: ${collectionSlug} with ID: ${id}`)\n\n try {\n const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug)\n const inputData = data ? stripVirtualFields(data, virtualFieldNames) : undefined\n const parsedData = inputData ? transformPointDataToPayload(inputData) : undefined\n\n const result = await payload.duplicate({\n id,\n collection: collectionSlug,\n depth,\n draft,\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n ...(parsedData ? { data: parsedData } : {}),\n ...(locale ? { locale } : {}),\n ...(fallbackLocale ? { fallbackLocale } : {}),\n ...(populate ? { populate: populate as PopulateType } : {}),\n ...(select ? { select: select as SelectType } : {}),\n ...(selectedLocales ? { selectedLocales } : {}),\n ...(showHiddenFields !== undefined ? { showHiddenFields } : {}),\n })\n\n logger.info(`Successfully duplicated document in ${collectionSlug} from ID: ${id}`)\n\n return {\n content: [\n {\n type: 'text',\n text: `Document duplicated successfully in collection \"${collectionSlug}\"!\\nDuplicated document:\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error duplicating document in ${collectionSlug}: ${errorMessage}`)\n return formatCollectionError({ action: 'duplicating', collectionSlug, error, req })\n }\n})\n"],"names":["z","defaultAccess","defineCollectionTool","getLogger","getCollectionVirtualFieldNames","stripVirtualFields","transformPointDataToPayload","formatCollectionError","DEFAULT_DESCRIPTION","duplicateDocumentTool","access","args","Boolean","permissions","collections","collectionSlug","create","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","object","id","union","string","number","describe","data","record","unknown","optional","depth","int","min","max","default","draft","boolean","fallbackLocale","locale","populate","select","selectedLocales","array","showHiddenFields","handler","authorizedMCP","req","payload","logger","info","virtualFieldNames","config","inputData","undefined","parsedData","result","duplicate","collection","overrideAccess","content","type","text","JSON","stringify","doc","error","errorMessage","Error","message","action"],"mappings":"AAEA,SAASA,CAAC,QAAQ,MAAK;AAEvB,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SACEC,8BAA8B,EAC9BC,kBAAkB,QACb,yCAAwC;AAC/C,SAASC,2BAA2B,QAAQ,gDAA+C;AAC3F,SAASC,qBAAqB,QAAQ,6BAA4B;AAElE,MAAMC,sBACJ;AAEF,OAAO,MAAMC,wBAAwBP,qBAAqB;IACxDQ,QAAQ,CAACC,OACPV,cAAcU,SAASC,QAAQD,KAAKE,WAAW,EAAEC,aAAa,CAACH,KAAKI,cAAc,CAAC,EAAEC;IACvFC,aAAa;QACXC,iBAAiB;QACjBC,gBAAgB;QAChBC,eAAe;QACfC,cAAc;QACdC,OAAO;IACT;IACAC,aAAaf;IACbgB,OAAOxB,EAAEyB,MAAM,CAAC;QACdC,IAAI1B,EAAE2B,KAAK,CAAC;YAAC3B,EAAE4B,MAAM;YAAI5B,EAAE6B,MAAM;SAAG,EAAEC,QAAQ,CAAC;QAC/CC,MAAM/B,EACHgC,MAAM,CAAChC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","sources":["../../../../src/mcp/builtin/collections/formatCollectionError.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;
|
|
1
|
+
{"version":3,"file":"formatCollectionError.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/formatCollectionError.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAE7D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AAgCxD,eAAO,MAAM,qBAAqB,4CAK/B;IACD,MAAM,EAAE,UAAU,GAAG,aAAa,GAAG,UAAU,CAAA;IAC/C,cAAc,EAAE,cAAc,CAAA;IAC9B,KAAK,EAAE,OAAO,CAAA;IACd,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,eAuCH,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/mcp/builtin/collections/formatCollectionError.ts"],"sourcesContent":["import type { CollectionSlug, PayloadRequest } from 'payload'\n\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../../src/mcp/builtin/collections/formatCollectionError.ts"],"sourcesContent":["import type { CollectionSlug, PayloadRequest } from 'payload'\n\nimport type { MCPToolResponse } from '../../../types.js'\n\nimport { getCollectionInputSchema } from '../../../utils/schemaConversion/getEntityInputSchema.js'\n\nconst getValidationErrors = (error: unknown): undefined | unknown[] => {\n if (!error || typeof error !== 'object') {\n return undefined\n }\n\n const data = 'data' in error ? error.data : undefined\n if (!data || typeof data !== 'object' || !('errors' in data) || !Array.isArray(data.errors)) {\n return undefined\n }\n\n return data.errors\n}\n\nconst isSchemaError = (error: unknown, message: string): boolean => {\n if (getValidationErrors(error)) {\n return true\n }\n\n const name = error && typeof error === 'object' && 'name' in error ? error.name : undefined\n\n return (\n name === 'CastError' ||\n name === 'ValidationError' ||\n message.includes('Cast to ') ||\n message.includes('validation failed')\n )\n}\n\nexport const formatCollectionError = ({\n action,\n collectionSlug,\n error,\n req,\n}: {\n action: 'creating' | 'duplicating' | 'updating'\n collectionSlug: CollectionSlug\n error: unknown\n req: PayloadRequest\n}): MCPToolResponse => {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n const errors = getValidationErrors(error) ?? [{ message: errorMessage }]\n\n if (!isSchemaError(error, errorMessage)) {\n return {\n content: [\n {\n type: 'text',\n text: `Error ${action} document in collection \"${collectionSlug}\": ${errorMessage}`,\n },\n ],\n isError: true,\n }\n }\n\n const schema = getCollectionInputSchema({ collectionSlug, req })\n const schemaText = schema\n ? `\\n\\nUse this schema for data:\\n\\`\\`\\`json\\n${JSON.stringify(schema)}\\n\\`\\`\\``\n : ''\n\n return {\n content: [\n {\n type: 'text',\n text: `Error ${action} document in collection \"${collectionSlug}\": ${errorMessage}${schemaText}`,\n },\n ],\n isError: true,\n ...(schema\n ? {\n structuredContent: {\n collectionSlug,\n errors,\n schema,\n },\n }\n : {}),\n }\n}\n"],"names":["getCollectionInputSchema","getValidationErrors","error","undefined","data","Array","isArray","errors","isSchemaError","message","name","includes","formatCollectionError","action","collectionSlug","req","errorMessage","Error","content","type","text","isError","schema","schemaText","JSON","stringify","structuredContent"],"mappings":"AAIA,SAASA,wBAAwB,QAAQ,0DAAyD;AAElG,MAAMC,sBAAsB,CAACC;IAC3B,IAAI,CAACA,SAAS,OAAOA,UAAU,UAAU;QACvC,OAAOC;IACT;IAEA,MAAMC,OAAO,UAAUF,QAAQA,MAAME,IAAI,GAAGD;IAC5C,IAAI,CAACC,QAAQ,OAAOA,SAAS,YAAY,CAAE,CAAA,YAAYA,IAAG,KAAM,CAACC,MAAMC,OAAO,CAACF,KAAKG,MAAM,GAAG;QAC3F,OAAOJ;IACT;IAEA,OAAOC,KAAKG,MAAM;AACpB;AAEA,MAAMC,gBAAgB,CAACN,OAAgBO;IACrC,IAAIR,oBAAoBC,QAAQ;QAC9B,OAAO;IACT;IAEA,MAAMQ,OAAOR,SAAS,OAAOA,UAAU,YAAY,UAAUA,QAAQA,MAAMQ,IAAI,GAAGP;IAElF,OACEO,SAAS,eACTA,SAAS,qBACTD,QAAQE,QAAQ,CAAC,eACjBF,QAAQE,QAAQ,CAAC;AAErB;AAEA,OAAO,MAAMC,wBAAwB,CAAC,EACpCC,MAAM,EACNC,cAAc,EACdZ,KAAK,EACLa,GAAG,EAMJ;IACC,MAAMC,eAAed,iBAAiBe,QAAQf,MAAMO,OAAO,GAAG;IAC9D,MAAMF,SAASN,oBAAoBC,UAAU;QAAC;YAAEO,SAASO;QAAa;KAAE;IAExE,IAAI,CAACR,cAAcN,OAAOc,eAAe;QACvC,OAAO;YACLE,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,MAAM,EAAEP,OAAO,yBAAyB,EAAEC,eAAe,GAAG,EAAEE,cAAc;gBACrF;aACD;YACDK,SAAS;QACX;IACF;IAEA,MAAMC,SAAStB,yBAAyB;QAAEc;QAAgBC;IAAI;IAC9D,MAAMQ,aAAaD,SACf,CAAC,2CAA2C,EAAEE,KAAKC,SAAS,CAACH,QAAQ,QAAQ,CAAC,GAC9E;IAEJ,OAAO;QACLJ,SAAS;YACP;gBACEC,MAAM;gBACNC,MAAM,CAAC,MAAM,EAAEP,OAAO,yBAAyB,EAAEC,eAAe,GAAG,EAAEE,eAAeO,YAAY;YAClG;SACD;QACDF,SAAS;QACT,GAAIC,SACA;YACEI,mBAAmB;gBACjBZ;gBACAP;gBACAe;YACF;QACF,IACA,CAAC,CAAC;IACR;AACF,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getCollectionSchemaTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/getCollectionSchemaTool.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"getCollectionSchemaTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/collections/getCollectionSchemaTool.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,uBAAuB,4CAyElC,CAAA"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { getAccessResults
|
|
1
|
+
import { getAccessResults } from 'payload';
|
|
2
2
|
import { defaultAccess } from '../../../defaultAccess.js';
|
|
3
3
|
import { defineCollectionTool } from '../../../defineTool.js';
|
|
4
|
+
import { getCollectionInputSchema } from '../../../utils/schemaConversion/getEntityInputSchema.js';
|
|
4
5
|
export const getCollectionSchemaTool = defineCollectionTool({
|
|
5
6
|
access: (args)=>{
|
|
6
7
|
const permissions = args.permissions?.collections?.[args.collectionSlug];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/mcp/builtin/collections/getCollectionSchemaTool.ts"],"sourcesContent":["import { getAccessResults
|
|
1
|
+
{"version":3,"sources":["../../../../src/mcp/builtin/collections/getCollectionSchemaTool.ts"],"sourcesContent":["import { getAccessResults } from 'payload'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getCollectionInputSchema } from '../../../utils/schemaConversion/getEntityInputSchema.js'\n\nexport const getCollectionSchemaTool = defineCollectionTool({\n access: (args) => {\n const permissions = args.permissions?.collections?.[args.collectionSlug]\n\n return defaultAccess(args) && Boolean(permissions?.create || permissions?.update)\n },\n annotations: {\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: true,\n title: 'Get Collection Schema',\n },\n description: 'Get the input schema for creating or updating documents in a collection.',\n}).handler(async ({ authorizedMCP, collectionSlug, req }) => {\n const permissions = authorizedMCP.overrideAccess\n ? null\n : (await getAccessResults({ req })).collections?.[collectionSlug]\n\n if (!authorizedMCP.overrideAccess && !permissions?.create && !permissions?.update) {\n return {\n content: [\n {\n type: 'text',\n text: `Error: MCP access to \"getCollectionSchema\" is not enabled for collection \"${collectionSlug}\"`,\n },\n ],\n isError: true,\n }\n }\n\n const inputSchema = getCollectionInputSchema({\n collectionSlug,\n req,\n ...(permissions ? { permissions } : {}),\n })\n\n if (!inputSchema) {\n return {\n content: [{ type: 'text', text: `Error: Collection \"${collectionSlug}\" not found` }],\n isError: true,\n }\n }\n\n const uploadConfig = req.payload.collections[collectionSlug]?.config.upload\n const maxFileSize = req.payload.config.upload.limits?.fileSize\n const upload = uploadConfig\n ? {\n enabled: true,\n filesRequiredOnCreate: uploadConfig.filesRequiredOnCreate !== false,\n mimeTypes: uploadConfig.mimeTypes ?? ['*/*'],\n sources: [\n ...(uploadConfig.pasteURL !== false ? ['externalURL'] : []),\n 'base64',\n 'uploadReference',\n ],\n ...(typeof maxFileSize === 'number' && Number.isFinite(maxFileSize) ? { maxFileSize } : {}),\n }\n : { enabled: false }\n\n return {\n content: [\n {\n type: 'text',\n text: `Schema for collection \"${collectionSlug}\":\\n\\`\\`\\`json\\n${JSON.stringify(inputSchema)}\\n\\`\\`\\`\\nUpload configuration:\\n\\`\\`\\`json\\n${JSON.stringify(upload)}\\n\\`\\`\\``,\n },\n ],\n structuredContent: {\n collectionSlug,\n schema: inputSchema,\n upload,\n },\n }\n})\n"],"names":["getAccessResults","defaultAccess","defineCollectionTool","getCollectionInputSchema","getCollectionSchemaTool","access","args","permissions","collections","collectionSlug","Boolean","create","update","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","handler","authorizedMCP","req","overrideAccess","content","type","text","isError","inputSchema","uploadConfig","payload","config","upload","maxFileSize","limits","fileSize","enabled","filesRequiredOnCreate","mimeTypes","sources","pasteURL","Number","isFinite","JSON","stringify","structuredContent","schema"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,UAAS;AAE1C,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,wBAAwB,QAAQ,0DAAyD;AAElG,OAAO,MAAMC,0BAA0BF,qBAAqB;IAC1DG,QAAQ,CAACC;QACP,MAAMC,cAAcD,KAAKC,WAAW,EAAEC,aAAa,CAACF,KAAKG,cAAc,CAAC;QAExE,OAAOR,cA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AAQ,CAACT,eAAe;YAAEA;QAAY,IAAI,CAAC,CAAC;IAC5F,IACA;QAAEG,SAAS;IAAM;IAErB,OAAO;QACLZ,SAAS;YACP;gBACEC,MAAM;gBACNC,MAAM,CAAC,uBAAuB,EAAEjB,eAAe,gBAAgB,EAAEkC,KAAKC,SAAS,CAAChB,aAAa,6CAA6C,EAAEe,KAAKC,SAAS,CAACZ,QAAQ,QAAQ,CAAC;YAC9K;SACD;QACDa,mBAAmB;YACjBpC;YACAqC,QAAQlB;YACRI;QACF;IACF;AACF,GAAE"}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
-
import { getCollectionInputSchema, getCollectionVirtualFieldNames, stripVirtualFields, transformPointDataToPayload } from 'payload';
|
|
2
1
|
import { z } from 'zod';
|
|
3
2
|
import { defaultAccess } from '../../../defaultAccess.js';
|
|
4
3
|
import { defineCollectionTool } from '../../../defineTool.js';
|
|
5
4
|
import { getLogger } from '../../../utils/getLogger.js';
|
|
5
|
+
import { getCollectionVirtualFieldNames, stripVirtualFields } from '../../../utils/getVirtualFieldNames.js';
|
|
6
|
+
import { getCollectionInputSchema } from '../../../utils/schemaConversion/getEntityInputSchema.js';
|
|
7
|
+
import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js';
|
|
6
8
|
import { whereSchema } from '../../../utils/whereSchema.js';
|
|
7
9
|
import { validateCollectionData } from '../validateEntityData.js';
|
|
8
10
|
import { fileInputSchema, resolveFile } from './fileInput.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/mcp/builtin/collections/updateTool.ts"],"sourcesContent":["import type { SelectType, Where } from 'payload'\n\nimport {\n getCollectionInputSchema,\n getCollectionVirtualFieldNames,\n stripVirtualFields,\n transformPointDataToPayload,\n} from 'payload'\nimport { z } from 'zod'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport { whereSchema } from '../../../utils/whereSchema.js'\nimport { validateCollectionData } from '../validateEntityData.js'\nimport { fileInputSchema, resolveFile } from './fileInput.js'\nimport { formatCollectionError } from './formatCollectionError.js'\n\nconst DEFAULT_DESCRIPTION =\n 'Update documents. Prefer uploadReference after upload, externalURL for URLs, or base64 for small local files.'\n\nexport const updateDocumentTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.update),\n annotations: {\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Update Document',\n },\n description: DEFAULT_DESCRIPTION,\n input: z.object({\n id: z.union([z.string(), z.number()]).describe('The ID of the document to update').optional(),\n data: z\n .record(z.string(), z.unknown())\n .describe(\n 'The fields to update. Only include fields permitted by the schema returned by getCollectionSchema.',\n ),\n depth: z\n .number()\n .describe('How many levels deep to populate relationships')\n .optional()\n .default(0),\n draft: z\n .boolean()\n .describe(\n 'Only if getCollectionSchema includes _status; otherwise _status does not exist. true saves only a draft version; false updates main and versions. data._status: \"published\" overrides true.',\n )\n .optional()\n .default(false),\n fallbackLocale: z\n .string()\n .describe('Optional: fallback locale code to use when requested locale is not available')\n .optional(),\n file: fileInputSchema.optional(),\n locale: z\n .string()\n .describe(\n 'Optional: locale code to update the document in (e.g., \"en\", \"es\"). Defaults to the default locale',\n )\n .optional(),\n overrideLock: z\n .boolean()\n .describe('Whether to override document locks')\n .optional()\n .default(true),\n overwriteExistingFiles: z\n .boolean()\n .describe('Whether to overwrite existing files')\n .optional()\n .default(false),\n publishAllLocales: z\n .boolean()\n .describe(\n 'For collections with localized publishing status, whether publishing should affect every locale. Set false with locale to publish only that locale.',\n )\n .optional(),\n select: z\n .record(z.string(), z.unknown())\n .describe(\n 'Optional: define exactly which fields you\\'d like to return in the response, e.g., {\"title\": true}',\n )\n .optional(),\n where: whereSchema\n .describe(\n 'Where clause to update multiple documents. Use field names with Payload operators, and/or arrays for grouping. Example: {\"title\":{\"contains\":\"test\"}}',\n )\n .optional(),\n }),\n}).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n\n const {\n id,\n data,\n depth,\n draft,\n fallbackLocale,\n file: fileInput,\n locale,\n overrideLock,\n overwriteExistingFiles,\n publishAllLocales,\n select,\n where,\n } = input\n\n logger.info(\n `Updating document in collection: ${collectionSlug}${id ? ` with ID: ${id}` : ' with where clause'}, draft: ${draft}${locale ? `, locale: ${locale}` : ''}`,\n )\n\n try {\n if (!id && !where) {\n return {\n content: [{ type: 'text', text: 'Error: Either id or where clause must be provided' }],\n }\n }\n\n const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug)\n const inputData = stripVirtualFields(data, virtualFieldNames)\n const validationError = validateCollectionData({\n collectionSlug,\n data: inputData,\n partial: true,\n req,\n })\n\n if (validationError) {\n return validationError\n }\n\n const parsedData = transformPointDataToPayload(inputData)\n const file = await resolveFile({ collectionSlug, input: fileInput, req })\n\n const whereClause: Where = where ?? {}\n\n if (id) {\n const result = await payload.update({\n id,\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: authorizedMCP.overrideAccess,\n overrideLock,\n req,\n ...(file ? { file } : {}),\n ...(overwriteExistingFiles ? { overwriteExistingFiles } : {}),\n ...(publishAllLocales !== undefined ? { publishAllLocales } : {}),\n ...(locale ? { locale } : {}),\n ...(fallbackLocale ? { fallbackLocale } : {}),\n ...(select ? { select: select as SelectType } : {}),\n })\n\n return {\n content: [\n {\n type: 'text',\n text: `Document updated successfully in collection \"${collectionSlug}\"!\\nUpdated document:\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as Record<string, unknown>,\n }\n }\n\n const result = await payload.update({\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: authorizedMCP.overrideAccess,\n overrideLock,\n req,\n where: whereClause,\n ...(file ? { file } : {}),\n ...(overwriteExistingFiles ? { overwriteExistingFiles } : {}),\n ...(publishAllLocales !== undefined ? { publishAllLocales } : {}),\n ...(locale ? { locale } : {}),\n ...(fallbackLocale ? { fallbackLocale } : {}),\n ...(select ? { select: select as SelectType } : {}),\n })\n\n const docs = result.docs || []\n const errors = result.errors || []\n\n let responseText = `Multiple documents updated in collection \"${collectionSlug}\"!\\nUpdated: ${docs.length} documents\\nErrors: ${errors.length}\\n---`\n if (docs.length > 0) {\n responseText += `\\n\\nUpdated documents:\\n\\`\\`\\`json\\n${JSON.stringify(docs)}\\n\\`\\`\\``\n }\n if (errors.length > 0) {\n responseText += `\\n\\nErrors:\\n\\`\\`\\`json\\n${JSON.stringify(errors)}\\n\\`\\`\\``\n\n const errorSchema = getCollectionInputSchema({ collectionSlug, req })\n\n if (errorSchema) {\n responseText += `\\n\\nUse this schema for data:\\n\\`\\`\\`json\\n${JSON.stringify(errorSchema)}\\n\\`\\`\\``\n }\n\n return {\n content: [{ type: 'text', text: responseText }],\n doc: { docs, errors } as unknown as Record<string, unknown>,\n isError: true,\n ...(errorSchema\n ? {\n structuredContent: {\n collectionSlug,\n docs,\n errors,\n schema: errorSchema,\n },\n }\n : {}),\n }\n }\n\n return {\n content: [{ type: 'text', text: responseText }],\n doc: { docs, errors } as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error updating document in ${collectionSlug}: ${errorMessage}`)\n return formatCollectionError({ action: 'updating', collectionSlug, error, req })\n }\n})\n"],"names":["getCollectionInputSchema","getCollectionVirtualFieldNames","stripVirtualFields","transformPointDataToPayload","z","defaultAccess","defineCollectionTool","getLogger","whereSchema","validateCollectionData","fileInputSchema","resolveFile","formatCollectionError","DEFAULT_DESCRIPTION","updateDocumentTool","access","args","Boolean","permissions","collections","collectionSlug","update","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","object","id","union","string","number","describe","optional","data","record","unknown","depth","default","draft","boolean","fallbackLocale","file","locale","overrideLock","overwriteExistingFiles","publishAllLocales","select","where","handler","authorizedMCP","req","payload","logger","fileInput","info","content","type","text","virtualFieldNames","config","inputData","validationError","partial","parsedData","whereClause","result","collection","overrideAccess","undefined","JSON","stringify","doc","docs","errors","responseText","length","errorSchema","isError","structuredContent","schema","error","errorMessage","Error","message","action"],"mappings":"AAEA,SACEA,wBAAwB,EACxBC,8BAA8B,EAC9BC,kBAAkB,EAClBC,2BAA2B,QACtB,UAAS;AAChB,SAASC,CAAC,QAAQ,MAAK;AAEvB,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SAASC,WAAW,QAAQ,gCAA+B;AAC3D,SAASC,sBAAsB,QAAQ,2BAA0B;AACjE,SAASC,eAAe,EAAEC,WAAW,QAAQ,iBAAgB;AAC7D,SAASC,qBAAqB,QAAQ,6BAA4B;AAElE,MAAMC,sBACJ;AAEF,OAAO,MAAMC,qBAAqBR,qBAAqB;IACrDS,QAAQ,CAACC,OACPX,cAAcW,SAASC,QAAQD,KAAKE,WAAW,EAAEC,aAAa,CAACH,KAAKI,cAAc,CAAC,EAAEC;IACvFC,aAAa;QACXC,iBAAiB;QACjBC,gBAAgB;QAChBC,eAAe;QACfC,cAAc;QACdC,OAAO;IACT;IACAC,aAAaf;IACbgB,OAAOzB,EAAE0B,MAAM,CAAC;QACdC,IAAI3B,EAAE4B,KAAK,CAAC;YAAC5B,EAAE6B,MAAM;YAAI7B,EAAE8B,MAAM;SAAG,EAAEC,QAAQ,CAAC,oCAAoCC,QAAQ;QAC3FC,MAAMjC,EACHkC,MAAM,CAAClC,EAAE6B,MAAM,IAAI7B,EAAEmC,OAAO,IAC5BJ,QAAQ,CACP;QAEJK,OAAOpC,EACJ8B,MAAM,GACNC,QAAQ,CAAC,kDACTC,QAAQ,GACRK,OAAO,CAAC;QACXC,OAAOtC,EACJuC,OAAO,GACPR,QAAQ,CACP,+LAEDC,QAAQ,GACRK,OAA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;gBAAC;oBAAEC,MAAM;oBAAQC,MAAMiB;gBAAa;aAAE;YAC/CH,KAAK;gBAAEC;gBAAMC;YAAO;QACtB;IACF,EAAE,OAAOO,OAAO;QACd,MAAMC,eAAeD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAG;QAC9D/B,OAAO4B,KAAK,CAAC,CAAC,2BAA2B,EAAEhE,eAAe,EAAE,EAAEiE,cAAc;QAC5E,OAAOzE,sBAAsB;YAAE4E,QAAQ;YAAYpE;YAAgBgE;YAAO9B;QAAI;IAChF;AACF,GAAE"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/mcp/builtin/collections/updateTool.ts"],"sourcesContent":["import type { SelectType, Where } from 'payload'\n\nimport { z } from 'zod'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineCollectionTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport {\n getCollectionVirtualFieldNames,\n stripVirtualFields,\n} from '../../../utils/getVirtualFieldNames.js'\nimport { getCollectionInputSchema } from '../../../utils/schemaConversion/getEntityInputSchema.js'\nimport { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'\nimport { whereSchema } from '../../../utils/whereSchema.js'\nimport { validateCollectionData } from '../validateEntityData.js'\nimport { fileInputSchema, resolveFile } from './fileInput.js'\nimport { formatCollectionError } from './formatCollectionError.js'\n\nconst DEFAULT_DESCRIPTION =\n 'Update documents. Prefer uploadReference after upload, externalURL for URLs, or base64 for small local files.'\n\nexport const updateDocumentTool = defineCollectionTool({\n access: (args) =>\n defaultAccess(args) && Boolean(args.permissions?.collections?.[args.collectionSlug]?.update),\n annotations: {\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Update Document',\n },\n description: DEFAULT_DESCRIPTION,\n input: z.object({\n id: z.union([z.string(), z.number()]).describe('The ID of the document to update').optional(),\n data: z\n .record(z.string(), z.unknown())\n .describe(\n 'The fields to update. Only include fields permitted by the schema returned by getCollectionSchema.',\n ),\n depth: z\n .number()\n .describe('How many levels deep to populate relationships')\n .optional()\n .default(0),\n draft: z\n .boolean()\n .describe(\n 'Only if getCollectionSchema includes _status; otherwise _status does not exist. true saves only a draft version; false updates main and versions. data._status: \"published\" overrides true.',\n )\n .optional()\n .default(false),\n fallbackLocale: z\n .string()\n .describe('Optional: fallback locale code to use when requested locale is not available')\n .optional(),\n file: fileInputSchema.optional(),\n locale: z\n .string()\n .describe(\n 'Optional: locale code to update the document in (e.g., \"en\", \"es\"). Defaults to the default locale',\n )\n .optional(),\n overrideLock: z\n .boolean()\n .describe('Whether to override document locks')\n .optional()\n .default(true),\n overwriteExistingFiles: z\n .boolean()\n .describe('Whether to overwrite existing files')\n .optional()\n .default(false),\n publishAllLocales: z\n .boolean()\n .describe(\n 'For collections with localized publishing status, whether publishing should affect every locale. Set false with locale to publish only that locale.',\n )\n .optional(),\n select: z\n .record(z.string(), z.unknown())\n .describe(\n 'Optional: define exactly which fields you\\'d like to return in the response, e.g., {\"title\": true}',\n )\n .optional(),\n where: whereSchema\n .describe(\n 'Where clause to update multiple documents. Use field names with Payload operators, and/or arrays for grouping. Example: {\"title\":{\"contains\":\"test\"}}',\n )\n .optional(),\n }),\n}).handler(async ({ authorizedMCP, collectionSlug, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n\n const {\n id,\n data,\n depth,\n draft,\n fallbackLocale,\n file: fileInput,\n locale,\n overrideLock,\n overwriteExistingFiles,\n publishAllLocales,\n select,\n where,\n } = input\n\n logger.info(\n `Updating document in collection: ${collectionSlug}${id ? ` with ID: ${id}` : ' with where clause'}, draft: ${draft}${locale ? `, locale: ${locale}` : ''}`,\n )\n\n try {\n if (!id && !where) {\n return {\n content: [{ type: 'text', text: 'Error: Either id or where clause must be provided' }],\n }\n }\n\n const virtualFieldNames = getCollectionVirtualFieldNames(payload.config, collectionSlug)\n const inputData = stripVirtualFields(data, virtualFieldNames)\n const validationError = validateCollectionData({\n collectionSlug,\n data: inputData,\n partial: true,\n req,\n })\n\n if (validationError) {\n return validationError\n }\n\n const parsedData = transformPointDataToPayload(inputData)\n const file = await resolveFile({ collectionSlug, input: fileInput, req })\n\n const whereClause: Where = where ?? {}\n\n if (id) {\n const result = await payload.update({\n id,\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: authorizedMCP.overrideAccess,\n overrideLock,\n req,\n ...(file ? { file } : {}),\n ...(overwriteExistingFiles ? { overwriteExistingFiles } : {}),\n ...(publishAllLocales !== undefined ? { publishAllLocales } : {}),\n ...(locale ? { locale } : {}),\n ...(fallbackLocale ? { fallbackLocale } : {}),\n ...(select ? { select: select as SelectType } : {}),\n })\n\n return {\n content: [\n {\n type: 'text',\n text: `Document updated successfully in collection \"${collectionSlug}\"!\\nUpdated document:\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as Record<string, unknown>,\n }\n }\n\n const result = await payload.update({\n collection: collectionSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: authorizedMCP.overrideAccess,\n overrideLock,\n req,\n where: whereClause,\n ...(file ? { file } : {}),\n ...(overwriteExistingFiles ? { overwriteExistingFiles } : {}),\n ...(publishAllLocales !== undefined ? { publishAllLocales } : {}),\n ...(locale ? { locale } : {}),\n ...(fallbackLocale ? { fallbackLocale } : {}),\n ...(select ? { select: select as SelectType } : {}),\n })\n\n const docs = result.docs || []\n const errors = result.errors || []\n\n let responseText = `Multiple documents updated in collection \"${collectionSlug}\"!\\nUpdated: ${docs.length} documents\\nErrors: ${errors.length}\\n---`\n if (docs.length > 0) {\n responseText += `\\n\\nUpdated documents:\\n\\`\\`\\`json\\n${JSON.stringify(docs)}\\n\\`\\`\\``\n }\n if (errors.length > 0) {\n responseText += `\\n\\nErrors:\\n\\`\\`\\`json\\n${JSON.stringify(errors)}\\n\\`\\`\\``\n\n const errorSchema = getCollectionInputSchema({ collectionSlug, req })\n\n if (errorSchema) {\n responseText += `\\n\\nUse this schema for data:\\n\\`\\`\\`json\\n${JSON.stringify(errorSchema)}\\n\\`\\`\\``\n }\n\n return {\n content: [{ type: 'text', text: responseText }],\n doc: { docs, errors } as unknown as Record<string, unknown>,\n isError: true,\n ...(errorSchema\n ? {\n structuredContent: {\n collectionSlug,\n docs,\n errors,\n schema: errorSchema,\n },\n }\n : {}),\n }\n }\n\n return {\n content: [{ type: 'text', text: responseText }],\n doc: { docs, errors } as unknown as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error updating document in ${collectionSlug}: ${errorMessage}`)\n return formatCollectionError({ action: 'updating', collectionSlug, error, req })\n }\n})\n"],"names":["z","defaultAccess","defineCollectionTool","getLogger","getCollectionVirtualFieldNames","stripVirtualFields","getCollectionInputSchema","transformPointDataToPayload","whereSchema","validateCollectionData","fileInputSchema","resolveFile","formatCollectionError","DEFAULT_DESCRIPTION","updateDocumentTool","access","args","Boolean","permissions","collections","collectionSlug","update","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","object","id","union","string","number","describe","optional","data","record","unknown","depth","default","draft","boolean","fallbackLocale","file","locale","overrideLock","overwriteExistingFiles","publishAllLocales","select","where","handler","authorizedMCP","req","payload","logger","fileInput","info","content","type","text","virtualFieldNames","config","inputData","validationError","partial","parsedData","whereClause","result","collection","overrideAccess","undefined","JSON","stringify","doc","docs","errors","responseText","length","errorSchema","isError","structuredContent","schema","error","errorMessage","Error","message","action"],"mappings":"AAEA,SAASA,CAAC,QAAQ,MAAK;AAEvB,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SACEC,8BAA8B,EAC9BC,kBAAkB,QACb,yCAAwC;AAC/C,SAASC,wBAAwB,QAAQ,0DAAyD;AAClG,SAASC,2BAA2B,QAAQ,gDAA+C;AAC3F,SAASC,WAAW,QAAQ,gCAA+B;AAC3D,SAASC,sB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chemaTool.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"getGlobalSchemaTool.d.ts","sourceRoot":"","sources":["../../../../src/mcp/builtin/globals/getGlobalSchemaTool.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,mBAAmB,wCAwD9B,CAAA"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { getAccessResults
|
|
1
|
+
import { getAccessResults } from 'payload';
|
|
2
2
|
import { defaultAccess } from '../../../defaultAccess.js';
|
|
3
3
|
import { defineGlobalTool } from '../../../defineTool.js';
|
|
4
|
+
import { getGlobalInputSchema } from '../../../utils/schemaConversion/getEntityInputSchema.js';
|
|
4
5
|
export const getGlobalSchemaTool = defineGlobalTool({
|
|
5
6
|
access: (args)=>{
|
|
6
7
|
const permissions = args.permissions?.globals?.[args.globalSlug];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/mcp/builtin/globals/getGlobalSchemaTool.ts"],"sourcesContent":["import { getAccessResults
|
|
1
|
+
{"version":3,"sources":["../../../../src/mcp/builtin/globals/getGlobalSchemaTool.ts"],"sourcesContent":["import { getAccessResults } from 'payload'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineGlobalTool } from '../../../defineTool.js'\nimport { getGlobalInputSchema } from '../../../utils/schemaConversion/getEntityInputSchema.js'\n\nexport const getGlobalSchemaTool = defineGlobalTool({\n access: (args) => {\n const permissions = args.permissions?.globals?.[args.globalSlug]\n\n return defaultAccess(args) && Boolean(permissions?.update)\n },\n annotations: {\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n readOnlyHint: true,\n title: 'Get Global Schema',\n },\n description: 'Get the input schema for updating a global.',\n}).handler(async ({ authorizedMCP, globalSlug, req }) => {\n const permissions = authorizedMCP.overrideAccess\n ? null\n : (await getAccessResults({ req })).globals?.[globalSlug]\n\n if (!authorizedMCP.overrideAccess && !permissions?.update) {\n return {\n content: [\n {\n type: 'text',\n text: `Error: MCP access to \"getGlobalSchema\" is not enabled for global \"${globalSlug}\"`,\n },\n ],\n isError: true,\n }\n }\n\n const inputSchema = getGlobalInputSchema({\n globalSlug,\n req,\n ...(permissions ? { permissions } : {}),\n })\n\n if (!inputSchema) {\n return {\n content: [{ type: 'text', text: `Error: Global \"${globalSlug}\" not found` }],\n isError: true,\n }\n }\n\n return {\n content: [\n {\n type: 'text',\n text: `Schema for global \"${globalSlug}\":\\n\\`\\`\\`json\\n${JSON.stringify(inputSchema)}\\n\\`\\`\\``,\n },\n ],\n structuredContent: {\n globalSlug,\n schema: inputSchema,\n },\n }\n})\n"],"names":["getAccessResults","defaultAccess","defineGlobalTool","getGlobalInputSchema","getGlobalSchemaTool","access","args","permissions","globals","globalSlug","Boolean","update","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","handler","authorizedMCP","req","overrideAccess","content","type","text","isError","inputSchema","JSON","stringify","structuredContent","schema"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,UAAS;AAE1C,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,gBAAgB,QAAQ,yBAAwB;AACzD,SAASC,oBAAoB,QAAQ,0DAAyD;AAE9F,OAAO,MAAMC,sBAAsBF,iBAAiB;IAClDG,QAAQ,CAACC;QACP,MAAMC,cAAcD,KAAKC,WAAW,EAAEC,SAAS,CAACF,KAAKG,UAAU,CAAC;QAEhE,OAAOR,cAAcK,SAASI,QAAQH,aAAaI;IACrD;IACAC,aAAa;QACXC,iBAAiB;QACjBC,gBAAgB;QAChBC,eAAe;QACfC,cAAc;QACdC,OAAO;IACT;IACAC,aAAa;AACf,GAAGC,OAAO,CAAC,OAAO,EAAEC,aAAa,EAAEX,UAAU,EAAEY,GAAG,EAAE;IAClD,MAAMd,cAAca,cAAcE,cAAc,GAC5C,OACA,AAAC,CAAA,MAAMtB,iBAAiB;QAAEqB;IAAI,EAAC,EAAGb,OAAO,EAAE,CAACC,WAAW;IAE3D,IAAI,CAACW,cAAcE,cAAc,IAAI,CAACf,aAAaI,QAAQ;QACzD,OAAO;YACLY,SAAS;gBACP;oBACEC,MAAM;oBACNC,MAAM,CAAC,kEAAkE,EAAEhB,WAAW,CAAC,CAAC;gBAC1F;aACD;YACDiB,SAAS;QACX;IACF;IAEA,MAAMC,cAAcxB,qBAAqB;QACvCM;QACAY;QACA,GAAId,cAAc;YAAEA;QAAY,IAAI,CAAC,CAAC;IACxC;IAEA,IAAI,CAACoB,aAAa;QAChB,OAAO;YACLJ,SAAS;gBAAC;oBAAEC,MAAM;oBAAQC,MAAM,CAAC,eAAe,EAAEhB,WAAW,WAAW,CAAC;gBAAC;aAAE;YAC5EiB,SAAS;QACX;IACF;IAEA,OAAO;QACLH,SAAS;YACP;gBACEC,MAAM;gBACNC,MAAM,CAAC,mBAAmB,EAAEhB,WAAW,gBAAgB,EAAEmB,KAAKC,SAAS,CAACF,aAAa,QAAQ,CAAC;YAChG;SACD;QACDG,mBAAmB;YACjBrB;YACAsB,QAAQJ;QACV;IACF;AACF,GAAE"}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { getGlobalVirtualFieldNames, stripVirtualFields, transformPointDataToPayload } from 'payload';
|
|
2
1
|
import { z } from 'zod';
|
|
3
2
|
import { defaultAccess } from '../../../defaultAccess.js';
|
|
4
3
|
import { defineGlobalTool } from '../../../defineTool.js';
|
|
5
4
|
import { getLogger } from '../../../utils/getLogger.js';
|
|
5
|
+
import { getGlobalVirtualFieldNames, stripVirtualFields } from '../../../utils/getVirtualFieldNames.js';
|
|
6
|
+
import { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js';
|
|
6
7
|
import { validateGlobalData } from '../validateEntityData.js';
|
|
7
8
|
const DEFAULT_DESCRIPTION = 'Update any Payload global by passing the global slug and data.';
|
|
8
9
|
export const updateGlobalTool = defineGlobalTool({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/mcp/builtin/globals/updateTool.ts"],"sourcesContent":["import type { SelectType } from 'payload'\n\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../../src/mcp/builtin/globals/updateTool.ts"],"sourcesContent":["import type { SelectType } from 'payload'\n\nimport { z } from 'zod'\n\nimport { defaultAccess } from '../../../defaultAccess.js'\nimport { defineGlobalTool } from '../../../defineTool.js'\nimport { getLogger } from '../../../utils/getLogger.js'\nimport {\n getGlobalVirtualFieldNames,\n stripVirtualFields,\n} from '../../../utils/getVirtualFieldNames.js'\nimport { transformPointDataToPayload } from '../../../utils/transformPointDataToPayload.js'\nimport { validateGlobalData } from '../validateEntityData.js'\n\nconst DEFAULT_DESCRIPTION = 'Update any Payload global by passing the global slug and data.'\n\nexport const updateGlobalTool = defineGlobalTool({\n access: (args) =>\n defaultAccess(args) && Boolean(args.permissions?.globals?.[args.globalSlug]?.update),\n annotations: {\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: false,\n readOnlyHint: false,\n title: 'Update Global',\n },\n description: DEFAULT_DESCRIPTION,\n input: z.object({\n data: z.record(z.string(), z.unknown()).describe('The global fields to update'),\n depth: z\n .number()\n .describe('Optional: Depth of relationships to populate')\n .optional()\n .default(0),\n draft: z\n .boolean()\n .describe('Optional: Whether to save as draft (default: false)')\n .optional()\n .default(false),\n fallbackLocale: z\n .string()\n .describe('Optional: fallback locale code to use when requested locale is not available')\n .optional(),\n locale: z\n .string()\n .describe(\n 'Optional: locale code to update data in (e.g., \"en\", \"es\"). Use \"all\" to update all locales for localized fields',\n )\n .optional(),\n select: z\n .record(z.string(), z.unknown())\n .describe(\n 'Optional: define exactly which fields you\\'d like to return in the response, e.g., {\"siteName\": true}',\n )\n .optional(),\n }),\n}).handler(async ({ authorizedMCP, globalSlug, input, req }) => {\n const payload = req.payload\n const logger = getLogger({ payload })\n\n const { data, depth, draft, fallbackLocale, locale, select } = input\n\n logger.info(\n `Updating global: ${globalSlug}, draft: ${draft}${locale ? `, locale: ${locale}` : ''}`,\n )\n\n try {\n const virtualFieldNames = getGlobalVirtualFieldNames(payload.config, globalSlug)\n const inputData = stripVirtualFields(data, virtualFieldNames)\n const validationError = validateGlobalData({ data: inputData, globalSlug, req })\n\n if (validationError) {\n return validationError\n }\n\n const parsedData = transformPointDataToPayload(inputData)\n\n const updateOptions: Parameters<typeof payload.updateGlobal>[0] = {\n slug: globalSlug,\n data: parsedData,\n depth,\n draft,\n overrideAccess: authorizedMCP.overrideAccess,\n req,\n }\n\n if (locale) {\n updateOptions.locale = locale\n }\n if (fallbackLocale) {\n updateOptions.fallbackLocale = fallbackLocale\n }\n if (select) {\n updateOptions.select = select as SelectType\n }\n\n const result = await payload.updateGlobal(updateOptions)\n\n return {\n content: [\n {\n type: 'text',\n text: `Global \"${globalSlug}\" updated successfully!\\n\\`\\`\\`json\\n${JSON.stringify(result)}\\n\\`\\`\\``,\n },\n ],\n doc: result as Record<string, unknown>,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n logger.error(`Error updating global ${globalSlug}: ${errorMessage}`)\n return {\n content: [{ type: 'text', text: `Error updating global \"${globalSlug}\": ${errorMessage}` }],\n }\n }\n})\n"],"names":["z","defaultAccess","defineGlobalTool","getLogger","getGlobalVirtualFieldNames","stripVirtualFields","transformPointDataToPayload","validateGlobalData","DEFAULT_DESCRIPTION","updateGlobalTool","access","args","Boolean","permissions","globals","globalSlug","update","annotations","destructiveHint","idempotentHint","openWorldHint","readOnlyHint","title","description","input","object","data","record","string","unknown","describe","depth","number","optional","default","draft","boolean","fallbackLocale","locale","select","handler","authorizedMCP","req","payload","logger","info","virtualFieldNames","config","inputData","validationError","parsedData","updateOptions","slug","overrideAccess","result","updateGlobal","content","type","text","JSON","stringify","doc","error","errorMessage","Error","message"],"mappings":"AAEA,SAASA,CAAC,QAAQ,MAAK;AAEvB,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,gBAAgB,QAAQ,yBAAwB;AACzD,SAASC,SAAS,QAAQ,8BAA6B;AACvD,SACEC,0BAA0B,EAC1BC,kBAAkB,QACb,yCAAwC;AA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AE,cAAc,EAAE,UAAU,EAAE,cAAc,EAAmB,MAAM,SAAS,CAAA;
|
|
1
|
+
{"version":3,"file":"validateEntityData.d.ts","sourceRoot":"","sources":["../../../src/mcp/builtin/validateEntityData.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,UAAU,EAAE,cAAc,EAAmB,MAAM,SAAS,CAAA;AAI1F,OAAO,KAAK,EAAkB,eAAe,EAAE,MAAM,gBAAgB,CAAA;AAuBrE,eAAO,MAAM,sBAAsB,4CAKhC;IACD,cAAc,EAAE,cAAc,CAAA;IAC9B,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC7B,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,eAAe,GAAG,IAQlB,CAAA;AAEJ,eAAO,MAAM,kBAAkB,+BAI5B;IACD,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC7B,UAAU,EAAE,UAAU,CAAA;IACtB,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,eAAe,GAAG,IAQlB,CAAA"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { CfWorkerJsonSchemaValidator } from '@modelcontextprotocol/server/validators/cf-worker';
|
|
2
|
-
import { getCollectionInputSchema, getGlobalInputSchema } from '
|
|
2
|
+
import { getCollectionInputSchema, getGlobalInputSchema } from '../../utils/schemaConversion/getEntityInputSchema.js';
|
|
3
3
|
/**
|
|
4
4
|
* Keep the default `shortcircuit: true` - `false` makes validating nested rich text exponentially slow.
|
|
5
5
|
*/ const validator = new CfWorkerJsonSchemaValidator({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/mcp/builtin/validateEntityData.ts"],"sourcesContent":["import type { CollectionSlug, GlobalSlug, PayloadRequest, SanitizedConfig } from 'payload'\n\nimport { CfWorkerJsonSchemaValidator } from '@modelcontextprotocol/server/validators/cf-worker'\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../src/mcp/builtin/validateEntityData.ts"],"sourcesContent":["import type { CollectionSlug, GlobalSlug, PayloadRequest, SanitizedConfig } from 'payload'\n\nimport { CfWorkerJsonSchemaValidator } from '@modelcontextprotocol/server/validators/cf-worker'\n\nimport type { JsonSchemaType, MCPToolResponse } from '../../types.js'\n\nimport {\n getCollectionInputSchema,\n getGlobalInputSchema,\n} from '../../utils/schemaConversion/getEntityInputSchema.js'\n\n/**\n * Keep the default `shortcircuit: true` - `false` makes validating nested rich text exponentially slow.\n */\nconst validator = new CfWorkerJsonSchemaValidator({ shortcircuit: true })\n\ntype EntityValidator = {\n schema: JsonSchemaType\n validate: ReturnType<(typeof validator)['getValidator']>\n}\n\n/**\n * - Caches each entity's schema and validator, so both are only built on the first request.\n * - Keyed by payload config, then by entity type, slug, partial and language.\n */\nconst validatorCache = new WeakMap<SanitizedConfig, Map<string, EntityValidator>>()\n\nexport const validateCollectionData = ({\n collectionSlug,\n data,\n partial,\n req,\n}: {\n collectionSlug: CollectionSlug\n data: Record<string, unknown>\n partial?: boolean\n req: PayloadRequest\n}): MCPToolResponse | null =>\n validateData({\n slug: collectionSlug,\n buildSchema: () => getCollectionInputSchema({ collectionSlug, req }),\n data,\n entity: 'collection',\n partial,\n req,\n })\n\nexport const validateGlobalData = ({\n data,\n globalSlug,\n req,\n}: {\n data: Record<string, unknown>\n globalSlug: GlobalSlug\n req: PayloadRequest\n}): MCPToolResponse | null =>\n validateData({\n slug: globalSlug,\n buildSchema: () => getGlobalInputSchema({ globalSlug, req }),\n data,\n entity: 'global',\n partial: true,\n req,\n })\n\nconst validateData = ({\n slug,\n buildSchema,\n data,\n entity,\n partial,\n req,\n}: {\n buildSchema: () => JsonSchemaType | null\n data: Record<string, unknown>\n entity: 'collection' | 'global'\n partial?: boolean\n req: PayloadRequest\n slug: string\n}): MCPToolResponse | null => {\n let cache = validatorCache.get(req.payload.config)\n if (!cache) {\n cache = new Map()\n validatorCache.set(req.payload.config, cache)\n }\n\n const cacheKey = `${entity}:${slug}:${partial ? 'partial' : 'full'}:${req.i18n.language}`\n let entityValidator = cache.get(cacheKey)\n\n if (!entityValidator) {\n const schema = buildSchema()\n\n if (!schema) {\n return null\n }\n\n entityValidator = {\n schema,\n validate: validator.getValidator(partial ? withoutRequired(schema) : schema),\n }\n cache.set(cacheKey, entityValidator)\n }\n\n const result = entityValidator.validate(data)\n\n if (result.valid) {\n return null\n }\n\n const { schema } = entityValidator\n\n return {\n content: [\n {\n type: 'text',\n text: `Invalid data for ${entity} \"${slug}\": ${result.errorMessage}\\n\\nUse this schema for data:\\n\\`\\`\\`json\\n${JSON.stringify(schema)}\\n\\`\\`\\``,\n },\n ],\n isError: true,\n structuredContent: {\n [`${entity}Slug`]: slug,\n errors: [{ message: result.errorMessage }],\n schema,\n },\n }\n}\n\n/** Updates are partial — drop the schema's top-level `required` before validating. */\nconst withoutRequired = (schema: JsonSchemaType): JsonSchemaType => {\n const { required: _required, ...rest } = schema\n return rest\n}\n"],"names":["CfWorkerJsonSchemaValidator","getCollectionInputSchema","getGlobalInputSchema","validator","shortcircuit","validatorCache","WeakMap","validateCollectionData","collectionSlug","data","partial","req","validateData","slug","buildSchema","entity","validateGlobalData","globalSlug","cache","get","payload","config","Map","set","cacheKey","i18n","language","entityValidator","schema","validate","getValidator","withoutRequired","result","valid","content","type","text","errorMessage","JSON","stringify","isError","structuredContent","errors","message","required","_required","rest"],"mappings":"AAEA,SAASA,2BAA2B,QAAQ,oDAAmD;AAI/F,SACEC,wBAAwB,EACxBC,oBAAoB,QACf,uDAAsD;AAE7D;;CAEC,GACD,MAAMC,YAAY,IAAIH,4BAA4B;IAAEI,cAAc;AAAK;AAOvE;;;CAGC,GACD,MAAMC,iBAAiB,IAAIC;AAE3B,OAAO,MAAMC,yBAAyB,CAAC,EACrCC,cAAc,EACdC,IAAI,EACJC,OAAO,EACPC,GAAG,EAMJ,GACCC,aAAa;QACXC,MAAML;QACN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AC,2CAA2C,EAAEC,KAAKC,SAAS,CAACX,QAAQ,QAAQ,CAAC;YAClJ;SACD;QACDY,SAAS;QACTC,mBAAmB;YACjB,CAAC,GAAG1B,OAAO,IAAI,CAAC,CAAC,EAAEF;YACnB6B,QAAQ;gBAAC;oBAAEC,SAASX,OAAOK,YAAY;gBAAC;aAAE;YAC1CT;QACF;IACF;AACF;AAEA,oFAAoF,GACpF,MAAMG,kBAAkB,CAACH;IACvB,MAAM,EAAEgB,UAAUC,SAAS,EAAE,GAAGC,MAAM,GAAGlB;IACzC,OAAOkB;AACT"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { SanitizedConfig } from 'payload';
|
|
2
|
+
/**
|
|
3
|
+
* Returns the names of all top-level virtual fields for a given collection slug.
|
|
4
|
+
*/
|
|
5
|
+
export declare function getCollectionVirtualFieldNames(config: SanitizedConfig, slug: string): string[];
|
|
6
|
+
/**
|
|
7
|
+
* Returns the names of all top-level virtual fields for a given global slug.
|
|
8
|
+
*/
|
|
9
|
+
export declare function getGlobalVirtualFieldNames(config: SanitizedConfig, slug: string): string[];
|
|
10
|
+
/**
|
|
11
|
+
* Strips virtual field values from a data object given a list of virtual field names.
|
|
12
|
+
*/
|
|
13
|
+
export declare function stripVirtualFields(data: Record<string, unknown>, virtualFieldNames: string[]): Record<string, unknown>;
|
|
14
|
+
//# sourceMappingURL=getVirtualFieldNames.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"getVirtualFieldNames.d.ts","sourceRoot":"","sources":["../../src/utils/getVirtualFieldNames.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AAI9C;;GAEG;AACH,wBAAgB,8BAA8B,CAAC,MAAM,EAAE,eAAe,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAU9F;AAED;;GAEG;AACH,wBAAgB,0BAA0B,CAAC,MAAM,EAAE,eAAe,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAU1F;AAED;;GAEG;AACH,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC7B,iBAAiB,EAAE,MAAM,EAAE,GAC1B,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAYzB"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { fieldIsVirtual } from 'payload/shared';
|
|
2
|
+
/**
|
|
3
|
+
* Returns the names of all top-level virtual fields for a given collection slug.
|
|
4
|
+
*/ export function getCollectionVirtualFieldNames(config, slug) {
|
|
5
|
+
const collection = config.collections.find((c)=>c.slug === slug);
|
|
6
|
+
if (!collection) {
|
|
7
|
+
return [];
|
|
8
|
+
}
|
|
9
|
+
return collection.flattenedFields.filter((field)=>'name' in field && fieldIsVirtual(field)).map((field)=>field.name);
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Returns the names of all top-level virtual fields for a given global slug.
|
|
13
|
+
*/ export function getGlobalVirtualFieldNames(config, slug) {
|
|
14
|
+
const global = config.globals.find((g)=>g.slug === slug);
|
|
15
|
+
if (!global) {
|
|
16
|
+
return [];
|
|
17
|
+
}
|
|
18
|
+
return global.flattenedFields.filter((field)=>'name' in field && fieldIsVirtual(field)).map((field)=>field.name);
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Strips virtual field values from a data object given a list of virtual field names.
|
|
22
|
+
*/ export function stripVirtualFields(data, virtualFieldNames) {
|
|
23
|
+
if (virtualFieldNames.length === 0) {
|
|
24
|
+
return data;
|
|
25
|
+
}
|
|
26
|
+
const stripped = {
|
|
27
|
+
...data
|
|
28
|
+
};
|
|
29
|
+
for (const name of virtualFieldNames){
|
|
30
|
+
delete stripped[name];
|
|
31
|
+
}
|
|
32
|
+
return stripped;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
//# sourceMappingURL=getVirtualFieldNames.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/utils/getVirtualFieldNames.ts"],"sourcesContent":["import type { SanitizedConfig } from 'payload'\n\nimport { fieldIsVirtual } from 'payload/shared'\n\n/**\n * Returns the names of all top-level virtual fields for a given collection slug.\n */\nexport function getCollectionVirtualFieldNames(config: SanitizedConfig, slug: string): string[] {\n const collection = config.collections.find((c) => c.slug === slug)\n\n if (!collection) {\n return []\n }\n\n return collection.flattenedFields\n .filter((field) => 'name' in field && fieldIsVirtual(field))\n .map((field) => (field as { name: string }).name)\n}\n\n/**\n * Returns the names of all top-level virtual fields for a given global slug.\n */\nexport function getGlobalVirtualFieldNames(config: SanitizedConfig, slug: string): string[] {\n const global = config.globals.find((g) => g.slug === slug)\n\n if (!global) {\n return []\n }\n\n return global.flattenedFields\n .filter((field) => 'name' in field && fieldIsVirtual(field))\n .map((field) => (field as { name: string }).name)\n}\n\n/**\n * Strips virtual field values from a data object given a list of virtual field names.\n */\nexport function stripVirtualFields(\n data: Record<string, unknown>,\n virtualFieldNames: string[],\n): Record<string, unknown> {\n if (virtualFieldNames.length === 0) {\n return data\n }\n\n const stripped = { ...data }\n\n for (const name of virtualFieldNames) {\n delete stripped[name]\n }\n\n return stripped\n}\n"],"names":["fieldIsVirtual","getCollectionVirtualFieldNames","config","slug","collection","collections","find","c","flattenedFields","filter","field","map","name","getGlobalVirtualFieldNames","global","globals","g","stripVirtualFields","data","virtualFieldNames","length","stripped"],"mappings":"AAEA,SAASA,cAAc,QAAQ,iBAAgB;AAE/C;;CAEC,GACD,OAAO,SAASC,+BAA+BC,MAAuB,EAAEC,IAAY;IAClF,MAAMC,aAAaF,OAAOG,WAAW,CAACC,IAAI,CAAC,CAACC,IAAMA,EAAEJ,IAAI,KAAKA;IAE7D,IAAI,CAACC,YAAY;QACf,OAAO,EAAE;IACX;IAEA,OAAOA,WAAWI,eAAe,CAC9BC,MAAM,CAAC,CAACC,QAAU,UAAUA,SAASV,eAAeU,QACpDC,GAAG,CAAC,CAACD,QAAU,AAACA,MAA2BE,IAAI;AACpD;AAEA;;CAEC,GACD,OAAO,SAASC,2BAA2BX,MAAuB,EAAEC,IAAY;IAC9E,MAAMW,SAASZ,OAAOa,OAAO,CAACT,IAAI,CAAC,CAACU,IAAMA,EAAEb,IAAI,KAAKA;IAErD,IAAI,CAACW,QAAQ;QACX,OAAO,EAAE;IACX;IAEA,OAAOA,OAAON,eAAe,CAC1BC,MAAM,CAAC,CAACC,QAAU,UAAUA,SAASV,eAAeU,QACpDC,GAAG,CAAC,CAACD,QAAU,AAACA,MAA2BE,IAAI;AACpD;AAEA;;CAEC,GACD,OAAO,SAASK,mBACdC,IAA6B,EAC7BC,iBAA2B;IAE3B,IAAIA,kBAAkBC,MAAM,KAAK,GAAG;QAClC,OAAOF;IACT;IAEA,MAAMG,WAAW;QAAE,GAAGH,IAAI;IAAC;IAE3B,KAAK,MAAMN,QAAQO,kBAAmB;QACpC,OAAOE,QAAQ,CAACT,KAAK;IACvB;IAEA,OAAOS;AACT"}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { FlattenedBlock, FlattenedField, Operation, SanitizedDocumentPermissions } from 'payload';
|
|
2
|
+
type FieldOperation = Exclude<Operation, 'delete'>;
|
|
3
|
+
type AllowedFieldOperations = Record<FieldOperation, boolean>;
|
|
4
|
+
/**
|
|
5
|
+
* Filters fields using the access results in `permissions`. `shouldExcludeField` receives the
|
|
6
|
+
* operations allowed by the entity, field, and its parents and decides whether to remove the
|
|
7
|
+
* field.
|
|
8
|
+
*
|
|
9
|
+
* Arrays, groups, named tabs, and blocks are filtered recursively. Rows and unnamed tabs are
|
|
10
|
+
* flattened by Payload, so their children are filtered at the containing level.
|
|
11
|
+
*
|
|
12
|
+
* @example Include fields writable through any collection operation the user can perform.
|
|
13
|
+
* ```ts
|
|
14
|
+
* filterFieldsByAccess({
|
|
15
|
+
* fields,
|
|
16
|
+
* permissions: collectionPermissions,
|
|
17
|
+
* shouldExcludeField: ({ create, update }) => !create && !update,
|
|
18
|
+
* })
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
21
|
+
export declare const filterFieldsByAccess: ({ blocks, fields, permissions, shouldExcludeField, }: {
|
|
22
|
+
blocks?: FlattenedBlock[];
|
|
23
|
+
fields: FlattenedField[];
|
|
24
|
+
permissions: SanitizedDocumentPermissions;
|
|
25
|
+
shouldExcludeField: (allowedOperations: AllowedFieldOperations) => boolean;
|
|
26
|
+
}) => FlattenedField[];
|
|
27
|
+
export {};
|
|
28
|
+
//# sourceMappingURL=filterFieldsByAccess.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"filterFieldsByAccess.d.ts","sourceRoot":"","sources":["../../../src/utils/schemaConversion/filterFieldsByAccess.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,cAAc,EACd,cAAc,EACd,SAAS,EACT,4BAA4B,EAE7B,MAAM,SAAS,CAAA;AAEhB,KAAK,cAAc,GAAG,OAAO,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAA;AAClD,KAAK,sBAAsB,GAAG,MAAM,CAAC,cAAc,EAAE,OAAO,CAAC,CAAA;AAE7D;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,oBAAoB,yDAK9B;IACD,MAAM,CAAC,EAAE,cAAc,EAAE,CAAA;IACzB,MAAM,EAAE,cAAc,EAAE,CAAA;IACxB,WAAW,EAAE,4BAA4B,CAAA;IACzC,kBAAkB,EAAE,CAAC,iBAAiB,EAAE,sBAAsB,KAAK,OAAO,CAAA;CAC3E,KAAG,cAAc,EAoFjB,CAAA"}
|