@blitznocode/blitz-orm 0.4.5 → 0.4.7
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.cjs +39 -0
- package/dist/index.d.cts +296 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +8 -10
- package/package.json +8 -4
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
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=[],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+=`
|
|
10
|
+
`,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"},
|
|
11
|
+
`;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,
|
|
12
|
+
`,S.push(b));}if(A&&A.length>0&&A.forEach(L=>{!g.includes(L.dbPath)&&!S.includes(L.dbPath)&&(y+=` owns ${L.dbPath},
|
|
13
|
+
`),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}:${$},
|
|
14
|
+
`,L.push(`${b}:${$}`));});}y=y.replace(/,\s*$/,`;
|
|
15
|
+
`),y+=`
|
|
16
|
+
`;}),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"},
|
|
17
|
+
`;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,
|
|
18
|
+
`,E.push(M));}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});}),F&&Object.keys(F).forEach(b=>{S.includes(b)||(y+=` relates ${b},
|
|
20
|
+
`);}),g&&g.length>0){let b=[];g.forEach($=>{let{plays:M}=$;!N.includes($.path)&&!b.includes(`${Q}:${M}`)&&(y+=` plays ${$.relation}:${M},
|
|
21
|
+
`,b.push(`${Q}:${M}`));});}y=y.replace(/,\s*$/,`;
|
|
22
|
+
`),y+=`
|
|
23
|
+
`;});let e=`define
|
|
24
|
+
|
|
25
|
+
`;return Ht(h).forEach(R=>{e+=`${R.dbPath} sub attribute,
|
|
26
|
+
`,R.contentType==="TEXT"||R.contentType==="ID"?e+=` value string;
|
|
27
|
+
`:R.contentType==="EMAIL"?(e+=` value string,
|
|
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,})$';
|
|
29
|
+
`):R.contentType==="DATE"?e+=` value datetime;
|
|
30
|
+
`:R.contentType==="BOOLEAN"?e+=` value boolean;
|
|
31
|
+
`:R.contentType==="NUMBER"&&(e+=` value long;
|
|
32
|
+
`);}),`${e}
|
|
33
|
+
|
|
34
|
+
${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,typedbClient.SessionType.SCHEMA),l=await f.transaction(typedbClient.TransactionType.WRITE);await l.query.define(u),await l.commit(),await l.close();let c=await f.transaction(typedbClient.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=immer.produce(a,u=>objectTraversal.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 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":""}})(),B=Array.isArray(p)?p.map(f=>({...f,...m})):[{...p,...m}];r.push(...B);}}),immer.produce(d,u=>objectTraversal.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?radash.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")}):radash.listify(r,t=>t),B=r.$filter?radash.listify(r.$filter,t=>t.toString().startsWith("$")?void 0:t.toString()).filter(t=>t&&d?.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,...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&&radash.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=radash.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 radash.unique(radash.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?radash.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?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,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)=>immer.produce(a,d=>objectTraversal.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=>radash.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=radash.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=immer.produce(o,y=>objectTraversal.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;}}),radash.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?radash.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(typedbClient.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?radash.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 radash.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=radash.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=radash.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=radash.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};
|
|
35
|
+
${F.join(" or ")};
|
|
36
|
+
`}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?radash.listify(n.roles,L=>L):[],R=o.$relation&&"roles"in n&&radash.mapEntries(n.roles,(L,E)=>[L,E.dbConnector?.path||L]),Q=radash.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 radash.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 radash.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=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=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=>immer.produce(B,f=>objectTraversal.traverse(f,({value:l,key:c,parent:o})=>{radash.isObject(l)&&(l=radash.shake(l,t=>t===void 0)),c==="$tempId"&&(o[c]=Re(l));})))(r),s=(B=>immer.produce(B,f=>objectTraversal.traverse(f,({value:l,meta:c,key:o})=>{if(radash.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_${uuid.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(radash.isObject(q)&&(t[F.path]={...P,...q}),Array.isArray(q))if(q.every(k=>radash.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=>immer.produce(B,f=>objectTraversal.traverse(f,({parent:l,key:c,value:o,meta:t})=>{if(radash.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=immer.current(n)[Symbol.for("parent")],q=h&&F.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")],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=radash.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 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 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},...radash.shake(radash.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:uuid.v4(),S=e[Symbol.for("parent")].path,E=(S?objectTraversal.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=radash.mapEntries(g,(S,L)=>radash.isArray(L)?[S,L]:radash.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=radash.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=radash.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 objectTraversal.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(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"&&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=>immer.produce(m,B=>{objectTraversal.traverse(B,({value:f,key:l,parent:c})=>{if(radash.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=>immer.produce(f,l=>objectTraversal.traverse(l,({value:c,key:o,parent:t})=>{if(o&&!o?.includes("$")&&(Array.isArray(c)||radash.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_${uuid.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(typedbClient.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 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 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 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 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
|
|
37
|
+
//! disabled as it has false positives
|
|
38
|
+
|
|
39
|
+
module.exports = ui;
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
import { TypeDBCredential, TypeDBClient, TypeDBSession } from 'typedb-client';
|
|
2
|
+
|
|
3
|
+
type BormConfig = {
|
|
4
|
+
server: {
|
|
5
|
+
provider: 'blitz-orm-js';
|
|
6
|
+
};
|
|
7
|
+
query?: {
|
|
8
|
+
noMetadata?: boolean;
|
|
9
|
+
simplifiedLinks?: boolean;
|
|
10
|
+
debugger?: boolean;
|
|
11
|
+
};
|
|
12
|
+
mutation?: {
|
|
13
|
+
noMetadata?: boolean;
|
|
14
|
+
};
|
|
15
|
+
dbConnectors: [ProviderObject, ...ProviderObject[]];
|
|
16
|
+
};
|
|
17
|
+
type ProviderObject = (TypeDBProviderObject & CommonProperties) | (TypeDBClusterProviderObject & CommonProperties);
|
|
18
|
+
interface CommonProperties {
|
|
19
|
+
id: string;
|
|
20
|
+
dbName: string;
|
|
21
|
+
}
|
|
22
|
+
type Provider = 'typeDB' | 'typeDBCluster';
|
|
23
|
+
interface TypeDBProviderObject {
|
|
24
|
+
provider: 'typeDB';
|
|
25
|
+
url: string;
|
|
26
|
+
}
|
|
27
|
+
interface TypeDBClusterProviderObject {
|
|
28
|
+
provider: 'typeDBCluster';
|
|
29
|
+
addresses: string[];
|
|
30
|
+
credentials: TypeDBCredential;
|
|
31
|
+
}
|
|
32
|
+
type DBConnector = {
|
|
33
|
+
id: string;
|
|
34
|
+
subs?: string;
|
|
35
|
+
path?: string;
|
|
36
|
+
as?: string;
|
|
37
|
+
};
|
|
38
|
+
type TypeDBHandles = Map<string, {
|
|
39
|
+
client: TypeDBClient;
|
|
40
|
+
session: TypeDBSession;
|
|
41
|
+
}>;
|
|
42
|
+
type DBHandles = {
|
|
43
|
+
typeDB: TypeDBHandles;
|
|
44
|
+
};
|
|
45
|
+
type BormSchema = {
|
|
46
|
+
entities: {
|
|
47
|
+
[s: string]: BormEntity;
|
|
48
|
+
};
|
|
49
|
+
relations: {
|
|
50
|
+
[s: string]: BormRelation;
|
|
51
|
+
};
|
|
52
|
+
};
|
|
53
|
+
type EnrichedBormSchema = {
|
|
54
|
+
entities: {
|
|
55
|
+
[s: string]: EnrichedBormEntity;
|
|
56
|
+
};
|
|
57
|
+
relations: {
|
|
58
|
+
[s: string]: EnrichedBormRelation;
|
|
59
|
+
};
|
|
60
|
+
};
|
|
61
|
+
type BormEntity = {
|
|
62
|
+
extends: string;
|
|
63
|
+
idFields?: string[];
|
|
64
|
+
defaultDBConnector: DBConnector;
|
|
65
|
+
dataFields?: DataField[];
|
|
66
|
+
linkFields?: LinkField[];
|
|
67
|
+
} | {
|
|
68
|
+
extends?: string;
|
|
69
|
+
idFields: string[];
|
|
70
|
+
defaultDBConnector: DBConnector;
|
|
71
|
+
dataFields?: DataField[];
|
|
72
|
+
linkFields?: LinkField[];
|
|
73
|
+
};
|
|
74
|
+
type BormRelation = BormEntity & {
|
|
75
|
+
defaultDBConnector: DBConnector & {
|
|
76
|
+
path: string;
|
|
77
|
+
};
|
|
78
|
+
roles?: {
|
|
79
|
+
[key: string]: RoleField;
|
|
80
|
+
};
|
|
81
|
+
};
|
|
82
|
+
type EnrichedBormEntity = Omit<BormEntity, 'linkFields' | 'idFields' | 'dataFields'> & {
|
|
83
|
+
extends?: string;
|
|
84
|
+
allExtends?: string[];
|
|
85
|
+
idFields: string[];
|
|
86
|
+
thingType: 'entity';
|
|
87
|
+
name: string;
|
|
88
|
+
computedFields: string[];
|
|
89
|
+
virtualFields: string[];
|
|
90
|
+
linkFields?: EnrichedLinkField[];
|
|
91
|
+
dataFields?: EnrichedDataField[];
|
|
92
|
+
};
|
|
93
|
+
type EnrichedBormRelation = Omit<BormRelation, 'linkFields' | 'dataFields'> & {
|
|
94
|
+
thingType: 'relation';
|
|
95
|
+
name: string;
|
|
96
|
+
computedFields: string[];
|
|
97
|
+
virtualFields: string[];
|
|
98
|
+
linkFields?: EnrichedLinkField[];
|
|
99
|
+
dataFields?: EnrichedDataField[];
|
|
100
|
+
roles: {
|
|
101
|
+
[key: string]: EnrichedRoleField;
|
|
102
|
+
};
|
|
103
|
+
};
|
|
104
|
+
type LinkField = BormField & {
|
|
105
|
+
relation: string;
|
|
106
|
+
plays: string;
|
|
107
|
+
} & ({
|
|
108
|
+
target: 'role';
|
|
109
|
+
filter?: Filter | Filter[];
|
|
110
|
+
} | {
|
|
111
|
+
target: 'relation';
|
|
112
|
+
});
|
|
113
|
+
type LinkedFieldWithThing = LinkField & {
|
|
114
|
+
thing: string;
|
|
115
|
+
thingType: ThingType;
|
|
116
|
+
};
|
|
117
|
+
type RequireAtLeastOne<T> = {
|
|
118
|
+
[K in keyof T]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<keyof T, K>>>;
|
|
119
|
+
}[keyof T];
|
|
120
|
+
type LinkFilter = {
|
|
121
|
+
$thing?: string;
|
|
122
|
+
$thingType?: string;
|
|
123
|
+
$role?: string;
|
|
124
|
+
[key: string]: string | number | Filter | undefined;
|
|
125
|
+
};
|
|
126
|
+
type Filter = DataFilter | LinkFilter | MiddleFilter;
|
|
127
|
+
type MiddleFilter = {
|
|
128
|
+
$and?: Filter[];
|
|
129
|
+
$or?: Filter[];
|
|
130
|
+
};
|
|
131
|
+
type DataFilter = RequireAtLeastOne<{
|
|
132
|
+
$eq?: any;
|
|
133
|
+
$ge?: number | string;
|
|
134
|
+
}>;
|
|
135
|
+
type EnrichedLinkField = BormField & {
|
|
136
|
+
name: string;
|
|
137
|
+
relation: string;
|
|
138
|
+
plays: string;
|
|
139
|
+
} & ({
|
|
140
|
+
target: 'role';
|
|
141
|
+
filter?: Filter | Filter[];
|
|
142
|
+
oppositeLinkFieldsPlayedBy: LinkedFieldWithThing[];
|
|
143
|
+
} | {
|
|
144
|
+
target: 'relation';
|
|
145
|
+
oppositeLinkFieldsPlayedBy: Pick<LinkedFieldWithThing, 'thing' | 'thingType' | 'plays'>[];
|
|
146
|
+
});
|
|
147
|
+
type BormField = {
|
|
148
|
+
path: string;
|
|
149
|
+
cardinality: CardinalityType;
|
|
150
|
+
ordered?: boolean;
|
|
151
|
+
embedded?: boolean;
|
|
152
|
+
rights?: RightType[];
|
|
153
|
+
};
|
|
154
|
+
type RoleField = {
|
|
155
|
+
cardinality: CardinalityType;
|
|
156
|
+
dbConnector?: DBConnector;
|
|
157
|
+
};
|
|
158
|
+
type EnrichedRoleField = RoleField & {
|
|
159
|
+
playedBy?: LinkedFieldWithThing[];
|
|
160
|
+
name: string;
|
|
161
|
+
};
|
|
162
|
+
type DataField = BormField & {
|
|
163
|
+
shared?: boolean;
|
|
164
|
+
default?: any;
|
|
165
|
+
contentType: ContentType;
|
|
166
|
+
validations?: any;
|
|
167
|
+
isVirtual?: boolean;
|
|
168
|
+
dbConnectors?: [DBConnector, ...DBConnector[]];
|
|
169
|
+
};
|
|
170
|
+
type EnrichedDataField = DataField & {
|
|
171
|
+
dbPath: string;
|
|
172
|
+
};
|
|
173
|
+
type ThingType = 'entity' | 'relation' | 'attribute';
|
|
174
|
+
type RightType = 'CREATE' | 'DELETE' | 'UPDATE' | 'LINK' | 'UNLINK';
|
|
175
|
+
type ContentType = 'ID' | 'JSON' | 'COLOR' | 'BOOLEAN' | 'POINT' | 'FILE' | 'EMAIL' | 'PHONE' | 'WEEK_DAY' | 'DURATION' | 'HOUR' | 'TIME' | 'DATE' | 'RATING' | 'CURRENCY' | 'PERCENTAGE' | 'NUMBER_DECIMAL' | 'NUMBER' | 'URL' | 'PASSWORD' | 'LANGUAGE_TEXT' | 'RICH_TEXT' | 'TEXT';
|
|
176
|
+
type CardinalityType = 'ONE' | 'MANY' | 'INTERVAL';
|
|
177
|
+
type RelationClassType = 'SYMMETRICAL' | 'OWNED';
|
|
178
|
+
type RequiredKey<T, K extends keyof T> = T & {
|
|
179
|
+
[P in K]-?: T[P];
|
|
180
|
+
};
|
|
181
|
+
type WithRequired<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>> & RequiredKey<T, K>;
|
|
182
|
+
type BQLMutationBlock = {
|
|
183
|
+
[key: string]: any;
|
|
184
|
+
$id?: string | string[];
|
|
185
|
+
$filter?: Filter | Filter[];
|
|
186
|
+
$tempId?: string;
|
|
187
|
+
$op?: string;
|
|
188
|
+
} & ({
|
|
189
|
+
$entity: string;
|
|
190
|
+
} | {
|
|
191
|
+
$relation: string;
|
|
192
|
+
});
|
|
193
|
+
type FilledBQLMutationBlock = WithRequired<BQLMutationBlock, '$tempId' | '$op'>;
|
|
194
|
+
type BQLFieldObj = {
|
|
195
|
+
$path: string;
|
|
196
|
+
} & Omit<RawBQLQuery, '$entity' | '$relation'>;
|
|
197
|
+
type BQLField = string | BQLFieldObj;
|
|
198
|
+
type RawBQLQuery = {
|
|
199
|
+
$id?: string | string[];
|
|
200
|
+
$filter?: Record<string, any>;
|
|
201
|
+
$fields?: BQLField[];
|
|
202
|
+
$excludedFields?: BQLField[];
|
|
203
|
+
} & ({
|
|
204
|
+
$entity: string;
|
|
205
|
+
} | {
|
|
206
|
+
$relation: string;
|
|
207
|
+
});
|
|
208
|
+
type RawBQLMutation = ({
|
|
209
|
+
$entity: string;
|
|
210
|
+
} | {
|
|
211
|
+
$relation: string;
|
|
212
|
+
}) & Record<string, any>;
|
|
213
|
+
type ParsedBQLQuery = Omit<RawBQLQuery, '$entity' | '$relation'> & {
|
|
214
|
+
$localFilters?: Record<string, any>;
|
|
215
|
+
$nestedFilters?: Record<string, any>;
|
|
216
|
+
} & ({
|
|
217
|
+
$entity: EnrichedBormEntity;
|
|
218
|
+
} | {
|
|
219
|
+
$relation: EnrichedBormRelation;
|
|
220
|
+
});
|
|
221
|
+
type ParsedBQLMutation = {
|
|
222
|
+
things: BQLMutationBlock[];
|
|
223
|
+
edges: BQLMutationBlock[];
|
|
224
|
+
};
|
|
225
|
+
type TQLRequest = {
|
|
226
|
+
entity?: string;
|
|
227
|
+
roles?: {
|
|
228
|
+
path: string;
|
|
229
|
+
request: string;
|
|
230
|
+
owner: string;
|
|
231
|
+
}[];
|
|
232
|
+
relations?: {
|
|
233
|
+
relation: string;
|
|
234
|
+
entity: string;
|
|
235
|
+
request: string;
|
|
236
|
+
}[];
|
|
237
|
+
insertionMatches?: string;
|
|
238
|
+
deletionMatches?: string;
|
|
239
|
+
insertions?: string;
|
|
240
|
+
deletions?: string;
|
|
241
|
+
};
|
|
242
|
+
type TQLEntityMutation = {
|
|
243
|
+
entity: string;
|
|
244
|
+
relations?: {
|
|
245
|
+
relation: string;
|
|
246
|
+
entity: string;
|
|
247
|
+
request: string;
|
|
248
|
+
}[];
|
|
249
|
+
};
|
|
250
|
+
type BQLResponseSingle = (({
|
|
251
|
+
$entity: string;
|
|
252
|
+
$id: string;
|
|
253
|
+
} | {
|
|
254
|
+
$relation: string;
|
|
255
|
+
$id: string;
|
|
256
|
+
}) | undefined) & Record<string, any>;
|
|
257
|
+
type BQLResponseMulti = BQLResponseSingle[];
|
|
258
|
+
type BQLResponse = BQLResponseSingle | BQLResponseMulti;
|
|
259
|
+
|
|
260
|
+
type BormProps = {
|
|
261
|
+
schema: BormSchema;
|
|
262
|
+
config: BormConfig;
|
|
263
|
+
};
|
|
264
|
+
declare class BormClient {
|
|
265
|
+
#private;
|
|
266
|
+
private schema;
|
|
267
|
+
private config;
|
|
268
|
+
private dbHandles?;
|
|
269
|
+
constructor({ schema, config }: BormProps);
|
|
270
|
+
init: () => Promise<void>;
|
|
271
|
+
introspect: () => Promise<BormSchema>;
|
|
272
|
+
define: () => Promise<void>;
|
|
273
|
+
query<T extends Record<string, any>>(query: RawBQLQuery & {
|
|
274
|
+
$filter: Record<string, any>;
|
|
275
|
+
} & ({
|
|
276
|
+
$entity: string;
|
|
277
|
+
} | {
|
|
278
|
+
$relation: string;
|
|
279
|
+
}), queryConfig?: any): Promise<(BQLResponseSingle & T)[] | (BQLResponseSingle & T)>;
|
|
280
|
+
query<T extends Record<string, any>>(query: RawBQLQuery & {
|
|
281
|
+
$id: string;
|
|
282
|
+
}, queryConfig?: any): Promise<BQLResponseSingle & T>;
|
|
283
|
+
query<T extends Record<string, any>>(query: RawBQLQuery & {
|
|
284
|
+
$id: string[];
|
|
285
|
+
}, queryConfig?: any): Promise<(BQLResponseSingle & T)[]>;
|
|
286
|
+
query<T extends Record<string, any>>(query: Omit<RawBQLQuery, '$id'> & ({
|
|
287
|
+
$entity: string;
|
|
288
|
+
} | {
|
|
289
|
+
$relation: string;
|
|
290
|
+
}), queryConfig?: any): Promise<(BQLResponseSingle & T)[]>;
|
|
291
|
+
mutate<T extends Record<string, any>>(mutation: RawBQLMutation, mutationConfig?: any): Promise<BQLResponseSingle & T>;
|
|
292
|
+
mutate(mutation: RawBQLMutation[], mutationConfig?: any): Promise<BQLResponseMulti>;
|
|
293
|
+
close: () => Promise<void>;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
export { BQLField, BQLFieldObj, BQLMutationBlock, BQLResponse, BQLResponseMulti, BQLResponseSingle, BormConfig, BormEntity, BormField, BormRelation, BormSchema, CardinalityType, CommonProperties, ContentType, DBConnector, DBHandles, DataField, DataFilter, EnrichedBormEntity, EnrichedBormRelation, EnrichedBormSchema, EnrichedDataField, EnrichedLinkField, EnrichedRoleField, FilledBQLMutationBlock, Filter, LinkField, LinkFilter, LinkedFieldWithThing, MiddleFilter, ParsedBQLMutation, ParsedBQLQuery, Provider, ProviderObject, RawBQLMutation, RawBQLQuery, RelationClassType, RightType, RoleField, TQLEntityMutation, TQLRequest, ThingType, TypeDBClusterProviderObject, TypeDBProviderObject, BormClient as default };
|
package/dist/index.d.ts
CHANGED
|
@@ -270,6 +270,13 @@ declare class BormClient {
|
|
|
270
270
|
init: () => Promise<void>;
|
|
271
271
|
introspect: () => Promise<BormSchema>;
|
|
272
272
|
define: () => Promise<void>;
|
|
273
|
+
query<T extends Record<string, any>>(query: RawBQLQuery & {
|
|
274
|
+
$filter: Record<string, any>;
|
|
275
|
+
} & ({
|
|
276
|
+
$entity: string;
|
|
277
|
+
} | {
|
|
278
|
+
$relation: string;
|
|
279
|
+
}), queryConfig?: any): Promise<(BQLResponseSingle & T)[] | (BQLResponseSingle & T)>;
|
|
273
280
|
query<T extends Record<string, any>>(query: RawBQLQuery & {
|
|
274
281
|
$id: string;
|
|
275
282
|
}, queryConfig?: any): Promise<BQLResponseSingle & T>;
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
var objectTraversal = require('object-traversal');
|
|
7
|
-
var uuid = require('uuid');
|
|
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';
|
|
8
6
|
|
|
9
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+=`
|
|
10
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"},
|
|
@@ -31,9 +29,9 @@ var ot={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1},mutation:{}};var Ht
|
|
|
31
29
|
`:R.contentType==="NUMBER"&&(e+=` value long;
|
|
32
30
|
`);}),`${e}
|
|
33
31
|
|
|
34
|
-
${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,typedbClient.SessionType.SCHEMA),l=await f.transaction(typedbClient.TransactionType.WRITE);await l.query.define(u),await l.commit(),await l.close();let c=await f.transaction(typedbClient.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=immer.produce(a,u=>objectTraversal.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 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":""}})(),B=Array.isArray(p)?p.map(f=>({...f,...m})):[{...p,...m}];r.push(...B);}}),immer.produce(d,u=>objectTraversal.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?radash.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")}):radash.listify(r,t=>t),B=r.$filter?radash.listify(r.$filter,t=>t.toString().startsWith("$")?void 0:t.toString()).filter(t=>t&&d?.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,...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&&radash.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=radash.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 radash.unique(radash.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?radash.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?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,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)=>immer.produce(a,d=>objectTraversal.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=>radash.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=radash.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=immer.produce(o,y=>objectTraversal.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;}}),radash.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?radash.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(typedbClient.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?radash.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 radash.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=radash.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=radash.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=radash.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};
|
|
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};
|
|
35
33
|
${F.join(" or ")};
|
|
36
|
-
`}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?radash.listify(n.roles,L=>L):[],R=o.$relation&&"roles"in n&&radash.mapEntries(n.roles,(L,E)=>[L,E.dbConnector?.path||L]),Q=radash.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 radash.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 radash.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=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=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=>immer.produce(B,f=>objectTraversal.traverse(f,({value:l,key:c,parent:o})=>{radash.isObject(l)&&(l=radash.shake(l,t=>t===void 0)),c==="$tempId"&&(o[c]=Re(l));})))(r),s=(B=>immer.produce(B,f=>objectTraversal.traverse(f,({value:l,meta:c,key:o})=>{if(radash.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_${uuid.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(radash.isObject(q)&&(t[F.path]={...P,...q}),Array.isArray(q))if(q.every(k=>radash.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=>immer.produce(B,f=>objectTraversal.traverse(f,({parent:l,key:c,value:o,meta:t})=>{if(radash.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=immer.current(n)[Symbol.for("parent")],q=h&&F.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")],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=radash.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 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 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},...radash.shake(radash.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:uuid.v4(),S=e[Symbol.for("parent")].path,E=(S?objectTraversal.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=radash.mapEntries(g,(S,L)=>radash.isArray(L)?[S,L]:radash.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=radash.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=radash.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 objectTraversal.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(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"&&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=>immer.produce(m,B=>{objectTraversal.traverse(B,({value:f,key:l,parent:c})=>{if(radash.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=>immer.produce(f,l=>objectTraversal.traverse(l,({value:c,key:o,parent:t})=>{if(o&&!o?.includes("$")&&(Array.isArray(c)||radash.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_${uuid.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(typedbClient.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 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 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 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 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
|
+
`}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
|
|
37
35
|
//! disabled as it has false positives
|
|
38
36
|
|
|
39
|
-
|
|
37
|
+
export { ui as default };
|
package/package.json
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blitznocode/blitz-orm",
|
|
3
|
-
"version": "0.4.
|
|
4
|
-
"main": "dist/index.
|
|
3
|
+
"version": "0.4.7",
|
|
4
|
+
"main": "dist/index.cjs",
|
|
5
5
|
"types": "dist/index.d.ts",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./dist"
|
|
9
|
+
},
|
|
6
10
|
"private": false,
|
|
7
11
|
"license": "AGPL-3.0-only",
|
|
8
12
|
"repository": {
|
|
@@ -57,8 +61,8 @@
|
|
|
57
61
|
],
|
|
58
62
|
"author": "blitznocode.com",
|
|
59
63
|
"scripts": {
|
|
60
|
-
"build": "tsup --dts --treeshake --minify",
|
|
61
|
-
"dev": "tsup --dts --watch",
|
|
64
|
+
"build": "tsup --clean --dts --treeshake --minify",
|
|
65
|
+
"dev": "tsup --dts --watch --sourcemap",
|
|
62
66
|
"knip": "knip",
|
|
63
67
|
"husky:prepare": "husky install",
|
|
64
68
|
"lint:check": "eslint src --quiet --ext .ts,.tsx",
|