@payloadcms/figma 0.0.1-alpha.29 → 0.0.1-alpha.30
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/api/figma-api.d.ts.map +1 -1
- package/dist/api/figma-api.js +4 -0
- package/dist/api/figma-api.js.map +1 -1
- package/dist/commands/deploy.d.ts.map +1 -1
- package/dist/commands/deploy.js +32 -50
- package/dist/commands/deploy.js.map +1 -1
- package/dist/db-content-api/README.md +108 -0
- package/dist/db-content-api/generated/content-api-types.d.ts +763 -190
- package/dist/db-content-api/generated/content-api-types.d.ts.map +1 -1
- package/dist/db-content-api/generated/content-api-types.js.map +1 -1
- package/dist/db-content-api/index.d.ts +6 -19
- package/dist/db-content-api/index.d.ts.map +1 -1
- package/dist/db-content-api/index.js +396 -687
- package/dist/db-content-api/index.js.map +1 -1
- package/dist/db-content-api/temp-utilities/pagination.d.ts +13 -0
- package/dist/db-content-api/temp-utilities/pagination.d.ts.map +1 -0
- package/dist/db-content-api/temp-utilities/pagination.js +45 -0
- package/dist/db-content-api/temp-utilities/pagination.js.map +1 -0
- package/dist/db-content-api/temp-utilities/slug.d.ts +2 -0
- package/dist/db-content-api/temp-utilities/slug.d.ts.map +1 -0
- package/dist/db-content-api/temp-utilities/slug.js +3 -0
- package/dist/db-content-api/temp-utilities/slug.js.map +1 -0
- package/dist/db-content-api/temp-utilities/sorting.d.ts +7 -0
- package/dist/db-content-api/temp-utilities/sorting.d.ts.map +1 -0
- package/dist/db-content-api/temp-utilities/sorting.js +71 -0
- package/dist/db-content-api/temp-utilities/sorting.js.map +1 -0
- package/dist/db-content-api/temp-utilities/unwrapDocument.d.ts +4 -0
- package/dist/db-content-api/temp-utilities/unwrapDocument.d.ts.map +1 -0
- package/dist/db-content-api/temp-utilities/unwrapDocument.js +45 -0
- package/dist/db-content-api/temp-utilities/unwrapDocument.js.map +1 -0
- package/dist/db-content-api/utilities/auth.d.ts +30 -0
- package/dist/db-content-api/utilities/auth.d.ts.map +1 -0
- package/dist/db-content-api/utilities/auth.js +81 -0
- package/dist/db-content-api/utilities/auth.js.map +1 -0
- package/dist/db-content-api/utilities/data.d.ts +24 -0
- package/dist/db-content-api/utilities/data.d.ts.map +1 -0
- package/dist/db-content-api/utilities/data.js +118 -0
- package/dist/db-content-api/utilities/data.js.map +1 -0
- package/dist/db-content-api/utilities/joins.d.ts +55 -0
- package/dist/db-content-api/utilities/joins.d.ts.map +1 -0
- package/dist/db-content-api/utilities/joins.js +130 -0
- package/dist/db-content-api/utilities/joins.js.map +1 -0
- package/dist/db-content-api/utilities/where.d.ts +12 -0
- package/dist/db-content-api/utilities/where.d.ts.map +1 -0
- package/dist/db-content-api/utilities/where.js +63 -0
- package/dist/db-content-api/utilities/where.js.map +1 -0
- package/dist/plugin/build-config.d.ts +1 -0
- package/dist/plugin/build-config.d.ts.map +1 -1
- package/dist/plugin/build-config.js +38 -0
- package/dist/plugin/build-config.js.map +1 -1
- package/dist/storage-content-api/api-types.d.ts +161 -0
- package/dist/storage-content-api/api-types.d.ts.map +1 -0
- package/dist/storage-content-api/api-types.js +6 -0
- package/dist/storage-content-api/api-types.js.map +1 -0
- package/dist/storage-content-api/client.d.ts +6 -0
- package/dist/storage-content-api/client.d.ts.map +1 -0
- package/dist/storage-content-api/client.js +36 -0
- package/dist/storage-content-api/client.js.map +1 -0
- package/dist/storage-content-api/generateURL.d.ts +7 -0
- package/dist/storage-content-api/generateURL.d.ts.map +1 -0
- package/dist/storage-content-api/generateURL.js +7 -0
- package/dist/storage-content-api/generateURL.js.map +1 -0
- package/dist/storage-content-api/handleDelete.d.ts +8 -0
- package/dist/storage-content-api/handleDelete.d.ts.map +1 -0
- package/dist/storage-content-api/handleDelete.js +15 -0
- package/dist/storage-content-api/handleDelete.js.map +1 -0
- package/dist/storage-content-api/handleUpload.d.ts +11 -0
- package/dist/storage-content-api/handleUpload.d.ts.map +1 -0
- package/dist/storage-content-api/handleUpload.js +126 -0
- package/dist/storage-content-api/handleUpload.js.map +1 -0
- package/dist/storage-content-api/index.d.ts +5 -0
- package/dist/storage-content-api/index.d.ts.map +1 -0
- package/dist/storage-content-api/index.js +31 -0
- package/dist/storage-content-api/index.js.map +1 -0
- package/dist/storage-content-api/staticHandler.d.ts +10 -0
- package/dist/storage-content-api/staticHandler.d.ts.map +1 -0
- package/dist/storage-content-api/staticHandler.js +35 -0
- package/dist/storage-content-api/staticHandler.js.map +1 -0
- package/dist/storage-content-api/types.d.ts +10 -0
- package/dist/storage-content-api/types.d.ts.map +1 -0
- package/dist/storage-content-api/types.js +3 -0
- package/dist/storage-content-api/types.js.map +1 -0
- package/dist/utils/lambda-config.d.ts.map +1 -1
- package/dist/utils/lambda-config.js +1 -0
- package/dist/utils/lambda-config.js.map +1 -1
- package/package.json +5 -2
- package/dist/db-content-api/types.d.ts +0 -31
- package/dist/db-content-api/types.d.ts.map +0 -1
- package/dist/db-content-api/types.js +0 -7
- package/dist/db-content-api/types.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/db-content-api/index.ts"],"sourcesContent":["import type {\n BaseDatabaseAdapter,\n CollectionConfig,\n Count,\n CountGlobalVersions,\n CountVersions,\n Create,\n CreateGlobal,\n CreateGlobalVersion,\n CreateVersion,\n DatabaseAdapterObj,\n DeleteMany,\n DeleteOne,\n DeleteVersions,\n Find,\n FindGlobal,\n FindGlobalVersions,\n FindOne,\n FindVersions,\n GlobalConfig,\n QueryDrafts,\n TraverseFieldsCallback,\n UpdateGlobal,\n UpdateGlobalVersion,\n UpdateMany,\n UpdateOne,\n UpdateVersion,\n Upsert,\n Where,\n} from 'payload'\n\nimport { createDatabaseAdapter, traverseFields } from 'payload'\nimport { v4 as uuid } from 'uuid'\n\nimport type { TokenStore } from '../auth/token-store.js'\nimport type { components } from './generated/content-api-types.js'\n\nimport { getValidProjectToken } from '../auth/project-token.js'\n\ntype CollectionsResponse = {\n data: Array<{ key: string }>\n total: number\n}\n\n// Field name mapping between Payload and Content API\n// TODO: Update these when Content API renames to internal_id/external_id (or similar)\nconst PAYLOAD_ID_FIELD = 'id'\nconst CONTENT_API_KEY_FIELD = 'key'\n\n// Module-level cache for devJwt tokens (encapsulated, not exposed on adapter)\nconst devJwtCache = new Map<string, string>()\n\n// Private helper to fetch JWT from dev endpoint (not exposed on adapter type)\nasync function fetchDevJwt(url: string, contentSystemId: string): Promise<string> {\n const usesSuperUser =\n !contentSystemId || contentSystemId === 'test-system' || contentSystemId === '*'\n const contentSystemIdForJWT = usesSuperUser ? '*' : contentSystemId\n\n const response = await fetch(`${url}/dev/jwt`, {\n body: JSON.stringify({ content_system_id: contentSystemIdForJWT }),\n headers: { 'Content-Type': 'application/json' },\n method: 'POST',\n })\n\n if (!response.ok) {\n throw new Error(`Failed to get dev JWT: ${response.status} ${response.statusText}`)\n }\n\n const { token } = await response.json()\n return token\n}\n\n// Discriminated union for auth modes\ntype ApiKeyAuth = {\n apiKey: string\n mode: 'apiKey'\n}\n\ntype TokenStoreAuth = {\n mode: 'tokenStore'\n tokenStore: TokenStore\n}\n\ntype DevJwtAuth = {\n mode: 'devJwt'\n}\n\ntype ContentAPIOptions = {\n auth: ApiKeyAuth | DevJwtAuth | TokenStoreAuth\n contentSystemId: string\n url: string\n}\n\nexport type ContentAPIAdapter = {\n auth: ApiKeyAuth | DevJwtAuth | TokenStoreAuth\n contentSystemId: string\n makeRequest<T = unknown>(\n path: string,\n options?: { body?: Record<string, unknown>; method?: string; retryCount?: number },\n ): Promise<T>\n url: string\n} & BaseDatabaseAdapter\n\nasync function init(this: ContentAPIAdapter) {\n // Log which auth mode is being used\n if (this.auth.mode === 'apiKey') {\n this.payload.logger.info('Using API Key authentication')\n } else if (this.auth.mode === 'tokenStore') {\n this.payload.logger.info('Using TokenStore authentication (local dev)')\n } else {\n this.payload.logger.info('Using Dev JWT authentication (testing)')\n }\n\n // Drop database if PAYLOAD_DROP_DATABASE is set (for tests)\n if (process.env.PAYLOAD_DROP_DATABASE === 'true') {\n this.payload.logger.info(`---- DROPPING CONTENT API SYSTEM (${this.contentSystemId}) ----`)\n try {\n await this.makeRequest('/dev/clear-db', {\n body: { contentSystemId: this.contentSystemId },\n method: 'POST',\n })\n this.payload.logger.info('---- DROPPED CONTENT API SYSTEM ----')\n } catch (error) {\n this.payload.logger.warn(`Failed to drop content system: ${(error as Error).message}`)\n }\n }\n\n // Fetch existing collections once\n let existingKeys: Set<string>\n try {\n const response = await this.makeRequest<CollectionsResponse>(\n `/api/v0/collections?contentSystemId=${this.contentSystemId}`,\n { method: 'GET' },\n )\n existingKeys = new Set(response.data.map((c) => c.key))\n this.payload.logger.info(`Found ${existingKeys.size} existing collections`)\n } catch (error) {\n this.payload.logger.warn(\n `Failed to fetch collections, will attempt to create all: ${(error as Error).message}`,\n )\n existingKeys = new Set()\n }\n\n // Create only missing collections\n for (const collection of this.payload.config.collections) {\n if (!existingKeys.has(collection.slug)) {\n await createCollection.call(this, collection.slug)\n }\n }\n\n // Create only missing global collections\n for (const global of this.payload.config.globals || []) {\n const globalKey = `_global-${global.slug}`\n if (!existingKeys.has(globalKey)) {\n await createCollection.call(this, globalKey)\n }\n }\n\n return\n}\n\n// Helper to create a collection\nasync function createCollection(this: ContentAPIAdapter, collectionKey: string) {\n try {\n await this.makeRequest('/api/v0/collections', {\n body: {\n name: collectionKey,\n contentSystemId: this.contentSystemId,\n key: collectionKey,\n },\n method: 'POST',\n })\n this.payload.logger.info(`Created collection: ${collectionKey}`)\n } catch (error) {\n const errorMessage = (error as Error).message\n // Still handle 409 gracefully in case of race conditions\n if (!errorMessage.includes('already exists') && !errorMessage.includes('409')) {\n this.payload.logger.warn(`Failed to create collection ${collectionKey}: ${errorMessage}`)\n }\n }\n}\n\n// Helper function to make HTTP requests to the Content API\nasync function makeRequest<T>(\n this: ContentAPIAdapter,\n path: string,\n options: {\n body?: Record<string, unknown>\n method?: string\n retryCount?: number\n } = {},\n): Promise<T> {\n const { body, method = 'POST', retryCount = 0 } = options\n\n // Build auth header based on auth mode\n let authHeader: Record<string, string>\n\n if (this.auth.mode === 'apiKey') {\n authHeader = { 'X-Api-Key': this.auth.apiKey }\n } else if (this.auth.mode === 'tokenStore') {\n const token = await getValidProjectToken(this.auth.tokenStore, this.contentSystemId)\n if (!token) {\n throw new Error('Authentication required. Run `npx @payloadcms/figma login` to authenticate.')\n }\n authHeader = { Authorization: `Bearer ${token}` }\n } else {\n // devJwt - inline cache handling\n let token = devJwtCache.get(this.contentSystemId)\n if (!token) {\n token = await fetchDevJwt(this.url, this.contentSystemId)\n devJwtCache.set(this.contentSystemId, token)\n this.payload.logger.info(`Dev JWT acquired for content system: ${this.contentSystemId}`)\n }\n authHeader = { Authorization: `Bearer ${token}` }\n }\n\n const requestUrl = `${this.url}${path}`\n const response = await fetch(requestUrl, {\n body: body ? JSON.stringify(body) : undefined,\n headers: { 'Content-Type': 'application/json', ...authHeader },\n method,\n })\n\n // Read response as text first (better for debugging)\n const text = await response.text()\n\n // Handle 401 - retry logic differs per mode\n if (response.status === 401 && retryCount === 0 && this.auth.mode === 'devJwt') {\n this.payload.logger.info('Dev JWT expired, refreshing...')\n devJwtCache.delete(this.contentSystemId)\n return this.makeRequest(path, { body, method, retryCount: retryCount + 1 })\n }\n // tokenStore handles refresh internally via getValidProjectToken\n // apiKey doesn't expire - 401 means invalid key\n\n // Check HTTP status\n if (!response.ok) {\n this.payload.logger.error({ msg: `HTTP ${response.status} from ${path}`, response: text })\n throw new Error(`Content API HTTP ${response.status}: ${text.substring(0, 200)}`)\n }\n\n // Parse JSON response\n try {\n const parsed = JSON.parse(text)\n\n // Check if the response is an error object (HTTP 200 but with error in body)\n if (parsed && typeof parsed === 'object' && 'error' in parsed) {\n throw new Error(`Content API error: ${parsed.message || parsed.error}`)\n }\n\n return parsed as T\n } catch (error) {\n // If it's already our custom error, re-throw it\n if (error instanceof Error && error.message.startsWith('Content API error:')) {\n throw error\n }\n\n this.payload.logger.error({\n err: error instanceof Error ? error : new Error(String(error)),\n msg: `Failed to parse JSON response from ${path}`,\n response: text,\n })\n throw new Error(`Invalid JSON response from content API: ${text.substring(0, 100)}...`)\n }\n}\n\n// ⚠️ TEMPORARY WORKAROUND - Remove once Content API is fixed\n//\n// TODO: Content API should accept Payload's native Where format instead of requiring conversion.\n// This converter exists because after a GitHub merge, Content API changed to expect a different format.\n//\n// Payload's format: { fieldName: { operator: value }, and: [...], or: [...] }\n// Content API expects: { and: [{ path, operator, value }], or: [{ path, operator, value }] }\n//\n// Once Content API accepts Payload's format:\n// 1. Remove this function entirely\n// 2. Remove all calls to convertPayloadWhereToContentAPI()\n// 3. Pass `where` directly to Content API endpoints\n// 4. Update CONTENT_API_ISSUES.md to mark Workaround #1 as resolved\nfunction convertPayloadWhereToContentAPI(\n where: undefined | Where,\n insideLogicalOperator: boolean = false,\n):\n | ({ path: string } & components['schemas']['WhereClause'])\n | components['schemas']['WhereClause'] {\n // ⚠️ WORKAROUND: Empty where {} should be { and: [] } not undefined\n // Content API requires a where clause structure even for \"no filter\"\n if (!where || Object.keys(where).length === 0) {\n return { and: [] }\n }\n\n // Extract the condition type (the variant with 'path', 'operator', 'value') from WhereClause union\n type WhereCondition = Extract<components['schemas']['WhereClause'], { path: string }>\n const conditions: (components['schemas']['WhereClause'] | WhereCondition)[] = []\n\n for (const [key, value] of Object.entries(where)) {\n if (key === 'and') {\n // Recursively convert nested 'and' conditions\n const nestedConditions = (value as Where[]).map((item) =>\n convertPayloadWhereToContentAPI(item, true),\n )\n return { and: nestedConditions }\n } else if (key === 'or') {\n // Recursively convert nested 'or' conditions\n const nestedConditions = (value as Where[]).map((item) =>\n convertPayloadWhereToContentAPI(item, true),\n )\n return { or: nestedConditions }\n } else {\n // Convert field conditions: { fieldName: { operator: value } }\n // to: { path: fieldName, operator, value }\n const operators = value as Record<string, unknown>\n for (const [op, operatorValue] of Object.entries(operators)) {\n let finalValue = operatorValue\n\n // Add wildcards for contains/like operators (Payload doesn't add them)\n if ((op === 'contains' || op === 'like') && typeof operatorValue === 'string') {\n finalValue = `%${operatorValue}%`\n }\n\n conditions.push({\n // Map Payload's 'id' field to Content API's 'key' field\n operator: op as WhereCondition['operator'],\n path: key === PAYLOAD_ID_FIELD ? CONTENT_API_KEY_FIELD : key,\n value: finalValue,\n })\n }\n }\n }\n\n // If inside a logical operator (and/or), return conditions directly\n // Otherwise, wrap in 'and' to match WhereClause type\n if (insideLogicalOperator && conditions.length === 1) {\n return conditions[0] as any\n }\n\n return { and: conditions } as components['schemas']['WhereClause']\n}\n\n// Add fallback sort to ensure consistent ordering when sorting by non-unique fields\n// Matches MongoDB adapter behavior\nfunction addFallbackSort(\n sort: string | string[] | undefined,\n collectionConfig: CollectionConfig | undefined,\n): string | string[] | undefined {\n if (!sort || !collectionConfig) {\n return sort\n }\n\n const sortArray = Array.isArray(sort) ? sort : [sort]\n\n // Determine fallback sort field\n let fallbackSort = '-id'\n if (collectionConfig.timestamps !== false) {\n fallbackSort = '-createdAt'\n }\n\n // Check if fallback sort is already included\n const hasFallback = sortArray.some(\n (item) => item === fallbackSort || item === fallbackSort.replace('-', ''),\n )\n\n if (hasFallback) {\n return sort\n }\n\n // Check if all sort fields are unique (then no fallback needed)\n // For simplicity, we'll always add fallback - checking uniqueness requires field traversal\n // which would be expensive. This matches the conservative approach.\n\n // Add fallback sort - always return array to preserve multiple sort fields\n return [...sortArray, fallbackSort]\n}\n\n// ⚠️ TEMPORARY WORKAROUND - Remove once Content API is fixed\n//\n// TODO: Content API should accept Payload's native Sort format instead of requiring conversion.\n// This converter exists because Content API expects a different format.\n//\n// Payload's format: \"-createdAt\" or [\"createdAt\", \"-updatedAt\"]\n// Content API expects: [{ path: \"createdAt\", direction: \"dsc\" }]\n//\n// Once Content API accepts Payload's format:\n// 1. Remove this function entirely\n// 2. Remove all calls to convertPayloadSortToContentAPI()\n// 3. Pass `sort` directly to Content API endpoints\nfunction convertPayloadSortToContentAPI(\n sort: string | string[] | undefined,\n): Array<{ direction: 'asc' | 'desc'; path: string }> | undefined {\n if (!sort) {\n return undefined\n }\n\n const sortArray = Array.isArray(sort) ? sort : [sort]\n\n return sortArray.map((field) => {\n let path = field\n let direction: 'asc' | 'desc' = 'asc'\n\n // Check if field starts with '-' for descending\n if (field.startsWith('-')) {\n path = field.substring(1) // Remove the '-'\n direction = 'desc'\n }\n\n // ⚠️ WORKAROUND: Strip \"version.\" prefix from field names\n // Payload sends \"-version.createdAt\" for version sort fields\n // but Content API expects just \"createdAt\"\n // TODO: Content API should handle version field paths correctly\n if (path.startsWith('version.')) {\n path = path.substring(8) // Remove \"version.\" prefix\n }\n\n return { direction, path }\n })\n}\n\n/**\n * Transform data before sending to Content API (WRITE operations)\n *\n * Conversions applied:\n * - RichText fields: Objects -> JSON strings\n * - Date fields: Date objects -> Unix timestamps (numbers)\n */\nfunction dataToContentAPI(this: ContentAPIAdapter, collectionSlug: string, data: unknown): 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 ? this.payload.config.globals?.find((g) => g.slug === actualSlug)\n : this.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, 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: Date -> Unix timestamp\n else if (field.type === 'date') {\n const dateValue = value instanceof Date ? value : new Date(value as number)\n if (!isNaN(dateValue.getTime())) {\n current[field.name] = dateValue.getTime()\n }\n }\n }\n }\n\n traverseFields({ callback, fields: collectionConfig.fields, ref: transformed })\n\n return transformed\n}\n\n/**\n * Transform data received from Content API (READ operations)\n *\n * Conversions applied:\n * - RichText fields: JSON strings -> Objects\n * - Date fields: Unix timestamps (numbers) -> Date objects\n */\nfunction dataFromContentAPI(\n this: ContentAPIAdapter,\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 ? this.payload.config.globals?.find((g) => g.slug === actualSlug)\n : this.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 this.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: Unix timestamp or ISO string -> Date\n else if (field.type === 'date') {\n current[field.name] = new Date(value as number)\n }\n }\n }\n\n traverseFields({ callback, fields: collectionConfig.fields, ref: transformed })\n\n return transformed\n}\n\n// Helper to unwrap Content API document format to Payload format\n// Content API returns: { id, data: { ...fields }, createdAt, updatedAt }\n// Payload expects: { id, ...fields, createdAt, updatedAt }\nfunction unwrapDocument(\n this: ContentAPIAdapter,\n doc: components['schemas']['Document'] | components['schemas']['DocumentVersion'],\n collectionSlug?: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): any {\n if (!doc) {\n return doc\n }\n\n // TODO\n // Document has 'key', DocumentVersion has 'documentId'\n const docId = CONTENT_API_KEY_FIELD in doc ? doc[CONTENT_API_KEY_FIELD] : doc.documentId\n\n const baseDoc = {\n ...doc.data, // Spread the actual document fields\n createdAt: doc.createdAt,\n [PAYLOAD_ID_FIELD]: docId, // Map Content API's key to Payload's id\n updatedAt: doc.updatedAt,\n }\n\n // Transform data from Content API format to Payload format\n if (collectionSlug) {\n return dataFromContentAPI.call(this, collectionSlug, baseDoc)\n }\n\n return baseDoc\n}\n\nconst findMany = async function findMany(\n this: ContentAPIAdapter,\n {\n collectionSlug,\n limit,\n page,\n pagination,\n skip,\n sort,\n where,\n }: {\n collectionSlug: string\n limit: number\n page: number\n pagination?: boolean\n skip?: number\n sort?: string | string[]\n where: Where\n },\n) {\n // Payload semantics: limit: 0 means \"no limit\" (get all documents)\n // Pass this through to Content API which follows the same convention\n const effectiveLimit = limit\n const offset = skip ?? (limit === 0 ? 0 : (page - 1) * limit)\n\n // Add fallback sort to ensure consistent ordering (matching MongoDB behavior)\n const collectionConfig = this.payload.config.collections.find((c) => c.slug === collectionSlug)\n const sortWithFallback = addFallbackSort(sort, collectionConfig)\n\n const response = await this.makeRequest<components['schemas']['FindDocumentsResponse']>(\n '/api/v0/documents:find',\n {\n body: {\n collectionKey: collectionSlug,\n contentSystemId: this.contentSystemId,\n limit: effectiveLimit,\n offset,\n sort: convertPayloadSortToContentAPI(sortWithFallback),\n where: convertPayloadWhereToContentAPI(where),\n },\n method: 'POST',\n },\n )\n\n return {\n docs: response.result.data.map((doc) => unwrapDocument.call(this, doc, collectionSlug)),\n hasNextPage:\n pagination !== false &&\n limit > 0 &&\n response.result.pagination.total > offset + response.result.data.length,\n hasPrevPage: pagination !== false && offset > 0,\n limit,\n nextPage:\n pagination !== false &&\n response.result.pagination.total > offset + response.result.data.length\n ? page + 1\n : null,\n page,\n pagingCounter: offset + 1,\n prevPage: pagination !== false && offset > 0 ? page - 1 : null,\n totalDocs: response.result.pagination.total,\n totalPages: limit > 0 ? Math.ceil(response.result.pagination.total / limit) : 1,\n }\n}\n\nconst find: Find = async function find(\n this: ContentAPIAdapter,\n { collection: collectionSlug, limit = 0, page = 1, pagination, skip, sort, where },\n) {\n // Apply defaultSort from collection config if no sort is provided\n const collectionConfig = this.payload.config.collections.find((c) => c.slug === collectionSlug)\n const effectiveSort = sort || collectionConfig?.defaultSort\n\n return findMany.call(this, {\n collectionSlug,\n limit,\n page,\n pagination,\n skip,\n sort: effectiveSort,\n where: where ?? {},\n })\n}\n\nconst findVersions: FindVersions = async function findVersions(\n this: ContentAPIAdapter,\n { collection: collectionSlug, limit = 0, page = 1, pagination, skip, sort, where },\n) {\n const offset = skip ?? (page - 1) * limit\n\n const response = await this.makeRequest<components['schemas']['FindDocumentsResponse']>(\n '/api/v0/document_versions:find',\n {\n body: {\n collectionKey: collectionSlug,\n contentSystemId: this.contentSystemId,\n limit,\n offset,\n sort: convertPayloadSortToContentAPI(sort),\n where: convertPayloadWhereToContentAPI(where ?? {}),\n },\n method: 'POST',\n },\n )\n\n return {\n docs: response.result.data.map((doc) => unwrapDocument.call(this, doc, collectionSlug)),\n hasNextPage:\n pagination !== false &&\n limit > 0 &&\n response.result.pagination.total > offset + response.result.data.length,\n hasPrevPage: pagination !== false && offset > 0,\n limit,\n nextPage:\n pagination !== false &&\n response.result.pagination.total > offset + response.result.data.length\n ? page + 1\n : null,\n page,\n pagingCounter: offset + 1,\n prevPage: pagination !== false && offset > 0 ? page - 1 : null,\n totalDocs: response.result.pagination.total,\n totalPages: limit > 0 ? Math.ceil(response.result.pagination.total / limit) : 1,\n }\n}\n\nconst queryDrafts: QueryDrafts = async function queryDrafts(\n this: ContentAPIAdapter,\n { collection: collectionSlug, limit, page, pagination, sort, where = {} },\n) {\n // TODO: review this\n // Content API doesn't have a separate \"draft\" concept\n // It only has versions with a \"latest\" flag\n // PayloadCMS drafts would typically be versions where latest=false\n // But this mapping may need adjustment based on your use case\n const result = await this.findVersions({\n collection: collectionSlug,\n limit,\n page,\n pagination,\n sort,\n where: {\n ...where,\n // Query non-latest versions as \"drafts\"\n latest: { equals: false },\n },\n })\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return result as any\n}\n\nconst createVersion: CreateVersion = async function createVersion(\n this: ContentAPIAdapter,\n { autosave, collectionSlug, parent, versionData },\n) {\n const response = await this.makeRequest<components['schemas']['CreateDocumentVersionResponse']>(\n '/api/v0/document_versions:create',\n {\n body: {\n collectionKey: collectionSlug,\n contentSystemId: this.contentSystemId,\n data: dataToContentAPI.call(this, collectionSlug, versionData),\n documentKey: parent,\n latest: !autosave,\n },\n method: 'POST',\n },\n )\n\n // Handle union type response: { id: string } | { data: DocumentVersion }\n if ('data' in response.result) {\n return unwrapDocument.call(this, response.result.data, collectionSlug)\n }\n throw new Error('Unexpected response format from createVersion')\n}\n\nconst updateVersion: UpdateVersion = async function updateVersion(\n this: ContentAPIAdapter,\n { id, collection: collectionSlug, versionData, where },\n) {\n const response = await this.makeRequest<components['schemas']['UpdateDocumentVersionResponse']>(\n '/api/v0/document_versions:update',\n {\n body: {\n collectionKey: collectionSlug,\n contentSystemId: this.contentSystemId,\n createOnMissing: false,\n data: dataToContentAPI.call(this, collectionSlug, versionData),\n where: convertPayloadWhereToContentAPI(where ?? { id: { equals: id } }),\n },\n method: 'POST',\n },\n )\n\n // Handle union type response: { count: number } | { data: DocumentVersion[] }\n if (!response?.result || !('data' in response.result)) {\n throw new Error('No document data in updateVersion response')\n }\n\n return unwrapDocument.call(this, response.result.data[0], collectionSlug)\n}\n\nconst deleteVersions: DeleteVersions = async function deleteVersions(\n this: ContentAPIAdapter,\n { collection: collectionSlug, where },\n) {\n await this.makeRequest('/api/v0/document_versions:delete', {\n body: {\n collectionKey: collectionSlug,\n contentSystemId: this.contentSystemId,\n returning: false, // Don't return deleted data (future-proof for when Content API supports this)\n where: convertPayloadWhereToContentAPI(where),\n },\n method: 'POST',\n })\n}\n\nconst findOne: FindOne = async function findOne(this: ContentAPIAdapter, { collection, where }) {\n const {\n docs: [first],\n } = await this.find({ collection, limit: 1, pagination: false, where })\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (first ?? null) as any\n}\n\nconst updateMany: UpdateMany = async function updateMany(\n this: ContentAPIAdapter,\n { collection: collectionSlug, data, where },\n) {\n const response = await this.makeRequest<components['schemas']['UpdateDocumentResponse']>(\n '/api/v0/documents:update',\n {\n body: {\n collectionKey: collectionSlug,\n contentSystemId: this.contentSystemId,\n createOnMissing: false,\n data: dataToContentAPI.call(this, collectionSlug, data),\n returning: {},\n where: convertPayloadWhereToContentAPI(where),\n },\n method: 'POST',\n },\n )\n\n // Handle union type: { count: number } | { data: Document[] }\n if (response.result && 'data' in response.result) {\n return response.result.data.map((doc) => unwrapDocument.call(this, doc, collectionSlug))\n }\n return null\n}\n\nconst updateOne: UpdateOne = async function updateOne(\n this: ContentAPIAdapter,\n { id, collection: collectionSlug, data, where },\n) {\n const response = await this.makeRequest<components['schemas']['UpdateDocumentResponse']>(\n '/api/v0/documents:update',\n {\n body: {\n collectionKey: collectionSlug,\n contentSystemId: this.contentSystemId,\n createOnMissing: false,\n data: dataToContentAPI.call(this, collectionSlug, data),\n where: convertPayloadWhereToContentAPI(where ?? { id: { equals: id } }),\n },\n method: 'POST',\n },\n )\n\n // Handle union type: { count: number } | { data: Document[] }\n if (response.result && 'data' in response.result) {\n const doc = response.result.data[0]\n if (!doc) {\n throw new Error('No document data in updateOne response')\n }\n return unwrapDocument.call(this, doc, collectionSlug)\n }\n throw new Error('Unexpected response format from updateOne')\n}\n\nconst deleteMany: DeleteMany = async function deleteMany(\n this: ContentAPIAdapter,\n { collection: collectionSlug, where },\n) {\n await this.makeRequest('/api/v0/documents:delete', {\n body: {\n collectionKey: collectionSlug,\n contentSystemId: this.contentSystemId,\n returning: false, // Don't return deleted data (future-proof for when Content API supports this)\n where: convertPayloadWhereToContentAPI(where),\n },\n method: 'POST',\n })\n}\n\nconst deleteOne: DeleteOne = async function deleteOne(\n this: ContentAPIAdapter,\n { collection: collectionSlug, where },\n) {\n await this.makeRequest('/api/v0/documents:delete', {\n body: {\n collectionKey: collectionSlug,\n contentSystemId: this.contentSystemId,\n returning: false, // Don't return deleted data (future-proof for when Content API supports this)\n where: convertPayloadWhereToContentAPI(where),\n },\n method: 'POST',\n })\n}\n\nconst create: Create = async function create(\n this: ContentAPIAdapter,\n { collection: collectionSlug, data },\n) {\n // Generate a document key if not provided\n // Content API has two ID fields:\n // - `id` (UUID, auto-generated by DB, internal use only)\n // - `key` (text, public document identifier, maps to Payload's `id`)\n // If Payload doesn't provide an ID, we generate a UUID\n // (same as other SQL-based Payload adapters like db-postgres and db-drizzle)\n const key = data[PAYLOAD_ID_FIELD] || uuid()\n\n const response = await this.makeRequest<components['schemas']['CreateDocumentResponse']>(\n '/api/v0/documents:create',\n {\n body: {\n collectionKey: collectionSlug,\n contentSystemId: this.contentSystemId,\n data: dataToContentAPI.call(this, collectionSlug, data),\n key,\n // returning is optional and currently ignored by Content API (always returns full document)\n },\n method: 'POST',\n },\n )\n\n // Handle union type response: { id: string } | { data: Document }\n if ('data' in response.result) {\n return unwrapDocument.call(this, response.result.data, collectionSlug)\n }\n throw new Error('Unexpected response format from create')\n}\n\nconst count: Count = async function count(\n this: ContentAPIAdapter,\n { collection: collectionSlug, where },\n) {\n const response = await this.makeRequest<components['schemas']['CountDocumentResponse']>(\n '/api/v0/documents:count',\n {\n body: {\n collectionKey: collectionSlug,\n contentSystemId: this.contentSystemId,\n where: convertPayloadWhereToContentAPI(where),\n },\n method: 'POST',\n },\n )\n\n return { totalDocs: response.result.count }\n}\n\nconst countVersions: CountVersions = async function countVersions(\n this: ContentAPIAdapter,\n { collection: collectionSlug, where },\n) {\n const response = await this.makeRequest<components['schemas']['CountDocumentVersionResponse']>(\n '/api/v0/document_versions:count',\n {\n body: {\n collectionKey: collectionSlug,\n contentSystemId: this.contentSystemId,\n where: convertPayloadWhereToContentAPI(where),\n },\n method: 'POST',\n },\n )\n\n return { totalDocs: response.result.count }\n}\n\nconst upsert: Upsert = async function upsert(\n this: ContentAPIAdapter,\n { collection: collectionSlug, data, where },\n) {\n const response = await this.makeRequest<components['schemas']['UpdateDocumentResponse']>(\n '/api/v0/documents:update',\n {\n body: {\n collectionKey: collectionSlug,\n contentSystemId: this.contentSystemId,\n createOnMissing: true,\n data: dataToContentAPI.call(this, collectionSlug, data),\n where: convertPayloadWhereToContentAPI(where),\n },\n method: 'POST',\n },\n )\n\n // Handle union type: { count: number } | { data: Document[] }\n if (response.result && 'data' in response.result) {\n const doc = response.result.data[0]\n if (!doc) {\n throw new Error('No document data in upsert response')\n }\n return unwrapDocument.call(this, doc, collectionSlug)\n }\n throw new Error('Unexpected response format from upsert')\n}\n\n// TODO: global should be a prefix or a resource in the REST API / Table in the DB?\nconst getGlobalSlug = (slug: string) => `_global-${slug}`\n\nconst createGlobal: CreateGlobal = function (this: ContentAPIAdapter, { slug, data }) {\n return this.create({ collection: getGlobalSlug(slug), data: { ...data, globalType: slug } })\n}\n\nconst findGlobal: FindGlobal = function (this: ContentAPIAdapter, { slug, where = {} }) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return this.findOne({ collection: getGlobalSlug(slug), where }) as any\n}\n\nconst updateGlobal: UpdateGlobal = function (this: ContentAPIAdapter, { slug, data }) {\n return this.updateOne({ collection: getGlobalSlug(slug), data, where: {} })\n}\n\nconst findGlobalVersions: FindGlobalVersions = function (\n this: ContentAPIAdapter,\n { global: slug, limit, page, pagination, skip, sort, where },\n) {\n return this.findVersions({\n collection: getGlobalSlug(slug),\n limit,\n page,\n pagination,\n skip,\n sort,\n where,\n })\n}\n\nconst createGlobalVersion: CreateGlobalVersion = function (\n this: ContentAPIAdapter,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n { autosave, createdAt, globalSlug, updatedAt, versionData, ...rest }: any,\n) {\n return this.createVersion({\n autosave,\n collectionSlug: getGlobalSlug(globalSlug),\n createdAt,\n parent: rest.parent,\n updatedAt,\n versionData,\n })\n}\n\nconst updateGlobalVersion: UpdateGlobalVersion = function (\n this: ContentAPIAdapter,\n { id, global: slug, versionData, where, ...rest },\n) {\n // UpdateVersion accepts either id OR where, not both\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const args: any = {\n collection: getGlobalSlug(slug),\n versionData,\n ...rest,\n }\n\n if (id !== undefined) {\n args.id = id\n } else if (where !== undefined) {\n args.where = where\n }\n\n return this.updateVersion(args)\n}\n\nconst countGlobalVersions: CountGlobalVersions = function (\n this: ContentAPIAdapter,\n { global: slug, where },\n) {\n return this.countVersions({ collection: getGlobalSlug(slug), where })\n}\n\nexport const contentAPIAdapter = (opts: ContentAPIOptions): DatabaseAdapterObj => {\n return {\n name: 'content_api',\n defaultIDType: 'text',\n init: ({ payload }) => {\n return createDatabaseAdapter<ContentAPIAdapter>({\n name: 'content_api',\n auth: opts.auth,\n beginTransaction: () => {\n return Promise.resolve('no-op-transaction')\n },\n commitTransaction: async () => {},\n contentSystemId: opts.contentSystemId,\n count,\n countGlobalVersions,\n countVersions,\n create,\n createGlobal,\n createGlobalVersion,\n createVersion,\n defaultIDType: 'text',\n deleteMany,\n deleteOne,\n deleteVersions,\n find,\n findDistinct: () => {\n return Promise.reject(\n new Error('findDistinct is not yet implemented for Content API adapter'),\n )\n },\n findGlobal,\n findGlobalVersions,\n findOne,\n findVersions,\n init,\n makeRequest,\n packageName: '@payloadcms/db-content-api',\n payload,\n queryDrafts,\n rollbackTransaction: async () => {},\n updateGlobal,\n updateGlobalVersion,\n updateMany,\n updateOne,\n updateVersion,\n upsert,\n url: opts.url,\n })\n },\n }\n}\n"],"names":["createDatabaseAdapter","traverseFields","v4","uuid","getValidProjectToken","PAYLOAD_ID_FIELD","CONTENT_API_KEY_FIELD","devJwtCache","Map","fetchDevJwt","url","contentSystemId","usesSuperUser","contentSystemIdForJWT","response","fetch","body","JSON","stringify","content_system_id","headers","method","ok","Error","status","statusText","token","json","init","auth","mode","payload","logger","info","process","env","PAYLOAD_DROP_DATABASE","makeRequest","error","warn","message","existingKeys","Set","data","map","c","key","size","collection","config","collections","has","slug","createCollection","call","global","globals","globalKey","collectionKey","name","errorMessage","includes","path","options","retryCount","authHeader","apiKey","tokenStore","Authorization","get","set","requestUrl","undefined","text","delete","msg","substring","parsed","parse","startsWith","err","String","convertPayloadWhereToContentAPI","where","insideLogicalOperator","Object","keys","length","and","conditions","value","entries","nestedConditions","item","or","operators","op","operatorValue","finalValue","push","operator","addFallbackSort","sort","collectionConfig","sortArray","Array","isArray","fallbackSort","timestamps","hasFallback","some","replace","convertPayloadSortToContentAPI","field","direction","dataToContentAPI","collectionSlug","transformed","isGlobal","actualSlug","find","g","fields","callback","ref","current","type","dateValue","Date","isNaN","getTime","dataFromContentAPI","parentPath","fieldPath","unwrapDocument","doc","docId","documentId","baseDoc","createdAt","updatedAt","findMany","limit","page","pagination","skip","effectiveLimit","offset","sortWithFallback","docs","result","hasNextPage","total","hasPrevPage","nextPage","pagingCounter","prevPage","totalDocs","totalPages","Math","ceil","effectiveSort","defaultSort","findVersions","queryDrafts","latest","equals","createVersion","autosave","parent","versionData","documentKey","updateVersion","id","createOnMissing","deleteVersions","returning","findOne","first","updateMany","updateOne","deleteMany","deleteOne","create","count","countVersions","upsert","getGlobalSlug","createGlobal","globalType","findGlobal","updateGlobal","findGlobalVersions","createGlobalVersion","globalSlug","rest","updateGlobalVersion","args","countGlobalVersions","contentAPIAdapter","opts","defaultIDType","beginTransaction","Promise","resolve","commitTransaction","findDistinct","reject","packageName","rollbackTransaction"],"mappings":"AA+BA,SAASA,qBAAqB,EAAEC,cAAc,QAAQ,UAAS;AAC/D,SAASC,MAAMC,IAAI,QAAQ,OAAM;AAKjC,SAASC,oBAAoB,QAAQ,2BAA0B;AAO/D,qDAAqD;AACrD,sFAAsF;AACtF,MAAMC,mBA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H,KAAKlH,KAAK,GAAGA;IACf;IAEA,OAAO,IAAI,CAACyF,aAAa,CAACyB;AAC5B;AAEA,MAAMC,sBAA2C,SAE/C,EAAE/I,QAAQH,IAAI,EAAE+B,KAAK,EAAE;IAEvB,OAAO,IAAI,CAACsG,aAAa,CAAC;QAAEzI,YAAY2I,cAAcvI;QAAO+B;IAAM;AACrE;AAEA,OAAO,MAAMoH,oBAAoB,CAACC;IAChC,OAAO;QACL7I,MAAM;QACN8I,eAAe;QACf7K,MAAM,CAAC,EAAEG,OAAO,EAAE;YAChB,OAAO/B,sBAAyC;gBAC9C2D,MAAM;gBACN9B,MAAM2K,KAAK3K,IAAI;gBACf6K,kBAAkB;oBAChB,OAAOC,QAAQC,OAAO,CAAC;gBACzB;gBACAC,mBAAmB,WAAa;gBAChClM,iBAAiB6L,KAAK7L,eAAe;gBACrC6K;gBACAc;gBACAb;gBACAF;gBACAK;gBACAK;gBACA1B;gBACAkC,eAAe;gBACfpB;gBACAC;gBACAP;gBACAvD;gBACAsF,cAAc;oBACZ,OAAOH,QAAQI,MAAM,CACnB,IAAIxL,MAAM;gBAEd;gBACAuK;gBACAE;gBACAf;gBACAd;gBACAvI;gBACAS;gBACA2K,aAAa;gBACbjL;gBACAqI;gBACA6C,qBAAqB,WAAa;gBAClClB;gBACAK;gBACAjB;gBACAC;gBACAR;gBACAc;gBACAhL,KAAK8L,KAAK9L,GAAG;YACf;QACF;IACF;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../src/db-content-api/index.ts"],"sourcesContent":["import type {\n BaseDatabaseAdapter,\n Count,\n CountArgs,\n CountGlobalVersionArgs,\n CountGlobalVersions,\n CountVersions,\n Create,\n CreateArgs,\n CreateGlobal,\n CreateGlobalArgs,\n CreateGlobalVersion,\n CreateGlobalVersionArgs,\n CreateVersion,\n CreateVersionArgs,\n DatabaseAdapterObj,\n DeleteMany,\n DeleteManyArgs,\n DeleteOne,\n DeleteOneArgs,\n DeleteVersions,\n DeleteVersionsArgs,\n Find,\n FindArgs,\n FindGlobal,\n FindGlobalArgs,\n FindGlobalVersions,\n FindGlobalVersionsArgs,\n FindOne,\n FindOneArgs,\n FindVersions,\n FindVersionsArgs,\n QueryDrafts,\n QueryDraftsArgs,\n UpdateGlobal,\n UpdateGlobalArgs,\n UpdateGlobalVersion,\n UpdateGlobalVersionArgs,\n UpdateMany,\n UpdateManyArgs,\n UpdateOne,\n UpdateOneArgs,\n UpdateVersion,\n UpdateVersionArgs,\n Upsert,\n UpsertArgs,\n} from 'payload'\n\nimport createClient from 'openapi-fetch'\nimport { createDatabaseAdapter } from 'payload'\nimport { v4 as uuid } from 'uuid'\n\nimport type { paths } from './generated/content-api-types.js'\n\nimport { getPaginationData } from './temp-utilities/pagination.js'\nimport { getGlobalSlug } from './temp-utilities/slug.js'\nimport { addFallbackSort, convertPayloadSortToContentAPI } from './temp-utilities/sorting.js'\nimport { unwrapDocument } from './temp-utilities/unwrapDocument.js'\nimport { type AuthMode, createAuthMiddleware, createErrorMiddleware } from './utilities/auth.js'\nimport { dataToContentAPI } from './utilities/data.js'\nimport { convertPayloadJoinsToContentAPI } from './utilities/joins.js'\nimport { convertPayloadWhereToContentAPI } from './utilities/where.js'\n\ntype ContentAPIOptions = {\n auth: AuthMode\n contentSystemId: string\n url: string\n}\n\nexport type ContentAPIAdapter = {\n auth: AuthMode\n client: ReturnType<typeof createClient<paths>>\n contentSystemId: string\n url: string\n} & BaseDatabaseAdapter\n\nasync function init(this: ContentAPIAdapter) {\n if (this.auth.mode === 'apiKey') {\n this.payload.logger.info('Using API Key authentication')\n } else if (this.auth.mode === 'tokenStore') {\n this.payload.logger.info('Using TokenStore authentication (local dev)')\n } else {\n this.payload.logger.info('Using Dev JWT authentication (testing)')\n }\n\n if (process.env.PAYLOAD_DROP_DATABASE === 'true') {\n this.payload.logger.info(`---- DROPPING CONTENT API SYSTEM (${this.contentSystemId}) ----`)\n try {\n await fetch(`${this.url}/dev/clear-db`, {\n body: JSON.stringify({ contentSystemId: this.contentSystemId }),\n headers: { 'Content-Type': 'application/json' },\n method: 'POST',\n })\n this.payload.logger.info('---- DROPPED CONTENT API SYSTEM ----')\n } catch (error) {\n this.payload.logger.warn(`Failed to drop content system: ${(error as Error).message}`)\n }\n }\n\n let existingIds: Set<string>\n try {\n const { data: response, error } = await this.client.GET(\n '/api/v0/content_systems/{contentSystemId}/collections',\n {\n params: { path: { contentSystemId: this.contentSystemId } },\n },\n )\n\n if (error) {\n throw new Error(JSON.stringify(error))\n }\n if (!response) {\n throw new Error('No response from collections endpoint')\n }\n\n existingIds = new Set(response.data.map((c) => c.id))\n this.payload.logger.info(`Found ${existingIds.size} existing collections`)\n } catch (error) {\n this.payload.logger.warn(\n `Failed to fetch collections, will attempt to create all: ${(error as Error).message}`,\n )\n existingIds = new Set()\n }\n\n for (const collection of this.payload.config.collections) {\n if (!existingIds.has(collection.slug)) {\n await createCollection.call(this, collection.slug)\n }\n }\n\n for (const global of this.payload.config.globals || []) {\n const globalId = `_global-${global.slug}`\n if (!existingIds.has(globalId)) {\n await createCollection.call(this, globalId)\n }\n }\n}\n\nasync function createCollection(this: ContentAPIAdapter, collectionId: string) {\n try {\n const { error } = await this.client.POST(\n '/api/v0/content_systems/{contentSystemId}/collections',\n {\n body: { id: collectionId },\n params: { path: { contentSystemId: this.contentSystemId } },\n },\n )\n\n if (error) {\n throw new Error(JSON.stringify(error))\n }\n this.payload.logger.info(`Created collection: ${collectionId}`)\n } catch (error) {\n const errorMessage = (error as Error).message\n if (!errorMessage.includes('already exists') && !errorMessage.includes('409')) {\n this.payload.logger.warn(`Failed to create collection ${collectionId}: ${errorMessage}`)\n }\n }\n}\n\nasync function findMany(\n this: ContentAPIAdapter,\n {\n collection,\n joins,\n limit,\n page,\n pagination,\n sort,\n where,\n // Not yet passed to Content API:\n // - select: supported by Content API, pass-through possible\n // Not supported by Content API:\n // - draftsEnabled, locale, versions, projection\n }: Pick<FindArgs, 'joins' | 'pagination' | 'sort' | 'where'> &\n Required<Pick<FindArgs, 'collection' | 'limit' | 'page'>>,\n) {\n const collectionConfig = this.payload.config.collections.find((c) => c.slug === collection)\n const sortWithFallback = addFallbackSort(sort, collectionConfig)\n\n const { data: response, error } = await this.client.POST('/api/v0/documents:find', {\n body: {\n collectionId: collection,\n contentSystemId: this.contentSystemId,\n join: collectionConfig\n ? convertPayloadJoinsToContentAPI(this.payload, collectionConfig, joins)\n : undefined,\n limit,\n page: page ?? 1,\n sort: convertPayloadSortToContentAPI(sortWithFallback),\n where: convertPayloadWhereToContentAPI(where ?? {}),\n },\n })\n\n if (error) {\n throw new Error(`Content API findMany error: ${JSON.stringify(error)}`)\n }\n if (!response) {\n throw new Error('No response from findMany')\n }\n\n return {\n docs: response.result.data.map((doc) => unwrapDocument(this.payload, doc, collection)),\n ...getPaginationData(response.result.pagination, pagination),\n }\n}\n\nasync function find(this: ContentAPIAdapter, args: FindArgs) {\n const collectionConfig = this.payload.config.collections.find((c) => c.slug === args.collection)\n return findMany.call(this, {\n collection: args.collection,\n joins: args.joins,\n limit: args.limit ?? 0,\n page: args.page ?? 1,\n pagination: args.pagination,\n sort: args.sort || collectionConfig?.defaultSort,\n where: args.where,\n })\n}\n\n// TODO: remove Omit when this PR is released: https://github.com/payloadcms/payload/pull/15183\nasync function findVersions(this: ContentAPIAdapter, args: Omit<FindVersionsArgs, 'skip'>) {\n const whereClause = convertPayloadWhereToContentAPI(args.where ?? {}, {\n parentToDocumentId: true,\n })\n\n const { data: response, error } = await this.client.POST('/api/v0/document_versions:find', {\n body: {\n collectionId: args.collection,\n contentSystemId: this.contentSystemId,\n limit: args.limit ?? 0,\n page: args.page ?? 1,\n sort: convertPayloadSortToContentAPI(args.sort),\n where: whereClause,\n },\n })\n\n if (error) {\n throw new Error(`Content API findVersions error: ${JSON.stringify(error)}`)\n }\n if (!response) {\n throw new Error('No response from findVersions')\n }\n\n const docs = response.result.data.map((doc) => unwrapDocument(this.payload, doc, args.collection))\n\n return {\n docs,\n ...getPaginationData(response.result.pagination, args.pagination),\n }\n}\n\nasync function queryDrafts(this: ContentAPIAdapter, args: QueryDraftsArgs) {\n return this.findVersions({\n collection: args.collection,\n limit: args.limit,\n page: args.page,\n pagination: args.pagination,\n sort: args.sort,\n where: { ...args.where, latest: { equals: true } },\n })\n}\n\nasync function createVersion(this: ContentAPIAdapter, args: CreateVersionArgs) {\n const { data: response, error } = await this.client.POST('/api/v0/document_versions:create', {\n body: {\n collectionId: args.collectionSlug,\n contentSystemId: this.contentSystemId,\n data: dataToContentAPI(this.payload, args.collectionSlug, args.versionData),\n documentId: String(args.parent),\n latest: !args.autosave,\n },\n })\n\n if (error) {\n throw new Error(`Content API createVersion error: ${JSON.stringify(error)}`)\n }\n if (!response) {\n throw new Error('No response from createVersion')\n }\n if (!('data' in response.result)) {\n throw new Error('Unexpected response format from createVersion')\n }\n\n return unwrapDocument(this.payload, response.result.data, args.collectionSlug)\n}\n\nasync function updateVersion(this: ContentAPIAdapter, args: UpdateVersionArgs) {\n const { data: response, error } = await this.client.POST('/api/v0/document_versions:update', {\n body: {\n collectionId: args.collection,\n contentSystemId: this.contentSystemId,\n createOnMissing: false,\n data: dataToContentAPI(this.payload, args.collection, args.versionData),\n where: convertPayloadWhereToContentAPI(args.where ?? { id: { equals: args.id } }),\n },\n })\n\n if (error) {\n throw new Error(`Content API updateVersion error: ${JSON.stringify(error)}`)\n }\n if (!response?.result || !('data' in response.result)) {\n throw new Error('No document data in updateVersion response')\n }\n\n const doc = response.result.data[0]\n if (!doc) {\n throw new Error('No document version matched the where clause')\n }\n\n return unwrapDocument(this.payload, doc, args.collection)\n}\n\nasync function deleteVersions(this: ContentAPIAdapter, args: DeleteVersionsArgs) {\n if (!args.collection) {\n throw new Error('deleteVersions requires a collection')\n }\n\n const { error } = await this.client.POST('/api/v0/document_versions:delete', {\n body: {\n collectionId: args.collection,\n contentSystemId: this.contentSystemId,\n where: convertPayloadWhereToContentAPI(args.where),\n },\n })\n\n if (error) {\n throw new Error(`Content API deleteVersions error: ${JSON.stringify(error)}`)\n }\n}\n\nasync function findOne(this: ContentAPIAdapter, args: FindOneArgs) {\n const { docs } = await this.find({\n collection: args.collection,\n joins: args.joins,\n limit: 1,\n pagination: false,\n where: args.where,\n })\n return docs[0] ?? null\n}\n\nasync function updateMany(this: ContentAPIAdapter, args: UpdateManyArgs) {\n const { data: response, error } = await this.client.POST('/api/v0/documents:update', {\n body: {\n collectionId: args.collection,\n contentSystemId: this.contentSystemId,\n createOnMissing: false,\n data: dataToContentAPI(this.payload, args.collection, args.data),\n returning: {},\n where: convertPayloadWhereToContentAPI(args.where),\n },\n })\n\n if (error) {\n throw new Error(`Content API updateMany error: ${JSON.stringify(error)}`)\n }\n if (!response) {\n throw new Error('No response from updateMany')\n }\n\n if (response.result && 'data' in response.result) {\n return response.result.data.map((doc) => unwrapDocument(this.payload, doc, args.collection))\n }\n return null\n}\n\nasync function updateOne(this: ContentAPIAdapter, args: UpdateOneArgs) {\n const { data: response, error } = await this.client.POST('/api/v0/documents:update', {\n body: {\n collectionId: args.collection,\n contentSystemId: this.contentSystemId,\n createOnMissing: false,\n data: dataToContentAPI(this.payload, args.collection, args.data),\n returning: {},\n where: convertPayloadWhereToContentAPI(args.where ?? { id: { equals: args.id } }),\n },\n })\n\n if (error) {\n throw new Error(`Content API updateOne error: ${JSON.stringify(error)}`)\n }\n if (!response) {\n throw new Error('No response from updateOne')\n }\n if (!response.result || !('data' in response.result)) {\n throw new Error('Unexpected response format from updateOne')\n }\n\n const doc = response.result.data[0]\n if (!doc) {\n throw new Error('No document matched the where clause for update')\n }\n\n return unwrapDocument(this.payload, doc, args.collection)\n}\n\nasync function deleteMany(this: ContentAPIAdapter, args: DeleteManyArgs) {\n const { error } = await this.client.POST('/api/v0/documents:delete', {\n body: {\n collectionId: args.collection,\n contentSystemId: this.contentSystemId,\n where: convertPayloadWhereToContentAPI(args.where),\n },\n })\n\n if (error) {\n throw new Error(`Content API deleteMany error: ${JSON.stringify(error)}`)\n }\n}\n\nasync function deleteOne(this: ContentAPIAdapter, args: DeleteOneArgs) {\n const { data: response, error } = await this.client.POST('/api/v0/documents:delete', {\n body: {\n collectionId: args.collection,\n contentSystemId: this.contentSystemId,\n returning: {}, // Request deleted document back\n where: convertPayloadWhereToContentAPI(args.where),\n },\n })\n\n if (error) {\n throw new Error(`Content API deleteOne error: ${JSON.stringify(error)}`)\n }\n if (!response?.result || !('data' in response.result)) {\n throw new Error('No document data in deleteOne response')\n }\n\n const doc = response.result.data[0]\n if (!doc) {\n throw new Error('No document matched the where clause for deletion')\n }\n\n return unwrapDocument(this.payload, doc, args.collection)\n}\n\nasync function create(this: ContentAPIAdapter, args: CreateArgs) {\n const id = (args.data.id as string | undefined) || uuid()\n\n const { data: response, error } = await this.client.POST('/api/v0/documents:create', {\n body: {\n id: String(id),\n collectionId: args.collection,\n contentSystemId: this.contentSystemId,\n data: dataToContentAPI(this.payload, args.collection, args.data),\n },\n })\n\n if (error) {\n throw new Error(`Content API create error: ${JSON.stringify(error)}`)\n }\n if (!response) {\n throw new Error('No response from create')\n }\n if (!('data' in response.result)) {\n throw new Error('Unexpected response format from create')\n }\n\n return unwrapDocument(this.payload, response.result.data, args.collection)\n}\n\nasync function count(this: ContentAPIAdapter, args: CountArgs) {\n const { data: response, error } = await this.client.POST('/api/v0/documents:count', {\n body: {\n collectionId: args.collection,\n contentSystemId: this.contentSystemId,\n where: convertPayloadWhereToContentAPI(args.where),\n },\n })\n\n if (error) {\n throw new Error(`Content API count error: ${JSON.stringify(error)}`)\n }\n if (!response) {\n throw new Error('No response from count')\n }\n\n return { totalDocs: response.result.count }\n}\n\nasync function countVersions(this: ContentAPIAdapter, args: CountArgs) {\n const { data: response, error } = await this.client.POST('/api/v0/document_versions:count', {\n body: {\n collectionId: args.collection,\n contentSystemId: this.contentSystemId,\n where: convertPayloadWhereToContentAPI(args.where),\n },\n })\n\n if (error) {\n throw new Error(`Content API countVersions error: ${JSON.stringify(error)}`)\n }\n if (!response) {\n throw new Error('No response from countVersions')\n }\n\n return { totalDocs: response.result.count }\n}\n\nasync function upsert(this: ContentAPIAdapter, args: UpsertArgs) {\n let documentId = args.data.id as string | undefined\n if (!documentId && args.where && 'id' in args.where) {\n const idClause = (args.where as Record<string, unknown>).id as Record<string, unknown>\n if (idClause && 'equals' in idClause) {\n documentId = idClause.equals as string\n }\n }\n if (!documentId) {\n documentId = uuid()\n }\n\n const { data: response, error } = await this.client.POST('/api/v0/documents:update', {\n body: {\n collectionId: args.collection,\n contentSystemId: this.contentSystemId,\n createOnMissing: { id: documentId },\n data: dataToContentAPI(this.payload, args.collection, args.data),\n where: convertPayloadWhereToContentAPI(args.where),\n },\n })\n\n if (error) {\n throw new Error(`Content API upsert error: ${JSON.stringify(error)}`)\n }\n if (!response) {\n throw new Error('No response from upsert')\n }\n if (!response.result || !('data' in response.result)) {\n throw new Error('Unexpected response format from upsert')\n }\n\n const doc = response.result.data[0]\n if (!doc) {\n throw new Error('No document data in upsert response')\n }\n\n return unwrapDocument(this.payload, doc, args.collection)\n}\n\nfunction createGlobal(this: ContentAPIAdapter, args: CreateGlobalArgs) {\n return this.create({\n collection: getGlobalSlug(args.slug),\n data: { ...args.data, globalType: args.slug },\n })\n}\n\nfunction findGlobal(this: ContentAPIAdapter, args: FindGlobalArgs) {\n return this.findOne({ collection: getGlobalSlug(args.slug), where: args.where ?? {} })\n}\n\nasync function updateGlobal(this: ContentAPIAdapter, args: UpdateGlobalArgs) {\n // Use upsert to ensure the global exists\n // Use slug as the consistent document ID for globals\n return this.upsert({\n collection: getGlobalSlug(args.slug),\n data: args.data,\n where: { id: { equals: args.slug } },\n })\n}\n\n// TODO: remove Omit when this PR is released: https://github.com/payloadcms/payload/pull/15183\nfunction findGlobalVersions(this: ContentAPIAdapter, args: Omit<FindGlobalVersionsArgs, 'skip'>) {\n return this.findVersions({\n collection: getGlobalSlug(args.global),\n limit: args.limit,\n page: args.page,\n pagination: args.pagination,\n sort: args.sort,\n where: args.where,\n })\n}\n\nfunction createGlobalVersion(this: ContentAPIAdapter, args: CreateGlobalVersionArgs) {\n // For globals, use the globalSlug as the consistent document ID\n // This matches what we do in updateGlobal\n return this.createVersion({\n autosave: args.autosave,\n collectionSlug: getGlobalSlug(args.globalSlug),\n createdAt: args.createdAt,\n parent: args.globalSlug,\n updatedAt: args.updatedAt,\n versionData: args.versionData,\n })\n}\n\nfunction updateGlobalVersion(this: ContentAPIAdapter, args: UpdateGlobalVersionArgs) {\n // UpdateVersion requires either id OR where, not both\n if (args.id !== undefined) {\n return this.updateVersion({\n id: args.id,\n collection: getGlobalSlug(args.global),\n versionData: args.versionData,\n })\n }\n // args.where is guaranteed by Payload when args.id is undefined\n return this.updateVersion({\n collection: getGlobalSlug(args.global),\n versionData: args.versionData,\n where: args.where,\n })\n}\n\nfunction countGlobalVersions(this: ContentAPIAdapter, args: CountGlobalVersionArgs) {\n return this.countVersions({ collection: getGlobalSlug(args.global), where: args.where })\n}\n\nexport const contentAPIAdapter = (opts: ContentAPIOptions): DatabaseAdapterObj => ({\n name: 'content_api',\n defaultIDType: 'text',\n init: ({ payload }) => {\n const client = createClient<paths>({ baseUrl: opts.url })\n\n const middlewareOpts = {\n auth: opts.auth,\n contentSystemId: opts.contentSystemId,\n logger: payload.logger,\n url: opts.url,\n }\n\n client.use(createAuthMiddleware(middlewareOpts))\n client.use(createErrorMiddleware(middlewareOpts))\n\n return createDatabaseAdapter<ContentAPIAdapter>({\n name: 'content_api',\n auth: opts.auth,\n beginTransaction: () => Promise.resolve('no-op-transaction'),\n client,\n commitTransaction: async () => {},\n contentSystemId: opts.contentSystemId,\n count: count as Count,\n countGlobalVersions: countGlobalVersions as CountGlobalVersions,\n countVersions: countVersions as CountVersions,\n create: create as Create,\n createGlobal: createGlobal as CreateGlobal,\n createGlobalVersion: createGlobalVersion as CreateGlobalVersion,\n createVersion: createVersion as CreateVersion,\n defaultIDType: 'text',\n deleteMany: deleteMany as DeleteMany,\n deleteOne: deleteOne as DeleteOne,\n deleteVersions: deleteVersions as DeleteVersions,\n find: find as Find,\n findDistinct: () =>\n Promise.reject(new Error('findDistinct is not yet implemented for Content API adapter')),\n findGlobal: findGlobal as FindGlobal,\n findGlobalVersions: findGlobalVersions as FindGlobalVersions,\n findOne: findOne as FindOne,\n findVersions: findVersions as FindVersions,\n init,\n packageName: '@payloadcms/db-content-api',\n payload,\n queryDrafts: queryDrafts as QueryDrafts,\n rollbackTransaction: async () => {},\n updateGlobal: updateGlobal as UpdateGlobal,\n updateGlobalVersion: updateGlobalVersion as UpdateGlobalVersion,\n updateMany: updateMany as UpdateMany,\n updateOne: updateOne as UpdateOne,\n updateVersion: updateVersion as UpdateVersion,\n upsert: upsert as Upsert,\n url: opts.url,\n })\n },\n})\n"],"names":["createClient","createDatabaseAdapter","v4","uuid","getPaginationData","getGlobalSlug","addFallbackSort","convertPayloadSortToContentAPI","unwrapDocument","createAuthMiddleware","createErrorMiddleware","dataToContentAPI","convertPayloadJoinsToContentAPI","convertPayloadWhereToContentAPI","init","auth","mode","payload","logger","info","process","env","PAYLOAD_DROP_DATABASE","contentSystemId","fetch","url","body","JSON","stringify","headers","method","error","warn","message","existingIds","data","response","client","GET","params","path","Error","Set","map","c","id","size","collection","config","collections","has","slug","createCollection","call","global","globals","globalId","collectionId","POST","errorMessage","includes","findMany","joins","limit","page","pagination","sort","where","collectionConfig","find","sortWithFallback","join","undefined","docs","result","doc","args","defaultSort","findVersions","whereClause","parentToDocumentId","queryDrafts","latest","equals","createVersion","collectionSlug","versionData","documentId","String","parent","autosave","updateVersion","createOnMissing","deleteVersions","findOne","updateMany","returning","updateOne","deleteMany","deleteOne","create","count","totalDocs","countVersions","upsert","idClause","createGlobal","globalType","findGlobal","updateGlobal","findGlobalVersions","createGlobalVersion","globalSlug","createdAt","updatedAt","updateGlobalVersion","countGlobalVersions","contentAPIAdapter","opts","name","defaultIDType","baseUrl","middlewareOpts","use","beginTransaction","Promise","resolve","commitTransaction","findDistinct","reject","packageName","rollbackTransaction"],"mappings":"AAgDA,OAAOA,kBA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A;gBACrBb,eAAeA;gBACfH,QAAQA;gBACRM,cAAcA;gBACdK,qBAAqBA;gBACrB3B,eAAeA;gBACfoC,eAAe;gBACftB,YAAYA;gBACZC,WAAWA;gBACXN,gBAAgBA;gBAChBxB,MAAMA;gBACN2D,cAAc,IACZH,QAAQI,MAAM,CAAC,IAAIxF,MAAM;gBAC3BmE,YAAYA;gBACZE,oBAAoBA;gBACpBhB,SAASA;gBACThB,cAAcA;gBACdhE;gBACAoH,aAAa;gBACbjH;gBACAgE,aAAaA;gBACbkD,qBAAqB,WAAa;gBAClCtB,cAAcA;gBACdM,qBAAqBA;gBACrBpB,YAAYA;gBACZE,WAAWA;gBACXN,eAAeA;gBACfa,QAAQA;gBACR/E,KAAK6F,KAAK7F,GAAG;YACf;QACF;IACF,CAAA,EAAE"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { components } from '../generated/content-api-types.js';
|
|
2
|
+
export declare const getPaginationData: (contentAPIPagination: components["schemas"]["Pagination"], pagination?: boolean) => {
|
|
3
|
+
hasNextPage: boolean;
|
|
4
|
+
hasPrevPage: boolean;
|
|
5
|
+
limit: number;
|
|
6
|
+
nextPage: number | null;
|
|
7
|
+
page: number;
|
|
8
|
+
pagingCounter: number;
|
|
9
|
+
prevPage: number | null;
|
|
10
|
+
totalDocs: number;
|
|
11
|
+
totalPages: number;
|
|
12
|
+
};
|
|
13
|
+
//# sourceMappingURL=pagination.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pagination.d.ts","sourceRoot":"","sources":["../../../src/db-content-api/temp-utilities/pagination.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mCAAmC,CAAA;AA6BnE,eAAO,MAAM,iBAAiB,yBACN,UAAU,CAAC,SAAS,CAAC,CAAC,YAAY,CAAC,eAC5C,OAAO;;;;;;;;;;CAiBrB,CAAA"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// Convert Content API pagination response to Payload's expected format
|
|
2
|
+
// Content API already calculates next/prev pages, we just need to transform the structure
|
|
3
|
+
//
|
|
4
|
+
// Content API format (nested):
|
|
5
|
+
// {
|
|
6
|
+
// data: [...],
|
|
7
|
+
// pagination: {
|
|
8
|
+
// total: 100,
|
|
9
|
+
// current: { limit: 10, page: 2 },
|
|
10
|
+
// next: { limit: 10, page: 3 },
|
|
11
|
+
// prev: { limit: 10, page: 1 }
|
|
12
|
+
// }
|
|
13
|
+
// }
|
|
14
|
+
//
|
|
15
|
+
// Payload format (flat):
|
|
16
|
+
// {
|
|
17
|
+
// docs: [...],
|
|
18
|
+
// hasNextPage: true,
|
|
19
|
+
// hasPrevPage: true,
|
|
20
|
+
// limit: 10,
|
|
21
|
+
// nextPage: 3,
|
|
22
|
+
// page: 2,
|
|
23
|
+
// pagingCounter: 11,
|
|
24
|
+
// prevPage: 1,
|
|
25
|
+
// totalDocs: 100,
|
|
26
|
+
// totalPages: 10
|
|
27
|
+
// }
|
|
28
|
+
export const getPaginationData = (contentAPIPagination, pagination)=>{
|
|
29
|
+
const { current, next, prev, total } = contentAPIPagination;
|
|
30
|
+
const hasNextPage = pagination !== false && next !== undefined;
|
|
31
|
+
const hasPrevPage = pagination !== false && prev !== undefined;
|
|
32
|
+
return {
|
|
33
|
+
hasNextPage,
|
|
34
|
+
hasPrevPage,
|
|
35
|
+
limit: current.limit,
|
|
36
|
+
nextPage: next?.page ?? null,
|
|
37
|
+
page: current.page,
|
|
38
|
+
pagingCounter: (current.page - 1) * current.limit + 1,
|
|
39
|
+
prevPage: prev?.page ?? null,
|
|
40
|
+
totalDocs: total,
|
|
41
|
+
totalPages: current.limit > 0 ? Math.ceil(total / current.limit) : 1
|
|
42
|
+
};
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
//# sourceMappingURL=pagination.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/db-content-api/temp-utilities/pagination.ts"],"sourcesContent":["import type { components } from '../generated/content-api-types.js'\n\n// Convert Content API pagination response to Payload's expected format\n// Content API already calculates next/prev pages, we just need to transform the structure\n//\n// Content API format (nested):\n// {\n// data: [...],\n// pagination: {\n// total: 100,\n// current: { limit: 10, page: 2 },\n// next: { limit: 10, page: 3 },\n// prev: { limit: 10, page: 1 }\n// }\n// }\n//\n// Payload format (flat):\n// {\n// docs: [...],\n// hasNextPage: true,\n// hasPrevPage: true,\n// limit: 10,\n// nextPage: 3,\n// page: 2,\n// pagingCounter: 11,\n// prevPage: 1,\n// totalDocs: 100,\n// totalPages: 10\n// }\nexport const getPaginationData = (\n contentAPIPagination: components['schemas']['Pagination'],\n pagination?: boolean,\n) => {\n const { current, next, prev, total } = contentAPIPagination\n const hasNextPage = pagination !== false && next !== undefined\n const hasPrevPage = pagination !== false && prev !== undefined\n\n return {\n hasNextPage,\n hasPrevPage,\n limit: current.limit,\n nextPage: next?.page ?? null,\n page: current.page,\n pagingCounter: (current.page - 1) * current.limit + 1,\n prevPage: prev?.page ?? null,\n totalDocs: total,\n totalPages: current.limit > 0 ? Math.ceil(total / current.limit) : 1,\n }\n}\n"],"names":["getPaginationData","contentAPIPagination","pagination","current","next","prev","total","hasNextPage","undefined","hasPrevPage","limit","nextPage","page","pagingCounter","prevPage","totalDocs","totalPages","Math","ceil"],"mappings":"AAEA,uEAAuE;AACvE,0FAA0F;AAC1F,EAAE;AACF,+BAA+B;AAC/B,IAAI;AACJ,iBAAiB;AACjB,kBAAkB;AAClB,kBAAkB;AAClB,uCAAuC;AACvC,oCAAoC;AACpC,mCAAmC;AACnC,MAAM;AACN,IAAI;AACJ,EAAE;AACF,yBAAyB;AACzB,IAAI;AACJ,iBAAiB;AACjB,uBAAuB;AACvB,uBAAuB;AACvB,eAAe;AACf,iBAAiB;AACjB,aAAa;AACb,uBAAuB;AACvB,iBAAiB;AACjB,oBAAoB;AACpB,mBAAmB;AACnB,IAAI;AACJ,OAAO,MAAMA,oBAAoB,CAC/BC,sBACAC;IAEA,MAAM,EAAEC,OAAO,EAAEC,IAAI,EAAEC,IAAI,EAAEC,KAAK,EAAE,GAAGL;IACvC,MAAMM,cAAcL,eAAe,SAASE,SAASI;IACrD,MAAMC,cAAcP,eAAe,SAASG,SAASG;IAErD,OAAO;QACLD;QACAE;QACAC,OAAOP,QAAQO,KAAK;QACpBC,UAAUP,MAAMQ,QAAQ;QACxBA,MAAMT,QAAQS,IAAI;QAClBC,eAAe,AAACV,CAAAA,QAAQS,IAAI,GAAG,CAAA,IAAKT,QAAQO,KAAK,GAAG;QACpDI,UAAUT,MAAMO,QAAQ;QACxBG,WAAWT;QACXU,YAAYb,QAAQO,KAAK,GAAG,IAAIO,KAAKC,IAAI,CAACZ,QAAQH,QAAQO,KAAK,IAAI;IACrE;AACF,EAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"slug.d.ts","sourceRoot":"","sources":["../../../src/db-content-api/temp-utilities/slug.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,aAAa,SAAU,MAAM,WAAsB,CAAA"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/db-content-api/temp-utilities/slug.ts"],"sourcesContent":["export const getGlobalSlug = (slug: string) => `_global-${slug}`\n"],"names":["getGlobalSlug","slug"],"mappings":"AAAA,OAAO,MAAMA,gBAAgB,CAACC,OAAiB,CAAC,QAAQ,EAAEA,MAAM,CAAA"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { CollectionConfig } from 'payload';
|
|
2
|
+
export declare function addFallbackSort(sort: string | string[] | undefined, collectionConfig: CollectionConfig | undefined): string | string[] | undefined;
|
|
3
|
+
export declare function convertPayloadSortToContentAPI(sort: string | string[] | undefined): Array<{
|
|
4
|
+
direction: 'asc' | 'desc';
|
|
5
|
+
path: string;
|
|
6
|
+
}> | undefined;
|
|
7
|
+
//# sourceMappingURL=sorting.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sorting.d.ts","sourceRoot":"","sources":["../../../src/db-content-api/temp-utilities/sorting.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAK/C,wBAAgB,eAAe,CAC7B,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,EACnC,gBAAgB,EAAE,gBAAgB,GAAG,SAAS,GAC7C,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CA4B/B;AAcD,wBAAgB,8BAA8B,CAC5C,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,GAClC,KAAK,CAAC;IAAE,SAAS,EAAE,KAAK,GAAG,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,GAAG,SAAS,CA2BhE"}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// Add fallback sort to ensure consistent ordering when sorting by non-unique fields
|
|
2
|
+
// Matches MongoDB adapter behavior
|
|
3
|
+
// TO-DECIDE: Should this live here or in content-api?
|
|
4
|
+
export function addFallbackSort(sort, collectionConfig) {
|
|
5
|
+
if (!sort || !collectionConfig) {
|
|
6
|
+
return sort;
|
|
7
|
+
}
|
|
8
|
+
const sortArray = Array.isArray(sort) ? sort : [
|
|
9
|
+
sort
|
|
10
|
+
];
|
|
11
|
+
// Determine fallback sort field
|
|
12
|
+
let fallbackSort = '-id';
|
|
13
|
+
if (collectionConfig.timestamps !== false) {
|
|
14
|
+
fallbackSort = '-createdAt';
|
|
15
|
+
}
|
|
16
|
+
// Check if fallback sort is already included
|
|
17
|
+
const hasFallback = sortArray.some((item)=>item === fallbackSort || item === fallbackSort.replace('-', ''));
|
|
18
|
+
if (hasFallback) {
|
|
19
|
+
return sort;
|
|
20
|
+
}
|
|
21
|
+
// Check if all sort fields are unique (then no fallback needed)
|
|
22
|
+
// For simplicity, we'll always add fallback - checking uniqueness requires field traversal
|
|
23
|
+
// which would be expensive. This matches the conservative approach.
|
|
24
|
+
// Add fallback sort - always return array to preserve multiple sort fields
|
|
25
|
+
return [
|
|
26
|
+
...sortArray,
|
|
27
|
+
fallbackSort
|
|
28
|
+
];
|
|
29
|
+
}
|
|
30
|
+
// ⚠️ TEMPORARY WORKAROUND - Remove once Content API is fixed
|
|
31
|
+
//
|
|
32
|
+
// TODO: Content API should accept Payload's native Sort format instead of requiring conversion.
|
|
33
|
+
// This converter exists because Content API expects a different format.
|
|
34
|
+
//
|
|
35
|
+
// Payload's format: "-createdAt" or ["createdAt", "-updatedAt"]
|
|
36
|
+
// Content API expects: [{ path: "createdAt", direction: "dsc" }]
|
|
37
|
+
//
|
|
38
|
+
// Once Content API accepts Payload's format:
|
|
39
|
+
// 1. Remove this function entirely
|
|
40
|
+
// 2. Remove all calls to convertPayloadSortToContentAPI()
|
|
41
|
+
// 3. Pass `sort` directly to Content API endpoints
|
|
42
|
+
export function convertPayloadSortToContentAPI(sort) {
|
|
43
|
+
if (!sort) {
|
|
44
|
+
return undefined;
|
|
45
|
+
}
|
|
46
|
+
const sortArray = Array.isArray(sort) ? sort : [
|
|
47
|
+
sort
|
|
48
|
+
];
|
|
49
|
+
return sortArray.map((field)=>{
|
|
50
|
+
let path = field;
|
|
51
|
+
let direction = 'asc';
|
|
52
|
+
// Check if field starts with '-' for descending
|
|
53
|
+
if (field.startsWith('-')) {
|
|
54
|
+
path = field.substring(1); // Remove the '-'
|
|
55
|
+
direction = 'desc';
|
|
56
|
+
}
|
|
57
|
+
// ⚠️ WORKAROUND: Strip "version." prefix from field names
|
|
58
|
+
// Payload sends "-version.createdAt" for version sort fields
|
|
59
|
+
// but Content API expects just "createdAt"
|
|
60
|
+
// TODO: Content API should handle version field paths correctly
|
|
61
|
+
if (path.startsWith('version.')) {
|
|
62
|
+
path = path.substring(8); // Remove "version." prefix
|
|
63
|
+
}
|
|
64
|
+
return {
|
|
65
|
+
direction,
|
|
66
|
+
path
|
|
67
|
+
};
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
//# sourceMappingURL=sorting.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/db-content-api/temp-utilities/sorting.ts"],"sourcesContent":["import type { CollectionConfig } from 'payload'\n\n// Add fallback sort to ensure consistent ordering when sorting by non-unique fields\n// Matches MongoDB adapter behavior\n// TO-DECIDE: Should this live here or in content-api?\nexport function addFallbackSort(\n sort: string | string[] | undefined,\n collectionConfig: CollectionConfig | undefined,\n): string | string[] | undefined {\n if (!sort || !collectionConfig) {\n return sort\n }\n\n const sortArray = Array.isArray(sort) ? sort : [sort]\n\n // Determine fallback sort field\n let fallbackSort = '-id'\n if (collectionConfig.timestamps !== false) {\n fallbackSort = '-createdAt'\n }\n\n // Check if fallback sort is already included\n const hasFallback = sortArray.some(\n (item) => item === fallbackSort || item === fallbackSort.replace('-', ''),\n )\n\n if (hasFallback) {\n return sort\n }\n\n // Check if all sort fields are unique (then no fallback needed)\n // For simplicity, we'll always add fallback - checking uniqueness requires field traversal\n // which would be expensive. This matches the conservative approach.\n\n // Add fallback sort - always return array to preserve multiple sort fields\n return [...sortArray, fallbackSort]\n}\n\n// ⚠️ TEMPORARY WORKAROUND - Remove once Content API is fixed\n//\n// TODO: Content API should accept Payload's native Sort format instead of requiring conversion.\n// This converter exists because Content API expects a different format.\n//\n// Payload's format: \"-createdAt\" or [\"createdAt\", \"-updatedAt\"]\n// Content API expects: [{ path: \"createdAt\", direction: \"dsc\" }]\n//\n// Once Content API accepts Payload's format:\n// 1. Remove this function entirely\n// 2. Remove all calls to convertPayloadSortToContentAPI()\n// 3. Pass `sort` directly to Content API endpoints\nexport function convertPayloadSortToContentAPI(\n sort: string | string[] | undefined,\n): Array<{ direction: 'asc' | 'desc'; path: string }> | undefined {\n if (!sort) {\n return undefined\n }\n\n const sortArray = Array.isArray(sort) ? sort : [sort]\n\n return sortArray.map((field) => {\n let path = field\n let direction: 'asc' | 'desc' = 'asc'\n\n // Check if field starts with '-' for descending\n if (field.startsWith('-')) {\n path = field.substring(1) // Remove the '-'\n direction = 'desc'\n }\n\n // ⚠️ WORKAROUND: Strip \"version.\" prefix from field names\n // Payload sends \"-version.createdAt\" for version sort fields\n // but Content API expects just \"createdAt\"\n // TODO: Content API should handle version field paths correctly\n if (path.startsWith('version.')) {\n path = path.substring(8) // Remove \"version.\" prefix\n }\n\n return { direction, path }\n })\n}\n"],"names":["addFallbackSort","sort","collectionConfig","sortArray","Array","isArray","fallbackSort","timestamps","hasFallback","some","item","replace","convertPayloadSortToContentAPI","undefined","map","field","path","direction","startsWith","substring"],"mappings":"AAEA,oFAAoF;AACpF,mCAAmC;AACnC,sDAAsD;AACtD,OAAO,SAASA,gBACdC,IAAmC,EACnCC,gBAA8C;IAE9C,IAAI,CAACD,QAAQ,CAACC,kBAAkB;QAC9B,OAAOD;IACT;IAEA,MAAME,YAAYC,MAAMC,OAAO,CAACJ,QAAQA,OAAO;QAACA;KAAK;IAErD,gCAAgC;IAChC,IAAIK,eAAe;IACnB,IAAIJ,iBAAiBK,UAAU,KAAK,OAAO;QACzCD,eAAe;IACjB;IAEA,6CAA6C;IAC7C,MAAME,cAAcL,UAAUM,IAAI,CAChC,CAACC,OAASA,SAASJ,gBAAgBI,SAASJ,aAAaK,OAAO,CAAC,KAAK;IAGxE,IAAIH,aAAa;QACf,OAAOP;IACT;IAEA,gEAAgE;IAChE,2FAA2F;IAC3F,oEAAoE;IAEpE,2EAA2E;IAC3E,OAAO;WAAIE;QAAWG;KAAa;AACrC;AAEA,6DAA6D;AAC7D,EAAE;AACF,gGAAgG;AAChG,wEAAwE;AACxE,EAAE;AACF,gEAAgE;AAChE,iEAAiE;AACjE,EAAE;AACF,6CAA6C;AAC7C,mCAAmC;AACnC,0DAA0D;AAC1D,mDAAmD;AACnD,OAAO,SAASM,+BACdX,IAAmC;IAEnC,IAAI,CAACA,MAAM;QACT,OAAOY;IACT;IAEA,MAAMV,YAAYC,MAAMC,OAAO,CAACJ,QAAQA,OAAO;QAACA;KAAK;IAErD,OAAOE,UAAUW,GAAG,CAAC,CAACC;QACpB,IAAIC,OAAOD;QACX,IAAIE,YAA4B;QAEhC,gDAAgD;QAChD,IAAIF,MAAMG,UAAU,CAAC,MAAM;YACzBF,OAAOD,MAAMI,SAAS,CAAC,IAAG,iBAAiB;YAC3CF,YAAY;QACd;QAEA,0DAA0D;QAC1D,6DAA6D;QAC7D,2CAA2C;QAC3C,gEAAgE;QAChE,IAAID,KAAKE,UAAU,CAAC,aAAa;YAC/BF,OAAOA,KAAKG,SAAS,CAAC,IAAG,2BAA2B;QACtD;QAEA,OAAO;YAAEF;YAAWD;QAAK;IAC3B;AACF"}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { Payload } from 'payload';
|
|
2
|
+
import type { components } from '../generated/content-api-types.js';
|
|
3
|
+
export declare function unwrapDocument(payload: Payload, doc: components['schemas']['Document'] | components['schemas']['DocumentVersion'], collectionSlug?: string): Record<string, unknown>;
|
|
4
|
+
//# sourceMappingURL=unwrapDocument.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"unwrapDocument.d.ts","sourceRoot":"","sources":["../../../src/db-content-api/temp-utilities/unwrapDocument.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AAEtC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mCAAmC,CAAA;AAUnE,wBAAgB,cAAc,CAC5B,OAAO,EAAE,OAAO,EAChB,GAAG,EAAE,UAAU,CAAC,SAAS,CAAC,CAAC,UAAU,CAAC,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC,iBAAiB,CAAC,EACjF,cAAc,CAAC,EAAE,MAAM,GACtB,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CA6CzB"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { dataFromContentAPI } from '../utilities/data.js';
|
|
2
|
+
// Helper to unwrap Content API document format to Payload format
|
|
3
|
+
// Content API returns: { id, data: { ...fields }, createdAt, updatedAt }
|
|
4
|
+
// Payload expects:
|
|
5
|
+
// - For documents: { id, ...fields, createdAt, updatedAt }
|
|
6
|
+
// - For versions: { id, version: { ...fields }, createdAt, updatedAt, ... }
|
|
7
|
+
export function unwrapDocument(payload, doc, collectionSlug) {
|
|
8
|
+
if (!doc) {
|
|
9
|
+
return doc;
|
|
10
|
+
}
|
|
11
|
+
// Check if this is a DocumentVersion (has documentId and latest fields)
|
|
12
|
+
const isVersion = 'documentId' in doc && 'latest' in doc;
|
|
13
|
+
if (isVersion) {
|
|
14
|
+
// For versions, Payload expects nested structure with 'version' field
|
|
15
|
+
const versionDoc = doc;
|
|
16
|
+
const baseDoc = {
|
|
17
|
+
id: versionDoc.id,
|
|
18
|
+
createdAt: versionDoc.createdAt,
|
|
19
|
+
latest: versionDoc.latest,
|
|
20
|
+
updatedAt: versionDoc.updatedAt,
|
|
21
|
+
version: versionDoc.data
|
|
22
|
+
};
|
|
23
|
+
// Transform data from Content API format to Payload format
|
|
24
|
+
if (collectionSlug) {
|
|
25
|
+
// Only transform the nested 'version' field
|
|
26
|
+
baseDoc.version = dataFromContentAPI(payload, collectionSlug, baseDoc.version);
|
|
27
|
+
}
|
|
28
|
+
return baseDoc;
|
|
29
|
+
} else {
|
|
30
|
+
// For regular documents, spread data at root level
|
|
31
|
+
const baseDoc = {
|
|
32
|
+
...doc.data,
|
|
33
|
+
id: doc.id,
|
|
34
|
+
createdAt: doc.createdAt,
|
|
35
|
+
updatedAt: doc.updatedAt
|
|
36
|
+
};
|
|
37
|
+
// Transform data from Content API format to Payload format
|
|
38
|
+
if (collectionSlug) {
|
|
39
|
+
return dataFromContentAPI(payload, collectionSlug, baseDoc);
|
|
40
|
+
}
|
|
41
|
+
return baseDoc;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
//# sourceMappingURL=unwrapDocument.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/db-content-api/temp-utilities/unwrapDocument.ts"],"sourcesContent":["import type { Payload } from 'payload'\n\nimport type { components } from '../generated/content-api-types.js'\n\nimport { dataFromContentAPI } from '../utilities/data.js'\n\n// Helper to unwrap Content API document format to Payload format\n// Content API returns: { id, data: { ...fields }, createdAt, updatedAt }\n// Payload expects:\n// - For documents: { id, ...fields, createdAt, updatedAt }\n\n// - For versions: { id, version: { ...fields }, createdAt, updatedAt, ... }\nexport function unwrapDocument(\n payload: Payload,\n doc: components['schemas']['Document'] | components['schemas']['DocumentVersion'],\n collectionSlug?: string,\n): Record<string, unknown> {\n if (!doc) {\n return doc as unknown as Record<string, unknown>\n }\n\n // Check if this is a DocumentVersion (has documentId and latest fields)\n const isVersion = 'documentId' in doc && 'latest' in doc\n\n if (isVersion) {\n // For versions, Payload expects nested structure with 'version' field\n const versionDoc = doc\n const baseDoc = {\n id: versionDoc.id,\n createdAt: versionDoc.createdAt,\n latest: versionDoc.latest,\n updatedAt: versionDoc.updatedAt,\n version: versionDoc.data, // Nest data inside 'version'\n }\n\n // Transform data from Content API format to Payload format\n if (collectionSlug) {\n // Only transform the nested 'version' field\n baseDoc.version = dataFromContentAPI(payload, collectionSlug, baseDoc.version) as Record<\n string,\n unknown\n >\n }\n\n return baseDoc as Record<string, unknown>\n } else {\n // For regular documents, spread data at root level\n const baseDoc = {\n ...doc.data, // Spread the actual document fields\n id: doc.id,\n createdAt: doc.createdAt,\n updatedAt: doc.updatedAt,\n }\n\n // Transform data from Content API format to Payload format\n if (collectionSlug) {\n return dataFromContentAPI(payload, collectionSlug, baseDoc) as Record<string, unknown>\n }\n\n return baseDoc as Record<string, unknown>\n }\n}\n"],"names":["dataFromContentAPI","unwrapDocument","payload","doc","collectionSlug","isVersion","versionDoc","baseDoc","id","createdAt","latest","updatedAt","version","data"],"mappings":"AAIA,SAASA,kBAAkB,QAAQ,uBAAsB;AAEzD,iEAAiE;AACjE,yEAAyE;AACzE,mBAAmB;AACnB,6DAA6D;AAE7D,8EAA8E;AAC9E,OAAO,SAASC,eACdC,OAAgB,EAChBC,GAAiF,EACjFC,cAAuB;IAEvB,IAAI,CAACD,KAAK;QACR,OAAOA;IACT;IAEA,wEAAwE;IACxE,MAAME,YAAY,gBAAgBF,OAAO,YAAYA;IAErD,IAAIE,WAAW;QACb,sEAAsE;QACtE,MAAMC,aAAaH;QACnB,MAAMI,UAAU;YACdC,IAAIF,WAAWE,EAAE;YACjBC,WAAWH,WAAWG,SAAS;YAC/BC,QAAQJ,WAAWI,MAAM;YACzBC,WAAWL,WAAWK,SAAS;YAC/BC,SAASN,WAAWO,IAAI;QAC1B;QAEA,2DAA2D;QAC3D,IAAIT,gBAAgB;YAClB,4CAA4C;YAC5CG,QAAQK,OAAO,GAAGZ,mBAAmBE,SAASE,gBAAgBG,QAAQK,OAAO;QAI/E;QAEA,OAAOL;IACT,OAAO;QACL,mDAAmD;QACnD,MAAMA,UAAU;YACd,GAAGJ,IAAIU,IAAI;YACXL,IAAIL,IAAIK,EAAE;YACVC,WAAWN,IAAIM,SAAS;YACxBE,WAAWR,IAAIQ,SAAS;QAC1B;QAEA,2DAA2D;QAC3D,IAAIP,gBAAgB;YAClB,OAAOJ,mBAAmBE,SAASE,gBAAgBG;QACrD;QAEA,OAAOA;IACT;AACF"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { Middleware } from 'openapi-fetch';
|
|
2
|
+
import type { Payload } from 'payload';
|
|
3
|
+
import type { TokenStore } from '../../auth/token-store.js';
|
|
4
|
+
type ApiKeyAuth = {
|
|
5
|
+
apiKey: string;
|
|
6
|
+
mode: 'apiKey';
|
|
7
|
+
};
|
|
8
|
+
type TokenStoreAuth = {
|
|
9
|
+
mode: 'tokenStore';
|
|
10
|
+
tokenStore: TokenStore;
|
|
11
|
+
};
|
|
12
|
+
type DevJwtAuth = {
|
|
13
|
+
mode: 'devJwt';
|
|
14
|
+
};
|
|
15
|
+
export type AuthMode = ApiKeyAuth | DevJwtAuth | TokenStoreAuth;
|
|
16
|
+
export declare function fetchDevJwt(url: string, contentSystemId: string): Promise<string>;
|
|
17
|
+
export declare function createAuthMiddleware(opts: {
|
|
18
|
+
auth: AuthMode;
|
|
19
|
+
contentSystemId: string;
|
|
20
|
+
logger: Payload['logger'];
|
|
21
|
+
url: string;
|
|
22
|
+
}): Middleware;
|
|
23
|
+
export declare function createErrorMiddleware(opts: {
|
|
24
|
+
auth: AuthMode;
|
|
25
|
+
contentSystemId: string;
|
|
26
|
+
logger: Payload['logger'];
|
|
27
|
+
url: string;
|
|
28
|
+
}): Middleware;
|
|
29
|
+
export {};
|
|
30
|
+
//# sourceMappingURL=auth.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../../src/db-content-api/utilities/auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAA;AAC/C,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AAEtC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAA;AAK3D,KAAK,UAAU,GAAG;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,QAAQ,CAAA;CAAE,CAAA;AACpD,KAAK,cAAc,GAAG;IAAE,IAAI,EAAE,YAAY,CAAC;IAAC,UAAU,EAAE,UAAU,CAAA;CAAE,CAAA;AACpE,KAAK,UAAU,GAAG;IAAE,IAAI,EAAE,QAAQ,CAAA;CAAE,CAAA;AACpC,MAAM,MAAM,QAAQ,GAAG,UAAU,GAAG,UAAU,GAAG,cAAc,CAAA;AAK/D,wBAAsB,WAAW,CAAC,GAAG,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAiBvF;AAED,wBAAgB,oBAAoB,CAAC,IAAI,EAAE;IACzC,IAAI,EAAE,QAAQ,CAAA;IACd,eAAe,EAAE,MAAM,CAAA;IACvB,MAAM,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAA;IACzB,GAAG,EAAE,MAAM,CAAA;CACZ,GAAG,UAAU,CAyBb;AAED,wBAAgB,qBAAqB,CAAC,IAAI,EAAE;IAC1C,IAAI,EAAE,QAAQ,CAAA;IACd,eAAe,EAAE,MAAM,CAAA;IACvB,MAAM,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAA;IACzB,GAAG,EAAE,MAAM,CAAA;CACZ,GAAG,UAAU,CAqCb"}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { getValidProjectToken } from '../../auth/project-token.js';
|
|
2
|
+
// Module-level cache for dev JWT tokens
|
|
3
|
+
const devJwtCache = new Map();
|
|
4
|
+
export async function fetchDevJwt(url, contentSystemId) {
|
|
5
|
+
const usesSuperUser = !contentSystemId || contentSystemId === 'test-system' || contentSystemId === '*';
|
|
6
|
+
const contentSystemIdForJWT = usesSuperUser ? '*' : contentSystemId;
|
|
7
|
+
const response = await fetch(`${url}/dev/jwt`, {
|
|
8
|
+
body: JSON.stringify({
|
|
9
|
+
content_system_id: contentSystemIdForJWT
|
|
10
|
+
}),
|
|
11
|
+
headers: {
|
|
12
|
+
'Content-Type': 'application/json'
|
|
13
|
+
},
|
|
14
|
+
method: 'POST'
|
|
15
|
+
});
|
|
16
|
+
if (!response.ok) {
|
|
17
|
+
throw new Error(`Failed to get dev JWT: ${response.status} ${response.statusText}`);
|
|
18
|
+
}
|
|
19
|
+
const { token } = await response.json();
|
|
20
|
+
return token;
|
|
21
|
+
}
|
|
22
|
+
export function createAuthMiddleware(opts) {
|
|
23
|
+
return {
|
|
24
|
+
async onRequest ({ request }) {
|
|
25
|
+
if (opts.auth.mode === 'apiKey') {
|
|
26
|
+
request.headers.set('X-Api-Key', opts.auth.apiKey);
|
|
27
|
+
} else if (opts.auth.mode === 'tokenStore') {
|
|
28
|
+
const token = await getValidProjectToken(opts.auth.tokenStore, opts.contentSystemId);
|
|
29
|
+
if (!token) {
|
|
30
|
+
throw new Error('Authentication required. Run `npx @payloadcms/figma login` to authenticate.');
|
|
31
|
+
}
|
|
32
|
+
request.headers.set('Authorization', `Bearer ${token}`);
|
|
33
|
+
} else {
|
|
34
|
+
let token = devJwtCache.get(opts.contentSystemId);
|
|
35
|
+
if (!token) {
|
|
36
|
+
token = await fetchDevJwt(opts.url, opts.contentSystemId);
|
|
37
|
+
devJwtCache.set(opts.contentSystemId, token);
|
|
38
|
+
opts.logger.info(`Dev JWT acquired for content system: ${opts.contentSystemId}`);
|
|
39
|
+
}
|
|
40
|
+
request.headers.set('Authorization', `Bearer ${token}`);
|
|
41
|
+
}
|
|
42
|
+
return request;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
export function createErrorMiddleware(opts) {
|
|
47
|
+
return {
|
|
48
|
+
async onResponse ({ request, response }) {
|
|
49
|
+
if (!response.ok) {
|
|
50
|
+
// Handle 401 retry for dev JWT
|
|
51
|
+
if (response.status === 401 && opts.auth.mode === 'devJwt') {
|
|
52
|
+
const retryCount = parseInt(request.headers.get('X-Retry-Count') || '0', 10);
|
|
53
|
+
if (retryCount < 1) {
|
|
54
|
+
opts.logger.info('Dev JWT expired, refreshing...');
|
|
55
|
+
devJwtCache.delete(opts.contentSystemId);
|
|
56
|
+
const newToken = await fetchDevJwt(opts.url, opts.contentSystemId);
|
|
57
|
+
devJwtCache.set(opts.contentSystemId, newToken);
|
|
58
|
+
// duplex: 'half' is required for Node.js fetch with streaming body
|
|
59
|
+
const newRequest = new Request(request.url, {
|
|
60
|
+
body: request.body,
|
|
61
|
+
duplex: 'half',
|
|
62
|
+
headers: new Headers(request.headers),
|
|
63
|
+
method: request.method
|
|
64
|
+
});
|
|
65
|
+
newRequest.headers.set('X-Retry-Count', '1');
|
|
66
|
+
newRequest.headers.set('Authorization', `Bearer ${newToken}`);
|
|
67
|
+
return fetch(newRequest);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
const text = await response.clone().text();
|
|
71
|
+
opts.logger.error({
|
|
72
|
+
msg: `HTTP ${response.status} from ${request.url}`,
|
|
73
|
+
response: text
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
return response;
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
//# sourceMappingURL=auth.js.map
|