import{ENTITY_SCHEMA_EXCLUDED_FOLDERS as c,CATALOG_ENTITIES_FILES_REGEX as n}from"../../../../constants/plugins/catalog-entities.js";import{parseAndValidateEntity as h}from"../../entities/validate-entity.js";import{promiseMapLimit as l}from"../../../../utils/async.js";import{extractEntitiesContent as o}from"../../entities/extract-entities-content.js";import{sha1 as r}from"../../../../utils/crypto.js";import{HashManager as f}from"../../utils/hash-manager.js";import{FileHashStatus as E,FileType as g}from"../../../../persistence/file-hashes/types.js";import{fsChangesStore as d}from"../../../../fs/utils/async-storage.js";const m=15;class x{context;catalogEntitiesService;#t;#e;#i;#a;constructor(t){this.context=t.context,this.catalogEntitiesService=t.catalogEntitiesService,this.#t=new f({hashManagerUpdateService:t.catalogEntitiesService,fileType:g.ENTITY_DEFINITION,fileHashesService:t.fileHashesService}),this.#e=t.isDevMode,this.#i=t.isFirstPluginRun,this.#a=t.catalogConfig}async extract(){if(this.#e&&!this.#i){const e=d?.getStore()??[];await this.#r(e);return}const t=await this.context.fs.scan(n);await this.#t.markAllHashesAsOutdated(),await l(t,m,async({relativePath:e})=>{if(c.some(s=>e.includes(s)))return;const i=await o(e,this.context);if(!i)return;const a=r(JSON.stringify(i));if(await this.#t.getHash(a)){await this.#t.setHash(a,E.UP_TO_DATE);return}await this.#s(i,a,e)}),await this.#t.clearOutdatedHashesAndRelatedRecords()}#n=async t=>{await this.catalogEntitiesService.deleteEntitiesAndRelationsByFilePathInLocalDatabase(t)};#o=async t=>{if(!t.match(n))return;await this.catalogEntitiesService.deleteEntitiesAndRelationsByFilePathInLocalDatabase(t);const e=await o(t,this.context);if(!e)return;const i=r(JSON.stringify(e));await this.#s(e,i,t)};#r=async t=>{for(const e of t)switch(e.event){case"add":case"change":await this.#o(e.path);break;case"unlink":await this.#n(e.path);break}};#s=async(t,e,i)=>{for(const a of t.entities)try{const s=h(a,this.#a);await this.catalogEntitiesService.createEntityInLocalDatabase({entity:s,sourceFile:i,fileHash:e})}catch(s){this.context.logger.warn(`Error extracting entity from ${i}. ${s.message}.`)}}}export{x as FsEntitiesExtractor};
