@blitznocode/blitz-orm 0.8.11 → 0.9.1
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.d.mts +107 -63
- package/dist/index.d.ts +107 -63
- package/dist/index.js +57 -53
- package/dist/index.mjs +60 -56
- package/package.json +3 -2
package/dist/index.js
CHANGED
|
@@ -5,61 +5,65 @@ var typedbDriver = require('typedb-driver');
|
|
|
5
5
|
var immer = require('immer');
|
|
6
6
|
var objectTraversal = require('object-traversal');
|
|
7
7
|
var uuid = require('uuid');
|
|
8
|
+
var robot3 = require('robot3');
|
|
9
|
+
var types = require('util/types');
|
|
8
10
|
|
|
9
|
-
var
|
|
10
|
-
`,Object.keys(
|
|
11
|
-
`;let
|
|
12
|
-
`,
|
|
13
|
-
`),
|
|
14
|
-
`,
|
|
15
|
-
`),
|
|
16
|
-
`;}),Object.keys(
|
|
17
|
-
`;let
|
|
18
|
-
`,
|
|
19
|
-
`),
|
|
20
|
-
`);}),
|
|
21
|
-
`,
|
|
22
|
-
`),
|
|
23
|
-
`;});let
|
|
11
|
+
var qt={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var tr=e=>{let t=[],n=new Map;return e.forEach(p=>{let{dbPath:a,contentType:d}=p,s=`${a}-${d}`;n.has(s)||(n.set(s,!0),t.push(p));}),t},Xt=async(e,t,n)=>{let a=(()=>{let h="",m=[];h+=`
|
|
12
|
+
`,Object.keys(t.entities).forEach(M=>{let P=t.entities[M],{idFields:R,dataFields:g,linkFields:b,name:k}=P,y=[],I=[],T=[];if("extends"in P){let F=t.entities[P.extends];F.dataFields&&F.dataFields.forEach(w=>{y.push(w.dbPath);}),F.linkFields&&F.linkFields.forEach(w=>{I.push(w.path);}),F.idFields&&F.idFields.forEach(w=>{T.push(w);});}h+=`${k} sub ${"extends"in P?P.extends:"entity"},
|
|
13
|
+
`;let A=[];if(R&&R.length>0){let F=new Set(R),Q=Array.from(F).map(C=>`${C}`).join(", ");T.includes(Q)||(h+=` owns ${Q} @key,
|
|
14
|
+
`,A.push(Q));}if(g&&g.length>0&&g.forEach(F=>{!y.includes(F.dbPath)&&!A.includes(F.dbPath)&&(h+=` owns ${F.dbPath},
|
|
15
|
+
`),m.push({dbPath:F.dbPath,contentType:F.contentType});}),b&&b.length>0){let F=[];b.forEach(w=>{let{relation:Q,plays:C}=w;!I.includes(w.path)&&!F.includes(`${Q}:${C}`)&&(h+=` plays ${Q}:${C},
|
|
16
|
+
`,F.push(`${Q}:${C}`));});}h=h.replace(/,\s*$/,`;
|
|
17
|
+
`),h+=`
|
|
18
|
+
`;}),Object.keys(t.relations).forEach(M=>{let P=t.relations[M],{idFields:R,dataFields:g,roles:b,name:k,linkFields:y}=P,I=[],T=[],A=[],F=[];if("extends"in P){let Q=t.relations[P.extends];Q.dataFields&&Q.dataFields.forEach(C=>{I.push(C.dbPath);}),Q.linkFields&&Q.linkFields.forEach(C=>{T.push(C.dbPath);}),Q.roles&&Object.values(Q.roles).forEach(S=>{A.push(S.name);}),Q.idFields&&Q.idFields.forEach(C=>{F.push(C);});}h+=`${k} sub ${"extends"in P?P.extends:"relation"},
|
|
19
|
+
`;let w=[];if(R&&R.length>0){let Q=new Set(R),S=Array.from(Q).map(N=>`${N}`).join(", ");F.includes(S)||(h+=` owns ${S} @key,
|
|
20
|
+
`,w.push(S));}if(g&&g.length>0&&g.forEach(Q=>{!I.includes(Q.dbPath)&&!w.includes(Q.dbPath)&&(h+=` owns ${Q.dbPath},
|
|
21
|
+
`),m.push({dbPath:Q.dbPath,contentType:Q.contentType});}),b&&Object.keys(b).forEach(Q=>{A.includes(Q)||(h+=` relates ${Q},
|
|
22
|
+
`);}),y&&y.length>0){let Q=[];y.forEach(C=>{let{plays:S}=C;!T.includes(C.path)&&!Q.includes(`${P}:${S}`)&&(h+=` plays ${C.relation}:${S},
|
|
23
|
+
`,Q.push(`${P}:${S}`));});}h=h.replace(/,\s*$/,`;
|
|
24
|
+
`),h+=`
|
|
25
|
+
`;});let E=`define
|
|
24
26
|
|
|
25
|
-
`;return
|
|
26
|
-
`,
|
|
27
|
-
`:
|
|
28
|
-
`,
|
|
29
|
-
`):
|
|
30
|
-
`:
|
|
31
|
-
`:
|
|
32
|
-
`);}),`${
|
|
27
|
+
`;return tr(m).forEach(M=>{E+=`${M.dbPath} sub attribute,
|
|
28
|
+
`,M.contentType==="TEXT"||M.contentType==="ID"?E+=` value string;
|
|
29
|
+
`:M.contentType==="EMAIL"?(E+=` value string,
|
|
30
|
+
`,E+=` regex '^(?=.{1,64}@)[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*@[^-][A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$';
|
|
31
|
+
`):M.contentType==="DATE"?E+=` value datetime;
|
|
32
|
+
`:M.contentType==="BOOLEAN"?E+=` value boolean;
|
|
33
|
+
`:M.contentType==="NUMBER"&&(E+=` value long;
|
|
34
|
+
`);}),`${E}
|
|
33
35
|
|
|
34
|
-
${c}`})(),p=f.dbConnectors[0].id,h=s.typeDB.get(p)?.session,w=s.typeDB.get(p)?.client;if(!h){console.log("Session Status: ","NO SESSION");return}await h.close();let[{dbName:g}]=f.dbConnectors;await(await w.databases.get(g)).delete(),await w.databases.create(g);let t=await w.session(f.dbConnectors[0].dbName,typedbDriver.SessionType.SCHEMA),o=await t.transaction(typedbDriver.TransactionType.WRITE);await o.query.define(F),await o.commit(),await o.close();let u=await t.transaction(typedbDriver.TransactionType.READ);(await(await u.query.match("match $a sub thing;")).collect()).forEach(async c=>{c.get("a");}),await u.close();};var Vt=(f,e,s)=>s?e:`${f}\xB7${e}`;var ft=(f,e)=>Object.values(Object.fromEntries(Object.entries(f).filter(([s,a])=>e(s,a))))[0],ut=(f,e)=>Object.fromEntries(Object.entries(f).filter(([s,a])=>e(s,a))),Wt=f=>{let e=[],s=immer.produce(f,F=>objectTraversal.traverse(F,({key:p,value:h,meta:w})=>{if(w.depth===2&&(p&&(h.dataFields=h.dataFields?.map(g=>({...g,cardinality:g.cardinality||"ONE",dbPath:Vt(p,g.path,g.shared)}))),h.extends)){let g=F.entities[h.extends]||F.relations[h.extends];if(h.allExtends=[h.extends,...g.allExtends||[]],h.idFields=g.idFields?(h.idFields||[]).concat(g.idFields):h.idFields,h.dataFields=g.dataFields?(h.dataFields||[]).concat(g.dataFields.map(R=>{let t=h.extends,o=f.entities[t]||f.relations[t];for(;!o.dataFields?.find(u=>u.path===R.path);)t="extends"in o?o.extends:void 0,o=f.entities[t]||f.relations[t];return {...R,dbPath:Vt(t,R.path,R.shared)}})):h.dataFields,h.linkFields=g.linkFields?(h.linkFields||[]).concat(g.linkFields):h.linkFields,"roles"in g){let R=h,t=g;R.roles=R.roles||{},R.roles={...R.roles,...t.roles},Object.keys(R.roles).length===0&&(R.roles={});}}},{traversalType:"breadth-first"}));return objectTraversal.traverse(f,({key:F,value:p,meta:h})=>{if(F==="linkFields"){let g=(()=>{if(!h.nodePath)throw new Error("No path");let[t,o]=h.nodePath.split(".");return {thing:o,thingType:t==="entities"?"entity":t==="relations"?"relation":""}})(),R=Array.isArray(p)?p.map(t=>({...t,...g})):[{...p,...g}];e.push(...R);}}),immer.produce(s,F=>objectTraversal.traverse(F,({value:p,key:h,meta:w})=>{if(w.depth===2&&p.idFields&&!p.id){p.name=h;let g=()=>{if(w.nodePath?.split(".")[0]==="entities")return "entity";if(w.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};p.thingType=g(),p.computedFields=[],p.virtualFields=[],p.requiredFields=[],p.enumFields=[],p.fnValidatedFields=[],"roles"in p&&Object.entries(p.roles).forEach(([t,o])=>{o.playedBy=e.filter(u=>u.relation===h&&u.plays===t)||[],o.name=t;}),"linkFields"in p&&p.linkFields&&p.linkFields?.forEach(t=>{if(t.target==="relation"){t.oppositeLinkFieldsPlayedBy=[{plays:t.path,thing:t.relation,thingType:"relation"}];return}let o=e.filter(n=>n.relation===t.relation&&n.plays!==t.plays)||[];t.oppositeLinkFieldsPlayedBy=o;let{filter:u}=t;t.oppositeLinkFieldsPlayedBy=t.oppositeLinkFieldsPlayedBy.filter(n=>n.target==="role"),u&&Array.isArray(u)&&(t.oppositeLinkFieldsPlayedBy=t.oppositeLinkFieldsPlayedBy.filter(n=>u.some(d=>n.thing===d.$role)),t.oppositeLinkFieldsPlayedBy=t.oppositeLinkFieldsPlayedBy.filter(n=>u.some(d=>n.thing===d.$thing))),u&&!Array.isArray(u)&&(t.oppositeLinkFieldsPlayedBy=t.oppositeLinkFieldsPlayedBy.filter(n=>n.$role===u.$role),t.oppositeLinkFieldsPlayedBy=t.oppositeLinkFieldsPlayedBy.filter(n=>n.thing===u.$thing));});}if(typeof p=="object"&&"playedBy"in p){if([...new Set(p.playedBy?.map(g=>g.thing))].length>1)throw new Error(`Unsupported: roleFields can be only played by one thing. Role: ${h} path:${w.nodePath}`);if(p.playedBy.length===0)throw new Error(`Unsupported: roleFields should be played at least by one thing. Role: ${h}, path:${w.nodePath}`)}if(w.depth===4){let[g,R]=w.nodePath?.split(".")||[],t=F[g][R];p.validations&&(p.validations.required&&t.requiredFields.push(p.path),p.validations.enum&&t.enumFields.push(p.path),p.validations.fn&&t.fnValidatedFields.push(p.path)),p.default?p.isVirtual?t.virtualFields.push(p.path):t.computedFields.push(p.path):p.isVirtual&&t.virtualFields.push(p.path);}}))},At=(f,e,s)=>{let a=N(f,e),F=a.linkFields?.find(w=>w.path===s);if(F)return F.cardinality;let p=a.dataFields?.find(w=>w.path===s);if(p)return p.cardinality;let h=a.roles[s];if(h)return h.cardinality},N=(f,e)=>{if(e.$thing){if(!e.$thingType)throw new Error("Missing $thingType in node$: {JSON.stringify(node, null, 2)");if(e.$thingType==="entity"){if(!(e.$thing in f.entities))throw new Error(`Missing entity '${e.$thing}' in the schema`);return f.entities[e.$thing]}if(e.$thingType==="relation"){if(!(e.$thing in f.relations))throw new Error(`Missing relation '${e.$thing}' in the schema`);return f.relations[e.$thing]}throw new Error(`Wrong schema or query for ${JSON.stringify(e,null,2)}`)}if(e.$entity){if(!(e.$entity in f.entities))throw new Error(`Missing entity '${e.$entity}' in the schema`);return f.entities[e.$entity]}if(e.$relation){if(!(e.$relation in f.relations))throw new Error(`Missing relation '${e.$relation}' in the schema`);return f.relations[e.$relation]}throw new Error(`Wrong schema or query for ${JSON.stringify(e,null,2)}`)},nt=(f,e)=>{let s=f.dataFields?.map(d=>d.path)||[],a=f.linkFields?.map(d=>d.path)||[],F="roles"in f?radash.listify(f.roles,d=>d):[],p=[...s||[],...a||[],...F||[]],w=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields"],...p];if(!e)return {fields:p,dataFields:s,roleFields:F,linkFields:a};let g=e.$fields?e.$fields.map(d=>{if(typeof d=="string")return d;if("$path"in d&&typeof d.$path=="string")return d.$path;throw new Error(" Wrongly structured query")}):radash.listify(e,d=>d),R=e.$filter?radash.listify(e.$filter,d=>d.toString().startsWith("$")?void 0:d.toString()).filter(d=>d&&s?.includes(d)):[],t=e.$filter?radash.listify(e.$filter,d=>d.toString().startsWith("$")?void 0:d.toString()).filter(d=>d&&[...F||[],...a||[]].includes(d)):[],o=[...g,...R].filter(d=>!w.includes(d)).filter(d=>d),u=e.$filter?ut(e.$filter,(d,i)=>R.includes(d)):{},n=e.$filter?ut(e.$filter,(d,i)=>t.includes(d)):{};return {fields:p,dataFields:s,roleFields:F,linkFields:a,usedFields:g,usedLinkFields:a.filter(d=>g.includes(d)),usedRoleFields:F.filter(d=>g.includes(d)),unidentifiedFields:o,...R.length?{localFilters:u}:{},...t.length?{nestedFilters:n}:{}}};var Ht=f=>{if(typeof f!="string")throw new Error("capitalizeFirstLetter: string is not a string");return f.charAt(0).toUpperCase()+f.slice(1).toLowerCase()},G=(f,e,s)=>{let F=(s.nodePath||"").split("."),p=radash.isArray(e)?F.slice(0,-2).join("."):F.slice(0,-1).join(".");return e?objectTraversal.getNodeByPath(f,p):{}},X=f=>Reflect.ownKeys(f).filter(e=>typeof e=="symbol").reduce((e,s)=>(e[s]=f[s],e),{}),Ut=f=>Object.keys(f).filter(e=>!e.startsWith("$")).length,st=f=>radash.isObject(f)&&("$entity"in f||"$relation"in f||"$thing"in f);var Kt=async(f,e)=>{let{bqlRequest:s,config:a,tqlRequest:F}=f,{rawTqlRes:p}=e;if(s){if(!p)throw new Error("TQL query not executed")}else throw new Error("BQL request not parsed");let{query:h}=s;if(!h){if(p.insertions?.length===0&&!F?.deletions){e.bqlRes={};return}let{mutation:w}=s;if(!w)throw new Error("TQL mutation not executed");let R=[...w.things,...w.edges].map(t=>{let o=p.insertions?.find(u=>u.get(`${t.$bzId}`))?.get(`${t.$bzId}`);if(t.$op==="create"||t.$op==="update"||t.$op==="link"){let u=o?.asThing().iid;return a.mutation?.noMetadata?radash.mapEntries(t,(n,d)=>[n.toString().startsWith("$")?Symbol.for(n):n,d]):{$dbId:u,...t,[t.path]:t.$id}}if(t.$op==="delete"||t.$op==="unlink")return t;if(t.$op!=="match")throw new Error(`Unsupported op ${t.$op}`)}).filter(t=>t);e.bqlRes=R;return}};var Je=(f,e)=>immer.produce(f,s=>objectTraversal.traverse(s,({value:a})=>{if(Array.isArray(a)||typeof a!="object"||a===null)return;a.$tempId&&(a.$tempId=`_:${a.$tempId}`),a.$fields&&delete a.$fields,a.$filter&&delete a.$filter,a.$show&&delete a.$show,a.$bzId&&delete a.$bzId,e.query?.noMetadata&&(a.$entity||a.$relation)&&(delete a.$entity,delete a.$relation,delete a.$id),Object.getOwnPropertySymbols(a).forEach(p=>{delete a[p];}),a.$excludedFields&&(a.$excludedFields.forEach(p=>{delete a[p];}),delete a.$excludedFields);})),Ze=(f,e)=>{let s={};return e.forEach(a=>{s[a.$bzId]=a.$id;}),f.forEach(a=>{Object.keys(a).forEach(F=>{s[a[F]]&&F!=="$tempId"&&(a[F]=s[a[F]]);});}),f},Ye=(f,e)=>{let s=e.map(F=>F.$bzId),a=!1;return f.forEach(F=>{Object.keys(F).forEach(p=>{s.includes(F[p])&&(a=!0);});}),a},Jt=async(f,e)=>{let{bqlRequest:s,config:a}=f;if(!s)throw new Error("BQL request not parsed");let F=e.bqlRes[0]?e.bqlRes:[e.bqlRes],p=f.bqlRequest?.mutation?.things;if(Ye(F,p)){let g=Ze(F,p);e.bqlRes=g[1]?g:g[0];}let w=Je(e.bqlRes,a);e.bqlRes=w;};var Zt=async f=>{let{bqlRequest:e,schema:s}=f;if(!e)throw new Error("BQL request not parsed");let{mutation:a}=e;if(!a)throw new Error("BQL request is not a mutation");let F=n=>{let d=n.$op,i=`$${n.$bzId}`,c=N(s,n),{idFields:r,defaultDBConnector:b}=c,P=b?.path||n.$entity||n.$relation,l=n.$id,T=r?.[0],A=radash.listify(n,(y,L)=>{if(y.startsWith("$")||y===T||L===void 0||L===null)return "";let O=c.dataFields?.find(j=>j.path===y);if(!O?.path)return "";let D=O.dbPath;if(["TEXT","ID","EMAIL"].includes(O.contentType))return `has ${D} '${L}'`;if(["NUMBER","BOOLEAN"].includes(O.contentType))return `has ${D} ${L}`;if(O.contentType==="DATE"){if(Number.isNaN(L.valueOf()))throw new Error("Invalid format, Nan Date");return L instanceof Date?`has ${D} ${L.toISOString().replace("Z","")}`:`has ${D} ${new Date(L).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${O.contentType}`)}).filter(y=>y),B=`${i}-atts`,M=radash.listify(n,y=>{if(y.startsWith("$")||y===T)return "";let L=c.dataFields?.find(D=>D.path===y);if(!L?.path)return "";let S=L.dbPath;return `{${B} isa ${S};}`}).filter(y=>y),k=n[Symbol.for("isLocalId")],m=radash.isArray(l)?`like '${l.join("|")}'`:`'${l}'`,Q=!k&&l?[`has ${T} ${m}`]:[],$=[...Q,...A].filter(y=>y).join(","),I=()=>{if(d==="delete"||d==="unlink"||d==="match")return `${i} isa ${[P,...Q].filter(y=>y).join(",")};`;if(d==="update"){if(!M.length)throw new Error("update without attributes");return `${i} isa ${[P,...Q].filter(y=>y).join(",")}, has ${B};
|
|
35
|
-
${M.join(" or ")};`}return ""},E=()=>d==="update"||d==="link"||d==="match"?`${i} isa ${[P,...Q].filter(y=>y).join(",")};`:"";if(st(n))return {op:d,deletionMatch:I(),insertionMatch:E(),insertion:d==="create"?`${i} isa ${[P,$].filter(y=>y).join(",")};`:d==="update"&&A.length?`${i} ${A.join(",")};`:"",deletion:d==="delete"?`${i} isa ${P};`:d==="update"&&M.length?`${i} has ${B};`:""};throw new Error("in attributes")},p=n=>{let d=n.$op,i=N(s,n),c=`$${n.$bzId}`,r=n.$id,b=i.defaultDBConnector?.path||n.$relation,P="roles"in i?radash.listify(i.roles,y=>y):[],l=n.$relation&&"roles"in i&&radash.mapEntries(i.roles,(y,L)=>[y,L.dbConnector?.path||y]),T=radash.listify(n,(y,L)=>{if(!P.includes(y))return null;if(!("roles"in i))throw new Error("This should have roles! ");let O=l[y];return Array.isArray(L)?L.map(S=>({path:O,id:S})):{path:O,id:L}}).filter(y=>y).flat(),A=T.map(y=>{if(!y?.path)throw new Error("Object without path");return `${y.path}: $${y.id}`}),B=T.length>0?`( ${A.join(" , ")} )`:"",M=n[Symbol.for("edgeType")];if(!M)throw new Error("[internal error] Symbol edgeType not defined");let k=B?`${c} ${B} ${M==="linkField"||d==="delete"||d==="unlink"?`isa ${b}`:""}`:"",m=`${c} ${M==="linkField"||d==="delete"?`isa ${b}`:""}`,Q=()=>k?d==="link"?`${k};`:d==="create"?`${k}, has id '${r}';`:"":"",$=()=>k&&d==="match"?`${k};`:"",I=()=>k?d==="delete"?`${k};`:d==="match"?`${k};`:"":"",E=()=>k?d==="delete"?`${m};`:d==="unlink"?`${c} ${B};`:"":"";return {deletionMatch:I(),insertionMatch:$(),deletion:E(),insertion:Q(),op:""}},h=(n,d)=>{let i=d==="edges"?p:F;if(Array.isArray(n))return n.map(T=>{let{preDeletionBatch:A,insertionMatch:B,deletionMatch:M,insertion:k,deletion:m}=i(T);return radash.shake({preDeletionBatch:A,insertionMatch:B,deletionMatch:M,insertion:k,deletion:m},Q=>!Q)}).filter(T=>T);let{preDeletionBatch:c,insertionMatch:r,deletionMatch:b,insertion:P,deletion:l}=i(n);return radash.shake({preDeletionBatch:c,insertionMatch:r,deletionMatch:b,insertion:P,deletion:l},T=>!T)},w=h(a.things),g=Array.isArray(w)?w:[w],R=h(a.edges,"edges"),t=Array.isArray(R)?R:[R],o=[...g,...t],u=radash.shake({insertionMatches:o.map(n=>n.insertionMatch).join(" ").trim(),deletionMatches:o.map(n=>n.deletionMatch).join(" ").trim(),insertions:o.map(n=>n.insertion).join(" ").trim(),deletions:o.map(n=>n.deletion).join(" ").trim()},n=>!n);f.tqlRequest=u;};var ti=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,ei=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,Yt=f=>{let s=f.toString().replace(ti,"").trim().split("=>")[0].split("{")[0].replace(ei,"").trim(),a=s.substring(s.indexOf("(")+1,s.lastIndexOf(")")).trim();return a?(a.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(p=>p.includes("{")&&p.includes("}")?(p.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(w=>w.split(":")[0].trim().replace(/['"[\]]/g,"")):p.trim()).filter(Boolean):[]};var tt=({currentThing:f,fieldSchema:e,mandatoryDependencies:s=!1})=>{if(!e||!e.default||!("fn"in e.default||"value"in e.default))throw new Error(`[Internal] Virtual field: No field schema found, or wrongly configured. Field: ${JSON.stringify(e,null,3)}`);if(e.default.type==="value")return e.default.value;if(s){let{fn:F}=e.default,h=Yt(F).filter(w=>!(w in f));if(h.length)throw new Error(`Virtual field: Missing arguments ${h.join(", ")}`)}return "default"in e?e.default?.fn(f):void 0},Gt=()=>{};var ht=Symbol.for("schema"),H=Symbol.for("queryPath");var ri=f=>{if(!f.startsWith("_:"))throw new Error('TempIds must start with "_:"');let e=f.substring(2);if(!/^[a-zA-Z0-9-_]+$/.test(e))throw new Error("$tempId must contain only alphanumeric characters, hyphens, and underscores.");if(f.length>36)throw new Error("$tempId must not be longer than 36 characters.");return e},te=async f=>{let{rawBqlRequest:e,schema:s}=f,F=(o=>immer.produce(o,u=>objectTraversal.traverse(u,({value:n,key:d,parent:i})=>{if(radash.isObject(n)&&(n=radash.shake(n,c=>c===void 0)),d==="$tempId"&&(i[d]=ri(n)),i&&radash.isArray(n)){if(!n.some(r=>typeof r=="object"&&"$id"in r))return;let c=n.flatMap(r=>typeof r=="string"?r:typeof r=="object"&&"$id"in r&&radash.isArray(r.$id)?r.$id.map(b=>({...r,$id:b})):r);i[d]=c;}})))(e),h=(o=>immer.produce(o,u=>objectTraversal.traverse(u,({value:n,meta:d,key:i})=>{if(radash.isObject(n)){if(n.$arrayOp)throw new Error("Array op not supported yet");if(i==="$filter"||d.nodePath?.includes(".$filter."))return;let c=n;if(c.$op==="create"&&c.$id)throw new Error("Can't write to computed field $id. Try writing to the id field directly.");let r=N(s,c),P=Object.keys(c).filter($=>r.virtualFields?.includes($));if(P.length>0){let $=P.filter(I=>c[I]);if($.length>0)throw new Error(`Can't set virtual fields: ["${$.join('","')}"]`)}let T=d.nodePath?.split(".")?.filter($=>Number.isNaN(parseInt($,10))).join(".");if(!r)throw new Error(`Schema not found for ${c.$entity||c.$relation}`);c.$bzId=c.$tempId??`T_${uuid.v4()}`,!T&&!c.$op&&(c.$id||c.$filter?c.$op="update":c.$op="create"),c[ht]=r,c[Symbol.for("dbId")]=r.defaultDBConnector.id;let{usedLinkFields:A,usedRoleFields:B}=nt(r,c),M=A.map($=>({fieldType:"linkField",path:$,schema:r.linkFields.find(I=>I.path===$)})),k=r.thingType==="relation"?B.map($=>({fieldType:"roleField",path:$,schema:ft(r.roles,I=>I===$)})):[];if(M.some($=>$.schema?.target==="role")&&M.some($=>$.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 m=k.filter($=>[...new Set($.schema.playedBy?.map(I=>I.thing))].length!==1);if(m.length>1)throw new Error(`Field: ${m[0].path} - If a role can be played by multiple things, you must specify the thing in the mutation: ${JSON.stringify(m[0].schema.playedBy)}. Schema: ${JSON.stringify(m[0].schema)}`);let Q=d.nodePath;if([...M,...k].forEach($=>{let I=c[$.path];if(I===void 0)return;let E=$.schema;if(!E)throw new Error(`Field ${$.path} not found in schema`);let y=$.fieldType==="roleField"?E?.playedBy[0]:E,O=E&&"relation"in E&&y?.relation===c.$relation?"$self":y?.relation?y?.relation:"$self",S=O==="$self"?r:s.relations[O];if(ft(S.roles,(q,C)=>q===$.path)?.playedBy?.length===0)throw new Error(`unused role: ${Q}.${$.path}`);if(!E)throw new Error(`Field ${$.path} not found in schema`);let j=$.fieldType==="linkField"?E?.oppositeLinkFieldsPlayedBy:E?.playedBy;if(!j)throw new Error(`No opposite fields found for ${JSON.stringify(E)}`);if([...new Set(j?.map(q=>q.thing))].length>1)throw new Error(`Field: ${$.path} - If a role can be played by multiple things, you must specify the thing in the mutation: ${JSON.stringify(j)}. Schema: ${JSON.stringify(E)}`);if(E.cardinality==="ONE"&&Array.isArray(I))throw new Error("Can't have an array in a cardinality === ONE link field");if(E.cardinality==="MANY"&&I!==null&&!Array.isArray(I)&&!I.$arrayOp)throw new Error(`${$.fieldType==="linkField"?E.path:E.name} is a cardinality === MANY thing. Use an array or a $arrayOp object`);if(st(I))return;let[v]=j,U="plays"in E?"linkField":"roleField",J={[`$${v.thingType}`]:v.thing,[Symbol.for("relation")]:O,[Symbol.for("edgeType")]:U,[Symbol.for("role")]:v.plays,[Symbol.for("oppositeRole")]:"plays"in E?E.plays:void 0,[Symbol.for("relFieldSchema")]:E};if(radash.isObject(I)){let q=I;if(!q.$op&&!q.$id&&!q.$filter&&!q.$tempId&&c.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${d.nodePath?`${d.nodePath}.`:""}${$.path}`);c[$.path]={...J,...q,$op:q.$op?q.$op:q.$id||q.$filter?"link":c.$op==="create"?"create":"update"};}if(Array.isArray(I))if(I.every(q=>radash.isObject(q)))c[$.path]=I.map(q=>({...J,...q,$op:q.$op?q.$op:q.$id||q.$filter?Ut(q)?"update":"link":"create"}));else if(I.every(q=>typeof q=="string"))c[$.path]=I.map(q=>({...J,$op:c.$op==="create"?"link":"replace",$id:q}));else throw new Error(`Invalid array value for ${$.path}`);if(typeof I=="string"&&(c[$.path]={...J,$op:c.$op==="create"?"link":"replace",$id:I}),I===null){let q={...J,$op:"unlink"};c[$.path]=E.cardinality==="MANY"?[q]:q;}}),!T&&!c.$entity&&!c.$relation)throw new Error("Root things must specify $entity or $relation")}})))(F),g=(o=>immer.produce(o,u=>objectTraversal.traverse(u,({parent:n,key:d,value:i,meta:c})=>{if(radash.isObject(i)){if(Object.keys(i).length===0)throw new Error("Empty object!");if(d==="$filter"||c.nodePath?.includes(".$filter."))return;let r=i,b=c.nodePath?.split(".");if(r.$tempId&&!(r.$op===void 0||r.$op==="link"||r.$op==="create"||r.$op==="update"))throw new Error(`Invalid op ${r.$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 P=b?.filter(B=>Number.isNaN(parseInt(B,10))).join("."),l=P?Array.isArray(n)?b?.slice(0,-1).join("."):c.nodePath:c.nodePath||"",A=G(o,n,c)?.$op;if(P&&!A)throw new Error("Error: Parent $op not detected");if(r.$op==="replace"&&A==="create"&&(r.$op="link"),n||(r.$parentKey=""),typeof n=="object"&&(Array.isArray(n)&&(r[Symbol.for("index")]=d),r[Symbol.for("path")]=l,r[Symbol.for("isRoot")]=!P,r[Symbol.for("depth")]=P?.split(".").length),!r.$entity&&!r.$relation)throw new Error(`Node ${JSON.stringify(r)} without $entity/$relation`)}})))(h),t=(o=>immer.produce(o,u=>objectTraversal.traverse(u,({value:n})=>{if(radash.isObject(n)){let d=n,i=N(s,d),{unidentifiedFields:c}=nt(i,d),{idFields:r}=i;if(!r)throw new Error("No idFields found");let[b]=r;if(d.$op==="create"&&!d[b]){let P=i.dataFields?.find(T=>T.path===b),l=tt({currentThing:d,fieldSchema:P,mandatoryDependencies:!0});if(typeof l!="string")throw new Error(`Default id field ${b} is not a string`);d[b]=l,d.$id=l;}if(c.length>0)throw new Error(`Unknown fields: [${c.join(",")}] in ${JSON.stringify(d)}`)}})))(g);f.filledBqlRequest=t;};var ee=f=>{let e=({value:s})=>(s&&typeof s=="object"&&"$id"in s&&(Object.keys(s).filter(p=>p.startsWith("$")).forEach(p=>delete s[p]),Object.keys(s).filter(p=>typeof p=="symbol").forEach(p=>delete s[p])),s);return immer.produce(f,s=>objectTraversal.traverse(s,e))};var oe=async f=>{let{filledBqlRequest:e,schema:s}=f,a=t=>{let o=[],u=[],n=r=>{if(r.$id)return r.$id;let b=N(s,r),{idFields:P}=b;if(!P)throw new Error(`no idFields: ${JSON.stringify(r)}`);let[l]=P;if(!l)throw new Error(`no idField: ${JSON.stringify(r)}`);let T=b.dataFields?.find(M=>M.path===l),A=tt({currentThing:r,fieldSchema:T,mandatoryDependencies:!0}),B=r[l]||r.$id||A;if(!B)throw new Error(`no idValue: ${JSON.stringify(r)}`);return B},d=r=>{if(r.$op==="create"){let b=n(r);if(o.find(P=>P.$id===b))throw new Error(`Duplicate id ${b} for node ${JSON.stringify(r)}`);if(u.find(P=>P.$bzId===r.$bzId))throw new Error(`Duplicate $bzid ${r.$bzId} for node ${JSON.stringify(r)}`);o.push({...r,$id:b});return}r.$tempId&&r.$op==="match"||o.push(r);},i=r=>{if(r.$op==="create"){let b=n(r);if(o.find(P=>P.$id===b),u.find(P=>P.$bzId===r.$bzId))throw new Error(`Duplicate %bzId ${r.$bzIdd} for edge ${JSON.stringify(r)}`);u.push({...r,$id:b});return}u.push(r);};return objectTraversal.traverse(t,({value:r,meta:b,parent:P})=>{if(!radash.isObject(r))return;let l=r;if(l.$entity||l.$relation){if(!l.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(l)}`);if(!l.$bzId)throw new Error("[internal error] BzId not found");let T=N(s,l),{dataFields:A,roleFields:B,linkFields:M,usedFields:k}=nt(T,l),m=()=>{if(l.$op==="create"||l.$op==="delete")return l.$op;if(l.$op==="update"){let $=k.filter(y=>A?.includes(y)),I=k.filter(y=>B?.includes(y)),E=k.filter(y=>M?.includes(y));if($.length>0)return "update";if(I.length>0||E.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(l)}`)}return "match"},Q={...l.$entity&&{$entity:l.$entity},...l.$relation&&{$relation:l.$relation},...l.$id&&{$id:l.$id},...l.$tempId&&{$tempId:l.$tempId},...l.$filter&&{$filter:l.$filter},...radash.shake(radash.pick(l,A||[""])),$op:m(),$bzId:l.$tempId?l.$tempId:l.$bzId,[Symbol.for("dbId")]:T.defaultDBConnector.id,[Symbol.for("path")]:l[Symbol.for("path")],[Symbol.for("isRoot")]:l[Symbol.for("isRoot")],[Symbol.for("isLocalId")]:l[Symbol.for("isLocalId")]||!1};if(d(Q),l[Symbol.for("relation")]&&l[Symbol.for("edgeType")]==="linkField"){if((l.$op==="link"||l.$op==="unlink")&&(l.$id||l.$filter)){if(l.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");o.push({...l,$op:"match"});}let $=l[Symbol.for("relation")]===l.$relation,I=$?l.$bzId:`LT_${uuid.v4()}`,y=G(t,P,b).$bzId;if(!y)throw new Error("No parent id found");if(l[Symbol.for("relation")]==="$self")return;let L=()=>{if(l.$op==="delete")return $?"match":"delete";if(l.$op==="unlink")return $?"unlink":"delete";if(l.$op==="link"||l.$op==="create")return $?"link":"create";if(l.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},O={$relation:l[Symbol.for("relation")],$bzId:I,...l.$tempId?{$tempId:l.$tempId}:{},$op:L(),...$?{}:{[l[Symbol.for("role")]]:l.$bzId},[l[Symbol.for("oppositeRole")]]:y,[Symbol.for("dbId")]:s.relations[l[Symbol.for("relation")]].defaultDBConnector.id,[Symbol.for("edgeType")]:"linkField",[Symbol.for("info")]:"normal linkField",[Symbol.for("path")]:l[Symbol.for("path")]};i(O),(l.$op==="unlink"||L()==="unlink")&&$&&i({$relation:l[Symbol.for("relation")],$bzId:I,$op:"match",[l[Symbol.for("oppositeRole")]]:y,[Symbol.for("dbId")]:s.relations[l[Symbol.for("relation")]].defaultDBConnector.id,[Symbol.for("edgeType")]:"linkField",[Symbol.for("info")]:"additional ownrelation unlink linkField",[Symbol.for("path")]:l[Symbol.for("path")]});}if(l.$relation){let $=ut(l,(y,L)=>B.includes(y)),I=radash.mapEntries($,(y,L)=>radash.isArray(L)?[y,L]:radash.isObject(L)?[y,L.$bzId]:[y,L]),E=ut(r,(y,L)=>y.startsWith("$")||y.startsWith("Symbol"));if(Object.keys($).filter(y=>!y.startsWith("$")).length>0){if(l.$op==="create"||l.$op==="delete"){let y=()=>{if(l.$op==="create")return "link";if(l.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},L=radash.mapEntries(I,(S,D)=>Array.isArray(D)?[S,D.map(j=>j.$bzId||j)]:[S,D.$bzId||D]),O={...E,$relation:l.$relation,$op:y(),...L,$bzId:l.$bzId,[Symbol.for("path")]:l[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"};i(O);return}if(l.$op==="match"||l.$op==="update"&&Object.keys($).length>0){let y=0;Object.entries($).forEach(([L,O])=>{let S=radash.isArray(O)?O:[O],D=j=>j==="create"||j==="replace"?"link":j;S.forEach(j=>{if(!j)return;let v=D(j.$op);if(v==="replace")throw new Error("Not supported yet: replace on roleFields");if(v==="unlink"&&y>0)throw y+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let U={...E,$relation:l.$relation,$op:v==="delete"?"unlink":v,[L]:j.$bzId,$bzId:l.$bzId,[Symbol.for("dbId")]:T.defaultDBConnector.id,[Symbol.for("path")]:l[Symbol.for("path")],[Symbol.for("info")]:"updating roleFields",[Symbol.for("edgeType")]:"roleField on L/U/R"};i(U);});});}}}}}),[o,u]};if(!e)throw new Error("Undefined filledBqlRequest");let [F,p]=a(e),h=F.reduce((t,o)=>{if(!o.$bzId)return [...t,o];let u=t.findIndex(n=>n.$bzId===o.$bzId);if(u===-1)return [...t,o];if(t[u].$op==="create"&&o.$op==="match")return t;if(t[u].$op==="match"&&(o.$op==="create"||o.$op==="match"))return [...t.slice(0,u),o,...t.slice(u+1)];throw new Error(`Unsupported operation combination for $tempId "${o.$tempId}". Existing: ${t[u].$op}. Current: ${o.$op}`)},[]),w=p.reduce((t,o)=>{let u=t.find(n=>(n.$id&&n.$id===o.$id||n.$bzId&&n.$bzId===o.$bzId)&&n.$relation===o.$relation&&n.$op===o.$op);if(u){let n={...u};return Object.keys(o).forEach(i=>{if(typeof i=="symbol"||i.startsWith("$"))return;let c=u[i],r=o[i];Array.isArray(c)&&Array.isArray(r)?n[i]=Array.from(new Set([...c,...r])):!Array.isArray(c)&&Array.isArray(r)?c!==void 0?n[i]=Array.from(new Set([c,...r])):n[i]=r:Array.isArray(c)&&!Array.isArray(r)?r!==void 0&&(n[i]=Array.from(new Set([...c,r]))):c!==null&&r!==null&&c!==void 0&&r!==void 0?n[i]=Array.from(new Set([c,r])):c==null&&(n[i]=r);}),[...t.filter(i=>!((i.$id&&i.$id===o.$id||i.$bzId&&i.$bzId===o.$bzId)&&i.$relation===o.$relation&&i.$op===o.$op)),n]}return [...t,o]},[]);[...new Set(w.map(t=>t.$relation))];h.forEach(t=>{if("$relation"in t&&w.filter(o=>o.$bzId===t.$bzId||o.$tempId&&o.$tempId===t.$tempId).length===0){if(t.$op==="delete"||t.$op==="match"||t.$op==="update")return;throw new Error(`[Borm] Can't create a relation without any player. Node: ${JSON.stringify(ee(t))}`)}}),f.bqlRequest={mutation:{things:h,edges:w}};};var $t=async(f,e)=>{let s=e.dbConnectors[0].id,a=f.typeDB.get(s)?.session,F=f.typeDB.get(s)?.client;if(!a||!a.isOpen()){if(!F)throw new Error("Client not found");a=await F.session(e.dbConnectors[0].dbName,typedbDriver.SessionType.DATA),f.typeDB.set(s,{client:F,session:a});}return {client:F,session:a}};var se=async(f,e)=>{let{dbHandles:s,tqlRequest:a,bqlRequest:F,config:p}=f;if(!a)throw new Error("TQL request not built");if(!(a.deletions&&a.deletionMatches||a.insertions))throw new Error("TQL request error, no things");if(!F?.mutation)throw new Error("BQL mutation not parsed");let{session:h}=await $t(s,p),w=await h.transaction(typedbDriver.TransactionType.WRITE);if(!w)throw new Error("Can't create transaction");let g=a.deletionMatches&&a.deletions&&`match ${a.deletionMatches} delete ${a.deletions}`,R=a.insertions&&`${a.insertionMatches?`match ${a.insertionMatches}`:""} insert ${a.insertions}`;g&&await w.query.delete(g);let t=R&&w.query.insert(R);try{let o=t?await t.collect():void 0;await w.commit(),await w.close(),e.rawTqlRes={insertions:o};}catch(o){throw await w.close(),new Error(`Transaction failed: ${o.message}`)}};var W="___",ae=async f=>{let{enrichedBqlQuery:e}=f;if(!e)throw new Error("BQL query not enriched");let s="",a=(t,o)=>{let u="",n="";for(let d in t){let i=t[d];if(Array.isArray(i))for(let c=0;c<i.length;c++)n+=`{$${o} has ${d} "${i[c]}";}`,c<i.length-1?n+="or":n+=";";else u+=`, has ${d} "${i}"`;}u+=`;
|
|
36
|
-
`,
|
|
37
|
-
|
|
38
|
-
`,
|
|
39
|
-
`,
|
|
40
|
-
`,
|
|
41
|
-
`,
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
`,
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
`,
|
|
49
|
-
`,
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
`,
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
`,
|
|
59
|
-
`,s+=`?queryPath as "queryPath"
|
|
60
|
-
;`,i){let r=i.filter(l=>l.$fieldType==="data");r&&r.length>0&&F(r,u);let b=i.filter(l=>l.$fieldType==="link");b&&b.length>0&&h(b,u,u);let P=i.filter(l=>l.$fieldType==="role");P&&P.length>0&&p(P,u,u);}}})(e),f.tqlRequest=w?g:s;};var qt=f=>{let e=f.dataFields?.map(p=>p.path)||[],s=f.linkFields?.map(p=>p.path)||[],a=Object.keys(f.roles||{})||[];return [...e,...s,...a]},Ct=(f,e)=>Object.keys(f||{}).some(a=>{if(!Array.isArray(f[a])){let F=e.idFields?.includes(a),p=e.dataFields?.some(h=>(h.dbPath===a||h.path===a)&&h?.validations?.unique);return F||p}return !1}),jt=(f,e)=>{let s=e.dataFields?.map(h=>({path:h.path,dbPath:h.dbPath}))||[],a=e.linkFields?.map(h=>({path:h.path,dbPath:h.dbPath}))||[],F=Object.keys(e.roles||{}).map(h=>({path:h,dbPath:h}))||[],p=[...s,...a,...F];return Object.entries(f||{}).reduce((h,[w,g])=>{let R=p.find(t=>t.path===w);return h[R?.dbPath||w]=g,h},{})},de=async f=>{let{rawBqlRequest:e,schema:s}=f;if(Array.isArray(e)){for(let t of e)if(!("$entity"in t)&&!("$relation"in t)&&(!("$thing"in t)||!("$thingType"in t)))throw new Error("No entity specified in query")}else if(!("$entity"in e)&&!("$relation"in e)&&(!("$thing"in e)||!("$thingType"in e)))throw new Error("No entity specified in query");let a=(t,o)=>typeof o=="string"?t.idFields?.includes(o):t.idFields?.includes(o.$path),F=(t,o,u,n,d)=>({$path:o,$dbPath:n,$thingType:"attribute",$as:t.$as||o,$var:o,$fieldType:"data",$excludedFields:t.$excludedFields,$justId:u,$id:t.$id,$filter:t.$filter,$isVirtual:d,$filterProcessed:!0}),p=(t,o,u,n,d)=>{let{target:i,oppositeLinkFieldsPlayedBy:c}=u;return c.map(r=>{let b=i==="role"?r.thingType:"relation",P=i==="role"?r.thing:u.relation,l={[`$${b}`]:P},T=N(s,l),A=t?.$fields?.filter(M=>a(T,M)).length===0,B=[];return typeof t!="string"?t.$fields?A?B=[...t.$fields,...T.idFields]:B=t.$fields:B=qt(T):B=["id"],t.$excludedFields&&(B=B.filter(M=>a(T,M)?!0:!t.$excludedFields.includes(M.$path))),{$thingType:b,$plays:u.plays,$playedBy:r,$path:r.path,$dbPath:d,$as:t.$as||o,$var:o,$thing:P,$fields:B,$excludedFields:t.$excludedFields,$fieldType:"link",$target:i,$intermediary:r.relation,$justId:n,$id:t.$id,$filter:jt(t.$filter,T),$idNotIncluded:A,$filterByUnique:Ct(t.$filter,T),$filterProcessed:!0}})},h=(t,o,u,n,d)=>u.playedBy.map(i=>{let{thing:c,thingType:r,relation:b}=i,P={[`$${r}`]:c},l=N(s,P),T=t?.$fields?.filter(B=>l?.idFields?.includes(B)||l?.idFields?.includes(B.$path)).length===0,A=[];return typeof t!="string"?t.$fields?T?A=[...t.$fields,...l.idFields]:A=t.$fields:A=qt(l):A=["id"],t.$excludedFields&&(A=A.filter(B=>a(l,B)?!0:!t.$excludedFields.includes(B.$path))),{$thingType:r,$path:o,$dbPath:d,$as:t.$as||o,$var:o,$thing:c,$fields:A,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:b,$justId:n,$id:t.$id,$filter:jt(t.$filter,l),$idNotIncluded:T,$filterByUnique:Ct(t.$filter,l),$playedBy:i,$filterProcessed:!0}}),w=(t,o)=>{let u=typeof t=="string"?t:t.$path,n=typeof t=="string",d=o.dataFields?.find(r=>r.path===u),i=o.linkFields?.find(r=>r.path===u),c=o.roles?.[u];if(d){let r=d.isVirtual&&d.default;return F(t,u,n,d.dbPath,r)}else {if(i)return p(t,u,i,n,i.dbPath);if(c)return h(t,u,c,n,c.dbPath)}return null},R=(t=>immer.produce(t,o=>objectTraversal.traverse(o,u=>{let{value:n,meta:d}=u,i=n;if(radash.isObject(i)){if(i.$id){let c=i.$entity||i.$relation?i:{[`$${i.$thingType}`]:i.$thing},r=N(s,c);if(!r?.name)throw new Error(`Schema not found for ${i.$thing}`);if(i.$path=r.name,Array.isArray(i.$id)||(i.$filterByUnique=!0),r?.idFields?.length===1){let[b]=r.idFields;i.$filter={...i.$filter,[b]:i.$id},delete i.$id;}else throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in i||"$relation"in i||"$thing"in i){let c=N(s,i);if(!c?.name)throw new Error(`Schema not found for ${i.$thing}`);i.$path=c.name;}if(i.$entity?(i.$thing=i.$entity,i.$thingType="entity",delete i.$entity):i.$relation&&(i.$thing=i.$relation,i.$thingType="relation",delete i.$relation),radash.isObject(i)&&"$thing"in i){let c=i.$entity||i.$relation?i:{[`$${i.$thingType}`]:i.$thing};i[H]=d.nodePath;let r=N(s,c);if(i.$filter&&(i.$filterByUnique=Ct(i.$filter,r),i.$filterProcessed||(i.$filter=jt(i.$filter,r))),i.$fields){i.$fields.filter(l=>r?.idFields?.includes(l)||r?.idFields?.includes(l.$path)).length>0||(i.$fields=[...i.$fields,...Array.isArray(r.idFields)?r.idFields:[]],i.$idNotIncluded=!0);let P=i.$fields?.flatMap(l=>{let T=w(l,r);return Array.isArray(T)?T:[T]}).filter(Boolean);i.$fields=P;}else {let P=qt(r)?.flatMap(l=>{let T=w(l,r);return Array.isArray(T)?T:[T]}).filter(Boolean);i.$fields=P;}i.$excludedFields&&(i.$fields=i.$fields.filter(b=>a(r,b)?!0:!i.$excludedFields.includes(b.$path)));}}})))(Array.isArray(e)?e:[e]);f.enrichedBqlQuery=R;};var pe=async(f,e)=>{let{dbHandles:s,enrichedBqlQuery:a,tqlRequest:F,config:p}=f;if(!a)throw new Error("BQL request not parsed");if(!F)throw new Error("TQL request not built");let h=new typedbDriver.TypeDBOptions;if(h.infer=!0,Array.isArray(F)){let g=await radash.parallel(F.length,F,async R=>{let{session:t}=await $t(s,p),o=await t.transaction(typedbDriver.TransactionType.READ,h);if(!o)throw new Error("Can't create transaction");let n=await o.query.fetch(R).collect();return await o.close(),n});e.rawTqlRes=g,e.isBatched=!0;}else {let{session:g}=await $t(s,p),R=await g.transaction(typedbDriver.TransactionType.READ,h);if(!R)throw new Error("Can't create transaction");let o=await R.query.fetch(F).collect();await R.close(),e.rawTqlRes=o;}};var ue=f=>{let e=/as:([a-zA-Z0-9_\-·]+)/,s=/justId:([a-zA-Z0-9_\-·]+)/,a=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,F=/filterByUnique:([a-zA-Z0-9_\-·]+)/,p=f.match(e),h=f.match(s),w=f.match(a),g=f.match(F);return {as:p?p[1]:null,justId:h?h[1]:null,idNotIncluded:w?w[1]:null,filterByUnique:g?g[1]:null}},gi=f=>{try{let s=(F=>{let p=F.replace("$metadata:","");return p=p.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),p=p.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(h,w,g)=>/^{.*}$/.test(g)?`:${g}`:`:${w}"${g}"`),p=p.replace(/\[([^\]]+)\]/g,(h,w)=>`[${w.split(",").map(g=>g.trim().startsWith("{")&&g.trim().endsWith("}")?g.trim():`"${g.trim()}"`).join(",")}]`),p})(f);return JSON.parse(s)}catch(e){return console.error(e),{as:[]}}},fe=async(f,e)=>{let{enrichedBqlQuery:s,rawBqlRequest:a,schema:F,config:p}=f,{rawTqlRes:h,isBatched:w}=e;if(s){if(!h)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");let g=(i,c)=>{let{$metaData:r}=i,{as:b}=gi(r),P=Object.entries(i).filter(([l])=>l!=="type"&&!l.includes("$")).map(([l,T])=>{let A=c.dataFields?.find(m=>m.path===l||m.dbPath===l),B=l==="id",M=Array.isArray(b)?b.find(m=>m[l])?.[l]:l,k;if(A?.cardinality==="ONE"){if(k=T[0]?T[0].value:p.query?.returnNulls?null:void 0,A.contentType==="DATE"&&(k=k&&`${k}Z`),B)return [[M,k],["$id",k]].filter(([m,Q])=>Q!==void 0)}else if(A?.cardinality==="MANY"){if(!radash.isArray(T))throw new Error("Typedb fetch has changed its format");if(T.length===0)return p.query?.returnNulls?[[M,null]]:[];A.contentType==="DATE"?k=T.map(m=>`${m.value}Z`):k=T.map(m=>m.value);}return [[M,k]].filter(([m,Q])=>Q!==void 0)}).flat();return Object.fromEntries([...P])},R=i=>i.reduce((c,r)=>{let{$roleFields:b,$metaData:P,$cardinality:l}=r,{as:T,justId:A,idNotIncluded:B,filterByUnique:M}=ue(P),k=b.map(m=>{let{dataFields:Q,currentSchema:$,linkFields:I,roleFields:E,schemaValue:y}=o(m),L=g(Q,$);if(A==="T")return L.id;{let O=t(I),S=R(E),D={...L};return B==="true"&&$?.idFields?.forEach(j=>delete D[j]),{...D,...O,...S,...y}}});return k.length>0?c[T]=l==="MANY"&&M==="false"?k:k[0]:p.query?.returnNulls&&(c[T]=null),c},{}),t=i=>i.reduce((c,r)=>{let{$linkFields:b,$metaData:P,$cardinality:l}=r,{as:T,justId:A,idNotIncluded:B,filterByUnique:M}=ue(P),k=b.map(m=>{let{dataFields:Q,currentSchema:$,linkFields:I,roleFields:E,schemaValue:y}=o(m),L=g(Q,$);if(A==="T")return L.id;{let O=t(I),S=R(E),D={...L};return B==="true"&&$.idFields?.forEach(j=>delete D[j]),{...D,...O,...S,...y}}});return c[T]=k.length>0?l==="MANY"&&M==="false"?k:k[0]:p.query?.returnNulls?null:void 0,c},{}),o=i=>{let c=Object.keys(i),r=c.find(m=>m.endsWith(".$dataFields"));if(!r)throw new Error("No datafields");let b=i[r],P=r.split(".")[r.split(".").length-2];if(b.$metaData=P,b.length===0)throw new Error("No datafields");let l=b.type,T={$thing:l.label,$thingType:l.root,[H]:i.queryPath.value},A={[`$${T.$thingType}`]:T.$thing},B=N(F,A),M=c.filter(m=>!m.endsWith(".$dataFields")&&B.linkFields?.some(Q=>Q.path===m.split(".").pop())).map(m=>({$linkFields:i[m],$key:m.split(".").pop(),$metaData:m.split(".")[m.split(".").length-2],$cardinality:B?.linkFields?.find(Q=>Q.path===m.split(".").pop())?.cardinality})),k=c.filter(m=>!m.endsWith(".$dataFields")&&B.roles?.[m.split(".").pop()]).map(m=>({$roleFields:i[m],$key:m.split(".").pop(),$metaData:m.split(".")[m.split(".").length-2],$cardinality:B.roles[m.split(".").pop()].cardinality}));return {dataFields:b,schemaValue:T,currentSchema:B,linkFields:M,roleFields:k}},u=i=>i.map(c=>{let{dataFields:r,currentSchema:b,linkFields:P,roleFields:l,schemaValue:T}=o(c),A=g(r,b),B=t(P),M=R(l),k=a?.$fields?.every(Q=>!b?.idFields?.includes(Q)&&!b?.idFields?.includes(Q.$path));return {...B,...M,...T,...!p.query?.noMetadata&&a.$id?{$id:Array.isArray(a.$id)?A.id:a.$id}:{},...k?Object.fromEntries(Object.entries(A).filter(([Q])=>!b?.idFields?.includes(Q))):A}}),d=(i=>{let c=r=>{let b=u(r);return a.$id&&!Array.isArray(a.$id)||s[0].$filterByUnique?b[0]??null:b.length===0?null:b};return w?i.map(c):c(i)})(h);e.bqlRes=d;};var Bi=Symbol.for("grandChildOfCreate"),he=async f=>{let{filledBqlRequest:e,config:s,schema:a}=f,F=(B,M)=>Object.keys(B).filter(k=>k.startsWith("$")?!1:M?!N(a,B).dataFields?.find(Q=>Q.path===k):!0);if(!e)throw new Error("[BQLE-M-PQ-1] No filledBqlRequest found");if(s.mutation?.preQuery===!1)return;let p=[];if(objectTraversal.traverse(e,({parent:B,key:M,value:k})=>{B&&M&&!M.includes("$")&&radash.isObject(B)?(Array.isArray(B[M])?B[M]:[B[M]]).forEach(Q=>{if(radash.isObject(Q)){if(B.$op!=="create")p.includes(Q.$op)||p.push(Q.$op);else if(Q.$op==="delete"||Q.$op==="unlink")throw new Error(`Cannot ${Q.$op} under a create`)}}):!B&&radash.isObject(k)&&(p.includes(k.$op)||p.push(k.$op));}),!p.includes("delete")&&!p.includes("unlink")&&!p.includes("replace")&&!p.includes("update")&&!p.includes("link"))return;let w=(B=>{let M=(k,m)=>{let Q=[],$={},I=["$op","$bzId","$parentKey"],E=["$relation","$entity","$id",...I];for(let y in k)if(!I.includes(y)&&!(E.includes(y)&&!m))if(!y.includes("$")&&(radash.isObject(k[y])||Array.isArray(k[y]))){let L=k[y];Array.isArray(L)&&L.length>0?L.forEach(O=>{Q.push({$path:y,...M(O)});}):Q.push({$path:y,...M(L)});}else $[y]=k[y];return {...$,$fields:Q}};return B.map(k=>M(k,!0))})(Array.isArray(e)?e:[e]),g=await Et(w,f.config,f.schema,f.dbHandles),R=(B,M)=>{let k=B.$id||B.id||B.$bzId;if(B.$objectPath){let{$objectPath:m}=B,Q=m?.beforePath||"root",$=Array.isArray(m.ids)?`[${m.ids}]`:m.ids;return {beforePath:`${Q}.${$}___${m.key}`,ids:k,key:M}}else return {beforePath:"root",ids:k,key:M}},t=(B,M)=>{let k=B?.beforePath||"root",m=M||(Array.isArray(B?.ids)?`[${B?.ids}]`:B?.ids);return `${k}.${m}___${B?.key}`},o=B=>{if(B.includes("[")&&B.includes("]")){let[M,k,m]=B.split(/[[\]]/);return k.split(",").map($=>`${M}${$}${m}`)}else return [B]},u={};(B=>immer.produce(B,M=>objectTraversal.traverse(M,k=>{let{key:m,parent:Q}=k;if(Q&&m&&Q.$id&&!m.includes("$")){let $=R(Q,m),I=t($);if(Array.isArray(Q[m])){let E=[];Q[m].forEach(y=>{radash.isObject(y)?(y.$objectPath=$,E.push(y.$id.toString())):y&&E.push(y.toString());}),u[I]={$objectPath:$,$ids:E};}else {let E=Q[m];radash.isObject(E)?(u[I]={$objectPath:$,$ids:[E.$id.toString()]},E.$objectPath=$):E&&(u[I]={$objectPath:$,$ids:[E.toString()]});}}})))(g||{});let d=B=>immer.produce(B,M=>objectTraversal.traverse(M,k=>{let{key:m,value:Q,parent:$}=k;$&&m&&!m.includes("$")&&(Array.isArray(Q)||radash.isObject(Q))&&!Array.isArray($)&&(Array.isArray($[m])?$[m].forEach(I=>{typeof I!="string"&&(I.$objectPath=R($,m),I.$parentIsCreate=$.$op==="create",I[Bi]=$.$parentIsCreate||$[Symbol.for("grandChildOfCreate")]);}):radash.isObject($[m])&&($[m].$parentIsCreate=$.$op==="create",$[m][Symbol.for("grandChildOfCreate")]=$.$parentIsCreate||$[Symbol.for("grandChildOfCreate")],$[m].$objectPath=R($,m)));})),i=d(e),r=(B=>{let M=($,I)=>{let E=[];$.filter(S=>S).forEach(S=>{let D=Object.keys(S).filter(j=>!j.startsWith("$")).length;if(Array.isArray(S.$id)&&D>0){let j=S.$id.map(v=>({...S,$id:v}));E=[...E,...j];}else E.push({...S});});let y=[],L=[],O=E.filter(S=>{let j=["delete","update","unlink"].includes(S.$op||""),v=F(S,!0).length;if((!S.$id||Array.isArray(S.$id)&&v>0||S.$filter)&&j)return !0;L.push({...S});});return O.length>0?O.forEach(S=>{let j=(z=>{let lt=(()=>{let _={};for(let x in z){let Y=N(a,z);!x.startsWith("$")&&Y.dataFields?.find(ot=>ot.path===x)&&(_[x]=z[x]);}return _})(),dt=Object.keys(z),Z=dt.filter(_=>!_.startsWith("$")),Tt=[],mt=(_,x)=>{if(_===Z.length){let ot={...x};dt.forEach(V=>{V.startsWith("$")&&(ot[V]=z[V]);}),Tt.push(ot);return}let Y={...x,[Z[_]]:z[Z[_]],...X(x),...lt};mt(_+1,Y),mt(_+1,x);};return mt(0,{...X(z)}),Tt})(S).filter(z=>!(z.$op==="update"&&Object.keys(z).filter(et=>!et.startsWith("$")).length===0)),v=[],U=t(S.$objectPath),q=u[U]?u[U].$ids:[],C=j.map((z,et)=>{let lt=N(a,z),Z=Object.keys(z).filter(x=>!x.includes("$")&&!lt.dataFields?.some(Y=>Y.path===x)).map(x=>(Array.isArray(z[x])?z[x].length>1?z[x].filter(V=>!V.$id||Array.isArray(V.$id)||V.$filter):z[x]:[z[x]]).map(V=>{let Lt=t(V.$objectPath);return {idsToKey:(Mt=>{let xt=[],pt=Mt.split("."),Ne=pt.slice(0,pt.length-1).join("."),De=pt.slice(pt.length-1,pt.length)[0].split("___")[1];for(let Qt in u)if(Qt.startsWith(Ne)&&Qt.endsWith(De)){let Pt=Qt.split("."),xe=Pt.slice(Pt.length-1,Pt.length)[0].split("___")[0];xt.push(xe);}return xt})(Lt),key:x,multiple:V}})).filter(x=>x!==void 0),_=(x=>{let Y=x.map(V=>V.map(it=>it.idsToKey));return (V=>V.length>0?V.reduce((it,ct)=>it.concat(ct),[]).reduce((it,ct)=>it?ct.filter(Mt=>it.includes(Mt)):ct):[])(Y)})(Z).filter(x=>!v.includes(x));if(v=[...v,..._],q=q.filter(x=>!_.includes(x)),et===j.length-1&&q.length>0)return {...z,$id:q,$bzId:`T1_${uuid.v4()}`,...X(z)};if(_.length>0)return {...z,$id:_,$bzId:`T2_${uuid.v4()}`,...X(z)}}).filter(z=>z!==void 0),je=(()=>{if(C.length===0&&!I?.$id)return O;if(C.length===0&&I?.$id){let z=Array.isArray(I.$id)?I.$id:[I.$id],et=[];return z.forEach(lt=>{let dt=t({...S.$objectPath,ids:lt}),Z=u[dt];Z&&et.push({...S,$id:Z.$ids,...X(S),$bzId:`T_${uuid.v4()}`});}),et}else return C.filter(z=>z!==void 0)})();y=[...L,...je].map(k);}):y=E.map(k),y},k=$=>{let I={...$,$bzId:$.$tempId??`T3_${uuid.v4()}`,...X($)},E=N(a,$);return Object.keys($).filter(y=>!y.includes("$")&&!E.dataFields?.some(L=>L.path===y)).forEach(y=>{let L=Array.isArray($[y])?$[y]:[$[y]],O=M(L,$);I[y]=O.length>0?O:void 0;}),I},m=[];return B.forEach($=>{m=[...m,...M([$])];}),m.map($=>k($))})(Array.isArray(i)?i:[i]),b=B=>B.map(M=>{let k=F(M,!0),m={...M};return k.forEach(Q=>{let $=Array.isArray(M[Q])?M[Q]:[M[Q]],I=[],E=[],y=[],L={},O=At(a,M,Q);$.filter(C=>C).forEach(C=>{C.$op==="replace"&&C.$id?(L=C,Array.isArray(C.$id)?E=[...E,...C.$id]:E.push(C.$id)):C.$op==="create"&&O==="ONE"&&C.id?(L=C,Array.isArray(C.id)?y=[...E,...C.id]:y.push(C.id)):I.push(C);});let S=t(L.$objectPath),j=o(S).map(C=>u[C]),v=[];j.filter(C=>C!=null).forEach(C=>{v=[...v,...C.$ids];});let U=v.filter(C=>!E.includes(C)),J=E.filter(C=>!v.includes(C)),q=X(L);U.length>0&&I.push({...L,$op:"unlink",$id:U,$bzId:`T4_${uuid.v4()}`,id:void 0,...q}),J.length>0&&J.forEach(C=>{I.push({...L,$op:"link",$id:C,$bzId:`T5_${uuid.v4()}`,...q});}),y.length>0&&y.forEach(C=>{I.push({...L,$op:"create",id:C,$bzId:`T6_${uuid.v4()}`,...q});}),m[Q]=b(I);}),m}),P=d(b(d(r)));(B=>immer.produce(B,M=>objectTraversal.traverse(M,k=>{let{key:m,value:Q,parent:$}=k;m&&$&&!m?.includes("$")&&(Array.isArray(Q)||radash.isObject(Q))&&!Array.isArray($)&&(Array.isArray(Q)?Q:[Q]).forEach(E=>{let y=u[t(E.$objectPath)],L=(D,j)=>D.every(v=>j.includes(v)),O=E.$id?Array.isArray(E.$id)?L(E.$id,y?y.$ids:[]):y?.$ids.includes(E.$id):y,S=At(a,$,E.$objectPath.key);if(E.$op==="link"&&O&&S==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${t(E.$objectPath)}" because it is already occupied.`);if(E.$op)switch(E.$op){case"delete":if(!O&&!s.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${E.$id}" because it is not linked to $id:"${$.$id}"`);break;case"update":if(!O&&!s.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${E.$id}" because it is not linked to $id:"${$.$id}"`);break;case"unlink":if(!O&&!s.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${E.$id}" because it is not linked to $id:"${$.$id}"`);break;case"link":if(O)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${E.$id}" because it is already linked to $id:"${$.$id}"`);break;}});})))(P);let A=(B=>immer.produce(B,M=>objectTraversal.traverse(M,k=>{let{value:m,meta:Q}=k;radash.isObject(m)&&(m[Symbol.for("path")]=Q.nodePath,delete m.$objectPath,delete m.$parentIsCreate);})))(P);f.filledBqlRequest=A;};var ge=async f=>{let{filledBqlRequest:e,schema:s}=f;if(!e)throw new Error("Filled BQL request is missing");let F=(w=>immer.produce(w,g=>objectTraversal.traverse(g,({value:R})=>{if(radash.isObject(R)){let t=R,o=N(s,t),{unidentifiedFields:u}=nt(o,t),{idFields:n,computedFields:d,virtualFields:i}=o;if(!n)throw new Error("No idFields found");let[c]=n,r=radash.listify(t,(l,T)=>T!==void 0?l:void 0),b=r.filter(l=>i?.includes(l));if(b.length>0)throw new Error(`Virtual fields can't be sent to DB: "${b.join(",")}"`);if(d.filter(l=>!r.includes(l)).forEach(l=>{let T=o.dataFields?.find(m=>m.path===l),B=o.linkFields?.find(m=>m.path===l)?.oppositeLinkFieldsPlayedBy[0],M="roles"in o?ft(o.roles,(m,Q)=>m===l):void 0,k=T||B||M;if(!k)throw new Error(`no field Def for ${l}`);if(l!==c&&t.$op==="create"&&!t[l]){let m=tt({currentThing:t,fieldSchema:k,mandatoryDependencies:!0});t[l]=m;}}),u.length>0)throw new Error(`Unknown fields: [${u.join(",")}] in ${JSON.stringify(t)}`)}})))(e),h=(w=>immer.produce(w,g=>objectTraversal.traverse(g,({value:R})=>{radash.isObject(R);})))(F);f.filledBqlRequest=h;};var kt=(f,e)=>{let s=N(e,f).hooks;if(s?.pre){let a=`on${Ht(f.$op)}`;return s.pre.filter(h=>h.triggers[a]?.()).flatMap(h=>h.actions)}return []};var we=async f=>{let{filledBqlRequest:e,schema:s}=f;if(!e)throw new Error("Filled BQL request is missing");let F=(g=>immer.produce(g,R=>objectTraversal.traverse(R,({value:t})=>{radash.isObject(t)&&Gt();})))(e),p=radash.isArray(F)?F:[F],w=(g=>immer.produce(g,R=>objectTraversal.traverse(R,({value:t,parent:o,key:u,meta:n})=>{if(st(t)){if(!o||u===void 0||u===null)throw new Error("[Internal] Parent is missing, should not happen as we artificially have always a root array");let d=kt(t,s).filter(b=>b.type==="transform"),i=structuredClone(G(g,o,n)),c=immer.isDraft(t)?immer.current(t):t,r=structuredClone(c);d.forEach(b=>{let P=b.fn(r,i);Object.keys(P).length!==0&&(o[u]={...c,...P});});}})))(p);if(!radash.isArray(w))throw new Error("[Internal] withTransformedNodes is not an array");w.length>1?f.filledBqlRequest=w:f.filledBqlRequest=w[0];};var Le=async f=>{let{filledBqlRequest:e,schema:s}=f;if(!e)throw new Error("Filled BQL request is missing");let a=p=>immer.produce(p,h=>objectTraversal.traverse(h,({value:w})=>{if(radash.isObject(w)&&("$entity"in w||"$relation"in w)){let g=w,{requiredFields:R,enumFields:t,fnValidatedFields:o}=N(s,g);"$op"in g&&g.$op==="create"&&R.forEach(u=>{if(!(u in g))throw new Error(`[Validations] Required field "${u}" is missing.`)}),("$op"in g&&g.$op==="update"||g.$op==="create")&&t.forEach(u=>{if(u in g){let n=g[ht]?.dataFields?.find(d=>d.path===u)?.validations?.enum;if(!n)throw new Error(`[Validations] Enum field "${u}" is missing enum options.`);if(radash.isArray(g[u]))g[u].some(d=>{if(!n.includes(d))throw new Error(`[Validations] Option "${d}" is not a valid option for field "${u}".`)});else if(n&&!n.includes(g[u]))throw new Error(`[Validations] Option "${g[u]}" is not a valid option for field "${u}".`)}}),("$op"in g&&g.$op==="update"||g.$op==="create")&&o.forEach(u=>{if(u in g)try{let n=g[ht]?.dataFields?.find(d=>d.path===u)?.validations?.fn;if(!n)throw new Error("Missing validation function.");if(!n(g[u]))throw new Error("Failed validation function.")}catch(n){throw new Error(`[Validations:attribute:${u}] ${n.message}`)}});}})),F=p=>immer.produce(p,h=>objectTraversal.traverse(h,({value:w,parent:g,meta:R})=>{if(radash.isObject(w)&&("$entity"in w||"$relation"in w)){let t="$entity"in w?w.$entity:w.$relation,o=w,u=structuredClone(G(p,g,R)),n=structuredClone(immer.isDraft(o)?immer.current(o):o);kt(o,s).forEach(i=>{if(i.type==="validate"){if(i.severity!=="error")return;try{let c=i.fn(n,u);if(c===!1)throw new Error(`${i.message}.`);if(c!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(c){throw new Error(`[Validations:thing:${t}] ${c.message}`)}}});}}));a(e),F(e);};var Me=async(f,e)=>{let{schema:s,enrichedBqlQuery:a}=f,{bqlRes:F}=e;if(!F)return;let h=(w=>immer.produce(w,g=>objectTraversal.traverse(g,({value:R})=>{if(radash.isObject(R)){let t=R;if(!t.$thing)throw new Error("[Internal] Thing is missing");if(t.$thing){let o=N(s,t),{virtualFields:u}=o,n=t[H];if(!n)throw new Error("[Internal] QueryPath is missing");let d=objectTraversal.getNodeByPath(a,n),i=d.$fields.map(r=>r.$path),c=d.$excludedFields;u.forEach(r=>{if(c?.includes(r)||i.length>0&&!i.includes(r))return;let b=o.dataFields?.find(P=>P.path===r);if(b?.default){let P=tt({currentThing:t,fieldSchema:b,mandatoryDependencies:!0});t[r]=P;}else if(t[r]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${r}`)}),c&&c.forEach(r=>{if(typeof r!="string")throw new Error("[Internal] ExcludedField is not a string");delete t[r];});}}})))(F);e.bqlRes=h;};var Re=async(f,e)=>{let{config:s}=f,{bqlRes:a}=e;if(!a)return;let p=(g=>immer.produce(g,R=>objectTraversal.traverse(R,({value:t})=>{radash.isObject(t);})))(a),w=(g=>immer.produce(g,R=>objectTraversal.traverse(R,({value:t})=>{if(radash.isObject(t)){let o=t;Object.keys(o).forEach(u=>{o[u]===void 0&&delete o[u];}),Object.getOwnPropertySymbols(o).forEach(u=>{delete o[u];}),s.query?.noMetadata===!0&&Object.keys(o).forEach(u=>{u.startsWith("$")&&delete o[u];});}})))(p);e.bqlRes=w;};var Ae={query:[de,ae,pe,fe,Me,Re],mutation:[te,he,ge,we,Le,oe,Zt,se,Kt,Jt]},Nt=async(f,e,s={},a=!0)=>{for(let F of f){let p=await F(e,s);if(p&&Array.isArray(p))for(let h of p)await Nt(h.pipeline,h.req,h.res,!1);}return a&&e.config.query?.debugger===!0&&typeof s.bqlRes=="object"?{...s.bqlRes,$debugger:{tqlRequest:e.tqlRequest}}:s.bqlRes},Et=(f,e,s,a)=>Nt(Ae.query,{config:e,schema:s,rawBqlRequest:f,dbHandles:a},{}),Oe=(f,e,s,a)=>Nt(Ae.mutation,{config:e,schema:s,rawBqlRequest:f,dbHandles:a},{});var Dt=class{schema;config;dbHandles;constructor({schema:e,config:s}){this.schema=e,this.config=s;}getDbHandles=()=>this.dbHandles;init=async()=>{let e={typeDB:new Map},s=Wt(this.schema);await Promise.all(this.config.dbConnectors.map(async a=>{if(a.provider==="typeDB"&&a.dbName){let[F,p]=await radash.tryit(typedbDriver.TypeDB.coreDriver)(a.url);if(F){let h=`[BORM:${a.provider}:${a.dbName}:core] ${F.message??"Can't create TypeDB Client"}`;throw new Error(h)}try{let h=await p.session(a.dbName,typedbDriver.SessionType.DATA);e.typeDB.set(a.id,{client:p,session:h});}catch(h){let w=`[BORM:${a.provider}:${a.dbName}:session] ${(h.messageTemplate?._messageBody()||h.message)??"Can't create TypeDB Session"}`;throw new Error(w)}}if(a.provider==="typeDBCluster"&&a.dbName){let[F,p]=await radash.tryit(typedbDriver.TypeDB.cloudDriver)(a.addresses,a.credentials);if(F){let h=`[BORM:${a.provider}:${a.dbName}:core] ${F.message??"Can't create TypeDB Cluster Client"}`;throw new Error(h)}try{let h=await p.session(a.dbName,typedbDriver.SessionType.DATA);e.typeDB.set(a.id,{client:p,session:h});}catch(h){let w=`[BORM:${a.provider}:${a.dbName}:session] ${(h.messageTemplate?._messageBody()||h.message)??"Can't create TypeDB Session"}`;throw new Error(w)}}})),this.schema=s,this.dbHandles=e;};#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(),vt(this.config,this.schema,this.dbHandles));query=async(e,s)=>{await this.#t();let a={...this.config,query:{...It.query,...this.config.query,...s}};return Et(e,a,this.schema,this.dbHandles)};mutate=async(e,s)=>{await this.#t();let a={...this.config,mutation:{...It.mutation,...this.config.mutation,...s}};return Oe(e,a,this.schema,this.dbHandles)};close=async()=>{this.dbHandles&&this.dbHandles.typeDB.forEach(async({client:e,session:s})=>{s.isOpen()&&await s.close(),await e.close();});}},so=Dt;//! Todo: delete when this works with the new $thing and $thingType fields
|
|
61
|
-
|
|
62
|
-
|
|
36
|
+
${h}`})(),d=e.dbConnectors[0].id,s=n.typeDB.get(d)?.session,B=n.typeDB.get(d)?.client;if(!s){console.log("Session Status: ","NO SESSION");return}await s.close();let[{dbName:L}]=e.dbConnectors;await(await B.databases.get(L)).delete(),await B.databases.create(L);let r=await B.session(e.dbConnectors[0].dbName,typedbDriver.SessionType.SCHEMA),l=await r.transaction(typedbDriver.TransactionType.WRITE);await l.query.define(a),await l.commit(),await l.close();let o=await r.transaction(typedbDriver.TransactionType.READ);(await(await o.query.match("match $a sub thing;")).collect()).forEach(async h=>{h.get("a");}),await o.close();};var te={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var re=(e,t,n)=>n?t:`${e}\xB7${t}`;var ne=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([n,p])=>t(n,p))))[0],mt=(e,t)=>Object.fromEntries(Object.entries(e).filter(([n,p])=>t(n,p))),ie=(e,t)=>{let n=[],p=immer.produce(e,d=>objectTraversal.traverse(d,({key:s,value:B,meta:L})=>{if(L.depth===2&&(s&&(B.dataFields=B.dataFields?.map(u=>({...u,cardinality:u.cardinality||"ONE",dbPath:re(s,u.path,u.shared)}))),B.extends)){let u=d.entities[B.extends]||d.relations[B.extends];if(B.allExtends=[B.extends,...u.allExtends||[]],B.idFields=u.idFields?(B.idFields||[]).concat(u.idFields):B.idFields,B.dataFields=u.dataFields?(B.dataFields||[]).concat(u.dataFields.map(r=>{let l=B.extends,o=e.entities[l]||e.relations[l];for(;!o.dataFields?.find(f=>f.path===r.path);)l="extends"in o?o.extends:void 0,o=e.entities[l]||e.relations[l];return {...r,dbPath:re(l,r.path,r.shared)}})):B.dataFields,B.linkFields=u.linkFields?(B.linkFields||[]).concat(u.linkFields):B.linkFields,"roles"in u){let r=B,l=u;r.roles=r.roles||{},r.roles={...r.roles,...l.roles},Object.keys(r.roles).length===0&&(r.roles={});}}},{traversalType:"breadth-first"}));return objectTraversal.traverse(e,({key:d,value:s,meta:B})=>{if(d==="linkFields"){let u=(()=>{if(!B.nodePath)throw new Error("No path");let[l,o]=B.nodePath.split(".");return {thing:o,thingType:l==="entities"?"entity":l==="relations"?"relation":""}})(),r=Array.isArray(s)?s.map(l=>({...l,...u})):[{...s,...u}];n.push(...r);}}),immer.produce(p,d=>objectTraversal.traverse(d,({value:s,key:B,meta:L})=>{if(L.depth===2&&s.idFields&&!s.id){s.name=B;let u=()=>{if(L.nodePath?.split(".")[0]==="entities")return "entity";if(L.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};s.thingType=u();let r=Object.keys(t).find(l=>t[l].get(s.defaultDBConnector.id));s.db=r,s.dbContext=te[r],s.computedFields=[],s.virtualFields=[],s.requiredFields=[],s.enumFields=[],s.fnValidatedFields=[],"roles"in s&&Object.entries(s.roles).forEach(([o,f])=>{f.fieldType="roleField",f.playedBy=n.filter(c=>c.relation===B&&c.plays===o)||[],f.name=o;}),"linkFields"in s&&s.linkFields&&s.linkFields?.forEach(o=>{if(o.fieldType="linkField",o.target==="relation"){o.oppositeLinkFieldsPlayedBy=[{plays:o.path,thing:o.relation,thingType:"relation"}];return}let f=n.filter(i=>i.relation===o.relation&&i.plays!==o.plays)||[];o.oppositeLinkFieldsPlayedBy=f;let{filter:c}=o;o.oppositeLinkFieldsPlayedBy=o.oppositeLinkFieldsPlayedBy.filter(i=>i.target==="role"),c&&Array.isArray(c)&&(o.oppositeLinkFieldsPlayedBy=o.oppositeLinkFieldsPlayedBy.filter(i=>c.some(h=>i.thing===h.$role)),o.oppositeLinkFieldsPlayedBy=o.oppositeLinkFieldsPlayedBy.filter(i=>c.some(h=>i.thing===h.$thing))),c&&!Array.isArray(c)&&(o.oppositeLinkFieldsPlayedBy=o.oppositeLinkFieldsPlayedBy.filter(i=>i.$role===c.$role),o.oppositeLinkFieldsPlayedBy=o.oppositeLinkFieldsPlayedBy.filter(i=>i.thing===c.$thing));});}if(typeof s=="object"&&"playedBy"in s){if([...new Set(s.playedBy?.map(u=>u.thing))].length>1)throw new Error(`Unsupported: roleFields can be only played by one thing. Role: ${B} path:${L.nodePath}`);if(s.playedBy.length===0)throw new Error(`Unsupported: roleFields should be played at least by one thing. Role: ${B}, path:${L.nodePath}`)}if(L.depth===4){let[u,r]=L.nodePath?.split(".")||[],l=d[u][r];s.validations&&(s.validations.required&&l.requiredFields.push(s.path),s.validations.enum&&l.enumFields.push(s.path),s.validations.fn&&l.fnValidatedFields.push(s.path)),s.default?s.isVirtual?l.virtualFields.push(s.path):l.computedFields.push(s.path):s.isVirtual&&l.virtualFields.push(s.path);}}))},O=(e,t)=>{if(!t)throw new Error("[Internal] No node for getCurrentSchema");if(t.$thing){if(t.$thingType==="entity"){if(!(t.$thing in e.entities))throw new Error(`Missing entity '${t.$thing}' in the schema`);return e.entities[t.$thing]}if(t.$thingType==="relation"){if(!(t.$thing in e.relations))throw new Error(`Missing relation '${t.$thing}' in the schema`);return e.relations[t.$thing]}if(t.$thing in e.entities&&t.$thing in e.relations)throw new Error(`Ambiguous $thing ${t.$thing}`);if(t.$thing in e.entities)return e.entities[t.$thing];if(t.$thing in e.relations)return e.relations[t.$thing];throw new Error(`Wrong schema or query for ${JSON.stringify(t,null,2)}`)}if(t.$entity){if(!(t.$entity in e.entities))throw new Error(`Missing entity '${t.$entity}' in the schema`);return e.entities[t.$entity]}if(t.$relation){if(!(t.$relation in e.relations))throw new Error(`Missing relation '${t.$relation}' in the schema`);return e.relations[t.$relation]}throw new Error(`Wrong schema or query for ${JSON.stringify(t,null,2)}`)},oe=(e,t)=>{let n=e.$thing||e.$entity||e.$relation;if(!n)throw new Error("[Internal] No thing found");if(e.$entity)return "entity";if(e.$relation)return "relation";if(t.entities[n])return "entity";if(t.relations[n])return "relation";throw new Error("No thing found")},xt=(e,t,n)=>{let p=O(e,t),a=p.linkFields?.find(B=>B.path===n);if(a)return a;let d=p.dataFields?.find(B=>B.path===n);if(d)return d;let s="roles"in p?p.roles?.[n]:void 0;if(s)return s},jt=(e,t,n)=>xt(e,t,n)?.cardinality,U=(e,t)=>{let n=e.dataFields?.map(c=>c.path)||[],p=e.linkFields?.map(c=>c.path)||[],a="roles"in e?radash.listify(e.roles,c=>c):[],d=[...n||[],...p||[],...a||[]],B=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...d];if(!t)return {fields:d,dataFields:n,roleFields:a,linkFields:p};let L=t.$fields?t.$fields.map(c=>{if(typeof c=="string")return c.startsWith("$")?void 0:c;if("$path"in c&&typeof c.$path=="string")return c.$path;throw new Error(" Wrongly structured query")}):radash.listify(t,c=>c.startsWith("$")?void 0:c).filter(c=>c!==void 0),u=t.$filter?radash.listify(t.$filter,c=>c.toString().startsWith("$")?void 0:c.toString()).filter(c=>c&&n?.includes(c)):[],r=t.$filter?radash.listify(t.$filter,c=>c.toString().startsWith("$")?void 0:c.toString()).filter(c=>c&&[...a||[],...p||[]].includes(c)):[],l=[...L,...u].filter(c=>!B.includes(c)).filter(c=>c),o=t.$filter?mt(t.$filter,(c,i)=>u.includes(c)):{},f=t.$filter?mt(t.$filter,(c,i)=>r.includes(c)):{};return {fields:d,dataFields:n,roleFields:a,linkFields:p,usedFields:L,usedLinkFields:p.filter(c=>L.includes(c)),usedRoleFields:a.filter(c=>L.includes(c)),usedDataFields:n.filter(c=>L.includes(c)),unidentifiedFields:l,...u.length?{localFilters:o}:{},...r.length?{nestedFilters:f}:{}}};var se=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},ae=(e,t,n)=>{let a=(n.nodePath||"").split("."),d=radash.isArray(t)?a.slice(0,-2).join("."):a.slice(0,-1).join(".");return t?objectTraversal.getNodeByPath(e,d):{}},J=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,n)=>(t[n]=e[n],t),{});var wt=e=>radash.isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),K=e=>{if(Array.isArray(e))return e.map(t=>K(t));if(e&&typeof e=="object"){let t=immer.isDraft(e)?immer.current(e):e,n={};return Object.entries(t).forEach(([p,a])=>{n[p]=K(a);}),n}else return e};var H=Symbol.for("queryPath"),bt=Symbol.for("stepPrint"),ot=Symbol.for("edgeType"),tt=Symbol.for("edgeSchema");var _="___",le=async e=>{let{enrichedBqlQuery:t}=e;if(!t)throw new Error("BQL query not enriched");let n="",p=(r,l)=>{let o="",f="";for(let c in r){let i=r[c];if(Array.isArray(i))for(let h=0;h<i.length;h++)f+=`{$${l} has ${c} "${i[h]}";}`,h<i.length-1?f+="or":f+=";";else o+=`, has ${c} "${i}"`;}o+=`;
|
|
37
|
+
`,n+=o,n+=f;},a=(r,l)=>{let o=[],f=[],c="";for(let m=0;m<r.length;m++)r[m].$isVirtual||o.push(` ${r[m].$dbPath}`),f.push(`{${r[m].$dbPath}:${r[m].$as}}`);let i=`${o.join(",")};
|
|
38
|
+
`;c=f.join(",");let h=`$metadata:{as:[${c}]}`;n+=`$${l} as "${l}.${h}.$dataFields": `,n+=i;},d=(r,l,o)=>{for(let f of r){let{$fields:c,$as:i,$justId:h,$idNotIncluded:m,$filterByUnique:E}=f,$=f[H],M=`$metadata:{as:${i},justId:${h?"T":"F"},idNotIncluded:${m},filterByUnique:${E}}`;if(n+=`"${o}.${M}.${f.$var}":{
|
|
39
|
+
`,n+=` match
|
|
40
|
+
`,f.$filter&&(n+=` $${l}${_}${f.$var} isa ${f.$thing}`,p(f.$filter,`${l}${_}${f.$var}`)),n+=` $${l} (${f.$var}: $${l}${_}${f.$var}) isa ${f.$intermediary};
|
|
41
|
+
`,c){let P=`M_${uuid.v4()}`;n+=`?queryPath${P} = "${$}";
|
|
42
|
+
`,n+=` fetch
|
|
43
|
+
`,n+=`?queryPath${P} as "queryPath"
|
|
44
|
+
;`;let R=c?.filter(k=>k.$fieldType==="data");R&&R.length>0&&a(R,`${l}${_}${f.$var}`,`${l}.${f.$var}`);let g=c?.filter(k=>k.$fieldType==="link");g&&g.length>0&&s(g,`${l}${_}${f.$var}`,`${l}.${f.$var}`);let b=c?.filter(k=>k.$fieldType==="role");b&&b.length>0&&d(b,`${l}${_}${f.$var}`,`${l}.${f.$var}`);}n+=`};
|
|
45
|
+
`;}},s=(r,l,o)=>{for(let f of r){let{$fields:c,$as:i,$justId:h,$idNotIncluded:m,$filterByUnique:E,$playedBy:$}=f,M=f[H],P=`$metadata:{as:${i},justId:${h?"T":"F"},idNotIncluded:${m},filterByUnique:${E}}`;if(n+=`"${o}.${P}.${f.$var}":{
|
|
46
|
+
`,n+=` match
|
|
47
|
+
`,f.$filter&&(n+=` $${l}${_}${f.$var} isa ${f.$thing}`,p(f.$filter,`${l}${_}${f.$var}`)),f.$target==="role"?n+=` $${l}_intermediary (${f.$plays}: $${l}, ${$.plays}: $${l}${_}${f.$var}) isa ${f.$intermediary};
|
|
48
|
+
`:n+=` $${l}${_}${f.$var} (${f.$plays}: $${l}) isa ${f.$thing};
|
|
49
|
+
`,c){let R=`M_${uuid.v4()}`;n+=`?queryPath${R} = "${M}";
|
|
50
|
+
`,n+=` fetch
|
|
51
|
+
`,n+=`?queryPath${R} as "queryPath"
|
|
52
|
+
;`;let g=c?.filter(y=>y.$fieldType==="data");g&&g.length>0&&a(g,`${l}${_}${f.$var}`);let b=c?.filter(y=>y.$fieldType==="link");b&&b.length>0&&s(b,`${l}${_}${f.$var}`,`${l}.${f.$var}`);let k=c?.filter(y=>y.$fieldType==="role");k&&k.length>0&&d(k,`${l}${_}${f.$var}`,`${l}.${f.$var}`);}n+=`};
|
|
53
|
+
`;}},B=t.length>1,L=[];(r=>{if(B)for(let l of r){let{$path:o,$thing:f,$filter:c,$fields:i}=l;if(!o)throw new Error("Path is not defined");let h=l[H];n+=`match
|
|
54
|
+
$${o} isa ${f} `,c?p(c,o):n+="; ";let m=`M_${uuid.v4()}`;if(n+=`?queryPath${m} = "${h}";
|
|
55
|
+
`,n+=`fetch
|
|
56
|
+
`,n+=`?queryPath${m} as "queryPath"
|
|
57
|
+
;`,i){let E=i.filter(P=>P.$fieldType==="data");E&&E.length>0&&a(E,o);let $=i.filter(P=>P.$fieldType==="link");$&&$.length>0&&s($,o,o);let M=i.filter(P=>P.$fieldType==="role");M&&M.length>0&&d(M,o,o);}L.push(n),n="";}else for(let l of r){let{$path:o,$thing:f,$filter:c,$fields:i}=l;if(!o||o==="undefined")throw new Error("Path is not defined");let h=l[H];if(n+=`match
|
|
58
|
+
$${o} isa ${f} `,c?p(c,o):n+="; ",n+=`?queryPath = "${h}";
|
|
59
|
+
`,n+=`fetch
|
|
60
|
+
`,n+=`?queryPath as "queryPath"
|
|
61
|
+
;`,i){let m=i.filter(M=>M.$fieldType==="data");m&&m.length>0&&a(m,o);let E=i.filter(M=>M.$fieldType==="link");E&&E.length>0&&s(E,o,o);let $=i.filter(M=>M.$fieldType==="role");$&&$.length>0&&d($,o,o);}}})(t),e.tqlRequest=B?L:n;};var zt=e=>{let t=e.dataFields?.map(d=>d.path)||[],n=e.linkFields?.map(d=>d.path)||[],p=Object.keys(e.roles||{})||[];return [...t,...n,...p]},vt=(e,t)=>Object.keys(e||{}).some(p=>{if(!Array.isArray(e[p])){let a=t.idFields?.includes(p),d=t.dataFields?.some(s=>(s.dbPath===p||s.path===p)&&s?.validations?.unique);return a||d}return !1}),Wt=(e,t)=>{let n=t.dataFields?.map(s=>({path:s.path,dbPath:s.dbPath}))||[],p=t.linkFields?.map(s=>({path:s.path,dbPath:s.dbPath}))||[],a=Object.keys(t.roles||{}).map(s=>({path:s,dbPath:s}))||[],d=[...n,...p,...a];return Object.entries(e||{}).reduce((s,[B,L])=>{let u=d.find(r=>r.path===B);return s[u?.dbPath||B]=L,s},{})},de=async e=>{let{rawBqlRequest:t,schema:n}=e;if(Array.isArray(t)){for(let r of t)if(!("$entity"in r)&&!("$relation"in r)&&(!("$thing"in r)||!("$thingType"in r)))throw new Error("No entity specified in query")}else if(!("$entity"in t)&&!("$relation"in t)&&(!("$thing"in t)||!("$thingType"in t)))throw new Error("No entity specified in query");let p=(r,l)=>typeof l=="string"?r.idFields?.includes(l):r.idFields?.includes(l.$path),a=(r,l,o,f,c)=>({$path:l,$dbPath:f,$thingType:"attribute",$as:r.$as||l,$var:l,$fieldType:"data",$excludedFields:r.$excludedFields,$justId:o,$id:r.$id,$filter:r.$filter,$isVirtual:c,$filterProcessed:!0}),d=(r,l,o,f,c)=>{let{target:i,oppositeLinkFieldsPlayedBy:h}=o;return h.map(m=>{let E=i==="role"?m.thingType:"relation",$=i==="role"?m.thing:o.relation,M={[`$${E}`]:$},P=O(n,M),R=r?.$fields?.filter(b=>p(P,b)).length===0,g=[];return typeof r!="string"?r.$fields?R?g=[...r.$fields,...P.idFields]:g=r.$fields:g=zt(P):g=["id"],r.$excludedFields&&(g=g.filter(b=>p(P,b)?!0:!r.$excludedFields.includes(b.$path))),{$thingType:E,$plays:o.plays,$playedBy:m,$path:m.path,$dbPath:c,$as:r.$as||l,$var:l,$thing:$,$fields:g,$excludedFields:r.$excludedFields,$fieldType:"link",$target:i,$intermediary:m.relation,$justId:f,$id:r.$id,$filter:Wt(r.$filter,P),$idNotIncluded:R,$filterByUnique:vt(r.$filter,P),$filterProcessed:!0}})},s=(r,l,o,f,c)=>o.playedBy.map(i=>{let{thing:h,thingType:m,relation:E}=i,$={[`$${m}`]:h},M=O(n,$),P=r?.$fields?.filter(g=>M?.idFields?.includes(g)||M?.idFields?.includes(g.$path)).length===0,R=[];return typeof r!="string"?r.$fields?P?R=[...r.$fields,...M.idFields]:R=r.$fields:R=zt(M):R=["id"],r.$excludedFields&&(R=R.filter(g=>p(M,g)?!0:!r.$excludedFields.includes(g.$path))),{$thingType:m,$path:l,$dbPath:c,$as:r.$as||l,$var:l,$thing:h,$fields:R,$excludedFields:r.$excludedFields,$fieldType:"role",$intermediary:E,$justId:f,$id:r.$id,$filter:Wt(r.$filter,M),$idNotIncluded:P,$filterByUnique:vt(r.$filter,M),$playedBy:i,$filterProcessed:!0}}),B=(r,l)=>{let o=typeof r=="string"?r:r.$path,f=typeof r=="string",c=l.dataFields?.find(m=>m.path===o),i=l.linkFields?.find(m=>m.path===o),h=l.roles?.[o];if(c){let m=c.isVirtual&&c.default;return a(r,o,f,c.dbPath,m)}else {if(i)return d(r,o,i,f,i.dbPath);if(h)return s(r,o,h,f,h.dbPath)}return null},u=(r=>immer.produce(r,l=>objectTraversal.traverse(l,o=>{let{value:f,meta:c}=o,i=f;if(radash.isObject(i)){if(i.$id){let h=i.$entity||i.$relation?i:{[`$${i.$thingType}`]:i.$thing},m=O(n,h);if(!m?.name)throw new Error(`Schema not found for ${i.$thing}`);if(i.$path=m.name,Array.isArray(i.$id)||(i.$filterByUnique=!0),m?.idFields?.length===1){let[E]=m.idFields;i.$filter={...i.$filter,[E]:i.$id},delete i.$id;}else throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in i||"$relation"in i||"$thing"in i){let h=O(n,i);if(!h?.name)throw new Error(`Schema not found for ${i.$thing}`);i.$path=h.name;}if(i.$entity?(i.$thing=i.$entity,i.$thingType="entity",delete i.$entity):i.$relation&&(i.$thing=i.$relation,i.$thingType="relation",delete i.$relation),radash.isObject(i)&&"$thing"in i){let h=i.$entity||i.$relation?i:{[`$${i.$thingType}`]:i.$thing};i[H]=c.nodePath;let m=O(n,h);if(i.$filter&&(i.$filterByUnique=vt(i.$filter,m),i.$filterProcessed||(i.$filter=Wt(i.$filter,m))),i.$fields){i.$fields.filter(M=>m?.idFields?.includes(M)||m?.idFields?.includes(M.$path)).length>0||(i.$fields=[...i.$fields,...Array.isArray(m.idFields)?m.idFields:[]],i.$idNotIncluded=!0);let $=i.$fields?.flatMap(M=>{let P=B(M,m);return Array.isArray(P)?P:[P]}).filter(Boolean);i.$fields=$;}else {let $=zt(m)?.flatMap(M=>{let P=B(M,m);return Array.isArray(P)?P:[P]}).filter(Boolean);i.$fields=$;}i.$excludedFields&&(i.$fields=i.$fields.filter(E=>p(m,E)?!0:!i.$excludedFields.includes(E.$path)));}}})))(Array.isArray(t)?t:[t]);e.enrichedBqlQuery=u;};var yt=async(e,t)=>{let n=t.dbConnectors[0].id,p=e.typeDB?.get(n)?.session,a=e.typeDB?.get(n)?.client;if(!p||!p.isOpen()){if(!a)throw new Error("Client not found");p=await a.session(t.dbConnectors[0].dbName,typedbDriver.SessionType.DATA),e.typeDB?.set(n,{client:a,session:p});}return {client:a,session:p}};var ue=async(e,t)=>{let{dbHandles:n,enrichedBqlQuery:p,tqlRequest:a,config:d}=e;if(!p)throw new Error("BQL request not parsed");if(!a)throw new Error("TQL request not built");let s=new typedbDriver.TypeDBOptions;if(s.infer=!0,Array.isArray(a)){let L=await radash.parallel(a.length,a,async u=>{let{session:r}=await yt(n,d),l=await r.transaction(typedbDriver.TransactionType.READ,s);if(!l)throw new Error("Can't create transaction");let f=await l.query.fetch(u).collect();return await l.close(),f});t.rawTqlRes=L,t.isBatched=!0;}else {let{session:L}=await yt(n,d),u=await L.transaction(typedbDriver.TransactionType.READ,s);if(!u)throw new Error("Can't create transaction");let l=await u.query.fetch(a).collect();await u.close(),t.rawTqlRes=l;}};var he=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,n=/justId:([a-zA-Z0-9_\-·]+)/,p=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,a=/filterByUnique:([a-zA-Z0-9_\-·]+)/,d=e.match(t),s=e.match(n),B=e.match(p),L=e.match(a);return {as:d?d[1]:null,justId:s?s[1]:null,idNotIncluded:B?B[1]:null,filterByUnique:L?L[1]:null}},ur=e=>{try{let n=(a=>{let d=a.replace("$metadata:","");return d=d.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),d=d.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(s,B,L)=>/^{.*}$/.test(L)?`:${L}`:`:${B}"${L}"`),d=d.replace(/\[([^\]]+)\]/g,(s,B)=>`[${B.split(",").map(L=>L.trim().startsWith("{")&&L.trim().endsWith("}")?L.trim():`"${L.trim()}"`).join(",")}]`),d})(e);return JSON.parse(n)}catch(t){return console.error(t),{as:[]}}},fe=async(e,t)=>{let{enrichedBqlQuery:n,rawBqlRequest:p,schema:a,config:d}=e,{rawTqlRes:s,isBatched:B}=t;if(n){if(!s)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");let L=(i,h)=>{let{$metaData:m}=i,{as:E}=ur(m),$=Object.entries(i).filter(([M])=>M!=="type"&&!M.includes("$")).map(([M,P])=>{let R=h.dataFields?.find(y=>y.path===M||y.dbPath===M),g=M==="id",b=Array.isArray(E)?E.find(y=>y[M])?.[M]:M,k;if(R?.cardinality==="ONE"){if(k=P[0]?P[0].value:d.query?.returnNulls?null:void 0,R.contentType==="DATE"&&(k=k&&`${k}Z`),g)return [[b,k],["$id",k]].filter(([y,I])=>I!==void 0)}else if(R?.cardinality==="MANY"){if(!radash.isArray(P))throw new Error("Typedb fetch has changed its format");if(P.length===0)return d.query?.returnNulls?[[b,null]]:[];R.contentType==="DATE"?k=P.map(y=>`${y.value}Z`):k=P.map(y=>y.value);}return [[b,k]].filter(([y,I])=>I!==void 0)}).flat();return Object.fromEntries([...$])},u=i=>i.reduce((h,m)=>{let{$roleFields:E,$metaData:$,$cardinality:M}=m,{as:P,justId:R,idNotIncluded:g,filterByUnique:b}=he($),k=E.map(y=>{let{dataFields:I,currentSchema:T,linkFields:A,roleFields:F,schemaValue:w}=l(y),Q=L(I,T);if(R==="T")return Q.id;{let C=r(A),S=u(F),N={...Q};return g==="true"&&T?.idFields?.forEach(D=>delete N[D]),{...N,...C,...S,...w}}});return k.length>0?h[P]=M==="MANY"&&b==="false"?k:k[0]:d.query?.returnNulls&&(h[P]=null),h},{}),r=i=>i.reduce((h,m)=>{let{$linkFields:E,$metaData:$,$cardinality:M}=m,{as:P,justId:R,idNotIncluded:g,filterByUnique:b}=he($),k=E.map(y=>{let{dataFields:I,currentSchema:T,linkFields:A,roleFields:F,schemaValue:w}=l(y),Q=L(I,T);if(R==="T")return Q.id;{let C=r(A),S=u(F),N={...Q};return g==="true"&&T.idFields?.forEach(D=>delete N[D]),{...N,...C,...S,...w}}});return h[P]=k.length>0?M==="MANY"&&b==="false"?k:k[0]:d.query?.returnNulls?null:void 0,h},{}),l=i=>{let h=Object.keys(i),m=h.find(y=>y.endsWith(".$dataFields"));if(!m)throw new Error("No datafields");let E=i[m],$=m.split(".")[m.split(".").length-2];if(E.$metaData=$,E.length===0)throw new Error("No datafields");let M=E.type,P={$thing:M.label,$thingType:M.root,[H]:i.queryPath.value},R={[`$${P.$thingType}`]:P.$thing},g=O(a,R),b=h.filter(y=>!y.endsWith(".$dataFields")&&g.linkFields?.some(I=>I.path===y.split(".").pop())).map(y=>({$linkFields:i[y],$key:y.split(".").pop(),$metaData:y.split(".")[y.split(".").length-2],$cardinality:g?.linkFields?.find(I=>I.path===y.split(".").pop())?.cardinality})),k=h.filter(y=>!y.endsWith(".$dataFields")&&g.roles?.[y.split(".").pop()]).map(y=>({$roleFields:i[y],$key:y.split(".").pop(),$metaData:y.split(".")[y.split(".").length-2],$cardinality:g.roles[y.split(".").pop()].cardinality}));return {dataFields:E,schemaValue:P,currentSchema:g,linkFields:b,roleFields:k}},o=i=>i.map(h=>{let{dataFields:m,currentSchema:E,linkFields:$,roleFields:M,schemaValue:P}=l(h),R=L(m,E),g=r($),b=u(M),k=p?.$fields?.every(I=>!E?.idFields?.includes(I)&&!E?.idFields?.includes(I.$path));return {...g,...b,...P,...!d.query?.noMetadata&&p.$id?{$id:Array.isArray(p.$id)?R.id:p.$id}:{},...k?Object.fromEntries(Object.entries(R).filter(([I])=>!E?.idFields?.includes(I))):R}}),c=(i=>{let h=m=>{let E=o(m);return p.$id&&!Array.isArray(p.$id)||n[0].$filterByUnique?E[0]??null:E.length===0?null:E};return B?i.map(h):h(i)})(s);t.bqlRes=c;};var hr=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,fr=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,$e=e=>{let n=e.toString().replace(hr,"").trim().split("=>")[0].split("{")[0].replace(fr,"").trim(),p=n.substring(n.indexOf("(")+1,n.lastIndexOf(")")).trim();return p?(p.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(d=>d.includes("{")&&d.includes("}")?(d.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(B=>B.split(":")[0].trim().replace(/['"[\]]/g,"")):d.trim()).filter(Boolean):[]};var lt=({currentThing:e,fieldSchema:t,mandatoryDependencies:n=!1})=>{if(!t||!t.default||!("fn"in t.default||"value"in t.default))throw new Error(`[Internal] Virtual field: No field schema found, or wrongly configured. Field: ${JSON.stringify(t,null,3)}`);if(t.default.type==="value")return t.default.value;if(n){let{fn:a}=t.default,s=$e(a).filter(B=>!(B in e));if(s.length)throw new Error(`Virtual field: Missing arguments ${s.join(", ")}`)}return "default"in t?t.default?.fn(e):void 0};var me=async(e,t)=>{let{schema:n,enrichedBqlQuery:p}=e,{bqlRes:a}=t;if(!a)return;let s=(B=>immer.produce(B,L=>objectTraversal.traverse(L,({value:u})=>{if(radash.isObject(u)){let r=u;if(!r.$thing)throw new Error("[Internal] Thing is missing");if(r.$thing){let l=O(n,r),{virtualFields:o}=l,f=r[H];if(!f)throw new Error("[Internal] QueryPath is missing");let c=objectTraversal.getNodeByPath(p,f),i=c.$fields.map(m=>m.$path),h=c.$excludedFields;o.forEach(m=>{if(h?.includes(m)||i.length>0&&!i.includes(m))return;let E=l.dataFields?.find($=>$.path===m);if(E?.default){let $=lt({currentThing:r,fieldSchema:E,mandatoryDependencies:!0});r[m]=$;}else if(r[m]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${m}`)}),h&&h.forEach(m=>{if(typeof m!="string")throw new Error("[Internal] ExcludedField is not a string");delete r[m];});}}})))(a);t.bqlRes=s;};var Fe=async(e,t)=>{let{config:n}=e,{bqlRes:p}=t;if(!p)return;let d=(L=>immer.produce(L,u=>objectTraversal.traverse(u,({value:r})=>{radash.isObject(r);})))(p),B=(L=>immer.produce(L,u=>objectTraversal.traverse(u,({value:r})=>{if(radash.isObject(r)){let l=r;Object.keys(l).forEach(o=>{l[o]===void 0&&delete l[o];}),Object.getOwnPropertySymbols(l).forEach(o=>{delete l[o];}),n.query?.noMetadata===!0&&Object.keys(l).forEach(o=>{o.startsWith("$")&&delete l[o];});}})))(d);t.bqlRes=B;};var Br={query:[de,le,ue,fe,me,Fe]},Ee=async(e,t,n={},p=!0)=>{for(let a of e){let d=await a(t,n);if(d&&Array.isArray(d))for(let s of d)await Ee(s.pipeline,s.req,s.res,!1);}return p&&t.config.query?.debugger===!0&&typeof n.bqlRes=="object"?{...n.bqlRes,$debugger:{tqlRequest:t.tqlRequest}}:n.bqlRes},Tt=(e,t,n,p)=>Ee(Br.query,{config:t,schema:n,rawBqlRequest:e,dbHandles:p},{});var ct=(e,t)=>{if(t.fieldType==="linkField"){let n=t.oppositeLinkFieldsPlayedBy;if(n?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!n?.length)throw new Error(`[Internal] Field ${e} should have a player`);return n}else if(t.fieldType==="roleField"){if([...new Set(t.playedBy?.map(n=>n.thing))].length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!t.playedBy?.length)throw new Error(`[Internal] Field ${e} should have a player`);return t.playedBy}else throw new Error(`[Internal] Field ${e} is not a linkField or roleField`)};var we=(e,t,n)=>{let p=radash.isArray(e[t])?e[t]:[e[t]];if(!p.every(a=>typeof a=="object"))if(p.every(a=>typeof a=="string")){let a=ct(t,n),[d]=a,s=e.$op==="create"?"link":"replace",B=d.thing,L=d.thingType;if(p.some(u=>u.startsWith("_:")))throw new Error("[Not supported] At least one child of a replace is a tempId");e[t]={$id:e[t],$op:s,$thing:B,$thingType:L,$bzId:`S_${uuid.v4()}`};}else throw new Error("[Mutation Error] Replace can only be used with a single id or an array of ids")};var gt=(e,t,n)=>{let p=O(n,t),{usedDataFields:a}=U(p,t);if(t.$op){if(t.$op==="create"&&t.$id)throw new Error("[Wrong format] Can't write to computed field $id. Try writing to the id field directly.");if(["unlink","delete","update"].includes(t.$op)&&e.$op==="create")throw new Error(`[Wrong format] Cannot ${t.$op} under a create`);if(t.$op==="delete"&&a.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&a.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var Mt=(e,t,n)=>{let p=O(n,t),{usedFields:a}=U(p,t);return t.$op?(gt(e,t,n),t.$op):t.$id||t.$filter?a.length>0?(gt(e,{...t,$op:"update"},n),"update"):(gt(e,{...t,$op:"link"},n),"link"):(gt(e,{...t,$op:"create"},n),"create")};var Te=(e,t)=>{let p=(radash.isArray(e.$root)?e.$root:[e.$root]).map(a=>{let d=Mt(a,a,t);return {...{...a.$thing?{}:{$thing:a.$entity||a.$relation},...a.$thingType?{}:{$thingType:oe(a,t)},...a.$op?{}:{$op:d},...a.$bzId?{}:{$bzId:`R_${uuid.v4()}`}},...a}});e.$root=radash.isArray(e.$root)?p:p[0];};var kt=(e,t)=>{let n=t[bt];return types.isSet(n)?n.has("clean")?(Reflect.set(t,bt,n.add("clean")),!0):!1:(Reflect.set(t,bt,new Set(["clean"])),!0)};var Me=(e,t,n)=>{if(kt("split_ids",e)){let p=(radash.isArray(e[t])?e[t]:[e[t]]).flatMap(a=>{if(radash.isObject(a)&&"$id"in a&&radash.isArray(a.$id)){let d=a;if(O(n,d),!d.$bzId)throw new Error("[Internal Error] No bzId found");return d.$id.map((s,B)=>({...K(d),$id:s,$bzId:`${d.$bzId}_${B}`,...J(d)}))}return a});(p.length>radash.isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=p);}};var Le=(e,t,n,p)=>{let a=(radash.isArray(e[t])?e[t]:[e[t]]).map(d=>{let s=ct(t,n),[B]=s,L=Mt(e,{...d,$thing:B.thing,$thingType:B.thingType},p),u=d.$bzId?d.$bzId:d.$tempId?d.$tempId:`N_${uuid.v4()}`;return {...d,[tt]:n,$thing:B.thing,$thingType:B.thingType,$op:L,$bzId:u}});e[t]=radash.isArray(e[t])?a:a[0];};var Qe=(e,t,n)=>{let p=e[t];p&&(radash.isArray(p)?p:[p]).forEach(a=>{let d=O(n,a),{unidentifiedFields:s}=U(d,a),{computedFields:B,virtualFields:L}=d,u=radash.listify(a,(o,f)=>f!==void 0?o:void 0),r=u.filter(o=>L?.includes(o));if(r.length>0)throw new Error(`Virtual fields can't be sent to DB: "${r.join(",")}"`);if(B.filter(o=>!u.includes(o)).forEach(o=>{let f=d.dataFields?.find(E=>E.path===o),i=d.linkFields?.find(E=>E.path===o)?.oppositeLinkFieldsPlayedBy[0],h="roles"in d?ne(d.roles,(E,$)=>E===o):void 0,m=f||i||h;if(!m)throw new Error(`no field Def for ${o}`);if(a.$op==="create"&&!a[o]){let E=lt({currentThing:a,fieldSchema:m,mandatoryDependencies:!0});a[o]=E;}}),s.length>0)throw new Error(`Unknown fields: [${s.join(",")}] in ${JSON.stringify(a)}`)});};var Ie=(e,t,n)=>{let p=ct(t,n),[a]=p;e[t]={$thing:a.thing,$thingType:a.thingType,$op:"unlink",$bzId:`U_${uuid.v4()}`,[tt]:n};};var Lt=(e,t)=>{let n=O(t,e).hooks;if(n?.pre){let p=`on${se(e.$op)}`;return n.pre.filter(s=>s.triggers[p]?.()).flatMap(s=>s.actions)}return []};var Re=(e,t,n)=>{(radash.isArray(e[t])?e[t]:[e[t]]).forEach(a=>{if("$thing"in a){let{requiredFields:d,enumFields:s,fnValidatedFields:B,dataFields:L}=O(n,a);if("$op"in a&&a.$op==="create"&&d.forEach(u=>{if(!(u in a))throw new Error(`[Validations] Required field "${u}" is missing.`)}),("$op"in a&&a.$op==="update"||a.$op==="create")&&s.forEach(u=>{if(u in a){let r=L?.find(l=>l.path===u)?.validations?.enum;if(!r)throw new Error(`[Validations] Enum field "${u}" is missing enum options.`);if(radash.isArray(a[u]))a[u].some(l=>{if(!r.includes(l))throw new Error(`[Validations] Option "${l}" is not a valid option for field "${u}".`)});else if(r&&!r.includes(a[u]))throw new Error(`[Validations] Option "${a[u]}" is not a valid option for field "${u}".`)}}),("$op"in a&&a.$op==="update"||a.$op==="create")&&B.forEach(u=>{if(u in a)try{let r=L?.find(l=>l.path===u)?.validations?.fn;if(!r)throw new Error("Missing validation function.");if(!r(a[u]))throw new Error("Failed validation function.")}catch(r){throw new Error(`[Validations:attribute:${u}] ${r.message}`)}}),radash.isObject(a)&&"$thing"in a){let u=a.$thing,r=a,l=radash.clone(K(e)),o=radash.clone(K(r));Lt(r,n).forEach(c=>{if(c.type==="validate"){if(c.severity!=="error")return;try{let i=c.fn(o,l);if(i===!1)throw new Error(`${c.message}.`);if(i!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(i){throw new Error(`[Validations:thing:${u}] ${i.message}`)}}});}}});};var Oe=(e,t,n)=>{let p=(radash.isArray(e[t])?e[t]:[e[t]]).map(a=>{if(wt(a)){let d=Lt(a,n).filter(L=>L.type==="transform"),s=radash.clone(K(e)),B=radash.clone(K(a));return d.forEach(L=>{let u=L.fn(B,s);Object.keys(u).length!==0&&(a={...B,...u});}),a}});e[t]=radash.isArray(e[t])?p:p[0];};var Or=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(kt("set_tempId",e))if(e.$tempId?.startsWith("_:")){let n=e.$tempId.substring(2);e.$tempId=n,e.$bzId=n;}else throw new Error('[Wrong format] TempIds must start with "_:"');else throw new Error("[Internal] TempId already modified")},qr=(e,t)=>{},Ht=(e,t)=>{let p=immer.produce({$rootWrap:{$root:e}},a=>objectTraversal.traverse(a,({value:d,parent:s,key:B,meta:L})=>{if(!(!s||!B)&&radash.isObject(d)){if(!("$root"in d)){if(!("$thing"in d||"$entity"in d||"$relation"in d))throw B==="$root"?new Error("Root things must specify $entity or $relation"):new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(immer.isDraft(d)?immer.current(d):d)}`)}let u=d;Object.keys(u).forEach(r=>{if(Or(u,r),r!=="$root"&&r.startsWith("$"))return;let l=r!=="$root"?xt(t,u,r):{fieldType:"rootField"};if(!l)throw new Error(`[Internal] Field ${r} not found in schema`);if("contentType"in l)return qr();if(["rootField","linkField","roleField"].includes(l.fieldType)){if(["linkField","roleField"].includes(l.fieldType)&&we(u,r,l),l.fieldType==="rootField"){if(!("$root"in u))throw new Error(`[Internal] Field ${r} is a rootField but the object is not a root`);Te(u,t);}let o=radash.isArray(u[r])?u[r]:[u[r]],f=L.nodePath?.split(".").slice(1).join(".");o.forEach(i=>{if(i){if(l?.cardinality==="ONE"&&!i.$op&&!i.$id&&!i.$filter&&!i.$tempId&&u.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${f}.${r}`);if(i.$tempId&&!(i.$op===void 0||i.$op==="link"||i.$op==="create"||i.$op==="update"))throw new Error(`Invalid op ${i.$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.`)}}),["linkField","roleField"].includes(l.fieldType)&&(u[r]===null?Ie(u,r,l):Le(u,r,l,t)),Me(u,r,t),["rootField","linkField","roleField"].includes(l.fieldType)&&Qe(u,r,t),(radash.isArray(u[r])?u[r]:[u[r]]).forEach(i=>{let h=O(t,i),{unidentifiedFields:m,usedLinkFields:E}=U(h,i);if(m.length>0)throw new Error(`Unknown fields: [${m.join(",")}] in ${JSON.stringify(d)}`);if(E.length>1){let $=h.linkFields?.filter(M=>E.includes(M.path));$?.some((M,P)=>$.some((R,g)=>{if(P!==g&&M.target!==R.target&&M.relation===R.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),Oe(u,r,t),Re(u,r,t);}});}}));return radash.isArray(p.$rootWrap.$root),p.$rootWrap.$root};var qe=async(e,t,n)=>{if(!e)throw new Error("TQL request not built");if(!(e.deletions&&e.deletionMatches||e.insertions))throw new Error("TQL request error, no things");let{session:p}=await yt(t,n),a=await p.transaction(typedbDriver.TransactionType.WRITE);if(!a)throw new Error("Can't create transaction");let d=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,s=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;d&&await a.query.delete(d);let B=s&&a.query.insert(s);try{let L=B?await B.collect():void 0;return await a.commit(),await a.close(),{insertions:L}}catch(L){throw await a.close(),new Error(`Transaction failed: ${L.message}`)}};var De=async(e,t,n,p)=>{let a=[...t,...n],d=a.map(s=>{let B=e.insertions?.find(L=>L.get(`${s.$bzId}`))?.get(`${s.$bzId}`);if(s.$op==="create"||s.$op==="update"||s.$op==="link"){if(s.$op!=="update"&&!B&&s.$id)return {$id:s.$id,$error:"Does not exist or it's not linked to the parent"};let L=B?.asThing().iid;if(p.mutation?.noMetadata)return Object.entries(s).filter(([l,o])=>!l.startsWith("$")).reduce((l,[o,f])=>{if(s.$thingType==="relation"){let c=a.filter(i=>i.$id&&i.$bzId===f);if(c.length>1)throw new Error(`Multiple things with the same bzId ${f}`);return c.length===1?(l[o]=c[0].$id,l):(l[o]=f,l)}return l[o]=f,l},{});let u=s.$tempId&&!s.$tempId.startsWith("_:")?{$tempId:`_:${s.$tempId}`}:{};return {$dbId:L,...s,[s.path]:s.$id,...u}}if(s.$op==="delete"||s.$op==="unlink")return s;if(s.$op!=="match")throw new Error(`Unsupported op ${s.$op}`)}).filter(s=>s);return radash.clone(d)};var xe=e=>{let t=({value:n})=>(n&&typeof n=="object"&&"$id"in n&&(Object.keys(n).filter(d=>d.startsWith("$")).forEach(d=>delete n[d]),Object.keys(n).filter(d=>typeof d=="symbol").forEach(d=>delete n[d])),n);return immer.produce(e,n=>objectTraversal.traverse(n,t))};var ve=async(e,t)=>{let n=u=>{let r=[],l=[],o=h=>{if(h.$id)return h.$id;let m=O(t,h),{idFields:E}=m;if(!E)throw new Error(`no idFields: ${JSON.stringify(h)}`);let[$]=E;if(!$)throw new Error(`no idField: ${JSON.stringify(h)}`);let M=m.dataFields?.find(g=>g.path===$),P=lt({currentThing:h,fieldSchema:M,mandatoryDependencies:!0}),R=h[$]||h.$id||P;if(!R)throw new Error(`no idValue: ${JSON.stringify(h)}`);return R},f=h=>{if(h.$op==="create"){let m=o(h);if(r.find(E=>E.$id===m))throw new Error(`Duplicate id ${m} for node ${JSON.stringify(h)}`);if(l.find(E=>E.$bzId===h.$bzId))throw new Error(`Duplicate $bzid ${h.$bzId} for node ${JSON.stringify(h)}`);r.push({...h,$id:m});return}h.$tempId&&h.$op==="match"||r.push(h);},c=h=>{if(h.$op==="create"){let m=o(h);if(r.find(E=>E.$id===m),l.find(E=>E.$bzId===h.$bzId))throw new Error(`Duplicate %bzId ${h.$bzIdd} for edge ${JSON.stringify(h)}`);l.push({...h,$id:m});return}l.push(h);};return objectTraversal.traverse(u,({value:h,parent:m,meta:E})=>{if(!radash.isObject(h))return;let $=h;if($.$thing){if(!$.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify($)}`);if(!$.$bzId)throw new Error("[internal error] BzId not found");let M=O(t,$),{dataFields:P,roleFields:R,linkFields:g,usedFields:b}=U(M,$),k=()=>{if($.$op==="create"||$.$op==="delete")return $.$op;if($.$op==="update"){let T=b.filter(w=>P?.includes(w)),A=b.filter(w=>R?.includes(w)),F=b.filter(w=>g?.includes(w));if(T.length>0)return "update";if(A.length>0||F.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify($)}`)}return "match"},y={...$.$id&&{$id:$.$id},...$.$tempId&&{$tempId:$.$tempId},...$.$filter&&{$filter:$.$filter},$thing:$.$thing,...$.$thingType&&{$thingType:$.$thingType},...radash.shake(radash.pick($,P||[""])),$op:k(),$bzId:$.$tempId?$.$tempId:$.$bzId};f(y);let I=$[tt];if(I?.fieldType==="linkField"){if(($.$op==="link"||$.$op==="unlink")&&($.$id||$.$filter)){if($.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");r.push({...$,$op:"match"});}let T=I.relation===$.$thing,A=T?$.$bzId:`LT_${uuid.v4()}`,w=ae(u,m,E).$bzId;if(!w)throw new Error("No parent id found");if($[Symbol.for("relation")]==="$self")return;let Q=()=>{if($.$op==="delete")return T?"match":"delete";if($.$op==="unlink")return T?"unlink":"delete";if($.$op==="link"||$.$op==="create")return T?"link":"create";if($.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},C={$bzId:A,$thing:I.relation,$thingType:"relation",...$.$tempId?{$tempId:$.$tempId}:{},$op:Q(),...T?{}:{[I.path]:$.$bzId},[I.plays]:w,[tt]:I,[ot]:"linkField"};c(C),($.$op==="unlink"||Q()==="unlink")&&T&&c({$thing:I.relation,$thingType:"relation",$bzId:A,$op:"match",[I.plays]:w,[tt]:I,[ot]:"linkField"});}if($.$thingType==="relation"){let T=mt($,(w,Q)=>R.includes(w)),A=radash.mapEntries(T,(w,Q)=>radash.isArray(Q)?[w,Q]:radash.isObject(Q)?[w,Q.$bzId]:[w,Q]),F=mt(h,(w,Q)=>w.startsWith("$")||w.startsWith("Symbol"));if(Object.keys(T).filter(w=>!w.startsWith("$")).length>0){if($.$op==="create"||$.$op==="delete"){let w=()=>{if($.$op==="create")return "link";if($.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},Q=O(t,$).roles,C=radash.mapEntries(A,(N,D)=>{let z=Q[N]?.cardinality;if(!z)throw new Error(`Role ${N} not found in schema`);if(Array.isArray(D)){if(z==="ONE"){if(D.length>1)throw new Error(`[Error] Role ${N} is not a MANY relation`);return [N,D[0].$bzId||D[0]]}return [N,D.map(V=>V.$bzId||V)]}return [N,D.$bzId||D]}),S={...F,$thing:$.$thing,$thingType:"relation",$op:w(),...C,$bzId:$.$bzId,[ot]:"roleField"};c(S);return}if($.$op==="match"||$.$op==="update"&&Object.keys(T).length>0){let w=0;Object.entries(T).forEach(([Q,C])=>{let S=radash.isArray(C)?C:[C],N=D=>D==="create"||D==="replace"?"link":D;S.forEach(D=>{if(!D)return;let z=N(D.$op);if(z==="replace")throw new Error("Not supported yet: replace on roleFields");if(z==="unlink"&&w>0)throw w+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let V={...F,$thing:$.$thing,$thingType:"relation",$op:z==="delete"?"unlink":z,[Q]:D.$bzId,$bzId:$.$bzId,[ot]:"roleField"};c(V);});});}}}}}),[r,l]},[p,a]=n(e),d=p.reduce((u,r)=>{if(!r.$bzId)return [...u,r];let l=u.findIndex(o=>o.$bzId===r.$bzId);if(l===-1)return [...u,r];if(u[l].$op==="create"&&r.$op==="match")return u;if(u[l].$op==="match"&&(r.$op==="create"||r.$op==="match"))return [...u.slice(0,l),r,...u.slice(l+1)];throw new Error(`[Wrong format] Wrong operation combination for $tempId "${r.$tempId}". Existing: ${u[l].$op}. Current: ${r.$op}`)},[]),s=a.reduce((u,r)=>{let l=u.find(o=>(o.$id&&o.$id===r.$id||o.$bzId&&o.$bzId===r.$bzId)&&o.$thing===r.$thing&&o.$op===r.$op);if(l){let o={...l};return Object.keys(r).forEach(c=>{if(typeof c=="symbol"||c.startsWith("$"))return;let i=l[c],h=r[c];Array.isArray(i)&&Array.isArray(h)?o[c]=Array.from(new Set([...i,...h])):!Array.isArray(i)&&Array.isArray(h)?i!==void 0?o[c]=Array.from(new Set([i,...h])):o[c]=h:Array.isArray(i)&&!Array.isArray(h)?h!==void 0&&(o[c]=Array.from(new Set([...i,h]))):i!==null&&h!==null&&i!==void 0&&h!==void 0?o[c]=Array.from(new Set([i,h])):i==null&&(o[c]=h);}),[...u.filter(c=>!((c.$id&&c.$id===r.$id||c.$bzId&&c.$bzId===r.$bzId)&&c.$thing===r.$thing&&c.$op===r.$op)),o]}return [...u,r]},[]);d.forEach(u=>{if((u.$thingType==="relation"||"relation"in u)&&s.filter(r=>r.$bzId===u.$bzId||r.$tempId&&r.$tempId===u.$tempId).length===0){if(u.$op==="delete"||u.$op==="match"||u.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(xe(u))}`)}});let B=[...d,...s];return new Set(B.filter(u=>u.$tempId).map(u=>u.$tempId)).forEach(u=>{if(B.filter(r=>r.$tempId===u&&r.$op==="create").length===0)throw new Error("Can't link a $tempId that has not been created in the current mutation.")}),{mergedThings:d,mergedEdges:s}};var We=async(e,t,n)=>{let p=o=>{let f=o.$op,c=`$${o.$bzId}`,i=O(n,o),{idFields:h,defaultDBConnector:m}=i,E=m?.path||o.$thing,$=o.$id,M=h?.[0],P=radash.listify(o,(A,F)=>{if(A.startsWith("$")||A===M||F===void 0||F===null)return "";let w=i.dataFields?.find(S=>S.path===A);if(!w?.path)return "";let C=w.dbPath;if(["TEXT","ID","EMAIL"].includes(w.contentType))return `has ${C} '${F}'`;if(["NUMBER","BOOLEAN"].includes(w.contentType))return `has ${C} ${F}`;if(w.contentType==="DATE"){if(Number.isNaN(F.valueOf()))throw new Error("Invalid format, Nan Date");return F instanceof Date?`has ${C} ${F.toISOString().replace("Z","")}`:`has ${C} ${new Date(F).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${w.contentType}`)}).filter(A=>A),R=`${c}-atts`,g=radash.listify(o,A=>{if(A.startsWith("$")||A===M)return "";let F=i.dataFields?.find(C=>C.path===A);if(!F?.path)return "";let Q=F.dbPath;return `{${R} isa ${Q};}`}).filter(A=>A),b=radash.isArray($)?`like '${$.join("|")}'`:`'${$}'`,k=$?[`has ${M} ${b}`]:[],y=[...k,...P].filter(A=>A).join(","),I=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${c} isa ${[E,...k].filter(A=>A).join(",")};`;if(f==="update"){if(!g.length)throw new Error("update without attributes");return `${c} isa ${[E,...k].filter(A=>A).join(",")}, has ${R};
|
|
62
|
+
${g.join(" or ")};`}return ""},T=()=>f==="update"||f==="link"||f==="match"?`${c} isa ${[E,...k].filter(A=>A).join(",")};`:"";if(wt(o))return {op:f,deletionMatch:I(),insertionMatch:T(),insertion:f==="create"?`${c} isa ${[E,y].filter(A=>A).join(",")};`:f==="update"&&P.length?`${c} ${P.join(",")};`:"",deletion:f==="delete"?`${c} isa ${E};`:f==="update"&&g.length?`${c} has ${R};`:""};throw new Error("in attributes")},a=o=>{let f=o.$op,c=O(n,o),i=`$${o.$bzId}`,h=o.$id,m=c.defaultDBConnector?.path||o.$thing,E="roles"in c?radash.listify(c.roles,F=>F):[],$="roles"in c?radash.mapEntries(c.roles,(F,w)=>[F,w.dbConnector?.path||F]):{},M=radash.listify(o,(F,w)=>{if(!E.includes(F))return null;if(!("roles"in c))throw new Error("This should have roles! ");let Q=$[F];return Array.isArray(w)?w.map(C=>({path:Q,id:C})):{path:Q,id:w}}).filter(F=>F).flat(),P=M.map(F=>{if(!F?.path)throw new Error("Object without path");return `${F.path}: $${F.id}`}),R=M.length>0?`( ${P.join(" , ")} )`:"",g=o[ot];if(!g)throw new Error("[internal error] Symbol edgeType not defined");let b=R?`${i} ${R} ${g==="linkField"||f==="delete"||f==="unlink"?`isa ${m}`:""}`:"",k=`${i} ${g==="linkField"||f==="delete"?`isa ${m}`:""}`,y=()=>b?f==="link"?`${b};`:f==="create"?`${b}, has id '${h}';`:"":"",I=()=>b&&f==="match"?`${b};`:"",T=()=>b?f==="delete"?`${b};`:f==="match"?`${b};`:"":"",A=()=>b?f==="delete"?`${k};`:f==="unlink"?`${i} ${R};`:"":"";return {deletionMatch:T(),insertionMatch:I(),deletion:A(),insertion:y(),op:""}},d=(o,f)=>{let c=f==="edges"?a:p;if(Array.isArray(o))return o.map(M=>{let{preDeletionBatch:P,insertionMatch:R,deletionMatch:g,insertion:b,deletion:k}=c(M);return radash.shake({preDeletionBatch:P,insertionMatch:R,deletionMatch:g,insertion:b,deletion:k},y=>!y)}).filter(M=>M);let{preDeletionBatch:i,insertionMatch:h,deletionMatch:m,insertion:E,deletion:$}=c(o);return radash.shake({preDeletionBatch:i,insertionMatch:h,deletionMatch:m,insertion:E,deletion:$},M=>!M)},s=d(e),B=Array.isArray(s)?s:[s],L=d(t,"edges"),u=Array.isArray(L)?L:[L],r=[...B,...u];return radash.shake({insertionMatches:r.map(o=>o.insertionMatch).join(" ").trim(),deletionMatches:r.map(o=>o.deletionMatch).join(" ").trim(),insertions:r.map(o=>o.insertion).join(" ").trim(),deletions:r.map(o=>o.deletion).join(" ").trim()},o=>!o)};var Kr=Symbol.for("grandChildOfCreate"),_e=async(e,t,n,p)=>{let a=(g,b)=>Object.keys(g).filter(k=>k.startsWith("$")?!1:b?!O(t,g).dataFields?.find(I=>I.path===k):!0);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(n.mutation?.preQuery===!1)return;let d=[];if(objectTraversal.traverse(e,({parent:g,key:b,value:k})=>{g&&b&&!b.includes("$")&&radash.isObject(g)?(Array.isArray(g[b])?g[b]:[g[b]]).forEach(I=>{if(radash.isObject(I)){if(g.$op!=="create")d.includes(I.$op)||d.push(I.$op);else if(I.$op==="delete"||I.$op==="unlink")throw new Error(`Cannot ${I.$op} under a create`)}}):!g&&radash.isObject(k)&&(d.includes(k.$op)||d.push(k.$op));}),!d.includes("delete")&&!d.includes("unlink")&&!d.includes("replace")&&!d.includes("update")&&!d.includes("link"))return;let B=(g=>{let b=(k,y)=>{let I=[],T={},A=["$op","$bzId","$parentKey"],F=["$relation","$entity","$id",...A];for(let w in k)if(!A.includes(w)&&!(F.includes(w)&&!y))if(!w.includes("$")&&(radash.isObject(k[w])||Array.isArray(k[w]))){let Q=k[w];Array.isArray(Q)&&Q.length>0?Q.forEach(C=>{I.push({$path:w,...b(C)});}):I.push({$path:w,...b(Q)});}else T[w]=k[w];return {...T,$fields:I}};return g.map(k=>b(k,!0))})(Array.isArray(e)?e:[e]),L=await Tt(B,n,t,p),u=(g,b)=>{let k=g.$id||g.id||g.$bzId;if(g.$objectPath){let{$objectPath:y}=g,I=y?.beforePath||"root",T=Array.isArray(y.ids)?`[${y.ids}]`:y.ids;return {beforePath:`${I}.${T}___${y.key}`,ids:k,key:b}}else return {beforePath:"root",ids:k,key:b}},r=(g,b)=>{let k=g?.beforePath||"root",y=b||(Array.isArray(g?.ids)?`[${g?.ids}]`:g?.ids);return `${k}.${y}___${g?.key}`},l=g=>{if(g.includes("[")&&g.includes("]")){let[b,k,y]=g.split(/[[\]]/);return k.split(",").map(T=>`${b}${T}${y}`)}else return [g]},o={};(g=>immer.produce(g,b=>objectTraversal.traverse(b,k=>{let{key:y,parent:I}=k;if(I&&y&&I.$id&&!y.includes("$")){let T=u(I,y),A=r(T);if(Array.isArray(I[y])){let F=[];I[y].forEach(w=>{radash.isObject(w)?(w.$objectPath=T,F.push(w.$id.toString())):w&&F.push(w.toString());}),o[A]={$objectPath:T,$ids:F};}else {let F=I[y];radash.isObject(F)?(o[A]={$objectPath:T,$ids:[F.$id.toString()]},F.$objectPath=T):F&&(o[A]={$objectPath:T,$ids:[F.toString()]});}}})))(L||{});let c=g=>immer.produce(g,b=>objectTraversal.traverse(b,k=>{let{key:y,value:I,parent:T}=k;T&&y&&!y.includes("$")&&(Array.isArray(I)||radash.isObject(I))&&!Array.isArray(T)&&(Array.isArray(T[y])?T[y].forEach(A=>{typeof A!="string"&&(A.$objectPath=u(T,y),A.$parentIsCreate=T.$op==="create",A[Kr]=T.$parentIsCreate||T[Symbol.for("grandChildOfCreate")]);}):radash.isObject(T[y])&&(T[y].$parentIsCreate=T.$op==="create",T[y][Symbol.for("grandChildOfCreate")]=T.$parentIsCreate||T[Symbol.for("grandChildOfCreate")],T[y].$objectPath=u(T,y)));})),i=c(e),m=(g=>{let b=(T,A)=>{let F=[];T.filter(S=>S).forEach(S=>{let N=Object.keys(S).filter(D=>!D.startsWith("$")).length;if(Array.isArray(S.$id)&&N>0){let D=S.$id.map(z=>({...S,$id:z}));F=[...F,...D];}else F.push({...S});});let w=[],Q=[],C=F.filter(S=>{let D=["delete","update","unlink"].includes(S.$op||""),z=a(S,!0).length;if((!S.$id||Array.isArray(S.$id)&&z>0||S.$filter)&&D)return !0;Q.push({...S});});return C.length>0?C.forEach(S=>{let D=(j=>{let ut=(()=>{let v={};for(let x in j){let X=O(t,j);!x.startsWith("$")&&X.dataFields?.find(at=>at.path===x)&&(v[x]=j[x]);}return v})(),ht=Object.keys(j),G=ht.filter(v=>!v.startsWith("$")),At=[],Ft=(v,x)=>{if(v===G.length){let at={...x};ht.forEach(W=>{W.startsWith("$")&&(at[W]=j[W]);}),At.push(at);return}let X={...x,[G[v]]:j[G[v]],...J(x),...ut};Ft(v+1,X),Ft(v+1,x);};return Ft(0,{...J(j)}),At})(S).filter(j=>!(j.$op==="update"&&Object.keys(j).filter(nt=>!nt.startsWith("$")).length===0)),z=[],V=r(S.$objectPath),Y=o[V]?o[V].$ids:[],q=D.map((j,nt)=>{let ut=O(t,j),G=Object.keys(j).filter(x=>!x.includes("$")&&!ut.dataFields?.some(X=>X.path===x)).map(x=>(Array.isArray(j[x])?j[x].length>1?j[x].filter(W=>!W.$id||Array.isArray(W.$id)||W.$filter):j[x]:[j[x]]).map(W=>{let Rt=r(W.$objectPath);return {idsToKey:(Ct=>{let Yt=[],$t=Ct.split("."),Ze=$t.slice(0,$t.length-1).join("."),Ye=$t.slice($t.length-1,$t.length)[0].split("___")[1];for(let St in o)if(St.startsWith(Ze)&&St.endsWith(Ye)){let Ot=St.split("."),Ge=Ot.slice(Ot.length-1,Ot.length)[0].split("___")[0];Yt.push(Ge);}return Yt})(Rt),key:x,multiple:W}})).filter(x=>x!==void 0),v=(x=>{let X=x.map(W=>W.map(it=>it.idsToKey));return (W=>W.length>0?W.reduce((it,ft)=>it.concat(ft),[]).reduce((it,ft)=>it?ft.filter(Ct=>it.includes(Ct)):ft):[])(X)})(G).filter(x=>!z.includes(x));if(z=[...z,...v],Y=Y.filter(x=>!v.includes(x)),nt===D.length-1&&Y.length>0)return {...j,$id:Y,$bzId:`T1_${uuid.v4()}`,...J(j)};if(v.length>0)return {...j,$id:v,$bzId:`T2_${uuid.v4()}`,...J(j)}}).filter(j=>j!==void 0),Je=(()=>{if(q.length===0&&!A?.$id)return C;if(q.length===0&&A?.$id){let j=Array.isArray(A.$id)?A.$id:[A.$id],nt=[];return j.forEach(ut=>{let ht=r({...S.$objectPath,ids:ut}),G=o[ht];G&&nt.push({...S,$id:G.$ids,...J(S),$bzId:`T_${uuid.v4()}`});}),nt}else return q.filter(j=>j!==void 0)})();w=[...Q,...Je].map(k);}):w=F.map(k),w},k=T=>{let A={...T,$bzId:T.$tempId??`T3_${uuid.v4()}`,...J(T)},F=O(t,T);return Object.keys(T).filter(w=>!w.includes("$")&&!F.dataFields?.some(Q=>Q.path===w)).forEach(w=>{let Q=Array.isArray(T[w])?T[w]:[T[w]],C=b(Q,T);A[w]=C.length>0?C:void 0;}),A},y=[];return g.forEach(T=>{y=[...y,...b([T])];}),y.map(T=>k(T))})(Array.isArray(i)?i:[i]),E=g=>g.map(b=>{let k=a(b,!0),y={...b};return k.forEach(I=>{let T=Array.isArray(b[I])?b[I]:[b[I]],A=[],F=[],w=[],Q={},C=jt(t,b,I);T.filter(q=>q).forEach(q=>{q.$op==="replace"&&q.$id?(Q=q,Array.isArray(q.$id)?F=[...F,...q.$id]:F.push(q.$id)):q.$op==="create"&&C==="ONE"&&q.id?(Q=q,Array.isArray(q.id)?w=[...F,...q.id]:w.push(q.id)):A.push(q);});let S=r(Q.$objectPath),D=l(S).map(q=>o[q]),z=[];D.filter(q=>q!=null).forEach(q=>{z=[...z,...q.$ids];});let V=z.filter(q=>!F.includes(q)),Pt=F.filter(q=>!z.includes(q)),Y=J(Q);V.length>0&&A.push({...Q,$op:"unlink",$id:V,$bzId:`T4_${uuid.v4()}`,id:void 0,...Y}),Pt.length>0&&Pt.forEach(q=>{A.push({...Q,$op:"link",$id:q,$bzId:`T5_${uuid.v4()}`,...Y});}),w.length>0&&w.forEach(q=>{A.push({...Q,$op:"create",id:q,$bzId:`T6_${uuid.v4()}`,...Y});}),y[I]=E(A);}),y}),$=c(E(c(m)));return (g=>immer.produce(g,b=>objectTraversal.traverse(b,k=>{let{key:y,value:I,parent:T}=k;y&&T&&!y?.includes("$")&&(Array.isArray(I)||radash.isObject(I))&&!Array.isArray(T)&&(Array.isArray(I)?I:[I]).forEach(F=>{let w=o[r(F.$objectPath)],Q=(N,D)=>N.every(z=>D.includes(z)),C=F.$id?Array.isArray(F.$id)?Q(F.$id,w?w.$ids:[]):w?.$ids.includes(F.$id):w,S=jt(t,T,F.$objectPath.key);if(F.$op==="link"&&C&&S==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${r(F.$objectPath)}" because it is already occupied.`);if(F.$op)switch(F.$op){case"delete":if(!C&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${F.$id}" because it is not linked to $id:"${T.$id}"`);break;case"update":if(!C&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${F.$id}" because it is not linked to $id:"${T.$id}"`);break;case"unlink":if(!C&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${F.$id}" because it is not linked to $id:"${T.$id}"`);break;case"link":if(C)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${F.$id}" because it is already linked to $id:"${T.$id}"`);break;}});})))($),(g=>immer.produce(g,b=>objectTraversal.traverse(b,k=>{let{value:y,meta:I}=k;radash.isObject(y)&&(y[Symbol.for("path")]=I.nodePath,delete y.$objectPath,delete y.$parentIsCreate);})))($)};var Ut=(e,t)=>t.data?{...e,bql:{...e.bql,current:t.data}}:e,Yr=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Gr=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),Xr=(e,t)=>({...e,typeDB:{...e.typeDB,tqlMutation:t.data}}),tn=(e,t)=>({...e,typeDB:{...e.typeDB,tqlRes:t.data}}),en=async e=>Object.keys(e.bql.current).length?Ht(e.bql.current,e.schema):Ht(e.bql.raw,e.schema),rn=async e=>_e(e.bql.current,e.schema,e.config,e.handles),nn=async e=>ve(e.bql.current,e.schema),on=async e=>We(e.bql.things,e.bql.edges,e.schema),sn=async e=>qe(e.typeDB.tqlMutation,e.handles,e.config),an=async e=>De(e.typeDB.tqlRes,e.bql.things,e.bql.edges,e.config),ln=()=>!0,pt=robot3.transition("error","error",robot3.reduce((e,t)=>({...e,error:t.error}))),cn=robot3.createMachine("enrich",{enrich:robot3.invoke(en,robot3.transition("done","preQuery",robot3.guard(ln),robot3.reduce(Ut)),robot3.transition("done","parseBQL",robot3.reduce(Ut)),pt),preQuery:robot3.invoke(rn,robot3.transition("done","parseBQL",robot3.reduce(Ut)),pt),parseBQL:robot3.invoke(nn,robot3.transition("done","buildMutation",robot3.reduce(Gr)),pt),buildMutation:robot3.invoke(on,robot3.transition("done","runMutation",robot3.reduce(Xr)),pt),runMutation:robot3.invoke(sn,robot3.transition("done","parseMutation",robot3.reduce(tn)),pt),parseMutation:robot3.invoke(an,robot3.transition("done","success",robot3.reduce(Yr)),pt),success:robot3.state(),error:robot3.state()},e=>e),dn=async e=>new Promise((t,n)=>{robot3.interpret(cn,p=>{p.machine.state.name==="success"&&t(p.context),p.machine.state.name==="error"&&n(p.context);},e);}),He=async(e,t,n,p)=>dn({bql:{raw:e,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:t,config:n,handles:p,depthLevel:0,error:null});immer.enableMapSet();var Zt=class{schema;config;dbHandles;constructor({schema:t,config:n}){this.schema=t,this.config=n;}getDbHandles=()=>this.dbHandles;init=async()=>{let t={typeDB:new Map,surrealDB:new Map};await Promise.all(this.config.dbConnectors.map(async p=>{if(p.provider==="typeDB"&&p.dbName){let[a,d]=await radash.tryit(typedbDriver.TypeDB.coreDriver)(p.url);if(a){let s=`[BORM:${p.provider}:${p.dbName}:core] ${a.message??"Can't create TypeDB Client"}`;throw new Error(s)}try{let s=await d.session(p.dbName,typedbDriver.SessionType.DATA);t.typeDB.set(p.id,{client:d,session:s});}catch(s){let B=`[BORM:${p.provider}:${p.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(B)}}if(p.provider==="typeDBCluster"&&p.dbName){let[a,d]=await radash.tryit(typedbDriver.TypeDB.cloudDriver)(p.addresses,p.credentials);if(a){let s=`[BORM:${p.provider}:${p.dbName}:core] ${a.message??"Can't create TypeDB Cluster Client"}`;throw new Error(s)}try{let s=await d.session(p.dbName,typedbDriver.SessionType.DATA);t.typeDB.set(p.id,{client:d,session:s});}catch(s){let B=`[BORM:${p.provider}:${p.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(B)}}}));let n=ie(this.schema,t);this.schema=n,this.dbHandles=t;};#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(),Xt(this.config,this.schema,this.dbHandles));query=async(t,n)=>{await this.#t();let p={...this.config,query:{...qt.query,...this.config.query,...n}};return Tt(t,p,this.schema,this.dbHandles)};mutate=async(t,n)=>{await this.#t();let p={...this.config,mutation:{...qt.mutation,...this.config.mutation,...n}},[a,d]=await radash.tryit(He)(t,this.schema,p,this.dbHandles);if(a)throw console.error(a.error.stack.split(`
|
|
63
|
+
`).slice(0,4).join(`
|
|
64
|
+
`)),new Error(a.error.message);return d.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:n})=>{n.isOpen()&&await n.close(),await t.close();});}},ys=Zt;//! Todo: delete when this works with the new $thing and $thingType fields
|
|
63
65
|
//! Todo: Sandbox the function in computeFunction()
|
|
66
|
+
//! reads all the insertions and gets the first match. This means each id must be unique
|
|
67
|
+
//!old
|
|
64
68
|
|
|
65
|
-
module.exports =
|
|
69
|
+
module.exports = ys;
|