{"version":3,"file":"content-structure.mjs","sources":["../../../server/src/services/content-structure.ts"],"sourcesContent":["import { errors } from '@strapi/utils';\n\nimport type { Core, Modules } from '@strapi/types';\n\nconst { ApplicationError } = errors;\n\ntype ContentStructureGroup = Modules.ContentStructure.ContentStructureGroup;\ntype ContentStructureFile = Modules.ContentStructure.ContentStructureFile;\ntype SectionKey = Modules.ContentStructure.ContentStructureSectionKey;\ntype ContentTypeKind = 'collectionType' | 'singleType';\n\nconst SECTION_KEYS: SectionKey[] = ['collectionTypes', 'singleTypes'];\n\nconst expectedKindFor = (sectionKey: SectionKey): ContentTypeKind => {\n  return sectionKey === 'collectionTypes' ? 'collectionType' : 'singleType';\n};\n\n/**\n * A mirror of the subset of the core `content-structure` service (strapi.get('content-structure'))\n * that this service consumes.\n */\nexport interface CoreContentStructureService {\n  getCleanedFile(): Promise<ContentStructureFile | null>;\n  write(structure: ContentStructureFile): Promise<void>;\n}\n\n/**\n * This service handles the CTB orchestration of folder-group WRITES. It handles:\n * - Context-aware validation that requires the content-type registry\n * - Context-aware pruning of references invalidated by CTB transaction.\n * - Persistence to filesystem via the core content-structure service.\n * It assumes that non-context-aware validation has already been performed.\n */\nexport interface ContentTypeBuilderContentStructureService {\n  /**\n   * Validates all references to content types in the provided content structure.\n   * Throws an ApplicationError naming every offending uid + rule.\n   */\n  validateContentTypeUidReferences(\n    structure: unknown,\n    contentTypeUids: Map<string, ContentTypeKind>\n  ): void;\n\n  validateFromUpdate(input: {\n    incomingStructure?: unknown;\n    upsertedUids: Map<string, ContentTypeKind>;\n    deletedUids: Set<string>;\n  }): void;\n\n  commitFromUpdate(input: {\n    incomingStructure?: unknown;\n    deletedUids: Set<string>;\n  }): Promise<boolean>;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n};\n\n/**\n * Formats a validated ContentStructureFile into a complete `groups.json` file.\n */\nconst formatContentStructureObjectAsFile = (structure: unknown): ContentStructureFile => {\n  const sections = isRecord(structure) && isRecord(structure.sections) ? structure.sections : {};\n\n  // Supplies all record groups with expected fields, so that the reference validator\n  // can access `children`/`id` unconditionally.\n  const coerceGroup = (raw: Record<string, unknown>): ContentStructureGroup => {\n    const childrenArray = (\n      Array.isArray(raw.children) ? raw.children : []\n    ) as Modules.ContentStructure.ContentStructureChild[];\n\n    return {\n      parent: typeof raw.parent === 'string' ? raw.parent : null,\n      name: typeof raw.name === 'string' ? raw.name : '',\n      id: typeof raw.id === 'string' ? raw.id : '',\n      children: childrenArray,\n    };\n  };\n\n  const coerceSection = (key: SectionKey): Modules.ContentStructure.ContentStructureSection => {\n    const raw = (sections as Record<string, unknown>)[key];\n    const groups = isRecord(raw) && Array.isArray(raw.groups) ? raw.groups : [];\n\n    return { groups: groups.filter(isRecord).map(coerceGroup) };\n  };\n\n  return {\n    version: 1,\n    sections: {\n      collectionTypes: coerceSection('collectionTypes'),\n      singleTypes: coerceSection('singleTypes'),\n    },\n  };\n};\n\nconst cloneFile = (file: ContentStructureFile): ContentStructureFile => ({\n  version: 1,\n  sections: {\n    collectionTypes: {\n      groups: file.sections.collectionTypes.groups.map((group) => ({\n        ...group,\n        children: [...group.children],\n      })),\n    },\n    singleTypes: {\n      groups: file.sections.singleTypes.groups.map((group) => ({\n        ...group,\n        children: [...group.children],\n      })),\n    },\n  },\n});\n\nexport function createContentStructureService(\n  strapi: Core.Strapi\n): ContentTypeBuilderContentStructureService {\n  const contentStructureService: CoreContentStructureService = strapi.get('content-structure');\n\n  const warn = (message: string) => {\n    strapi.log.warn(`[content-structure] ${message}`);\n  };\n\n  /**\n   * Builds an effective set of content type uids and their kind by resolving the pre-transaction content type registry with the list of upserted and deleted uids.\n   */\n  const buildEffectiveUidKindSet = (\n    upsertedUids: Map<string, ContentTypeKind>,\n    deletedUids: Set<string>\n  ): Map<string, ContentTypeKind> => {\n    const effective = new Map<string, ContentTypeKind>();\n\n    for (const [uid, contentType] of Object.entries(strapi.contentTypes)) {\n      effective.set(uid, contentType.kind === 'singleType' ? 'singleType' : 'collectionType');\n    }\n\n    for (const uid of deletedUids) {\n      effective.delete(uid);\n    }\n\n    for (const [uid, kind] of upsertedUids) {\n      effective.set(uid, kind);\n    }\n\n    return effective;\n  };\n\n  /**\n   * Remove references to content types that have been deleted\n   */\n  const pruneStructure = (\n    file: ContentStructureFile,\n    deletedUids: Set<string>\n  ): ContentStructureFile => {\n    const cloned = cloneFile(file);\n\n    for (const sectionKey of SECTION_KEYS) {\n      for (const group of cloned.sections[sectionKey].groups) {\n        group.children = group.children.filter((child) => {\n          if (child.type !== 'contentType') {\n            return true;\n          }\n\n          const { uid } = child;\n\n          if (deletedUids.has(uid)) {\n            warn(`Pruned deleted content type \"${uid}\" from group \"${group.id}\"`);\n            return false;\n          }\n\n          return true;\n        });\n      }\n    }\n\n    return cloned;\n  };\n\n  const validateContentTypeUidReferences = (\n    structure: unknown,\n    contentTypeKinds: Map<string, ContentTypeKind>\n  ): void => {\n    const file = formatContentStructureObjectAsFile(structure);\n    const violations: string[] = [];\n\n    for (const sectionKey of SECTION_KEYS) {\n      const expectedKind = expectedKindFor(sectionKey);\n\n      for (const group of file.sections[sectionKey].groups) {\n        for (const child of group.children) {\n          if (child.type !== 'contentType') {\n            continue;\n          }\n\n          const { uid } = child;\n\n          // Referenced content type exists (in the effective set).\n          if (!contentTypeKinds.has(uid)) {\n            violations.push(\n              `Content type \"${uid}\" in group \"${group.id}\" does not exist in section \"${sectionKey}\"`\n            );\n            continue;\n          }\n\n          // Kind matches section.\n          if (contentTypeKinds.get(uid) !== expectedKind) {\n            violations.push(\n              `Content type \"${uid}\" in group \"${group.id}\" is a ${contentTypeKinds.get(\n                uid\n              )} and cannot be placed in section \"${sectionKey}\"`\n            );\n          }\n        }\n      }\n    }\n\n    if (violations.length > 0) {\n      throw new ApplicationError(`Invalid content structure:\\n- ${violations.join('\\n- ')}`, {\n        errors: violations.map((message) => ({\n          name: 'ApplicationError',\n          path: [] as string[],\n          message,\n        })),\n      });\n    }\n  };\n\n  const validateFromUpdate = ({\n    incomingStructure,\n    upsertedUids,\n    deletedUids,\n  }: {\n    incomingStructure?: unknown;\n    upsertedUids: Map<string, ContentTypeKind>;\n    deletedUids: Set<string>;\n  }): void => {\n    if (incomingStructure === undefined || incomingStructure === null) {\n      return;\n    }\n\n    const effectiveKinds = buildEffectiveUidKindSet(upsertedUids, deletedUids);\n    const pruned = pruneStructure(\n      formatContentStructureObjectAsFile(incomingStructure),\n      deletedUids\n    );\n\n    validateContentTypeUidReferences(pruned, effectiveKinds);\n  };\n\n  const commitFromUpdate = async ({\n    incomingStructure,\n    deletedUids,\n  }: {\n    incomingStructure?: unknown;\n    deletedUids: Set<string>;\n  }): Promise<boolean> => {\n    if (incomingStructure !== undefined && incomingStructure !== null) {\n      const pruned = pruneStructure(\n        formatContentStructureObjectAsFile(incomingStructure),\n        deletedUids\n      );\n\n      await contentStructureService.write(pruned);\n      return true;\n    }\n\n    if (deletedUids.size > 0) {\n      const current = await contentStructureService.getCleanedFile();\n\n      if (!current) {\n        return false;\n      }\n\n      const pruned = pruneStructure(current, deletedUids);\n\n      await contentStructureService.write(pruned);\n      return true;\n    }\n\n    return false;\n  };\n\n  return {\n    validateContentTypeUidReferences,\n    validateFromUpdate,\n    commitFromUpdate,\n  };\n}\n"],"names":["ApplicationError","errors","SECTION_KEYS","expectedKindFor","sectionKey","isRecord","value","Array","isArray","formatContentStructureObjectAsFile","structure","sections","coerceGroup","raw","childrenArray","children","parent","name","id","coerceSection","key","groups","filter","map","version","collectionTypes","singleTypes","cloneFile","file","group","createContentStructureService","strapi","contentStructureService","get","warn","message","log","buildEffectiveUidKindSet","upsertedUids","deletedUids","effective","Map","uid","contentType","Object","entries","contentTypes","set","kind","delete","pruneStructure","cloned","child","type","has","validateContentTypeUidReferences","contentTypeKinds","violations","expectedKind","push","length","join","path","validateFromUpdate","incomingStructure","undefined","effectiveKinds","pruned","commitFromUpdate","write","size","current","getCleanedFile"],"mappings":";;AAIA,MAAM,E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