@blitznocode/blitz-orm 0.4.8 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,37 +1,39 @@
1
- import { tryit, mapEntries, isArray, isString, listify, flat, shake, isObject, unique, pick } from 'radash';
2
- import { TypeDB, SessionType, TransactionType } from 'typedb-client';
3
- import { produce, current } from 'immer';
4
- import { traverse, getNodeByPath } from 'object-traversal';
5
- import { v4 } from 'uuid';
1
+ 'use strict';
6
2
 
7
- var ot={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1},mutation:{}};var Ht=a=>{let r=[],d=new Map;return a.forEach(i=>{let{dbPath:u,contentType:p}=i,s=`${u}-${p}`;d.has(s)||(d.set(s,!0),r.push(i));}),r},ht=async(a,r,d)=>{let u=(()=>{let y="",h=[];y+=`
8
- `,Object.keys(r.entities).forEach(R=>{let Q=r.entities[R],{idFields:I,dataFields:A,linkFields:F,name:q}=Q,g=[],O=[],N=[];if(Q.extends){let L=r.entities[Q.extends];L.dataFields&&L.dataFields.forEach(E=>{g.push(E.dbPath);}),L.linkFields&&L.linkFields.forEach(E=>{O.push(E.path);}),L.idFields&&L.idFields.forEach(E=>{N.push(E);});}y+=`${q} sub ${Q.extends?Q.extends:"entity"},
9
- `;let S=[];if(I&&I.length>0){let L=new Set(I),b=Array.from(L).map($=>`${$}`).join(", ");N.includes(b)||(y+=` owns ${b} @key,
10
- `,S.push(b));}if(A&&A.length>0&&A.forEach(L=>{!g.includes(L.dbPath)&&!S.includes(L.dbPath)&&(y+=` owns ${L.dbPath},
11
- `),h.push({dbPath:L.dbPath,contentType:L.contentType});}),F&&F.length>0){let L=[];F.forEach(E=>{let{relation:b,plays:$}=E;!O.includes(E.path)&&!L.includes(`${b}:${$}`)&&(y+=` plays ${b}:${$},
3
+ var radash = require('radash');
4
+ var typedbClient = require('typedb-client');
5
+ var immer = require('immer');
6
+ var objectTraversal = require('object-traversal');
7
+ var uuid = require('uuid');
8
+
9
+ var ot={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1},mutation:{}};var Ht=a=>{let r=[],c=new Map;return a.forEach(i=>{let{dbPath:u,contentType:p}=i,s=`${u}-${p}`;c.has(s)||(c.set(s,!0),r.push(i));}),r},ht=async(a,r,c)=>{let u=(()=>{let y="",h=[];y+=`
10
+ `,Object.keys(r.entities).forEach(F=>{let M=r.entities[F],{idFields:I,dataFields:A,linkFields:R,name:q}=M,g=[],O=[],N=[];if(M.extends){let L=r.entities[M.extends];L.dataFields&&L.dataFields.forEach(E=>{g.push(E.dbPath);}),L.linkFields&&L.linkFields.forEach(E=>{O.push(E.path);}),L.idFields&&L.idFields.forEach(E=>{N.push(E);});}y+=`${q} sub ${M.extends?M.extends:"entity"},
11
+ `;let T=[];if(I&&I.length>0){let L=new Set(I),b=Array.from(L).map($=>`${$}`).join(", ");N.includes(b)||(y+=` owns ${b} @key,
12
+ `,T.push(b));}if(A&&A.length>0&&A.forEach(L=>{!g.includes(L.dbPath)&&!T.includes(L.dbPath)&&(y+=` owns ${L.dbPath},
13
+ `),h.push({dbPath:L.dbPath,contentType:L.contentType});}),R&&R.length>0){let L=[];R.forEach(E=>{let{relation:b,plays:$}=E;!O.includes(E.path)&&!L.includes(`${b}:${$}`)&&(y+=` plays ${b}:${$},
12
14
  `,L.push(`${b}:${$}`));});}y=y.replace(/,\s*$/,`;
13
15
  `),y+=`
14
- `;}),Object.keys(r.relations).forEach(R=>{let Q=r.relations[R],{idFields:I,dataFields:A,roles:F,name:q,linkFields:g}=Q,O=[],N=[],S=[],L=[];if(Q.extends){let b=r.relations[Q.extends];b.dataFields&&b.dataFields.forEach($=>{O.push($.dbPath);}),b.linkFields&&b.linkFields.forEach($=>{N.push($.dbPath);}),b.roles&&Object.values(b.roles).forEach(M=>{S.push(M.name);}),b.idFields&&b.idFields.forEach($=>{L.push($);});}y+=`${q} sub ${Q.extends?Q.extends:"relation"},
15
- `;let E=[];if(I&&I.length>0){let b=new Set(I),M=Array.from(b).map(P=>`${P}`).join(", ");L.includes(M)||(y+=` owns ${M} @key,
16
- `,E.push(M));}if(A&&A.length>0&&A.forEach(b=>{!O.includes(b.dbPath)&&!E.includes(b.dbPath)&&(y+=` owns ${b.dbPath},
17
- `),h.push({dbPath:b.dbPath,contentType:b.contentType});}),F&&Object.keys(F).forEach(b=>{S.includes(b)||(y+=` relates ${b},
18
- `);}),g&&g.length>0){let b=[];g.forEach($=>{let{plays:M}=$;!N.includes($.path)&&!b.includes(`${Q}:${M}`)&&(y+=` plays ${$.relation}:${M},
19
- `,b.push(`${Q}:${M}`));});}y=y.replace(/,\s*$/,`;
16
+ `;}),Object.keys(r.relations).forEach(F=>{let M=r.relations[F],{idFields:I,dataFields:A,roles:R,name:q,linkFields:g}=M,O=[],N=[],T=[],L=[];if(M.extends){let b=r.relations[M.extends];b.dataFields&&b.dataFields.forEach($=>{O.push($.dbPath);}),b.linkFields&&b.linkFields.forEach($=>{N.push($.dbPath);}),b.roles&&Object.values(b.roles).forEach(Q=>{T.push(Q.name);}),b.idFields&&b.idFields.forEach($=>{L.push($);});}y+=`${q} sub ${M.extends?M.extends:"relation"},
17
+ `;let E=[];if(I&&I.length>0){let b=new Set(I),Q=Array.from(b).map(k=>`${k}`).join(", ");L.includes(Q)||(y+=` owns ${Q} @key,
18
+ `,E.push(Q));}if(A&&A.length>0&&A.forEach(b=>{!O.includes(b.dbPath)&&!E.includes(b.dbPath)&&(y+=` owns ${b.dbPath},
19
+ `),h.push({dbPath:b.dbPath,contentType:b.contentType});}),R&&Object.keys(R).forEach(b=>{T.includes(b)||(y+=` relates ${b},
20
+ `);}),g&&g.length>0){let b=[];g.forEach($=>{let{plays:Q}=$;!N.includes($.path)&&!b.includes(`${M}:${Q}`)&&(y+=` plays ${$.relation}:${Q},
21
+ `,b.push(`${M}:${Q}`));});}y=y.replace(/,\s*$/,`;
20
22
  `),y+=`
21
23
  `;});let e=`define
22
24
 
23
- `;return Ht(h).forEach(R=>{e+=`${R.dbPath} sub attribute,
24
- `,R.contentType==="TEXT"||R.contentType==="ID"?e+=` value string;
25
- `:R.contentType==="EMAIL"?(e+=` value string,
25
+ `;return Ht(h).forEach(F=>{e+=`${F.dbPath} sub attribute,
26
+ `,F.contentType==="TEXT"||F.contentType==="ID"?e+=` value string;
27
+ `:F.contentType==="EMAIL"?(e+=` value string,
26
28
  `,e+=` regex '^(?=.{1,64}@)[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*@[^-][A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$';
27
- `):R.contentType==="DATE"?e+=` value datetime;
28
- `:R.contentType==="BOOLEAN"?e+=` value boolean;
29
- `:R.contentType==="NUMBER"&&(e+=` value long;
29
+ `):F.contentType==="DATE"?e+=` value datetime;
30
+ `:F.contentType==="BOOLEAN"?e+=` value boolean;
31
+ `:F.contentType==="NUMBER"&&(e+=` value long;
30
32
  `);}),`${e}
31
33
 
32
- ${y}`})(),p=a.dbConnectors[0].id,s=d.typeDB.get(p)?.session,w=d.typeDB.get(p)?.client;if(!s){console.log("Session Status: ","NO SESSION");return}s.close();let[{dbName:m}]=a.dbConnectors;await(await w.databases.get(m)).delete(),await w.databases.create(m);let f=await w.session(a.dbConnectors[0].dbName,SessionType.SCHEMA),l=await f.transaction(TransactionType.WRITE);await l.query.define(u),await l.commit(),await l.close();let c=await f.transaction(TransactionType.READ),o="match $a sub thing;";(await(await c.query.match(o)).collect()).forEach(async y=>{y.get("a");}),await c.close();};var $t=(a,r,d)=>d?r:`${a}\xB7${r}`,gt=a=>{let r=a.split("\xB7");return r[r.length-1]},J=(a,r)=>Object.values(Object.fromEntries(Object.entries(a).filter(([d,i])=>r(d,i))))[0],_=(a,r)=>Object.fromEntries(Object.entries(a).filter(([d,i])=>r(d,i))),bt=a=>{let r=[],d=produce(a,u=>traverse(u,({key:p,value:s,meta:w})=>{if(w.depth===2&&(p&&(s.dataFields=s.dataFields?.map(m=>({...m,dbPath:$t(p,m.path,m.shared)}))),s.extends)){let m=u.entities[s.extends]||u.relations[s.extends];if(s.allExtends=[s.extends,...m.allExtends||[]],s.idFields=m.idFields?(s.idFields||[]).concat(m.idFields):s.idFields,s.dataFields=m.dataFields?(s.dataFields||[]).concat(m.dataFields.map(B=>{let f=s.extends,l=a.entities[f]||a.relations[f];for(;!l.dataFields?.find(c=>c.path===B.path);)f=l.extends,l=a.entities[f]||a.relations[f];return {...B,dbPath:$t(f,B.path,B.shared)}})):s.dataFields,s.linkFields=m.linkFields?(s.linkFields||[]).concat(m.linkFields):s.linkFields,"roles"in m){let B=s,f=m;B.roles=B.roles||{},B.roles={...B.roles,...f.roles},Object.keys(B.roles).length===0&&(B.roles={});}}},{traversalType:"breadth-first"}));return traverse(a,({key:u,value:p,meta:s})=>{if(u==="linkFields"){let m=(()=>{if(!s.nodePath)throw new Error("No path");let[f,l]=s.nodePath.split(".");return {thing:l,thingType:f==="entities"?"entity":f==="relations"?"relation":""}})(),B=Array.isArray(p)?p.map(f=>({...f,...m})):[{...p,...m}];r.push(...B);}}),produce(d,u=>traverse(u,({value:p,key:s,meta:w})=>{if(w.depth===2&&p.idFields&&!p.id){p.name=s;let m=()=>{if(w.nodePath?.split(".")[0]==="entities")return "entity";if(w.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};p.thingType=m(),p.computedFields=[],p.virtualFields=[],"roles"in p&&Object.entries(p.roles).forEach(([f,l])=>{l.playedBy=r.filter(c=>c.relation===s&&c.plays===f)||[],l.name=f;}),"linkFields"in p&&p.linkFields&&p.linkFields?.forEach(f=>{if(f.target==="relation"){f.oppositeLinkFieldsPlayedBy=[{plays:f.path,thing:f.relation,thingType:"relation"}];return}let l=r.filter(o=>o.relation===f.relation&&o.plays!==f.plays)||[];f.oppositeLinkFieldsPlayedBy=l;let{filter:c}=f;f.oppositeLinkFieldsPlayedBy=f.oppositeLinkFieldsPlayedBy.filter(o=>o.target==="role"),c&&Array.isArray(c)&&(f.oppositeLinkFieldsPlayedBy=f.oppositeLinkFieldsPlayedBy.filter(o=>c.some(t=>o.thing===t.$role)),f.oppositeLinkFieldsPlayedBy=f.oppositeLinkFieldsPlayedBy.filter(o=>c.some(t=>o.thing===t.$thing))),c&&!Array.isArray(c)&&(f.oppositeLinkFieldsPlayedBy=f.oppositeLinkFieldsPlayedBy.filter(o=>o.$role===c.$role),f.oppositeLinkFieldsPlayedBy=f.oppositeLinkFieldsPlayedBy.filter(o=>o.thing===c.$thing));});}if(typeof p=="object"&&"playedBy"in p){if([...new Set(p.playedBy?.map(m=>m.thing))].length>1)throw new Error(`Unsupported: roleFields can be only played by one thing. Role: ${s} path:${w.nodePath}`);if(p.playedBy.length===0)throw new Error(`Unsupported: roleFields should be played at least by one thing. Role: ${s}, path:${w.nodePath}`)}if(w.depth===4&&(p.default||p.computedValue)){let[m,B]=w.nodePath?.split(".")||[];p.isVirtual?u[m][B].virtualFields.push(p.path):u[m][B].computedFields.push(p.path);}}))},x=(a,r)=>{if(r.$entity){if(!(r.$entity in a.entities))throw new Error(`Missing entity '${r.$entity}' in the schema`);return a.entities[r.$entity]}if(r.$relation){if(!(r.$relation in a.relations))throw new Error(`Missing relation '${r.$relation}' in the schema`);return a.relations[r.$relation]}throw new Error(`Wrong schema or query for ${JSON.stringify(r)}`)},j=(a,r)=>{let d=a.dataFields?.map(t=>t.path)||[],i=a.linkFields?.map(t=>t.path)||[],u="roles"in a?listify(a.roles,t=>t):[],p=[...d||[],...i||[],...u||[]],w=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields"],...p];if(!r)return {fields:p,dataFields:d,roleFields:u,linkFields:i};let m=r.$fields?r.$fields.map(t=>{if(typeof t=="string")return t;if("$path"in t&&typeof t.$path=="string")return t.$path;throw new Error(" Wrongly structured query")}):listify(r,t=>t),B=r.$filter?listify(r.$filter,t=>t.toString().startsWith("$")?void 0:t.toString()).filter(t=>t&&d?.includes(t)):[],f=r.$filter?listify(r.$filter,t=>t.toString().startsWith("$")?void 0:t.toString()).filter(t=>t&&[...u||[],...i||[]].includes(t)):[],l=[...m,...B].filter(t=>!w.includes(t)).filter(t=>t),c=r.$filter?_(r.$filter,(t,n)=>B.includes(t)):{},o=r.$filter?_(r.$filter,(t,n)=>f.includes(t)):{};return {fields:p,dataFields:d,roleFields:u,linkFields:i,usedFields:m,usedLinkFields:i.filter(t=>m.includes(t)),usedRoleFields:u.filter(t=>m.includes(t)),unidentifiedFields:l,...B.length?{localFilters:c}:{},...f.length?{nestedFilters:o}:{}}},Bt=(a,r)=>{let d=r.$localFilters&&listify(r.$localFilters,(u,p)=>`has ${a.dataFields?.find(w=>w.path===u)?.dbPath} '${p}'`);return d?.length?`, ${d.join(",")}`:""},W=a=>a!==null,K=(a,r)=>Object.values(a).reduce((d,i)=>(i.extends===r&&d.push(i.name),d),[]);var te=(a,r)=>a.map(i=>{let u=[...i.conceptMaps],s=i.owner.asThing().type.label.name,w=r.entities[s]?r.entities[s]:r.relations[s];if(!w.idFields)throw new Error(`No idFields defined for ${s}`);let m=r.entities[s]?"entity":"relation",B=u.map(l=>{let c=l.get("attribute")?.asAttribute();return c?[gt(c.type.label.name),c.value]:[]}),f=Object.fromEntries(B);return {...f,[`$${m}`]:s,$id:f[w.idFields[0]]}}),ee=(a,r,d)=>a.flatMap(u=>u.conceptMaps.map(s=>{let w=new Map;return r.forEach(m=>{let B=s.get(`${m}_id`)?.asAttribute().value.toString(),f=s.get(m),l=f?.isEntity()?f.asEntity().type.label.name:f?.asRelation().type.label.name,o={id:B,entityName:(()=>l?(d.entities[l]??d.relations[l]).allExtends?.includes(m)?m:l:m)()};B&&w.set(m,o);}),w})),ne=(a,r,d)=>a.flatMap(u=>u.conceptMaps.map(s=>{let w=s.get(`${r}_id`)?.asAttribute().value.toString(),m=s.get(`${d}_id`)?.asAttribute().value.toString();return {ownerId:w,path:d,roleId:m}})),ie=(a,r)=>{let d=listify(a.roles,(i,u)=>{if([...new Set(u.playedBy?.map(w=>w.thing))].length!==1)throw new Error("a role can be played by two entities throws the same relation");if(!u.playedBy)throw new Error("Role not being played by nobody");let p=u.playedBy[0].plays,s=K(r.entities,p);return [p,...s]});return unique(flat(d))},H=async(a,r)=>{let{schema:d,bqlRequest:i,config:u,tqlRequest:p}=a,{rawTqlRes:s}=r;if(i){if(!s)throw new Error("TQL query not executed")}else throw new Error("BQL request not parsed");let{query:w}=i;if(!w){if(s.insertions?.length===0&&!p?.deletions){r.bqlRes={};return}let{mutation:c}=i;if(!c)throw new Error("TQL mutation not executed");let t=[...c.things,...c.edges].map(n=>{let y=s.insertions?.find(h=>h.get(`${n.$bzId}`))?.get(`${n.$bzId}`);if(n.$op==="create"||n.$op==="update"||n.$op==="link"){if(!y?.asThing().iid)throw new Error(`Thing not received on mutation: ${JSON.stringify(n)}. Probably the relation had all its edges deleted instead of replaced`);let h=y?.asThing().iid;return u.mutation?.noMetadata?mapEntries(n,(e,T)=>[e.toString().startsWith("$")?Symbol.for(e):e,T]):{$dbId:h,...n,[n.path]:n.$id}}if(n.$op==="delete"||n.$op==="unlink")return n;if(n.$op!=="match")throw new Error(`Unsupported op ${n.$op}`)}).filter(n=>n);r.bqlRes=t.length>1?t:t[0];return}if(!s.entity)throw new Error("TQL query not executed");let m=te(s.entity,d),B=s.relations?.map(c=>{let o=d.relations[c.relation],t=ie(o,d),n=ee(c.conceptMapGroups,[...t,o.name],d);return {name:c.relation,links:n}}),f=s.roles?.map(c=>({name:c.ownerPath,links:ne(c.conceptMapGroups,c.ownerPath,c.path)})),l=r.cache||{entities:new Map,relations:new Map,roleLinks:new Map};m.forEach(c=>{let o=c.$entity||c.$relation,t=c.$id,n=l.entities.get(o)||new Map;n.set(t,{...c,$show:!0}),l.entities.set(o,n);}),B?.forEach(c=>{let o=c.name,t=l.relations.get(o)||[];t.push(...c.links),l.relations.set(o,t),c.links.forEach(n=>{[...n.entries()].forEach(([y,{entityName:h,id:e}])=>{let T=l.entities.get(h)||new Map,Q={[d.entities[h]?.thingType||d.relations[h].thingType]:h,$id:e,...T.get(e)};T.set(e,Q),l.entities.set(h,T);});});}),f?.forEach(c=>{let o=d.relations[c.name]||d.entities[c.name];c.links.forEach(t=>{let n=l.roleLinks.get(t.ownerId)||{},y=n[t.path];y?isArray(y)?y.push(t.roleId):isString(y)&&y!==t.roleId&&(y=[y,t.roleId]):y=t.roleId,n[t.path]=y,l.roleLinks.set(t.ownerId,n),o.roles[t.path].playedBy?.forEach(h=>{let e=l.entities.get(h.thing)||new Map,T={$entity:h.thing,$id:t.roleId,...e.get(t.roleId)};e.set(t.roleId,T),l.entities.set(h.thing,e);});});}),r.cache=l;};var re=/((\/\/.*$)|(\/\*.*\*\/))/gm,oe=/(\s*async\s*|\s*function\s*)+/,se=/(?:function\s*[^(\s]*\s*|\s*=>\s*|^\s*)\(([^)]*)\)/,ae=/[ ,\n\r\t]+/,wt=a=>{let r=a.toString().replace(re,"").replace(oe,"").trim(),d=se.exec(r);if(!d)return [];let i;for(let u of d.slice(1))if(u){i=u;break}return i?(i=i.replace(/\{\s*/g,"").replace(/\s*\}/g,""),i.split(ae).filter(u=>u.trim()!=="")):[]};var Z=({currentThing:a,fieldSchema:r,mandatoryDependencies:d=!1})=>{if(!r||!r.default||!r.default.value)throw new Error("Virtual field: No field schema found, or wrongly configured");let i=r.default.value,p=wt(i).filter(w=>!(w in a));if(d&&p.length)throw new Error(`Virtual field: Missing arguments ${p.join(", ")}`);return "default"in r?r.default?.value(a):void 0};var ce=(a,r)=>a.length===1&&typeof a[0]!="string"&&a[0].$id===r?a[0]:a,Rt=a=>typeof a=="string"||!!a.$show,Ft=(a,r)=>produce(a,d=>traverse(d,({value:i})=>{if(Array.isArray(i)||typeof i!="object")return;i.$tempId&&(i.$tempId=`_:${i.$tempId}`),i.$fields&&delete i.$fields,i.$filter&&delete i.$filter,i.$show&&delete i.$show,i.$bzId&&delete i.$bzId,r.query?.noMetadata&&(i.$entity||i.$relation)&&(delete i.$entity,delete i.$relation,delete i.$id),Object.getOwnPropertySymbols(a).forEach(p=>{delete i[p];}),i.$excludedFields&&(i.$excludedFields.forEach(p=>{delete i[p];}),delete i.$excludedFields);})),at=(a,r,d,i)=>a.map(([u,p])=>{if(!r||!r.includes(u))return null;if(!d.$fields||d.$fields.includes(i))return u;let s=d.$fields.find(w=>isObject(w)&&w.$path===i);if(s){let w={..._(p,(B,f)=>B.startsWith("$"))},m=s.$fields?{...w,$fields:s.$fields}:w;if(s.$id){if(Array.isArray(s.$id))return s.$id.includes(u)?m:null;if(s.$id===u)return m}if(m.$fields&&m.$fields.includes("id")&&!m.$show){let B="";return m.$fields.forEach(f=>{f==="id"?B=m.$id:B=m;}),B}return m}return null}).filter(u=>u),de=(a,r)=>{let d={};return r.forEach(i=>{d[i.$bzId]=i.$id;}),a.forEach(i=>{Object.keys(i).forEach(u=>{d[i[u]]&&u!=="$tempId"&&(i[u]=d[i[u]]);});}),a},pe=(a,r)=>{let d=r.map(u=>u.$bzId),i=!1;return a.forEach(u=>{Object.keys(u).forEach(p=>{d.includes(u[p])&&(i=!0);});}),i},St=async(a,r)=>{let{bqlRequest:d,config:i,schema:u}=a,{cache:p}=r;if(!d)throw new Error("BQL request not parsed");let{query:s}=d;if(!s){let y=r.bqlRes[0]?r.bqlRes:[r.bqlRes],h=a.bqlRequest?.mutation?.things;if(pe(y,h)){let R=de(y,h);r.bqlRes=R[1]?R:R[0];}let T=Ft(r.bqlRes,i);r.bqlRes=T;return}if(!p)return;let w="$entity"in s?s.$entity:s.$relation,m=p.entities.get(w.name);if(!m){r.bqlRes=null;return}let f=listify(s.$filter,y=>y).some(y=>w.dataFields?.find(h=>h.path===y)?.validations?.unique),l=!Array.isArray(d.query)&&(d.query?.$id&&!Array.isArray(d.query?.$id)||f);if(Array.isArray(a.rawBqlRequest))throw new Error("Query arrays not implemented yet");let c=m,o=[...c].length?[...c].map(([y,h])=>({...a.rawBqlRequest,$id:y})):a.rawBqlRequest,t=produce(o,y=>traverse(y,({value:h})=>{let e=h;if(!e?.$entity&&!e?.$relation)return;let T="$entity"in e?e.$entity:e.$relation;if(T){let R=Array.isArray(e.$id)?e.$id:[e.$id],Q="$relation"in e?u.relations[e.$relation]:u.entities[e.$entity],{dataFields:I,roleFields:A}=j(Q),F=p.entities.get(T);if(!F)return;[...F].forEach(([g,O])=>{if(R.includes(g)){let N=e.$fields?e.$fields:I,{virtualFields:S}=Q;S?.forEach($=>{if(N?.includes($)&&e[$]===void 0){let M=Q.dataFields?.find(k=>k.path===$),P=Z({currentThing:O,fieldSchema:M});e[$]=P;}}),listify(O,($,M)=>{$.startsWith("$")||N?.includes($)&&(e[$]=M);});let L=p.roleLinks.get(g),E=e.$fields?e.$fields.filter($=>typeof $=="string"):A,b=e.$fields?.filter($=>typeof $=="object")?.map($=>$.$path)||[];Object.entries(L||{}).forEach(([$,M])=>{if(![...E,...b].includes($))return;if(!("roles"in Q))throw new Error("No roles in schema");let P=Array.isArray(M)?[...new Set(M)]:[M],{cardinality:k,playedBy:z}=Q.roles[$],C=[...new Set(z?.map(D=>D.thing))]?.flatMap(D=>{let rt=p.entities.get(D);return rt?at([...rt],P,e,$):[]});if(C?.length){if(C.length===1&&C[0]===e.$id)return;if(k==="ONE"){e[$]=C[0];return}e[$]=C.filter(D=>typeof D=="string"||typeof D=="object"&&D?.$show);}});}});let q=Q.linkFields;q&&q.forEach(g=>{let O=p.relations.get(g.relation),N=g.oppositeLinkFieldsPlayedBy;if(!O)return null;if(g.target==="relation"){let S=[...O].reduce((L,E)=>{let b=E.get(g.plays)?.id;if(b&&b===R[0]){let $=E.get(g.relation);if(!$)return L;L[$.entityName]||(L[$.entityName]=new Set),L[$.entityName].add($.id);}return L},{});return Object.entries(S).map(([L,E])=>{let b=p.entities.get(L);if(!b)return null;let $=at([...b],[...E.values()],e,g.path).filter(W).filter(Rt);if($.length===0)return null;if($&&$.length){if(g.cardinality==="ONE")return e[g.path]=$[0],null;e[g.path]=$;}return null}),null}return g.target==="role"&&N.forEach(S=>{if(!O)return;let L=[...O].reduce((E,b)=>{let $=b.get(g.plays)?.id;if($&&$===R[0]){let M=b.get(S.plays);if(!M)return E;E[M.entityName]||(E[M.entityName]=new Set),E[M.entityName].add(M.id);}return E},{});Object.entries(L).forEach(([E,b])=>{let $=p.entities.get(E);if(!$)return;let M=at([...$],[...b.values()],e,g.path).filter(W).filter(Rt);if(M.length!==0&&M&&M.length){if(g.cardinality==="ONE"){e[g.path]=M[0];return}e[g.path]=M;let P={},k=G=>(G.$path===g.path&&(P=G),G?.$fields?.forEach(k)),z="";s.$fields?.forEach(k),P&&(Array.isArray(P.$id)||(z=P.$id)),e[g.path]=ce(M,z);}});}),null});}})),n=Ft(t,i);r.bqlRes=l?n[0]:n;};var Y=async a=>{let{schema:r,bqlRequest:d}=a;if(!d?.query)throw new Error("BQL query not parsed");let{query:i}=d,u="$entity"in i?i.$entity:i.$relation,p=u.defaultDBConnector.path||u.name;if(!p)throw new Error(`No thing path in ${JSON.stringify(u)}`);if(!u.idFields)throw new Error("No id fields");let[s]=u.idFields,w=`$${p}_id`,m=`, has ${s} ${w};`;i.$id&&(Array.isArray(i.$id)?m+=` ${w} like "${i.$id.join("|")}";`:m+=` ${w} "${i.$id}";`);let B=Bt(u,i),f="roles"in u?listify(u.roles,(t,n)=>({path:t,var:`$${t}`,schema:n})):[],l=`match $${p} isa ${p}, has attribute $attribute ${B} ${m} group $${p};`,c=f.map(t=>{if(!t.schema.playedBy||[...new Set(t.schema.playedBy?.map(y=>y.thing))].length!==1)throw new Error("Unsupported: Role played by multiple linkfields or none");let n=t.schema.playedBy[0].thing;return {path:t.path,owner:p,request:`match $${p} (${t.path}: ${t.var} ) isa ${p} ${m} ${t.var} isa ${n}, has id ${t.var}_id; group $${p};`}}),o=u.linkFields?.flatMap(t=>{let n=`$${t.plays}_id`,y=`, has ${s} ${n};`;i.$id&&(Array.isArray(i.$id)?y+=` ${n} like "${i.$id.join("|")}";`:y+=` ${n} "${i.$id}";`);let h=`match $${t.plays} isa ${p}${B} ${y}`,e=t.target==="relation",R=`$${t.relation}`,Q=`${e?R:""} (${t.plays}: $${t.plays}`,I=t.oppositeLinkFieldsPlayedBy.map(S=>e?null:`${S.plays}: $${S.plays}`),A=[Q,...I].filter(S=>S).join(",");if(r.relations[t.relation]===void 0)throw new Error(`Relation ${t.relation} not found in schema`);let F=r.relations[t.relation].defaultDBConnector.path||t.relation,q=`) isa ${F};`,g=t.oppositeLinkFieldsPlayedBy.map(S=>`$${e?S.thing:S.plays} isa ${S.thing}, has id $${e?S.thing:S.plays}_id;`).join(" "),O=`group $${t.plays};`,N=`${h} ${A} ${q} ${g} ${O}`;return {relation:F,entity:p,request:N}});a.tqlRequest={entity:l,...c?.length?{roles:c}:{},...o?.length?{relations:o}:{}};};var Qt=async a=>{let{rawBqlRequest:r,schema:d}=a;if(!("$entity"in r)&&!("$relation"in r))throw new Error("No entity specified in query");let i=x(d,r);if(!i)throw new Error(`Thing '${r}' not found in schema`);let{unidentifiedFields:u,localFilters:p,nestedFilters:s}=j(i,r);if(u&&u.length>0)throw new Error(`Unknown fields: [${u.join(",")}] in ${JSON.stringify(r)}`);a.bqlRequest={query:{...a.rawBqlRequest,...i.thingType==="entity"?{$entity:i}:{},...i.thingType==="relation"?{$relation:i}:{},...p?{$localFilters:p}:{},...s?{$nestedFilters:s}:{}}};};var X=async(a,r)=>{let{dbHandles:d,bqlRequest:i,tqlRequest:u,config:p}=a;if(!i)throw new Error("BQL request not parsed");if(!u)throw new Error("TQL request not built");if(!u.entity)throw new Error("BQL request error, no entities");let{query:s}=i;if(!s)throw new Error("BQL request is not a query");let w=p.dbConnectors[0].id,m=d.typeDB.get(w)?.session;if(!m?.isOpen())throw new Error("Session is closed");let B=await m.transaction(TransactionType.READ);if(!B)throw new Error("Can't create transaction");let f=B.query.matchGroup(u.entity),l=u.roles?.map(y=>({...y,stream:B.query.matchGroup(y.request)})),c=u.relations?.map(y=>({...y,stream:B.query.matchGroup(y.request)})),o=await f.collect(),t=await Promise.all(l?.map(async y=>({path:y.path,ownerPath:y.owner,conceptMapGroups:await y.stream.collect()}))||[]),n=await Promise.all(c?.map(async y=>({relation:y.relation,entity:y.entity,conceptMapGroups:await y.stream.collect()}))||[]);await B.close(),r.rawTqlRes={entity:o,...t?.length&&{roles:t},...n?.length&&{relations:n}};};var lt=async(a,r)=>{let{bqlRequest:d,schema:i}=a,{cache:u}=r;if(!d)throw new Error("BQL request not parsed");if(!u)throw new Error("Cache not initialized");let{query:p}=d;if(!p)return;let{$fields:s}=p;if(!("$entity"in p)&&!("$relation"in p))throw new Error("Node attributes not supported");let w="$entity"in p?p.$entity:p.$relation;if(!s||!Array.isArray(s))return;let m=s.filter(o=>typeof o!="string"&&o.$path),B=w.linkFields?.filter(o=>m.findIndex(t=>t.$path===o.path)!==-1).flatMap(o=>o.oppositeLinkFieldsPlayedBy)||[],f="roles"in w?listify(w.roles,(o,t)=>m.findIndex(n=>n.$path===o)!==-1?t:null).flatMap(o=>o?.playedBy).filter(o=>o):[],c=[...B,...f]?.map(o=>{if(!o)return null;let{thing:t}=o,n=K(i.entities,t);return [t,...n].map(y=>{let h=u.entities.get(y);if(!h)return null;let e=Array.from(h.values()).reduce((g,O)=>("$show"in O||g.push(O.$id),g),[]);if(e.length===0)return null;let T=i.entities[y]?{...i.entities[y],thingType:"entity"}:{...i.relations[y],thingType:"relation"},R=s.find(g=>typeof g=="object"&&g.$path===o.plays),Q=R?.$id,I=Q?Array.isArray(Q)?Q:[Q]:[],A=R?.$filter,q={query:{$id:I.length?I.filter(g=>e.includes(g)):e,$fields:R?.$fields,...T.thingType==="entity"?{$entity:T}:{},...T.thingType==="relation"?{$relation:T}:{},...A?{$localFilters:A}:{}}};return {req:{...a,bqlRequest:q},res:r,pipeline:[Y,X,H,lt]}}).filter(W)}).filter(W);if(c?.length)return flat(c)};var Mt=async a=>{let{bqlRequest:r,schema:d}=a;if(!r)throw new Error("BQL request not parsed");let{mutation:i}=r;if(!i)throw new Error("BQL request is not a mutation");let u=o=>{let t=o.$op,n=`$${o.$bzId}`,y=x(d,o),{idFields:h,defaultDBConnector:e}=y,T=e?.path||o.$entity||o.$relation,R=o.$id,Q=h?.[0],I=listify(o,(E,b)=>{if(E.startsWith("$")||E===Q||!b)return "";let $=y.dataFields?.find(k=>k.path===E);if(!$?.path)return "";let P=$.dbPath;if(["TEXT","ID","EMAIL"].includes($.contentType))return `has ${P} '${b}'`;if(["NUMBER"].includes($.contentType))return `has ${P} ${b}`;if($.contentType==="DATE"){if(Number.isNaN(b.valueOf()))throw new Error("Invalid format, Nan Date");return b instanceof Date?`has ${P} ${b.toISOString().replace("Z","")}`:`has ${P} ${new Date(b).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${$.contentType}`)}).filter(E=>E),A=`${n}-atts`,F=listify(o,(E,b)=>{if(E.startsWith("$")||E===Q||!b)return "";let $=y.dataFields?.find(k=>k.path===E);if(!$?.path)return "";let P=$.dbPath;return `{${A} isa ${P};}`}).filter(E=>E),q=o[Symbol.for("isLocalId")],g=isArray(R)?`like '${R.join("|")}'`:`'${R}'`,O=!q&&R?[`has ${Q} ${g}`]:[],N=[...O,...I].filter(E=>E).join(","),S=()=>{if(t==="delete"||t==="unlink"||t==="match")return `${n} isa ${[T,...O].filter(E=>E).join(",")};`;if(t==="update"){if(!F.length)throw new Error("update without attributes");return `${n} isa ${[T,...O].filter(E=>E).join(",")}, has ${A};
33
- ${F.join(" or ")};
34
- `}return ""},L=()=>t==="update"||t==="link"||t==="match"?`${n} isa ${[T,...O].filter(E=>E).join(",")};`:"";if(o.$entity||o.$relation)return {op:t,deletionMatch:S(),insertionMatch:L(),insertion:t==="create"?`${n} isa ${[T,N].filter(E=>E).join(",")};`:t==="update"&&I.length?`${n} ${I.join(",")};`:"",deletion:t==="delete"?`${n} isa ${T};`:t==="update"&&F.length?`${n} has ${A};`:""};throw new Error("in attributes")},p=o=>{let t=o.$op,n=x(d,o),y=`$${o.$bzId}`,h=o.$id,e=n.defaultDBConnector?.path||o.$relation,T="roles"in n?listify(n.roles,L=>L):[],R=o.$relation&&"roles"in n&&mapEntries(n.roles,(L,E)=>[L,E.dbConnector?.path||L]),Q=listify(o,(L,E)=>{if(!T.includes(L))return null;if(!("roles"in n))throw new Error("This should have roles! ");let b=R[L];return Array.isArray(E)?E.map($=>({path:b,id:$})):{path:b,id:E}}).filter(L=>L).flat(),I=Q.map(L=>{if(!L?.path)throw new Error("Object without path");return `${L.path}: $${L.id}`}),A=Q.length>0?`( ${I.join(" , ")} )`:"",F=A?`${y} ${A} ${o[Symbol.for("edgeType")]==="linkField"||t==="delete"||t==="unlink"?`isa ${e}`:""}`:"",q=`${y} ${o[Symbol.for("edgeType")]==="linkField"||t==="delete"?`isa ${e}`:""}`,g=()=>F?t==="link"?`${F};`:t==="create"?`${F}, has id '${h}';`:"":"",O=()=>F&&t==="match"?`${F};`:"",N=()=>F?t==="delete"?`${F};`:t==="match"?`${F};`:"":"",S=()=>F?t==="delete"?`${q};`:t==="unlink"?`${y} ${A};`:"":"";return {deletionMatch:N(),insertionMatch:O(),deletion:S(),insertion:g(),op:""}},s=(o,t)=>{let n=t==="edges"?p:u;if(Array.isArray(o))return o.map(Q=>{let{preDeletionBatch:I,insertionMatch:A,deletionMatch:F,insertion:q,deletion:g}=n(Q);return shake({preDeletionBatch:I,insertionMatch:A,deletionMatch:F,insertion:q,deletion:g},O=>!O)}).filter(Q=>Q);let{preDeletionBatch:y,insertionMatch:h,deletionMatch:e,insertion:T,deletion:R}=n(o);return shake({preDeletionBatch:y,insertionMatch:h,deletionMatch:e,insertion:T,deletion:R},Q=>!Q)},w=s(i.things),m=Array.isArray(w)?w:[w],B=s(i.edges,"edges"),f=Array.isArray(B)?B:[B],l=[...m,...f],c=shake({insertionMatches:l.map(o=>o.insertionMatch).join(" ").trim(),deletionMatches:l.map(o=>o.deletionMatch).join(" ").trim(),insertions:l.map(o=>o.insertion).join(" ").trim(),deletions:l.map(o=>o.deletion).join(" ").trim()},o=>!o);a.tqlRequest=c;};var Re=a=>{if(!a.startsWith("_:"))throw new Error("ID must start with '_:'.");let r=a.substring(2);if(!/^[a-zA-Z0-9-_]+$/.test(r))throw new Error("$tempId must contain only alphanumeric characters, hyphens, and underscores.");if(a.length>36)throw new Error("$tempId must not be longer than 36 characters.");return r},qt=async a=>{let{rawBqlRequest:r,schema:d}=a,u=(B=>produce(B,f=>traverse(f,({value:l,key:c,parent:o})=>{isObject(l)&&(l=shake(l,t=>t===void 0)),c==="$tempId"&&(o[c]=Re(l));})))(r),s=(B=>produce(B,f=>traverse(f,({value:l,meta:c,key:o})=>{if(isObject(l)){if(l.$arrayOp)throw new Error("Array op not supported yet");if(o==="$filter"||c.nodePath?.includes(".$filter."))return;let t=l;if(t.$op==="create"&&t.$id)throw new Error("Can't write to computed field $id. Try writing to the id field directly.");let n=x(d,t),h=c.nodePath?.split(".")?.filter(F=>Number.isNaN(parseInt(F,10))).join(".");if(!n)throw new Error(`Schema not found for ${t.$entity||t.$relation}`);t.$bzId=t.$tempId??`T_${v4()}`,t[Symbol.for("schema")]=n,t[Symbol.for("dbId")]=n.defaultDBConnector.id;let{usedLinkFields:e,usedRoleFields:T}=j(n,t),R=e.map(F=>({fieldType:"linkField",path:F,schema:n.linkFields.find(q=>q.path===F)})),Q=n.thingType==="relation"?T.map(F=>({fieldType:"roleField",path:F,schema:J(n.roles,q=>q===F)})):[];if(R.some(F=>F.schema?.target==="role")&&R.some(F=>F.schema?.target==="relation"))throw new Error("Unsupported: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.");let I=Q.filter(F=>[...new Set(F.schema.playedBy?.map(q=>q.thing))].length!==1);if(I.length>1)throw new Error(`Field: ${I[0].path} - If a role can be played by multiple things, you must specify the thing in the mutation: ${JSON.stringify(I[0].schema.playedBy)}. Schema: ${JSON.stringify(I[0].schema)}`);let A=c.nodePath;if([...R,...Q].forEach(F=>{let q=t[F.path];if(q===void 0)return;let g=F.schema;if(!g)throw new Error(`Field ${F.path} not found in schema`);let O=F.fieldType==="roleField"?g?.playedBy[0]:g,S=(()=>g&&"relation"in g&&O?.relation===t.$relation?"$self":O?.relation?O?.relation:"$self")(),L=S==="$self"?n:d.relations[S];if(J(L.roles,(k,z)=>k===F.path)?.playedBy?.length===0)throw new Error(`unused role: ${A}.${F.path}`);if(!g)throw new Error(`Field ${F.path} not found in schema`);let b=F.fieldType==="linkField"?g?.oppositeLinkFieldsPlayedBy:g?.playedBy;if(!b)throw new Error(`No opposite fields found for ${JSON.stringify(g)}`);if([...new Set(b?.map(k=>k.thing))].length>1)throw new Error(`Field: ${F.path} - If a role can be played by multiple things, you must specify the thing in the mutation: ${JSON.stringify(b)}. Schema: ${JSON.stringify(g)}`);if(g.cardinality==="ONE"&&Array.isArray(q))throw new Error("Can't have an array in a cardinality === ONE link field");if(g.cardinality==="MANY"&&q!==null&&!Array.isArray(q)&&!q.$arrayOp)throw new Error(`${F.fieldType==="linkField"?g.path:g.name} is a cardinality === MANY thing. Use an array or a $arrayOp object`);if(q?.$entity||q?.$relation)return;let[$]=b,M="plays"in g?"linkField":"roleField",P={[`$${$.thingType}`]:$.thing,[Symbol.for("relation")]:S,[Symbol.for("edgeType")]:M,[Symbol.for("parent")]:{path:A,...t.$id?{$id:t.$id}:{},...t.$tempId?{$tempId:t.$tempId}:{},...t.filter?{filter:t.filter}:{},links:b},[Symbol.for("role")]:$.plays,[Symbol.for("oppositeRole")]:"plays"in g?g.plays:void 0,[Symbol.for("relFieldSchema")]:g};if(isObject(q)&&(t[F.path]={...P,...q}),Array.isArray(q))if(q.every(k=>isObject(k)))t[F.path]=q.map(k=>({...P,...k}));else if(q.every(k=>typeof k=="string"))t[F.path]=q.map(k=>({...P,$op:t.$op==="create"?"link":"replace",$id:k}));else throw new Error(`Invalid array value for ${F.path}`);if(typeof q=="string"&&(t[F.path]={...P,$op:t.$op==="create"?"link":"replace",$id:q}),q===null){let k={...P,$op:"unlink"};t[F.path]=g.cardinality==="MANY"?[k]:k;}}),!h&&!t.$entity&&!t.$relation)throw new Error("Root things must specify $entity or $relation")}})))(u),m=(B=>produce(B,f=>traverse(f,({parent:l,key:c,value:o,meta:t})=>{if(isObject(o)){if(Object.keys(o).length===0)throw new Error("Empty object!");if(c==="$filter"||t.nodePath?.includes(".$filter."))return;let n=o,y=t.nodePath?.split(".");if(n.$tempId&&!(n.$op===void 0||n.$op==="link"||n.$op==="create"||n.$op==="update"))throw new Error(`Invalid op ${n.$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.`);let h=y?.filter(C=>Number.isNaN(parseInt(C,10))).join("."),e=h?Array.isArray(l)?y?.slice(0,-1).join("."):t.nodePath:t.nodePath||"",T=x(d,n),{unidentifiedFields:R,dataFields:Q,roleFields:I,linkFields:A}=j(T,n),F=current(n)[Symbol.for("parent")],q=h&&F.path,O=(q?getNodeByPath(f,q):f)?.$op;if(h&&!O)throw new Error("Error: Parent $op not detected");let N=n[Symbol.for("relFieldSchema")],S=Object.keys(n).some(C=>Q?.includes(C)),L=Object.keys(n).some(C=>[...I,...A].includes(C)),E=()=>{if(n.$op)return n.$op;if(h&&!n.$id&&!n.$tempId&&O!=="create"&&N.cardinality==="ONE")throw new Error(`Please specify if it is a create or an update. Path: ${t.nodePath}`);if(n.$tempId)return "create";if((n.$id||n.$filter)&&S)return "update";if((n.$id||n.$filter)&&h&&!S&&!L)return "link";if(!n.$filter&&!n.$id&&!n.$tempId)return "create";if((n.$id||n.$filter)&&!S&&L)return "match";throw new Error("Wrong op")};if(n.$op||(n.$op=E()),l||(n.$parentKey=""),typeof l=="object"&&(Array.isArray(l)&&(n[Symbol.for("index")]=c),n[Symbol.for("path")]=e,n[Symbol.for("isRoot")]=!h,n[Symbol.for("depth")]=h?.split(".").length),!n.$entity&&!n.$relation)throw new Error(`Node ${JSON.stringify(n)} without $entity/$relation`);let{idFields:b,computedFields:$,virtualFields:M}=T;if(!b)throw new Error("No idFields found");let[P]=b,k=listify(n,(C,D)=>D!==void 0?C:void 0),z=k.filter(C=>M?.includes(C));if(z.length>0)throw new Error(`Virtual fields can't be sent to DB: "${z.join(",")}"`);if($.filter(C=>!k.includes(C)).forEach(C=>{let D=T.dataFields?.find(V=>V.path===C),Wt=T.linkFields?.find(V=>V.path===C)?.oppositeLinkFieldsPlayedBy[0],Gt="roles"in T?J(T.roles,(V,Oe)=>V===C):void 0,ut=D||Wt||Gt;if(!ut)throw new Error(`no field Def for ${C}`);if(C===P&&n.$op==="create"&&!n[C]){let V=Z({currentThing:n,fieldSchema:ut,mandatoryDependencies:!0});n[C]=V,n.$id=V;}}),R.length>0)throw new Error(`Unknown fields: [${R.join(",")}] in ${JSON.stringify(n)}`)}})))(s);a.filledBqlRequest=m;};var Pt=async a=>{let{filledBqlRequest:r,schema:d}=a,i=f=>{let l=[],c=[],o=h=>{if(h.$id)return h.$id;let e=x(d,h),{idFields:T}=e;if(!T)throw new Error(`no idFields: ${JSON.stringify(h)}`);let[R]=T;if(!R)throw new Error(`no idField: ${JSON.stringify(h)}`);let Q=e.dataFields?.find(F=>F.path===R),I=h.$op==="create"?Q?.default?.value():null,A=h[R]||h.$id||I;if(!A)throw new Error(`no idValue: ${JSON.stringify(h)}`);return A},t=h=>{if(h.$op==="create"){let e=o(h);if(l.find(T=>T.$id===e))throw new Error(`Duplicate id ${e} for node ${JSON.stringify(h)}`);if(c.find(T=>T.$bzId===h.$bzId))throw new Error(`Duplicate $bzid ${h.$bzId} for node ${JSON.stringify(h)}`);l.push({...h,$id:e});return}h.$tempId&&h.$op==="match"||l.push(h);},n=h=>{if(h.$op==="create"){let e=o(h);if(l.find(T=>T.$id===e),c.find(T=>T.$bzId===h.$bzId))throw new Error(`Duplicate %bzId ${h.$bzIdd} for edge ${JSON.stringify(h)}`);c.push({...h,$id:e});return}c.push(h);};return traverse(f,({value:h})=>{if(!isObject(h))return;let e=h;if(e.$entity||e.$relation){if(!e.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(e)}`);if(!e.$bzId)throw new Error("[internal error] BzId not found");let T=x(d,e),{dataFields:R,roleFields:Q,linkFields:I,usedFields:A}=j(T,e),F=()=>{if(e.$op==="create"||e.$op==="delete")return e.$op;if(e.$op==="update"){let g=A.filter(S=>R?.includes(S)),O=A.filter(S=>Q?.includes(S)),N=A.filter(S=>I?.includes(S));if(g.length>0)return "update";if(O.length>0||N.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(e)}`)}return "match"},q={...e.$entity&&{$entity:e.$entity},...e.$relation&&{$relation:e.$relation},...e.$id&&{$id:e.$id},...e.$tempId&&{$tempId:e.$tempId},...e.$filter&&{$filter:e.$filter},...shake(pick(e,R||[""])),$op:F(),$bzId:e.$bzId,[Symbol.for("dbId")]:T.defaultDBConnector.id,[Symbol.for("path")]:e[Symbol.for("path")],[Symbol.for("parent")]:e[Symbol.for("parent")],[Symbol.for("isRoot")]:e[Symbol.for("isRoot")],[Symbol.for("isLocalId")]:e[Symbol.for("isLocalId")]||!1};if(t(q),e[Symbol.for("relation")]&&e[Symbol.for("edgeType")]==="linkField"){if((e.$op==="link"||e.$op==="unlink")&&(e.$id||e.$filter)){if(e.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");l.push({...e,$op:"match"});}let g=e[Symbol.for("relation")]===e.$relation,O=g?e.$bzId:v4(),S=e[Symbol.for("parent")].path,E=(S?getNodeByPath(f,S):f).$bzId;if(!E)throw new Error("No parent id found");if(e[Symbol.for("relation")]==="$self")return;let b=()=>{if(e.$op==="delete")return g?"match":"delete";if(e.$op==="unlink")return g?"unlink":"delete";if(e.$op==="link"||e.$op==="create")return g?"link":"create";if(e.$op==="replace")throw new Error("Unsupported: Replaces not implemented yet");return "match"},$={$relation:e[Symbol.for("relation")],$bzId:O,...e.$tempId?{$tempId:e.$tempId}:{},$op:b(),...g?{}:{[e[Symbol.for("role")]]:e.$bzId},[e[Symbol.for("oppositeRole")]]:E,[Symbol.for("dbId")]:d.relations[e[Symbol.for("relation")]].defaultDBConnector.id,[Symbol.for("edgeType")]:"linkField",[Symbol.for("info")]:"normal linkField",[Symbol.for("path")]:e[Symbol.for("path")],[Symbol.for("parent")]:e[Symbol.for("parent")]};n($),(e.$op==="unlink"||b()==="unlink")&&g&&n({$relation:e[Symbol.for("relation")],$bzId:O,$op:"match",[e[Symbol.for("oppositeRole")]]:E,[Symbol.for("dbId")]:d.relations[e[Symbol.for("relation")]].defaultDBConnector.id,[Symbol.for("edgeType")]:"linkField",[Symbol.for("info")]:"additional ownrelation unlink linkField",[Symbol.for("path")]:e[Symbol.for("path")],[Symbol.for("parent")]:e[Symbol.for("parent")]});}if(e.$relation){let g=_(e,(S,L)=>Q.includes(S)),O=mapEntries(g,(S,L)=>isArray(L)?[S,L]:isObject(L)?[S,L.$bzId]:[S,L]),N=_(h,(S,L)=>S.startsWith("$")||S.startsWith("Symbol"));if(Object.keys(g).filter(S=>!S.startsWith("$")).length>0){if(e.$op==="create"||e.$op==="delete"){let S=()=>{if(e.$op==="create")return "link";if(e.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},L=mapEntries(O,(b,$)=>Array.isArray($)?[b,$.map(M=>M.$bzId||M)]:[b,$.$bzId||$]),E={...N,$relation:e.$relation,$op:S(),...L,$bzId:e.$bzId,[Symbol.for("path")]:e[Symbol.for("path")],[Symbol.for("dbId")]:T.defaultDBConnector.id,[Symbol.for("info")]:"coming from created or deleted relation",[Symbol.for("edgeType")]:"roleField on C/D"};n(E);return}if(e.$op==="match"||e.$op==="update"&&Object.keys(g).length>0){let S=0;Object.entries(g).forEach(([L,E])=>{let b=isArray(E)?E:[E],$=M=>M==="create"||M==="replace"?"link":M;b.forEach(M=>{let P=$(M.$op);if(P==="replace")throw new Error("Not supported yet: replace on roleFields");if(P==="unlink"&&S>0)throw S+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let k={...N,$relation:e.$relation,$op:P,[L]:M.$bzId,$bzId:e.$bzId,[Symbol.for("dbId")]:T.defaultDBConnector.id,[Symbol.for("parent")]:e[Symbol.for("parent")],[Symbol.for("path")]:e[Symbol.for("path")],[Symbol.for("info")]:"updating roleFields",[Symbol.for("edgeType")]:"roleField on L/U/R"};n(k);});});}}}}}),[l,c]};if(!r)throw new Error("Undefined filledBqlRequest");let [u,p]=i(r),s=u.reduce((f,l)=>{if(!l.$bzId)return [...f,l];let c=f.findIndex(o=>o.$bzId===l.$bzId);if(c===-1)return [...f,l];if(f[c].$op==="create"&&l.$op==="match")return f;if(f[c].$op==="match"&&(l.$op==="create"||l.$op==="match"))return [...f.slice(0,c),l,...f.slice(c+1)];throw new Error(`Unsupported operation combination for $tempId "${l.$tempId}". Existing: ${f[c].$op}. Current: ${l.$op}`)},[]),w=p.reduce((f,l)=>{let c=f.find(o=>(o.$id&&o.$id===l.$id||o.$bzId&&o.$bzId===l.$bzId)&&o.$relation===l.$relation&&o.$op===l.$op);if(c){let o={...c};return Object.keys(l).forEach(n=>{if(typeof n=="symbol"||n.startsWith("$"))return;let y=c[n],h=l[n];Array.isArray(y)&&Array.isArray(h)?o[n]=Array.from(new Set([...y,...h])):!Array.isArray(y)&&Array.isArray(h)?y!==void 0?o[n]=Array.from(new Set([y,...h])):o[n]=h:Array.isArray(y)&&!Array.isArray(h)?h!==void 0&&(o[n]=Array.from(new Set([...y,h]))):y||(o[n]=h);}),[...f.filter(n=>!((n.$id&&n.$id===l.$id||n.$bzId&&n.$bzId===l.$bzId)&&n.$relation===l.$relation&&n.$op===l.$op)),o]}return [...f,l]},[]);[...new Set(w.map(f=>f.$relation))];a.bqlRequest={mutation:{things:s,edges:w}};};var Nt=async a=>{let{filledBqlRequest:r}=a,i=(m=>{let B=!1;return traverse(m,({value:f})=>f.$op==="replace"?(B=!0,!1):!0),B})(r),p=(m=>{if(Array.isArray(m)){let B=[],f=null,l=null;if(traverse(m,({value:o,key:t,meta:n})=>{n.depth===2&&(t==="$relation"?f=o:t==="$entity"?l=o:t==="$id"&&typeof o=="string"&&B.push(o));}),!f&&!l)throw new Error("Neither $relation nor $entity found in the blocks");let c={$id:B};return f&&(c.$relation=f),l&&(c.$entity=l),c}return m})(r),s=await nt(p,a.config,a.schema,a.dbHandles);if((m=>produce(m,B=>{traverse(B,({value:f,key:l,parent:c})=>{if(isObject(f)&&f.$op==="link"&&c&&c[l].$op==="link"&&!Array.isArray(s)&&s&&s[l]&&!parseInt(l)&&s[l].$op!=="link")throw new Error(`You already have ${l} filled for this.`)});}))(r),i){let B=(f=>produce(f,l=>traverse(l,({value:c,key:o,parent:t})=>{if(o&&!o?.includes("$")&&(Array.isArray(c)||isObject(c))){let n=Array.isArray(c)?c:[c],y={};n.forEach(R=>{R.$op==="replace"&&(R.$op="link"),R.$entity?y.$entity=R.$entity:R.$relation&&(y.$relation=R.$relation);});let h=[],e=Array.isArray(s)?s.find(R=>R.$id===t.$id):s,T=e?e[o]:null;Array.isArray(T)?h=T.map(R=>typeof R=="object"?R.$id:R):typeof T=="string"&&(h=[T]),h.forEach(R=>{let Q=T[0].$op==="replace"?null:n.find(I=>I.$id===R&&I.$op==="link");if(!Q&&!n.some(I=>I.$id===R)){let I={...y,$op:"unlink",$id:R,$bzId:`T_${v4()}`};Array.isArray(c)?c.push(I):t[o]=[c,I];}else if(Q){let I=n.findIndex(A=>A.$id===R&&A.$op==="link");I>-1&&n.splice(I,1);}});}})))(r);a.filledBqlRequest=B;}};var Dt=async(a,r)=>{let{dbHandles:d,tqlRequest:i,bqlRequest:u,config:p}=a;if(!i)throw new Error("TQL request not built");if(!(i.deletions&&i.deletionMatches||i.insertions))throw new Error("TQL request error, no things");if(!u?.mutation)throw new Error("BQL mutation not parsed");let s=p.dbConnectors[0].id,w=d.typeDB.get(s)?.session;if(!w)throw new Error("Session not found");if(!w.isOpen())throw new Error("Session is closed");let m=await w.transaction(TransactionType.WRITE);if(!m)throw new Error("Can't create transaction");let B=i.deletionMatches&&i.deletions&&`match ${i.deletionMatches} delete ${i.deletions}`,f=i.insertions&&`${i.insertionMatches?`match ${i.insertionMatches}`:""} insert ${i.insertions}`;B&&m.query.delete(B);let l=f&&m.query.insert(f);try{let c=l?await l.collect():void 0;await m.commit(),await m.close(),r.rawTqlRes={insertions:c};}catch(c){throw await m.close(),new Error(`Transaction failed: ${c.message}`)}};var xt={query:[Qt,Y,X,H,lt],mutation:[qt,Nt,Pt,Mt,Dt,H]},Ie=[St],it=async(a,r,d={},i=!0)=>{for(let u of a){let p=await u(r,d);if(p&&Array.isArray(p))for(let s of p)await it(s.pipeline,s.req,s.res,!1);}if(i)return await it(Ie,r,d,!1),r.config.query?.debugger===!0&&typeof d.bqlRes=="object"?{...d.bqlRes,$debugger:{tqlRequest:r.tqlRequest}}:d.bqlRes},nt=(a,r,d,i)=>it(xt.query,{config:r,schema:d,rawBqlRequest:a,dbHandles:i},{}),jt=(a,r,d,i)=>it(xt.mutation,{config:r,schema:d,rawBqlRequest:a,dbHandles:i},{});var ft=class{schema;config;dbHandles;constructor({schema:r,config:d}){this.schema=r,this.config=d;}init=async()=>{let r={typeDB:new Map},d=bt(this.schema);await Promise.all(this.config.dbConnectors.map(async i=>{if(i.provider==="typeDB"&&i.dbName){let[u,p]=await tryit(TypeDB.coreClient)(i.url);if(u){let s=`[BORM:${i.provider}:${i.dbName}] ${u.message??"Can't create TypeDB Client"}`;throw new Error(s)}try{let s=await p.session(i.dbName,SessionType.DATA);r.typeDB.set(i.id,{client:p,session:s});}catch(s){let w=`[BORM:${i.provider}:${i.dbName}] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(w)}}if(i.provider==="typeDBCluster"&&i.dbName){let[u,p]=await tryit(TypeDB.clusterClient)(i.addresses,i.credentials);if(u){let s=`[BORM:${i.provider}:${i.dbName}] ${u.message??"Can't create TypeDB Cluster Client"}`;throw new Error(s)}try{let s=await p.session(i.dbName,SessionType.DATA);r.typeDB.set(i.id,{client:p,session:s});}catch(s){let w=`[BORM:${i.provider}:${i.dbName}] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(w)}}})),this.schema=d,this.dbHandles=r;};#t=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#t(),this.schema);define=async()=>(await this.#t(),ht(this.config,this.schema,this.dbHandles));async query(r,d){await this.#t();let i={...this.config,query:{...ot.query,...this.config.query,...d}};return nt(r,i,this.schema,this.dbHandles)}async mutate(r,d){await this.#t();let i={...this.config,mutation:{...ot.mutation,...this.config.mutation,...d}};return jt(r,i,this.schema,this.dbHandles)}close=async()=>{this.dbHandles&&this.dbHandles.typeDB.forEach(async({client:r,session:d})=>{console.log("Closing session"),await d.close(),console.log("Closing client"),await r.close();});}},ui=ft;//! reads all the insertions and gets the first match. This means each id must be unique
34
+ ${y}`})(),p=a.dbConnectors[0].id,s=c.typeDB.get(p)?.session,B=c.typeDB.get(p)?.client;if(!s){console.log("Session Status: ","NO SESSION");return}s.close();let[{dbName:m}]=a.dbConnectors;await(await B.databases.get(m)).delete(),await B.databases.create(m);let f=await B.session(a.dbConnectors[0].dbName,typedbClient.SessionType.SCHEMA),l=await f.transaction(typedbClient.TransactionType.WRITE);await l.query.define(u),await l.commit(),await l.close();let d=await f.transaction(typedbClient.TransactionType.READ),o="match $a sub thing;";(await(await d.query.match(o)).collect()).forEach(async y=>{y.get("a");}),await d.close();};var $t=(a,r,c)=>c?r:`${a}\xB7${r}`,gt=a=>{let r=a.split("\xB7");return r[r.length-1]},J=(a,r)=>Object.values(Object.fromEntries(Object.entries(a).filter(([c,i])=>r(c,i))))[0],_=(a,r)=>Object.fromEntries(Object.entries(a).filter(([c,i])=>r(c,i))),bt=a=>{let r=[],c=immer.produce(a,u=>objectTraversal.traverse(u,({key:p,value:s,meta:B})=>{if(B.depth===2&&(p&&(s.dataFields=s.dataFields?.map(m=>({...m,dbPath:$t(p,m.path,m.shared)}))),s.extends)){let m=u.entities[s.extends]||u.relations[s.extends];if(s.allExtends=[s.extends,...m.allExtends||[]],s.idFields=m.idFields?(s.idFields||[]).concat(m.idFields):s.idFields,s.dataFields=m.dataFields?(s.dataFields||[]).concat(m.dataFields.map(w=>{let f=s.extends,l=a.entities[f]||a.relations[f];for(;!l.dataFields?.find(d=>d.path===w.path);)f=l.extends,l=a.entities[f]||a.relations[f];return {...w,dbPath:$t(f,w.path,w.shared)}})):s.dataFields,s.linkFields=m.linkFields?(s.linkFields||[]).concat(m.linkFields):s.linkFields,"roles"in m){let w=s,f=m;w.roles=w.roles||{},w.roles={...w.roles,...f.roles},Object.keys(w.roles).length===0&&(w.roles={});}}},{traversalType:"breadth-first"}));return objectTraversal.traverse(a,({key:u,value:p,meta:s})=>{if(u==="linkFields"){let m=(()=>{if(!s.nodePath)throw new Error("No path");let[f,l]=s.nodePath.split(".");return {thing:l,thingType:f==="entities"?"entity":f==="relations"?"relation":""}})(),w=Array.isArray(p)?p.map(f=>({...f,...m})):[{...p,...m}];r.push(...w);}}),immer.produce(c,u=>objectTraversal.traverse(u,({value:p,key:s,meta:B})=>{if(B.depth===2&&p.idFields&&!p.id){p.name=s;let m=()=>{if(B.nodePath?.split(".")[0]==="entities")return "entity";if(B.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};p.thingType=m(),p.computedFields=[],p.virtualFields=[],"roles"in p&&Object.entries(p.roles).forEach(([f,l])=>{l.playedBy=r.filter(d=>d.relation===s&&d.plays===f)||[],l.name=f;}),"linkFields"in p&&p.linkFields&&p.linkFields?.forEach(f=>{if(f.target==="relation"){f.oppositeLinkFieldsPlayedBy=[{plays:f.path,thing:f.relation,thingType:"relation"}];return}let l=r.filter(o=>o.relation===f.relation&&o.plays!==f.plays)||[];f.oppositeLinkFieldsPlayedBy=l;let{filter:d}=f;f.oppositeLinkFieldsPlayedBy=f.oppositeLinkFieldsPlayedBy.filter(o=>o.target==="role"),d&&Array.isArray(d)&&(f.oppositeLinkFieldsPlayedBy=f.oppositeLinkFieldsPlayedBy.filter(o=>d.some(t=>o.thing===t.$role)),f.oppositeLinkFieldsPlayedBy=f.oppositeLinkFieldsPlayedBy.filter(o=>d.some(t=>o.thing===t.$thing))),d&&!Array.isArray(d)&&(f.oppositeLinkFieldsPlayedBy=f.oppositeLinkFieldsPlayedBy.filter(o=>o.$role===d.$role),f.oppositeLinkFieldsPlayedBy=f.oppositeLinkFieldsPlayedBy.filter(o=>o.thing===d.$thing));});}if(typeof p=="object"&&"playedBy"in p){if([...new Set(p.playedBy?.map(m=>m.thing))].length>1)throw new Error(`Unsupported: roleFields can be only played by one thing. Role: ${s} path:${B.nodePath}`);if(p.playedBy.length===0)throw new Error(`Unsupported: roleFields should be played at least by one thing. Role: ${s}, path:${B.nodePath}`)}if(B.depth===4&&(p.default||p.computedValue)){let[m,w]=B.nodePath?.split(".")||[];p.isVirtual?u[m][w].virtualFields.push(p.path):u[m][w].computedFields.push(p.path);}}))},x=(a,r)=>{if(r.$entity){if(!(r.$entity in a.entities))throw new Error(`Missing entity '${r.$entity}' in the schema`);return a.entities[r.$entity]}if(r.$relation){if(!(r.$relation in a.relations))throw new Error(`Missing relation '${r.$relation}' in the schema`);return a.relations[r.$relation]}throw new Error(`Wrong schema or query for ${JSON.stringify(r)}`)},j=(a,r)=>{let c=a.dataFields?.map(t=>t.path)||[],i=a.linkFields?.map(t=>t.path)||[],u="roles"in a?radash.listify(a.roles,t=>t):[],p=[...c||[],...i||[],...u||[]],B=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields"],...p];if(!r)return {fields:p,dataFields:c,roleFields:u,linkFields:i};let m=r.$fields?r.$fields.map(t=>{if(typeof t=="string")return t;if("$path"in t&&typeof t.$path=="string")return t.$path;throw new Error(" Wrongly structured query")}):radash.listify(r,t=>t),w=r.$filter?radash.listify(r.$filter,t=>t.toString().startsWith("$")?void 0:t.toString()).filter(t=>t&&c?.includes(t)):[],f=r.$filter?radash.listify(r.$filter,t=>t.toString().startsWith("$")?void 0:t.toString()).filter(t=>t&&[...u||[],...i||[]].includes(t)):[],l=[...m,...w].filter(t=>!B.includes(t)).filter(t=>t),d=r.$filter?_(r.$filter,(t,n)=>w.includes(t)):{},o=r.$filter?_(r.$filter,(t,n)=>f.includes(t)):{};return {fields:p,dataFields:c,roleFields:u,linkFields:i,usedFields:m,usedLinkFields:i.filter(t=>m.includes(t)),usedRoleFields:u.filter(t=>m.includes(t)),unidentifiedFields:l,...w.length?{localFilters:d}:{},...f.length?{nestedFilters:o}:{}}},wt=(a,r)=>{let c=r.$localFilters&&radash.listify(r.$localFilters,(u,p)=>`has ${a.dataFields?.find(B=>B.path===u)?.dbPath} '${p}'`);return c?.length?`, ${c.join(",")}`:""},W=a=>a!==null,K=(a,r)=>Object.values(a).reduce((c,i)=>(i.extends===r&&c.push(i.name),c),[]);var te=(a,r)=>a.map(i=>{let u=[...i.conceptMaps],s=i.owner.asThing().type.label.name,B=r.entities[s]?r.entities[s]:r.relations[s];if(!B.idFields)throw new Error(`No idFields defined for ${s}`);let m=r.entities[s]?"entity":"relation",w=u.map(l=>{let d=l.get("attribute")?.asAttribute();return d?[gt(d.type.label.name),d.value]:[]}),f=Object.fromEntries(w);return {...f,[`$${m}`]:s,$id:f[B.idFields[0]]}}),ee=(a,r,c)=>a.flatMap(u=>u.conceptMaps.map(s=>{let B=new Map;return r.forEach(m=>{let w=s.get(`${m}_id`)?.asAttribute().value.toString(),f=s.get(m),l=f?.isEntity()?f.asEntity().type.label.name:f?.asRelation().type.label.name,o={id:w,entityName:(()=>l?(c.entities[l]??c.relations[l]).allExtends?.includes(m)?m:l:m)()};w&&B.set(m,o);}),B})),ne=(a,r,c)=>a.flatMap(u=>u.conceptMaps.map(s=>{let B=s.get(`${r}_id`)?.asAttribute().value.toString(),m=s.get(`${c}_id`)?.asAttribute().value.toString();return {ownerId:B,path:c,roleId:m}})),ie=(a,r)=>{let c=radash.listify(a.roles,(i,u)=>{if([...new Set(u.playedBy?.map(B=>B.thing))].length!==1)throw new Error("a role can be played by two entities throws the same relation");if(!u.playedBy)throw new Error("Role not being played by nobody");let p=u.playedBy[0].plays,s=K(r.entities,p);return [p,...s]});return radash.unique(radash.flat(c))},H=async(a,r)=>{let{schema:c,bqlRequest:i,config:u,tqlRequest:p}=a,{rawTqlRes:s}=r;if(i){if(!s)throw new Error("TQL query not executed")}else throw new Error("BQL request not parsed");let{query:B}=i;if(!B){if(s.insertions?.length===0&&!p?.deletions){r.bqlRes={};return}let{mutation:d}=i;if(!d)throw new Error("TQL mutation not executed");let t=[...d.things,...d.edges].map(n=>{let y=s.insertions?.find(h=>h.get(`${n.$bzId}`))?.get(`${n.$bzId}`);if(n.$op==="create"||n.$op==="update"||n.$op==="link"){if(!y?.asThing().iid)throw new Error(`Thing not received on mutation: ${JSON.stringify(n)}. Probably the relation had all its edges deleted instead of replaced`);let h=y?.asThing().iid;return u.mutation?.noMetadata?radash.mapEntries(n,(e,S)=>[e.toString().startsWith("$")?Symbol.for(e):e,S]):{$dbId:h,...n,[n.path]:n.$id}}if(n.$op==="delete"||n.$op==="unlink")return n;if(n.$op!=="match")throw new Error(`Unsupported op ${n.$op}`)}).filter(n=>n);r.bqlRes=t;return}if(!s.entity)throw new Error("TQL query not executed");let m=te(s.entity,c),w=s.relations?.map(d=>{let o=c.relations[d.relation],t=ie(o,c),n=ee(d.conceptMapGroups,[...t,o.name],c);return {name:d.relation,links:n}}),f=s.roles?.map(d=>({name:d.ownerPath,links:ne(d.conceptMapGroups,d.ownerPath,d.path)})),l=r.cache||{entities:new Map,relations:new Map,roleLinks:new Map};m.forEach(d=>{let o=d.$entity||d.$relation,t=d.$id,n=l.entities.get(o)||new Map;n.set(t,{...d,$show:!0}),l.entities.set(o,n);}),w?.forEach(d=>{let o=d.name,t=l.relations.get(o)||[];t.push(...d.links),l.relations.set(o,t),d.links.forEach(n=>{[...n.entries()].forEach(([y,{entityName:h,id:e}])=>{let S=l.entities.get(h)||new Map,M={[c.entities[h]?.thingType||c.relations[h].thingType]:h,$id:e,...S.get(e)};S.set(e,M),l.entities.set(h,S);});});}),f?.forEach(d=>{let o=c.relations[d.name]||c.entities[d.name];d.links.forEach(t=>{let n=l.roleLinks.get(t.ownerId)||{},y=n[t.path];y?radash.isArray(y)?y.push(t.roleId):radash.isString(y)&&y!==t.roleId&&(y=[y,t.roleId]):y=t.roleId,n[t.path]=y,l.roleLinks.set(t.ownerId,n),o.roles[t.path].playedBy?.forEach(h=>{let e=l.entities.get(h.thing)||new Map,S={$entity:h.thing,$id:t.roleId,...e.get(t.roleId)};e.set(t.roleId,S),l.entities.set(h.thing,e);});});}),r.cache=l;};var re=/((\/\/.*$)|(\/\*.*\*\/))/gm,oe=/(\s*async\s*|\s*function\s*)+/,se=/(?:function\s*[^(\s]*\s*|\s*=>\s*|^\s*)\(([^)]*)\)/,ae=/[ ,\n\r\t]+/,Bt=a=>{let r=a.toString().replace(re,"").replace(oe,"").trim(),c=se.exec(r);if(!c)return [];let i;for(let u of c.slice(1))if(u){i=u;break}return i?(i=i.replace(/\{\s*/g,"").replace(/\s*\}/g,""),i.split(ae).filter(u=>u.trim()!=="")):[]};var Z=({currentThing:a,fieldSchema:r,mandatoryDependencies:c=!1})=>{if(!r||!r.default||!r.default.value)throw new Error("Virtual field: No field schema found, or wrongly configured");let i=r.default.value,p=Bt(i).filter(B=>!(B in a));if(c&&p.length)throw new Error(`Virtual field: Missing arguments ${p.join(", ")}`);return "default"in r?r.default?.value(a):void 0};var ce=(a,r)=>a.length===1&&typeof a[0]!="string"&&a[0].$id===r?a[0]:a,Ft=a=>typeof a=="string"||!!a.$show,Rt=(a,r)=>immer.produce(a,c=>objectTraversal.traverse(c,({value:i})=>{if(Array.isArray(i)||typeof i!="object")return;i.$tempId&&(i.$tempId=`_:${i.$tempId}`),i.$fields&&delete i.$fields,i.$filter&&delete i.$filter,i.$show&&delete i.$show,i.$bzId&&delete i.$bzId,r.query?.noMetadata&&(i.$entity||i.$relation)&&(delete i.$entity,delete i.$relation,delete i.$id),Object.getOwnPropertySymbols(i).forEach(p=>{delete i[p];}),i.$excludedFields&&(i.$excludedFields.forEach(p=>{delete i[p];}),delete i.$excludedFields);})),at=(a,r,c,i)=>a.map(([u,p])=>{if(!r||!r.includes(u))return null;if(!c.$fields||c.$fields.includes(i))return u;let s=c.$fields.find(B=>radash.isObject(B)&&B.$path===i);if(s){let B={..._(p,(w,f)=>w.startsWith("$"))},m=s.$fields?{...B,$fields:s.$fields}:B;if(s.$id){if(Array.isArray(s.$id))return s.$id.includes(u)?m:null;if(s.$id===u)return m}if(m.$fields&&m.$fields.includes("id")&&!m.$show){let w="";return m.$fields.forEach(f=>{f==="id"?w=m.$id:w=m;}),w}return m}return null}).filter(u=>u),de=(a,r)=>{let c={};return r.forEach(i=>{c[i.$bzId]=i.$id;}),a.forEach(i=>{Object.keys(i).forEach(u=>{c[i[u]]&&u!=="$tempId"&&(i[u]=c[i[u]]);});}),a},pe=(a,r)=>{let c=r.map(u=>u.$bzId),i=!1;return a.forEach(u=>{Object.keys(u).forEach(p=>{c.includes(u[p])&&(i=!0);});}),i},Tt=async(a,r)=>{let{bqlRequest:c,config:i,schema:u}=a,{cache:p}=r;if(!c)throw new Error("BQL request not parsed");let{query:s}=c;if(!s){let y=r.bqlRes[0]?r.bqlRes:[r.bqlRes],h=a.bqlRequest?.mutation?.things;if(pe(y,h)){let F=de(y,h);r.bqlRes=F[1]?F:F[0];}let S=Rt(r.bqlRes,i);r.bqlRes=S;return}if(!p)return;let B="$entity"in s?s.$entity:s.$relation,m=p.entities.get(B.name);if(!m){r.bqlRes=null;return}let f=radash.listify(s.$filter,y=>y).some(y=>B.dataFields?.find(h=>h.path===y)?.validations?.unique),l=!Array.isArray(c.query)&&(c.query?.$id&&!Array.isArray(c.query?.$id)||f);if(Array.isArray(a.rawBqlRequest))throw new Error("Query arrays not implemented yet");let d=m,o=[...d].length?[...d].map(([y,h])=>({...a.rawBqlRequest,$id:y})):a.rawBqlRequest,t=immer.produce(o,y=>objectTraversal.traverse(y,({value:h})=>{let e=h;if(!e?.$entity&&!e?.$relation)return;let S="$entity"in e?e.$entity:e.$relation;if(S){let F=Array.isArray(e.$id)?e.$id:[e.$id],M="$relation"in e?u.relations[e.$relation]:u.entities[e.$entity],{dataFields:I,roleFields:A}=j(M),R=p.entities.get(S);if(!R)return;[...R].forEach(([g,O])=>{if(F.includes(g)){let N=e.$fields?e.$fields:I,{virtualFields:T}=M;T?.forEach($=>{if(N?.includes($)&&e[$]===void 0){let Q=M.dataFields?.find(P=>P.path===$),k=Z({currentThing:O,fieldSchema:Q});e[$]=k;}}),radash.listify(O,($,Q)=>{$.startsWith("$")||N?.includes($)&&(e[$]=Q);});let L=p.roleLinks.get(g),E=e.$fields?e.$fields.filter($=>typeof $=="string"):A,b=e.$fields?.filter($=>typeof $=="object")?.map($=>$.$path)||[];Object.entries(L||{}).forEach(([$,Q])=>{if(![...E,...b].includes($))return;if(!("roles"in M))throw new Error("No roles in schema");let k=Array.isArray(Q)?[...new Set(Q)]:[Q],{cardinality:P,playedBy:z}=M.roles[$],C=[...new Set(z?.map(D=>D.thing))]?.flatMap(D=>{let rt=p.entities.get(D);return rt?at([...rt],k,e,$):[]});if(C?.length){if(C.length===1&&C[0]===e.$id)return;if(P==="ONE"){e[$]=C[0];return}e[$]=C.filter(D=>typeof D=="string"||typeof D=="object"&&D?.$show);}});}});let q=M.linkFields;q&&q.forEach(g=>{let O=p.relations.get(g.relation),N=g.oppositeLinkFieldsPlayedBy;if(!O)return null;if(g.target==="relation"){let T=[...O].reduce((L,E)=>{let b=E.get(g.plays)?.id;if(b&&b===F[0]){let $=E.get(g.relation);if(!$)return L;L[$.entityName]||(L[$.entityName]=new Set),L[$.entityName].add($.id);}return L},{});return Object.entries(T).map(([L,E])=>{let b=p.entities.get(L);if(!b)return null;let $=at([...b],[...E.values()],e,g.path).filter(W).filter(Ft);if($.length===0)return null;if($&&$.length){if(g.cardinality==="ONE")return e[g.path]=$[0],null;e[g.path]=$;}return null}),null}return g.target==="role"&&N.forEach(T=>{if(!O)return;let L=[...O].reduce((E,b)=>{let $=b.get(g.plays)?.id;if($&&$===F[0]){let Q=b.get(T.plays);if(!Q)return E;E[Q.entityName]||(E[Q.entityName]=new Set),E[Q.entityName].add(Q.id);}return E},{});Object.entries(L).forEach(([E,b])=>{let $=p.entities.get(E);if(!$)return;let Q=at([...$],[...b.values()],e,g.path).filter(W).filter(Ft);if(Q.length!==0&&Q&&Q.length){if(g.cardinality==="ONE"){e[g.path]=Q[0];return}e[g.path]=Q;let k={},P=G=>(G.$path===g.path&&(k=G),G?.$fields?.forEach(P)),z="";s.$fields?.forEach(P),k&&(Array.isArray(k.$id)||(z=k.$id)),e[g.path]=ce(Q,z);}});}),null});}})),n=Rt(t,i);r.bqlRes=l?n[0]:n;};var Y=async a=>{let{schema:r,bqlRequest:c}=a;if(!c?.query)throw new Error("BQL query not parsed");let{query:i}=c,u="$entity"in i?i.$entity:i.$relation,p=u.defaultDBConnector.path||u.name;if(!p)throw new Error(`No thing path in ${JSON.stringify(u)}`);if(!u.idFields)throw new Error("No id fields");let[s]=u.idFields,B=`$${p}_id`,m=`, has ${s} ${B};`;i.$id&&(Array.isArray(i.$id)?m+=` ${B} like "${i.$id.join("|")}";`:m+=` ${B} "${i.$id}";`);let w=wt(u,i),f="roles"in u?radash.listify(u.roles,(t,n)=>({path:t,var:`$${t}`,schema:n})):[],l=`match $${p} isa ${p}, has attribute $attribute ${w} ${m} group $${p};`,d=f.map(t=>{if(!t.schema.playedBy||[...new Set(t.schema.playedBy?.map(y=>y.thing))].length!==1)throw new Error("Unsupported: Role played by multiple linkfields or none");let n=t.schema.playedBy[0].thing;return {path:t.path,owner:p,request:`match $${p} (${t.path}: ${t.var} ) isa ${p} ${m} ${t.var} isa ${n}, has id ${t.var}_id; group $${p};`}}),o=u.linkFields?.flatMap(t=>{let n=`$${t.plays}_id`,y=`, has ${s} ${n};`;i.$id&&(Array.isArray(i.$id)?y+=` ${n} like "${i.$id.join("|")}";`:y+=` ${n} "${i.$id}";`);let h=`match $${t.plays} isa ${p}${w} ${y}`,e=t.target==="relation",F=`$${t.relation}`,M=`${e?F:""} (${t.plays}: $${t.plays}`,I=t.oppositeLinkFieldsPlayedBy.map(T=>e?null:`${T.plays}: $${T.plays}`),A=[M,...I].filter(T=>T).join(",");if(r.relations[t.relation]===void 0)throw new Error(`Relation ${t.relation} not found in schema`);let R=r.relations[t.relation].defaultDBConnector.path||t.relation,q=`) isa ${R};`,g=t.oppositeLinkFieldsPlayedBy.map(T=>`$${e?T.thing:T.plays} isa ${T.thing}, has id $${e?T.thing:T.plays}_id;`).join(" "),O=`group $${t.plays};`,N=`${h} ${A} ${q} ${g} ${O}`;return {relation:R,entity:p,request:N}});a.tqlRequest={entity:l,...d?.length?{roles:d}:{},...o?.length?{relations:o}:{}};};var Mt=async a=>{let{rawBqlRequest:r,schema:c}=a;if(!("$entity"in r)&&!("$relation"in r))throw new Error("No entity specified in query");let i=x(c,r);if(!i)throw new Error(`Thing '${r}' not found in schema`);let{unidentifiedFields:u,localFilters:p,nestedFilters:s}=j(i,r);if(u&&u.length>0)throw new Error(`Unknown fields: [${u.join(",")}] in ${JSON.stringify(r)}`);a.bqlRequest={query:{...a.rawBqlRequest,...i.thingType==="entity"?{$entity:i}:{},...i.thingType==="relation"?{$relation:i}:{},...p?{$localFilters:p}:{},...s?{$nestedFilters:s}:{}}};};var X=async(a,r)=>{let{dbHandles:c,bqlRequest:i,tqlRequest:u,config:p}=a;if(!i)throw new Error("BQL request not parsed");if(!u)throw new Error("TQL request not built");if(!u.entity)throw new Error("BQL request error, no entities");let{query:s}=i;if(!s)throw new Error("BQL request is not a query");let B=p.dbConnectors[0].id,m=c.typeDB.get(B)?.session;if(!m?.isOpen())throw new Error("Session is closed");let w=await m.transaction(typedbClient.TransactionType.READ);if(!w)throw new Error("Can't create transaction");let f=w.query.matchGroup(u.entity),l=u.roles?.map(y=>({...y,stream:w.query.matchGroup(y.request)})),d=u.relations?.map(y=>({...y,stream:w.query.matchGroup(y.request)})),o=await f.collect(),t=await Promise.all(l?.map(async y=>({path:y.path,ownerPath:y.owner,conceptMapGroups:await y.stream.collect()}))||[]),n=await Promise.all(d?.map(async y=>({relation:y.relation,entity:y.entity,conceptMapGroups:await y.stream.collect()}))||[]);await w.close(),r.rawTqlRes={entity:o,...t?.length&&{roles:t},...n?.length&&{relations:n}};};var lt=async(a,r)=>{let{bqlRequest:c,schema:i}=a,{cache:u}=r;if(!c)throw new Error("BQL request not parsed");if(!u)throw new Error("Cache not initialized");let{query:p}=c;if(!p)return;let{$fields:s}=p;if(!("$entity"in p)&&!("$relation"in p))throw new Error("Node attributes not supported");let B="$entity"in p?p.$entity:p.$relation;if(!s||!Array.isArray(s))return;let m=s.filter(o=>typeof o!="string"&&o.$path),w=B.linkFields?.filter(o=>m.findIndex(t=>t.$path===o.path)!==-1).flatMap(o=>o.oppositeLinkFieldsPlayedBy)||[],f="roles"in B?radash.listify(B.roles,(o,t)=>m.findIndex(n=>n.$path===o)!==-1?t:null).flatMap(o=>o?.playedBy).filter(o=>o):[],d=[...w,...f]?.map(o=>{if(!o)return null;let{thing:t}=o,n=K(i.entities,t);return [t,...n].map(y=>{let h=u.entities.get(y);if(!h)return null;let e=Array.from(h.values()).reduce((g,O)=>("$show"in O||g.push(O.$id),g),[]);if(e.length===0)return null;let S=i.entities[y]?{...i.entities[y],thingType:"entity"}:{...i.relations[y],thingType:"relation"},F=s.find(g=>typeof g=="object"&&g.$path===o.plays),M=F?.$id,I=M?Array.isArray(M)?M:[M]:[],A=F?.$filter,q={query:{$id:I.length?I.filter(g=>e.includes(g)):e,$fields:F?.$fields,...S.thingType==="entity"?{$entity:S}:{},...S.thingType==="relation"?{$relation:S}:{},...A?{$localFilters:A}:{}}};return {req:{...a,bqlRequest:q},res:r,pipeline:[Y,X,H,lt]}}).filter(W)}).filter(W);if(d?.length)return radash.flat(d)};var Qt=async a=>{let{bqlRequest:r,schema:c}=a;if(!r)throw new Error("BQL request not parsed");let{mutation:i}=r;if(!i)throw new Error("BQL request is not a mutation");let u=o=>{let t=o.$op,n=`$${o.$bzId}`,y=x(c,o),{idFields:h,defaultDBConnector:e}=y,S=e?.path||o.$entity||o.$relation,F=o.$id,M=h?.[0],I=radash.listify(o,(E,b)=>{if(E.startsWith("$")||E===M||!b)return "";let $=y.dataFields?.find(P=>P.path===E);if(!$?.path)return "";let k=$.dbPath;if(["TEXT","ID","EMAIL"].includes($.contentType))return `has ${k} '${b}'`;if(["NUMBER"].includes($.contentType))return `has ${k} ${b}`;if($.contentType==="DATE"){if(Number.isNaN(b.valueOf()))throw new Error("Invalid format, Nan Date");return b instanceof Date?`has ${k} ${b.toISOString().replace("Z","")}`:`has ${k} ${new Date(b).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${$.contentType}`)}).filter(E=>E),A=`${n}-atts`,R=radash.listify(o,(E,b)=>{if(E.startsWith("$")||E===M||!b)return "";let $=y.dataFields?.find(P=>P.path===E);if(!$?.path)return "";let k=$.dbPath;return `{${A} isa ${k};}`}).filter(E=>E),q=o[Symbol.for("isLocalId")],g=radash.isArray(F)?`like '${F.join("|")}'`:`'${F}'`,O=!q&&F?[`has ${M} ${g}`]:[],N=[...O,...I].filter(E=>E).join(","),T=()=>{if(t==="delete"||t==="unlink"||t==="match")return `${n} isa ${[S,...O].filter(E=>E).join(",")};`;if(t==="update"){if(!R.length)throw new Error("update without attributes");return `${n} isa ${[S,...O].filter(E=>E).join(",")}, has ${A};
35
+ ${R.join(" or ")};
36
+ `}return ""},L=()=>t==="update"||t==="link"||t==="match"?`${n} isa ${[S,...O].filter(E=>E).join(",")};`:"";if(o.$entity||o.$relation)return {op:t,deletionMatch:T(),insertionMatch:L(),insertion:t==="create"?`${n} isa ${[S,N].filter(E=>E).join(",")};`:t==="update"&&I.length?`${n} ${I.join(",")};`:"",deletion:t==="delete"?`${n} isa ${S};`:t==="update"&&R.length?`${n} has ${A};`:""};throw new Error("in attributes")},p=o=>{let t=o.$op,n=x(c,o),y=`$${o.$bzId}`,h=o.$id,e=n.defaultDBConnector?.path||o.$relation,S="roles"in n?radash.listify(n.roles,L=>L):[],F=o.$relation&&"roles"in n&&radash.mapEntries(n.roles,(L,E)=>[L,E.dbConnector?.path||L]),M=radash.listify(o,(L,E)=>{if(!S.includes(L))return null;if(!("roles"in n))throw new Error("This should have roles! ");let b=F[L];return Array.isArray(E)?E.map($=>({path:b,id:$})):{path:b,id:E}}).filter(L=>L).flat(),I=M.map(L=>{if(!L?.path)throw new Error("Object without path");return `${L.path}: $${L.id}`}),A=M.length>0?`( ${I.join(" , ")} )`:"",R=A?`${y} ${A} ${o[Symbol.for("edgeType")]==="linkField"||t==="delete"||t==="unlink"?`isa ${e}`:""}`:"",q=`${y} ${o[Symbol.for("edgeType")]==="linkField"||t==="delete"?`isa ${e}`:""}`,g=()=>R?t==="link"?`${R};`:t==="create"?`${R}, has id '${h}';`:"":"",O=()=>R&&t==="match"?`${R};`:"",N=()=>R?t==="delete"?`${R};`:t==="match"?`${R};`:"":"",T=()=>R?t==="delete"?`${q};`:t==="unlink"?`${y} ${A};`:"":"";return {deletionMatch:N(),insertionMatch:O(),deletion:T(),insertion:g(),op:""}},s=(o,t)=>{let n=t==="edges"?p:u;if(Array.isArray(o))return o.map(M=>{let{preDeletionBatch:I,insertionMatch:A,deletionMatch:R,insertion:q,deletion:g}=n(M);return radash.shake({preDeletionBatch:I,insertionMatch:A,deletionMatch:R,insertion:q,deletion:g},O=>!O)}).filter(M=>M);let{preDeletionBatch:y,insertionMatch:h,deletionMatch:e,insertion:S,deletion:F}=n(o);return radash.shake({preDeletionBatch:y,insertionMatch:h,deletionMatch:e,insertion:S,deletion:F},M=>!M)},B=s(i.things),m=Array.isArray(B)?B:[B],w=s(i.edges,"edges"),f=Array.isArray(w)?w:[w],l=[...m,...f],d=radash.shake({insertionMatches:l.map(o=>o.insertionMatch).join(" ").trim(),deletionMatches:l.map(o=>o.deletionMatch).join(" ").trim(),insertions:l.map(o=>o.insertion).join(" ").trim(),deletions:l.map(o=>o.deletion).join(" ").trim()},o=>!o);a.tqlRequest=d;};var Fe=a=>{if(!a.startsWith("_:"))throw new Error("ID must start with '_:'.");let r=a.substring(2);if(!/^[a-zA-Z0-9-_]+$/.test(r))throw new Error("$tempId must contain only alphanumeric characters, hyphens, and underscores.");if(a.length>36)throw new Error("$tempId must not be longer than 36 characters.");return r},qt=async a=>{let{rawBqlRequest:r,schema:c}=a,u=(w=>immer.produce(w,f=>objectTraversal.traverse(f,({value:l,key:d,parent:o})=>{radash.isObject(l)&&(l=radash.shake(l,t=>t===void 0)),d==="$tempId"&&(o[d]=Fe(l));})))(r),s=(w=>immer.produce(w,f=>objectTraversal.traverse(f,({value:l,meta:d,key:o})=>{if(radash.isObject(l)){if(l.$arrayOp)throw new Error("Array op not supported yet");if(o==="$filter"||d.nodePath?.includes(".$filter."))return;let t=l;if(t.$op==="create"&&t.$id)throw new Error("Can't write to computed field $id. Try writing to the id field directly.");let n=x(c,t),h=d.nodePath?.split(".")?.filter(R=>Number.isNaN(parseInt(R,10))).join(".");if(!n)throw new Error(`Schema not found for ${t.$entity||t.$relation}`);t.$bzId=t.$tempId??`T_${uuid.v4()}`,t[Symbol.for("schema")]=n,t[Symbol.for("dbId")]=n.defaultDBConnector.id;let{usedLinkFields:e,usedRoleFields:S}=j(n,t),F=e.map(R=>({fieldType:"linkField",path:R,schema:n.linkFields.find(q=>q.path===R)})),M=n.thingType==="relation"?S.map(R=>({fieldType:"roleField",path:R,schema:J(n.roles,q=>q===R)})):[];if(F.some(R=>R.schema?.target==="role")&&F.some(R=>R.schema?.target==="relation"))throw new Error("Unsupported: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.");let I=M.filter(R=>[...new Set(R.schema.playedBy?.map(q=>q.thing))].length!==1);if(I.length>1)throw new Error(`Field: ${I[0].path} - If a role can be played by multiple things, you must specify the thing in the mutation: ${JSON.stringify(I[0].schema.playedBy)}. Schema: ${JSON.stringify(I[0].schema)}`);let A=d.nodePath;if([...F,...M].forEach(R=>{let q=t[R.path];if(q===void 0)return;let g=R.schema;if(!g)throw new Error(`Field ${R.path} not found in schema`);let O=R.fieldType==="roleField"?g?.playedBy[0]:g,T=(()=>g&&"relation"in g&&O?.relation===t.$relation?"$self":O?.relation?O?.relation:"$self")(),L=T==="$self"?n:c.relations[T];if(J(L.roles,(P,z)=>P===R.path)?.playedBy?.length===0)throw new Error(`unused role: ${A}.${R.path}`);if(!g)throw new Error(`Field ${R.path} not found in schema`);let b=R.fieldType==="linkField"?g?.oppositeLinkFieldsPlayedBy:g?.playedBy;if(!b)throw new Error(`No opposite fields found for ${JSON.stringify(g)}`);if([...new Set(b?.map(P=>P.thing))].length>1)throw new Error(`Field: ${R.path} - If a role can be played by multiple things, you must specify the thing in the mutation: ${JSON.stringify(b)}. Schema: ${JSON.stringify(g)}`);if(g.cardinality==="ONE"&&Array.isArray(q))throw new Error("Can't have an array in a cardinality === ONE link field");if(g.cardinality==="MANY"&&q!==null&&!Array.isArray(q)&&!q.$arrayOp)throw new Error(`${R.fieldType==="linkField"?g.path:g.name} is a cardinality === MANY thing. Use an array or a $arrayOp object`);if(q?.$entity||q?.$relation)return;let[$]=b,Q="plays"in g?"linkField":"roleField",k={[`$${$.thingType}`]:$.thing,[Symbol.for("relation")]:T,[Symbol.for("edgeType")]:Q,[Symbol.for("parent")]:{path:A,...t.$id?{$id:t.$id}:{},...t.$tempId?{$tempId:t.$tempId}:{},...t.filter?{filter:t.filter}:{},links:b},[Symbol.for("role")]:$.plays,[Symbol.for("oppositeRole")]:"plays"in g?g.plays:void 0,[Symbol.for("relFieldSchema")]:g};if(radash.isObject(q)&&(t[R.path]={...k,...q}),Array.isArray(q))if(q.every(P=>radash.isObject(P)))t[R.path]=q.map(P=>({...k,...P}));else if(q.every(P=>typeof P=="string"))t[R.path]=q.map(P=>({...k,$op:t.$op==="create"?"link":"replace",$id:P}));else throw new Error(`Invalid array value for ${R.path}`);if(typeof q=="string"&&(t[R.path]={...k,$op:t.$op==="create"?"link":"replace",$id:q}),q===null){let P={...k,$op:"unlink"};t[R.path]=g.cardinality==="MANY"?[P]:P;}}),!h&&!t.$entity&&!t.$relation)throw new Error("Root things must specify $entity or $relation")}})))(u),m=(w=>immer.produce(w,f=>objectTraversal.traverse(f,({parent:l,key:d,value:o,meta:t})=>{if(radash.isObject(o)){if(Object.keys(o).length===0)throw new Error("Empty object!");if(d==="$filter"||t.nodePath?.includes(".$filter."))return;let n=o,y=t.nodePath?.split(".");if(n.$tempId&&!(n.$op===void 0||n.$op==="link"||n.$op==="create"||n.$op==="update"))throw new Error(`Invalid op ${n.$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.`);let h=y?.filter(C=>Number.isNaN(parseInt(C,10))).join("."),e=h?Array.isArray(l)?y?.slice(0,-1).join("."):t.nodePath:t.nodePath||"",S=x(c,n),{unidentifiedFields:F,dataFields:M,roleFields:I,linkFields:A}=j(S,n),R=immer.current(n)[Symbol.for("parent")],q=h&&R.path,O=(q?objectTraversal.getNodeByPath(f,q):f)?.$op;if(h&&!O)throw new Error("Error: Parent $op not detected");let N=n[Symbol.for("relFieldSchema")],T=Object.keys(n).some(C=>M?.includes(C)),L=Object.keys(n).some(C=>[...I,...A].includes(C)),E=()=>{if(n.$op)return n.$op;if(h&&!n.$id&&!n.$tempId&&O!=="create"&&N.cardinality==="ONE")throw new Error(`Please specify if it is a create or an update. Path: ${t.nodePath}`);if(n.$tempId)return "create";if((n.$id||n.$filter)&&T)return "update";if((n.$id||n.$filter)&&h&&!T&&!L)return "link";if(!n.$filter&&!n.$id&&!n.$tempId)return "create";if((n.$id||n.$filter)&&!T&&L)return "match";throw new Error("Wrong op")};if(n.$op||(n.$op=E()),l||(n.$parentKey=""),typeof l=="object"&&(Array.isArray(l)&&(n[Symbol.for("index")]=d),n[Symbol.for("path")]=e,n[Symbol.for("isRoot")]=!h,n[Symbol.for("depth")]=h?.split(".").length),!n.$entity&&!n.$relation)throw new Error(`Node ${JSON.stringify(n)} without $entity/$relation`);let{idFields:b,computedFields:$,virtualFields:Q}=S;if(!b)throw new Error("No idFields found");let[k]=b,P=radash.listify(n,(C,D)=>D!==void 0?C:void 0),z=P.filter(C=>Q?.includes(C));if(z.length>0)throw new Error(`Virtual fields can't be sent to DB: "${z.join(",")}"`);if($.filter(C=>!P.includes(C)).forEach(C=>{let D=S.dataFields?.find(V=>V.path===C),Wt=S.linkFields?.find(V=>V.path===C)?.oppositeLinkFieldsPlayedBy[0],Gt="roles"in S?J(S.roles,(V,Oe)=>V===C):void 0,ut=D||Wt||Gt;if(!ut)throw new Error(`no field Def for ${C}`);if(C===k&&n.$op==="create"&&!n[C]){let V=Z({currentThing:n,fieldSchema:ut,mandatoryDependencies:!0});n[C]=V,n.$id=V;}}),F.length>0)throw new Error(`Unknown fields: [${F.join(",")}] in ${JSON.stringify(n)}`)}})))(s);a.filledBqlRequest=m;};var kt=async a=>{let{filledBqlRequest:r,schema:c}=a,i=f=>{let l=[],d=[],o=h=>{if(h.$id)return h.$id;let e=x(c,h),{idFields:S}=e;if(!S)throw new Error(`no idFields: ${JSON.stringify(h)}`);let[F]=S;if(!F)throw new Error(`no idField: ${JSON.stringify(h)}`);let M=e.dataFields?.find(R=>R.path===F),I=h.$op==="create"?M?.default?.value():null,A=h[F]||h.$id||I;if(!A)throw new Error(`no idValue: ${JSON.stringify(h)}`);return A},t=h=>{if(h.$op==="create"){let e=o(h);if(l.find(S=>S.$id===e))throw new Error(`Duplicate id ${e} for node ${JSON.stringify(h)}`);if(d.find(S=>S.$bzId===h.$bzId))throw new Error(`Duplicate $bzid ${h.$bzId} for node ${JSON.stringify(h)}`);l.push({...h,$id:e});return}h.$tempId&&h.$op==="match"||l.push(h);},n=h=>{if(h.$op==="create"){let e=o(h);if(l.find(S=>S.$id===e),d.find(S=>S.$bzId===h.$bzId))throw new Error(`Duplicate %bzId ${h.$bzIdd} for edge ${JSON.stringify(h)}`);d.push({...h,$id:e});return}d.push(h);};return objectTraversal.traverse(f,({value:h})=>{if(!radash.isObject(h))return;let e=h;if(e.$entity||e.$relation){if(!e.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(e)}`);if(!e.$bzId)throw new Error("[internal error] BzId not found");let S=x(c,e),{dataFields:F,roleFields:M,linkFields:I,usedFields:A}=j(S,e),R=()=>{if(e.$op==="create"||e.$op==="delete")return e.$op;if(e.$op==="update"){let g=A.filter(T=>F?.includes(T)),O=A.filter(T=>M?.includes(T)),N=A.filter(T=>I?.includes(T));if(g.length>0)return "update";if(O.length>0||N.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(e)}`)}return "match"},q={...e.$entity&&{$entity:e.$entity},...e.$relation&&{$relation:e.$relation},...e.$id&&{$id:e.$id},...e.$tempId&&{$tempId:e.$tempId},...e.$filter&&{$filter:e.$filter},...radash.shake(radash.pick(e,F||[""])),$op:R(),$bzId:e.$bzId,[Symbol.for("dbId")]:S.defaultDBConnector.id,[Symbol.for("path")]:e[Symbol.for("path")],[Symbol.for("parent")]:e[Symbol.for("parent")],[Symbol.for("isRoot")]:e[Symbol.for("isRoot")],[Symbol.for("isLocalId")]:e[Symbol.for("isLocalId")]||!1};if(t(q),e[Symbol.for("relation")]&&e[Symbol.for("edgeType")]==="linkField"){if((e.$op==="link"||e.$op==="unlink")&&(e.$id||e.$filter)){if(e.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");l.push({...e,$op:"match"});}let g=e[Symbol.for("relation")]===e.$relation,O=g?e.$bzId:uuid.v4(),T=e[Symbol.for("parent")].path,E=(T?objectTraversal.getNodeByPath(f,T):f).$bzId;if(!E)throw new Error("No parent id found");if(e[Symbol.for("relation")]==="$self")return;let b=()=>{if(e.$op==="delete")return g?"match":"delete";if(e.$op==="unlink")return g?"unlink":"delete";if(e.$op==="link"||e.$op==="create")return g?"link":"create";if(e.$op==="replace")throw new Error("Unsupported: Replaces not implemented yet");return "match"},$={$relation:e[Symbol.for("relation")],$bzId:O,...e.$tempId?{$tempId:e.$tempId}:{},$op:b(),...g?{}:{[e[Symbol.for("role")]]:e.$bzId},[e[Symbol.for("oppositeRole")]]:E,[Symbol.for("dbId")]:c.relations[e[Symbol.for("relation")]].defaultDBConnector.id,[Symbol.for("edgeType")]:"linkField",[Symbol.for("info")]:"normal linkField",[Symbol.for("path")]:e[Symbol.for("path")],[Symbol.for("parent")]:e[Symbol.for("parent")]};n($),(e.$op==="unlink"||b()==="unlink")&&g&&n({$relation:e[Symbol.for("relation")],$bzId:O,$op:"match",[e[Symbol.for("oppositeRole")]]:E,[Symbol.for("dbId")]:c.relations[e[Symbol.for("relation")]].defaultDBConnector.id,[Symbol.for("edgeType")]:"linkField",[Symbol.for("info")]:"additional ownrelation unlink linkField",[Symbol.for("path")]:e[Symbol.for("path")],[Symbol.for("parent")]:e[Symbol.for("parent")]});}if(e.$relation){let g=_(e,(T,L)=>M.includes(T)),O=radash.mapEntries(g,(T,L)=>radash.isArray(L)?[T,L]:radash.isObject(L)?[T,L.$bzId]:[T,L]),N=_(h,(T,L)=>T.startsWith("$")||T.startsWith("Symbol"));if(Object.keys(g).filter(T=>!T.startsWith("$")).length>0){if(e.$op==="create"||e.$op==="delete"){let T=()=>{if(e.$op==="create")return "link";if(e.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},L=radash.mapEntries(O,(b,$)=>Array.isArray($)?[b,$.map(Q=>Q.$bzId||Q)]:[b,$.$bzId||$]),E={...N,$relation:e.$relation,$op:T(),...L,$bzId:e.$bzId,[Symbol.for("path")]:e[Symbol.for("path")],[Symbol.for("dbId")]:S.defaultDBConnector.id,[Symbol.for("info")]:"coming from created or deleted relation",[Symbol.for("edgeType")]:"roleField on C/D"};n(E);return}if(e.$op==="match"||e.$op==="update"&&Object.keys(g).length>0){let T=0;Object.entries(g).forEach(([L,E])=>{let b=radash.isArray(E)?E:[E],$=Q=>Q==="create"||Q==="replace"?"link":Q;b.forEach(Q=>{let k=$(Q.$op);if(k==="replace")throw new Error("Not supported yet: replace on roleFields");if(k==="unlink"&&T>0)throw T+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let P={...N,$relation:e.$relation,$op:k,[L]:Q.$bzId,$bzId:e.$bzId,[Symbol.for("dbId")]:S.defaultDBConnector.id,[Symbol.for("parent")]:e[Symbol.for("parent")],[Symbol.for("path")]:e[Symbol.for("path")],[Symbol.for("info")]:"updating roleFields",[Symbol.for("edgeType")]:"roleField on L/U/R"};n(P);});});}}}}}),[l,d]};if(!r)throw new Error("Undefined filledBqlRequest");let [u,p]=i(r),s=u.reduce((f,l)=>{if(!l.$bzId)return [...f,l];let d=f.findIndex(o=>o.$bzId===l.$bzId);if(d===-1)return [...f,l];if(f[d].$op==="create"&&l.$op==="match")return f;if(f[d].$op==="match"&&(l.$op==="create"||l.$op==="match"))return [...f.slice(0,d),l,...f.slice(d+1)];throw new Error(`Unsupported operation combination for $tempId "${l.$tempId}". Existing: ${f[d].$op}. Current: ${l.$op}`)},[]),B=p.reduce((f,l)=>{let d=f.find(o=>(o.$id&&o.$id===l.$id||o.$bzId&&o.$bzId===l.$bzId)&&o.$relation===l.$relation&&o.$op===l.$op);if(d){let o={...d};return Object.keys(l).forEach(n=>{if(typeof n=="symbol"||n.startsWith("$"))return;let y=d[n],h=l[n];Array.isArray(y)&&Array.isArray(h)?o[n]=Array.from(new Set([...y,...h])):!Array.isArray(y)&&Array.isArray(h)?y!==void 0?o[n]=Array.from(new Set([y,...h])):o[n]=h:Array.isArray(y)&&!Array.isArray(h)?h!==void 0&&(o[n]=Array.from(new Set([...y,h]))):y||(o[n]=h);}),[...f.filter(n=>!((n.$id&&n.$id===l.$id||n.$bzId&&n.$bzId===l.$bzId)&&n.$relation===l.$relation&&n.$op===l.$op)),o]}return [...f,l]},[]);[...new Set(B.map(f=>f.$relation))];a.bqlRequest={mutation:{things:s,edges:B}};};var Nt=async a=>{let{filledBqlRequest:r}=a,i=(m=>{let w=!1;return objectTraversal.traverse(m,({value:f})=>f.$op==="replace"?(w=!0,!1):!0),w})(r),p=(m=>{if(Array.isArray(m)){let w=[],f=null,l=null;if(objectTraversal.traverse(m,({value:o,key:t,meta:n})=>{n.depth===2&&(t==="$relation"?f=o:t==="$entity"?l=o:t==="$id"&&typeof o=="string"&&w.push(o));}),!f&&!l)throw new Error("Neither $relation nor $entity found in the blocks");let d={$id:w};return f&&(d.$relation=f),l&&(d.$entity=l),d}return m})(r),s=await nt(p,a.config,a.schema,a.dbHandles);if((m=>immer.produce(m,w=>{objectTraversal.traverse(w,({value:f,key:l,parent:d})=>{if(radash.isObject(f)&&f.$op==="link"&&d&&d[l].$op==="link"&&!Array.isArray(s)&&s&&s[l]&&!parseInt(l)&&s[l].$op!=="link")throw new Error(`You already have ${l} filled for this.`)});}))(r),i){let w=(f=>immer.produce(f,l=>objectTraversal.traverse(l,({value:d,key:o,parent:t})=>{if(o&&!o?.includes("$")&&(Array.isArray(d)||radash.isObject(d))){let n=Array.isArray(d)?d:[d],y={};n.forEach(F=>{F.$op==="replace"&&(F.$op="link"),F.$entity?y.$entity=F.$entity:F.$relation&&(y.$relation=F.$relation);});let h=[],e=Array.isArray(s)?s.find(F=>F.$id===t.$id):s,S=e?e[o]:null;Array.isArray(S)?h=S.map(F=>typeof F=="object"?F.$id:F):typeof S=="string"&&(h=[S]),h.forEach(F=>{let M=S[0].$op==="replace"?null:n.find(I=>I.$id===F&&I.$op==="link");if(!M&&!n.some(I=>I.$id===F)){let I={...y,$op:"unlink",$id:F,$bzId:`T_${uuid.v4()}`};Array.isArray(d)?d.push(I):t[o]=[d,I];}else if(M){let I=n.findIndex(A=>A.$id===F&&A.$op==="link");I>-1&&n.splice(I,1);}});}})))(r);a.filledBqlRequest=w;}};var Dt=async(a,r)=>{let{dbHandles:c,tqlRequest:i,bqlRequest:u,config:p}=a;if(!i)throw new Error("TQL request not built");if(!(i.deletions&&i.deletionMatches||i.insertions))throw new Error("TQL request error, no things");if(!u?.mutation)throw new Error("BQL mutation not parsed");let s=p.dbConnectors[0].id,B=c.typeDB.get(s)?.session;if(!B)throw new Error("Session not found");if(!B.isOpen())throw new Error("Session is closed");let m=await B.transaction(typedbClient.TransactionType.WRITE);if(!m)throw new Error("Can't create transaction");let w=i.deletionMatches&&i.deletions&&`match ${i.deletionMatches} delete ${i.deletions}`,f=i.insertions&&`${i.insertionMatches?`match ${i.insertionMatches}`:""} insert ${i.insertions}`;w&&m.query.delete(w);let l=f&&m.query.insert(f);try{let d=l?await l.collect():void 0;await m.commit(),await m.close(),r.rawTqlRes={insertions:d};}catch(d){throw await m.close(),new Error(`Transaction failed: ${d.message}`)}};var xt={query:[Mt,Y,X,H,lt],mutation:[qt,Nt,kt,Qt,Dt,H]},Ie=[Tt],it=async(a,r,c={},i=!0)=>{for(let u of a){let p=await u(r,c);if(p&&Array.isArray(p))for(let s of p)await it(s.pipeline,s.req,s.res,!1);}return i?(await it(Ie,r,c,!1),r.config.query?.debugger===!0&&typeof c.bqlRes=="object"?{...c.bqlRes,$debugger:{tqlRequest:r.tqlRequest}}:c.bqlRes):c.bqlRes},nt=(a,r,c,i)=>it(xt.query,{config:r,schema:c,rawBqlRequest:a,dbHandles:i},{}),jt=(a,r,c,i)=>it(xt.mutation,{config:r,schema:c,rawBqlRequest:a,dbHandles:i},{});var ft=class{schema;config;dbHandles;constructor({schema:r,config:c}){this.schema=r,this.config=c;}init=async()=>{let r={typeDB:new Map},c=bt(this.schema);await Promise.all(this.config.dbConnectors.map(async i=>{if(i.provider==="typeDB"&&i.dbName){let[u,p]=await radash.tryit(typedbClient.TypeDB.coreClient)(i.url);if(u){let s=`[BORM:${i.provider}:${i.dbName}] ${u.message??"Can't create TypeDB Client"}`;throw new Error(s)}try{let s=await p.session(i.dbName,typedbClient.SessionType.DATA);r.typeDB.set(i.id,{client:p,session:s});}catch(s){let B=`[BORM:${i.provider}:${i.dbName}] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(B)}}if(i.provider==="typeDBCluster"&&i.dbName){let[u,p]=await radash.tryit(typedbClient.TypeDB.clusterClient)(i.addresses,i.credentials);if(u){let s=`[BORM:${i.provider}:${i.dbName}] ${u.message??"Can't create TypeDB Cluster Client"}`;throw new Error(s)}try{let s=await p.session(i.dbName,typedbClient.SessionType.DATA);r.typeDB.set(i.id,{client:p,session:s});}catch(s){let B=`[BORM:${i.provider}:${i.dbName}] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(B)}}})),this.schema=c,this.dbHandles=r;};#t=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#t(),this.schema);define=async()=>(await this.#t(),ht(this.config,this.schema,this.dbHandles));query=async(r,c)=>{await this.#t();let i={...this.config,query:{...ot.query,...this.config.query,...c}};return nt(r,i,this.schema,this.dbHandles)};mutate=async(r,c)=>{await this.#t();let i={...this.config,mutation:{...ot.mutation,...this.config.mutation,...c}};return jt(r,i,this.schema,this.dbHandles)};close=async()=>{this.dbHandles&&this.dbHandles.typeDB.forEach(async({client:r,session:c})=>{console.log("Closing session"),await c.close(),console.log("Closing client"),await r.close();});}},Ri=ft;//! reads all the insertions and gets the first match. This means each id must be unique
35
37
  //! disabled as it has false positives
36
38
 
37
- export { ui as default };
39
+ module.exports = Ri;
package/dist/index.mjs ADDED
@@ -0,0 +1,37 @@
1
+ import { tryit, mapEntries, isArray, isString, listify, flat, shake, isObject, unique, pick } from 'radash';
2
+ import { TypeDB, SessionType, TransactionType } from 'typedb-client';
3
+ import { produce, current } from 'immer';
4
+ import { traverse, getNodeByPath } from 'object-traversal';
5
+ import { v4 } from 'uuid';
6
+
7
+ var ot={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1},mutation:{}};var Ht=a=>{let r=[],c=new Map;return a.forEach(i=>{let{dbPath:u,contentType:p}=i,s=`${u}-${p}`;c.has(s)||(c.set(s,!0),r.push(i));}),r},ht=async(a,r,c)=>{let u=(()=>{let y="",h=[];y+=`
8
+ `,Object.keys(r.entities).forEach(F=>{let M=r.entities[F],{idFields:I,dataFields:A,linkFields:R,name:q}=M,g=[],O=[],N=[];if(M.extends){let L=r.entities[M.extends];L.dataFields&&L.dataFields.forEach(E=>{g.push(E.dbPath);}),L.linkFields&&L.linkFields.forEach(E=>{O.push(E.path);}),L.idFields&&L.idFields.forEach(E=>{N.push(E);});}y+=`${q} sub ${M.extends?M.extends:"entity"},
9
+ `;let T=[];if(I&&I.length>0){let L=new Set(I),b=Array.from(L).map($=>`${$}`).join(", ");N.includes(b)||(y+=` owns ${b} @key,
10
+ `,T.push(b));}if(A&&A.length>0&&A.forEach(L=>{!g.includes(L.dbPath)&&!T.includes(L.dbPath)&&(y+=` owns ${L.dbPath},
11
+ `),h.push({dbPath:L.dbPath,contentType:L.contentType});}),R&&R.length>0){let L=[];R.forEach(E=>{let{relation:b,plays:$}=E;!O.includes(E.path)&&!L.includes(`${b}:${$}`)&&(y+=` plays ${b}:${$},
12
+ `,L.push(`${b}:${$}`));});}y=y.replace(/,\s*$/,`;
13
+ `),y+=`
14
+ `;}),Object.keys(r.relations).forEach(F=>{let M=r.relations[F],{idFields:I,dataFields:A,roles:R,name:q,linkFields:g}=M,O=[],N=[],T=[],L=[];if(M.extends){let b=r.relations[M.extends];b.dataFields&&b.dataFields.forEach($=>{O.push($.dbPath);}),b.linkFields&&b.linkFields.forEach($=>{N.push($.dbPath);}),b.roles&&Object.values(b.roles).forEach(Q=>{T.push(Q.name);}),b.idFields&&b.idFields.forEach($=>{L.push($);});}y+=`${q} sub ${M.extends?M.extends:"relation"},
15
+ `;let E=[];if(I&&I.length>0){let b=new Set(I),Q=Array.from(b).map(k=>`${k}`).join(", ");L.includes(Q)||(y+=` owns ${Q} @key,
16
+ `,E.push(Q));}if(A&&A.length>0&&A.forEach(b=>{!O.includes(b.dbPath)&&!E.includes(b.dbPath)&&(y+=` owns ${b.dbPath},
17
+ `),h.push({dbPath:b.dbPath,contentType:b.contentType});}),R&&Object.keys(R).forEach(b=>{T.includes(b)||(y+=` relates ${b},
18
+ `);}),g&&g.length>0){let b=[];g.forEach($=>{let{plays:Q}=$;!N.includes($.path)&&!b.includes(`${M}:${Q}`)&&(y+=` plays ${$.relation}:${Q},
19
+ `,b.push(`${M}:${Q}`));});}y=y.replace(/,\s*$/,`;
20
+ `),y+=`
21
+ `;});let e=`define
22
+
23
+ `;return Ht(h).forEach(F=>{e+=`${F.dbPath} sub attribute,
24
+ `,F.contentType==="TEXT"||F.contentType==="ID"?e+=` value string;
25
+ `:F.contentType==="EMAIL"?(e+=` value string,
26
+ `,e+=` regex '^(?=.{1,64}@)[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*@[^-][A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$';
27
+ `):F.contentType==="DATE"?e+=` value datetime;
28
+ `:F.contentType==="BOOLEAN"?e+=` value boolean;
29
+ `:F.contentType==="NUMBER"&&(e+=` value long;
30
+ `);}),`${e}
31
+
32
+ ${y}`})(),p=a.dbConnectors[0].id,s=c.typeDB.get(p)?.session,B=c.typeDB.get(p)?.client;if(!s){console.log("Session Status: ","NO SESSION");return}s.close();let[{dbName:m}]=a.dbConnectors;await(await B.databases.get(m)).delete(),await B.databases.create(m);let f=await B.session(a.dbConnectors[0].dbName,SessionType.SCHEMA),l=await f.transaction(TransactionType.WRITE);await l.query.define(u),await l.commit(),await l.close();let d=await f.transaction(TransactionType.READ),o="match $a sub thing;";(await(await d.query.match(o)).collect()).forEach(async y=>{y.get("a");}),await d.close();};var $t=(a,r,c)=>c?r:`${a}\xB7${r}`,gt=a=>{let r=a.split("\xB7");return r[r.length-1]},J=(a,r)=>Object.values(Object.fromEntries(Object.entries(a).filter(([c,i])=>r(c,i))))[0],_=(a,r)=>Object.fromEntries(Object.entries(a).filter(([c,i])=>r(c,i))),bt=a=>{let r=[],c=produce(a,u=>traverse(u,({key:p,value:s,meta:B})=>{if(B.depth===2&&(p&&(s.dataFields=s.dataFields?.map(m=>({...m,dbPath:$t(p,m.path,m.shared)}))),s.extends)){let m=u.entities[s.extends]||u.relations[s.extends];if(s.allExtends=[s.extends,...m.allExtends||[]],s.idFields=m.idFields?(s.idFields||[]).concat(m.idFields):s.idFields,s.dataFields=m.dataFields?(s.dataFields||[]).concat(m.dataFields.map(w=>{let f=s.extends,l=a.entities[f]||a.relations[f];for(;!l.dataFields?.find(d=>d.path===w.path);)f=l.extends,l=a.entities[f]||a.relations[f];return {...w,dbPath:$t(f,w.path,w.shared)}})):s.dataFields,s.linkFields=m.linkFields?(s.linkFields||[]).concat(m.linkFields):s.linkFields,"roles"in m){let w=s,f=m;w.roles=w.roles||{},w.roles={...w.roles,...f.roles},Object.keys(w.roles).length===0&&(w.roles={});}}},{traversalType:"breadth-first"}));return traverse(a,({key:u,value:p,meta:s})=>{if(u==="linkFields"){let m=(()=>{if(!s.nodePath)throw new Error("No path");let[f,l]=s.nodePath.split(".");return {thing:l,thingType:f==="entities"?"entity":f==="relations"?"relation":""}})(),w=Array.isArray(p)?p.map(f=>({...f,...m})):[{...p,...m}];r.push(...w);}}),produce(c,u=>traverse(u,({value:p,key:s,meta:B})=>{if(B.depth===2&&p.idFields&&!p.id){p.name=s;let m=()=>{if(B.nodePath?.split(".")[0]==="entities")return "entity";if(B.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};p.thingType=m(),p.computedFields=[],p.virtualFields=[],"roles"in p&&Object.entries(p.roles).forEach(([f,l])=>{l.playedBy=r.filter(d=>d.relation===s&&d.plays===f)||[],l.name=f;}),"linkFields"in p&&p.linkFields&&p.linkFields?.forEach(f=>{if(f.target==="relation"){f.oppositeLinkFieldsPlayedBy=[{plays:f.path,thing:f.relation,thingType:"relation"}];return}let l=r.filter(o=>o.relation===f.relation&&o.plays!==f.plays)||[];f.oppositeLinkFieldsPlayedBy=l;let{filter:d}=f;f.oppositeLinkFieldsPlayedBy=f.oppositeLinkFieldsPlayedBy.filter(o=>o.target==="role"),d&&Array.isArray(d)&&(f.oppositeLinkFieldsPlayedBy=f.oppositeLinkFieldsPlayedBy.filter(o=>d.some(t=>o.thing===t.$role)),f.oppositeLinkFieldsPlayedBy=f.oppositeLinkFieldsPlayedBy.filter(o=>d.some(t=>o.thing===t.$thing))),d&&!Array.isArray(d)&&(f.oppositeLinkFieldsPlayedBy=f.oppositeLinkFieldsPlayedBy.filter(o=>o.$role===d.$role),f.oppositeLinkFieldsPlayedBy=f.oppositeLinkFieldsPlayedBy.filter(o=>o.thing===d.$thing));});}if(typeof p=="object"&&"playedBy"in p){if([...new Set(p.playedBy?.map(m=>m.thing))].length>1)throw new Error(`Unsupported: roleFields can be only played by one thing. Role: ${s} path:${B.nodePath}`);if(p.playedBy.length===0)throw new Error(`Unsupported: roleFields should be played at least by one thing. Role: ${s}, path:${B.nodePath}`)}if(B.depth===4&&(p.default||p.computedValue)){let[m,w]=B.nodePath?.split(".")||[];p.isVirtual?u[m][w].virtualFields.push(p.path):u[m][w].computedFields.push(p.path);}}))},x=(a,r)=>{if(r.$entity){if(!(r.$entity in a.entities))throw new Error(`Missing entity '${r.$entity}' in the schema`);return a.entities[r.$entity]}if(r.$relation){if(!(r.$relation in a.relations))throw new Error(`Missing relation '${r.$relation}' in the schema`);return a.relations[r.$relation]}throw new Error(`Wrong schema or query for ${JSON.stringify(r)}`)},j=(a,r)=>{let c=a.dataFields?.map(t=>t.path)||[],i=a.linkFields?.map(t=>t.path)||[],u="roles"in a?listify(a.roles,t=>t):[],p=[...c||[],...i||[],...u||[]],B=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields"],...p];if(!r)return {fields:p,dataFields:c,roleFields:u,linkFields:i};let m=r.$fields?r.$fields.map(t=>{if(typeof t=="string")return t;if("$path"in t&&typeof t.$path=="string")return t.$path;throw new Error(" Wrongly structured query")}):listify(r,t=>t),w=r.$filter?listify(r.$filter,t=>t.toString().startsWith("$")?void 0:t.toString()).filter(t=>t&&c?.includes(t)):[],f=r.$filter?listify(r.$filter,t=>t.toString().startsWith("$")?void 0:t.toString()).filter(t=>t&&[...u||[],...i||[]].includes(t)):[],l=[...m,...w].filter(t=>!B.includes(t)).filter(t=>t),d=r.$filter?_(r.$filter,(t,n)=>w.includes(t)):{},o=r.$filter?_(r.$filter,(t,n)=>f.includes(t)):{};return {fields:p,dataFields:c,roleFields:u,linkFields:i,usedFields:m,usedLinkFields:i.filter(t=>m.includes(t)),usedRoleFields:u.filter(t=>m.includes(t)),unidentifiedFields:l,...w.length?{localFilters:d}:{},...f.length?{nestedFilters:o}:{}}},wt=(a,r)=>{let c=r.$localFilters&&listify(r.$localFilters,(u,p)=>`has ${a.dataFields?.find(B=>B.path===u)?.dbPath} '${p}'`);return c?.length?`, ${c.join(",")}`:""},W=a=>a!==null,K=(a,r)=>Object.values(a).reduce((c,i)=>(i.extends===r&&c.push(i.name),c),[]);var te=(a,r)=>a.map(i=>{let u=[...i.conceptMaps],s=i.owner.asThing().type.label.name,B=r.entities[s]?r.entities[s]:r.relations[s];if(!B.idFields)throw new Error(`No idFields defined for ${s}`);let m=r.entities[s]?"entity":"relation",w=u.map(l=>{let d=l.get("attribute")?.asAttribute();return d?[gt(d.type.label.name),d.value]:[]}),f=Object.fromEntries(w);return {...f,[`$${m}`]:s,$id:f[B.idFields[0]]}}),ee=(a,r,c)=>a.flatMap(u=>u.conceptMaps.map(s=>{let B=new Map;return r.forEach(m=>{let w=s.get(`${m}_id`)?.asAttribute().value.toString(),f=s.get(m),l=f?.isEntity()?f.asEntity().type.label.name:f?.asRelation().type.label.name,o={id:w,entityName:(()=>l?(c.entities[l]??c.relations[l]).allExtends?.includes(m)?m:l:m)()};w&&B.set(m,o);}),B})),ne=(a,r,c)=>a.flatMap(u=>u.conceptMaps.map(s=>{let B=s.get(`${r}_id`)?.asAttribute().value.toString(),m=s.get(`${c}_id`)?.asAttribute().value.toString();return {ownerId:B,path:c,roleId:m}})),ie=(a,r)=>{let c=listify(a.roles,(i,u)=>{if([...new Set(u.playedBy?.map(B=>B.thing))].length!==1)throw new Error("a role can be played by two entities throws the same relation");if(!u.playedBy)throw new Error("Role not being played by nobody");let p=u.playedBy[0].plays,s=K(r.entities,p);return [p,...s]});return unique(flat(c))},H=async(a,r)=>{let{schema:c,bqlRequest:i,config:u,tqlRequest:p}=a,{rawTqlRes:s}=r;if(i){if(!s)throw new Error("TQL query not executed")}else throw new Error("BQL request not parsed");let{query:B}=i;if(!B){if(s.insertions?.length===0&&!p?.deletions){r.bqlRes={};return}let{mutation:d}=i;if(!d)throw new Error("TQL mutation not executed");let t=[...d.things,...d.edges].map(n=>{let y=s.insertions?.find(h=>h.get(`${n.$bzId}`))?.get(`${n.$bzId}`);if(n.$op==="create"||n.$op==="update"||n.$op==="link"){if(!y?.asThing().iid)throw new Error(`Thing not received on mutation: ${JSON.stringify(n)}. Probably the relation had all its edges deleted instead of replaced`);let h=y?.asThing().iid;return u.mutation?.noMetadata?mapEntries(n,(e,S)=>[e.toString().startsWith("$")?Symbol.for(e):e,S]):{$dbId:h,...n,[n.path]:n.$id}}if(n.$op==="delete"||n.$op==="unlink")return n;if(n.$op!=="match")throw new Error(`Unsupported op ${n.$op}`)}).filter(n=>n);r.bqlRes=t;return}if(!s.entity)throw new Error("TQL query not executed");let m=te(s.entity,c),w=s.relations?.map(d=>{let o=c.relations[d.relation],t=ie(o,c),n=ee(d.conceptMapGroups,[...t,o.name],c);return {name:d.relation,links:n}}),f=s.roles?.map(d=>({name:d.ownerPath,links:ne(d.conceptMapGroups,d.ownerPath,d.path)})),l=r.cache||{entities:new Map,relations:new Map,roleLinks:new Map};m.forEach(d=>{let o=d.$entity||d.$relation,t=d.$id,n=l.entities.get(o)||new Map;n.set(t,{...d,$show:!0}),l.entities.set(o,n);}),w?.forEach(d=>{let o=d.name,t=l.relations.get(o)||[];t.push(...d.links),l.relations.set(o,t),d.links.forEach(n=>{[...n.entries()].forEach(([y,{entityName:h,id:e}])=>{let S=l.entities.get(h)||new Map,M={[c.entities[h]?.thingType||c.relations[h].thingType]:h,$id:e,...S.get(e)};S.set(e,M),l.entities.set(h,S);});});}),f?.forEach(d=>{let o=c.relations[d.name]||c.entities[d.name];d.links.forEach(t=>{let n=l.roleLinks.get(t.ownerId)||{},y=n[t.path];y?isArray(y)?y.push(t.roleId):isString(y)&&y!==t.roleId&&(y=[y,t.roleId]):y=t.roleId,n[t.path]=y,l.roleLinks.set(t.ownerId,n),o.roles[t.path].playedBy?.forEach(h=>{let e=l.entities.get(h.thing)||new Map,S={$entity:h.thing,$id:t.roleId,...e.get(t.roleId)};e.set(t.roleId,S),l.entities.set(h.thing,e);});});}),r.cache=l;};var re=/((\/\/.*$)|(\/\*.*\*\/))/gm,oe=/(\s*async\s*|\s*function\s*)+/,se=/(?:function\s*[^(\s]*\s*|\s*=>\s*|^\s*)\(([^)]*)\)/,ae=/[ ,\n\r\t]+/,Bt=a=>{let r=a.toString().replace(re,"").replace(oe,"").trim(),c=se.exec(r);if(!c)return [];let i;for(let u of c.slice(1))if(u){i=u;break}return i?(i=i.replace(/\{\s*/g,"").replace(/\s*\}/g,""),i.split(ae).filter(u=>u.trim()!=="")):[]};var Z=({currentThing:a,fieldSchema:r,mandatoryDependencies:c=!1})=>{if(!r||!r.default||!r.default.value)throw new Error("Virtual field: No field schema found, or wrongly configured");let i=r.default.value,p=Bt(i).filter(B=>!(B in a));if(c&&p.length)throw new Error(`Virtual field: Missing arguments ${p.join(", ")}`);return "default"in r?r.default?.value(a):void 0};var ce=(a,r)=>a.length===1&&typeof a[0]!="string"&&a[0].$id===r?a[0]:a,Ft=a=>typeof a=="string"||!!a.$show,Rt=(a,r)=>produce(a,c=>traverse(c,({value:i})=>{if(Array.isArray(i)||typeof i!="object")return;i.$tempId&&(i.$tempId=`_:${i.$tempId}`),i.$fields&&delete i.$fields,i.$filter&&delete i.$filter,i.$show&&delete i.$show,i.$bzId&&delete i.$bzId,r.query?.noMetadata&&(i.$entity||i.$relation)&&(delete i.$entity,delete i.$relation,delete i.$id),Object.getOwnPropertySymbols(i).forEach(p=>{delete i[p];}),i.$excludedFields&&(i.$excludedFields.forEach(p=>{delete i[p];}),delete i.$excludedFields);})),at=(a,r,c,i)=>a.map(([u,p])=>{if(!r||!r.includes(u))return null;if(!c.$fields||c.$fields.includes(i))return u;let s=c.$fields.find(B=>isObject(B)&&B.$path===i);if(s){let B={..._(p,(w,f)=>w.startsWith("$"))},m=s.$fields?{...B,$fields:s.$fields}:B;if(s.$id){if(Array.isArray(s.$id))return s.$id.includes(u)?m:null;if(s.$id===u)return m}if(m.$fields&&m.$fields.includes("id")&&!m.$show){let w="";return m.$fields.forEach(f=>{f==="id"?w=m.$id:w=m;}),w}return m}return null}).filter(u=>u),de=(a,r)=>{let c={};return r.forEach(i=>{c[i.$bzId]=i.$id;}),a.forEach(i=>{Object.keys(i).forEach(u=>{c[i[u]]&&u!=="$tempId"&&(i[u]=c[i[u]]);});}),a},pe=(a,r)=>{let c=r.map(u=>u.$bzId),i=!1;return a.forEach(u=>{Object.keys(u).forEach(p=>{c.includes(u[p])&&(i=!0);});}),i},Tt=async(a,r)=>{let{bqlRequest:c,config:i,schema:u}=a,{cache:p}=r;if(!c)throw new Error("BQL request not parsed");let{query:s}=c;if(!s){let y=r.bqlRes[0]?r.bqlRes:[r.bqlRes],h=a.bqlRequest?.mutation?.things;if(pe(y,h)){let F=de(y,h);r.bqlRes=F[1]?F:F[0];}let S=Rt(r.bqlRes,i);r.bqlRes=S;return}if(!p)return;let B="$entity"in s?s.$entity:s.$relation,m=p.entities.get(B.name);if(!m){r.bqlRes=null;return}let f=listify(s.$filter,y=>y).some(y=>B.dataFields?.find(h=>h.path===y)?.validations?.unique),l=!Array.isArray(c.query)&&(c.query?.$id&&!Array.isArray(c.query?.$id)||f);if(Array.isArray(a.rawBqlRequest))throw new Error("Query arrays not implemented yet");let d=m,o=[...d].length?[...d].map(([y,h])=>({...a.rawBqlRequest,$id:y})):a.rawBqlRequest,t=produce(o,y=>traverse(y,({value:h})=>{let e=h;if(!e?.$entity&&!e?.$relation)return;let S="$entity"in e?e.$entity:e.$relation;if(S){let F=Array.isArray(e.$id)?e.$id:[e.$id],M="$relation"in e?u.relations[e.$relation]:u.entities[e.$entity],{dataFields:I,roleFields:A}=j(M),R=p.entities.get(S);if(!R)return;[...R].forEach(([g,O])=>{if(F.includes(g)){let N=e.$fields?e.$fields:I,{virtualFields:T}=M;T?.forEach($=>{if(N?.includes($)&&e[$]===void 0){let Q=M.dataFields?.find(P=>P.path===$),k=Z({currentThing:O,fieldSchema:Q});e[$]=k;}}),listify(O,($,Q)=>{$.startsWith("$")||N?.includes($)&&(e[$]=Q);});let L=p.roleLinks.get(g),E=e.$fields?e.$fields.filter($=>typeof $=="string"):A,b=e.$fields?.filter($=>typeof $=="object")?.map($=>$.$path)||[];Object.entries(L||{}).forEach(([$,Q])=>{if(![...E,...b].includes($))return;if(!("roles"in M))throw new Error("No roles in schema");let k=Array.isArray(Q)?[...new Set(Q)]:[Q],{cardinality:P,playedBy:z}=M.roles[$],C=[...new Set(z?.map(D=>D.thing))]?.flatMap(D=>{let rt=p.entities.get(D);return rt?at([...rt],k,e,$):[]});if(C?.length){if(C.length===1&&C[0]===e.$id)return;if(P==="ONE"){e[$]=C[0];return}e[$]=C.filter(D=>typeof D=="string"||typeof D=="object"&&D?.$show);}});}});let q=M.linkFields;q&&q.forEach(g=>{let O=p.relations.get(g.relation),N=g.oppositeLinkFieldsPlayedBy;if(!O)return null;if(g.target==="relation"){let T=[...O].reduce((L,E)=>{let b=E.get(g.plays)?.id;if(b&&b===F[0]){let $=E.get(g.relation);if(!$)return L;L[$.entityName]||(L[$.entityName]=new Set),L[$.entityName].add($.id);}return L},{});return Object.entries(T).map(([L,E])=>{let b=p.entities.get(L);if(!b)return null;let $=at([...b],[...E.values()],e,g.path).filter(W).filter(Ft);if($.length===0)return null;if($&&$.length){if(g.cardinality==="ONE")return e[g.path]=$[0],null;e[g.path]=$;}return null}),null}return g.target==="role"&&N.forEach(T=>{if(!O)return;let L=[...O].reduce((E,b)=>{let $=b.get(g.plays)?.id;if($&&$===F[0]){let Q=b.get(T.plays);if(!Q)return E;E[Q.entityName]||(E[Q.entityName]=new Set),E[Q.entityName].add(Q.id);}return E},{});Object.entries(L).forEach(([E,b])=>{let $=p.entities.get(E);if(!$)return;let Q=at([...$],[...b.values()],e,g.path).filter(W).filter(Ft);if(Q.length!==0&&Q&&Q.length){if(g.cardinality==="ONE"){e[g.path]=Q[0];return}e[g.path]=Q;let k={},P=G=>(G.$path===g.path&&(k=G),G?.$fields?.forEach(P)),z="";s.$fields?.forEach(P),k&&(Array.isArray(k.$id)||(z=k.$id)),e[g.path]=ce(Q,z);}});}),null});}})),n=Rt(t,i);r.bqlRes=l?n[0]:n;};var Y=async a=>{let{schema:r,bqlRequest:c}=a;if(!c?.query)throw new Error("BQL query not parsed");let{query:i}=c,u="$entity"in i?i.$entity:i.$relation,p=u.defaultDBConnector.path||u.name;if(!p)throw new Error(`No thing path in ${JSON.stringify(u)}`);if(!u.idFields)throw new Error("No id fields");let[s]=u.idFields,B=`$${p}_id`,m=`, has ${s} ${B};`;i.$id&&(Array.isArray(i.$id)?m+=` ${B} like "${i.$id.join("|")}";`:m+=` ${B} "${i.$id}";`);let w=wt(u,i),f="roles"in u?listify(u.roles,(t,n)=>({path:t,var:`$${t}`,schema:n})):[],l=`match $${p} isa ${p}, has attribute $attribute ${w} ${m} group $${p};`,d=f.map(t=>{if(!t.schema.playedBy||[...new Set(t.schema.playedBy?.map(y=>y.thing))].length!==1)throw new Error("Unsupported: Role played by multiple linkfields or none");let n=t.schema.playedBy[0].thing;return {path:t.path,owner:p,request:`match $${p} (${t.path}: ${t.var} ) isa ${p} ${m} ${t.var} isa ${n}, has id ${t.var}_id; group $${p};`}}),o=u.linkFields?.flatMap(t=>{let n=`$${t.plays}_id`,y=`, has ${s} ${n};`;i.$id&&(Array.isArray(i.$id)?y+=` ${n} like "${i.$id.join("|")}";`:y+=` ${n} "${i.$id}";`);let h=`match $${t.plays} isa ${p}${w} ${y}`,e=t.target==="relation",F=`$${t.relation}`,M=`${e?F:""} (${t.plays}: $${t.plays}`,I=t.oppositeLinkFieldsPlayedBy.map(T=>e?null:`${T.plays}: $${T.plays}`),A=[M,...I].filter(T=>T).join(",");if(r.relations[t.relation]===void 0)throw new Error(`Relation ${t.relation} not found in schema`);let R=r.relations[t.relation].defaultDBConnector.path||t.relation,q=`) isa ${R};`,g=t.oppositeLinkFieldsPlayedBy.map(T=>`$${e?T.thing:T.plays} isa ${T.thing}, has id $${e?T.thing:T.plays}_id;`).join(" "),O=`group $${t.plays};`,N=`${h} ${A} ${q} ${g} ${O}`;return {relation:R,entity:p,request:N}});a.tqlRequest={entity:l,...d?.length?{roles:d}:{},...o?.length?{relations:o}:{}};};var Mt=async a=>{let{rawBqlRequest:r,schema:c}=a;if(!("$entity"in r)&&!("$relation"in r))throw new Error("No entity specified in query");let i=x(c,r);if(!i)throw new Error(`Thing '${r}' not found in schema`);let{unidentifiedFields:u,localFilters:p,nestedFilters:s}=j(i,r);if(u&&u.length>0)throw new Error(`Unknown fields: [${u.join(",")}] in ${JSON.stringify(r)}`);a.bqlRequest={query:{...a.rawBqlRequest,...i.thingType==="entity"?{$entity:i}:{},...i.thingType==="relation"?{$relation:i}:{},...p?{$localFilters:p}:{},...s?{$nestedFilters:s}:{}}};};var X=async(a,r)=>{let{dbHandles:c,bqlRequest:i,tqlRequest:u,config:p}=a;if(!i)throw new Error("BQL request not parsed");if(!u)throw new Error("TQL request not built");if(!u.entity)throw new Error("BQL request error, no entities");let{query:s}=i;if(!s)throw new Error("BQL request is not a query");let B=p.dbConnectors[0].id,m=c.typeDB.get(B)?.session;if(!m?.isOpen())throw new Error("Session is closed");let w=await m.transaction(TransactionType.READ);if(!w)throw new Error("Can't create transaction");let f=w.query.matchGroup(u.entity),l=u.roles?.map(y=>({...y,stream:w.query.matchGroup(y.request)})),d=u.relations?.map(y=>({...y,stream:w.query.matchGroup(y.request)})),o=await f.collect(),t=await Promise.all(l?.map(async y=>({path:y.path,ownerPath:y.owner,conceptMapGroups:await y.stream.collect()}))||[]),n=await Promise.all(d?.map(async y=>({relation:y.relation,entity:y.entity,conceptMapGroups:await y.stream.collect()}))||[]);await w.close(),r.rawTqlRes={entity:o,...t?.length&&{roles:t},...n?.length&&{relations:n}};};var lt=async(a,r)=>{let{bqlRequest:c,schema:i}=a,{cache:u}=r;if(!c)throw new Error("BQL request not parsed");if(!u)throw new Error("Cache not initialized");let{query:p}=c;if(!p)return;let{$fields:s}=p;if(!("$entity"in p)&&!("$relation"in p))throw new Error("Node attributes not supported");let B="$entity"in p?p.$entity:p.$relation;if(!s||!Array.isArray(s))return;let m=s.filter(o=>typeof o!="string"&&o.$path),w=B.linkFields?.filter(o=>m.findIndex(t=>t.$path===o.path)!==-1).flatMap(o=>o.oppositeLinkFieldsPlayedBy)||[],f="roles"in B?listify(B.roles,(o,t)=>m.findIndex(n=>n.$path===o)!==-1?t:null).flatMap(o=>o?.playedBy).filter(o=>o):[],d=[...w,...f]?.map(o=>{if(!o)return null;let{thing:t}=o,n=K(i.entities,t);return [t,...n].map(y=>{let h=u.entities.get(y);if(!h)return null;let e=Array.from(h.values()).reduce((g,O)=>("$show"in O||g.push(O.$id),g),[]);if(e.length===0)return null;let S=i.entities[y]?{...i.entities[y],thingType:"entity"}:{...i.relations[y],thingType:"relation"},F=s.find(g=>typeof g=="object"&&g.$path===o.plays),M=F?.$id,I=M?Array.isArray(M)?M:[M]:[],A=F?.$filter,q={query:{$id:I.length?I.filter(g=>e.includes(g)):e,$fields:F?.$fields,...S.thingType==="entity"?{$entity:S}:{},...S.thingType==="relation"?{$relation:S}:{},...A?{$localFilters:A}:{}}};return {req:{...a,bqlRequest:q},res:r,pipeline:[Y,X,H,lt]}}).filter(W)}).filter(W);if(d?.length)return flat(d)};var Qt=async a=>{let{bqlRequest:r,schema:c}=a;if(!r)throw new Error("BQL request not parsed");let{mutation:i}=r;if(!i)throw new Error("BQL request is not a mutation");let u=o=>{let t=o.$op,n=`$${o.$bzId}`,y=x(c,o),{idFields:h,defaultDBConnector:e}=y,S=e?.path||o.$entity||o.$relation,F=o.$id,M=h?.[0],I=listify(o,(E,b)=>{if(E.startsWith("$")||E===M||!b)return "";let $=y.dataFields?.find(P=>P.path===E);if(!$?.path)return "";let k=$.dbPath;if(["TEXT","ID","EMAIL"].includes($.contentType))return `has ${k} '${b}'`;if(["NUMBER"].includes($.contentType))return `has ${k} ${b}`;if($.contentType==="DATE"){if(Number.isNaN(b.valueOf()))throw new Error("Invalid format, Nan Date");return b instanceof Date?`has ${k} ${b.toISOString().replace("Z","")}`:`has ${k} ${new Date(b).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${$.contentType}`)}).filter(E=>E),A=`${n}-atts`,R=listify(o,(E,b)=>{if(E.startsWith("$")||E===M||!b)return "";let $=y.dataFields?.find(P=>P.path===E);if(!$?.path)return "";let k=$.dbPath;return `{${A} isa ${k};}`}).filter(E=>E),q=o[Symbol.for("isLocalId")],g=isArray(F)?`like '${F.join("|")}'`:`'${F}'`,O=!q&&F?[`has ${M} ${g}`]:[],N=[...O,...I].filter(E=>E).join(","),T=()=>{if(t==="delete"||t==="unlink"||t==="match")return `${n} isa ${[S,...O].filter(E=>E).join(",")};`;if(t==="update"){if(!R.length)throw new Error("update without attributes");return `${n} isa ${[S,...O].filter(E=>E).join(",")}, has ${A};
33
+ ${R.join(" or ")};
34
+ `}return ""},L=()=>t==="update"||t==="link"||t==="match"?`${n} isa ${[S,...O].filter(E=>E).join(",")};`:"";if(o.$entity||o.$relation)return {op:t,deletionMatch:T(),insertionMatch:L(),insertion:t==="create"?`${n} isa ${[S,N].filter(E=>E).join(",")};`:t==="update"&&I.length?`${n} ${I.join(",")};`:"",deletion:t==="delete"?`${n} isa ${S};`:t==="update"&&R.length?`${n} has ${A};`:""};throw new Error("in attributes")},p=o=>{let t=o.$op,n=x(c,o),y=`$${o.$bzId}`,h=o.$id,e=n.defaultDBConnector?.path||o.$relation,S="roles"in n?listify(n.roles,L=>L):[],F=o.$relation&&"roles"in n&&mapEntries(n.roles,(L,E)=>[L,E.dbConnector?.path||L]),M=listify(o,(L,E)=>{if(!S.includes(L))return null;if(!("roles"in n))throw new Error("This should have roles! ");let b=F[L];return Array.isArray(E)?E.map($=>({path:b,id:$})):{path:b,id:E}}).filter(L=>L).flat(),I=M.map(L=>{if(!L?.path)throw new Error("Object without path");return `${L.path}: $${L.id}`}),A=M.length>0?`( ${I.join(" , ")} )`:"",R=A?`${y} ${A} ${o[Symbol.for("edgeType")]==="linkField"||t==="delete"||t==="unlink"?`isa ${e}`:""}`:"",q=`${y} ${o[Symbol.for("edgeType")]==="linkField"||t==="delete"?`isa ${e}`:""}`,g=()=>R?t==="link"?`${R};`:t==="create"?`${R}, has id '${h}';`:"":"",O=()=>R&&t==="match"?`${R};`:"",N=()=>R?t==="delete"?`${R};`:t==="match"?`${R};`:"":"",T=()=>R?t==="delete"?`${q};`:t==="unlink"?`${y} ${A};`:"":"";return {deletionMatch:N(),insertionMatch:O(),deletion:T(),insertion:g(),op:""}},s=(o,t)=>{let n=t==="edges"?p:u;if(Array.isArray(o))return o.map(M=>{let{preDeletionBatch:I,insertionMatch:A,deletionMatch:R,insertion:q,deletion:g}=n(M);return shake({preDeletionBatch:I,insertionMatch:A,deletionMatch:R,insertion:q,deletion:g},O=>!O)}).filter(M=>M);let{preDeletionBatch:y,insertionMatch:h,deletionMatch:e,insertion:S,deletion:F}=n(o);return shake({preDeletionBatch:y,insertionMatch:h,deletionMatch:e,insertion:S,deletion:F},M=>!M)},B=s(i.things),m=Array.isArray(B)?B:[B],w=s(i.edges,"edges"),f=Array.isArray(w)?w:[w],l=[...m,...f],d=shake({insertionMatches:l.map(o=>o.insertionMatch).join(" ").trim(),deletionMatches:l.map(o=>o.deletionMatch).join(" ").trim(),insertions:l.map(o=>o.insertion).join(" ").trim(),deletions:l.map(o=>o.deletion).join(" ").trim()},o=>!o);a.tqlRequest=d;};var Fe=a=>{if(!a.startsWith("_:"))throw new Error("ID must start with '_:'.");let r=a.substring(2);if(!/^[a-zA-Z0-9-_]+$/.test(r))throw new Error("$tempId must contain only alphanumeric characters, hyphens, and underscores.");if(a.length>36)throw new Error("$tempId must not be longer than 36 characters.");return r},qt=async a=>{let{rawBqlRequest:r,schema:c}=a,u=(w=>produce(w,f=>traverse(f,({value:l,key:d,parent:o})=>{isObject(l)&&(l=shake(l,t=>t===void 0)),d==="$tempId"&&(o[d]=Fe(l));})))(r),s=(w=>produce(w,f=>traverse(f,({value:l,meta:d,key:o})=>{if(isObject(l)){if(l.$arrayOp)throw new Error("Array op not supported yet");if(o==="$filter"||d.nodePath?.includes(".$filter."))return;let t=l;if(t.$op==="create"&&t.$id)throw new Error("Can't write to computed field $id. Try writing to the id field directly.");let n=x(c,t),h=d.nodePath?.split(".")?.filter(R=>Number.isNaN(parseInt(R,10))).join(".");if(!n)throw new Error(`Schema not found for ${t.$entity||t.$relation}`);t.$bzId=t.$tempId??`T_${v4()}`,t[Symbol.for("schema")]=n,t[Symbol.for("dbId")]=n.defaultDBConnector.id;let{usedLinkFields:e,usedRoleFields:S}=j(n,t),F=e.map(R=>({fieldType:"linkField",path:R,schema:n.linkFields.find(q=>q.path===R)})),M=n.thingType==="relation"?S.map(R=>({fieldType:"roleField",path:R,schema:J(n.roles,q=>q===R)})):[];if(F.some(R=>R.schema?.target==="role")&&F.some(R=>R.schema?.target==="relation"))throw new Error("Unsupported: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.");let I=M.filter(R=>[...new Set(R.schema.playedBy?.map(q=>q.thing))].length!==1);if(I.length>1)throw new Error(`Field: ${I[0].path} - If a role can be played by multiple things, you must specify the thing in the mutation: ${JSON.stringify(I[0].schema.playedBy)}. Schema: ${JSON.stringify(I[0].schema)}`);let A=d.nodePath;if([...F,...M].forEach(R=>{let q=t[R.path];if(q===void 0)return;let g=R.schema;if(!g)throw new Error(`Field ${R.path} not found in schema`);let O=R.fieldType==="roleField"?g?.playedBy[0]:g,T=(()=>g&&"relation"in g&&O?.relation===t.$relation?"$self":O?.relation?O?.relation:"$self")(),L=T==="$self"?n:c.relations[T];if(J(L.roles,(P,z)=>P===R.path)?.playedBy?.length===0)throw new Error(`unused role: ${A}.${R.path}`);if(!g)throw new Error(`Field ${R.path} not found in schema`);let b=R.fieldType==="linkField"?g?.oppositeLinkFieldsPlayedBy:g?.playedBy;if(!b)throw new Error(`No opposite fields found for ${JSON.stringify(g)}`);if([...new Set(b?.map(P=>P.thing))].length>1)throw new Error(`Field: ${R.path} - If a role can be played by multiple things, you must specify the thing in the mutation: ${JSON.stringify(b)}. Schema: ${JSON.stringify(g)}`);if(g.cardinality==="ONE"&&Array.isArray(q))throw new Error("Can't have an array in a cardinality === ONE link field");if(g.cardinality==="MANY"&&q!==null&&!Array.isArray(q)&&!q.$arrayOp)throw new Error(`${R.fieldType==="linkField"?g.path:g.name} is a cardinality === MANY thing. Use an array or a $arrayOp object`);if(q?.$entity||q?.$relation)return;let[$]=b,Q="plays"in g?"linkField":"roleField",k={[`$${$.thingType}`]:$.thing,[Symbol.for("relation")]:T,[Symbol.for("edgeType")]:Q,[Symbol.for("parent")]:{path:A,...t.$id?{$id:t.$id}:{},...t.$tempId?{$tempId:t.$tempId}:{},...t.filter?{filter:t.filter}:{},links:b},[Symbol.for("role")]:$.plays,[Symbol.for("oppositeRole")]:"plays"in g?g.plays:void 0,[Symbol.for("relFieldSchema")]:g};if(isObject(q)&&(t[R.path]={...k,...q}),Array.isArray(q))if(q.every(P=>isObject(P)))t[R.path]=q.map(P=>({...k,...P}));else if(q.every(P=>typeof P=="string"))t[R.path]=q.map(P=>({...k,$op:t.$op==="create"?"link":"replace",$id:P}));else throw new Error(`Invalid array value for ${R.path}`);if(typeof q=="string"&&(t[R.path]={...k,$op:t.$op==="create"?"link":"replace",$id:q}),q===null){let P={...k,$op:"unlink"};t[R.path]=g.cardinality==="MANY"?[P]:P;}}),!h&&!t.$entity&&!t.$relation)throw new Error("Root things must specify $entity or $relation")}})))(u),m=(w=>produce(w,f=>traverse(f,({parent:l,key:d,value:o,meta:t})=>{if(isObject(o)){if(Object.keys(o).length===0)throw new Error("Empty object!");if(d==="$filter"||t.nodePath?.includes(".$filter."))return;let n=o,y=t.nodePath?.split(".");if(n.$tempId&&!(n.$op===void 0||n.$op==="link"||n.$op==="create"||n.$op==="update"))throw new Error(`Invalid op ${n.$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.`);let h=y?.filter(C=>Number.isNaN(parseInt(C,10))).join("."),e=h?Array.isArray(l)?y?.slice(0,-1).join("."):t.nodePath:t.nodePath||"",S=x(c,n),{unidentifiedFields:F,dataFields:M,roleFields:I,linkFields:A}=j(S,n),R=current(n)[Symbol.for("parent")],q=h&&R.path,O=(q?getNodeByPath(f,q):f)?.$op;if(h&&!O)throw new Error("Error: Parent $op not detected");let N=n[Symbol.for("relFieldSchema")],T=Object.keys(n).some(C=>M?.includes(C)),L=Object.keys(n).some(C=>[...I,...A].includes(C)),E=()=>{if(n.$op)return n.$op;if(h&&!n.$id&&!n.$tempId&&O!=="create"&&N.cardinality==="ONE")throw new Error(`Please specify if it is a create or an update. Path: ${t.nodePath}`);if(n.$tempId)return "create";if((n.$id||n.$filter)&&T)return "update";if((n.$id||n.$filter)&&h&&!T&&!L)return "link";if(!n.$filter&&!n.$id&&!n.$tempId)return "create";if((n.$id||n.$filter)&&!T&&L)return "match";throw new Error("Wrong op")};if(n.$op||(n.$op=E()),l||(n.$parentKey=""),typeof l=="object"&&(Array.isArray(l)&&(n[Symbol.for("index")]=d),n[Symbol.for("path")]=e,n[Symbol.for("isRoot")]=!h,n[Symbol.for("depth")]=h?.split(".").length),!n.$entity&&!n.$relation)throw new Error(`Node ${JSON.stringify(n)} without $entity/$relation`);let{idFields:b,computedFields:$,virtualFields:Q}=S;if(!b)throw new Error("No idFields found");let[k]=b,P=listify(n,(C,D)=>D!==void 0?C:void 0),z=P.filter(C=>Q?.includes(C));if(z.length>0)throw new Error(`Virtual fields can't be sent to DB: "${z.join(",")}"`);if($.filter(C=>!P.includes(C)).forEach(C=>{let D=S.dataFields?.find(V=>V.path===C),Wt=S.linkFields?.find(V=>V.path===C)?.oppositeLinkFieldsPlayedBy[0],Gt="roles"in S?J(S.roles,(V,Oe)=>V===C):void 0,ut=D||Wt||Gt;if(!ut)throw new Error(`no field Def for ${C}`);if(C===k&&n.$op==="create"&&!n[C]){let V=Z({currentThing:n,fieldSchema:ut,mandatoryDependencies:!0});n[C]=V,n.$id=V;}}),F.length>0)throw new Error(`Unknown fields: [${F.join(",")}] in ${JSON.stringify(n)}`)}})))(s);a.filledBqlRequest=m;};var kt=async a=>{let{filledBqlRequest:r,schema:c}=a,i=f=>{let l=[],d=[],o=h=>{if(h.$id)return h.$id;let e=x(c,h),{idFields:S}=e;if(!S)throw new Error(`no idFields: ${JSON.stringify(h)}`);let[F]=S;if(!F)throw new Error(`no idField: ${JSON.stringify(h)}`);let M=e.dataFields?.find(R=>R.path===F),I=h.$op==="create"?M?.default?.value():null,A=h[F]||h.$id||I;if(!A)throw new Error(`no idValue: ${JSON.stringify(h)}`);return A},t=h=>{if(h.$op==="create"){let e=o(h);if(l.find(S=>S.$id===e))throw new Error(`Duplicate id ${e} for node ${JSON.stringify(h)}`);if(d.find(S=>S.$bzId===h.$bzId))throw new Error(`Duplicate $bzid ${h.$bzId} for node ${JSON.stringify(h)}`);l.push({...h,$id:e});return}h.$tempId&&h.$op==="match"||l.push(h);},n=h=>{if(h.$op==="create"){let e=o(h);if(l.find(S=>S.$id===e),d.find(S=>S.$bzId===h.$bzId))throw new Error(`Duplicate %bzId ${h.$bzIdd} for edge ${JSON.stringify(h)}`);d.push({...h,$id:e});return}d.push(h);};return traverse(f,({value:h})=>{if(!isObject(h))return;let e=h;if(e.$entity||e.$relation){if(!e.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(e)}`);if(!e.$bzId)throw new Error("[internal error] BzId not found");let S=x(c,e),{dataFields:F,roleFields:M,linkFields:I,usedFields:A}=j(S,e),R=()=>{if(e.$op==="create"||e.$op==="delete")return e.$op;if(e.$op==="update"){let g=A.filter(T=>F?.includes(T)),O=A.filter(T=>M?.includes(T)),N=A.filter(T=>I?.includes(T));if(g.length>0)return "update";if(O.length>0||N.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(e)}`)}return "match"},q={...e.$entity&&{$entity:e.$entity},...e.$relation&&{$relation:e.$relation},...e.$id&&{$id:e.$id},...e.$tempId&&{$tempId:e.$tempId},...e.$filter&&{$filter:e.$filter},...shake(pick(e,F||[""])),$op:R(),$bzId:e.$bzId,[Symbol.for("dbId")]:S.defaultDBConnector.id,[Symbol.for("path")]:e[Symbol.for("path")],[Symbol.for("parent")]:e[Symbol.for("parent")],[Symbol.for("isRoot")]:e[Symbol.for("isRoot")],[Symbol.for("isLocalId")]:e[Symbol.for("isLocalId")]||!1};if(t(q),e[Symbol.for("relation")]&&e[Symbol.for("edgeType")]==="linkField"){if((e.$op==="link"||e.$op==="unlink")&&(e.$id||e.$filter)){if(e.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");l.push({...e,$op:"match"});}let g=e[Symbol.for("relation")]===e.$relation,O=g?e.$bzId:v4(),T=e[Symbol.for("parent")].path,E=(T?getNodeByPath(f,T):f).$bzId;if(!E)throw new Error("No parent id found");if(e[Symbol.for("relation")]==="$self")return;let b=()=>{if(e.$op==="delete")return g?"match":"delete";if(e.$op==="unlink")return g?"unlink":"delete";if(e.$op==="link"||e.$op==="create")return g?"link":"create";if(e.$op==="replace")throw new Error("Unsupported: Replaces not implemented yet");return "match"},$={$relation:e[Symbol.for("relation")],$bzId:O,...e.$tempId?{$tempId:e.$tempId}:{},$op:b(),...g?{}:{[e[Symbol.for("role")]]:e.$bzId},[e[Symbol.for("oppositeRole")]]:E,[Symbol.for("dbId")]:c.relations[e[Symbol.for("relation")]].defaultDBConnector.id,[Symbol.for("edgeType")]:"linkField",[Symbol.for("info")]:"normal linkField",[Symbol.for("path")]:e[Symbol.for("path")],[Symbol.for("parent")]:e[Symbol.for("parent")]};n($),(e.$op==="unlink"||b()==="unlink")&&g&&n({$relation:e[Symbol.for("relation")],$bzId:O,$op:"match",[e[Symbol.for("oppositeRole")]]:E,[Symbol.for("dbId")]:c.relations[e[Symbol.for("relation")]].defaultDBConnector.id,[Symbol.for("edgeType")]:"linkField",[Symbol.for("info")]:"additional ownrelation unlink linkField",[Symbol.for("path")]:e[Symbol.for("path")],[Symbol.for("parent")]:e[Symbol.for("parent")]});}if(e.$relation){let g=_(e,(T,L)=>M.includes(T)),O=mapEntries(g,(T,L)=>isArray(L)?[T,L]:isObject(L)?[T,L.$bzId]:[T,L]),N=_(h,(T,L)=>T.startsWith("$")||T.startsWith("Symbol"));if(Object.keys(g).filter(T=>!T.startsWith("$")).length>0){if(e.$op==="create"||e.$op==="delete"){let T=()=>{if(e.$op==="create")return "link";if(e.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},L=mapEntries(O,(b,$)=>Array.isArray($)?[b,$.map(Q=>Q.$bzId||Q)]:[b,$.$bzId||$]),E={...N,$relation:e.$relation,$op:T(),...L,$bzId:e.$bzId,[Symbol.for("path")]:e[Symbol.for("path")],[Symbol.for("dbId")]:S.defaultDBConnector.id,[Symbol.for("info")]:"coming from created or deleted relation",[Symbol.for("edgeType")]:"roleField on C/D"};n(E);return}if(e.$op==="match"||e.$op==="update"&&Object.keys(g).length>0){let T=0;Object.entries(g).forEach(([L,E])=>{let b=isArray(E)?E:[E],$=Q=>Q==="create"||Q==="replace"?"link":Q;b.forEach(Q=>{let k=$(Q.$op);if(k==="replace")throw new Error("Not supported yet: replace on roleFields");if(k==="unlink"&&T>0)throw T+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let P={...N,$relation:e.$relation,$op:k,[L]:Q.$bzId,$bzId:e.$bzId,[Symbol.for("dbId")]:S.defaultDBConnector.id,[Symbol.for("parent")]:e[Symbol.for("parent")],[Symbol.for("path")]:e[Symbol.for("path")],[Symbol.for("info")]:"updating roleFields",[Symbol.for("edgeType")]:"roleField on L/U/R"};n(P);});});}}}}}),[l,d]};if(!r)throw new Error("Undefined filledBqlRequest");let [u,p]=i(r),s=u.reduce((f,l)=>{if(!l.$bzId)return [...f,l];let d=f.findIndex(o=>o.$bzId===l.$bzId);if(d===-1)return [...f,l];if(f[d].$op==="create"&&l.$op==="match")return f;if(f[d].$op==="match"&&(l.$op==="create"||l.$op==="match"))return [...f.slice(0,d),l,...f.slice(d+1)];throw new Error(`Unsupported operation combination for $tempId "${l.$tempId}". Existing: ${f[d].$op}. Current: ${l.$op}`)},[]),B=p.reduce((f,l)=>{let d=f.find(o=>(o.$id&&o.$id===l.$id||o.$bzId&&o.$bzId===l.$bzId)&&o.$relation===l.$relation&&o.$op===l.$op);if(d){let o={...d};return Object.keys(l).forEach(n=>{if(typeof n=="symbol"||n.startsWith("$"))return;let y=d[n],h=l[n];Array.isArray(y)&&Array.isArray(h)?o[n]=Array.from(new Set([...y,...h])):!Array.isArray(y)&&Array.isArray(h)?y!==void 0?o[n]=Array.from(new Set([y,...h])):o[n]=h:Array.isArray(y)&&!Array.isArray(h)?h!==void 0&&(o[n]=Array.from(new Set([...y,h]))):y||(o[n]=h);}),[...f.filter(n=>!((n.$id&&n.$id===l.$id||n.$bzId&&n.$bzId===l.$bzId)&&n.$relation===l.$relation&&n.$op===l.$op)),o]}return [...f,l]},[]);[...new Set(B.map(f=>f.$relation))];a.bqlRequest={mutation:{things:s,edges:B}};};var Nt=async a=>{let{filledBqlRequest:r}=a,i=(m=>{let w=!1;return traverse(m,({value:f})=>f.$op==="replace"?(w=!0,!1):!0),w})(r),p=(m=>{if(Array.isArray(m)){let w=[],f=null,l=null;if(traverse(m,({value:o,key:t,meta:n})=>{n.depth===2&&(t==="$relation"?f=o:t==="$entity"?l=o:t==="$id"&&typeof o=="string"&&w.push(o));}),!f&&!l)throw new Error("Neither $relation nor $entity found in the blocks");let d={$id:w};return f&&(d.$relation=f),l&&(d.$entity=l),d}return m})(r),s=await nt(p,a.config,a.schema,a.dbHandles);if((m=>produce(m,w=>{traverse(w,({value:f,key:l,parent:d})=>{if(isObject(f)&&f.$op==="link"&&d&&d[l].$op==="link"&&!Array.isArray(s)&&s&&s[l]&&!parseInt(l)&&s[l].$op!=="link")throw new Error(`You already have ${l} filled for this.`)});}))(r),i){let w=(f=>produce(f,l=>traverse(l,({value:d,key:o,parent:t})=>{if(o&&!o?.includes("$")&&(Array.isArray(d)||isObject(d))){let n=Array.isArray(d)?d:[d],y={};n.forEach(F=>{F.$op==="replace"&&(F.$op="link"),F.$entity?y.$entity=F.$entity:F.$relation&&(y.$relation=F.$relation);});let h=[],e=Array.isArray(s)?s.find(F=>F.$id===t.$id):s,S=e?e[o]:null;Array.isArray(S)?h=S.map(F=>typeof F=="object"?F.$id:F):typeof S=="string"&&(h=[S]),h.forEach(F=>{let M=S[0].$op==="replace"?null:n.find(I=>I.$id===F&&I.$op==="link");if(!M&&!n.some(I=>I.$id===F)){let I={...y,$op:"unlink",$id:F,$bzId:`T_${v4()}`};Array.isArray(d)?d.push(I):t[o]=[d,I];}else if(M){let I=n.findIndex(A=>A.$id===F&&A.$op==="link");I>-1&&n.splice(I,1);}});}})))(r);a.filledBqlRequest=w;}};var Dt=async(a,r)=>{let{dbHandles:c,tqlRequest:i,bqlRequest:u,config:p}=a;if(!i)throw new Error("TQL request not built");if(!(i.deletions&&i.deletionMatches||i.insertions))throw new Error("TQL request error, no things");if(!u?.mutation)throw new Error("BQL mutation not parsed");let s=p.dbConnectors[0].id,B=c.typeDB.get(s)?.session;if(!B)throw new Error("Session not found");if(!B.isOpen())throw new Error("Session is closed");let m=await B.transaction(TransactionType.WRITE);if(!m)throw new Error("Can't create transaction");let w=i.deletionMatches&&i.deletions&&`match ${i.deletionMatches} delete ${i.deletions}`,f=i.insertions&&`${i.insertionMatches?`match ${i.insertionMatches}`:""} insert ${i.insertions}`;w&&m.query.delete(w);let l=f&&m.query.insert(f);try{let d=l?await l.collect():void 0;await m.commit(),await m.close(),r.rawTqlRes={insertions:d};}catch(d){throw await m.close(),new Error(`Transaction failed: ${d.message}`)}};var xt={query:[Mt,Y,X,H,lt],mutation:[qt,Nt,kt,Qt,Dt,H]},Ie=[Tt],it=async(a,r,c={},i=!0)=>{for(let u of a){let p=await u(r,c);if(p&&Array.isArray(p))for(let s of p)await it(s.pipeline,s.req,s.res,!1);}return i?(await it(Ie,r,c,!1),r.config.query?.debugger===!0&&typeof c.bqlRes=="object"?{...c.bqlRes,$debugger:{tqlRequest:r.tqlRequest}}:c.bqlRes):c.bqlRes},nt=(a,r,c,i)=>it(xt.query,{config:r,schema:c,rawBqlRequest:a,dbHandles:i},{}),jt=(a,r,c,i)=>it(xt.mutation,{config:r,schema:c,rawBqlRequest:a,dbHandles:i},{});var ft=class{schema;config;dbHandles;constructor({schema:r,config:c}){this.schema=r,this.config=c;}init=async()=>{let r={typeDB:new Map},c=bt(this.schema);await Promise.all(this.config.dbConnectors.map(async i=>{if(i.provider==="typeDB"&&i.dbName){let[u,p]=await tryit(TypeDB.coreClient)(i.url);if(u){let s=`[BORM:${i.provider}:${i.dbName}] ${u.message??"Can't create TypeDB Client"}`;throw new Error(s)}try{let s=await p.session(i.dbName,SessionType.DATA);r.typeDB.set(i.id,{client:p,session:s});}catch(s){let B=`[BORM:${i.provider}:${i.dbName}] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(B)}}if(i.provider==="typeDBCluster"&&i.dbName){let[u,p]=await tryit(TypeDB.clusterClient)(i.addresses,i.credentials);if(u){let s=`[BORM:${i.provider}:${i.dbName}] ${u.message??"Can't create TypeDB Cluster Client"}`;throw new Error(s)}try{let s=await p.session(i.dbName,SessionType.DATA);r.typeDB.set(i.id,{client:p,session:s});}catch(s){let B=`[BORM:${i.provider}:${i.dbName}] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(B)}}})),this.schema=c,this.dbHandles=r;};#t=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#t(),this.schema);define=async()=>(await this.#t(),ht(this.config,this.schema,this.dbHandles));query=async(r,c)=>{await this.#t();let i={...this.config,query:{...ot.query,...this.config.query,...c}};return nt(r,i,this.schema,this.dbHandles)};mutate=async(r,c)=>{await this.#t();let i={...this.config,mutation:{...ot.mutation,...this.config.mutation,...c}};return jt(r,i,this.schema,this.dbHandles)};close=async()=>{this.dbHandles&&this.dbHandles.typeDB.forEach(async({client:r,session:c})=>{console.log("Closing session"),await c.close(),console.log("Closing client"),await r.close();});}},Ri=ft;//! reads all the insertions and gets the first match. This means each id must be unique
35
+ //! disabled as it has false positives
36
+
37
+ export { Ri as default };
package/package.json CHANGED
@@ -1,11 +1,15 @@
1
1
  {
2
2
  "name": "@blitznocode/blitz-orm",
3
- "version": "0.4.8",
3
+ "version": "0.5.0",
4
4
  "main": "dist/index.cjs",
5
+ "module": "./dist/index.mjs",
5
6
  "types": "dist/index.d.ts",
6
- "type": "module",
7
7
  "exports": {
8
- ".": "./dist/index.cjs"
8
+ ".": {
9
+ "require": "./dist/index.cjs",
10
+ "import": "./dist/index.mjs",
11
+ "types": "./dist/index.d.ts"
12
+ }
9
13
  },
10
14
  "private": false,
11
15
  "license": "AGPL-3.0-only",
@@ -36,6 +40,7 @@
36
40
  "@types/jest": "^29.5.5",
37
41
  "@types/node": "^20.8.6",
38
42
  "@types/uuid": "^9.0.5",
43
+ "esbuild": "^0.19.5",
39
44
  "eslint": "^8.51.0",
40
45
  "jest": "^29.7.0",
41
46
  "knip": "^2.34.0",
@@ -61,7 +66,7 @@
61
66
  ],
62
67
  "author": "blitznocode.com",
63
68
  "scripts": {
64
- "build": "tsup --clean --dts --treeshake --minify",
69
+ "build": "tsup src/index.ts --format cjs,esm --clean --dts --treeshake --minify",
65
70
  "dev": "tsup --dts --watch --sourcemap",
66
71
  "knip": "knip",
67
72
  "husky:prepare": "husky install",
@@ -73,6 +78,7 @@
73
78
  "pub": "pnpm build && pnpm publish",
74
79
  "test": "jest --coverage",
75
80
  "test:ignoreTodo": "jest -t \"^(?!.*TODO:).*\" --detectOpenHandles",
81
+ "test:buildSchema": "npx esbuild tests/mocks/buildSchema.ts --bundle --loader:.ts=ts --platform=node --format=cjs --outfile=tests/mocks/buildSchema.js && node tests/mocks/buildSchema.js",
76
82
  "test:watch": "jest --watch",
77
83
  "types": "tsc --noEmit"
78
84
  }
package/readme.md CHANGED
@@ -59,6 +59,16 @@ Blitz-orm is currently in alpha version and not ready for production use. Some k
59
59
  ## What is Currently Working
60
60
  To see what is currently working and find examples, please check the test folder, where you will find a variety of queries and mutations.
61
61
 
62
+ ## TypeGen
63
+ This orm includes a basic typeGen that gets you types depending on the structure of the borm Schema. You can use it like this:
64
+ ```
65
+ type UserType = GenerateType<typeof typesSchema.relations.User>;
66
+
67
+ ```
68
+ Due to typescript limitations and also to be able to type fields from extended things, you will need to compile your bormSchema to a particular format. In order to make this work you can see the example that we have in the tests that you can run with `pnpm test:buildSchema`.
69
+
70
+ You can also use it with your base schema without compiling but some fields might not be there and you might need to ignore some ts errors. Also you will need "as const" at the end of your schema.
71
+
62
72
  ## The future of this package
63
73
  - Achieve 100% compatibility with typeDB functions
64
74
  - Enhance functionality with new features such as, cardinality management, ordered attributes, Vectors (ordered relations)...