@blitznocode/blitz-orm 0.9.19 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,67 +2,82 @@
2
2
 
3
3
  var radash = require('radash');
4
4
  var typedbDriver = require('typedb-driver');
5
+ var surrealdb_node = require('surrealdb.node');
5
6
  var immer = require('immer');
6
7
  var objectTraversal = require('object-traversal');
7
8
  var uuid = require('uuid');
8
- require('acorn');
9
9
  var types = require('util/types');
10
+ require('acorn');
11
+ var caseAnything = require('case-anything');
10
12
 
11
- var _t={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var Qn=e=>{let t=[],n=new Map;return e.forEach(o=>{let{dbPath:l,contentType:a}=o,d=`${l}-${a}`;n.has(d)||(n.set(d,!0),t.push(o));}),t},ce=async(e,t,n)=>{let l=(()=>{let m="",p=[];m+=`
12
- `,Object.keys(t.entities).forEach($=>{let Q=t.entities[$],{idFields:C,dataFields:g,linkFields:b,name:F}=Q,y=[],P=[],M=[];if("extends"in Q){let E=t.entities[Q.extends];E.dataFields&&E.dataFields.forEach(I=>{y.push(I.dbPath);}),E.linkFields&&E.linkFields.forEach(I=>{P.push(I.path);}),E.idFields&&E.idFields.forEach(I=>{M.push(I);});}m+=`${F} sub ${"extends"in Q?Q.extends:"entity"},
13
- `;let L=[];if(C&&C.length>0){let E=new Set(C),w=Array.from(E).map(O=>`${O}`).join(", ");M.includes(w)||(m+=` owns ${w} @key,
14
- `,L.push(w));}if(g&&g.length>0&&g.forEach(E=>{!y.includes(E.dbPath)&&!L.includes(E.dbPath)&&(m+=` owns ${E.dbPath},
15
- `),p.push({dbPath:E.dbPath,contentType:E.contentType});}),b&&b.length>0){let E=[];b.forEach(I=>{let{relation:w,plays:O}=I;!P.includes(I.path)&&!E.includes(`${w}:${O}`)&&(m+=` plays ${w}:${O},
16
- `,E.push(`${w}:${O}`));});}m=m.replace(/,\s*$/,`;
13
+ var Ye={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var wn=t=>{let e=[],r=new Map;return t.forEach(n=>{let{dbPath:o,contentType:i}=n,p=`${o}-${i}`;r.has(p)||(r.set(p,!0),e.push(n));}),e},At=async(t,e,r)=>{let o=(()=>{let m="",y=[];m+=`
14
+ `,Object.keys(e.entities).forEach(g=>{let Q=e.entities[g],{idFields:M,dataFields:L,linkFields:A,name:R}=Q,D=[],N=[],x=[];if("extends"in Q){let F=e.entities[Q.extends];F.dataFields&&F.dataFields.forEach(k=>{D.push(k.dbPath);}),F.linkFields&&F.linkFields.forEach(k=>{N.push(k.path);}),F.idFields&&F.idFields.forEach(k=>{x.push(k);});}m+=`${R} sub ${"extends"in Q?Q.extends:"entity"},
15
+ `;let w=[];if(M&&M.length>0){let F=new Set(M),E=Array.from(F).map(b=>`${b}`).join(", ");x.includes(E)||(m+=` owns ${E} @key,
16
+ `,w.push(E));}if(L&&L.length>0&&L.forEach(F=>{!D.includes(F.dbPath)&&!w.includes(F.dbPath)&&(m+=` owns ${F.dbPath},
17
+ `),y.push({dbPath:F.dbPath,contentType:F.contentType});}),A&&A.length>0){let F=[];A.forEach(k=>{let{relation:E,plays:b}=k;!N.includes(k.path)&&!F.includes(`${E}:${b}`)&&(m+=` plays ${E}:${b},
18
+ `,F.push(`${E}:${b}`));});}m=m.replace(/,\s*$/,`;
17
19
  `),m+=`
18
- `;}),Object.keys(t.relations).forEach($=>{let Q=t.relations[$],{idFields:C,dataFields:g,roles:b,name:F,linkFields:y}=Q,P=[],M=[],L=[],E=[];if("extends"in Q){let w=t.relations[Q.extends];w.dataFields&&w.dataFields.forEach(O=>{P.push(O.dbPath);}),w.linkFields&&w.linkFields.forEach(O=>{M.push(O.dbPath);}),w.roles&&Object.values(w.roles).forEach(R=>{L.push(R.name);}),w.idFields&&w.idFields.forEach(O=>{E.push(O);});}m+=`${F} sub ${"extends"in Q?Q.extends:"relation"},
19
- `;let I=[];if(C&&C.length>0){let w=new Set(C),R=Array.from(w).map(z=>`${z}`).join(", ");E.includes(R)||(m+=` owns ${R} @key,
20
- `,I.push(R));}if(g&&g.length>0&&g.forEach(w=>{!P.includes(w.dbPath)&&!I.includes(w.dbPath)&&(m+=` owns ${w.dbPath},
21
- `),p.push({dbPath:w.dbPath,contentType:w.contentType});}),b&&Object.keys(b).forEach(w=>{L.includes(w)||(m+=` relates ${w},
22
- `);}),y&&y.length>0){let w=[];y.forEach(O=>{let{plays:R}=O;!M.includes(O.path)&&!w.includes(`${Q}:${R}`)&&(m+=` plays ${O.relation}:${R},
23
- `,w.push(`${Q}:${R}`));});}m=m.replace(/,\s*$/,`;
20
+ `;}),Object.keys(e.relations).forEach(g=>{let Q=e.relations[g],{idFields:M,dataFields:L,roles:A,name:R,linkFields:D}=Q,N=[],x=[],w=[],F=[];if("extends"in Q){let E=e.relations[Q.extends];E.dataFields&&E.dataFields.forEach(b=>{N.push(b.dbPath);}),E.linkFields&&E.linkFields.forEach(b=>{x.push(b.dbPath);}),E.roles&&Object.values(E.roles).forEach(S=>{w.push(S.name);}),E.idFields&&E.idFields.forEach(b=>{F.push(b);});}m+=`${R} sub ${"extends"in Q?Q.extends:"relation"},
21
+ `;let k=[];if(M&&M.length>0){let E=new Set(M),S=Array.from(E).map(_=>`${_}`).join(", ");F.includes(S)||(m+=` owns ${S} @key,
22
+ `,k.push(S));}if(L&&L.length>0&&L.forEach(E=>{!N.includes(E.dbPath)&&!k.includes(E.dbPath)&&(m+=` owns ${E.dbPath},
23
+ `),y.push({dbPath:E.dbPath,contentType:E.contentType});}),A&&Object.keys(A).forEach(E=>{w.includes(E)||(m+=` relates ${E},
24
+ `);}),D&&D.length>0){let E=[];D.forEach(b=>{let{plays:S}=b;!x.includes(b.path)&&!E.includes(`${Q}:${S}`)&&(m+=` plays ${b.relation}:${S},
25
+ `,E.push(`${Q}:${S}`));});}m=m.replace(/,\s*$/,`;
24
26
  `),m+=`
25
27
  `;});let B=`define
26
28
 
27
- `;return Qn(p).forEach($=>{B+=`${$.dbPath} sub attribute,
28
- `,$.contentType==="TEXT"||$.contentType==="ID"?B+=` value string;
29
- `:$.contentType==="EMAIL"?(B+=` value string,
29
+ `;return wn(y).forEach(g=>{B+=`${g.dbPath} sub attribute,
30
+ `,g.contentType==="TEXT"||g.contentType==="ID"?B+=` value string;
31
+ `:g.contentType==="EMAIL"?(B+=` value string,
30
32
  `,B+=` regex '^(?=.{1,64}@)[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*@[^-][A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$';
31
- `):$.contentType==="DATE"?B+=` value datetime;
32
- `:$.contentType==="BOOLEAN"?B+=` value boolean;
33
- `:$.contentType==="NUMBER"&&(B+=` value long;
33
+ `):g.contentType==="DATE"?B+=` value datetime;
34
+ `:g.contentType==="BOOLEAN"?B+=` value boolean;
35
+ `:g.contentType==="NUMBER"&&(B+=` value long;
34
36
  `);}),`${B}
35
37
 
36
- ${m}`})(),a=e.dbConnectors[0].id,d=n.typeDB.get(a)?.session,h=n.typeDB.get(a)?.client;if(!d){console.log("Session Status: ","NO SESSION");return}await d.close();let[{dbName:T}]=e.dbConnectors;await(await h.databases.get(T)).delete(),await h.databases.create(T);let r=await h.session(e.dbConnectors[0].dbName,typedbDriver.SessionType.SCHEMA),i=await r.transaction(typedbDriver.TransactionType.WRITE);await i.query.define(l),await i.commit(),await i.close();let s=await r.transaction(typedbDriver.TransactionType.READ);(await(await s.query.match("match $a sub thing;")).collect()).forEach(async m=>{m.get("a");}),await s.close();};var de={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var he=(e,t,n)=>n?t:`${e}\xB7${t}`;var fe=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([n,o])=>t(n,o))))[0],Ft=(e,t)=>Object.fromEntries(Object.entries(e).filter(([n,o])=>t(n,o))),$e=(e,t)=>{let n=[],o=immer.produce(e,a=>objectTraversal.traverse(a,({key:d,value:h,meta:T})=>{if(T.depth===2&&(d&&(h.dataFields=h.dataFields?.map(k=>({...k,cardinality:k.cardinality||"ONE",dbPath:he(d,k.path,k.shared)}))),h.extends)){if(!h.defaultDBConnector.as)throw new Error(`[Schema] ${d} is extending a thing but missing the "as" property in its defaultDBConnector`);let k=a.entities[h.extends]||a.relations[h.extends];if(h.allExtends=[h.extends,...k.allExtends||[]],h.idFields=k.idFields?(h.idFields||[]).concat(k.idFields):h.idFields,h.dataFields=k.dataFields?(h.dataFields||[]).concat(k.dataFields.map(r=>{let i=h.extends,s=e.entities[i]||e.relations[i];for(;!s.dataFields?.find(f=>f.path===r.path);)i="extends"in s?s.extends:void 0,s=e.entities[i]||e.relations[i];return {...r,dbPath:he(i,r.path,r.shared)}})):h.dataFields,h.linkFields=k.linkFields?(h.linkFields||[]).concat(k.linkFields):h.linkFields,"roles"in k){let r=h,i=k;r.roles=r.roles||{},r.roles={...r.roles,...i.roles},Object.keys(r.roles).length===0&&(r.roles={});}k?.hooks?.pre&&(h.hooks=h.hooks||{},h.hooks.pre=h.hooks.pre||[],h.hooks.pre=[...k?.hooks?.pre||[],...h?.hooks?.pre||[]]);}},{traversalType:"breadth-first"}));return objectTraversal.traverse(e,({key:a,value:d,meta:h})=>{if(a==="linkFields"){let k=(()=>{if(!h.nodePath)throw new Error("No path");let[i,s]=h.nodePath.split(".");return {thing:s,thingType:i==="entities"?"entity":i==="relations"?"relation":""}})(),r=Array.isArray(d)?d.map(i=>({...i,...k})):[{...d,...k}];n.push(...r);}}),immer.produce(o,a=>objectTraversal.traverse(a,({value:d,key:h,meta:T})=>{if(T.depth===2&&d.idFields&&!d.id){d.name=h;let k=()=>{if(T.nodePath?.split(".")[0]==="entities")return "entity";if(T.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};d.thingType=k();let r=Object.keys(t).find(i=>t[i]?.get(d.defaultDBConnector.id));d.db=r,d.dbContext=de[r],d.computedFields=[],d.virtualFields=[],d.requiredFields=[],d.enumFields=[],d.fnValidatedFields=[],"roles"in d&&Object.entries(d.roles).forEach(([s,f])=>{f.fieldType="roleField",f.playedBy=n.filter(u=>u.relation===h&&u.plays===s)||[],f.name=s;}),"linkFields"in d&&d.linkFields&&d.linkFields?.forEach(s=>{if(s.fieldType="linkField",s.target==="relation"){s.oppositeLinkFieldsPlayedBy=[{plays:s.path,thing:s.relation,thingType:"relation"}];return}let f=n.filter(c=>c.relation===s.relation&&c.plays!==s.plays)||[];s.oppositeLinkFieldsPlayedBy=f;let{filter:u}=s;s.oppositeLinkFieldsPlayedBy=s.oppositeLinkFieldsPlayedBy.filter(c=>c.target==="role"),u&&Array.isArray(u)&&(s.oppositeLinkFieldsPlayedBy=s.oppositeLinkFieldsPlayedBy.filter(c=>u.some(m=>c.thing===m.$role)),s.oppositeLinkFieldsPlayedBy=s.oppositeLinkFieldsPlayedBy.filter(c=>u.some(m=>c.thing===m.$thing))),u&&!Array.isArray(u)&&(s.oppositeLinkFieldsPlayedBy=s.oppositeLinkFieldsPlayedBy.filter(c=>c.$role===u.$role),s.oppositeLinkFieldsPlayedBy=s.oppositeLinkFieldsPlayedBy.filter(c=>c.thing===u.$thing));});}if(typeof d=="object"&&"playedBy"in d){let k=[...new Set(d.playedBy.map(r=>r.thing))];if(k.length>1)throw new Error(`[Schema] roleFields can be only played by one thing. Role: ${h}, path:${T.nodePath}, played by: ${k.join(", ")}`);if(d.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${h}, path:${T.nodePath}`)}if(T.depth===4){let[k,r]=T.nodePath?.split(".")||[],i=a[k][r];d.validations&&(d.validations.required&&i.requiredFields.push(d.path),d.validations.enum&&i.enumFields.push(d.path),d.validations.fn&&i.fnValidatedFields.push(d.path)),d.default?d.isVirtual?i.virtualFields.push(d.path):i.computedFields.push(d.path):d.isVirtual&&i.virtualFields.push(d.path);}}))},kt=(e,t)=>{if(t in e.entities)return e.entities[t];if(t in e.relations)return e.relations[t];throw new Error(`${t} is not defined in the schema`)},A=(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)}`)},me=(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")},Kt=(e,t,n)=>{let o=A(e,t),l=o.linkFields?.find(h=>h.path===n);if(l)return l;let a=o.dataFields?.find(h=>h.path===n);if(a)return a;let d="roles"in o?o.roles?.[n]:void 0;if(d)return d},vt=(e,t,n)=>Kt(e,t,n)?.cardinality,J=(e,t)=>{let n=e.dataFields?.map(u=>u.path)||[],o=e.linkFields?.map(u=>u.path)||[],l="roles"in e?radash.listify(e.roles,u=>u):[],a=[...n||[],...o||[],...l||[]],h=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...a];if(!t)return {fields:a,dataFields:n,roleFields:l,linkFields:o};let T=t.$fields?t.$fields.map(u=>{if(typeof u=="string"){if(u.startsWith("$")||u.startsWith("%"))return;if(!a.includes(u))throw new Error(`Field ${u} not found in the schema`);return u}if("$path"in u&&typeof u.$path=="string")return u.$path;throw new Error("[Wrong format] Wrongly structured query")}):radash.listify(t,u=>{if(!(u.startsWith("$")||u.startsWith("%"))){if(!a.includes(u))throw new Error(`[Schema] Field ${u} not found in the schema`);return u}}).filter(u=>u!==void 0),k=t.$filter?radash.listify(t.$filter,u=>u.toString().startsWith("$")?void 0:u.toString()).filter(u=>u&&n?.includes(u)):[],r=t.$filter?radash.listify(t.$filter,u=>u.toString().startsWith("$")?void 0:u.toString()).filter(u=>u&&[...l||[],...o||[]].includes(u)):[],i=[...T,...k].filter(u=>!u?.startsWith("%")).filter(u=>!h.includes(u)).filter(u=>u),s=t.$filter?Ft(t.$filter,(u,c)=>k.includes(u)):{},f=t.$filter?Ft(t.$filter,(u,c)=>r.includes(u)):{};return {fields:a,dataFields:n,roleFields:l,linkFields:o,usedFields:T,usedLinkFields:o.filter(u=>T.includes(u)),usedRoleFields:l.filter(u=>T.includes(u)),usedDataFields:n.filter(u=>T.includes(u)),unidentifiedFields:i,...k.length?{localFilters:s}:{},...r.length?{nestedFilters:f}:{}}};var ye=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},ge=(e,t,n)=>{let l=(n.nodePath||"").split("."),a=radash.isArray(t)?l.slice(0,-2).join("."):l.slice(0,-1).join(".");return t?objectTraversal.getNodeByPath(e,a):{}},v=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,n)=>(t[n]=e[n],t),{});var Lt=e=>radash.isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),rt=e=>{if(Array.isArray(e))return e.map(t=>immer.current(t));if(e&&typeof e=="object"){let t=immer.isDraft(e)?immer.current(e):e,n={};return Object.entries(t).forEach(([o,l])=>{n[o]=immer.isDraft(l)?immer.current(l):l;}),n}else return e};var U=Symbol.for("queryPath"),Qt=Symbol.for("stepPrint"),ct=Symbol.for("edgeType"),it=Symbol.for("edgeSchema");var K="___",Be=async e=>{let{enrichedBqlQuery:t}=e;if(!t)throw new Error("BQL query not enriched");let n="",o=(r,i)=>{let s="",f="";for(let u in r){let c=r[u];if(Array.isArray(c))for(let m=0;m<c.length;m++)f+=`{$${i} has ${u} "${c[m]}";}`,m<c.length-1?f+="or":f+=";";else s+=`, has ${u} "${c}"`;}s+=`;
37
- `,n+=s,n+=f;},l=(r,i)=>{let s=[],f=[],u="";for(let p=0;p<r.length;p++)r[p].$isVirtual||s.push(` ${r[p].$dbPath}`),f.push(`{${r[p].$dbPath}:${r[p].$as}}`);let c=`${s.join(",")};
38
- `;u=f.join(",");let m=`$metadata:{as:[${u}]}`;n+=`$${i} as "${i}.${m}.$dataFields": `,n+=c;},a=(r,i,s)=>{for(let f of r){let{$fields:u,$as:c,$justId:m,$idNotIncluded:p,$filterByUnique:B}=f,S=f[U],$=`$metadata:{as:${c},justId:${m?"T":"F"},idNotIncluded:${p},filterByUnique:${B}}`;if(n+=`"${s}.${$}.${f.$var}":{
39
- `,n+=` match
40
- `,f.$filter&&(n+=` $${i}${K}${f.$var} isa ${f.$thing}`,o(f.$filter,`${i}${K}${f.$var}`)),n+=` $${i} (${f.$var}: $${i}${K}${f.$var}) isa ${f.$intermediary};
41
- `,u){let Q=`M_${uuid.v4()}`;n+=`?queryPath${Q} = "${S}";
42
- `,n+=` fetch
43
- `,n+=`?queryPath${Q} as "queryPath"
44
- ;`;let C=u?.filter(F=>F.$fieldType==="data");C&&C.length>0&&l(C,`${i}${K}${f.$var}`,`${i}.${f.$var}`);let g=u?.filter(F=>F.$fieldType==="link");g&&g.length>0&&d(g,`${i}${K}${f.$var}`,`${i}.${f.$var}`);let b=u?.filter(F=>F.$fieldType==="role");b&&b.length>0&&a(b,`${i}${K}${f.$var}`,`${i}.${f.$var}`);}n+=`};
45
- `;}},d=(r,i,s)=>{for(let f of r){let{$fields:u,$as:c,$justId:m,$idNotIncluded:p,$filterByUnique:B,$playedBy:S}=f,$=f[U],Q=`$metadata:{as:${c},justId:${m?"T":"F"},idNotIncluded:${p},filterByUnique:${B}}`;if(n+=`"${s}.${Q}.${f.$var}":{
46
- `,n+=` match
47
- `,f.$filter&&(n+=` $${i}${K}${f.$var} isa ${f.$thing}`,o(f.$filter,`${i}${K}${f.$var}`)),f.$target==="role"?n+=` $${i}_intermediary (${f.$plays}: $${i}, ${S.plays}: $${i}${K}${f.$var}) isa ${f.$intermediary};
48
- `:n+=` $${i}${K}${f.$var} (${f.$plays}: $${i}) isa ${f.$thing};
49
- `,u){let C=`M_${uuid.v4()}`;n+=`?queryPath${C} = "${$}";
50
- `,n+=` fetch
51
- `,n+=`?queryPath${C} as "queryPath"
52
- ;`;let g=u?.filter(y=>y.$fieldType==="data");g&&g.length>0&&l(g,`${i}${K}${f.$var}`);let b=u?.filter(y=>y.$fieldType==="link");b&&b.length>0&&d(b,`${i}${K}${f.$var}`,`${i}.${f.$var}`);let F=u?.filter(y=>y.$fieldType==="role");F&&F.length>0&&a(F,`${i}${K}${f.$var}`,`${i}.${f.$var}`);}n+=`};
53
- `;}},h=t.length>1,T=[];(r=>{if(h)for(let i of r){let{$path:s,$thing:f,$filter:u,$fields:c}=i;if(!s)throw new Error("Path is not defined");let m=i[U];n+=`match
54
- $${s} isa ${f} `,u?o(u,s):n+="; ";let p=`M_${uuid.v4()}`;if(n+=`?queryPath${p} = "${m}";
55
- `,n+=`fetch
56
- `,n+=`?queryPath${p} as "queryPath"
57
- ;`,c){let B=c.filter(Q=>Q.$fieldType==="data");B&&B.length>0&&l(B,s);let S=c.filter(Q=>Q.$fieldType==="link");S&&S.length>0&&d(S,s,s);let $=c.filter(Q=>Q.$fieldType==="role");$&&$.length>0&&a($,s,s);}T.push(n),n="";}else for(let i of r){let{$path:s,$thing:f,$filter:u,$fields:c}=i;if(!s||s==="undefined")throw new Error("Path is not defined");let m=i[U];if(n+=`match
58
- $${s} isa ${f} `,u?o(u,s):n+="; ",n+=`?queryPath = "${m}";
59
- `,n+=`fetch
60
- `,n+=`?queryPath as "queryPath"
61
- ;`,c){let p=c.filter($=>$.$fieldType==="data");p&&p.length>0&&l(p,s);let B=c.filter($=>$.$fieldType==="link");B&&B.length>0&&d(B,s,s);let S=c.filter($=>$.$fieldType==="role");S&&S.length>0&&a(S,s,s);}}})(t),e.tqlRequest=h?T:n;};var Jt=e=>{let t=e.dataFields?.map(a=>a.path)||[],n=e.linkFields?.map(a=>a.path)||[],o=Object.keys(e.roles||{})||[];return [...t,...n,...o]},Zt=(e,t)=>Object.keys(e||{}).some(o=>{if(!Array.isArray(e[o])){let l=t.idFields?.includes(o),a=t.dataFields?.some(d=>(d.dbPath===o||d.path===o)&&d?.validations?.unique);return l||a}return !1}),Yt=(e,t)=>{let n=t.dataFields?.map(d=>({path:d.path,dbPath:d.dbPath}))||[],o=t.linkFields?.map(d=>({path:d.path,dbPath:d.dbPath}))||[],l=Object.keys(t.roles||{}).map(d=>({path:d,dbPath:d}))||[],a=[...n,...o,...l];return Object.entries(e||{}).reduce((d,[h,T])=>{let k=a.find(r=>r.path===h);return d[k?.dbPath||h]=T,d},{})},Fe=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 o=(r,i)=>typeof i=="string"?r.idFields?.includes(i):r.idFields?.includes(i.$path),l=(r,i,s,f,u)=>({$path:i,$dbPath:f,$thingType:"attribute",$as:r.$as||i,$var:i,$fieldType:"data",$excludedFields:r.$excludedFields,$justId:s,$id:r.$id,$filter:r.$filter,$isVirtual:u,$filterProcessed:!0}),a=(r,i,s,f,u)=>{let{target:c,oppositeLinkFieldsPlayedBy:m}=s;return m.map(p=>{let B=c==="role"?p.thingType:"relation",S=c==="role"?p.thing:s.relation,$={[`$${B}`]:S},Q=A(n,$),C=r?.$fields?.filter(b=>o(Q,b)).length===0,g=[];return typeof r!="string"?r.$fields?C?g=[...r.$fields,...Q.idFields]:g=r.$fields:g=Jt(Q):g=["id"],r.$excludedFields&&(g=g.filter(b=>o(Q,b)?!0:!r.$excludedFields.includes(b.$path))),{$thingType:B,$plays:s.plays,$playedBy:p,$path:p.path,$dbPath:u,$as:r.$as||i,$var:i,$thing:S,$fields:g,$excludedFields:r.$excludedFields,$fieldType:"link",$target:c,$intermediary:p.relation,$justId:f,$id:r.$id,$filter:Yt(r.$filter,Q),$idNotIncluded:C,$filterByUnique:Zt(r.$filter,Q),$filterProcessed:!0}})},d=(r,i,s,f,u)=>s.playedBy.map(c=>{let{thing:m,thingType:p,relation:B}=c,S={[`$${p}`]:m},$=A(n,S),Q=r?.$fields?.filter(g=>$?.idFields?.includes(g)||$?.idFields?.includes(g.$path)).length===0,C=[];return typeof r!="string"?r.$fields?Q?C=[...r.$fields,...$.idFields]:C=r.$fields:C=Jt($):C=["id"],r.$excludedFields&&(C=C.filter(g=>o($,g)?!0:!r.$excludedFields.includes(g.$path))),{$thingType:p,$path:i,$dbPath:u,$as:r.$as||i,$var:i,$thing:m,$fields:C,$excludedFields:r.$excludedFields,$fieldType:"role",$intermediary:B,$justId:f,$id:r.$id,$filter:Yt(r.$filter,$),$idNotIncluded:Q,$filterByUnique:Zt(r.$filter,$),$playedBy:c,$filterProcessed:!0}}),h=(r,i)=>{let s=typeof r=="string"?r:r.$path,f=typeof r=="string",u=i.dataFields?.find(p=>p.path===s),c=i.linkFields?.find(p=>p.path===s),m=i.roles?.[s];if(u){let p=u.isVirtual&&u.default;return l(r,s,f,u.dbPath,p)}else {if(c)return a(r,s,c,f,c.dbPath);if(m)return d(r,s,m,f,m.dbPath)}return null},k=(r=>immer.produce(r,i=>objectTraversal.traverse(i,s=>{let{value:f,meta:u}=s,c=f;if(radash.isObject(c)){if(c.$id){let m=c.$entity||c.$relation?c:{[`$${c.$thingType}`]:c.$thing},p=A(n,m);if(!p?.name)throw new Error(`Schema not found for ${c.$thing}`);if(c.$path=p.name,Array.isArray(c.$id)||(c.$filterByUnique=!0),p?.idFields?.length===1){let[B]=p.idFields;c.$filter={...c.$filter,[B]:c.$id},delete c.$id;}else throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in c||"$relation"in c||"$thing"in c){let m=A(n,c);if(!m?.name)throw new Error(`Schema not found for ${c.$thing}`);c.$path=m.name;}if(c.$entity?(c.$thing=c.$entity,c.$thingType="entity",delete c.$entity):c.$relation&&(c.$thing=c.$relation,c.$thingType="relation",delete c.$relation),radash.isObject(c)&&"$thing"in c){let m=c.$entity||c.$relation?c:{[`$${c.$thingType}`]:c.$thing};c[U]=u.nodePath;let p=A(n,m);if(c.$filter&&(c.$filterByUnique=Zt(c.$filter,p),c.$filterProcessed||(c.$filter=Yt(c.$filter,p))),c.$fields){c.$fields.filter($=>p?.idFields?.includes($)||p?.idFields?.includes($.$path)).length>0||(c.$fields=[...c.$fields,...Array.isArray(p.idFields)?p.idFields:[]],c.$idNotIncluded=!0);let S=c.$fields?.flatMap($=>{let Q=h($,p);return Array.isArray(Q)?Q:[Q]}).filter(Boolean);c.$fields=S;}else {let S=Jt(p)?.flatMap($=>{let Q=h($,p);return Array.isArray(Q)?Q:[Q]}).filter(Boolean);c.$fields=S;}c.$excludedFields&&(c.$fields=c.$fields.filter(B=>o(p,B)?!0:!c.$excludedFields.includes(B.$path)));}}})))(Array.isArray(t)?t:[t]);e.enrichedBqlQuery=k;};var wt=async(e,t)=>{let n=t.dbConnectors[0].id,o=e.typeDB?.get(n)?.session,l=e.typeDB?.get(n)?.client;if(!o||!o.isOpen()){if(!l)throw new Error("Client not found");o=await l.session(t.dbConnectors[0].dbName,typedbDriver.SessionType.DATA),e.typeDB?.set(n,{client:l,session:o});}return {client:l,session:o}};var be=async(e,t)=>{let{dbHandles:n,enrichedBqlQuery:o,tqlRequest:l,config:a}=e;if(!o)throw new Error("BQL request not parsed");if(!l)throw new Error("TQL request not built");let d=new typedbDriver.TypeDBOptions;if(d.infer=!0,Array.isArray(l)){let T=await radash.parallel(l.length,l,async k=>{let{session:r}=await wt(n,a),i=await r.transaction(typedbDriver.TransactionType.READ,d);if(!i)throw new Error("Can't create transaction");let f=await i.query.fetch(k).collect();return await i.close(),f});t.rawTqlRes=T,t.isBatched=!0;}else {let{session:T}=await wt(n,a),k=await T.transaction(typedbDriver.TransactionType.READ,d);if(!k)throw new Error("Can't create transaction");let i=await k.query.fetch(l).collect();await k.close(),t.rawTqlRes=i;}};var Te=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,n=/justId:([a-zA-Z0-9_\-·]+)/,o=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,l=/filterByUnique:([a-zA-Z0-9_\-·]+)/,a=e.match(t),d=e.match(n),h=e.match(o),T=e.match(l);return {as:a?a[1]:null,justId:d?d[1]:null,idNotIncluded:h?h[1]:null,filterByUnique:T?T[1]:null}},xn=e=>{try{let n=(l=>{let a=l.replace("$metadata:","");return a=a.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),a=a.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(d,h,T)=>/^{.*}$/.test(T)?`:${T}`:`:${h}"${T}"`),a=a.replace(/\[([^\]]+)\]/g,(d,h)=>`[${h.split(",").map(T=>T.trim().startsWith("{")&&T.trim().endsWith("}")?T.trim():`"${T.trim()}"`).join(",")}]`),a})(e);return JSON.parse(n)}catch(t){return console.error(t),{as:[]}}},Me=async(e,t)=>{let{enrichedBqlQuery:n,rawBqlRequest:o,schema:l,config:a}=e,{rawTqlRes:d,isBatched:h}=t;if(n){if(!d)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");let T=(c,m)=>{let{$metaData:p}=c,{as:B}=xn(p),S=Object.entries(c).filter(([$])=>$!=="type"&&!$.startsWith("$")).map(([$,Q])=>{let C=m.dataFields?.find(y=>y.path===$||y.dbPath===$),g=$==="id",b=Array.isArray(B)?B.find(y=>y[$])?.[$]:$,F;if(C?.cardinality==="ONE"){if(F=Q[0]?Q[0].value:a.query?.returnNulls?null:void 0,C.contentType==="DATE"?F=F&&`${F}Z`:C.contentType==="JSON"&&(F=F&&JSON.parse(F)),g)return [[b,F],["$id",F]].filter(([y,P])=>P!==void 0)}else if(C?.cardinality==="MANY"){if(!radash.isArray(Q))throw new Error("Typedb fetch has changed its format");if(Q.length===0)return a.query?.returnNulls?[[b,null]]:[];C.contentType==="DATE"?F=Q.map(y=>`${y.value}Z`):C.contentType==="JSON"?F=Q.map(y=>y.value&&JSON.parse(y.value)):F=Q.map(y=>y.value);}return [[b,F]].filter(([y,P])=>P!==void 0)}).flat();return Object.fromEntries([...S])},k=c=>c.reduce((m,p)=>{let{$roleFields:B,$metaData:S,$cardinality:$}=p,{as:Q,justId:C,idNotIncluded:g,filterByUnique:b}=Te(S),F=B.map(y=>{let{dataFields:P,currentSchema:M,linkFields:L,roleFields:E,schemaValue:I}=i(y),w=T(P,M);if(C==="T")return w.id;{let O=r(L),R=k(E),z={...w};return g==="true"&&M?.idFields?.forEach(N=>delete z[N]),{...z,...O,...R,...I}}});return F.length>0?m[Q]=$==="MANY"&&b==="false"?F:F[0]:a.query?.returnNulls&&(m[Q]=null),m},{}),r=c=>c.reduce((m,p)=>{let{$linkFields:B,$metaData:S,$cardinality:$}=p,{as:Q,justId:C,idNotIncluded:g,filterByUnique:b}=Te(S),F=B.map(y=>{let{dataFields:P,currentSchema:M,linkFields:L,roleFields:E,schemaValue:I}=i(y),w=T(P,M);if(C==="T")return w.id;{let O=r(L),R=k(E),z={...w};return g==="true"&&M.idFields?.forEach(N=>delete z[N]),{...z,...O,...R,...I}}});return m[Q]=F.length>0?$==="MANY"&&b==="false"?F:F[0]:a.query?.returnNulls?null:void 0,m},{}),i=c=>{let m=Object.keys(c),p=m.find(y=>y.endsWith(".$dataFields"));if(!p)throw new Error("No datafields");let B=c[p],S=p.split(".")[p.split(".").length-2];if(B.$metaData=S,B.length===0)throw new Error("No datafields");let $=B.type,Q={$thing:$.label,$thingType:$.root,[U]:c.queryPath.value},C={[`$${Q.$thingType}`]:Q.$thing},g=A(l,C),b=m.filter(y=>!y.endsWith(".$dataFields")&&g.linkFields?.some(P=>P.path===y.split(".").pop())).map(y=>({$linkFields:c[y],$key:y.split(".").pop(),$metaData:y.split(".")[y.split(".").length-2],$cardinality:g?.linkFields?.find(P=>P.path===y.split(".").pop())?.cardinality})),F=m.filter(y=>!y.endsWith(".$dataFields")&&g.roles?.[y.split(".").pop()]).map(y=>({$roleFields:c[y],$key:y.split(".").pop(),$metaData:y.split(".")[y.split(".").length-2],$cardinality:g.roles[y.split(".").pop()].cardinality}));return {dataFields:B,schemaValue:Q,currentSchema:g,linkFields:b,roleFields:F}},s=c=>c.map(m=>{let{dataFields:p,currentSchema:B,linkFields:S,roleFields:$,schemaValue:Q}=i(m),C=T(p,B),g=r(S),b=k($),F=o?.$fields?.every(P=>!B?.idFields?.includes(P)&&!B?.idFields?.includes(P.$path));return {...g,...b,...Q,...!a.query?.noMetadata&&o.$id?{$id:Array.isArray(o.$id)?C.id:o.$id}:{},...F?Object.fromEntries(Object.entries(C).filter(([P])=>!B?.idFields?.includes(P))):C}}),u=(c=>{let m=p=>{let B=s(p);return o.$id&&!Array.isArray(o.$id)||n[0].$filterByUnique?B[0]??null:B.length===0?null:B};return h?c.map(m):m(c)})(d);t.bqlRes=u;};var jn=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Nn=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,ke=e=>{let n=e.toString().replace(jn,"").trim().split("=>")[0].split("{")[0].replace(Nn,"").trim(),o=n.substring(n.indexOf("(")+1,n.lastIndexOf(")")).trim();return o?(o.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(a=>a.includes("{")&&a.includes("}")?(a.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(h=>h.split(":")[0].trim().replace(/['"[\]]/g,"")):a.trim()).filter(Boolean):[]};var ft=({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:l}=t.default,d=ke(l).filter(h=>!(h in e));if(d.length)throw new Error(`Virtual field: Missing arguments ${d.join(", ")}`)}if(!t.default.fn)throw new Error("[Schema] No fn in default field schema");return "default"in t?t.default?.fn(e):void 0};var Le=async(e,t)=>{let{schema:n,enrichedBqlQuery:o}=e,{bqlRes:l}=t;if(!l)return;let d=(h=>immer.produce(h,T=>objectTraversal.traverse(T,({value:k})=>{if(radash.isObject(k)){let r=k;if(!r.$thing)return;if(r.$thing){let i=A(n,r),{virtualFields:s}=i,f=r[U];if(!f)throw new Error("[Internal] QueryPath is missing");let u=objectTraversal.getNodeByPath(o,f),c=u.$fields.map(p=>p.$path),m=u.$excludedFields;s.forEach(p=>{if(m?.includes(p)||c.length>0&&!c.includes(p))return;let B=i.dataFields?.find(S=>S.path===p);if(B?.default){let S=ft({currentThing:r,fieldSchema:B,mandatoryDependencies:!0});r[p]=S;}else if(r[p]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${p}`)}),m&&m.forEach(p=>{if(typeof p!="string")throw new Error("[Internal] ExcludedField is not a string");delete r[p];});}}})))(l);t.bqlRes=d;};var Se=async(e,t)=>{let{config:n}=e,{bqlRes:o}=t;if(!o)return;let a=(T=>immer.produce(T,k=>objectTraversal.traverse(k,({value:r})=>{radash.isObject(r);})))(o),h=(T=>immer.produce(T,k=>objectTraversal.traverse(k,({value:r})=>{if(radash.isObject(r)){let i=r;Object.keys(i).forEach(s=>{i[s]===void 0&&delete i[s];}),Object.getOwnPropertySymbols(i).forEach(s=>{delete i[s];}),n.query?.noMetadata===!0&&Object.keys(i).forEach(s=>{s.startsWith("$")&&delete i[s];});}})))(a);t.bqlRes=h;};var Hn={query:[Fe,Be,be,Me,Le,Se]},Ce=async(e,t,n={},o=!0)=>{for(let l of e){let a=await l(t,n);if(a&&Array.isArray(a))for(let d of a)await Ce(d.pipeline,d.req,d.res,!1);}return o&&t.config.query?.debugger===!0&&typeof n.bqlRes=="object"?{...n.bqlRes,$debugger:{tqlRequest:t.tqlRequest}}:n.bqlRes},It=(e,t,n,o)=>Ce(Hn.query,{config:t,schema:n,rawBqlRequest:e,dbHandles:o},{});var $t=(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 Oe=(e,t,n)=>{let o=radash.isArray(e[t])?e[t]:[e[t]];if(!o.every(l=>typeof l=="object"))if(o.every(l=>typeof l=="string")){let l=$t(t,n),[a]=l,d=e.$op==="create"?"link":"replace",h=a.thing,T=a.thingType;if(o.some(k=>k.startsWith("_:")))throw new Error("[Not supported] At least one child of a replace is a tempId");e[t]={$id:e[t],$op:d,$thing:h,$thingType:T,$bzId:`S_${uuid.v4()}`};}else throw new Error(`[Mutation Error] Replace can only be used with a single id or an array of ids. (Field: ${t} Nodes: ${JSON.stringify(o)} Parent: ${JSON.stringify(e,null,2)})`)};var dt=(e,t,n)=>{let o=A(n,t),{usedDataFields:l}=J(o,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"&&l.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&l.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var Pt=(e,t,n)=>{let o=A(n,t),{usedFields:l}=J(o,t);return t.$op?(dt(e,t,n),t.$op):t.$id||t.$filter?l.length>0?(dt(e,{...t,$op:"update"},n),"update"):(dt(e,{...t,$op:"link"},n),"link"):t.$tempId?l.length>0?(dt(e,{...t,$op:"create"},n),"create"):(dt(e,{...t,$op:"create"},n),"link"):(dt(e,{...t,$op:"create"},n),"create")};var Ae=(e,t)=>{let o=(radash.isArray(e.$root)?e.$root:[e.$root]).map(l=>{let a=Pt(l,l,t);return {...{...l.$thing?{}:{$thing:l.$entity||l.$relation},...l.$thingType?{}:{$thingType:me(l,t)},...l.$op?{}:{$op:a},...l.$bzId?{}:{$bzId:`R_${uuid.v4()}`}},...l}});e.$root=radash.isArray(e.$root)?o:o[0];};var St=(e,t)=>{let n=t[Qt];return types.isSet(n)?n.has("clean")?(Reflect.set(t,Qt,n.add("clean")),!0):!1:(Reflect.set(t,Qt,new Set(["clean"])),!0)};var qe=(e,t,n)=>{if(St("split_ids",e)){let o=(radash.isArray(e[t])?e[t]:[e[t]]).flatMap(l=>{if(radash.isObject(l)&&"$id"in l&&radash.isArray(l.$id)){let a=l;if(A(n,a),!a.$bzId)throw new Error("[Internal Error] No bzId found");return a.$id.map((d,h)=>({...rt(a),$id:d,$bzId:`${a.$bzId}_${h}`,...v(a)}))}return l});(o.length>radash.isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=o);}};var xe=(e,t,n,o)=>{let l=(radash.isArray(e[t])?e[t]:[e[t]]).map(a=>{let d=$t(t,n),[h]=d,T=Pt(e,{...a,$thing:h.thing,$thingType:h.thingType},o),k=a.$bzId?a.$bzId:a.$tempId?a.$tempId:`N_${uuid.v4()}`;if(!n)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(n)}`);return {...a,[it]:n,$thing:h.thing,$thingType:h.thingType,$op:T,$bzId:k}});e[t]=radash.isArray(e[t])?l:l[0];};var je=(e,t,n)=>{let o=e[t];o&&(radash.isArray(o)?o:[o]).forEach(l=>{let a=A(n,l),{unidentifiedFields:d}=J(a,l),{computedFields:h,virtualFields:T}=a,k=radash.listify(l,(s,f)=>f!==void 0?s:void 0),r=k.filter(s=>T?.includes(s));if(r.length>0)throw new Error(`Virtual fields can't be sent to DB: "${r.join(",")}"`);if(h.filter(s=>!k.includes(s)).forEach(s=>{let f=a.dataFields?.find(B=>B.path===s),c=a.linkFields?.find(B=>B.path===s)?.oppositeLinkFieldsPlayedBy[0],m="roles"in a?fe(a.roles,(B,S)=>B===s):void 0,p=f||c||m;if(!p)throw new Error(`no field Def for ${s}`);if(l.$op==="create"&&!l[s]){let B=ft({currentThing:l,fieldSchema:p,mandatoryDependencies:!0});l[s]=B;}}),d.length>0)throw new Error(`Unknown fields: [${d.join(",")}] in ${JSON.stringify(l)}`)});};var Ct=(e,t)=>{let n=A(t,e).hooks;if(n?.pre){let o=`on${ye(e.$op)}`;return n.pre.filter(d=>!d.triggers||d.triggers[o]?.()).flatMap(d=>d.actions)}return []};var We=(e,t,n,o)=>{(radash.isArray(e[t])?e[t]:[e[t]]).forEach(a=>{if("$thing"in a){let{requiredFields:d,enumFields:h,fnValidatedFields:T,dataFields:k}=A(n,a);if("$op"in a&&a.$op==="create"&&d.forEach(r=>{if(!(r in a))throw new Error(`[Validations] Required field "${r}" is missing.`)}),("$op"in a&&a.$op==="update"||a.$op==="create")&&h.forEach(r=>{if(r in a){let i=k?.find(s=>s.path===r)?.validations?.enum;if(!i)throw new Error(`[Validations] Enum field "${r}" is missing enum options.`);if(radash.isArray(a[r]))a[r].some(s=>{if(!i.includes(s))throw new Error(`[Validations] Option "${s}" is not a valid option for field "${r}".`)});else if(i&&!i.includes(a[r]))throw new Error(`[Validations] Option "${a[r]}" is not a valid option for field "${r}".`)}}),("$op"in a&&a.$op==="update"||a.$op==="create")&&T.forEach(r=>{if(r in a)try{let i=k?.find(s=>s.path===r)?.validations?.fn;if(!i)throw new Error("Missing validation function.");if(!i(a[r]))throw new Error("Failed validation function.")}catch(i){throw new Error(`[Validations:attribute:${r}] ${i.message}`)}}),radash.isObject(a)&&"$thing"in a){let r=a.$thing,i=a,s=radash.clone(rt(e)),f=radash.clone(rt(i)),u=o.mutation?.context||{};Ct(i,n).forEach(m=>{if(m.type==="validate"){if(m.severity!=="error")return;try{let p=m.fn(f,s,u);if(p===!1)throw new Error(`${m.message}.`);if(p!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(p){throw new Error(`[Validations:thing:${r}] ${p.message}`)}}});}}});};var He=(e,t,n,o)=>{let l=(radash.isArray(e[t])?e[t]:[e[t]]).map(a=>{if(Lt(a)){let d=Ct(a,n).filter(r=>r.type==="transform"),h=radash.clone(rt(e)),T=radash.clone(rt(a)),k=o.mutation?.context||{};return d.forEach(r=>{let i=r.fn(T,h,k);Object.keys(i).length!==0&&(a={...T,...i,...v(a)});}),a}});e[t]=radash.isArray(e[t])?l:l[0];};var Ke=(e,t,n)=>{let o=$t(t,n),[l]=o;e[t]={$thing:l.thing,$thingType:l.thingType,$op:"unlink",$bzId:`U_${uuid.v4()}`,[it]:n};};var ar=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(St("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")},lr=(e,t)=>{},te=(e,t,n)=>{let l=immer.produce({$rootWrap:{$root:e}},a=>objectTraversal.traverse(a,({value:d,parent:h,key:T,meta:k})=>{if(!(!h||!T)&&radash.isObject(d)){if(!("$root"in d)){if(!("$thing"in d||"$entity"in d||"$relation"in d))throw T==="$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 r=d;Object.keys(r).forEach(i=>{if(ar(r,i),i!=="$root"&&(i.startsWith("$")||i.startsWith("%")))return;let s=i!=="$root"?Kt(t,r,i):{fieldType:"rootField"};if(!s)throw new Error(`[Internal] Field ${i} not found in schema`);if("contentType"in s)return lr();if(["rootField","linkField","roleField"].includes(s.fieldType)){if(["linkField","roleField"].includes(s.fieldType)&&(r[i]===null?Ke(r,i,s):Oe(r,i,s)),s.fieldType==="rootField"){if(!("$root"in r))throw new Error(`[Internal] Field ${i} is a rootField but the object is not a root`);Ae(r,t);}let f=radash.isArray(r[i])?r[i]:[r[i]],u=k.nodePath?.split(".").slice(1).join(".");f.forEach(m=>{if(m){if(s?.cardinality==="ONE"&&!m.$op&&!m.$id&&!m.$filter&&!m.$tempId&&r.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${u}.${i}`);if(m.$tempId&&!(m.$op===void 0||m.$op==="link"||m.$op==="create"||m.$op==="update"))throw new Error(`Invalid op ${m.$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(s.fieldType)&&xe(r,i,s,t),qe(r,i,t),["rootField","linkField","roleField"].includes(s.fieldType)&&je(r,i,t),(radash.isArray(r[i])?r[i]:[r[i]]).forEach(m=>{let p=A(t,m),{unidentifiedFields:B,usedLinkFields:S,usedFields:$,fields:Q}=J(p,m);if($.forEach(C=>{if(!Q.includes(C))throw new Error(`[Schema] Field ${C} not found in the schema`)}),B.length>0)throw new Error(`Unknown fields: [${B.join(",")}] in ${JSON.stringify(d)}`);if(S.length>1){let C=p.linkFields?.filter(g=>S.includes(g.path));C?.some((g,b)=>C.some((F,y)=>{if(b!==y&&g.target!==F.target&&g.relation===F.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),He(r,i,t,n),We(r,i,t,n);}});}}));return radash.isArray(l.$rootWrap.$root),l.$rootWrap.$root};var ve=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:o}=await wt(t,n),l=await o.transaction(typedbDriver.TransactionType.WRITE);if(!l)throw new Error("Can't create transaction");let a=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,d=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;a&&await l.query.delete(a);let h=d&&l.query.insert(d);try{let T=h?await h.collect():void 0;return await l.commit(),await l.close(),{insertions:T}}catch(T){throw await l.close(),new Error(`Transaction failed: ${T.message}`)}};var Ue=async(e,t,n,o,l)=>{let a=[...t,...n],d=a.map(h=>{let T=e.insertions?.find(i=>i.get(`${h.$bzId}`))?.get(`${h.$bzId}`),k=h.$thing||h.$relation||h.$entity,r=k?kt(o,k):void 0;if(h.$op==="create"||h.$op==="update"||h.$op==="link"){if(h.$op!=="update"&&!T&&h.$id)return {$id:h.$id,$error:"Does not exist or it's not linked to the parent"};let i=T?.asThing().iid,s=Object.entries(h).filter(([u,c])=>!u.startsWith("$")).reduce((u,[c,m])=>{if(r?.dataFields?.find(B=>B.path===c)?.contentType==="JSON")return u[c]=JSON.parse(m),u;if(h.$thingType==="relation"){let B=a.filter(S=>S.$id&&S.$bzId===m);if(B.length>1)throw new Error(`Multiple things with the same bzId ${m}`);return B.length===1?(u[c]=B[0].$id,u):(u[c]=m,u)}return u[c]=m,u},{});if(l.mutation?.noMetadata)return s;let f=h.$tempId&&!h.$tempId.startsWith("_:")?{$tempId:`_:${h.$tempId}`}:{};return {$dbId:i,...h,...s,[h.path]:h.$id,...f}}if(h.$op==="delete"||h.$op==="unlink")return h;if(h.$op!=="match")throw new Error(`Unsupported op ${h.$op}`)}).filter(h=>h);return radash.clone(d)};var Je=e=>{let t=({value:n})=>(n&&typeof n=="object"&&"$id"in n&&(Object.keys(n).filter(a=>a.startsWith("$")).forEach(a=>delete n[a]),Object.keys(n).filter(a=>typeof a=="symbol").forEach(a=>delete n[a])),n);return immer.produce(e,n=>objectTraversal.traverse(n,t))};var Xe=async(e,t)=>{let n=r=>{let i=[],s=[],f=p=>{if(p.$id)return p.$id;let B=A(t,p),{idFields:S}=B;if(!S)throw new Error(`no idFields: ${JSON.stringify(p)}`);let[$]=S;if(!$)throw new Error(`no idField: ${JSON.stringify(p)}`);let Q=B.dataFields?.find(b=>b.path===$),C=ft({currentThing:p,fieldSchema:Q,mandatoryDependencies:!0}),g=p[$]||p.$id||C;if(!g)throw new Error(`no idValue: ${JSON.stringify(p)}`);return g},u=p=>{if(p.$op==="create"){let B=f(p);if(i.find(S=>S.$id===B&&S.$op==="create"))throw new Error(`Duplicate id ${B} for node ${JSON.stringify(p)}`);if(s.find(S=>S.$bzId===p.$bzId))throw new Error(`Duplicate $bzId ${p.$bzId} for node ${JSON.stringify(p)}`);i.push({...p,$id:B});return}p.$tempId&&p.$op==="match"||i.push(p);},c=p=>{if(p.$op==="create"){let B=f(p);if(i.find(S=>S.$id===B),s.find(S=>S.$bzId===p.$bzId))throw new Error(`Duplicate %bzId ${p.$bzIdd} for edge ${JSON.stringify(p)}`);s.push({...p,$id:B});return}s.push(p);};return objectTraversal.traverse(r,({value:p,parent:B,meta:S})=>{if(!radash.isObject(p))return;let $=p;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 Q=A(t,$),{dataFields:C,roleFields:g,linkFields:b,usedFields:F}=J(Q,$),y=()=>{if($.$op==="create"||$.$op==="delete")return $.$op;if($.$op==="update"){let L=F.filter(w=>C?.includes(w)),E=F.filter(w=>g?.includes(w)),I=F.filter(w=>b?.includes(w));if(L.length>0)return "update";if(E.length>0||I.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify($)}`)}return "match"},P={...$.$id&&{$id:$.$id},...$.$tempId&&{$tempId:$.$tempId},...$.$filter&&{$filter:$.$filter},$thing:$.$thing,...$.$thingType&&{$thingType:$.$thingType},...radash.shake(radash.pick($,C||[""])),$op:y(),$bzId:$.$bzId};u(P);let M=$[it];if(M?.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");i.push({...$,$op:"match"});}let L=M.relation===$.$thing,E=L?$.$bzId:`LT_${uuid.v4()}`,w=ge(r,B,S).$bzId;if(!w)throw new Error("No parent id found");let O=()=>{if($.$op==="delete")return L?"match":"delete";if($.$op==="unlink")return L?"unlink":"delete";if($.$op==="link"||$.$op==="create")return L?"link":"create";if($.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},R=A(t,{$thing:M.relation,$thingType:"relation"});if(!Object.keys(R.roles).includes(M.plays))throw new Error(`[Wrong format] Field ${M.plays} is not a role of relation ${M.relation}`);let N={$bzId:E,$thing:M.relation,$thingType:"relation",...$.$tempId?{$tempId:$.$tempId}:{},$op:O(),...L?{}:{[M.path]:$.$bzId},[M.plays]:w,[it]:M,[ct]:"linkField"};c(N),($.$op==="unlink"||O()==="unlink")&&L&&c({$thing:M.relation,$thingType:"relation",$bzId:E,$op:"match",[M.plays]:w,[it]:M,[ct]:"linkField"});}if($.$thingType==="relation"){let L=Ft($,(w,O)=>g.includes(w)),E=radash.mapEntries(L,(w,O)=>radash.isArray(O)?[w,O]:radash.isObject(O)?[w,O.$bzId]:[w,O]),I=Ft(p,(w,O)=>w.startsWith("$")||w.startsWith("Symbol"));if(Object.keys(L).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")},O=A(t,$).roles,R=radash.mapEntries(E,(N,D)=>{let _=O[N]?.cardinality;if(!_)throw new Error(`Role ${N} not found in schema`);if(Array.isArray(D)){if(_==="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(X=>X.$bzId||X)]}return [N,D.$bzId||D]}),z={...I,$thing:$.$thing,$thingType:"relation",$op:w(),...R,$bzId:$.$bzId,[ct]:"roleField"};c(z);return}if($.$op==="match"||$.$op==="update"&&Object.keys(L).length>0){let w=0;Object.entries(L).forEach(([O,R])=>{let z=radash.isArray(R)?R:[R],N=D=>D==="create"||D==="replace"?"link":D;z.forEach(D=>{if(!D)return;let _=N(D.$op);if(_==="replace")throw new Error("Not supported yet: replace on roleFields");if(_==="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 X={...I,$thing:$.$thing,$thingType:"relation",$op:_==="delete"?"unlink":_,[O]:D.$bzId,$bzId:$.$bzId,[ct]:"roleField"};c(X);});});}}}}}),[i,s]},[o,l]=n(e),a=o.reduce((r,i)=>{if(!i.$bzId)return [...r,i];let s=r.findIndex(f=>f.$bzId===i.$bzId);if(s===-1)return [...r,i];if(r[s].$op==="create"&&i.$op==="match")return r;if(r[s].$op==="match"&&(i.$op==="create"||i.$op==="match"))return [...r.slice(0,s),i,...r.slice(s+1)];throw new Error(`[Wrong format] Wrong operation combination for $tempId "${i.$tempId}". Existing: ${r[s].$op}. Current: ${i.$op}`)},[]),d=l.reduce((r,i)=>{let s=r.find(f=>(f.$id&&f.$id===i.$id||f.$bzId&&f.$bzId===i.$bzId)&&f.$thing===i.$thing&&f.$op===i.$op);if(s){let f={...s};return Object.keys(i).forEach(c=>{if(typeof c=="symbol"||c.startsWith("$"))return;let m=s[c],p=i[c];Array.isArray(m)&&Array.isArray(p)?f[c]=Array.from(new Set([...m,...p])):!Array.isArray(m)&&Array.isArray(p)?m!==void 0?f[c]=Array.from(new Set([m,...p])):f[c]=p:Array.isArray(m)&&!Array.isArray(p)?p!==void 0&&(f[c]=Array.from(new Set([...m,p]))):m!==null&&p!==null&&m!==void 0&&p!==void 0?f[c]=Array.from(new Set([m,p])):m==null&&(f[c]=p);}),[...r.filter(c=>!((c.$id&&c.$id===i.$id||c.$bzId&&c.$bzId===i.$bzId)&&c.$thing===i.$thing&&c.$op===i.$op)),f]}return [...r,i]},[]);a.forEach(r=>{if((r.$thingType==="relation"||"relation"in r)&&d.filter(i=>i.$bzId===r.$bzId||i.$tempId&&i.$tempId===r.$tempId).length===0){if(r.$op==="delete"||r.$op==="match"||r.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(Je(r))}`)}});let h=[...a,...d],T=new Set(h.filter(r=>r.$tempId).map(r=>r.$tempId)),k=Array.from(T).filter(r=>!h.some(i=>i.$tempId===r&&i.$op==="create"));if(k.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${k.join(", ")}`);return {mergedThings:a,mergedEdges:d}};var tn=async(e,t,n)=>{let o=s=>{let f=s.$op,u=`$${s.$bzId}`,c=A(n,s),{idFields:m,defaultDBConnector:p}=c,B=p?.path||s.$thing,S=s.$id,$=m?.[0],Q=radash.listify(s,(L,E)=>{if(L.startsWith("$")||L.startsWith("%")||L===$||E===void 0||E===null)return "";let I=c.dataFields?.find(R=>R.path===L);if(!I?.path)return "";let O=I.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(I.contentType))return `has ${O} '${E}'`;if(["NUMBER","BOOLEAN"].includes(I.contentType))return `has ${O} ${E}`;if(I.contentType==="DATE"){if(Number.isNaN(E.valueOf()))throw new Error("Invalid format, Nan Date");return E instanceof Date?`has ${O} ${E.toISOString().replace("Z","")}`:`has ${O} ${new Date(E).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${I.contentType}`)}).filter(L=>L),C=`${u}-atts`,g=radash.listify(s,L=>{if(L.startsWith("$")||L.startsWith("%")||L===$)return "";let E=c.dataFields?.find(O=>O.path===L);if(!E?.path)return "";let w=E.dbPath;return `{${C} isa ${w};}`}).filter(L=>L),b=radash.isArray(S)?`like '${S.join("|")}'`:`'${S}'`,F=S?[`has ${$} ${b}`]:[],y=[...F,...Q].filter(L=>L).join(","),P=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${u} isa ${[B,...F].filter(L=>L).join(",")};`;if(f==="update"){if(!g.length)throw new Error("update without attributes");return `${u} isa ${[B,...F].filter(L=>L).join(",")}, has ${C};
62
- ${g.join(" or ")};`}return ""},M=()=>f==="update"||f==="link"||f==="match"?`${u} isa ${[B,...F].filter(L=>L).join(",")};`:"";if(Lt(s))return {op:f,deletionMatch:P(),insertionMatch:M(),insertion:f==="create"?`${u} isa ${[B,y].filter(L=>L).join(",")};`:f==="update"&&Q.length?`${u} ${Q.join(",")};`:"",deletion:f==="delete"?`${u} isa ${B};`:f==="update"&&g.length?`${u} has ${C};`:""};throw new Error("in attributes")},l=s=>{let f=s.$op,u=A(n,s),c=`$${s.$bzId}`,m=s.$id,p=u.defaultDBConnector?.path||s.$thing,B="roles"in u?radash.listify(u.roles,E=>E):[],S="roles"in u?radash.mapEntries(u.roles,(E,I)=>[E,I.dbConnector?.path||E]):{},$=radash.listify(s,(E,I)=>{if(!B.includes(E))return null;if(!("roles"in u))throw new Error("This should have roles! ");let w=S[E];return Array.isArray(I)?I.map(O=>({path:w,id:O})):{path:w,id:I}}).filter(E=>E).flat(),Q=$.map(E=>{if(!E?.path)throw new Error("Object without path");return `${E.path}: $${E.id}`}),C=$.length>0?`( ${Q.join(" , ")} )`:"",g=s[ct];if(!g)throw new Error("[internal error] Symbol edgeType not defined");let b=C?`${c} ${C} ${g==="linkField"||f==="delete"||f==="unlink"?`isa ${p}`:""}`:"",F=`${c} ${g==="linkField"||f==="delete"?`isa ${p}`:""}`,y=()=>b?f==="link"?`${b};`:f==="create"?`${b}, has id '${m}';`:"":"",P=()=>b&&f==="match"?`${b};`:"",M=()=>b?f==="delete"?`${b};`:f==="match"?`${b};`:"":"",L=()=>b?f==="delete"?`${F};`:f==="unlink"?`${c} ${C};`:"":"";return {deletionMatch:M(),insertionMatch:P(),deletion:L(),insertion:y(),op:""}},a=(s,f)=>{let u=f==="edges"?l:o;if(Array.isArray(s))return s.map($=>{let{preDeletionBatch:Q,insertionMatch:C,deletionMatch:g,insertion:b,deletion:F}=u($);return radash.shake({preDeletionBatch:Q,insertionMatch:C,deletionMatch:g,insertion:b,deletion:F},y=>!y)}).filter($=>$);let{preDeletionBatch:c,insertionMatch:m,deletionMatch:p,insertion:B,deletion:S}=u(s);return radash.shake({preDeletionBatch:c,insertionMatch:m,deletionMatch:p,insertion:B,deletion:S},$=>!$)},d=a(e),h=Array.isArray(d)?d:[d],T=a(t,"edges"),k=Array.isArray(T)?T:[T],r=[...h,...k];return radash.shake({insertionMatches:r.map(s=>s.insertionMatch).join(" ").trim(),deletionMatches:r.map(s=>s.deletionMatch).join(" ").trim(),insertions:r.map(s=>s.insertion).join(" ").trim(),deletions:r.map(s=>s.deletion).join(" ").trim()},s=>!s)};var Br=Symbol.for("grandChildOfCreate"),en=async(e,t,n,o)=>{let l=(g,b)=>Object.keys(g).filter(F=>F.startsWith("$")?!1:b?!A(t,g).dataFields?.find(P=>P.path===F):!0);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(n.mutation?.preQuery===!1)return;let a=[];if(objectTraversal.traverse(e,({parent:g,key:b,value:F})=>{g&&b&&!b.includes("$")&&radash.isObject(g)?(Array.isArray(g[b])?g[b]:[g[b]]).forEach(P=>{if(radash.isObject(P)){if(g.$op!=="create")a.includes(P.$op)||a.push(P.$op);else if(P.$op==="delete"||P.$op==="unlink")throw new Error(`Cannot ${P.$op} under a create`)}}):!g&&radash.isObject(F)&&(a.includes(F.$op)||a.push(F.$op));}),!a.includes("delete")&&!a.includes("unlink")&&!a.includes("replace")&&!a.includes("update")&&!a.includes("link"))return;let h=(g=>{let b=(F,y)=>{let P=[],M={},L=["$op","$bzId","$parentKey"],E=["$relation","$entity","$id",...L];for(let I in F)if(!L.includes(I)&&!(E.includes(I)&&!y))if(!I.includes("$")&&(radash.isObject(F[I])||Array.isArray(F[I]))){let w=F[I];Array.isArray(w)&&w.length>0?w.forEach(O=>{P.push({$path:I,...b(O)});}):P.push({$path:I,...b(w)});}else M[I]=F[I];return {...M,$fields:P}};return g.map(F=>b(F,!0))})(Array.isArray(e)?e:[e]),T=await It(h,n,t,o),k=(g,b)=>{let F=g.$id||g.id||g.$bzId;if(g.$objectPath){let{$objectPath:y}=g,P=y?.beforePath||"root",M=Array.isArray(y.ids)?`[${y.ids}]`:y.ids;return {beforePath:`${P}.${M}___${y.key}`,ids:F,key:b}}else return {beforePath:"root",ids:F,key:b}},r=(g,b)=>{let F=g?.beforePath||"root",y=b||(Array.isArray(g?.ids)?`[${g?.ids}]`:g?.ids);return `${F}.${y}___${g?.key}`},i=g=>{if(g.includes("[")&&g.includes("]")){let[b,F,y]=g.split(/[[\]]/);return F.split(",").map(M=>`${b}${M}${y}`)}else return [g]},s={};(g=>immer.produce(g,b=>objectTraversal.traverse(b,F=>{let{key:y,parent:P}=F;if(P&&y&&P.$id&&!y.includes("$")){let M=k(P,y),L=r(M);if(Array.isArray(P[y])){let E=[];P[y].forEach(I=>{radash.isObject(I)?(I.$objectPath=M,E.push(I.$id.toString())):I&&E.push(I.toString());}),s[L]={$objectPath:M,$ids:E};}else {let E=P[y];radash.isObject(E)?(s[L]={$objectPath:M,$ids:[E.$id.toString()]},E.$objectPath=M):E&&(s[L]={$objectPath:M,$ids:[E.toString()]});}}})))(T||{});let u=g=>immer.produce(g,b=>objectTraversal.traverse(b,F=>{let{key:y,value:P,parent:M}=F;M&&y&&!y.includes("$")&&(Array.isArray(P)||radash.isObject(P))&&!Array.isArray(M)&&(Array.isArray(M[y])?M[y].forEach(L=>{typeof L!="string"&&(L.$objectPath=k(M,y),L.$parentIsCreate=M.$op==="create",L[Br]=M.$parentIsCreate||M[Symbol.for("grandChildOfCreate")]);}):radash.isObject(M[y])&&(M[y].$parentIsCreate=M.$op==="create",M[y][Symbol.for("grandChildOfCreate")]=M.$parentIsCreate||M[Symbol.for("grandChildOfCreate")],M[y].$objectPath=k(M,y)));})),c=u(e),p=(g=>{let b=(M,L)=>{let E=[];M.filter(R=>R).forEach(R=>{let z=Object.keys(R).filter(N=>!N.startsWith("$")).length;if(Array.isArray(R.$id)&&z>0){let N=R.$id.map(D=>({...R,$id:D}));E=[...E,...N];}else E.push({...R});});let I=[],w=[],O=E.filter(R=>{let N=["delete","update","unlink"].includes(R.$op||""),D=l(R,!0).length;if((!R.$id||Array.isArray(R.$id)&&D>0||R.$filter)&&N)return !0;w.push({...R});});return O.length>0?O.forEach(R=>{let N=(j=>{let yt=(()=>{let V={};for(let x in j){let nt=A(t,j);!x.startsWith("$")&&nt.dataFields?.find(ht=>ht.path===x)&&(V[x]=j[x]);}return V})(),gt=Object.keys(j),et=gt.filter(V=>!V.startsWith("$")),xt=[],Tt=(V,x)=>{if(V===et.length){let ht={...x};gt.forEach(H=>{H.startsWith("$")&&(ht[H]=j[H]);}),xt.push(ht);return}let nt={...x,[et[V]]:j[et[V]],...v(x),...yt};Tt(V+1,nt),Tt(V+1,x);};return Tt(0,{...v(j)}),xt})(R).filter(j=>!(j.$op==="update"&&Object.keys(j).filter(at=>!at.startsWith("$")).length===0)),D=[],_=r(R.$objectPath),tt=s[_]?s[_].$ids:[],q=N.map((j,at)=>{let yt=A(t,j),et=Object.keys(j).filter(x=>!x.includes("$")&&!yt.dataFields?.some(nt=>nt.path===x)).map(x=>(Array.isArray(j[x])?j[x].length>1?j[x].filter(H=>!H.$id||Array.isArray(H.$id)||H.$filter):j[x]:[j[x]]).map(H=>{let jt=r(H.$objectPath);return {idsToKey:(Nt=>{let ae=[],Et=Nt.split("."),Tn=Et.slice(0,Et.length-1).join("."),Mn=Et.slice(Et.length-1,Et.length)[0].split("___")[1];for(let zt in s)if(zt.startsWith(Tn)&&zt.endsWith(Mn)){let Wt=zt.split("."),kn=Wt.slice(Wt.length-1,Wt.length)[0].split("___")[0];ae.push(kn);}return ae})(jt),key:x,multiple:H}})).filter(x=>x!==void 0),V=(x=>{let nt=x.map(H=>H.map(lt=>lt.idsToKey));return (H=>H.length>0?H.reduce((lt,Bt)=>lt.concat(Bt),[]).reduce((lt,Bt)=>lt?Bt.filter(Nt=>lt.includes(Nt)):Bt):[])(nt)})(et).filter(x=>!D.includes(x));if(D=[...D,...V],tt=tt.filter(x=>!V.includes(x)),at===N.length-1&&tt.length>0)return {...j,$id:tt,$bzId:`T1_${uuid.v4()}`,...v(j)};if(V.length>0)return {...j,$id:V,$bzId:`T2_${uuid.v4()}`,...v(j)}}).filter(j=>j!==void 0),bn=(()=>{if(q.length===0&&!L?.$id)return O;if(q.length===0&&L?.$id){let j=Array.isArray(L.$id)?L.$id:[L.$id],at=[];return j.forEach(yt=>{let gt=r({...R.$objectPath,ids:yt}),et=s[gt];et&&at.push({...R,$id:et.$ids,...v(R),$bzId:`T_${uuid.v4()}`});}),at}else return q.filter(j=>j!==void 0)})();I=[...w,...bn].map(F);}):I=E.map(F),I},F=M=>{let L={...M,$bzId:M.$tempId??`T3_${uuid.v4()}`,...v(M)},E=A(t,M);return Object.keys(M).filter(I=>!I.includes("$")&&!E.dataFields?.some(w=>w.path===I)).forEach(I=>{let w=Array.isArray(M[I])?M[I]:[M[I]],O=b(w,M);L[I]=O.length>0?O:void 0;}),L},y=[];return g.forEach(M=>{y=[...y,...b([M])];}),y.map(M=>F(M))})(Array.isArray(c)?c:[c]),B=g=>g.map(b=>{let F=l(b,!0),y={...b};return F.forEach(P=>{let M=Array.isArray(b[P])?b[P]:[b[P]],L=[],E=[],I=[],w={},O=vt(t,b,P);M.filter(q=>q).forEach(q=>{q.$op==="replace"&&q.$id?(w=q,Array.isArray(q.$id)?E=[...E,...q.$id]:E.push(q.$id)):q.$op==="create"&&O==="ONE"&&q.id?(w=q,Array.isArray(q.id)?I=[...E,...q.id]:I.push(q.id)):L.push(q);});let R=r(w.$objectPath),N=i(R).map(q=>s[q]),D=[];N.filter(q=>q!=null).forEach(q=>{D=[...D,...q.$ids];});let _=D.filter(q=>!E.includes(q)),X=E.filter(q=>!D.includes(q)),tt=v(w);_.length>0&&L.push({...w,$op:"unlink",$id:_,$bzId:`T4_${uuid.v4()}`,id:void 0,...tt}),X.length>0&&X.forEach(q=>{L.push({...w,$op:"link",$id:q,$bzId:`T5_${uuid.v4()}`,...tt});}),I.length>0&&I.forEach(q=>{L.push({...w,$op:"create",id:q,$bzId:`T6_${uuid.v4()}`,...tt});}),y[P]=B(L);}),y}),S=u(B(u(p)));return (g=>immer.produce(g,b=>objectTraversal.traverse(b,F=>{let{key:y,value:P,parent:M}=F;y&&M&&!y?.includes("$")&&(Array.isArray(P)||radash.isObject(P))&&!Array.isArray(M)&&(Array.isArray(P)?P:[P]).forEach(E=>{let I=s[r(E.$objectPath)],w=(z,N)=>z.every(D=>N.includes(D)),O=E.$id?Array.isArray(E.$id)?w(E.$id,I?I.$ids:[]):I?.$ids.includes(E.$id):I,R=vt(t,M,E.$objectPath.key);if(E.$op==="link"&&O&&R==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${r(E.$objectPath)}" because it is already occupied.`);if(E.$op)switch(E.$op){case"delete":if(!O&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${E.$id}" because it is not linked to $id:"${M.$id}"`);break;case"update":if(!O&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${E.$id}" because it is not linked to $id:"${M.$id}"`);break;case"unlink":if(!O&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${E.$id}" because it is not linked to $id:"${M.$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:"${M.$id}"`);break;}});})))(S),(g=>immer.produce(g,b=>objectTraversal.traverse(b,F=>{let{value:y,meta:P}=F;radash.isObject(y)&&(y[Symbol.for("path")]=P.nodePath,delete y.$objectPath,delete y.$parentIsCreate);})))(S)};function W(e){return {enumerable:!0,value:e}}function nn(e){return {enumerable:!0,writable:!0,value:e}}var mt={},Er=()=>!0,rn=()=>({}),sn=e=>e,Fr=(e,t,n,o)=>e.apply(n,o)&&t.apply(n,o),wr=(e,t,n,[o,l])=>t.call(n,e.call(n,o,l),l),ot=(e,t)=>Object.freeze(Object.create(e,t));function on(e,t,n){return e.reduce((o,l)=>function(...a){return n(o,l,this,a)},t)}function an(e){return ot(this,{fn:W(e)})}var ln={},Y=an.bind(ln);var cn={},dn=an.bind(cn);function At(e,t){return t.filter(n=>e.isPrototypeOf(n))}function pn(e,t,...n){let o=on(At(cn,n).map(a=>a.fn),Er,Fr),l=on(At(ln,n).map(a=>a.fn),sn,wr);return ot(this,{from:W(e),to:W(t),guards:W(o),reducers:W(l)})}var un={},hn={},G=pn.bind(un);pn.bind(hn,null);function br(e,t,n){return re(t,e,n,this.immediates)||e}function fn(e){let t=new Map;for(let n of e)t.has(n.from)||t.set(n.from,[]),t.get(n.from).push(n);return t}var Tr={enter:sn};function $n(...e){let t=At(un,e),n=At(hn,e),o={final:W(e.length===0),transitions:W(fn(t))};return n.length&&(o.immediates=W(n),o.enter=W(br)),ot(Tr,o)}var Mr={enter(e,t,n){let o=this.fn.call(t,t.context,n);return ne.isPrototypeOf(o)?ot(mn,{machine:W(o),transitions:W(this.transitions)}).enter(e,t,n):(o.then(l=>t.send({type:"done",data:l})).catch(l=>t.send({type:"error",error:l})),e)}},mn={enter(e,t,n){if(t.child=ie(this.machine,o=>{t.onChange(o),t.child==o&&o.machine.state.value.final&&(delete t.child,t.send({type:"done",data:o.context}));},t.context,n),t.child.machine.state.value.final){let o=t.child.context;return delete t.child,re(t,e,{type:"done",data:o},this.transitions.get("done"))}return e}};function st(e,...t){let n=W(fn(t));return ne.isPrototypeOf(e)?ot(mn,{machine:W(e),transitions:n}):ot(Mr,{fn:W(e),transitions:n})}var ne={get state(){return {name:this.current,value:this.states[this.current]}}};function yn(e,t,n=rn){return typeof e!="string"&&(n=t||rn,t=e,e=Object.keys(t)[0]),mt._create&&mt._create(e,t),ot(ne,{context:W(n),current:W(e),states:W(t)})}function re(e,t,n,o){let{context:l}=e;for(let{to:a,guards:d,reducers:h}of o)if(d(l,n)){e.context=h.call(e,l,n);let T=t.original||t,k=ot(T,{current:W(a),original:{value:T}});mt._onEnter&&mt._onEnter(t,a,e.context,l,n);let r=k.state.value;return e.machine=k,e.onChange(e),r.enter(k,e,n)}}function kr(e,t){let n=t.type||t,{machine:o}=e,{value:l,name:a}=o.state;return l.transitions.has(n)?re(e,o,t,l.transitions.get(n))||o:(mt._send&&mt._send(n,a),o)}var Lr={send(e){kr(this,e);}};function ie(e,t,n,o){let l=Object.create(Lr,{machine:nn(e),context:nn(e.context(n,o)),onChange:W(t)});return l.send=l.send.bind(l),l.machine=l.machine.state.value.enter(l.machine,l,o),l}var gn=(e,t)=>immer.produce(e,o=>qt(t,o)),qt=(e,t,n)=>{if(typeof t=="string")return;if(Array.isArray(t)){t.forEach(l=>qt(e,l,n));return}let o=kt(e,n||t.$entity||t.$relation||t.$thing);Object.entries(t).forEach(([l])=>{l.startsWith("$")||Ir(e,t,l,o);});},Ir=(e,t,n,o)=>{let l=t[n];if(!l)return;let a=o.dataFields?.find(h=>h.path===n);if(a){a.contentType==="JSON"&&l!=null&&(t[n]=JSON.stringify(l));return}let d=o.linkFields?.find(h=>h.path===n);if(d){let h=d.oppositeLinkFieldsPlayedBy[0]?.thing;qt(e,l,h);return}if(o.thingType==="relation"){let h=o.roles[n],[T]=h.playedBy||[];if(!T)throw new Error(`Role ${h.name} in ${o} is not played by anything`);qt(e,l,T.thing);}};var Bn=$n,Dt=(e,t)=>t.data?{...e,bql:{...e.bql,current:t.data}}:e,Pr=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Sr=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),Cr=(e,t)=>({...e,typeDB:{...e.typeDB,tqlMutation:t.data}}),Or=(e,t)=>({...e,typeDB:{...e.typeDB,tqlRes:t.data}}),Rr=async e=>Object.keys(e.bql.current).length?te(e.bql.current,e.schema,e.config):te(e.bql.raw,e.schema,e.config),Ar=async e=>en(e.bql.current,e.schema,e.config,e.handles),qr=async e=>Xe(e.bql.current,e.schema),Dr=async e=>tn(e.bql.things,e.bql.edges,e.schema),xr=async e=>ve(e.typeDB.tqlMutation,e.handles,e.config),jr=async e=>Ue(e.typeDB.tqlRes,e.bql.things,e.bql.edges,e.schema,e.config),Nr=()=>!0,ut=G("error","error",Y((e,t)=>({...e,error:t.error}))),zr=yn("stringify",{stringify:st(async e=>gn(e.bql.raw,e.schema),G("done","enrich",Y(Dt)),ut),enrich:st(Rr,G("done","preQuery",dn(Nr),Y(Dt)),G("done","parseBQL",Y(Dt)),ut),preQuery:st(Ar,G("done","parseBQL",Y(Dt)),ut),parseBQL:st(qr,G("done","buildMutation",Y(Sr)),ut),buildMutation:st(Dr,G("done","runMutation",Y(Cr)),ut),runMutation:st(xr,G("done","parseMutation",Y(Or)),ut),parseMutation:st(jr,G("done","success",Y(Pr)),ut),success:Bn(),error:Bn()},e=>e),Wr=async e=>new Promise((t,n)=>{ie(zr,o=>{o.machine.state.name==="success"&&t(o.context),o.machine.state.name==="error"&&n(o.context);},e);}),En=async(e,t,n,o)=>Wr({bql:{raw:e,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:t,config:n,handles:o,depthLevel:0,error:null});immer.enableMapSet();var se=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 o=>{if(o.provider==="typeDB"&&o.dbName){let[l,a]=await radash.tryit(typedbDriver.TypeDB.coreDriver)(o.url);if(l){let d=`[BORM:${o.provider}:${o.dbName}:core] ${l.message??"Can't create TypeDB Client"}`;throw new Error(d)}try{let d=await a.session(o.dbName,typedbDriver.SessionType.DATA);t.typeDB.set(o.id,{client:a,session:d});}catch(d){let h=`[BORM:${o.provider}:${o.dbName}:session] ${(d.messageTemplate?._messageBody()||d.message)??"Can't create TypeDB Session"}`;throw new Error(h)}}if(o.provider==="typeDBCluster"&&o.dbName){let[l,a]=await radash.tryit(typedbDriver.TypeDB.cloudDriver)(o.addresses,o.credentials);if(l){let d=`[BORM:${o.provider}:${o.dbName}:core] ${l.message??"Can't create TypeDB Cluster Client"}`;throw new Error(d)}try{let d=await a.session(o.dbName,typedbDriver.SessionType.DATA);t.typeDB.set(o.id,{client:a,session:d});}catch(d){let h=`[BORM:${o.provider}:${o.dbName}:session] ${(d.messageTemplate?._messageBody()||d.message)??"Can't create TypeDB Session"}`;throw new Error(h)}}}));let n=$e(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(),ce(this.config,this.schema,this.dbHandles));query=async(t,n)=>{await this.#t();let o={...this.config,query:{..._t.query,...this.config.query,...n}};return It(t,o,this.schema,this.dbHandles)};mutate=async(t,n)=>{await this.#t();let o={...this.config,mutation:{..._t.mutation,...this.config.mutation,...n}},[l,a]=await radash.tryit(En)(t,this.schema,o,this.dbHandles);if(l){let h=new Error(l.error.message);throw h.stack=l.error.stack,h}return a.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:n})=>{n.isOpen()&&await n.close(),await t.close();});}},ia=se;//! Todo: delete when this works with the new $thing and $thingType fields
38
+ ${m}`})(),i=t.dbConnectors[0].id,p=r.typeDB.get(i)?.session,d=r.typeDB.get(i)?.client;if(!p){console.log("Session Status: ","NO SESSION");return}await p.close();let[{dbName:h}]=t.dbConnectors;await(await d.databases.get(h)).delete(),await d.databases.create(h);let s=await d.session(t.dbConnectors[0].dbName,typedbDriver.SessionType.SCHEMA),a=await s.transaction(typedbDriver.TransactionType.WRITE);await a.query.define(o),await a.commit(),await a.close();let u=await s.transaction(typedbDriver.TransactionType.READ);(await(await u.query.match("match $a sub thing;")).collect()).forEach(async m=>{m.get("a");}),await u.close();};var Dt={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var Ct=(t,e,r)=>r?e:`${t}\xB7${e}`;var Ot=(t,e)=>Object.values(Object.fromEntries(Object.entries(t).filter(([r,n])=>e(r,n))))[0],Se=(t,e)=>Object.fromEntries(Object.entries(t).filter(([r,n])=>e(r,n))),xt=(t,e)=>{let r=[],n=immer.produce(t,i=>objectTraversal.traverse(i,({key:p,value:d,meta:h})=>{if(h.depth===2&&(p&&(d.dataFields=d.dataFields?.map($=>({...$,cardinality:$.cardinality||"ONE",dbPath:Ct(p,$.path,$.shared)}))),d.extends)){if(!d.defaultDBConnector.as)throw new Error(`[Schema] ${p} is extending a thing but missing the "as" property in its defaultDBConnector`);let $=i.entities[d.extends]||i.relations[d.extends];if(d.allExtends=[d.extends,...$.allExtends||[]],d.idFields=$.idFields?(d.idFields||[]).concat($.idFields):d.idFields,d.dataFields=$.dataFields?(d.dataFields||[]).concat($.dataFields.map(s=>{let a=d.extends,u=t.entities[a]||t.relations[a];for(;!u.dataFields?.find(f=>f.path===s.path);)a="extends"in u?u.extends:void 0,u=t.entities[a]||t.relations[a];return {...s,dbPath:Ct(a,s.path,s.shared)}})):d.dataFields,d.linkFields=$.linkFields?(d.linkFields||[]).concat($.linkFields):d.linkFields,"roles"in $){let s=d,a=$;s.roles=s.roles||{},s.roles={...s.roles,...a.roles},Object.keys(s.roles).length===0&&(s.roles={});}$?.hooks?.pre&&(d.hooks=d.hooks||{},d.hooks.pre=d.hooks.pre||[],d.hooks.pre=[...$?.hooks?.pre||[],...d?.hooks?.pre||[]]);}},{traversalType:"breadth-first"}));return objectTraversal.traverse(t,({key:i,value:p,meta:d})=>{if(i==="linkFields"){let $=(()=>{if(!d.nodePath)throw new Error("No path");let[a,u]=d.nodePath.split(".");return {thing:u,thingType:a==="entities"?"entity":a==="relations"?"relation":""}})(),s=Array.isArray(p)?p.map(a=>({...a,...$})):[{...p,...$}];r.push(...s);}}),immer.produce(n,i=>objectTraversal.traverse(i,({value:p,key:d,meta:h})=>{if(h.depth===2&&p.idFields&&!p.id){p.name=d;let $=()=>{if(h.nodePath?.split(".")[0]==="entities")return "entity";if(h.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};p.thingType=$();let s=Object.keys(e).find(a=>e[a]?.get(p.defaultDBConnector.id));p.db=s,p.dbContext=Dt[s],p.computedFields=[],p.virtualFields=[],p.requiredFields=[],p.enumFields=[],p.fnValidatedFields=[],"roles"in p&&Object.entries(p.roles).forEach(([u,f])=>{f.fieldType="roleField",f.playedBy=r.filter(l=>l.relation===d&&l.plays===u)||[],f.name=u;}),"linkFields"in p&&p.linkFields&&p.linkFields?.forEach(u=>{if(u.fieldType="linkField",u.target==="relation"){u.oppositeLinkFieldsPlayedBy=[{plays:u.path,thing:u.relation,thingType:"relation"}];return}let f=r.filter(c=>c.relation===u.relation&&c.plays!==u.plays)||[];u.oppositeLinkFieldsPlayedBy=f;let{filter:l}=u;u.oppositeLinkFieldsPlayedBy=u.oppositeLinkFieldsPlayedBy.filter(c=>c.target==="role"),l&&Array.isArray(l)&&(u.oppositeLinkFieldsPlayedBy=u.oppositeLinkFieldsPlayedBy.filter(c=>l.some(m=>c.thing===m.$role)),u.oppositeLinkFieldsPlayedBy=u.oppositeLinkFieldsPlayedBy.filter(c=>l.some(m=>c.thing===m.$thing))),l&&!Array.isArray(l)&&(u.oppositeLinkFieldsPlayedBy=u.oppositeLinkFieldsPlayedBy.filter(c=>c.$role===l.$role),u.oppositeLinkFieldsPlayedBy=u.oppositeLinkFieldsPlayedBy.filter(c=>c.thing===l.$thing));});}if(typeof p=="object"&&"playedBy"in p){let $=[...new Set(p.playedBy.map(s=>s.thing))];if($.length>1)throw new Error(`[Schema] roleFields can be only played by one thing. Role: ${d}, path:${h.nodePath}, played by: ${$.join(", ")}`);if(p.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${d}, path:${h.nodePath}`)}if(h.depth===4){let[$,s]=h.nodePath?.split(".")||[],a=i[$][s];p.validations&&(p.validations.required&&a.requiredFields.push(p.path),p.validations.enum&&a.enumFields.push(p.path),p.validations.fn&&a.fnValidatedFields.push(p.path)),p.default?p.isVirtual?a.virtualFields.push(p.path):a.computedFields.push(p.path):p.isVirtual&&a.virtualFields.push(p.path);}}))},G=(t,e)=>{if(e in t.entities)return t.entities[e];if(e in t.relations)return t.relations[e];throw new Error(`${e} is not defined in the schema`)},C=(t,e)=>{if(!e)throw new Error("[Internal] No node for getCurrentSchema");if(e.$thing){if(e.$thingType==="entity"){if(!(e.$thing in t.entities))throw new Error(`Missing entity '${e.$thing}' in the schema`);return t.entities[e.$thing]}if(e.$thingType==="relation"){if(!(e.$thing in t.relations))throw new Error(`Missing relation '${e.$thing}' in the schema`);return t.relations[e.$thing]}if(e.$thing in t.entities&&e.$thing in t.relations)throw new Error(`Ambiguous $thing ${e.$thing}`);if(e.$thing in t.entities)return t.entities[e.$thing];if(e.$thing in t.relations)return t.relations[e.$thing];throw new Error(`Wrong schema or query for ${JSON.stringify(e,null,2)}`)}if(e.$entity){if(!(e.$entity in t.entities))throw new Error(`Missing entity '${e.$entity}' in the schema`);return t.entities[e.$entity]}if(e.$relation){if(!(e.$relation in t.relations))throw new Error(`Missing relation '${e.$relation}' in the schema`);return t.relations[e.$relation]}throw new Error(`Wrong schema or query for ${JSON.stringify(e,null,2)}`)},jt=(t,e)=>{let r=t.$thing||t.$entity||t.$relation;if(!r)throw new Error("[Internal] No thing found");if(t.$entity)return "entity";if(t.$relation)return "relation";if(e.entities[r])return "entity";if(e.relations[r])return "relation";throw new Error("No thing found")},et=(t,e,r)=>{let n=C(t,e),o=n.linkFields?.find(d=>d.path===r);if(o)return o;let i=n.dataFields?.find(d=>d.path===r);if(i)return i;let p="roles"in n?n.roles?.[r]:void 0;if(p)return p},tt=(t,e,r)=>et(t,e,r)?.cardinality,pe=(t,e)=>{let r=t.dataFields?.map(l=>l.path)||[],n=t.linkFields?.map(l=>l.path)||[],o="roles"in t?radash.listify(t.roles,l=>l):[],i=[...r||[],...n||[],...o||[]],d=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...i];if(!e)return {fields:i,dataFields:r,roleFields:o,linkFields:n};let h=e.$fields?e.$fields.map(l=>{if(typeof l=="string"){if(l.startsWith("$")||l.startsWith("%"))return;if(!i.includes(l))throw new Error(`Field ${l} not found in the schema`);return l}if("$path"in l&&typeof l.$path=="string")return l.$path;throw new Error("[Wrong format] Wrongly structured query")}):radash.listify(e,l=>{if(!(l.startsWith("$")||l.startsWith("%"))){if(!i.includes(l))throw new Error(`[Schema] Field ${l} not found in the schema`);return l}}).filter(l=>l!==void 0),$=e.$filter?radash.listify(e.$filter,l=>l.toString().startsWith("$")?void 0:l.toString()).filter(l=>l&&r?.includes(l)):[],s=e.$filter?radash.listify(e.$filter,l=>l.toString().startsWith("$")?void 0:l.toString()).filter(l=>l&&[...o||[],...n||[]].includes(l)):[],a=[...h,...$].filter(l=>!l?.startsWith("%")).filter(l=>!d.includes(l)).filter(l=>l),u=e.$filter?Se(e.$filter,(l,c)=>$.includes(l)):{},f=e.$filter?Se(e.$filter,(l,c)=>s.includes(l)):{};return {fields:i,dataFields:r,roleFields:o,linkFields:n,usedFields:h,usedLinkFields:n.filter(l=>h.includes(l)),usedRoleFields:o.filter(l=>h.includes(l)),usedDataFields:r.filter(l=>h.includes(l)),unidentifiedFields:a,...$.length?{localFilters:u}:{},...s.length?{nestedFilters:f}:{}}};var Nt=t=>{if(typeof t!="string")throw new Error("capitalizeFirstLetter: string is not a string");return t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()},_t=(t,e,r)=>{let o=(r.nodePath||"").split("."),i=radash.isArray(e)?o.slice(0,-2).join("."):o.slice(0,-1).join(".");return e?objectTraversal.getNodeByPath(t,i):{}},ye=t=>Reflect.ownKeys(t).filter(e=>typeof e=="symbol").reduce((e,r)=>(e[r]=t[r],e),{});var De=t=>radash.isObject(t)&&("$entity"in t||"$relation"in t||"$thing"in t),me=t=>{if(Array.isArray(t))return t.map(e=>immer.current(e));if(t&&typeof t=="object"){let e=immer.isDraft(t)?immer.current(t):t,r={};return Object.entries(e).forEach(([n,o])=>{r[n]=immer.isDraft(o)?immer.current(o):o;}),r}else return t},le=(t,e)=>{if(t===void 0)throw e?new Error(e):new Error("Value is undefined");return t},q=(t,e)=>{let r="";for(let n=0;n<e;n++)r+=" ";return `${r}${t}`};var Le=(t,e)=>{if(e.fieldType==="linkField"){let r=e.oppositeLinkFieldsPlayedBy;if(r?.length!==1)throw new Error(`[Internal] Field ${t} should have a single player`);if(!r?.length)throw new Error(`[Internal] Field ${t} should have a player`);return r}else if(e.fieldType==="roleField"){if([...new Set(e.playedBy?.map(r=>r.thing))].length!==1)throw new Error(`[Internal] Field ${t} should have a single player`);if(!e.playedBy?.length)throw new Error(`[Internal] Field ${t} should have a player`);return e.playedBy}else throw new Error(`[Internal] Field ${t} is not a linkField or roleField`)};var zt=(t,e,r)=>{let n=radash.isArray(t[e])?t[e]:[t[e]];if(!n.every(o=>typeof o=="object"))if(n.every(o=>typeof o=="string")){let o=Le(e,r),[i]=o,p=t.$op==="create"?"link":"replace",d=i.thing,h=i.thingType;if(n.some($=>$.startsWith("_:")))throw new Error("[Not supported] At least one child of a replace is a tempId");t[e]={$id:t[e],$op:p,$thing:d,$thingType:h,$bzId:`S_${uuid.v4()}`};}else throw new Error(`[Mutation Error] Replace can only be used with a single id or an array of ids. (Field: ${e} Nodes: ${JSON.stringify(n)} Parent: ${JSON.stringify(t,null,2)})`)};var we=(t,e,r)=>{let n=C(r,e),{usedDataFields:o}=pe(n,e);if(e.$op){if(e.$op==="create"&&e.$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(e.$op)&&t.$op==="create")throw new Error(`[Wrong format] Cannot ${e.$op} under a create`);if(e.$op==="delete"&&o.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(e.$op)&&o.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return e.$op}};var Pe=(t,e,r)=>{let n=C(r,e),{usedFields:o}=pe(n,e);return e.$op?(we(t,e,r),e.$op):e.$id||e.$filter?o.length>0?(we(t,{...e,$op:"update"},r),"update"):(we(t,{...e,$op:"link"},r),"link"):e.$tempId?o.length>0?(we(t,{...e,$op:"create"},r),"create"):(we(t,{...e,$op:"create"},r),"link"):(we(t,{...e,$op:"create"},r),"create")};var Wt=(t,e)=>{let n=(radash.isArray(t.$root)?t.$root:[t.$root]).map(o=>{let i=Pe(o,o,e);return {...{...o.$thing?{}:{$thing:o.$entity||o.$relation},...o.$thingType?{}:{$thingType:jt(o,e)},...o.$op?{}:{$op:i},...o.$bzId?{}:{$bzId:`R_${uuid.v4()}`}},...o}});t.$root=radash.isArray(t.$root)?n:n[0];};var v=Symbol.for("queryPath"),Ie=Symbol.for("stepPrint"),Te=Symbol.for("edgeType"),ge=Symbol.for("edgeSchema");var Ce=(t,e)=>{let r=e[Ie];return types.isSet(r)?r.has("clean")?(Reflect.set(e,Ie,r.add("clean")),!0):!1:(Reflect.set(e,Ie,new Set(["clean"])),!0)};var Ht=(t,e,r)=>{if(Ce("split_ids",t)){let n=(radash.isArray(t[e])?t[e]:[t[e]]).flatMap(o=>{if(radash.isObject(o)&&"$id"in o&&radash.isArray(o.$id)){let i=o;if(C(r,i),!i.$bzId)throw new Error("[Internal Error] No bzId found");return i.$id.map((p,d)=>({...me(i),$id:p,$bzId:`${i.$bzId}_${d}`,...ye(i)}))}return o});(n.length>radash.isArray(t[e])?t[e]:[t[e]].length)&&(t[e]=n);}};var Ut=(t,e,r,n)=>{let o=(radash.isArray(t[e])?t[e]:[t[e]]).map(i=>{let p=Le(e,r),[d]=p,h=Pe(t,{...i,$thing:d.thing,$thingType:d.thingType},n),$=i.$bzId?i.$bzId:i.$tempId?i.$tempId:`N_${uuid.v4()}`;if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);return {...i,[ge]:r,$thing:d.thing,$thingType:d.thingType,$op:h,$bzId:$}});t[e]=radash.isArray(t[e])?o:o[0];};var Pn=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,In=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,Kt=t=>{let r=t.toString().replace(Pn,"").trim().split("=>")[0].split("{")[0].replace(In,"").trim(),n=r.substring(r.indexOf("(")+1,r.lastIndexOf(")")).trim();return n?(n.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(i=>i.includes("{")&&i.includes("}")?(i.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(d=>d.split(":")[0].trim().replace(/['"[\]]/g,"")):i.trim()).filter(Boolean):[]};var Be=({currentThing:t,fieldSchema:e,mandatoryDependencies:r=!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(r){let{fn:o}=e.default,p=Kt(o).filter(d=>!(d in t));if(p.length)throw new Error(`Virtual field: Missing arguments ${p.join(", ")}`)}if(!e.default.fn)throw new Error("[Schema] No fn in default field schema");return "default"in e?e.default?.fn(t):void 0};var Jt=(t,e,r)=>{let n=t[e];n&&(radash.isArray(n)?n:[n]).forEach(o=>{let i=C(r,o),{unidentifiedFields:p}=pe(i,o),{computedFields:d,virtualFields:h}=i,$=radash.listify(o,(u,f)=>f!==void 0?u:void 0),s=$.filter(u=>h?.includes(u));if(s.length>0)throw new Error(`Virtual fields can't be sent to DB: "${s.join(",")}"`);if(d.filter(u=>!$.includes(u)).forEach(u=>{let f=i.dataFields?.find(B=>B.path===u),c=i.linkFields?.find(B=>B.path===u)?.oppositeLinkFieldsPlayedBy[0],m="roles"in i?Ot(i.roles,(B,T)=>B===u):void 0,y=f||c||m;if(!y)throw new Error(`no field Def for ${u}`);if(o.$op==="create"&&!o[u]){let B=Be({currentThing:o,fieldSchema:y,mandatoryDependencies:!0});o[u]=B;}}),p.length>0)throw new Error(`Unknown fields: [${p.join(",")}] in ${JSON.stringify(o)}`)});};var Oe=(t,e)=>{let r=C(e,t).hooks;if(r?.pre){let n=`on${Nt(t.$op)}`;return r.pre.filter(p=>!p.triggers||p.triggers[n]?.()).flatMap(p=>p.actions)}return []};var Gt=(t,e,r,n)=>{(radash.isArray(t[e])?t[e]:[t[e]]).forEach(i=>{if("$thing"in i){let{requiredFields:p,enumFields:d,fnValidatedFields:h,dataFields:$}=C(r,i);if("$op"in i&&i.$op==="create"&&p.forEach(s=>{if(!(s in i))throw new Error(`[Validations] Required field "${s}" is missing.`)}),("$op"in i&&i.$op==="update"||i.$op==="create")&&d.forEach(s=>{if(s in i){let a=$?.find(u=>u.path===s)?.validations?.enum;if(!a)throw new Error(`[Validations] Enum field "${s}" is missing enum options.`);if(radash.isArray(i[s]))i[s].some(u=>{if(!a.includes(u))throw new Error(`[Validations] Option "${u}" is not a valid option for field "${s}".`)});else if(a&&!a.includes(i[s]))throw new Error(`[Validations] Option "${i[s]}" is not a valid option for field "${s}".`)}}),("$op"in i&&i.$op==="update"||i.$op==="create")&&h.forEach(s=>{if(s in i)try{let a=$?.find(u=>u.path===s)?.validations?.fn;if(!a)throw new Error("Missing validation function.");if(!a(i[s]))throw new Error("Failed validation function.")}catch(a){throw new Error(`[Validations:attribute:${s}] ${a.message}`)}}),radash.isObject(i)&&"$thing"in i){let s=i.$thing,a=i,u=radash.clone(me(t)),f=radash.clone(me(a)),l=n.mutation?.context||{};Oe(a,r).forEach(m=>{if(m.type==="validate"){if(m.severity!=="error")return;try{let y=m.fn(f,u,l);if(y===!1)throw new Error(`${m.message}.`);if(y!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(y){throw new Error(`[Validations:thing:${s}] ${y.message}`)}}});}}});};var tr=(t,e,r,n)=>{let o=(radash.isArray(t[e])?t[e]:[t[e]]).map(i=>{if(De(i)){let p=Oe(i,r).filter(s=>s.type==="transform"),d=radash.clone(me(t)),h=radash.clone(me(i)),$=n.mutation?.context||{};return p.forEach(s=>{let a=s.fn(h,d,$);Object.keys(a).length!==0&&(i={...h,...a,...ye(i)});}),i}});t[e]=radash.isArray(t[e])?o:o[0];};var rr=(t,e,r)=>{let n=Le(e,r),[o]=n;t[e]={$thing:o.thing,$thingType:o.thingType,$op:"unlink",$bzId:`U_${uuid.v4()}`,[ge]:r};};var Hn=(t,e)=>{if(t[e]===void 0&&delete t[e],e==="$tempId")if(Ce("set_tempId",t))if(t.$tempId?.startsWith("_:")){let r=t.$tempId.substring(2);t.$tempId=r,t.$bzId=r;}else throw new Error('[Wrong format] TempIds must start with "_:"');else throw new Error("[Internal] TempId already modified")},vn=(t,e)=>{},it=(t,e,r)=>{let o=immer.produce({$rootWrap:{$root:t}},i=>objectTraversal.traverse(i,({value:p,parent:d,key:h,meta:$})=>{if(!(!d||!h)&&radash.isObject(p)){if(!("$root"in p)){if(!("$thing"in p||"$entity"in p||"$relation"in p))throw h==="$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(p)?immer.current(p):p)}`)}let s=p;Object.keys(s).forEach(a=>{if(Hn(s,a),a!=="$root"&&(a.startsWith("$")||a.startsWith("%")))return;let u=a!=="$root"?et(e,s,a):{fieldType:"rootField"};if(!u)throw new Error(`[Internal] Field ${a} not found in schema`);if("contentType"in u)return vn();if(["rootField","linkField","roleField"].includes(u.fieldType)){if(["linkField","roleField"].includes(u.fieldType)&&(s[a]===null?rr(s,a,u):zt(s,a,u)),u.fieldType==="rootField"){if(!("$root"in s))throw new Error(`[Internal] Field ${a} is a rootField but the object is not a root`);Wt(s,e);}let f=radash.isArray(s[a])?s[a]:[s[a]],l=$.nodePath?.split(".").slice(1).join(".");f.forEach(m=>{if(m){if(u?.cardinality==="ONE"&&!m.$op&&!m.$id&&!m.$filter&&!m.$tempId&&s.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${l}.${a}`);if(m.$tempId&&!(m.$op===void 0||m.$op==="link"||m.$op==="create"||m.$op==="update"))throw new Error(`Invalid op ${m.$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(u.fieldType)&&Ut(s,a,u,e),Ht(s,a,e),["rootField","linkField","roleField"].includes(u.fieldType)&&Jt(s,a,e),(radash.isArray(s[a])?s[a]:[s[a]]).forEach(m=>{let y=C(e,m),{unidentifiedFields:B,usedLinkFields:T,usedFields:g,fields:Q}=pe(y,m);if(g.forEach(M=>{if(!Q.includes(M))throw new Error(`[Schema] Field ${M} not found in the schema`)}),B.length>0)throw new Error(`Unknown fields: [${B.join(",")}] in ${JSON.stringify(p)}`);if(T.length>1){let M=y.linkFields?.filter(L=>T.includes(L.path));M?.some((L,A)=>M.some((R,D)=>{if(A!==D&&L.target!==R.target&&L.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.")}));}}),tr(s,a,e,r),Gt(s,a,e,r);}});}}));return radash.isArray(o.$rootWrap.$root),o.$rootWrap.$root};var Qe=async(t,e)=>{let r=e.dbConnectors[0].id,n=t.typeDB?.get(r)?.session,o=t.typeDB?.get(r)?.client;if(!n||!n.isOpen()){if(!o)throw new Error("Client not found");n=await o.session(e.dbConnectors[0].dbName,typedbDriver.SessionType.DATA),t.typeDB?.set(r,{client:o,session:n});}return {client:o,session:n}};var nr=async(t,e,r)=>{if(!t)throw new Error("TQL request not built");if(!(t.deletions&&t.deletionMatches||t.insertions))throw new Error("TQL request error, no things");let{session:n}=await Qe(e,r),o=await n.transaction(typedbDriver.TransactionType.WRITE);if(!o)throw new Error("Can't create transaction");let i=t.deletionMatches&&t.deletions&&`match ${t.deletionMatches} delete ${t.deletions}`,p=t.insertions&&`${t.insertionMatches?`match ${t.insertionMatches}`:""} insert ${t.insertions}`;i&&await o.query.delete(i);let d=p&&o.query.insert(p);try{let h=d?await d.collect():void 0;return await o.commit(),await o.close(),{insertions:h}}catch(h){throw await o.close(),new Error(`Transaction failed: ${h.message}`)}};var ir=async(t,e,r,n,o)=>{let i=[...e,...r],p=i.map(d=>{let h=t.insertions?.find(a=>a.get(`${d.$bzId}`))?.get(`${d.$bzId}`),$=d.$thing||d.$relation||d.$entity,s=$?G(n,$):void 0;if(d.$op==="create"||d.$op==="update"||d.$op==="link"){if(d.$op!=="update"&&!h&&d.$id)return {$id:d.$id,$error:"Does not exist or it's not linked to the parent"};let a=h?.asThing().iid,u=Object.entries(d).filter(([l,c])=>!l.startsWith("$")).reduce((l,[c,m])=>{if(s?.dataFields?.find(B=>B.path===c)?.contentType==="JSON")return l[c]=JSON.parse(m),l;if(d.$thingType==="relation"){let B=i.filter(T=>T.$id&&T.$bzId===m);if(B.length>1)throw new Error(`Multiple things with the same bzId ${m}`);return B.length===1?(l[c]=B[0].$id,l):(l[c]=m,l)}return l[c]=m,l},{});if(o.mutation?.noMetadata)return u;let f=d.$tempId&&!d.$tempId.startsWith("_:")?{$tempId:`_:${d.$tempId}`}:{};return {$dbId:a,...d,...u,[d.path]:d.$id,...f}}if(d.$op==="delete"||d.$op==="unlink")return d;if(d.$op!=="match")throw new Error(`Unsupported op ${d.$op}`)}).filter(d=>d);return radash.clone(p)};var sr=t=>{let e=({value:r})=>(r&&typeof r=="object"&&"$id"in r&&(Object.keys(r).filter(i=>i.startsWith("$")).forEach(i=>delete r[i]),Object.keys(r).filter(i=>typeof i=="symbol").forEach(i=>delete r[i])),r);return immer.produce(t,r=>objectTraversal.traverse(r,e))};var cr=async(t,e)=>{let r=s=>{let a=[],u=[],f=y=>{if(y.$id)return y.$id;let B=C(e,y),{idFields:T}=B;if(!T)throw new Error(`no idFields: ${JSON.stringify(y)}`);let[g]=T;if(!g)throw new Error(`no idField: ${JSON.stringify(y)}`);let Q=B.dataFields?.find(A=>A.path===g),M=Be({currentThing:y,fieldSchema:Q,mandatoryDependencies:!0}),L=y[g]||y.$id||M;if(!L)throw new Error(`no idValue: ${JSON.stringify(y)}`);return L},l=y=>{if(y.$op==="create"){let B=f(y);if(a.find(T=>T.$id===B&&T.$op==="create"))throw new Error(`Duplicate id ${B} for node ${JSON.stringify(y)}`);if(u.find(T=>T.$bzId===y.$bzId))throw new Error(`Duplicate $bzId ${y.$bzId} for node ${JSON.stringify(y)}`);a.push({...y,$id:B});return}y.$tempId&&y.$op==="match"||a.push(y);},c=y=>{if(y.$op==="create"){let B=f(y);if(a.find(T=>T.$id===B),u.find(T=>T.$bzId===y.$bzId))throw new Error(`Duplicate %bzId ${y.$bzIdd} for edge ${JSON.stringify(y)}`);u.push({...y,$id:B});return}u.push(y);};return objectTraversal.traverse(s,({value:y,parent:B,meta:T})=>{if(!radash.isObject(y))return;let g=y;if(g.$thing){if(!g.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(g)}`);if(!g.$bzId)throw new Error("[internal error] BzId not found");let Q=C(e,g),{dataFields:M,roleFields:L,linkFields:A,usedFields:R}=pe(Q,g),D=()=>{if(g.$op==="create"||g.$op==="delete")return g.$op;if(g.$op==="update"){let w=R.filter(E=>M?.includes(E)),F=R.filter(E=>L?.includes(E)),k=R.filter(E=>A?.includes(E));if(w.length>0)return "update";if(F.length>0||k.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(g)}`)}return "match"},N={...g.$id&&{$id:g.$id},...g.$tempId&&{$tempId:g.$tempId},...g.$filter&&{$filter:g.$filter},$thing:g.$thing,...g.$thingType&&{$thingType:g.$thingType},...radash.shake(radash.pick(g,M||[""])),$op:D(),$bzId:g.$bzId};l(N);let x=g[ge];if(x?.fieldType==="linkField"){if((g.$op==="link"||g.$op==="unlink")&&(g.$id||g.$filter)){if(g.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");a.push({...g,$op:"match"});}let w=x.relation===g.$thing,F=w?g.$bzId:`LT_${uuid.v4()}`,E=_t(s,B,T).$bzId;if(!E)throw new Error("No parent id found");let b=()=>{if(g.$op==="delete")return w?"match":"delete";if(g.$op==="unlink")return w?"unlink":"delete";if(g.$op==="link"||g.$op==="create")return w?"link":"create";if(g.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},S=C(e,{$thing:x.relation,$thingType:"relation"});if(!Object.keys(S.roles).includes(x.plays))throw new Error(`[Wrong format] Field ${x.plays} is not a role of relation ${x.relation}`);let I={$bzId:F,$thing:x.relation,$thingType:"relation",...g.$tempId?{$tempId:g.$tempId}:{},$op:b(),...w?{}:{[x.path]:g.$bzId},[x.plays]:E,[ge]:x,[Te]:"linkField"};c(I),(g.$op==="unlink"||b()==="unlink")&&w&&c({$thing:x.relation,$thingType:"relation",$bzId:F,$op:"match",[x.plays]:E,[ge]:x,[Te]:"linkField"});}if(g.$thingType==="relation"){let w=Se(g,(E,b)=>L.includes(E)),F=radash.mapEntries(w,(E,b)=>radash.isArray(b)?[E,b]:radash.isObject(b)?[E,b.$bzId]:[E,b]),k=Se(y,(E,b)=>E.startsWith("$")||E.startsWith("Symbol"));if(Object.keys(w).filter(E=>!E.startsWith("$")).length>0){if(g.$op==="create"||g.$op==="delete"){let E=()=>{if(g.$op==="create")return "link";if(g.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},b=C(e,g).roles,S=radash.mapEntries(F,(I,O)=>{let H=b[I]?.cardinality;if(!H)throw new Error(`Role ${I} not found in schema`);if(Array.isArray(O)){if(H==="ONE"){if(O.length>1)throw new Error(`[Error] Role ${I} is not a MANY relation`);return [I,O[0].$bzId||O[0]]}return [I,O.map(oe=>oe.$bzId||oe)]}return [I,O.$bzId||O]}),_={...k,$thing:g.$thing,$thingType:"relation",$op:E(),...S,$bzId:g.$bzId,[Te]:"roleField"};c(_);return}if(g.$op==="match"||g.$op==="update"&&Object.keys(w).length>0){let E=0;Object.entries(w).forEach(([b,S])=>{let _=radash.isArray(S)?S:[S],I=O=>O==="create"||O==="replace"?"link":O;_.forEach(O=>{if(!O)return;let H=I(O.$op);if(H==="replace")throw new Error("Not supported yet: replace on roleFields");if(H==="unlink"&&E>0)throw E+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let oe={...k,$thing:g.$thing,$thingType:"relation",$op:H==="delete"?"unlink":H,[b]:O.$bzId,$bzId:g.$bzId,[Te]:"roleField"};c(oe);});});}}}}}),[a,u]},[n,o]=r(t),i=n.reduce((s,a)=>{if(!a.$bzId)return [...s,a];let u=s.findIndex(f=>f.$bzId===a.$bzId);if(u===-1)return [...s,a];if(s[u].$op==="create"&&a.$op==="match")return s;if(s[u].$op==="match"&&(a.$op==="create"||a.$op==="match"))return [...s.slice(0,u),a,...s.slice(u+1)];throw new Error(`[Wrong format] Wrong operation combination for $tempId "${a.$tempId}". Existing: ${s[u].$op}. Current: ${a.$op}`)},[]),p=o.reduce((s,a)=>{let u=s.find(f=>(f.$id&&f.$id===a.$id||f.$bzId&&f.$bzId===a.$bzId)&&f.$thing===a.$thing&&f.$op===a.$op);if(u){let f={...u};return Object.keys(a).forEach(c=>{if(typeof c=="symbol"||c.startsWith("$"))return;let m=u[c],y=a[c];Array.isArray(m)&&Array.isArray(y)?f[c]=Array.from(new Set([...m,...y])):!Array.isArray(m)&&Array.isArray(y)?m!==void 0?f[c]=Array.from(new Set([m,...y])):f[c]=y:Array.isArray(m)&&!Array.isArray(y)?y!==void 0&&(f[c]=Array.from(new Set([...m,y]))):m!==null&&y!==null&&m!==void 0&&y!==void 0?f[c]=Array.from(new Set([m,y])):m==null&&(f[c]=y);}),[...s.filter(c=>!((c.$id&&c.$id===a.$id||c.$bzId&&c.$bzId===a.$bzId)&&c.$thing===a.$thing&&c.$op===a.$op)),f]}return [...s,a]},[]);i.forEach(s=>{if((s.$thingType==="relation"||"relation"in s)&&p.filter(a=>a.$bzId===s.$bzId||a.$tempId&&a.$tempId===s.$tempId).length===0){if(s.$op==="delete"||s.$op==="match"||s.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(sr(s))}`)}});let d=[...i,...p],h=new Set(d.filter(s=>s.$tempId).map(s=>s.$tempId)),$=Array.from(h).filter(s=>!d.some(a=>a.$tempId===s&&a.$op==="create"));if($.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${$.join(", ")}`);return {mergedThings:i,mergedEdges:p}};var dr=async(t,e,r)=>{let n=u=>{let f=u.$op,l=`$${u.$bzId}`,c=C(r,u),{idFields:m,defaultDBConnector:y}=c,B=y?.path||u.$thing,T=u.$id,g=m?.[0],Q=radash.listify(u,(w,F)=>{if(w.startsWith("$")||w.startsWith("%")||w===g||F===void 0||F===null)return "";let k=c.dataFields?.find(S=>S.path===w);if(!k?.path)return "";let b=k.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(k.contentType))return `has ${b} '${F}'`;if(["NUMBER","BOOLEAN"].includes(k.contentType))return `has ${b} ${F}`;if(k.contentType==="DATE"){if(Number.isNaN(F.valueOf()))throw new Error("Invalid format, Nan Date");return F instanceof Date?`has ${b} ${F.toISOString().replace("Z","")}`:`has ${b} ${new Date(F).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${k.contentType}`)}).filter(w=>w),M=`${l}-atts`,L=radash.listify(u,w=>{if(w.startsWith("$")||w.startsWith("%")||w===g)return "";let F=c.dataFields?.find(b=>b.path===w);if(!F?.path)return "";let E=F.dbPath;return `{${M} isa ${E};}`}).filter(w=>w),A=radash.isArray(T)?`like '${T.join("|")}'`:`'${T}'`,R=T?[`has ${g} ${A}`]:[],D=[...R,...Q].filter(w=>w).join(","),N=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${l} isa ${[B,...R].filter(w=>w).join(",")};`;if(f==="update"){if(!L.length)throw new Error("update without attributes");return `${l} isa ${[B,...R].filter(w=>w).join(",")}, has ${M};
39
+ ${L.join(" or ")};`}return ""},x=()=>f==="update"||f==="link"||f==="match"?`${l} isa ${[B,...R].filter(w=>w).join(",")};`:"";if(De(u))return {op:f,deletionMatch:N(),insertionMatch:x(),insertion:f==="create"?`${l} isa ${[B,D].filter(w=>w).join(",")};`:f==="update"&&Q.length?`${l} ${Q.join(",")};`:"",deletion:f==="delete"?`${l} isa ${B};`:f==="update"&&L.length?`${l} has ${M};`:""};throw new Error("in attributes")},o=u=>{let f=u.$op,l=C(r,u),c=`$${u.$bzId}`,m=u.$id,y=l.defaultDBConnector?.path||u.$thing,B="roles"in l?radash.listify(l.roles,F=>F):[],T="roles"in l?radash.mapEntries(l.roles,(F,k)=>[F,k.dbConnector?.path||F]):{},g=radash.listify(u,(F,k)=>{if(!B.includes(F))return null;if(!("roles"in l))throw new Error("This should have roles! ");let E=T[F];return Array.isArray(k)?k.map(b=>({path:E,id:b})):{path:E,id:k}}).filter(F=>F).flat(),Q=g.map(F=>{if(!F?.path)throw new Error("Object without path");return `${F.path}: $${F.id}`}),M=g.length>0?`( ${Q.join(" , ")} )`:"",L=u[Te];if(!L)throw new Error("[internal error] Symbol edgeType not defined");let A=M?`${c} ${M} ${L==="linkField"||f==="delete"||f==="unlink"?`isa ${y}`:""}`:"",R=`${c} ${L==="linkField"||f==="delete"?`isa ${y}`:""}`,D=()=>A?f==="link"?`${A};`:f==="create"?`${A}, has id '${m}';`:"":"",N=()=>A&&f==="match"?`${A};`:"",x=()=>A?f==="delete"?`${A};`:f==="match"?`${A};`:"":"",w=()=>A?f==="delete"?`${R};`:f==="unlink"?`${c} ${M};`:"":"";return {deletionMatch:x(),insertionMatch:N(),deletion:w(),insertion:D(),op:""}},i=(u,f)=>{let l=f==="edges"?o:n;if(Array.isArray(u))return u.map(g=>{let{preDeletionBatch:Q,insertionMatch:M,deletionMatch:L,insertion:A,deletion:R}=l(g);return radash.shake({preDeletionBatch:Q,insertionMatch:M,deletionMatch:L,insertion:A,deletion:R},D=>!D)}).filter(g=>g);let{preDeletionBatch:c,insertionMatch:m,deletionMatch:y,insertion:B,deletion:T}=l(u);return radash.shake({preDeletionBatch:c,insertionMatch:m,deletionMatch:y,insertion:B,deletion:T},g=>!g)},p=i(t),d=Array.isArray(p)?p:[p],h=i(e,"edges"),$=Array.isArray(h)?h:[h],s=[...d,...$];return radash.shake({insertionMatches:s.map(u=>u.insertionMatch).join(" ").trim(),deletionMatches:s.map(u=>u.deletionMatch).join(" ").trim(),insertions:s.map(u=>u.insertion).join(" ").trim(),deletions:s.map(u=>u.deletion).join(" ").trim()},u=>!u)};var ot="___",pr=async t=>{let{enrichedBqlQuery:e,schema:r}=t;if(!e)throw new Error("BQL query not enriched");let n="",o=(s,a,u)=>{let f=[],l=[],c="";for(let B=0;B<s.length;B++)s[B].$isVirtual||f.push(s[B].$dbPath),l.push(`{${s[B].$dbPath}:${s[B].$as}}`);let m=f.join(", ");c=l.join(",");let y=`$metadata:{as:[${c}]}`;n+=P(`$${a} as "${a}.${y}.$dataFields": ${m};`,u);},i=(s,a,u,f)=>{let l=f+1;for(let c of s){let{$fields:m,$as:y,$justId:B,$idNotIncluded:T,$filterByUnique:g,$thing:Q,$sort:M,$offset:L,$limit:A}=c,R=c[v],D=`$metadata:{as:${y},justId:${B?"T":"F"},idNotIncluded:${T},filterByUnique:${g}}`;n+=P(`"${u}.${D}.${c.$var}": {`,f),n+=P("match",l);let N=`${a}${ot}${c.$var}`;n+=P(`$${N} isa ${c.$thing};`,l),n+=P(`$${a} (${c.$var}: $${a}${ot}${c.$var}) isa ${c.$intermediary};`,l),c.$filter&&(n+=je({$filter:c.$filter,$var:N,$thing:c.$thing,schema:r,depth:l}));let x=_e({schema:r,$thing:Q,$var:N,$sort:M,depth:l});if(x&&(n+=x.match),m){let w=`M_${uuid.v4()}`;n+=P(`
40
+ ?queryPath${w} = "${R}";`,l),n+=P("fetch",l),n+=P(`?queryPath${w} as "queryPath";`,l);let F=m?.filter(b=>b.$fieldType==="data");F&&F.length>0&&o(F,N,`${a}.${c.$var}`);let k=m?.filter(b=>b.$fieldType==="link");k&&k.length>0&&p(k,N,`${a}.${c.$var}`,l);let E=m?.filter(b=>b.$fieldType==="role");E&&E.length>0&&i(E,N,`${a}.${c.$var}`,l);}x&&(n+=x.sort),typeof L=="number"&&(n+=P(`offset ${L};`,l)),typeof A=="number"&&(n+=P(`limit ${A};`,l)),n+=P("};",f);}},p=(s,a,u,f)=>{let l=f+1;for(let c of s){let{$fields:m,$as:y,$justId:B,$idNotIncluded:T,$filterByUnique:g,$playedBy:Q,$thing:M,$sort:L,$offset:A,$limit:R}=c,D=c[v],N=`$metadata:{as:${y},justId:${B?"T":"F"},idNotIncluded:${T},filterByUnique:${g}}`;n+=P(`"${u}.${N}.${c.$var}": {`,f),n+=P("match",l);let x=`${a}${ot}${c.$var}`;n+=P(`$${x} isa ${c.$thing};`,l),c.$filter&&(n+=je({$filter:c.$filter,$var:x,$thing:c.$thing,schema:r,depth:l}));let w=_e({schema:r,$thing:M,$var:x,$sort:L,depth:l});if(w&&(n+=w.match),c.$target==="role"?n+=P(`$${a}_intermediary (${c.$plays}: $${a}, ${Q.plays}: $${x}) isa ${c.$intermediary};`,l):n+=`
41
+ $${x} (${c.$plays}: $${a}) isa ${c.$thing};`,m){let F=`M_${uuid.v4()}`;n+=P(`?queryPath${F} = "${D}";`,l),n+=P("fetch",l),n+=P(`?queryPath${F} as "queryPath";`,l);let k=m?.filter(S=>S.$fieldType==="data");k&&k.length>0&&o(k,x,l);let E=m?.filter(S=>S.$fieldType==="link");E&&E.length>0&&p(E,x,`${a}.${c.$var}`,l);let b=m?.filter(S=>S.$fieldType==="role");b&&b.length>0&&i(b,x,`${a}.${c.$var}`,l);}w&&(n+=w.sort),typeof A=="number"&&(n+=P(`offset ${A};`,l)),typeof R=="number"&&(n+=P(`limit ${R};`,l)),n+=P("};",f);}},d=e.length>1,h=[];(s=>{if(d)for(let a of s){let{$path:u,$thing:f,$filter:l,$fields:c,$sort:m,$offset:y,$limit:B}=a;if(!u)throw new Error("Path is not defined");let T=a[v];if(n+=`
42
+ match
43
+ $${u} isa ${f};`,l){let M=je({$filter:l,$var:u,$thing:f,schema:r,depth:0});n+=`
44
+ ${M}`;}let g=_e({schema:r,$thing:f,$var:u,$sort:m,depth:0});g&&(n+=g.match);let Q=`M_${uuid.v4()}`;if(n+=`
45
+ ?queryPath${Q} = "${T}";`,n+=`
46
+ fetch`,n+=`
47
+ ?queryPath${Q} as "queryPath";`,c){let M=c.filter(R=>R.$fieldType==="data");M&&M.length>0&&o(M,u,0);let L=c.filter(R=>R.$fieldType==="link");L&&L.length>0&&p(L,u,u,0);let A=c.filter(R=>R.$fieldType==="role");A&&A.length>0&&i(A,u,u,0);}g&&(n+=g.sort),typeof y=="number"&&(n+=`
48
+ offset ${y};`),typeof B=="number"&&(n+=`
49
+ limit ${B};`),h.push(n),n="";}else for(let a of s){let{$path:u,$thing:f,$filter:l,$fields:c,$sort:m,$offset:y,$limit:B}=a;if(!u||u==="undefined")throw new Error("Path is not defined");let T=a[v];n+=`
50
+ match
51
+ $${u} isa ${f};`,l&&(n+=je({$filter:l,$var:u,$thing:f,schema:r,depth:0}));let g=_e({schema:r,$thing:f,$var:u,$sort:m,depth:0});if(g&&(n+=g.match),n+=`
52
+ ?queryPath = "${T}";`,n+=`
53
+ fetch`,n+=`
54
+ ?queryPath as "queryPath";`,c){let Q=c.filter(A=>A.$fieldType==="data");Q&&Q.length>0&&o(Q,u,0);let M=c.filter(A=>A.$fieldType==="link");M&&M.length>0&&p(M,u,u,0);let L=c.filter(A=>A.$fieldType==="role");L&&L.length>0&&i(L,u,u,0);}g&&(n+=g.sort),typeof y=="number"&&(n+=`
55
+ offset ${y};`),typeof B=="number"&&(n+=`
56
+ limit ${B};`);}})(e),t.tqlRequest=d?h:n;},je=t=>{let{$filter:e,$var:r,$thing:n,schema:o,depth:i}=t,{$not:p,...d}=e,h=G(o,n),$=[];return Object.entries(p||{}).forEach(([s,a])=>{if(h.dataFields?.find(l=>l.dbPath===s)){a===null?$.push(P(`$${r} has ${s} $${s}_${uuid.v4()};`,i)):Array.isArray(a)?a.forEach(l=>{$.push(P(`not { $${r} has ${s} ${ie(l)}; };`,i));}):$.push(P(`not { $${r} has ${s} ${ie(a)}; };`,i));return}let f=h.linkFields?.find(l=>l.path===s);if(f){let[l]=f.oppositeLinkFieldsPlayedBy,m=G(o,l.thing).idFields?.[0];if(!m)throw new Error(`"${l.thing}" does not have an id field`);if(f.target==="relation")a===null?$.push(P(`(${f.plays}: $${r}) isa ${f.relation};`,i)):Array.isArray(a)?a.forEach(y=>{$.push(P(`not { (${f.plays}: $${r}) isa ${f.relation}, has ${m} ${ie(y)}; };`,i));}):$.push(P(`not { (${f.plays}: $${r}) isa ${f.relation}, has ${m} ${ie(a)}; };`,i));else {let y=`${l.thing}_${uuid.v4()}`;a===null?$.push(P(`$${y} isa ${l.thing}; (${f.plays}: $${r}, ${l.plays}: $${y}) isa ${f.relation};`,i)):Array.isArray(a)?a.forEach(B=>{$.push(P(`not { $${y} isa ${l.thing}, has ${m} ${ie(B)}; (${f.plays}: $${r}, ${l.plays}: $${y}) isa ${f.relation}; };`,i));}):$.push(P(`not { $${y} isa ${l.thing}, has ${m} ${ie(a)}; (${f.plays}: $${r}, ${l.plays}: $${y}) isa ${f.relation}; };`,i));}return}if(h.thingType==="relation"){let l=h.roles[s];if(l){let[c]=l.playedBy||[],y=G(o,c.thing).idFields?.[0];if(!y)throw new Error(`"${c.thing}" does not have an id field`);let B=`${c.thing}_${uuid.v4()}`;a===null?$.push(P(`$${r} (${c.plays}: ${B});`,i)):Array.isArray(a)?a.forEach(T=>{$.push(P(`not { $${B} isa ${c.thing}, has ${y} ${ie(T)}; $${r} (${c.plays}: $${B}); };`,i));}):$.push(P(`not { $${B} isa ${c.thing}, has ${y} ${ie(a)}; $${r} (${c.plays}: $${B}); };`,i));return}}}),Object.entries(d).forEach(([s,a])=>{if(h.dataFields?.find(l=>l.dbPath===s)){if(a===null)$.push(P(`not { $${r} has ${s} $${s}_${uuid.v4()}; };`,i));else if(Array.isArray(a)){let l=a.map(m=>`$${r} has ${s} ${ie(m)};`),c=Ne(l);c&&$.push(P(c,i));}else $.push(P(`$${r} has ${s} ${ie(a)};`,i));return}let f=h.linkFields?.find(l=>l.path===s);if(f){let[l]=f.oppositeLinkFieldsPlayedBy,m=G(o,l.thing).idFields?.[0];if(!m)throw new Error(`"${l.thing}" does not have an id field`);if(f.target==="relation")if(a===null)$.push(P(`not { (${f.plays}: $${r}) isa ${f.relation}; };`,i));else if(Array.isArray(a)){let y=a.map(T=>`(${f.plays}: $${r}) isa ${f.relation}, has ${m} ${ie(T)};`),B=Ne(y);B&&$.push(P(B,i));}else $.push(P(`(${f.plays}: $${r}) isa ${f.relation}, has ${m} ${ie(a)};`,i));else {let y=`${l.thing}_${uuid.v4()}`;if(a===null)$.push(P(`not { $${y} isa ${l.thing}; (${f.plays}: $${r}, ${l.plays}: $${y}) isa ${f.relation}; };`,i));else if(Array.isArray(a)){let B=a.map(g=>`$${y} isa ${l.thing}, has ${m} ${ie(g)}; (${f.plays}: $${r}, ${l.plays}: $${y}) isa ${f.relation};`),T=Ne(B);T&&$.push(P(T,i));}else $.push(P(`$${y} isa ${l.thing}, has ${m} ${ie(a)}; (${f.plays}: $${r}, ${l.plays}: $${y}) isa ${f.relation};`,i));}return}if(h.thingType==="relation"){let l=h.roles[s];if(l){let[c]=l.playedBy||[],y=G(o,c.thing).idFields?.[0];if(!y)throw new Error(`"${c.thing}" does not have an id field`);let B=`${c.thing}_${uuid.v4()}`;if(a===null)$.push(P(`not { $${r} (${c.plays}: ${B}); };`,i));else if(Array.isArray(a)){let T=a.map(Q=>`$${B} isa ${c.thing}, has ${y} ${ie(Q)}; $${r} (${c.plays}: $${B});`),g=Ne(T);g&&$.push(P(g,i));}else $.push(P(`$${B} isa ${c.thing}, has ${y} ${ie(a)}; $${r} (${c.plays}: $${B});`,i));return}}throw new Error(`"${n}" does not have property "${s}"`)}),$.join(`
57
+ `)},Ne=t=>{if(t.length>1)return `{ ${t.join(" } or { ")} };`;let[e]=t;return e},ie=t=>typeof t=="string"?`'${t}'`:t instanceof Date?`'${t.toISOString().replace("Z","")}'`:`${t}`,ii=t=>typeof t=="string"?{field:t,desc:!1}:{...t,desc:t.desc??!1},_e=t=>{let{$var:e,$thing:r,schema:n,$sort:o,depth:i}=t,p=G(n,r),d=[],h=[];if(o?.forEach($=>{let s=ii($),a=p.dataFields?.find(l=>l.path===s.field);if(!a)throw new Error(`"${r}" does not have data field "${s.field}"`);let u=`${s.field}_${uuid.v4()}`;d.push(P("{",i)),d.push(P(`$${e} has ${a.dbPath} $${u}_1;`,i+1)),d.push(P("not {",i+1)),d.push(P(`$${e} has ${a.dbPath} $${u}_2;`,i+2)),d.push(P(`$${u}_2 < $${u}_1;`,i+2)),d.push(P("};",i+1)),d.push(P(`?${u}_ = $${u}_1;`,i+1)),d.push(P("} or {",i)),d.push(P(`not { $${e} has ${a.dbPath} $${u}_1; };`,i+1)),d.push(P(`?${u}_ = "~";`,i+1)),d.push(P("};",i)),d.push(P(`?${u} = ?${u}_;`,i));let f=s.desc?"desc":"asc";h.push(`?${u} ${f}`);}),d.length!==0)return {match:d.join(""),sort:P(`sort ${h.join(", ")};`,i)}},P=(t,e)=>{let r="";for(let n=0;n<e;n++)r+=" ";return `
58
+ ${r}${t}`};var at=t=>{let e=t.dataFields?.map(i=>i.path)||[],r=t.linkFields?.map(i=>i.path)||[],n=Object.keys(t.roles||{})||[];return [...e,...r,...n]},lt=(t,e)=>Object.keys(t||{}).some(n=>{if(!Array.isArray(t[n])){let o=e.idFields?.includes(n),i=e.dataFields?.some(p=>(p.dbPath===n||p.path===n)&&p?.validations?.unique);return o||i}return !1}),ct=(t,e)=>{let r=e.dataFields?.map(p=>({path:p.path,dbPath:p.dbPath}))||[],n=e.linkFields?.map(p=>({path:p.path,dbPath:p.dbPath}))||[],o=Object.keys(e.roles||{}).map(p=>({path:p,dbPath:p}))||[],i=[...r,...n,...o];return Object.entries(t||{}).reduce((p,[d,h])=>{let $=i.find(s=>s.path===d);return p[$?.dbPath||d]=h,p},{})},ze=async t=>{let{rawBqlRequest:e,schema:r}=t;if(Array.isArray(e)){for(let s of e)if(!("$entity"in s)&&!("$relation"in s)&&(!("$thing"in s)||!("$thingType"in s)))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 n=(s,a)=>typeof a=="string"?s.idFields?.includes(a):s.idFields?.includes(a.$path),o=(s,a,u,f,l)=>({$path:a,$dbPath:f,$thingType:"attribute",$as:s.$as||a,$var:a,$fieldType:"data",$excludedFields:s.$excludedFields,$justId:u,$id:s.$id,$filter:s.$filter,$isVirtual:l,$filterProcessed:!0}),i=(s,a,u,f,l)=>{let{target:c,oppositeLinkFieldsPlayedBy:m}=u;return m.map(y=>{let B=c==="role"?y.thingType:"relation",T=c==="role"?y.thing:u.relation,g={[`$${B}`]:T},Q=C(r,g),M=s?.$fields?.filter(A=>n(Q,A)).length===0,L=[];return typeof s!="string"?s.$fields?M?L=[...s.$fields,...Q.idFields]:L=s.$fields:L=at(Q):L=["id"],s.$excludedFields&&(L=L.filter(A=>n(Q,A)?!0:!s.$excludedFields.includes(A.$path))),{$thingType:B,$plays:u.plays,$playedBy:y,$path:y.path,$dbPath:l,$as:s.$as||a,$var:a,$thing:T,$fields:L,$excludedFields:s.$excludedFields,$fieldType:"link",$target:c,$intermediary:y.relation,$justId:f,$id:s.$id,$filter:ct(s.$filter,Q),$idNotIncluded:M,$filterByUnique:lt(s.$filter,Q),$filterProcessed:!0,$sort:s.$sort,$offset:s.$offset,$limit:s.$limit}})},p=(s,a,u,f,l)=>u.playedBy.map(c=>{let{thing:m,thingType:y,relation:B}=c,T={[`$${y}`]:m},g=C(r,T),Q=s?.$fields?.filter(L=>g?.idFields?.includes(L)||g?.idFields?.includes(L.$path)).length===0,M=[];if(typeof s!="string")if(s.$fields)if(Q){let L=g.idFields||[];M=[...s.$fields,...L];}else M=s.$fields;else M=at(g);else M=["id"];return s.$excludedFields&&(M=M.filter(L=>n(g,L)?!0:!s.$excludedFields.includes(L.$path))),{$thingType:y,$path:a,$dbPath:l,$as:s.$as||a,$var:a,$thing:m,$fields:M,$excludedFields:s.$excludedFields,$fieldType:"role",$intermediary:B,$justId:f,$id:s.$id,$filter:ct(s.$filter,g),$idNotIncluded:Q,$filterByUnique:lt(s.$filter,g),$playedBy:c,$filterProcessed:!0,$sort:s.$sort,$offset:s.$offset,$limit:s.$limit}}),d=(s,a)=>{let u=typeof s=="string"?s:s.$path,f=typeof s=="string",l=a.dataFields?.find(y=>y.path===u),c=a.linkFields?.find(y=>y.path===u),m=a.roles?.[u];if(l){let y=l.isVirtual&&l.default;return o(s,u,f,l.dbPath,y)}else {if(c)return i(s,u,c,f,c.dbPath);if(m)return p(s,u,m,f,m.dbPath)}return null},$=(s=>immer.produce(s,a=>objectTraversal.traverse(a,u=>{let{value:f,meta:l}=u,c=f;if(radash.isObject(c)){if(c.$id){let m=c.$entity||c.$relation?c:{[`$${c.$thingType}`]:c.$thing},y=C(r,m);if(!y?.name)throw new Error(`Schema not found for ${c.$thing}`);if(c.$path=y.name,Array.isArray(c.$id)||(c.$filterByUnique=!0),y?.idFields?.length===1){let[B]=y.idFields;c.$filter={...c.$filter,[B]:c.$id},delete c.$id;}else throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in c||"$relation"in c||"$thing"in c){let m=C(r,c);if(!m?.name)throw new Error(`Schema not found for ${c.$thing}`);c.$path=m.name;}if(c.$entity?(c.$thing=c.$entity,c.$thingType="entity",delete c.$entity):c.$relation&&(c.$thing=c.$relation,c.$thingType="relation",delete c.$relation),radash.isObject(c)&&"$thing"in c){let m=c.$entity||c.$relation?c:{[`$${c.$thingType}`]:c.$thing};c[v]=l.nodePath;let y=C(r,m);if(c.$filter&&(c.$filterByUnique=lt(c.$filter,y),c.$filterProcessed||(c.$filter=ct(c.$filter,y))),c.$fields){c.$fields.filter(g=>y?.idFields?.includes(g)||y?.idFields?.includes(g.$path)).length>0||(c.$fields=[...c.$fields,...Array.isArray(y.idFields)?y.idFields:[]],c.$idNotIncluded=!0);let T=c.$fields?.flatMap(g=>{let Q=d(g,y);return Array.isArray(Q)?Q:[Q]}).filter(Boolean);c.$fields=T;}else {let T=at(y)?.flatMap(g=>{let Q=d(g,y);return Array.isArray(Q)?Q:[Q]}).filter(Boolean);c.$fields=T;}c.$excludedFields&&(c.$fields=c.$fields.filter(B=>n(y,B)?!0:!c.$excludedFields.includes(B.$path)));}}})))(Array.isArray(e)?e:[e]);t.enrichedBqlQuery=$;};var $r=async(t,e)=>{let{dbHandles:r,enrichedBqlQuery:n,tqlRequest:o,config:i}=t;if(!n)throw new Error("BQL request not parsed");if(!o)throw new Error("TQL request not built");let p=new typedbDriver.TypeDBOptions;if(p.infer=!0,Array.isArray(o)){let h=await radash.parallel(o.length,o,async $=>{let{session:s}=await Qe(r,i),a=await s.transaction(typedbDriver.TransactionType.READ,p);if(!a)throw new Error("Can't create transaction");let f=await a.query.fetch($).collect();return await a.close(),f});e.rawTqlRes=h,e.isBatched=!0;}else {let{session:h}=await Qe(r,i),$=await h.transaction(typedbDriver.TransactionType.READ,p);if(!$)throw new Error("Can't create transaction");let a=await $.query.fetch(o).collect();await $.close(),e.rawTqlRes=a;}};var fr=t=>{let e=/as:([a-zA-Z0-9_\-·]+)/,r=/justId:([a-zA-Z0-9_\-·]+)/,n=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,o=/filterByUnique:([a-zA-Z0-9_\-·]+)/,i=t.match(e),p=t.match(r),d=t.match(n),h=t.match(o);return {as:i?i[1]:null,justId:p?p[1]:null,idNotIncluded:d?d[1]:null,filterByUnique:h?h[1]:null}},di=t=>{try{let r=(o=>{let i=o.replace("$metadata:","");return i=i.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),i=i.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(p,d,h)=>/^{.*}$/.test(h)?`:${h}`:`:${d}"${h}"`),i=i.replace(/\[([^\]]+)\]/g,(p,d)=>`[${d.split(",").map(h=>h.trim().startsWith("{")&&h.trim().endsWith("}")?h.trim():`"${h.trim()}"`).join(",")}]`),i})(t);return JSON.parse(r)}catch(e){return console.error(e),{as:[]}}},yr=async(t,e)=>{let{enrichedBqlQuery:r,rawBqlRequest:n,schema:o,config:i}=t,{rawTqlRes:p,isBatched:d}=e;if(r){if(!p)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");let h=(c,m)=>{let{$metaData:y}=c,{as:B}=di(y),T=Object.entries(c).filter(([g])=>g!=="type"&&!g.startsWith("$")).map(([g,Q])=>{let M=m.dataFields?.find(D=>D.path===g||D.dbPath===g),L=g==="id",A=Array.isArray(B)?B.find(D=>D[g])?.[g]:g,R;if(M?.cardinality==="ONE"){if(R=Q[0]?Q[0].value:i.query?.returnNulls?null:void 0,M.contentType==="DATE"?R=R&&`${R}Z`:M.contentType==="JSON"&&(R=R&&JSON.parse(R)),L)return [[A,R],["$id",R]].filter(([D,N])=>N!==void 0)}else if(M?.cardinality==="MANY"){if(!radash.isArray(Q))throw new Error("Typedb fetch has changed its format");if(Q.length===0)return i.query?.returnNulls?[[A,null]]:[];M.contentType==="DATE"?R=Q.map(D=>`${D.value}Z`):M.contentType==="JSON"?R=Q.map(D=>D.value&&JSON.parse(D.value)):R=Q.map(D=>D.value);}return [[A,R]].filter(([D,N])=>N!==void 0)}).flat();return Object.fromEntries([...T])},$=c=>c.reduce((m,y)=>{let{$roleFields:B,$metaData:T,$cardinality:g}=y,{as:Q,justId:M,idNotIncluded:L,filterByUnique:A}=fr(T),R=B.map(D=>{let{dataFields:N,currentSchema:x,linkFields:w,roleFields:F,schemaValue:k}=a(D),E=h(N,x);if(M==="T")return E.id;{let b=s(w),S=$(F),_={...E};return L==="true"&&x?.idFields?.forEach(I=>delete _[I]),{..._,...b,...S,...k}}});return R.length>0?m[Q]=g==="MANY"&&A==="false"?R:R[0]:i.query?.returnNulls&&(m[Q]=null),m},{}),s=c=>c.reduce((m,y)=>{let{$linkFields:B,$metaData:T,$cardinality:g}=y,{as:Q,justId:M,idNotIncluded:L,filterByUnique:A}=fr(T),R=B.map(D=>{let{dataFields:N,currentSchema:x,linkFields:w,roleFields:F,schemaValue:k}=a(D),E=h(N,x);if(M==="T")return E.id;{let b=s(w),S=$(F),_={...E};return L==="true"&&x.idFields?.forEach(I=>delete _[I]),{..._,...b,...S,...k}}});return m[Q]=R.length>0?g==="MANY"&&A==="false"?R:R[0]:i.query?.returnNulls?null:void 0,m},{}),a=c=>{let m=Object.keys(c),y=m.find(D=>D.endsWith(".$dataFields"));if(!y)throw new Error("No datafields");let B=c[y],T=y.split(".")[y.split(".").length-2];if(B.$metaData=T,B.length===0)throw new Error("No datafields");let g=B.type,Q={$thing:g.label,$thingType:g.root,[v]:c.queryPath.value},M={[`$${Q.$thingType}`]:Q.$thing},L=C(o,M),A=m.filter(D=>!D.endsWith(".$dataFields")&&L.linkFields?.some(N=>N.path===D.split(".").pop())).map(D=>({$linkFields:c[D],$key:D.split(".").pop(),$metaData:D.split(".")[D.split(".").length-2],$cardinality:L?.linkFields?.find(N=>N.path===D.split(".").pop())?.cardinality})),R=m.filter(D=>!D.endsWith(".$dataFields")&&L.roles?.[D.split(".").pop()]).map(D=>({$roleFields:c[D],$key:D.split(".").pop(),$metaData:D.split(".")[D.split(".").length-2],$cardinality:L.roles[D.split(".").pop()].cardinality}));return {dataFields:B,schemaValue:Q,currentSchema:L,linkFields:A,roleFields:R}},u=c=>c.map(m=>{let{dataFields:y,currentSchema:B,linkFields:T,roleFields:g,schemaValue:Q}=a(m),M=h(y,B),L=s(T),A=$(g),R=n?.$fields?.every(N=>!B?.idFields?.includes(N)&&!B?.idFields?.includes(N.$path));return {...L,...A,...Q,...!i.query?.noMetadata&&n.$id?{$id:Array.isArray(n.$id)?M.id:n.$id}:{},...R?Object.fromEntries(Object.entries(M).filter(([N])=>!B?.idFields?.includes(N))):M}}),l=(c=>{let m=y=>{let B=u(y);return n.$id&&!Array.isArray(n.$id)||r[0].$filterByUnique?B[0]??null:B.length===0?null:B};return d?c.map(m):m(c)})(p);e.bqlRes=l;};var mr=async(t,e)=>{let{schema:r,enrichedBqlQuery:n}=t,{bqlRes:o}=e;if(!o)return;let p=(d=>immer.produce(d,h=>objectTraversal.traverse(h,({value:$})=>{if(radash.isObject($)){let s=$;if(!s.$thing)return;if(s.$thing){let a=C(r,s),{virtualFields:u}=a,f=s[v];if(!f)throw new Error("[Internal] QueryPath is missing");let l=objectTraversal.getNodeByPath(n,f),c=l.$fields.map(y=>y.$path),m=l.$excludedFields;u.forEach(y=>{if(m?.includes(y)||c.length>0&&!c.includes(y))return;let B=a.dataFields?.find(T=>T.path===y);if(B?.default){let T=Be({currentThing:s,fieldSchema:B,mandatoryDependencies:!0});s[y]=T;}else if(s[y]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${y}`)}),m&&m.forEach(y=>{if(typeof y!="string")throw new Error("[Internal] ExcludedField is not a string");delete s[y];});}}})))(o);e.bqlRes=p;};var Fr=async(t,e)=>{let{config:r}=t,{bqlRes:n}=e;if(!n)return;let i=(h=>immer.produce(h,$=>objectTraversal.traverse($,({value:s})=>{radash.isObject(s);})))(n),d=(h=>immer.produce(h,$=>objectTraversal.traverse($,({value:s})=>{if(radash.isObject(s)){let a=s;Object.keys(a).forEach(u=>{a[u]===void 0&&delete a[u];}),Object.getOwnPropertySymbols(a).forEach(u=>{delete a[u];}),r.query?.noMetadata===!0&&Object.keys(a).forEach(u=>{u.startsWith("$")&&delete a[u];});}})))(i);e.bqlRes=d;};var yi=(t,e)=>{for(let r in e){let n=e[r];if(t.query?.returnNulls){if(Array.isArray(n)&&n.length===0){e[r]=null;continue}}else {if(n===null){delete e[r];continue}if(Array.isArray(n)&&n.length===0){delete e[r];continue}}}},br=({config:t,item:e,query:r,schema:n})=>{let o=n[r.$thingType==="entity"?"entities":"relations"][r.$thing];if(yi(t,e),Object.getOwnPropertySymbols(e).forEach(i=>{delete e[i];}),t.query?.noMetadata===!0&&Object.keys(e).forEach(i=>{i.startsWith("$")&&delete e[i];}),r.$idNotIncluded){let i=o.idFields?.[0];delete e[i??"id"];}},wr=async(t,e)=>{let{config:r,enrichedBqlQuery:n,schema:o}=t,{bqlRes:i}=e;if(!i)return;if(n.length>1)throw new Error("batch query unimplemented");let[d]=n,h=immer.produce(i,$=>{if(Array.isArray($))for(let s of $)br({config:r,item:s,query:d,schema:o});else br({config:r,item:$,query:d,schema:o});});e.bqlRes=h;};var Lr=(t,e,r,n=[])=>{let o=Object.values(t[e]).filter(i=>i.extends===r).map(i=>i.name);return o.length===0?[...n]:o.reduce((i,p)=>[...i,p,...Lr(t,e,p,i)],n)},gi=t=>t.$path==="id"?`meta::id(${t.$path}) as id`:`${t.$path}`,Bi=(t,e)=>r=>{if(e.$thingType==="entity")return r;let o=t.relations[e.$thing];return Object.entries(o.roles).reduce((i,[p,d])=>{let h=i[p];return d.cardinality==="ONE"&&Array.isArray(h)?{...i,[p]:h[0]}:i},r)},Qr=(t,e)=>{let r=e.$fields.filter($=>$.$thingType==="attribute"),n=e.$fields.filter($=>$.$thingType==="entity"),i=e.$fields.filter($=>$.$thingType==="relation").map($=>`(SELECT VALUE meta::id(id) as id FROM <-${$.$thing}_${$.$plays}<-${$.$thing}) as \`${$.$as}\``),p=n.map($=>{let s=radash.pascal($.$playedBy.relation);return e.$thingType==="relation"?`(SELECT VALUE meta::id(id) as id FROM ->${s}_${$.$playedBy.plays}.out) as ${$.$as}`:`(SELECT VALUE meta::id(id) as id FROM <-${s}_${$.$playedBy.path}<-${s}->${s}_${$.$playedBy.plays}.out) as ${$.$as}`}),d=e.$filter?`WHERE ${Object.entries(e.$filter).map(([$,s])=>`${$} = ${e.$thing}:\`${s}\``).join(",")}`:"";return `SELECT
59
+ ${[...r.map(gi),...p,...i].join(",")}
60
+ FROM ${t}
61
+ ${d}
62
+ FETCH ${n.map($=>$.$path).join(",")}
63
+ PARALLEL`},Ei=async(t,e)=>{console.log(`
64
+
65
+ buildSurrealDbQuery
66
+ `,JSON.stringify(t));let{dbHandles:r,enrichedBqlQuery:n,schema:o}=t;if(!n)throw new Error("BQL request not parsed");if(!r.surrealDB)throw new Error("missing SurrealDB in dbHandles");let i=t.config.dbConnectors.find($=>$.provider==="surrealDB");if(!i)throw new Error("missing SurrealDB config");let p=r.surrealDB.get(i.id);if(!p)throw new Error(`missing SurrealDB client with id of ${i.id}`);let{client:d}=p,h=await Promise.all(t.enrichedBqlQuery.map(async $=>{let s;if($.$thingType==="relation"){let a=radash.pascal($.$thing),u=Qr(a,$);s=(await d.query(u)).map(l=>({$id:l.id,$thing:caseAnything.trainCase(a),$thingType:"relation",...l,id:l.id,[v]:n[0][v]}));}else {let a=[$.$thing,...Lr(t.schema,"entities",$.$thing)];s=(await Promise.all(a.map(async f=>(await d.query(Qr(f,$))).map(c=>({$id:radash.dash(c.id),$thing:f,$thingType:"entity",...c,id:radash.dash(c.id),[v]:n[0][v]}))))).flat();}if(!s)throw new Error("empty query result");return s.map(Bi(o,$))}));if(t.enrichedBqlQuery.length>1)throw new Error("batch query unimplemented");e.bqlRes=t.enrichedBqlQuery[0]?.$filter?.id?h[0][0]:h[0];},kr={query:[ze,Ei,wr],mutation:[]};var Fi={query:[ze,pr,$r,yr,mr,Fr]},dt=async(t,e,r,n=!0)=>{for(let o of t){let i=await o(e,r);if(i&&Array.isArray(i))for(let p of i)await dt(p.pipeline,p.req,p.res,!1);}return n&&e.config.query?.debugger===!0&&typeof r.bqlRes=="object"?{...r.bqlRes,$debugger:{tqlRequest:e.tqlRequest}}:r.bqlRes},Sr=(t,e,r,n)=>{if(n.typeDB&&n.typeDB.size>0)return dt(Fi.query,{config:e,schema:r,rawBqlRequest:t,dbHandles:n},{});if(n.surrealDB&&n.surrealDB.size>0)return dt(kr.query,{config:e,schema:r,rawBqlRequest:t,dbHandles:n},{});throw new Error("no pipeline defined")};var qr="___",bi=Symbol.for("grandChildOfCreate"),Rr=async(t,e,r,n)=>{let o=(w,F)=>Object.keys(w).filter(k=>!k.startsWith("$")&&w[k]!==void 0?F?!C(e,w).dataFields?.find(b=>b.path===k):!0:!1);if(!t)throw new Error("[BQLE-M-PQ-1] No blocks found");if(r.mutation?.preQuery===!1)return;let i=[];if(objectTraversal.traverse(t,({parent:w,key:F,value:k})=>{w&&F&&!F.includes("$")&&radash.isObject(w)?(Array.isArray(w[F])?w[F]:[w[F]]).forEach(b=>{if(radash.isObject(b)){if(w.$op!=="create")i.includes(b.$op)||i.push(b.$op);else if(b.$op==="delete"||b.$op==="unlink")throw new Error(`Cannot ${b.$op} under a create`)}}):!w&&radash.isObject(k)&&(i.includes(k.$op)||i.push(k.$op));}),!i.includes("delete")&&!i.includes("unlink")&&!i.includes("replace")&&!i.includes("update")&&!i.includes("link"))return;let d=(w=>{let F=(k,E)=>{let b=[],S={},_=["$op","$bzId","$parentKey"],I=["$relation","$entity","$id",..._];for(let O in k)if(!_.includes(O)&&!(I.includes(O)&&!E))if(!O.includes("$")&&(radash.isObject(k[O])||Array.isArray(k[O]))){let H=k[O];Array.isArray(H)&&H.length>0?H.forEach(oe=>{b.push({$path:O,...F(oe)});}):b.push({$path:O,...F(H)});}else S[O]=k[O];return {...S,$fields:b}};return w.map(k=>F(k,!0))})(Array.isArray(t)?t:[t]),h=await Sr(d,r,e,n),$=(w,F)=>{let k=w.$id||w.id||w.$bzId;if(w.$objectPath){let{$objectPath:E}=w,b=E?.beforePath||"root",S=Array.isArray(E.ids)?`[${E.ids}]`:E.ids;return {beforePath:`${b}.${S}___${E.key}`,ids:k,key:F}}else return {beforePath:"root",ids:k,key:F}},s=(w,F)=>{let k=w?.beforePath||"root",E=F||(Array.isArray(w?.ids)?`[${w?.ids}]`:w?.ids);return `${k}.${E}___${w?.key}`},a=w=>{if(w.includes("[")&&w.includes("]")){let[F,k,E]=w.split(/[[\]]/);return k.split(",").map(S=>`${F}${S}${E}`)}else return [w]},u={};(w=>immer.produce(w,F=>objectTraversal.traverse(F,k=>{let{key:E,parent:b}=k;if(b&&E&&b.$id&&!E.includes("$")){let S=$(b,E),_=s(S);if(Array.isArray(b[E])){let I=[];b[E].forEach(O=>{radash.isObject(O)?(O.$objectPath=S,I.push(O.$id.toString())):O&&I.push(O.toString());}),u[_]={$objectPath:S,$ids:I};}else {let I=b[E];radash.isObject(I)?(u[_]={$objectPath:S,$ids:[I.$id.toString()]},I.$objectPath=S):I&&(u[_]={$objectPath:S,$ids:[I.toString()]});}}})))(h||{});let l=w=>immer.produce(w,F=>objectTraversal.traverse(F,k=>{let{key:E,value:b,parent:S}=k;S&&E&&!E.includes("$")&&(Array.isArray(b)||radash.isObject(b))&&!Array.isArray(S)&&(Array.isArray(S[E])?S[E].forEach(_=>{typeof _!="string"&&(_.$objectPath=$(S,E),_.$parentIsCreate=S.$op==="create",_[bi]=S.$parentIsCreate||S[Symbol.for("grandChildOfCreate")]);}):radash.isObject(S[E])&&(S[E].$parentIsCreate=S.$op==="create",S[E][Symbol.for("grandChildOfCreate")]=S.$parentIsCreate||S[Symbol.for("grandChildOfCreate")],S[E].$objectPath=$(S,E)));})),c=l(t),m=w=>{let F=[];return w.forEach(E=>{if(!E.$id&&!E.id&&!E.$tempId){let b=s(E.$objectPath),S=u[b];S?S?.$ids.forEach(_=>{let I={...E,$id:_,$bzId:`T4_${uuid.v4()}`};F.push(I);}):F.push(E);}else F.push(E);}),F.map(E=>{let b={...E};return o(b,!0).forEach(S=>{let _=Array.isArray(b[S])?b[S]:[b[S]],I=m(_);b[S]=I;}),b})},y=m(Array.isArray(c)?c:[c]),B=l(y),g=(w=>{let F=k=>{let E=Y=>{let ee=[],V=[],z=[];return Y.forEach(J=>{let ae=o(J,!0);if(ae.length>0){let j=!1;ae.forEach(W=>{(Array.isArray(J[W])?J[W]:[J[W]]).filter(re=>!re.$id&&!re.id&&typeof J=="object").length&&(j=!0);}),j?ee.push(J):V.push(J);}else z.push({...J,$bzId:J.$tempId||`T_${uuid.v4()}`});}),{operationWithMultiples:ee,operationWithoutMultiples:V,otherOps:z}},{operationWithMultiples:b,operationWithoutMultiples:S,otherOps:_}=E(k),I=Y=>{let V=(()=>{let W={};for(let ne in Y){let te=C(e,Y);!ne.startsWith("$")&&te.dataFields?.find(re=>re.path===ne)&&(W[ne]=Y[ne]);}return W})(),z=Object.keys(Y),J=o(Y,!0),ae=[],j=(W,ne)=>{if(W===J.length){let re={...ne};z.forEach(ce=>{ce.startsWith("$")&&(re[ce]=Y[ce]);}),ae.push({...re,...V});return}let te={...ne,[J[W]]:Y[J[W]],...ye(ne),...V};j(W+1,te),j(W+1,ne);};return j(0,{...ye(Y)}),ae},O=[];return b.forEach(Y=>{let ee=I(Y),V=[];ee.forEach(z=>{let J=o(z,!0);if(z.$op==="create")V.push(z);else if(z.$id){let ae=s(z.$objectPath),j=[];if(J.forEach(W=>{let ne=`${ae.includes("undefined")?"root":ae}.${z.$id}${qr}${W}`,te=u[ne];z[W].filter(ce=>ce.$op==="unlink"||ce.$op==="delete"||ce.$op==="update").length>0?te&&j.push({key:W,ids:te.$ids}):j.push({key:W,ids:[""]});}),j.length===J.length&&!V.find(W=>W.$id===z.$id))V.push(z);else {let W={...z,$bzId:z.$tempId||`T4_${uuid.v4()}`};J.forEach(te=>{let re=z[te].filter(ce=>ce.$id);re.length>0?W[te]=re:W[te]=void 0;}),o(W,!0).length>0&&V.push(W);}}else if(z.$objectPath){let ae=s(z.$objectPath),j=u[ae]?.$ids||[];j.forEach(W=>{let ne=[];J.forEach(te=>{let re=`${ae}.${W}${qr}${te}`,ce=u[re];ce&&ne.push({key:te,ids:ce.$ids});}),J.length===0?j.filter(re=>!V.find(ce=>ce.$id===re)).forEach(re=>{V.push({...z,$id:re,$bzId:z.$tempId||`T_${uuid.v4()}`});}):ne.length===J.length&&!V.find(te=>te.$id===W)&&V.push({...z,$id:W,$bzId:z.$tempId||`T_${uuid.v4()}`});});}else V.push(z);}),V.forEach(z=>{O.push(z);});}),[...O,...S,..._].filter(Y=>o(Y).length>0?!0:Y.$op!=="update").map(Y=>{let ee={...Y};return o(ee,!0).forEach(V=>{let z=Array.isArray(ee[V])?ee[V]:[ee[V]],J=F(z);ee[V]=J;}),ee})};return F(w)})(Array.isArray(B)?B:[B]),Q=w=>w.map(F=>{let k=o(F,!0),E={...F};return k.forEach(b=>{let S=Array.isArray(F[b])?F[b]:[F[b]],_=[],I=[],O=[],H={},oe=tt(e,F,b);S.filter(j=>j).forEach(j=>{j.$op==="replace"&&j.$id?(H=j,Array.isArray(j.$id)?I=[...I,...j.$id]:I.push(j.$id)):j.$op==="create"&&oe==="ONE"&&j.id?(H=j,Array.isArray(j.id)?O=[...I,...j.id]:O.push(j.id)):_.push(j);});let Re=s(H.$objectPath),ee=a(Re).map(j=>u[j]),V=[];ee.filter(j=>j!=null).forEach(j=>{V=[...V,...j.$ids];});let z=V.filter(j=>!I.includes(j)),J=I.filter(j=>!V.includes(j)),ae=ye(H);z.length>0&&_.push({...H,$op:"unlink",$id:z,$bzId:H.$tempId||`T4_${uuid.v4()}`,id:void 0,...ae}),J.length>0&&J.forEach(j=>{_.push({...H,$op:"link",$id:j,$bzId:H.$tempId||`T5_${uuid.v4()}`,...ae});}),O.length>0&&O.forEach(j=>{_.push({...H,$op:"create",id:j,$bzId:H.$tempId||`T6_${uuid.v4()}`,...ae});}),E[b]=Q(_);}),E}),M=l(Q(l(g)));(w=>immer.produce(w,F=>objectTraversal.traverse(F,k=>{let{key:E,value:b,parent:S}=k;E&&S&&!E?.includes("$")&&(Array.isArray(b)||radash.isObject(b))&&!Array.isArray(S)&&(Array.isArray(b)?b:[b]).forEach(I=>{let O=u[s(I.$objectPath)],H=(Y,ee)=>Y.every(V=>ee.includes(V)),oe=I.$id?Array.isArray(I.$id)?H(I.$id,O?O.$ids:[]):O?.$ids.includes(I.$id):O,Re=tt(e,S,I.$objectPath.key);if(I.$op==="link"&&oe&&Re==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${s(I.$objectPath)}" because it is already occupied.`);if(I.$op)switch(I.$op){case"delete":if(!oe&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${I.$id}" because it is not linked to $id:"${S.$id}"`);break;case"update":if(!oe&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${I.$id}" because it is not linked to $id:"${S.$id}"`);break;case"unlink":if(!oe&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${I.$id}" because it is not linked to $id:"${S.$id}"`);break;case"link":if(oe)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${I.$id}" because it is already linked to $id:"${S.$id}"`);break;}});})))(M);let R=(w=>immer.produce(w,F=>objectTraversal.traverse(F,k=>{let{value:E,meta:b}=k;radash.isObject(E)&&(E[Symbol.for("path")]=b.nodePath,delete E.$objectPath,delete E.$parentIsCreate);})))(M);return [...Array.isArray(R)?R:[R]].sort((w,F)=>w.$op==="create"&&F.$op!=="create"?-1:w.$op!=="create"&&F.$op==="create"?1:0)};function X(t){return {enumerable:!0,value:t}}function Ar(t){return {enumerable:!0,writable:!0,value:t}}var ke={},wi=()=>!0,Dr=()=>({}),Ir=t=>t,Ti=(t,e,r,n)=>t.apply(r,n)&&e.apply(r,n),Qi=(t,e,r,[n,o])=>e.call(r,t.call(r,n,o),o),Fe=(t,e)=>Object.freeze(Object.create(t,e));function Pr(t,e,r){return t.reduce((n,o)=>function(...i){return r(n,o,this,i)},e)}function Cr(t){return Fe(this,{fn:X(t)})}var Or={},U=Cr.bind(Or);var xr={},jr=Cr.bind(xr);function We(t,e){return e.filter(r=>t.isPrototypeOf(r))}function Nr(t,e,...r){let n=Pr(We(xr,r).map(i=>i.fn),wi,Ti),o=Pr(We(Or,r).map(i=>i.fn),Ir,Qi);return Fe(this,{from:X(t),to:X(e),guards:X(n),reducers:X(o)})}var _r={},zr={},K=Nr.bind(_r);Nr.bind(zr,null);function Mi(t,e,r){return ut(e,t,r,this.immediates)||t}function Vr(t){let e=new Map;for(let r of t)e.has(r.from)||e.set(r.from,[]),e.get(r.from).push(r);return e}var Li={enter:Ir};function de(...t){let e=We(_r,t),r=We(zr,t),n={final:X(t.length===0),transitions:X(Vr(e))};return r.length&&(n.immediates=X(r),n.enter=X(Mi)),Fe(Li,n)}var ki={enter(t,e,r){let n=this.fn.call(e,e.context,r);return pt.isPrototypeOf(n)?Fe(Wr,{machine:X(n),transitions:X(this.transitions)}).enter(t,e,r):(n.then(o=>e.send({type:"done",data:o})).catch(o=>e.send({type:"error",error:o})),t)}},Wr={enter(t,e,r){if(e.child=fe(this.machine,n=>{e.onChange(n),e.child==n&&n.machine.state.value.final&&(delete e.child,e.send({type:"done",data:n.context}));},e.context,r),e.child.machine.state.value.final){let n=e.child.context;return delete e.child,ut(e,t,{type:"done",data:n},this.transitions.get("done"))}return t}};function Z(t,...e){let r=X(Vr(e));return pt.isPrototypeOf(t)?Fe(Wr,{machine:X(t),transitions:r}):Fe(ki,{fn:X(t),transitions:r})}var pt={get state(){return {name:this.current,value:this.states[this.current]}}};function be(t,e,r=Dr){return typeof t!="string"&&(r=e||Dr,e=t,t=Object.keys(e)[0]),ke._create&&ke._create(t,e),Fe(pt,{context:X(r),current:X(t),states:X(e)})}function ut(t,e,r,n){let{context:o}=t;for(let{to:i,guards:p,reducers:d}of n)if(p(o,r)){t.context=d.call(t,o,r);let h=e.original||e,$=Fe(h,{current:X(i),original:{value:h}});ke._onEnter&&ke._onEnter(e,i,t.context,o,r);let s=$.state.value;return t.machine=$,t.onChange(t),s.enter($,t,r)}}function Si(t,e){let r=e.type||e,{machine:n}=t,{value:o,name:i}=n.state;return o.transitions.has(r)?ut(t,n,e,o.transitions.get(r))||n:(ke._send&&ke._send(r,i),n)}var qi={send(t){Si(this,t);}};function fe(t,e,r,n){let o=Object.create(qi,{machine:Ar(t),context:Ar(t.context(r,n)),onChange:X(e)});return o.send=o.send.bind(o),o.machine=o.machine.state.value.enter(o.machine,o,n),o}var Hr=(t,e)=>immer.produce(t,n=>He(e,n)),He=(t,e,r)=>{if(typeof e=="string")return;if(Array.isArray(e)){e.forEach(o=>He(t,o,r));return}let n=G(t,r||e.$entity||e.$relation||e.$thing);Object.entries(e).forEach(([o])=>{o.startsWith("$")||Ai(t,e,o,n);});},Ai=(t,e,r,n)=>{let o=e[r];if(!o)return;let i=n.dataFields?.find(d=>d.path===r);if(i){i.contentType==="JSON"&&o!=null&&(e[r]=JSON.stringify(o));return}let p=n.linkFields?.find(d=>d.path===r);if(p){let d=p.oppositeLinkFieldsPlayedBy[0]?.thing;He(t,o,d);return}if(n.thingType==="relation"){let d=n.roles[r],[h]=d.playedBy||[];if(!h)throw new Error(`Role ${d.name} in ${n} is not played by anything`);He(t,o,h.thing);}};var vr=de,ve=(t,e)=>e.data?{...t,bql:{...t.bql,current:e.data}}:t,Di=(t,e)=>({...t,bql:{...t.bql,res:e.data}}),Pi=(t,e)=>({...t,bql:{...t.bql,things:e.data.mergedThings,edges:e.data.mergedEdges}}),Ii=(t,e)=>({...t,typeDB:{...t.typeDB,tqlMutation:e.data}}),Ci=(t,e)=>({...t,typeDB:{...t.typeDB,tqlRes:e.data}}),Oi=async t=>Object.keys(t.bql.current).length?it(t.bql.current,t.schema,t.config):it(t.bql.raw,t.schema,t.config),xi=async t=>Rr(t.bql.current,t.schema,t.config,t.handles),ji=async t=>cr(t.bql.current,t.schema),Ni=async t=>dr(t.bql.things,t.bql.edges,t.schema),_i=async t=>nr(t.typeDB.tqlMutation,t.handles,t.config),zi=async t=>ir(t.typeDB.tqlRes,t.bql.things,t.bql.edges,t.schema,t.config),Vi=()=>!0,Me=K("error","error",U((t,e)=>({...t,error:e.error}))),Wi=be("stringify",{stringify:Z(async t=>Hr(t.bql.raw,t.schema),K("done","enrich",U(ve)),Me),enrich:Z(Oi,K("done","preQuery",jr(Vi),U(ve)),K("done","parseBQL",U(ve)),Me),preQuery:Z(xi,K("done","parseBQL",U(ve)),Me),parseBQL:Z(ji,K("done","buildMutation",U(Pi)),Me),buildMutation:Z(Ni,K("done","runMutation",U(Ii)),Me),runMutation:Z(_i,K("done","parseMutation",U(Ci)),Me),parseMutation:Z(zi,K("done","success",U(Di)),Me),success:vr(),error:vr()},t=>t),Hi=async t=>new Promise((e,r)=>{fe(Wi,n=>{n.machine.state.name==="success"&&e(n.context),n.machine.state.name==="error"&&r(n.context);},t);}),Ur=async(t,e,r,n)=>Hi({bql:{raw:t,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:e,config:r,handles:n,depthLevel:0,error:null});var Yr=(t,e)=>{if(!e)return;let r=vi(e);return Ui(r,t.query?.noMetadata??!1)},vi=t=>immer.produce(t,e=>objectTraversal.traverse(e,({value:r})=>{radash.isObject(r);})),Ui=(t,e)=>immer.produce(t,r=>objectTraversal.traverse(r,({value:n})=>{if(radash.isObject(n)){let o=n;Object.keys(o).forEach(i=>{o[i]===void 0&&delete o[i];}),Object.getOwnPropertySymbols(o).forEach(i=>{delete o[i];}),e===!0&&Object.keys(o).forEach(i=>{i.startsWith("$")&&delete o[i];});}}));var tn=(t,e)=>{for(let o of t)if(!("$entity"in o)&&!("$relation"in o)&&(!("$thing"in o)||!("$thingType"in o)))throw new Error("No entity specified in query");let r=Array.isArray(t)?t:[t];return immer.produce(r,o=>objectTraversal.traverse(o,i=>{let{value:p,meta:d}=i,h=p;if(radash.isObject(h)){if(h.$id){let $=h.$entity||h.$relation?h:{[`$${h.$thingType}`]:h.$thing},s=C(e,$);if(!s?.name)throw new Error(`Schema not found for ${h.$thing}`);if(h.$path=s.name,Array.isArray(h.$id)||(h.$filterByUnique=!0),s?.idFields?.length===1){let[a]=s.idFields;h.$filter={...h.$filter,[a]:h.$id},delete h.$id;}else throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in h||"$relation"in h||"$thing"in h){let $=C(e,h);if(!$?.name)throw new Error(`Schema not found for ${h.$thing}`);h.$path=$.name;}if(h.$entity?(h.$thing=h.$entity,h.$thingType="entity",delete h.$entity):h.$relation&&(h.$thing=h.$relation,h.$thingType="relation",delete h.$relation),radash.isObject(h)&&"$thing"in h){let $=h.$entity||h.$relation?h:{[`$${h.$thingType}`]:h.$thing};h[v]=d.nodePath;let s=C(e,$);if(h.$filter&&(h.$filterByUnique=$t(h.$filter,s),h.$filterProcessed||(h.$filter=h.$filter&&ft(h.$filter,s))),h.$fields){h.$fields.some(f=>s?.idFields?.includes(f?.$path||f))||(h.$fields=[...h.$fields,...Array.isArray(s.idFields)?s.idFields:[]],h.$idNotIncluded=!0);let u=h.$fields?.flatMap(f=>{let l=en(f,s,e);return Array.isArray(l)?l:[l]}).filter(Boolean);h.$fields=u;}else {let u=ht(s)?.flatMap(f=>{let l=en(f,s,e);return Array.isArray(l)?l:[l]}).filter(Boolean);h.$fields=u;}h.$excludedFields&&(h.$fields=h.$fields.filter(a=>Ue(s,a)?!0:!h.$excludedFields.includes(a.$path)));}}}))},ht=t=>{let e=t.dataFields?.map(i=>i.path)||[],r=t.linkFields?.map(i=>i.path)||[],n=Object.keys(t.roles||{})||[];return [...e,...r,...n]},$t=(t,e)=>Object.keys(t||{}).some(n=>{if(!Array.isArray(t[n])){let o=e.idFields?.includes(n),i=e.dataFields?.some(p=>(p.dbPath===n||p.path===n)&&p?.validations?.unique);return o||i}return !1}),ft=(t,e)=>{let r={};if(e.dataFields?.forEach(p=>{p.path!==p.dbPath&&(r[p.path]=p.dbPath);}),Object.keys(r).length===0)return t;let{$not:n,...o}=t,i=Xr(o,r);return n&&(i.$not=Xr(n,r)),i},Xr=(t,e)=>{let r={};return Object.entries(t).forEach(([n,o])=>{let i=e[n]||n;r[i]=o;}),r},Ue=(t,e)=>typeof e=="string"?t.idFields?.includes(e):t.idFields?.includes(e.$path),Zi=t=>{let{field:e,fieldStr:r,$justId:n,dbPath:o,isVirtual:i}=t;return {$path:r,$dbPath:o,$thingType:"attribute",$as:e.$as||r,$var:r,$fieldType:"data",$justId:n,$id:e.$id,$isVirtual:i}},Yi=t=>{let{field:e,fieldStr:r,linkField:n,$justId:o,dbPath:i,schema:p}=t,{target:d,oppositeLinkFieldsPlayedBy:h}=n;return h.map($=>{let s=d==="role"?$.thingType:"relation",a=d==="role"?$.thing:n.relation,u={[`$${s}`]:a},f=C(p,u),l=e?.$fields?.filter(m=>Ue(f,m)).length===0,c=[];if(typeof e!="string")if(e.$fields)if(l){let m=f.idFields||[];c=[...e.$fields,...m];}else c=e.$fields;else c=ht(f);else c=["id"];return e.$excludedFields&&(c=c.filter(m=>Ue(f,m)?!0:!e.$excludedFields.includes(m.$path))),{$thingType:s,$plays:n.plays,$playedBy:$,$path:$.path,$dbPath:i,$as:e.$as||r,$var:r,$thing:a,$fields:c,$excludedFields:e.$excludedFields,$fieldType:"link",$target:d,$intermediary:$.relation,$justId:o,$id:e.$id,$filter:e.$filter&&ft(e.$filter,f),$idNotIncluded:l,$filterByUnique:$t(e.$filter,f),$filterProcessed:!0,$sort:e.$sort,$offset:e.$offset,$limit:e.$limit}})},Gi=t=>{let{field:e,fieldStr:r,roleField:n,$justId:o,dbPath:i,schema:p}=t;return n.playedBy.map(d=>{let{thing:h,thingType:$,relation:s}=d,a={[`$${$}`]:h},u=C(p,a),f=e?.$fields?.filter(c=>u?.idFields?.includes(c)||u?.idFields?.includes(c.$path)).length===0,l=[];if(typeof e!="string")if(e.$fields)if(f){let c=u.idFields||[];l=[...e.$fields,...c];}else l=e.$fields;else l=ht(u);else l=["id"];return e.$excludedFields&&(l=l.filter(c=>Ue(u,c)?!0:!e.$excludedFields.includes(c.$path))),{$thingType:$,$path:r,$dbPath:i,$as:e.$as||r,$var:r,$thing:h,$fields:l,$excludedFields:e.$excludedFields,$fieldType:"role",$intermediary:s,$justId:o,$id:e.$id,$filter:e.$filter&&ft(e.$filter,u),$idNotIncluded:f,$filterByUnique:$t(e.$filter,u),$playedBy:d,$filterProcessed:!0,$sort:e.$sort,$offset:e.$offset,$limit:e.$limit}})},en=(t,e,r)=>{let n=typeof t=="string"?t:t.$path,o=typeof t=="string",i=e.dataFields?.find(h=>h.path===n),p=e.linkFields?.find(h=>h.path===n),d=e.roles?.[n];if(i){let h=!!i.isVirtual&&!!i.default;return Zi({field:t,fieldStr:n,$justId:o,dbPath:i.dbPath,isVirtual:h})}else {if(p)return Yi({field:t,fieldStr:n,linkField:p,$justId:o,dbPath:p.path,schema:r});if(d)return Gi({field:t,fieldStr:n,roleField:d,$justId:o,dbPath:n,schema:r})}return null};var rn=async(t,e,r)=>r?(i=>immer.produce(i,p=>objectTraversal.traverse(p,({value:d})=>{if(radash.isObject(d)){let h=d;if(!h.$thing)return;if(h.$thing){let $=C(t,h),{virtualFields:s}=$,a=h[v];if(!a)throw new Error("[Internal] QueryPath is missing");let u=objectTraversal.getNodeByPath(e,a),f=u.$fields.map(c=>c.$path),l=u.$excludedFields;s.forEach(c=>{if(l?.includes(c)||f.length>0&&!f.includes(c))return;let m=$.dataFields?.find(y=>y.path===c);if(m?.default){let y=Be({currentThing:h,fieldSchema:m,mandatoryDependencies:!0});h[c]=y;}else if(h[c]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${c}`)}),l&&l.forEach(c=>{if(typeof c!="string")throw new Error("[Internal] ExcludedField is not a string");delete h[c];});}}})))(r):void 0;var sn=t=>{let{queries:e,schema:r}=t;return e.map(n=>ns({query:n,schema:r}))},ns=t=>{let{query:e,schema:r}=t;if(e.$fields.length===0)return null;let n=[];n.push("SELECT");let o=yt({queries:e.$fields,level:1,schema:r});o&&n.push(o);let i=e.$filter&&on(e.$filter,0)||[];return n.push(...i),n.push(`FROM ${e.$thing}`),n.join(`
67
+ `)},yt=t=>{let{queries:e,schema:r,level:n}=t,o=[];return e.forEach(i=>{let p=is({query:i,level:n,schema:r});p&&o.push(p);}),o.length===0?null:o.join(`,
68
+ `)},is=t=>{let{query:e,schema:r,level:n}=t;return e.$fieldType==="data"?ss({query:e,level:n}):e.$fieldType==="link"?os({query:e,level:n,schema:r}):e.$fieldType==="role"?as({query:e,level:n,schema:r}):null},ss=t=>{let{query:e,level:r}=t;return e.$isVirtual?null:e.$path==="id"?q(`meta::id(\`${e.$path}\`) AS ${e.$as}`,r):e.$path===e.$as?q(`\`${e.$path}\``,r):q(`\`${e.$path}\` AS \`${e.$as}\``,r)},os=t=>{let{query:e,schema:r,level:n}=t;if(e.$fields.length===0)return null;let o=[];o.push(q("(",n));let i=n+1;o.push(q("SELECT",i));let p=i+1,d=yt({queries:e.$fields,level:p,schema:r});d&&o.push(d);let h=[e.$playedBy.thing,...an(r,e.$playedBy.thingType,e.$playedBy.thing)],$;return e.$target==="relation"?$=h.map(s=>`<-\`${e.$playedBy.thing}_${e.$plays}\`<-\`${s}\``).join(", "):$=h.map(s=>`<-\`${e.$playedBy.relation}_${e.$plays}\`<-\`${e.$playedBy.relation}\`->\`${e.$playedBy.relation}_${e.$playedBy.plays}\`->\`${s}\``).join(", "),o.push(q(`FROM ${$}`,i)),o.push(q(`) AS \`${e.$as}\``,n)),o.join(`
69
+ `)},as=t=>{let{query:e,schema:r,level:n}=t;if(e.$fields.length===0)return null;let o=[];o.push(q("(",n));let i=n+1;o.push(q("SELECT",i));let p=i+1,d=yt({queries:e.$fields,level:p,schema:r});d&&o.push(d);let $=[e.$playedBy.thing,...an(r,e.$thingType,e.$thing)].map(s=>`->\`${e.$playedBy.relation}_${e.$playedBy.plays}\`->\`${s}\``).join(", ");return o.push(q(`FROM ${$}`,i)),e.$filter&&o.push(...on(e.$filter,i)),o.push(q(`) AS \`${e.$as}\``,n)),o.join(`
70
+ `)},on=(t,e)=>{let r=[],{$not:n,...o}=t,i=e+1;Object.entries(o).forEach(([h,$])=>{r.push(q(`${h}=${JSON.stringify($)}`,i));}),n&&Object.entries(n).forEach(([h,$])=>{r.push(`${h}!=${JSON.stringify($)}`);});let[p,...d]=r;return p?[q("WHERE (",e),q(p,i),...d.map(h=>q(`AND ${h}`,i)),q(")",e)]:r},an=(t,e,r)=>{let n=nn(t,e,r),o=0;for(;n[o];)n.push(...nn(t,e,n[o])),o++;return n},nn=(t,e,r)=>Object.values(e==="entity"?t.entities:t.relations).filter(o=>o.extends===r).map(o=>o.name);var ln=async t=>{let{client:e,queries:r}=t;return await Promise.all(r.map(n=>e.query(n)))};var cn=t=>{let{res:e,queries:r}=t;return e.map((n,o)=>dn(r[o],n))},dn=(t,e)=>e.map(r=>pn(t,r)),pn=(t,e)=>{let r={};return t.$fields.forEach(n=>{let o=n.$as,i=e[o];n.$path==="id"&&t.$idNotIncluded||(r[o]=ls(n,i));}),r},ls=(t,e)=>t.$fieldType==="data"?e??null:t.$justId?t.$filterByUnique?e[0]?.id??null:e?.map(r=>r.id)??[]:t.$filterByUnique?pn(t,e[0]):dn(t,e);var mt=K("error","error",U((t,e)=>({...t,error:e.error}))),cs=be("build",{build:Z(async t=>sn({queries:t.bql.queries,schema:t.schema}),K("done","run",U((t,e)=>({...t,surql:{...t.surql,queries:e.data}}))),mt),run:Z(async t=>ln({client:t.client,queries:le(t.surql.queries)}),K("done","parse",U((t,e)=>({...t,surql:{...t.surql,res:e.data}}))),mt),parse:Z(async t=>cn({res:le(t.surql.res),queries:t.bql.queries,schema:t.schema,config:t.config}),K("done","success",U((t,e)=>({...t,bql:{...t.bql,res:e.data}}))),mt),success:de(),error:de()},t=>t),ds=async t=>new Promise((e,r)=>{fe(cs,n=>{n.machine.state.name==="success"&&e(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},t);}),un=async(t,e,r,n)=>ds({bql:{queries:t},surql:{},schema:e,config:r,client:n,error:null});var gt="___",hn=async t=>{let{queries:e,schema:r}=t;return e.map(n=>ps({query:n,schema:r}))},ps=t=>{let{query:e,schema:r}=t,{$path:n,$thing:o,$filter:i,$fields:p,$sort:d,$offset:h,$limit:$}=e;if(!n)throw new Error("Path is not defined");let s=[],a=e[v];if(s.push("match"),s.push(`$${n} isa ${o};`),i){let l=bt({$filter:i,$var:n,$thing:o,schema:r,depth:0});s.push(`
71
+ ${l}`);}let u=wt({schema:r,$thing:o,$var:n,$sort:d,depth:0});u&&s.push(u.match);let f=`M_${uuid.v4()}`;if(s.push(`?queryPath${f} = "${a}";`),s.push("fetch"),s.push(`?queryPath${f} as "queryPath";`),p){let l=p.filter(y=>y.$fieldType==="data");l&&l.length>0&&s.push(...Bt(l,n,0));let c=p.filter(y=>y.$fieldType==="link");c&&c.length>0&&s.push(...Ft(c,n,n,0,r));let m=p.filter(y=>y.$fieldType==="role");m&&m.length>0&&s.push(...Et(m,n,n,0,r));}return u&&s.push(u.sort),typeof h=="number"&&s.push(`
72
+ offset ${h};`),typeof $=="number"&&s.push(`
73
+ limit ${$};`),s.join(`
74
+ `)},Bt=(t,e,r)=>{let n=[],o=[];for(let $=0;$<t.length;$++)t[$].$isVirtual||n.push(t[$].$dbPath),o.push(`{${t[$].$dbPath}:${t[$].$as}}`);let i=n.join(", "),d=`$metadata:{as:[${o.join(",")}]}`;return [q(`$${e} as "${e}.${d}.$dataFields": ${i};`,r)]},Et=(t,e,r,n,o)=>{let i=n+1,p=[];for(let d of t){let{$fields:h,$as:$,$justId:s,$idNotIncluded:a,$filterByUnique:u,$thing:f,$sort:l,$offset:c,$limit:m}=d,y=d[v],B=`$metadata:{as:${$},justId:${s?"T":"F"},idNotIncluded:${a},filterByUnique:${u}}`;p.push(q(`"${r}.${B}.${d.$var}": {`,n)),p.push(q("match",i));let T=`${e}${gt}${d.$var}`;p.push(q(`$${T} isa ${d.$thing};`,i)),p.push(q(`$${e} (${d.$var}: $${e}${gt}${d.$var}) isa ${d.$intermediary};`,i)),d.$filter&&p.push(bt({$filter:d.$filter,$var:T,$thing:d.$thing,schema:o,depth:i}));let g=wt({schema:o,$thing:f,$var:T,$sort:l,depth:i});if(g&&p.push(g.match),h){let Q=`M_${uuid.v4()}`;p.push(q(`
75
+ ?queryPath${Q} = "${y}";`,i)),p.push(q("fetch",i)),p.push(q(`?queryPath${Q} as "queryPath";`,i));let M=h?.filter(R=>R.$fieldType==="data");M&&M.length>0&&p.push(...Bt(M,T,i));let L=h?.filter(R=>R.$fieldType==="link");L&&L.length>0&&p.push(...Ft(L,T,`${e}.${d.$var}`,i,o));let A=h?.filter(R=>R.$fieldType==="role");A&&A.length>0&&p.push(...Et(A,T,`${e}.${d.$var}`,i,o));}g&&p.push(g.sort),typeof c=="number"&&p.push(q(`offset ${c};`,i)),typeof m=="number"&&p.push(q(`limit ${m};`,i)),p.push(q("};",n));}return p},Ft=(t,e,r,n,o)=>{let i=n+1,p=[];for(let d of t){let{$fields:h,$as:$,$justId:s,$idNotIncluded:a,$filterByUnique:u,$playedBy:f,$thing:l,$sort:c,$offset:m,$limit:y}=d,B=d[v],T=`$metadata:{as:${$},justId:${s?"T":"F"},idNotIncluded:${a},filterByUnique:${u}}`;p.push(q(`"${r}.${T}.${d.$var}": {`,n)),p.push(q("match",i));let g=`${e}${gt}${d.$var}`;p.push(q(`$${g} isa ${d.$thing};`,i)),d.$filter&&p.push(bt({$filter:d.$filter,$var:g,$thing:d.$thing,schema:o,depth:i}));let Q=wt({schema:o,$thing:l,$var:g,$sort:c,depth:i});if(Q&&p.push(Q.match),d.$target==="role"?p.push(q(`$${e}_intermediary (${d.$plays}: $${e}, ${f.plays}: $${g}) isa ${d.$intermediary};`,i)):p.push(`
76
+ $${g} (${d.$plays}: $${e}) isa ${d.$thing};`),h){let M=`M_${uuid.v4()}`;p.push(q(`?queryPath${M} = "${B}";`,i)),p.push(q("fetch",i)),p.push(q(`?queryPath${M} as "queryPath";`,i));let L=h?.filter(D=>D.$fieldType==="data");L&&L.length>0&&p.push(...Bt(L,g,i));let A=h?.filter(D=>D.$fieldType==="link");A&&A.length>0&&p.push(...Ft(A,g,`${e}.${d.$var}`,i,o));let R=h?.filter(D=>D.$fieldType==="role");R&&R.length>0&&p.push(...Et(R,g,`${e}.${d.$var}`,i,o));}Q&&p.push(Q.sort),typeof m=="number"&&p.push(q(`offset ${m};`,i)),typeof y=="number"&&p.push(q(`limit ${y};`,i)),p.push(q("};",n));}return p},bt=t=>{let{$filter:e,$var:r,$thing:n,schema:o,depth:i}=t,{$not:p,...d}=e,h=G(o,n),$=[];return Object.entries(p||{}).forEach(([s,a])=>{if(h.dataFields?.find(l=>l.dbPath===s)){a===null?$.push(q(`$${r} has ${s} $${s}_${uuid.v4()};`,i)):Array.isArray(a)?a.forEach(l=>{$.push(q(`not { $${r} has ${s} ${se(l)}; };`,i));}):$.push(q(`not { $${r} has ${s} ${se(a)}; };`,i));return}let f=h.linkFields?.find(l=>l.path===s);if(f){let[l]=f.oppositeLinkFieldsPlayedBy,m=G(o,l.thing).idFields?.[0];if(!m)throw new Error(`"${l.thing}" does not have an id field`);if(f.target==="relation")a===null?$.push(q(`(${f.plays}: $${r}) isa ${f.relation};`,i)):Array.isArray(a)?a.forEach(y=>{$.push(q(`not { (${f.plays}: $${r}) isa ${f.relation}, has ${m} ${se(y)}; };`,i));}):$.push(q(`not { (${f.plays}: $${r}) isa ${f.relation}, has ${m} ${se(a)}; };`,i));else {let y=`${l.thing}_${uuid.v4()}`;a===null?$.push(q(`$${y} isa ${l.thing}; (${f.plays}: $${r}, ${l.plays}: $${y}) isa ${f.relation};`,i)):Array.isArray(a)?a.forEach(B=>{$.push(q(`not { $${y} isa ${l.thing}, has ${m} ${se(B)}; (${f.plays}: $${r}, ${l.plays}: $${y}) isa ${f.relation}; };`,i));}):$.push(q(`not { $${y} isa ${l.thing}, has ${m} ${se(a)}; (${f.plays}: $${r}, ${l.plays}: $${y}) isa ${f.relation}; };`,i));}return}if(h.thingType==="relation"){let l=h.roles[s];if(l){let[c]=l.playedBy||[],y=G(o,c.thing).idFields?.[0];if(!y)throw new Error(`"${c.thing}" does not have an id field`);let B=`${c.thing}_${uuid.v4()}`;a===null?$.push(q(`$${r} (${c.plays}: ${B});`,i)):Array.isArray(a)?a.forEach(T=>{$.push(q(`not { $${B} isa ${c.thing}, has ${y} ${se(T)}; $${r} (${c.plays}: $${B}); };`,i));}):$.push(q(`not { $${B} isa ${c.thing}, has ${y} ${se(a)}; $${r} (${c.plays}: $${B}); };`,i));return}}}),Object.entries(d).forEach(([s,a])=>{if(h.dataFields?.find(l=>l.dbPath===s)){if(a===null)$.push(q(`not { $${r} has ${s} $${s}_${uuid.v4()}; };`,i));else if(Array.isArray(a)){let l=a.map(m=>`$${r} has ${s} ${se(m)};`),c=Ke(l);c&&$.push(q(c,i));}else $.push(q(`$${r} has ${s} ${se(a)};`,i));return}let f=h.linkFields?.find(l=>l.path===s);if(f){let[l]=f.oppositeLinkFieldsPlayedBy,m=G(o,l.thing).idFields?.[0];if(!m)throw new Error(`"${l.thing}" does not have an id field`);if(f.target==="relation")if(a===null)$.push(q(`not { (${f.plays}: $${r}) isa ${f.relation}; };`,i));else if(Array.isArray(a)){let y=a.map(T=>`(${f.plays}: $${r}) isa ${f.relation}, has ${m} ${se(T)};`),B=Ke(y);B&&$.push(q(B,i));}else $.push(q(`(${f.plays}: $${r}) isa ${f.relation}, has ${m} ${se(a)};`,i));else {let y=`${l.thing}_${uuid.v4()}`;if(a===null)$.push(q(`not { $${y} isa ${l.thing}; (${f.plays}: $${r}, ${l.plays}: $${y}) isa ${f.relation}; };`,i));else if(Array.isArray(a)){let B=a.map(g=>`$${y} isa ${l.thing}, has ${m} ${se(g)}; (${f.plays}: $${r}, ${l.plays}: $${y}) isa ${f.relation};`),T=Ke(B);T&&$.push(q(T,i));}else $.push(q(`$${y} isa ${l.thing}, has ${m} ${se(a)}; (${f.plays}: $${r}, ${l.plays}: $${y}) isa ${f.relation};`,i));}return}if(h.thingType==="relation"){let l=h.roles[s];if(l){let[c]=l.playedBy||[],y=G(o,c.thing).idFields?.[0];if(!y)throw new Error(`"${c.thing}" does not have an id field`);let B=`${c.thing}_${uuid.v4()}`;if(a===null)$.push(q(`not { $${r} (${c.plays}: ${B}); };`,i));else if(Array.isArray(a)){let T=a.map(Q=>`$${B} isa ${c.thing}, has ${y} ${se(Q)}; $${r} (${c.plays}: $${B});`),g=Ke(T);g&&$.push(q(g,i));}else $.push(q(`$${B} isa ${c.thing}, has ${y} ${se(a)}; $${r} (${c.plays}: $${B});`,i));return}}throw new Error(`"${n}" does not have property "${s}"`)}),$.join(`
77
+ `)},Ke=t=>{if(t.length>1)return `{ ${t.join(" } or { ")} };`;let[e]=t;return e},se=t=>typeof t=="string"?`'${t}'`:t instanceof Date?`'${t.toISOString().replace("Z","")}'`:`${t}`,us=t=>typeof t=="string"?{field:t,desc:!1}:{...t,desc:t.desc??!1},wt=t=>{let{$var:e,$thing:r,schema:n,$sort:o,depth:i}=t,p=G(n,r),d=[],h=[];if(o?.forEach($=>{let s=us($),a=p.dataFields?.find(l=>l.path===s.field);if(!a)throw new Error(`"${r}" does not have data field "${s.field}"`);let u=`${s.field}_${uuid.v4()}`;d.push(q("{",i)),d.push(q(`$${e} has ${a.dbPath} $${u}_1;`,i+1)),d.push(q("not {",i+1)),d.push(q(`$${e} has ${a.dbPath} $${u}_2;`,i+2)),d.push(q(`$${u}_2 < $${u}_1;`,i+2)),d.push(q("};",i+1)),d.push(q(`?${u}_ = $${u}_1;`,i+1)),d.push(q("} or {",i)),d.push(q(`not { $${e} has ${a.dbPath} $${u}_1; };`,i+1)),d.push(q(`?${u}_ = "~";`,i+1)),d.push(q("};",i)),d.push(q(`?${u} = ?${u}_;`,i));let f=s.desc?"desc":"asc";h.push(`?${u} ${f}`);}),d.length!==0)return {match:d.join(""),sort:q(`sort ${h.join(", ")};`,i)}};var fn=async t=>{let{enrichedBqlQuery:e,rawBqlRequest:r,schema:n,config:o,rawTqlRes:i}=t;if(e){if(!i)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");return i.map((p,d)=>{let h=r[d],$=e[d];return $s(p,h,$,n,o)})},$s=(t,e,r,n,o)=>t.length===0?null:r.$filterByUnique?$n(t[0],e,n,o):t.map(i=>$n(i,e,n,o)),$n=(t,e,r,n)=>{let{dataFields:o,currentSchema:i,linkFields:p,roleFields:d,schemaValue:h}=Tt(t,r),$=Qt(o,i,n),s=Lt(p,r,n),a=Mt(d,r,n);console.log("parseObj/parsedLinkFields",JSON.stringify(s)),console.log("parseObj/parsedRoleFields",JSON.stringify(a));let u=e?.$fields?.every(l=>!i?.idFields?.includes(typeof l=="string"?l:l.$path));return {...s,...a,...h,...!n.query?.noMetadata&&e.$id?{$id:Array.isArray(e.$id)?$.id:e.$id}:{},...u?Object.fromEntries(Object.entries($).filter(([l])=>!i?.idFields?.includes(l))):$}},Tt=(t,e)=>{let r=Object.keys(t),n=r.find(u=>u.endsWith(".$dataFields"));if(!n)throw new Error("No datafields");let o=t[n],i=n.split(".")[n.split(".").length-2];if(o.$metaData=i,o.length===0)throw new Error("No datafields");let p=o.type,d={$thing:p.label,$thingType:p.root,[v]:t.queryPath.value},h={[`$${d.$thingType}`]:d.$thing},$=C(e,h),s=r.filter(u=>{let f=le(u.split(".").pop());return !u.endsWith(".$dataFields")&&$.linkFields?.some(l=>l.path===f)}).map(u=>{let f=le(u.split(".").pop()),l=le($.linkFields?.find(c=>c.path===f));return {$linkFields:t[u],$key:f,$metaData:u.split(".")[u.split(".").length-2],$cardinality:l.cardinality}}),a=r.filter(u=>{let f=u.split(".").pop();return f&&!u.endsWith(".$dataFields")&&$.thingType==="relation"&&$.roles?.[f]}).map(u=>{let f=le(u.split(".").pop());return {$roleFields:t[u],$key:f,$metaData:u.split(".")[u.split(".").length-2],$cardinality:$.roles[f].cardinality}});return {dataFields:o,schemaValue:d,currentSchema:$,linkFields:s,roleFields:a}},Qt=(t,e,r)=>{let{$metaData:n}=t,{as:o}=fs(n),i=Object.entries(t).filter(([p])=>p!=="type"&&!p.startsWith("$")).map(([p,d])=>{let h=e.dataFields?.find(u=>u.path===p||u.dbPath===p),$=p==="id",s=Array.isArray(o)?o.find(u=>u[p])?.[p]:p,a;if(h?.cardinality==="ONE"){if(a=d[0]?d[0].value:r.query?.returnNulls?null:void 0,h.contentType==="DATE"?a=a&&`${a}Z`:h.contentType==="JSON"&&(a=a&&JSON.parse(a)),$)return [[s,a],["$id",a]].filter(([u,f])=>f!==void 0)}else if(h?.cardinality==="MANY"){if(!radash.isArray(d))throw new Error("Typedb fetch has changed its format");if(d.length===0)return r.query?.returnNulls?[[s,null]]:[];h.contentType==="DATE"?a=d.map(u=>`${u.value}Z`):h.contentType==="JSON"?a=d.map(u=>u.value&&JSON.parse(u.value)):a=d.map(u=>u.value);}return [[s,a]].filter(([u,f])=>f!==void 0)}).flat();return Object.fromEntries([...i])},Mt=(t,e,r)=>{let n={};return t.forEach(o=>{let{$roleFields:i,$metaData:p,$cardinality:d}=o,{as:h,justId:$,idNotIncluded:s,filterByUnique:a}=yn(p);if(h===null){console.log("parseRoleFields/as is null");return}let u=i.map(f=>{let{dataFields:l,currentSchema:c,linkFields:m,roleFields:y,schemaValue:B}=Tt(f,e),T=Qt(l,c,r);if($==="T")return T.id;{let g=Lt(m,e,r),Q=Mt(y,e,r),M={...T};return s==="true"&&c?.idFields?.forEach(L=>delete M[L]),{...M,...g,...Q,...B}}});u.length>0?n[h]=d==="MANY"&&a==="false"?u:u[0]:r.query?.returnNulls&&(n[h]=null);}),n},Lt=(t,e,r)=>{let n={};return t.forEach(o=>{let{$linkFields:i,$metaData:p,$cardinality:d}=o,{as:h,justId:$,idNotIncluded:s,filterByUnique:a}=yn(p);if(h===null){console.log("parseLinkFields/as is null");return}let u=i.map(f=>{let{dataFields:l,currentSchema:c,linkFields:m,roleFields:y,schemaValue:B}=Tt(f,e),T=Qt(l,c,r);if($==="T")return T.id;{let g=Lt(m,e,r),Q=Mt(y,e,r),M={...T};return s==="true"&&c.idFields?.forEach(L=>delete M[L]),{...M,...g,...Q,...B}}});n[h]=u.length>0?d==="MANY"&&a==="false"?u:u[0]:r.query?.returnNulls?null:void 0;}),n},yn=t=>{let e=/as:([a-zA-Z0-9_\-·]+)/,r=/justId:([a-zA-Z0-9_\-·]+)/,n=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,o=/filterByUnique:([a-zA-Z0-9_\-·]+)/,i=t.match(e),p=t.match(r),d=t.match(n),h=t.match(o);return {as:i?i[1]:null,justId:p?p[1]:null,idNotIncluded:d?d[1]:null,filterByUnique:h?h[1]:null}},fs=t=>{try{let r=(o=>{let i=o.replace("$metadata:","");return i=i.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),i=i.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(p,d,h)=>/^{.*}$/.test(h)?`:${h}`:`:${d}"${h}"`),i=i.replace(/\[([^\]]+)\]/g,(p,d)=>`[${d.split(",").map(h=>h.trim().startsWith("{")&&h.trim().endsWith("}")?h.trim():`"${h.trim()}"`).join(",")}]`),i})(t);return JSON.parse(r)}catch(e){return console.error(e),{as:[]}}};var mn=async t=>{let{tqlRequest:e,dbHandles:r,config:n}=t,o=new typedbDriver.TypeDBOptions;o.infer=!0;let{session:i}=await Qe(r,n),p=await i.transaction(typedbDriver.TransactionType.READ,o);if(!p)throw new Error("Can't create transaction");return await radash.parallel(e.length,e,async h=>await p.query.fetch(h).collect())};var Bs=(t,e)=>e.data?{...t,bql:{...t.bql,res:e.data}}:t,Es=(t,e)=>e.data?{...t,tql:{...t.tql,queries:e.data}}:t,Fs=(t,e)=>e.data?{...t,tql:{...t.tql,res:e.data}}:t,kt=K("error","error",U((t,e)=>({...t,error:e.error}))),bs=be("build",{build:Z(async t=>hn({queries:t.bql.queries,schema:t.schema}),K("done","run",U(Es)),kt),run:Z(async t=>mn({dbHandles:t.handles,tqlRequest:le(t.tql.queries),config:t.config}),K("done","parse",U(Fs)),kt),parse:Z(async t=>fn({rawBqlRequest:t.bql.raw,enrichedBqlQuery:t.bql.queries,schema:t.schema,config:t.config,rawTqlRes:le(t.tql.res)}),K("done","success",U(Bs)),kt),success:de(),error:de()},t=>t),ws=async t=>new Promise((e,r)=>{fe(bs,n=>{n.machine.state.name==="success"&&e(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},t);}),gn=async(t,e,r,n,o)=>ws({bql:{raw:t,queries:e},tql:{},schema:r,config:n,handles:o,error:null});var Ts=(t,e)=>e.data?{...t,bql:{...t.bql,queries:e.data}}:t,St=(t,e)=>e.data?{...t,bql:{...t.bql,res:e.data}}:t,Je=K("error","error",U((t,e)=>({...t,error:e.error}))),Qs=be("enrich",{enrich:Z(async t=>tn(t.bql.raw,t.schema),K("done","adapter",U(Ts)),Je),adapter:Z(async t=>{let e={};t.bql.queries?.forEach((d,h)=>{let $=t.bql.raw[h],s=G(t.schema,d.$thing),{id:a}=s.defaultDBConnector;if(s.db==="typeDB"){if(!e[a]){let f=t.handles.typeDB?.get(a)?.client;if(!f)throw new Error(`TypeDB client with id "${s.defaultDBConnector.id}" does not exist`);e[a]={db:"typeDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else if(s.db==="surrealDB"){if(!e[a]){let f=t.handles.surrealDB?.get(a)?.client;if(!f)throw new Error(`SurrealDB client with id "${s.defaultDBConnector.id}" does not exist`);e[a]={db:"surrealDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else throw new Error(`Unsupported DB "${s.db}"`);let u=e[a];u.rawBql.push($),u.bqlQueries.push(d),u.indices.push(h);});let r=Object.values(e),n=r.map(d=>d.db==="typeDB"?gn(d.rawBql,d.bqlQueries,t.schema,t.config,t.handles):un(d.bqlQueries,t.schema,t.config,d.client)),o=await Promise.all(n),i=r.flatMap((d,h)=>{let $=o[h];return d.indices.map((s,a)=>({index:s,result:$[a]}))});return i.sort((d,h)=>d.index<h.index?-1:d.index>h.index?1:0),i.map(({result:d})=>d)},K("done","postHooks",U(St)),Je),postHooks:Z(async t=>rn(t.schema,le(t.bql.queries),le(t.bql.res)),K("done","clean",U(St)),Je),clean:Z(async t=>Yr(t.config,le(t.bql.res)),K("done","success",U(St)),Je),success:de(),error:de()},t=>t),Ms=async t=>new Promise((e,r)=>{fe(Qs,n=>{n.machine.state.name==="success"&&e(n.context),n.machine.state.name==="error"&&r(n.context);},t);}),Bn=async(t,e,r,n)=>Ms({bql:{raw:t},schema:e,config:r,handles:n,error:null});immer.enableMapSet();var qt=class{schema;config;dbHandles;constructor({schema:e,config:r}){this.schema=e,this.config=r;}getDbHandles=()=>this.dbHandles;init=async()=>{let e={typeDB:new Map,surrealDB:new Map};await Promise.all(this.config.dbConnectors.map(async n=>{if(n.provider==="surrealDB"){let o=new surrealdb_node.Surreal;await o.connect(n.url),await o.signin({namespace:n.namespace,database:n.dbName,username:n.username,password:n.password}),e.surrealDB.set(n.id,{client:o});}if(n.provider==="typeDB"&&n.dbName){let[o,i]=await radash.tryit(typedbDriver.TypeDB.coreDriver)(n.url);if(o){let p=`[BORM:${n.provider}:${n.dbName}:core] ${o.message??"Can't create TypeDB Client"}`;throw new Error(p)}try{let p=await i.session(n.dbName,typedbDriver.SessionType.DATA);e.typeDB.set(n.id,{client:i,session:p});}catch(p){let d=`[BORM:${n.provider}:${n.dbName}:session] ${(p.messageTemplate?._messageBody()||p.message)??"Can't create TypeDB Session"}`;throw new Error(d)}}if(n.provider==="typeDBCluster"&&n.dbName){let[o,i]=await radash.tryit(typedbDriver.TypeDB.cloudDriver)(n.addresses,n.credentials);if(o){let p=`[BORM:${n.provider}:${n.dbName}:core] ${o.message??"Can't create TypeDB Cluster Client"}`;throw new Error(p)}try{let p=await i.session(n.dbName,typedbDriver.SessionType.DATA);e.typeDB.set(n.id,{client:i,session:p});}catch(p){let d=`[BORM:${n.provider}:${n.dbName}:session] ${(p.messageTemplate?._messageBody()||p.message)??"Can't create TypeDB Session"}`;throw new Error(d)}}}));let r=xt(this.schema,e);this.schema=r,this.dbHandles=e;};#e=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#e(),this.schema);define=async()=>(await this.#e(),At(this.config,this.schema,this.dbHandles));query=async(e,r)=>{await this.#e();let n={...this.config,query:{...Ye.query,...this.config.query,...r}},o=Array.isArray(e),i=o?e:[e],[p,d]=await radash.tryit(Bn)(i,this.schema,n,this.dbHandles);if(p){let $=new Error(p.error);throw $.stack=p.error.stack,$}let h=d.bql.res;return o?h:h[0]};mutate=async(e,r)=>{await this.#e();let n={...this.config,mutation:{...Ye.mutation,...this.config.mutation,...r}},[o,i]=await radash.tryit(Ur)(e,this.schema,n,this.dbHandles);if(o){let d=new Error(o.error.message);throw d.stack=o.error.stack,d}return i.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:e,session:r})=>{r.isOpen()&&await r.close(),await e.close();});}},Zc=qt;//! Todo: delete when this works with the new $thing and $thingType fields
63
78
  //! Todo: Sandbox the function in nodeCompute() instead of the existing fieldCompute()
64
79
  //! Todo: Sandbox the function in computeFunction()
65
80
  //! reads all the insertions and gets the first match. This means each id must be unique
66
81
  //!old
67
82
 
68
- module.exports = ia;
83
+ module.exports = Zc;