@payloadcms/figma 0.0.1-alpha.27 → 0.0.1-alpha.28

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.
@@ -50,18 +50,35 @@ async function init() {
50
50
  this.payload.logger.warn(`Failed to drop content system: ${error.message}`);
51
51
  }
52
52
  }
53
- // Create collections if they don't exist
53
+ // Fetch existing collections once
54
+ let existingKeys;
55
+ try {
56
+ const response = await this.makeRequest(`/api/v0/collections?contentSystemId=${this.contentSystemId}`, {
57
+ method: 'GET'
58
+ });
59
+ existingKeys = new Set(response.data.map((c)=>c.key));
60
+ this.payload.logger.info(`Found ${existingKeys.size} existing collections`);
61
+ } catch (error) {
62
+ this.payload.logger.warn(`Failed to fetch collections, will attempt to create all: ${error.message}`);
63
+ existingKeys = new Set();
64
+ }
65
+ // Create only missing collections
54
66
  for (const collection of this.payload.config.collections){
55
- await createCollectionIfNotExists.call(this, collection.slug);
67
+ if (!existingKeys.has(collection.slug)) {
68
+ await createCollection.call(this, collection.slug);
69
+ }
56
70
  }
57
- // Create global collections
71
+ // Create only missing global collections
58
72
  for (const global of this.payload.config.globals || []){
59
- await createCollectionIfNotExists.call(this, `_global-${global.slug}`);
73
+ const globalKey = `_global-${global.slug}`;
74
+ if (!existingKeys.has(globalKey)) {
75
+ await createCollection.call(this, globalKey);
76
+ }
60
77
  }
61
78
  return;
62
79
  }
