@payloadcms/figma 0.0.1-alpha.30 → 0.0.1-alpha.31
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/db-content-api/index.d.ts.map +1 -1
- package/dist/db-content-api/index.js +29 -8
- package/dist/db-content-api/index.js.map +1 -1
- package/dist/db-content-api/temp-utilities/unwrapDocument.d.ts.map +1 -1
- package/dist/db-content-api/temp-utilities/unwrapDocument.js +11 -3
- package/dist/db-content-api/temp-utilities/unwrapDocument.js.map +1 -1
- package/dist/db-content-api/utilities/data/applyDefaults.d.ts +7 -0
- package/dist/db-content-api/utilities/data/applyDefaults.d.ts.map +1 -0
- package/dist/db-content-api/utilities/data/applyDefaults.js +59 -0
- package/dist/db-content-api/utilities/data/applyDefaults.js.map +1 -0
- package/dist/db-content-api/utilities/data/castFieldValue.d.ts +11 -0
- package/dist/db-content-api/utilities/data/castFieldValue.d.ts.map +1 -0
- package/dist/db-content-api/utilities/data/castFieldValue.js +66 -0
- package/dist/db-content-api/utilities/data/castFieldValue.js.map +1 -0
- package/dist/db-content-api/utilities/{data.d.ts → data/index.d.ts} +7 -3
- package/dist/db-content-api/utilities/data/index.d.ts.map +1 -0
- package/dist/db-content-api/utilities/{data.js → data/index.js} +54 -6
- package/dist/db-content-api/utilities/data/index.js.map +1 -0
- package/dist/db-content-api/utilities/data/stripFields.d.ts +48 -0
- package/dist/db-content-api/utilities/data/stripFields.d.ts.map +1 -0
- package/dist/db-content-api/utilities/data/stripFields.js +195 -0
- package/dist/db-content-api/utilities/data/stripFields.js.map +1 -0
- package/dist/db-content-api/utilities/where.d.ts.map +1 -1
- package/dist/db-content-api/utilities/where.js +46 -2
- package/dist/db-content-api/utilities/where.js.map +1 -1
- package/dist/exports/client.d.ts +1 -0
- package/dist/exports/client.d.ts.map +1 -1
- package/dist/exports/client.js +1 -0
- package/dist/exports/client.js.map +1 -1
- package/dist/plugin/build-config.d.ts.map +1 -1
- package/dist/plugin/build-config.js +14 -0
- package/dist/plugin/build-config.js.map +1 -1
- package/dist/storage-content-api/client-uploads/ClientUploadHandler.d.ts +9 -0
- package/dist/storage-content-api/client-uploads/ClientUploadHandler.d.ts.map +1 -0
- package/dist/storage-content-api/client-uploads/ClientUploadHandler.js +42 -0
- package/dist/storage-content-api/client-uploads/ClientUploadHandler.js.map +1 -0
- package/dist/storage-content-api/client-uploads/generateSignedURL.d.ts +13 -0
- package/dist/storage-content-api/client-uploads/generateSignedURL.d.ts.map +1 -0
- package/dist/storage-content-api/client-uploads/generateSignedURL.js +31 -0
- package/dist/storage-content-api/client-uploads/generateSignedURL.js.map +1 -0
- package/dist/storage-content-api/handleUpload.d.ts.map +1 -1
- package/dist/storage-content-api/handleUpload.js +13 -3
- package/dist/storage-content-api/handleUpload.js.map +1 -1
- package/dist/storage-content-api/staticHandler.d.ts.map +1 -1
- package/dist/storage-content-api/staticHandler.js +22 -2
- package/dist/storage-content-api/staticHandler.js.map +1 -1
- package/package.json +1 -1
- package/dist/db-content-api/utilities/data.d.ts.map +0 -1
- package/dist/db-content-api/utilities/data.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/plugin/build-config.ts"],"sourcesContent":["import type { Config, SanitizedConfig } from 'payload'\n\nimport { cloudStoragePlugin } from '@payloadcms/plugin-cloud-storage'\nimport { lexicalEditor } from '@payloadcms/richtext-lexical'\nimport { buildConfig as payloadBuildConfig } from 'payload'\n\nimport type { StorageClientConfig } from '../storage-content-api/index.js'\n\nimport { getTokenStore } from '../auth/token-store.js'\nimport { contentAPIAdapter } from '../db-content-api/index.js'\nimport { health } from '../endpoints/health.js'\nimport { oAuth2Plugin } from '../oauth/index.js'\nimport { contentApiStorageAdapter } from '../storage-content-api/index.js'\n\n/**\n * Configuration type for Payload projects on the Figma platform.\n *\n * Differences from standard Payload Config:\n * - `db`: Omitted (auto-injected by Figma platform)\n * - `secret`: Omitted (auto-injected by Figma platform)\n * - `editor`: Optional (defaults to lexicalEditor() if not provided)\n *\n * @example\n * // Minimal config\n * const config: FigmaConfig = {\n * figma: {\n * contentSystemId: process.env.FIGMA_CONTENT_SYSTEM_ID!\n * },\n * collections: [...]\n * }\n *\n * @example\n * // With custom editor\n * const config: FigmaConfig = {\n * figma: {\n * contentSystemId: process.env.FIGMA_CONTENT_SYSTEM_ID!\n * },\n * collections: [...],\n * editor: lexicalEditor({ features: [...] })\n * }\n *\n * @example\n * // Disable Content System (use custom db)\n * const config: FigmaConfig = {\n * figma: {\n * contentSystemId: process.env.FIGMA_CONTENT_SYSTEM_ID!,\n * useContentSystem: false\n * },\n * db: mongooseAdapter({ url: process.env.DATABASE_URI }),\n * collections: [...]\n * }\n */\nexport type FigmaConfig = {\n editor?: Config['editor']\n} & {\n figma: {\n contentSystemId: string\n storage?: boolean\n useContentSystem?: boolean\n }\n} & Omit<Config, 'db' | 'editor' | 'secret'> &\n Partial<Pick<Config, 'db'>>\n\n/**\n * Figma platform wrapper for Payload's buildConfig.\n * Automatically injects:\n * - Figma database adapter\n * - Secret (platform-provided)\n * - Default lexicalEditor (if no custom editor specified)\n *\n * @param config - Payload configuration (db and secret omitted, editor optional)\n * @returns Promise<SanitizedConfig> - Built Payload configuration\n */\nexport async function buildFigmaConfig(config: FigmaConfig): Promise<SanitizedConfig> {\n // Validate required environment variable\n if (!config.figma.contentSystemId) {\n throw new Error(\n 'FIGMA_CONTENT_SYSTEM_ID is required. ' +\n 'Ensure your .env file contains: FIGMA_CONTENT_SYSTEM_ID=your-content-system-id',\n )\n }\n\n const DEFAULT_CONTENT_API_URL =\n 'https://us-east-1.cms-tenants-001-staging.figmacontentstaging.com'\n\n const url = process.env.FIGMA_CONTENT_API_URL || DEFAULT_CONTENT_API_URL\n const { contentSystemId } = config.figma\n\n // Determine database adapter based on environment\n let db: Config['db']\n\n if (config.figma.useContentSystem === false) {\n db = config.db!\n } else if (process.env.FIGMA_CONTENT_API_ACCESS_KEY) {\n db = contentAPIAdapter({\n auth: { apiKey: process.env.FIGMA_CONTENT_API_ACCESS_KEY, mode: 'apiKey' },\n contentSystemId,\n url,\n })\n } else if (process.env.FIGMA_DEV_JWT === 'true') {\n db = contentAPIAdapter({\n auth: { mode: 'devJwt' },\n contentSystemId,\n url,\n })\n } else {\n db = contentAPIAdapter({\n auth: { mode: 'tokenStore', tokenStore: getTokenStore() },\n contentSystemId,\n url,\n })\n }\n\n // Build storage plugin if there are upload collections and storage is not disabled\n const uploadCollections = (config.collections || []).filter((c) => c.upload)\n let storagePlugin: ReturnType<typeof cloudStoragePlugin> | undefined\n\n if (uploadCollections.length > 0 && config.figma.storage !== false) {\n const storageConfig: StorageClientConfig = process.env.FIGMA_CONTENT_API_ACCESS_KEY\n ? { baseUrl: url, contentApiKey: process.env.FIGMA_CONTENT_API_ACCESS_KEY }\n : process.env.FIGMA_DEV_JWT === 'true'\n ? {\n auth: { mode: 'devJwt' },\n baseUrl: url,\n contentSystemId,\n }\n : {\n auth: { mode: 'tokenStore', tokenStore: getTokenStore() },\n baseUrl: url,\n contentSystemId,\n }\n\n const adapter = contentApiStorageAdapter(storageConfig)\n\n const collectionsMap = uploadCollections.reduce(\n (acc, c) => {\n acc[c.slug] = { adapter, disableLocalStorage: true }\n return acc\n },\n {} as Record<string, { adapter: typeof adapter; disableLocalStorage: boolean }>,\n )\n\n storagePlugin = cloudStoragePlugin({ collections: collectionsMap })\n }\n\n // Build complete config with Figma platform defaults\n const configWithFigmaDefaults: Config = {\n ...config,\n custom: {\n figma: config.figma || {},\n },\n db,\n editor: config.editor ?? lexicalEditor(),\n endpoints: [...(config.endpoints ?? []), health],\n secret: 'MY_SECRET',\n // Add oauth to plugins if not already present\n plugins: [\n ...(config.plugins ?? []),\n ...(storagePlugin ? [storagePlugin] : []),\n oAuth2Plugin({\n collections: [\n {\n slug: 'users',\n // Use adapter because Figma app doesn't support OIDC scopes\n authorizationURLParams: {\n response_mode: 'query',\n response_type: 'code',\n },\n clientID: process.env.FIGMA_OAUTH_CLIENT_ID!,\n clientSecret: process.env.FIGMA_OAUTH_CLIENT_SECRET,\n identityMetadata: 'https://staging.figma.com/.well-known/openid-configuration',\n scope: ['current_user:read'],\n token: 'id_token', // Adapter creates JWT id_token from Figma user info\n usernameField: 'email',\n },\n ],\n debug: !!process.env.DEBUG,\n disabled: false,\n }),\n ],\n }\n\n // Delegate to Payload's buildConfig\n return await payloadBuildConfig(configWithFigmaDefaults)\n}\n"],"names":["cloudStoragePlugin","lexicalEditor","buildConfig","payloadBuildConfig","getTokenStore","contentAPIAdapter","health","oAuth2Plugin","contentApiStorageAdapter","buildFigmaConfig","config","figma","contentSystemId","Error","DEFAULT_CONTENT_API_URL","url","process","env","FIGMA_CONTENT_API_URL","db","useContentSystem","FIGMA_CONTENT_API_ACCESS_KEY","auth","apiKey","mode","FIGMA_DEV_JWT","tokenStore","uploadCollections","collections","filter","c","upload","storagePlugin","length","storage","storageConfig","baseUrl","contentApiKey","adapter","collectionsMap","reduce","acc","slug","disableLocalStorage","configWithFigmaDefaults","custom","editor","endpoints","secret","plugins","authorizationURLParams","response_mode","response_type","clientID","FIGMA_OAUTH_CLIENT_ID","clientSecret","FIGMA_OAUTH_CLIENT_SECRET","identityMetadata","scope","token","usernameField","debug","DEBUG","disabled"],"mappings":"AAEA,SAASA,kBAAkB,QAAQ,mCAAkC;AACrE,SAASC,aAAa,QAAQ,+BAA8B;AAC5D,SAASC,eAAeC,kBAAkB,QAAQ,UAAS;AAI3D,SAASC,aAAa,QAAQ,yBAAwB;AACtD,SAASC,iBAAiB,QAAQ,6BAA4B;AAC9D,SAASC,MAAM,QAAQ,yBAAwB;AAC/C,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,wBAAwB,QAAQ,kCAAiC;AAmD1E;;;;;;;;;CASC,GACD,OAAO,eAAeC,iBAAiBC,MAAmB;IACxD,yCAAyC;IACzC,IAAI,CAACA,OAAOC,KAAK,CAACC,eAAe,EAAE;QACjC,MAAM,IAAIC,MACR,0CACE;IAEN;IAEA,MA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I,iBAAiBZ,kBAAkBa,MAAM,CAC7C,CAACC,KAAKX;YACJW,GAAG,CAACX,EAAEY,IAAI,CAAC,GAAG;gBAAEJ;gBAASK,qBAAqB;YAAK;YACnD,OAAOF;QACT,GACA,CAAC;QAGHT,gBAAgBhC,mBAAmB;YAAE4B,aAAaW;QAAe;IACnE;IAEA,qDAAqD;IACrD,MAAMK,0BAAkC;QACtC,GAAGlC,MAAM;QACTmC,QAAQ;YACNlC,OAAOD,OAAOC,KAAK,IAAI,CAAC;QAC1B;QACAQ;QACA2B,QAAQpC,OAAOoC,MAAM,IAAI7C;QACzB8C,WAAW;eAAKrC,OAAOqC,SAAS,IAAI,EAAE;YAAGzC;SAAO;QAChD0C,QAAQ;QACR,8CAA8C;QAC9CC,SAAS;eACHvC,OAAOuC,OAAO,IAAI,EAAE;eACpBjB,gBAAgB;gBAACA;aAAc,GAAG,EAAE;YACxCzB,aAAa;gBACXqB,aAAa;oBACX;wBACEc,MAAM;wBACN,4DAA4D;wBAC5DQ,wBAAwB;4BACtBC,eAAe;4BACfC,eAAe;wBACjB;wBACAC,UAAUrC,QAAQC,GAAG,CAACqC,qBAAqB;wBAC3CC,cAAcvC,QAAQC,GAAG,CAACuC,yBAAyB;wBACnDC,kBAAkB;wBAClBC,OAAO;4BAAC;yBAAoB;wBAC5BC,OAAO;wBACPC,eAAe;oBACjB;iBACD;gBACDC,OAAO,CAAC,CAAC7C,QAAQC,GAAG,CAAC6C,KAAK;gBAC1BC,UAAU;YACZ;SACD;IACH;IAEA,oCAAoC;IACpC,OAAO,MAAM5D,mBAAmByC;AAClC"}
|
|
1
|
+
{"version":3,"sources":["../../src/plugin/build-config.ts"],"sourcesContent":["import type { Config, SanitizedConfig } from 'payload'\n\nimport { cloudStoragePlugin } from '@payloadcms/plugin-cloud-storage'\nimport { initClientUploads } from '@payloadcms/plugin-cloud-storage/utilities'\nimport { lexicalEditor } from '@payloadcms/richtext-lexical'\nimport { buildConfig as payloadBuildConfig } from 'payload'\n\nimport type { StorageClientConfig } from '../storage-content-api/index.js'\n\nimport { getTokenStore } from '../auth/token-store.js'\nimport { contentAPIAdapter } from '../db-content-api/index.js'\nimport { health } from '../endpoints/health.js'\nimport { oAuth2Plugin } from '../oauth/index.js'\nimport { createStorageClient } from '../storage-content-api/client.js'\nimport { getGenerateSignedURLHandler } from '../storage-content-api/client-uploads/generateSignedURL.js'\nimport { contentApiStorageAdapter } from '../storage-content-api/index.js'\n\n/**\n * Configuration type for Payload projects on the Figma platform.\n *\n * Differences from standard Payload Config:\n * - `db`: Omitted (auto-injected by Figma platform)\n * - `secret`: Omitted (auto-injected by Figma platform)\n * - `editor`: Optional (defaults to lexicalEditor() if not provided)\n *\n * @example\n * // Minimal config\n * const config: FigmaConfig = {\n * figma: {\n * contentSystemId: process.env.FIGMA_CONTENT_SYSTEM_ID!\n * },\n * collections: [...]\n * }\n *\n * @example\n * // With custom editor\n * const config: FigmaConfig = {\n * figma: {\n * contentSystemId: process.env.FIGMA_CONTENT_SYSTEM_ID!\n * },\n * collections: [...],\n * editor: lexicalEditor({ features: [...] })\n * }\n *\n * @example\n * // Disable Content System (use custom db)\n * const config: FigmaConfig = {\n * figma: {\n * contentSystemId: process.env.FIGMA_CONTENT_SYSTEM_ID!,\n * useContentSystem: false\n * },\n * db: mongooseAdapter({ url: process.env.DATABASE_URI }),\n * collections: [...]\n * }\n */\nexport type FigmaConfig = {\n editor?: Config['editor']\n} & {\n figma: {\n contentSystemId: string\n storage?: boolean\n useContentSystem?: boolean\n }\n} & Omit<Config, 'db' | 'editor' | 'secret'> &\n Partial<Pick<Config, 'db'>>\n\n/**\n * Figma platform wrapper for Payload's buildConfig.\n * Automatically injects:\n * - Figma database adapter\n * - Secret (platform-provided)\n * - Default lexicalEditor (if no custom editor specified)\n *\n * @param config - Payload configuration (db and secret omitted, editor optional)\n * @returns Promise<SanitizedConfig> - Built Payload configuration\n */\nexport async function buildFigmaConfig(config: FigmaConfig): Promise<SanitizedConfig> {\n // Validate required environment variable\n if (!config.figma.contentSystemId) {\n throw new Error(\n 'FIGMA_CONTENT_SYSTEM_ID is required. ' +\n 'Ensure your .env file contains: FIGMA_CONTENT_SYSTEM_ID=your-content-system-id',\n )\n }\n\n const DEFAULT_CONTENT_API_URL =\n 'https://us-east-1.cms-tenants-001-staging.figmacontentstaging.com'\n\n const url = process.env.FIGMA_CONTENT_API_URL || DEFAULT_CONTENT_API_URL\n const { contentSystemId } = config.figma\n\n // Determine database adapter based on environment\n let db: Config['db']\n\n if (config.figma.useContentSystem === false) {\n db = config.db!\n } else if (process.env.FIGMA_CONTENT_API_ACCESS_KEY) {\n db = contentAPIAdapter({\n auth: { apiKey: process.env.FIGMA_CONTENT_API_ACCESS_KEY, mode: 'apiKey' },\n contentSystemId,\n url,\n })\n } else if (process.env.FIGMA_DEV_JWT === 'true') {\n db = contentAPIAdapter({\n auth: { mode: 'devJwt' },\n contentSystemId,\n url,\n })\n } else {\n db = contentAPIAdapter({\n auth: { mode: 'tokenStore', tokenStore: getTokenStore() },\n contentSystemId,\n url,\n })\n }\n\n // Build storage plugin if there are upload collections and storage is not disabled\n const uploadCollections = (config.collections || []).filter((c) => c.upload)\n let storagePlugin: ReturnType<typeof cloudStoragePlugin> | undefined\n\n if (uploadCollections.length > 0 && config.figma.storage !== false) {\n const storageConfig: StorageClientConfig = process.env.FIGMA_CONTENT_API_ACCESS_KEY\n ? { baseUrl: url, contentApiKey: process.env.FIGMA_CONTENT_API_ACCESS_KEY }\n : process.env.FIGMA_DEV_JWT === 'true'\n ? {\n auth: { mode: 'devJwt' },\n baseUrl: url,\n contentSystemId,\n }\n : {\n auth: { mode: 'tokenStore', tokenStore: getTokenStore() },\n baseUrl: url,\n contentSystemId,\n }\n\n const adapter = contentApiStorageAdapter(storageConfig)\n const storageClient = createStorageClient(storageConfig)\n\n const collectionsMap = uploadCollections.reduce(\n (acc, c) => {\n acc[c.slug] = { adapter, disableLocalStorage: true }\n return acc\n },\n {} as Record<string, { adapter: typeof adapter; disableLocalStorage: boolean }>,\n )\n\n initClientUploads({\n clientHandler: '@payloadcms/figma/client#ContentApiClientUploadHandler',\n collections: collectionsMap,\n config: config as unknown as Config,\n enabled: true,\n serverHandler: getGenerateSignedURLHandler({ client: storageClient }),\n serverHandlerPath: '/content-api-storage-signed-url',\n })\n\n storagePlugin = cloudStoragePlugin({ collections: collectionsMap })\n }\n\n // Build complete config with Figma platform defaults\n const configWithFigmaDefaults: Config = {\n ...config,\n custom: {\n figma: config.figma || {},\n },\n db,\n editor: config.editor ?? lexicalEditor(),\n endpoints: [...(config.endpoints ?? []), health],\n secret: 'MY_SECRET',\n // Add oauth to plugins if not already present\n plugins: [\n ...(config.plugins ?? []),\n ...(storagePlugin ? [storagePlugin] : []),\n oAuth2Plugin({\n collections: [\n {\n slug: 'users',\n // Use adapter because Figma app doesn't support OIDC scopes\n authorizationURLParams: {\n response_mode: 'query',\n response_type: 'code',\n },\n clientID: process.env.FIGMA_OAUTH_CLIENT_ID!,\n clientSecret: process.env.FIGMA_OAUTH_CLIENT_SECRET,\n identityMetadata: 'https://staging.figma.com/.well-known/openid-configuration',\n scope: ['current_user:read'],\n token: 'id_token', // Adapter creates JWT id_token from Figma user info\n usernameField: 'email',\n },\n ],\n debug: !!process.env.DEBUG,\n disabled: false,\n }),\n ],\n }\n\n // Delegate to Payload's buildConfig\n return await payloadBuildConfig(configWithFigmaDefaults)\n}\n"],"names":["cloudStoragePlugin","initClientUploads","lexicalEditor","buildConfig","payloadBuildConfig","getTokenStore","contentAPIAdapter","health","oAuth2Plugin","createStorageClient","getGenerateSignedURLHandler","contentApiStorageAdapter","buildFigmaConfig","config","figma","contentSystemId","Error","DEFAULT_CONTENT_API_URL","url","process","env","FIGMA_CONTENT_API_URL","db","useContentSystem","FIGMA_CONTENT_API_ACCESS_KEY","auth","apiKey","mode","FIGMA_DEV_JWT","tokenStore","uploadCollections","collections","filter","c","upload","storagePlugin","length","storage","storageConfig","baseUrl","contentApiKey","adapter","storageClient","collectionsMap","reduce","acc","slug","disableLocalStorage","clientHandler","enabled","serverHandler","client","serverHandlerPath","configWithFigmaDefaults","custom","editor","endpoints","secret","plugins","authorizationURLParams","response_mode","response_type","clientID","FIGMA_OAUTH_CLIENT_ID","clientSecret","FIGMA_OAUTH_CLIENT_SECRET","identityMetadata","scope","token","usernameField","debug","DEBUG","disabled"],"mappings":"AAEA,SAASA,kBAAkB,QAAQ,mCAAkC;AACrE,SAASC,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,aAAa,QAAQ,+BAA8B;AAC5D,SAASC,eAAeC,kBAAkB,QAAQ,UAAS;AAI3D,SAASC,aAAa,QAAQ,yBAAwB;AACtD,SAASC,iBAAiB,QAAQ,6BAA4B;AAC9D,SAASC,MAAM,QAAQ,yBAAwB;AAC/C,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,mBAAmB,QAAQ,mCAAkC;AACtE,SAASC,2BAA2B,QAAQ,6DAA4D;AACxG,SAASC,wBAAwB,QAAQ,kCAAiC;AAmD1E;;;;;;;;;CASC,GACD,OAAO,eAAeC,iBAAiBC,MAAmB;IACxD,yCAAyC;IACzC,IAAI,CAACA,OAAOC,KAAK,CAACC,eAAe,EAAE;QACjC,MAAM,IAAIC,MACR,0CACE;IAEN;IAEA,MAAMC,0BACJ;IAEF,MAAMC,MAAMC,QAAQC,GAAG,CAACC,qBAAqB,IAAIJ;IACjD,MAAM,EAAEF,eAAe,EAAE,GAAGF,OAAOC,KAAK;IAExC,kDAAkD;IAClD,IAAIQ;IAEJ,IAAIT,OAAOC,KAAK,CAACS,gBAAgB,KAAK,OAAO;QAC3CD,KAAKT,OAAOS,EAAE;IAChB,OAAO,IAAIH,QAAQC,GAAG,CAACI,4BAA4B,EAAE;QACnDF,KAAKhB,kBAAkB;YACrBmB,MAAM;gBAAEC,QAAQP,QAAQC,GAAG,CAACI,4BAA4B;gBAAEG,MAAM;YAAS;YACzEZ;YACAG;QACF;IACF,OAAO,IAAIC,QAAQC,GAAG,CAACQ,aA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,QAAQ;YACNxC,OAAOD,OAAOC,KAAK,IAAI,CAAC;QAC1B;QACAQ;QACAiC,QAAQ1C,OAAO0C,MAAM,IAAIrD;QACzBsD,WAAW;eAAK3C,OAAO2C,SAAS,IAAI,EAAE;YAAGjD;SAAO;QAChDkD,QAAQ;QACR,8CAA8C;QAC9CC,SAAS;eACH7C,OAAO6C,OAAO,IAAI,EAAE;eACpBvB,gBAAgB;gBAACA;aAAc,GAAG,EAAE;YACxC3B,aAAa;gBACXuB,aAAa;oBACX;wBACEe,MAAM;wBACN,4DAA4D;wBAC5Da,wBAAwB;4BACtBC,eAAe;4BACfC,eAAe;wBACjB;wBACAC,UAAU3C,QAAQC,GAAG,CAAC2C,qBAAqB;wBAC3CC,cAAc7C,QAAQC,GAAG,CAAC6C,yBAAyB;wBACnDC,kBAAkB;wBAClBC,OAAO;4BAAC;yBAAoB;wBAC5BC,OAAO;wBACPC,eAAe;oBACjB;iBACD;gBACDC,OAAO,CAAC,CAACnD,QAAQC,GAAG,CAACmD,KAAK;gBAC1BC,UAAU;YACZ;SACD;IACH;IAEA,oCAAoC;IACpC,OAAO,MAAMpE,mBAAmBiD;AAClC"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export declare const ContentApiClientUploadHandler: ({ children, collectionSlug, enabled, extra, prefix, serverHandlerPath, }: {
|
|
2
|
+
children: import("react").ReactNode;
|
|
3
|
+
collectionSlug: import("payload").UploadCollectionSlug;
|
|
4
|
+
enabled?: boolean;
|
|
5
|
+
extra: Record<string, unknown>;
|
|
6
|
+
prefix?: string;
|
|
7
|
+
serverHandlerPath: `/${string}`;
|
|
8
|
+
}) => import("react").JSX.Element;
|
|
9
|
+
//# sourceMappingURL=ClientUploadHandler.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ClientUploadHandler.d.ts","sourceRoot":"","sources":["../../../src/storage-content-api/client-uploads/ClientUploadHandler.tsx"],"names":[],"mappings":"AAGA,eAAO,MAAM,6BAA6B;;;;;;;aAoBf,OAAO,aAiBhC,CAAA"}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { createClientUploadHandler } from '@payloadcms/plugin-cloud-storage/client';
|
|
3
|
+
export const ContentApiClientUploadHandler = createClientUploadHandler({
|
|
4
|
+
handler: async ({ apiRoute, collectionSlug, file, prefix, serverHandlerPath, serverURL })=>{
|
|
5
|
+
// Build endpoint URL: serverURL + apiRoute + serverHandlerPath
|
|
6
|
+
const endpointRoute = `${serverURL}${apiRoute}${serverHandlerPath}`;
|
|
7
|
+
const response = await fetch(endpointRoute, {
|
|
8
|
+
body: JSON.stringify({
|
|
9
|
+
collectionSlug,
|
|
10
|
+
filename: file.name,
|
|
11
|
+
mimeType: file.type
|
|
12
|
+
}),
|
|
13
|
+
credentials: 'include',
|
|
14
|
+
headers: {
|
|
15
|
+
'Content-Type': 'application/json'
|
|
16
|
+
},
|
|
17
|
+
method: 'POST'
|
|
18
|
+
});
|
|
19
|
+
if (!response.ok) {
|
|
20
|
+
throw new Error(`Failed to get presigned URL: ${response.status} ${response.statusText}`);
|
|
21
|
+
}
|
|
22
|
+
const { url } = await response.json();
|
|
23
|
+
const uploadResponse = await fetch(url, {
|
|
24
|
+
body: file,
|
|
25
|
+
headers: {
|
|
26
|
+
'Content-Type': file.type
|
|
27
|
+
},
|
|
28
|
+
method: 'PUT'
|
|
29
|
+
});
|
|
30
|
+
if (!uploadResponse.ok) {
|
|
31
|
+
throw new Error(`Failed to upload to S3: ${uploadResponse.status} ${uploadResponse.statusText}`);
|
|
32
|
+
}
|
|
33
|
+
// Include original filename so handleUpload can distinguish from resized versions
|
|
34
|
+
return {
|
|
35
|
+
clientUploaded: true,
|
|
36
|
+
filename: file.name,
|
|
37
|
+
prefix
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
//# sourceMappingURL=ClientUploadHandler.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/storage-content-api/client-uploads/ClientUploadHandler.tsx"],"sourcesContent":["'use client'\nimport { createClientUploadHandler } from '@payloadcms/plugin-cloud-storage/client'\n\nexport const ContentApiClientUploadHandler = createClientUploadHandler({\n handler: async ({ apiRoute, collectionSlug, file, prefix, serverHandlerPath, serverURL }) => {\n // Build endpoint URL: serverURL + apiRoute + serverHandlerPath\n const endpointRoute = `${serverURL}${apiRoute}${serverHandlerPath}`\n\n const response = await fetch(endpointRoute, {\n body: JSON.stringify({\n collectionSlug,\n filename: file.name,\n mimeType: file.type,\n }),\n credentials: 'include',\n headers: { 'Content-Type': 'application/json' },\n method: 'POST',\n })\n\n if (!response.ok) {\n throw new Error(`Failed to get presigned URL: ${response.status} ${response.statusText}`)\n }\n\n const { url } = (await response.json()) as { url: string }\n\n const uploadResponse = await fetch(url, {\n body: file,\n headers: { 'Content-Type': file.type },\n method: 'PUT',\n })\n\n if (!uploadResponse.ok) {\n throw new Error(\n `Failed to upload to S3: ${uploadResponse.status} ${uploadResponse.statusText}`,\n )\n }\n\n // Include original filename so handleUpload can distinguish from resized versions\n return { clientUploaded: true, filename: file.name, prefix }\n },\n})\n"],"names":["createClientUploadHandler","ContentApiClientUploadHandler","handler","apiRoute","collectionSlug","file","prefix","serverHandlerPath","serverURL","endpointRoute","response","fetch","body","JSON","stringify","filename","name","mimeType","type","credentials","headers","method","ok","Error","status","statusText","url","json","uploadResponse","clientUploaded"],"mappings":"AAAA;AACA,SAASA,yBAAyB,QAAQ,0CAAyC;AAEnF,OAAO,MAAMC,gCAAgCD,0BAA0B;IACrEE,SAAS,OAAO,EAAEC,QAAQ,EAAEC,cAAc,EAAEC,IAAI,EAAEC,MAAM,EAAEC,iBAAiB,EAAEC,SAAS,EAAE;QACtF,+DAA+D;QAC/D,MAAMC,gBAAgB,GAAGD,YAAYL,WAAWI,mBAAmB;QAEnE,MAAMG,WAAW,MAAMC,MAAMF,eAAe;YAC1CG,MAAMC,KAAKC,SAAS,CAAC;gBACnBV;gBACAW,UAAUV,KAAKW,IAAI;gBACnBC,UAAUZ,KAAKa,IAAI;YACrB;YACAC,aAAa;YACbC,SAAS;gBAAE,gBAAgB;YAAmB;YAC9CC,QAAQ;QACV;QAEA,IAAI,CAACX,SAASY,EAAE,EAAE;YAChB,MAAM,IAAIC,MAAM,CAAC,6BAA6B,EAAEb,SAASc,MAAM,CAAC,CAAC,EAAEd,SAASe,UAAU,EAAE;QAC1F;QAEA,MAAM,EAAEC,GAAG,EAAE,GAAI,MAAMhB,SAASiB,IAAI;QAEpC,MAAMC,iBAAiB,MAAMjB,MAAMe,KAAK;YACtCd,MAAMP;YACNe,SAAS;gBAAE,gBAAgBf,KAAKa,IAAI;YAAC;YACrCG,QAAQ;QACV;QAEA,IAAI,CAACO,eAAeN,EAAE,EAAE;YACtB,MAAM,IAAIC,MACR,CAAC,wBAAwB,EAAEK,eAAeJ,MAAM,CAAC,CAAC,EAAEI,eAAeH,UAAU,EAAE;QAEnF;QAEA,kFAAkF;QAClF,OAAO;YAAEI,gBAAgB;YAAMd,UAAUV,KAAKW,IAAI;YAAEV;QAAO;IAC7D;AACF,GAAE"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { PayloadHandler } from 'payload';
|
|
2
|
+
import type { StorageClient } from '../client.js';
|
|
3
|
+
type ClientUploadsAccess = (args: {
|
|
4
|
+
collectionSlug: string;
|
|
5
|
+
req: Parameters<PayloadHandler>[0];
|
|
6
|
+
}) => boolean | Promise<boolean>;
|
|
7
|
+
type Args = {
|
|
8
|
+
access?: ClientUploadsAccess;
|
|
9
|
+
client: StorageClient;
|
|
10
|
+
};
|
|
11
|
+
export declare const getGenerateSignedURLHandler: ({ access, client, }: Args) => PayloadHandler;
|
|
12
|
+
export {};
|
|
13
|
+
//# sourceMappingURL=generateSignedURL.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generateSignedURL.d.ts","sourceRoot":"","sources":["../../../src/storage-content-api/client-uploads/generateSignedURL.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAI7C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAA;AAEjD,KAAK,mBAAmB,GAAG,CAAC,IAAI,EAAE;IAChC,cAAc,EAAE,MAAM,CAAA;IACtB,GAAG,EAAE,UAAU,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAA;CACnC,KAAK,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;AAEhC,KAAK,IAAI,GAAG;IACV,MAAM,CAAC,EAAE,mBAAmB,CAAA;IAC5B,MAAM,EAAE,aAAa,CAAA;CACtB,CAAA;AAID,eAAO,MAAM,2BAA2B,wBAGrC,IAAI,KAAG,cA0BT,CAAA"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { APIError, Forbidden } from 'payload';
|
|
2
|
+
const defaultAccess = ({ req })=>!!req.user;
|
|
3
|
+
export const getGenerateSignedURLHandler = ({ access = defaultAccess, client })=>{
|
|
4
|
+
return async (req)=>{
|
|
5
|
+
if (!req.json) {
|
|
6
|
+
throw new APIError('Content-Type expected to be application/json', 400);
|
|
7
|
+
}
|
|
8
|
+
const { collectionSlug, filename, mimeType } = await req.json();
|
|
9
|
+
if (!await access({
|
|
10
|
+
collectionSlug,
|
|
11
|
+
req
|
|
12
|
+
})) {
|
|
13
|
+
throw new Forbidden();
|
|
14
|
+
}
|
|
15
|
+
const { data, error } = await client.POST('/api/v0/uploads/sign', {
|
|
16
|
+
body: {
|
|
17
|
+
contentType: mimeType,
|
|
18
|
+
expiresIn: 3600,
|
|
19
|
+
filename
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
if (error || !data) {
|
|
23
|
+
throw new APIError(`Failed to get presigned upload URL: ${JSON.stringify(error)}`);
|
|
24
|
+
}
|
|
25
|
+
return Response.json({
|
|
26
|
+
url: data.url
|
|
27
|
+
});
|
|
28
|
+
};
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
//# sourceMappingURL=generateSignedURL.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/storage-content-api/client-uploads/generateSignedURL.ts"],"sourcesContent":["import type { PayloadHandler } from 'payload'\n\nimport { APIError, Forbidden } from 'payload'\n\nimport type { StorageClient } from '../client.js'\n\ntype ClientUploadsAccess = (args: {\n collectionSlug: string\n req: Parameters<PayloadHandler>[0]\n}) => boolean | Promise<boolean>\n\ntype Args = {\n access?: ClientUploadsAccess\n client: StorageClient\n}\n\nconst defaultAccess: ClientUploadsAccess = ({ req }) => !!req.user\n\nexport const getGenerateSignedURLHandler = ({\n access = defaultAccess,\n client,\n}: Args): PayloadHandler => {\n return async (req) => {\n if (!req.json) {\n throw new APIError('Content-Type expected to be application/json', 400)\n }\n\n const { collectionSlug, filename, mimeType } = (await req.json()) as {\n collectionSlug: string\n filename: string\n mimeType: string\n }\n\n if (!(await access({ collectionSlug, req }))) {\n throw new Forbidden()\n }\n\n const { data, error } = await client.POST('/api/v0/uploads/sign', {\n body: { contentType: mimeType, expiresIn: 3600, filename },\n })\n\n if (error || !data) {\n throw new APIError(`Failed to get presigned upload URL: ${JSON.stringify(error)}`)\n }\n\n return Response.json({ url: data.url })\n }\n}\n"],"names":["APIError","Forbidden","defaultAccess","req","user","getGenerateSignedURLHandler","access","client","json","collectionSlug","filename","mimeType","data","error","POST","body","contentType","expiresIn","JSON","stringify","Response","url"],"mappings":"AAEA,SAASA,QAAQ,EAAEC,SAAS,QAAQ,UAAS;AAc7C,MAAMC,gBAAqC,CAAC,EAAEC,GAAG,EAAE,GAAK,CAAC,CAACA,IAAIC,IAAI;AAElE,OAAO,MAAMC,8BAA8B,CAAC,EAC1CC,SAASJ,aAAa,EACtBK,MAAM,EACD;IACL,OAAO,OAAOJ;QACZ,IAAI,CAACA,IAAIK,IAAI,EAAE;YACb,MAAM,IAAIR,SAAS,gDAAgD;QACrE;QAEA,MAAM,EAAES,cAAc,EAAEC,QAAQ,EAAEC,QAAQ,EAAE,GAAI,MAAMR,IAAIK,IAAI;QAM9D,IAAI,CAAE,MAAMF,OAAO;YAAEG;YAAgBN;QAAI,IAAK;YAC5C,MAAM,IAAIF;QACZ;QAEA,MAAM,EAAEW,IAAI,EAAEC,KAAK,EAAE,GAAG,MAAMN,OAAOO,IAAI,CAAC,wBAAwB;YAChEC,MAAM;gBAAEC,aAAaL;gBAAUM,WAAW;gBAAMP;YAAS;QAC3D;QAEA,IAAIG,SAAS,CAACD,MAAM;YAClB,MAAM,IAAIZ,SAAS,CAAC,oCAAoC,EAAEkB,KAAKC,SAAS,CAACN,QAAQ;QACnF;QAEA,OAAOO,SAASZ,IAAI,CAAC;YAAEa,KAAKT,KAAKS,GAAG;QAAC;IACvC;AACF,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handleUpload.d.ts","sourceRoot":"","sources":["../../src/storage-content-api/handleUpload.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,wCAAwC,CAAA;AAC1E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAK/C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAEhD,KAAK,IAAI,GAAG;IACV,MAAM,EAAE,aAAa,CAAA;IACrB,UAAU,EAAE,gBAAgB,CAAA;IAC5B,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB,CAAA;
|
|
1
|
+
{"version":3,"file":"handleUpload.d.ts","sourceRoot":"","sources":["../../src/storage-content-api/handleUpload.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,wCAAwC,CAAA;AAC1E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAK/C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAEhD,KAAK,IAAI,GAAG;IACV,MAAM,EAAE,aAAa,CAAA;IACrB,UAAU,EAAE,gBAAgB,CAAA;IAC5B,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB,CAAA;AAKD,eAAO,MAAM,eAAe,uBAA6B,IAAI,KAAG,YAmC/D,CAAA"}
|
|
@@ -1,13 +1,23 @@
|
|
|
1
1
|
import fs from 'fs';
|
|
2
2
|
import path from 'path';
|
|
3
|
-
const PART_SIZE =
|
|
3
|
+
const PART_SIZE = 64 * 1024 * 1024 // 64MB per part
|
|
4
|
+
;
|
|
5
|
+
const MAX_FILE_SIZE_BEFORE_MULTIPART = 100 * 1024 * 1024 // 100MB
|
|
4
6
|
;
|
|
5
7
|
export const getHandleUpload = ({ client, prefix = '' })=>{
|
|
6
|
-
return async ({ data, file })=>{
|
|
8
|
+
return async ({ clientUploadContext, data, file })=>{
|
|
9
|
+
// Skip if client already uploaded THIS SPECIFIC file
|
|
10
|
+
// clientUploadContext.filename contains the original filename that was client-uploaded
|
|
11
|
+
// Resized versions (different filename) should still be uploaded
|
|
12
|
+
const clientUploadedFilename = clientUploadContext && typeof clientUploadContext === 'object' && 'filename' in clientUploadContext ? clientUploadContext.filename : undefined;
|
|
13
|
+
const isOriginalClientUploaded = clientUploadContext && typeof clientUploadContext === 'object' && 'clientUploaded' in clientUploadContext && clientUploadContext.clientUploaded && file.filename === clientUploadedFilename;
|
|
14
|
+
if (isOriginalClientUploaded) {
|
|
15
|
+
return data;
|
|
16
|
+
}
|
|
7
17
|
const fileKey = path.posix.join(data.prefix || prefix, file.filename);
|
|
8
18
|
const fileData = file.tempFilePath ? fs.readFileSync(file.tempFilePath) : file.buffer;
|
|
9
19
|
const fileSize = file.filesize || fileData.length;
|
|
10
|
-
if (fileSize >
|
|
20
|
+
if (fileSize > MAX_FILE_SIZE_BEFORE_MULTIPART) {
|
|
11
21
|
await uploadMultipart({
|
|
12
22
|
client,
|
|
13
23
|
fileData,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/storage-content-api/handleUpload.ts"],"sourcesContent":["import type { HandleUpload } from '@payloadcms/plugin-cloud-storage/types'\nimport type { CollectionConfig } from 'payload'\n\nimport fs from 'fs'\nimport path from 'path'\n\nimport type { StorageClient } from './client.js'\n\ntype Args = {\n client: StorageClient\n collection: CollectionConfig\n prefix?: string\n}\n\nconst PART_SIZE =
|
|
1
|
+
{"version":3,"sources":["../../src/storage-content-api/handleUpload.ts"],"sourcesContent":["import type { HandleUpload } from '@payloadcms/plugin-cloud-storage/types'\nimport type { CollectionConfig } from 'payload'\n\nimport fs from 'fs'\nimport path from 'path'\n\nimport type { StorageClient } from './client.js'\n\ntype Args = {\n client: StorageClient\n collection: CollectionConfig\n prefix?: string\n}\n\nconst PART_SIZE = 64 * 1024 * 1024 // 64MB per part\nconst MAX_FILE_SIZE_BEFORE_MULTIPART = 100 * 1024 * 1024 // 100MB\n\nexport const getHandleUpload = ({ client, prefix = '' }: Args): HandleUpload => {\n return async ({ clientUploadContext, data, file }) => {\n // Skip if client already uploaded THIS SPECIFIC file\n // clientUploadContext.filename contains the original filename that was client-uploaded\n // Resized versions (different filename) should still be uploaded\n const clientUploadedFilename =\n clientUploadContext &&\n typeof clientUploadContext === 'object' &&\n 'filename' in clientUploadContext\n ? clientUploadContext.filename\n : undefined\n\n const isOriginalClientUploaded =\n clientUploadContext &&\n typeof clientUploadContext === 'object' &&\n 'clientUploaded' in clientUploadContext &&\n clientUploadContext.clientUploaded &&\n file.filename === clientUploadedFilename\n\n if (isOriginalClientUploaded) {\n return data\n }\n\n const fileKey = path.posix.join(data.prefix || prefix, file.filename)\n const fileData = file.tempFilePath ? fs.readFileSync(file.tempFilePath) : file.buffer\n const fileSize = file.filesize || fileData.length\n\n if (fileSize > MAX_FILE_SIZE_BEFORE_MULTIPART) {\n await uploadMultipart({ client, fileData, fileKey, mimeType: file.mimeType })\n } else {\n await uploadSingleFile({ client, fileData, fileKey, mimeType: file.mimeType })\n }\n\n return data\n }\n}\n\nasync function uploadSingleFile({\n client,\n fileData,\n fileKey,\n mimeType,\n}: {\n client: StorageClient\n fileData: Buffer\n fileKey: string\n mimeType: string\n}): Promise<void> {\n const { data, error } = await client.POST('/api/v0/uploads/sign', {\n body: { contentType: mimeType, expiresIn: 3600, filename: fileKey },\n })\n\n if (error || !data) {\n throw new Error(`Failed to get presigned upload URL: ${JSON.stringify(error)}`)\n }\n\n const uploadResponse = await fetch(data.url, {\n body: fileData,\n headers: { 'Content-Type': mimeType },\n method: 'PUT',\n })\n\n if (!uploadResponse.ok) {\n throw new Error(`Failed to upload to S3: ${uploadResponse.status} ${uploadResponse.statusText}`)\n }\n}\n\nasync function uploadMultipart({\n client,\n fileData,\n fileKey,\n mimeType,\n}: {\n client: StorageClient\n fileData: Buffer\n fileKey: string\n mimeType: string\n}): Promise<void> {\n const { data: initiateData, error: initiateError } = await client.POST(\n '/api/v0/uploads/multipart/initiate',\n {\n body: { contentType: mimeType, filename: fileKey },\n },\n )\n\n if (initiateError || !initiateData) {\n throw new Error(`Failed to initiate multipart upload: ${JSON.stringify(initiateError)}`)\n }\n\n const { uploadId } = initiateData\n\n try {\n const numParts = Math.ceil(fileData.length / PART_SIZE)\n const partNumbers = Array.from({ length: numParts }, (_, i) => i + 1)\n\n const { data: partsData, error: partsError } = await client.POST(\n '/api/v0/uploads/multipart/parts',\n {\n body: { expiresIn: 3600, filename: fileKey, partNumbers, uploadId },\n },\n )\n\n if (partsError || !partsData) {\n throw new Error(`Failed to get part URLs: ${JSON.stringify(partsError)}`)\n }\n\n const { parts } = partsData\n\n if (!parts || !Array.isArray(parts)) {\n throw new Error('Invalid response from part URLs endpoint: parts is not an array')\n }\n\n const uploadedParts = await Promise.all(\n parts.map(async ({ partNumber, url }) => {\n const start = (partNumber - 1) * PART_SIZE\n const end = Math.min(start + PART_SIZE, fileData.length)\n const partData = fileData.slice(start, end)\n\n const uploadResponse = await fetch(url, {\n body: partData,\n headers: { 'Content-Type': mimeType },\n method: 'PUT',\n })\n\n const etag = uploadResponse.headers.get('ETag')\n if (!etag) {\n throw new Error(`No ETag returned for part ${partNumber}`)\n }\n\n return { ETag: etag, PartNumber: partNumber }\n }),\n )\n\n const { error: completeError } = await client.POST('/api/v0/uploads/multipart/complete', {\n body: { filename: fileKey, parts: uploadedParts, uploadId },\n })\n\n if (completeError) {\n throw new Error(`Failed to complete multipart upload: ${JSON.stringify(completeError)}`)\n }\n } catch (error) {\n try {\n await client.POST('/api/v0/uploads/multipart/abort', {\n body: { filename: fileKey, uploadId },\n })\n } catch {\n // Ignore abort errors\n }\n throw error\n }\n}\n"],"names":["fs","path","PART_SIZE","MAX_FILE_SIZE_BEFORE_MULTIPART","getHandleUpload","client","prefix","clientUploadContext","data","file","clientUploadedFilename","filename","undefined","isOriginalClientUploaded","clientUploaded","fileKey","posix","join","fileData","tempFilePath","readFileSync","buffer","fileSize","filesize","length","uploadMultipart","mimeType","uploadSingleFile","error","POST","body","contentType","expiresIn","Error","JSON","stringify","uploadResponse","fetch","url","headers","method","ok","status","statusText","initiateData","initiateError","uploadId","numParts","Math","ceil","partNumbers","Array","from","_","i","partsData","partsError","parts","isArray","uploadedParts","Promise","all","map","partNumber","start","end","min","partData","slice","etag","get","ETag","PartNumber","completeError"],"mappings":"AAGA,OAAOA,QAAQ,KAAI;AACnB,OAAOC,UAAU,OAAM;AAUvB,MAAMC,YAAY,KAAK,OAAO,KAAK,gBAAgB;;AACnD,MAAMC,iCAAiC,MAAM,OAAO,KAAK,QAAQ;;AAEjE,OAAO,MAAMC,kBAAkB,CAAC,EAAEC,MAAM,EAAEC,SAAS,EAAE,EAAQ;IAC3D,OAAO,OAAO,EAAEC,mBAAmB,EAAEC,IAAI,EAAEC,IAAI,EAAE;QAC/C,qDAAqD;QACrD,uFAAuF;QACvF,iEAAiE;QACjE,MAAMC,yBACJH,uBACA,OAAOA,wBAAwB,YAC/B,cAAcA,sBACVA,oBAAoBI,QAAQ,GAC5BC;QAEN,MAAMC,2BACJN,uBACA,OAAOA,wBAAwB,YAC/B,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I,KAAG,
|
|
1
|
+
{"version":3,"file":"staticHandler.d.ts","sourceRoot":"","sources":["../../src/storage-content-api/staticHandler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,wCAAwC,CAAA;AAC3E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAK/C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAEhD,KAAK,IAAI,GAAG;IACV,MAAM,EAAE,aAAa,CAAA;IACrB,UAAU,EAAE,gBAAgB,CAAA;CAC7B,CAAA;AAED,eAAO,MAAM,UAAU,2BAA4B,IAAI,KAAG,aAuCzD,CAAA"}
|
|
@@ -22,9 +22,29 @@ export const getHandler = ({ client, collection })=>{
|
|
|
22
22
|
status: 500
|
|
23
23
|
});
|
|
24
24
|
}
|
|
25
|
-
|
|
25
|
+
// Fetch file bytes from S3 (required for Payload's image processing)
|
|
26
|
+
const fileResponse = await fetch(data.url);
|
|
27
|
+
if (!fileResponse.ok) {
|
|
28
|
+
req.payload.logger.error(`S3 fetch failed: ${fileResponse.status} ${fileResponse.statusText}`);
|
|
29
|
+
return new Response('Failed to fetch file from storage', {
|
|
30
|
+
status: 502
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
const contentType = fileResponse.headers.get('content-type') || 'application/octet-stream';
|
|
34
|
+
const contentLength = fileResponse.headers.get('content-length');
|
|
35
|
+
return new Response(fileResponse.body, {
|
|
36
|
+
headers: {
|
|
37
|
+
'Content-Type': contentType,
|
|
38
|
+
...contentLength && {
|
|
39
|
+
'Content-Length': contentLength
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
});
|
|
26
43
|
} catch (err) {
|
|
27
|
-
req.payload.logger.error(
|
|
44
|
+
req.payload.logger.error({
|
|
45
|
+
err,
|
|
46
|
+
msg: 'Error in staticHandler'
|
|
47
|
+
});
|
|
28
48
|
return new Response('Internal Server Error', {
|
|
29
49
|
status: 500
|
|
30
50
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/storage-content-api/staticHandler.ts"],"sourcesContent":["import type { StaticHandler } from '@payloadcms/plugin-cloud-storage/types'\nimport type { CollectionConfig } from 'payload'\n\nimport { getFilePrefix } from '@payloadcms/plugin-cloud-storage/utilities'\nimport path from 'path'\n\nimport type { StorageClient } from './client.js'\n\ntype Args = {\n client: StorageClient\n collection: CollectionConfig\n}\n\nexport const getHandler = ({ client, collection }: Args): StaticHandler => {\n return async (req, { params: { clientUploadContext, filename } }) => {\n try {\n const prefix = await getFilePrefix({ clientUploadContext, collection, filename, req })\n const key = path.posix.join(prefix, filename)\n\n const { data, error } = await client.POST('/api/v0/uploads/download/sign', {\n body: { expiresIn: 7200, filename: key },\n })\n\n if (error || !data) {\n req.payload.logger.error(`Failed to get signed download URL: ${JSON.stringify(error)}`)\n return new Response('Internal Server Error', { status: 500 })\n }\n\n return Response.
|
|
1
|
+
{"version":3,"sources":["../../src/storage-content-api/staticHandler.ts"],"sourcesContent":["import type { StaticHandler } from '@payloadcms/plugin-cloud-storage/types'\nimport type { CollectionConfig } from 'payload'\n\nimport { getFilePrefix } from '@payloadcms/plugin-cloud-storage/utilities'\nimport path from 'path'\n\nimport type { StorageClient } from './client.js'\n\ntype Args = {\n client: StorageClient\n collection: CollectionConfig\n}\n\nexport const getHandler = ({ client, collection }: Args): StaticHandler => {\n return async (req, { params: { clientUploadContext, filename } }) => {\n try {\n const prefix = await getFilePrefix({ clientUploadContext, collection, filename, req })\n const key = path.posix.join(prefix, filename)\n\n const { data, error } = await client.POST('/api/v0/uploads/download/sign', {\n body: { expiresIn: 7200, filename: key },\n })\n\n if (error || !data) {\n req.payload.logger.error(`Failed to get signed download URL: ${JSON.stringify(error)}`)\n return new Response('Internal Server Error', { status: 500 })\n }\n\n // Fetch file bytes from S3 (required for Payload's image processing)\n const fileResponse = await fetch(data.url)\n\n if (!fileResponse.ok) {\n req.payload.logger.error(\n `S3 fetch failed: ${fileResponse.status} ${fileResponse.statusText}`,\n )\n return new Response('Failed to fetch file from storage', { status: 502 })\n }\n\n const contentType = fileResponse.headers.get('content-type') || 'application/octet-stream'\n const contentLength = fileResponse.headers.get('content-length')\n\n return new Response(fileResponse.body, {\n headers: {\n 'Content-Type': contentType,\n ...(contentLength && { 'Content-Length': contentLength }),\n },\n })\n } catch (err) {\n req.payload.logger.error({ err, msg: 'Error in staticHandler' })\n return new Response('Internal Server Error', { status: 500 })\n }\n }\n}\n"],"names":["getFilePrefix","path","getHandler","client","collection","req","params","clientUploadContext","filename","prefix","key","posix","join","data","error","POST","body","expiresIn","payload","logger","JSON","stringify","Response","status","fileResponse","fetch","url","ok","statusText","contentType","headers","get","contentLength","err","msg"],"mappings":"AAGA,SAASA,aAAa,QAAQ,6CAA4C;AAC1E,OAAOC,UAAU,OAAM;AASvB,OAAO,MAAMC,aAAa,CAAC,EAAEC,MAAM,EAAEC,UAAU,EAAQ;IACrD,OAAO,OAAOC,KAAK,EAAEC,QAAQ,EAAEC,mBAAmB,EAAEC,QAAQ,EAAE,EAAE;QAC9D,IAAI;YACF,MAAMC,SAAS,MAAMT,cAAc;gBAAEO;gBAAqBH;gBAAYI;gBAAUH;YAAI;YACpF,MAAMK,MAAMT,KAAKU,KAAK,CAACC,IAAI,CAACH,QAAQD;YAEpC,MAAM,EAAEK,IAAI,EAAEC,KAAK,EAAE,GAAG,MAAMX,OAAOY,IAAI,CAAC,iCAAiC;gBACzEC,MAAM;oBAAEC,WAAW;oBAAMT,UAAUE;gBAAI;YACzC;YAEA,IAAII,SAAS,CAACD,MAAM;gBAClBR,IAAIa,OAAO,CAACC,MAAM,CAACL,KAAK,CAAC,CAAC,mCAAmC,EAAEM,KAAKC,SAAS,CAACP,QAAQ;gBACtF,OAAO,IAAIQ,SAAS,yBAAyB;oBAAEC,QAAQ;gBAAI;YAC7D;YAEA,qEAAqE;YACrE,MAAMC,eAAe,MAAMC,MAAMZ,KAAKa,GAAG;YAEzC,IAAI,CAACF,aAAaG,EAAE,EAAE;gBACpBtB,IAAIa,OAAO,CAACC,MAAM,CAACL,KAAK,CACtB,CAAC,iBAAiB,EAAEU,aAAaD,MAAM,CAAC,CAAC,EAAEC,aAAaI,UAAU,EAAE;gBAEtE,OAAO,IAAIN,SAAS,qCAAqC;oBAAEC,QAAQ;gBAAI;YACzE;YAEA,MAAMM,cAAcL,aAAaM,OAAO,CAACC,GAAG,CAAC,mBAAmB;YAChE,MAAMC,gBAAgBR,aAAaM,OAAO,CAACC,GAAG,CAAC;YAE/C,OAAO,IAAIT,SAASE,aAAaR,IAAI,EAAE;gBACrCc,SAAS;oBACP,gBAAgBD;oBAChB,GAAIG,iBAAiB;wBAAE,kBAAkBA;oBAAc,CAAC;gBAC1D;YACF;QACF,EAAE,OAAOC,KAAK;YACZ5B,IAAIa,OAAO,CAACC,MAAM,CAACL,KAAK,CAAC;gBAAEmB;gBAAKC,KAAK;YAAyB;YAC9D,OAAO,IAAIZ,SAAS,yBAAyB;gBAAEC,QAAQ;YAAI;QAC7D;IACF;AACF,EAAC"}
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"data.d.ts","sourceRoot":"","sources":["../../../src/db-content-api/utilities/data.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAkC,OAAO,EAA0B,MAAM,SAAS,CAAA;AAI9F,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mCAAmC,CAAA;AAEnE,KAAK,kBAAkB,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC,oBAAoB,CAAC,CAAA;AAErE;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAC9B,OAAO,EAAE,OAAO,EAChB,cAAc,EAAE,MAAM,EACtB,IAAI,EAAE,OAAO,GACZ,kBAAkB,CA2CpB;AAED;;;;;;;;GAQG;AACH,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,OAAO,EAChB,cAAc,EAAE,MAAM,EACtB,IAAI,EAAE,OAAO,GACZ,OAAO,CAgET"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/db-content-api/utilities/data.ts"],"sourcesContent":["import type { CollectionConfig, GlobalConfig, Payload, TraverseFieldsCallback } from 'payload'\n\nimport { traverseFields } from 'payload'\n\nimport type { components } from '../generated/content-api-types.js'\n\ntype DataWithOperations = components['schemas']['DataWithOperations']\n\n/**\n * Transform data before sending to Content API (WRITE operations)\n *\n * Conversions applied:\n * - RichText fields: Objects -> JSON strings\n *\n * Note: Date fields are automatically converted to ISO strings by JSON.stringify()\n */\nexport function dataToContentAPI(\n payload: Payload,\n collectionSlug: string,\n data: unknown,\n): DataWithOperations {\n if (!data || typeof data !== 'object') {\n return data as DataWithOperations\n }\n\n // Deep clone to avoid mutating original data\n const transformed = JSON.parse(JSON.stringify(data))\n\n // Get collection config\n const isGlobal = collectionSlug.startsWith('_global-')\n const actualSlug = isGlobal ? collectionSlug.substring(8) : collectionSlug\n const collectionConfig: CollectionConfig | GlobalConfig | undefined = isGlobal\n ? payload.config.globals?.find((g) => g.slug === actualSlug)\n : payload.config.collections.find((c) => c.slug === actualSlug)\n\n if (!collectionConfig?.fields) {\n return transformed as DataWithOperations\n }\n\n // Use Payload's traverseFields to iterate over all fields\n const callback: TraverseFieldsCallback = ({ field, ref }) => {\n if (!('name' in field) || !field.name) {\n return\n }\n if (!ref || typeof ref !== 'object') {\n return\n }\n\n const current = ref as Record<string, unknown>\n const value = current[field.name]\n\n if (value !== null && value !== undefined) {\n // RichText: object -> JSON string\n if (field.type === 'richText' && typeof value !== 'string') {\n current[field.name] = JSON.stringify(value)\n }\n // Date fields are already handled by JSON.stringify() which converts Date -> ISO string\n }\n }\n\n traverseFields({ callback, fields: collectionConfig.fields, ref: transformed })\n\n return transformed as DataWithOperations\n}\n\n/**\n * Transform data received from Content API (READ operations)\n *\n * Conversions applied:\n * - RichText fields: JSON strings -> Objects\n *\n * Note: Date fields come as ISO strings from Content API and stay as strings\n * (matching MongoDB and other adapters' behavior)\n */\nexport function dataFromContentAPI(\n payload: Payload,\n collectionSlug: string,\n data: unknown,\n): unknown {\n if (!data || typeof data !== 'object') {\n return data\n }\n\n // Deep clone to avoid mutating original data\n const transformed = JSON.parse(JSON.stringify(data))\n\n // Get collection config\n const isGlobal = collectionSlug.startsWith('_global-')\n const actualSlug = isGlobal ? collectionSlug.substring(8) : collectionSlug\n const collectionConfig: CollectionConfig | GlobalConfig | undefined = isGlobal\n ? payload.config.globals?.find((g) => g.slug === actualSlug)\n : payload.config.collections.find((c) => c.slug === actualSlug)\n\n if (!collectionConfig?.fields) {\n return transformed\n }\n\n // Use Payload's traverseFields to iterate over all fields\n const callback: TraverseFieldsCallback = ({ field, parentPath, ref }) => {\n if (!('name' in field) || !field.name) {\n return\n }\n if (!ref || typeof ref !== 'object') {\n return\n }\n\n const current = ref as Record<string, unknown>\n const value = current[field.name]\n\n if (value !== null && value !== undefined) {\n // RichText: JSON string -> object\n if (field.type === 'richText' && typeof value === 'string') {\n try {\n current[field.name] = JSON.parse(value)\n } catch (error) {\n const fieldPath = parentPath ? `${parentPath}.${field.name}` : field.name\n payload.logger.warn({\n err: error instanceof Error ? error : new Error(String(error)),\n msg: `Failed to parse richtext field '${fieldPath}' in collection '${collectionSlug}'`,\n })\n }\n }\n // Date fields: Already ISO strings from Content API, no conversion needed\n }\n }\n\n traverseFields({ callback, fields: collectionConfig.fields, ref: transformed })\n\n // Handle auth-specific fields that aren't in the field schema\n // When these fields are null in DB, Content API omits them from response (undefined)\n // But Payload expects them to be null, not undefined\n // Only add them if the collection has auth enabled\n if ('auth' in collectionConfig && collectionConfig.auth) {\n const authFields = ['resetPasswordExpiration', 'lockUntil']\n for (const fieldName of authFields) {\n if (!(fieldName in (transformed as Record<string, unknown>))) {\n ;(transformed as Record<string, unknown>)[fieldName] = null\n }\n }\n }\n\n return transformed\n}\n"],"names":["traverseFields","dataToContentAPI","payload","collectionSlug","data","transformed","JSON","parse","stringify","isGlobal","startsWith","actualSlug","substring","collectionConfig","config","globals","find","g","slug","collections","c","fields","callback","field","ref","name","current","value","undefined","type","dataFromContentAPI","parentPath","error","fieldPath","logger","warn","err","Error","String","msg","auth","authFields","fieldName"],"mappings":"AAEA,SAASA,cAAc,QAAQ,UAAS;AAMxC;;;;;;;CAOC,GACD,OAAO,SAASC,iBACdC,OAAgB,EAChBC,cAAsB,EACtBC,IAAa;IAEb,IAAI,CAACA,QAAQ,OAAOA,SAAS,UAAU;QACrC,OAAOA;IACT;IAEA,6CAA6C;IAC7C,MAAMC,cAAcC,KAAKC,KAAK,CAACD,KAAKE,SAAS,CAACJ;IAE9C,wBAAwB;IACxB,MAAMK,WAAWN,eAAeO,UAAU,CAAC;IAC3C,MAAMC,aAAaF,WAAWN,eAAeS,SAAS,CAAC,KAAKT;IAC5D,MAAMU,mBAAgEJ,WAClEP,QAAQY,MAAM,CAACC,OAAO,EAAEC,KAAK,CAACC,IAAMA,EAAEC,IAAI,KAAKP,cAC/CT,QAAQY,MAAM,CAACK,WAAW,CAACH,IAAI,CAAC,CAACI,IAAMA,EAAEF,IAAI,KAAKP;IAEtD,IAAI,CAACE,kBAAkBQ,QAAQ;QAC7B,OAAOhB;IACT;IAEA,0DAA0D;IAC1D,MAAMiB,WAAmC,CAAC,EAAEC,KAAK,EAAEC,GAAG,EAAE;QACtD,IAAI,CAAE,CAAA,UAAUD,KAAI,KAAM,CAACA,MAAME,IAAI,EAAE;YACrC;QACF;QACA,IAAI,CAACD,OAAO,OAAOA,QAAQ,UAAU;YACnC;QACF;QAEA,MAAME,UAAUF;QAChB,MAAMG,QAAQD,OAAO,CAACH,MAAME,IAAI,CAAC;QAEjC,IAAIE,UAAU,QAAQA,UAAUC,WAAW;YACzC,kCAAkC;YAClC,IAAIL,MAAMM,IAAI,KAAK,cAAc,OAAOF,UAAU,UAAU;gBAC1DD,OAAO,CAACH,MAAME,IAAI,CAAC,GAAGnB,KAAKE,SAAS,CAACmB;YACvC;QACA,wFAAwF;QAC1F;IACF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