@blitznocode/blitz-orm 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Wt=Object.create;var tt=Object.defineProperty;var Gt=Object.getOwnPropertyDescriptor;var Ht=Object.getOwnPropertyNames;var Ut=Object.getPrototypeOf,_t=Object.prototype.hasOwnProperty;var Vt=(r,n)=>{for(var a in n)tt(r,a,{get:n[a],enumerable:!0})},bt=(r,n,a,i)=>{if(n&&typeof n=="object"||typeof n=="function")for(let c of Ht(n))!_t.call(r,c)&&c!==a&&tt(r,c,{get:()=>n[c],enumerable:!(i=Gt(n,c))||i.enumerable});return r};var ct=(r,n,a)=>(a=r!=null?Wt(Ut(r)):{},bt(n||!r||!r.__esModule?tt(a,"default",{value:r,enumerable:!0}):a,r)),Jt=r=>bt(tt({},"__esModule",{value:!0}),r);var ee={};Vt(ee,{default:()=>te});module.exports=Jt(ee);var jt=require("radash"),dt=require("typedb-client");var ft={query:{simplifiedLinks:!0},mutation:{}};var ht=ct(require("immer")),et=require("object-traversal"),z=require("radash"),Et=(r,n,a)=>a?n:`${r}\xB7${n}`,Rt=r=>{let n=r.split("\xB7");return n[n.length-1]},nt=(r,n)=>Object.values(Object.fromEntries(Object.entries(r).filter(([a,i])=>n(a,i))))[0],G=(r,n)=>Object.fromEntries(Object.entries(r).filter(([a,i])=>n(a,i))),Lt=r=>{let n=[],a=(0,ht.default)(r,c=>(0,et.traverse)(c,({key:l,value:o,meta:u})=>{if(u.depth===2&&(l&&(o.dataFields=o.dataFields?.map(p=>({...p,dbPath:Et(l,p.path,p.shared)}))),o.extends)){let p=c.entities[o.extends]||c.relations[o.extends];if(o.idFields=p.idFields?(o.idFields||[]).concat(p.idFields):o.idFields,o.dataFields=p.dataFields?(o.dataFields||[]).concat(p.dataFields.map(y=>{let f=o.extends,w=r.entities[f]||r.relations[f];for(;!w.dataFields?.find(s=>s.path===y.path);)f=w.extends,w=r.entities[f]||r.relations[f];return{...y,dbPath:Et(f,y.path,y.shared)}})):o.dataFields,o.linkFields=p.linkFields?(o.linkFields||[]).concat(p.linkFields):o.linkFields,"roles"in p){let y=o,f=p;y.roles=y.roles||{},y.roles={...y.roles,...f.roles},Object.keys(y.roles).length===0&&(y.roles={})}}},{traversalType:"breadth-first"}));return(0,et.traverse)(r,({key:c,value:l,meta:o})=>{if(c==="linkFields"){let p=(()=>{if(!o.nodePath)throw new Error("No path");let[f,w]=o.nodePath.split(".");return{thing:w,thingType:f==="entities"?"entity":f==="relations"?"relation":""}})(),y=Array.isArray(l)?l.map(f=>({...f,...p})):[{...l,...p}];n.push(...y)}}),(0,ht.default)(a,c=>(0,et.traverse)(c,({value:l,key:o,meta:u})=>{if(u.depth===2&&l.idFields&&!l.id){l.name=o;let p=()=>{if(u.nodePath?.split(".")[0]==="entities")return"entity";if(u.nodePath?.split(".")[0]==="relations")return"relation";throw new Error("Unsupported node attributes")};l.thingType=p(),l.computedFields=[],"roles"in l&&Object.entries(l.roles).forEach(([f,w])=>{w.playedBy=n.filter(s=>s.relation===o&&s.plays===f)||[],w.name=f}),"linkFields"in l&&l.linkFields&&l.linkFields?.forEach(f=>{if(f.target==="relation"){f.oppositeLinkFieldsPlayedBy=[{plays:f.path,thing:f.relation,thingType:"relation"}];return}let w=n.filter(t=>t.relation===f.relation&&t.plays!==f.plays)||[];f.oppositeLinkFieldsPlayedBy=w;let{filter:s}=f;f.oppositeLinkFieldsPlayedBy=f.oppositeLinkFieldsPlayedBy.filter(t=>t.target==="role"),s&&Array.isArray(s)&&(f.oppositeLinkFieldsPlayedBy=f.oppositeLinkFieldsPlayedBy.filter(t=>s.some(e=>t.thing===e.$role)),f.oppositeLinkFieldsPlayedBy=f.oppositeLinkFieldsPlayedBy.filter(t=>s.some(e=>t.thing===e.$thing))),s&&!Array.isArray(s)&&(f.oppositeLinkFieldsPlayedBy=f.oppositeLinkFieldsPlayedBy.filter(t=>t.$role===s.$role),f.oppositeLinkFieldsPlayedBy=f.oppositeLinkFieldsPlayedBy.filter(t=>t.thing===s.$thing))})}if(typeof l=="object"&&"playedBy"in l){if([...new Set(l.playedBy?.map(p=>p.thing))].length>1)throw new Error(`Unsupported: roleFields can be only played by one thing. Role: ${o} path:${u.nodePath}`);if(l.playedBy.length===0)throw new Error(`Unsupported: roleFields should be played at least by one thing. Role: ${o}, path:${u.nodePath}`)}if(u.depth===4&&(l.default||l.computedValue)){let[p,y]=u.nodePath?.split(".")||[];c[p][y].computedFields.push(l.path)}}))},D=(r,n)=>{if(n.$entity){if(!(n.$entity in r.entities))throw new Error(`Missing entity '${n.$entity}' in the schema`);return r.entities[n.$entity]}if(n.$relation){if(!(n.$relation in r.relations))throw new Error(`Missing relation '${n.$relation}' in the schema`);return r.relations[n.$relation]}throw new Error(`Wrong schema or query for ${JSON.stringify(n)}`)},H=(r,n)=>{let a=r.dataFields?.map(e=>e.path)||[],i=r.linkFields?.map(e=>e.path)||[],c="roles"in r?(0,z.listify)(r.roles,e=>e):[],l=[...a||[],...i||[],...c||[]],u=[...["$entity","$op","$id","$tempId","$relation","$parentKey","$filter","$fields"],...l];if(!n)return{fields:l,dataFields:a,roleFields:c,linkFields:i};let p=n.$fields?n.$fields.map(e=>{if(typeof e=="string")return e;if("$path"in e&&typeof e.$path=="string")return e.$path;throw new Error(" Wrongly structured query")}):(0,z.listify)(n,e=>e),y=n.$filter?(0,z.listify)(n.$filter,e=>e.toString().startsWith("$")?void 0:e.toString()).filter(e=>e&&a?.includes(e)):[],f=n.$filter?(0,z.listify)(n.$filter,e=>e.toString().startsWith("$")?void 0:e.toString()).filter(e=>e&&[...c||[],...i||[]].includes(e)):[],w=[...p,...y].filter(e=>!u.includes(e)).filter(e=>e),s=n.$filter?G(n.$filter,(e,d)=>y.includes(e)):{},t=n.$filter?G(n.$filter,(e,d)=>f.includes(e)):{};return{fields:l,dataFields:a,roleFields:c,linkFields:i,usedFields:p,usedLinkFields:i.filter(e=>p.includes(e)),usedRoleFields:c.filter(e=>p.includes(e)),unidentifiedFields:w,...y.length?{localFilters:s}:{},...f.length?{nestedFilters:t}:{}}},Ft=(r,n)=>{let a=n.$localFilters&&(0,z.listify)(n.$localFilters,(c,l)=>`has ${r.dataFields?.find(u=>u.path===c)?.dbPath} '${l}'`);return a?.length?`, ${a.join(",")}`:""};function K(r){return r!==null}var it=(r,n)=>Object.values(r).reduce((a,i)=>(i.extends===n&&a.push(i.name),a),[]);function yt(r){return typeof r=="string"||!!r.$show}var st=require("radash");var A=require("radash");var zt=(r,n)=>r.map(i=>{let c=[...i.conceptMaps],o=i.owner.asThing().type.label.name,u=n.entities[o]?n.entities[o]:n.relations[o];if(!u.idFields)throw new Error(`No idFields defined for ${o}`);let p=n.entities[o]?"entity":"relation",y=c.map(w=>{let s=w.get("attribute")?.asAttribute();return s?[Rt(s.type.label.name),s.value]:[]}),f=Object.fromEntries(y);return{...f,[`$${p}`]:o,$id:f[u.idFields[0]]}}),Kt=(r,n)=>r.flatMap(i=>i.conceptMaps.map(l=>{let o=new Map;return n.forEach(u=>{let p=l.get(`${u}_id`)?.asAttribute().value.toString(),y=l.get(u),f=y?.isEntity()?y.asEntity().type.label.name:y?.asRelation().type.label.name,w={id:p,entityName:f??u};p&&o.set(u,w)}),o})),Yt=(r,n,a)=>r.flatMap(c=>c.conceptMaps.map(o=>{let u=o.get(`${n}_id`)?.asAttribute().value.toString(),p=o.get(`${a}_id`)?.asAttribute().value.toString();return{ownerId:u,path:a,roleId:p}})),Zt=(r,n)=>{let a=(0,A.listify)(r.roles,(i,c)=>{if([...new Set(c.playedBy?.map(u=>u.thing))].length!==1)throw new Error("a role can be played by two entities throws the same relation");if(!c.playedBy)throw new Error("Role not being played by nobody");let l=c.playedBy[0].plays,o=it(n.entities,l);return[l,...o]});return(0,A.unique)((0,A.flat)(a))},Y=async(r,n)=>{let{schema:a,bqlRequest:i,config:c,tqlRequest:l}=r,{rawTqlRes:o}=n;if(i){if(!o)throw new Error("TQL query not executed")}else throw new Error("BQL request not parsed");let{query:u}=i;if(!u){if(o.insertions?.length===0&&!l?.deletions)throw new Error("Nothing has changed in DB, probably one of the ids specified in the mutation does not exist");let{mutation:s}=i;if(!s)throw new Error("TQL mutation not executed");let e=[...s.things,...s.edges].map(d=>{let m=o.insertions?.find(F=>F.get(`${d.$tempId||d.$id}`))?.get(`${d.$tempId||d.$id}`);if(d.$op==="create"||d.$op==="update"||d.$op==="link"){if(!m?.asThing().iid)throw new Error(`Thing not received on mutation: ${JSON.stringify(d)}`);let F=m?.asThing().iid;return c.mutation?.noMetadata?(0,A.mapEntries)(d,(g,k)=>[g.toString().startsWith("$")?Symbol.for(g):g,k]):{$dbId:F,...d}}if(d.$op==="delete"||d.$op==="unlink")return d;if(d.$op!=="noop")throw new Error(`Unsupported op ${d.$op}`)}).filter(d=>d);n.bqlRes=e.length>1?e:e[0];return}if(!o.entity)throw new Error("TQL query not executed");let p=zt(o.entity,a),y=o.relations?.map(s=>{let t=a.relations[s.relation],e=Zt(t,a),d=Kt(s.conceptMapGroups,[...e,t.name]);return{name:s.relation,links:d}}),f=o.roles?.map(s=>({name:s.ownerPath,links:Yt(s.conceptMapGroups,s.ownerPath,s.path)})),w=n.cache||{entities:new Map,relations:new Map,roleLinks:new Map};p.forEach(s=>{let t=s.$entity||s.$relation,e=s.$id,d=w.entities.get(t)||new Map;d.set(e,{...s,$show:!0}),w.entities.set(t,d)}),y?.forEach(s=>{let t=s.name,e=w.relations.get(t)||[];e.push(...s.links),w.relations.set(t,e),s.links.forEach(d=>{[...d.entries()].forEach(([m,{entityName:F,id:g}])=>{let k=w.entities.get(F)||new Map,B={[(()=>{if(a.entities[F])return"entity";if(a.relations[F])return"relation";throw new Error("Entity or relation not found")})()]:F,$id:g,...k.get(g)};k.set(g,B),w.entities.set(F,k)})})}),f?.forEach(s=>{let t=a.relations[s.name]||a.entities[s.name];s.links.forEach(e=>{let d=w.roleLinks.get(e.ownerId)||{},m=d[e.path];m?(0,A.isArray)(m)?m.push(e.roleId):(0,A.isString)(m)&&m!==e.roleId&&(m=[m,e.roleId]):m=e.roleId,d[e.path]=m,w.roleLinks.set(e.ownerId,d),t.roles[e.path].playedBy?.forEach(F=>{let g=w.entities.get(F.thing)||new Map,k={$entity:F.thing,$id:e.roleId,...g.get(e.roleId)};g.set(e.roleId,k),w.entities.set(F.thing,g)})})}),n.cache=w};var Xt=require("radash");var mt=ct(require("immer")),$t=require("object-traversal"),Z=require("radash");var St=(r,n)=>(0,mt.default)(r,a=>(0,$t.traverse)(a,({value:i})=>{if(Array.isArray(i)||typeof i!="object")return;i.$fields&&delete i.$fields,i.$filter&&delete i.$filter,i.$show&&delete i.$show,n.query?.noMetadata&&(i.$entity||i.$relation)&&(delete i.$entity,delete i.$relation,delete i.$id),Object.getOwnPropertySymbols(r).forEach(l=>{delete i[l]})})),ut=(r,n,a,i)=>r.map(([c,l])=>{if(!n||!n.includes(c))return null;if(!a.$fields||a.$fields.includes(i))return c;let o=a.$fields.find(u=>(0,Z.isObject)(u)&&u.$path===i);if(o){let u={...G(l,(y,f)=>y.startsWith("$"))},p=o.$fields?{...u,$fields:o.$fields}:u;if(o.$id){if(Array.isArray(o.$id))return o.$id.includes(c)?p:null;if(o.$id===c)return p}return p}return null}).filter(c=>c),Tt=async(r,n)=>{let{bqlRequest:a,config:i,schema:c}=r,{cache:l}=n;if(!a)throw new Error("BQL request not parsed");let{query:o}=a;if(!o){n.bqlRes=St(n.bqlRes,i);return}if(!l)return;let u="$entity"in o?o.$entity:o.$relation,p=l.entities.get(u.name);if(!p){n.bqlRes=null;return}let f=(0,Z.listify)(o.$filter,m=>m).some(m=>u.dataFields?.find(F=>F.path===m)?.validations?.unique),w=!Array.isArray(a.query)&&(a.query?.$id&&!Array.isArray(a.query?.$id)||f);if(Array.isArray(r.rawBqlRequest))throw new Error("Query arrays not implemented yet");let s=p,t=[...s].length?[...s].map(([m,F])=>({...r.rawBqlRequest,$id:m})):r.rawBqlRequest,e=(0,mt.default)(t,m=>(0,$t.traverse)(m,({value:F})=>{let g=F;if(!g?.$entity&&!g?.$relation)return;let k="$entity"in g?g.$entity:g.$relation;if(k){let O=Array.isArray(g.$id)?g.$id:[g.$id],R="$relation"in g?c.relations[g.$relation]:c.entities[g.$entity],{dataFields:B,roleFields:b}=H(R),S=l.entities.get(k);if(!S)return;[...S].forEach(([L,Q])=>{if(O.includes(L)){let P=g.$fields?g.$fields:B;(0,Z.listify)(Q,(E,h)=>{E.startsWith("$")||P?.includes(E)&&(g[E]=h)});let M=l.roleLinks.get(L),T=g.$fields?g.$fields.filter(E=>typeof E=="string"):b,$=g.$fields?.filter(E=>typeof E=="object")?.map(E=>E.$path)||[];Object.entries(M||{}).forEach(([E,h])=>{if(![...T,...$].includes(E))return;if(!("roles"in R))throw new Error("No roles in schema");let C=Array.isArray(h)?[...new Set(h)]:[h],{cardinality:I,playedBy:j}=R.roles[E],_=[...new Set(j?.map(x=>x.thing))]?.flatMap(x=>{let J=l.entities.get(x);return J?ut([...J],C,g,E):[]});if(_?.length){if(_.length===1&&_[0]===g.$id)return;if(I==="ONE"){g[E]=_[0];return}g[E]=_.filter(x=>typeof x=="string"||typeof x=="object"&&x?.$show)}})}});let q=R.linkFields;q&&q.forEach(L=>{let Q=l.relations.get(L.relation),P=L.oppositeLinkFieldsPlayedBy;if(!Q)return null;if(L.target==="relation"){let M=[...Q].reduce((T,$)=>{let E=$.get(L.plays)?.id;if(E&&E===O[0]){let h=$.get(L.relation);if(!h)return T;T[h.entityName]||(T[h.entityName]=new Set),T[h.entityName].add(h.id)}return T},{});return Object.entries(M).map(([T,$])=>{let E=l.entities.get(T);if(!E)return null;let h=ut([...E],[...$.values()],g,L.path).filter(K).filter(yt);if(h.length===0)return null;if(h&&h.length){if(L.cardinality==="ONE")return g[L.path]=h[0],null;g[L.path]=h}return null}),null}return L.target==="role"&&P.forEach(M=>{if(!Q)return;let T=[...Q].reduce(($,E)=>{let h=E.get(L.plays)?.id;if(h&&h===O[0]){let C=E.get(M.plays);if(!C)return $;$[C.entityName]||($[C.entityName]=new Set),$[C.entityName].add(C.id)}return $},{});Object.entries(T).forEach(([$,E])=>{let h=l.entities.get($);if(!h)return;let C=ut([...h],[...E.values()],g,L.path).filter(K).filter(yt);if(C.length!==0&&C&&C.length){if(L.cardinality==="ONE"){g[L.path]=C[0];return}g[L.path]=C}})}),null})}})),d=St(e,i);n.bqlRes=w?d[0]:d};var Mt=require("radash");var rt=async r=>{let{schema:n,bqlRequest:a}=r;if(!a?.query)throw new Error("BQL query not parsed");let{query:i}=a,c="$entity"in i?i.$entity:i.$relation,l=c.defaultDBConnector.path||c.name;if(!c.idFields)throw new Error("No id fields");let[o]=c.idFields,u=`$${l}_id`,p=`, has ${o} ${u};`;i.$id&&(Array.isArray(i.$id)?p+=` ${u} like "${i.$id.join("|")}";`:p+=` ${u} "${i.$id}";`);let y=Ft(c,i),f="roles"in c?(0,Mt.listify)(c.roles,(e,d)=>({path:e,var:`$${e}`,schema:d})):[],w=`match $${l} isa ${l}, has attribute $attribute ${y} ${p} group $${l};`,s=f.map(e=>{if(!e.schema.playedBy||[...new Set(e.schema.playedBy?.map(m=>m.thing))].length!==1)throw new Error("Unsupported: Role played by multiple linkfields or none");let d=e.schema.playedBy[0].thing;return{path:e.path,owner:l,request:`match $${l} (${e.path}: ${e.var} ) isa ${l} ${p} ${e.var} isa ${d}, has id ${e.var}_id; group $${l};`}}),t=c.linkFields?.flatMap(e=>{let d=`$${e.plays}_id`,m=`, has ${o} ${d};`;i.$id&&(Array.isArray(i.$id)?m+=` ${d} like "${i.$id.join("|")}";`:m+=` ${d} "${i.$id}";`);let F=`match $${e.plays} isa ${l}${y} ${m}`,g=e.target==="relation",O=`$${e.relation}`,R=`${g?O:""} (${e.plays}: $${e.plays}`,B=e.oppositeLinkFieldsPlayedBy.map(M=>g?null:`${M.plays}: $${M.plays}`),b=[R,...B].filter(M=>M).join(","),S=n.relations[e.relation].defaultDBConnector.path||e.relation,q=`) isa ${S};`,L=e.oppositeLinkFieldsPlayedBy.map(M=>`$${g?M.thing:M.plays} isa ${M.thing}, has id $${g?M.thing:M.plays}_id;`).join(", "),Q=`group $${e.plays};`,P=`${F} ${b} ${q} ${L} ${Q}`;return{relation:S,entity:l,request:P}});r.tqlRequest={entity:w,...s?.length?{roles:s}:{},...t?.length?{relations:t}:{}}};var qt=async r=>{let{rawBqlRequest:n,schema:a}=r;if(!("$entity"in n)&&!("$relation"in n))throw new Error("No entity specified in query");let i=D(a,n);if(!i)throw new Error(`Thing '${n}' not found in schema`);let{unidentifiedFields:c,localFilters:l,nestedFilters:o}=H(i,n);if(c&&c.length>0)throw new Error(`Unknown fields: [${c.join(",")}] in ${JSON.stringify(n)}`);r.bqlRequest={query:{...r.rawBqlRequest,...i.thingType==="entity"?{$entity:i}:{},...i.thingType==="relation"?{$relation:i}:{},...l?{$localFilters:l}:{},...o?{$nestedFilters:o}:{}}}};var Qt=require("typedb-client"),ot=async(r,n)=>{let{dbHandles:a,bqlRequest:i,tqlRequest:c,config:l}=r;if(!i)throw new Error("BQL request not parsed");if(!c)throw new Error("TQL request not built");if(!c.entity)throw new Error("BQL request error, no entities");let{query:o}=i;if(!o)throw new Error("BQL request is not a query");let u=l.dbConnectors[0].id,p=a.typeDB.get(u)?.session;if(!p?.isOpen())throw new Error("Session is closed");let y=await p.transaction(Qt.TransactionType.READ);if(!y)throw new Error("Can't create transaction");let f=y.query.matchGroup(c.entity),w=c.roles?.map(m=>({...m,stream:y.query.matchGroup(m.request)})),s=c.relations?.map(m=>({...m,stream:y.query.matchGroup(m.request)})),t=await f.collect(),e=await Promise.all(w?.map(async m=>({path:m.path,ownerPath:m.owner,conceptMapGroups:await m.stream.collect()}))||[]),d=await Promise.all(s?.map(async m=>({relation:m.relation,entity:m.entity,conceptMapGroups:await m.stream.collect()}))||[]);await y.close(),n.rawTqlRes={entity:t,...e?.length&&{roles:e},...d?.length&&{relations:d}}};var gt=async(r,n)=>{let{bqlRequest:a,schema:i}=r,{cache:c}=n;if(!a)throw new Error("BQL request not parsed");if(!c)throw new Error("Cache not initialized");let{query:l}=a;if(!l)return;let{$fields:o}=l;if(!("$entity"in l)&&!("$relation"in l))throw new Error("Node attributes not supported");let u="$entity"in l?l.$entity:l.$relation;if(!o||!Array.isArray(o))return;let p=o.filter(t=>typeof t!="string"&&t.$path),y=u.linkFields?.filter(t=>p.findIndex(e=>e.$path===t.path)!==-1).flatMap(t=>t.oppositeLinkFieldsPlayedBy)||[],f="roles"in u?(0,st.listify)(u.roles,(t,e)=>p.findIndex(d=>d.$path===t)!==-1?e:null).flatMap(t=>t?.playedBy).filter(t=>t):[],s=[...y,...f]?.map(t=>{if(!t)return null;let{thing:e}=t,d=it(i.entities,e);return[e,...d].map(m=>{let F=c.entities.get(m);if(!F)return null;let g=Array.from(F.values()).reduce((L,Q)=>("$show"in Q||L.push(Q.$id),L),[]);if(g.length===0)return null;let k=i.entities[m]?{...i.entities[m],thingType:"entity"}:{...i.relations[m],thingType:"relation"},O=o.find(L=>typeof L=="object"&&L.$path===t.plays),R=O?.$id,B=R?Array.isArray(R)?R:[R]:[],b=O?.$filter,q={query:{$id:B.length?B.filter(L=>g.includes(L)):g,$fields:O?.$fields,...k.thingType==="entity"?{$entity:k}:{},...k.thingType==="relation"?{$relation:k}:{},...b?{$localFilters:b}:{}}};return{req:{...r,bqlRequest:q},res:n,pipeline:[rt,ot,Y,gt]}}).filter(K)}).filter(K);if(s?.length)return(0,st.flat)(s)};var N=require("radash");var kt=async r=>{let{bqlRequest:n,schema:a}=r;if(!n)throw new Error("BQL request not parsed");let{mutation:i}=n;if(!i)throw new Error("BQL request is not a mutation");let c=t=>{let e=t.$op,d=t.$tempId||t.$id,m=D(a,t),F=m.defaultDBConnector?.path||t.$entity||t.$relation,{idFields:g}=m;if(!g)throw new Error("no idFields");let k=g[0],O=(0,N.listify)(t,($,E)=>{if($.startsWith("$")||$===k||!E)return"";let h=m.dataFields?.find(j=>j.path===$);if(!h?.path)return"";let I=h.dbPath;if(["TEXT","ID","EMAIL"].includes(h.contentType))return`has ${I} '${E}'`;if(["NUMBER"].includes(h.contentType))return`has ${I} ${E}`;if(h.contentType==="DATE"){if(Number.isNaN(E.valueOf()))throw new Error("Invalid format, Nan Date");return E instanceof Date?`has ${I} ${E.toISOString().replace("Z","")}`:`has ${I} ${new Date(E).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${h.contentType}`)}).filter($=>$),R=`$${d}-atts`,B=(0,N.listify)(t,($,E)=>{if($.startsWith("$")||$===k||!E)return"";let h=m.dataFields?.find(j=>j.path===$);if(!h?.path)return"";let I=h.dbPath;return`{${R} isa ${I};}`}).filter($=>$),b=t[k]||t.$id,S=m.dataFields?.find($=>$.path===k),q=t.$op==="create"?S?.default?.value():null,L=b||q,Q=L?[`has ${k} '${L}'`]:[],P=[...Q,...O].filter($=>$).join(","),M=()=>{if(e==="delete"||e==="unlink"||e==="noop")return`$${d} isa ${[F,...Q].filter($=>$).join(",")};`;if(e==="update"){if(!B.length)throw new Error("update without attributes");return`$${d} isa ${[F,...Q].filter($=>$).join(",")}, has ${R};
1
+ "use strict";var Wt=Object.create;var tt=Object.defineProperty;var Gt=Object.getOwnPropertyDescriptor;var Ht=Object.getOwnPropertyNames;var Ut=Object.getPrototypeOf,_t=Object.prototype.hasOwnProperty;var Vt=(o,n)=>{for(var s in n)tt(o,s,{get:n[s],enumerable:!0})},bt=(o,n,s,i)=>{if(n&&typeof n=="object"||typeof n=="function")for(let d of Ht(n))!_t.call(o,d)&&d!==s&&tt(o,d,{get:()=>n[d],enumerable:!(i=Gt(n,d))||i.enumerable});return o};var ct=(o,n,s)=>(s=o!=null?Wt(Ut(o)):{},bt(n||!o||!o.__esModule?tt(s,"default",{value:o,enumerable:!0}):s,o)),Jt=o=>bt(tt({},"__esModule",{value:!0}),o);var ee={};Vt(ee,{default:()=>te});module.exports=Jt(ee);var jt=require("radash"),dt=require("typedb-client");var ft={query:{simplifiedLinks:!0},mutation:{}};var ht=ct(require("immer")),et=require("object-traversal"),z=require("radash"),Et=(o,n,s)=>s?n:`${o}\xB7${n}`,Rt=o=>{let n=o.split("\xB7");return n[n.length-1]},nt=(o,n)=>Object.values(Object.fromEntries(Object.entries(o).filter(([s,i])=>n(s,i))))[0],G=(o,n)=>Object.fromEntries(Object.entries(o).filter(([s,i])=>n(s,i))),Lt=o=>{let n=[],s=(0,ht.default)(o,d=>(0,et.traverse)(d,({key:l,value:r,meta:$})=>{if($.depth===2&&(l&&(r.dataFields=r.dataFields?.map(p=>({...p,dbPath:Et(l,p.path,p.shared)}))),r.extends)){let p=d.entities[r.extends]||d.relations[r.extends];if(r.allExtends=[r.extends,...p.allExtends||[]],r.idFields=p.idFields?(r.idFields||[]).concat(p.idFields):r.idFields,r.dataFields=p.dataFields?(r.dataFields||[]).concat(p.dataFields.map(y=>{let f=r.extends,w=o.entities[f]||o.relations[f];for(;!w.dataFields?.find(a=>a.path===y.path);)f=w.extends,w=o.entities[f]||o.relations[f];return{...y,dbPath:Et(f,y.path,y.shared)}})):r.dataFields,r.linkFields=p.linkFields?(r.linkFields||[]).concat(p.linkFields):r.linkFields,"roles"in p){let y=r,f=p;y.roles=y.roles||{},y.roles={...y.roles,...f.roles},Object.keys(y.roles).length===0&&(y.roles={})}}},{traversalType:"breadth-first"}));return(0,et.traverse)(o,({key:d,value:l,meta:r})=>{if(d==="linkFields"){let p=(()=>{if(!r.nodePath)throw new Error("No path");let[f,w]=r.nodePath.split(".");return{thing:w,thingType:f==="entities"?"entity":f==="relations"?"relation":""}})(),y=Array.isArray(l)?l.map(f=>({...f,...p})):[{...l,...p}];n.push(...y)}}),(0,ht.default)(s,d=>(0,et.traverse)(d,({value:l,key:r,meta:$})=>{if($.depth===2&&l.idFields&&!l.id){l.name=r;let p=()=>{if($.nodePath?.split(".")[0]==="entities")return"entity";if($.nodePath?.split(".")[0]==="relations")return"relation";throw new Error("Unsupported node attributes")};l.thingType=p(),l.computedFields=[],"roles"in l&&Object.entries(l.roles).forEach(([f,w])=>{w.playedBy=n.filter(a=>a.relation===r&&a.plays===f)||[],w.name=f}),"linkFields"in l&&l.linkFields&&l.linkFields?.forEach(f=>{if(f.target==="relation"){f.oppositeLinkFieldsPlayedBy=[{plays:f.path,thing:f.relation,thingType:"relation"}];return}let w=n.filter(t=>t.relation===f.relation&&t.plays!==f.plays)||[];f.oppositeLinkFieldsPlayedBy=w;let{filter:a}=f;f.oppositeLinkFieldsPlayedBy=f.oppositeLinkFieldsPlayedBy.filter(t=>t.target==="role"),a&&Array.isArray(a)&&(f.oppositeLinkFieldsPlayedBy=f.oppositeLinkFieldsPlayedBy.filter(t=>a.some(e=>t.thing===e.$role)),f.oppositeLinkFieldsPlayedBy=f.oppositeLinkFieldsPlayedBy.filter(t=>a.some(e=>t.thing===e.$thing))),a&&!Array.isArray(a)&&(f.oppositeLinkFieldsPlayedBy=f.oppositeLinkFieldsPlayedBy.filter(t=>t.$role===a.$role),f.oppositeLinkFieldsPlayedBy=f.oppositeLinkFieldsPlayedBy.filter(t=>t.thing===a.$thing))})}if(typeof l=="object"&&"playedBy"in l){if([...new Set(l.playedBy?.map(p=>p.thing))].length>1)throw new Error(`Unsupported: roleFields can be only played by one thing. Role: ${r} path:${$.nodePath}`);if(l.playedBy.length===0)throw new Error(`Unsupported: roleFields should be played at least by one thing. Role: ${r}, path:${$.nodePath}`)}if($.depth===4&&(l.default||l.computedValue)){let[p,y]=$.nodePath?.split(".")||[];d[p][y].computedFields.push(l.path)}}))},D=(o,n)=>{if(n.$entity){if(!(n.$entity in o.entities))throw new Error(`Missing entity '${n.$entity}' in the schema`);return o.entities[n.$entity]}if(n.$relation){if(!(n.$relation in o.relations))throw new Error(`Missing relation '${n.$relation}' in the schema`);return o.relations[n.$relation]}throw new Error(`Wrong schema or query for ${JSON.stringify(n)}`)},H=(o,n)=>{let s=o.dataFields?.map(e=>e.path)||[],i=o.linkFields?.map(e=>e.path)||[],d="roles"in o?(0,z.listify)(o.roles,e=>e):[],l=[...s||[],...i||[],...d||[]],$=[...["$entity","$op","$id","$tempId","$relation","$parentKey","$filter","$fields"],...l];if(!n)return{fields:l,dataFields:s,roleFields:d,linkFields:i};let p=n.$fields?n.$fields.map(e=>{if(typeof e=="string")return e;if("$path"in e&&typeof e.$path=="string")return e.$path;throw new Error(" Wrongly structured query")}):(0,z.listify)(n,e=>e),y=n.$filter?(0,z.listify)(n.$filter,e=>e.toString().startsWith("$")?void 0:e.toString()).filter(e=>e&&s?.includes(e)):[],f=n.$filter?(0,z.listify)(n.$filter,e=>e.toString().startsWith("$")?void 0:e.toString()).filter(e=>e&&[...d||[],...i||[]].includes(e)):[],w=[...p,...y].filter(e=>!$.includes(e)).filter(e=>e),a=n.$filter?G(n.$filter,(e,c)=>y.includes(e)):{},t=n.$filter?G(n.$filter,(e,c)=>f.includes(e)):{};return{fields:l,dataFields:s,roleFields:d,linkFields:i,usedFields:p,usedLinkFields:i.filter(e=>p.includes(e)),usedRoleFields:d.filter(e=>p.includes(e)),unidentifiedFields:w,...y.length?{localFilters:a}:{},...f.length?{nestedFilters:t}:{}}},Ft=(o,n)=>{let s=n.$localFilters&&(0,z.listify)(n.$localFilters,(d,l)=>`has ${o.dataFields?.find($=>$.path===d)?.dbPath} '${l}'`);return s?.length?`, ${s.join(",")}`:""};function K(o){return o!==null}var it=(o,n)=>Object.values(o).reduce((s,i)=>(i.extends===n&&s.push(i.name),s),[]);function yt(o){return typeof o=="string"||!!o.$show}var st=require("radash");var A=require("radash");var zt=(o,n)=>o.map(i=>{let d=[...i.conceptMaps],r=i.owner.asThing().type.label.name,$=n.entities[r]?n.entities[r]:n.relations[r];if(!$.idFields)throw new Error(`No idFields defined for ${r}`);let p=n.entities[r]?"entity":"relation",y=d.map(w=>{let a=w.get("attribute")?.asAttribute();return a?[Rt(a.type.label.name),a.value]:[]}),f=Object.fromEntries(y);return{...f,[`$${p}`]:r,$id:f[$.idFields[0]]}}),Kt=(o,n,s)=>o.flatMap(d=>d.conceptMaps.map(r=>{let $=new Map;return n.forEach(p=>{let y=r.get(`${p}_id`)?.asAttribute().value.toString(),f=r.get(p),w=f?.isEntity()?f.asEntity().type.label.name:f?.asRelation().type.label.name,t={id:y,entityName:(()=>w?(s.entities[w]??s.relations[w]).allExtends?.includes(p)?p:w:p)()};y&&$.set(p,t)}),$})),Yt=(o,n,s)=>o.flatMap(d=>d.conceptMaps.map(r=>{let $=r.get(`${n}_id`)?.asAttribute().value.toString(),p=r.get(`${s}_id`)?.asAttribute().value.toString();return{ownerId:$,path:s,roleId:p}})),Zt=(o,n)=>{let s=(0,A.listify)(o.roles,(i,d)=>{if([...new Set(d.playedBy?.map($=>$.thing))].length!==1)throw new Error("a role can be played by two entities throws the same relation");if(!d.playedBy)throw new Error("Role not being played by nobody");let l=d.playedBy[0].plays,r=it(n.entities,l);return[l,...r]});return(0,A.unique)((0,A.flat)(s))},Y=async(o,n)=>{let{schema:s,bqlRequest:i,config:d,tqlRequest:l}=o,{rawTqlRes:r}=n;if(i){if(!r)throw new Error("TQL query not executed")}else throw new Error("BQL request not parsed");let{query:$}=i;if(!$){if(r.insertions?.length===0&&!l?.deletions)throw new Error("Nothing has changed in DB, probably one of the ids specified in the mutation does not exist");let{mutation:a}=i;if(!a)throw new Error("TQL mutation not executed");let e=[...a.things,...a.edges].map(c=>{let u=r.insertions?.find(F=>F.get(`${c.$tempId||c.$id}`))?.get(`${c.$tempId||c.$id}`);if(c.$op==="create"||c.$op==="update"||c.$op==="link"){if(!u?.asThing().iid)throw new Error(`Thing not received on mutation: ${JSON.stringify(c)}`);let F=u?.asThing().iid;return d.mutation?.noMetadata?(0,A.mapEntries)(c,(g,k)=>[g.toString().startsWith("$")?Symbol.for(g):g,k]):{$dbId:F,...c}}if(c.$op==="delete"||c.$op==="unlink")return c;if(c.$op!=="noop")throw new Error(`Unsupported op ${c.$op}`)}).filter(c=>c);n.bqlRes=e.length>1?e:e[0];return}if(!r.entity)throw new Error("TQL query not executed");let p=zt(r.entity,s),y=r.relations?.map(a=>{let t=s.relations[a.relation],e=Zt(t,s),c=Kt(a.conceptMapGroups,[...e,t.name],s);return{name:a.relation,links:c}}),f=r.roles?.map(a=>({name:a.ownerPath,links:Yt(a.conceptMapGroups,a.ownerPath,a.path)})),w=n.cache||{entities:new Map,relations:new Map,roleLinks:new Map};p.forEach(a=>{let t=a.$entity||a.$relation,e=a.$id,c=w.entities.get(t)||new Map;c.set(e,{...a,$show:!0}),w.entities.set(t,c)}),y?.forEach(a=>{let t=a.name,e=w.relations.get(t)||[];e.push(...a.links),w.relations.set(t,e),a.links.forEach(c=>{[...c.entries()].forEach(([u,{entityName:F,id:g}])=>{let k=w.entities.get(F)||new Map,R={[s.entities[F]?.thingType||s.relations[F].thingType]:F,$id:g,...k.get(g)};k.set(g,R),w.entities.set(F,k)})})}),f?.forEach(a=>{let t=s.relations[a.name]||s.entities[a.name];a.links.forEach(e=>{let c=w.roleLinks.get(e.ownerId)||{},u=c[e.path];u?(0,A.isArray)(u)?u.push(e.roleId):(0,A.isString)(u)&&u!==e.roleId&&(u=[u,e.roleId]):u=e.roleId,c[e.path]=u,w.roleLinks.set(e.ownerId,c),t.roles[e.path].playedBy?.forEach(F=>{let g=w.entities.get(F.thing)||new Map,k={$entity:F.thing,$id:e.roleId,...g.get(e.roleId)};g.set(e.roleId,k),w.entities.set(F.thing,g)})})}),n.cache=w};var Xt=require("radash");var mt=ct(require("immer")),$t=require("object-traversal"),Z=require("radash");var St=(o,n)=>(0,mt.default)(o,s=>(0,$t.traverse)(s,({value:i})=>{if(Array.isArray(i)||typeof i!="object")return;i.$fields&&delete i.$fields,i.$filter&&delete i.$filter,i.$show&&delete i.$show,n.query?.noMetadata&&(i.$entity||i.$relation)&&(delete i.$entity,delete i.$relation,delete i.$id),Object.getOwnPropertySymbols(o).forEach(l=>{delete i[l]})})),ut=(o,n,s,i)=>o.map(([d,l])=>{if(!n||!n.includes(d))return null;if(!s.$fields||s.$fields.includes(i))return d;let r=s.$fields.find($=>(0,Z.isObject)($)&&$.$path===i);if(r){let $={...G(l,(y,f)=>y.startsWith("$"))},p=r.$fields?{...$,$fields:r.$fields}:$;if(r.$id){if(Array.isArray(r.$id))return r.$id.includes(d)?p:null;if(r.$id===d)return p}return p}return null}).filter(d=>d),Tt=async(o,n)=>{let{bqlRequest:s,config:i,schema:d}=o,{cache:l}=n;if(!s)throw new Error("BQL request not parsed");let{query:r}=s;if(!r){n.bqlRes=St(n.bqlRes,i);return}if(!l)return;let $="$entity"in r?r.$entity:r.$relation,p=l.entities.get($.name);if(!p){n.bqlRes=null;return}let f=(0,Z.listify)(r.$filter,u=>u).some(u=>$.dataFields?.find(F=>F.path===u)?.validations?.unique),w=!Array.isArray(s.query)&&(s.query?.$id&&!Array.isArray(s.query?.$id)||f);if(Array.isArray(o.rawBqlRequest))throw new Error("Query arrays not implemented yet");let a=p,t=[...a].length?[...a].map(([u,F])=>({...o.rawBqlRequest,$id:u})):o.rawBqlRequest,e=(0,mt.default)(t,u=>(0,$t.traverse)(u,({value:F})=>{let g=F;if(!g?.$entity&&!g?.$relation)return;let k="$entity"in g?g.$entity:g.$relation;if(k){let O=Array.isArray(g.$id)?g.$id:[g.$id],R="$relation"in g?d.relations[g.$relation]:d.entities[g.$entity],{dataFields:B,roleFields:b}=H(R),S=l.entities.get(k);if(!S)return;[...S].forEach(([L,Q])=>{if(O.includes(L)){let P=g.$fields?g.$fields:B;(0,Z.listify)(Q,(E,h)=>{E.startsWith("$")||!P?.includes(E)||(g[E]=h)});let M=l.roleLinks.get(L),T=g.$fields?g.$fields.filter(E=>typeof E=="string"):b,m=g.$fields?.filter(E=>typeof E=="object")?.map(E=>E.$path)||[];Object.entries(M||{}).forEach(([E,h])=>{if(![...T,...m].includes(E))return;if(!("roles"in R))throw new Error("No roles in schema");let C=Array.isArray(h)?[...new Set(h)]:[h],{cardinality:I,playedBy:j}=R.roles[E],_=[...new Set(j?.map(x=>x.thing))]?.flatMap(x=>{let J=l.entities.get(x);return J?ut([...J],C,g,E):[]});if(_?.length){if(_.length===1&&_[0]===g.$id)return;if(I==="ONE"){g[E]=_[0];return}g[E]=_.filter(x=>typeof x=="string"||typeof x=="object"&&x?.$show)}})}});let q=R.linkFields;q&&q.forEach(L=>{let Q=l.relations.get(L.relation),P=L.oppositeLinkFieldsPlayedBy;if(!Q)return null;if(L.target==="relation"){let M=[...Q].reduce((T,m)=>{let E=m.get(L.plays)?.id;if(E&&E===O[0]){let h=m.get(L.relation);if(!h)return T;T[h.entityName]||(T[h.entityName]=new Set),T[h.entityName].add(h.id)}return T},{});return Object.entries(M).map(([T,m])=>{let E=l.entities.get(T);if(!E)return null;let h=ut([...E],[...m.values()],g,L.path).filter(K).filter(yt);if(h.length===0)return null;if(h&&h.length){if(L.cardinality==="ONE")return g[L.path]=h[0],null;g[L.path]=h}return null}),null}return L.target==="role"&&P.forEach(M=>{if(!Q)return;let T=[...Q].reduce((m,E)=>{let h=E.get(L.plays)?.id;if(h&&h===O[0]){let C=E.get(M.plays);if(!C)return m;m[C.entityName]||(m[C.entityName]=new Set),m[C.entityName].add(C.id)}return m},{});Object.entries(T).forEach(([m,E])=>{let h=l.entities.get(m);if(!h)return;let C=ut([...h],[...E.values()],g,L.path).filter(K).filter(yt);if(C.length!==0&&C&&C.length){if(L.cardinality==="ONE"){g[L.path]=C[0];return}g[L.path]=C}})}),null})}})),c=St(e,i);n.bqlRes=w?c[0]:c};var Mt=require("radash");var rt=async o=>{let{schema:n,bqlRequest:s}=o;if(!s?.query)throw new Error("BQL query not parsed");let{query:i}=s,d="$entity"in i?i.$entity:i.$relation,l=d.defaultDBConnector.path||d.name;if(!l)throw new Error(`No thing path in ${JSON.stringify(d)}`);if(!d.idFields)throw new Error("No id fields");let[r]=d.idFields,$=`$${l}_id`,p=`, has ${r} ${$};`;i.$id&&(Array.isArray(i.$id)?p+=` ${$} like "${i.$id.join("|")}";`:p+=` ${$} "${i.$id}";`);let y=Ft(d,i),f="roles"in d?(0,Mt.listify)(d.roles,(e,c)=>({path:e,var:`$${e}`,schema:c})):[],w=`match $${l} isa ${l}, has attribute $attribute ${y} ${p} group $${l};`,a=f.map(e=>{if(!e.schema.playedBy||[...new Set(e.schema.playedBy?.map(u=>u.thing))].length!==1)throw new Error("Unsupported: Role played by multiple linkfields or none");let c=e.schema.playedBy[0].thing;return{path:e.path,owner:l,request:`match $${l} (${e.path}: ${e.var} ) isa ${l} ${p} ${e.var} isa ${c}, has id ${e.var}_id; group $${l};`}}),t=d.linkFields?.flatMap(e=>{let c=`$${e.plays}_id`,u=`, has ${r} ${c};`;i.$id&&(Array.isArray(i.$id)?u+=` ${c} like "${i.$id.join("|")}";`:u+=` ${c} "${i.$id}";`);let F=`match $${e.plays} isa ${l}${y} ${u}`,g=e.target==="relation",O=`$${e.relation}`,R=`${g?O:""} (${e.plays}: $${e.plays}`,B=e.oppositeLinkFieldsPlayedBy.map(M=>g?null:`${M.plays}: $${M.plays}`),b=[R,...B].filter(M=>M).join(",");if(n.relations[e.relation]===void 0)throw new Error(`Relation ${e.relation} not found in schema`);let S=n.relations[e.relation].defaultDBConnector.path||e.relation,q=`) isa ${S};`,L=e.oppositeLinkFieldsPlayedBy.map(M=>`$${g?M.thing:M.plays} isa ${M.thing}, has id $${g?M.thing:M.plays}_id;`).join(", "),Q=`group $${e.plays};`,P=`${F} ${b} ${q} ${L} ${Q}`;return{relation:S,entity:l,request:P}});o.tqlRequest={entity:w,...a?.length?{roles:a}:{},...t?.length?{relations:t}:{}}};var qt=async o=>{let{rawBqlRequest:n,schema:s}=o;if(!("$entity"in n)&&!("$relation"in n))throw new Error("No entity specified in query");let i=D(s,n);if(!i)throw new Error(`Thing '${n}' not found in schema`);let{unidentifiedFields:d,localFilters:l,nestedFilters:r}=H(i,n);if(d&&d.length>0)throw new Error(`Unknown fields: [${d.join(",")}] in ${JSON.stringify(n)}`);o.bqlRequest={query:{...o.rawBqlRequest,...i.thingType==="entity"?{$entity:i}:{},...i.thingType==="relation"?{$relation:i}:{},...l?{$localFilters:l}:{},...r?{$nestedFilters:r}:{}}}};var Qt=require("typedb-client"),ot=async(o,n)=>{let{dbHandles:s,bqlRequest:i,tqlRequest:d,config:l}=o;if(!i)throw new Error("BQL request not parsed");if(!d)throw new Error("TQL request not built");if(!d.entity)throw new Error("BQL request error, no entities");let{query:r}=i;if(!r)throw new Error("BQL request is not a query");let $=l.dbConnectors[0].id,p=s.typeDB.get($)?.session;if(!p?.isOpen())throw new Error("Session is closed");let y=await p.transaction(Qt.TransactionType.READ);if(!y)throw new Error("Can't create transaction");let f=y.query.matchGroup(d.entity),w=d.roles?.map(u=>({...u,stream:y.query.matchGroup(u.request)})),a=d.relations?.map(u=>({...u,stream:y.query.matchGroup(u.request)})),t=await f.collect(),e=await Promise.all(w?.map(async u=>({path:u.path,ownerPath:u.owner,conceptMapGroups:await u.stream.collect()}))||[]),c=await Promise.all(a?.map(async u=>({relation:u.relation,entity:u.entity,conceptMapGroups:await u.stream.collect()}))||[]);await y.close(),n.rawTqlRes={entity:t,...e?.length&&{roles:e},...c?.length&&{relations:c}}};var gt=async(o,n)=>{let{bqlRequest:s,schema:i}=o,{cache:d}=n;if(!s)throw new Error("BQL request not parsed");if(!d)throw new Error("Cache not initialized");let{query:l}=s;if(!l)return;let{$fields:r}=l;if(!("$entity"in l)&&!("$relation"in l))throw new Error("Node attributes not supported");let $="$entity"in l?l.$entity:l.$relation;if(!r||!Array.isArray(r))return;let p=r.filter(t=>typeof t!="string"&&t.$path),y=$.linkFields?.filter(t=>p.findIndex(e=>e.$path===t.path)!==-1).flatMap(t=>t.oppositeLinkFieldsPlayedBy)||[],f="roles"in $?(0,st.listify)($.roles,(t,e)=>p.findIndex(c=>c.$path===t)!==-1?e:null).flatMap(t=>t?.playedBy).filter(t=>t):[],a=[...y,...f]?.map(t=>{if(!t)return null;let{thing:e}=t,c=it(i.entities,e);return[e,...c].map(u=>{let F=d.entities.get(u);if(!F)return null;let g=Array.from(F.values()).reduce((L,Q)=>("$show"in Q||L.push(Q.$id),L),[]);if(g.length===0)return null;let k=i.entities[u]?{...i.entities[u],thingType:"entity"}:{...i.relations[u],thingType:"relation"},O=r.find(L=>typeof L=="object"&&L.$path===t.plays),R=O?.$id,B=R?Array.isArray(R)?R:[R]:[],b=O?.$filter,q={query:{$id:B.length?B.filter(L=>g.includes(L)):g,$fields:O?.$fields,...k.thingType==="entity"?{$entity:k}:{},...k.thingType==="relation"?{$relation:k}:{},...b?{$localFilters:b}:{}}};return{req:{...o,bqlRequest:q},res:n,pipeline:[rt,ot,Y,gt]}}).filter(K)}).filter(K);if(a?.length)return(0,st.flat)(a)};var N=require("radash");var kt=async o=>{let{bqlRequest:n,schema:s}=o;if(!n)throw new Error("BQL request not parsed");let{mutation:i}=n;if(!i)throw new Error("BQL request is not a mutation");let d=t=>{let e=t.$op,c=t.$tempId||t.$id,u=D(s,t),F=u.defaultDBConnector?.path||t.$entity||t.$relation,{idFields:g}=u;if(!g)throw new Error("no idFields");let k=g[0],O=(0,N.listify)(t,(m,E)=>{if(m.startsWith("$")||m===k||!E)return"";let h=u.dataFields?.find(j=>j.path===m);if(!h?.path)return"";let I=h.dbPath;if(["TEXT","ID","EMAIL"].includes(h.contentType))return`has ${I} '${E}'`;if(["NUMBER"].includes(h.contentType))return`has ${I} ${E}`;if(h.contentType==="DATE"){if(Number.isNaN(E.valueOf()))throw new Error("Invalid format, Nan Date");return E instanceof Date?`has ${I} ${E.toISOString().replace("Z","")}`:`has ${I} ${new Date(E).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${h.contentType}`)}).filter(m=>m),R=`$${c}-atts`,B=(0,N.listify)(t,(m,E)=>{if(m.startsWith("$")||m===k||!E)return"";let h=u.dataFields?.find(j=>j.path===m);if(!h?.path)return"";let I=h.dbPath;return`{${R} isa ${I};}`}).filter(m=>m),b=t[k]||t.$id,S=u.dataFields?.find(m=>m.path===k),q=t.$op==="create"?S?.default?.value():null,L=b||q,Q=L?[`has ${k} '${L}'`]:[],P=[...Q,...O].filter(m=>m).join(","),M=()=>{if(e==="delete"||e==="unlink"||e==="noop")return`$${c} isa ${[F,...Q].filter(m=>m).join(",")};`;if(e==="update"){if(!B.length)throw new Error("update without attributes");return`$${c} isa ${[F,...Q].filter(m=>m).join(",")}, has ${R};
2
2
  ${B.join(" or ")};
3
- `}return""},T=()=>e==="update"||e==="link"||e==="noop"?`$${d} isa ${[F,...Q].filter($=>$).join(",")};`:"";if(t.$entity||t.$relation)return{op:e,deletionMatch:M(),insertionMatch:T(),insertion:e==="create"?`$${d} isa ${[F,P].filter($=>$).join(",")};`:e==="update"&&O.length?`$${d} ${O.join(",")};`:"",deletion:e==="delete"?`$${d} isa ${F};`:e==="update"&&B.length?`$${d} has ${R};`:""};throw new Error("in attributes")},l=t=>{let e=t.$op,d=t.$tempId||t.$id,m=D(a,t),F=m.defaultDBConnector?.path||t.$relation,g="roles"in m?(0,N.listify)(m.roles,M=>M):[],k=t.$relation&&"roles"in m&&(0,N.mapEntries)(m.roles,(M,T)=>[M,T.dbConnector?.path||M]),O=(0,N.listify)(t,(M,T)=>{if(!g.includes(M))return null;if(!("roles"in m))throw new Error("This should have roles! ");let $=k[M];return Array.isArray(T)?T.map(E=>({path:$,id:E})):{path:$,id:T}}).filter(M=>M).flat(),R=O.map(M=>{if(!M?.path)throw new Error("Object without path");return`${M.path}: $${M.id}`}),B=O.length>0?`( ${R.join(" , ")} )`:"",b=B?`$${d} ${B} ${t[Symbol.for("edgeType")]==="linkField"||e==="delete"||e==="unlink"?`isa ${F}`:""}`:"",S=`$${d} ${t[Symbol.for("edgeType")]==="linkField"||e==="delete"?`isa ${F}`:""}`,q=()=>b?e==="link"?`${b};`:e==="create"?`${b}, has id '${d}';`:"":"",L=()=>b&&e==="noop"?`${b};`:"",Q=()=>b?e==="delete"?`${b};`:e==="noop"?`${b};`:"":"",P=()=>b?e==="delete"?`${S};`:e==="unlink"?`$${d} ${B};`:"":"";return{deletionMatch:Q(),insertionMatch:L(),deletion:P(),insertion:q(),op:""}},o=(t,e)=>{let d=e==="edges"?l:c;if(Array.isArray(t))return t.map(R=>{let{preDeletionBatch:B,insertionMatch:b,deletionMatch:S,insertion:q,deletion:L}=d(R);return(0,N.shake)({preDeletionBatch:B,insertionMatch:b,deletionMatch:S,insertion:q,deletion:L},Q=>!Q)}).filter(R=>R);let{preDeletionBatch:m,insertionMatch:F,deletionMatch:g,insertion:k,deletion:O}=d(t);return(0,N.shake)({preDeletionBatch:m,insertionMatch:F,deletionMatch:g,insertion:k,deletion:O},R=>!R)},u=o(i.things),p=Array.isArray(u)?u:[u],y=o(i.edges,"edges"),f=Array.isArray(y)?y:[y],w=[...p,...f],s=(0,N.shake)({insertionMatches:w.map(t=>t.insertionMatch).join(" ").trim(),deletionMatches:w.map(t=>t.deletionMatch).join(" ").trim(),insertions:w.map(t=>t.insertion).join(" ").trim(),deletions:w.map(t=>t.deletion).join(" ").trim()},t=>!t);r.tqlRequest=s};var X=ct(require("immer")),v=require("object-traversal"),V=require("radash"),Bt=require("uuid");var Ot=async r=>{let{rawBqlRequest:n,schema:a}=r,c=(u=>(0,X.default)(u,p=>(0,v.traverse)(p,({value:y,meta:f,key:w})=>{if((0,V.isObject)(y)){if(y.$arrayOp)throw new Error("Array op not supported yet");if(w==="$filter"||f.nodePath?.includes(".$filter."))return;let s=y,t=D(a,y),d=f.nodePath?.split(".")?.filter(B=>Number.isNaN(parseInt(B,10))).join(".");if(!t)throw new Error(`Schema not found for ${y.$entity||y.$relation}`);s[Symbol.for("bzId")]=(0,Bt.v4)(),s[Symbol.for("schema")]=t,s[Symbol.for("dbId")]=t.defaultDBConnector.id;let{usedLinkFields:m,usedRoleFields:F}=H(t,s),g=m.map(B=>({fieldType:"linkField",path:B,schema:t.linkFields.find(b=>b.path===B)})),k=t.thingType==="relation"?F.map(B=>({fieldType:"roleField",path:B,schema:nt(t.roles,b=>b===B)})):[];if(g.some(B=>B.schema?.target==="role")&&g.some(B=>B.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 O=k.filter(B=>[...new Set(B.schema.playedBy?.map(b=>b.thing))].length!==1);if(O.length>1)throw new Error(`Field: ${O[0].path} - If a role can be played by multiple things, you must specify the thing in the mutation: ${JSON.stringify(O[0].schema.playedBy)}. Schema: ${JSON.stringify(O[0].schema)}`);let R=f.nodePath;if([...g,...k].forEach(B=>{let b=s[B.path];if(b===void 0)return;let S=(B.fieldType==="roleField",B.schema);if(!S)throw new Error(`Field ${B.path} not found in schema`);let q=B.fieldType==="roleField"?S?.playedBy[0]:S,Q=(()=>S&&"relation"in S&&q?.relation===s.$relation?"$self":q?.relation?q?.relation:"$self")(),P=Q==="$self"?t:a.relations[Q];if(nt(P.roles,(h,C)=>h===B.path)?.playedBy?.length===0)throw new Error(`unused role: ${R}.${B.path}`);if(!S)throw new Error(`Field ${B.path} not found in schema`);let T=B.fieldType==="linkField"?S?.oppositeLinkFieldsPlayedBy:S?.playedBy;if(!T)throw new Error(`No opposite fields found for ${JSON.stringify(S)}`);if([...new Set(T?.map(h=>h.thing))].length>1)throw new Error(`Field: ${B.path} - If a role can be played by multiple things, you must specify the thing in the mutation: ${JSON.stringify(T)}. Schema: ${JSON.stringify(S)}`);if(S.cardinality==="ONE"&&Array.isArray(b))throw new Error("Can't have an array in a cardinality === ONE link field");if(S.cardinality==="MANY"&&b!==null&&!Array.isArray(b)&&!b.$arrayOp)throw new Error(`${B.fieldType==="linkField"?S.path:S.name} is a cardinality === MANY thing. Use an array or a $arrayOp object`);if(b?.$entity||b?.$relation)return;let $=T[0],E={[`$${$.thingType}`]:$.thing,[Symbol.for("relation")]:Q,[Symbol.for("edgeType")]:"plays"in S?"linkField":"roleField",[Symbol.for("parent")]:{path:R,...s.$id?{$id:s.$id}:{},...s.$tempId?{$tempId:s.$tempId}:{},...s.filter?{filter:s.filter}:{},links:T},[Symbol.for("role")]:$.plays,[Symbol.for("oppositeRole")]:"plays"in S?S.plays:void 0,[Symbol.for("relFieldSchema")]:S};if((0,V.isObject)(b)&&(t.thingType==="relation"&&b.$tempId?s[B.path]=b.$tempId:s[B.path]={...E,...b}),Array.isArray(b))if(b.every(h=>(0,V.isObject)(h)))s[B.path]=b.map(h=>h.$tempId&&t.thingType==="relation"&&(h.$op==="link"||!h.$op)?h.$tempId:{...E,...h});else if(b.every(h=>typeof h=="string"))s[B.path]=b.map(h=>({...E,$op:"replace",$id:h}));else throw new Error(`Invalid array value for ${B.path}`);if(typeof b=="string"&&(s[B.path]={...E,$op:s.$op==="create"?"link":"replace",$id:b}),b===null){let h={...E,$op:"unlink"};s[B.path]=S.cardinality==="MANY"?[h]:h}}),!d&&!s.$entity&&!s.$relation)throw new Error("Root things must specify $entity or $relation")}})))(n),o=(u=>(0,X.default)(u,p=>(0,v.traverse)(p,({parent:y,key:f,value:w,meta:s})=>{if((0,V.isObject)(w)){if(Object.keys(w).length===0)throw new Error("Empty object!");if(f==="$filter"||s.nodePath?.includes(".$filter."))return;let t=w,e=s.nodePath?.split("."),d=e?.filter(I=>Number.isNaN(parseInt(I,10))).join("."),m=d?Array.isArray(y)?e?.slice(0,-1).join("."):s.nodePath:s.nodePath||"",F=D(a,t),{unidentifiedFields:g,dataFields:k,roleFields:O,linkFields:R}=H(F,t),B=(0,X.current)(t)[Symbol.for("parent")],b=d&&B.path,q=(b?(0,v.getNodeByPath)(p,b):p)?.$op;if(d&&!q)throw new Error("Error: Parent $op not detected");let L=t[Symbol.for("relFieldSchema")];if(q!=="create"&&t.$op==="replace")throw new Error("Unsupported: For replaces, please do an unlink + a link instead");let Q=Object.keys(t).some(I=>k?.includes(I)),P=Object.keys(t).some(I=>[...O,...R].includes(I)),M=()=>{if(t.$op)return t.$op;if(d&&!t.$id&&!t.$tempId&&q!=="create"&&L.cardinality==="ONE")throw new Error(`Please specify if it is a create or an update: ${JSON.stringify(t)} `);if(t.$tempId&&d)return"link";if(t.$tempId&&!d)return"create";if((t.$id||t.$filter)&&Q)return"update";if((t.$id||t.$filter)&&d&&!Q&&!P)return"link";if(!t.$filter&&!t.$id&&!t.$tempId)return"create";if((t.$id||t.$filter)&&!Q&&P)return"noop";throw new Error("Wrong op")};if(t.$op||(t.$op=M()),y||(t.$parentKey=""),typeof y=="object"&&(Array.isArray(y)&&(t[Symbol.for("index")]=f),t[Symbol.for("path")]=m,t[Symbol.for("isRoot")]=!d,t[Symbol.for("depth")]=d?.split(".").length),!t.$entity&&!t.$relation)throw new Error(`Node ${JSON.stringify(t)} without $entity/$relation`);let{idFields:T,computedFields:$}=F;if(!T)throw new Error("No idFields found");let E=T[0],h=(0,V.listify)(t,(I,j)=>j?I:void 0);if($.filter(I=>!h.includes(I)).forEach(I=>{let j=F.dataFields?.find(W=>W.path===I),_=F.linkFields?.find(W=>W.path===I)?.oppositeLinkFieldsPlayedBy[0],x="roles"in F?nt(F.roles,(W,ne)=>W===I):void 0,J=j||_||x;if(!J)throw new Error(`no field Def for ${I}`);if(I===E&&t.$op==="create"&&!t[I]){let W="default"in J?J.default?.value():void 0;if(!W)throw new Error(`No default value for ${I}`);t[I]=W,t.$id=W}}),!t.$id)if(t[E])t.$id=t[E];else{if(t.$op==="create")throw new Error(`No id found for ${JSON.stringify(t)}`);t.$tempId=`all-${(0,Bt.v4)()}`}if(g.length>0)throw new Error(`Unknown fields: [${g.join(",")}] in ${JSON.stringify(t)}`)}})))(c);Array.isArray(o),r.filledBqlRequest=o};var lt=require("object-traversal"),U=require("radash"),at=require("uuid");var It=async r=>{let{filledBqlRequest:n,schema:a}=r,i=u=>{let p=[],y=[],f=t=>{if(t.$op==="create"&&p.find(e=>e.$id===t.$id))throw new Error(`Duplicate id ${t.$id}`);p.push(t)},w=t=>{if(t.$op==="create"&&y.find(e=>e.$id===t.$id))throw new Error(`Duplicate id ${t.$id}`);y.push(t)};return(0,lt.traverse)(u,({value:t})=>{if(t.$entity||t.$relation){if(!t.$id&&!t.$tempId&&!["link","unlink"].includes(t.$op))throw new Error("An id must be specified either in the mutation or has tu have a default value in the schema");let e=D(a,t),{dataFields:d,roleFields:m,linkFields:F,usedFields:g}=H(e,t),k=()=>{if(t.$op==="create"||t.$op==="delete")return t.$op;if(t.$op==="update"){let R=g.filter(S=>d?.includes(S)),B=g.filter(S=>m?.includes(S)),b=g.filter(S=>F?.includes(S));if(R.length>0)return"update";if(B.length>0||b.length>0)return"noop";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(t)}`)}return"noop"},O={...t.$entity&&{$entity:t.$entity},...t.$relation&&{$relation:t.$relation},...t.$id&&{$id:t.$id},...t.$tempId&&{$tempId:t.$tempId},...t.$filter&&{$filter:t.$filter},...(0,U.shake)((0,U.pick)(t,d||[""])),$op:k(),[Symbol.for("bzId")]:t[Symbol.for("bzId")],[Symbol.for("dbId")]:e.defaultDBConnector.id,[Symbol.for("path")]:t[Symbol.for("path")],[Symbol.for("parent")]:t[Symbol.for("parent")],[Symbol.for("isRoot")]:t[Symbol.for("isRoot")]};if(Array.isArray(O.$id)?O.$id.forEach(R=>{f({...O,$id:R})}):f(O),t[Symbol.for("relation")]&&t[Symbol.for("edgeType")]==="linkField"){if((t.$op==="link"||t.$op==="unlink")&&(t.$id||t.$filter)){if(t.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");p.push({...t,$op:"noop"})}let R=t[Symbol.for("relation")]===t.$relation;if(R&&!(t.$id||t.$tempId))throw new Error("No id or tempId found for complex link");let B=R?t.$id||t.$tempId:(0,at.v4)(),S=t[Symbol.for("parent")].path,q=S?(0,lt.getNodeByPath)(u,S):u,L=q.$id||q.$tempId;if(!L)throw new Error("No parent id found");if(t[Symbol.for("relation")]==="$self")return;let Q=()=>t.$op==="unlink"||t.$op==="delete"?R?"unlink":"delete":t.$op==="link"||t.$op==="create"?R?"link":"create":"noop",P={$relation:t[Symbol.for("relation")],$op:Q(),...t.$op==="unlink"?{$tempId:B}:{$id:B},...R?{}:{[t[Symbol.for("role")]]:t.$tempId||t.$id},[t[Symbol.for("oppositeRole")]]:L,[Symbol.for("bzId")]:(0,at.v4)(),[Symbol.for("dbId")]:a.relations[t[Symbol.for("relation")]].defaultDBConnector.id,[Symbol.for("edgeType")]:"linkField",[Symbol.for("path")]:t[Symbol.for("path")],[Symbol.for("parent")]:t[Symbol.for("parent")]};w(P),(t.$op==="unlink"||Q()==="unlink")&&R&&w({$relation:t[Symbol.for("relation")],$op:"noop",...t.$op==="unlink"?{$tempId:B}:{$id:B},[t[Symbol.for("oppositeRole")]]:L,[Symbol.for("bzId")]:(0,at.v4)(),[Symbol.for("dbId")]:a.relations[t[Symbol.for("relation")]].defaultDBConnector.id,[Symbol.for("edgeType")]:"linkField",[Symbol.for("path")]:t[Symbol.for("path")],[Symbol.for("parent")]:t[Symbol.for("parent")]})}if(t.$relation){let R=t,B=G(R,(q,L)=>m.includes(q)),b=(0,U.mapEntries)(B,(q,L)=>[q,L]),S=G(R,(q,L)=>q.startsWith("$")||q.startsWith("Symbol"));if(Object.keys(B).filter(q=>!q.startsWith("$")).length>0){if(R.$op==="create"||R.$op==="delete"){let q=()=>{if(R.$op==="create")return"link";if(R.$op==="delete")return"unlink";throw new Error("Unsupported parent of edge op")},L=(0,U.mapEntries)(b,(P,M)=>Array.isArray(M)?[P,M.map(T=>T.$id||T)]:[P,M.$id||M]),Q={...S,$relation:R.$relation,$op:q(),...L,[Symbol.for("dbId")]:e.defaultDBConnector.id,[Symbol.for("path")]:t[Symbol.for("path")],[Symbol.for("info")]:"coming from created or deleted relation",[Symbol.for("edgeType")]:"roleField on C/D"};w(Q);return}if(R.$op==="noop"||R.$op==="update"&&Object.keys(B).length>0){let q=G(b,(T,$)=>(Array.isArray($)?$:[$]).some(h=>h.$op==="link"||h.$op==="create")),L=(0,U.mapEntries)(q,(T,$)=>{let E=Array.isArray($)?$:[$];return[T,E.filter(h=>h.$op==="link"||h.$op==="create").flatMap(h=>h.$id||h.$tempId)]}),Q=G(b,(T,$)=>(Array.isArray($)?$:[$]).some(h=>h.$op==="unlink"||h.$op==="delete")),P=(0,U.mapEntries)(Q,(T,$)=>{let E=Array.isArray($)?$:[$];return[T,E.filter(h=>h.$op==="unlink"||h.$op==="delete").flatMap(h=>h.$id||h.$tempId)]});[{op:"link",obj:L},{op:"unlink",obj:P},{op:"replace",obj:{}}].forEach(T=>{if(Object.keys(T.obj).length){if(T.op==="unlink"&&Object.keys(T.obj).length>1)throw new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let $={...S,$relation:R.$relation,$op:T.op,...T.obj,[Symbol.for("dbId")]:e.defaultDBConnector.id,[Symbol.for("parent")]:t[Symbol.for("parent")],[Symbol.for("path")]:t[Symbol.for("path")],[Symbol.for("info")]:"updating roleFields",[Symbol.for("edgeType")]:"roleField on L/U/R"};w($),$.$op==="unlink"&&w({...$,$op:"noop"})}})}}}}}),[p,y]};if(!n)throw new Error("Undefined filledBqlRequest");let[c,l]=i(n),o=l.reduce((u,p)=>{let y=u.find(f=>(f.$id&&f.$id===p.$id||f.$tempId&&f.$tempId===p.$tempId)&&f.$relation===p.$relation&&f.$op===p.$op);if(y){let f={...y,...p};return[...u.filter(s=>!((s.$id&&s.$id===p.$id||s.$tempId&&s.$tempId===p.$tempId)&&s.$relation===p.$relation&&s.$op===p.$op)),f]}return[...u,p]},[]);r.bqlRequest={mutation:{things:c,edges:o}}};var Pt=require("typedb-client"),Ct=async(r,n)=>{let{dbHandles:a,tqlRequest:i,bqlRequest:c,config:l}=r;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(!c?.mutation)throw new Error("BQL mutation not parsed");let o=l.dbConnectors[0].id,u=a.typeDB.get(o)?.session;if(!u?.isOpen())throw new Error("Session is closed");let p=await u.transaction(Pt.TransactionType.WRITE);if(!p)throw new Error("Can't create transaction");let y=i.deletionMatches&&i.deletions&&`match ${i.deletionMatches} delete ${i.deletions}`,f=i.insertions&&`${i.insertionMatches?`match ${i.insertionMatches}`:""} insert ${i.insertions}`;y&&p.query.delete(y);let w=f&&p.query.insert(f),s=w?await w.collect():void 0;await p.commit(),await p.close(),n.rawTqlRes={insertions:s}};var At={query:[qt,rt,ot,Y,gt],mutation:[Ot,It,kt,Ct,Y]},vt=[Tt],pt=async(r,n,a={},i=!0)=>{for(let c of r){let l=await c(n,a);if(l&&Array.isArray(l))for(let o of l)await pt(o.pipeline,o.req,o.res,!1)}if(i)return await pt(vt,n,a,!1),a.bqlRes},Nt=(r,n,a,i)=>pt(At.query,{config:n,schema:a,rawBqlRequest:r,dbHandles:i},{}),Dt=(r,n,a,i)=>pt(At.mutation,{config:n,schema:a,rawBqlRequest:r,dbHandles:i},{});var wt=class{schema;config;dbHandles;constructor({schema:n,config:a}){this.schema=n,this.config=a}init=async()=>{let n={typeDB:new Map},a=Lt(this.schema);await Promise.all(this.config.dbConnectors.map(async i=>{if(i.provider==="typeDB"&&i.dbName){let[c,l]=await(0,jt.tryit)(dt.TypeDB.coreClient)(i.url);if(c){let o=`[BORM:${i.provider}:${i.dbName}] ${c.message??"Can't create TypeDB Client"}`;throw new Error(o)}try{let o=await l.session(i.dbName,dt.SessionType.DATA);n.typeDB.set(i.id,{client:l,session:o})}catch(o){let u=`[BORM:${i.provider}:${i.dbName}] ${(o.messageTemplate?._messageBody()||o.message)??"Can't create TypeDB Session"}`;throw new Error(u)}}})),this.schema=a,this.dbHandles=n};#t=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#t(),this.schema);query=async(n,a)=>{await this.#t();let i={...this.config,query:{...ft.query,...this.config.query,...a}};return Nt(n,i,this.schema,this.dbHandles)};mutate=async(n,a)=>{await this.#t();let i={...this.config,mutation:{...ft.mutation,...this.config.mutation,...a}};return Dt(n,i,this.schema,this.dbHandles)};close=async()=>{this.dbHandles&&this.dbHandles.typeDB.forEach(async({client:n,session:a})=>{console.log("Closing session"),await a.close(),console.log("Closing client"),await n.close()})}},te=wt;0&&(module.exports={});
3
+ `}return""},T=()=>e==="update"||e==="link"||e==="noop"?`$${c} isa ${[F,...Q].filter(m=>m).join(",")};`:"";if(t.$entity||t.$relation)return{op:e,deletionMatch:M(),insertionMatch:T(),insertion:e==="create"?`$${c} isa ${[F,P].filter(m=>m).join(",")};`:e==="update"&&O.length?`$${c} ${O.join(",")};`:"",deletion:e==="delete"?`$${c} isa ${F};`:e==="update"&&B.length?`$${c} has ${R};`:""};throw new Error("in attributes")},l=t=>{let e=t.$op,c=t.$tempId||t.$id,u=D(s,t),F=u.defaultDBConnector?.path||t.$relation,g="roles"in u?(0,N.listify)(u.roles,M=>M):[],k=t.$relation&&"roles"in u&&(0,N.mapEntries)(u.roles,(M,T)=>[M,T.dbConnector?.path||M]),O=(0,N.listify)(t,(M,T)=>{if(!g.includes(M))return null;if(!("roles"in u))throw new Error("This should have roles! ");let m=k[M];return Array.isArray(T)?T.map(E=>({path:m,id:E})):{path:m,id:T}}).filter(M=>M).flat(),R=O.map(M=>{if(!M?.path)throw new Error("Object without path");return`${M.path}: $${M.id}`}),B=O.length>0?`( ${R.join(" , ")} )`:"",b=B?`$${c} ${B} ${t[Symbol.for("edgeType")]==="linkField"||e==="delete"||e==="unlink"?`isa ${F}`:""}`:"",S=`$${c} ${t[Symbol.for("edgeType")]==="linkField"||e==="delete"?`isa ${F}`:""}`,q=()=>b?e==="link"?`${b};`:e==="create"?`${b}, has id '${c}';`:"":"",L=()=>b&&e==="noop"?`${b};`:"",Q=()=>b?e==="delete"?`${b};`:e==="noop"?`${b};`:"":"",P=()=>b?e==="delete"?`${S};`:e==="unlink"?`$${c} ${B};`:"":"";return{deletionMatch:Q(),insertionMatch:L(),deletion:P(),insertion:q(),op:""}},r=(t,e)=>{let c=e==="edges"?l:d;if(Array.isArray(t))return t.map(R=>{let{preDeletionBatch:B,insertionMatch:b,deletionMatch:S,insertion:q,deletion:L}=c(R);return(0,N.shake)({preDeletionBatch:B,insertionMatch:b,deletionMatch:S,insertion:q,deletion:L},Q=>!Q)}).filter(R=>R);let{preDeletionBatch:u,insertionMatch:F,deletionMatch:g,insertion:k,deletion:O}=c(t);return(0,N.shake)({preDeletionBatch:u,insertionMatch:F,deletionMatch:g,insertion:k,deletion:O},R=>!R)},$=r(i.things),p=Array.isArray($)?$:[$],y=r(i.edges,"edges"),f=Array.isArray(y)?y:[y],w=[...p,...f],a=(0,N.shake)({insertionMatches:w.map(t=>t.insertionMatch).join(" ").trim(),deletionMatches:w.map(t=>t.deletionMatch).join(" ").trim(),insertions:w.map(t=>t.insertion).join(" ").trim(),deletions:w.map(t=>t.deletion).join(" ").trim()},t=>!t);o.tqlRequest=a};var X=ct(require("immer")),v=require("object-traversal"),V=require("radash"),Bt=require("uuid");var Ot=async o=>{let{rawBqlRequest:n,schema:s}=o,d=($=>(0,X.default)($,p=>(0,v.traverse)(p,({value:y,meta:f,key:w})=>{if((0,V.isObject)(y)){if(y.$arrayOp)throw new Error("Array op not supported yet");if(w==="$filter"||f.nodePath?.includes(".$filter."))return;let a=y,t=D(s,y),c=f.nodePath?.split(".")?.filter(B=>Number.isNaN(parseInt(B,10))).join(".");if(!t)throw new Error(`Schema not found for ${y.$entity||y.$relation}`);a[Symbol.for("bzId")]=(0,Bt.v4)(),a[Symbol.for("schema")]=t,a[Symbol.for("dbId")]=t.defaultDBConnector.id;let{usedLinkFields:u,usedRoleFields:F}=H(t,a),g=u.map(B=>({fieldType:"linkField",path:B,schema:t.linkFields.find(b=>b.path===B)})),k=t.thingType==="relation"?F.map(B=>({fieldType:"roleField",path:B,schema:nt(t.roles,b=>b===B)})):[];if(g.some(B=>B.schema?.target==="role")&&g.some(B=>B.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 O=k.filter(B=>[...new Set(B.schema.playedBy?.map(b=>b.thing))].length!==1);if(O.length>1)throw new Error(`Field: ${O[0].path} - If a role can be played by multiple things, you must specify the thing in the mutation: ${JSON.stringify(O[0].schema.playedBy)}. Schema: ${JSON.stringify(O[0].schema)}`);let R=f.nodePath;if([...g,...k].forEach(B=>{let b=a[B.path];if(b===void 0)return;let S=(B.fieldType==="roleField",B.schema);if(!S)throw new Error(`Field ${B.path} not found in schema`);let q=B.fieldType==="roleField"?S?.playedBy[0]:S,Q=(()=>S&&"relation"in S&&q?.relation===a.$relation?"$self":q?.relation?q?.relation:"$self")(),P=Q==="$self"?t:s.relations[Q];if(nt(P.roles,(h,C)=>h===B.path)?.playedBy?.length===0)throw new Error(`unused role: ${R}.${B.path}`);if(!S)throw new Error(`Field ${B.path} not found in schema`);let T=B.fieldType==="linkField"?S?.oppositeLinkFieldsPlayedBy:S?.playedBy;if(!T)throw new Error(`No opposite fields found for ${JSON.stringify(S)}`);if([...new Set(T?.map(h=>h.thing))].length>1)throw new Error(`Field: ${B.path} - If a role can be played by multiple things, you must specify the thing in the mutation: ${JSON.stringify(T)}. Schema: ${JSON.stringify(S)}`);if(S.cardinality==="ONE"&&Array.isArray(b))throw new Error("Can't have an array in a cardinality === ONE link field");if(S.cardinality==="MANY"&&b!==null&&!Array.isArray(b)&&!b.$arrayOp)throw new Error(`${B.fieldType==="linkField"?S.path:S.name} is a cardinality === MANY thing. Use an array or a $arrayOp object`);if(b?.$entity||b?.$relation)return;let m=T[0],E={[`$${m.thingType}`]:m.thing,[Symbol.for("relation")]:Q,[Symbol.for("edgeType")]:"plays"in S?"linkField":"roleField",[Symbol.for("parent")]:{path:R,...a.$id?{$id:a.$id}:{},...a.$tempId?{$tempId:a.$tempId}:{},...a.filter?{filter:a.filter}:{},links:T},[Symbol.for("role")]:m.plays,[Symbol.for("oppositeRole")]:"plays"in S?S.plays:void 0,[Symbol.for("relFieldSchema")]:S};if((0,V.isObject)(b)&&(t.thingType==="relation"&&b.$tempId?a[B.path]=b.$tempId:a[B.path]={...E,...b}),Array.isArray(b))if(b.every(h=>(0,V.isObject)(h)))a[B.path]=b.map(h=>h.$tempId&&t.thingType==="relation"&&(h.$op==="link"||!h.$op)?h.$tempId:{...E,...h});else if(b.every(h=>typeof h=="string"))a[B.path]=b.map(h=>({...E,$op:a.$op==="create"?"link":"replace",$id:h}));else throw new Error(`Invalid array value for ${B.path}`);if(typeof b=="string"&&(a[B.path]={...E,$op:a.$op==="create"?"link":"replace",$id:b}),b===null){let h={...E,$op:"unlink"};a[B.path]=S.cardinality==="MANY"?[h]:h}}),!c&&!a.$entity&&!a.$relation)throw new Error("Root things must specify $entity or $relation")}})))(n),r=($=>(0,X.default)($,p=>(0,v.traverse)(p,({parent:y,key:f,value:w,meta:a})=>{if((0,V.isObject)(w)){if(Object.keys(w).length===0)throw new Error("Empty object!");if(f==="$filter"||a.nodePath?.includes(".$filter."))return;let t=w,e=a.nodePath?.split("."),c=e?.filter(I=>Number.isNaN(parseInt(I,10))).join("."),u=c?Array.isArray(y)?e?.slice(0,-1).join("."):a.nodePath:a.nodePath||"",F=D(s,t),{unidentifiedFields:g,dataFields:k,roleFields:O,linkFields:R}=H(F,t),B=(0,X.current)(t)[Symbol.for("parent")],b=c&&B.path,q=(b?(0,v.getNodeByPath)(p,b):p)?.$op;if(c&&!q)throw new Error("Error: Parent $op not detected");let L=t[Symbol.for("relFieldSchema")];if(t.$op==="replace"){if(q!=="create")throw new Error("Unsupported: For replaces, please do an unlink + a link instead");t.$op="link"}let Q=Object.keys(t).some(I=>k?.includes(I)),P=Object.keys(t).some(I=>[...O,...R].includes(I)),M=()=>{if(t.$op)return t.$op;if(c&&!t.$id&&!t.$tempId&&q!=="create"&&L.cardinality==="ONE")throw new Error(`Please specify if it is a create or an update: ${JSON.stringify(t)} `);if(t.$tempId&&c)return"link";if(t.$tempId&&!c)return"create";if((t.$id||t.$filter)&&Q)return"update";if((t.$id||t.$filter)&&c&&!Q&&!P)return"link";if(!t.$filter&&!t.$id&&!t.$tempId)return"create";if((t.$id||t.$filter)&&!Q&&P)return"noop";throw new Error("Wrong op")};if(t.$op||(t.$op=M()),y||(t.$parentKey=""),typeof y=="object"&&(Array.isArray(y)&&(t[Symbol.for("index")]=f),t[Symbol.for("path")]=u,t[Symbol.for("isRoot")]=!c,t[Symbol.for("depth")]=c?.split(".").length),!t.$entity&&!t.$relation)throw new Error(`Node ${JSON.stringify(t)} without $entity/$relation`);let{idFields:T,computedFields:m}=F;if(!T)throw new Error("No idFields found");let E=T[0],h=(0,V.listify)(t,(I,j)=>j?I:void 0);if(m.filter(I=>!h.includes(I)).forEach(I=>{let j=F.dataFields?.find(W=>W.path===I),_=F.linkFields?.find(W=>W.path===I)?.oppositeLinkFieldsPlayedBy[0],x="roles"in F?nt(F.roles,(W,ne)=>W===I):void 0,J=j||_||x;if(!J)throw new Error(`no field Def for ${I}`);if(I===E&&t.$op==="create"&&!t[I]){let W="default"in J?J.default?.value():void 0;if(!W)throw new Error(`No default value for ${I}`);t[I]=W,t.$id=W}}),!t.$id)if(t[E])t.$id=t[E];else{if(t.$op==="create")throw new Error(`No id found for ${JSON.stringify(t)}`);t.$tempId=`all-${(0,Bt.v4)()}`}if(g.length>0)throw new Error(`Unknown fields: [${g.join(",")}] in ${JSON.stringify(t)}`)}})))(d);Array.isArray(r),o.filledBqlRequest=r};var lt=require("object-traversal"),U=require("radash"),at=require("uuid");var It=async o=>{let{filledBqlRequest:n,schema:s}=o,i=$=>{let p=[],y=[],f=t=>{if(t.$op==="create"&&p.find(e=>e.$id===t.$id))throw new Error(`Duplicate id ${t.$id}`);p.push(t)},w=t=>{if(t.$op==="create"&&y.find(e=>e.$id===t.$id))throw new Error(`Duplicate id ${t.$id}`);y.push(t)};return(0,lt.traverse)($,({value:t})=>{if(t.$entity||t.$relation){if(!t.$id&&!t.$tempId&&!["link","unlink"].includes(t.$op))throw new Error("An id must be specified either in the mutation or has tu have a default value in the schema");let e=D(s,t),{dataFields:c,roleFields:u,linkFields:F,usedFields:g}=H(e,t),k=()=>{if(t.$op==="create"||t.$op==="delete")return t.$op;if(t.$op==="update"){let R=g.filter(S=>c?.includes(S)),B=g.filter(S=>u?.includes(S)),b=g.filter(S=>F?.includes(S));if(R.length>0)return"update";if(B.length>0||b.length>0)return"noop";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(t)}`)}return"noop"},O={...t.$entity&&{$entity:t.$entity},...t.$relation&&{$relation:t.$relation},...t.$id&&{$id:t.$id},...t.$tempId&&{$tempId:t.$tempId},...t.$filter&&{$filter:t.$filter},...(0,U.shake)((0,U.pick)(t,c||[""])),$op:k(),[Symbol.for("bzId")]:t[Symbol.for("bzId")],[Symbol.for("dbId")]:e.defaultDBConnector.id,[Symbol.for("path")]:t[Symbol.for("path")],[Symbol.for("parent")]:t[Symbol.for("parent")],[Symbol.for("isRoot")]:t[Symbol.for("isRoot")]};if(Array.isArray(O.$id)?O.$id.forEach(R=>{f({...O,$id:R})}):f(O),t[Symbol.for("relation")]&&t[Symbol.for("edgeType")]==="linkField"){if((t.$op==="link"||t.$op==="unlink")&&(t.$id||t.$filter)){if(t.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");p.push({...t,$op:"noop"})}let R=t[Symbol.for("relation")]===t.$relation;if(R&&!(t.$id||t.$tempId))throw new Error("No id or tempId found for complex link");let B=R?t.$id||t.$tempId:(0,at.v4)(),S=t[Symbol.for("parent")].path,q=S?(0,lt.getNodeByPath)($,S):$,L=q.$id||q.$tempId;if(!L)throw new Error("No parent id found");if(t[Symbol.for("relation")]==="$self")return;let Q=()=>{if(t.$op==="unlink"||t.$op==="delete")return R?"unlink":"delete";if(t.$op==="link"||t.$op==="create")return R?"link":"create";if(t.$op==="replace")throw new Error("Unsupported: Replaces not implemented yet");return"noop"},P={$relation:t[Symbol.for("relation")],$op:Q(),...t.$op==="unlink"?{$tempId:B}:{$id:B},...R?{}:{[t[Symbol.for("role")]]:t.$tempId||t.$id},[t[Symbol.for("oppositeRole")]]:L,[Symbol.for("bzId")]:(0,at.v4)(),[Symbol.for("dbId")]:s.relations[t[Symbol.for("relation")]].defaultDBConnector.id,[Symbol.for("edgeType")]:"linkField",[Symbol.for("path")]:t[Symbol.for("path")],[Symbol.for("parent")]:t[Symbol.for("parent")]};w(P),(t.$op==="unlink"||Q()==="unlink")&&R&&w({$relation:t[Symbol.for("relation")],$op:"noop",...t.$op==="unlink"?{$tempId:B}:{$id:B},[t[Symbol.for("oppositeRole")]]:L,[Symbol.for("bzId")]:(0,at.v4)(),[Symbol.for("dbId")]:s.relations[t[Symbol.for("relation")]].defaultDBConnector.id,[Symbol.for("edgeType")]:"linkField",[Symbol.for("path")]:t[Symbol.for("path")],[Symbol.for("parent")]:t[Symbol.for("parent")]})}if(t.$relation){let R=t,B=G(R,(q,L)=>u.includes(q)),b=(0,U.mapEntries)(B,(q,L)=>[q,L]),S=G(R,(q,L)=>q.startsWith("$")||q.startsWith("Symbol"));if(Object.keys(B).filter(q=>!q.startsWith("$")).length>0){if(R.$op==="create"||R.$op==="delete"){let q=()=>{if(R.$op==="create")return"link";if(R.$op==="delete")return"unlink";throw new Error("Unsupported parent of edge op")},L=(0,U.mapEntries)(b,(P,M)=>Array.isArray(M)?[P,M.map(T=>T.$id||T)]:[P,M.$id||M]),Q={...S,$relation:R.$relation,$op:q(),...L,[Symbol.for("dbId")]:e.defaultDBConnector.id,[Symbol.for("path")]:t[Symbol.for("path")],[Symbol.for("info")]:"coming from created or deleted relation",[Symbol.for("edgeType")]:"roleField on C/D"};w(Q);return}if(R.$op==="noop"||R.$op==="update"&&Object.keys(B).length>0){let q=G(b,(T,m)=>(Array.isArray(m)?m:[m]).some(h=>h.$op==="link"||h.$op==="create")),L=(0,U.mapEntries)(q,(T,m)=>{let E=Array.isArray(m)?m:[m];return[T,E.filter(h=>h.$op==="link"||h.$op==="create").flatMap(h=>h.$id||h.$tempId)]}),Q=G(b,(T,m)=>(Array.isArray(m)?m:[m]).some(h=>h.$op==="unlink"||h.$op==="delete")),P=(0,U.mapEntries)(Q,(T,m)=>{let E=Array.isArray(m)?m:[m];return[T,E.filter(h=>h.$op==="unlink"||h.$op==="delete").flatMap(h=>h.$id||h.$tempId)]});[{op:"link",obj:L},{op:"unlink",obj:P},{op:"replace",obj:{}}].forEach(T=>{if(Object.keys(T.obj).length){if(T.op==="unlink"&&Object.keys(T.obj).length>1)throw new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let m={...S,$relation:R.$relation,$op:T.op,...T.obj,[Symbol.for("dbId")]:e.defaultDBConnector.id,[Symbol.for("parent")]:t[Symbol.for("parent")],[Symbol.for("path")]:t[Symbol.for("path")],[Symbol.for("info")]:"updating roleFields",[Symbol.for("edgeType")]:"roleField on L/U/R"};w(m),m.$op==="unlink"&&w({...m,$op:"noop"})}})}}}}}),[p,y]};if(!n)throw new Error("Undefined filledBqlRequest");let[d,l]=i(n),r=l.reduce(($,p)=>{let y=$.find(f=>(f.$id&&f.$id===p.$id||f.$tempId&&f.$tempId===p.$tempId)&&f.$relation===p.$relation&&f.$op===p.$op);if(y){let f={...y,...p};return[...$.filter(a=>!((a.$id&&a.$id===p.$id||a.$tempId&&a.$tempId===p.$tempId)&&a.$relation===p.$relation&&a.$op===p.$op)),f]}return[...$,p]},[]);o.bqlRequest={mutation:{things:d,edges:r}}};var Pt=require("typedb-client"),Ct=async(o,n)=>{let{dbHandles:s,tqlRequest:i,bqlRequest:d,config:l}=o;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(!d?.mutation)throw new Error("BQL mutation not parsed");let r=l.dbConnectors[0].id,$=s.typeDB.get(r)?.session;if(!$?.isOpen())throw new Error("Session is closed");let p=await $.transaction(Pt.TransactionType.WRITE);if(!p)throw new Error("Can't create transaction");let y=i.deletionMatches&&i.deletions&&`match ${i.deletionMatches} delete ${i.deletions}`,f=i.insertions&&`${i.insertionMatches?`match ${i.insertionMatches}`:""} insert ${i.insertions}`;y&&p.query.delete(y);let w=f&&p.query.insert(f),a=w?await w.collect():void 0;await p.commit(),await p.close(),n.rawTqlRes={insertions:a}};var At={query:[qt,rt,ot,Y,gt],mutation:[Ot,It,kt,Ct,Y]},vt=[Tt],pt=async(o,n,s={},i=!0)=>{for(let d of o){let l=await d(n,s);if(l&&Array.isArray(l))for(let r of l)await pt(r.pipeline,r.req,r.res,!1)}if(i)return await pt(vt,n,s,!1),s.bqlRes},Nt=(o,n,s,i)=>pt(At.query,{config:n,schema:s,rawBqlRequest:o,dbHandles:i},{}),Dt=(o,n,s,i)=>pt(At.mutation,{config:n,schema:s,rawBqlRequest:o,dbHandles:i},{});var wt=class{schema;config;dbHandles;constructor({schema:n,config:s}){this.schema=n,this.config=s}init=async()=>{let n={typeDB:new Map},s=Lt(this.schema);await Promise.all(this.config.dbConnectors.map(async i=>{if(i.provider==="typeDB"&&i.dbName){let[d,l]=await(0,jt.tryit)(dt.TypeDB.coreClient)(i.url);if(d){let r=`[BORM:${i.provider}:${i.dbName}] ${d.message??"Can't create TypeDB Client"}`;throw new Error(r)}try{let r=await l.session(i.dbName,dt.SessionType.DATA);n.typeDB.set(i.id,{client:l,session:r})}catch(r){let $=`[BORM:${i.provider}:${i.dbName}] ${(r.messageTemplate?._messageBody()||r.message)??"Can't create TypeDB Session"}`;throw new Error($)}}})),this.schema=s,this.dbHandles=n};#t=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#t(),this.schema);query=async(n,s)=>{await this.#t();let i={...this.config,query:{...ft.query,...this.config.query,...s}};return Nt(n,i,this.schema,this.dbHandles)};mutate=async(n,s)=>{await this.#t();let i={...this.config,mutation:{...ft.mutation,...this.config.mutation,...s}};return Dt(n,i,this.schema,this.dbHandles)};close=async()=>{!this.dbHandles||this.dbHandles.typeDB.forEach(async({client:n,session:s})=>{console.log("Closing session"),await s.close(),console.log("Closing client"),await n.close()})}},te=wt;0&&(module.exports={});
4
4
  //! reads all the insertions and gets the first match. This means each id must be unique
package/package.json CHANGED
@@ -1,70 +1,73 @@
1
- {
2
- "name": "@blitznocode/blitz-orm",
3
- "version": "0.1.0",
4
- "main": "dist/index.js",
5
- "types": "dist/index.d.ts",
6
- "scripts": {
7
- "dev": "tsup --watch",
8
- "build": "tsup --minify",
9
- "lint": "eslint . --ext .ts,.cjs",
10
- "lint-staged": "lint-staged --concurrent false",
11
- "types": "tsc --noEmit",
12
- "test": "jest --coverage",
13
- "test:watch": "jest --watch",
14
- "deploy": "npm run build && npm publish"
15
- },
16
- "private": false,
17
- "license": "AGPL-3.0-only",
18
- "repository": {
19
- "type": "git",
20
- "url": "https://github.com/Blitzapps/blitz-orm"
21
- },
22
- "files": [
23
- "README.md",
24
- "dist"
25
- ],
26
- "engines": {
27
- "node": ">=16.8.0"
28
- },
29
- "dependencies": {
30
- "immer": "^9.0.19",
31
- "nanoid": "^4.0.1",
32
- "object-traversal": "^1.0.1",
33
- "radash": "^10.7.0",
34
- "typedb-client": "^2.14.2",
35
- "uuid": "^9.0.0"
36
- },
37
- "devDependencies": {
38
- "@types/jest": "^29.2.5",
39
- "@types/node": "^18.11.18",
40
- "@types/uuid": "^9.0.0",
41
- "@typescript-eslint/eslint-plugin": "^5.50.0",
42
- "@typescript-eslint/parser": "^5.50.0",
43
- "eslint": "^8.33.0",
44
- "eslint-config-airbnb-base": "^15.0.0",
45
- "eslint-config-airbnb-typescript": "^17.0.0",
46
- "eslint-config-prettier": "^8.6.0",
47
- "eslint-plugin-import": "^2.27.5",
48
- "eslint-plugin-prettier": "^4.2.1",
49
- "eslint-plugin-unused-imports": "^2.0.0",
50
- "jest": "^29.3.1",
51
- "prettier": "^2.8.3",
52
- "ts-jest": "^29.0.3",
53
- "tsup": "^6.5.0",
54
- "typescript": "^4.9.5"
55
- },
56
- "description": "Blitz-orm is a public package that can be open-sourced",
57
- "bugs": {
58
- "url": "https://github.com/Blitzapps/blitz-orm/issues"
59
- },
60
- "homepage": "https://github.com/Blitzapps/blitz-orm#readme",
61
- "directories": {
62
- "test": "tests"
63
- },
64
- "keywords": [
65
- "ORM",
66
- "database",
67
- "graph-database"
68
- ],
69
- "author": "blitznocode"
70
- }
1
+ {
2
+ "name": "@blitznocode/blitz-orm",
3
+ "version": "0.1.2",
4
+ "main": "dist/index.js",
5
+ "types": "dist/index.d.ts",
6
+ "scripts": {
7
+ "dev": "tsup --watch",
8
+ "build": "tsup --minify",
9
+ "lint": "eslint . --ext .ts,.cjs",
10
+ "lint-staged": "lint-staged --concurrent false",
11
+ "types": "tsc --noEmit",
12
+ "test": "jest --coverage",
13
+ "test:watch": "jest --watch",
14
+ "deploy": "npm run build && npm publish"
15
+ },
16
+ "private": false,
17
+ "license": "AGPL-3.0-only",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "https://github.com/Blitzapps/blitz-orm"
21
+ },
22
+ "files": [
23
+ "README.md",
24
+ "dist"
25
+ ],
26
+ "engines": {
27
+ "node": ">=16.8.0"
28
+ },
29
+ "publishConfig": {
30
+ "registry": "https://registry.npmjs.org/"
31
+ },
32
+ "dependencies": {
33
+ "immer": "^9.0.19",
34
+ "nanoid": "^4.0.1",
35
+ "object-traversal": "^1.0.1",
36
+ "radash": "^10.7.0",
37
+ "typedb-client": "^2.17.0",
38
+ "uuid": "^9.0.0"
39
+ },
40
+ "devDependencies": {
41
+ "@types/jest": "^29.2.5",
42
+ "@types/node": "^18.11.18",
43
+ "@types/uuid": "^9.0.0",
44
+ "@typescript-eslint/eslint-plugin": "^5.50.0",
45
+ "@typescript-eslint/parser": "^5.50.0",
46
+ "eslint": "^8.33.0",
47
+ "eslint-config-airbnb-base": "^15.0.0",
48
+ "eslint-config-airbnb-typescript": "^17.0.0",
49
+ "eslint-config-prettier": "^8.6.0",
50
+ "eslint-plugin-import": "^2.27.5",
51
+ "eslint-plugin-prettier": "^4.2.1",
52
+ "eslint-plugin-unused-imports": "^2.0.0",
53
+ "jest": "^29.3.1",
54
+ "prettier": "^2.8.3",
55
+ "ts-jest": "^29.0.3",
56
+ "tsup": "^6.5.0",
57
+ "typescript": "^4.9.5"
58
+ },
59
+ "description": "Blitz-orm is a public package that can be open-sourced",
60
+ "bugs": {
61
+ "url": "https://github.com/Blitzapps/blitz-orm/issues"
62
+ },
63
+ "homepage": "https://github.com/Blitzapps/blitz-orm#readme",
64
+ "directories": {
65
+ "test": "tests"
66
+ },
67
+ "keywords": [
68
+ "ORM",
69
+ "database",
70
+ "graph-database"
71
+ ],
72
+ "author": "blitznocode"
73
+ }
package/readme.md CHANGED
@@ -1,66 +1,66 @@
1
- # Blitz-orm
2
- Blitz-orm is an Object Relational Mapper (ORM) for graph databases that uses a JSON query language called Blitz Query Language (BQL). BQL is similar to GraphQL but uses JSON instead of strings.
3
-
4
- Blitz-orm is similar to other ORM packages such as Prisma. You define a BQL schema and it gets translated to different databases (currently only compatible with TypeDB).
5
-
6
- ## Compatibility
7
- Currently, the only database that is compatible with Blitz-orm is TypeDB. The goal is to build adapters for other graph databases such as Dgraph and Neo4j, as well as classic databases like PostgreSQL and MongoDB in the future.
8
-
9
- ## How to Use
10
- 1. Install the package using your package manager, for example:
11
- `yarn add @blitznocode/blitz-orm`
12
- 2. Create a Borm schema. You can find an example in the test folder.
13
- 3. The borm.define() function is currently not working, so you will need to manually translate your BQL schema into a TypeQL schema (an example can be found in the test folder).
14
- 4. Create a configuration file with the database name that you have created in TypeDB.
15
- 5. Initialize Blitz-orm in a file like this:
16
- ```
17
- import BormClient from '@blitznocode/blitz-orm';
18
-
19
- import { bormConfig } from './borm.config';
20
- import { schema } from './schema';
21
-
22
- const bormClient = new BormClient({
23
- schema,
24
- config: bormConfig,
25
- });
26
-
27
- export default bormClient;
28
- ```
29
- 6. You can then run queries and mutations like this:
30
- ```
31
- const res = await bormClient.mutate({$entity: 'User', name: 'Ann'}, { noMetadata: true });
32
- ```
33
- ## Gotchas
34
- 1) There is no borm.define() method yet. This means you will need to translate your borm schema into typeQL schema manually
35
- 2) Private (non shared) attributes are defined in typeDB as "nameOfTheThing·nameOfTheAttribute", where "·" is a mid-do. As an example:
36
- ```
37
- #shared attribute (shared: true) :
38
- title sub attribute, value string;
39
- #as a private attribute (shared: false), default behaviour:
40
- book·title sub attribute, value string;
41
- ```
42
-
43
- ## Documentation & example queries
44
- You can find example mutations and queries in the tests
45
- There is no official documentation but you can check the draft RFC:
46
- https://www.notion.so/blitzapps/BlitzORM-RFC-eb4a5e1464754cd7857734eabdeaa73c
47
-
48
- The RFC includes future features and is not updated so please keep an eye on the query and mutation tests as those are designed for the features already working.
49
-
50
- ## How to Run TypeDB Locally
51
- To run TypeDB locally, follow the official instructions at https://docs.vaticle.com/docs/running-typedb/install-and-run. It is recommended to run TypeDB Studio, define the schema there, and test with pure TypeQL before using Blitz-orm.
52
-
53
- ## Collaboration & Contact
54
- You can contribute to the project by adding adapters for other databases, developing a BQL-to-GraphQL mapper, enhancing performance, or contributing to the public roadmap for this package (not yet published). To get in touch, please send an email to loic@blitznocode.com.
55
-
56
- ## Warning
57
- Blitz-orm is currently in alpha version and not ready for production use. Some key queries and mutations do work, but there is still much that needs to be done and performance improvements are needed. One of the biggest performance issues is with nested queries, as they currently require a call to TypeDB for each level of depth.
58
-
59
- ## What is Currently Working
60
- To see what is currently working and find examples, please check the test folder, where you will find a variety of queries and mutations.
61
-
62
- ## The future of this package
63
- - Achieve 100% compatibility with typeDB functions
64
- - Enhance functionality with new features such as, cardinality management, ordered attributes, Vectors (ordered relations)...
65
- - Expand compatibility to other graph databases and traditional databases such as PostgreSQL or MongoDB
66
- - Enable the ability to split queries and mutations across multiple databases (for example, some data stored in PostgreSQL and other data in typeQL, all queried from a single point)
1
+ # Blitz-orm
2
+ Blitz-orm is an Object Relational Mapper (ORM) for graph databases that uses a JSON query language called Blitz Query Language (BQL). BQL is similar to GraphQL but uses JSON instead of strings.
3
+
4
+ Blitz-orm is similar to other ORM packages such as Prisma. You define a BQL schema and it gets translated to different databases (currently only compatible with TypeDB).
5
+
6
+ ## Compatibility
7
+ Currently, the only database that is compatible with Blitz-orm is TypeDB. The goal is to build adapters for other graph databases such as Dgraph and Neo4j, as well as classic databases like PostgreSQL and MongoDB in the future.
8
+
9
+ ## How to Use
10
+ 1. Install the package using your package manager, for example:
11
+ `yarn add @blitznocode/blitz-orm`
12
+ 2. Create a Borm schema. You can find an example in the test folder.
13
+ 3. The borm.define() function is currently not working, so you will need to manually translate your BQL schema into a TypeQL schema (an example can be found in the test folder).
14
+ 4. Create a configuration file with the database name that you have created in TypeDB.
15
+ 5. Initialize Blitz-orm in a file like this:
16
+ ```
17
+ import BormClient from '@blitznocode/blitz-orm';
18
+
19
+ import { bormConfig } from './borm.config';
20
+ import { schema } from './schema';
21
+
22
+ const bormClient = new BormClient({
23
+ schema,
24
+ config: bormConfig,
25
+ });
26
+
27
+ export default bormClient;
28
+ ```
29
+ 6. You can then run queries and mutations like this:
30
+ ```
31
+ const res = await bormClient.mutate({$entity: 'User', name: 'Ann'}, { noMetadata: true });
32
+ ```
33
+ ## Gotchas
34
+ 1) There is no borm.define() method yet. This means you will need to translate your borm schema into typeQL schema manually
35
+ 2) Private (non shared) attributes are defined in typeDB as "nameOfTheThing·nameOfTheAttribute", where "·" is a mid-do. As an example:
36
+ ```
37
+ #shared attribute (shared: true) :
38
+ title sub attribute, value string;
39
+ #as a private attribute (shared: false), default behaviour:
40
+ book·title sub attribute, value string;
41
+ ```
42
+
43
+ ## Documentation & example queries
44
+ You can find example mutations and queries in the tests
45
+ There is no official documentation but you can check the draft RFC:
46
+ https://www.notion.so/blitzapps/BlitzORM-RFC-eb4a5e1464754cd7857734eabdeaa73c
47
+
48
+ The RFC includes future features and is not updated so please keep an eye on the query and mutation tests as those are designed for the features already working.
49
+
50
+ ## How to Run TypeDB Locally
51
+ To run TypeDB locally, follow the official instructions at https://docs.vaticle.com/docs/running-typedb/install-and-run. It is recommended to run TypeDB Studio, define the schema there, and test with pure TypeQL before using Blitz-orm.
52
+
53
+ ## Collaboration & Contact
54
+ You can contribute to the project by adding adapters for other databases, developing a BQL-to-GraphQL mapper, enhancing performance, or contributing to the public roadmap for this package (not yet published). To get in touch, please send an email to loic@blitznocode.com.
55
+
56
+ ## Warning
57
+ Blitz-orm is currently in alpha version and not ready for production use. Some key queries and mutations do work, but there is still much that needs to be done and performance improvements are needed. One of the biggest performance issues is with nested queries, as they currently require a call to TypeDB for each level of depth.
58
+
59
+ ## What is Currently Working
60
+ To see what is currently working and find examples, please check the test folder, where you will find a variety of queries and mutations.
61
+
62
+ ## The future of this package
63
+ - Achieve 100% compatibility with typeDB functions
64
+ - Enhance functionality with new features such as, cardinality management, ordered attributes, Vectors (ordered relations)...
65
+ - Expand compatibility to other graph databases and traditional databases such as PostgreSQL or MongoDB
66
+ - Enable the ability to split queries and mutations across multiple databases (for example, some data stored in PostgreSQL and other data in typeQL, all queried from a single point)