63
- // Helper to create a collection if it doesn't exist
64
- async function createCollectionIfNotExists(collectionKey) {
80
+ // Helper to create a collection
81
+ async function createCollection(collectionKey) {
65
82
  try {
66
83
  await this.makeRequest('/api/v0/collections', {
67
84
  body: {
@@ -73,8 +90,8 @@ async function createCollectionIfNotExists(collectionKey) {
73
90
  });
74
91
  this.payload.logger.info(`Created collection: ${collectionKey}`);
75
92
  } catch (error) {
76
- // If collection already exists, that's fine - ignore the error
77
93
  const errorMessage = error.message;
94
+ // Still handle 409 gracefully in case of race conditions
78
95
  if (!errorMessage.includes('already exists') && !errorMessage.includes('409')) {
79
96
  this.payload.logger.warn(`Failed to create collection ${collectionKey}: ${errorMessage}`);
80
97
  }
@@ -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\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 // Create collections if they don't exist\n for (const collection of this.payload.config.collections) {\n await createCollectionIfNotExists.call(this, collection.slug)\n }\n\n // Create global collections\n for (const global of this.payload.config.globals || []) {\n await createCollectionIfNotExists.call(this, `_global-${global.slug}`)\n }\n\n return\n}\n\n// Helper to create a collection if it doesn't exist\nasync function createCollectionIfNotExists(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 // If collection already exists, that's fine - ignore the 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 ${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","collection","config","collections","createCollectionIfNotExists","call","slug","global","globals","collectionKey","name","key","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","map","item","or","operators","op","operatorValue","finalValue","push","operator","addFallbackSort","sort","collectionConfig","sortArray","Array","isArray","fallbackSort","timestamps","hasFallback","some","replace","convertPayloadSortToContentAPI","field","direction","dataToContentAPI","collectionSlug","data","transformed","isGlobal","actualSlug","find","g","c","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;AAE/D,qDAAqD;AACrD,sFAAsF;AACtF,MAAMC,mBAAmB;AACzB,MAAMC,wBAAwB;AAE9B,8EAA8E;AAC9E,MAAMC,cAAc,IAAIC;AAExB,8EAA8E;AAC9E,eAAeC,YAAYC,GAAW,EAAEC,eAAuB;IAC7D,MAAMC,gBACJ,CAACD,mBAAmBA,oBAAoB,iBAAiBA,oBAAoB;IAC/E,MAAME,wBAAwBD,gBAAgB,MAAMD;IAEpD,MAAMG,WAAW,MAAMC,MAAM,GAAGL,IAAI,QAAQ,CAAC,EAAE;QAC7CM,MAAMC,KAAKC,SAAS,CAAC;YAAEC,mBAAmBN;QAAsB;QAChEO,SAAS;YAAE,gBAAgB;QAAmB;QAC9CC,QAAQ;IACV;IAEA,IAAI,CAACP,SAASQ,EAAE,EAAE;QAChB,MAAM,IAAIC,MAAM,CAAC,uBAAuB,EAAET,SAASU,MAAM,CAAC,CAAC,EAAEV,SAASW,UAAU,EAAE;IACpF;IAEA,MAAM,EAAEC,KAAK,EAAE,GAAG,MAAMZ,SAASa,IAAI;IACrC,OAAOD;AACT;AAiCA,eAAeE;IACb,oCAAoC;IACpC,IAAI,IAAI,CAACC,IAAI,CAACC,IAAI,KAAK,UAAU;QAC/B,IAAI,CAACC,OAAO,CAACC,MAAM,CAACC,IAAI,CAAC;IAC3B,OAAO,IAAI,IAAI,CAACJ,IAAI,CAACC,IAAI,KAAK,cAAc;QAC1C,IAAI,CAACC,OAAO,CAACC,MAAM,CAACC,IAAI,CAAC;IAC3B,OAAO;QACL,IAAI,CAACF,OAAO,CAACC,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AAOC,QAAQC,OAAO,CAAC;gBACzB;gBACAC,mBAAmB,WAAa;gBAChC7L,iBAAiBwL,KAAKxL,eAAe;gBACrCwK;gBACAc;gBACAb;gBACAF;gBACAK;gBACAK;gBACA1B;gBACAkC,eAAe;gBACfpB;gBACAC;gBACAP;gBACAxD;gBACAuF,cAAc;oBACZ,OAAOH,QAAQI,MAAM,CACnB,IAAInL,MAAM;gBAEd;gBACAkK;gBACAE;gBACAf;gBACAd;gBACAlI;gBACAS;gBACAsK,aAAa;gBACb5K;gBACAgI;gBACA6C,qBAAqB,WAAa;gBAClClB;gBACAK;gBACAjB;gBACAC;gBACAR;gBACAc;gBACA3K,KAAKyL,KAAKzL,GAAG;YACf;QACF;IACF;AACF,EAAC"}
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,mBAAmB;AACzB,MAAMC,wBAAwB;AAE9B,8EAA8E;AAC9E,MAAMC,cAAc,IAAIC;AAExB,8EAA8E;AAC9E,eAAeC,YAAYC,GAAW,EAAEC,eAAuB;IAC7D,MAAMC,gBACJ,CAACD,mBAAmBA,oBAAoB,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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"}
@@ -29,6 +29,11 @@ export type DetectionResult = {
29
29
  needsImportChange: boolean;
30
30
  /** Whether a `secret` property exists in the config */
31
31
  secretProperty?: boolean;
32
+ /** Sharp configuration if present */
33
+ sharpProperty?: {
34
+ /** NPM package sharp is imported from (always 'sharp') */
35
+ importSource: string;
36
+ };
32
37
  };
33
38
  /**
34
39
  * Detect what changes are needed in the payload config file
@@ -1 +1 @@
1
- {"version":3,"file":"payload-config-ast.d.ts","sourceRoot":"","sources":["../../src/utils/payload-config-ast.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,UAAU,CAAA;AAM1C;;GAEG;AACH,MAAM,MAAM,eAAe,GAAG;IAC5B,gDAAgD;IAChD,UAAU,CAAC,EAAE;QACX,gFAAgF;QAChF,OAAO,EAAE,MAAM,CAAA;QACf,gFAAgF;QAChF,YAAY,EAAE,MAAM,CAAA;KACrB,CAAA;IACD,sCAAsC;IACtC,cAAc,CAAC,EAAE;QACf,qFAAqF;QACrF,YAAY,EAAE,MAAM,CAAA;QACpB,oEAAoE;QACpE,SAAS,EAAE,OAAO,CAAA;KACnB,CAAA;IACD,wDAAwD;IACxD,iBAAiB,EAAE,OAAO,CAAA;IAC1B,sGAAsG;IACtG,QAAQ,EAAE,OAAO,CAAA;IACjB,0FAA0F;IAC1F,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB,uFAAuF;IACvF,sBAAsB,EAAE,OAAO,CAAA;IAC/B,mFAAmF;IACnF,iBAAiB,EAAE,OAAO,CAAA;IAC1B,uDAAuD;IACvD,cAAc,CAAC,EAAE,OAAO,CAAA;CACzB,CAAA;AAED;;GAEG;AACH,wBAAgB,qBAAqB,CAAC,UAAU,EAAE,UAAU,GAAG,eAAe,CAqJ7E;AAED,MAAM,MAAM,qBAAqB,GAAG;IAClC,OAAO,EAAE,MAAM,EAAE,CAAA;IACjB,QAAQ,EAAE,OAAO,CAAA;CAClB,CAAA;AA0CD;;;GAGG;AACH,wBAAgB,kBAAkB,CAChC,UAAU,EAAE,UAAU,EACtB,SAAS,EAAE,eAAe,GACzB,qBAAqB,CAwKvB;AAED,MAAM,MAAM,mBAAmB,GAAG;IAChC,eAAe,EAAE,MAAM,CAAA;IACvB,gBAAgB,CAAC,EAAE,OAAO,CAAA;CAC3B,CAAA;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAC9B,UAAU,EAAE,UAAU,EACtB,MAAM,EAAE,mBAAmB,GAC1B,qBAAqB,CAqDvB;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,UAAU,EAAE,UAAU,GAAG,mBAAmB,GAAG,IAAI,CA4ElF"}
1
+ {"version":3,"file":"payload-config-ast.d.ts","sourceRoot":"","sources":["../../src/utils/payload-config-ast.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UA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mBAAmB,GAC1B,qBAAqB,CAqDvB;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,UAAU,EAAE,UAAU,GAAG,mBAAmB,GAAG,IAAI,CA4ElF"}
@@ -112,6 +112,15 @@ import * as log from './log.js';
112
112
  }
113
113
  }
114
114
  }
115
+ // Check for sharp property
116
+ const sharpProperty = configArg.getProperty('sharp');
117
+ if (sharpProperty) {
118
+ // Find the import source for sharp
119
+ const sharpImport = imports.find((imp)=>imp.getModuleSpecifierValue() === 'sharp' || imp.getNamedImports().some((ni)=>ni.getName() === 'sharp'));
120
+ result.sharpProperty = {
121
+ importSource: sharpImport?.getModuleSpecifierValue() || 'sharp'
122
+ };
123
+ }
115
124
  // Check for figma property
116
125
  const figmaProperty = configArg.getProperty('figma');
117
126
  if (figmaProperty) {
@@ -243,7 +252,16 @@ import * as log from './log.js';
243
252
  modified = true;
244
253
  }
245
254
  }
246
- // 4. Update buildConfig import
255
+ // 4. Remove sharp property
256
+ if (detection.sharpProperty) {
257
+ const sharpProperty = configArg.getProperty('sharp');
258
+ if (sharpProperty) {
259
+ sharpProperty.remove();
260
+ changes.push('Removed sharp property');
261
+ modified = true;
262
+ }
263
+ }
264
+ // 5. Update buildConfig import
247
265
  if (detection.needsImportChange) {
248
266
  if (payloadImport) {
249
267
  if (detection.hasOtherPayloadImports) {
@@ -285,7 +303,7 @@ import * as log from './log.js';
285
303
  modified = true;
286
304
  }
287
305
  }
288
- // 5. Remove orphaned imports
306
+ // 6. Remove orphaned imports
289
307
  // Re-fetch imports after each removal to avoid stale references
290
308
  if (detection.dbProperty) {
291
309
  const currentImports = sourceFile.getImportDeclarations();
@@ -305,6 +323,15 @@ import * as log from './log.js';
305
323
  modified = true;
306
324
  }
307
325
  }
326
+ if (detection.sharpProperty) {
327
+ const currentImports = sourceFile.getImportDeclarations();
328
+ const sharpImport = currentImports.find((imp)=>imp.getModuleSpecifierValue() === 'sharp');
329
+ if (sharpImport) {
330
+ sharpImport.remove();
331
+ changes.push('Removed sharp import');
332
+ modified = true;
333
+ }
334
+ }
308
335
  return {
309
336
  changes,
310
337
  modified
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/payload-config-ast.ts"],"sourcesContent":["import type { SourceFile } from 'ts-morph'\n\nimport { Node, SyntaxKind } from 'ts-morph'\n\nimport * as log from './log.js'\n\n/**\n * Result of detecting what changes are needed in a payload config file\n */\nexport type DetectionResult = {\n /** Database adapter configuration if present */\n dbProperty?: {\n /** Name of the adapter function (e.g., 'mongooseAdapter', 'postgresAdapter') */\n adapter: string\n /** NPM package the adapter is imported from (e.g., '@payloadcms/db-mongodb') */\n importSource: string\n }\n /** Editor configuration if present */\n editorProperty?: {\n /** NPM package the editor is imported from (e.g., '@payloadcms/richtext-lexical') */\n importSource: string\n /** Whether this is a default editor with no custom configuration */\n isDefault: boolean\n }\n /** Whether the config already has a `figma` property */\n figmaObjectExists: boolean\n /** Whether buildConfig/buildFigmaConfig uses an import alias (e.g., 'buildConfig as createConfig') */\n hasAlias: boolean\n /** Whether a buildConfig or buildFigmaConfig call was found (undefined if not checked) */\n hasBuildConfig?: boolean\n /** Whether there are other imports from 'payload' besides buildConfig (e.g., types) */\n hasOtherPayloadImports: boolean\n /** Whether the import needs to be changed from 'payload' to '@payloadcms/figma' */\n needsImportChange: boolean\n /** Whether a `secret` property exists in the config */\n secretProperty?: boolean\n}\n\n/**\n * Detect what changes are needed in the payload config file\n */\nexport function detectRequiredChanges(sourceFile: SourceFile): DetectionResult {\n const result: DetectionResult = {\n figmaObjectExists: false,\n hasAlias: false,\n hasOtherPayloadImports: false,\n needsImportChange: false,\n }\n\n // Find buildConfig import\n const imports = sourceFile.getImportDeclarations()\n const payloadImport = imports.find(\n (imp) =>\n imp.getModuleSpecifierValue() === 'payload' ||\n imp.getModuleSpecifierValue() === '@payloadcms/figma',\n )\n\n if (!payloadImport) {\n log.debug('No payload or @payloadcms/figma import found')\n result.hasBuildConfig = false\n return result\n }\n\n log.debug(`Found import from: ${payloadImport.getModuleSpecifierValue()}`)\n\n const moduleSpecifier = payloadImport.getModuleSpecifierValue()\n const namedImports = payloadImport.getNamedImports()\n\n // Determine which function name to look for based on the import source\n // - From 'payload': look for buildConfig (needs migration)\n // - From '@payloadcms/figma': look for buildFigmaConfig (already migrated)\n const expectedFunctionName = moduleSpecifier === 'payload' ? 'buildConfig' : 'buildFigmaConfig'\n\n const buildConfigImport = namedImports.find((ni) => ni.getName() === expectedFunctionName)\n\n if (!buildConfigImport) {\n result.hasBuildConfig = false\n return result\n }\n\n // Check for alias and get the actual name used in code\n const aliasNode = buildConfigImport.getAliasNode()\n const buildConfigName = aliasNode ? aliasNode.getText() : expectedFunctionName\n if (aliasNode) {\n result.hasAlias = true\n }\n\n // Check if import needs change\n if (moduleSpecifier === 'payload') {\n result.needsImportChange = true\n\n // Check if there are other imports from payload\n if (namedImports.length > 1) {\n result.hasOtherPayloadImports = true\n }\n }\n\n // Find buildConfig call in export default\n // First try to find export default with the buildConfig call\n const exportAssignment = sourceFile.getFirstDescendantByKind(SyntaxKind.ExportAssignment)\n let buildConfigCall = null\n\n if (exportAssignment) {\n // Look for buildConfig call in the export default\n const callExpressions = exportAssignment.getDescendantsOfKind(SyntaxKind.CallExpression)\n buildConfigCall = callExpressions.find((ce) => {\n const expr = ce.getExpression()\n return expr.getText() === buildConfigName\n })\n }\n\n // If not found in export default, search all call expressions\n if (!buildConfigCall) {\n const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)\n buildConfigCall = callExpressions.find((ce) => {\n const expr = ce.getExpression()\n return expr.getText() === buildConfigName\n })\n }\n\n if (!buildConfigCall) {\n result.hasBuildConfig = false\n return result\n }\n\n // Get config object\n const configArg = buildConfigCall.getArguments()[0]\n if (!configArg || !Node.isObjectLiteralExpression(configArg)) {\n return result\n }\n\n // Check for db property\n const dbProperty = configArg.getProperty('db')\n if (dbProperty) {\n const dbValue = dbProperty.getChildrenOfKind(SyntaxKind.CallExpression)[0]\n if (dbValue) {\n const adapterName = dbValue.getExpression().getText()\n\n // Find the import source for this adapter\n const adapterImport = imports.find((imp) =>\n imp.getNamedImports().some((ni) => ni.getName() === adapterName),\n )\n\n if (adapterImport) {\n result.dbProperty = {\n adapter: adapterName,\n importSource: adapterImport.getModuleSpecifierValue(),\n }\n }\n }\n }\n\n // Check for secret property\n const secretProperty = configArg.getProperty('secret')\n if (secretProperty) {\n result.secretProperty = true\n }\n\n // Check for editor property\n const editorProperty = configArg.getProperty('editor')\n if (editorProperty) {\n const editorValue = editorProperty.getChildrenOfKind(SyntaxKind.CallExpression)[0]\n if (editorValue) {\n const editorName = editorValue.getExpression().getText()\n\n // Find the import source\n const editorImport = imports.find((imp) =>\n imp.getNamedImports().some((ni) => ni.getName() === editorName),\n )\n\n if (editorImport && editorName === 'lexicalEditor') {\n // Check if it has arguments\n const args = editorValue.getArguments()\n const isDefault = args.length === 0\n\n result.editorProperty = {\n importSource: editorImport.getModuleSpecifierValue(),\n isDefault,\n }\n }\n }\n }\n\n // Check for figma property\n const figmaProperty = configArg.getProperty('figma')\n if (figmaProperty) {\n result.figmaObjectExists = true\n }\n\n return result\n}\n\nexport type ASTModificationResult = {\n changes: string[]\n modified: boolean\n}\n\n/**\n * Remove all comments\n * @returns true if any comments were removed\n */\nfunction removeAllComments(sourceFile: SourceFile): boolean {\n const ranges: Array<[number, number]> = []\n\n // Recursively collect comments from node and ALL children (including tokens)\n const collectComments = (node: Node) => {\n node.getLeadingCommentRanges().forEach((range) => {\n ranges.push([range.getPos(), range.getEnd()])\n })\n node.getTrailingCommentRanges().forEach((range) => {\n ranges.push([range.getPos(), range.getEnd()])\n })\n\n // Process ALL children including token nodes (commas, braces, etc.)\n node.getChildren().forEach(collectComments)\n }\n\n collectComments(sourceFile)\n\n if (ranges.length === 0) {\n return false\n }\n\n // Remove duplicates and sort in reverse order to avoid position shifts\n const uniqueRanges = Array.from(new Set(ranges.map((r) => JSON.stringify(r)))).map(\n (r) => JSON.parse(r) as [number, number],\n )\n uniqueRanges.sort((a, b) => b[0] - a[0])\n\n // Remove each comment range\n for (const [pos, end] of uniqueRanges) {\n sourceFile.removeText(pos, end)\n }\n\n return true\n}\n\n/**\n * Apply modifications to the source file based on detection result\n * Modifies the AST in memory - caller must call sourceFile.save()\n */\nexport function applyModifications(\n sourceFile: SourceFile,\n detection: DetectionResult,\n): ASTModificationResult {\n const changes: string[] = []\n let modified = false\n\n if (detection.hasBuildConfig === false || detection.hasAlias) {\n log.debug(\n `Skipping modifications: hasBuildConfig=${detection.hasBuildConfig}, hasAlias=${detection.hasAlias}`,\n )\n return { changes: [], modified: false }\n }\n\n // 1. Remove all comments FIRST (before AST modifications that might shift positions)\n const hadComments = removeAllComments(sourceFile)\n if (hadComments) {\n changes.push('Removed comments')\n modified = true\n }\n\n // Find the import declarations\n const imports = sourceFile.getImportDeclarations()\n const payloadImport = imports.find((imp) => imp.getModuleSpecifierValue() === 'payload')\n\n // Get the buildConfig name (could be aliased)\n let buildConfigName = 'buildConfig'\n if (payloadImport) {\n const buildConfigImport = payloadImport\n .getNamedImports()\n .find((ni) => ni.getName() === 'buildConfig')\n if (buildConfigImport) {\n const aliasNode = buildConfigImport.getAliasNode()\n buildConfigName = aliasNode ? aliasNode.getText() : 'buildConfig'\n }\n }\n\n // Find buildConfig call in export default (prefer export default)\n const exportAssignment = sourceFile.getFirstDescendantByKind(SyntaxKind.ExportAssignment)\n let buildConfigCall = null\n\n if (exportAssignment) {\n const callExpressions = exportAssignment.getDescendantsOfKind(SyntaxKind.CallExpression)\n buildConfigCall = callExpressions.find((ce) => {\n const expr = ce.getExpression()\n return expr.getText() === buildConfigName\n })\n }\n\n // If not found in export default, search all call expressions\n if (!buildConfigCall) {\n const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)\n buildConfigCall = callExpressions.find((ce) => {\n const expr = ce.getExpression()\n return expr.getText() === buildConfigName\n })\n }\n\n if (!buildConfigCall) {\n return { changes: [], modified: false }\n }\n\n const configArg = buildConfigCall.getArguments()[0]\n if (!configArg || !Node.isObjectLiteralExpression(configArg)) {\n return { changes: [], modified: false }\n }\n\n // 1. Remove db property\n if (detection.dbProperty) {\n const dbProperty = configArg.getProperty('db')\n if (dbProperty) {\n dbProperty.remove()\n changes.push('Removed db property')\n modified = true\n }\n }\n\n // 2. Remove secret property\n if (detection.secretProperty) {\n const secretProperty = configArg.getProperty('secret')\n if (secretProperty) {\n secretProperty.remove()\n changes.push('Removed secret property')\n modified = true\n }\n }\n\n // 3. Remove editor if default\n if (detection.editorProperty?.isDefault) {\n const editorProperty = configArg.getProperty('editor')\n if (editorProperty) {\n editorProperty.remove()\n changes.push('Removed default editor property')\n modified = true\n }\n }\n\n // 4. Update buildConfig import\n if (detection.needsImportChange) {\n if (payloadImport) {\n if (detection.hasOtherPayloadImports) {\n // Remove buildConfig from payload import, add new figma import\n const namedImports = payloadImport.getNamedImports()\n const buildConfigImport = namedImports.find((ni) => ni.getName() === 'buildConfig')\n if (buildConfigImport) {\n buildConfigImport.remove()\n\n // If payload import is now empty, remove it\n if (payloadImport.getNamedImports().length === 0) {\n payloadImport.remove()\n }\n }\n\n // Add new import at the top\n sourceFile.addImportDeclaration({\n moduleSpecifier: '@payloadcms/figma',\n namedImports: ['buildFigmaConfig'],\n })\n\n changes.push('Split buildConfig import to @payloadcms/figma')\n } else {\n // Replace entire import: change module specifier and rename all references\n const buildConfigImport = payloadImport\n .getNamedImports()\n .find((ni) => ni.getName() === 'buildConfig')\n if (buildConfigImport) {\n // Change the import name\n buildConfigImport.setName('buildFigmaConfig')\n\n // Find and rename all usages of 'buildConfig' in the file\n const identifiers = sourceFile.getDescendantsOfKind(SyntaxKind.Identifier)\n identifiers.forEach((identifier) => {\n if (identifier.getText() === 'buildConfig') {\n identifier.replaceWithText('buildFigmaConfig')\n }\n })\n }\n payloadImport.setModuleSpecifier('@payloadcms/figma')\n changes.push('Changed buildConfig import to @payloadcms/figma')\n }\n modified = true\n }\n }\n\n // 5. Remove orphaned imports\n // Re-fetch imports after each removal to avoid stale references\n if (detection.dbProperty) {\n const currentImports = sourceFile.getImportDeclarations()\n const dbImport = currentImports.find(\n (imp) => imp.getModuleSpecifierValue() === detection.dbProperty?.importSource,\n )\n if (dbImport) {\n dbImport.remove()\n changes.push(`Removed ${detection.dbProperty.adapter} import`)\n modified = true\n }\n }\n\n if (detection.editorProperty?.isDefault) {\n const currentImports = sourceFile.getImportDeclarations()\n const editorImport = currentImports.find(\n (imp) => imp.getModuleSpecifierValue() === detection.editorProperty?.importSource,\n )\n if (editorImport) {\n editorImport.remove()\n changes.push('Removed lexicalEditor import')\n modified = true\n }\n }\n\n return { changes, modified }\n}\n\nexport type FigmaPropertyConfig = {\n contentSystemId: string\n useContentSystem?: boolean\n}\n\n/**\n * Add figma property to buildConfig if it doesn't exist\n * Modifies the AST in memory - caller must call sourceFile.save()\n */\nexport function addFigmaProperty(\n sourceFile: SourceFile,\n config: FigmaPropertyConfig,\n): ASTModificationResult {\n const changes: string[] = []\n let modified = false\n\n // Find buildFigmaConfig call (this function is only used with Figma configs)\n const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)\n const buildConfigCall = callExpressions.find((ce) => {\n const expr = ce.getExpression()\n const text = expr.getText()\n return text === 'buildFigmaConfig' || text.endsWith('.buildFigmaConfig')\n })\n\n if (!buildConfigCall) {\n log.debug('No buildFigmaConfig call found')\n return { changes: [], modified: false }\n }\n\n // Get config object argument\n const configArg = buildConfigCall.getArguments()[0]\n if (!configArg || !Node.isObjectLiteralExpression(configArg)) {\n log.debug('buildConfig argument is not an object literal')\n return { changes: [], modified: false }\n }\n\n // Check if figma property already exists\n const existingFigmaProperty = configArg.getProperty('figma')\n if (existingFigmaProperty) {\n log.debug('figma property already exists, skipping')\n return { changes: ['Skipped: figma property already exists'], modified: false }\n }\n\n // Add figma property\n // Note: useContentSystem is optional and defaults to true, so we don't generate it during init\n // contentSystemId is stored in .env file and referenced via process.env with non-null assertion\n const figmaObj =\n config.useContentSystem === false\n ? `{\n contentSystemId: process.env.FIGMA_CONTENT_SYSTEM_ID!,\n useContentSystem: false,\n }`\n : `{\n contentSystemId: process.env.FIGMA_CONTENT_SYSTEM_ID!,\n }`\n\n configArg.addPropertyAssignment({\n name: 'figma',\n initializer: figmaObj,\n })\n\n changes.push(`Added figma property (contentSystemId: ${config.contentSystemId})`)\n modified = true\n\n return { changes, modified }\n}\n\n/**\n * Read figma configuration from payload.config.ts\n * Returns the figma object if it exists, null otherwise\n */\nexport function readFigmaConfig(sourceFile: SourceFile): FigmaPropertyConfig | null {\n // Find buildFigmaConfig call (this function is only used with Figma configs)\n const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)\n const buildConfigCall = callExpressions.find((ce) => {\n const expr = ce.getExpression()\n const text = expr.getText()\n return text === 'buildFigmaConfig' || text.endsWith('.buildFigmaConfig')\n })\n\n if (!buildConfigCall) {\n log.debug('No buildFigmaConfig call found')\n return null\n }\n\n // Get config object argument\n const configArg = buildConfigCall.getArguments()[0]\n if (!configArg || !Node.isObjectLiteralExpression(configArg)) {\n log.debug('buildConfig argument is not an object literal')\n return null\n }\n\n // Find figma property\n const figmaProperty = configArg.getProperty('figma')\n if (!figmaProperty || !Node.isPropertyAssignment(figmaProperty)) {\n log.debug('No figma property found in buildConfig')\n return null\n }\n\n // Get initializer (the object value)\n const initializer = figmaProperty.getInitializer()\n if (!initializer || !Node.isObjectLiteralExpression(initializer)) {\n log.debug('figma property is not an object literal')\n return null\n }\n\n // Extract values\n const contentSystemIdProp = initializer.getProperty('contentSystemId')\n const useContentSystemProp = initializer.getProperty('useContentSystem')\n\n if (!contentSystemIdProp) {\n log.debug('Missing required figma property: contentSystemId')\n return null\n }\n\n // Extract contentSystemId - support both literal strings and env var references\n let contentSystemId: string | undefined\n if (Node.isPropertyAssignment(contentSystemIdProp)) {\n const initializer = contentSystemIdProp.getInitializer()\n const text = initializer?.getText() || ''\n\n // Support both patterns:\n // 1. Literal string: 'cms_abc123' or \"cms_abc123\"\n // 2. Environment variable: process.env.FIGMA_CONTENT_SYSTEM_ID\n if (text.includes('process.env.FIGMA_CONTENT_SYSTEM_ID')) {\n // For env var reference, return a marker that indicates it's from env\n // The actual value will be read at runtime\n contentSystemId = 'process.env.FIGMA_CONTENT_SYSTEM_ID'\n } else {\n // Remove quotes for literal strings\n contentSystemId = text.replace(/['\"]/g, '')\n }\n }\n\n const useContentSystem = Node.isPropertyAssignment(useContentSystemProp)\n ? useContentSystemProp.getInitializer()?.getText() === 'true'\n : undefined // Optional: undefined if not specified\n\n if (!contentSystemId) {\n log.debug('Could not extract contentSystemId value')\n return null\n }\n\n return {\n contentSystemId,\n useContentSystem,\n }\n}\n"],"names":["Node","SyntaxKind","log","detectRequiredChanges","sourceFile","result","figmaObjectExists","hasAlias","hasOtherPayloadImports","needsImportChange","imports","getImportDeclarations","payloadImport","find","imp","getModuleSpecifierValue","debug","hasBuildConfig","moduleSpecifier","namedImports","getNamedImports","expectedFunctionName","buildConfigImport","ni","getName","aliasNode","getAliasNode","buildConfigName","getText","length","exportAssignment","getFirstDescendantByKind","ExportAssignment","buildConfigCall","callExpressions","getDescendantsOfKind","CallExpression","ce","expr","getExpression","configArg","getArguments","isObjectLiteralExpression","dbProperty","getProperty","dbValue","getChildrenOfKind","adapterName","adapterImport","some","adapter","importSource","secretProperty","editorProperty","editorValue","editorName","editorImport","args","isDefault","figmaProperty","removeAllComments","ranges","collectComments","node","getLeadingCommentRanges","forEach","range","push","getPos","getEnd","getTrailingCommentRanges","getChildren","uniqueRanges","Array","from","Set","map","r","JSON","stringify","parse","sort","a","b","pos","end","removeText","applyModifications","detection","changes","modified","hadComments","remove","addImportDeclaration","setName","identifiers","Identifier","identifier","replaceWithText","setModuleSpecifier","currentImports","dbImport","addFigmaProperty","config","text","endsWith","existingFigmaProperty","figmaObj","useContentSystem","addPropertyAssignment","name","initializer","contentSystemId","readFigmaConfig","isPropertyAssignment","getInitializer","contentSystemIdProp","useContentSystemProp","includes","replace","undefined"],"mappings":"AAEA,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;IACT;IAEA,sBAAsB;IACtB,MAAM2C,gBAAgBnB,UAAUI,WAAW,CAAC;IAC5C,IAAI,CAACe,iBAAiB,CAAC3D,KAAKkH,oBAAoB,CAACvD,gBAAgB;QAC/DzD,IAAIc,KAAK,CAAC;QACV,OAAO;IACT;IAEA,qCAAqC;IACrC,MAAM+F,cAAcpD,cAAcwD,cAAc;IAChD,IAAI,CAACJ,eAAe,CAAC/G,KAAK0C,yBAAyB,CAACqE,cAAc;QAChE7G,IAAIc,KAAK,CAAC;QACV,OAAO;IACT;IAEA,iBAAiB;IACjB,MAAMoG,sBAAsBL,YAAYnE,WAAW,CAAC;IACpD,MAAMyE,uBAAuBN,YAAYnE,WAAW,CAAC;IAErD,IAAI,CAACwE,qBAAqB;QACxBlH,IAAIc,KAAK,CAAC;QACV,OAAO;IACT;IAEA,gFAAgF;IAChF,IAAIgG;IACJ,IAAIhH,KAAKkH,oBAAoB,CAACE,sBAAsB;QAClD,MAAML,cAAcK,oBAAoBD,cAAc;QACtD,MAAMX,OAAOO,aAAanF,aAAa;QAEvC,yBAAyB;QACzB,kDAAkD;QAClD,+DAA+D;QAC/D,IAAI4E,KAAKc,QAAQ,CAAC,wCAAwC;YACxD,sEAAsE;YACtE,2CAA2C;YAC3CN,kBAAkB;QACpB,OAAO;YACL,oCAAoC;YACpCA,kBAAkBR,KAAKe,OAAO,CAAC,SAAS;QAC1C;IACF;IAEA,MAAMX,mBAAmB5G,KAAKkH,oBAAoB,CAACG,wBAC/CA,qBAAqBF,cAAc,IAAIvF,cAAc,SACrD4F,UAAU,uCAAuC;;IAErD,IAAI,CAACR,iBAAiB;QACpB9G,IAAIc,KAAK,CAAC;QACV,OAAO;IACT;IAEA,OAAO;QACLgG;QACAJ;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/utils/payload-config-ast.ts"],"sourcesContent":["import type { SourceFile } from 'ts-morph'\n\nimport { Node, SyntaxKind } from 'ts-morph'\n\nimport * as log from './log.js'\n\n/**\n * Result of detecting what changes are needed in a payload config file\n */\nexport type DetectionResult = {\n /** Database adapter configuration if present */\n dbProperty?: {\n /** Name of the adapter function (e.g., 'mongooseAdapter', 'postgresAdapter') */\n adapter: string\n /** NPM package the adapter is imported from (e.g., '@payloadcms/db-mongodb') */\n importSource: string\n }\n /** Editor configuration if present */\n editorProperty?: {\n /** NPM package the editor is imported from (e.g., '@payloadcms/richtext-lexical') */\n importSource: string\n /** Whether this is a default editor with no custom configuration */\n isDefault: boolean\n }\n /** Whether the config already has a `figma` property */\n figmaObjectExists: boolean\n /** Whether buildConfig/buildFigmaConfig uses an import alias (e.g., 'buildConfig as createConfig') */\n hasAlias: boolean\n /** Whether a buildConfig or buildFigmaConfig call was found (undefined if not checked) */\n hasBuildConfig?: boolean\n /** Whether there are other imports from 'payload' besides buildConfig (e.g., types) */\n hasOtherPayloadImports: boolean\n /** Whether the import needs to be changed from 'payload' to '@payloadcms/figma' */\n needsImportChange: boolean\n /** Whether a `secret` property exists in the config */\n secretProperty?: boolean\n /** Sharp configuration if present */\n sharpProperty?: {\n /** NPM package sharp is imported from (always 'sharp') */\n importSource: string\n }\n}\n\n/**\n * Detect what changes are needed in the payload config file\n */\nexport function detectRequiredChanges(sourceFile: SourceFile): DetectionResult {\n const result: DetectionResult = {\n figmaObjectExists: false,\n hasAlias: false,\n hasOtherPayloadImports: false,\n needsImportChange: false,\n }\n\n // Find buildConfig import\n const imports = sourceFile.getImportDeclarations()\n const payloadImport = imports.find(\n (imp) =>\n imp.getModuleSpecifierValue() === 'payload' ||\n imp.getModuleSpecifierValue() === '@payloadcms/figma',\n )\n\n if (!payloadImport) {\n log.debug('No payload or @payloadcms/figma import found')\n result.hasBuildConfig = false\n return result\n }\n\n log.debug(`Found import from: ${payloadImport.getModuleSpecifierValue()}`)\n\n const moduleSpecifier = payloadImport.getModuleSpecifierValue()\n const namedImports = payloadImport.getNamedImports()\n\n // Determine which function name to look for based on the import source\n // - From 'payload': look for buildConfig (needs migration)\n // - From '@payloadcms/figma': look for buildFigmaConfig (already migrated)\n const expectedFunctionName = moduleSpecifier === 'payload' ? 'buildConfig' : 'buildFigmaConfig'\n\n const buildConfigImport = namedImports.find((ni) => ni.getName() === expectedFunctionName)\n\n if (!buildConfigImport) {\n result.hasBuildConfig = false\n return result\n }\n\n // Check for alias and get the actual name used in code\n const aliasNode = buildConfigImport.getAliasNode()\n const buildConfigName = aliasNode ? aliasNode.getText() : expectedFunctionName\n if (aliasNode) {\n result.hasAlias = true\n }\n\n // Check if import needs change\n if (moduleSpecifier === 'payload') {\n result.needsImportChange = true\n\n // Check if there are other imports from payload\n if (namedImports.length > 1) {\n result.hasOtherPayloadImports = true\n }\n }\n\n // Find buildConfig call in export default\n // First try to find export default with the buildConfig call\n const exportAssignment = sourceFile.getFirstDescendantByKind(SyntaxKind.ExportAssignment)\n let buildConfigCall = null\n\n if (exportAssignment) {\n // Look for buildConfig call in the export default\n const callExpressions = exportAssignment.getDescendantsOfKind(SyntaxKind.CallExpression)\n buildConfigCall = callExpressions.find((ce) => {\n const expr = ce.getExpression()\n return expr.getText() === buildConfigName\n })\n }\n\n // If not found in export default, search all call expressions\n if (!buildConfigCall) {\n const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)\n buildConfigCall = callExpressions.find((ce) => {\n const expr = ce.getExpression()\n return expr.getText() === buildConfigName\n })\n }\n\n if (!buildConfigCall) {\n result.hasBuildConfig = false\n return result\n }\n\n // Get config object\n const configArg = buildConfigCall.getArguments()[0]\n if (!configArg || !Node.isObjectLiteralExpression(configArg)) {\n return result\n }\n\n // Check for db property\n const dbProperty = configArg.getProperty('db')\n if (dbProperty) {\n const dbValue = dbProperty.getChildrenOfKind(SyntaxKind.CallExpression)[0]\n if (dbValue) {\n const adapterName = dbValue.getExpression().getText()\n\n // Find the import source for this adapter\n const adapterImport = imports.find((imp) =>\n imp.getNamedImports().some((ni) => ni.getName() === adapterName),\n )\n\n if (adapterImport) {\n result.dbProperty = {\n adapter: adapterName,\n importSource: adapterImport.getModuleSpecifierValue(),\n }\n }\n }\n }\n\n // Check for secret property\n const secretProperty = configArg.getProperty('secret')\n if (secretProperty) {\n result.secretProperty = true\n }\n\n // Check for editor property\n const editorProperty = configArg.getProperty('editor')\n if (editorProperty) {\n const editorValue = editorProperty.getChildrenOfKind(SyntaxKind.CallExpression)[0]\n if (editorValue) {\n const editorName = editorValue.getExpression().getText()\n\n // Find the import source\n const editorImport = imports.find((imp) =>\n imp.getNamedImports().some((ni) => ni.getName() === editorName),\n )\n\n if (editorImport && editorName === 'lexicalEditor') {\n // Check if it has arguments\n const args = editorValue.getArguments()\n const isDefault = args.length === 0\n\n result.editorProperty = {\n importSource: editorImport.getModuleSpecifierValue(),\n isDefault,\n }\n }\n }\n }\n\n // Check for sharp property\n const sharpProperty = configArg.getProperty('sharp')\n if (sharpProperty) {\n // Find the import source for sharp\n const sharpImport = imports.find(\n (imp) =>\n imp.getModuleSpecifierValue() === 'sharp' ||\n imp.getNamedImports().some((ni) => ni.getName() === 'sharp'),\n )\n\n result.sharpProperty = {\n importSource: sharpImport?.getModuleSpecifierValue() || 'sharp',\n }\n }\n\n // Check for figma property\n const figmaProperty = configArg.getProperty('figma')\n if (figmaProperty) {\n result.figmaObjectExists = true\n }\n\n return result\n}\n\nexport type ASTModificationResult = {\n changes: string[]\n modified: boolean\n}\n\n/**\n * Remove all comments\n * @returns true if any comments were removed\n */\nfunction removeAllComments(sourceFile: SourceFile): boolean {\n const ranges: Array<[number, number]> = []\n\n // Recursively collect comments from node and ALL children (including tokens)\n const collectComments = (node: Node) => {\n node.getLeadingCommentRanges().forEach((range) => {\n ranges.push([range.getPos(), range.getEnd()])\n })\n node.getTrailingCommentRanges().forEach((range) => {\n ranges.push([range.getPos(), range.getEnd()])\n })\n\n // Process ALL children including token nodes (commas, braces, etc.)\n node.getChildren().forEach(collectComments)\n }\n\n collectComments(sourceFile)\n\n if (ranges.length === 0) {\n return false\n }\n\n // Remove duplicates and sort in reverse order to avoid position shifts\n const uniqueRanges = Array.from(new Set(ranges.map((r) => JSON.stringify(r)))).map(\n (r) => JSON.parse(r) as [number, number],\n )\n uniqueRanges.sort((a, b) => b[0] - a[0])\n\n // Remove each comment range\n for (const [pos, end] of uniqueRanges) {\n sourceFile.removeText(pos, end)\n }\n\n return true\n}\n\n/**\n * Apply modifications to the source file based on detection result\n * Modifies the AST in memory - caller must call sourceFile.save()\n */\nexport function applyModifications(\n sourceFile: SourceFile,\n detection: DetectionResult,\n): ASTModificationResult {\n const changes: string[] = []\n let modified = false\n\n if (detection.hasBuildConfig === false || detection.hasAlias) {\n log.debug(\n `Skipping modifications: hasBuildConfig=${detection.hasBuildConfig}, hasAlias=${detection.hasAlias}`,\n )\n return { changes: [], modified: false }\n }\n\n // 1. Remove all comments FIRST (before AST modifications that might shift positions)\n const hadComments = removeAllComments(sourceFile)\n if (hadComments) {\n changes.push('Removed comments')\n modified = true\n }\n\n // Find the import declarations\n const imports = sourceFile.getImportDeclarations()\n const payloadImport = imports.find((imp) => imp.getModuleSpecifierValue() === 'payload')\n\n // Get the buildConfig name (could be aliased)\n let buildConfigName = 'buildConfig'\n if (payloadImport) {\n const buildConfigImport = payloadImport\n .getNamedImports()\n .find((ni) => ni.getName() === 'buildConfig')\n if (buildConfigImport) {\n const aliasNode = buildConfigImport.getAliasNode()\n buildConfigName = aliasNode ? aliasNode.getText() : 'buildConfig'\n }\n }\n\n // Find buildConfig call in export default (prefer export default)\n const exportAssignment = sourceFile.getFirstDescendantByKind(SyntaxKind.ExportAssignment)\n let buildConfigCall = null\n\n if (exportAssignment) {\n const callExpressions = exportAssignment.getDescendantsOfKind(SyntaxKind.CallExpression)\n buildConfigCall = callExpressions.find((ce) => {\n const expr = ce.getExpression()\n return expr.getText() === buildConfigName\n })\n }\n\n // If not found in export default, search all call expressions\n if (!buildConfigCall) {\n const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)\n buildConfigCall = callExpressions.find((ce) => {\n const expr = ce.getExpression()\n return expr.getText() === buildConfigName\n })\n }\n\n if (!buildConfigCall) {\n return { changes: [], modified: false }\n }\n\n const configArg = buildConfigCall.getArguments()[0]\n if (!configArg || !Node.isObjectLiteralExpression(configArg)) {\n return { changes: [], modified: false }\n }\n\n // 1. Remove db property\n if (detection.dbProperty) {\n const dbProperty = configArg.getProperty('db')\n if (dbProperty) {\n dbProperty.remove()\n changes.push('Removed db property')\n modified = true\n }\n }\n\n // 2. Remove secret property\n if (detection.secretProperty) {\n const secretProperty = configArg.getProperty('secret')\n if (secretProperty) {\n secretProperty.remove()\n changes.push('Removed secret property')\n modified = true\n }\n }\n\n // 3. Remove editor if default\n if (detection.editorProperty?.isDefault) {\n const editorProperty = configArg.getProperty('editor')\n if (editorProperty) {\n editorProperty.remove()\n changes.push('Removed default editor property')\n modified = true\n }\n }\n\n // 4. Remove sharp property\n if (detection.sharpProperty) {\n const sharpProperty = configArg.getProperty('sharp')\n if (sharpProperty) {\n sharpProperty.remove()\n changes.push('Removed sharp property')\n modified = true\n }\n }\n\n // 5. Update buildConfig import\n if (detection.needsImportChange) {\n if (payloadImport) {\n if (detection.hasOtherPayloadImports) {\n // Remove buildConfig from payload import, add new figma import\n const namedImports = payloadImport.getNamedImports()\n const buildConfigImport = namedImports.find((ni) => ni.getName() === 'buildConfig')\n if (buildConfigImport) {\n buildConfigImport.remove()\n\n // If payload import is now empty, remove it\n if (payloadImport.getNamedImports().length === 0) {\n payloadImport.remove()\n }\n }\n\n // Add new import at the top\n sourceFile.addImportDeclaration({\n moduleSpecifier: '@payloadcms/figma',\n namedImports: ['buildFigmaConfig'],\n })\n\n changes.push('Split buildConfig import to @payloadcms/figma')\n } else {\n // Replace entire import: change module specifier and rename all references\n const buildConfigImport = payloadImport\n .getNamedImports()\n .find((ni) => ni.getName() === 'buildConfig')\n if (buildConfigImport) {\n // Change the import name\n buildConfigImport.setName('buildFigmaConfig')\n\n // Find and rename all usages of 'buildConfig' in the file\n const identifiers = sourceFile.getDescendantsOfKind(SyntaxKind.Identifier)\n identifiers.forEach((identifier) => {\n if (identifier.getText() === 'buildConfig') {\n identifier.replaceWithText('buildFigmaConfig')\n }\n })\n }\n payloadImport.setModuleSpecifier('@payloadcms/figma')\n changes.push('Changed buildConfig import to @payloadcms/figma')\n }\n modified = true\n }\n }\n\n // 6. Remove orphaned imports\n // Re-fetch imports after each removal to avoid stale references\n if (detection.dbProperty) {\n const currentImports = sourceFile.getImportDeclarations()\n const dbImport = currentImports.find(\n (imp) => imp.getModuleSpecifierValue() === detection.dbProperty?.importSource,\n )\n if (dbImport) {\n dbImport.remove()\n changes.push(`Removed ${detection.dbProperty.adapter} import`)\n modified = true\n }\n }\n\n if (detection.editorProperty?.isDefault) {\n const currentImports = sourceFile.getImportDeclarations()\n const editorImport = currentImports.find(\n (imp) => imp.getModuleSpecifierValue() === detection.editorProperty?.importSource,\n )\n if (editorImport) {\n editorImport.remove()\n changes.push('Removed lexicalEditor import')\n modified = true\n }\n }\n\n if (detection.sharpProperty) {\n const currentImports = sourceFile.getImportDeclarations()\n const sharpImport = currentImports.find((imp) => imp.getModuleSpecifierValue() === 'sharp')\n if (sharpImport) {\n sharpImport.remove()\n changes.push('Removed sharp import')\n modified = true\n }\n }\n\n return { changes, modified }\n}\n\nexport type FigmaPropertyConfig = {\n contentSystemId: string\n useContentSystem?: boolean\n}\n\n/**\n * Add figma property to buildConfig if it doesn't exist\n * Modifies the AST in memory - caller must call sourceFile.save()\n */\nexport function addFigmaProperty(\n sourceFile: SourceFile,\n config: FigmaPropertyConfig,\n): ASTModificationResult {\n const changes: string[] = []\n let modified = false\n\n // Find buildFigmaConfig call (this function is only used with Figma configs)\n const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)\n const buildConfigCall = callExpressions.find((ce) => {\n const expr = ce.getExpression()\n const text = expr.getText()\n return text === 'buildFigmaConfig' || text.endsWith('.buildFigmaConfig')\n })\n\n if (!buildConfigCall) {\n log.debug('No buildFigmaConfig call found')\n return { changes: [], modified: false }\n }\n\n // Get config object argument\n const configArg = buildConfigCall.getArguments()[0]\n if (!configArg || !Node.isObjectLiteralExpression(configArg)) {\n log.debug('buildConfig argument is not an object literal')\n return { changes: [], modified: false }\n }\n\n // Check if figma property already exists\n const existingFigmaProperty = configArg.getProperty('figma')\n if (existingFigmaProperty) {\n log.debug('figma property already exists, skipping')\n return { changes: ['Skipped: figma property already exists'], modified: false }\n }\n\n // Add figma property\n // Note: useContentSystem is optional and defaults to true, so we don't generate it during init\n // contentSystemId is stored in .env file and referenced via process.env with non-null assertion\n const figmaObj =\n config.useContentSystem === false\n ? `{\n contentSystemId: process.env.FIGMA_CONTENT_SYSTEM_ID!,\n useContentSystem: false,\n }`\n : `{\n contentSystemId: process.env.FIGMA_CONTENT_SYSTEM_ID!,\n }`\n\n configArg.addPropertyAssignment({\n name: 'figma',\n initializer: figmaObj,\n })\n\n changes.push(`Added figma property (contentSystemId: ${config.contentSystemId})`)\n modified = true\n\n return { changes, modified }\n}\n\n/**\n * Read figma configuration from payload.config.ts\n * Returns the figma object if it exists, null otherwise\n */\nexport function readFigmaConfig(sourceFile: SourceFile): FigmaPropertyConfig | null {\n // Find buildFigmaConfig call (this function is only used with Figma configs)\n const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)\n const buildConfigCall = callExpressions.find((ce) => {\n const expr = ce.getExpression()\n const text = expr.getText()\n return text === 'buildFigmaConfig' || text.endsWith('.buildFigmaConfig')\n })\n\n if (!buildConfigCall) {\n log.debug('No buildFigmaConfig call found')\n return null\n }\n\n // Get config object argument\n const configArg = buildConfigCall.getArguments()[0]\n if (!configArg || !Node.isObjectLiteralExpression(configArg)) {\n log.debug('buildConfig argument is not an object literal')\n return null\n }\n\n // Find figma property\n const figmaProperty = configArg.getProperty('figma')\n if (!figmaProperty || !Node.isPropertyAssignment(figmaProperty)) {\n log.debug('No figma property found in buildConfig')\n return null\n }\n\n // Get initializer (the object value)\n const initializer = figmaProperty.getInitializer()\n if (!initializer || !Node.isObjectLiteralExpression(initializer)) {\n log.debug('figma property is not an object literal')\n return null\n }\n\n // Extract values\n const contentSystemIdProp = initializer.getProperty('contentSystemId')\n const useContentSystemProp = initializer.getProperty('useContentSystem')\n\n if (!contentSystemIdProp) {\n log.debug('Missing required figma property: contentSystemId')\n return null\n }\n\n // Extract contentSystemId - support both literal strings and env var references\n let contentSystemId: string | undefined\n if (Node.isPropertyAssignment(contentSystemIdProp)) {\n const initializer = contentSystemIdProp.getInitializer()\n const text = initializer?.getText() || ''\n\n // Support both patterns:\n // 1. Literal string: 'cms_abc123' or \"cms_abc123\"\n // 2. Environment variable: process.env.FIGMA_CONTENT_SYSTEM_ID\n if (text.includes('process.env.FIGMA_CONTENT_SYSTEM_ID')) {\n // For env var reference, return a marker that indicates it's from env\n // The actual value will be read at runtime\n contentSystemId = 'process.env.FIGMA_CONTENT_SYSTEM_ID'\n } else {\n // Remove quotes for literal strings\n contentSystemId = text.replace(/['\"]/g, '')\n }\n }\n\n const useContentSystem = Node.isPropertyAssignment(useContentSystemProp)\n ? useContentSystemProp.getInitializer()?.getText() === 'true'\n : undefined // Optional: undefined if not specified\n\n if (!contentSystemId) {\n log.debug('Could not extract contentSystemId value')\n return null\n }\n\n return {\n contentSystemId,\n useContentSystem,\n }\n}\n"],"names":["Node","SyntaxKind","log","detectRequiredChanges","sourceFile","result","figmaObjectExists","hasAlias","hasOtherPayloadImports","needsImportChange","imports","getImportDeclarations","payloadImport","find","imp","getModuleSpecifierValue","debug","hasBuildConfig","moduleSpecifier","namedImports","getNamedImports","expectedFunctionName","buildConfigImport","ni","getName","aliasNode","getAliasNode","buildConfigName","getText","length","exportAssignment","getFirstDescendantByKind","ExportAssignment","buildConfigCall","callExpressions","getDescendantsOfKind","CallExpression","ce","expr","getExpression","configArg","getArguments","isObjectLiteralExpression","dbProperty","getProperty","dbValue","getChildrenOfKind","adapterName","adapterImport","some","adapter","importSource","secretProperty","editorProperty","editorValue","editorName","editorImport","args","isDefault","sharpProperty","sharpImport","figmaProperty","removeAllComments","ranges","collectComments","node","getLeadingCommentRanges","forEach","range","push","getPos","getEnd","getTrailingCommentRanges","getChildren","uniqueRanges","Array","from","Set","map","r","JSON","stringify","parse","sort","a","b","pos","end","removeText","applyModifications","detection","changes","modified","hadComments","remove","addImportDeclaration","setName","identifiers","Identifier","identifier","replaceWithText","setModuleSpecifier","currentImports","dbImport","addFigmaProperty","config","text","endsWith","existingFigmaProperty","figmaObj","useContentSystem","addPropertyAssignment","name","initializer","contentSystemId","readFigmaConfig","isPropertyAssignment","getInitializer","contentSystemIdProp","useContentSystemProp","includes","replace","undefined"],"mappings":"AAEA,SAASA,IAAI,EAAEC,UAAU,QAAQ,WAAU;AAE3C,YAAYC,SAAS,WAAU;AAuC/B;;CAEC,GACD,OAAO,SAASC,sBAAsBC,UAAsB;IAC1D,MAAMC,SAA0B;QAC9BC,mBAAmB;QACnBC,UAAU;QACVC,wBAAwB;QACxBC,mBAAmB;IACrB;IAEA,0BAA0B;IAC1B,MAAMC,UAAUN,WAAWO,qBAAqB;IAChD,MAAMC,gBAAgBF,QAAQG,IAAI,CAChC,CAACC,MACCA,IAAIC,uBAAuB,OAAO,aAClCD,IAAIC,uBAAuB,OAAO;IAGtC,IAAI,CAACH,eAAe;QAClBV,IAAIc,KAAK,CAAC;QACVX,OAAOY,cAAc,GAAG;QACxB,OAAOZ;IACT;IAEAH,IAAIc,KAAK,CAAC,CAAC,mBAAmB,EAAEJ,cAAcG,uBAAuB,IAAI;IAEzE,MAAMG,kBAAkBN,cAAcG,uBAAuB;IAC7D,MAAMI,eAAeP,cAAcQ,eAAe;IAElD,uEAAuE;IACvE,2DAA2D;IAC3D,2EAA2E;IAC3E,MAAMC,uBAAuBH,oBAAoB,YAAY,gBAAgB;IAE7E,MAAMI,oBAAoBH,aAAaN,IAAI,CAAC,CAACU,KAAOA,GAAGC,OAAO,OAAOH;IAErE,IAAI,CAACC,mBAAmB;QACtBjB,OAAOY,cAAc,GAAG;QACxB,OAAOZ;IACT;IAEA,uDAAu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AAKoH,oBAAoB,CAACvD,gBAAgB;QAC/D3D,IAAIc,KAAK,CAAC;QACV,OAAO;IACT;IAEA,qCAAqC;IACrC,MAAMiG,cAAcpD,cAAcwD,cAAc;IAChD,IAAI,CAACJ,eAAe,CAACjH,KAAK0C,yBAAyB,CAACuE,cAAc;QAChE/G,IAAIc,KAAK,CAAC;QACV,OAAO;IACT;IAEA,iBAAiB;IACjB,MAAMsG,sBAAsBL,YAAYrE,WAAW,CAAC;IACpD,MAAM2E,uBAAuBN,YAAYrE,WAAW,CAAC;IAErD,IAAI,CAAC0E,qBAAqB;QACxBpH,IAAIc,KAAK,CAAC;QACV,OAAO;IACT;IAEA,gFAAgF;IAChF,IAAIkG;IACJ,IAAIlH,KAAKoH,oBAAoB,CAACE,sBAAsB;QAClD,MAAML,cAAcK,oBAAoBD,cAAc;QACtD,MAAMX,OAAOO,aAAarF,aAAa;QAEvC,yBAAyB;QACzB,kDAAkD;QAClD,+DAA+D;QAC/D,IAAI8E,KAAKc,QAAQ,CAAC,wCAAwC;YACxD,sEAAsE;YACtE,2CAA2C;YAC3CN,kBAAkB;QACpB,OAAO;YACL,oCAAoC;YACpCA,kBAAkBR,KAAKe,OAAO,CAAC,SAAS;QAC1C;IACF;IAEA,MAAMX,mBAAmB9G,KAAKoH,oBAAoB,CAACG,wBAC/CA,qBAAqBF,cAAc,IAAIzF,cAAc,SACrD8F,UAAU,uCAAuC;;IAErD,IAAI,CAACR,iBAAiB;QACpBhH,IAAIc,KAAK,CAAC;QACV,OAAO;IACT;IAEA,OAAO;QACLkG;QACAJ;IACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"payload-config-modifier.d.ts","sourceRoot":"","sources":["../../src/utils/payload-config-modifier.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AAI1D,OAAO,EAIL,KAAK,mBAAmB,EACzB,MAAM,yBAAyB,CAAA;AAKhC,MAAM,MAAM,kBAAkB,GA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