@blitznocode/blitz-orm 0.6.4 → 0.7.0-beta

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/default.config.ts","../src/define/index.ts","../src/helpers.ts","../src/pipeline/postprocess/parseTQLMutation.ts","../src/pipeline/postprocess/fieldsOperator.ts","../src/pipeline/postprocess/buildBQLTree.ts","../src/engine/helpers.ts","../src/engine/compute.ts","../src/pipeline/preprocess/buildTQLMutation.ts","../src/pipeline/preprocess/fill.ts","../src/pipeline/preprocess/parseBQLMutation.ts","../src/pipeline/transaction/runTQLMutation.ts","../src/pipeline/transaction/helpers.ts","../src/pipeline/preprocess/buildTQLQuery.ts","../src/pipeline/preprocess/enrichBQLQuery.ts","../src/pipeline/transaction/runTQLQuery.ts","../src/pipeline/postprocess/parseTQLQuery.ts","../src/pipeline/preprocess/newPreQuery.ts","../src/pipeline/pipeline.ts"],"sourcesContent":["import { tryit } from 'radash';\nimport { TypeDB, SessionType } from 'typedb-driver';\n\nimport { defaultConfig } from './default.config';\nimport { bormDefine } from './define';\nimport { enrichSchema } from './helpers';\nimport { mutationPipeline, queryPipeline } from './pipeline/pipeline';\nimport type {\n\tBormConfig,\n\tBormSchema,\n\tDBHandles,\n\tMutateConfig,\n\tQueryConfig,\n\tRawBQLMutation,\n\tRawBQLQuery,\n} from './types';\n\nexport * from './types';\n\ntype BormProps = {\n\tschema: BormSchema;\n\tconfig: BormConfig;\n};\n\nclass BormClient {\n\tprivate schema: BormSchema;\n\n\tprivate config: BormConfig;\n\n\tprivate dbHandles?: DBHandles;\n\n\tconstructor({ schema, config }: BormProps) {\n\t\tthis.schema = schema;\n\t\tthis.config = config;\n\t}\n\n\tinit = async () => {\n\t\tconst dbHandles = { typeDB: new Map() };\n\t\tconst enrichedSchema = enrichSchema(this.schema);\n\t\tawait Promise.all(\n\t\t\tthis.config.dbConnectors.map(async (dbc) => {\n\t\t\t\tif (dbc.provider === 'typeDB' && dbc.dbName) {\n\t\t\t\t\t// const client = await TypeDB.coreClient(dbc.url);\n\t\t\t\t\t// const clientErr = undefined;\n\t\t\t\t\tconst [clientErr, client] = await tryit(TypeDB.coreDriver)(dbc.url);\n\t\t\t\t\tif (clientErr) {\n\t\t\t\t\t\tconst message = `[BORM:${dbc.provider}:${dbc.dbName}:core] ${\n\t\t\t\t\t\t\t// clientErr.messageTemplate?._messageBody() ?? \"Can't create TypeDB Client\"\n\t\t\t\t\t\t\tclientErr.message ?? \"Can't create TypeDB Client\"\n\t\t\t\t\t\t}`;\n\t\t\t\t\t\tthrow new Error(message);\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst session = await client.session(dbc.dbName, SessionType.DATA);\n\t\t\t\t\t\tdbHandles.typeDB.set(dbc.id, { client, session });\n\t\t\t\t\t} catch (sessionErr: any) {\n\t\t\t\t\t\tconst message = `[BORM:${dbc.provider}:${dbc.dbName}:session] ${\n\t\t\t\t\t\t\t// eslint-disable-next-line no-underscore-dangle\n\t\t\t\t\t\t\t(sessionErr.messageTemplate?._messageBody() || sessionErr.message) ?? \"Can't create TypeDB Session\"\n\t\t\t\t\t\t}`;\n\t\t\t\t\t\tthrow new Error(message);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (dbc.provider === 'typeDBCluster' && dbc.dbName) {\n\t\t\t\t\tconst [clientErr, client] = await tryit(TypeDB.enterpriseDriver)(dbc.addresses, dbc.credentials);\n\n\t\t\t\t\tif (clientErr) {\n\t\t\t\t\t\tconst message = `[BORM:${dbc.provider}:${dbc.dbName}:core] ${\n\t\t\t\t\t\t\t// clientErr.messageTemplate?._messageBody() ?? \"Can't create TypeDB Client\"\n\t\t\t\t\t\t\tclientErr.message ?? \"Can't create TypeDB Cluster Client\"\n\t\t\t\t\t\t}`;\n\t\t\t\t\t\tthrow new Error(message);\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst session = await client.session(dbc.dbName, SessionType.DATA);\n\t\t\t\t\t\tdbHandles.typeDB.set(dbc.id, { client, session });\n\t\t\t\t\t} catch (sessionErr: any) {\n\t\t\t\t\t\tconst message = `[BORM:${dbc.provider}:${dbc.dbName}:session] ${\n\t\t\t\t\t\t\t// eslint-disable-next-line no-underscore-dangle\n\t\t\t\t\t\t\t(sessionErr.messageTemplate?._messageBody() || sessionErr.message) ?? \"Can't create TypeDB Session\"\n\t\t\t\t\t\t}`;\n\t\t\t\t\t\tthrow new Error(message);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\t\t// @ts-expect-error - it becomes enrichedSchema here\n\t\tthis.schema = enrichedSchema;\n\t\tthis.dbHandles = dbHandles;\n\t};\n\n\t#enforceConnection = async () => {\n\t\tif (!this.dbHandles) {\n\t\t\tawait this.init();\n\t\t\tif (!this.dbHandles) {\n\t\t\t\tthrow new Error(\"Can't init BormClient\");\n\t\t\t}\n\t\t}\n\t};\n\n\tintrospect = async () => {\n\t\tawait this.#enforceConnection();\n\t\treturn this.schema;\n\t};\n\n\tdefine = async () => {\n\t\tawait this.#enforceConnection();\n\t\treturn bormDefine(this.config, this.schema, this.dbHandles);\n\t};\n\n\t/// no types yet, but we can do \"as ...\" after getting the type fro the schema\n\tquery = async (query: RawBQLQuery | RawBQLQuery[], queryConfig?: QueryConfig) => {\n\t\tawait this.#enforceConnection();\n\t\tconst qConfig = {\n\t\t\t...this.config,\n\t\t\tquery: { ...defaultConfig.query, ...this.config.query, ...queryConfig },\n\t\t};\n\t\t// @ts-expect-error - enforceConnection ensures dbHandles is defined\n\t\treturn queryPipeline(query, qConfig, this.schema, this.dbHandles);\n\t};\n\n\tmutate = async (mutation: RawBQLMutation | RawBQLMutation[], mutationConfig?: MutateConfig) => {\n\t\tawait this.#enforceConnection();\n\t\tconst mConfig = {\n\t\t\t...this.config,\n\t\t\tmutation: {\n\t\t\t\t...defaultConfig.mutation,\n\t\t\t\t...this.config.mutation,\n\t\t\t\t...mutationConfig,\n\t\t\t},\n\t\t};\n\t\t// @ts-expect-error - enforceConnection ensures dbHandles is defined\n\t\treturn mutationPipeline(mutation, mConfig, this.schema, this.dbHandles);\n\t};\n\n\tclose = async () => {\n\t\tif (!this.dbHandles) {\n\t\t\treturn;\n\t\t}\n\t\tthis.dbHandles.typeDB.forEach(async ({ client, session }) => {\n\t\t\tconsole.log('Closing session');\n\t\t\tawait session.close();\n\t\t\tconsole.log('Closing client');\n\t\t\tawait client.close();\n\t\t});\n\t};\n}\n\nexport default BormClient;\n","import type { BormConfig } from './types';\n\nexport const defaultConfig: Partial<BormConfig> = {\n\tquery: {\n\t\tnoMetadata: false,\n\t\tsimplifiedLinks: true,\n\t\tdebugger: false,\n\t\treturnNulls: false,\n\t},\n\n\tmutation: {\n\t\tnoMetadata: false,\n\t\tpreQuery: true,\n\t\tignoreNonexistingThings: false,\n\t},\n};\n","import { SessionType, TransactionType } from 'typedb-driver';\n\nimport type { BormConfig, BormSchema, LinkField } from '../types';\n\ntype Attribute = {\n\tdbPath: string;\n\tcontentType: string;\n};\n\nconst removeDuplicateObjects = (arr: Attribute[]) => {\n\tconst uniqueObjects: Attribute[] = [];\n\n\tconst uniqueMap = new Map();\n\n\tarr.forEach((obj) => {\n\t\tconst { dbPath, contentType } = obj;\n\t\tconst key = `${dbPath}-${contentType}`;\n\n\t\tif (!uniqueMap.has(key)) {\n\t\t\tuniqueMap.set(key, true);\n\t\t\tuniqueObjects.push(obj);\n\t\t}\n\t});\n\n\treturn uniqueObjects;\n};\n\nexport const bormDefine = async (config: BormConfig, schema: BormSchema, dbHandles: any) => {\n\tconst convertSchema = () => {\n\t\tlet output = '';\n\t\tconst usedAttributes: Attribute[] = [];\n\n\t\toutput += '\\n';\n\n\t\t// CONVERTING ENTITIES\n\n\t\tObject.keys(schema.entities).forEach((entityName) => {\n\t\t\tconst entity = schema.entities[entityName];\n\t\t\t// @ts-expect-error - TODO description\n\t\t\tconst { idFields, dataFields, linkFields, name } = entity;\n\t\t\t// Checks to see if parent already contains these fields\n\t\t\tconst commonDataFields: string[] = [];\n\t\t\tconst commonLinkFields: string[] = [];\n\t\t\tconst commonIdFields: string[] = [];\n\n\t\t\t// If extended by parent, get rid of parent's declared attributes\n\t\t\tif (entity.extends) {\n\t\t\t\tconst parentEntity = schema.entities[entity.extends];\n\t\t\t\tif (parentEntity.dataFields) {\n\t\t\t\t\tparentEntity.dataFields.forEach((dataField: any) => {\n\t\t\t\t\t\tcommonDataFields.push(dataField.dbPath);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (parentEntity.linkFields) {\n\t\t\t\t\tparentEntity.linkFields.forEach((linkField: LinkField) => {\n\t\t\t\t\t\tcommonLinkFields.push(linkField.path);\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (parentEntity.idFields) {\n\t\t\t\t\tparentEntity.idFields.forEach((idField: any) => {\n\t\t\t\t\t\tcommonIdFields.push(idField);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\toutput += `${name} sub ${entity.extends ? entity.extends : 'entity'},\\n`;\n\t\t\t// Removes ids from data fields, so their attributes aren't repeated\n\t\t\tconst idsAsData: string[] = [];\n\t\t\t// Adding id fields\n\t\t\tif (idFields && idFields.length > 0) {\n\t\t\t\tconst setIds = new Set(idFields);\n\t\t\t\tconst newIdFields = Array.from(setIds);\n\t\t\t\tconst idFieldsString = newIdFields.map((field: string) => `${field}`).join(', ');\n\t\t\t\tif (!commonIdFields.includes(idFieldsString)) {\n\t\t\t\t\toutput += ` owns ${idFieldsString} @key,\\n`;\n\t\t\t\t\tidsAsData.push(idFieldsString);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Adding data fields\n\t\t\tif (dataFields && dataFields.length > 0) {\n\t\t\t\tdataFields.forEach((field: any) => {\n\t\t\t\t\tif (!commonDataFields.includes(field.dbPath) && !idsAsData.includes(field.dbPath)) {\n\t\t\t\t\t\toutput += ` owns ${field.dbPath},\\n`;\n\t\t\t\t\t}\n\t\t\t\t\tusedAttributes.push({ dbPath: field.dbPath, contentType: field.contentType });\n\t\t\t\t});\n\t\t\t}\n\t\t\t// Adding link fields\n\t\t\tif (linkFields && linkFields.length > 0) {\n\t\t\t\tconst usedLinkFields: string[] = [];\n\t\t\t\tlinkFields.forEach((linkField) => {\n\t\t\t\t\tconst { relation, plays } = linkField;\n\t\t\t\t\tif (!commonLinkFields.includes(linkField.path) && !usedLinkFields.includes(`${relation}:${plays}`)) {\n\t\t\t\t\t\toutput += ` plays ${relation}:${plays},\\n`;\n\t\t\t\t\t\tusedLinkFields.push(`${relation}:${plays}`);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\toutput = output.replace(/,\\s*$/, ';\\n');\n\t\t\toutput += '\\n';\n\t\t});\n\n\t\t// CONVERTING RELATIONS\n\t\tObject.keys(schema.relations).forEach((relationName) => {\n\t\t\tconst relation = schema.relations[relationName];\n\t\t\t// TODO: fix name ts error\n\t\t\t// @ts-expect-error - TODO description\n\t\t\tconst { idFields, dataFields, roles, name, linkFields } = relation;\n\t\t\t// Checks to see if parent already contains these fields\n\t\t\tconst commonDataFields: string[] = [];\n\t\t\tconst commonLinkFields: string[] = [];\n\t\t\tconst commonRoleFields: string[] = [];\n\t\t\tconst commonIdFields: string[] = [];\n\n\t\t\t// If extended by parent, get rid of parent's declared attributes\n\t\t\tif (relation.extends) {\n\t\t\t\tconst parentRelation = schema.relations[relation.extends];\n\t\t\t\tif (parentRelation.dataFields) {\n\t\t\t\t\tparentRelation.dataFields.forEach((dataField: any) => {\n\t\t\t\t\t\tcommonDataFields.push(dataField.dbPath);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (parentRelation.linkFields) {\n\t\t\t\t\tparentRelation.linkFields.forEach((linkField: any) => {\n\t\t\t\t\t\tcommonLinkFields.push(linkField.dbPath);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (parentRelation.roles) {\n\t\t\t\t\tconst roleFields = Object.values(parentRelation.roles);\n\t\t\t\t\troleFields.forEach((roleField: any) => {\n\t\t\t\t\t\tcommonRoleFields.push(roleField.name);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (parentRelation.idFields) {\n\t\t\t\t\tparentRelation.idFields.forEach((idField: any) => {\n\t\t\t\t\t\tcommonIdFields.push(idField);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\toutput += `${name} sub ${relation.extends ? relation.extends : 'relation'},\\n`;\n\t\t\t// Removes ids from data fields, so their attributes aren't repeated\n\t\t\tconst idsAsData: string[] = [];\n\t\t\t// Adding id fields\n\t\t\tif (idFields && idFields.length > 0) {\n\t\t\t\tconst setIds = new Set(idFields);\n\t\t\t\tconst newIdFields = Array.from(setIds);\n\t\t\t\tconst idFieldsString = newIdFields.map((field: string) => `${field}`).join(', ');\n\t\t\t\tif (!commonIdFields.includes(idFieldsString)) {\n\t\t\t\t\toutput += ` owns ${idFieldsString} @key,\\n`;\n\t\t\t\t\tidsAsData.push(idFieldsString);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Adding data fields\n\t\t\tif (dataFields && dataFields.length > 0) {\n\t\t\t\tdataFields.forEach((field: any) => {\n\t\t\t\t\tif (!commonDataFields.includes(field.dbPath) && !idsAsData.includes(field.dbPath)) {\n\t\t\t\t\t\toutput += ` owns ${field.dbPath},\\n`;\n\t\t\t\t\t}\n\t\t\t\t\tusedAttributes.push({ dbPath: field.dbPath, contentType: field.contentType });\n\t\t\t\t});\n\t\t\t}\n\t\t\t// Adding role fields\n\t\t\tif (roles) {\n\t\t\t\tObject.keys(roles).forEach((roleName) => {\n\t\t\t\t\tif (!commonRoleFields.includes(roleName)) {\n\t\t\t\t\t\toutput += ` relates ${roleName},\\n`;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\t// Adding link fields\n\t\t\tif (linkFields && linkFields.length > 0) {\n\t\t\t\tconst usedLinkFields: string[] = [];\n\t\t\t\tlinkFields.forEach((linkField) => {\n\t\t\t\t\tconst { plays } = linkField;\n\t\t\t\t\tif (!commonLinkFields.includes(linkField.path) && !usedLinkFields.includes(`${relation}:${plays}`)) {\n\t\t\t\t\t\toutput += ` plays ${linkField.relation}:${plays},\\n`;\n\t\t\t\t\t\tusedLinkFields.push(`${relation}:${plays}`);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\toutput = output.replace(/,\\s*$/, ';\\n');\n\t\t\toutput += '\\n';\n\t\t});\n\n\t\t// DEFINING ATTRIBUTES\n\n\t\tlet attributes = 'define\\n\\n';\n\t\tconst newUsedAttributes = removeDuplicateObjects(usedAttributes);\n\n\t\tnewUsedAttributes.forEach((attribute: Attribute) => {\n\t\t\tattributes += `${attribute.dbPath} sub attribute,\\n`;\n\t\t\t// All conditions for BORM to TQL attribute types\n\t\t\tif (attribute.contentType === 'TEXT' || attribute.contentType === 'ID') {\n\t\t\t\tattributes += ' value string;\\n';\n\t\t\t} else if (attribute.contentType === 'EMAIL') {\n\t\t\t\tattributes += ' value string,\\n';\n\t\t\t\tattributes +=\n\t\t\t\t\t\" regex '^(?=.{1,64}@)[A-Za-z0-9_-]+(\\\\.[A-Za-z0-9_-]+)*@[^-][A-Za-z0-9-]+(\\\\.[A-Za-z0-9-]+)*(\\\\.[A-Za-z]{2,})$';\\n\";\n\t\t\t} else if (attribute.contentType === 'DATE') {\n\t\t\t\tattributes += ' value datetime;\\n';\n\t\t\t} else if (attribute.contentType === 'BOOLEAN') {\n\t\t\t\tattributes += ' value boolean;\\n';\n\t\t\t} else if (attribute.contentType === 'NUMBER') {\n\t\t\t\tattributes += ' value long;\\n';\n\t\t\t}\n\t\t});\n\n\t\treturn `${attributes}\\n\\n${output}`;\n\t};\n\n\t// TYPE DB TRANSACTIONS\n\n\tconst typeDBString = convertSchema();\n\tconst singleHandlerV0 = config.dbConnectors[0].id;\n\tconst session = dbHandles.typeDB.get(singleHandlerV0)?.session;\n\tconst client = dbHandles.typeDB.get(singleHandlerV0)?.client;\n\tif (!session) {\n\t\tconsole.log('Session Status: ', 'NO SESSION');\n\t\treturn;\n\t}\n\n\tsession.close();\n\tconst [{ dbName }] = config.dbConnectors;\n\tconst db = await client.databases.get(dbName);\n\tawait db.delete();\n\tawait client.databases.create(dbName);\n\n\tconst schemaSession = await client.session(config.dbConnectors[0].dbName, SessionType.SCHEMA);\n\n\t// 3. Defining new schema\n\tconst schemaTransaction = await schemaSession.transaction(TransactionType.WRITE);\n\n\tawait schemaTransaction.query.define(typeDBString);\n\tawait schemaTransaction.commit();\n\tawait schemaTransaction.close();\n\n\tconst getSchemaTransaction = await schemaSession.transaction(TransactionType.READ);\n\tconst getSchemaQuery = 'match $a sub thing;';\n\tconst getSchemaStream = await getSchemaTransaction.query.match(getSchemaQuery);\n\tconst schemaThings = await getSchemaStream.collect();\n\tschemaThings.forEach(async (conceptMap: any) => {\n\t\t// * Match the group as the main entity\n\t\tconst thing = conceptMap.get('a');\n\t\tconst { _label } = thing;\n\t\tconst { _name } = _label;\n\t});\n\tawait getSchemaTransaction.close();\n\t// 4. Closing sessions\n};\n","/* eslint-disable no-param-reassign */\nimport { produce } from 'immer';\nimport type { TraversalCallbackContext } from 'object-traversal';\nimport { traverse } from 'object-traversal';\nimport { listify } from 'radash';\n\n// todo: split helpers between common helpers, typeDBhelpers, dgraphelpers...\nimport type {\n\tBormSchema,\n\tBormRelation,\n\tBQLMutationBlock,\n\tEnrichedBormEntity,\n\tEnrichedBormRelation,\n\tEnrichedBormSchema,\n\tLinkedFieldWithThing,\n\tParsedBQLQuery,\n\tRawBQLQuery,\n\tDataField,\n\tBormEntity,\n} from './types';\n\nconst getDbPath = (thing: string, attribute: string, shared?: boolean) =>\n\tshared ? attribute : `${thing}·${attribute}`;\n\nexport const getPath = (dbPath: string) => {\n\tconst parts = dbPath.split('·');\n\treturn parts[parts.length - 1];\n};\n\nexport const oFind = <RemovedKeys extends string, T extends Record<string | number | symbol, any>>(\n\tobj: T,\n\tfn: (k: string | number | symbol, v: any) => boolean,\n): Omit<T, RemovedKeys>[Exclude<keyof T, RemovedKeys>] =>\n\tObject.values(Object.fromEntries(Object.entries(obj).filter(([k, v]) => fn(k, v))))[0];\n\nexport const oFilter = <K extends string | number | symbol, T extends Record<K, any>>(\n\tobj: T,\n\tfn: (k: K, v: any) => boolean,\n): Partial<T> => Object.fromEntries(Object.entries(obj).filter(([k, v]) => fn(k as K, v))) as Partial<T>;\n\nexport const enrichSchema = (schema: BormSchema): EnrichedBormSchema => {\n\tconst allLinkedFields: LinkedFieldWithThing[] = [];\n\t// #region 1)\n\n\tconst withExtensionsSchema = produce(schema, (draft) =>\n\t\ttraverse(\n\t\t\tdraft,\n\t\t\t({ key, value, meta }: TraversalCallbackContext) => {\n\t\t\t\tif (meta.depth !== 2) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (key) {\n\t\t\t\t\t// * Adding dbPath of local dataFields\n\t\t\t\t\tvalue.dataFields = value.dataFields?.map((df: DataField) => ({\n\t\t\t\t\t\t...df,\n\t\t\t\t\t\tdbPath: getDbPath(key, df.path, df.shared),\n\t\t\t\t\t}));\n\t\t\t\t}\n\t\t\t\tif (value.extends) {\n\t\t\t\t\tconst extendedSchema = draft.entities[value.extends] || draft.relations[value.extends];\n\t\t\t\t\t/// find out all the thingTypes this thingType is extending\n\t\t\t\t\t// @ts-expect-error allExtends does not belong to the nonEnriched schema so this ts error is expecte\n\t\t\t\t\tvalue.allExtends = [value.extends, ...(extendedSchema.allExtends || [])];\n\t\t\t\t\tvalue as BormEntity | BormRelation;\n\n\t\t\t\t\tvalue.idFields = extendedSchema.idFields\n\t\t\t\t\t\t? (value.idFields || []).concat(extendedSchema.idFields)\n\t\t\t\t\t\t: value.idFields;\n\t\t\t\t\tvalue.dataFields = extendedSchema.dataFields\n\t\t\t\t\t\t? (value.dataFields || []).concat(\n\t\t\t\t\t\t\t\textendedSchema.dataFields.map((df: DataField) => {\n\t\t\t\t\t\t\t\t\t// * Adding dbPath of extended dataFields\n\t\t\t\t\t\t\t\t\tlet deepExtendedThing = value.extends;\n\t\t\t\t\t\t\t\t\tlet deepSchema = schema.entities[deepExtendedThing] || schema.relations[deepExtendedThing];\n\t\t\t\t\t\t\t\t\twhile (!deepSchema.dataFields?.find((deepDf: DataField) => deepDf.path === df.path)) {\n\t\t\t\t\t\t\t\t\t\tdeepExtendedThing = deepSchema.extends;\n\t\t\t\t\t\t\t\t\t\tdeepSchema = schema.entities[deepExtendedThing] || schema.relations[deepExtendedThing];\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t...df,\n\t\t\t\t\t\t\t\t\t\tdbPath: getDbPath(deepExtendedThing, df.path, df.shared),\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t )\n\t\t\t\t\t\t: value.dataFields;\n\t\t\t\t\tvalue.linkFields = extendedSchema.linkFields\n\t\t\t\t\t\t? (value.linkFields || []).concat(extendedSchema.linkFields)\n\t\t\t\t\t\t: value.linkFields;\n\n\t\t\t\t\tif ('roles' in extendedSchema) {\n\t\t\t\t\t\tconst val = value as BormRelation;\n\t\t\t\t\t\tconst extendedRelationSchema = extendedSchema as BormRelation;\n\t\t\t\t\t\tval.roles = val.roles || {};\n\t\t\t\t\t\tval.roles = {\n\t\t\t\t\t\t\t...val.roles,\n\t\t\t\t\t\t\t...extendedRelationSchema.roles,\n\t\t\t\t\t\t};\n\t\t\t\t\t\tif (Object.keys(val.roles).length === 0) {\n\t\t\t\t\t\t\tval.roles = {};\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t\t{ traversalType: 'breadth-first' },\n\t\t),\n\t);\n\t// #endregion\n\n\t// * Gather linkfields\n\ttraverse(schema, ({ key, value, meta }: TraversalCallbackContext) => {\n\t\tif (key === 'linkFields') {\n\t\t\tconst getThingTypes = () => {\n\t\t\t\tif (!meta.nodePath) {\n\t\t\t\t\tthrow new Error('No path');\n\t\t\t\t}\n\t\t\t\tconst [thingPath, thing] = meta.nodePath.split('.');\n\t\t\t\tconst thingType = thingPath === 'entities' ? 'entity' : thingPath === 'relations' ? 'relation' : '';\n\t\t\t\treturn {\n\t\t\t\t\tthing,\n\t\t\t\t\tthingType,\n\t\t\t\t};\n\t\t\t};\n\t\t\tconst thingTypes = getThingTypes();\n\t\t\tconst withThing = !Array.isArray(value)\n\t\t\t\t? [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t...value,\n\t\t\t\t\t\t\t...thingTypes,\n\t\t\t\t\t\t},\n\t\t\t\t ]\n\t\t\t\t: value.map((x) => ({ ...x, ...thingTypes }));\n\n\t\t\tallLinkedFields.push(...withThing);\n\t\t}\n\t});\n\n\t// * Enrich the schema\n\n\tconst enrichedSchema = produce(withExtensionsSchema, (draft) =>\n\t\ttraverse(draft, ({ value, key, meta }: TraversalCallbackContext) => {\n\t\t\t// id things\n\t\t\tif (meta.depth === 2 && value.idFields && !value.id) {\n\t\t\t\t// depth 2 are entities and relations\n\t\t\t\t// eslint-disable-next-line prefer-destructuring\n\t\t\t\tvalue.name = key;\n\t\t\t\tconst thingType = () => {\n\t\t\t\t\tif (meta.nodePath?.split('.')[0] === 'entities') {\n\t\t\t\t\t\treturn 'entity';\n\t\t\t\t\t}\n\t\t\t\t\tif (meta.nodePath?.split('.')[0] === 'relations') {\n\t\t\t\t\t\treturn 'relation';\n\t\t\t\t\t}\n\t\t\t\t\tthrow new Error('Unsupported node attributes');\n\t\t\t\t};\n\t\t\t\tvalue.thingType = thingType();\n\t\t\t\t// init the array of computed values\n\t\t\t\tvalue.computedFields = [];\n\t\t\t\tvalue.virtualFields = [];\n\t\t\t\t// adding all the linkfields to roles\n\t\t\t\tif ('roles' in value) {\n\t\t\t\t\tconst val = value as EnrichedBormRelation;\n\n\t\t\t\t\tObject.entries(val.roles).forEach(([roleKey, role]) => {\n\t\t\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\t\t\trole.playedBy = allLinkedFields.filter((x) => x.relation === key && x.plays === roleKey) || [];\n\t\t\t\t\t\trole.name = roleKey;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif ('linkFields' in value && value.linkFields) {\n\t\t\t\t\tconst val = value as EnrichedBormRelation;\n\n\t\t\t\t\tval.linkFields?.forEach((linkField) => {\n\t\t\t\t\t\tif (linkField.target === 'relation') {\n\t\t\t\t\t\t\tlinkField.oppositeLinkFieldsPlayedBy = [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tplays: linkField.path,\n\t\t\t\t\t\t\t\t\tthing: linkField.relation,\n\t\t\t\t\t\t\t\t\tthingType: 'relation',\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst allOppositeLinkFields =\n\t\t\t\t\t\t\tallLinkedFields.filter((x) => x.relation === linkField.relation && x.plays !== linkField.plays) || [];\n\n\t\t\t\t\t\t// by default, all oppositeLinkFields\n\t\t\t\t\t\tlinkField.oppositeLinkFieldsPlayedBy = allOppositeLinkFields;\n\n\t\t\t\t\t\t// #region FILTERING OPPOSITE LINKFIELDS\n\t\t\t\t\t\tconst { filter } = linkField;\n\t\t\t\t\t\t// todo: not sure about this\n\t\t\t\t\t\tlinkField.oppositeLinkFieldsPlayedBy = linkField.oppositeLinkFieldsPlayedBy.filter(\n\t\t\t\t\t\t\t(x) => x.target === 'role',\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (filter && Array.isArray(filter)) {\n\t\t\t\t\t\t\tlinkField.oppositeLinkFieldsPlayedBy = linkField.oppositeLinkFieldsPlayedBy.filter((lf) =>\n\t\t\t\t\t\t\t\t// @ts-expect-error - TODO description\n\t\t\t\t\t\t\t\tfilter.some((ft) => lf.thing === ft.$role),\n\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\tlinkField.oppositeLinkFieldsPlayedBy = linkField.oppositeLinkFieldsPlayedBy.filter((lf) =>\n\t\t\t\t\t\t\t\t// @ts-expect-error - TODO description\n\t\t\t\t\t\t\t\tfilter.some((ft) => lf.thing === ft.$thing),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (filter && !Array.isArray(filter)) {\n\t\t\t\t\t\t\tlinkField.oppositeLinkFieldsPlayedBy = linkField.oppositeLinkFieldsPlayedBy.filter(\n\t\t\t\t\t\t\t\t// @ts-expect-error - TODO description\n\t\t\t\t\t\t\t\t(lf) => lf.$role === filter.$role,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tlinkField.oppositeLinkFieldsPlayedBy = linkField.oppositeLinkFieldsPlayedBy.filter(\n\t\t\t\t\t\t\t\t// @ts-expect-error - TODO description\n\t\t\t\t\t\t\t\t(lf) => lf.thing === filter.$thing,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// #endregion\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// role fields\n\t\t\tif (typeof value === 'object' && 'playedBy' in value) {\n\t\t\t\t// if (value.playedBy.length > 1) {\n\t\t\t\tif ([...new Set(value.playedBy?.map((x: LinkedFieldWithThing) => x.thing))].length > 1) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Unsupported: roleFields can be only played by one thing. Role: ${key} path:${meta.nodePath}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (value.playedBy.length === 0) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Unsupported: roleFields should be played at least by one thing. Role: ${key}, path:${meta.nodePath}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// if default or computed, add to computed fields list\n\t\t\tif (meta.depth === 4 && (value.default || value.computedValue)) {\n\t\t\t\tconst [type, thingId] = meta.nodePath?.split('.') || [];\n\t\t\t\t// todo:\n\t\t\t\tif (value.isVirtual) {\n\t\t\t\t\t// @ts-expect-error - TODO description\n\t\t\t\t\tdraft[type][thingId].virtualFields.push(value.path);\n\t\t\t\t} else {\n\t\t\t\t\t// @ts-expect-error - TODO description\n\t\t\t\t\tdraft[type][thingId].computedFields.push(value.path);\n\t\t\t\t}\n\t\t\t}\n\t\t}),\n\t) as EnrichedBormSchema;\n\n\t// console.log('enrichedShema', JSON.stringify(enrichedSchema, null, 3));\n\treturn enrichedSchema;\n};\n\nexport const getCurrentSchema = (\n\tschema: BormSchema | EnrichedBormSchema,\n\tnode: Partial<BQLMutationBlock>,\n): EnrichedBormEntity | EnrichedBormRelation => {\n\tif (node.$entity) {\n\t\tif (!(node.$entity in schema.entities)) {\n\t\t\tthrow new Error(`Missing entity '${node.$entity}' in the schema`);\n\t\t}\n\t\treturn schema.entities[node.$entity] as EnrichedBormEntity;\n\t}\n\tif (node.$relation) {\n\t\tif (!(node.$relation in schema.relations)) {\n\t\t\tthrow new Error(`Missing relation '${node.$relation}' in the schema`);\n\t\t}\n\t\treturn schema.relations[node.$relation] as EnrichedBormRelation;\n\t}\n\tthrow new Error(`Wrong schema or query for ${JSON.stringify(node, null, 2)}`);\n};\n\ntype ReturnTypeWithoutNode = {\n\tfields: string[];\n\tdataFields: string[];\n\troleFields: string[];\n\tlinkFields: string[];\n};\n\ntype ReturnTypeWithNode = ReturnTypeWithoutNode & {\n\tusedFields: string[];\n\tusedRoleFields: string[];\n\tusedLinkFields: string[];\n\tunidentifiedFields: string[];\n};\n\n// todo: do something so this enriches the query so no need to call it multiple times\nexport const getCurrentFields = <T extends (BQLMutationBlock | RawBQLQuery) | undefined>(\n\tcurrentSchema: EnrichedBormEntity | EnrichedBormRelation,\n\tnode?: T,\n): T extends undefined ? ReturnTypeWithoutNode : ReturnTypeWithNode => {\n\tconst availableDataFields = currentSchema.dataFields?.map((x) => x.path) || [];\n\tconst availableLinkFields = currentSchema.linkFields?.map((x) => x.path) || [];\n\tconst availableRoleFields = 'roles' in currentSchema ? listify(currentSchema.roles, (k: string) => k) : [];\n\tconst availableFields = [\n\t\t...(availableDataFields || []),\n\t\t...(availableLinkFields || []),\n\t\t...(availableRoleFields || []),\n\t];\n\n\t// spot non existing fields\n\tconst reservedRootFields = [\n\t\t'$entity',\n\t\t'$op',\n\t\t'$id',\n\t\t'$tempId',\n\t\t'$bzId',\n\t\t'$relation',\n\t\t'$parentKey',\n\t\t'$filter',\n\t\t'$fields',\n\t\t'$excludedFields',\n\t];\n\n\tconst allowedFields = [...reservedRootFields, ...availableFields];\n\n\tif (!node) {\n\t\treturn {\n\t\t\tfields: availableFields,\n\t\t\tdataFields: availableDataFields,\n\t\t\troleFields: availableRoleFields,\n\t\t\tlinkFields: availableLinkFields,\n\t\t} as ReturnTypeWithNode;\n\t}\n\tconst usedFields = node.$fields\n\t\t? (node.$fields.map((x: string | { $path: string }) => {\n\t\t\t\tif (typeof x === 'string') {\n\t\t\t\t\treturn x;\n\t\t\t\t}\n\t\t\t\tif ('$path' in x && typeof x.$path === 'string') {\n\t\t\t\t\treturn x.$path;\n\t\t\t\t}\n\t\t\t\tthrow new Error(' Wrongly structured query');\n\t\t }) as string[])\n\t\t: listify<any, string, string>(node, (k: string) => k);\n\n\tconst localFilterFields = !node.$filter\n\t\t? []\n\t\t: listify(node.$filter, (k: string) => (k.toString().startsWith('$') ? undefined : k.toString())).filter(\n\t\t\t\t(x) => x && availableDataFields?.includes(x),\n\t\t );\n\tconst nestedFilterFields = !node.$filter\n\t\t? []\n\t\t: listify(node.$filter, (k: string) => (k.toString().startsWith('$') ? undefined : k.toString())).filter(\n\t\t\t\t(x) => x && [...(availableRoleFields || []), ...(availableLinkFields || [])]?.includes(x),\n\t\t );\n\n\tconst unidentifiedFields = [...usedFields, ...localFilterFields]\n\t\t// @ts-expect-error - TODO description\n\t\t.filter((x) => !allowedFields.includes(x))\n\t\t.filter((x) => x) as string[]; // todo 🤔\n\tconst localFilters = !node.$filter ? {} : oFilter(node.$filter, (k: string, _v) => localFilterFields.includes(k));\n\tconst nestedFilters = !node.$filter ? {} : oFilter(node.$filter, (k: string, _v) => nestedFilterFields.includes(k));\n\n\treturn {\n\t\tfields: availableFields,\n\t\tdataFields: availableDataFields,\n\t\troleFields: availableRoleFields,\n\t\tlinkFields: availableLinkFields,\n\t\tusedFields,\n\t\tusedLinkFields: availableLinkFields.filter((x) => usedFields.includes(x)),\n\t\tusedRoleFields: availableRoleFields.filter((x) => usedFields.includes(x)),\n\t\tunidentifiedFields,\n\t\t...(localFilterFields.length ? { localFilters } : {}),\n\t\t...(nestedFilterFields.length ? { nestedFilters } : {}),\n\t} as ReturnTypeWithNode;\n};\n\n// todo: move this function to typeDBhelpers\nexport const getLocalFilters = (\n\tcurrentSchema: EnrichedBormEntity | EnrichedBormRelation,\n\t// todo: node?: BQLMutationBlock | ParsedBQLQuery\n\tnode: ParsedBQLQuery,\n) => {\n\tconst localFilters =\n\t\tnode.$localFilters &&\n\t\tlistify(node.$localFilters, (k: string, v) => {\n\t\t\tconst currentDataField = currentSchema.dataFields?.find((x) => x.path === k);\n\t\t\treturn `has ${currentDataField?.dbPath} '${v}'`;\n\t\t});\n\tconst localFiltersTql = localFilters?.length ? `, ${localFilters.join(',')}` : '';\n\treturn localFiltersTql;\n};\n\n/*\nexport const arrayAt = <T>(arr: T[] | undefined, index: number): T | undefined => {\n\tif (arr === undefined || !Array.isArray(arr) || index < -arr.length || index >= arr.length) {\n\t\treturn undefined;\n\t}\n\treturn arr[index < 0 ? arr.length + index : index];\n};*/\n\nexport const notNull = <TValue>(value: TValue | null): value is TValue => {\n\treturn value !== null;\n};\n\nexport const extractChildEntities = (entities: EnrichedBormSchema['entities'], parentEntity: string) => {\n\treturn Object.values(entities).reduce((acc: string[], value) => {\n\t\tif (value.extends === parentEntity) {\n\t\t\tacc.push(value.name);\n\t\t}\n\t\treturn acc;\n\t}, []);\n};\n","import { mapEntries } from 'radash';\n\nimport type { BQLMutationBlock } from '../../types';\nimport type { PipelineOperation } from '../pipeline';\n\nexport const parseTQLMutation: PipelineOperation = async (req, res) => {\n\tconst { bqlRequest, config, tqlRequest } = req;\n\tconst { rawTqlRes } = res;\n\tif (!bqlRequest) {\n\t\tthrow new Error('BQL request not parsed');\n\t} else if (!rawTqlRes) {\n\t\tthrow new Error('TQL query not executed');\n\t}\n\tconst { query } = bqlRequest;\n\n\t// <--------------- MUTATIONS\n\tif (!query) {\n\t\tif (rawTqlRes.insertions?.length === 0 && !tqlRequest?.deletions) {\n\t\t\t// if no insertions and no delete operations\n\t\t\tres.bqlRes = {}; // return an empty object to continue further steps without error\n\t\t\treturn;\n\t\t}\n\t\tconst { mutation } = bqlRequest;\n\t\tif (!mutation) {\n\t\t\tthrow new Error('TQL mutation not executed');\n\t\t}\n\t\t// console.log('config.mutation', config.mutation);\n\n\t\t// todo: check if something weird happened\n\t\tconst expected = [...mutation.things, ...mutation.edges];\n\t\tconst result = expected\n\t\t\t.map((exp) => {\n\t\t\t\t//! reads all the insertions and gets the first match. This means each id must be unique\n\t\t\t\tconst currentNode = rawTqlRes.insertions?.find((y) => y.get(`${exp.$bzId}`))?.get(`${exp.$bzId}`);\n\n\t\t\t\t// console.log('current:', JSON.stringify(x));\n\n\t\t\t\tif (exp.$op === 'create' || exp.$op === 'update' || exp.$op === 'link') {\n\t\t\t\t\tconst dbIdd = currentNode?.asThing().iid;\n\t\t\t\t\tif (config.mutation?.noMetadata) {\n\t\t\t\t\t\treturn mapEntries(exp, (k: string, v) => [\n\t\t\t\t\t\t\tk.toString().startsWith('$') ? Symbol.for(k) : k,\n\t\t\t\t\t\t\tv,\n\t\t\t\t\t\t]) as BQLMutationBlock;\n\t\t\t\t\t}\n\t\t\t\t\treturn { $dbId: dbIdd, ...exp, ...{ [exp.path]: exp.$id } } as BQLMutationBlock;\n\t\t\t\t}\n\t\t\t\tif (exp.$op === 'delete' || exp.$op === 'unlink') {\n\t\t\t\t\t// todo when typeDB confirms deletions, check them here\n\t\t\t\t\treturn exp as BQLMutationBlock;\n\t\t\t\t}\n\t\t\t\tif (exp.$op === 'match') {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\tthrow new Error(`Unsupported op ${exp.$op}`);\n\n\t\t\t\t// console.log('config', config);\n\t\t\t})\n\t\t\t.filter((z) => z);\n\n\t\t// todo\n\t\tres.bqlRes = result;\n\t\treturn;\n\t}\n};\n","import { isObject } from 'radash';\n\nimport type { BormConfig, BQLField, BQLResponseSingle } from '../../types';\nimport type { PipelineOperation } from '../pipeline';\n\nconst filterBQLRes = (row: BQLResponseSingle, config: BormConfig, fields: BQLField[] | undefined) =>\n\trow === null || typeof row === 'string'\n\t\t? row\n\t\t: Object.entries(row).reduce((acc, [k, v]): any => {\n\t\t\t\tconst isMetadataDisabled = !!(config.query?.noMetadata || config.mutation?.noMetadata);\n\t\t\t\tconst isWhitelisted = !fields || fields.length === 0 || fields.includes(k);\n\t\t\t\tconst nestedFields = fields?.find((f) => isObject(f) && f.$path === k);\n\t\t\t\tconst isMetadata = k.startsWith('$');\n\t\t\t\tconst isSymbol = typeof k === 'symbol';\n\t\t\t\tif (isSymbol || (isMetadataDisabled && isMetadata) || (!isMetadata && !isWhitelisted && !nestedFields)) {\n\t\t\t\t\t// * Drop property\n\t\t\t\t\treturn acc;\n\t\t\t\t}\n\t\t\t\tif (Array.isArray(v)) {\n\t\t\t\t\t// * Recurse into array\n\t\t\t\t\treturn {\n\t\t\t\t\t\t...acc,\n\t\t\t\t\t\t[k]: v.map((vChild: BQLResponseSingle) =>\n\t\t\t\t\t\t\t// @ts-expect-error if nestedFields is string, it's undefined and will be ignored\n\t\t\t\t\t\t\tfilterBQLRes(vChild, config, nestedFields?.$fields),\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (isObject(v)) {\n\t\t\t\t\t// * Recurse into object\n\t\t\t\t\treturn {\n\t\t\t\t\t\t...acc,\n\t\t\t\t\t\t[k]: filterBQLRes(\n\t\t\t\t\t\t\tv as BQLResponseSingle,\n\t\t\t\t\t\t\tconfig,\n\t\t\t\t\t\t\t// @ts-expect-error if nestedFields is string, it's undefined and will be ignored\n\t\t\t\t\t\t\tnestedFields?.$fields,\n\t\t\t\t\t\t),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\t// * Keep property as is\n\t\t\t\treturn { ...acc, [k]: v };\n\t\t }, {});\n\nexport const processFieldsOperator: PipelineOperation = async (req, res) => {\n\tconst { bqlRequest, config } = req;\n\tif (!res.bqlRes) {\n\t\tthrow new Error('BQL response not parsed');\n\t}\n\tlet filtered = res.bqlRes;\n\tif (filtered === null) {\n\t\treturn;\n\t}\n\n\tconst initialFields = bqlRequest?.query?.$fields;\n\tfiltered = Array.isArray(filtered)\n\t\t? res.bqlRes.map((r: BQLResponseSingle) => filterBQLRes(r, config, initialFields))\n\t\t: filterBQLRes(filtered, config, initialFields);\n\n\tres.bqlRes = filtered;\n};\n","/* eslint-disable no-param-reassign */\nimport { produce } from 'immer';\nimport type { TraversalCallbackContext } from 'object-traversal';\nimport { traverse } from 'object-traversal';\nimport { isObject, listify } from 'radash';\n\nimport { getCurrentFields, notNull, oFilter } from '../../helpers';\nimport type { BormConfig, BQLFieldObj, BQLMutationBlock, RawBQLQuery } from '../../types';\nimport type { Entity, PipelineOperation } from '../pipeline';\nimport { compute } from '../../engine/compute';\n\nconst isOne = (children: any[], $id: string) => {\n\tif (children.length === 1 && typeof children[0] !== 'string' ? children[0].$id === $id : false) {\n\t\treturn children[0];\n\t}\n\treturn children;\n};\n\nconst isStringOrHasShow = <TValue extends { $show?: boolean }>(value: TValue | string): value is TValue => {\n\treturn typeof value === 'string' || !!value.$show;\n};\n\nconst cleanOutput = (obj: RawBQLQuery | BQLMutationBlock | BQLMutationBlock[], config: BormConfig) =>\n\tproduce(obj, (draft) =>\n\t\ttraverse(draft, ({ value }: TraversalCallbackContext) => {\n\t\t\t// if it is an array or an object, then return as they will be managed later\n\t\t\tif (Array.isArray(value) || !(typeof value === 'object') || value === null) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (value.$tempId) {\n\t\t\t\tvalue.$tempId = `_:${value.$tempId}`;\n\t\t\t}\n\t\t\tif (value.$fields) {\n\t\t\t\tdelete value.$fields;\n\t\t\t}\n\t\t\tif (value.$filter) {\n\t\t\t\tdelete value.$filter;\n\t\t\t}\n\t\t\tif (value.$show) {\n\t\t\t\tdelete value.$show;\n\t\t\t}\n\t\t\tif (value.$bzId) {\n\t\t\t\tdelete value.$bzId;\n\t\t\t}\n\n\t\t\tif (config.query?.noMetadata && (value.$entity || value.$relation)) {\n\t\t\t\tdelete value.$entity;\n\t\t\t\tdelete value.$relation;\n\t\t\t\tdelete value.$id;\n\t\t\t}\n\n\t\t\tconst symbols = Object.getOwnPropertySymbols(value);\n\t\t\tsymbols.forEach((symbol) => {\n\t\t\t\tdelete value[symbol];\n\t\t\t});\n\n\t\t\tif (value.$excludedFields) {\n\t\t\t\tvalue.$excludedFields.forEach((field: any) => {\n\t\t\t\t\tdelete value[field];\n\t\t\t\t});\n\t\t\t\tdelete value.$excludedFields;\n\t\t\t}\n\t\t}),\n\t);\n\nconst filterChildrenEntities = (things: [string, Entity][], ids: string | string[], node: RawBQLQuery, path: string) =>\n\tthings\n\t\t.map(([id, entity]) => {\n\t\t\tif (!ids) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (!ids.includes(id)) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (!node.$fields) {\n\t\t\t\treturn id;\n\t\t\t}\n\t\t\tif (node.$fields.includes(path)) {\n\t\t\t\treturn id;\n\t\t\t}\n\t\t\tconst currentFieldConf = node.$fields.find((f) => isObject(f) && f.$path === path) as BQLFieldObj;\n\n\t\t\tif (currentFieldConf) {\n\t\t\t\tconst onlyMetadataEntity = {\n\t\t\t\t\t...oFilter(entity, (k: string, _v) => k.startsWith('$')),\n\t\t\t\t};\n\t\t\t\tconst withFieldsEntity = currentFieldConf.$fields\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t...onlyMetadataEntity,\n\t\t\t\t\t\t\t$fields: currentFieldConf.$fields,\n\t\t\t\t\t }\n\t\t\t\t\t: onlyMetadataEntity;\n\t\t\t\t// console.log('withFieldsEntity', withFieldsEntity);\n\n\t\t\t\tif (currentFieldConf.$id) {\n\t\t\t\t\tif (Array.isArray(currentFieldConf.$id)) {\n\t\t\t\t\t\tif (currentFieldConf.$id.includes(id)) {\n\t\t\t\t\t\t\treturn withFieldsEntity;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t\tif (currentFieldConf.$id === id) {\n\t\t\t\t\t\treturn withFieldsEntity;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// console.log('Main log: ', JSON.stringify(withFieldsEntity, null, 2));\n\n\t\t\t\tif (withFieldsEntity.$fields && withFieldsEntity.$fields.includes('id') && !withFieldsEntity.$show) {\n\t\t\t\t\tlet returnVal = '';\n\n\t\t\t\t\twithFieldsEntity.$fields.forEach((field: string) => {\n\t\t\t\t\t\tif (field === 'id') {\n\t\t\t\t\t\t\t// @ts-expect-error - TODO description\n\t\t\t\t\t\t\treturnVal = withFieldsEntity.$id;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// @ts-expect-error - TODO description\n\t\t\t\t\t\t\treturnVal = withFieldsEntity;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\treturn returnVal;\n\t\t\t\t}\n\t\t\t\t// no id, then every entity\n\t\t\t\t// TODO: include other branch merge changes here\n\t\t\t\treturn withFieldsEntity;\n\t\t\t}\n\t\t\treturn null;\n\t\t})\n\t\t.filter((x) => x);\n\nconst replaceBzIds = (resItems: any[], things: any[]) => {\n\tconst mapping = {};\n\n\t// Create a mapping from $bzId to $id\n\tthings.forEach((thing: any) => {\n\t\t// @ts-expect-error - TODO description\n\t\tmapping[thing.$bzId] = thing.$id;\n\t});\n\t// Replace values in the first array\n\tresItems.forEach((item) => {\n\t\tObject.keys(item).forEach((key) => {\n\t\t\t// @ts-expect-error - TODO description\n\t\t\tif (mapping[item[key]] && key !== '$tempId') {\n\t\t\t\t// @ts-expect-error - TODO description\n\n\t\t\t\titem[key] = mapping[item[key]];\n\t\t\t}\n\t\t});\n\t});\n\n\treturn resItems;\n};\n\nconst hasMatches = (resItems: any[], things: any[]): boolean => {\n\tconst bzIds = things.map((thing) => thing.$bzId);\n\tlet found = false;\n\n\tresItems.forEach((item) => {\n\t\tObject.keys(item).forEach((key) => {\n\t\t\tif (bzIds.includes(item[key])) {\n\t\t\t\tfound = true;\n\t\t\t}\n\t\t});\n\t});\n\n\treturn found;\n};\n\nexport const buildBQLTree: PipelineOperation = async (req, res) => {\n\tconst { bqlRequest, config, schema } = req;\n\t// const queryConfig = config.query;\n\tconst { cache } = res;\n\t// console.log('cache', cache);\n\tif (!bqlRequest) {\n\t\tthrow new Error('BQL request not parsed');\n\t}\n\n\tconst { query } = bqlRequest;\n\tif (!query) {\n\t\t// @ts-expect-error - TODO description\n\t\tconst resItems = res.bqlRes[0] ? res.bqlRes : [res.bqlRes];\n\t\tconst things = req.bqlRequest?.mutation?.things;\n\t\t// @ts-expect-error - TODO description\n\t\tconst matchesFound = hasMatches(resItems, things);\n\t\tif (matchesFound) {\n\t\t\t// @ts-expect-error - TODO description\n\t\t\tconst replaced = replaceBzIds(resItems, things);\n\t\t\tres.bqlRes = replaced[1] ? replaced : replaced[0];\n\t\t}\n\t\t// @ts-expect-error - TODO description\n\t\tconst output = cleanOutput(res.bqlRes, config);\n\t\tres.bqlRes = output;\n\n\t\treturn;\n\t}\n\tif (!cache) {\n\t\treturn;\n\t}\n\n\tconst thingSchema = '$entity' in query ? query.$entity : query.$relation;\n\n\tconst entityMap = cache.entities.get(thingSchema.name);\n\tif (!entityMap) {\n\t\tres.bqlRes = null;\n\t\treturn;\n\t}\n\n\t// todo:\n\t// @ts-expect-error - TODO description\n\tconst filterFields = listify(query.$filter, (x) => x);\n\tconst atLeastOneUnique = filterFields.some(\n\t\t(x) => thingSchema.dataFields?.find((y) => y.path === x)?.validations?.unique,\n\t);\n\n\tconst monoOutput =\n\t\t!Array.isArray(bqlRequest.query) &&\n\t\t((bqlRequest.query?.$id && !Array.isArray(bqlRequest.query?.$id)) || atLeastOneUnique);\n\t// todo: add the other two cases\n\t// || bqlRequest.query?.$filter?.[filtered by an id field]);\n\t// || !bqlRequest.query.limit !== 1;\n\n\tif (Array.isArray(req.rawBqlRequest)) {\n\t\tthrow new Error('Query arrays not implemented yet');\n\t}\n\n\tconst rootThings = entityMap;\n\t// root element is not an array but we need it to be one so we can traverse it\n\tconst structuredAnswer = [...rootThings].length\n\t\t? [...rootThings].map(([id, _entity]) => ({\n\t\t\t\t...req.rawBqlRequest,\n\t\t\t\t$id: id,\n\t\t }))\n\t\t: req.rawBqlRequest;\n\n\tconst bqlTree = produce(structuredAnswer, (draft) =>\n\t\ttraverse(draft, ({ value: val }: TraversalCallbackContext) => {\n\t\t\tconst value = val as RawBQLQuery;\n\t\t\t// @ts-expect-error - TODO description\n\t\t\tif (!value?.$entity && !value?.$relation) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// @ts-expect-error todo\n\t\t\tconst thingName = '$entity' in value ? value.$entity : value.$relation;\n\t\t\tif (thingName) {\n\t\t\t\t// INIT\n\t\t\t\tconst currentIds = Array.isArray(value.$id) ? value.$id : [value.$id];\n\t\t\t\t// @ts-expect-error todo\n\t\t\t\tconst currentSchema = '$relation' in value ? schema.relations[value.$relation] : schema.entities[value.$entity];\n\n\t\t\t\tconst { dataFields, roleFields, fields } = getCurrentFields(currentSchema);\n\n\t\t\t\tif (config.query?.returnNulls) {\n\t\t\t\t\t/// by default, all queried values are null, then they will be override by the different things if they find values\n\t\t\t\t\t/// this enables to update caches if values have been deleted\n\t\t\t\t\tconst queriedPaths = value.$fields ? value.$fields.map((x) => (typeof x === 'string' ? x : x.$path)) : fields;\n\t\t\t\t\tqueriedPaths.forEach((path) => {\n\t\t\t\t\t\t// @ts-expect-error - TODO description\n\t\t\t\t\t\tvalue[path] = null;\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\t// #region DATAFIELDS\n\t\t\t\tconst currentEntities = cache.entities.get(thingName);\n\t\t\t\tif (!currentEntities) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t[...currentEntities].forEach(([id, entity]) => {\n\t\t\t\t\tif (currentIds.includes(id)) {\n\t\t\t\t\t\t// if $fields is present, only return those fields, if not, everything\n\t\t\t\t\t\tconst queriedDataFields = value.$fields ? value.$fields : dataFields;\n\n\t\t\t\t\t\t/// Virtual fields\n\t\t\t\t\t\tconst { virtualFields } = currentSchema;\n\t\t\t\t\t\t//for each vitualFIelfd present in the queried datas print them\n\t\t\t\t\t\tvirtualFields?.forEach((virtualField) => {\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\tqueriedDataFields?.includes(virtualField) &&\n\t\t\t\t\t\t\t\t// @ts-expect-error - No need to compute if it was received somehow from the DB or if it is not a virtual field\n\t\t\t\t\t\t\t\t(value[virtualField] === undefined || value[virtualField] === null)\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tconst fieldSchema = currentSchema.dataFields?.find((x) => x.path === virtualField);\n\t\t\t\t\t\t\t\tconst computedValue = compute({ currentThing: entity, fieldSchema: fieldSchema });\n\n\t\t\t\t\t\t\t\t// @ts-expect-error - TODO description\n\t\t\t\t\t\t\t\tvalue[virtualField] = computedValue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tlistify(entity, (k, v) => {\n\t\t\t\t\t\t\tif (k.startsWith('$')) {\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!queriedDataFields?.includes(k)) {\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// @ts-expect-error - TODO description\n\t\t\t\t\t\t\tvalue[k] = v;\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\t// #endregion\n\t\t\t\t\t\t// #region ROLE FIELDS\n\t\t\t\t\t\tconst links = cache.roleLinks.get(id);\n\t\t\t\t\t\tconst flatRoleFields = value.$fields ? value.$fields.filter((x) => typeof x === 'string') : roleFields;\n\n\t\t\t\t\t\tconst embeddedRoleFields =\n\t\t\t\t\t\t\tvalue.$fields\n\t\t\t\t\t\t\t\t?.filter((x) => typeof x === 'object')\n\t\t\t\t\t\t\t\t// @ts-expect-error already said it's an object 🤔\n\t\t\t\t\t\t\t\t?.map((y) => y.$path) || [];\n\n\t\t\t\t\t\tObject.entries(links || {}).forEach(([rolePath, linkedIds]) => {\n\t\t\t\t\t\t\t// if not listed, skip\n\t\t\t\t\t\t\tif (![...flatRoleFields, ...embeddedRoleFields].includes(rolePath)) {\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!('roles' in currentSchema)) {\n\t\t\t\t\t\t\t\tthrow new Error('No roles in schema');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst uniqueLinkedIds = !Array.isArray(linkedIds) ? [linkedIds] : [...new Set(linkedIds)];\n\n\t\t\t\t\t\t\tconst { cardinality, playedBy } = currentSchema.roles[rolePath];\n\n\t\t\t\t\t\t\tconst thingNames = [...new Set(playedBy?.map((x) => x.thing))];\n\n\t\t\t\t\t\t\tconst children = thingNames?.flatMap((x) => {\n\t\t\t\t\t\t\t\tconst thingEntities = cache.entities.get(x);\n\t\t\t\t\t\t\t\tif (!thingEntities) {\n\t\t\t\t\t\t\t\t\treturn [];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn filterChildrenEntities([...thingEntities], uniqueLinkedIds, value, rolePath);\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tif (children?.length) {\n\t\t\t\t\t\t\t\t// if the only children is the current entity, don't return it\n\t\t\t\t\t\t\t\tif (children.length === 1 && children[0] === value.$id) {\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tif (cardinality === 'ONE') {\n\t\t\t\t\t\t\t\t\t// @ts-expect-error - TODO description\n\t\t\t\t\t\t\t\t\t// eslint-disable-next-line prefer-destructuring\n\t\t\t\t\t\t\t\t\tvalue[rolePath] = children[0];\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// @ts-expect-error - TODO description\n\t\t\t\t\t\t\t\tvalue[rolePath] = children.filter((x) => typeof x === 'string' || (typeof x === 'object' && x?.$show));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\t// #endregion\n\t\t\t\t// #region LINKFIELDS\n\t\t\t\tconst currentLinkFields = currentSchema.linkFields;\n\t\t\t\tif (currentLinkFields) {\n\t\t\t\t\tcurrentLinkFields.forEach((linkField) => {\n\t\t\t\t\t\t// console.log('linkField', linkField);\n\n\t\t\t\t\t\tconst currentRelation = cache.relations.get(linkField.relation) as\n\t\t\t\t\t\t\t| undefined\n\t\t\t\t\t\t\t| Map<string, { entityName: string; id: string }>[];\n\t\t\t\t\t\t// console.log('currentRelation', currentRelation);\n\t\t\t\t\t\t// FIX: show get the related entity, not the parent one\n\t\t\t\t\t\tconst tunnel = linkField.oppositeLinkFieldsPlayedBy;\n\t\t\t\t\t\tif (!currentRelation) {\n\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// FIX: should be fixed to match new relation object type\n\t\t\t\t\t\tif (linkField.target === 'relation') {\n\t\t\t\t\t\t\tconst linkedEntities = [...currentRelation].reduce((acc: Record<string, Set<string>>, relation) => {\n\t\t\t\t\t\t\t\tconst id = relation.get(linkField.plays)?.id;\n\t\t\t\t\t\t\t\tif (id && id === currentIds[0]) {\n\t\t\t\t\t\t\t\t\t// TODO: should never undefined, relation implies at least 2 roles\n\t\t\t\t\t\t\t\t\t// check why some relations have size 1\n\t\t\t\t\t\t\t\t\tconst opposingRole = relation.get(linkField.relation) as\n\t\t\t\t\t\t\t\t\t\t| {\n\t\t\t\t\t\t\t\t\t\t\t\tentityName: string;\n\t\t\t\t\t\t\t\t\t\t\t\tid: string;\n\t\t\t\t\t\t\t\t\t\t }\n\t\t\t\t\t\t\t\t\t\t| undefined;\n\t\t\t\t\t\t\t\t\tif (!opposingRole) {\n\t\t\t\t\t\t\t\t\t\treturn acc;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (!acc[opposingRole.entityName]) {\n\t\t\t\t\t\t\t\t\t\tacc[opposingRole.entityName] = new Set();\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tacc[opposingRole.entityName].add(opposingRole.id);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn acc;\n\t\t\t\t\t\t\t}, {});\n\n\t\t\t\t\t\t\tObject.entries(linkedEntities).map(([key, linkedEntityVal]) => {\n\t\t\t\t\t\t\t\tconst allCurrentLinkFieldThings = cache.entities.get(key);\n\t\t\t\t\t\t\t\tif (!allCurrentLinkFieldThings) {\n\t\t\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tconst children = filterChildrenEntities(\n\t\t\t\t\t\t\t\t\t[...allCurrentLinkFieldThings],\n\t\t\t\t\t\t\t\t\t[...linkedEntityVal.values()],\n\t\t\t\t\t\t\t\t\tvalue,\n\t\t\t\t\t\t\t\t\tlinkField.path,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t.filter(notNull)\n\t\t\t\t\t\t\t\t\t.filter(isStringOrHasShow);\n\n\t\t\t\t\t\t\t\tif (children.length === 0) {\n\t\t\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tif (children && children.length) {\n\t\t\t\t\t\t\t\t\tif (linkField.cardinality === 'ONE') {\n\t\t\t\t\t\t\t\t\t\t// @ts-expect-error - TODO description\n\t\t\t\t\t\t\t\t\t\t// eslint-disable-next-line prefer-destructuring\n\t\t\t\t\t\t\t\t\t\tvalue[linkField.path] = children[0];\n\t\t\t\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t// @ts-expect-error - TODO description\n\t\t\t\t\t\t\t\t\tvalue[linkField.path] = children;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t// console.log('children', children);\n\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (linkField.target === 'role') {\n\t\t\t\t\t\t\t// Maybe should iterate over role and then get opposing entityIds\n\t\t\t\t\t\t\ttunnel.forEach((t) => {\n\t\t\t\t\t\t\t\tif (!currentRelation) {\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tconst linkedEntities = [...currentRelation].reduce((acc: Record<string, Set<string>>, relation) => {\n\t\t\t\t\t\t\t\t\t// Check why I need to use t.\n\t\t\t\t\t\t\t\t\tconst id = relation.get(linkField.plays)?.id;\n\t\t\t\t\t\t\t\t\tif (id && id === currentIds[0]) {\n\t\t\t\t\t\t\t\t\t\t// TODO: should never undefined, relation implies at least 2 roles\n\t\t\t\t\t\t\t\t\t\t// check why some relations have size 1\n\t\t\t\t\t\t\t\t\t\tconst opposingRole = relation.get(t.plays) as\n\t\t\t\t\t\t\t\t\t\t\t| {\n\t\t\t\t\t\t\t\t\t\t\t\t\tentityName: string;\n\t\t\t\t\t\t\t\t\t\t\t\t\tid: string;\n\t\t\t\t\t\t\t\t\t\t\t }\n\t\t\t\t\t\t\t\t\t\t\t| undefined;\n\t\t\t\t\t\t\t\t\t\tif (!opposingRole) {\n\t\t\t\t\t\t\t\t\t\t\treturn acc;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tif (!acc[opposingRole.entityName]) {\n\t\t\t\t\t\t\t\t\t\t\tacc[opposingRole.entityName] = new Set();\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tacc[opposingRole.entityName].add(opposingRole.id);\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\treturn acc;\n\t\t\t\t\t\t\t\t}, {});\n\n\t\t\t\t\t\t\t\tObject.entries(linkedEntities).forEach(([key, linkedEntityVal]) => {\n\t\t\t\t\t\t\t\t\tconst allCurrentLinkFieldThings = cache.entities.get(key);\n\t\t\t\t\t\t\t\t\tif (!allCurrentLinkFieldThings) {\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tconst children = filterChildrenEntities(\n\t\t\t\t\t\t\t\t\t\t[...allCurrentLinkFieldThings],\n\t\t\t\t\t\t\t\t\t\t[...linkedEntityVal.values()],\n\t\t\t\t\t\t\t\t\t\tvalue,\n\t\t\t\t\t\t\t\t\t\tlinkField.path,\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t.filter(notNull)\n\t\t\t\t\t\t\t\t\t\t.filter(isStringOrHasShow);\n\t\t\t\t\t\t\t\t\tif (children.length === 0) {\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif (children && children.length) {\n\t\t\t\t\t\t\t\t\t\tif (linkField.cardinality === 'ONE') {\n\t\t\t\t\t\t\t\t\t\t\t// @ts-expect-error - TODO description\n\t\t\t\t\t\t\t\t\t\t\t// eslint-disable-next-line prefer-destructuring\n\t\t\t\t\t\t\t\t\t\t\tvalue[linkField.path] = children[0];\n\t\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t// @ts-expect-error - TODO description\n\t\t\t\t\t\t\t\t\t\tvalue[linkField.path] = children;\n\n\t\t\t\t\t\t\t\t\t\tlet filtered: { $id?: string } | { $id?: string }[] = {};\n\t\t\t\t\t\t\t\t\t\tconst filterFunc = (o: any): boolean => {\n\t\t\t\t\t\t\t\t\t\t\tif (o.$path === linkField.path) {\n\t\t\t\t\t\t\t\t\t\t\t\tfiltered = o;\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\treturn o?.$fields?.forEach(filterFunc);\n\t\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\t\tlet pathAndIdMatch = '';\n\t\t\t\t\t\t\t\t\t\tquery.$fields?.forEach(filterFunc);\n\t\t\t\t\t\t\t\t\t\tif (filtered) {\n\t\t\t\t\t\t\t\t\t\t\tif (!Array.isArray(filtered.$id)) {\n\t\t\t\t\t\t\t\t\t\t\t\t// @ts-expect-error - TODO description\n\t\t\t\t\t\t\t\t\t\t\t\tpathAndIdMatch = filtered.$id;\n\n\t\t\t\t\t\t\t\t\t\t\t\t// if (filtered.$id.length === 1) {\n\t\t\t\t\t\t\t\t\t\t\t\t// const firstEl = filtered.$id[0];\n\t\t\t\t\t\t\t\t\t\t\t\t// pathAndIdMatch = firstEl;\n\t\t\t\t\t\t\t\t\t\t\t\t// }\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t// @ts-expect-error - TODO description\n\t\t\t\t\t\t\t\t\t\tvalue[linkField.path] = isOne(children, pathAndIdMatch);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t// const $id = $fieldConf ? $fieldConf.$id : null;\n\t\t\t\t\t\t\t\t// const childrenCurrentIds = Array.isArray($id) ? $id : [$id];\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\t// #endregion\n\t\t\t}\n\t\t\t// console.log('VALUE', isDraft(value) ? current(value) : value);\n\t\t}),\n\t);\n\n\tconst withoutFieldFilters = cleanOutput(bqlTree, config);\n\n\t// res.bqlRes = monoOutput ? bqlRes[0] : bqlRes;\n\t// @ts-expect-error - TODO description\n\tres.bqlRes = monoOutput ? withoutFieldFilters[0] : withoutFieldFilters;\n};\n","const STRIP_COMMENTS = /((\\/\\/.*$)|(\\/\\*.*\\*\\/))/gm;\nconst STRIP_KEYWORDS = /(\\s*async\\s*|\\s*function\\s*)+/;\n// This regex captures parameters, ignoring any patterns inside the function body\nconst ARGUMENT_NAMES = /(?:function\\s*[^(\\s]*\\s*|\\s*=>\\s*|^\\s*)\\(([^)]*)\\)/;\nconst ARGUMENT_SPLIT = /[ ,\\n\\r\\t]+/;\n\nexport const getParamNames = (func: (...args: any[]) => any): string[] => {\n\tconst fnStr: string = func.toString().replace(STRIP_COMMENTS, '').replace(STRIP_KEYWORDS, '').trim();\n\tconst matches: RegExpExecArray | null = ARGUMENT_NAMES.exec(fnStr);\n\n\tif (!matches) {\n\t\treturn [];\n\t}\n\n\tlet match: string | undefined;\n\tfor (const matchGroup of matches.slice(1)) {\n\t\tif (matchGroup) {\n\t\t\tmatch = matchGroup;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (!match) {\n\t\treturn [];\n\t}\n\n\t// Handle destructured parameters by removing curly braces and spaces\n\tmatch = match.replace(/\\{\\s*/g, '').replace(/\\s*\\}/g, '');\n\n\treturn match.split(ARGUMENT_SPLIT).filter((part) => part.trim() !== '');\n};\n","import type { BQLMutationBlock, EnrichedDataField } from '../types';\nimport { getParamNames } from './helpers';\n\nexport const compute = ({\n\tcurrentThing,\n\tfieldSchema,\n\tmandatoryDependencies = false,\n}: {\n\tcurrentThing: BQLMutationBlock;\n\tfieldSchema?: EnrichedDataField;\n\tmandatoryDependencies?: boolean;\n}) => {\n\tif (!fieldSchema || !fieldSchema.default || !fieldSchema.default.value) {\n\t\tthrow new Error('Virtual field: No field schema found, or wrongly configured');\n\t}\n\tconst fn = fieldSchema.default.value;\n\n\tconst args = getParamNames(fn);\n\n\t//check if all the args are in the entity, if not, throw a missing error with all the not present ones\n\tconst missingArgs = args.filter((arg) => !(arg in currentThing));\n\tif (mandatoryDependencies && missingArgs.length) {\n\t\tthrow new Error(`Virtual field: Missing arguments ${missingArgs.join(', ')}`);\n\t}\n\tconst computedValue = 'default' in fieldSchema ? fieldSchema.default?.value(currentThing) : undefined;\n\treturn computedValue;\n};\n","import { isArray, listify, mapEntries, shake } from 'radash';\n\nimport { getCurrentSchema } from '../../helpers';\nimport type { BQLMutationBlock } from '../../types';\nimport type { PipelineOperation } from '../pipeline';\n\nexport const buildTQLMutation: PipelineOperation = async (req) => {\n\tconst { bqlRequest, schema } = req;\n\tif (!bqlRequest) {\n\t\tthrow new Error('BQL request not parsed');\n\t}\n\tconst { mutation } = bqlRequest;\n\tif (!mutation) {\n\t\tthrow new Error('BQL request is not a mutation');\n\t}\n\n\t// todo: Split attributes and edges\n\tconst nodeToTypeQL = (\n\t\tnode: BQLMutationBlock,\n\t): {\n\t\tpreDeletionBatch?: any[];\n\t\tdeletionMatch?: string;\n\t\tinsertionMatch?: string;\n\t\tdeletion?: string;\n\t\tinsertion?: string;\n\t\top: string;\n\t} => {\n\t\t// console.log('--------nodeToTypeQL-----------');\n\t\t// console.log('id', node.$id);\n\t\tconst op = node.$op as string;\n\t\tconst bzId = `$${node.$bzId}`;\n\t\tconst currentSchema = getCurrentSchema(schema, node);\n\t\tconst { idFields, defaultDBConnector } = currentSchema;\n\n\t\tconst thingDbPath = defaultDBConnector?.path || node.$entity || node.$relation;\n\n\t\tconst idValue = node.$id;\n\n\t\t// todo: composite ids\n\t\tconst idField = idFields?.[0];\n\n\t\tconst attributes = listify(node, (k, v) => {\n\t\t\t// @ts-expect-error - TODO description\n\t\t\tif (k.startsWith('$') || k === idField || v === undefined || v === null) {\n\t\t\t\treturn '';\n\t\t\t}\n\t\t\t// if (k.startsWith('$') || !v) return '';\n\t\t\tconst currentDataField = currentSchema.dataFields?.find((x) => x.path === k);\n\t\t\t// console.log('currentDataField', currentDataField);\n\t\t\tconst fieldDbPath = currentDataField?.path;\n\n\t\t\tif (!fieldDbPath) {\n\t\t\t\t// throw new Error('noFieldDbPath');\n\t\t\t\treturn '';\n\t\t\t}\n\t\t\tconst dbField = currentDataField.dbPath;\n\n\t\t\tif (['TEXT', 'ID', 'EMAIL'].includes(currentDataField.contentType)) {\n\t\t\t\treturn `has ${dbField} '${v}'`;\n\t\t\t}\n\t\t\tif (['NUMBER', 'BOOLEAN'].includes(currentDataField.contentType)) {\n\t\t\t\treturn `has ${dbField} ${v}`;\n\t\t\t}\n\t\t\tif (currentDataField.contentType === 'DATE') {\n\t\t\t\tif (Number.isNaN(v.valueOf())) {\n\t\t\t\t\tthrow new Error('Invalid format, Nan Date');\n\t\t\t\t}\n\t\t\t\tif (v instanceof Date) {\n\t\t\t\t\treturn `has ${dbField} ${v.toISOString().replace('Z', '')}`;\n\t\t\t\t}\n\t\t\t\treturn `has ${dbField} ${new Date(v).toISOString().replace('Z', '')}`;\n\t\t\t}\n\t\t\tthrow new Error(`Unsupported contentType ${currentDataField.contentType}`);\n\t\t}).filter((x) => x);\n\n\t\tconst attributesVar = `${bzId}-atts`;\n\n\t\tconst matchAttributes = listify(node, (k) => {\n\t\t\t// @ts-expect-error - TODO description\n\t\t\tif (k.startsWith('$') || k === idField) {\n\t\t\t\treturn '';\n\t\t\t}\n\t\t\t// if (k.startsWith('$') || !v) return '';\n\t\t\tconst currentDataField = currentSchema.dataFields?.find((x) => x.path === k);\n\t\t\t// console.log('currentDataField', currentDataField);\n\t\t\tconst fieldDbPath = currentDataField?.path;\n\n\t\t\tif (!fieldDbPath) {\n\t\t\t\t// throw new Error('noFieldDbPath');\n\t\t\t\treturn '';\n\t\t\t}\n\t\t\tconst dbField = currentDataField.dbPath;\n\n\t\t\treturn `{${attributesVar} isa ${dbField};}`;\n\t\t}).filter((x) => x);\n\n\t\tconst isLocalId: boolean = node[Symbol.for('isLocalId') as any]; /// this are local ids that are ony used to define links between stuff but that are not in the db (the \"all-xxx\" ids)\n\n\t\tconst idValueTQL = isArray(idValue) ? `like '${idValue.join('|')}'` : `'${idValue}'`;\n\t\tconst idAttributes =\n\t\t\t!isLocalId && idValue // it must have id values, and they must be realDBIds\n\t\t\t\t? // if it is a relation, add only the id fields in the lines where we add the roles also so it does not get defined twice\n\t\t\t\t [`has ${idField} ${idValueTQL}`]\n\t\t\t\t: [];\n\n\t\tconst allAttributes = [...idAttributes, ...attributes].filter((x) => x).join(',');\n\n\t\tconst getDeletionMatchInNodes = () => {\n\t\t\t// if (node.$tempId) return ''; /// commented because we need tempIds to work when replacing a unlink/link all operation\n\t\t\t// todo: ensure parents belong to grandparents. [https://github.com/Blitzapps/blitz/issues/9]\n\t\t\tif (op === 'delete' || op === 'unlink' || op === 'match') {\n\t\t\t\treturn `${bzId} isa ${[thingDbPath, ...idAttributes].filter((x) => x).join(',')};`;\n\t\t\t}\n\t\t\tif (op === 'update') {\n\t\t\t\tif (!matchAttributes.length) {\n\t\t\t\t\tthrow new Error('update without attributes');\n\t\t\t\t}\n\t\t\t\treturn `${bzId} isa ${[thingDbPath, ...idAttributes].filter((x) => x).join(',')}, has ${attributesVar};\n ${matchAttributes.join(' or ')};`;\n\t\t\t}\n\t\t\treturn '';\n\t\t};\n\n\t\tconst getInsertionMatchInNodes = () => {\n\t\t\t// todo: ensure parents belong to grandparents. [https://github.com/Blitzapps/blitz/issues/9]\n\t\t\t// if (node.$tempId) return ''; /// same as getDeletionMatch\n\t\t\tif (op === 'update' || op === 'link' || op === 'match') {\n\t\t\t\treturn `${bzId} isa ${[thingDbPath, ...idAttributes].filter((x) => x).join(',')};`;\n\t\t\t}\n\t\t\treturn '';\n\t\t};\n\n\t\tif (node.$entity || node.$relation) {\n\t\t\treturn {\n\t\t\t\top,\n\t\t\t\tdeletionMatch: getDeletionMatchInNodes(),\n\t\t\t\tinsertionMatch: getInsertionMatchInNodes(),\n\t\t\t\tinsertion:\n\t\t\t\t\top === 'create'\n\t\t\t\t\t\t? `${bzId} isa ${[thingDbPath, allAttributes].filter((x) => x).join(',')};`\n\t\t\t\t\t\t: op === 'update' && attributes.length\n\t\t\t\t\t\t? `${bzId} ${attributes.join(',')};`\n\t\t\t\t\t\t: '',\n\t\t\t\tdeletion:\n\t\t\t\t\top === 'delete'\n\t\t\t\t\t\t? `${bzId} isa ${thingDbPath};`\n\t\t\t\t\t\t: op === 'update' && matchAttributes.length\n\t\t\t\t\t\t? `${bzId} has ${attributesVar};`\n\t\t\t\t\t\t: '',\n\t\t\t};\n\t\t}\n\n\t\tthrow new Error('in attributes');\n\t};\n\n\tconst edgeToTypeQL = (\n\t\tnode: BQLMutationBlock,\n\t): {\n\t\tpreDeletionBatch?: any[];\n\t\tdeletionMatch?: string;\n\t\tinsertionMatch?: string;\n\t\tdeletion?: string;\n\t\tinsertion?: string;\n\t\top: string;\n\t} => {\n\t\tconst op = node.$op as string;\n\t\tconst currentSchema = getCurrentSchema(schema, node);\n\t\tconst bzId = `$${node.$bzId}`;\n\t\tconst idValue = node.$id;\n\n\t\tconst relationDbPath = currentSchema.defaultDBConnector?.path || node.$relation;\n\n\t\tconst roleFields = 'roles' in currentSchema ? listify(currentSchema.roles, (k) => k) : [];\n\n\t\tconst roleDbPaths =\n\t\t\tnode.$relation &&\n\t\t\t'roles' in currentSchema &&\n\t\t\tmapEntries(currentSchema.roles, (k, v) => [k, v.dbConnector?.path || k]);\n\n\t\t// roles can be specified in three ways, either they are a roleField in the node, they are the children of something, or they have a default/computed link\n\t\t// 1) roleFields\n\n\t\tconst fromRoleFields = listify(node, (k: string, v) => {\n\t\t\tif (!roleFields.includes(k)) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (!('roles' in currentSchema)) {\n\t\t\t\tthrow new Error('This should have roles! ');\n\t\t\t}\n\t\t\tconst roleDbPath = roleDbPaths[k];\n\t\t\tif (Array.isArray(v)) {\n\t\t\t\treturn v.map((x) => ({ path: roleDbPath, id: x }));\n\t\t\t}\n\t\t\treturn { path: roleDbPath, id: v };\n\t\t})\n\t\t\t.filter((x) => x)\n\t\t\t.flat();\n\n\t\t/// if one of the roles's id is undefined it means it applies to every object of that thingType so we need to create an id for it\n\t\tconst fromRoleFieldsTql = fromRoleFields.map((x) => {\n\t\t\tif (!x?.path) {\n\t\t\t\tthrow new Error('Object without path');\n\t\t\t}\n\t\t\treturn `${x.path}: $${x.id}`;\n\t\t});\n\n\t\tconst roles = fromRoleFields.length > 0 ? `( ${fromRoleFieldsTql.join(' , ')} )` : '';\n\n\t\t// console.log('roles', roles);\n\n\t\tconst relationTql = !roles\n\t\t\t? ''\n\t\t\t: `${bzId} ${roles} ${\n\t\t\t\t\tnode[Symbol.for('edgeType') as any] === 'linkField' || op === 'delete' || op === 'unlink'\n\t\t\t\t\t\t? `isa ${relationDbPath}`\n\t\t\t\t\t\t: ''\n\t\t\t }`;\n\n\t\tconst relationTqlWithoutRoles = `${bzId} ${\n\t\t\tnode[Symbol.for('edgeType') as any] === 'linkField' || op === 'delete' ? `isa ${relationDbPath}` : ''\n\t\t}`;\n\n\t\tconst getInsertionsInEdges = () => {\n\t\t\tif (!relationTql) {\n\t\t\t\treturn '';\n\t\t\t}\n\t\t\tif (op === 'link') {\n\t\t\t\treturn `${relationTql};`;\n\t\t\t}\n\t\t\tif (op === 'create') {\n\t\t\t\treturn `${relationTql}, has id '${idValue}';`;\n\t\t\t}\n\t\t\treturn '';\n\t\t};\n\n\t\tconst getInsertionMatchInEdges = () => {\n\t\t\tif (!relationTql) {\n\t\t\t\treturn '';\n\t\t\t}\n\t\t\t// if (op === 'link') return `${relationTql};`;\n\t\t\t// if (op === 'create') return `${relationTqlWithoutRoles};`;\n\t\t\tif (op === 'match') {\n\t\t\t\treturn `${relationTql};`;\n\t\t\t}\n\t\t\treturn '';\n\t\t};\n\n\t\tconst getDeletionMatchInEdges = () => {\n\t\t\tif (!relationTql) {\n\t\t\t\treturn '';\n\t\t\t}\n\t\t\t/// edge delete: we are removing an automatic relation\n\t\t\tif (op === 'delete') {\n\t\t\t\treturn `${relationTql};`;\n\t\t\t}\n\t\t\t/// edge unlink means: We are editing a real relation's roles\n\t\t\tif (op === 'unlink') {\n\t\t\t\t/* return `${bzId} ($roles-${node.$bzId}: $players-${node.$bzId}) isa ${relationDbPath}; ${fromRoleFields\n .map((role) => `{$roles-${node.$bzId} type ${relationDbPath}:${role?.path};}`)\n .join(` or `)};`; */\n\t\t\t\t/// unlinking more than one role is not supported yet\n\t\t\t\t/// this got commented as the match brings what is needed but will probably need a refacto\n\t\t\t\t/// this is coded as generating a match block in [parseBQLmutation.ts], toEdges(edgeType1)\n\t\t\t\t// return `${bzId} ${roles} isa ${relationDbPath};`;\n\t\t\t}\n\t\t\tif (op === 'match') {\n\t\t\t\treturn `${relationTql};`;\n\t\t\t}\n\t\t\treturn '';\n\t\t};\n\n\t\tconst getDeletionsInEdges = () => {\n\t\t\tif (!relationTql) {\n\t\t\t\treturn '';\n\t\t\t}\n\t\t\t// todo: same as insertions, better manage the ids here\n\t\t\tif (op === 'delete') {\n\t\t\t\treturn `${relationTqlWithoutRoles};`;\n\t\t\t}\n\t\t\tif (op === 'unlink') {\n\t\t\t\treturn `${bzId} ${roles};`;\n\t\t\t}\n\t\t\t// if (op === 'unlink') return `${bzId} ($roles-${node.$bzId}: $players-${node.$bzId});`;\n\t\t\treturn '';\n\t\t};\n\n\t\t/* const getPreDeletionBatch = () => {\n if (op === 'unlink') {\n return fromRoleFields\n .filter((y) => y)\n .map((x) => {\n return {\n match: `${bzId} (${x?.path}: $${x?.id}) isa ${relationDbPath};`,\n deletion: `${bzId} (${x?.path}: $${x?.id}) ${\n node[Symbol.for('edgeType') as any] === 'linkField' ? `isa ${relationDbPath}` : ''\n }`,\n };\n });\n }\n return [];\n }; */\n\n\t\treturn {\n\t\t\t// preDeletionBatch: getPreDeletionBatch(),\n\t\t\tdeletionMatch: getDeletionMatchInEdges(),\n\t\t\tinsertionMatch: getInsertionMatchInEdges(),\n\t\t\tdeletion: getDeletionsInEdges(),\n\t\t\tinsertion: getInsertionsInEdges(),\n\t\t\top: '',\n\t\t};\n\t};\n\n\tconst toTypeQL = (\n\t\tnodes: BQLMutationBlock[] | BQLMutationBlock,\n\t\tmode?: 'nodes' | 'edges',\n\t):\n\t\t| {\n\t\t\t\tpreDeletionBatch?: any[];\n\t\t\t\tinsertionMatch?: string;\n\t\t\t\tdeletionMatch?: string;\n\t\t\t\tinsertion?: string;\n\t\t\t\tdeletion?: string;\n\t\t }[]\n\t\t| {\n\t\t\t\tpreDeletionBatch?: any[];\n\t\t\t\tinsertionMatch?: string;\n\t\t\t\tdeletionMatch?: string;\n\t\t\t\tinsertion?: string;\n\t\t\t\tdeletion?: string;\n\t\t } => {\n\t\tconst typeQL = mode === 'edges' ? edgeToTypeQL : nodeToTypeQL;\n\n\t\tif (Array.isArray(nodes)) {\n\t\t\treturn nodes\n\t\t\t\t.map((x) => {\n\t\t\t\t\tconst { preDeletionBatch, insertionMatch, deletionMatch, insertion, deletion } = typeQL(x);\n\t\t\t\t\treturn shake({ preDeletionBatch, insertionMatch, deletionMatch, insertion, deletion }, (z) => !z); /// ! WARNING: falsy values are removed (0, \"\", etc)\n\t\t\t\t})\n\t\t\t\t.filter((y) => y);\n\t\t}\n\t\tconst { preDeletionBatch, insertionMatch, deletionMatch, insertion, deletion } = typeQL(nodes);\n\n\t\treturn shake({ preDeletionBatch, insertionMatch, deletionMatch, insertion, deletion }, (z) => !z); /// ! WARNING: falsy values are removed (0, \"\", etc)\n\t};\n\n\t// const thingStreams = thingsWithOps.map((x) => toTypeQL([...x.thingDependencies, ...x.edgeDependencies]));\n\t// const edgeStreams = edgesWithOps.map((x) => toTypeQL([...x.thingDependencies, ...x.edgeDependencies], 'edges'));\n\n\t// console.log('thingStreams', JSON.stringify(thingStreams, null, 3));\n\t// console.log('edgeStreams', edgeStreams);\n\n\tconst nodeOperations = toTypeQL(mutation.things);\n\tconst arrayNodeOperations = Array.isArray(nodeOperations) ? nodeOperations : [nodeOperations];\n\tconst edgeOperations = toTypeQL(mutation.edges, 'edges');\n\tconst arrayEdgeOperations = Array.isArray(edgeOperations) ? edgeOperations : [edgeOperations];\n\t// console.log('nodeOperations', nodeOperations);\n\t// console.log('edgeOperations', edgeOperations);\n\n\tconst allOperations = [...arrayNodeOperations, ...arrayEdgeOperations];\n\t// console.log('allOperations', allOperations);\n\n\t// todo: split BQL mutation in N DBstreams per DB\n\t// todo: then pack them per DB,\n\t// const dbHandleList = config.dbConnectors.map((x) => x.id);\n\n\t// const creations = [];\n\n\tconst tqlRequest = shake(\n\t\t{\n\t\t\t// preDeletionBatch: allOperations.flatMap((x) => x.preDeletionBatch).filter((y) => y !== undefined),\n\t\t\tinsertionMatches: allOperations\n\t\t\t\t.map((x) => x.insertionMatch)\n\t\t\t\t.join(' ')\n\t\t\t\t.trim(),\n\t\t\tdeletionMatches: allOperations\n\t\t\t\t.map((x) => x.deletionMatch)\n\t\t\t\t.join(' ')\n\t\t\t\t.trim(),\n\t\t\tinsertions: allOperations\n\t\t\t\t.map((x) => x.insertion)\n\t\t\t\t.join(' ')\n\t\t\t\t.trim(),\n\t\t\tdeletions: allOperations\n\t\t\t\t.map((x) => x.deletion)\n\t\t\t\t.join(' ')\n\t\t\t\t.trim(),\n\t\t\t// ...(typeQLRelations?.length && { relations: typeQLRelations }),\n\t\t},\n\t\t(x) => !x,\n\t);\n\treq.tqlRequest = tqlRequest;\n};\n","import { produce, current } from 'immer';\nimport type { TraversalCallbackContext } from 'object-traversal';\nimport { traverse, getNodeByPath } from 'object-traversal';\nimport { isObject, listify, shake } from 'radash';\nimport { v4 as uuidv4 } from 'uuid';\n\nimport { getCurrentFields, getCurrentSchema, oFind } from '../../helpers';\nimport type {\n\tBQLMutationBlock,\n\tEnrichedBormRelation,\n\tEnrichedDataField,\n\tEnrichedLinkField,\n\tEnrichedRoleField,\n\tFilledBQLMutationBlock,\n} from '../../types';\nimport type { PipelineOperation } from '../pipeline';\nimport { compute } from '../../engine/compute';\n\n// parseBQLQueryObjectives:\n// 1) Validate the query (getRawBQLQuery)\n// 2) Prepare it in a universally way for any DB (output an enrichedBQLQuery)\n\nconst sanitizeTempId = (id: string): string => {\n\t// Ensure the string starts with \"_:\"\n\tif (!id.startsWith('_:')) {\n\t\tthrow new Error(\"ID must start with '_:'.\");\n\t}\n\n\t// Remove the prefix \"_:\" for further validation\n\tconst sanitizedId = id.substring(2);\n\n\t// Ensure there are no symbols (only alphanumeric characters, hyphens, and underscores)\n\tif (!/^[a-zA-Z0-9-_]+$/.test(sanitizedId)) {\n\t\tthrow new Error('$tempId must contain only alphanumeric characters, hyphens, and underscores.');\n\t}\n\n\t// Ensure the ID is no longer than 36 characters (including the \"_:\" prefix)\n\tif (id.length > 36) {\n\t\tthrow new Error('$tempId must not be longer than 36 characters.');\n\t}\n\n\treturn sanitizedId;\n};\n\nexport const fillBQLMutation: PipelineOperation = async (req) => {\n\tconst { rawBqlRequest, schema } = req;\n\n\t// STEP 1, remove undefined stuff and sanitize tempIds\n\tconst shakeBqlRequest = (blocks: BQLMutationBlock | BQLMutationBlock[]): BQLMutationBlock | BQLMutationBlock[] => {\n\t\treturn produce(blocks, (draft) =>\n\t\t\ttraverse(draft, ({ value: val, key, parent }: TraversalCallbackContext) => {\n\t\t\t\tif (isObject(val)) {\n\t\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\t\tval = shake(val, (att) => att === undefined);\n\t\t\t\t}\n\t\t\t\tif (key === '$tempId') {\n\t\t\t\t\t// @ts-expect-error - TODO description\n\t\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\t\tparent[key] = sanitizeTempId(val);\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\t};\n\n\tconst shakedBqlRequest = shakeBqlRequest(rawBqlRequest);\n\n\t// console.log('shakedBqlRequest', JSON.stringify(shakedBqlRequest, null, 3));\n\n\tconst stringToObjects = (blocks: BQLMutationBlock | BQLMutationBlock[]): BQLMutationBlock | BQLMutationBlock[] => {\n\t\treturn produce(blocks, (draft) =>\n\t\t\ttraverse(draft, ({ value: val, meta, key }: TraversalCallbackContext) => {\n\t\t\t\tif (isObject(val)) {\n\t\t\t\t\t// <---------------mutating all objects---------------->\n\t\t\t\t\t// @ts-expect-error - TODO description\n\t\t\t\t\tif (val.$arrayOp) {\n\t\t\t\t\t\tthrow new Error('Array op not supported yet');\n\t\t\t\t\t}\n\t\t\t\t\t/// ignore filters. In the future maybe transform the shortcuts of filters here (like $eq being a default)\n\t\t\t\t\tif (key === '$filter' || meta.nodePath?.includes('.$filter.')) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst value = val as BQLMutationBlock; /// removing undefined values, nulls are no shaked as they are used to delete fields\n\n\t\t\t\t\tif (value.$op === 'create' && value.$id) {\n\t\t\t\t\t\tthrow new Error(\"Can't write to computed field $id. Try writing to the id field directly.\");\n\t\t\t\t\t}\n\t\t\t\t\t// console.log('<---------------------value', isDraft(value) ? current(value) : value);\n\n\t\t\t\t\tconst currentSchema = getCurrentSchema(schema, value);\n\n\t\t\t\t\tconst nodePathArray = meta.nodePath?.split('.');\n\n\t\t\t\t\tconst notRoot = nodePathArray?.filter((x) => Number.isNaN(parseInt(x, 10))).join('.');\n\n\t\t\t\t\tif (!currentSchema) {\n\t\t\t\t\t\tthrow new Error(`Schema not found for ${value.$entity || value.$relation}`);\n\t\t\t\t\t}\n\n\t\t\t\t\tvalue.$bzId = value.$tempId ?? `T_${uuidv4()}`;\n\n\t\t\t\t\tvalue[Symbol.for('schema') as any] = currentSchema;\n\t\t\t\t\tvalue[Symbol.for('dbId') as any] = currentSchema.defaultDBConnector.id;\n\n\t\t\t\t\tconst { usedLinkFields, usedRoleFields } = getCurrentFields(currentSchema, value);\n\n\t\t\t\t\ttype RoleFieldMap = {\n\t\t\t\t\t\tfieldType: 'roleField';\n\t\t\t\t\t\tpath: string;\n\t\t\t\t\t\tschema: EnrichedRoleField;\n\t\t\t\t\t};\n\n\t\t\t\t\ttype LinkFieldMap = {\n\t\t\t\t\t\tfieldType: 'linkField';\n\t\t\t\t\t\tpath: string;\n\t\t\t\t\t\tschema: EnrichedLinkField;\n\t\t\t\t\t};\n\n\t\t\t\t\tconst usedLinkFieldsMap = usedLinkFields.map(\n\t\t\t\t\t\t(linkFieldPath): LinkFieldMap => ({\n\t\t\t\t\t\t\tfieldType: 'linkField',\n\t\t\t\t\t\t\tpath: linkFieldPath,\n\t\t\t\t\t\t\t// @ts-expect-error - TODO description\n\t\t\t\t\t\t\tschema: currentSchema.linkFields.find((y) => y.path === linkFieldPath),\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\n\t\t\t\t\tconst usedRoleFieldsMap =\n\t\t\t\t\t\tcurrentSchema.thingType === 'relation'\n\t\t\t\t\t\t\t? usedRoleFields.map(\n\t\t\t\t\t\t\t\t\t(roleFieldPath): RoleFieldMap => ({\n\t\t\t\t\t\t\t\t\t\tfieldType: 'roleField',\n\t\t\t\t\t\t\t\t\t\tpath: roleFieldPath,\n\t\t\t\t\t\t\t\t\t\tschema: oFind(currentSchema.roles, (k) => k === roleFieldPath) as EnrichedRoleField,\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t: [];\n\n\t\t\t\t\t/// validations\n\t\t\t\t\t/// If the current value uses at least one linkfield with target === 'role' and at least another field with target === 'relation', throw an unsupported (yet) error\n\t\t\t\t\tif (\n\t\t\t\t\t\tusedLinkFieldsMap.some((x) => x.schema?.target === 'role') &&\n\t\t\t\t\t\tusedLinkFieldsMap.some((x) => x.schema?.target === 'relation')\n\t\t\t\t\t) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\"Unsupported: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.\",\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\t/// multiple possible things in a role\n\t\t\t\t\tconst multiplayedRoles = usedRoleFieldsMap.filter(\n\t\t\t\t\t\t(roleField) => [...new Set(roleField.schema.playedBy?.map((x) => x.thing))].length !== 1,\n\t\t\t\t\t);\n\n\t\t\t\t\tif (multiplayedRoles.length > 1) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Field: ${\n\t\t\t\t\t\t\t\tmultiplayedRoles[0].path\n\t\t\t\t\t\t\t} - If a role can be played by multiple things, you must specify the thing in the mutation: ${JSON.stringify(\n\t\t\t\t\t\t\t\tmultiplayedRoles[0].schema.playedBy,\n\t\t\t\t\t\t\t)}. Schema: ${JSON.stringify(multiplayedRoles[0].schema)}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\tconst currentPath = meta.nodePath;\n\n\t\t\t\t\t/// <---------------mutating children objects ---------------->\n\t\t\t\t\t[...usedLinkFieldsMap, ...usedRoleFieldsMap]?.forEach((currentField) => {\n\t\t\t\t\t\tconst currentValue = value[currentField.path];\n\n\t\t\t\t\t\t/// ignore undefined\n\t\t\t\t\t\tif (currentValue === undefined) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// console.log(':::', { currentField });\n\n\t\t\t\t\t\tconst currentFieldSchema = currentField.schema;\n\n\t\t\t\t\t\tif (!currentFieldSchema) {\n\t\t\t\t\t\t\tthrow new Error(`Field ${currentField.path} not found in schema`);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst currentEdgeSchema =\n\t\t\t\t\t\t\t// @ts-expect-error - TODO description\n\t\t\t\t\t\t\tcurrentField.fieldType === 'roleField' ? currentFieldSchema?.playedBy[0] : currentFieldSchema;\n\n\t\t\t\t\t\tconst getCurrentRelation = () => {\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\tcurrentFieldSchema &&\n\t\t\t\t\t\t\t\t'relation' in currentFieldSchema &&\n\t\t\t\t\t\t\t\tcurrentEdgeSchema?.relation === value.$relation\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\treturn '$self';\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (currentEdgeSchema?.relation) {\n\t\t\t\t\t\t\t\treturn currentEdgeSchema?.relation;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn '$self';\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tconst relation = getCurrentRelation();\n\t\t\t\t\t\tconst relationSchema =\n\t\t\t\t\t\t\trelation === '$self' ? (currentSchema as EnrichedBormRelation) : schema.relations[relation];\n\n\t\t\t\t\t\t// console.log('relationSchema', relationSchema);\n\n\t\t\t\t\t\tconst currentFieldRole = oFind(relationSchema.roles, (k, _v) => k === currentField.path);\n\n\t\t\t\t\t\t// console.log('currentFieldRole', currentFieldRole);\n\n\t\t\t\t\t\tif (currentFieldRole?.playedBy?.length === 0) {\n\t\t\t\t\t\t\tthrow new Error(`unused role: ${currentPath}.${currentField.path}`);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t/// <-- VALIDATIONS -->\n\t\t\t\t\t\tif (!currentFieldSchema) {\n\t\t\t\t\t\t\tthrow new Error(`Field ${currentField.path} not found in schema`);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst oppositeFields =\n\t\t\t\t\t\t\tcurrentField.fieldType === 'linkField'\n\t\t\t\t\t\t\t\t? (currentFieldSchema as EnrichedLinkField)?.oppositeLinkFieldsPlayedBy\n\t\t\t\t\t\t\t\t: (currentFieldSchema as EnrichedRoleField)?.playedBy;\n\n\t\t\t\t\t\tif (!oppositeFields) {\n\t\t\t\t\t\t\tthrow new Error(`No opposite fields found for ${JSON.stringify(currentFieldSchema)}`);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif ([...new Set(oppositeFields?.map((x) => x.thing))].length > 1) {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t`Field: ${\n\t\t\t\t\t\t\t\t\tcurrentField.path\n\t\t\t\t\t\t\t\t} - If a role can be played by multiple things, you must specify the thing in the mutation: ${JSON.stringify(\n\t\t\t\t\t\t\t\t\toppositeFields,\n\t\t\t\t\t\t\t\t)}. Schema: ${JSON.stringify(currentFieldSchema)}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (currentFieldSchema.cardinality === 'ONE') {\n\t\t\t\t\t\t\tif (Array.isArray(currentValue)) {\n\t\t\t\t\t\t\t\tthrow new Error(\"Can't have an array in a cardinality === ONE link field\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// if is only one object, current is not a create, and the object has no op, throw error\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// cardinality many are always arrays, unless it's an object that specifies an arrayOp like\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tcurrentFieldSchema.cardinality === 'MANY' &&\n\t\t\t\t\t\t\tcurrentValue !== null &&\n\t\t\t\t\t\t\t!Array.isArray(currentValue) &&\n\t\t\t\t\t\t\t!currentValue.$arrayOp\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t`${\n\t\t\t\t\t\t\t\t\t// @ts-expect-error - TODO description\n\t\t\t\t\t\t\t\t\tcurrentField.fieldType === 'linkField' ? currentFieldSchema.path : currentFieldSchema.name\n\t\t\t\t\t\t\t\t} is a cardinality === MANY thing. Use an array or a $arrayOp object`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// ignore those properly configured. Todo: migrate to $thing\n\t\t\t\t\t\tif (currentValue?.$entity || currentValue?.$relation) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst [childrenLinkField] = oppositeFields;\n\n\t\t\t\t\t\t/// now we have the parent, so we can add the dependencies\n\t\t\t\t\t\t// const parentMeta = value[Symbol.for('parent') as any];\n\t\t\t\t\t\t// const parentPath = parentMeta.path;\n\t\t\t\t\t\t// const parentNode = !parentPath ? blocks : getNodeByPath(blocks, parentPath);\n\n\t\t\t\t\t\t/// this is the child object, so these Symbol.for... don't belong to the current node\n\n\t\t\t\t\t\tconst currentFieldType = 'plays' in currentFieldSchema ? 'linkField' : 'roleField';\n\t\t\t\t\t\tconst childrenThingObj = {\n\t\t\t\t\t\t\t[`$${childrenLinkField.thingType}`]: childrenLinkField.thing,\n\t\t\t\t\t\t\t[Symbol.for('relation') as any]: relation,\n\t\t\t\t\t\t\t[Symbol.for('edgeType') as any]: currentFieldType,\n\t\t\t\t\t\t\t[Symbol.for('parent') as any]: {\n\t\t\t\t\t\t\t\tpath: currentPath,\n\t\t\t\t\t\t\t\t...(value.$id ? { $id: value.$id } : {}),\n\t\t\t\t\t\t\t\t...(value.$tempId ? { $tempId: value.$tempId } : {}),\n\t\t\t\t\t\t\t\t...(value.filter ? { filter: value.filter } : {}),\n\t\t\t\t\t\t\t\tlinks: oppositeFields,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t[Symbol.for('role') as any]: childrenLinkField.plays, // this is the currentChildren\n\t\t\t\t\t\t\t// this is the parent\n\t\t\t\t\t\t\t[Symbol.for('oppositeRole') as any]: 'plays' in currentFieldSchema ? currentFieldSchema.plays : undefined, // todo\n\t\t\t\t\t\t\t[Symbol.for('relFieldSchema') as any]: currentFieldSchema,\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\t// console.log('childrenThingObj', childrenThingObj);\n\n\t\t\t\t\t\tif (isObject(currentValue)) {\n\t\t\t\t\t\t\t/// probably here we are missing some link + update data for instance (the update data)\n\t\t\t\t\t\t\t// todo: for that reason it could be a good idea to send the other object as a thing outside?\n\t\t\t\t\t\t\t// todo: Another alternative could be to send the full object and treat this later\n\n\t\t\t\t\t\t\tvalue[currentField.path] = {\n\t\t\t\t\t\t\t\t...childrenThingObj,\n\t\t\t\t\t\t\t\t...currentValue,\n\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\t// console.log('[obj]value', value[field as string]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// todo: this does not allow the case accounts: ['id1','id2',{$tempId:'temp1'}] ideally tempIds should have some indicator like :_temp1 later so we can do ['id1','id2',':_tempid'] instead\n\n\t\t\t\t\t\t/// we already know it's 'MANY'\n\t\t\t\t\t\tif (Array.isArray(currentValue)) {\n\t\t\t\t\t\t\t// todo: check for arrays that are values and not vectors\n\t\t\t\t\t\t\tif (currentValue.every((x) => isObject(x))) {\n\t\t\t\t\t\t\t\tvalue[currentField.path] = currentValue.map((y) => {\n\t\t\t\t\t\t\t\t\t/// when a tempId is specified, in a relation, same as with $id, is a link by default\n\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t...childrenThingObj,\n\t\t\t\t\t\t\t\t\t\t...y,\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t// console.log('[obj-arr]value', value[field as string]);\n\t\t\t\t\t\t\t} else if (currentValue.every((x) => typeof x === 'string')) {\n\t\t\t\t\t\t\t\tvalue[currentField.path] = currentValue.map((y) => ({\n\t\t\t\t\t\t\t\t\t...childrenThingObj,\n\t\t\t\t\t\t\t\t\t$op: value.$op === 'create' ? 'link' : 'replace',\n\t\t\t\t\t\t\t\t\t$id: y,\n\t\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tthrow new Error(`Invalid array value for ${currentField.path}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t/// we already know it's 'ONE'\n\t\t\t\t\t\tif (typeof currentValue === 'string') {\n\t\t\t\t\t\t\tvalue[currentField.path] = {\n\t\t\t\t\t\t\t\t...childrenThingObj,\n\t\t\t\t\t\t\t\t$op: value.$op === 'create' ? 'link' : 'replace', // if the parent is being created, then is not a replace, is a new link\n\t\t\t\t\t\t\t\t$id: currentValue, // todo: now all strings are ids and not tempIds, but in the future this might change\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t/// can be both MANY or ONE\n\t\t\t\t\t\tif (currentValue === null) {\n\t\t\t\t\t\t\tconst neutralObject = {\n\t\t\t\t\t\t\t\t...childrenThingObj,\n\t\t\t\t\t\t\t\t$op: 'unlink', // todo: embedded => delete\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tvalue[currentField.path] = currentFieldSchema.cardinality === 'MANY' ? [neutralObject] : neutralObject;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\t\t// console.log('value', current(value));\n\n\t\t\t\t\tif (!notRoot && !value.$entity && !value.$relation) {\n\t\t\t\t\t\tthrow new Error('Root things must specify $entity or $relation');\n\t\t\t\t\t}\n\t\t\t\t\tif (!notRoot) {\n\t\t\t\t\t\t// no need to do nothing with root objects or objects that already\n\t\t\t\t\t}\n\t\t\t\t\t// we will get the $entity/$relation of the nonRoot that don't have it\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\t};\n\n\tconst withObjects = stringToObjects(shakedBqlRequest);\n\t// console.log('withObjects', withObjects);\n\n\tconst fill = (blocks: BQLMutationBlock | BQLMutationBlock[]): FilledBQLMutationBlock | FilledBQLMutationBlock[] => {\n\t\t// @ts-expect-error - TODO description\n\t\treturn produce(blocks, (draft) =>\n\t\t\ttraverse(draft, ({ parent, key, value: val, meta }: TraversalCallbackContext) => {\n\t\t\t\tif (isObject(val)) {\n\t\t\t\t\tif (Object.keys(val).length === 0) {\n\t\t\t\t\t\tthrow new Error('Empty object!');\n\t\t\t\t\t}\n\t\t\t\t\tif (key === '$filter' || meta.nodePath?.includes('.$filter.')) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst value = val as BQLMutationBlock;\n\t\t\t\t\t// console.log('value', value);\n\t\t\t\t\t// const currentTempId = value.$tempId || uuuiidv4();\n\n\t\t\t\t\tconst nodePathArray = meta.nodePath?.split('.');\n\n\t\t\t\t\t///nodes with tempId require always an op because we can't know if it is a create or an update\n\t\t\t\t\tif (value.$tempId) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t!(value.$op === undefined || value.$op === 'link' || value.$op === 'create' || value.$op === 'update')\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t`Invalid op ${value.$op} for tempId. TempIds can be created, or when created in another part of the same mutation. In the future maybe we can use them to catch stuff in the DB as well and group them under the same tempId.`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tconst notRoot = nodePathArray?.filter((x) => Number.isNaN(parseInt(x, 10))).join('.');\n\n\t\t\t\t\tconst currentPath = !notRoot\n\t\t\t\t\t\t? meta.nodePath || '' /// keep the number in the root or set to root ''\n\t\t\t\t\t\t: Array.isArray(parent)\n\t\t\t\t\t\t? nodePathArray?.slice(0, -1).join('.')\n\t\t\t\t\t\t: meta.nodePath;\n\n\t\t\t\t\tconst currentSchema = getCurrentSchema(schema, value);\n\t\t\t\t\t// todo:\n\t\t\t\t\tconst { unidentifiedFields, dataFields, roleFields, linkFields } = getCurrentFields(currentSchema, value);\n\n\t\t\t\t\t/// get parent node\n\t\t\t\t\tconst parentMeta = current(value)[Symbol.for('parent') as any];\n\t\t\t\t\tconst parentPath = notRoot && parentMeta.path;\n\t\t\t\t\tconst parentNode = !parentPath ? draft : getNodeByPath(draft, parentPath); /// draft instead of blocks as the $op is computed\n\t\t\t\t\tconst parentOp = parentNode?.$op;\n\n\t\t\t\t\tif (notRoot && !parentOp) {\n\t\t\t\t\t\tthrow new Error('Error: Parent $op not detected');\n\t\t\t\t\t}\n\n\t\t\t\t\tconst currentFieldSchema = value[Symbol.for('relFieldSchema') as any];\n\n\t\t\t\t\t// todo: move the getOp logic to the first traverse of the fill so that the $op is available\n\t\t\t\t\t// We are doing something twice from the former traverse\n\t\t\t\t\tif (value.$op === 'replace') {\n\t\t\t\t\t\tif (parentOp === 'create') {\n\t\t\t\t\t\t\tvalue.$op = 'link';\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// console.log('currentValue', isDraft(value) ? current(value) : value);\n\n\t\t\t\t\tconst hasUpdatedDataFields = Object.keys(value).some((x) => dataFields?.includes(x));\n\n\t\t\t\t\tconst hasUpdatedChildren = Object.keys(value).some((x) => [...roleFields, ...linkFields]?.includes(x));\n\t\t\t\t\tconst getOp = () => {\n\t\t\t\t\t\tif (value.$op) {\n\t\t\t\t\t\t\treturn value.$op;\n\t\t\t\t\t\t} // if there is an op, then thats the one\n\t\t\t\t\t\t/// nested objects are create by default, unless is too ambiguous\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tnotRoot &&\n\t\t\t\t\t\t\t!value.$id &&\n\t\t\t\t\t\t\t!value.$tempId &&\n\t\t\t\t\t\t\tparentOp !== 'create' &&\n\t\t\t\t\t\t\tcurrentFieldSchema.cardinality === 'ONE'\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tthrow new Error(`Please specify if it is a create or an update. Path: ${meta.nodePath}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (value.$tempId) {\n\t\t\t\t\t\t\treturn 'create';\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// todo: can move these to the first level traversal\n\t\t\t\t\t\tif ((value.$id || value.$filter) && hasUpdatedDataFields) {\n\t\t\t\t\t\t\treturn 'update';\n\t\t\t\t\t\t} // if there is an id or a filter, is an update. If it was a delete,it has been specified\n\t\t\t\t\t\tif ((value.$id || value.$filter) && notRoot && !hasUpdatedDataFields && !hasUpdatedChildren) {\n\t\t\t\t\t\t\treturn 'link';\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!value.$filter && !value.$id && !value.$tempId) {\n\t\t\t\t\t\t\treturn 'create';\n\t\t\t\t\t\t} // if it is not a delete, or an update, is a create (for this V0, missing link, unlink)\n\t\t\t\t\t\tif ((value.$id || value.$filter) && !hasUpdatedDataFields && hasUpdatedChildren) {\n\t\t\t\t\t\t\treturn 'match';\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthrow new Error('Wrong op');\n\t\t\t\t\t};\n\t\t\t\t\t// if (!value.$tempId && !value.$id) value.$tempId = currentTempId;\n\t\t\t\t\tif (!value.$op) {\n\t\t\t\t\t\tvalue.$op = getOp();\n\t\t\t\t\t}\n\t\t\t\t\tif (!parent) {\n\t\t\t\t\t\tvalue.$parentKey = '';\n\t\t\t\t\t} // root\n\n\t\t\t\t\t// console.log('value', current(value));\n\t\t\t\t\t// errors\n\t\t\t\t\t/* if (!(value.$id || value.$tempId || value.$filter) && ['delete', 'link', 'update'].includes(value.$op)) {\n throw new Error('Targeted operations (update, delete, link) require an $id or a $filter');\n } */\n\t\t\t\t\tif (typeof parent === 'object') {\n\t\t\t\t\t\t// spot rights conflicts\n\n\t\t\t\t\t\t// modify current\n\t\t\t\t\t\tconst ArParent = Array.isArray(parent);\n\t\t\t\t\t\tif (ArParent) {\n\t\t\t\t\t\t\tvalue[Symbol.for('index') as any] = key;\n\t\t\t\t\t\t} // nodePathArray.at(-1);\n\t\t\t\t\t\tvalue[Symbol.for('path') as any] = currentPath;\n\t\t\t\t\t\tvalue[Symbol.for('isRoot') as any] = !notRoot;\n\t\t\t\t\t\tvalue[Symbol.for('depth') as any] = notRoot?.split('.').length;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!value.$entity && !value.$relation) {\n\t\t\t\t\t\tthrow new Error(`Node ${JSON.stringify(value)} without $entity/$relation`);\n\t\t\t\t\t}\n\n\t\t\t\t\tconst { idFields, computedFields, virtualFields } = currentSchema;\n\t\t\t\t\t// todo: composite ids\n\t\t\t\t\tif (!idFields) {\n\t\t\t\t\t\tthrow new Error('No idFields found');\n\t\t\t\t\t}\n\t\t\t\t\tconst [idField] = idFields;\n\t\t\t\t\t// console.log('computedFields', computedFields);\n\n\t\t\t\t\tconst filledFields = listify(value, (attKey, v) => (v !== undefined ? attKey : undefined)) as string[];\n\t\t\t\t\t/// if at least one of the filled fields is virtual, then throw error\n\t\t\t\t\tconst virtualFilledFields = filledFields.filter((x) => virtualFields?.includes(x));\n\t\t\t\t\tif (virtualFilledFields.length > 0) {\n\t\t\t\t\t\tthrow new Error(`Virtual fields can't be sent to DB: \"${virtualFilledFields.join(',')}\"`);\n\t\t\t\t\t}\n\t\t\t\t\tconst missingComputedFields = computedFields.filter((x) => !filledFields.includes(x));\n\n\t\t\t\t\t// fill computed values\n\t\t\t\t\tmissingComputedFields.forEach((fieldPath) => {\n\t\t\t\t\t\t// console.log('fieldPath', fieldPath);\n\n\t\t\t\t\t\tconst currentFieldDef = currentSchema.dataFields?.find((x) => x.path === fieldPath);\n\t\t\t\t\t\tconst currentLinkDef = currentSchema.linkFields?.find((x) => x.path === fieldPath);\n\t\t\t\t\t\t// todo: multiple playedBy\n\t\t\t\t\t\tconst currentLinkedDef = currentLinkDef?.oppositeLinkFieldsPlayedBy[0];\n\n\t\t\t\t\t\tconst currentRoleDef =\n\t\t\t\t\t\t\t'roles' in currentSchema ? oFind(currentSchema.roles, (k, _v) => k === fieldPath) : undefined;\n\t\t\t\t\t\tconst currentDef = currentFieldDef || currentLinkedDef || currentRoleDef;\n\t\t\t\t\t\tif (!currentDef) {\n\t\t\t\t\t\t\tthrow new Error(`no field Def for ${fieldPath}`);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// We generate id fields when needed\n\t\t\t\t\t\tif (fieldPath === idField && value.$op === 'create' && !value[fieldPath]) {\n\t\t\t\t\t\t\tconst defaultValue = compute({\n\t\t\t\t\t\t\t\tcurrentThing: value,\n\t\t\t\t\t\t\t\tfieldSchema: currentDef as EnrichedDataField, //id is always a datafield.\n\t\t\t\t\t\t\t\tmandatoryDependencies: true, //can't send to db without every dependency being there\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tvalue[fieldPath] = defaultValue; // we already checked that this value has not been defined\n\t\t\t\t\t\t\t// value.$id = defaultValue; // op=create don't need $id anymore, they have $bzId\n\t\t\t\t\t\t\tvalue.$id = defaultValue;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\t\t/*\n\n // if a valid id is setup, move it to $id\n if (!value.$id) {\n if (value[idField]) {\n /// this is in creation when adding an id\n // value.$id = value[idField];\n } else {\n if (value.$op === 'create') {\n // throw new Error(`No id found for ${JSON.stringify(value)}`);\n }\n /// link, update, unlink or delete, without id, it gets a generic\n if (!value.$tempId) {\n // const localId = `all-${uuidv4()}`;\n // value.$tempId = tempId; No longer using this workaround, isLocalid is better\n // todo: probably $localId or Symbol.for(\"localId\") would be better to reuse $id 🤔\n // value.$id = localId; /// we also need to setup it as the $id for chained stuff\n /// we need to tag it as a nonDbid\n value[Symbol.for('isLocalId') as any] = true;\n }\n /// if value.$idTemp id nothing to change, it keeps the current tempId\n }\n } */\n\n\t\t\t\t\tif (unidentifiedFields.length > 0) {\n\t\t\t\t\t\tthrow new Error(`Unknown fields: [${unidentifiedFields.join(',')}] in ${JSON.stringify(value)}`);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\t};\n\n\tconst filledBQLMutation = fill(withObjects);\n\n\t// console.log('filledBQLMutation', JSON.stringify(filledBQLMutation, null, 3));\n\n\tif (Array.isArray(filledBQLMutation)) {\n\t\treq.filledBqlRequest = filledBQLMutation as FilledBQLMutationBlock[];\n\t} else {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\treq.filledBqlRequest = filledBQLMutation as FilledBQLMutationBlock;\n\t}\n};\n","import type { TraversalCallbackContext } from 'object-traversal';\nimport { getNodeByPath, traverse } from 'object-traversal';\nimport { isArray, isObject, mapEntries, pick, shake } from 'radash';\nimport { v4 as uuidv4 } from 'uuid';\n\nimport { oFilter, getCurrentFields, getCurrentSchema } from '../../helpers';\nimport type { BQLMutationBlock, FilledBQLMutationBlock } from '../../types';\nimport type { PipelineOperation } from '../pipeline';\n\nexport const parseBQLMutation: PipelineOperation = async (req) => {\n\tconst { filledBqlRequest, schema } = req;\n\n\tconst listNodes = (blocks: FilledBQLMutationBlock | FilledBQLMutationBlock[]) => {\n\t\t// todo: make immutable\n\n\t\tconst nodes: BQLMutationBlock[] = [];\n\t\tconst edges: BQLMutationBlock[] = [];\n\n\t\t/*\n function getIdsByPath(path: string) {\n const ids = nodes.filter((node) => node[Symbol.for('path') as any] === path).map((node) => node.id);\n return ids.length === 1 ? ids[0] : ids;\n } */\n\n\t\tconst getIdValue = (node: BQLMutationBlock) => {\n\t\t\tif (node.$id) {\n\t\t\t\treturn node.$id;\n\t\t\t}\n\n\t\t\tconst currentSchema = getCurrentSchema(schema, node);\n\t\t\tconst { idFields } = currentSchema;\n\n\t\t\tif (!idFields) {\n\t\t\t\tthrow new Error(`no idFields: ${JSON.stringify(node)}`);\n\t\t\t}\n\t\t\t// todo: composite ids\n\t\t\tconst [idField] = idFields;\n\t\t\tif (!idField) {\n\t\t\t\tthrow new Error(`no idField: ${JSON.stringify(node)}`);\n\t\t\t}\n\t\t\tconst idDataField = currentSchema.dataFields?.find((x) => x.path === idField);\n\t\t\tconst idDefaultValue = node.$op === 'create' ? idDataField?.default?.value() : null;\n\t\t\tconst idValue = node[idField] || node.$id || idDefaultValue;\n\n\t\t\tif (!idValue) {\n\t\t\t\tthrow new Error(`no idValue: ${JSON.stringify(node)}`);\n\t\t\t}\n\t\t\treturn idValue;\n\t\t};\n\n\t\tconst toNodes = (node: BQLMutationBlock) => {\n\t\t\tif (node.$op === 'create') {\n\t\t\t\tconst idValue = getIdValue(node);\n\n\t\t\t\tif (nodes.find((x) => x.$id === idValue)) {\n\t\t\t\t\tthrow new Error(`Duplicate id ${idValue} for node ${JSON.stringify(node)}`);\n\t\t\t\t}\n\t\t\t\tif (edges.find((x) => x.$bzId === node.$bzId)) {\n\t\t\t\t\tthrow new Error(`Duplicate $bzid ${node.$bzId} for node ${JSON.stringify(node)}`);\n\t\t\t\t}\n\t\t\t\tnodes.push({ ...node, $id: idValue });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (node.$tempId && node.$op === 'match') {\n\t\t\t\t/// we don't add to the node list, those that are being matched as they don't need to be matched in db and if they have a $tempId then it means... they are being created in the same query!\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tnodes.push(node);\n\t\t};\n\n\t\tconst toEdges = (edge: BQLMutationBlock) => {\n\t\t\tif (edge.$op === 'create') {\n\t\t\t\tconst idValue = getIdValue(edge);\n\n\t\t\t\tif (nodes.find((x) => x.$id === idValue)) {\n\t\t\t\t\t// throw new Error(`Duplicate id ${idValue} for edge ${JSON.stringify(edge)}`);\n\t\t\t\t}\n\t\t\t\tif (edges.find((x) => x.$bzId === edge.$bzId)) {\n\t\t\t\t\tthrow new Error(`Duplicate %bzId ${edge.$bzIdd} for edge ${JSON.stringify(edge)}`);\n\t\t\t\t}\n\t\t\t\tedges.push({ ...edge, $id: idValue });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tedges.push(edge);\n\t\t};\n\n\t\tconst listOp = ({ value: val }: TraversalCallbackContext) => {\n\t\t\tif (!isObject(val)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst value = val as BQLMutationBlock;\n\n\t\t\t/// no idea why this is needed lol, but sometimes is indeed undefined 🤷‍♀️\n\t\t\tif (value.$entity || value.$relation) {\n\t\t\t\tif (!value.$op) {\n\t\t\t\t\tthrow new Error(`Operation should be defined at this step ${JSON.stringify(value)}`);\n\t\t\t\t}\n\n\t\t\t\tif (!value.$bzId) {\n\t\t\t\t\tthrow new Error('[internal error] BzId not found');\n\t\t\t\t}\n\t\t\t\t/// this is used to group the right delete/unlink operations with the involved things\n\n\t\t\t\tconst currentThingSchema = getCurrentSchema(schema, value);\n\t\t\t\tconst {\n\t\t\t\t\tdataFields: dataFieldPaths,\n\t\t\t\t\troleFields: roleFieldPaths,\n\t\t\t\t\tlinkFields: linkFieldPaths,\n\t\t\t\t\tusedFields,\n\t\t\t\t} = getCurrentFields(currentThingSchema, value);\n\n\t\t\t\tconst getChildOp = () => {\n\t\t\t\t\tif (value.$op === 'create' || value.$op === 'delete') {\n\t\t\t\t\t\treturn value.$op;\n\t\t\t\t\t}\n\t\t\t\t\t// if its un update because linkfields or rolefields updated, but no attributes, then it a match\n\t\t\t\t\tif (value.$op === 'update') {\n\t\t\t\t\t\tconst usedDataFields = usedFields.filter((x: string) => dataFieldPaths?.includes(x));\n\t\t\t\t\t\tconst usedRoleFields = usedFields.filter((x: string) => roleFieldPaths?.includes(x));\n\t\t\t\t\t\tconst usedLinkFields = usedFields.filter((x: string) => linkFieldPaths?.includes(x));\n\t\t\t\t\t\tif (usedDataFields.length > 0) {\n\t\t\t\t\t\t\treturn 'update';\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (usedRoleFields.length > 0 || usedLinkFields.length > 0) {\n\t\t\t\t\t\t\treturn 'match';\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthrow new Error(`No fields on an $op:\"update\" for node ${JSON.stringify(value)}`);\n\t\t\t\t\t}\n\n\t\t\t\t\treturn 'match';\n\t\t\t\t};\n\n\t\t\t\tconst dataObj = {\n\t\t\t\t\t...(value.$entity && { $entity: value.$entity }),\n\t\t\t\t\t...(value.$relation && { $relation: value.$relation }),\n\t\t\t\t\t...(value.$id && { $id: value.$id }),\n\t\t\t\t\t...(value.$tempId && { $tempId: value.$tempId }),\n\t\t\t\t\t...(value.$filter && { $filter: value.$filter }),\n\t\t\t\t\t...shake(pick(value, dataFieldPaths || [''])),\n\t\t\t\t\t$op: getChildOp(),\n\t\t\t\t\t$bzId: value.$bzId,\n\t\t\t\t\t[Symbol.for('dbId')]: currentThingSchema.defaultDBConnector.id,\n\t\t\t\t\t// [Symbol.for('dependencies')]: value[Symbol.for('dependencies')],\n\t\t\t\t\t[Symbol.for('path')]: value[Symbol.for('path') as any],\n\n\t\t\t\t\t[Symbol.for('parent')]: value[Symbol.for('parent') as any],\n\t\t\t\t\t[Symbol.for('isRoot')]: value[Symbol.for('isRoot') as any],\n\t\t\t\t\t[Symbol.for('isLocalId')]: value[Symbol.for('isLocalId') as any] || false,\n\t\t\t\t};\n\n\t\t\t\t/// split nodes with multiple ids // why? //no longer doing that\n\t\t\t\ttoNodes(dataObj);\n\n\t\t\t\t// console.log('value', isDraft(value) ? current(value) : value);\n\n\t\t\t\t// CASE 1: HAVE A PARENT THROUGH LINKFIELDS\n\t\t\t\tif (\n\t\t\t\t\tvalue[Symbol.for('relation') as any] &&\n\t\t\t\t\tvalue[Symbol.for('edgeType') as any] === 'linkField'\n\t\t\t\t\t// value[Symbol.for('relation')] !== '$self'\n\t\t\t\t) {\n\t\t\t\t\tif (value.$op === 'link' || value.$op === 'unlink') {\n\t\t\t\t\t\tif (value.$id || value.$filter) {\n\t\t\t\t\t\t\tif (value.$tempId) {\n\t\t\t\t\t\t\t\tthrow new Error(\"can't specify a existing and a new element at once. Use an id/filter or a tempId\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tnodes.push({ ...value, $op: 'match' });\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// we add a \"linkable\" version of it so we can query it in the insertion\n\t\t\t\t\t}\n\n\t\t\t\t\t// this linkObj comes from nesting, which means it has no properties and no ID\n\t\t\t\t\t// relations explicitely created are not impacted by this, and they get the $id from it's actual current value\n\n\t\t\t\t\tconst ownRelation = value[Symbol.for('relation') as any] === value.$relation;\n\n\t\t\t\t\tconst linkTempId = ownRelation ? value.$bzId : uuidv4();\n\n\t\t\t\t\tconst parentMeta = value[Symbol.for('parent') as any];\n\t\t\t\t\tconst parentPath = parentMeta.path;\n\t\t\t\t\tconst parentNode = !parentPath ? blocks : getNodeByPath(blocks, parentPath);\n\t\t\t\t\tconst parentId = parentNode.$bzId;\n\t\t\t\t\tif (!parentId) {\n\t\t\t\t\t\tthrow new Error('No parent id found');\n\t\t\t\t\t}\n\n\t\t\t\t\tif (value[Symbol.for('relation') as any] === '$self') {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst getLinkObjOp = () => {\n\t\t\t\t\t\tif (value.$op === 'delete') {\n\t\t\t\t\t\t\tif (ownRelation) {\n\t\t\t\t\t\t\t\treturn 'match';\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn 'delete';\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (value.$op === 'unlink') {\n\t\t\t\t\t\t\tif (ownRelation) {\n\t\t\t\t\t\t\t\treturn 'unlink';\n\t\t\t\t\t\t\t} // delete already present in the nodes array\n\t\t\t\t\t\t\treturn 'delete';\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (value.$op === 'link' || value.$op === 'create') {\n\t\t\t\t\t\t\tif (ownRelation) {\n\t\t\t\t\t\t\t\treturn 'link';\n\t\t\t\t\t\t\t} // create already present in the nodes array\n\t\t\t\t\t\t\treturn 'create';\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// todo: probably check replaces\n\t\t\t\t\t\tif (value.$op === 'replace') {\n\t\t\t\t\t\t\t// Currently pre-queries do not cross reference data nested below a create operation\n\t\t\t\t\t\t\tthrow new Error('Unsupported: Nested replaces not implemented yet');\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn 'match';\n\t\t\t\t\t};\n\n\t\t\t\t\tconst edgeType1 = {\n\t\t\t\t\t\t$relation: value[Symbol.for('relation') as any],\n\t\t\t\t\t\t$bzId: linkTempId,\n\t\t\t\t\t\t...(value.$tempId ? { $tempId: value.$tempId } : {}),\n\t\t\t\t\t\t$op: getLinkObjOp(),\n\n\t\t\t\t\t\t// roles\n\t\t\t\t\t\t...(!ownRelation ? { [value[Symbol.for('role') as any]]: value.$bzId } : {}),\n\t\t\t\t\t\t[value[Symbol.for('oppositeRole') as any]]: parentId,\n\n\t\t\t\t\t\t[Symbol.for('dbId')]: schema.relations[value[Symbol.for('relation') as any]].defaultDBConnector.id,\n\t\t\t\t\t\t[Symbol.for('edgeType')]: 'linkField',\n\t\t\t\t\t\t[Symbol.for('info')]: 'normal linkField',\n\t\t\t\t\t\t[Symbol.for('path')]: value[Symbol.for('path') as any],\n\t\t\t\t\t\t[Symbol.for('parent')]: value[Symbol.for('parent') as any],\n\t\t\t\t\t};\n\n\t\t\t\t\t// const testVal = {};\n\n\t\t\t\t\t// todo: stuff 😂\n\t\t\t\t\ttoEdges(edgeType1);\n\n\t\t\t\t\t/// when it has a parent through a linkfield, we need to add an additional node (its dependency), as well as a match\n\t\t\t\t\t/// no need for links, as links will have all the related things in the \"link\" object. While unlinks required dependencies as match and deletions as unlink (or dependencies would be also added)\n\t\t\t\t\t/// this is only for relations that are not $self, as other relations will be deleted and don't need a match\n\t\t\t\t\tif ((value.$op === 'unlink' || getLinkObjOp() === 'unlink') && ownRelation) {\n\t\t\t\t\t\ttoEdges({\n\t\t\t\t\t\t\t$relation: value[Symbol.for('relation') as any],\n\t\t\t\t\t\t\t$bzId: linkTempId,\n\t\t\t\t\t\t\t$op: 'match',\n\t\t\t\t\t\t\t[value[Symbol.for('oppositeRole') as any]]: parentId,\n\t\t\t\t\t\t\t[Symbol.for('dbId')]: schema.relations[value[Symbol.for('relation') as any]].defaultDBConnector.id,\n\t\t\t\t\t\t\t[Symbol.for('edgeType')]: 'linkField',\n\t\t\t\t\t\t\t[Symbol.for('info')]: 'additional ownrelation unlink linkField',\n\t\t\t\t\t\t\t[Symbol.for('path')]: value[Symbol.for('path') as any],\n\t\t\t\t\t\t\t[Symbol.for('parent')]: value[Symbol.for('parent') as any],\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// CASE 2: IS RELATION AND HAS THINGS IN THEIR ROLES\n\t\t\t\tif (value.$relation) {\n\t\t\t\t\tconst rolesObjFiltered = oFilter(value, (k: string, _v) => roleFieldPaths.includes(k));\n\n\t\t\t\t\t/// we don't manage cardinality MANY for now, its managed differently if we are on a create/delete op or nested link/unlink op\n\t\t\t\t\t// todo: this is super weird, remove\n\t\t\t\t\tconst rolesObjOnlyIds = mapEntries(rolesObjFiltered, (k, v) => {\n\t\t\t\t\t\tif (isArray(v)) {\n\t\t\t\t\t\t\treturn [k, v];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (isObject(v)) {\n\t\t\t\t\t\t\t// @ts-expect-error - TODO description\n\t\t\t\t\t\t\treturn [k, v.$bzId];\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn [k, v];\n\t\t\t\t\t});\n\n\t\t\t\t\t// console.log('rolesObjOnlyIds', rolesObjOnlyIds);\n\n\t\t\t\t\tconst objWithMetaDataOnly = oFilter(val, (k, _v) => {\n\t\t\t\t\t\t// @ts-expect-error - TODO description\n\t\t\t\t\t\treturn k.startsWith('$') || k.startsWith('Symbol');\n\t\t\t\t\t});\n\n\t\t\t\t\tif (Object.keys(rolesObjFiltered).filter((x) => !x.startsWith('$')).length > 0) {\n\t\t\t\t\t\t// #region 2.1) relations on creation/deletion\n\t\t\t\t\t\tif (value.$op === 'create' || value.$op === 'delete') {\n\t\t\t\t\t\t\t/// if the relation is being created, then all objects in the roles are actually add\n\t\t\t\t\t\t\tconst getEdgeOp = () => {\n\t\t\t\t\t\t\t\tif (value.$op === 'create') {\n\t\t\t\t\t\t\t\t\treturn 'link';\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (value.$op === 'delete') {\n\t\t\t\t\t\t\t\t\treturn 'match';\n\t\t\t\t\t\t\t\t} /// if i'm not wrong, no need to unlink becasue is the director relation and will disappear 🤔\n\t\t\t\t\t\t\t\tthrow new Error('Unsupported parent of edge op');\n\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\t/// group ids when cardinality MANY\n\t\t\t\t\t\t\tconst rolesObjOnlyIdsGrouped = mapEntries(rolesObjOnlyIds, (k, v) => {\n\t\t\t\t\t\t\t\tif (Array.isArray(v)) {\n\t\t\t\t\t\t\t\t\t/// Replace the array of objects with an array of ids\n\t\t\t\t\t\t\t\t\treturn [k, v.map((vNested: any) => vNested.$bzId || vNested)];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn [k, v.$bzId || v];\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t// console.log('rolesObjOnlyIdsGrouped', rolesObjOnlyIdsGrouped);\n\n\t\t\t\t\t\t\t// todo: validations\n\t\t\t\t\t\t\t/// 1) each ONE role has only ONE element // 2) no delete ops // 3) no arrayOps, because it's empty (or maybe yes and just consider it an add?) ...\n\t\t\t\t\t\t\tconst edgeType2 = {\n\t\t\t\t\t\t\t\t...objWithMetaDataOnly,\n\t\t\t\t\t\t\t\t$relation: value.$relation,\n\t\t\t\t\t\t\t\t$op: getEdgeOp(),\n\t\t\t\t\t\t\t\t...rolesObjOnlyIdsGrouped, // override role fields by ids or tempIDs\n\t\t\t\t\t\t\t\t$bzId: value.$bzId,\n\t\t\t\t\t\t\t\t[Symbol.for('path')]: value[Symbol.for('path') as any],\n\t\t\t\t\t\t\t\t[Symbol.for('dbId')]: currentThingSchema.defaultDBConnector.id,\n\t\t\t\t\t\t\t\t[Symbol.for('info')]: 'coming from created or deleted relation',\n\t\t\t\t\t\t\t\t[Symbol.for('edgeType')]: 'roleField on C/D',\n\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\ttoEdges(edgeType2);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// #endregion\n\t\t\t\t\t\t// region 2.2 relations on nested stuff\n\t\t\t\t\t\t// todo: probably remove the match here\n\t\t\t\t\t\tif (value.$op === 'match' || (value.$op === 'update' && Object.keys(rolesObjFiltered).length > 0)) {\n\t\t\t\t\t\t\tlet totalUnlinks = 0;\n\n\t\t\t\t\t\t\tObject.entries(rolesObjFiltered).forEach(([role, operations]) => {\n\t\t\t\t\t\t\t\tconst operationsArray = isArray(operations) ? operations : [operations];\n\n\t\t\t\t\t\t\t\tconst getOp = (childOp: string) => {\n\t\t\t\t\t\t\t\t\tif (childOp === 'create' || childOp === 'replace') {\n\t\t\t\t\t\t\t\t\t\t// if the children is being created, the edge is a link\n\t\t\t\t\t\t\t\t\t\treturn 'link';\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\treturn childOp;\n\t\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\t\toperationsArray.forEach((operation) => {\n\t\t\t\t\t\t\t\t\tif (!operation) {\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tconst op = getOp(operation.$op);\n\t\t\t\t\t\t\t\t\t/// validations\n\t\t\t\t\t\t\t\t\tif (op === 'replace') {\n\t\t\t\t\t\t\t\t\t\tthrow new Error('Not supported yet: replace on roleFields');\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (op === 'unlink' && totalUnlinks > 0) {\n\t\t\t\t\t\t\t\t\t\ttotalUnlinks += 1; // ugly temp solution while multiple roles can't be replaced\n\t\t\t\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t\t\t\t'Not supported yet: Cannot unlink more than one role at a time, please split into two mutations',\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tconst edgeType3 = {\n\t\t\t\t\t\t\t\t\t\t...objWithMetaDataOnly,\n\t\t\t\t\t\t\t\t\t\t$relation: value.$relation,\n\t\t\t\t\t\t\t\t\t\t$op: op === 'delete' ? 'unlink' : op,\n\t\t\t\t\t\t\t\t\t\t[role]: operation.$bzId,\n\t\t\t\t\t\t\t\t\t\t$bzId: value.$bzId,\n\t\t\t\t\t\t\t\t\t\t[Symbol.for('dbId')]: currentThingSchema.defaultDBConnector.id,\n\t\t\t\t\t\t\t\t\t\t[Symbol.for('parent')]: value[Symbol.for('parent') as any],\n\t\t\t\t\t\t\t\t\t\t[Symbol.for('path')]: value[Symbol.for('path') as any],\n\t\t\t\t\t\t\t\t\t\t[Symbol.for('info')]: 'updating roleFields',\n\t\t\t\t\t\t\t\t\t\t[Symbol.for('edgeType')]: 'roleField on L/U/R',\n\t\t\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\t\t\ttoEdges(edgeType3);\n\t\t\t\t\t\t\t\t\t/// when unlinking stuff, it must be merged with other potential roles.\n\t\t\t\t\t\t\t\t\t/// so we need to add it as both as match and 'unlink' so it gets merged with other unlinks\n\t\t\t\t\t\t\t\t\t// todo maybe a way to transform unlinks already in its own matches later? maybe split match-unlink and match-link\n\t\t\t\t\t\t\t\t\tif (op === 'unlink') {\n\t\t\t\t\t\t\t\t\t\t// toEdges({ ...edgeType3, $op: 'match' }); ///apparently no longer needed\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// #endregion\n\t\t\t\t\t\t// throw new Error('Unsupported direct relation operation');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\t// console.log('[blocks]', JSON.stringify(blocks, null, 3));\n\t\t// console.log('[blocks]', blocks);\n\n\t\ttraverse(blocks, listOp);\n\n\t\treturn [nodes, edges];\n\t};\n\n\tif (!filledBqlRequest) {\n\t\tthrow new Error('Undefined filledBqlRequest');\n\t}\n\n\tconst [parsedThings, parsedEdges] = listNodes(filledBqlRequest);\n\t// console.log('parsedThings', parsedThings);\n\t// console.log('parsedEdges', parsedEdges);\n\n\t/// some cases where we extract things, they must be ignored.\n\t/// One of this cases is the situation where we have a thing that is linked somwhere and created, or updated.\n\t/// If it is only linked, we indeed need it with a \"match\" op, but if it is already there is no need to init it\n\tconst mergedThings = parsedThings.reduce((acc, thing) => {\n\t\t// Skip if the current item doesn't have a $tempId\n\t\tif (!thing.$bzId) {\n\t\t\treturn [...acc, thing];\n\t\t}\n\n\t\t// Check if this $tempId already exists in the accumulator\n\t\tconst existingIndex = acc.findIndex((t) => t.$bzId === thing.$bzId);\n\n\t\tif (existingIndex === -1) {\n\t\t\t// If it doesn't exist, add it to the accumulator\n\t\t\treturn [...acc, thing];\n\t\t}\n\t\t// If it exists, let's check the $op\n\t\tif (acc[existingIndex].$op === 'create' && thing.$op === 'match') {\n\t\t\t// If existing is 'create' and current is 'match', ignore current\n\t\t\treturn acc;\n\t\t}\n\t\tif (acc[existingIndex].$op === 'match' && (thing.$op === 'create' || thing.$op === 'match')) {\n\t\t\t// If existing is 'match' and current is 'create' or 'match', replace existing with current\n\t\t\treturn [...acc.slice(0, existingIndex), thing, ...acc.slice(existingIndex + 1)];\n\t\t}\n\t\t// For all other cases, throw an error\n\t\tthrow new Error(\n\t\t\t`Unsupported operation combination for $tempId \"${thing.$tempId}\". Existing: ${acc[existingIndex].$op}. Current: ${thing.$op}`,\n\t\t);\n\t}, [] as BQLMutationBlock[]);\n\n\t/// merge attributes of relations that share the same $id\n\t/// WHY => because sometimes we get the relation because of having a parent, and other times because it is specified in the relation's properties\n\tconst mergedEdges = parsedEdges.reduce((acc, curr) => {\n\t\tconst existingEdge = acc.find(\n\t\t\t(r) =>\n\t\t\t\t((r.$id && r.$id === curr.$id) || (r.$bzId && r.$bzId === curr.$bzId)) &&\n\t\t\t\tr.$relation === curr.$relation &&\n\t\t\t\tr.$op === curr.$op,\n\t\t);\n\n\t\tif (existingEdge) {\n\t\t\tconst newRelation = { ...existingEdge };\n\n\t\t\tObject.keys(curr).forEach((key) => {\n\t\t\t\tif (typeof key === 'symbol' || key.startsWith('$')) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst existingVal = existingEdge[key];\n\t\t\t\tconst currVal = curr[key];\n\n\t\t\t\tif (Array.isArray(existingVal) && Array.isArray(currVal)) {\n\t\t\t\t\tnewRelation[key] = Array.from(new Set([...existingVal, ...currVal]));\n\t\t\t\t} else if (!Array.isArray(existingVal) && Array.isArray(currVal)) {\n\t\t\t\t\tif (existingVal !== undefined) {\n\t\t\t\t\t\t// Avoid merging with undefined values.\n\t\t\t\t\t\tnewRelation[key] = Array.from(new Set([existingVal, ...currVal]));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnewRelation[key] = currVal;\n\t\t\t\t\t}\n\t\t\t\t} else if (Array.isArray(existingVal) && !Array.isArray(currVal)) {\n\t\t\t\t\tif (currVal !== undefined) {\n\t\t\t\t\t\t// Avoid merging with undefined values.\n\t\t\t\t\t\tnewRelation[key] = Array.from(new Set([...existingVal, currVal]));\n\t\t\t\t\t}\n\t\t\t\t} else if (!existingVal) {\n\t\t\t\t\tnewRelation[key] = currVal;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tconst newAcc = acc.filter(\n\t\t\t\t(r) =>\n\t\t\t\t\t!(\n\t\t\t\t\t\t((r.$id && r.$id === curr.$id) || (r.$bzId && r.$bzId === curr.$bzId)) &&\n\t\t\t\t\t\tr.$relation === curr.$relation &&\n\t\t\t\t\t\tr.$op === curr.$op\n\t\t\t\t\t),\n\t\t\t);\n\n\t\t\treturn [...newAcc, newRelation];\n\t\t}\n\n\t\treturn [...acc, curr];\n\t}, [] as BQLMutationBlock[]);\n\n\t// console.log('mergedThings', mergedThings);\n\t// console.log('mergedEdges', mergedEdges);\n\n\t/// VALIDATIONS\n\t/// in the same mutation, we can't link cardinality ONE stuff in multiple places\n\t/// case a: We have two different edges (from intermediary relations) doing links with the same entity\n\n\tconst uniqueRelations = [...new Set(mergedEdges.map((x) => x.$relation))];\n\t// Let's define an object to hold the problematic edges\n\t// const problematicEdges = {};\n\t/*\n // Iterate over the unique relations\n uniqueRelations.forEach(relation => {\n // Get the schema for the current relation\n const schema = schema.relations[relation];\n \n // Define the 'dangerous' roles\n const dangerousRoles = Object.keys(schema.roles).filter(role => schema.roles[role].cardinality === 'ONE');\n \n // Now, we want to keep only the edges which include these dangerous roles\n const filteredEdges = mergedEdges.filter(edge => edge.$relation === relation && dangerousRoles.some(role => edge.hasOwnProperty(role)));\n console.log('filteredEdges', filteredEdges)\n \n // For each dangerous role, check if any violations of the cardinality rule occur\n dangerousRoles.forEach((role) => {\n let roleValues = {};\n \n // Iterate over the filtered edges\n filteredEdges.forEach(edge => {\n // Define the opposite role\n const oppositeRoles = Object.keys(edge).filter(key => key !== role && key !== '$relation' && key !== '$op' && key !== '$id');\n \n oppositeRoles.forEach(oppositeRole => {\n // Initialize the set of role values associated with the oppositeRole value, if necessary\n if (!roleValues[oppositeRole]) {\n roleValues[oppositeRole] = new Set();\n }\n \n // Add the role value to the set of role values associated with the oppositeRole value\n roleValues[oppositeRole].add(edge[role]);\n \n // If the role value set size is more than 1 and the opposite role is not a 'ONE' cardinality role, add it to problematicEdges\n \n if (roleValues[oppositeRole].size > 1 && schema.relations[relation].roles[oppositeRole].cardinality !== 'ONE') {\n \n if (!problematicEdges[relation]) {\n \n problematicEdges[relation] = {};\n }\n \n if (!problematicEdges[relation][role]) {\n \n problematicEdges[relation][role] = [];\n }\n throw new Error(`Illegal cardinality: The ${role} role in ${relation} is linked to multiple ${oppositeRole} roles.`);\n }\n });\n });\n });\n }\n ); */\n\n\t/// todo: issue 1: relations with >2 roles will not work\n\t/// todo: issue 2: replaces don't work as they are indeed repeated for cardinality ONE\n\t// eslint-disable-next-line unused-imports/no-unused-vars\n\tconst _checkCardinality = (): void => {\n\t\t// The problematic edges will be stored here\n\t\tconst problematicEdges: Record<string, Set<string>> = {};\n\n\t\tuniqueRelations.forEach((relation) => {\n\t\t\tconst cardinalityOneRoles = Object.keys(schema.relations[relation].roles).filter(\n\t\t\t\t(role) => schema.relations[relation].roles[role].cardinality === 'ONE',\n\t\t\t);\n\n\t\t\t// console.log('cardinalityOneRoles', `${relation}: ${cardinalityOneRoles}`);\n\n\t\t\t// For each role with cardinality ONE\n\t\t\tcardinalityOneRoles.forEach((oneRole) => {\n\t\t\t\t// A map from ids of the opposite role to a set of ids of the 'oneRole'\n\t\t\t\tconst idMapping: Record<string, Set<string>> = {};\n\n\t\t\t\t// Look through all the edges\n\t\t\t\tmergedEdges.forEach((edge) => {\n\t\t\t\t\tif (edge.$relation === relation && edge[oneRole]) {\n\t\t\t\t\t\t// Extract id from the 'oneRole'\n\t\t\t\t\t\tconst oneId = edge[oneRole];\n\n\t\t\t\t\t\t// Get the ids from the other role\n\t\t\t\t\t\tconst otherRole = Object.keys(edge).find(\n\t\t\t\t\t\t\t(role) => role !== '$relation' && role !== '$op' && role !== '$id' && role !== oneRole,\n\t\t\t\t\t\t);\n\t\t\t\t\t\t// console.log('edge', edge, 'otherRole', otherRole);\n\n\t\t\t\t\t\tif (otherRole) {\n\t\t\t\t\t\t\tconst otherId = edge[otherRole];\n\n\t\t\t\t\t\t\t// Map the 'otherId' to the 'oneId'\n\t\t\t\t\t\t\tif (!idMapping[otherId]) {\n\t\t\t\t\t\t\t\tidMapping[otherId] = new Set();\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tidMapping[otherId].add(oneId);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// Check if any 'otherId' is related to multiple 'oneIds'\n\t\t\t\tObject.entries(idMapping).forEach(([otherId, oneIds]) => {\n\t\t\t\t\tif (oneIds.size > 1) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`${relation} has illegal cardinality: The ${oneRole} role is linked to multiple ${Object.keys(\n\t\t\t\t\t\t\t\tidMapping[otherId],\n\t\t\t\t\t\t\t).join(',')} roles.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t});\n\n\t\t// If there are any problematic edges, throw an error\n\t\tif (Object.keys(problematicEdges).length > 0) {\n\t\t\tlet errorMessage = '';\n\t\t\tObject.entries(problematicEdges).forEach(([otherId, errorSet]) => {\n\t\t\t\terrorMessage +=\n\t\t\t\t\t`\"${otherId}\" is connected to many entities. ` +\n\t\t\t\t\t`${Array.from(errorSet).join(' ')}` +\n\t\t\t\t\t\"The relation's role is of cardinality ONE.\\n\";\n\t\t\t});\n\n\t\t\tthrow new Error(errorMessage);\n\t\t}\n\t};\n\n\t//! disabled as it has false positives\n\t// todo\n\t// checkCardinality(); // todo: add mergedEdges and schema as params and import from other parseBQLMutationHelpers\n\n\t/// case b: We have repeated the same relation id in two places and we are asigning it one of the roles more than one item\n\n\t/// case c: Before merge, a role with cardinality ONE has an array => This one is already managed before, so n\n\n\treq.bqlRequest = {\n\t\tmutation: {\n\t\t\tthings: mergedThings,\n\t\t\tedges: mergedEdges,\n\t\t},\n\t};\n};\n","import { TransactionType } from 'typedb-driver';\n\nimport type { PipelineOperation } from '../pipeline';\nimport { getSessionOrOpenNewOne } from './helpers';\n\nexport const runTQLMutation: PipelineOperation = async (req, res) => {\n\tconst { dbHandles, tqlRequest, bqlRequest, config } = req;\n\tif (!tqlRequest) {\n\t\tthrow new Error('TQL request not built');\n\t}\n\tif (!((tqlRequest.deletions && tqlRequest.deletionMatches) || tqlRequest.insertions)) {\n\t\tthrow new Error('TQL request error, no things');\n\t}\n\tif (!bqlRequest?.mutation) {\n\t\tthrow new Error('BQL mutation not parsed');\n\t}\n\n\tconst { session } = await getSessionOrOpenNewOne(dbHandles, config);\n\n\tconst mutateTransaction = await session.transaction(TransactionType.WRITE);\n\n\tif (!mutateTransaction) {\n\t\tthrow new Error(\"Can't create transaction\");\n\t}\n\t// console.log('tqlRequest!', JSON.stringify(tqlRequest, null, 2));\n\n\t// deletes and pre-update deletes\n\tconst tqlDeletion =\n\t\ttqlRequest.deletionMatches &&\n\t\ttqlRequest.deletions &&\n\t\t`match ${tqlRequest.deletionMatches} delete ${tqlRequest.deletions}`;\n\n\t// insertions and updates\n\tconst tqlInsertion =\n\t\ttqlRequest.insertions &&\n\t\t`${tqlRequest.insertionMatches ? `match ${tqlRequest.insertionMatches}` : ''} insert ${tqlRequest.insertions}`;\n\n\t// does not receive a result\n\tif (tqlDeletion) {\n\t\t// console.log('DELETING: ', tqlDeletion);\n\t\tawait mutateTransaction.query.delete(tqlDeletion);\n\t\t// console.log('X: ', x);\n\t}\n\n\tconst insertionsStream = tqlInsertion && mutateTransaction.query.insert(tqlInsertion);\n\n\ttry {\n\t\tconst insertionsRes = insertionsStream ? await insertionsStream.collect() : undefined;\n\t\t// console.log('INSERTION: ', insertionsRes);\n\n\t\tawait mutateTransaction.commit();\n\t\tawait mutateTransaction.close();\n\t\tres.rawTqlRes = { insertions: insertionsRes };\n\t} catch (e: any) {\n\t\tawait mutateTransaction.close();\n\t\tthrow new Error(`Transaction failed: ${e.message}`);\n\t}\n\n\t// const ids = bqlRequest.mutation.entities.map((e) => e.$id as string);\n\t// res.bqlRes = ids;\n};\n","import { SessionType } from 'typedb-driver';\nimport type { BormConfig, DBHandles } from '../../types';\n\nexport const getSessionOrOpenNewOne = async (dbHandles: DBHandles, config: BormConfig) => {\n\tconst singleHandlerV0 = config.dbConnectors[0].id;\n\tlet session = dbHandles.typeDB.get(singleHandlerV0)?.session;\n\tconst client = dbHandles.typeDB.get(singleHandlerV0)?.client;\n\n\tif (!session || !session.isOpen()) {\n\t\tif (!client) {\n\t\t\tthrow new Error('Client not found');\n\t\t}\n\t\tsession = await client.session(config.dbConnectors[0].dbName, SessionType.DATA);\n\t\tdbHandles.typeDB.set(singleHandlerV0, { client, session });\n\t}\n\n\treturn { client, session };\n};\n","import type { PipelineOperation } from '../pipeline';\n\nconst separator = '___';\n\nexport const newBuildTQLQuery: PipelineOperation = async (req) => {\n\tconst { enrichedBqlQuery } = req;\n\tif (!enrichedBqlQuery) {\n\t\tthrow new Error('BQL query not enriched');\n\t}\n\n\tlet tqlStr = '';\n\n\ttype ValueBlock = {\n\t\t$thing: string;\n\t\t$thingType: 'entity' | 'relation' | 'thing' | 'attribute';\n\t\t$path?: string;\n\t\t$as?: string;\n\t\t$var?: string;\n\t\t$fields?: ValueBlock[];\n\t\t$filter?: object;\n\t\t$fieldType?: 'data' | 'role' | 'link';\n\t};\n\n\tconst processFilters = ($filter: object, $var: string) => {\n\t\tlet simpleHas = '';\n\t\tlet orHas = '';\n\n\t\tfor (const key in $filter) {\n\t\t\t// @ts-expect-error todo\n\t\t\tconst filterKey = $filter[key];\n\t\t\tif (Array.isArray(filterKey)) {\n\t\t\t\tfor (let i = 0; i < filterKey.length; i++) {\n\t\t\t\t\torHas += `{$${$var} has ${key} \"${filterKey[i]}\";}`;\n\t\t\t\t\tif (i < filterKey.length - 1) {\n\t\t\t\t\t\torHas += 'or';\n\t\t\t\t\t} else {\n\t\t\t\t\t\torHas += ';';\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsimpleHas += `, has ${key} \"${filterKey}\"`;\n\t\t\t}\n\t\t}\n\t\tsimpleHas += '; \\n';\n\t\ttqlStr += simpleHas;\n\t\ttqlStr += orHas;\n\t};\n\n\tconst processDataFields = (\n\t\tdataFields: {\n\t\t\t$path: string;\n\t\t\t$dbPath: string;\n\t\t\t$thingType: 'attribute';\n\t\t\t$as: string;\n\t\t\t$var: string;\n\t\t\t$fieldType: 'data';\n\t\t\t$justId: boolean;\n\t\t\t$isVirtual: boolean;\n\t\t}[],\n\t\t$path: string,\n\t) => {\n\t\tconst postStrParts = [];\n\t\tconst asMetaDataParts = [];\n\t\tconst virtualMetaDataParts = [];\n\n\t\tlet $asMetaData = '';\n\t\tlet $virtualMetaData = '';\n\n\t\tfor (let i = 0; i < dataFields.length; i++) {\n\t\t\tif (!dataFields[i].$isVirtual) {\n\t\t\t\tpostStrParts.push(` ${dataFields[i].$dbPath}`);\n\t\t\t} else {\n\t\t\t\tvirtualMetaDataParts.push(`${dataFields[i].$dbPath}`);\n\t\t\t}\n\t\t\tasMetaDataParts.push(`{${dataFields[i].$dbPath}:${dataFields[i].$as}}`);\n\t\t}\n\n\t\tconst postStr = `${postStrParts.join(',')};\\n`;\n\t\t$asMetaData = asMetaDataParts.join(',');\n\t\t$virtualMetaData = virtualMetaDataParts.join(',');\n\n\t\tconst $metaData = `$metadata:{as:[${$asMetaData}],virtual:[${$virtualMetaData}]}`;\n\n\t\ttqlStr += `$${$path} as \"${$path}.${$metaData}.$dataFields\": `;\n\t\ttqlStr += postStr;\n\t};\n\n\tconst processRoleFields = (\n\t\troleFields: {\n\t\t\t$path: string;\n\t\t\t$dbPath: string;\n\t\t\t$thingType: 'entity' | 'relation' | 'thing';\n\t\t\t$as: string;\n\t\t\t$var: string;\n\t\t\t$fieldType: 'link';\n\t\t\t$target: 'role' | 'relation';\n\t\t\t$fields?: ValueBlock[];\n\t\t\t$thing: string;\n\t\t\t$plays: string;\n\t\t\t$intermediary: string;\n\t\t\t$justId: boolean;\n\t\t\t$filter: object;\n\t\t\t$idNotIncluded: boolean;\n\t\t\t$filterByUnique: boolean;\n\t\t\t$playedBy: any;\n\t\t}[],\n\t\t$path: string,\n\t\tdotPath: string,\n\t) => {\n\t\tfor (const roleField of roleFields) {\n\t\t\tconst { $fields, $as, $justId, $idNotIncluded, $filterByUnique } = roleField;\n\n\t\t\tconst $metaData = `$metadata:{as:${$as},justId:${\n\t\t\t\t$justId ? 'T' : 'F'\n\t\t\t},idNotIncluded:${$idNotIncluded},filterByUnique:${$filterByUnique}}`;\n\t\t\ttqlStr += `\"${dotPath}.${$metaData}.${roleField.$var}\":{ \\n`;\n\t\t\ttqlStr += '\\tmatch \\n';\n\t\t\tif (roleField.$filter) {\n\t\t\t\ttqlStr += ` $${$path}${separator}${roleField.$var} isa ${roleField.$thing}`;\n\t\t\t\tprocessFilters(roleField.$filter, `${$path}${separator}${roleField.$var}`);\n\t\t\t}\n\t\t\ttqlStr += `\\t$${$path} (${roleField.$var}: $${$path}${separator}${roleField.$var}) isa ${roleField.$intermediary}; \\n`;\n\n\t\t\tif ($fields) {\n\t\t\t\ttqlStr += '\\tfetch \\n';\n\t\t\t}\n\t\t\tconst dataFields = $fields?.filter((f) => f.$fieldType === 'data');\n\t\t\tif (dataFields && dataFields.length > 0) {\n\t\t\t\t// @ts-expect-error todo\n\t\t\t\tprocessDataFields(dataFields, `${$path}${separator}${roleField.$var}`, `${$path}.${roleField.$var}`);\n\t\t\t}\n\n\t\t\tconst linkFields = $fields?.filter((f) => f.$fieldType === 'link');\n\t\t\tif (linkFields && linkFields.length > 0) {\n\t\t\t\t// @ts-expect-error todo\n\t\t\t\tprocessLinkFields(linkFields, `${$path}${separator}${roleField.$var}`, `${$path}.${roleField.$var}`);\n\t\t\t}\n\t\t\tconst roleFields = $fields?.filter((f) => f.$fieldType === 'role');\n\t\t\tif (roleFields && roleFields.length > 0) {\n\t\t\t\t// @ts-expect-error todo\n\t\t\t\tprocessRoleFields(roleFields, `${$path}${separator}${roleField.$var}`, `${$path}.${roleField.$var}`);\n\t\t\t}\n\t\t\ttqlStr += '}; \\n';\n\t\t}\n\t};\n\n\tconst processLinkFields = (\n\t\tlinkFields: {\n\t\t\t$path: string;\n\t\t\t$dbPath: string;\n\t\t\t$thingType: 'entity' | 'relation' | 'thing';\n\t\t\t$as: string;\n\t\t\t$var: string;\n\t\t\t$fieldType: 'link';\n\t\t\t$target: 'role' | 'relation';\n\t\t\t$fields?: ValueBlock[];\n\t\t\t$intermediary?: string;\n\t\t\t$thing: string;\n\t\t\t$plays: string;\n\t\t\t$justId: boolean;\n\t\t\t$filter: object;\n\t\t\t$idNotIncluded: boolean;\n\t\t\t$filterByUnique: boolean;\n\t\t\t$playedBy: any;\n\t\t}[],\n\t\t$path: string,\n\t\tdotPath: string,\n\t) => {\n\t\tfor (const linkField of linkFields) {\n\t\t\tconst { $fields, $as, $justId, $idNotIncluded, $filterByUnique, $playedBy } = linkField;\n\t\t\tconst $metaData = `$metadata:{as:${$as},justId:${\n\t\t\t\t$justId ? 'T' : 'F'\n\t\t\t},idNotIncluded:${$idNotIncluded},filterByUnique:${$filterByUnique}}`;\n\t\t\ttqlStr += `\"${dotPath}.${$metaData}.${linkField.$var}\":{ \\n`;\n\t\t\ttqlStr += '\\tmatch \\n';\n\t\t\tif (linkField.$filter) {\n\t\t\t\ttqlStr += ` $${$path}${separator}${linkField.$var} isa ${linkField.$thing}`;\n\t\t\t\tprocessFilters(linkField.$filter, `${$path}${separator}${linkField.$var}`);\n\t\t\t}\n\t\t\t// a. intermediary\n\t\t\tif (linkField.$target === 'role') {\n\t\t\t\ttqlStr += `\\t$${$path}_intermediary (${linkField.$plays}: $${$path}, ${$playedBy.plays}: $${$path}${separator}${linkField.$var}) isa ${linkField.$intermediary}; \\n`;\n\t\t\t} else {\n\t\t\t\t// b. no intermediary\n\t\t\t\ttqlStr += `\\t$${$path}${separator}${linkField.$var} (${linkField.$plays}: $${$path}) isa ${linkField.$thing}; \\n`;\n\t\t\t}\n\n\t\t\tif ($fields) {\n\t\t\t\ttqlStr += '\\tfetch \\n';\n\t\t\t}\n\t\t\tconst dataFields = $fields?.filter((f) => f.$fieldType === 'data');\n\t\t\tif (dataFields && dataFields.length > 0) {\n\t\t\t\t// @ts-expect-error todo\n\t\t\t\tprocessDataFields(dataFields, `${$path}${separator}${linkField.$var}`);\n\t\t\t}\n\n\t\t\tconst linkFields = $fields?.filter((f) => f.$fieldType === 'link');\n\t\t\tif (linkFields && linkFields.length > 0) {\n\t\t\t\t// @ts-expect-error todo\n\t\t\t\tprocessLinkFields(linkFields, `${$path}${separator}${linkField.$var}`, `${$path}.${linkField.$var}`);\n\t\t\t}\n\n\t\t\tconst roleFields = $fields?.filter((f) => f.$fieldType === 'role');\n\t\t\tif (roleFields && roleFields.length > 0) {\n\t\t\t\t// @ts-expect-error todo\n\t\t\t\tprocessRoleFields(roleFields, `${$path}${separator}${linkField.$var}`, `${$path}.${linkField.$var}`);\n\t\t\t}\n\t\t\ttqlStr += '}; \\n';\n\t\t}\n\t};\n\tconst isBatched = enrichedBqlQuery.length > 1;\n\tconst tqlStrings: string[] = [];\n\n\tconst builder = (enrichedBqlQuery: ValueBlock[]) => {\n\t\t// Batched\n\t\tif (isBatched) {\n\t\t\tfor (const query of enrichedBqlQuery) {\n\t\t\t\tconst { $path, $thing, $filter, $fields } = query;\n\t\t\t\ttqlStr += `match \\n \\t $${$path} isa ${$thing} `;\n\t\t\t\tif ($filter) {\n\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\tprocessFilters($filter, $path);\n\t\t\t\t} else {\n\t\t\t\t\ttqlStr += '; ';\n\t\t\t\t}\n\t\t\t\tif ($fields) {\n\t\t\t\t\ttqlStr += 'fetch \\n';\n\t\t\t\t}\n\t\t\t\tconst dataFields = $fields?.filter((f) => f.$fieldType === 'data');\n\t\t\t\tif (dataFields && dataFields.length > 0) {\n\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\tprocessDataFields(dataFields, $path);\n\t\t\t\t}\n\n\t\t\t\tconst linkFields = $fields?.filter((f) => f.$fieldType === 'link');\n\t\t\t\tif (linkFields && linkFields.length > 0) {\n\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\tprocessLinkFields(linkFields, $path, $path);\n\t\t\t\t}\n\n\t\t\t\tconst roleFields = $fields?.filter((f) => f.$fieldType === 'role');\n\t\t\t\tif (roleFields && roleFields.length > 0) {\n\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\tprocessRoleFields(roleFields, $path, $path);\n\t\t\t\t}\n\t\t\t\ttqlStrings.push(tqlStr);\n\t\t\t\ttqlStr = '';\n\t\t\t}\n\t\t} else {\n\t\t\tfor (const query of enrichedBqlQuery) {\n\t\t\t\tconst { $path, $thing, $filter, $fields } = query;\n\t\t\t\ttqlStr += `match \\n \\t $${$path} isa ${$thing} `;\n\t\t\t\tif ($filter) {\n\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\tprocessFilters($filter, $path);\n\t\t\t\t} else {\n\t\t\t\t\ttqlStr += '; ';\n\t\t\t\t}\n\t\t\t\tif ($fields) {\n\t\t\t\t\ttqlStr += 'fetch \\n';\n\t\t\t\t}\n\t\t\t\tconst dataFields = $fields?.filter((f) => f.$fieldType === 'data');\n\t\t\t\tif (dataFields && dataFields.length > 0) {\n\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\tprocessDataFields(dataFields, $path);\n\t\t\t\t}\n\n\t\t\t\tconst linkFields = $fields?.filter((f) => f.$fieldType === 'link');\n\t\t\t\tif (linkFields && linkFields.length > 0) {\n\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\tprocessLinkFields(linkFields, $path, $path);\n\t\t\t\t}\n\n\t\t\t\tconst roleFields = $fields?.filter((f) => f.$fieldType === 'role');\n\t\t\t\tif (roleFields && roleFields.length > 0) {\n\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\tprocessRoleFields(roleFields, $path, $path);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n\tbuilder(enrichedBqlQuery);\n\t// todo: type the tqlRequest\n\t// @ts-expect-error todo\n\treq.tqlRequest = isBatched ? tqlStrings : tqlStr;\n};\n","import { produce } from 'immer';\nimport type { PipelineOperation } from '../pipeline';\nimport { traverse } from 'object-traversal';\nimport { getCurrentSchema } from '../../helpers';\nimport { isObject } from 'radash';\nimport type { BQLMutationBlock, EnrichedBormEntity, EnrichedBormRelation } from '../../types';\n\nconst getAllFields = (currentSchema: any) => {\n\tconst dataFields = currentSchema.dataFields?.map((field: any) => field.path) || [];\n\tconst linkFields = currentSchema.linkFields?.map((field: any) => field.path) || [];\n\tconst roleFields = Object.keys(currentSchema.roles || {}) || [];\n\tconst allFields = [...dataFields, ...linkFields, ...roleFields];\n\treturn allFields;\n};\n\nconst checkFilterByUnique = ($filter: any, currentSchema: EnrichedBormEntity | EnrichedBormRelation) => {\n\tconst fields = Object.keys($filter || {});\n\n\treturn fields.some((field) => {\n\t\tif (!Array.isArray($filter[field])) {\n\t\t\tconst isIdField = currentSchema.idFields?.includes(field);\n\t\t\tconst isUniqueDataField = currentSchema.dataFields?.some(\n\t\t\t\t(f) => (f.dbPath === field || f.path === field) && f?.validations?.unique,\n\t\t\t);\n\n\t\t\treturn isIdField || isUniqueDataField;\n\t\t}\n\t\treturn false;\n\t});\n};\n\nconst processFilter = ($filter: any, currentSchema: EnrichedBormEntity | EnrichedBormRelation) => {\n\t// Map data fields, link fields, and role fields to a simplified structure\n\tconst dataFields = currentSchema.dataFields?.map((field) => ({ path: field.path, dbPath: field.dbPath })) || [];\n\t// @ts-expect-error todo\n\tconst linkFields = currentSchema.linkFields?.map((field) => ({ path: field.path, dbPath: field.dbPath })) || [];\n\t// @ts-expect-error todo\n\tconst roleFields = Object.keys(currentSchema.roles || {}).map((field) => ({ path: field, dbPath: field })) || [];\n\n\t// Combine all fields into a single array\n\tconst allFields = [...dataFields, ...linkFields, ...roleFields];\n\n\t// Reduce the filter object to a new structure\n\treturn Object.entries($filter || {}).reduce((newFilter, [filterKey, filterValue]) => {\n\t\tconst field = allFields.find((o) => o.path === filterKey);\n\t\t// @ts-expect-error todo\n\t\t// eslint-disable-next-line no-param-reassign\n\t\tnewFilter[field?.dbPath || filterKey] = filterValue;\n\t\treturn newFilter;\n\t}, {});\n};\n\nexport const enrichBQLQuery: PipelineOperation = async (req) => {\n\tconst { rawBqlRequest: rawBqlQuery, schema } = req;\n\n\tif (!Array.isArray(rawBqlQuery)) {\n\t\tif (\n\t\t\t!('$entity' in rawBqlQuery) &&\n\t\t\t!('$relation' in rawBqlQuery) &&\n\t\t\t(!('$thing' in rawBqlQuery) || !('$thingType' in rawBqlQuery))\n\t\t) {\n\t\t\tthrow new Error('No entity specified in query');\n\t\t}\n\t} else {\n\t\tfor (const item of rawBqlQuery) {\n\t\t\tif (!('$entity' in item) && !('$relation' in item) && (!('$thing' in item) || !('$thingType' in item))) {\n\t\t\t\tthrow new Error('No entity specified in query');\n\t\t\t}\n\t\t}\n\t}\n\n\tconst createDataField = (field: any, fieldStr: string, $justId: boolean, dbPath: string, isVirtual?: boolean) => {\n\t\t// todo: get all dependencies of the virtual field in the query and then remove from the output\n\t\treturn {\n\t\t\t$path: fieldStr,\n\t\t\t$dbPath: dbPath,\n\t\t\t$thingType: 'attribute',\n\t\t\t$as: field.$as || fieldStr,\n\t\t\t$var: fieldStr,\n\t\t\t$fieldType: 'data',\n\t\t\t$justId,\n\t\t\t$id: field.$id,\n\t\t\t$filter: field.$filter,\n\t\t\t$isVirtual: isVirtual,\n\t\t\t// ...(typeof field !== 'string' && { $fields: [...field.$fields, ...['id']] }),\n\t\t\t$filterProcessed: true,\n\t\t};\n\t};\n\n\tconst createLinkField = (field: any, fieldStr: string, linkField: any, $justId: boolean, dbPath: string) => {\n\t\tconst { target, oppositeLinkFieldsPlayedBy } = linkField;\n\t\treturn oppositeLinkFieldsPlayedBy.map((playedBy: any) => {\n\t\t\tconst $thingType = target === 'role' ? playedBy.thingType : 'relation';\n\t\t\tconst $thing = target === 'role' ? playedBy.thing : linkField.relation;\n\t\t\tconst node = { [`$${$thingType}`]: $thing };\n\t\t\tconst currentSchema = getCurrentSchema(schema, node);\n\t\t\tconst idNotIncluded =\n\t\t\t\tfield?.$fields?.filter(\n\t\t\t\t\t(field: any) => currentSchema?.idFields?.includes(field) || currentSchema?.idFields?.includes(field.$path),\n\t\t\t\t).length === 0;\n\n\t\t\tlet fields = [];\n\t\t\tif (typeof field !== 'string') {\n\t\t\t\tif (field.$fields) {\n\t\t\t\t\tif (idNotIncluded) {\n\t\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\t\tfields = [...field.$fields, ...currentSchema.idFields];\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfields = field.$fields;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfields = getAllFields(currentSchema);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfields = ['id'];\n\t\t\t}\n\t\t\tif (field.$excludedFields) {\n\t\t\t\tfields = fields.filter((f: { $path: string }) => !field.$excludedFields.includes(f.$path));\n\t\t\t}\n\t\t\treturn {\n\t\t\t\t$thingType,\n\t\t\t\t$plays: linkField.plays,\n\t\t\t\t$playedBy: playedBy,\n\t\t\t\t$path: playedBy.path,\n\t\t\t\t$dbPath: dbPath,\n\t\t\t\t$as: field.$as || fieldStr,\n\t\t\t\t$var: fieldStr,\n\t\t\t\t$thing,\n\t\t\t\t$fields: fields,\n\t\t\t\t$fieldType: 'link',\n\t\t\t\t$target: target,\n\t\t\t\t$intermediary: playedBy.relation,\n\t\t\t\t$justId,\n\t\t\t\t$id: field.$id,\n\t\t\t\t$filter: processFilter(field.$filter, currentSchema),\n\t\t\t\t$idNotIncluded: idNotIncluded,\n\t\t\t\t$filterByUnique: checkFilterByUnique(field.$filter, currentSchema),\n\t\t\t\t$filterProcessed: true,\n\t\t\t};\n\t\t});\n\t};\n\n\tconst createRoleField = (field: any, fieldStr: string, roleField: any, $justId: boolean, dbPath: string) => {\n\t\treturn roleField.playedBy.map((playedBy: any) => {\n\t\t\tconst { thing, thingType, relation } = playedBy;\n\t\t\tconst node = { [`$${thingType}`]: thing };\n\t\t\tconst currentSchema = getCurrentSchema(schema, node);\n\t\t\tconst idNotIncluded =\n\t\t\t\tfield?.$fields?.filter(\n\t\t\t\t\t(field: any) => currentSchema?.idFields?.includes(field) || currentSchema?.idFields?.includes(field.$path),\n\t\t\t\t).length === 0;\n\n\t\t\tlet fields = [];\n\t\t\tif (typeof field !== 'string') {\n\t\t\t\tif (field.$fields) {\n\t\t\t\t\tif (idNotIncluded) {\n\t\t\t\t\t\tfields = [...field.$fields, ...currentSchema.idFields];\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfields = field.$fields;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfields = getAllFields(currentSchema);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfields = ['id'];\n\t\t\t}\n\n\t\t\tif (field.$excludedFields) {\n\t\t\t\tfields = fields.filter((f: { $path: string }) => !field.$excludedFields.includes(f.$path));\n\t\t\t}\n\t\t\treturn {\n\t\t\t\t$thingType: thingType,\n\t\t\t\t$path: fieldStr,\n\t\t\t\t$dbPath: dbPath,\n\t\t\t\t$as: field.$as || fieldStr,\n\t\t\t\t$var: fieldStr,\n\t\t\t\t$thing: thing,\n\t\t\t\t$fields: fields,\n\t\t\t\t$fieldType: 'role',\n\t\t\t\t$intermediary: relation,\n\t\t\t\t$justId,\n\t\t\t\t$id: field.$id,\n\t\t\t\t$filter: processFilter(field.$filter, currentSchema),\n\t\t\t\t$idNotIncluded: idNotIncluded,\n\t\t\t\t$filterByUnique: checkFilterByUnique(field.$filter, currentSchema),\n\t\t\t\t$playedBy: playedBy,\n\t\t\t\t$filterProcessed: true,\n\t\t\t};\n\t\t});\n\t};\n\tconst processField = (field: any, schema: any) => {\n\t\tconst fieldStr = typeof field === 'string' ? field : field.$path;\n\t\tconst justId = typeof field === 'string';\n\t\tconst isDataField = schema.dataFields?.find((dataField: any) => dataField.path === fieldStr);\n\t\tconst isLinkField = schema.linkFields?.find((linkField: any) => linkField.path === fieldStr);\n\t\tconst isRoleField = schema.roles?.[fieldStr];\n\n\t\tif (isDataField) {\n\t\t\treturn createDataField(field, fieldStr, justId, isDataField.dbPath, isDataField.isVirtual);\n\t\t} else if (isLinkField) {\n\t\t\treturn createLinkField(field, fieldStr, isLinkField, justId, isLinkField.dbPath);\n\t\t} else if (isRoleField) {\n\t\t\treturn createRoleField(field, fieldStr, isRoleField, justId, isRoleField.dbPath);\n\t\t}\n\t\treturn null;\n\t};\n\tconst parser = (blocks: any) => {\n\t\treturn produce(blocks, (draft: any) =>\n\t\t\ttraverse(draft, (context) => {\n\t\t\t\tconst { value: val } = context;\n\t\t\t\tconst value: BQLMutationBlock = val;\n\t\t\t\tif (isObject(value)) {\n\t\t\t\t\t// 1. Moving $id into filter based on schema's idFields\n\t\t\t\t\tif (value.$id) {\n\t\t\t\t\t\tconst node = value.$entity || value.$relation ? value : { [`$${value.$thingType}`]: value.$thing };\n\t\t\t\t\t\tconst currentSchema = getCurrentSchema(schema, node);\n\t\t\t\t\t\tvalue.$path = currentSchema.name;\n\t\t\t\t\t\tif (!Array.isArray(value.$id)) {\n\t\t\t\t\t\t\tvalue.$filterByUnique = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// todo: composite ids\n\t\t\t\t\t\tif (currentSchema?.idFields?.length === 1) {\n\t\t\t\t\t\t\tconst [idField] = currentSchema.idFields;\n\t\t\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\t\t\tvalue.$filter = { ...value.$filter, ...{ [idField]: value.$id } };\n\t\t\t\t\t\t\tdelete value.$id;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tthrow new Error('Multiple ids not yet enabled / composite ids');\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if ('$entity' in value || '$relation' in value) {\n\t\t\t\t\t\tconst currentSchema = getCurrentSchema(schema, value);\n\t\t\t\t\t\tvalue.$path = currentSchema.name;\n\t\t\t\t\t\tvalue.$as = currentSchema.name;\n\t\t\t\t\t}\n\t\t\t\t\t// 2. Converting $entity or $relation into $thingType and $thing\n\t\t\t\t\tif (value.$entity) {\n\t\t\t\t\t\tvalue.$thing = value.$entity;\n\t\t\t\t\t\tvalue.$thingType = 'entity';\n\t\t\t\t\t\tdelete value.$entity;\n\t\t\t\t\t} else if (value.$relation) {\n\t\t\t\t\t\tvalue.$thing = value.$relation;\n\t\t\t\t\t\tvalue.$thingType = 'relation';\n\t\t\t\t\t\tdelete value.$relation;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (isObject(value) && '$thing' in value) {\n\t\t\t\t\t\tconst node = value.$entity || value.$relation ? value : { [`$${value.$thingType}`]: value.$thing };\n\t\t\t\t\t\tconst currentSchema = getCurrentSchema(schema, node);\n\t\t\t\t\t\tif (value.$filter) {\n\t\t\t\t\t\t\tvalue.$filterByUnique = checkFilterByUnique(value.$filter, currentSchema);\n\t\t\t\t\t\t\tif (!value.$filterProcessed) {\n\t\t\t\t\t\t\t\tvalue.$filter = processFilter(value.$filter, currentSchema);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// if no fields, then it's all fields\n\t\t\t\t\t\tif (value.$fields) {\n\t\t\t\t\t\t\tconst idFieldIncluded =\n\t\t\t\t\t\t\t\tvalue.$fields.filter(\n\t\t\t\t\t\t\t\t\t(field: any) =>\n\t\t\t\t\t\t\t\t\t\tcurrentSchema?.idFields?.includes(field) || currentSchema?.idFields?.includes(field.$path),\n\t\t\t\t\t\t\t\t).length > 0;\n\t\t\t\t\t\t\tif (!idFieldIncluded) {\n\t\t\t\t\t\t\t\tvalue.$fields = [...value.$fields, ...currentSchema.idFields];\n\t\t\t\t\t\t\t\tvalue.$idNotIncluded = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst newFields = value.$fields\n\t\t\t\t\t\t\t\t?.flatMap((field: any) => {\n\t\t\t\t\t\t\t\t\tconst processed = processField(field, currentSchema);\n\t\t\t\t\t\t\t\t\tif (Array.isArray(processed)) {\n\t\t\t\t\t\t\t\t\t\treturn processed;\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\treturn [processed];\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t.filter(Boolean);\n\t\t\t\t\t\t\tvalue.$fields = newFields;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tconst allFields = getAllFields(currentSchema);\n\t\t\t\t\t\t\tconst newFields = allFields\n\t\t\t\t\t\t\t\t?.flatMap((field: any) => {\n\t\t\t\t\t\t\t\t\tconst processed = processField(field, currentSchema);\n\t\t\t\t\t\t\t\t\tif (Array.isArray(processed)) {\n\t\t\t\t\t\t\t\t\t\treturn processed;\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\treturn [processed];\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t.filter(Boolean);\n\t\t\t\t\t\t\tvalue.$fields = newFields;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (value.$excludedFields) {\n\t\t\t\t\t\t\tvalue.$fields = value.$fields.filter((f: { $path: string }) => !value.$excludedFields.includes(f.$path));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\t};\n\n\tconst enrichedBqlQuery = parser(Array.isArray(rawBqlQuery) ? rawBqlQuery : [rawBqlQuery]);\n\t// console.log('enrichedBqlQuery', JSON.stringify(enrichedBqlQuery, null, 2));\n\n\treq.enrichedBqlQuery = enrichedBqlQuery;\n};\n","import { TransactionType } from 'typedb-driver';\n\nimport type { PipelineOperation } from '../pipeline';\nimport { getSessionOrOpenNewOne } from './helpers';\nimport { parallel } from 'radash';\n\nexport const newRunTQLQuery: PipelineOperation = async (req, res) => {\n\tconst { dbHandles, enrichedBqlQuery, tqlRequest, config } = req;\n\tif (!enrichedBqlQuery) {\n\t\tthrow new Error('BQL request not parsed');\n\t}\n\tif (!tqlRequest) {\n\t\tthrow new Error('TQL request not built');\n\t}\n\t// console.log('tqlRequest', tqlRequest);\n\tconst isBatched = Array.isArray(tqlRequest);\n\tif (isBatched) {\n\t\tconst resArray = await parallel(tqlRequest.length, tqlRequest, async (queryString) => {\n\t\t\tconst { session } = await getSessionOrOpenNewOne(dbHandles, config);\n\n\t\t\tconst transaction = await session.transaction(TransactionType.READ);\n\t\t\tif (!transaction) {\n\t\t\t\tthrow new Error(\"Can't create transaction\");\n\t\t\t}\n\t\t\tconst tqlStream = transaction.query.fetch(queryString as string);\n\t\t\tconst tqlRes = await tqlStream.collect();\n\t\t\tawait transaction.close();\n\t\t\treturn tqlRes;\n\t\t});\n\t\t// todo: type the rawTqlRes\n\t\t// @ts-expect-error todo\n\t\tres.rawTqlRes = resArray;\n\t\tres.isBatched = true;\n\t} else {\n\t\tconst { session } = await getSessionOrOpenNewOne(dbHandles, config);\n\n\t\tconst transaction = await session.transaction(TransactionType.READ);\n\t\tif (!transaction) {\n\t\t\tthrow new Error(\"Can't create transaction\");\n\t\t}\n\t\tconst tqlStream = transaction.query.fetch(tqlRequest as string);\n\t\tconst tqlRes = await tqlStream.collect();\n\t\t// console.log('tqlRes', JSON.stringify(tqlRes, null, 2));\n\n\t\tawait transaction.close();\n\n\t\t// todo: type the rawTqlRes\n\t\t// @ts-expect-error todo\n\t\tres.rawTqlRes = tqlRes;\n\t}\n};\n","import { compute } from '../../engine/compute';\nimport { getCurrentSchema } from '../../helpers';\nimport type { EnrichedBormEntity, EnrichedBormRelation } from '../../types';\nimport type { PipelineOperation } from '../pipeline';\n\nconst parseMetaData = (str: string) => {\n\tconst asRegex = /as:([a-zA-Z0-9_\\-·]+)/;\n\tconst justIdRegex = /justId:([a-zA-Z0-9_\\-·]+)/;\n\tconst idNotIncludedRegex = /idNotIncluded:([a-zA-Z0-9_\\-·]+)/;\n\tconst filterByUniqueRegex = /filterByUnique:([a-zA-Z0-9_\\-·]+)/;\n\n\tconst asMatch = str.match(asRegex);\n\tconst justIdMatch = str.match(justIdRegex);\n\tconst idNotIncludedMatch = str.match(idNotIncludedRegex);\n\tconst filterByUniqueMatch = str.match(filterByUniqueRegex);\n\n\treturn {\n\t\tas: asMatch ? asMatch[1] : null,\n\t\tjustId: justIdMatch ? justIdMatch[1] : null,\n\t\tidNotIncluded: idNotIncludedMatch ? idNotIncludedMatch[1] : null,\n\t\tfilterByUnique: filterByUniqueMatch ? filterByUniqueMatch[1] : null,\n\t};\n};\n\nconst parseArrayMetadata = (str: string) => {\n\ttry {\n\t\tconst convertToJson = (str: string) => {\n\t\t\t// Remove $metadata: from the string\n\t\t\tlet jsonString = str.replace('$metadata:', '');\n\n\t\t\t// Enclose keys in quotes\n\t\t\tjsonString = jsonString.replace(/([a-zA-Z0-9_\\-·]+)(?=:)/g, '\"$1\"');\n\n\t\t\t// Enclose values in quotes, handling nested object values separately\n\t\t\tjsonString = jsonString.replace(/:(\\s*)([a-zA-Z0-9_\\-·]+)/g, (match, p1, p2) => {\n\t\t\t\t// Check if the value is part of an object\n\t\t\t\tif (/^{.*}$/.test(p2)) {\n\t\t\t\t\treturn `:${p2}`;\n\t\t\t\t} else {\n\t\t\t\t\treturn `:${p1}\"${p2}\"`;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t// Convert array elements (non-object) to strings\n\t\t\tjsonString = jsonString.replace(/\\[([^\\]]+)\\]/g, (match, p1) => {\n\t\t\t\treturn `[${p1\n\t\t\t\t\t.split(',')\n\t\t\t\t\t.map((s: string) => {\n\t\t\t\t\t\t// Check if element is an object-like structure\n\t\t\t\t\t\tif (s.trim().startsWith('{') && s.trim().endsWith('}')) {\n\t\t\t\t\t\t\treturn s.trim();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treturn `\"${s.trim()}\"`;\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\t.join(',')}]`;\n\t\t\t});\n\n\t\t\treturn jsonString;\n\t\t};\n\t\tconst converted = convertToJson(str);\n\n\t\tconst parsed = JSON.parse(converted);\n\t\treturn parsed;\n\t} catch (e) {\n\t\tconsole.error(e);\n\t\treturn { as: [], virtual: [] };\n\t}\n};\n\nexport const parseTQLQuery: PipelineOperation = async (req, res) => {\n\tconst { enrichedBqlQuery, rawBqlRequest, schema, config } = req;\n\tconst { rawTqlRes, isBatched } = res;\n\tif (!enrichedBqlQuery) {\n\t\tthrow new Error('BQL request not enriched');\n\t} else if (!rawTqlRes) {\n\t\tthrow new Error('TQL query not executed');\n\t}\n\t// console.log('parse.rawTqlRes', JSON.stringify(rawTqlRes, null, 2));\n\t// console.log('rawBqlRequest', JSON.stringify(rawBqlRequest, null, 2));\n\n\tconst parseDataFields = (dataFields: any, currentSchema: EnrichedBormEntity | EnrichedBormRelation) => {\n\t\tconst { $metaData } = dataFields;\n\t\tconst { as: $as, virtual } = parseArrayMetadata($metaData);\n\n\t\t// Process the main data fields\n\t\tconst mainDataFields = Object.entries(dataFields)\n\t\t\t.filter(([key]) => key !== 'type' && !key.includes('$'))\n\t\t\t.map(([key, value]) => {\n\t\t\t\tconst field = currentSchema.dataFields?.find((f) => f.path === key || f.dbPath === key);\n\t\t\t\tconst isIdField = key === 'id';\n\t\t\t\tconst $asKey = Array.isArray($as) ? $as.find((o) => o[key])?.[key] : key;\n\t\t\t\tlet fieldValue;\n\t\t\t\tif (field?.cardinality === 'ONE') {\n\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\tfieldValue = value[0] ? value[0].value : config.query?.returnNulls ? null : undefined;\n\t\t\t\t\tif (isIdField && !config.query?.noMetadata) {\n\t\t\t\t\t\treturn [\n\t\t\t\t\t\t\t[$asKey, fieldValue],\n\t\t\t\t\t\t\t['$id', fieldValue],\n\t\t\t\t\t\t].filter(([_, v]) => v !== undefined);\n\t\t\t\t\t}\n\t\t\t\t} else if (field?.cardinality === 'MANY') {\n\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\tfieldValue = value.map((o) => o.value);\n\t\t\t\t}\n\t\t\t\treturn [[$asKey, fieldValue]].filter(([_, v]) => v !== undefined);\n\t\t\t})\n\t\t\t.flat();\n\n\t\t// Process virtual fields\n\t\tconst virtualFields = virtual.map((key: string) => {\n\t\t\tconst $asKey = $as.find((o: any) => o[key])?.[key];\n\t\t\tconst field = currentSchema.dataFields?.find((f) => f.isVirtual && f.dbPath === key);\n\t\t\tconst computedValue = compute({ currentThing: Object.fromEntries(mainDataFields), fieldSchema: field });\n\t\t\treturn [$asKey, computedValue];\n\t\t});\n\n\t\treturn Object.fromEntries([...mainDataFields, ...virtualFields]);\n\t};\n\n\tconst parseRoleFields = (\n\t\troleFields: { $roleFields: object[]; $key: string; $metaData: string; $cardinality: 'MANY' | 'ONE' }[],\n\t) => {\n\t\treturn roleFields.reduce((roleFieldsRes, roleField) => {\n\t\t\tconst { $roleFields, $metaData, $cardinality } = roleField;\n\t\t\tconst { as, justId, idNotIncluded, filterByUnique } = parseMetaData($metaData);\n\n\t\t\tconst items = $roleFields.map((item) => {\n\t\t\t\tconst { dataFields, currentSchema, linkFields, roleFields, schemaValue } = parseFields(item);\n\t\t\t\tconst parsedDataFields = parseDataFields(dataFields, currentSchema);\n\n\t\t\t\tif (justId === 'T') {\n\t\t\t\t\treturn parsedDataFields.id;\n\t\t\t\t} else {\n\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\tconst parsedLinkFields = parseLinkFields(linkFields);\n\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\tconst parsedRoleFields = parseRoleFields(roleFields);\n\t\t\t\t\tconst resDataFields = { ...parsedDataFields };\n\t\t\t\t\tif (idNotIncluded === 'true') {\n\t\t\t\t\t\tcurrentSchema?.idFields?.forEach((field) => delete resDataFields[field]);\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\t...resDataFields,\n\t\t\t\t\t\t...parsedLinkFields,\n\t\t\t\t\t\t...parsedRoleFields,\n\t\t\t\t\t\t...(!config.query?.noMetadata && { ...schemaValue }),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tif (items.length > 0) {\n\t\t\t\t// @ts-expect-error todo\n\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\troleFieldsRes[as] = $cardinality === 'MANY' && filterByUnique === 'false' ? items : items[0];\n\t\t\t} else if (config.query?.returnNulls) {\n\t\t\t\t// @ts-expect-error todo\n\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\troleFieldsRes[as] = null;\n\t\t\t}\n\n\t\t\treturn roleFieldsRes;\n\t\t}, {});\n\t};\n\n\tconst parseLinkFields = (\n\t\tlinkFields: { $linkFields: object[]; $key: string; $metaData: string; $cardinality: 'MANY' | 'ONE' }[],\n\t) => {\n\t\treturn linkFields.reduce((linkFieldsRes, linkField) => {\n\t\t\tconst { $linkFields, $metaData, $cardinality } = linkField;\n\t\t\tconst { as, justId, idNotIncluded, filterByUnique } = parseMetaData($metaData);\n\n\t\t\tconst items = $linkFields.map((item) => {\n\t\t\t\tconst { dataFields, currentSchema, linkFields, roleFields, schemaValue } = parseFields(item);\n\t\t\t\tconst parsedDataFields = parseDataFields(dataFields, currentSchema);\n\n\t\t\t\tif (justId === 'T') {\n\t\t\t\t\treturn parsedDataFields.id;\n\t\t\t\t} else {\n\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\tconst parsedLinkFields = parseLinkFields(linkFields);\n\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\tconst parsedRoleFields = parseRoleFields(roleFields);\n\t\t\t\t\tconst resDataFields = { ...parsedDataFields };\n\n\t\t\t\t\tif (idNotIncluded === 'true') {\n\t\t\t\t\t\tcurrentSchema.idFields?.forEach((field) => delete resDataFields[field]);\n\t\t\t\t\t}\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\t...resDataFields,\n\t\t\t\t\t\t...parsedLinkFields,\n\t\t\t\t\t\t...parsedRoleFields,\n\t\t\t\t\t\t...(!config.query?.noMetadata && { ...schemaValue }),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t// @ts-expect-error todo\n\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\tlinkFieldsRes[as] =\n\t\t\t\titems.length > 0\n\t\t\t\t\t? $cardinality === 'MANY' && filterByUnique === 'false'\n\t\t\t\t\t\t? items\n\t\t\t\t\t\t: items[0]\n\t\t\t\t\t: config.query?.returnNulls\n\t\t\t\t\t? null\n\t\t\t\t\t: undefined;\n\n\t\t\treturn linkFieldsRes;\n\t\t}, {});\n\t};\n\n\tconst parseFields = (obj: any) => {\n\t\tconst keys = Object.keys(obj);\n\n\t\t// Find and process $dataFields\n\t\tconst dataFieldsKey = keys.find((key) => key.endsWith('.$dataFields'));\n\t\tif (!dataFieldsKey) {\n\t\t\tthrow new Error('No datafields');\n\t\t}\n\n\t\tconst dataFields = obj[dataFieldsKey];\n\t\tconst metaDataKey = dataFieldsKey.split('.')[dataFieldsKey.split('.').length - 2];\n\t\tdataFields.$metaData = metaDataKey;\n\n\t\tif (dataFields.length === 0) {\n\t\t\tthrow new Error('No datafields');\n\t\t}\n\n\t\tconst dataFieldsThing = dataFields.type;\n\t\tconst schemaValue = {\n\t\t\t$thing: dataFieldsThing.label,\n\t\t\t$thingType: dataFieldsThing.root,\n\t\t};\n\t\tconst node = { [`$${schemaValue.$thingType}`]: schemaValue.$thing };\n\t\tconst currentSchema = getCurrentSchema(schema, node);\n\n\t\t// Process linkFields and roleFields\n\t\tconst linkFields = keys\n\t\t\t.filter(\n\t\t\t\t(key) =>\n\t\t\t\t\t!key.endsWith('.$dataFields') && currentSchema.linkFields?.some((o) => o.path === key.split('.').pop()),\n\t\t\t)\n\t\t\t.map((key) => ({\n\t\t\t\t$linkFields: obj[key],\n\t\t\t\t$key: key.split('.').pop(),\n\t\t\t\t$metaData: key.split('.')[key.split('.').length - 2],\n\t\t\t\t$cardinality: currentSchema?.linkFields?.find((o) => o.path === key.split('.').pop())?.cardinality,\n\t\t\t}));\n\n\t\tconst roleFields = keys\n\t\t\t// @ts-expect-error todo\n\t\t\t.filter((key) => !key.endsWith('.$dataFields') && currentSchema.roles?.[key.split('.').pop()])\n\t\t\t.map((key) => ({\n\t\t\t\t$roleFields: obj[key],\n\t\t\t\t$key: key.split('.').pop(),\n\t\t\t\t$metaData: key.split('.')[key.split('.').length - 2],\n\t\t\t\t// @ts-expect-error todo\n\t\t\t\t$cardinality: currentSchema.roles[key.split('.').pop()].cardinality,\n\t\t\t}));\n\n\t\treturn { dataFields, schemaValue, currentSchema, linkFields, roleFields };\n\t};\n\n\tconst realParse = (tqlRes: any) => {\n\t\treturn tqlRes.map((resItem: any) => {\n\t\t\tconst { dataFields, currentSchema, linkFields, roleFields, schemaValue } = parseFields(resItem);\n\t\t\tconst parsedDataFields = parseDataFields(dataFields, currentSchema);\n\t\t\t// @ts-expect-error todo\n\t\t\tconst parsedLinkFields = parseLinkFields(linkFields);\n\t\t\t// @ts-expect-error todo\n\t\t\tconst parsedRoleFields = parseRoleFields(roleFields);\n\n\t\t\tconst idNotIncluded = rawBqlRequest?.$fields?.every(\n\t\t\t\t// @ts-expect-error todo\n\t\t\t\t(field) => !currentSchema?.idFields?.includes(field) && !currentSchema?.idFields?.includes(field.$path),\n\t\t\t);\n\n\t\t\tconst finalObj = {\n\t\t\t\t...parsedLinkFields,\n\t\t\t\t...parsedRoleFields,\n\t\t\t\t...(!config.query?.noMetadata ? { ...schemaValue } : {}),\n\t\t\t\t...(!config.query?.noMetadata && rawBqlRequest.$id\n\t\t\t\t\t? { $id: Array.isArray(rawBqlRequest.$id) ? parsedDataFields['id'] : rawBqlRequest.$id }\n\t\t\t\t\t: {}),\n\t\t\t\t...(idNotIncluded\n\t\t\t\t\t? Object.fromEntries(\n\t\t\t\t\t\t\tObject.entries(parsedDataFields).filter(([key]) => !currentSchema?.idFields?.includes(key)),\n\t\t\t\t\t )\n\t\t\t\t\t: parsedDataFields),\n\t\t\t};\n\n\t\t\treturn finalObj;\n\t\t});\n\t};\n\n\tconst parser = (tqlRes: any) => {\n\t\tconst processResponse = (resItems: any) => {\n\t\t\tconst parsedItems = realParse(resItems);\n\t\t\treturn (rawBqlRequest.$id && !Array.isArray(rawBqlRequest.$id)) || enrichedBqlQuery[0].$filterByUnique\n\t\t\t\t? parsedItems[0] ?? null\n\t\t\t\t: parsedItems.length === 0\n\t\t\t\t? null\n\t\t\t\t: parsedItems;\n\t\t};\n\n\t\treturn isBatched ? tqlRes.map(processResponse) : processResponse(tqlRes);\n\t};\n\n\tconst parsedTqlRes = parser(rawTqlRes);\n\t// console.log('parsedTqlRes', JSON.stringify(parsedTqlRes, null, 2));\n\tres.bqlRes = parsedTqlRes;\n\t// console.log('enrichedBqlQuery', JSON.stringify(enrichedBqlQuery, null, 2));\n};\n","import { traverse } from 'object-traversal';\nimport { queryPipeline, type PipelineOperation } from '../pipeline';\nimport type { FilledBQLMutationBlock } from '../../types';\nimport { isObject } from 'radash';\nimport { produce } from 'immer';\nimport { getCurrentSchema } from '../../helpers';\nimport { v4 as uuidv4 } from 'uuid';\n\nexport const preQueryPathSeparator = '___';\ntype ObjectPath = { beforePath: string; ids: string | string[]; key: string };\n\nexport const newPreQuery: PipelineOperation = async (req) => {\n\tconst { filledBqlRequest, config, schema } = req;\n\n\tconst getFieldKeys = (block: FilledBQLMutationBlock, noDataFields?: boolean) => {\n\t\treturn Object.keys(block).filter((key) => {\n\t\t\tif (!key.startsWith('$')) {\n\t\t\t\tif (noDataFields) {\n\t\t\t\t\tconst currentSchema = getCurrentSchema(schema, block);\n\t\t\t\t\tif (!currentSchema.dataFields?.find((field) => field.path === key)) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t});\n\t};\n\n\tif (!filledBqlRequest) {\n\t\tthrow new Error('[BQLE-M-0] No filledBqlRequest found');\n\t}\n\n\tconsole.log('filledBql: ', JSON.stringify(filledBqlRequest, null, 2));\n\n\t// 1. Check config for pre-query === true\n\t// todo: If false, remove the replace conversion in enrich step\n\tif (config.mutation?.preQuery === false) {\n\t\treturn;\n\t}\n\n\t// 2. Check operations to make sure they include: Delete, Unlink, Link, Replace, Updater\n\tconst ops: string[] = [];\n\n\ttraverse(filledBqlRequest, ({ parent, key, value }) => {\n\t\t// if (key === '$op') {\n\t\t// \tif (!ops.includes(value) && parent) {\n\t\t// \t\tops.push(value);\n\t\t// \t}\n\t\t// }\n\t\tif (parent && key && !key.includes('$') && isObject(parent)) {\n\t\t\tconst values = Array.isArray(parent[key]) ? parent[key] : [parent[key]];\n\t\t\t// @ts-expect-error todo\n\t\t\tvalues.forEach((val) => {\n\t\t\t\tif (isObject(val)) {\n\t\t\t\t\tif (parent.$op !== 'create') {\n\t\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\t\tif (!ops.includes(val.$op)) {\n\t\t\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\t\t\tops.push(val.$op);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\t\tif (val.$op === 'delete' || val.$op === 'unlink') {\n\t\t\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\t\t\tthrow new Error(`Cannot ${val.$op} under a create`);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t} else if (!parent && isObject(value)) {\n\t\t\t// @ts-expect-error todo\n\t\t\tif (!ops.includes(value.$op)) {\n\t\t\t\t// @ts-expect-error todo\n\t\t\t\tops.push(value.$op);\n\t\t\t}\n\t\t}\n\t});\n\n\tif (\n\t\t!ops.includes('delete') &&\n\t\t!ops.includes('unlink') &&\n\t\t!ops.includes('replace') &&\n\t\t!ops.includes('update') &&\n\t\t!ops.includes('link')\n\t) {\n\t\treturn;\n\t}\n\n\tconst convertMutationToQuery = (blocks: FilledBQLMutationBlock[]) => {\n\t\tconst processBlock = (block: FilledBQLMutationBlock, root?: boolean) => {\n\t\t\tconst $fields: any[] = [];\n\t\t\tconst filteredBlock = {};\n\t\t\tconst toRemoveFromRoot = ['$op', '$bzId', '$parentKey'];\n\t\t\tconst toRemove = ['$relation', '$entity', '$id', ...toRemoveFromRoot];\n\t\t\tfor (const k in block) {\n\t\t\t\tif (toRemoveFromRoot.includes(k)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (toRemove.includes(k) && !root) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!k.includes('$') && (isObject(block[k]) || Array.isArray(block[k]))) {\n\t\t\t\t\tconst v = block[k];\n\t\t\t\t\tif (Array.isArray(v) && v.length > 0) {\n\t\t\t\t\t\tv.forEach((opBlock) => {\n\t\t\t\t\t\t\t// const includedKeys = Object.keys(opBlock)\n\t\t\t\t\t\t\t// \t.filter((o) => !o.startsWith('$'))\n\t\t\t\t\t\t\t// \t.join('__');\n\n\t\t\t\t\t\t\t$fields.push({\n\t\t\t\t\t\t\t\t$path: k,\n\t\t\t\t\t\t\t\t...processBlock(opBlock),\n\t\t\t\t\t\t\t\t// $as: opBlock.$bzId,\n\t\t\t\t\t\t\t\t// $as: `${k}_${includedKeys}`,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$fields.push({\n\t\t\t\t\t\t\t$path: k,\n\t\t\t\t\t\t\t...processBlock(v),\n\t\t\t\t\t\t\t// $as: v.$bzId,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\tfilteredBlock[k] = block[k];\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn {\n\t\t\t\t...filteredBlock,\n\t\t\t\t$fields,\n\t\t\t\t// $as: block.$bzId,\n\t\t\t};\n\t\t};\n\t\treturn blocks.map((block) => processBlock(block, true));\n\t};\n\n\tconst preQueryReq = convertMutationToQuery(Array.isArray(filledBqlRequest) ? filledBqlRequest : [filledBqlRequest]);\n\n\t// console.log('preQueryReq', JSON.stringify(preQueryReq, null, 2));\n\n\t// @ts-expect-error todo\n\tconst preQueryRes = await queryPipeline(preQueryReq, req.config, req.schema, req.dbHandles);\n\t// console.log('preQueryRes', JSON.stringify(preQueryRes, null, 2));\n\n\tconst getObjectPath = (parent: any, key: string) => {\n\t\tconst idField: string | string[] = parent.$id || parent.id || parent.$bzId;\n\t\tif (parent.$objectPath) {\n\t\t\tconst { $objectPath } = parent;\n\n\t\t\tconst root = $objectPath?.beforePath || 'root';\n\t\t\tconst ids = Array.isArray($objectPath.ids) ? `[${$objectPath.ids}]` : $objectPath.ids;\n\t\t\tconst final = `${root}.${ids}___${$objectPath.key}`;\n\n\t\t\tconst new$objectPath = {\n\t\t\t\tbeforePath: final,\n\t\t\t\tids: idField,\n\t\t\t\tkey,\n\t\t\t};\n\t\t\treturn new$objectPath;\n\t\t} else {\n\t\t\treturn {\n\t\t\t\tbeforePath: 'root',\n\t\t\t\tids: idField,\n\t\t\t\tkey,\n\t\t\t};\n\t\t}\n\n\t\t// return `${parent.$objectPath || 'root'}${idField ? `.${idField}` : ''}${preQueryPathSeparator}${key}`;\n\t};\n\n\tconst objectPathToKey = ($objectPath: ObjectPath, hardId?: string) => {\n\t\tconst root = $objectPath?.beforePath || 'root';\n\t\tconst ids = hardId ? hardId : Array.isArray($objectPath?.ids) ? `[${$objectPath?.ids}]` : $objectPath?.ids;\n\n\t\tconst final = `${root}.${ids}___${$objectPath?.key}`;\n\t\treturn final;\n\t};\n\n\tconst convertManyPaths = (input: string) => {\n\t\t// Check if the string contains square brackets\n\t\tif (input.includes('[') && input.includes(']')) {\n\t\t\t// Extract the part before the brackets, the items within the brackets, and the part after the brackets\n\t\t\tconst [prefix, itemsWithBrackets, suffix] = input.split(/[[\\]]/);\n\t\t\tconst items = itemsWithBrackets.split(',');\n\n\t\t\t// Combine each item with the prefix and suffix and return the array\n\t\t\treturn items.map((item) => `${prefix}${item}${suffix}`);\n\t\t} else {\n\t\t\t// If no brackets are present, return an array with the original string\n\t\t\treturn [input];\n\t\t}\n\t};\n\n\t// 3. Create cache of paths\n\ttype Cache<K extends string, V extends string> = {\n\t\t[key in K]: V;\n\t};\n\tconst cache: Cache<string, string> = {};\n\tconst cachePaths = (\n\t\tblocks: FilledBQLMutationBlock | FilledBQLMutationBlock[],\n\t): FilledBQLMutationBlock | FilledBQLMutationBlock[] => {\n\t\treturn produce(blocks, (draft) =>\n\t\t\ttraverse(draft, (context) => {\n\t\t\t\tconst { key, parent } = context;\n\n\t\t\t\tif (parent && key && parent.$id && !key.includes('$')) {\n\t\t\t\t\tconst newObjPath = getObjectPath(parent, key);\n\t\t\t\t\tconst cacheKey = objectPathToKey(newObjPath);\n\t\t\t\t\tif (Array.isArray(parent[key])) {\n\t\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\t\tconst cacheArray = [];\n\t\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\t\tparent[key].forEach((val) => {\n\t\t\t\t\t\t\tif (isObject(val)) {\n\t\t\t\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\t\t\t\t\tval.$objectPath = newObjPath;\n\t\t\t\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\t\t\t\tcacheArray.push(val.$id.toString());\n\t\t\t\t\t\t\t} else if (val) {\n\t\t\t\t\t\t\t\tcacheArray.push(val.toString());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\t\tcache[cacheKey] = { $objectPath: newObjPath, $ids: cacheArray };\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst val = parent[key];\n\t\t\t\t\t\tif (isObject(val)) {\n\t\t\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\t\t\tcache[cacheKey] = { $objectPath: newObjPath, $ids: [val.$id.toString()] };\n\n\t\t\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\t\t\t\tval.$objectPath = newObjPath;\n\t\t\t\t\t\t} else if (val) {\n\t\t\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\t\t\tcache[cacheKey] = { $objectPath: newObjPath, $ids: [val.toString()] };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\t};\n\t// @ts-expect-error todo\n\tcachePaths(preQueryRes || {});\n\n\t// console.log('cache', JSON.stringify(cache, null, 2));\n\n\tconst fillObjectPaths = (\n\t\tblocks: FilledBQLMutationBlock | FilledBQLMutationBlock[],\n\t): FilledBQLMutationBlock | FilledBQLMutationBlock[] => {\n\t\treturn produce(blocks, (draft) =>\n\t\t\ttraverse(draft, (context) => {\n\t\t\t\tconst { key, value, parent } = context;\n\t\t\t\tif (\n\t\t\t\t\tparent &&\n\t\t\t\t\tkey &&\n\t\t\t\t\t!key.includes('$') &&\n\t\t\t\t\t(Array.isArray(value) || isObject(value)) &&\n\t\t\t\t\t!Array.isArray(parent)\n\t\t\t\t) {\n\t\t\t\t\tif (Array.isArray(parent[key])) {\n\t\t\t\t\t\tparent[key].forEach(\n\t\t\t\t\t\t\t(o: string | { $objectPath: ObjectPath; $parentIsCreate: boolean; $grandChildOfCreate: boolean }) => {\n\t\t\t\t\t\t\t\tif (typeof o !== 'string') {\n\t\t\t\t\t\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\t\t\t\t\t\to.$objectPath = getObjectPath(parent, key);\n\t\t\t\t\t\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\t\t\t\t\t\to.$parentIsCreate = parent.$op === 'create';\n\t\t\t\t\t\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\t\t\t\t\t\to.$grandChildOfCreate = parent.$parentIsCreate || parent.$grandChildOfCreate;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t} else if (isObject(parent[key])) {\n\t\t\t\t\t\tparent[key].$parentIsCreate = parent.$op === 'create';\n\t\t\t\t\t\tparent[key].$grandChildOfCreate = parent.$parentIsCreate || parent.$grandChildOfCreate;\n\t\t\t\t\t\tparent[key].$objectPath = getObjectPath(parent, key);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\t};\n\n\tconst bqlWithObjectPaths = fillObjectPaths(filledBqlRequest);\n\n\tconst splitBzIds = (blocks: FilledBQLMutationBlock[]) => {\n\t\tconst processBlocks = (\n\t\t\toperationBlocks: FilledBQLMutationBlock[],\n\t\t\tparentOperationBlock?: FilledBQLMutationBlock,\n\t\t) => {\n\t\t\tlet processIds: FilledBQLMutationBlock[] = [];\n\t\t\toperationBlocks.forEach((operationBlock) => {\n\t\t\t\tconst fieldCount = Object.keys(operationBlock).filter((key) => !key.startsWith('$')).length;\n\n\t\t\t\tif (Array.isArray(operationBlock.$id) && fieldCount > 0) {\n\t\t\t\t\tconst splitBlocksById = operationBlock.$id.map((id) => {\n\t\t\t\t\t\treturn { ...operationBlock, $id: id };\n\t\t\t\t\t});\n\t\t\t\t\tprocessIds = [...processIds, ...splitBlocksById];\n\t\t\t\t} else {\n\t\t\t\t\tprocessIds.push(operationBlock);\n\t\t\t\t}\n\t\t\t});\n\t\t\tlet newOperationBlocks: FilledBQLMutationBlock[] = [];\n\t\t\tconst fieldsWithoutMultiples: FilledBQLMutationBlock[] = [];\n\t\t\tconst fieldsWithMultiples = processIds.filter((operationBlock) => {\n\t\t\t\tconst ops = ['delete', 'update', 'unlink'];\n\t\t\t\t// Block must have one of the above operations\n\t\t\t\tconst isCorrectOp = ops.includes(operationBlock.$op || '');\n\t\t\t\tconst fieldCount = Object.keys(operationBlock).filter((key) => !key.startsWith('$')).length;\n\t\t\t\t// Block must either not have $id, have an array of $ids, or have a filter\n\t\t\t\tconst isMultiple =\n\t\t\t\t\t!operationBlock.$id || (Array.isArray(operationBlock.$id) && fieldCount > 0) || operationBlock.$filter;\n\t\t\t\tif (isMultiple && isCorrectOp) {\n\t\t\t\t\treturn true;\n\t\t\t\t} else {\n\t\t\t\t\tfieldsWithoutMultiples.push(operationBlock);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tif (fieldsWithMultiples.length > 0) {\n\t\t\t\tfieldsWithMultiples.forEach((opBlock) => {\n\t\t\t\t\tconst getAllKeyCombinations = (obj: FilledBQLMutationBlock) => {\n\t\t\t\t\t\t// Get all keys, but only use non-$ keys for generating combinations\n\t\t\t\t\t\tconst allKeys = Object.keys(obj);\n\t\t\t\t\t\tconst combinableKeys = allKeys.filter((key) => !key.startsWith('$'));\n\n\t\t\t\t\t\tconst allCombinations: FilledBQLMutationBlock[] = [];\n\n\t\t\t\t\t\tconst generateCombinations = (index: number, currentObj: FilledBQLMutationBlock) => {\n\t\t\t\t\t\t\tif (index === combinableKeys.length) {\n\t\t\t\t\t\t\t\t// Construct the full object with the current id\n\t\t\t\t\t\t\t\tconst fullObj = { ...currentObj };\n\t\t\t\t\t\t\t\tallKeys.forEach((key) => {\n\t\t\t\t\t\t\t\t\tif (key.startsWith('$')) {\n\t\t\t\t\t\t\t\t\t\tfullObj[key] = obj[key];\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tallCombinations.push(fullObj);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Include the current key\n\t\t\t\t\t\t\tconst newObjInclude = { ...currentObj, [combinableKeys[index]]: obj[combinableKeys[index]] };\n\t\t\t\t\t\t\tgenerateCombinations(index + 1, newObjInclude);\n\n\t\t\t\t\t\t\t// Exclude the current key and move to the next\n\t\t\t\t\t\t\tgenerateCombinations(index + 1, currentObj);\n\t\t\t\t\t\t};\n\t\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\t\tgenerateCombinations(0, {});\n\n\t\t\t\t\t\treturn allCombinations;\n\t\t\t\t\t};\n\t\t\t\t\tconst allCombinations: FilledBQLMutationBlock[] = getAllKeyCombinations(opBlock).filter(\n\t\t\t\t\t\t(opBlock) =>\n\t\t\t\t\t\t\t!(opBlock.$op === 'update' && Object.keys(opBlock).filter((key) => !key.startsWith('$')).length === 0),\n\t\t\t\t\t);\n\n\t\t\t\t\tlet included: string[] = [];\n\t\t\t\t\tconst emptyObjCKey = objectPathToKey(opBlock.$objectPath);\n\t\t\t\t\tconst cacheR = cache[emptyObjCKey];\n\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\tlet remaining: string[] = cacheR ? cache[emptyObjCKey].$ids : [];\n\t\t\t\t\tconst combinationsFromCache = allCombinations\n\t\t\t\t\t\t.map((combination: FilledBQLMutationBlock, index: number) => {\n\t\t\t\t\t\t\tconst _currentSchema = getCurrentSchema(schema, combination);\n\t\t\t\t\t\t\tconst combinableKeys = Object.keys(combination).filter(\n\t\t\t\t\t\t\t\t(fieldKey) => !fieldKey.includes('$') && !_currentSchema.dataFields?.some((o) => o.path === fieldKey),\n\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\tconst cachesFound = combinableKeys\n\t\t\t\t\t\t\t\t.map((key: string) => {\n\t\t\t\t\t\t\t\t\t// todo: test with adjacent operations that aren't multiples and also many multiples\n\t\t\t\t\t\t\t\t\tconst multiples = Array.isArray(combination[key])\n\t\t\t\t\t\t\t\t\t\t? combination[key].length > 1\n\t\t\t\t\t\t\t\t\t\t\t? combination[key].filter(\n\t\t\t\t\t\t\t\t\t\t\t\t\t(opBlock: FilledBQLMutationBlock) =>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t!opBlock.$id || Array.isArray(opBlock.$id) || opBlock.$filter,\n\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t: combination[key]\n\t\t\t\t\t\t\t\t\t\t: [combination[key]];\n\t\t\t\t\t\t\t\t\tconst processedMultiples = multiples.map((multiple: FilledBQLMutationBlock) => {\n\t\t\t\t\t\t\t\t\t\tconst cKey = objectPathToKey(multiple.$objectPath);\n\t\t\t\t\t\t\t\t\t\tconst getIdsToKey = (searchKey: string) => {\n\t\t\t\t\t\t\t\t\t\t\tconst ids = [];\n\t\t\t\t\t\t\t\t\t\t\tconst searchSegments = searchKey.split('.');\n\t\t\t\t\t\t\t\t\t\t\tconst starting = searchSegments.slice(0, searchSegments.length - 1).join('.');\n\t\t\t\t\t\t\t\t\t\t\t// eslint-disable-next-line prefer-destructuring\n\t\t\t\t\t\t\t\t\t\t\tconst ending = searchSegments\n\t\t\t\t\t\t\t\t\t\t\t\t.slice(searchSegments.length - 1, searchSegments.length)[0]\n\t\t\t\t\t\t\t\t\t\t\t\t.split('___')[1];\n\t\t\t\t\t\t\t\t\t\t\tfor (const key in cache) {\n\t\t\t\t\t\t\t\t\t\t\t\tif (key.startsWith(starting) && key.endsWith(ending)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst searchSegments = key.split('.');\n\t\t\t\t\t\t\t\t\t\t\t\t\t// eslint-disable-next-line prefer-destructuring\n\t\t\t\t\t\t\t\t\t\t\t\t\tconst id = searchSegments\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t.slice(searchSegments.length - 1, searchSegments.length)[0]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t.split('___')[0];\n\t\t\t\t\t\t\t\t\t\t\t\t\tids.push(id);\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\treturn ids;\n\t\t\t\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\t\t\t\tconst idsToKey = getIdsToKey(cKey);\n\t\t\t\t\t\t\t\t\t\treturn { idsToKey, key, multiple };\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\treturn processedMultiples;\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t.filter((key) => key !== undefined);\n\t\t\t\t\t\t\tconst findCommonIds = (\n\t\t\t\t\t\t\t\tdata: { idsToKey: string[]; key: string; multiple: FilledBQLMutationBlock }[][],\n\t\t\t\t\t\t\t) => {\n\t\t\t\t\t\t\t\tconst preppedArray = data.map((operations) => {\n\t\t\t\t\t\t\t\t\tconst ids = operations.map((operation) => {\n\t\t\t\t\t\t\t\t\t\treturn operation.idsToKey;\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\treturn ids;\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tconst findCommonElements = (arr: string[][][]) => {\n\t\t\t\t\t\t\t\t\tif (arr.length > 0) {\n\t\t\t\t\t\t\t\t\t\t// Flatten the array to two dimensions\n\n\t\t\t\t\t\t\t\t\t\tconst flatArray = arr.reduce((acc, val) => acc.concat(val), []);\n\n\t\t\t\t\t\t\t\t\t\t// Find common elements\n\t\t\t\t\t\t\t\t\t\treturn flatArray.reduce((acc, subArr) => {\n\t\t\t\t\t\t\t\t\t\t\tif (!acc) {\n\t\t\t\t\t\t\t\t\t\t\t\treturn subArr;\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\treturn subArr.filter((item) => acc.includes(item));\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\treturn [];\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\t\treturn findCommonElements(preppedArray);\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tconst commonIds = findCommonIds(cachesFound);\n\t\t\t\t\t\t\tconst filteredCommonIds = commonIds.filter((id) => !included.includes(id));\n\t\t\t\t\t\t\tincluded = [...included, ...filteredCommonIds];\n\t\t\t\t\t\t\tremaining = remaining.filter((id) => !filteredCommonIds.includes(id));\n\t\t\t\t\t\t\t// the last combination is always without the fields with multiples, so it's all remaining ids found in the cache\n\t\t\t\t\t\t\tif (index === allCombinations.length - 1 && remaining.length > 0) {\n\t\t\t\t\t\t\t\tconst newOp = {\n\t\t\t\t\t\t\t\t\t...combination,\n\t\t\t\t\t\t\t\t\t$id: remaining,\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\treturn newOp;\n\t\t\t\t\t\t\t} else if (filteredCommonIds.length > 0) {\n\t\t\t\t\t\t\t\tconst newOp = {\n\t\t\t\t\t\t\t\t\t...combination,\n\t\t\t\t\t\t\t\t\t$id: filteredCommonIds,\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\treturn newOp;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.filter((combination) => combination !== undefined);\n\t\t\t\t\t// console.log('combinationsFromCache', JSON.stringify(combinationsFromCache, null, 2));\n\t\t\t\t\tconst returnFields =\n\t\t\t\t\t\tcombinationsFromCache.length === 0 && !parentOperationBlock?.$id\n\t\t\t\t\t\t\t? fieldsWithMultiples\n\t\t\t\t\t\t\t: combinationsFromCache;\n\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\tnewOperationBlocks = [...fieldsWithoutMultiples, ...returnFields].map(processOperationBlock);\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tnewOperationBlocks = processIds.map(processOperationBlock);\n\t\t\t}\n\t\t\treturn newOperationBlocks;\n\t\t};\n\t\tconst processOperationBlock = (operationBlock: FilledBQLMutationBlock) => {\n\t\t\tconst newBlock: FilledBQLMutationBlock = { ...operationBlock, $bzId: `T_${uuidv4()}` };\n\t\t\tconst currentSchema = getCurrentSchema(schema, operationBlock);\n\t\t\tObject.keys(operationBlock)\n\t\t\t\t// field must be a roleField or linkField\n\t\t\t\t.filter((fieldKey) => !fieldKey.includes('$') && !currentSchema.dataFields?.some((o) => o.path === fieldKey))\n\t\t\t\t.forEach((fieldKey) => {\n\t\t\t\t\tconst operationBlocks: FilledBQLMutationBlock[] = Array.isArray(operationBlock[fieldKey])\n\t\t\t\t\t\t? operationBlock[fieldKey]\n\t\t\t\t\t\t: [operationBlock[fieldKey]];\n\t\t\t\t\tconst newOperationBlocks = processBlocks(operationBlocks, operationBlock);\n\t\t\t\t\tnewBlock[fieldKey] = newOperationBlocks;\n\t\t\t\t});\n\t\t\treturn newBlock;\n\t\t};\n\t\tlet newBlocks: FilledBQLMutationBlock[] = [];\n\t\t// For each root block in a potentially batched mutation\n\t\tblocks.forEach((block) => {\n\t\t\tnewBlocks = [...newBlocks, ...processBlocks([block])];\n\t\t});\n\t\t// todo: if the original blocks are the same keys, then find a way to keep them the same (without ids), but with their children processed\n\n\t\tconst splitBlocks = newBlocks.map(processOperationBlock);\n\t\treturn splitBlocks;\n\t};\n\n\t// console.log('filledBql', JSON.stringify([filledBqlRequest], null, 2));\n\n\tconst splitBql = splitBzIds(Array.isArray(bqlWithObjectPaths) ? bqlWithObjectPaths : [bqlWithObjectPaths]);\n\t// console.log('splitBql', JSON.stringify(splitBql, null, 2));\n\n\tconst processReplaces = (blocks: FilledBQLMutationBlock[]) => {\n\t\treturn blocks.map((block) => {\n\t\t\tconst fields = getFieldKeys(block, true);\n\t\t\tconst newBlock = { ...block };\n\t\t\t// console.log('block', JSON.stringify({ block, fields }, null, 2));\n\t\t\tfields.forEach((field) => {\n\t\t\t\tconst opBlocks: FilledBQLMutationBlock[] = Array.isArray(block[field]) ? block[field] : [block[field]];\n\t\t\t\tconst newOpBlocks: FilledBQLMutationBlock[] = [];\n\t\t\t\t// todo: create an array of ids being added as links, to filter from the unlinks\n\t\t\t\topBlocks.forEach((opBlock) => {\n\t\t\t\t\tif (opBlock.$op === 'replace') {\n\t\t\t\t\t\tconst cacheKey = objectPathToKey(opBlock.$objectPath);\n\t\t\t\t\t\tconst cacheKeys = convertManyPaths(cacheKey);\n\t\t\t\t\t\tconst foundKeys = cacheKeys.map((cacheKey) => {\n\t\t\t\t\t\t\treturn cache[cacheKey];\n\t\t\t\t\t\t});\n\t\t\t\t\t\t// console.log('foundKeys: ', JSON.stringify(foundKeys, null, 2));\n\n\t\t\t\t\t\tconst cacheFound = foundKeys.length === cacheKeys.length;\n\t\t\t\t\t\tconst linksToNotInclude: string[] = [];\n\t\t\t\t\t\t// 1. Generate unlinks based on the pre-query\n\t\t\t\t\t\tif (cacheFound) {\n\t\t\t\t\t\t\tfoundKeys.forEach((foundKey) => {\n\t\t\t\t\t\t\t\tif (foundKey) {\n\t\t\t\t\t\t\t\t\tconst unlinkIds: string[] = [];\n\t\t\t\t\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\t\t\t\t\tfoundKey.$ids\n\t\t\t\t\t\t\t\t\t\t.filter((id: string) => {\n\t\t\t\t\t\t\t\t\t\t\tlinksToNotInclude.push(id);\n\t\t\t\t\t\t\t\t\t\t\treturn id !== opBlock.$id;\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t.forEach((id: string) => {\n\t\t\t\t\t\t\t\t\t\t\tunlinkIds.push(id);\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tnewOpBlocks.push({ ...opBlock, $op: 'unlink', $id: unlinkIds, $bzId: `T_${uuidv4()}` });\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tArray.isArray(opBlock.$id)\n\t\t\t\t\t\t\t\t? !opBlock.$id.every((id) => linksToNotInclude.includes(id))\n\t\t\t\t\t\t\t\t: // @ts-expect-error todo\n\t\t\t\t\t\t\t\t !linksToNotInclude.includes(opBlock.$id)\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t// 2. Generate link based on the pre-query\n\t\t\t\t\t\t\tnewOpBlocks.push({ ...opBlock, $op: 'link', $bzId: `T_${uuidv4()}` });\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// console.log('cacheFound', JSON.stringify({ cacheFound, cacheKey }, null, 2));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnewOpBlocks.push(opBlock);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tnewBlock[field] = processReplaces(newOpBlocks);\n\t\t\t});\n\t\t\treturn newBlock;\n\t\t});\n\t};\n\n\t// @ts-expect-error todo\n\tconst processedReplaces = fillObjectPaths(processReplaces(fillObjectPaths(splitBql)));\n\n\t// console.log('processedReplaces', JSON.stringify(processedReplaces, null, 2));\n\n\tconst throwErrors = (\n\t\tblocks: FilledBQLMutationBlock | FilledBQLMutationBlock[],\n\t): FilledBQLMutationBlock | FilledBQLMutationBlock[] => {\n\t\treturn produce(blocks, (draft) =>\n\t\t\ttraverse(draft, (context) => {\n\t\t\t\tconst { key, value, parent } = context;\n\n\t\t\t\t// a. only work for role fields that are arrays or objects\n\t\t\t\tif (\n\t\t\t\t\tkey &&\n\t\t\t\t\tparent &&\n\t\t\t\t\t!key?.includes('$') &&\n\t\t\t\t\t(Array.isArray(value) || isObject(value)) &&\n\t\t\t\t\t!Array.isArray(parent)\n\t\t\t\t) {\n\t\t\t\t\tconst values: FilledBQLMutationBlock[] = Array.isArray(value) ? value : [value];\n\n\t\t\t\t\tvalues.forEach((thing) => {\n\t\t\t\t\t\t// todo: If user op is trying to link something that already has it's role filled by something else\n\t\t\t\t\t\tconst parentSchema = getCurrentSchema(schema, parent);\n\t\t\t\t\t\tconst findCardinality = () => {\n\t\t\t\t\t\t\tconst dataFieldFound = parentSchema.dataFields?.find((field) => field.path === thing.$objectPath.key);\n\t\t\t\t\t\t\tif (dataFieldFound) {\n\t\t\t\t\t\t\t\treturn dataFieldFound.cardinality;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst linkFieldFound = parentSchema.linkFields?.find((field) => field.path === thing.$objectPath.key);\n\t\t\t\t\t\t\tif (linkFieldFound) {\n\t\t\t\t\t\t\t\treturn linkFieldFound.cardinality;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\t\t\tconst roleFieldFound = parentSchema.roles?.[thing.$objectPath.key];\n\t\t\t\t\t\t\tif (linkFieldFound) {\n\t\t\t\t\t\t\t\treturn roleFieldFound.cardinality;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tconst cacheFound = cache[objectPathToKey(thing.$objectPath)];\n\n\t\t\t\t\t\tconst processArrayIdsFound = (arrayOfIds: string[], cacheOfIds: string[]) => {\n\t\t\t\t\t\t\treturn arrayOfIds.every((id) => cacheOfIds.includes(id));\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tconst isOccupied = thing.$id\n\t\t\t\t\t\t\t? Array.isArray(thing.$id)\n\t\t\t\t\t\t\t\t? // @ts-expect-error todo\n\t\t\t\t\t\t\t\t processArrayIdsFound(thing.$id, cacheFound.$ids)\n\t\t\t\t\t\t\t\t: // @ts-expect-error todo\n\t\t\t\t\t\t\t\t cacheFound?.$ids.includes(thing.$id)\n\t\t\t\t\t\t\t: cacheFound;\n\t\t\t\t\t\tconst cardinality = findCardinality();\n\t\t\t\t\t\t// console.log('isOccupied', JSON.stringify({ cacheFound, isOccupied, thing }, null, 2));\n\n\t\t\t\t\t\tif (thing.$op === 'link' && isOccupied && cardinality === 'ONE') {\n\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t`[BQLE-Q-M-2] Cannot link on:\"${objectPathToKey(thing.$objectPath)}\" because it is already occupied.`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (thing.$op) {\n\t\t\t\t\t\t\tswitch (thing.$op) {\n\t\t\t\t\t\t\t\tcase 'delete':\n\t\t\t\t\t\t\t\t\tif (!isOccupied) {\n\t\t\t\t\t\t\t\t\t\tif (!config.mutation?.ignoreNonexistingThings) {\n\t\t\t\t\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t\t\t\t\t`[BQLE-Q-M-2] Cannot delete $id:\"${thing.$id}\" because it is not linked to $id:\"${parent.$id}\"`,\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t// todo: prune\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase 'update':\n\t\t\t\t\t\t\t\t\tif (!isOccupied) {\n\t\t\t\t\t\t\t\t\t\tif (!config.mutation?.ignoreNonexistingThings) {\n\t\t\t\t\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t\t\t\t\t`[BQLE-Q-M-2] Cannot update $id:\"${thing.$id}\" because it is not linked to $id:\"${parent.$id}\"`,\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase 'unlink':\n\t\t\t\t\t\t\t\t\tif (!isOccupied) {\n\t\t\t\t\t\t\t\t\t\tif (!config.mutation?.ignoreNonexistingThings) {\n\t\t\t\t\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t\t\t\t\t`[BQLE-Q-M-2] Cannot unlink $id:\"${thing.$id}\" because it is not linked to $id:\"${parent.$id}\"`,\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase 'link':\n\t\t\t\t\t\t\t\t\tif (isOccupied) {\n\t\t\t\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t\t\t\t`[BQLE-Q-M-2] Cannot link $id:\"${thing.$id}\" because it is already linked to $id:\"${parent.$id}\"`,\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\t};\n\n\tthrowErrors(processedReplaces);\n\n\tconst fillPaths = (\n\t\tblocks: FilledBQLMutationBlock | FilledBQLMutationBlock[],\n\t): FilledBQLMutationBlock | FilledBQLMutationBlock[] => {\n\t\treturn produce(blocks, (draft) =>\n\t\t\ttraverse(draft, (context) => {\n\t\t\t\tconst { parent, key, value, meta } = context;\n\t\t\t\tif (isObject(value)) {\n\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\tvalue[Symbol.for('path') as any] = meta.nodePath;\n\t\t\t\t\t// // @ts-expect-error todo\n\t\t\t\t\t// value.$_path = meta.nodePath;\n\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\tdelete value.$objectPath;\n\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\tdelete value.$parentIsCreate;\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\tkey &&\n\t\t\t\t\tparent &&\n\t\t\t\t\t!key?.includes('$') &&\n\t\t\t\t\t(Array.isArray(value) || isObject(value)) &&\n\t\t\t\t\t!Array.isArray(parent)\n\t\t\t\t) {\n\t\t\t\t\tconst values = Array.isArray(value) ? value : [value];\n\t\t\t\t\tvalues.forEach((val) => {\n\t\t\t\t\t\tif (isObject(val)) {\n\t\t\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\t\t\t\tval[Symbol.for('parent') as any] = {\n\t\t\t\t\t\t\t\t// @ts-expect-error todo\n\t\t\t\t\t\t\t\t...value[Symbol.for('parent') as any],\n\t\t\t\t\t\t\t\tpath: parent[Symbol.for('path') as any],\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\t\t\t\t// val.$_parentPath = parent[Symbol.for('path') as any];\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\t};\n\n\tconst final = fillPaths(processedReplaces);\n\tconsole.log('final', JSON.stringify(final, null, 2));\n\treq.filledBqlRequest = final;\n};\n","/* eslint-disable no-await-in-loop */\nimport type { ConceptMap, ConceptMapGroup } from 'typedb-driver';\n\nimport { buildBQLTree, parseTQLMutation } from './postprocess';\nimport { buildTQLMutation } from './preprocess/buildTQLMutation';\nimport { fillBQLMutation } from './preprocess/fill';\nimport { parseBQLMutation } from './preprocess/parseBQLMutation';\nimport { runTQLMutation } from './transaction/runTQLMutation';\nimport type {\n\tBormConfig,\n\tBQLResponse,\n\tDBHandles,\n\tEnrichedBormSchema,\n\tParsedBQLMutation as BQLMutation,\n\tParsedBQLQuery as BQLQuery,\n\tRawBQLQuery as RawBQLRequest,\n\tTQLRequest,\n\tFilledBQLMutationBlock,\n\tBQLResponseMulti,\n} from '../types';\nimport { newBuildTQLQuery } from './preprocess/buildTQLQuery';\nimport { enrichBQLQuery } from './preprocess/enrichBQLQuery';\nimport { newRunTQLQuery } from './transaction/runTQLQuery';\nimport { parseTQLQuery } from './postprocess/parseTQLQuery';\nimport { newPreQuery } from './preprocess/newPreQuery';\n\nexport type RelationName = string;\nexport type EntityName = string;\n\nexport type ID = string;\ntype EntityID = ID;\nexport type Entity = { $entity: string; $id: string; $show?: boolean } & Record<string, any>;\n\ntype Request = {\n\trawBqlRequest: RawBQLRequest;\n\tfilledBqlRequest?: FilledBQLMutationBlock[] | FilledBQLMutationBlock; // todo: transform into filledBQLRequest with queries as well\n\tbqlRequest?: { query?: BQLQuery; mutation?: BQLMutation };\n\tschema: EnrichedBormSchema;\n\tconfig: BormConfig;\n\ttqlRequest?: TQLRequest;\n\tdbHandles: DBHandles;\n\t// todo: define type\n\tenrichedBqlQuery?: any;\n};\n\ntype Response = {\n\trawTqlRes?: {\n\t\t// queries\n\t\tentity?: ConceptMapGroup[];\n\t\troles?: {\n\t\t\tpath: string;\n\t\t\townerPath: string;\n\t\t\tconceptMapGroups: ConceptMapGroup[];\n\t\t}[];\n\t\trelations?: {\n\t\t\trelation: string;\n\t\t\tentity: string;\n\t\t\tconceptMapGroups: ConceptMapGroup[];\n\t\t}[];\n\t\t// mutations\n\t\tinsertions?: ConceptMap[];\n\t};\n\tcache?: {\n\t\tentities: Map<EntityName, Map<EntityID, Entity>>;\n\t\trelations: Map<RelationName, Map<EntityName, EntityID>[]>;\n\t\troleLinks: Map<EntityID, { [path: string]: EntityID | EntityID[] }>;\n\t};\n\tbqlRes?: BQLResponse | null;\n\tparsedTqlRes?: BQLResponse | null;\n\tisBatched?: boolean;\n};\n\ntype NextPipeline = {\n\treq: Request;\n\tres: Response;\n\tpipeline: PipelineOperation[];\n};\n\nexport type PipelineOperation = (req: Request, res: Response) => Promise<void | NextPipeline[]>;\n\ntype Pipeline = PipelineOperation[];\n\nconst Pipelines: Record<string, Pipeline> = {\n\tquery: [enrichBQLQuery, newBuildTQLQuery, newRunTQLQuery, parseTQLQuery],\n\tmutation: [\n\t\tfillBQLMutation,\n\t\tnewPreQuery,\n\t\tparseBQLMutation,\n\t\tbuildTQLMutation,\n\t\trunTQLMutation,\n\t\tparseTQLMutation,\n\t\tbuildBQLTree,\n\t],\n};\n\n// const finalPipeline = [buildBQLTree, processFieldsOperator, processIdOperator];\n// const finalPipeline = [];\n\nconst runPipeline = async (\n\tpipeline: Pipeline,\n\treq: Request,\n\tres: Response = {},\n\troot = true,\n\t// todo: ts antoine\n\t// eslint-disable-next-line consistent-return\n): Promise<BQLResponse> => {\n\t// console.log('Heeeeey', pipeline);\n\t// todo: ts antoine\n\t// eslint-disable-next-line no-restricted-syntax\n\tfor (const operation of pipeline) {\n\t\t// console.log('operation', operation.name);\n\n\t\tconst next = await operation(req, res);\n\t\tif (next && Array.isArray(next)) {\n\t\t\t// eslint-disable-next-line no-restricted-syntax\n\t\t\tfor (const nextPipeline of next) {\n\t\t\t\tawait runPipeline(nextPipeline.pipeline, nextPipeline.req, nextPipeline.res, false);\n\t\t\t}\n\t\t}\n\t}\n\tif (root) {\n\t\t// await runPipeline(finalPipeline, req, res, false);\n\t\t// console.log(res.tqlRes?.entities.map((e) => e.entries));\n\t\t/// when debugging add the tqlRequest\n\t\t/// todo: At some point, make the debugger more precise so we can decide what to add in this object (for instance also the answer?)\n\t\tif (req.config.query?.debugger === true && typeof res.bqlRes === 'object') {\n\t\t\treturn { ...res.bqlRes, $debugger: { tqlRequest: req.tqlRequest } } as BQLResponse;\n\t\t}\n\n\t\t//TODO: split type output of mutation pipeline and query pipeline\n\t\treturn res.bqlRes as BQLResponse;\n\t}\n\treturn res.bqlRes as BQLResponse;\n};\n\nexport const queryPipeline = (\n\tbqlRequest: RawBQLRequest,\n\tbormConfig: BormConfig,\n\tbormSchema: EnrichedBormSchema,\n\tdbHandles: DBHandles,\n) =>\n\trunPipeline(\n\t\tPipelines.query,\n\t\t{\n\t\t\tconfig: bormConfig,\n\t\t\tschema: bormSchema,\n\t\t\trawBqlRequest: bqlRequest,\n\t\t\tdbHandles,\n\t\t},\n\t\t{},\n\t);\n\nexport const mutationPipeline = (\n\tbqlRequest: RawBQLRequest,\n\tbormConfig: BormConfig,\n\tbormSchema: EnrichedBormSchema,\n\tdbHandles: DBHandles,\n) =>\n\trunPipeline(\n\t\tPipelines.mutation,\n\t\t{\n\t\t\tconfig: bormConfig,\n\t\t\tschema: bormSchema,\n\t\t\trawBqlRequest: bqlRequest,\n\t\t\tdbHandles,\n\t\t},\n\t\t{},\n\t) as Promise<BQLResponseMulti>;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,kBAAsB;AACtB,IAAAC,wBAAoC;;;ACC7B,IAAM,gBAAqC;AAAA,EACjD,OAAO;AAAA,IACN,YAAY;AAAA,IACZ,iBAAiB;AAAA,I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YAAM,OAAO,MAAM;AAAA,IACpB,CAAC;AAAA,EACF;AACD;AAEA,IAAO,cAAQ;","names":["import_radash","import_typedb_driver","import_radash","import_radash","import_immer","import_object_traversal","import_radash","import_radash","preDeletionBatch","insertionMatch","deletionMatch","insertion","deletion","import_immer","import_object_traversal","import_radash","uuidv4","import_object_traversal","import_radash","import_uuid","uuidv4","import_typedb_driver","import_typedb_driver","roleFields","linkFields","enrichedBqlQuery","import_immer","import_object_traversal","import_radash","field","schema","import_typedb_driver","import_radash","str","roleFields","linkFields","import_object_traversal","import_radash","import_immer","import_uuid","final","ops","allCombinations","opBlock","key","searchSegments","uuidv4","cacheKey"]}