@blitznocode/blitz-orm 0.9.6 → 0.9.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -5,85 +5,64 @@ var typedbDriver = require('typedb-driver');
5
5
  var immer = require('immer');
6
6
  var objectTraversal = require('object-traversal');
7
7
  var uuid = require('uuid');
8
- var Er = require('robot3');
9
8
  var types = require('util/types');
10
9
 
11
- function _interopNamespace(e) {
12
- if (e && e.__esModule) return e;
13
- var n = Object.create(null);
14
- if (e) {
15
- Object.keys(e).forEach(function (k) {
16
- if (k !== 'default') {
17
- var d = Object.getOwnPropertyDescriptor(e, k);
18
- Object.defineProperty(n, k, d.get ? d : {
19
- enumerable: true,
20
- get: function () { return e[k]; }
21
- });
22
- }
23
- });
24
- }
25
- n.default = e;
26
- return Object.freeze(n);
27
- }
28
-
29
- var Er__namespace = /*#__PURE__*/_interopNamespace(Er);
30
-
31
- var qt={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var er=e=>{let t=[],n=new Map;return e.forEach(p=>{let{dbPath:a,contentType:d}=p,s=`${a}-${d}`;n.has(s)||(n.set(s,!0),t.push(p));}),t},Xt=async(e,t,n)=>{let a=(()=>{let h="",m=[];h+=`
32
- `,Object.keys(t.entities).forEach(M=>{let P=t.entities[M],{idFields:R,dataFields:g,linkFields:b,name:k}=P,y=[],I=[],T=[];if("extends"in P){let F=t.entities[P.extends];F.dataFields&&F.dataFields.forEach(w=>{y.push(w.dbPath);}),F.linkFields&&F.linkFields.forEach(w=>{I.push(w.path);}),F.idFields&&F.idFields.forEach(w=>{T.push(w);});}h+=`${k} sub ${"extends"in P?P.extends:"entity"},
33
- `;let A=[];if(R&&R.length>0){let F=new Set(R),Q=Array.from(F).map(C=>`${C}`).join(", ");T.includes(Q)||(h+=` owns ${Q} @key,
34
- `,A.push(Q));}if(g&&g.length>0&&g.forEach(F=>{!y.includes(F.dbPath)&&!A.includes(F.dbPath)&&(h+=` owns ${F.dbPath},
35
- `),m.push({dbPath:F.dbPath,contentType:F.contentType});}),b&&b.length>0){let F=[];b.forEach(w=>{let{relation:Q,plays:C}=w;!I.includes(w.path)&&!F.includes(`${Q}:${C}`)&&(h+=` plays ${Q}:${C},
36
- `,F.push(`${Q}:${C}`));});}h=h.replace(/,\s*$/,`;
10
+ var Nt={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var bn=e=>{let t=[],n=new Map;return e.forEach(o=>{let{dbPath:i,contentType:c}=o,l=`${i}-${c}`;n.has(l)||(n.set(l,!0),t.push(o));}),t},se=async(e,t,n)=>{let i=(()=>{let h="",m=[];h+=`
11
+ `,Object.keys(t.entities).forEach(k=>{let P=t.entities[k],{idFields:C,dataFields:B,linkFields:b,name:L}=P,y=[],I=[],T=[];if("extends"in P){let F=t.entities[P.extends];F.dataFields&&F.dataFields.forEach(w=>{y.push(w.dbPath);}),F.linkFields&&F.linkFields.forEach(w=>{I.push(w.path);}),F.idFields&&F.idFields.forEach(w=>{T.push(w);});}h+=`${L} sub ${"extends"in P?P.extends:"entity"},
12
+ `;let A=[];if(C&&C.length>0){let F=new Set(C),Q=Array.from(F).map(R=>`${R}`).join(", ");T.includes(Q)||(h+=` owns ${Q} @key,
13
+ `,A.push(Q));}if(B&&B.length>0&&B.forEach(F=>{!y.includes(F.dbPath)&&!A.includes(F.dbPath)&&(h+=` owns ${F.dbPath},
14
+ `),m.push({dbPath:F.dbPath,contentType:F.contentType});}),b&&b.length>0){let F=[];b.forEach(w=>{let{relation:Q,plays:R}=w;!I.includes(w.path)&&!F.includes(`${Q}:${R}`)&&(h+=` plays ${Q}:${R},
15
+ `,F.push(`${Q}:${R}`));});}h=h.replace(/,\s*$/,`;
37
16
  `),h+=`
38
- `;}),Object.keys(t.relations).forEach(M=>{let P=t.relations[M],{idFields:R,dataFields:g,roles:b,name:k,linkFields:y}=P,I=[],T=[],A=[],F=[];if("extends"in P){let Q=t.relations[P.extends];Q.dataFields&&Q.dataFields.forEach(C=>{I.push(C.dbPath);}),Q.linkFields&&Q.linkFields.forEach(C=>{T.push(C.dbPath);}),Q.roles&&Object.values(Q.roles).forEach(S=>{A.push(S.name);}),Q.idFields&&Q.idFields.forEach(C=>{F.push(C);});}h+=`${k} sub ${"extends"in P?P.extends:"relation"},
39
- `;let w=[];if(R&&R.length>0){let Q=new Set(R),S=Array.from(Q).map(N=>`${N}`).join(", ");F.includes(S)||(h+=` owns ${S} @key,
40
- `,w.push(S));}if(g&&g.length>0&&g.forEach(Q=>{!I.includes(Q.dbPath)&&!w.includes(Q.dbPath)&&(h+=` owns ${Q.dbPath},
17
+ `;}),Object.keys(t.relations).forEach(k=>{let P=t.relations[k],{idFields:C,dataFields:B,roles:b,name:L,linkFields:y}=P,I=[],T=[],A=[],F=[];if("extends"in P){let Q=t.relations[P.extends];Q.dataFields&&Q.dataFields.forEach(R=>{I.push(R.dbPath);}),Q.linkFields&&Q.linkFields.forEach(R=>{T.push(R.dbPath);}),Q.roles&&Object.values(Q.roles).forEach(O=>{A.push(O.name);}),Q.idFields&&Q.idFields.forEach(R=>{F.push(R);});}h+=`${L} sub ${"extends"in P?P.extends:"relation"},
18
+ `;let w=[];if(C&&C.length>0){let Q=new Set(C),O=Array.from(Q).map(N=>`${N}`).join(", ");F.includes(O)||(h+=` owns ${O} @key,
19
+ `,w.push(O));}if(B&&B.length>0&&B.forEach(Q=>{!I.includes(Q.dbPath)&&!w.includes(Q.dbPath)&&(h+=` owns ${Q.dbPath},
41
20
  `),m.push({dbPath:Q.dbPath,contentType:Q.contentType});}),b&&Object.keys(b).forEach(Q=>{A.includes(Q)||(h+=` relates ${Q},
42
- `);}),y&&y.length>0){let Q=[];y.forEach(C=>{let{plays:S}=C;!T.includes(C.path)&&!Q.includes(`${P}:${S}`)&&(h+=` plays ${C.relation}:${S},
43
- `,Q.push(`${P}:${S}`));});}h=h.replace(/,\s*$/,`;
21
+ `);}),y&&y.length>0){let Q=[];y.forEach(R=>{let{plays:O}=R;!T.includes(R.path)&&!Q.includes(`${P}:${O}`)&&(h+=` plays ${R.relation}:${O},
22
+ `,Q.push(`${P}:${O}`));});}h=h.replace(/,\s*$/,`;
44
23
  `),h+=`
45
24
  `;});let E=`define
46
25
 
47
- `;return er(m).forEach(M=>{E+=`${M.dbPath} sub attribute,
48
- `,M.contentType==="TEXT"||M.contentType==="ID"?E+=` value string;
49
- `:M.contentType==="EMAIL"?(E+=` value string,
26
+ `;return bn(m).forEach(k=>{E+=`${k.dbPath} sub attribute,
27
+ `,k.contentType==="TEXT"||k.contentType==="ID"?E+=` value string;
28
+ `:k.contentType==="EMAIL"?(E+=` value string,
50
29
  `,E+=` regex '^(?=.{1,64}@)[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*@[^-][A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$';
51
- `):M.contentType==="DATE"?E+=` value datetime;
52
- `:M.contentType==="BOOLEAN"?E+=` value boolean;
53
- `:M.contentType==="NUMBER"&&(E+=` value long;
30
+ `):k.contentType==="DATE"?E+=` value datetime;
31
+ `:k.contentType==="BOOLEAN"?E+=` value boolean;
32
+ `:k.contentType==="NUMBER"&&(E+=` value long;
54
33
  `);}),`${E}
55
34
 
56
- ${h}`})(),d=e.dbConnectors[0].id,s=n.typeDB.get(d)?.session,B=n.typeDB.get(d)?.client;if(!s){console.log("Session Status: ","NO SESSION");return}await s.close();let[{dbName:L}]=e.dbConnectors;await(await B.databases.get(L)).delete(),await B.databases.create(L);let r=await B.session(e.dbConnectors[0].dbName,typedbDriver.SessionType.SCHEMA),l=await r.transaction(typedbDriver.TransactionType.WRITE);await l.query.define(a),await l.commit(),await l.close();let o=await r.transaction(typedbDriver.TransactionType.READ);(await(await o.query.match("match $a sub thing;")).collect()).forEach(async h=>{h.get("a");}),await o.close();};var te={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var re=(e,t,n)=>n?t:`${e}\xB7${t}`;var ne=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([n,p])=>t(n,p))))[0],mt=(e,t)=>Object.fromEntries(Object.entries(e).filter(([n,p])=>t(n,p))),ie=(e,t)=>{let n=[],p=immer.produce(e,d=>objectTraversal.traverse(d,({key:s,value:B,meta:L})=>{if(L.depth===2&&(s&&(B.dataFields=B.dataFields?.map(u=>({...u,cardinality:u.cardinality||"ONE",dbPath:re(s,u.path,u.shared)}))),B.extends)){let u=d.entities[B.extends]||d.relations[B.extends];if(B.allExtends=[B.extends,...u.allExtends||[]],B.idFields=u.idFields?(B.idFields||[]).concat(u.idFields):B.idFields,B.dataFields=u.dataFields?(B.dataFields||[]).concat(u.dataFields.map(r=>{let l=B.extends,o=e.entities[l]||e.relations[l];for(;!o.dataFields?.find(f=>f.path===r.path);)l="extends"in o?o.extends:void 0,o=e.entities[l]||e.relations[l];return {...r,dbPath:re(l,r.path,r.shared)}})):B.dataFields,B.linkFields=u.linkFields?(B.linkFields||[]).concat(u.linkFields):B.linkFields,"roles"in u){let r=B,l=u;r.roles=r.roles||{},r.roles={...r.roles,...l.roles},Object.keys(r.roles).length===0&&(r.roles={});}}},{traversalType:"breadth-first"}));return objectTraversal.traverse(e,({key:d,value:s,meta:B})=>{if(d==="linkFields"){let u=(()=>{if(!B.nodePath)throw new Error("No path");let[l,o]=B.nodePath.split(".");return {thing:o,thingType:l==="entities"?"entity":l==="relations"?"relation":""}})(),r=Array.isArray(s)?s.map(l=>({...l,...u})):[{...s,...u}];n.push(...r);}}),immer.produce(p,d=>objectTraversal.traverse(d,({value:s,key:B,meta:L})=>{if(L.depth===2&&s.idFields&&!s.id){s.name=B;let u=()=>{if(L.nodePath?.split(".")[0]==="entities")return "entity";if(L.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};s.thingType=u();let r=Object.keys(t).find(l=>t[l].get(s.defaultDBConnector.id));s.db=r,s.dbContext=te[r],s.computedFields=[],s.virtualFields=[],s.requiredFields=[],s.enumFields=[],s.fnValidatedFields=[],"roles"in s&&Object.entries(s.roles).forEach(([o,f])=>{f.fieldType="roleField",f.playedBy=n.filter(c=>c.relation===B&&c.plays===o)||[],f.name=o;}),"linkFields"in s&&s.linkFields&&s.linkFields?.forEach(o=>{if(o.fieldType="linkField",o.target==="relation"){o.oppositeLinkFieldsPlayedBy=[{plays:o.path,thing:o.relation,thingType:"relation"}];return}let f=n.filter(i=>i.relation===o.relation&&i.plays!==o.plays)||[];o.oppositeLinkFieldsPlayedBy=f;let{filter:c}=o;o.oppositeLinkFieldsPlayedBy=o.oppositeLinkFieldsPlayedBy.filter(i=>i.target==="role"),c&&Array.isArray(c)&&(o.oppositeLinkFieldsPlayedBy=o.oppositeLinkFieldsPlayedBy.filter(i=>c.some(h=>i.thing===h.$role)),o.oppositeLinkFieldsPlayedBy=o.oppositeLinkFieldsPlayedBy.filter(i=>c.some(h=>i.thing===h.$thing))),c&&!Array.isArray(c)&&(o.oppositeLinkFieldsPlayedBy=o.oppositeLinkFieldsPlayedBy.filter(i=>i.$role===c.$role),o.oppositeLinkFieldsPlayedBy=o.oppositeLinkFieldsPlayedBy.filter(i=>i.thing===c.$thing));});}if(typeof s=="object"&&"playedBy"in s){if([...new Set(s.playedBy?.map(u=>u.thing))].length>1)throw new Error(`Unsupported: roleFields can be only played by one thing. Role: ${B} path:${L.nodePath}`);if(s.playedBy.length===0)throw new Error(`Unsupported: roleFields should be played at least by one thing. Role: ${B}, path:${L.nodePath}`)}if(L.depth===4){let[u,r]=L.nodePath?.split(".")||[],l=d[u][r];s.validations&&(s.validations.required&&l.requiredFields.push(s.path),s.validations.enum&&l.enumFields.push(s.path),s.validations.fn&&l.fnValidatedFields.push(s.path)),s.default?s.isVirtual?l.virtualFields.push(s.path):l.computedFields.push(s.path):s.isVirtual&&l.virtualFields.push(s.path);}}))},O=(e,t)=>{if(!t)throw new Error("[Internal] No node for getCurrentSchema");if(t.$thing){if(t.$thingType==="entity"){if(!(t.$thing in e.entities))throw new Error(`Missing entity '${t.$thing}' in the schema`);return e.entities[t.$thing]}if(t.$thingType==="relation"){if(!(t.$thing in e.relations))throw new Error(`Missing relation '${t.$thing}' in the schema`);return e.relations[t.$thing]}if(t.$thing in e.entities&&t.$thing in e.relations)throw new Error(`Ambiguous $thing ${t.$thing}`);if(t.$thing in e.entities)return e.entities[t.$thing];if(t.$thing in e.relations)return e.relations[t.$thing];throw new Error(`Wrong schema or query for ${JSON.stringify(t,null,2)}`)}if(t.$entity){if(!(t.$entity in e.entities))throw new Error(`Missing entity '${t.$entity}' in the schema`);return e.entities[t.$entity]}if(t.$relation){if(!(t.$relation in e.relations))throw new Error(`Missing relation '${t.$relation}' in the schema`);return e.relations[t.$relation]}throw new Error(`Wrong schema or query for ${JSON.stringify(t,null,2)}`)},oe=(e,t)=>{let n=e.$thing||e.$entity||e.$relation;if(!n)throw new Error("[Internal] No thing found");if(e.$entity)return "entity";if(e.$relation)return "relation";if(t.entities[n])return "entity";if(t.relations[n])return "relation";throw new Error("No thing found")},xt=(e,t,n)=>{let p=O(e,t),a=p.linkFields?.find(B=>B.path===n);if(a)return a;let d=p.dataFields?.find(B=>B.path===n);if(d)return d;let s="roles"in p?p.roles?.[n]:void 0;if(s)return s},jt=(e,t,n)=>xt(e,t,n)?.cardinality,U=(e,t)=>{let n=e.dataFields?.map(c=>c.path)||[],p=e.linkFields?.map(c=>c.path)||[],a="roles"in e?radash.listify(e.roles,c=>c):[],d=[...n||[],...p||[],...a||[]],B=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...d];if(!t)return {fields:d,dataFields:n,roleFields:a,linkFields:p};let L=t.$fields?t.$fields.map(c=>{if(typeof c=="string")return c.startsWith("$")?void 0:c;if("$path"in c&&typeof c.$path=="string")return c.$path;throw new Error(" Wrongly structured query")}):radash.listify(t,c=>c.startsWith("$")?void 0:c).filter(c=>c!==void 0),u=t.$filter?radash.listify(t.$filter,c=>c.toString().startsWith("$")?void 0:c.toString()).filter(c=>c&&n?.includes(c)):[],r=t.$filter?radash.listify(t.$filter,c=>c.toString().startsWith("$")?void 0:c.toString()).filter(c=>c&&[...a||[],...p||[]].includes(c)):[],l=[...L,...u].filter(c=>!B.includes(c)).filter(c=>c),o=t.$filter?mt(t.$filter,(c,i)=>u.includes(c)):{},f=t.$filter?mt(t.$filter,(c,i)=>r.includes(c)):{};return {fields:d,dataFields:n,roleFields:a,linkFields:p,usedFields:L,usedLinkFields:p.filter(c=>L.includes(c)),usedRoleFields:a.filter(c=>L.includes(c)),usedDataFields:n.filter(c=>L.includes(c)),unidentifiedFields:l,...u.length?{localFilters:o}:{},...r.length?{nestedFilters:f}:{}}};var se=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},ae=(e,t,n)=>{let a=(n.nodePath||"").split("."),d=radash.isArray(t)?a.slice(0,-2).join("."):a.slice(0,-1).join(".");return t?objectTraversal.getNodeByPath(e,d):{}},J=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,n)=>(t[n]=e[n],t),{});var wt=e=>radash.isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),K=e=>{if(Array.isArray(e))return e.map(t=>K(t));if(e&&typeof e=="object"){let t=immer.isDraft(e)?immer.current(e):e,n={};return Object.entries(t).forEach(([p,a])=>{n[p]=K(a);}),n}else return e};var H=Symbol.for("queryPath"),bt=Symbol.for("stepPrint"),ot=Symbol.for("edgeType"),tt=Symbol.for("edgeSchema");var _="___",le=async e=>{let{enrichedBqlQuery:t}=e;if(!t)throw new Error("BQL query not enriched");let n="",p=(r,l)=>{let o="",f="";for(let c in r){let i=r[c];if(Array.isArray(i))for(let h=0;h<i.length;h++)f+=`{$${l} has ${c} "${i[h]}";}`,h<i.length-1?f+="or":f+=";";else o+=`, has ${c} "${i}"`;}o+=`;
57
- `,n+=o,n+=f;},a=(r,l)=>{let o=[],f=[],c="";for(let m=0;m<r.length;m++)r[m].$isVirtual||o.push(` ${r[m].$dbPath}`),f.push(`{${r[m].$dbPath}:${r[m].$as}}`);let i=`${o.join(",")};
58
- `;c=f.join(",");let h=`$metadata:{as:[${c}]}`;n+=`$${l} as "${l}.${h}.$dataFields": `,n+=i;},d=(r,l,o)=>{for(let f of r){let{$fields:c,$as:i,$justId:h,$idNotIncluded:m,$filterByUnique:E}=f,$=f[H],M=`$metadata:{as:${i},justId:${h?"T":"F"},idNotIncluded:${m},filterByUnique:${E}}`;if(n+=`"${o}.${M}.${f.$var}":{
35
+ ${h}`})(),c=e.dbConnectors[0].id,l=n.typeDB.get(c)?.session,g=n.typeDB.get(c)?.client;if(!l){console.log("Session Status: ","NO SESSION");return}await l.close();let[{dbName:M}]=e.dbConnectors;await(await g.databases.get(M)).delete(),await g.databases.create(M);let r=await g.session(e.dbConnectors[0].dbName,typedbDriver.SessionType.SCHEMA),d=await r.transaction(typedbDriver.TransactionType.WRITE);await d.query.define(i),await d.commit(),await d.close();let a=await r.transaction(typedbDriver.TransactionType.READ);(await(await a.query.match("match $a sub thing;")).collect()).forEach(async h=>{h.get("a");}),await a.close();};var ae={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var ce=(e,t,n)=>n?t:`${e}\xB7${t}`;var de=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([n,o])=>t(n,o))))[0],Bt=(e,t)=>Object.fromEntries(Object.entries(e).filter(([n,o])=>t(n,o))),pe=(e,t)=>{let n=[],o=immer.produce(e,c=>objectTraversal.traverse(c,({key:l,value:g,meta:M})=>{if(M.depth===2&&(l&&(g.dataFields=g.dataFields?.map(u=>({...u,cardinality:u.cardinality||"ONE",dbPath:ce(l,u.path,u.shared)}))),g.extends)){let u=c.entities[g.extends]||c.relations[g.extends];if(g.allExtends=[g.extends,...u.allExtends||[]],g.idFields=u.idFields?(g.idFields||[]).concat(u.idFields):g.idFields,g.dataFields=u.dataFields?(g.dataFields||[]).concat(u.dataFields.map(r=>{let d=g.extends,a=e.entities[d]||e.relations[d];for(;!a.dataFields?.find(f=>f.path===r.path);)d="extends"in a?a.extends:void 0,a=e.entities[d]||e.relations[d];return {...r,dbPath:ce(d,r.path,r.shared)}})):g.dataFields,g.linkFields=u.linkFields?(g.linkFields||[]).concat(u.linkFields):g.linkFields,"roles"in u){let r=g,d=u;r.roles=r.roles||{},r.roles={...r.roles,...d.roles},Object.keys(r.roles).length===0&&(r.roles={});}}},{traversalType:"breadth-first"}));return objectTraversal.traverse(e,({key:c,value:l,meta:g})=>{if(c==="linkFields"){let u=(()=>{if(!g.nodePath)throw new Error("No path");let[d,a]=g.nodePath.split(".");return {thing:a,thingType:d==="entities"?"entity":d==="relations"?"relation":""}})(),r=Array.isArray(l)?l.map(d=>({...d,...u})):[{...l,...u}];n.push(...r);}}),immer.produce(o,c=>objectTraversal.traverse(c,({value:l,key:g,meta:M})=>{if(M.depth===2&&l.idFields&&!l.id){l.name=g;let u=()=>{if(M.nodePath?.split(".")[0]==="entities")return "entity";if(M.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};l.thingType=u();let r=Object.keys(t).find(d=>t[d].get(l.defaultDBConnector.id));l.db=r,l.dbContext=ae[r],l.computedFields=[],l.virtualFields=[],l.requiredFields=[],l.enumFields=[],l.fnValidatedFields=[],"roles"in l&&Object.entries(l.roles).forEach(([a,f])=>{f.fieldType="roleField",f.playedBy=n.filter(p=>p.relation===g&&p.plays===a)||[],f.name=a;}),"linkFields"in l&&l.linkFields&&l.linkFields?.forEach(a=>{if(a.fieldType="linkField",a.target==="relation"){a.oppositeLinkFieldsPlayedBy=[{plays:a.path,thing:a.relation,thingType:"relation"}];return}let f=n.filter(s=>s.relation===a.relation&&s.plays!==a.plays)||[];a.oppositeLinkFieldsPlayedBy=f;let{filter:p}=a;a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter(s=>s.target==="role"),p&&Array.isArray(p)&&(a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter(s=>p.some(h=>s.thing===h.$role)),a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter(s=>p.some(h=>s.thing===h.$thing))),p&&!Array.isArray(p)&&(a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter(s=>s.$role===p.$role),a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter(s=>s.thing===p.$thing));});}if(typeof l=="object"&&"playedBy"in l){if([...new Set(l.playedBy?.map(u=>u.thing))].length>1)throw new Error(`Unsupported: roleFields can be only played by one thing. Role: ${g} path:${M.nodePath}`);if(l.playedBy.length===0)throw new Error(`Unsupported: roleFields should be played at least by one thing. Role: ${g}, path:${M.nodePath}`)}if(M.depth===4){let[u,r]=M.nodePath?.split(".")||[],d=c[u][r];l.validations&&(l.validations.required&&d.requiredFields.push(l.path),l.validations.enum&&d.enumFields.push(l.path),l.validations.fn&&d.fnValidatedFields.push(l.path)),l.default?l.isVirtual?d.virtualFields.push(l.path):d.computedFields.push(l.path):l.isVirtual&&d.virtualFields.push(l.path);}}))},S=(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)}`)},ue=(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")},_t=(e,t,n)=>{let o=S(e,t),i=o.linkFields?.find(g=>g.path===n);if(i)return i;let c=o.dataFields?.find(g=>g.path===n);if(c)return c;let l="roles"in o?o.roles?.[n]:void 0;if(l)return l},Wt=(e,t,n)=>_t(e,t,n)?.cardinality,J=(e,t)=>{let n=e.dataFields?.map(p=>p.path)||[],o=e.linkFields?.map(p=>p.path)||[],i="roles"in e?radash.listify(e.roles,p=>p):[],c=[...n||[],...o||[],...i||[]],g=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...c];if(!t)return {fields:c,dataFields:n,roleFields:i,linkFields:o};let M=t.$fields?t.$fields.map(p=>{if(typeof p=="string")return p.startsWith("$")?void 0:p;if("$path"in p&&typeof p.$path=="string")return p.$path;throw new Error(" Wrongly structured query")}):radash.listify(t,p=>p.startsWith("$")?void 0:p).filter(p=>p!==void 0),u=t.$filter?radash.listify(t.$filter,p=>p.toString().startsWith("$")?void 0:p.toString()).filter(p=>p&&n?.includes(p)):[],r=t.$filter?radash.listify(t.$filter,p=>p.toString().startsWith("$")?void 0:p.toString()).filter(p=>p&&[...i||[],...o||[]].includes(p)):[],d=[...M,...u].filter(p=>!g.includes(p)).filter(p=>p),a=t.$filter?Bt(t.$filter,(p,s)=>u.includes(p)):{},f=t.$filter?Bt(t.$filter,(p,s)=>r.includes(p)):{};return {fields:c,dataFields:n,roleFields:i,linkFields:o,usedFields:M,usedLinkFields:o.filter(p=>M.includes(p)),usedRoleFields:i.filter(p=>M.includes(p)),usedDataFields:n.filter(p=>M.includes(p)),unidentifiedFields:d,...u.length?{localFilters:a}:{},...r.length?{nestedFilters:f}:{}}};var he=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},fe=(e,t,n)=>{let i=(n.nodePath||"").split("."),c=radash.isArray(t)?i.slice(0,-2).join("."):i.slice(0,-1).join(".");return t?objectTraversal.getNodeByPath(e,c):{}},Z=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,n)=>(t[n]=e[n],t),{});var Mt=e=>radash.isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),U=e=>{if(Array.isArray(e))return e.map(t=>U(t));if(e&&typeof e=="object"){let t=immer.isDraft(e)?immer.current(e):e,n={};return Object.entries(t).forEach(([o,i])=>{n[o]=U(i);}),n}else return e};var K=Symbol.for("queryPath"),kt=Symbol.for("stepPrint"),at=Symbol.for("edgeType"),rt=Symbol.for("edgeSchema");var v="___",$e=async e=>{let{enrichedBqlQuery:t}=e;if(!t)throw new Error("BQL query not enriched");let n="",o=(r,d)=>{let a="",f="";for(let p in r){let s=r[p];if(Array.isArray(s))for(let h=0;h<s.length;h++)f+=`{$${d} has ${p} "${s[h]}";}`,h<s.length-1?f+="or":f+=";";else a+=`, has ${p} "${s}"`;}a+=`;
36
+ `,n+=a,n+=f;},i=(r,d)=>{let a=[],f=[],p="";for(let m=0;m<r.length;m++)r[m].$isVirtual||a.push(` ${r[m].$dbPath}`),f.push(`{${r[m].$dbPath}:${r[m].$as}}`);let s=`${a.join(",")};
37
+ `;p=f.join(",");let h=`$metadata:{as:[${p}]}`;n+=`$${d} as "${d}.${h}.$dataFields": `,n+=s;},c=(r,d,a)=>{for(let f of r){let{$fields:p,$as:s,$justId:h,$idNotIncluded:m,$filterByUnique:E}=f,$=f[K],k=`$metadata:{as:${s},justId:${h?"T":"F"},idNotIncluded:${m},filterByUnique:${E}}`;if(n+=`"${a}.${k}.${f.$var}":{
59
38
  `,n+=` match
60
- `,f.$filter&&(n+=` $${l}${_}${f.$var} isa ${f.$thing}`,p(f.$filter,`${l}${_}${f.$var}`)),n+=` $${l} (${f.$var}: $${l}${_}${f.$var}) isa ${f.$intermediary};
61
- `,c){let P=`M_${uuid.v4()}`;n+=`?queryPath${P} = "${$}";
39
+ `,f.$filter&&(n+=` $${d}${v}${f.$var} isa ${f.$thing}`,o(f.$filter,`${d}${v}${f.$var}`)),n+=` $${d} (${f.$var}: $${d}${v}${f.$var}) isa ${f.$intermediary};
40
+ `,p){let P=`M_${uuid.v4()}`;n+=`?queryPath${P} = "${$}";
62
41
  `,n+=` fetch
63
42
  `,n+=`?queryPath${P} as "queryPath"
64
- ;`;let R=c?.filter(k=>k.$fieldType==="data");R&&R.length>0&&a(R,`${l}${_}${f.$var}`,`${l}.${f.$var}`);let g=c?.filter(k=>k.$fieldType==="link");g&&g.length>0&&s(g,`${l}${_}${f.$var}`,`${l}.${f.$var}`);let b=c?.filter(k=>k.$fieldType==="role");b&&b.length>0&&d(b,`${l}${_}${f.$var}`,`${l}.${f.$var}`);}n+=`};
65
- `;}},s=(r,l,o)=>{for(let f of r){let{$fields:c,$as:i,$justId:h,$idNotIncluded:m,$filterByUnique:E,$playedBy:$}=f,M=f[H],P=`$metadata:{as:${i},justId:${h?"T":"F"},idNotIncluded:${m},filterByUnique:${E}}`;if(n+=`"${o}.${P}.${f.$var}":{
43
+ ;`;let C=p?.filter(L=>L.$fieldType==="data");C&&C.length>0&&i(C,`${d}${v}${f.$var}`,`${d}.${f.$var}`);let B=p?.filter(L=>L.$fieldType==="link");B&&B.length>0&&l(B,`${d}${v}${f.$var}`,`${d}.${f.$var}`);let b=p?.filter(L=>L.$fieldType==="role");b&&b.length>0&&c(b,`${d}${v}${f.$var}`,`${d}.${f.$var}`);}n+=`};
44
+ `;}},l=(r,d,a)=>{for(let f of r){let{$fields:p,$as:s,$justId:h,$idNotIncluded:m,$filterByUnique:E,$playedBy:$}=f,k=f[K],P=`$metadata:{as:${s},justId:${h?"T":"F"},idNotIncluded:${m},filterByUnique:${E}}`;if(n+=`"${a}.${P}.${f.$var}":{
66
45
  `,n+=` match
67
- `,f.$filter&&(n+=` $${l}${_}${f.$var} isa ${f.$thing}`,p(f.$filter,`${l}${_}${f.$var}`)),f.$target==="role"?n+=` $${l}_intermediary (${f.$plays}: $${l}, ${$.plays}: $${l}${_}${f.$var}) isa ${f.$intermediary};
68
- `:n+=` $${l}${_}${f.$var} (${f.$plays}: $${l}) isa ${f.$thing};
69
- `,c){let R=`M_${uuid.v4()}`;n+=`?queryPath${R} = "${M}";
46
+ `,f.$filter&&(n+=` $${d}${v}${f.$var} isa ${f.$thing}`,o(f.$filter,`${d}${v}${f.$var}`)),f.$target==="role"?n+=` $${d}_intermediary (${f.$plays}: $${d}, ${$.plays}: $${d}${v}${f.$var}) isa ${f.$intermediary};
47
+ `:n+=` $${d}${v}${f.$var} (${f.$plays}: $${d}) isa ${f.$thing};
48
+ `,p){let C=`M_${uuid.v4()}`;n+=`?queryPath${C} = "${k}";
70
49
  `,n+=` fetch
71
- `,n+=`?queryPath${R} as "queryPath"
72
- ;`;let g=c?.filter(y=>y.$fieldType==="data");g&&g.length>0&&a(g,`${l}${_}${f.$var}`);let b=c?.filter(y=>y.$fieldType==="link");b&&b.length>0&&s(b,`${l}${_}${f.$var}`,`${l}.${f.$var}`);let k=c?.filter(y=>y.$fieldType==="role");k&&k.length>0&&d(k,`${l}${_}${f.$var}`,`${l}.${f.$var}`);}n+=`};
73
- `;}},B=t.length>1,L=[];(r=>{if(B)for(let l of r){let{$path:o,$thing:f,$filter:c,$fields:i}=l;if(!o)throw new Error("Path is not defined");let h=l[H];n+=`match
74
- $${o} isa ${f} `,c?p(c,o):n+="; ";let m=`M_${uuid.v4()}`;if(n+=`?queryPath${m} = "${h}";
50
+ `,n+=`?queryPath${C} as "queryPath"
51
+ ;`;let B=p?.filter(y=>y.$fieldType==="data");B&&B.length>0&&i(B,`${d}${v}${f.$var}`);let b=p?.filter(y=>y.$fieldType==="link");b&&b.length>0&&l(b,`${d}${v}${f.$var}`,`${d}.${f.$var}`);let L=p?.filter(y=>y.$fieldType==="role");L&&L.length>0&&c(L,`${d}${v}${f.$var}`,`${d}.${f.$var}`);}n+=`};
52
+ `;}},g=t.length>1,M=[];(r=>{if(g)for(let d of r){let{$path:a,$thing:f,$filter:p,$fields:s}=d;if(!a)throw new Error("Path is not defined");let h=d[K];n+=`match
53
+ $${a} isa ${f} `,p?o(p,a):n+="; ";let m=`M_${uuid.v4()}`;if(n+=`?queryPath${m} = "${h}";
75
54
  `,n+=`fetch
76
55
  `,n+=`?queryPath${m} as "queryPath"
77
- ;`,i){let E=i.filter(P=>P.$fieldType==="data");E&&E.length>0&&a(E,o);let $=i.filter(P=>P.$fieldType==="link");$&&$.length>0&&s($,o,o);let M=i.filter(P=>P.$fieldType==="role");M&&M.length>0&&d(M,o,o);}L.push(n),n="";}else for(let l of r){let{$path:o,$thing:f,$filter:c,$fields:i}=l;if(!o||o==="undefined")throw new Error("Path is not defined");let h=l[H];if(n+=`match
78
- $${o} isa ${f} `,c?p(c,o):n+="; ",n+=`?queryPath = "${h}";
56
+ ;`,s){let E=s.filter(P=>P.$fieldType==="data");E&&E.length>0&&i(E,a);let $=s.filter(P=>P.$fieldType==="link");$&&$.length>0&&l($,a,a);let k=s.filter(P=>P.$fieldType==="role");k&&k.length>0&&c(k,a,a);}M.push(n),n="";}else for(let d of r){let{$path:a,$thing:f,$filter:p,$fields:s}=d;if(!a||a==="undefined")throw new Error("Path is not defined");let h=d[K];if(n+=`match
57
+ $${a} isa ${f} `,p?o(p,a):n+="; ",n+=`?queryPath = "${h}";
79
58
  `,n+=`fetch
80
59
  `,n+=`?queryPath as "queryPath"
81
- ;`,i){let m=i.filter(M=>M.$fieldType==="data");m&&m.length>0&&a(m,o);let E=i.filter(M=>M.$fieldType==="link");E&&E.length>0&&s(E,o,o);let $=i.filter(M=>M.$fieldType==="role");$&&$.length>0&&d($,o,o);}}})(t),e.tqlRequest=B?L:n;};var zt=e=>{let t=e.dataFields?.map(d=>d.path)||[],n=e.linkFields?.map(d=>d.path)||[],p=Object.keys(e.roles||{})||[];return [...t,...n,...p]},vt=(e,t)=>Object.keys(e||{}).some(p=>{if(!Array.isArray(e[p])){let a=t.idFields?.includes(p),d=t.dataFields?.some(s=>(s.dbPath===p||s.path===p)&&s?.validations?.unique);return a||d}return !1}),Wt=(e,t)=>{let n=t.dataFields?.map(s=>({path:s.path,dbPath:s.dbPath}))||[],p=t.linkFields?.map(s=>({path:s.path,dbPath:s.dbPath}))||[],a=Object.keys(t.roles||{}).map(s=>({path:s,dbPath:s}))||[],d=[...n,...p,...a];return Object.entries(e||{}).reduce((s,[B,L])=>{let u=d.find(r=>r.path===B);return s[u?.dbPath||B]=L,s},{})},de=async e=>{let{rawBqlRequest:t,schema:n}=e;if(Array.isArray(t)){for(let r of t)if(!("$entity"in r)&&!("$relation"in r)&&(!("$thing"in r)||!("$thingType"in r)))throw new Error("No entity specified in query")}else if(!("$entity"in t)&&!("$relation"in t)&&(!("$thing"in t)||!("$thingType"in t)))throw new Error("No entity specified in query");let p=(r,l)=>typeof l=="string"?r.idFields?.includes(l):r.idFields?.includes(l.$path),a=(r,l,o,f,c)=>({$path:l,$dbPath:f,$thingType:"attribute",$as:r.$as||l,$var:l,$fieldType:"data",$excludedFields:r.$excludedFields,$justId:o,$id:r.$id,$filter:r.$filter,$isVirtual:c,$filterProcessed:!0}),d=(r,l,o,f,c)=>{let{target:i,oppositeLinkFieldsPlayedBy:h}=o;return h.map(m=>{let E=i==="role"?m.thingType:"relation",$=i==="role"?m.thing:o.relation,M={[`$${E}`]:$},P=O(n,M),R=r?.$fields?.filter(b=>p(P,b)).length===0,g=[];return typeof r!="string"?r.$fields?R?g=[...r.$fields,...P.idFields]:g=r.$fields:g=zt(P):g=["id"],r.$excludedFields&&(g=g.filter(b=>p(P,b)?!0:!r.$excludedFields.includes(b.$path))),{$thingType:E,$plays:o.plays,$playedBy:m,$path:m.path,$dbPath:c,$as:r.$as||l,$var:l,$thing:$,$fields:g,$excludedFields:r.$excludedFields,$fieldType:"link",$target:i,$intermediary:m.relation,$justId:f,$id:r.$id,$filter:Wt(r.$filter,P),$idNotIncluded:R,$filterByUnique:vt(r.$filter,P),$filterProcessed:!0}})},s=(r,l,o,f,c)=>o.playedBy.map(i=>{let{thing:h,thingType:m,relation:E}=i,$={[`$${m}`]:h},M=O(n,$),P=r?.$fields?.filter(g=>M?.idFields?.includes(g)||M?.idFields?.includes(g.$path)).length===0,R=[];return typeof r!="string"?r.$fields?P?R=[...r.$fields,...M.idFields]:R=r.$fields:R=zt(M):R=["id"],r.$excludedFields&&(R=R.filter(g=>p(M,g)?!0:!r.$excludedFields.includes(g.$path))),{$thingType:m,$path:l,$dbPath:c,$as:r.$as||l,$var:l,$thing:h,$fields:R,$excludedFields:r.$excludedFields,$fieldType:"role",$intermediary:E,$justId:f,$id:r.$id,$filter:Wt(r.$filter,M),$idNotIncluded:P,$filterByUnique:vt(r.$filter,M),$playedBy:i,$filterProcessed:!0}}),B=(r,l)=>{let o=typeof r=="string"?r:r.$path,f=typeof r=="string",c=l.dataFields?.find(m=>m.path===o),i=l.linkFields?.find(m=>m.path===o),h=l.roles?.[o];if(c){let m=c.isVirtual&&c.default;return a(r,o,f,c.dbPath,m)}else {if(i)return d(r,o,i,f,i.dbPath);if(h)return s(r,o,h,f,h.dbPath)}return null},u=(r=>immer.produce(r,l=>objectTraversal.traverse(l,o=>{let{value:f,meta:c}=o,i=f;if(radash.isObject(i)){if(i.$id){let h=i.$entity||i.$relation?i:{[`$${i.$thingType}`]:i.$thing},m=O(n,h);if(!m?.name)throw new Error(`Schema not found for ${i.$thing}`);if(i.$path=m.name,Array.isArray(i.$id)||(i.$filterByUnique=!0),m?.idFields?.length===1){let[E]=m.idFields;i.$filter={...i.$filter,[E]:i.$id},delete i.$id;}else throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in i||"$relation"in i||"$thing"in i){let h=O(n,i);if(!h?.name)throw new Error(`Schema not found for ${i.$thing}`);i.$path=h.name;}if(i.$entity?(i.$thing=i.$entity,i.$thingType="entity",delete i.$entity):i.$relation&&(i.$thing=i.$relation,i.$thingType="relation",delete i.$relation),radash.isObject(i)&&"$thing"in i){let h=i.$entity||i.$relation?i:{[`$${i.$thingType}`]:i.$thing};i[H]=c.nodePath;let m=O(n,h);if(i.$filter&&(i.$filterByUnique=vt(i.$filter,m),i.$filterProcessed||(i.$filter=Wt(i.$filter,m))),i.$fields){i.$fields.filter(M=>m?.idFields?.includes(M)||m?.idFields?.includes(M.$path)).length>0||(i.$fields=[...i.$fields,...Array.isArray(m.idFields)?m.idFields:[]],i.$idNotIncluded=!0);let $=i.$fields?.flatMap(M=>{let P=B(M,m);return Array.isArray(P)?P:[P]}).filter(Boolean);i.$fields=$;}else {let $=zt(m)?.flatMap(M=>{let P=B(M,m);return Array.isArray(P)?P:[P]}).filter(Boolean);i.$fields=$;}i.$excludedFields&&(i.$fields=i.$fields.filter(E=>p(m,E)?!0:!i.$excludedFields.includes(E.$path)));}}})))(Array.isArray(t)?t:[t]);e.enrichedBqlQuery=u;};var yt=async(e,t)=>{let n=t.dbConnectors[0].id,p=e.typeDB?.get(n)?.session,a=e.typeDB?.get(n)?.client;if(!p||!p.isOpen()){if(!a)throw new Error("Client not found");p=await a.session(t.dbConnectors[0].dbName,typedbDriver.SessionType.DATA),e.typeDB?.set(n,{client:a,session:p});}return {client:a,session:p}};var ue=async(e,t)=>{let{dbHandles:n,enrichedBqlQuery:p,tqlRequest:a,config:d}=e;if(!p)throw new Error("BQL request not parsed");if(!a)throw new Error("TQL request not built");let s=new typedbDriver.TypeDBOptions;if(s.infer=!0,Array.isArray(a)){let L=await radash.parallel(a.length,a,async u=>{let{session:r}=await yt(n,d),l=await r.transaction(typedbDriver.TransactionType.READ,s);if(!l)throw new Error("Can't create transaction");let f=await l.query.fetch(u).collect();return await l.close(),f});t.rawTqlRes=L,t.isBatched=!0;}else {let{session:L}=await yt(n,d),u=await L.transaction(typedbDriver.TransactionType.READ,s);if(!u)throw new Error("Can't create transaction");let l=await u.query.fetch(a).collect();await u.close(),t.rawTqlRes=l;}};var he=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,n=/justId:([a-zA-Z0-9_\-·]+)/,p=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,a=/filterByUnique:([a-zA-Z0-9_\-·]+)/,d=e.match(t),s=e.match(n),B=e.match(p),L=e.match(a);return {as:d?d[1]:null,justId:s?s[1]:null,idNotIncluded:B?B[1]:null,filterByUnique:L?L[1]:null}},hr=e=>{try{let n=(a=>{let d=a.replace("$metadata:","");return d=d.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),d=d.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(s,B,L)=>/^{.*}$/.test(L)?`:${L}`:`:${B}"${L}"`),d=d.replace(/\[([^\]]+)\]/g,(s,B)=>`[${B.split(",").map(L=>L.trim().startsWith("{")&&L.trim().endsWith("}")?L.trim():`"${L.trim()}"`).join(",")}]`),d})(e);return JSON.parse(n)}catch(t){return console.error(t),{as:[]}}},fe=async(e,t)=>{let{enrichedBqlQuery:n,rawBqlRequest:p,schema:a,config:d}=e,{rawTqlRes:s,isBatched:B}=t;if(n){if(!s)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");let L=(i,h)=>{let{$metaData:m}=i,{as:E}=hr(m),$=Object.entries(i).filter(([M])=>M!=="type"&&!M.includes("$")).map(([M,P])=>{let R=h.dataFields?.find(y=>y.path===M||y.dbPath===M),g=M==="id",b=Array.isArray(E)?E.find(y=>y[M])?.[M]:M,k;if(R?.cardinality==="ONE"){if(k=P[0]?P[0].value:d.query?.returnNulls?null:void 0,R.contentType==="DATE"&&(k=k&&`${k}Z`),g)return [[b,k],["$id",k]].filter(([y,I])=>I!==void 0)}else if(R?.cardinality==="MANY"){if(!radash.isArray(P))throw new Error("Typedb fetch has changed its format");if(P.length===0)return d.query?.returnNulls?[[b,null]]:[];R.contentType==="DATE"?k=P.map(y=>`${y.value}Z`):k=P.map(y=>y.value);}return [[b,k]].filter(([y,I])=>I!==void 0)}).flat();return Object.fromEntries([...$])},u=i=>i.reduce((h,m)=>{let{$roleFields:E,$metaData:$,$cardinality:M}=m,{as:P,justId:R,idNotIncluded:g,filterByUnique:b}=he($),k=E.map(y=>{let{dataFields:I,currentSchema:T,linkFields:A,roleFields:F,schemaValue:w}=l(y),Q=L(I,T);if(R==="T")return Q.id;{let C=r(A),S=u(F),N={...Q};return g==="true"&&T?.idFields?.forEach(D=>delete N[D]),{...N,...C,...S,...w}}});return k.length>0?h[P]=M==="MANY"&&b==="false"?k:k[0]:d.query?.returnNulls&&(h[P]=null),h},{}),r=i=>i.reduce((h,m)=>{let{$linkFields:E,$metaData:$,$cardinality:M}=m,{as:P,justId:R,idNotIncluded:g,filterByUnique:b}=he($),k=E.map(y=>{let{dataFields:I,currentSchema:T,linkFields:A,roleFields:F,schemaValue:w}=l(y),Q=L(I,T);if(R==="T")return Q.id;{let C=r(A),S=u(F),N={...Q};return g==="true"&&T.idFields?.forEach(D=>delete N[D]),{...N,...C,...S,...w}}});return h[P]=k.length>0?M==="MANY"&&b==="false"?k:k[0]:d.query?.returnNulls?null:void 0,h},{}),l=i=>{let h=Object.keys(i),m=h.find(y=>y.endsWith(".$dataFields"));if(!m)throw new Error("No datafields");let E=i[m],$=m.split(".")[m.split(".").length-2];if(E.$metaData=$,E.length===0)throw new Error("No datafields");let M=E.type,P={$thing:M.label,$thingType:M.root,[H]:i.queryPath.value},R={[`$${P.$thingType}`]:P.$thing},g=O(a,R),b=h.filter(y=>!y.endsWith(".$dataFields")&&g.linkFields?.some(I=>I.path===y.split(".").pop())).map(y=>({$linkFields:i[y],$key:y.split(".").pop(),$metaData:y.split(".")[y.split(".").length-2],$cardinality:g?.linkFields?.find(I=>I.path===y.split(".").pop())?.cardinality})),k=h.filter(y=>!y.endsWith(".$dataFields")&&g.roles?.[y.split(".").pop()]).map(y=>({$roleFields:i[y],$key:y.split(".").pop(),$metaData:y.split(".")[y.split(".").length-2],$cardinality:g.roles[y.split(".").pop()].cardinality}));return {dataFields:E,schemaValue:P,currentSchema:g,linkFields:b,roleFields:k}},o=i=>i.map(h=>{let{dataFields:m,currentSchema:E,linkFields:$,roleFields:M,schemaValue:P}=l(h),R=L(m,E),g=r($),b=u(M),k=p?.$fields?.every(I=>!E?.idFields?.includes(I)&&!E?.idFields?.includes(I.$path));return {...g,...b,...P,...!d.query?.noMetadata&&p.$id?{$id:Array.isArray(p.$id)?R.id:p.$id}:{},...k?Object.fromEntries(Object.entries(R).filter(([I])=>!E?.idFields?.includes(I))):R}}),c=(i=>{let h=m=>{let E=o(m);return p.$id&&!Array.isArray(p.$id)||n[0].$filterByUnique?E[0]??null:E.length===0?null:E};return B?i.map(h):h(i)})(s);t.bqlRes=c;};var fr=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,$r=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,$e=e=>{let n=e.toString().replace(fr,"").trim().split("=>")[0].split("{")[0].replace($r,"").trim(),p=n.substring(n.indexOf("(")+1,n.lastIndexOf(")")).trim();return p?(p.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(d=>d.includes("{")&&d.includes("}")?(d.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(B=>B.split(":")[0].trim().replace(/['"[\]]/g,"")):d.trim()).filter(Boolean):[]};var lt=({currentThing:e,fieldSchema:t,mandatoryDependencies:n=!1})=>{if(!t||!t.default||!("fn"in t.default||"value"in t.default))throw new Error(`[Internal] Virtual field: No field schema found, or wrongly configured. Field: ${JSON.stringify(t,null,3)}`);if(t.default.type==="value")return t.default.value;if(n){let{fn:a}=t.default,s=$e(a).filter(B=>!(B in e));if(s.length)throw new Error(`Virtual field: Missing arguments ${s.join(", ")}`)}return "default"in t?t.default?.fn(e):void 0};var me=async(e,t)=>{let{schema:n,enrichedBqlQuery:p}=e,{bqlRes:a}=t;if(!a)return;let s=(B=>immer.produce(B,L=>objectTraversal.traverse(L,({value:u})=>{if(radash.isObject(u)){let r=u;if(!r.$thing)throw new Error("[Internal] Thing is missing");if(r.$thing){let l=O(n,r),{virtualFields:o}=l,f=r[H];if(!f)throw new Error("[Internal] QueryPath is missing");let c=objectTraversal.getNodeByPath(p,f),i=c.$fields.map(m=>m.$path),h=c.$excludedFields;o.forEach(m=>{if(h?.includes(m)||i.length>0&&!i.includes(m))return;let E=l.dataFields?.find($=>$.path===m);if(E?.default){let $=lt({currentThing:r,fieldSchema:E,mandatoryDependencies:!0});r[m]=$;}else if(r[m]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${m}`)}),h&&h.forEach(m=>{if(typeof m!="string")throw new Error("[Internal] ExcludedField is not a string");delete r[m];});}}})))(a);t.bqlRes=s;};var Fe=async(e,t)=>{let{config:n}=e,{bqlRes:p}=t;if(!p)return;let d=(L=>immer.produce(L,u=>objectTraversal.traverse(u,({value:r})=>{radash.isObject(r);})))(p),B=(L=>immer.produce(L,u=>objectTraversal.traverse(u,({value:r})=>{if(radash.isObject(r)){let l=r;Object.keys(l).forEach(o=>{l[o]===void 0&&delete l[o];}),Object.getOwnPropertySymbols(l).forEach(o=>{delete l[o];}),n.query?.noMetadata===!0&&Object.keys(l).forEach(o=>{o.startsWith("$")&&delete l[o];});}})))(d);t.bqlRes=B;};var Fr={query:[de,le,ue,fe,me,Fe]},Ee=async(e,t,n={},p=!0)=>{for(let a of e){let d=await a(t,n);if(d&&Array.isArray(d))for(let s of d)await Ee(s.pipeline,s.req,s.res,!1);}return p&&t.config.query?.debugger===!0&&typeof n.bqlRes=="object"?{...n.bqlRes,$debugger:{tqlRequest:t.tqlRequest}}:n.bqlRes},Tt=(e,t,n,p)=>Ee(Fr.query,{config:t,schema:n,rawBqlRequest:e,dbHandles:p},{});var we=Er__namespace;var ct=(e,t)=>{if(t.fieldType==="linkField"){let n=t.oppositeLinkFieldsPlayedBy;if(n?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!n?.length)throw new Error(`[Internal] Field ${e} should have a player`);return n}else if(t.fieldType==="roleField"){if([...new Set(t.playedBy?.map(n=>n.thing))].length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!t.playedBy?.length)throw new Error(`[Internal] Field ${e} should have a player`);return t.playedBy}else throw new Error(`[Internal] Field ${e} is not a linkField or roleField`)};var be=(e,t,n)=>{let p=radash.isArray(e[t])?e[t]:[e[t]];if(!p.every(a=>typeof a=="object"))if(p.every(a=>typeof a=="string")){let a=ct(t,n),[d]=a,s=e.$op==="create"?"link":"replace",B=d.thing,L=d.thingType;if(p.some(u=>u.startsWith("_:")))throw new Error("[Not supported] At least one child of a replace is a tempId");e[t]={$id:e[t],$op:s,$thing:B,$thingType:L,$bzId:`S_${uuid.v4()}`};}else throw new Error("[Mutation Error] Replace can only be used with a single id or an array of ids")};var gt=(e,t,n)=>{let p=O(n,t),{usedDataFields:a}=U(p,t);if(t.$op){if(t.$op==="create"&&t.$id)throw new Error("[Wrong format] Can't write to computed field $id. Try writing to the id field directly.");if(["unlink","delete","update"].includes(t.$op)&&e.$op==="create")throw new Error(`[Wrong format] Cannot ${t.$op} under a create`);if(t.$op==="delete"&&a.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&a.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var Mt=(e,t,n)=>{let p=O(n,t),{usedFields:a}=U(p,t);return t.$op?(gt(e,t,n),t.$op):t.$id||t.$filter?a.length>0?(gt(e,{...t,$op:"update"},n),"update"):(gt(e,{...t,$op:"link"},n),"link"):(gt(e,{...t,$op:"create"},n),"create")};var Me=(e,t)=>{let p=(radash.isArray(e.$root)?e.$root:[e.$root]).map(a=>{let d=Mt(a,a,t);return {...{...a.$thing?{}:{$thing:a.$entity||a.$relation},...a.$thingType?{}:{$thingType:oe(a,t)},...a.$op?{}:{$op:d},...a.$bzId?{}:{$bzId:`R_${uuid.v4()}`}},...a}});e.$root=radash.isArray(e.$root)?p:p[0];};var kt=(e,t)=>{let n=t[bt];return types.isSet(n)?n.has("clean")?(Reflect.set(t,bt,n.add("clean")),!0):!1:(Reflect.set(t,bt,new Set(["clean"])),!0)};var ke=(e,t,n)=>{if(kt("split_ids",e)){let p=(radash.isArray(e[t])?e[t]:[e[t]]).flatMap(a=>{if(radash.isObject(a)&&"$id"in a&&radash.isArray(a.$id)){let d=a;if(O(n,d),!d.$bzId)throw new Error("[Internal Error] No bzId found");return d.$id.map((s,B)=>({...K(d),$id:s,$bzId:`${d.$bzId}_${B}`,...J(d)}))}return a});(p.length>radash.isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=p);}};var Qe=(e,t,n,p)=>{let a=(radash.isArray(e[t])?e[t]:[e[t]]).map(d=>{let s=ct(t,n),[B]=s,L=Mt(e,{...d,$thing:B.thing,$thingType:B.thingType},p),u=d.$bzId?d.$bzId:d.$tempId?d.$tempId:`N_${uuid.v4()}`;return {...d,[tt]:n,$thing:B.thing,$thingType:B.thingType,$op:L,$bzId:u}});e[t]=radash.isArray(e[t])?a:a[0];};var Ie=(e,t,n)=>{let p=e[t];p&&(radash.isArray(p)?p:[p]).forEach(a=>{let d=O(n,a),{unidentifiedFields:s}=U(d,a),{computedFields:B,virtualFields:L}=d,u=radash.listify(a,(o,f)=>f!==void 0?o:void 0),r=u.filter(o=>L?.includes(o));if(r.length>0)throw new Error(`Virtual fields can't be sent to DB: "${r.join(",")}"`);if(B.filter(o=>!u.includes(o)).forEach(o=>{let f=d.dataFields?.find(E=>E.path===o),i=d.linkFields?.find(E=>E.path===o)?.oppositeLinkFieldsPlayedBy[0],h="roles"in d?ne(d.roles,(E,$)=>E===o):void 0,m=f||i||h;if(!m)throw new Error(`no field Def for ${o}`);if(a.$op==="create"&&!a[o]){let E=lt({currentThing:a,fieldSchema:m,mandatoryDependencies:!0});a[o]=E;}}),s.length>0)throw new Error(`Unknown fields: [${s.join(",")}] in ${JSON.stringify(a)}`)});};var Pe=(e,t,n)=>{let p=ct(t,n),[a]=p;e[t]={$thing:a.thing,$thingType:a.thingType,$op:"unlink",$bzId:`U_${uuid.v4()}`,[tt]:n};};var Lt=(e,t)=>{let n=O(t,e).hooks;if(n?.pre){let p=`on${se(e.$op)}`;return n.pre.filter(s=>s.triggers[p]?.()).flatMap(s=>s.actions)}return []};var Ce=(e,t,n)=>{(radash.isArray(e[t])?e[t]:[e[t]]).forEach(a=>{if("$thing"in a){let{requiredFields:d,enumFields:s,fnValidatedFields:B,dataFields:L}=O(n,a);if("$op"in a&&a.$op==="create"&&d.forEach(u=>{if(!(u in a))throw new Error(`[Validations] Required field "${u}" is missing.`)}),("$op"in a&&a.$op==="update"||a.$op==="create")&&s.forEach(u=>{if(u in a){let r=L?.find(l=>l.path===u)?.validations?.enum;if(!r)throw new Error(`[Validations] Enum field "${u}" is missing enum options.`);if(radash.isArray(a[u]))a[u].some(l=>{if(!r.includes(l))throw new Error(`[Validations] Option "${l}" is not a valid option for field "${u}".`)});else if(r&&!r.includes(a[u]))throw new Error(`[Validations] Option "${a[u]}" is not a valid option for field "${u}".`)}}),("$op"in a&&a.$op==="update"||a.$op==="create")&&B.forEach(u=>{if(u in a)try{let r=L?.find(l=>l.path===u)?.validations?.fn;if(!r)throw new Error("Missing validation function.");if(!r(a[u]))throw new Error("Failed validation function.")}catch(r){throw new Error(`[Validations:attribute:${u}] ${r.message}`)}}),radash.isObject(a)&&"$thing"in a){let u=a.$thing,r=a,l=radash.clone(K(e)),o=radash.clone(K(r));Lt(r,n).forEach(c=>{if(c.type==="validate"){if(c.severity!=="error")return;try{let i=c.fn(o,l);if(i===!1)throw new Error(`${c.message}.`);if(i!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(i){throw new Error(`[Validations:thing:${u}] ${i.message}`)}}});}}});};var qe=(e,t,n)=>{let p=(radash.isArray(e[t])?e[t]:[e[t]]).map(a=>{if(wt(a)){let d=Lt(a,n).filter(L=>L.type==="transform"),s=radash.clone(K(e)),B=radash.clone(K(a));return d.forEach(L=>{let u=L.fn(B,s);Object.keys(u).length!==0&&(a={...B,...u});}),a}});e[t]=radash.isArray(e[t])?p:p[0];};var Dr=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(kt("set_tempId",e))if(e.$tempId?.startsWith("_:")){let n=e.$tempId.substring(2);e.$tempId=n,e.$bzId=n;}else throw new Error('[Wrong format] TempIds must start with "_:"');else throw new Error("[Internal] TempId already modified")},xr=(e,t)=>{},Ht=(e,t)=>{let p=immer.produce({$rootWrap:{$root:e}},a=>objectTraversal.traverse(a,({value:d,parent:s,key:B,meta:L})=>{if(!(!s||!B)&&radash.isObject(d)){if(!("$root"in d)){if(!("$thing"in d||"$entity"in d||"$relation"in d))throw B==="$root"?new Error("Root things must specify $entity or $relation"):new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(immer.isDraft(d)?immer.current(d):d)}`)}let u=d;Object.keys(u).forEach(r=>{if(Dr(u,r),r!=="$root"&&r.startsWith("$"))return;let l=r!=="$root"?xt(t,u,r):{fieldType:"rootField"};if(!l)throw new Error(`[Internal] Field ${r} not found in schema`);if("contentType"in l)return xr();if(["rootField","linkField","roleField"].includes(l.fieldType)){if(["linkField","roleField"].includes(l.fieldType)&&be(u,r,l),l.fieldType==="rootField"){if(!("$root"in u))throw new Error(`[Internal] Field ${r} is a rootField but the object is not a root`);Me(u,t);}let o=radash.isArray(u[r])?u[r]:[u[r]],f=L.nodePath?.split(".").slice(1).join(".");o.forEach(i=>{if(i){if(l?.cardinality==="ONE"&&!i.$op&&!i.$id&&!i.$filter&&!i.$tempId&&u.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${f}.${r}`);if(i.$tempId&&!(i.$op===void 0||i.$op==="link"||i.$op==="create"||i.$op==="update"))throw new Error(`Invalid op ${i.$op} for tempId. TempIds can be created, or when created in another part of the same mutation. In the future maybe we can use them to catch stuff in the DB as well and group them under the same tempId.`)}}),["linkField","roleField"].includes(l.fieldType)&&(u[r]===null?Pe(u,r,l):Qe(u,r,l,t)),ke(u,r,t),["rootField","linkField","roleField"].includes(l.fieldType)&&Ie(u,r,t),(radash.isArray(u[r])?u[r]:[u[r]]).forEach(i=>{let h=O(t,i),{unidentifiedFields:m,usedLinkFields:E}=U(h,i);if(m.length>0)throw new Error(`Unknown fields: [${m.join(",")}] in ${JSON.stringify(d)}`);if(E.length>1){let $=h.linkFields?.filter(M=>E.includes(M.path));$?.some((M,P)=>$.some((R,g)=>{if(P!==g&&M.target!==R.target&&M.relation===R.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),qe(u,r,t),Ce(u,r,t);}});}}));return radash.isArray(p.$rootWrap.$root),p.$rootWrap.$root};var De=async(e,t,n)=>{if(!e)throw new Error("TQL request not built");if(!(e.deletions&&e.deletionMatches||e.insertions))throw new Error("TQL request error, no things");let{session:p}=await yt(t,n),a=await p.transaction(typedbDriver.TransactionType.WRITE);if(!a)throw new Error("Can't create transaction");let d=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,s=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;d&&await a.query.delete(d);let B=s&&a.query.insert(s);try{let L=B?await B.collect():void 0;return await a.commit(),await a.close(),{insertions:L}}catch(L){throw await a.close(),new Error(`Transaction failed: ${L.message}`)}};var xe=async(e,t,n,p)=>{let a=[...t,...n],d=a.map(s=>{let B=e.insertions?.find(L=>L.get(`${s.$bzId}`))?.get(`${s.$bzId}`);if(s.$op==="create"||s.$op==="update"||s.$op==="link"){if(s.$op!=="update"&&!B&&s.$id)return {$id:s.$id,$error:"Does not exist or it's not linked to the parent"};let L=B?.asThing().iid;if(p.mutation?.noMetadata)return Object.entries(s).filter(([l,o])=>!l.startsWith("$")).reduce((l,[o,f])=>{if(s.$thingType==="relation"){let c=a.filter(i=>i.$id&&i.$bzId===f);if(c.length>1)throw new Error(`Multiple things with the same bzId ${f}`);return c.length===1?(l[o]=c[0].$id,l):(l[o]=f,l)}return l[o]=f,l},{});let u=s.$tempId&&!s.$tempId.startsWith("_:")?{$tempId:`_:${s.$tempId}`}:{};return {$dbId:L,...s,[s.path]:s.$id,...u}}if(s.$op==="delete"||s.$op==="unlink")return s;if(s.$op!=="match")throw new Error(`Unsupported op ${s.$op}`)}).filter(s=>s);return radash.clone(d)};var je=e=>{let t=({value:n})=>(n&&typeof n=="object"&&"$id"in n&&(Object.keys(n).filter(d=>d.startsWith("$")).forEach(d=>delete n[d]),Object.keys(n).filter(d=>typeof d=="symbol").forEach(d=>delete n[d])),n);return immer.produce(e,n=>objectTraversal.traverse(n,t))};var We=async(e,t)=>{let n=u=>{let r=[],l=[],o=h=>{if(h.$id)return h.$id;let m=O(t,h),{idFields:E}=m;if(!E)throw new Error(`no idFields: ${JSON.stringify(h)}`);let[$]=E;if(!$)throw new Error(`no idField: ${JSON.stringify(h)}`);let M=m.dataFields?.find(g=>g.path===$),P=lt({currentThing:h,fieldSchema:M,mandatoryDependencies:!0}),R=h[$]||h.$id||P;if(!R)throw new Error(`no idValue: ${JSON.stringify(h)}`);return R},f=h=>{if(h.$op==="create"){let m=o(h);if(r.find(E=>E.$id===m))throw new Error(`Duplicate id ${m} for node ${JSON.stringify(h)}`);if(l.find(E=>E.$bzId===h.$bzId))throw new Error(`Duplicate $bzid ${h.$bzId} for node ${JSON.stringify(h)}`);r.push({...h,$id:m});return}h.$tempId&&h.$op==="match"||r.push(h);},c=h=>{if(h.$op==="create"){let m=o(h);if(r.find(E=>E.$id===m),l.find(E=>E.$bzId===h.$bzId))throw new Error(`Duplicate %bzId ${h.$bzIdd} for edge ${JSON.stringify(h)}`);l.push({...h,$id:m});return}l.push(h);};return objectTraversal.traverse(u,({value:h,parent:m,meta:E})=>{if(!radash.isObject(h))return;let $=h;if($.$thing){if(!$.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify($)}`);if(!$.$bzId)throw new Error("[internal error] BzId not found");let M=O(t,$),{dataFields:P,roleFields:R,linkFields:g,usedFields:b}=U(M,$),k=()=>{if($.$op==="create"||$.$op==="delete")return $.$op;if($.$op==="update"){let T=b.filter(w=>P?.includes(w)),A=b.filter(w=>R?.includes(w)),F=b.filter(w=>g?.includes(w));if(T.length>0)return "update";if(A.length>0||F.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify($)}`)}return "match"},y={...$.$id&&{$id:$.$id},...$.$tempId&&{$tempId:$.$tempId},...$.$filter&&{$filter:$.$filter},$thing:$.$thing,...$.$thingType&&{$thingType:$.$thingType},...radash.shake(radash.pick($,P||[""])),$op:k(),$bzId:$.$tempId?$.$tempId:$.$bzId};f(y);let I=$[tt];if(I?.fieldType==="linkField"){if(($.$op==="link"||$.$op==="unlink")&&($.$id||$.$filter)){if($.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");r.push({...$,$op:"match"});}let T=I.relation===$.$thing,A=T?$.$bzId:`LT_${uuid.v4()}`,w=ae(u,m,E).$bzId;if(!w)throw new Error("No parent id found");if($[Symbol.for("relation")]==="$self")return;let Q=()=>{if($.$op==="delete")return T?"match":"delete";if($.$op==="unlink")return T?"unlink":"delete";if($.$op==="link"||$.$op==="create")return T?"link":"create";if($.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},C={$bzId:A,$thing:I.relation,$thingType:"relation",...$.$tempId?{$tempId:$.$tempId}:{},$op:Q(),...T?{}:{[I.path]:$.$bzId},[I.plays]:w,[tt]:I,[ot]:"linkField"};c(C),($.$op==="unlink"||Q()==="unlink")&&T&&c({$thing:I.relation,$thingType:"relation",$bzId:A,$op:"match",[I.plays]:w,[tt]:I,[ot]:"linkField"});}if($.$thingType==="relation"){let T=mt($,(w,Q)=>R.includes(w)),A=radash.mapEntries(T,(w,Q)=>radash.isArray(Q)?[w,Q]:radash.isObject(Q)?[w,Q.$bzId]:[w,Q]),F=mt(h,(w,Q)=>w.startsWith("$")||w.startsWith("Symbol"));if(Object.keys(T).filter(w=>!w.startsWith("$")).length>0){if($.$op==="create"||$.$op==="delete"){let w=()=>{if($.$op==="create")return "link";if($.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},Q=O(t,$).roles,C=radash.mapEntries(A,(N,D)=>{let z=Q[N]?.cardinality;if(!z)throw new Error(`Role ${N} not found in schema`);if(Array.isArray(D)){if(z==="ONE"){if(D.length>1)throw new Error(`[Error] Role ${N} is not a MANY relation`);return [N,D[0].$bzId||D[0]]}return [N,D.map(V=>V.$bzId||V)]}return [N,D.$bzId||D]}),S={...F,$thing:$.$thing,$thingType:"relation",$op:w(),...C,$bzId:$.$bzId,[ot]:"roleField"};c(S);return}if($.$op==="match"||$.$op==="update"&&Object.keys(T).length>0){let w=0;Object.entries(T).forEach(([Q,C])=>{let S=radash.isArray(C)?C:[C],N=D=>D==="create"||D==="replace"?"link":D;S.forEach(D=>{if(!D)return;let z=N(D.$op);if(z==="replace")throw new Error("Not supported yet: replace on roleFields");if(z==="unlink"&&w>0)throw w+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let V={...F,$thing:$.$thing,$thingType:"relation",$op:z==="delete"?"unlink":z,[Q]:D.$bzId,$bzId:$.$bzId,[ot]:"roleField"};c(V);});});}}}}}),[r,l]},[p,a]=n(e),d=p.reduce((u,r)=>{if(!r.$bzId)return [...u,r];let l=u.findIndex(o=>o.$bzId===r.$bzId);if(l===-1)return [...u,r];if(u[l].$op==="create"&&r.$op==="match")return u;if(u[l].$op==="match"&&(r.$op==="create"||r.$op==="match"))return [...u.slice(0,l),r,...u.slice(l+1)];throw new Error(`[Wrong format] Wrong operation combination for $tempId "${r.$tempId}". Existing: ${u[l].$op}. Current: ${r.$op}`)},[]),s=a.reduce((u,r)=>{let l=u.find(o=>(o.$id&&o.$id===r.$id||o.$bzId&&o.$bzId===r.$bzId)&&o.$thing===r.$thing&&o.$op===r.$op);if(l){let o={...l};return Object.keys(r).forEach(c=>{if(typeof c=="symbol"||c.startsWith("$"))return;let i=l[c],h=r[c];Array.isArray(i)&&Array.isArray(h)?o[c]=Array.from(new Set([...i,...h])):!Array.isArray(i)&&Array.isArray(h)?i!==void 0?o[c]=Array.from(new Set([i,...h])):o[c]=h:Array.isArray(i)&&!Array.isArray(h)?h!==void 0&&(o[c]=Array.from(new Set([...i,h]))):i!==null&&h!==null&&i!==void 0&&h!==void 0?o[c]=Array.from(new Set([i,h])):i==null&&(o[c]=h);}),[...u.filter(c=>!((c.$id&&c.$id===r.$id||c.$bzId&&c.$bzId===r.$bzId)&&c.$thing===r.$thing&&c.$op===r.$op)),o]}return [...u,r]},[]);d.forEach(u=>{if((u.$thingType==="relation"||"relation"in u)&&s.filter(r=>r.$bzId===u.$bzId||r.$tempId&&r.$tempId===u.$tempId).length===0){if(u.$op==="delete"||u.$op==="match"||u.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(je(u))}`)}});let B=[...d,...s];return new Set(B.filter(u=>u.$tempId).map(u=>u.$tempId)).forEach(u=>{if(B.filter(r=>r.$tempId===u&&r.$op==="create").length===0)throw new Error("Can't link a $tempId that has not been created in the current mutation.")}),{mergedThings:d,mergedEdges:s}};var _e=async(e,t,n)=>{let p=o=>{let f=o.$op,c=`$${o.$bzId}`,i=O(n,o),{idFields:h,defaultDBConnector:m}=i,E=m?.path||o.$thing,$=o.$id,M=h?.[0],P=radash.listify(o,(A,F)=>{if(A.startsWith("$")||A===M||F===void 0||F===null)return "";let w=i.dataFields?.find(S=>S.path===A);if(!w?.path)return "";let C=w.dbPath;if(["TEXT","ID","EMAIL"].includes(w.contentType))return `has ${C} '${F}'`;if(["NUMBER","BOOLEAN"].includes(w.contentType))return `has ${C} ${F}`;if(w.contentType==="DATE"){if(Number.isNaN(F.valueOf()))throw new Error("Invalid format, Nan Date");return F instanceof Date?`has ${C} ${F.toISOString().replace("Z","")}`:`has ${C} ${new Date(F).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${w.contentType}`)}).filter(A=>A),R=`${c}-atts`,g=radash.listify(o,A=>{if(A.startsWith("$")||A===M)return "";let F=i.dataFields?.find(C=>C.path===A);if(!F?.path)return "";let Q=F.dbPath;return `{${R} isa ${Q};}`}).filter(A=>A),b=radash.isArray($)?`like '${$.join("|")}'`:`'${$}'`,k=$?[`has ${M} ${b}`]:[],y=[...k,...P].filter(A=>A).join(","),I=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${c} isa ${[E,...k].filter(A=>A).join(",")};`;if(f==="update"){if(!g.length)throw new Error("update without attributes");return `${c} isa ${[E,...k].filter(A=>A).join(",")}, has ${R};
82
- ${g.join(" or ")};`}return ""},T=()=>f==="update"||f==="link"||f==="match"?`${c} isa ${[E,...k].filter(A=>A).join(",")};`:"";if(wt(o))return {op:f,deletionMatch:I(),insertionMatch:T(),insertion:f==="create"?`${c} isa ${[E,y].filter(A=>A).join(",")};`:f==="update"&&P.length?`${c} ${P.join(",")};`:"",deletion:f==="delete"?`${c} isa ${E};`:f==="update"&&g.length?`${c} has ${R};`:""};throw new Error("in attributes")},a=o=>{let f=o.$op,c=O(n,o),i=`$${o.$bzId}`,h=o.$id,m=c.defaultDBConnector?.path||o.$thing,E="roles"in c?radash.listify(c.roles,F=>F):[],$="roles"in c?radash.mapEntries(c.roles,(F,w)=>[F,w.dbConnector?.path||F]):{},M=radash.listify(o,(F,w)=>{if(!E.includes(F))return null;if(!("roles"in c))throw new Error("This should have roles! ");let Q=$[F];return Array.isArray(w)?w.map(C=>({path:Q,id:C})):{path:Q,id:w}}).filter(F=>F).flat(),P=M.map(F=>{if(!F?.path)throw new Error("Object without path");return `${F.path}: $${F.id}`}),R=M.length>0?`( ${P.join(" , ")} )`:"",g=o[ot];if(!g)throw new Error("[internal error] Symbol edgeType not defined");let b=R?`${i} ${R} ${g==="linkField"||f==="delete"||f==="unlink"?`isa ${m}`:""}`:"",k=`${i} ${g==="linkField"||f==="delete"?`isa ${m}`:""}`,y=()=>b?f==="link"?`${b};`:f==="create"?`${b}, has id '${h}';`:"":"",I=()=>b&&f==="match"?`${b};`:"",T=()=>b?f==="delete"?`${b};`:f==="match"?`${b};`:"":"",A=()=>b?f==="delete"?`${k};`:f==="unlink"?`${i} ${R};`:"":"";return {deletionMatch:T(),insertionMatch:I(),deletion:A(),insertion:y(),op:""}},d=(o,f)=>{let c=f==="edges"?a:p;if(Array.isArray(o))return o.map(M=>{let{preDeletionBatch:P,insertionMatch:R,deletionMatch:g,insertion:b,deletion:k}=c(M);return radash.shake({preDeletionBatch:P,insertionMatch:R,deletionMatch:g,insertion:b,deletion:k},y=>!y)}).filter(M=>M);let{preDeletionBatch:i,insertionMatch:h,deletionMatch:m,insertion:E,deletion:$}=c(o);return radash.shake({preDeletionBatch:i,insertionMatch:h,deletionMatch:m,insertion:E,deletion:$},M=>!M)},s=d(e),B=Array.isArray(s)?s:[s],L=d(t,"edges"),u=Array.isArray(L)?L:[L],r=[...B,...u];return radash.shake({insertionMatches:r.map(o=>o.insertionMatch).join(" ").trim(),deletionMatches:r.map(o=>o.deletionMatch).join(" ").trim(),insertions:r.map(o=>o.insertion).join(" ").trim(),deletions:r.map(o=>o.deletion).join(" ").trim()},o=>!o)};var Jr=Symbol.for("grandChildOfCreate"),Ve=async(e,t,n,p)=>{let a=(g,b)=>Object.keys(g).filter(k=>k.startsWith("$")?!1:b?!O(t,g).dataFields?.find(I=>I.path===k):!0);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(n.mutation?.preQuery===!1)return;let d=[];if(objectTraversal.traverse(e,({parent:g,key:b,value:k})=>{g&&b&&!b.includes("$")&&radash.isObject(g)?(Array.isArray(g[b])?g[b]:[g[b]]).forEach(I=>{if(radash.isObject(I)){if(g.$op!=="create")d.includes(I.$op)||d.push(I.$op);else if(I.$op==="delete"||I.$op==="unlink")throw new Error(`Cannot ${I.$op} under a create`)}}):!g&&radash.isObject(k)&&(d.includes(k.$op)||d.push(k.$op));}),!d.includes("delete")&&!d.includes("unlink")&&!d.includes("replace")&&!d.includes("update")&&!d.includes("link"))return;let B=(g=>{let b=(k,y)=>{let I=[],T={},A=["$op","$bzId","$parentKey"],F=["$relation","$entity","$id",...A];for(let w in k)if(!A.includes(w)&&!(F.includes(w)&&!y))if(!w.includes("$")&&(radash.isObject(k[w])||Array.isArray(k[w]))){let Q=k[w];Array.isArray(Q)&&Q.length>0?Q.forEach(C=>{I.push({$path:w,...b(C)});}):I.push({$path:w,...b(Q)});}else T[w]=k[w];return {...T,$fields:I}};return g.map(k=>b(k,!0))})(Array.isArray(e)?e:[e]),L=await Tt(B,n,t,p),u=(g,b)=>{let k=g.$id||g.id||g.$bzId;if(g.$objectPath){let{$objectPath:y}=g,I=y?.beforePath||"root",T=Array.isArray(y.ids)?`[${y.ids}]`:y.ids;return {beforePath:`${I}.${T}___${y.key}`,ids:k,key:b}}else return {beforePath:"root",ids:k,key:b}},r=(g,b)=>{let k=g?.beforePath||"root",y=b||(Array.isArray(g?.ids)?`[${g?.ids}]`:g?.ids);return `${k}.${y}___${g?.key}`},l=g=>{if(g.includes("[")&&g.includes("]")){let[b,k,y]=g.split(/[[\]]/);return k.split(",").map(T=>`${b}${T}${y}`)}else return [g]},o={};(g=>immer.produce(g,b=>objectTraversal.traverse(b,k=>{let{key:y,parent:I}=k;if(I&&y&&I.$id&&!y.includes("$")){let T=u(I,y),A=r(T);if(Array.isArray(I[y])){let F=[];I[y].forEach(w=>{radash.isObject(w)?(w.$objectPath=T,F.push(w.$id.toString())):w&&F.push(w.toString());}),o[A]={$objectPath:T,$ids:F};}else {let F=I[y];radash.isObject(F)?(o[A]={$objectPath:T,$ids:[F.$id.toString()]},F.$objectPath=T):F&&(o[A]={$objectPath:T,$ids:[F.toString()]});}}})))(L||{});let c=g=>immer.produce(g,b=>objectTraversal.traverse(b,k=>{let{key:y,value:I,parent:T}=k;T&&y&&!y.includes("$")&&(Array.isArray(I)||radash.isObject(I))&&!Array.isArray(T)&&(Array.isArray(T[y])?T[y].forEach(A=>{typeof A!="string"&&(A.$objectPath=u(T,y),A.$parentIsCreate=T.$op==="create",A[Jr]=T.$parentIsCreate||T[Symbol.for("grandChildOfCreate")]);}):radash.isObject(T[y])&&(T[y].$parentIsCreate=T.$op==="create",T[y][Symbol.for("grandChildOfCreate")]=T.$parentIsCreate||T[Symbol.for("grandChildOfCreate")],T[y].$objectPath=u(T,y)));})),i=c(e),m=(g=>{let b=(T,A)=>{let F=[];T.filter(S=>S).forEach(S=>{let N=Object.keys(S).filter(D=>!D.startsWith("$")).length;if(Array.isArray(S.$id)&&N>0){let D=S.$id.map(z=>({...S,$id:z}));F=[...F,...D];}else F.push({...S});});let w=[],Q=[],C=F.filter(S=>{let D=["delete","update","unlink"].includes(S.$op||""),z=a(S,!0).length;if((!S.$id||Array.isArray(S.$id)&&z>0||S.$filter)&&D)return !0;Q.push({...S});});return C.length>0?C.forEach(S=>{let D=(j=>{let ut=(()=>{let v={};for(let x in j){let X=O(t,j);!x.startsWith("$")&&X.dataFields?.find(at=>at.path===x)&&(v[x]=j[x]);}return v})(),ht=Object.keys(j),G=ht.filter(v=>!v.startsWith("$")),At=[],Ft=(v,x)=>{if(v===G.length){let at={...x};ht.forEach(W=>{W.startsWith("$")&&(at[W]=j[W]);}),At.push(at);return}let X={...x,[G[v]]:j[G[v]],...J(x),...ut};Ft(v+1,X),Ft(v+1,x);};return Ft(0,{...J(j)}),At})(S).filter(j=>!(j.$op==="update"&&Object.keys(j).filter(nt=>!nt.startsWith("$")).length===0)),z=[],V=r(S.$objectPath),Y=o[V]?o[V].$ids:[],q=D.map((j,nt)=>{let ut=O(t,j),G=Object.keys(j).filter(x=>!x.includes("$")&&!ut.dataFields?.some(X=>X.path===x)).map(x=>(Array.isArray(j[x])?j[x].length>1?j[x].filter(W=>!W.$id||Array.isArray(W.$id)||W.$filter):j[x]:[j[x]]).map(W=>{let Rt=r(W.$objectPath);return {idsToKey:(Ct=>{let Yt=[],$t=Ct.split("."),Ye=$t.slice(0,$t.length-1).join("."),Ge=$t.slice($t.length-1,$t.length)[0].split("___")[1];for(let St in o)if(St.startsWith(Ye)&&St.endsWith(Ge)){let Ot=St.split("."),Xe=Ot.slice(Ot.length-1,Ot.length)[0].split("___")[0];Yt.push(Xe);}return Yt})(Rt),key:x,multiple:W}})).filter(x=>x!==void 0),v=(x=>{let X=x.map(W=>W.map(it=>it.idsToKey));return (W=>W.length>0?W.reduce((it,ft)=>it.concat(ft),[]).reduce((it,ft)=>it?ft.filter(Ct=>it.includes(Ct)):ft):[])(X)})(G).filter(x=>!z.includes(x));if(z=[...z,...v],Y=Y.filter(x=>!v.includes(x)),nt===D.length-1&&Y.length>0)return {...j,$id:Y,$bzId:`T1_${uuid.v4()}`,...J(j)};if(v.length>0)return {...j,$id:v,$bzId:`T2_${uuid.v4()}`,...J(j)}}).filter(j=>j!==void 0),Ze=(()=>{if(q.length===0&&!A?.$id)return C;if(q.length===0&&A?.$id){let j=Array.isArray(A.$id)?A.$id:[A.$id],nt=[];return j.forEach(ut=>{let ht=r({...S.$objectPath,ids:ut}),G=o[ht];G&&nt.push({...S,$id:G.$ids,...J(S),$bzId:`T_${uuid.v4()}`});}),nt}else return q.filter(j=>j!==void 0)})();w=[...Q,...Ze].map(k);}):w=F.map(k),w},k=T=>{let A={...T,$bzId:T.$tempId??`T3_${uuid.v4()}`,...J(T)},F=O(t,T);return Object.keys(T).filter(w=>!w.includes("$")&&!F.dataFields?.some(Q=>Q.path===w)).forEach(w=>{let Q=Array.isArray(T[w])?T[w]:[T[w]],C=b(Q,T);A[w]=C.length>0?C:void 0;}),A},y=[];return g.forEach(T=>{y=[...y,...b([T])];}),y.map(T=>k(T))})(Array.isArray(i)?i:[i]),E=g=>g.map(b=>{let k=a(b,!0),y={...b};return k.forEach(I=>{let T=Array.isArray(b[I])?b[I]:[b[I]],A=[],F=[],w=[],Q={},C=jt(t,b,I);T.filter(q=>q).forEach(q=>{q.$op==="replace"&&q.$id?(Q=q,Array.isArray(q.$id)?F=[...F,...q.$id]:F.push(q.$id)):q.$op==="create"&&C==="ONE"&&q.id?(Q=q,Array.isArray(q.id)?w=[...F,...q.id]:w.push(q.id)):A.push(q);});let S=r(Q.$objectPath),D=l(S).map(q=>o[q]),z=[];D.filter(q=>q!=null).forEach(q=>{z=[...z,...q.$ids];});let V=z.filter(q=>!F.includes(q)),Pt=F.filter(q=>!z.includes(q)),Y=J(Q);V.length>0&&A.push({...Q,$op:"unlink",$id:V,$bzId:`T4_${uuid.v4()}`,id:void 0,...Y}),Pt.length>0&&Pt.forEach(q=>{A.push({...Q,$op:"link",$id:q,$bzId:`T5_${uuid.v4()}`,...Y});}),w.length>0&&w.forEach(q=>{A.push({...Q,$op:"create",id:q,$bzId:`T6_${uuid.v4()}`,...Y});}),y[I]=E(A);}),y}),$=c(E(c(m)));return (g=>immer.produce(g,b=>objectTraversal.traverse(b,k=>{let{key:y,value:I,parent:T}=k;y&&T&&!y?.includes("$")&&(Array.isArray(I)||radash.isObject(I))&&!Array.isArray(T)&&(Array.isArray(I)?I:[I]).forEach(F=>{let w=o[r(F.$objectPath)],Q=(N,D)=>N.every(z=>D.includes(z)),C=F.$id?Array.isArray(F.$id)?Q(F.$id,w?w.$ids:[]):w?.$ids.includes(F.$id):w,S=jt(t,T,F.$objectPath.key);if(F.$op==="link"&&C&&S==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${r(F.$objectPath)}" because it is already occupied.`);if(F.$op)switch(F.$op){case"delete":if(!C&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${F.$id}" because it is not linked to $id:"${T.$id}"`);break;case"update":if(!C&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${F.$id}" because it is not linked to $id:"${T.$id}"`);break;case"unlink":if(!C&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${F.$id}" because it is not linked to $id:"${T.$id}"`);break;case"link":if(C)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${F.$id}" because it is already linked to $id:"${T.$id}"`);break;}});})))($),(g=>immer.produce(g,b=>objectTraversal.traverse(b,k=>{let{value:y,meta:I}=k;radash.isObject(y)&&(y[Symbol.for("path")]=I.nodePath,delete y.$objectPath,delete y.$parentIsCreate);})))($)};var{createMachine:Zr,invoke:dt,transition:et,reduce:rt,guard:Yr,interpret:Gr,state:Xr}=we,He=Xr,Ut=(e,t)=>t.data?{...e,bql:{...e.bql,current:t.data}}:e,tn=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),en=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),rn=(e,t)=>({...e,typeDB:{...e.typeDB,tqlMutation:t.data}}),nn=(e,t)=>({...e,typeDB:{...e.typeDB,tqlRes:t.data}}),on=async e=>Object.keys(e.bql.current).length?Ht(e.bql.current,e.schema):Ht(e.bql.raw,e.schema),sn=async e=>Ve(e.bql.current,e.schema,e.config,e.handles),an=async e=>We(e.bql.current,e.schema),ln=async e=>_e(e.bql.things,e.bql.edges,e.schema),cn=async e=>De(e.typeDB.tqlMutation,e.handles,e.config),dn=async e=>xe(e.typeDB.tqlRes,e.bql.things,e.bql.edges,e.config),pn=()=>!0,pt=et("error","error",rt((e,t)=>({...e,error:t.error}))),un=Zr("enrich",{enrich:dt(on,et("done","preQuery",Yr(pn),rt(Ut)),et("done","parseBQL",rt(Ut)),pt),preQuery:dt(sn,et("done","parseBQL",rt(Ut)),pt),parseBQL:dt(an,et("done","buildMutation",rt(en)),pt),buildMutation:dt(ln,et("done","runMutation",rt(rn)),pt),runMutation:dt(cn,et("done","parseMutation",rt(nn)),pt),parseMutation:dt(dn,et("done","success",rt(tn)),pt),success:He(),error:He()},e=>e),hn=async e=>new Promise((t,n)=>{Gr(un,p=>{p.machine.state.name==="success"&&t(p.context),p.machine.state.name==="error"&&n(p.context);},e);}),Ke=async(e,t,n,p)=>hn({bql:{raw:e,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:t,config:n,handles:p,depthLevel:0,error:null});immer.enableMapSet();var Zt=class{schema;config;dbHandles;constructor({schema:t,config:n}){this.schema=t,this.config=n;}getDbHandles=()=>this.dbHandles;init=async()=>{let t={typeDB:new Map,surrealDB:new Map};await Promise.all(this.config.dbConnectors.map(async p=>{if(p.provider==="typeDB"&&p.dbName){let[a,d]=await radash.tryit(typedbDriver.TypeDB.coreDriver)(p.url);if(a){let s=`[BORM:${p.provider}:${p.dbName}:core] ${a.message??"Can't create TypeDB Client"}`;throw new Error(s)}try{let s=await d.session(p.dbName,typedbDriver.SessionType.DATA);t.typeDB.set(p.id,{client:d,session:s});}catch(s){let B=`[BORM:${p.provider}:${p.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(B)}}if(p.provider==="typeDBCluster"&&p.dbName){let[a,d]=await radash.tryit(typedbDriver.TypeDB.cloudDriver)(p.addresses,p.credentials);if(a){let s=`[BORM:${p.provider}:${p.dbName}:core] ${a.message??"Can't create TypeDB Cluster Client"}`;throw new Error(s)}try{let s=await d.session(p.dbName,typedbDriver.SessionType.DATA);t.typeDB.set(p.id,{client:d,session:s});}catch(s){let B=`[BORM:${p.provider}:${p.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(B)}}}));let n=ie(this.schema,t);this.schema=n,this.dbHandles=t;};#t=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#t(),this.schema);define=async()=>(await this.#t(),Xt(this.config,this.schema,this.dbHandles));query=async(t,n)=>{await this.#t();let p={...this.config,query:{...qt.query,...this.config.query,...n}};return Tt(t,p,this.schema,this.dbHandles)};mutate=async(t,n)=>{await this.#t();let p={...this.config,mutation:{...qt.mutation,...this.config.mutation,...n}},[a,d]=await radash.tryit(Ke)(t,this.schema,p,this.dbHandles);if(a)throw console.error(a.error.stack.split(`
60
+ ;`,s){let m=s.filter(k=>k.$fieldType==="data");m&&m.length>0&&i(m,a);let E=s.filter(k=>k.$fieldType==="link");E&&E.length>0&&l(E,a,a);let $=s.filter(k=>k.$fieldType==="role");$&&$.length>0&&c($,a,a);}}})(t),e.tqlRequest=g?M:n;};var vt=e=>{let t=e.dataFields?.map(c=>c.path)||[],n=e.linkFields?.map(c=>c.path)||[],o=Object.keys(e.roles||{})||[];return [...t,...n,...o]},Ht=(e,t)=>Object.keys(e||{}).some(o=>{if(!Array.isArray(e[o])){let i=t.idFields?.includes(o),c=t.dataFields?.some(l=>(l.dbPath===o||l.path===o)&&l?.validations?.unique);return i||c}return !1}),Kt=(e,t)=>{let n=t.dataFields?.map(l=>({path:l.path,dbPath:l.dbPath}))||[],o=t.linkFields?.map(l=>({path:l.path,dbPath:l.dbPath}))||[],i=Object.keys(t.roles||{}).map(l=>({path:l,dbPath:l}))||[],c=[...n,...o,...i];return Object.entries(e||{}).reduce((l,[g,M])=>{let u=c.find(r=>r.path===g);return l[u?.dbPath||g]=M,l},{})},ye=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,d)=>typeof d=="string"?r.idFields?.includes(d):r.idFields?.includes(d.$path),i=(r,d,a,f,p)=>({$path:d,$dbPath:f,$thingType:"attribute",$as:r.$as||d,$var:d,$fieldType:"data",$excludedFields:r.$excludedFields,$justId:a,$id:r.$id,$filter:r.$filter,$isVirtual:p,$filterProcessed:!0}),c=(r,d,a,f,p)=>{let{target:s,oppositeLinkFieldsPlayedBy:h}=a;return h.map(m=>{let E=s==="role"?m.thingType:"relation",$=s==="role"?m.thing:a.relation,k={[`$${E}`]:$},P=S(n,k),C=r?.$fields?.filter(b=>o(P,b)).length===0,B=[];return typeof r!="string"?r.$fields?C?B=[...r.$fields,...P.idFields]:B=r.$fields:B=vt(P):B=["id"],r.$excludedFields&&(B=B.filter(b=>o(P,b)?!0:!r.$excludedFields.includes(b.$path))),{$thingType:E,$plays:a.plays,$playedBy:m,$path:m.path,$dbPath:p,$as:r.$as||d,$var:d,$thing:$,$fields:B,$excludedFields:r.$excludedFields,$fieldType:"link",$target:s,$intermediary:m.relation,$justId:f,$id:r.$id,$filter:Kt(r.$filter,P),$idNotIncluded:C,$filterByUnique:Ht(r.$filter,P),$filterProcessed:!0}})},l=(r,d,a,f,p)=>a.playedBy.map(s=>{let{thing:h,thingType:m,relation:E}=s,$={[`$${m}`]:h},k=S(n,$),P=r?.$fields?.filter(B=>k?.idFields?.includes(B)||k?.idFields?.includes(B.$path)).length===0,C=[];return typeof r!="string"?r.$fields?P?C=[...r.$fields,...k.idFields]:C=r.$fields:C=vt(k):C=["id"],r.$excludedFields&&(C=C.filter(B=>o(k,B)?!0:!r.$excludedFields.includes(B.$path))),{$thingType:m,$path:d,$dbPath:p,$as:r.$as||d,$var:d,$thing:h,$fields:C,$excludedFields:r.$excludedFields,$fieldType:"role",$intermediary:E,$justId:f,$id:r.$id,$filter:Kt(r.$filter,k),$idNotIncluded:P,$filterByUnique:Ht(r.$filter,k),$playedBy:s,$filterProcessed:!0}}),g=(r,d)=>{let a=typeof r=="string"?r:r.$path,f=typeof r=="string",p=d.dataFields?.find(m=>m.path===a),s=d.linkFields?.find(m=>m.path===a),h=d.roles?.[a];if(p){let m=p.isVirtual&&p.default;return i(r,a,f,p.dbPath,m)}else {if(s)return c(r,a,s,f,s.dbPath);if(h)return l(r,a,h,f,h.dbPath)}return null},u=(r=>immer.produce(r,d=>objectTraversal.traverse(d,a=>{let{value:f,meta:p}=a,s=f;if(radash.isObject(s)){if(s.$id){let h=s.$entity||s.$relation?s:{[`$${s.$thingType}`]:s.$thing},m=S(n,h);if(!m?.name)throw new Error(`Schema not found for ${s.$thing}`);if(s.$path=m.name,Array.isArray(s.$id)||(s.$filterByUnique=!0),m?.idFields?.length===1){let[E]=m.idFields;s.$filter={...s.$filter,[E]:s.$id},delete s.$id;}else throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in s||"$relation"in s||"$thing"in s){let h=S(n,s);if(!h?.name)throw new Error(`Schema not found for ${s.$thing}`);s.$path=h.name;}if(s.$entity?(s.$thing=s.$entity,s.$thingType="entity",delete s.$entity):s.$relation&&(s.$thing=s.$relation,s.$thingType="relation",delete s.$relation),radash.isObject(s)&&"$thing"in s){let h=s.$entity||s.$relation?s:{[`$${s.$thingType}`]:s.$thing};s[K]=p.nodePath;let m=S(n,h);if(s.$filter&&(s.$filterByUnique=Ht(s.$filter,m),s.$filterProcessed||(s.$filter=Kt(s.$filter,m))),s.$fields){s.$fields.filter(k=>m?.idFields?.includes(k)||m?.idFields?.includes(k.$path)).length>0||(s.$fields=[...s.$fields,...Array.isArray(m.idFields)?m.idFields:[]],s.$idNotIncluded=!0);let $=s.$fields?.flatMap(k=>{let P=g(k,m);return Array.isArray(P)?P:[P]}).filter(Boolean);s.$fields=$;}else {let $=vt(m)?.flatMap(k=>{let P=g(k,m);return Array.isArray(P)?P:[P]}).filter(Boolean);s.$fields=$;}s.$excludedFields&&(s.$fields=s.$fields.filter(E=>o(m,E)?!0:!s.$excludedFields.includes(E.$path)));}}})))(Array.isArray(t)?t:[t]);e.enrichedBqlQuery=u;};var Ft=async(e,t)=>{let n=t.dbConnectors[0].id,o=e.typeDB?.get(n)?.session,i=e.typeDB?.get(n)?.client;if(!o||!o.isOpen()){if(!i)throw new Error("Client not found");o=await i.session(t.dbConnectors[0].dbName,typedbDriver.SessionType.DATA),e.typeDB?.set(n,{client:i,session:o});}return {client:i,session:o}};var Be=async(e,t)=>{let{dbHandles:n,enrichedBqlQuery:o,tqlRequest:i,config:c}=e;if(!o)throw new Error("BQL request not parsed");if(!i)throw new Error("TQL request not built");let l=new typedbDriver.TypeDBOptions;if(l.infer=!0,Array.isArray(i)){let M=await radash.parallel(i.length,i,async u=>{let{session:r}=await Ft(n,c),d=await r.transaction(typedbDriver.TransactionType.READ,l);if(!d)throw new Error("Can't create transaction");let f=await d.query.fetch(u).collect();return await d.close(),f});t.rawTqlRes=M,t.isBatched=!0;}else {let{session:M}=await Ft(n,c),u=await M.transaction(typedbDriver.TransactionType.READ,l);if(!u)throw new Error("Can't create transaction");let d=await u.query.fetch(i).collect();await u.close(),t.rawTqlRes=d;}};var Fe=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,n=/justId:([a-zA-Z0-9_\-·]+)/,o=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,i=/filterByUnique:([a-zA-Z0-9_\-·]+)/,c=e.match(t),l=e.match(n),g=e.match(o),M=e.match(i);return {as:c?c[1]:null,justId:l?l[1]:null,idNotIncluded:g?g[1]:null,filterByUnique:M?M[1]:null}},Sn=e=>{try{let n=(i=>{let c=i.replace("$metadata:","");return c=c.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),c=c.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(l,g,M)=>/^{.*}$/.test(M)?`:${M}`:`:${g}"${M}"`),c=c.replace(/\[([^\]]+)\]/g,(l,g)=>`[${g.split(",").map(M=>M.trim().startsWith("{")&&M.trim().endsWith("}")?M.trim():`"${M.trim()}"`).join(",")}]`),c})(e);return JSON.parse(n)}catch(t){return console.error(t),{as:[]}}},Ee=async(e,t)=>{let{enrichedBqlQuery:n,rawBqlRequest:o,schema:i,config:c}=e,{rawTqlRes:l,isBatched:g}=t;if(n){if(!l)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");let M=(s,h)=>{let{$metaData:m}=s,{as:E}=Sn(m),$=Object.entries(s).filter(([k])=>k!=="type"&&!k.includes("$")).map(([k,P])=>{let C=h.dataFields?.find(y=>y.path===k||y.dbPath===k),B=k==="id",b=Array.isArray(E)?E.find(y=>y[k])?.[k]:k,L;if(C?.cardinality==="ONE"){if(L=P[0]?P[0].value:c.query?.returnNulls?null:void 0,C.contentType==="DATE"&&(L=L&&`${L}Z`),B)return [[b,L],["$id",L]].filter(([y,I])=>I!==void 0)}else if(C?.cardinality==="MANY"){if(!radash.isArray(P))throw new Error("Typedb fetch has changed its format");if(P.length===0)return c.query?.returnNulls?[[b,null]]:[];C.contentType==="DATE"?L=P.map(y=>`${y.value}Z`):L=P.map(y=>y.value);}return [[b,L]].filter(([y,I])=>I!==void 0)}).flat();return Object.fromEntries([...$])},u=s=>s.reduce((h,m)=>{let{$roleFields:E,$metaData:$,$cardinality:k}=m,{as:P,justId:C,idNotIncluded:B,filterByUnique:b}=Fe($),L=E.map(y=>{let{dataFields:I,currentSchema:T,linkFields:A,roleFields:F,schemaValue:w}=d(y),Q=M(I,T);if(C==="T")return Q.id;{let R=r(A),O=u(F),N={...Q};return B==="true"&&T?.idFields?.forEach(D=>delete N[D]),{...N,...R,...O,...w}}});return L.length>0?h[P]=k==="MANY"&&b==="false"?L:L[0]:c.query?.returnNulls&&(h[P]=null),h},{}),r=s=>s.reduce((h,m)=>{let{$linkFields:E,$metaData:$,$cardinality:k}=m,{as:P,justId:C,idNotIncluded:B,filterByUnique:b}=Fe($),L=E.map(y=>{let{dataFields:I,currentSchema:T,linkFields:A,roleFields:F,schemaValue:w}=d(y),Q=M(I,T);if(C==="T")return Q.id;{let R=r(A),O=u(F),N={...Q};return B==="true"&&T.idFields?.forEach(D=>delete N[D]),{...N,...R,...O,...w}}});return h[P]=L.length>0?k==="MANY"&&b==="false"?L:L[0]:c.query?.returnNulls?null:void 0,h},{}),d=s=>{let h=Object.keys(s),m=h.find(y=>y.endsWith(".$dataFields"));if(!m)throw new Error("No datafields");let E=s[m],$=m.split(".")[m.split(".").length-2];if(E.$metaData=$,E.length===0)throw new Error("No datafields");let k=E.type,P={$thing:k.label,$thingType:k.root,[K]:s.queryPath.value},C={[`$${P.$thingType}`]:P.$thing},B=S(i,C),b=h.filter(y=>!y.endsWith(".$dataFields")&&B.linkFields?.some(I=>I.path===y.split(".").pop())).map(y=>({$linkFields:s[y],$key:y.split(".").pop(),$metaData:y.split(".")[y.split(".").length-2],$cardinality:B?.linkFields?.find(I=>I.path===y.split(".").pop())?.cardinality})),L=h.filter(y=>!y.endsWith(".$dataFields")&&B.roles?.[y.split(".").pop()]).map(y=>({$roleFields:s[y],$key:y.split(".").pop(),$metaData:y.split(".")[y.split(".").length-2],$cardinality:B.roles[y.split(".").pop()].cardinality}));return {dataFields:E,schemaValue:P,currentSchema:B,linkFields:b,roleFields:L}},a=s=>s.map(h=>{let{dataFields:m,currentSchema:E,linkFields:$,roleFields:k,schemaValue:P}=d(h),C=M(m,E),B=r($),b=u(k),L=o?.$fields?.every(I=>!E?.idFields?.includes(I)&&!E?.idFields?.includes(I.$path));return {...B,...b,...P,...!c.query?.noMetadata&&o.$id?{$id:Array.isArray(o.$id)?C.id:o.$id}:{},...L?Object.fromEntries(Object.entries(C).filter(([I])=>!E?.idFields?.includes(I))):C}}),p=(s=>{let h=m=>{let E=a(m);return o.$id&&!Array.isArray(o.$id)||n[0].$filterByUnique?E[0]??null:E.length===0?null:E};return g?s.map(h):h(s)})(l);t.bqlRes=p;};var qn=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Dn=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,we=e=>{let n=e.toString().replace(qn,"").trim().split("=>")[0].split("{")[0].replace(Dn,"").trim(),o=n.substring(n.indexOf("(")+1,n.lastIndexOf(")")).trim();return o?(o.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(c=>c.includes("{")&&c.includes("}")?(c.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(g=>g.split(":")[0].trim().replace(/['"[\]]/g,"")):c.trim()).filter(Boolean):[]};var pt=({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:i}=t.default,l=we(i).filter(g=>!(g in e));if(l.length)throw new Error(`Virtual field: Missing arguments ${l.join(", ")}`)}return "default"in t?t.default?.fn(e):void 0};var be=async(e,t)=>{let{schema:n,enrichedBqlQuery:o}=e,{bqlRes:i}=t;if(!i)return;let l=(g=>immer.produce(g,M=>objectTraversal.traverse(M,({value:u})=>{if(radash.isObject(u)){let r=u;if(!r.$thing)throw new Error("[Internal] Thing is missing");if(r.$thing){let d=S(n,r),{virtualFields:a}=d,f=r[K];if(!f)throw new Error("[Internal] QueryPath is missing");let p=objectTraversal.getNodeByPath(o,f),s=p.$fields.map(m=>m.$path),h=p.$excludedFields;a.forEach(m=>{if(h?.includes(m)||s.length>0&&!s.includes(m))return;let E=d.dataFields?.find($=>$.path===m);if(E?.default){let $=pt({currentThing:r,fieldSchema:E,mandatoryDependencies:!0});r[m]=$;}else if(r[m]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${m}`)}),h&&h.forEach(m=>{if(typeof m!="string")throw new Error("[Internal] ExcludedField is not a string");delete r[m];});}}})))(i);t.bqlRes=l;};var Le=async(e,t)=>{let{config:n}=e,{bqlRes:o}=t;if(!o)return;let c=(M=>immer.produce(M,u=>objectTraversal.traverse(u,({value:r})=>{radash.isObject(r);})))(o),g=(M=>immer.produce(M,u=>objectTraversal.traverse(u,({value:r})=>{if(radash.isObject(r)){let d=r;Object.keys(d).forEach(a=>{d[a]===void 0&&delete d[a];}),Object.getOwnPropertySymbols(d).forEach(a=>{delete d[a];}),n.query?.noMetadata===!0&&Object.keys(d).forEach(a=>{a.startsWith("$")&&delete d[a];});}})))(c);t.bqlRes=g;};var _n={query:[ye,$e,Be,Ee,be,Le]},Qe=async(e,t,n={},o=!0)=>{for(let i of e){let c=await i(t,n);if(c&&Array.isArray(c))for(let l of c)await Qe(l.pipeline,l.req,l.res,!1);}return o&&t.config.query?.debugger===!0&&typeof n.bqlRes=="object"?{...n.bqlRes,$debugger:{tqlRequest:t.tqlRequest}}:n.bqlRes},Lt=(e,t,n,o)=>Qe(_n.query,{config:t,schema:n,rawBqlRequest:e,dbHandles:o},{});var ut=(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 Ie=(e,t,n)=>{let o=radash.isArray(e[t])?e[t]:[e[t]];if(!o.every(i=>typeof i=="object"))if(o.every(i=>typeof i=="string")){let i=ut(t,n),[c]=i,l=e.$op==="create"?"link":"replace",g=c.thing,M=c.thingType;if(o.some(u=>u.startsWith("_:")))throw new Error("[Not supported] At least one child of a replace is a tempId");e[t]={$id:e[t],$op:l,$thing:g,$thingType:M,$bzId:`S_${uuid.v4()}`};}else throw new Error("[Mutation Error] Replace can only be used with a single id or an array of ids")};var Et=(e,t,n)=>{let o=S(n,t),{usedDataFields:i}=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"&&i.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&i.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var Qt=(e,t,n)=>{let o=S(n,t),{usedFields:i}=J(o,t);return t.$op?(Et(e,t,n),t.$op):t.$id||t.$filter?i.length>0?(Et(e,{...t,$op:"update"},n),"update"):(Et(e,{...t,$op:"link"},n),"link"):(Et(e,{...t,$op:"create"},n),"create")};var Ae=(e,t)=>{let o=(radash.isArray(e.$root)?e.$root:[e.$root]).map(i=>{let c=Qt(i,i,t);return {...{...i.$thing?{}:{$thing:i.$entity||i.$relation},...i.$thingType?{}:{$thingType:ue(i,t)},...i.$op?{}:{$op:c},...i.$bzId?{}:{$bzId:`R_${uuid.v4()}`}},...i}});e.$root=radash.isArray(e.$root)?o:o[0];};var It=(e,t)=>{let n=t[kt];return types.isSet(n)?n.has("clean")?(Reflect.set(t,kt,n.add("clean")),!0):!1:(Reflect.set(t,kt,new Set(["clean"])),!0)};var Ce=(e,t,n)=>{if(It("split_ids",e)){let o=(radash.isArray(e[t])?e[t]:[e[t]]).flatMap(i=>{if(radash.isObject(i)&&"$id"in i&&radash.isArray(i.$id)){let c=i;if(S(n,c),!c.$bzId)throw new Error("[Internal Error] No bzId found");return c.$id.map((l,g)=>({...U(c),$id:l,$bzId:`${c.$bzId}_${g}`,...Z(c)}))}return i});(o.length>radash.isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=o);}};var Oe=(e,t,n,o)=>{let i=(radash.isArray(e[t])?e[t]:[e[t]]).map(c=>{let l=ut(t,n),[g]=l,M=Qt(e,{...c,$thing:g.thing,$thingType:g.thingType},o),u=c.$bzId?c.$bzId:c.$tempId?c.$tempId:`N_${uuid.v4()}`;return {...c,[rt]:n,$thing:g.thing,$thingType:g.thingType,$op:M,$bzId:u}});e[t]=radash.isArray(e[t])?i:i[0];};var Se=(e,t,n)=>{let o=e[t];o&&(radash.isArray(o)?o:[o]).forEach(i=>{let c=S(n,i),{unidentifiedFields:l}=J(c,i),{computedFields:g,virtualFields:M}=c,u=radash.listify(i,(a,f)=>f!==void 0?a:void 0),r=u.filter(a=>M?.includes(a));if(r.length>0)throw new Error(`Virtual fields can't be sent to DB: "${r.join(",")}"`);if(g.filter(a=>!u.includes(a)).forEach(a=>{let f=c.dataFields?.find(E=>E.path===a),s=c.linkFields?.find(E=>E.path===a)?.oppositeLinkFieldsPlayedBy[0],h="roles"in c?de(c.roles,(E,$)=>E===a):void 0,m=f||s||h;if(!m)throw new Error(`no field Def for ${a}`);if(i.$op==="create"&&!i[a]){let E=pt({currentThing:i,fieldSchema:m,mandatoryDependencies:!0});i[a]=E;}}),l.length>0)throw new Error(`Unknown fields: [${l.join(",")}] in ${JSON.stringify(i)}`)});};var qe=(e,t,n)=>{let o=ut(t,n),[i]=o;e[t]={$thing:i.thing,$thingType:i.thingType,$op:"unlink",$bzId:`U_${uuid.v4()}`,[rt]:n};};var Pt=(e,t)=>{let n=S(t,e).hooks;if(n?.pre){let o=`on${he(e.$op)}`;return n.pre.filter(l=>l.triggers[o]?.()).flatMap(l=>l.actions)}return []};var je=(e,t,n)=>{(radash.isArray(e[t])?e[t]:[e[t]]).forEach(i=>{if("$thing"in i){let{requiredFields:c,enumFields:l,fnValidatedFields:g,dataFields:M}=S(n,i);if("$op"in i&&i.$op==="create"&&c.forEach(u=>{if(!(u in i))throw new Error(`[Validations] Required field "${u}" is missing.`)}),("$op"in i&&i.$op==="update"||i.$op==="create")&&l.forEach(u=>{if(u in i){let r=M?.find(d=>d.path===u)?.validations?.enum;if(!r)throw new Error(`[Validations] Enum field "${u}" is missing enum options.`);if(radash.isArray(i[u]))i[u].some(d=>{if(!r.includes(d))throw new Error(`[Validations] Option "${d}" is not a valid option for field "${u}".`)});else if(r&&!r.includes(i[u]))throw new Error(`[Validations] Option "${i[u]}" is not a valid option for field "${u}".`)}}),("$op"in i&&i.$op==="update"||i.$op==="create")&&g.forEach(u=>{if(u in i)try{let r=M?.find(d=>d.path===u)?.validations?.fn;if(!r)throw new Error("Missing validation function.");if(!r(i[u]))throw new Error("Failed validation function.")}catch(r){throw new Error(`[Validations:attribute:${u}] ${r.message}`)}}),radash.isObject(i)&&"$thing"in i){let u=i.$thing,r=i,d=radash.clone(U(e)),a=radash.clone(U(r));Pt(r,n).forEach(p=>{if(p.type==="validate"){if(p.severity!=="error")return;try{let s=p.fn(a,d);if(s===!1)throw new Error(`${p.message}.`);if(s!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(s){throw new Error(`[Validations:thing:${u}] ${s.message}`)}}});}}});};var _e=(e,t,n)=>{let o=(radash.isArray(e[t])?e[t]:[e[t]]).map(i=>{if(Mt(i)){let c=Pt(i,n).filter(M=>M.type==="transform"),l=radash.clone(U(e)),g=radash.clone(U(i));return c.forEach(M=>{let u=M.fn(g,l);Object.keys(u).length!==0&&(i={...g,...u});}),i}});e[t]=radash.isArray(e[t])?o:o[0];};var ir=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(It("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")},or=(e,t)=>{},Zt=(e,t)=>{let o=immer.produce({$rootWrap:{$root:e}},i=>objectTraversal.traverse(i,({value:c,parent:l,key:g,meta:M})=>{if(!(!l||!g)&&radash.isObject(c)){if(!("$root"in c)){if(!("$thing"in c||"$entity"in c||"$relation"in c))throw g==="$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(c)?immer.current(c):c)}`)}let u=c;Object.keys(u).forEach(r=>{if(ir(u,r),r!=="$root"&&r.startsWith("$"))return;let d=r!=="$root"?_t(t,u,r):{fieldType:"rootField"};if(!d)throw new Error(`[Internal] Field ${r} not found in schema`);if("contentType"in d)return or();if(["rootField","linkField","roleField"].includes(d.fieldType)){if(["linkField","roleField"].includes(d.fieldType)&&Ie(u,r,d),d.fieldType==="rootField"){if(!("$root"in u))throw new Error(`[Internal] Field ${r} is a rootField but the object is not a root`);Ae(u,t);}let a=radash.isArray(u[r])?u[r]:[u[r]],f=M.nodePath?.split(".").slice(1).join(".");a.forEach(s=>{if(s){if(d?.cardinality==="ONE"&&!s.$op&&!s.$id&&!s.$filter&&!s.$tempId&&u.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${f}.${r}`);if(s.$tempId&&!(s.$op===void 0||s.$op==="link"||s.$op==="create"||s.$op==="update"))throw new Error(`Invalid op ${s.$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(d.fieldType)&&(u[r]===null?qe(u,r,d):Oe(u,r,d,t)),Ce(u,r,t),["rootField","linkField","roleField"].includes(d.fieldType)&&Se(u,r,t),(radash.isArray(u[r])?u[r]:[u[r]]).forEach(s=>{let h=S(t,s),{unidentifiedFields:m,usedLinkFields:E}=J(h,s);if(m.length>0)throw new Error(`Unknown fields: [${m.join(",")}] in ${JSON.stringify(c)}`);if(E.length>1){let $=h.linkFields?.filter(k=>E.includes(k.path));$?.some((k,P)=>$.some((C,B)=>{if(P!==B&&k.target!==C.target&&k.relation===C.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),_e(u,r,t),je(u,r,t);}});}}));return radash.isArray(o.$rootWrap.$root),o.$rootWrap.$root};var We=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 Ft(t,n),i=await o.transaction(typedbDriver.TransactionType.WRITE);if(!i)throw new Error("Can't create transaction");let c=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,l=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;c&&await i.query.delete(c);let g=l&&i.query.insert(l);try{let M=g?await g.collect():void 0;return await i.commit(),await i.close(),{insertions:M}}catch(M){throw await i.close(),new Error(`Transaction failed: ${M.message}`)}};var Ve=async(e,t,n,o)=>{let i=[...t,...n],c=i.map(l=>{let g=e.insertions?.find(M=>M.get(`${l.$bzId}`))?.get(`${l.$bzId}`);if(l.$op==="create"||l.$op==="update"||l.$op==="link"){if(l.$op!=="update"&&!g&&l.$id)return {$id:l.$id,$error:"Does not exist or it's not linked to the parent"};let M=g?.asThing().iid;if(o.mutation?.noMetadata)return Object.entries(l).filter(([d,a])=>!d.startsWith("$")).reduce((d,[a,f])=>{if(l.$thingType==="relation"){let p=i.filter(s=>s.$id&&s.$bzId===f);if(p.length>1)throw new Error(`Multiple things with the same bzId ${f}`);return p.length===1?(d[a]=p[0].$id,d):(d[a]=f,d)}return d[a]=f,d},{});let u=l.$tempId&&!l.$tempId.startsWith("_:")?{$tempId:`_:${l.$tempId}`}:{};return {$dbId:M,...l,[l.path]:l.$id,...u}}if(l.$op==="delete"||l.$op==="unlink")return l;if(l.$op!=="match")throw new Error(`Unsupported op ${l.$op}`)}).filter(l=>l);return radash.clone(c)};var ve=e=>{let t=({value:n})=>(n&&typeof n=="object"&&"$id"in n&&(Object.keys(n).filter(c=>c.startsWith("$")).forEach(c=>delete n[c]),Object.keys(n).filter(c=>typeof c=="symbol").forEach(c=>delete n[c])),n);return immer.produce(e,n=>objectTraversal.traverse(n,t))};var Je=async(e,t)=>{let n=u=>{let r=[],d=[],a=h=>{if(h.$id)return h.$id;let m=S(t,h),{idFields:E}=m;if(!E)throw new Error(`no idFields: ${JSON.stringify(h)}`);let[$]=E;if(!$)throw new Error(`no idField: ${JSON.stringify(h)}`);let k=m.dataFields?.find(B=>B.path===$),P=pt({currentThing:h,fieldSchema:k,mandatoryDependencies:!0}),C=h[$]||h.$id||P;if(!C)throw new Error(`no idValue: ${JSON.stringify(h)}`);return C},f=h=>{if(h.$op==="create"){let m=a(h);if(r.find(E=>E.$id===m))throw new Error(`Duplicate id ${m} for node ${JSON.stringify(h)}`);if(d.find(E=>E.$bzId===h.$bzId))throw new Error(`Duplicate $bzid ${h.$bzId} for node ${JSON.stringify(h)}`);r.push({...h,$id:m});return}h.$tempId&&h.$op==="match"||r.push(h);},p=h=>{if(h.$op==="create"){let m=a(h);if(r.find(E=>E.$id===m),d.find(E=>E.$bzId===h.$bzId))throw new Error(`Duplicate %bzId ${h.$bzIdd} for edge ${JSON.stringify(h)}`);d.push({...h,$id:m});return}d.push(h);};return objectTraversal.traverse(u,({value:h,parent:m,meta:E})=>{if(!radash.isObject(h))return;let $=h;if($.$thing){if(!$.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify($)}`);if(!$.$bzId)throw new Error("[internal error] BzId not found");let k=S(t,$),{dataFields:P,roleFields:C,linkFields:B,usedFields:b}=J(k,$),L=()=>{if($.$op==="create"||$.$op==="delete")return $.$op;if($.$op==="update"){let T=b.filter(w=>P?.includes(w)),A=b.filter(w=>C?.includes(w)),F=b.filter(w=>B?.includes(w));if(T.length>0)return "update";if(A.length>0||F.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify($)}`)}return "match"},y={...$.$id&&{$id:$.$id},...$.$tempId&&{$tempId:$.$tempId},...$.$filter&&{$filter:$.$filter},$thing:$.$thing,...$.$thingType&&{$thingType:$.$thingType},...radash.shake(radash.pick($,P||[""])),$op:L(),$bzId:$.$tempId?$.$tempId:$.$bzId};f(y);let I=$[rt];if(I?.fieldType==="linkField"){if(($.$op==="link"||$.$op==="unlink")&&($.$id||$.$filter)){if($.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");r.push({...$,$op:"match"});}let T=I.relation===$.$thing,A=T?$.$bzId:`LT_${uuid.v4()}`,w=fe(u,m,E).$bzId;if(!w)throw new Error("No parent id found");if($[Symbol.for("relation")]==="$self")return;let Q=()=>{if($.$op==="delete")return T?"match":"delete";if($.$op==="unlink")return T?"unlink":"delete";if($.$op==="link"||$.$op==="create")return T?"link":"create";if($.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},R={$bzId:A,$thing:I.relation,$thingType:"relation",...$.$tempId?{$tempId:$.$tempId}:{},$op:Q(),...T?{}:{[I.path]:$.$bzId},[I.plays]:w,[rt]:I,[at]:"linkField"};p(R),($.$op==="unlink"||Q()==="unlink")&&T&&p({$thing:I.relation,$thingType:"relation",$bzId:A,$op:"match",[I.plays]:w,[rt]:I,[at]:"linkField"});}if($.$thingType==="relation"){let T=Bt($,(w,Q)=>C.includes(w)),A=radash.mapEntries(T,(w,Q)=>radash.isArray(Q)?[w,Q]:radash.isObject(Q)?[w,Q.$bzId]:[w,Q]),F=Bt(h,(w,Q)=>w.startsWith("$")||w.startsWith("Symbol"));if(Object.keys(T).filter(w=>!w.startsWith("$")).length>0){if($.$op==="create"||$.$op==="delete"){let w=()=>{if($.$op==="create")return "link";if($.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},Q=S(t,$).roles,R=radash.mapEntries(A,(N,D)=>{let z=Q[N]?.cardinality;if(!z)throw new Error(`Role ${N} not found in schema`);if(Array.isArray(D)){if(z==="ONE"){if(D.length>1)throw new Error(`[Error] Role ${N} is not a MANY relation`);return [N,D[0].$bzId||D[0]]}return [N,D.map(H=>H.$bzId||H)]}return [N,D.$bzId||D]}),O={...F,$thing:$.$thing,$thingType:"relation",$op:w(),...R,$bzId:$.$bzId,[at]:"roleField"};p(O);return}if($.$op==="match"||$.$op==="update"&&Object.keys(T).length>0){let w=0;Object.entries(T).forEach(([Q,R])=>{let O=radash.isArray(R)?R:[R],N=D=>D==="create"||D==="replace"?"link":D;O.forEach(D=>{if(!D)return;let z=N(D.$op);if(z==="replace")throw new Error("Not supported yet: replace on roleFields");if(z==="unlink"&&w>0)throw w+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let H={...F,$thing:$.$thing,$thingType:"relation",$op:z==="delete"?"unlink":z,[Q]:D.$bzId,$bzId:$.$bzId,[at]:"roleField"};p(H);});});}}}}}),[r,d]},[o,i]=n(e),c=o.reduce((u,r)=>{if(!r.$bzId)return [...u,r];let d=u.findIndex(a=>a.$bzId===r.$bzId);if(d===-1)return [...u,r];if(u[d].$op==="create"&&r.$op==="match")return u;if(u[d].$op==="match"&&(r.$op==="create"||r.$op==="match"))return [...u.slice(0,d),r,...u.slice(d+1)];throw new Error(`[Wrong format] Wrong operation combination for $tempId "${r.$tempId}". Existing: ${u[d].$op}. Current: ${r.$op}`)},[]),l=i.reduce((u,r)=>{let d=u.find(a=>(a.$id&&a.$id===r.$id||a.$bzId&&a.$bzId===r.$bzId)&&a.$thing===r.$thing&&a.$op===r.$op);if(d){let a={...d};return Object.keys(r).forEach(p=>{if(typeof p=="symbol"||p.startsWith("$"))return;let s=d[p],h=r[p];Array.isArray(s)&&Array.isArray(h)?a[p]=Array.from(new Set([...s,...h])):!Array.isArray(s)&&Array.isArray(h)?s!==void 0?a[p]=Array.from(new Set([s,...h])):a[p]=h:Array.isArray(s)&&!Array.isArray(h)?h!==void 0&&(a[p]=Array.from(new Set([...s,h]))):s!==null&&h!==null&&s!==void 0&&h!==void 0?a[p]=Array.from(new Set([s,h])):s==null&&(a[p]=h);}),[...u.filter(p=>!((p.$id&&p.$id===r.$id||p.$bzId&&p.$bzId===r.$bzId)&&p.$thing===r.$thing&&p.$op===r.$op)),a]}return [...u,r]},[]);c.forEach(u=>{if((u.$thingType==="relation"||"relation"in u)&&l.filter(r=>r.$bzId===u.$bzId||r.$tempId&&r.$tempId===u.$tempId).length===0){if(u.$op==="delete"||u.$op==="match"||u.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(ve(u))}`)}});let g=[...c,...l];return new Set(g.filter(u=>u.$tempId).map(u=>u.$tempId)).forEach(u=>{if(g.filter(r=>r.$tempId===u&&r.$op==="create").length===0)throw new Error("Can't link a $tempId that has not been created in the current mutation.")}),{mergedThings:c,mergedEdges:l}};var Ze=async(e,t,n)=>{let o=a=>{let f=a.$op,p=`$${a.$bzId}`,s=S(n,a),{idFields:h,defaultDBConnector:m}=s,E=m?.path||a.$thing,$=a.$id,k=h?.[0],P=radash.listify(a,(A,F)=>{if(A.startsWith("$")||A===k||F===void 0||F===null)return "";let w=s.dataFields?.find(O=>O.path===A);if(!w?.path)return "";let R=w.dbPath;if(["TEXT","ID","EMAIL"].includes(w.contentType))return `has ${R} '${F}'`;if(["NUMBER","BOOLEAN"].includes(w.contentType))return `has ${R} ${F}`;if(w.contentType==="DATE"){if(Number.isNaN(F.valueOf()))throw new Error("Invalid format, Nan Date");return F instanceof Date?`has ${R} ${F.toISOString().replace("Z","")}`:`has ${R} ${new Date(F).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${w.contentType}`)}).filter(A=>A),C=`${p}-atts`,B=radash.listify(a,A=>{if(A.startsWith("$")||A===k)return "";let F=s.dataFields?.find(R=>R.path===A);if(!F?.path)return "";let Q=F.dbPath;return `{${C} isa ${Q};}`}).filter(A=>A),b=radash.isArray($)?`like '${$.join("|")}'`:`'${$}'`,L=$?[`has ${k} ${b}`]:[],y=[...L,...P].filter(A=>A).join(","),I=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${p} isa ${[E,...L].filter(A=>A).join(",")};`;if(f==="update"){if(!B.length)throw new Error("update without attributes");return `${p} isa ${[E,...L].filter(A=>A).join(",")}, has ${C};
61
+ ${B.join(" or ")};`}return ""},T=()=>f==="update"||f==="link"||f==="match"?`${p} isa ${[E,...L].filter(A=>A).join(",")};`:"";if(Mt(a))return {op:f,deletionMatch:I(),insertionMatch:T(),insertion:f==="create"?`${p} isa ${[E,y].filter(A=>A).join(",")};`:f==="update"&&P.length?`${p} ${P.join(",")};`:"",deletion:f==="delete"?`${p} isa ${E};`:f==="update"&&B.length?`${p} has ${C};`:""};throw new Error("in attributes")},i=a=>{let f=a.$op,p=S(n,a),s=`$${a.$bzId}`,h=a.$id,m=p.defaultDBConnector?.path||a.$thing,E="roles"in p?radash.listify(p.roles,F=>F):[],$="roles"in p?radash.mapEntries(p.roles,(F,w)=>[F,w.dbConnector?.path||F]):{},k=radash.listify(a,(F,w)=>{if(!E.includes(F))return null;if(!("roles"in p))throw new Error("This should have roles! ");let Q=$[F];return Array.isArray(w)?w.map(R=>({path:Q,id:R})):{path:Q,id:w}}).filter(F=>F).flat(),P=k.map(F=>{if(!F?.path)throw new Error("Object without path");return `${F.path}: $${F.id}`}),C=k.length>0?`( ${P.join(" , ")} )`:"",B=a[at];if(!B)throw new Error("[internal error] Symbol edgeType not defined");let b=C?`${s} ${C} ${B==="linkField"||f==="delete"||f==="unlink"?`isa ${m}`:""}`:"",L=`${s} ${B==="linkField"||f==="delete"?`isa ${m}`:""}`,y=()=>b?f==="link"?`${b};`:f==="create"?`${b}, has id '${h}';`:"":"",I=()=>b&&f==="match"?`${b};`:"",T=()=>b?f==="delete"?`${b};`:f==="match"?`${b};`:"":"",A=()=>b?f==="delete"?`${L};`:f==="unlink"?`${s} ${C};`:"":"";return {deletionMatch:T(),insertionMatch:I(),deletion:A(),insertion:y(),op:""}},c=(a,f)=>{let p=f==="edges"?i:o;if(Array.isArray(a))return a.map(k=>{let{preDeletionBatch:P,insertionMatch:C,deletionMatch:B,insertion:b,deletion:L}=p(k);return radash.shake({preDeletionBatch:P,insertionMatch:C,deletionMatch:B,insertion:b,deletion:L},y=>!y)}).filter(k=>k);let{preDeletionBatch:s,insertionMatch:h,deletionMatch:m,insertion:E,deletion:$}=p(a);return radash.shake({preDeletionBatch:s,insertionMatch:h,deletionMatch:m,insertion:E,deletion:$},k=>!k)},l=c(e),g=Array.isArray(l)?l:[l],M=c(t,"edges"),u=Array.isArray(M)?M:[M],r=[...g,...u];return radash.shake({insertionMatches:r.map(a=>a.insertionMatch).join(" ").trim(),deletionMatches:r.map(a=>a.deletionMatch).join(" ").trim(),insertions:r.map(a=>a.insertion).join(" ").trim(),deletions:r.map(a=>a.deletion).join(" ").trim()},a=>!a)};var mr=Symbol.for("grandChildOfCreate"),Ye=async(e,t,n,o)=>{let i=(B,b)=>Object.keys(B).filter(L=>L.startsWith("$")?!1:b?!S(t,B).dataFields?.find(I=>I.path===L):!0);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(n.mutation?.preQuery===!1)return;let c=[];if(objectTraversal.traverse(e,({parent:B,key:b,value:L})=>{B&&b&&!b.includes("$")&&radash.isObject(B)?(Array.isArray(B[b])?B[b]:[B[b]]).forEach(I=>{if(radash.isObject(I)){if(B.$op!=="create")c.includes(I.$op)||c.push(I.$op);else if(I.$op==="delete"||I.$op==="unlink")throw new Error(`Cannot ${I.$op} under a create`)}}):!B&&radash.isObject(L)&&(c.includes(L.$op)||c.push(L.$op));}),!c.includes("delete")&&!c.includes("unlink")&&!c.includes("replace")&&!c.includes("update")&&!c.includes("link"))return;let g=(B=>{let b=(L,y)=>{let I=[],T={},A=["$op","$bzId","$parentKey"],F=["$relation","$entity","$id",...A];for(let w in L)if(!A.includes(w)&&!(F.includes(w)&&!y))if(!w.includes("$")&&(radash.isObject(L[w])||Array.isArray(L[w]))){let Q=L[w];Array.isArray(Q)&&Q.length>0?Q.forEach(R=>{I.push({$path:w,...b(R)});}):I.push({$path:w,...b(Q)});}else T[w]=L[w];return {...T,$fields:I}};return B.map(L=>b(L,!0))})(Array.isArray(e)?e:[e]),M=await Lt(g,n,t,o),u=(B,b)=>{let L=B.$id||B.id||B.$bzId;if(B.$objectPath){let{$objectPath:y}=B,I=y?.beforePath||"root",T=Array.isArray(y.ids)?`[${y.ids}]`:y.ids;return {beforePath:`${I}.${T}___${y.key}`,ids:L,key:b}}else return {beforePath:"root",ids:L,key:b}},r=(B,b)=>{let L=B?.beforePath||"root",y=b||(Array.isArray(B?.ids)?`[${B?.ids}]`:B?.ids);return `${L}.${y}___${B?.key}`},d=B=>{if(B.includes("[")&&B.includes("]")){let[b,L,y]=B.split(/[[\]]/);return L.split(",").map(T=>`${b}${T}${y}`)}else return [B]},a={};(B=>immer.produce(B,b=>objectTraversal.traverse(b,L=>{let{key:y,parent:I}=L;if(I&&y&&I.$id&&!y.includes("$")){let T=u(I,y),A=r(T);if(Array.isArray(I[y])){let F=[];I[y].forEach(w=>{radash.isObject(w)?(w.$objectPath=T,F.push(w.$id.toString())):w&&F.push(w.toString());}),a[A]={$objectPath:T,$ids:F};}else {let F=I[y];radash.isObject(F)?(a[A]={$objectPath:T,$ids:[F.$id.toString()]},F.$objectPath=T):F&&(a[A]={$objectPath:T,$ids:[F.toString()]});}}})))(M||{});let p=B=>immer.produce(B,b=>objectTraversal.traverse(b,L=>{let{key:y,value:I,parent:T}=L;T&&y&&!y.includes("$")&&(Array.isArray(I)||radash.isObject(I))&&!Array.isArray(T)&&(Array.isArray(T[y])?T[y].forEach(A=>{typeof A!="string"&&(A.$objectPath=u(T,y),A.$parentIsCreate=T.$op==="create",A[mr]=T.$parentIsCreate||T[Symbol.for("grandChildOfCreate")]);}):radash.isObject(T[y])&&(T[y].$parentIsCreate=T.$op==="create",T[y][Symbol.for("grandChildOfCreate")]=T.$parentIsCreate||T[Symbol.for("grandChildOfCreate")],T[y].$objectPath=u(T,y)));})),s=p(e),m=(B=>{let b=(T,A)=>{let F=[];T.filter(O=>O).forEach(O=>{let N=Object.keys(O).filter(D=>!D.startsWith("$")).length;if(Array.isArray(O.$id)&&N>0){let D=O.$id.map(z=>({...O,$id:z}));F=[...F,...D];}else F.push({...O});});let w=[],Q=[],R=F.filter(O=>{let D=["delete","update","unlink"].includes(O.$op||""),z=i(O,!0).length;if((!O.$id||Array.isArray(O.$id)&&z>0||O.$filter)&&D)return !0;Q.push({...O});});return R.length>0?R.forEach(O=>{let D=(j=>{let $t=(()=>{let W={};for(let x in j){let nt=S(t,j);!x.startsWith("$")&&nt.dataFields?.find(dt=>dt.path===x)&&(W[x]=j[x]);}return W})(),mt=Object.keys(j),et=mt.filter(W=>!W.startsWith("$")),St=[],bt=(W,x)=>{if(W===et.length){let dt={...x};mt.forEach(V=>{V.startsWith("$")&&(dt[V]=j[V]);}),St.push(dt);return}let nt={...x,[et[W]]:j[et[W]],...Z(x),...$t};bt(W+1,nt),bt(W+1,x);};return bt(0,{...Z(j)}),St})(O).filter(j=>!(j.$op==="update"&&Object.keys(j).filter(ot=>!ot.startsWith("$")).length===0)),z=[],H=r(O.$objectPath),tt=a[H]?a[H].$ids:[],q=D.map((j,ot)=>{let $t=S(t,j),et=Object.keys(j).filter(x=>!x.includes("$")&&!$t.dataFields?.some(nt=>nt.path===x)).map(x=>(Array.isArray(j[x])?j[x].length>1?j[x].filter(V=>!V.$id||Array.isArray(V.$id)||V.$filter):j[x]:[j[x]]).map(V=>{let qt=r(V.$objectPath);return {idsToKey:(Dt=>{let ie=[],gt=Dt.split("."),Bn=gt.slice(0,gt.length-1).join("."),Fn=gt.slice(gt.length-1,gt.length)[0].split("___")[1];for(let xt in a)if(xt.startsWith(Bn)&&xt.endsWith(Fn)){let jt=xt.split("."),En=jt.slice(jt.length-1,jt.length)[0].split("___")[0];ie.push(En);}return ie})(qt),key:x,multiple:V}})).filter(x=>x!==void 0),W=(x=>{let nt=x.map(V=>V.map(st=>st.idsToKey));return (V=>V.length>0?V.reduce((st,yt)=>st.concat(yt),[]).reduce((st,yt)=>st?yt.filter(Dt=>st.includes(Dt)):yt):[])(nt)})(et).filter(x=>!z.includes(x));if(z=[...z,...W],tt=tt.filter(x=>!W.includes(x)),ot===D.length-1&&tt.length>0)return {...j,$id:tt,$bzId:`T1_${uuid.v4()}`,...Z(j)};if(W.length>0)return {...j,$id:W,$bzId:`T2_${uuid.v4()}`,...Z(j)}}).filter(j=>j!==void 0),gn=(()=>{if(q.length===0&&!A?.$id)return R;if(q.length===0&&A?.$id){let j=Array.isArray(A.$id)?A.$id:[A.$id],ot=[];return j.forEach($t=>{let mt=r({...O.$objectPath,ids:$t}),et=a[mt];et&&ot.push({...O,$id:et.$ids,...Z(O),$bzId:`T_${uuid.v4()}`});}),ot}else return q.filter(j=>j!==void 0)})();w=[...Q,...gn].map(L);}):w=F.map(L),w},L=T=>{let A={...T,$bzId:T.$tempId??`T3_${uuid.v4()}`,...Z(T)},F=S(t,T);return Object.keys(T).filter(w=>!w.includes("$")&&!F.dataFields?.some(Q=>Q.path===w)).forEach(w=>{let Q=Array.isArray(T[w])?T[w]:[T[w]],R=b(Q,T);A[w]=R.length>0?R:void 0;}),A},y=[];return B.forEach(T=>{y=[...y,...b([T])];}),y.map(T=>L(T))})(Array.isArray(s)?s:[s]),E=B=>B.map(b=>{let L=i(b,!0),y={...b};return L.forEach(I=>{let T=Array.isArray(b[I])?b[I]:[b[I]],A=[],F=[],w=[],Q={},R=Wt(t,b,I);T.filter(q=>q).forEach(q=>{q.$op==="replace"&&q.$id?(Q=q,Array.isArray(q.$id)?F=[...F,...q.$id]:F.push(q.$id)):q.$op==="create"&&R==="ONE"&&q.id?(Q=q,Array.isArray(q.id)?w=[...F,...q.id]:w.push(q.id)):A.push(q);});let O=r(Q.$objectPath),D=d(O).map(q=>a[q]),z=[];D.filter(q=>q!=null).forEach(q=>{z=[...z,...q.$ids];});let H=z.filter(q=>!F.includes(q)),Ot=F.filter(q=>!z.includes(q)),tt=Z(Q);H.length>0&&A.push({...Q,$op:"unlink",$id:H,$bzId:`T4_${uuid.v4()}`,id:void 0,...tt}),Ot.length>0&&Ot.forEach(q=>{A.push({...Q,$op:"link",$id:q,$bzId:`T5_${uuid.v4()}`,...tt});}),w.length>0&&w.forEach(q=>{A.push({...Q,$op:"create",id:q,$bzId:`T6_${uuid.v4()}`,...tt});}),y[I]=E(A);}),y}),$=p(E(p(m)));return (B=>immer.produce(B,b=>objectTraversal.traverse(b,L=>{let{key:y,value:I,parent:T}=L;y&&T&&!y?.includes("$")&&(Array.isArray(I)||radash.isObject(I))&&!Array.isArray(T)&&(Array.isArray(I)?I:[I]).forEach(F=>{let w=a[r(F.$objectPath)],Q=(N,D)=>N.every(z=>D.includes(z)),R=F.$id?Array.isArray(F.$id)?Q(F.$id,w?w.$ids:[]):w?.$ids.includes(F.$id):w,O=Wt(t,T,F.$objectPath.key);if(F.$op==="link"&&R&&O==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${r(F.$objectPath)}" because it is already occupied.`);if(F.$op)switch(F.$op){case"delete":if(!R&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${F.$id}" because it is not linked to $id:"${T.$id}"`);break;case"update":if(!R&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${F.$id}" because it is not linked to $id:"${T.$id}"`);break;case"unlink":if(!R&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${F.$id}" because it is not linked to $id:"${T.$id}"`);break;case"link":if(R)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${F.$id}" because it is already linked to $id:"${T.$id}"`);break;}});})))($),(B=>immer.produce(B,b=>objectTraversal.traverse(b,L=>{let{value:y,meta:I}=L;radash.isObject(y)&&(y[Symbol.for("path")]=I.nodePath,delete y.$objectPath,delete y.$parentIsCreate);})))($)};function _(e){return {enumerable:!0,value:e}}function Ge(e){return {enumerable:!0,writable:!0,value:e}}var ht={},yr=()=>!0,Xe=()=>({}),en=e=>e,gr=(e,t,n,o)=>e.apply(n,o)&&t.apply(n,o),Br=(e,t,n,[o,i])=>t.call(n,e.call(n,o,i),i),it=(e,t)=>Object.freeze(Object.create(e,t));function tn(e,t,n){return e.reduce((o,i)=>function(...c){return n(o,i,this,c)},t)}function nn(e){return it(this,{fn:_(e)})}var rn={},G=nn.bind(rn);var on={},sn=nn.bind(on);function Rt(e,t){return t.filter(n=>e.isPrototypeOf(n))}function an(e,t,...n){let o=tn(Rt(on,n).map(c=>c.fn),yr,gr),i=tn(Rt(rn,n).map(c=>c.fn),en,Br);return it(this,{from:_(e),to:_(t),guards:_(o),reducers:_(i)})}var ln={},cn={},X=an.bind(ln);an.bind(cn,null);function Fr(e,t,n){return Xt(t,e,n,this.immediates)||e}function dn(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 Er={enter:en};function pn(...e){let t=Rt(ln,e),n=Rt(cn,e),o={final:_(e.length===0),transitions:_(dn(t))};return n.length&&(o.immediates=_(n),o.enter=_(Fr)),it(Er,o)}var wr={enter(e,t,n){let o=this.fn.call(t,t.context,n);return Gt.isPrototypeOf(o)?it(un,{machine:_(o),transitions:_(this.transitions)}).enter(e,t,n):(o.then(i=>t.send({type:"done",data:i})).catch(i=>t.send({type:"error",error:i})),e)}},un={enter(e,t,n){if(t.child=te(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,Xt(t,e,{type:"done",data:o},this.transitions.get("done"))}return e}};function ct(e,...t){let n=_(dn(t));return Gt.isPrototypeOf(e)?it(un,{machine:_(e),transitions:n}):it(wr,{fn:_(e),transitions:n})}var Gt={get state(){return {name:this.current,value:this.states[this.current]}}};function hn(e,t,n=Xe){return typeof e!="string"&&(n=t||Xe,t=e,e=Object.keys(t)[0]),ht._create&&ht._create(e,t),it(Gt,{context:_(n),current:_(e),states:_(t)})}function Xt(e,t,n,o){let{context:i}=e;for(let{to:c,guards:l,reducers:g}of o)if(l(i,n)){e.context=g.call(e,i,n);let M=t.original||t,u=it(M,{current:_(c),original:{value:M}});ht._onEnter&&ht._onEnter(t,c,e.context,i,n);let r=u.state.value;return e.machine=u,e.onChange(e),r.enter(u,e,n)}}function br(e,t){let n=t.type||t,{machine:o}=e,{value:i,name:c}=o.state;return i.transitions.has(n)?Xt(e,o,t,i.transitions.get(n))||o:(ht._send&&ht._send(n,c),o)}var Tr={send(e){br(this,e);}};function te(e,t,n,o){let i=Object.create(Tr,{machine:Ge(e),context:Ge(e.context(n,o)),onChange:_(t)});return i.send=i.send.bind(i),i.machine=i.machine.state.value.enter(i.machine,i,o),i}var fn=pn,ee=(e,t)=>t.data?{...e,bql:{...e.bql,current:t.data}}:e,Mr=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),kr=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),Lr=(e,t)=>({...e,typeDB:{...e.typeDB,tqlMutation:t.data}}),Qr=(e,t)=>({...e,typeDB:{...e.typeDB,tqlRes:t.data}}),Ir=async e=>Object.keys(e.bql.current).length?Zt(e.bql.current,e.schema):Zt(e.bql.raw,e.schema),Pr=async e=>Ye(e.bql.current,e.schema,e.config,e.handles),Ar=async e=>Je(e.bql.current,e.schema),Cr=async e=>Ze(e.bql.things,e.bql.edges,e.schema),Rr=async e=>We(e.typeDB.tqlMutation,e.handles,e.config),Or=async e=>Ve(e.typeDB.tqlRes,e.bql.things,e.bql.edges,e.config),Sr=()=>!0,ft=X("error","error",G((e,t)=>({...e,error:t.error}))),qr=hn("enrich",{enrich:ct(Ir,X("done","preQuery",sn(Sr),G(ee)),X("done","parseBQL",G(ee)),ft),preQuery:ct(Pr,X("done","parseBQL",G(ee)),ft),parseBQL:ct(Ar,X("done","buildMutation",G(kr)),ft),buildMutation:ct(Cr,X("done","runMutation",G(Lr)),ft),runMutation:ct(Rr,X("done","parseMutation",G(Qr)),ft),parseMutation:ct(Or,X("done","success",G(Mr)),ft),success:fn(),error:fn()},e=>e),Dr=async e=>new Promise((t,n)=>{te(qr,o=>{o.machine.state.name==="success"&&t(o.context),o.machine.state.name==="error"&&n(o.context);},e);}),$n=async(e,t,n,o)=>Dr({bql:{raw:e,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:t,config:n,handles:o,depthLevel:0,error:null});immer.enableMapSet();var re=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[i,c]=await radash.tryit(typedbDriver.TypeDB.coreDriver)(o.url);if(i){let l=`[BORM:${o.provider}:${o.dbName}:core] ${i.message??"Can't create TypeDB Client"}`;throw new Error(l)}try{let l=await c.session(o.dbName,typedbDriver.SessionType.DATA);t.typeDB.set(o.id,{client:c,session:l});}catch(l){let g=`[BORM:${o.provider}:${o.dbName}:session] ${(l.messageTemplate?._messageBody()||l.message)??"Can't create TypeDB Session"}`;throw new Error(g)}}if(o.provider==="typeDBCluster"&&o.dbName){let[i,c]=await radash.tryit(typedbDriver.TypeDB.cloudDriver)(o.addresses,o.credentials);if(i){let l=`[BORM:${o.provider}:${o.dbName}:core] ${i.message??"Can't create TypeDB Cluster Client"}`;throw new Error(l)}try{let l=await c.session(o.dbName,typedbDriver.SessionType.DATA);t.typeDB.set(o.id,{client:c,session:l});}catch(l){let g=`[BORM:${o.provider}:${o.dbName}:session] ${(l.messageTemplate?._messageBody()||l.message)??"Can't create TypeDB Session"}`;throw new Error(g)}}}));let n=pe(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(),se(this.config,this.schema,this.dbHandles));query=async(t,n)=>{await this.#t();let o={...this.config,query:{...Nt.query,...this.config.query,...n}};return Lt(t,o,this.schema,this.dbHandles)};mutate=async(t,n)=>{await this.#t();let o={...this.config,mutation:{...Nt.mutation,...this.config.mutation,...n}},[i,c]=await radash.tryit($n)(t,this.schema,o,this.dbHandles);if(i)throw console.error(i.error.stack.split(`
83
62
  `).slice(0,4).join(`
84
- `)),new Error(a.error.message);return d.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:n})=>{n.isOpen()&&await n.close(),await t.close();});}},Es=Zt;//! Todo: delete when this works with the new $thing and $thingType fields
63
+ `)),new Error(i.error.message);return c.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:n})=>{n.isOpen()&&await n.close(),await t.close();});}},Hs=re;//! Todo: delete when this works with the new $thing and $thingType fields
85
64
  //! Todo: Sandbox the function in computeFunction()
86
65
  //! reads all the insertions and gets the first match. This means each id must be unique
87
66
  //!old
88
67
 
89
- module.exports = Es;
68
+ module.exports = Hs;
package/dist/index.mjs CHANGED
@@ -3,65 +3,64 @@ import { TransactionType, TypeDB, SessionType, TypeDBOptions } from 'typedb-driv
3
3
  import { enableMapSet, produce, isDraft, current } from 'immer';
4
4
  import { traverse, getNodeByPath } from 'object-traversal';
5
5
  import { v4 } from 'uuid';
6
- import * as Er from 'robot3';
7
6
  import { isSet } from 'util/types';
8
7
 
9
- var qt={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var er=e=>{let t=[],n=new Map;return e.forEach(p=>{let{dbPath:a,contentType:d}=p,s=`${a}-${d}`;n.has(s)||(n.set(s,!0),t.push(p));}),t},Xt=async(e,t,n)=>{let a=(()=>{let h="",m=[];h+=`
10
- `,Object.keys(t.entities).forEach(M=>{let P=t.entities[M],{idFields:R,dataFields:g,linkFields:b,name:k}=P,y=[],I=[],T=[];if("extends"in P){let F=t.entities[P.extends];F.dataFields&&F.dataFields.forEach(w=>{y.push(w.dbPath);}),F.linkFields&&F.linkFields.forEach(w=>{I.push(w.path);}),F.idFields&&F.idFields.forEach(w=>{T.push(w);});}h+=`${k} sub ${"extends"in P?P.extends:"entity"},
11
- `;let A=[];if(R&&R.length>0){let F=new Set(R),Q=Array.from(F).map(C=>`${C}`).join(", ");T.includes(Q)||(h+=` owns ${Q} @key,
12
- `,A.push(Q));}if(g&&g.length>0&&g.forEach(F=>{!y.includes(F.dbPath)&&!A.includes(F.dbPath)&&(h+=` owns ${F.dbPath},
13
- `),m.push({dbPath:F.dbPath,contentType:F.contentType});}),b&&b.length>0){let F=[];b.forEach(w=>{let{relation:Q,plays:C}=w;!I.includes(w.path)&&!F.includes(`${Q}:${C}`)&&(h+=` plays ${Q}:${C},
14
- `,F.push(`${Q}:${C}`));});}h=h.replace(/,\s*$/,`;
8
+ var Nt={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var bn=e=>{let t=[],n=new Map;return e.forEach(o=>{let{dbPath:i,contentType:c}=o,l=`${i}-${c}`;n.has(l)||(n.set(l,!0),t.push(o));}),t},se=async(e,t,n)=>{let i=(()=>{let h="",m=[];h+=`
9
+ `,Object.keys(t.entities).forEach(k=>{let P=t.entities[k],{idFields:C,dataFields:B,linkFields:b,name:L}=P,y=[],I=[],T=[];if("extends"in P){let F=t.entities[P.extends];F.dataFields&&F.dataFields.forEach(w=>{y.push(w.dbPath);}),F.linkFields&&F.linkFields.forEach(w=>{I.push(w.path);}),F.idFields&&F.idFields.forEach(w=>{T.push(w);});}h+=`${L} sub ${"extends"in P?P.extends:"entity"},
10
+ `;let A=[];if(C&&C.length>0){let F=new Set(C),Q=Array.from(F).map(R=>`${R}`).join(", ");T.includes(Q)||(h+=` owns ${Q} @key,
11
+ `,A.push(Q));}if(B&&B.length>0&&B.forEach(F=>{!y.includes(F.dbPath)&&!A.includes(F.dbPath)&&(h+=` owns ${F.dbPath},
12
+ `),m.push({dbPath:F.dbPath,contentType:F.contentType});}),b&&b.length>0){let F=[];b.forEach(w=>{let{relation:Q,plays:R}=w;!I.includes(w.path)&&!F.includes(`${Q}:${R}`)&&(h+=` plays ${Q}:${R},
13
+ `,F.push(`${Q}:${R}`));});}h=h.replace(/,\s*$/,`;
15
14
  `),h+=`
16
- `;}),Object.keys(t.relations).forEach(M=>{let P=t.relations[M],{idFields:R,dataFields:g,roles:b,name:k,linkFields:y}=P,I=[],T=[],A=[],F=[];if("extends"in P){let Q=t.relations[P.extends];Q.dataFields&&Q.dataFields.forEach(C=>{I.push(C.dbPath);}),Q.linkFields&&Q.linkFields.forEach(C=>{T.push(C.dbPath);}),Q.roles&&Object.values(Q.roles).forEach(S=>{A.push(S.name);}),Q.idFields&&Q.idFields.forEach(C=>{F.push(C);});}h+=`${k} sub ${"extends"in P?P.extends:"relation"},
17
- `;let w=[];if(R&&R.length>0){let Q=new Set(R),S=Array.from(Q).map(N=>`${N}`).join(", ");F.includes(S)||(h+=` owns ${S} @key,
18
- `,w.push(S));}if(g&&g.length>0&&g.forEach(Q=>{!I.includes(Q.dbPath)&&!w.includes(Q.dbPath)&&(h+=` owns ${Q.dbPath},
15
+ `;}),Object.keys(t.relations).forEach(k=>{let P=t.relations[k],{idFields:C,dataFields:B,roles:b,name:L,linkFields:y}=P,I=[],T=[],A=[],F=[];if("extends"in P){let Q=t.relations[P.extends];Q.dataFields&&Q.dataFields.forEach(R=>{I.push(R.dbPath);}),Q.linkFields&&Q.linkFields.forEach(R=>{T.push(R.dbPath);}),Q.roles&&Object.values(Q.roles).forEach(O=>{A.push(O.name);}),Q.idFields&&Q.idFields.forEach(R=>{F.push(R);});}h+=`${L} sub ${"extends"in P?P.extends:"relation"},
16
+ `;let w=[];if(C&&C.length>0){let Q=new Set(C),O=Array.from(Q).map(N=>`${N}`).join(", ");F.includes(O)||(h+=` owns ${O} @key,
17
+ `,w.push(O));}if(B&&B.length>0&&B.forEach(Q=>{!I.includes(Q.dbPath)&&!w.includes(Q.dbPath)&&(h+=` owns ${Q.dbPath},
19
18
  `),m.push({dbPath:Q.dbPath,contentType:Q.contentType});}),b&&Object.keys(b).forEach(Q=>{A.includes(Q)||(h+=` relates ${Q},
20
- `);}),y&&y.length>0){let Q=[];y.forEach(C=>{let{plays:S}=C;!T.includes(C.path)&&!Q.includes(`${P}:${S}`)&&(h+=` plays ${C.relation}:${S},
21
- `,Q.push(`${P}:${S}`));});}h=h.replace(/,\s*$/,`;
19
+ `);}),y&&y.length>0){let Q=[];y.forEach(R=>{let{plays:O}=R;!T.includes(R.path)&&!Q.includes(`${P}:${O}`)&&(h+=` plays ${R.relation}:${O},
20
+ `,Q.push(`${P}:${O}`));});}h=h.replace(/,\s*$/,`;
22
21
  `),h+=`
23
22
  `;});let E=`define
24
23
 
25
- `;return er(m).forEach(M=>{E+=`${M.dbPath} sub attribute,
26
- `,M.contentType==="TEXT"||M.contentType==="ID"?E+=` value string;
27
- `:M.contentType==="EMAIL"?(E+=` value string,
24
+ `;return bn(m).forEach(k=>{E+=`${k.dbPath} sub attribute,
25
+ `,k.contentType==="TEXT"||k.contentType==="ID"?E+=` value string;
26
+ `:k.contentType==="EMAIL"?(E+=` value string,
28
27
  `,E+=` regex '^(?=.{1,64}@)[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*@[^-][A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$';
29
- `):M.contentType==="DATE"?E+=` value datetime;
30
- `:M.contentType==="BOOLEAN"?E+=` value boolean;
31
- `:M.contentType==="NUMBER"&&(E+=` value long;
28
+ `):k.contentType==="DATE"?E+=` value datetime;
29
+ `:k.contentType==="BOOLEAN"?E+=` value boolean;
30
+ `:k.contentType==="NUMBER"&&(E+=` value long;
32
31
  `);}),`${E}
33
32
 
34
- ${h}`})(),d=e.dbConnectors[0].id,s=n.typeDB.get(d)?.session,B=n.typeDB.get(d)?.client;if(!s){console.log("Session Status: ","NO SESSION");return}await s.close();let[{dbName:L}]=e.dbConnectors;await(await B.databases.get(L)).delete(),await B.databases.create(L);let r=await B.session(e.dbConnectors[0].dbName,SessionType.SCHEMA),l=await r.transaction(TransactionType.WRITE);await l.query.define(a),await l.commit(),await l.close();let o=await r.transaction(TransactionType.READ);(await(await o.query.match("match $a sub thing;")).collect()).forEach(async h=>{h.get("a");}),await o.close();};var te={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var re=(e,t,n)=>n?t:`${e}\xB7${t}`;var ne=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([n,p])=>t(n,p))))[0],mt=(e,t)=>Object.fromEntries(Object.entries(e).filter(([n,p])=>t(n,p))),ie=(e,t)=>{let n=[],p=produce(e,d=>traverse(d,({key:s,value:B,meta:L})=>{if(L.depth===2&&(s&&(B.dataFields=B.dataFields?.map(u=>({...u,cardinality:u.cardinality||"ONE",dbPath:re(s,u.path,u.shared)}))),B.extends)){let u=d.entities[B.extends]||d.relations[B.extends];if(B.allExtends=[B.extends,...u.allExtends||[]],B.idFields=u.idFields?(B.idFields||[]).concat(u.idFields):B.idFields,B.dataFields=u.dataFields?(B.dataFields||[]).concat(u.dataFields.map(r=>{let l=B.extends,o=e.entities[l]||e.relations[l];for(;!o.dataFields?.find(f=>f.path===r.path);)l="extends"in o?o.extends:void 0,o=e.entities[l]||e.relations[l];return {...r,dbPath:re(l,r.path,r.shared)}})):B.dataFields,B.linkFields=u.linkFields?(B.linkFields||[]).concat(u.linkFields):B.linkFields,"roles"in u){let r=B,l=u;r.roles=r.roles||{},r.roles={...r.roles,...l.roles},Object.keys(r.roles).length===0&&(r.roles={});}}},{traversalType:"breadth-first"}));return traverse(e,({key:d,value:s,meta:B})=>{if(d==="linkFields"){let u=(()=>{if(!B.nodePath)throw new Error("No path");let[l,o]=B.nodePath.split(".");return {thing:o,thingType:l==="entities"?"entity":l==="relations"?"relation":""}})(),r=Array.isArray(s)?s.map(l=>({...l,...u})):[{...s,...u}];n.push(...r);}}),produce(p,d=>traverse(d,({value:s,key:B,meta:L})=>{if(L.depth===2&&s.idFields&&!s.id){s.name=B;let u=()=>{if(L.nodePath?.split(".")[0]==="entities")return "entity";if(L.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};s.thingType=u();let r=Object.keys(t).find(l=>t[l].get(s.defaultDBConnector.id));s.db=r,s.dbContext=te[r],s.computedFields=[],s.virtualFields=[],s.requiredFields=[],s.enumFields=[],s.fnValidatedFields=[],"roles"in s&&Object.entries(s.roles).forEach(([o,f])=>{f.fieldType="roleField",f.playedBy=n.filter(c=>c.relation===B&&c.plays===o)||[],f.name=o;}),"linkFields"in s&&s.linkFields&&s.linkFields?.forEach(o=>{if(o.fieldType="linkField",o.target==="relation"){o.oppositeLinkFieldsPlayedBy=[{plays:o.path,thing:o.relation,thingType:"relation"}];return}let f=n.filter(i=>i.relation===o.relation&&i.plays!==o.plays)||[];o.oppositeLinkFieldsPlayedBy=f;let{filter:c}=o;o.oppositeLinkFieldsPlayedBy=o.oppositeLinkFieldsPlayedBy.filter(i=>i.target==="role"),c&&Array.isArray(c)&&(o.oppositeLinkFieldsPlayedBy=o.oppositeLinkFieldsPlayedBy.filter(i=>c.some(h=>i.thing===h.$role)),o.oppositeLinkFieldsPlayedBy=o.oppositeLinkFieldsPlayedBy.filter(i=>c.some(h=>i.thing===h.$thing))),c&&!Array.isArray(c)&&(o.oppositeLinkFieldsPlayedBy=o.oppositeLinkFieldsPlayedBy.filter(i=>i.$role===c.$role),o.oppositeLinkFieldsPlayedBy=o.oppositeLinkFieldsPlayedBy.filter(i=>i.thing===c.$thing));});}if(typeof s=="object"&&"playedBy"in s){if([...new Set(s.playedBy?.map(u=>u.thing))].length>1)throw new Error(`Unsupported: roleFields can be only played by one thing. Role: ${B} path:${L.nodePath}`);if(s.playedBy.length===0)throw new Error(`Unsupported: roleFields should be played at least by one thing. Role: ${B}, path:${L.nodePath}`)}if(L.depth===4){let[u,r]=L.nodePath?.split(".")||[],l=d[u][r];s.validations&&(s.validations.required&&l.requiredFields.push(s.path),s.validations.enum&&l.enumFields.push(s.path),s.validations.fn&&l.fnValidatedFields.push(s.path)),s.default?s.isVirtual?l.virtualFields.push(s.path):l.computedFields.push(s.path):s.isVirtual&&l.virtualFields.push(s.path);}}))},O=(e,t)=>{if(!t)throw new Error("[Internal] No node for getCurrentSchema");if(t.$thing){if(t.$thingType==="entity"){if(!(t.$thing in e.entities))throw new Error(`Missing entity '${t.$thing}' in the schema`);return e.entities[t.$thing]}if(t.$thingType==="relation"){if(!(t.$thing in e.relations))throw new Error(`Missing relation '${t.$thing}' in the schema`);return e.relations[t.$thing]}if(t.$thing in e.entities&&t.$thing in e.relations)throw new Error(`Ambiguous $thing ${t.$thing}`);if(t.$thing in e.entities)return e.entities[t.$thing];if(t.$thing in e.relations)return e.relations[t.$thing];throw new Error(`Wrong schema or query for ${JSON.stringify(t,null,2)}`)}if(t.$entity){if(!(t.$entity in e.entities))throw new Error(`Missing entity '${t.$entity}' in the schema`);return e.entities[t.$entity]}if(t.$relation){if(!(t.$relation in e.relations))throw new Error(`Missing relation '${t.$relation}' in the schema`);return e.relations[t.$relation]}throw new Error(`Wrong schema or query for ${JSON.stringify(t,null,2)}`)},oe=(e,t)=>{let n=e.$thing||e.$entity||e.$relation;if(!n)throw new Error("[Internal] No thing found");if(e.$entity)return "entity";if(e.$relation)return "relation";if(t.entities[n])return "entity";if(t.relations[n])return "relation";throw new Error("No thing found")},xt=(e,t,n)=>{let p=O(e,t),a=p.linkFields?.find(B=>B.path===n);if(a)return a;let d=p.dataFields?.find(B=>B.path===n);if(d)return d;let s="roles"in p?p.roles?.[n]:void 0;if(s)return s},jt=(e,t,n)=>xt(e,t,n)?.cardinality,U=(e,t)=>{let n=e.dataFields?.map(c=>c.path)||[],p=e.linkFields?.map(c=>c.path)||[],a="roles"in e?listify(e.roles,c=>c):[],d=[...n||[],...p||[],...a||[]],B=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...d];if(!t)return {fields:d,dataFields:n,roleFields:a,linkFields:p};let L=t.$fields?t.$fields.map(c=>{if(typeof c=="string")return c.startsWith("$")?void 0:c;if("$path"in c&&typeof c.$path=="string")return c.$path;throw new Error(" Wrongly structured query")}):listify(t,c=>c.startsWith("$")?void 0:c).filter(c=>c!==void 0),u=t.$filter?listify(t.$filter,c=>c.toString().startsWith("$")?void 0:c.toString()).filter(c=>c&&n?.includes(c)):[],r=t.$filter?listify(t.$filter,c=>c.toString().startsWith("$")?void 0:c.toString()).filter(c=>c&&[...a||[],...p||[]].includes(c)):[],l=[...L,...u].filter(c=>!B.includes(c)).filter(c=>c),o=t.$filter?mt(t.$filter,(c,i)=>u.includes(c)):{},f=t.$filter?mt(t.$filter,(c,i)=>r.includes(c)):{};return {fields:d,dataFields:n,roleFields:a,linkFields:p,usedFields:L,usedLinkFields:p.filter(c=>L.includes(c)),usedRoleFields:a.filter(c=>L.includes(c)),usedDataFields:n.filter(c=>L.includes(c)),unidentifiedFields:l,...u.length?{localFilters:o}:{},...r.length?{nestedFilters:f}:{}}};var se=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},ae=(e,t,n)=>{let a=(n.nodePath||"").split("."),d=isArray(t)?a.slice(0,-2).join("."):a.slice(0,-1).join(".");return t?getNodeByPath(e,d):{}},J=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,n)=>(t[n]=e[n],t),{});var wt=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),K=e=>{if(Array.isArray(e))return e.map(t=>K(t));if(e&&typeof e=="object"){let t=isDraft(e)?current(e):e,n={};return Object.entries(t).forEach(([p,a])=>{n[p]=K(a);}),n}else return e};var H=Symbol.for("queryPath"),bt=Symbol.for("stepPrint"),ot=Symbol.for("edgeType"),tt=Symbol.for("edgeSchema");var _="___",le=async e=>{let{enrichedBqlQuery:t}=e;if(!t)throw new Error("BQL query not enriched");let n="",p=(r,l)=>{let o="",f="";for(let c in r){let i=r[c];if(Array.isArray(i))for(let h=0;h<i.length;h++)f+=`{$${l} has ${c} "${i[h]}";}`,h<i.length-1?f+="or":f+=";";else o+=`, has ${c} "${i}"`;}o+=`;
35
- `,n+=o,n+=f;},a=(r,l)=>{let o=[],f=[],c="";for(let m=0;m<r.length;m++)r[m].$isVirtual||o.push(` ${r[m].$dbPath}`),f.push(`{${r[m].$dbPath}:${r[m].$as}}`);let i=`${o.join(",")};
36
- `;c=f.join(",");let h=`$metadata:{as:[${c}]}`;n+=`$${l} as "${l}.${h}.$dataFields": `,n+=i;},d=(r,l,o)=>{for(let f of r){let{$fields:c,$as:i,$justId:h,$idNotIncluded:m,$filterByUnique:E}=f,$=f[H],M=`$metadata:{as:${i},justId:${h?"T":"F"},idNotIncluded:${m},filterByUnique:${E}}`;if(n+=`"${o}.${M}.${f.$var}":{
33
+ ${h}`})(),c=e.dbConnectors[0].id,l=n.typeDB.get(c)?.session,g=n.typeDB.get(c)?.client;if(!l){console.log("Session Status: ","NO SESSION");return}await l.close();let[{dbName:M}]=e.dbConnectors;await(await g.databases.get(M)).delete(),await g.databases.create(M);let r=await g.session(e.dbConnectors[0].dbName,SessionType.SCHEMA),d=await r.transaction(TransactionType.WRITE);await d.query.define(i),await d.commit(),await d.close();let a=await r.transaction(TransactionType.READ);(await(await a.query.match("match $a sub thing;")).collect()).forEach(async h=>{h.get("a");}),await a.close();};var ae={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var ce=(e,t,n)=>n?t:`${e}\xB7${t}`;var de=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([n,o])=>t(n,o))))[0],Bt=(e,t)=>Object.fromEntries(Object.entries(e).filter(([n,o])=>t(n,o))),pe=(e,t)=>{let n=[],o=produce(e,c=>traverse(c,({key:l,value:g,meta:M})=>{if(M.depth===2&&(l&&(g.dataFields=g.dataFields?.map(u=>({...u,cardinality:u.cardinality||"ONE",dbPath:ce(l,u.path,u.shared)}))),g.extends)){let u=c.entities[g.extends]||c.relations[g.extends];if(g.allExtends=[g.extends,...u.allExtends||[]],g.idFields=u.idFields?(g.idFields||[]).concat(u.idFields):g.idFields,g.dataFields=u.dataFields?(g.dataFields||[]).concat(u.dataFields.map(r=>{let d=g.extends,a=e.entities[d]||e.relations[d];for(;!a.dataFields?.find(f=>f.path===r.path);)d="extends"in a?a.extends:void 0,a=e.entities[d]||e.relations[d];return {...r,dbPath:ce(d,r.path,r.shared)}})):g.dataFields,g.linkFields=u.linkFields?(g.linkFields||[]).concat(u.linkFields):g.linkFields,"roles"in u){let r=g,d=u;r.roles=r.roles||{},r.roles={...r.roles,...d.roles},Object.keys(r.roles).length===0&&(r.roles={});}}},{traversalType:"breadth-first"}));return traverse(e,({key:c,value:l,meta:g})=>{if(c==="linkFields"){let u=(()=>{if(!g.nodePath)throw new Error("No path");let[d,a]=g.nodePath.split(".");return {thing:a,thingType:d==="entities"?"entity":d==="relations"?"relation":""}})(),r=Array.isArray(l)?l.map(d=>({...d,...u})):[{...l,...u}];n.push(...r);}}),produce(o,c=>traverse(c,({value:l,key:g,meta:M})=>{if(M.depth===2&&l.idFields&&!l.id){l.name=g;let u=()=>{if(M.nodePath?.split(".")[0]==="entities")return "entity";if(M.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};l.thingType=u();let r=Object.keys(t).find(d=>t[d].get(l.defaultDBConnector.id));l.db=r,l.dbContext=ae[r],l.computedFields=[],l.virtualFields=[],l.requiredFields=[],l.enumFields=[],l.fnValidatedFields=[],"roles"in l&&Object.entries(l.roles).forEach(([a,f])=>{f.fieldType="roleField",f.playedBy=n.filter(p=>p.relation===g&&p.plays===a)||[],f.name=a;}),"linkFields"in l&&l.linkFields&&l.linkFields?.forEach(a=>{if(a.fieldType="linkField",a.target==="relation"){a.oppositeLinkFieldsPlayedBy=[{plays:a.path,thing:a.relation,thingType:"relation"}];return}let f=n.filter(s=>s.relation===a.relation&&s.plays!==a.plays)||[];a.oppositeLinkFieldsPlayedBy=f;let{filter:p}=a;a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter(s=>s.target==="role"),p&&Array.isArray(p)&&(a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter(s=>p.some(h=>s.thing===h.$role)),a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter(s=>p.some(h=>s.thing===h.$thing))),p&&!Array.isArray(p)&&(a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter(s=>s.$role===p.$role),a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter(s=>s.thing===p.$thing));});}if(typeof l=="object"&&"playedBy"in l){if([...new Set(l.playedBy?.map(u=>u.thing))].length>1)throw new Error(`Unsupported: roleFields can be only played by one thing. Role: ${g} path:${M.nodePath}`);if(l.playedBy.length===0)throw new Error(`Unsupported: roleFields should be played at least by one thing. Role: ${g}, path:${M.nodePath}`)}if(M.depth===4){let[u,r]=M.nodePath?.split(".")||[],d=c[u][r];l.validations&&(l.validations.required&&d.requiredFields.push(l.path),l.validations.enum&&d.enumFields.push(l.path),l.validations.fn&&d.fnValidatedFields.push(l.path)),l.default?l.isVirtual?d.virtualFields.push(l.path):d.computedFields.push(l.path):l.isVirtual&&d.virtualFields.push(l.path);}}))},S=(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)}`)},ue=(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")},_t=(e,t,n)=>{let o=S(e,t),i=o.linkFields?.find(g=>g.path===n);if(i)return i;let c=o.dataFields?.find(g=>g.path===n);if(c)return c;let l="roles"in o?o.roles?.[n]:void 0;if(l)return l},Wt=(e,t,n)=>_t(e,t,n)?.cardinality,J=(e,t)=>{let n=e.dataFields?.map(p=>p.path)||[],o=e.linkFields?.map(p=>p.path)||[],i="roles"in e?listify(e.roles,p=>p):[],c=[...n||[],...o||[],...i||[]],g=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...c];if(!t)return {fields:c,dataFields:n,roleFields:i,linkFields:o};let M=t.$fields?t.$fields.map(p=>{if(typeof p=="string")return p.startsWith("$")?void 0:p;if("$path"in p&&typeof p.$path=="string")return p.$path;throw new Error(" Wrongly structured query")}):listify(t,p=>p.startsWith("$")?void 0:p).filter(p=>p!==void 0),u=t.$filter?listify(t.$filter,p=>p.toString().startsWith("$")?void 0:p.toString()).filter(p=>p&&n?.includes(p)):[],r=t.$filter?listify(t.$filter,p=>p.toString().startsWith("$")?void 0:p.toString()).filter(p=>p&&[...i||[],...o||[]].includes(p)):[],d=[...M,...u].filter(p=>!g.includes(p)).filter(p=>p),a=t.$filter?Bt(t.$filter,(p,s)=>u.includes(p)):{},f=t.$filter?Bt(t.$filter,(p,s)=>r.includes(p)):{};return {fields:c,dataFields:n,roleFields:i,linkFields:o,usedFields:M,usedLinkFields:o.filter(p=>M.includes(p)),usedRoleFields:i.filter(p=>M.includes(p)),usedDataFields:n.filter(p=>M.includes(p)),unidentifiedFields:d,...u.length?{localFilters:a}:{},...r.length?{nestedFilters:f}:{}}};var he=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},fe=(e,t,n)=>{let i=(n.nodePath||"").split("."),c=isArray(t)?i.slice(0,-2).join("."):i.slice(0,-1).join(".");return t?getNodeByPath(e,c):{}},Z=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,n)=>(t[n]=e[n],t),{});var Mt=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),U=e=>{if(Array.isArray(e))return e.map(t=>U(t));if(e&&typeof e=="object"){let t=isDraft(e)?current(e):e,n={};return Object.entries(t).forEach(([o,i])=>{n[o]=U(i);}),n}else return e};var K=Symbol.for("queryPath"),kt=Symbol.for("stepPrint"),at=Symbol.for("edgeType"),rt=Symbol.for("edgeSchema");var v="___",$e=async e=>{let{enrichedBqlQuery:t}=e;if(!t)throw new Error("BQL query not enriched");let n="",o=(r,d)=>{let a="",f="";for(let p in r){let s=r[p];if(Array.isArray(s))for(let h=0;h<s.length;h++)f+=`{$${d} has ${p} "${s[h]}";}`,h<s.length-1?f+="or":f+=";";else a+=`, has ${p} "${s}"`;}a+=`;
34
+ `,n+=a,n+=f;},i=(r,d)=>{let a=[],f=[],p="";for(let m=0;m<r.length;m++)r[m].$isVirtual||a.push(` ${r[m].$dbPath}`),f.push(`{${r[m].$dbPath}:${r[m].$as}}`);let s=`${a.join(",")};
35
+ `;p=f.join(",");let h=`$metadata:{as:[${p}]}`;n+=`$${d} as "${d}.${h}.$dataFields": `,n+=s;},c=(r,d,a)=>{for(let f of r){let{$fields:p,$as:s,$justId:h,$idNotIncluded:m,$filterByUnique:E}=f,$=f[K],k=`$metadata:{as:${s},justId:${h?"T":"F"},idNotIncluded:${m},filterByUnique:${E}}`;if(n+=`"${a}.${k}.${f.$var}":{
37
36
  `,n+=` match
38
- `,f.$filter&&(n+=` $${l}${_}${f.$var} isa ${f.$thing}`,p(f.$filter,`${l}${_}${f.$var}`)),n+=` $${l} (${f.$var}: $${l}${_}${f.$var}) isa ${f.$intermediary};
39
- `,c){let P=`M_${v4()}`;n+=`?queryPath${P} = "${$}";
37
+ `,f.$filter&&(n+=` $${d}${v}${f.$var} isa ${f.$thing}`,o(f.$filter,`${d}${v}${f.$var}`)),n+=` $${d} (${f.$var}: $${d}${v}${f.$var}) isa ${f.$intermediary};
38
+ `,p){let P=`M_${v4()}`;n+=`?queryPath${P} = "${$}";
40
39
  `,n+=` fetch
41
40
  `,n+=`?queryPath${P} as "queryPath"
42
- ;`;let R=c?.filter(k=>k.$fieldType==="data");R&&R.length>0&&a(R,`${l}${_}${f.$var}`,`${l}.${f.$var}`);let g=c?.filter(k=>k.$fieldType==="link");g&&g.length>0&&s(g,`${l}${_}${f.$var}`,`${l}.${f.$var}`);let b=c?.filter(k=>k.$fieldType==="role");b&&b.length>0&&d(b,`${l}${_}${f.$var}`,`${l}.${f.$var}`);}n+=`};
43
- `;}},s=(r,l,o)=>{for(let f of r){let{$fields:c,$as:i,$justId:h,$idNotIncluded:m,$filterByUnique:E,$playedBy:$}=f,M=f[H],P=`$metadata:{as:${i},justId:${h?"T":"F"},idNotIncluded:${m},filterByUnique:${E}}`;if(n+=`"${o}.${P}.${f.$var}":{
41
+ ;`;let C=p?.filter(L=>L.$fieldType==="data");C&&C.length>0&&i(C,`${d}${v}${f.$var}`,`${d}.${f.$var}`);let B=p?.filter(L=>L.$fieldType==="link");B&&B.length>0&&l(B,`${d}${v}${f.$var}`,`${d}.${f.$var}`);let b=p?.filter(L=>L.$fieldType==="role");b&&b.length>0&&c(b,`${d}${v}${f.$var}`,`${d}.${f.$var}`);}n+=`};
42
+ `;}},l=(r,d,a)=>{for(let f of r){let{$fields:p,$as:s,$justId:h,$idNotIncluded:m,$filterByUnique:E,$playedBy:$}=f,k=f[K],P=`$metadata:{as:${s},justId:${h?"T":"F"},idNotIncluded:${m},filterByUnique:${E}}`;if(n+=`"${a}.${P}.${f.$var}":{
44
43
  `,n+=` match
45
- `,f.$filter&&(n+=` $${l}${_}${f.$var} isa ${f.$thing}`,p(f.$filter,`${l}${_}${f.$var}`)),f.$target==="role"?n+=` $${l}_intermediary (${f.$plays}: $${l}, ${$.plays}: $${l}${_}${f.$var}) isa ${f.$intermediary};
46
- `:n+=` $${l}${_}${f.$var} (${f.$plays}: $${l}) isa ${f.$thing};
47
- `,c){let R=`M_${v4()}`;n+=`?queryPath${R} = "${M}";
44
+ `,f.$filter&&(n+=` $${d}${v}${f.$var} isa ${f.$thing}`,o(f.$filter,`${d}${v}${f.$var}`)),f.$target==="role"?n+=` $${d}_intermediary (${f.$plays}: $${d}, ${$.plays}: $${d}${v}${f.$var}) isa ${f.$intermediary};
45
+ `:n+=` $${d}${v}${f.$var} (${f.$plays}: $${d}) isa ${f.$thing};
46
+ `,p){let C=`M_${v4()}`;n+=`?queryPath${C} = "${k}";
48
47
  `,n+=` fetch
49
- `,n+=`?queryPath${R} as "queryPath"
50
- ;`;let g=c?.filter(y=>y.$fieldType==="data");g&&g.length>0&&a(g,`${l}${_}${f.$var}`);let b=c?.filter(y=>y.$fieldType==="link");b&&b.length>0&&s(b,`${l}${_}${f.$var}`,`${l}.${f.$var}`);let k=c?.filter(y=>y.$fieldType==="role");k&&k.length>0&&d(k,`${l}${_}${f.$var}`,`${l}.${f.$var}`);}n+=`};
51
- `;}},B=t.length>1,L=[];(r=>{if(B)for(let l of r){let{$path:o,$thing:f,$filter:c,$fields:i}=l;if(!o)throw new Error("Path is not defined");let h=l[H];n+=`match
52
- $${o} isa ${f} `,c?p(c,o):n+="; ";let m=`M_${v4()}`;if(n+=`?queryPath${m} = "${h}";
48
+ `,n+=`?queryPath${C} as "queryPath"
49
+ ;`;let B=p?.filter(y=>y.$fieldType==="data");B&&B.length>0&&i(B,`${d}${v}${f.$var}`);let b=p?.filter(y=>y.$fieldType==="link");b&&b.length>0&&l(b,`${d}${v}${f.$var}`,`${d}.${f.$var}`);let L=p?.filter(y=>y.$fieldType==="role");L&&L.length>0&&c(L,`${d}${v}${f.$var}`,`${d}.${f.$var}`);}n+=`};
50
+ `;}},g=t.length>1,M=[];(r=>{if(g)for(let d of r){let{$path:a,$thing:f,$filter:p,$fields:s}=d;if(!a)throw new Error("Path is not defined");let h=d[K];n+=`match
51
+ $${a} isa ${f} `,p?o(p,a):n+="; ";let m=`M_${v4()}`;if(n+=`?queryPath${m} = "${h}";
53
52
  `,n+=`fetch
54
53
  `,n+=`?queryPath${m} as "queryPath"
55
- ;`,i){let E=i.filter(P=>P.$fieldType==="data");E&&E.length>0&&a(E,o);let $=i.filter(P=>P.$fieldType==="link");$&&$.length>0&&s($,o,o);let M=i.filter(P=>P.$fieldType==="role");M&&M.length>0&&d(M,o,o);}L.push(n),n="";}else for(let l of r){let{$path:o,$thing:f,$filter:c,$fields:i}=l;if(!o||o==="undefined")throw new Error("Path is not defined");let h=l[H];if(n+=`match
56
- $${o} isa ${f} `,c?p(c,o):n+="; ",n+=`?queryPath = "${h}";
54
+ ;`,s){let E=s.filter(P=>P.$fieldType==="data");E&&E.length>0&&i(E,a);let $=s.filter(P=>P.$fieldType==="link");$&&$.length>0&&l($,a,a);let k=s.filter(P=>P.$fieldType==="role");k&&k.length>0&&c(k,a,a);}M.push(n),n="";}else for(let d of r){let{$path:a,$thing:f,$filter:p,$fields:s}=d;if(!a||a==="undefined")throw new Error("Path is not defined");let h=d[K];if(n+=`match
55
+ $${a} isa ${f} `,p?o(p,a):n+="; ",n+=`?queryPath = "${h}";
57
56
  `,n+=`fetch
58
57
  `,n+=`?queryPath as "queryPath"
59
- ;`,i){let m=i.filter(M=>M.$fieldType==="data");m&&m.length>0&&a(m,o);let E=i.filter(M=>M.$fieldType==="link");E&&E.length>0&&s(E,o,o);let $=i.filter(M=>M.$fieldType==="role");$&&$.length>0&&d($,o,o);}}})(t),e.tqlRequest=B?L:n;};var zt=e=>{let t=e.dataFields?.map(d=>d.path)||[],n=e.linkFields?.map(d=>d.path)||[],p=Object.keys(e.roles||{})||[];return [...t,...n,...p]},vt=(e,t)=>Object.keys(e||{}).some(p=>{if(!Array.isArray(e[p])){let a=t.idFields?.includes(p),d=t.dataFields?.some(s=>(s.dbPath===p||s.path===p)&&s?.validations?.unique);return a||d}return !1}),Wt=(e,t)=>{let n=t.dataFields?.map(s=>({path:s.path,dbPath:s.dbPath}))||[],p=t.linkFields?.map(s=>({path:s.path,dbPath:s.dbPath}))||[],a=Object.keys(t.roles||{}).map(s=>({path:s,dbPath:s}))||[],d=[...n,...p,...a];return Object.entries(e||{}).reduce((s,[B,L])=>{let u=d.find(r=>r.path===B);return s[u?.dbPath||B]=L,s},{})},de=async e=>{let{rawBqlRequest:t,schema:n}=e;if(Array.isArray(t)){for(let r of t)if(!("$entity"in r)&&!("$relation"in r)&&(!("$thing"in r)||!("$thingType"in r)))throw new Error("No entity specified in query")}else if(!("$entity"in t)&&!("$relation"in t)&&(!("$thing"in t)||!("$thingType"in t)))throw new Error("No entity specified in query");let p=(r,l)=>typeof l=="string"?r.idFields?.includes(l):r.idFields?.includes(l.$path),a=(r,l,o,f,c)=>({$path:l,$dbPath:f,$thingType:"attribute",$as:r.$as||l,$var:l,$fieldType:"data",$excludedFields:r.$excludedFields,$justId:o,$id:r.$id,$filter:r.$filter,$isVirtual:c,$filterProcessed:!0}),d=(r,l,o,f,c)=>{let{target:i,oppositeLinkFieldsPlayedBy:h}=o;return h.map(m=>{let E=i==="role"?m.thingType:"relation",$=i==="role"?m.thing:o.relation,M={[`$${E}`]:$},P=O(n,M),R=r?.$fields?.filter(b=>p(P,b)).length===0,g=[];return typeof r!="string"?r.$fields?R?g=[...r.$fields,...P.idFields]:g=r.$fields:g=zt(P):g=["id"],r.$excludedFields&&(g=g.filter(b=>p(P,b)?!0:!r.$excludedFields.includes(b.$path))),{$thingType:E,$plays:o.plays,$playedBy:m,$path:m.path,$dbPath:c,$as:r.$as||l,$var:l,$thing:$,$fields:g,$excludedFields:r.$excludedFields,$fieldType:"link",$target:i,$intermediary:m.relation,$justId:f,$id:r.$id,$filter:Wt(r.$filter,P),$idNotIncluded:R,$filterByUnique:vt(r.$filter,P),$filterProcessed:!0}})},s=(r,l,o,f,c)=>o.playedBy.map(i=>{let{thing:h,thingType:m,relation:E}=i,$={[`$${m}`]:h},M=O(n,$),P=r?.$fields?.filter(g=>M?.idFields?.includes(g)||M?.idFields?.includes(g.$path)).length===0,R=[];return typeof r!="string"?r.$fields?P?R=[...r.$fields,...M.idFields]:R=r.$fields:R=zt(M):R=["id"],r.$excludedFields&&(R=R.filter(g=>p(M,g)?!0:!r.$excludedFields.includes(g.$path))),{$thingType:m,$path:l,$dbPath:c,$as:r.$as||l,$var:l,$thing:h,$fields:R,$excludedFields:r.$excludedFields,$fieldType:"role",$intermediary:E,$justId:f,$id:r.$id,$filter:Wt(r.$filter,M),$idNotIncluded:P,$filterByUnique:vt(r.$filter,M),$playedBy:i,$filterProcessed:!0}}),B=(r,l)=>{let o=typeof r=="string"?r:r.$path,f=typeof r=="string",c=l.dataFields?.find(m=>m.path===o),i=l.linkFields?.find(m=>m.path===o),h=l.roles?.[o];if(c){let m=c.isVirtual&&c.default;return a(r,o,f,c.dbPath,m)}else {if(i)return d(r,o,i,f,i.dbPath);if(h)return s(r,o,h,f,h.dbPath)}return null},u=(r=>produce(r,l=>traverse(l,o=>{let{value:f,meta:c}=o,i=f;if(isObject(i)){if(i.$id){let h=i.$entity||i.$relation?i:{[`$${i.$thingType}`]:i.$thing},m=O(n,h);if(!m?.name)throw new Error(`Schema not found for ${i.$thing}`);if(i.$path=m.name,Array.isArray(i.$id)||(i.$filterByUnique=!0),m?.idFields?.length===1){let[E]=m.idFields;i.$filter={...i.$filter,[E]:i.$id},delete i.$id;}else throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in i||"$relation"in i||"$thing"in i){let h=O(n,i);if(!h?.name)throw new Error(`Schema not found for ${i.$thing}`);i.$path=h.name;}if(i.$entity?(i.$thing=i.$entity,i.$thingType="entity",delete i.$entity):i.$relation&&(i.$thing=i.$relation,i.$thingType="relation",delete i.$relation),isObject(i)&&"$thing"in i){let h=i.$entity||i.$relation?i:{[`$${i.$thingType}`]:i.$thing};i[H]=c.nodePath;let m=O(n,h);if(i.$filter&&(i.$filterByUnique=vt(i.$filter,m),i.$filterProcessed||(i.$filter=Wt(i.$filter,m))),i.$fields){i.$fields.filter(M=>m?.idFields?.includes(M)||m?.idFields?.includes(M.$path)).length>0||(i.$fields=[...i.$fields,...Array.isArray(m.idFields)?m.idFields:[]],i.$idNotIncluded=!0);let $=i.$fields?.flatMap(M=>{let P=B(M,m);return Array.isArray(P)?P:[P]}).filter(Boolean);i.$fields=$;}else {let $=zt(m)?.flatMap(M=>{let P=B(M,m);return Array.isArray(P)?P:[P]}).filter(Boolean);i.$fields=$;}i.$excludedFields&&(i.$fields=i.$fields.filter(E=>p(m,E)?!0:!i.$excludedFields.includes(E.$path)));}}})))(Array.isArray(t)?t:[t]);e.enrichedBqlQuery=u;};var yt=async(e,t)=>{let n=t.dbConnectors[0].id,p=e.typeDB?.get(n)?.session,a=e.typeDB?.get(n)?.client;if(!p||!p.isOpen()){if(!a)throw new Error("Client not found");p=await a.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(n,{client:a,session:p});}return {client:a,session:p}};var ue=async(e,t)=>{let{dbHandles:n,enrichedBqlQuery:p,tqlRequest:a,config:d}=e;if(!p)throw new Error("BQL request not parsed");if(!a)throw new Error("TQL request not built");let s=new TypeDBOptions;if(s.infer=!0,Array.isArray(a)){let L=await parallel(a.length,a,async u=>{let{session:r}=await yt(n,d),l=await r.transaction(TransactionType.READ,s);if(!l)throw new Error("Can't create transaction");let f=await l.query.fetch(u).collect();return await l.close(),f});t.rawTqlRes=L,t.isBatched=!0;}else {let{session:L}=await yt(n,d),u=await L.transaction(TransactionType.READ,s);if(!u)throw new Error("Can't create transaction");let l=await u.query.fetch(a).collect();await u.close(),t.rawTqlRes=l;}};var he=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,n=/justId:([a-zA-Z0-9_\-·]+)/,p=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,a=/filterByUnique:([a-zA-Z0-9_\-·]+)/,d=e.match(t),s=e.match(n),B=e.match(p),L=e.match(a);return {as:d?d[1]:null,justId:s?s[1]:null,idNotIncluded:B?B[1]:null,filterByUnique:L?L[1]:null}},hr=e=>{try{let n=(a=>{let d=a.replace("$metadata:","");return d=d.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),d=d.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(s,B,L)=>/^{.*}$/.test(L)?`:${L}`:`:${B}"${L}"`),d=d.replace(/\[([^\]]+)\]/g,(s,B)=>`[${B.split(",").map(L=>L.trim().startsWith("{")&&L.trim().endsWith("}")?L.trim():`"${L.trim()}"`).join(",")}]`),d})(e);return JSON.parse(n)}catch(t){return console.error(t),{as:[]}}},fe=async(e,t)=>{let{enrichedBqlQuery:n,rawBqlRequest:p,schema:a,config:d}=e,{rawTqlRes:s,isBatched:B}=t;if(n){if(!s)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");let L=(i,h)=>{let{$metaData:m}=i,{as:E}=hr(m),$=Object.entries(i).filter(([M])=>M!=="type"&&!M.includes("$")).map(([M,P])=>{let R=h.dataFields?.find(y=>y.path===M||y.dbPath===M),g=M==="id",b=Array.isArray(E)?E.find(y=>y[M])?.[M]:M,k;if(R?.cardinality==="ONE"){if(k=P[0]?P[0].value:d.query?.returnNulls?null:void 0,R.contentType==="DATE"&&(k=k&&`${k}Z`),g)return [[b,k],["$id",k]].filter(([y,I])=>I!==void 0)}else if(R?.cardinality==="MANY"){if(!isArray(P))throw new Error("Typedb fetch has changed its format");if(P.length===0)return d.query?.returnNulls?[[b,null]]:[];R.contentType==="DATE"?k=P.map(y=>`${y.value}Z`):k=P.map(y=>y.value);}return [[b,k]].filter(([y,I])=>I!==void 0)}).flat();return Object.fromEntries([...$])},u=i=>i.reduce((h,m)=>{let{$roleFields:E,$metaData:$,$cardinality:M}=m,{as:P,justId:R,idNotIncluded:g,filterByUnique:b}=he($),k=E.map(y=>{let{dataFields:I,currentSchema:T,linkFields:A,roleFields:F,schemaValue:w}=l(y),Q=L(I,T);if(R==="T")return Q.id;{let C=r(A),S=u(F),N={...Q};return g==="true"&&T?.idFields?.forEach(D=>delete N[D]),{...N,...C,...S,...w}}});return k.length>0?h[P]=M==="MANY"&&b==="false"?k:k[0]:d.query?.returnNulls&&(h[P]=null),h},{}),r=i=>i.reduce((h,m)=>{let{$linkFields:E,$metaData:$,$cardinality:M}=m,{as:P,justId:R,idNotIncluded:g,filterByUnique:b}=he($),k=E.map(y=>{let{dataFields:I,currentSchema:T,linkFields:A,roleFields:F,schemaValue:w}=l(y),Q=L(I,T);if(R==="T")return Q.id;{let C=r(A),S=u(F),N={...Q};return g==="true"&&T.idFields?.forEach(D=>delete N[D]),{...N,...C,...S,...w}}});return h[P]=k.length>0?M==="MANY"&&b==="false"?k:k[0]:d.query?.returnNulls?null:void 0,h},{}),l=i=>{let h=Object.keys(i),m=h.find(y=>y.endsWith(".$dataFields"));if(!m)throw new Error("No datafields");let E=i[m],$=m.split(".")[m.split(".").length-2];if(E.$metaData=$,E.length===0)throw new Error("No datafields");let M=E.type,P={$thing:M.label,$thingType:M.root,[H]:i.queryPath.value},R={[`$${P.$thingType}`]:P.$thing},g=O(a,R),b=h.filter(y=>!y.endsWith(".$dataFields")&&g.linkFields?.some(I=>I.path===y.split(".").pop())).map(y=>({$linkFields:i[y],$key:y.split(".").pop(),$metaData:y.split(".")[y.split(".").length-2],$cardinality:g?.linkFields?.find(I=>I.path===y.split(".").pop())?.cardinality})),k=h.filter(y=>!y.endsWith(".$dataFields")&&g.roles?.[y.split(".").pop()]).map(y=>({$roleFields:i[y],$key:y.split(".").pop(),$metaData:y.split(".")[y.split(".").length-2],$cardinality:g.roles[y.split(".").pop()].cardinality}));return {dataFields:E,schemaValue:P,currentSchema:g,linkFields:b,roleFields:k}},o=i=>i.map(h=>{let{dataFields:m,currentSchema:E,linkFields:$,roleFields:M,schemaValue:P}=l(h),R=L(m,E),g=r($),b=u(M),k=p?.$fields?.every(I=>!E?.idFields?.includes(I)&&!E?.idFields?.includes(I.$path));return {...g,...b,...P,...!d.query?.noMetadata&&p.$id?{$id:Array.isArray(p.$id)?R.id:p.$id}:{},...k?Object.fromEntries(Object.entries(R).filter(([I])=>!E?.idFields?.includes(I))):R}}),c=(i=>{let h=m=>{let E=o(m);return p.$id&&!Array.isArray(p.$id)||n[0].$filterByUnique?E[0]??null:E.length===0?null:E};return B?i.map(h):h(i)})(s);t.bqlRes=c;};var fr=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,$r=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,$e=e=>{let n=e.toString().replace(fr,"").trim().split("=>")[0].split("{")[0].replace($r,"").trim(),p=n.substring(n.indexOf("(")+1,n.lastIndexOf(")")).trim();return p?(p.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(d=>d.includes("{")&&d.includes("}")?(d.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(B=>B.split(":")[0].trim().replace(/['"[\]]/g,"")):d.trim()).filter(Boolean):[]};var lt=({currentThing:e,fieldSchema:t,mandatoryDependencies:n=!1})=>{if(!t||!t.default||!("fn"in t.default||"value"in t.default))throw new Error(`[Internal] Virtual field: No field schema found, or wrongly configured. Field: ${JSON.stringify(t,null,3)}`);if(t.default.type==="value")return t.default.value;if(n){let{fn:a}=t.default,s=$e(a).filter(B=>!(B in e));if(s.length)throw new Error(`Virtual field: Missing arguments ${s.join(", ")}`)}return "default"in t?t.default?.fn(e):void 0};var me=async(e,t)=>{let{schema:n,enrichedBqlQuery:p}=e,{bqlRes:a}=t;if(!a)return;let s=(B=>produce(B,L=>traverse(L,({value:u})=>{if(isObject(u)){let r=u;if(!r.$thing)throw new Error("[Internal] Thing is missing");if(r.$thing){let l=O(n,r),{virtualFields:o}=l,f=r[H];if(!f)throw new Error("[Internal] QueryPath is missing");let c=getNodeByPath(p,f),i=c.$fields.map(m=>m.$path),h=c.$excludedFields;o.forEach(m=>{if(h?.includes(m)||i.length>0&&!i.includes(m))return;let E=l.dataFields?.find($=>$.path===m);if(E?.default){let $=lt({currentThing:r,fieldSchema:E,mandatoryDependencies:!0});r[m]=$;}else if(r[m]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${m}`)}),h&&h.forEach(m=>{if(typeof m!="string")throw new Error("[Internal] ExcludedField is not a string");delete r[m];});}}})))(a);t.bqlRes=s;};var Fe=async(e,t)=>{let{config:n}=e,{bqlRes:p}=t;if(!p)return;let d=(L=>produce(L,u=>traverse(u,({value:r})=>{isObject(r);})))(p),B=(L=>produce(L,u=>traverse(u,({value:r})=>{if(isObject(r)){let l=r;Object.keys(l).forEach(o=>{l[o]===void 0&&delete l[o];}),Object.getOwnPropertySymbols(l).forEach(o=>{delete l[o];}),n.query?.noMetadata===!0&&Object.keys(l).forEach(o=>{o.startsWith("$")&&delete l[o];});}})))(d);t.bqlRes=B;};var Fr={query:[de,le,ue,fe,me,Fe]},Ee=async(e,t,n={},p=!0)=>{for(let a of e){let d=await a(t,n);if(d&&Array.isArray(d))for(let s of d)await Ee(s.pipeline,s.req,s.res,!1);}return p&&t.config.query?.debugger===!0&&typeof n.bqlRes=="object"?{...n.bqlRes,$debugger:{tqlRequest:t.tqlRequest}}:n.bqlRes},Tt=(e,t,n,p)=>Ee(Fr.query,{config:t,schema:n,rawBqlRequest:e,dbHandles:p},{});var we=Er;var ct=(e,t)=>{if(t.fieldType==="linkField"){let n=t.oppositeLinkFieldsPlayedBy;if(n?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!n?.length)throw new Error(`[Internal] Field ${e} should have a player`);return n}else if(t.fieldType==="roleField"){if([...new Set(t.playedBy?.map(n=>n.thing))].length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!t.playedBy?.length)throw new Error(`[Internal] Field ${e} should have a player`);return t.playedBy}else throw new Error(`[Internal] Field ${e} is not a linkField or roleField`)};var be=(e,t,n)=>{let p=isArray(e[t])?e[t]:[e[t]];if(!p.every(a=>typeof a=="object"))if(p.every(a=>typeof a=="string")){let a=ct(t,n),[d]=a,s=e.$op==="create"?"link":"replace",B=d.thing,L=d.thingType;if(p.some(u=>u.startsWith("_:")))throw new Error("[Not supported] At least one child of a replace is a tempId");e[t]={$id:e[t],$op:s,$thing:B,$thingType:L,$bzId:`S_${v4()}`};}else throw new Error("[Mutation Error] Replace can only be used with a single id or an array of ids")};var gt=(e,t,n)=>{let p=O(n,t),{usedDataFields:a}=U(p,t);if(t.$op){if(t.$op==="create"&&t.$id)throw new Error("[Wrong format] Can't write to computed field $id. Try writing to the id field directly.");if(["unlink","delete","update"].includes(t.$op)&&e.$op==="create")throw new Error(`[Wrong format] Cannot ${t.$op} under a create`);if(t.$op==="delete"&&a.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&a.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var Mt=(e,t,n)=>{let p=O(n,t),{usedFields:a}=U(p,t);return t.$op?(gt(e,t,n),t.$op):t.$id||t.$filter?a.length>0?(gt(e,{...t,$op:"update"},n),"update"):(gt(e,{...t,$op:"link"},n),"link"):(gt(e,{...t,$op:"create"},n),"create")};var Me=(e,t)=>{let p=(isArray(e.$root)?e.$root:[e.$root]).map(a=>{let d=Mt(a,a,t);return {...{...a.$thing?{}:{$thing:a.$entity||a.$relation},...a.$thingType?{}:{$thingType:oe(a,t)},...a.$op?{}:{$op:d},...a.$bzId?{}:{$bzId:`R_${v4()}`}},...a}});e.$root=isArray(e.$root)?p:p[0];};var kt=(e,t)=>{let n=t[bt];return isSet(n)?n.has("clean")?(Reflect.set(t,bt,n.add("clean")),!0):!1:(Reflect.set(t,bt,new Set(["clean"])),!0)};var ke=(e,t,n)=>{if(kt("split_ids",e)){let p=(isArray(e[t])?e[t]:[e[t]]).flatMap(a=>{if(isObject(a)&&"$id"in a&&isArray(a.$id)){let d=a;if(O(n,d),!d.$bzId)throw new Error("[Internal Error] No bzId found");return d.$id.map((s,B)=>({...K(d),$id:s,$bzId:`${d.$bzId}_${B}`,...J(d)}))}return a});(p.length>isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=p);}};var Qe=(e,t,n,p)=>{let a=(isArray(e[t])?e[t]:[e[t]]).map(d=>{let s=ct(t,n),[B]=s,L=Mt(e,{...d,$thing:B.thing,$thingType:B.thingType},p),u=d.$bzId?d.$bzId:d.$tempId?d.$tempId:`N_${v4()}`;return {...d,[tt]:n,$thing:B.thing,$thingType:B.thingType,$op:L,$bzId:u}});e[t]=isArray(e[t])?a:a[0];};var Ie=(e,t,n)=>{let p=e[t];p&&(isArray(p)?p:[p]).forEach(a=>{let d=O(n,a),{unidentifiedFields:s}=U(d,a),{computedFields:B,virtualFields:L}=d,u=listify(a,(o,f)=>f!==void 0?o:void 0),r=u.filter(o=>L?.includes(o));if(r.length>0)throw new Error(`Virtual fields can't be sent to DB: "${r.join(",")}"`);if(B.filter(o=>!u.includes(o)).forEach(o=>{let f=d.dataFields?.find(E=>E.path===o),i=d.linkFields?.find(E=>E.path===o)?.oppositeLinkFieldsPlayedBy[0],h="roles"in d?ne(d.roles,(E,$)=>E===o):void 0,m=f||i||h;if(!m)throw new Error(`no field Def for ${o}`);if(a.$op==="create"&&!a[o]){let E=lt({currentThing:a,fieldSchema:m,mandatoryDependencies:!0});a[o]=E;}}),s.length>0)throw new Error(`Unknown fields: [${s.join(",")}] in ${JSON.stringify(a)}`)});};var Pe=(e,t,n)=>{let p=ct(t,n),[a]=p;e[t]={$thing:a.thing,$thingType:a.thingType,$op:"unlink",$bzId:`U_${v4()}`,[tt]:n};};var Lt=(e,t)=>{let n=O(t,e).hooks;if(n?.pre){let p=`on${se(e.$op)}`;return n.pre.filter(s=>s.triggers[p]?.()).flatMap(s=>s.actions)}return []};var Ce=(e,t,n)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(a=>{if("$thing"in a){let{requiredFields:d,enumFields:s,fnValidatedFields:B,dataFields:L}=O(n,a);if("$op"in a&&a.$op==="create"&&d.forEach(u=>{if(!(u in a))throw new Error(`[Validations] Required field "${u}" is missing.`)}),("$op"in a&&a.$op==="update"||a.$op==="create")&&s.forEach(u=>{if(u in a){let r=L?.find(l=>l.path===u)?.validations?.enum;if(!r)throw new Error(`[Validations] Enum field "${u}" is missing enum options.`);if(isArray(a[u]))a[u].some(l=>{if(!r.includes(l))throw new Error(`[Validations] Option "${l}" is not a valid option for field "${u}".`)});else if(r&&!r.includes(a[u]))throw new Error(`[Validations] Option "${a[u]}" is not a valid option for field "${u}".`)}}),("$op"in a&&a.$op==="update"||a.$op==="create")&&B.forEach(u=>{if(u in a)try{let r=L?.find(l=>l.path===u)?.validations?.fn;if(!r)throw new Error("Missing validation function.");if(!r(a[u]))throw new Error("Failed validation function.")}catch(r){throw new Error(`[Validations:attribute:${u}] ${r.message}`)}}),isObject(a)&&"$thing"in a){let u=a.$thing,r=a,l=clone(K(e)),o=clone(K(r));Lt(r,n).forEach(c=>{if(c.type==="validate"){if(c.severity!=="error")return;try{let i=c.fn(o,l);if(i===!1)throw new Error(`${c.message}.`);if(i!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(i){throw new Error(`[Validations:thing:${u}] ${i.message}`)}}});}}});};var qe=(e,t,n)=>{let p=(isArray(e[t])?e[t]:[e[t]]).map(a=>{if(wt(a)){let d=Lt(a,n).filter(L=>L.type==="transform"),s=clone(K(e)),B=clone(K(a));return d.forEach(L=>{let u=L.fn(B,s);Object.keys(u).length!==0&&(a={...B,...u});}),a}});e[t]=isArray(e[t])?p:p[0];};var Dr=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(kt("set_tempId",e))if(e.$tempId?.startsWith("_:")){let n=e.$tempId.substring(2);e.$tempId=n,e.$bzId=n;}else throw new Error('[Wrong format] TempIds must start with "_:"');else throw new Error("[Internal] TempId already modified")},xr=(e,t)=>{},Ht=(e,t)=>{let p=produce({$rootWrap:{$root:e}},a=>traverse(a,({value:d,parent:s,key:B,meta:L})=>{if(!(!s||!B)&&isObject(d)){if(!("$root"in d)){if(!("$thing"in d||"$entity"in d||"$relation"in d))throw B==="$root"?new Error("Root things must specify $entity or $relation"):new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(d)?current(d):d)}`)}let u=d;Object.keys(u).forEach(r=>{if(Dr(u,r),r!=="$root"&&r.startsWith("$"))return;let l=r!=="$root"?xt(t,u,r):{fieldType:"rootField"};if(!l)throw new Error(`[Internal] Field ${r} not found in schema`);if("contentType"in l)return xr();if(["rootField","linkField","roleField"].includes(l.fieldType)){if(["linkField","roleField"].includes(l.fieldType)&&be(u,r,l),l.fieldType==="rootField"){if(!("$root"in u))throw new Error(`[Internal] Field ${r} is a rootField but the object is not a root`);Me(u,t);}let o=isArray(u[r])?u[r]:[u[r]],f=L.nodePath?.split(".").slice(1).join(".");o.forEach(i=>{if(i){if(l?.cardinality==="ONE"&&!i.$op&&!i.$id&&!i.$filter&&!i.$tempId&&u.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${f}.${r}`);if(i.$tempId&&!(i.$op===void 0||i.$op==="link"||i.$op==="create"||i.$op==="update"))throw new Error(`Invalid op ${i.$op} for tempId. TempIds can be created, or when created in another part of the same mutation. In the future maybe we can use them to catch stuff in the DB as well and group them under the same tempId.`)}}),["linkField","roleField"].includes(l.fieldType)&&(u[r]===null?Pe(u,r,l):Qe(u,r,l,t)),ke(u,r,t),["rootField","linkField","roleField"].includes(l.fieldType)&&Ie(u,r,t),(isArray(u[r])?u[r]:[u[r]]).forEach(i=>{let h=O(t,i),{unidentifiedFields:m,usedLinkFields:E}=U(h,i);if(m.length>0)throw new Error(`Unknown fields: [${m.join(",")}] in ${JSON.stringify(d)}`);if(E.length>1){let $=h.linkFields?.filter(M=>E.includes(M.path));$?.some((M,P)=>$.some((R,g)=>{if(P!==g&&M.target!==R.target&&M.relation===R.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),qe(u,r,t),Ce(u,r,t);}});}}));return isArray(p.$rootWrap.$root),p.$rootWrap.$root};var De=async(e,t,n)=>{if(!e)throw new Error("TQL request not built");if(!(e.deletions&&e.deletionMatches||e.insertions))throw new Error("TQL request error, no things");let{session:p}=await yt(t,n),a=await p.transaction(TransactionType.WRITE);if(!a)throw new Error("Can't create transaction");let d=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,s=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;d&&await a.query.delete(d);let B=s&&a.query.insert(s);try{let L=B?await B.collect():void 0;return await a.commit(),await a.close(),{insertions:L}}catch(L){throw await a.close(),new Error(`Transaction failed: ${L.message}`)}};var xe=async(e,t,n,p)=>{let a=[...t,...n],d=a.map(s=>{let B=e.insertions?.find(L=>L.get(`${s.$bzId}`))?.get(`${s.$bzId}`);if(s.$op==="create"||s.$op==="update"||s.$op==="link"){if(s.$op!=="update"&&!B&&s.$id)return {$id:s.$id,$error:"Does not exist or it's not linked to the parent"};let L=B?.asThing().iid;if(p.mutation?.noMetadata)return Object.entries(s).filter(([l,o])=>!l.startsWith("$")).reduce((l,[o,f])=>{if(s.$thingType==="relation"){let c=a.filter(i=>i.$id&&i.$bzId===f);if(c.length>1)throw new Error(`Multiple things with the same bzId ${f}`);return c.length===1?(l[o]=c[0].$id,l):(l[o]=f,l)}return l[o]=f,l},{});let u=s.$tempId&&!s.$tempId.startsWith("_:")?{$tempId:`_:${s.$tempId}`}:{};return {$dbId:L,...s,[s.path]:s.$id,...u}}if(s.$op==="delete"||s.$op==="unlink")return s;if(s.$op!=="match")throw new Error(`Unsupported op ${s.$op}`)}).filter(s=>s);return clone(d)};var je=e=>{let t=({value:n})=>(n&&typeof n=="object"&&"$id"in n&&(Object.keys(n).filter(d=>d.startsWith("$")).forEach(d=>delete n[d]),Object.keys(n).filter(d=>typeof d=="symbol").forEach(d=>delete n[d])),n);return produce(e,n=>traverse(n,t))};var We=async(e,t)=>{let n=u=>{let r=[],l=[],o=h=>{if(h.$id)return h.$id;let m=O(t,h),{idFields:E}=m;if(!E)throw new Error(`no idFields: ${JSON.stringify(h)}`);let[$]=E;if(!$)throw new Error(`no idField: ${JSON.stringify(h)}`);let M=m.dataFields?.find(g=>g.path===$),P=lt({currentThing:h,fieldSchema:M,mandatoryDependencies:!0}),R=h[$]||h.$id||P;if(!R)throw new Error(`no idValue: ${JSON.stringify(h)}`);return R},f=h=>{if(h.$op==="create"){let m=o(h);if(r.find(E=>E.$id===m))throw new Error(`Duplicate id ${m} for node ${JSON.stringify(h)}`);if(l.find(E=>E.$bzId===h.$bzId))throw new Error(`Duplicate $bzid ${h.$bzId} for node ${JSON.stringify(h)}`);r.push({...h,$id:m});return}h.$tempId&&h.$op==="match"||r.push(h);},c=h=>{if(h.$op==="create"){let m=o(h);if(r.find(E=>E.$id===m),l.find(E=>E.$bzId===h.$bzId))throw new Error(`Duplicate %bzId ${h.$bzIdd} for edge ${JSON.stringify(h)}`);l.push({...h,$id:m});return}l.push(h);};return traverse(u,({value:h,parent:m,meta:E})=>{if(!isObject(h))return;let $=h;if($.$thing){if(!$.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify($)}`);if(!$.$bzId)throw new Error("[internal error] BzId not found");let M=O(t,$),{dataFields:P,roleFields:R,linkFields:g,usedFields:b}=U(M,$),k=()=>{if($.$op==="create"||$.$op==="delete")return $.$op;if($.$op==="update"){let T=b.filter(w=>P?.includes(w)),A=b.filter(w=>R?.includes(w)),F=b.filter(w=>g?.includes(w));if(T.length>0)return "update";if(A.length>0||F.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify($)}`)}return "match"},y={...$.$id&&{$id:$.$id},...$.$tempId&&{$tempId:$.$tempId},...$.$filter&&{$filter:$.$filter},$thing:$.$thing,...$.$thingType&&{$thingType:$.$thingType},...shake(pick($,P||[""])),$op:k(),$bzId:$.$tempId?$.$tempId:$.$bzId};f(y);let I=$[tt];if(I?.fieldType==="linkField"){if(($.$op==="link"||$.$op==="unlink")&&($.$id||$.$filter)){if($.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");r.push({...$,$op:"match"});}let T=I.relation===$.$thing,A=T?$.$bzId:`LT_${v4()}`,w=ae(u,m,E).$bzId;if(!w)throw new Error("No parent id found");if($[Symbol.for("relation")]==="$self")return;let Q=()=>{if($.$op==="delete")return T?"match":"delete";if($.$op==="unlink")return T?"unlink":"delete";if($.$op==="link"||$.$op==="create")return T?"link":"create";if($.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},C={$bzId:A,$thing:I.relation,$thingType:"relation",...$.$tempId?{$tempId:$.$tempId}:{},$op:Q(),...T?{}:{[I.path]:$.$bzId},[I.plays]:w,[tt]:I,[ot]:"linkField"};c(C),($.$op==="unlink"||Q()==="unlink")&&T&&c({$thing:I.relation,$thingType:"relation",$bzId:A,$op:"match",[I.plays]:w,[tt]:I,[ot]:"linkField"});}if($.$thingType==="relation"){let T=mt($,(w,Q)=>R.includes(w)),A=mapEntries(T,(w,Q)=>isArray(Q)?[w,Q]:isObject(Q)?[w,Q.$bzId]:[w,Q]),F=mt(h,(w,Q)=>w.startsWith("$")||w.startsWith("Symbol"));if(Object.keys(T).filter(w=>!w.startsWith("$")).length>0){if($.$op==="create"||$.$op==="delete"){let w=()=>{if($.$op==="create")return "link";if($.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},Q=O(t,$).roles,C=mapEntries(A,(N,D)=>{let z=Q[N]?.cardinality;if(!z)throw new Error(`Role ${N} not found in schema`);if(Array.isArray(D)){if(z==="ONE"){if(D.length>1)throw new Error(`[Error] Role ${N} is not a MANY relation`);return [N,D[0].$bzId||D[0]]}return [N,D.map(V=>V.$bzId||V)]}return [N,D.$bzId||D]}),S={...F,$thing:$.$thing,$thingType:"relation",$op:w(),...C,$bzId:$.$bzId,[ot]:"roleField"};c(S);return}if($.$op==="match"||$.$op==="update"&&Object.keys(T).length>0){let w=0;Object.entries(T).forEach(([Q,C])=>{let S=isArray(C)?C:[C],N=D=>D==="create"||D==="replace"?"link":D;S.forEach(D=>{if(!D)return;let z=N(D.$op);if(z==="replace")throw new Error("Not supported yet: replace on roleFields");if(z==="unlink"&&w>0)throw w+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let V={...F,$thing:$.$thing,$thingType:"relation",$op:z==="delete"?"unlink":z,[Q]:D.$bzId,$bzId:$.$bzId,[ot]:"roleField"};c(V);});});}}}}}),[r,l]},[p,a]=n(e),d=p.reduce((u,r)=>{if(!r.$bzId)return [...u,r];let l=u.findIndex(o=>o.$bzId===r.$bzId);if(l===-1)return [...u,r];if(u[l].$op==="create"&&r.$op==="match")return u;if(u[l].$op==="match"&&(r.$op==="create"||r.$op==="match"))return [...u.slice(0,l),r,...u.slice(l+1)];throw new Error(`[Wrong format] Wrong operation combination for $tempId "${r.$tempId}". Existing: ${u[l].$op}. Current: ${r.$op}`)},[]),s=a.reduce((u,r)=>{let l=u.find(o=>(o.$id&&o.$id===r.$id||o.$bzId&&o.$bzId===r.$bzId)&&o.$thing===r.$thing&&o.$op===r.$op);if(l){let o={...l};return Object.keys(r).forEach(c=>{if(typeof c=="symbol"||c.startsWith("$"))return;let i=l[c],h=r[c];Array.isArray(i)&&Array.isArray(h)?o[c]=Array.from(new Set([...i,...h])):!Array.isArray(i)&&Array.isArray(h)?i!==void 0?o[c]=Array.from(new Set([i,...h])):o[c]=h:Array.isArray(i)&&!Array.isArray(h)?h!==void 0&&(o[c]=Array.from(new Set([...i,h]))):i!==null&&h!==null&&i!==void 0&&h!==void 0?o[c]=Array.from(new Set([i,h])):i==null&&(o[c]=h);}),[...u.filter(c=>!((c.$id&&c.$id===r.$id||c.$bzId&&c.$bzId===r.$bzId)&&c.$thing===r.$thing&&c.$op===r.$op)),o]}return [...u,r]},[]);d.forEach(u=>{if((u.$thingType==="relation"||"relation"in u)&&s.filter(r=>r.$bzId===u.$bzId||r.$tempId&&r.$tempId===u.$tempId).length===0){if(u.$op==="delete"||u.$op==="match"||u.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(je(u))}`)}});let B=[...d,...s];return new Set(B.filter(u=>u.$tempId).map(u=>u.$tempId)).forEach(u=>{if(B.filter(r=>r.$tempId===u&&r.$op==="create").length===0)throw new Error("Can't link a $tempId that has not been created in the current mutation.")}),{mergedThings:d,mergedEdges:s}};var _e=async(e,t,n)=>{let p=o=>{let f=o.$op,c=`$${o.$bzId}`,i=O(n,o),{idFields:h,defaultDBConnector:m}=i,E=m?.path||o.$thing,$=o.$id,M=h?.[0],P=listify(o,(A,F)=>{if(A.startsWith("$")||A===M||F===void 0||F===null)return "";let w=i.dataFields?.find(S=>S.path===A);if(!w?.path)return "";let C=w.dbPath;if(["TEXT","ID","EMAIL"].includes(w.contentType))return `has ${C} '${F}'`;if(["NUMBER","BOOLEAN"].includes(w.contentType))return `has ${C} ${F}`;if(w.contentType==="DATE"){if(Number.isNaN(F.valueOf()))throw new Error("Invalid format, Nan Date");return F instanceof Date?`has ${C} ${F.toISOString().replace("Z","")}`:`has ${C} ${new Date(F).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${w.contentType}`)}).filter(A=>A),R=`${c}-atts`,g=listify(o,A=>{if(A.startsWith("$")||A===M)return "";let F=i.dataFields?.find(C=>C.path===A);if(!F?.path)return "";let Q=F.dbPath;return `{${R} isa ${Q};}`}).filter(A=>A),b=isArray($)?`like '${$.join("|")}'`:`'${$}'`,k=$?[`has ${M} ${b}`]:[],y=[...k,...P].filter(A=>A).join(","),I=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${c} isa ${[E,...k].filter(A=>A).join(",")};`;if(f==="update"){if(!g.length)throw new Error("update without attributes");return `${c} isa ${[E,...k].filter(A=>A).join(",")}, has ${R};
60
- ${g.join(" or ")};`}return ""},T=()=>f==="update"||f==="link"||f==="match"?`${c} isa ${[E,...k].filter(A=>A).join(",")};`:"";if(wt(o))return {op:f,deletionMatch:I(),insertionMatch:T(),insertion:f==="create"?`${c} isa ${[E,y].filter(A=>A).join(",")};`:f==="update"&&P.length?`${c} ${P.join(",")};`:"",deletion:f==="delete"?`${c} isa ${E};`:f==="update"&&g.length?`${c} has ${R};`:""};throw new Error("in attributes")},a=o=>{let f=o.$op,c=O(n,o),i=`$${o.$bzId}`,h=o.$id,m=c.defaultDBConnector?.path||o.$thing,E="roles"in c?listify(c.roles,F=>F):[],$="roles"in c?mapEntries(c.roles,(F,w)=>[F,w.dbConnector?.path||F]):{},M=listify(o,(F,w)=>{if(!E.includes(F))return null;if(!("roles"in c))throw new Error("This should have roles! ");let Q=$[F];return Array.isArray(w)?w.map(C=>({path:Q,id:C})):{path:Q,id:w}}).filter(F=>F).flat(),P=M.map(F=>{if(!F?.path)throw new Error("Object without path");return `${F.path}: $${F.id}`}),R=M.length>0?`( ${P.join(" , ")} )`:"",g=o[ot];if(!g)throw new Error("[internal error] Symbol edgeType not defined");let b=R?`${i} ${R} ${g==="linkField"||f==="delete"||f==="unlink"?`isa ${m}`:""}`:"",k=`${i} ${g==="linkField"||f==="delete"?`isa ${m}`:""}`,y=()=>b?f==="link"?`${b};`:f==="create"?`${b}, has id '${h}';`:"":"",I=()=>b&&f==="match"?`${b};`:"",T=()=>b?f==="delete"?`${b};`:f==="match"?`${b};`:"":"",A=()=>b?f==="delete"?`${k};`:f==="unlink"?`${i} ${R};`:"":"";return {deletionMatch:T(),insertionMatch:I(),deletion:A(),insertion:y(),op:""}},d=(o,f)=>{let c=f==="edges"?a:p;if(Array.isArray(o))return o.map(M=>{let{preDeletionBatch:P,insertionMatch:R,deletionMatch:g,insertion:b,deletion:k}=c(M);return shake({preDeletionBatch:P,insertionMatch:R,deletionMatch:g,insertion:b,deletion:k},y=>!y)}).filter(M=>M);let{preDeletionBatch:i,insertionMatch:h,deletionMatch:m,insertion:E,deletion:$}=c(o);return shake({preDeletionBatch:i,insertionMatch:h,deletionMatch:m,insertion:E,deletion:$},M=>!M)},s=d(e),B=Array.isArray(s)?s:[s],L=d(t,"edges"),u=Array.isArray(L)?L:[L],r=[...B,...u];return shake({insertionMatches:r.map(o=>o.insertionMatch).join(" ").trim(),deletionMatches:r.map(o=>o.deletionMatch).join(" ").trim(),insertions:r.map(o=>o.insertion).join(" ").trim(),deletions:r.map(o=>o.deletion).join(" ").trim()},o=>!o)};var Jr=Symbol.for("grandChildOfCreate"),Ve=async(e,t,n,p)=>{let a=(g,b)=>Object.keys(g).filter(k=>k.startsWith("$")?!1:b?!O(t,g).dataFields?.find(I=>I.path===k):!0);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(n.mutation?.preQuery===!1)return;let d=[];if(traverse(e,({parent:g,key:b,value:k})=>{g&&b&&!b.includes("$")&&isObject(g)?(Array.isArray(g[b])?g[b]:[g[b]]).forEach(I=>{if(isObject(I)){if(g.$op!=="create")d.includes(I.$op)||d.push(I.$op);else if(I.$op==="delete"||I.$op==="unlink")throw new Error(`Cannot ${I.$op} under a create`)}}):!g&&isObject(k)&&(d.includes(k.$op)||d.push(k.$op));}),!d.includes("delete")&&!d.includes("unlink")&&!d.includes("replace")&&!d.includes("update")&&!d.includes("link"))return;let B=(g=>{let b=(k,y)=>{let I=[],T={},A=["$op","$bzId","$parentKey"],F=["$relation","$entity","$id",...A];for(let w in k)if(!A.includes(w)&&!(F.includes(w)&&!y))if(!w.includes("$")&&(isObject(k[w])||Array.isArray(k[w]))){let Q=k[w];Array.isArray(Q)&&Q.length>0?Q.forEach(C=>{I.push({$path:w,...b(C)});}):I.push({$path:w,...b(Q)});}else T[w]=k[w];return {...T,$fields:I}};return g.map(k=>b(k,!0))})(Array.isArray(e)?e:[e]),L=await Tt(B,n,t,p),u=(g,b)=>{let k=g.$id||g.id||g.$bzId;if(g.$objectPath){let{$objectPath:y}=g,I=y?.beforePath||"root",T=Array.isArray(y.ids)?`[${y.ids}]`:y.ids;return {beforePath:`${I}.${T}___${y.key}`,ids:k,key:b}}else return {beforePath:"root",ids:k,key:b}},r=(g,b)=>{let k=g?.beforePath||"root",y=b||(Array.isArray(g?.ids)?`[${g?.ids}]`:g?.ids);return `${k}.${y}___${g?.key}`},l=g=>{if(g.includes("[")&&g.includes("]")){let[b,k,y]=g.split(/[[\]]/);return k.split(",").map(T=>`${b}${T}${y}`)}else return [g]},o={};(g=>produce(g,b=>traverse(b,k=>{let{key:y,parent:I}=k;if(I&&y&&I.$id&&!y.includes("$")){let T=u(I,y),A=r(T);if(Array.isArray(I[y])){let F=[];I[y].forEach(w=>{isObject(w)?(w.$objectPath=T,F.push(w.$id.toString())):w&&F.push(w.toString());}),o[A]={$objectPath:T,$ids:F};}else {let F=I[y];isObject(F)?(o[A]={$objectPath:T,$ids:[F.$id.toString()]},F.$objectPath=T):F&&(o[A]={$objectPath:T,$ids:[F.toString()]});}}})))(L||{});let c=g=>produce(g,b=>traverse(b,k=>{let{key:y,value:I,parent:T}=k;T&&y&&!y.includes("$")&&(Array.isArray(I)||isObject(I))&&!Array.isArray(T)&&(Array.isArray(T[y])?T[y].forEach(A=>{typeof A!="string"&&(A.$objectPath=u(T,y),A.$parentIsCreate=T.$op==="create",A[Jr]=T.$parentIsCreate||T[Symbol.for("grandChildOfCreate")]);}):isObject(T[y])&&(T[y].$parentIsCreate=T.$op==="create",T[y][Symbol.for("grandChildOfCreate")]=T.$parentIsCreate||T[Symbol.for("grandChildOfCreate")],T[y].$objectPath=u(T,y)));})),i=c(e),m=(g=>{let b=(T,A)=>{let F=[];T.filter(S=>S).forEach(S=>{let N=Object.keys(S).filter(D=>!D.startsWith("$")).length;if(Array.isArray(S.$id)&&N>0){let D=S.$id.map(z=>({...S,$id:z}));F=[...F,...D];}else F.push({...S});});let w=[],Q=[],C=F.filter(S=>{let D=["delete","update","unlink"].includes(S.$op||""),z=a(S,!0).length;if((!S.$id||Array.isArray(S.$id)&&z>0||S.$filter)&&D)return !0;Q.push({...S});});return C.length>0?C.forEach(S=>{let D=(j=>{let ut=(()=>{let v={};for(let x in j){let X=O(t,j);!x.startsWith("$")&&X.dataFields?.find(at=>at.path===x)&&(v[x]=j[x]);}return v})(),ht=Object.keys(j),G=ht.filter(v=>!v.startsWith("$")),At=[],Ft=(v,x)=>{if(v===G.length){let at={...x};ht.forEach(W=>{W.startsWith("$")&&(at[W]=j[W]);}),At.push(at);return}let X={...x,[G[v]]:j[G[v]],...J(x),...ut};Ft(v+1,X),Ft(v+1,x);};return Ft(0,{...J(j)}),At})(S).filter(j=>!(j.$op==="update"&&Object.keys(j).filter(nt=>!nt.startsWith("$")).length===0)),z=[],V=r(S.$objectPath),Y=o[V]?o[V].$ids:[],q=D.map((j,nt)=>{let ut=O(t,j),G=Object.keys(j).filter(x=>!x.includes("$")&&!ut.dataFields?.some(X=>X.path===x)).map(x=>(Array.isArray(j[x])?j[x].length>1?j[x].filter(W=>!W.$id||Array.isArray(W.$id)||W.$filter):j[x]:[j[x]]).map(W=>{let Rt=r(W.$objectPath);return {idsToKey:(Ct=>{let Yt=[],$t=Ct.split("."),Ye=$t.slice(0,$t.length-1).join("."),Ge=$t.slice($t.length-1,$t.length)[0].split("___")[1];for(let St in o)if(St.startsWith(Ye)&&St.endsWith(Ge)){let Ot=St.split("."),Xe=Ot.slice(Ot.length-1,Ot.length)[0].split("___")[0];Yt.push(Xe);}return Yt})(Rt),key:x,multiple:W}})).filter(x=>x!==void 0),v=(x=>{let X=x.map(W=>W.map(it=>it.idsToKey));return (W=>W.length>0?W.reduce((it,ft)=>it.concat(ft),[]).reduce((it,ft)=>it?ft.filter(Ct=>it.includes(Ct)):ft):[])(X)})(G).filter(x=>!z.includes(x));if(z=[...z,...v],Y=Y.filter(x=>!v.includes(x)),nt===D.length-1&&Y.length>0)return {...j,$id:Y,$bzId:`T1_${v4()}`,...J(j)};if(v.length>0)return {...j,$id:v,$bzId:`T2_${v4()}`,...J(j)}}).filter(j=>j!==void 0),Ze=(()=>{if(q.length===0&&!A?.$id)return C;if(q.length===0&&A?.$id){let j=Array.isArray(A.$id)?A.$id:[A.$id],nt=[];return j.forEach(ut=>{let ht=r({...S.$objectPath,ids:ut}),G=o[ht];G&&nt.push({...S,$id:G.$ids,...J(S),$bzId:`T_${v4()}`});}),nt}else return q.filter(j=>j!==void 0)})();w=[...Q,...Ze].map(k);}):w=F.map(k),w},k=T=>{let A={...T,$bzId:T.$tempId??`T3_${v4()}`,...J(T)},F=O(t,T);return Object.keys(T).filter(w=>!w.includes("$")&&!F.dataFields?.some(Q=>Q.path===w)).forEach(w=>{let Q=Array.isArray(T[w])?T[w]:[T[w]],C=b(Q,T);A[w]=C.length>0?C:void 0;}),A},y=[];return g.forEach(T=>{y=[...y,...b([T])];}),y.map(T=>k(T))})(Array.isArray(i)?i:[i]),E=g=>g.map(b=>{let k=a(b,!0),y={...b};return k.forEach(I=>{let T=Array.isArray(b[I])?b[I]:[b[I]],A=[],F=[],w=[],Q={},C=jt(t,b,I);T.filter(q=>q).forEach(q=>{q.$op==="replace"&&q.$id?(Q=q,Array.isArray(q.$id)?F=[...F,...q.$id]:F.push(q.$id)):q.$op==="create"&&C==="ONE"&&q.id?(Q=q,Array.isArray(q.id)?w=[...F,...q.id]:w.push(q.id)):A.push(q);});let S=r(Q.$objectPath),D=l(S).map(q=>o[q]),z=[];D.filter(q=>q!=null).forEach(q=>{z=[...z,...q.$ids];});let V=z.filter(q=>!F.includes(q)),Pt=F.filter(q=>!z.includes(q)),Y=J(Q);V.length>0&&A.push({...Q,$op:"unlink",$id:V,$bzId:`T4_${v4()}`,id:void 0,...Y}),Pt.length>0&&Pt.forEach(q=>{A.push({...Q,$op:"link",$id:q,$bzId:`T5_${v4()}`,...Y});}),w.length>0&&w.forEach(q=>{A.push({...Q,$op:"create",id:q,$bzId:`T6_${v4()}`,...Y});}),y[I]=E(A);}),y}),$=c(E(c(m)));return (g=>produce(g,b=>traverse(b,k=>{let{key:y,value:I,parent:T}=k;y&&T&&!y?.includes("$")&&(Array.isArray(I)||isObject(I))&&!Array.isArray(T)&&(Array.isArray(I)?I:[I]).forEach(F=>{let w=o[r(F.$objectPath)],Q=(N,D)=>N.every(z=>D.includes(z)),C=F.$id?Array.isArray(F.$id)?Q(F.$id,w?w.$ids:[]):w?.$ids.includes(F.$id):w,S=jt(t,T,F.$objectPath.key);if(F.$op==="link"&&C&&S==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${r(F.$objectPath)}" because it is already occupied.`);if(F.$op)switch(F.$op){case"delete":if(!C&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${F.$id}" because it is not linked to $id:"${T.$id}"`);break;case"update":if(!C&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${F.$id}" because it is not linked to $id:"${T.$id}"`);break;case"unlink":if(!C&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${F.$id}" because it is not linked to $id:"${T.$id}"`);break;case"link":if(C)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${F.$id}" because it is already linked to $id:"${T.$id}"`);break;}});})))($),(g=>produce(g,b=>traverse(b,k=>{let{value:y,meta:I}=k;isObject(y)&&(y[Symbol.for("path")]=I.nodePath,delete y.$objectPath,delete y.$parentIsCreate);})))($)};var{createMachine:Zr,invoke:dt,transition:et,reduce:rt,guard:Yr,interpret:Gr,state:Xr}=we,He=Xr,Ut=(e,t)=>t.data?{...e,bql:{...e.bql,current:t.data}}:e,tn=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),en=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),rn=(e,t)=>({...e,typeDB:{...e.typeDB,tqlMutation:t.data}}),nn=(e,t)=>({...e,typeDB:{...e.typeDB,tqlRes:t.data}}),on=async e=>Object.keys(e.bql.current).length?Ht(e.bql.current,e.schema):Ht(e.bql.raw,e.schema),sn=async e=>Ve(e.bql.current,e.schema,e.config,e.handles),an=async e=>We(e.bql.current,e.schema),ln=async e=>_e(e.bql.things,e.bql.edges,e.schema),cn=async e=>De(e.typeDB.tqlMutation,e.handles,e.config),dn=async e=>xe(e.typeDB.tqlRes,e.bql.things,e.bql.edges,e.config),pn=()=>!0,pt=et("error","error",rt((e,t)=>({...e,error:t.error}))),un=Zr("enrich",{enrich:dt(on,et("done","preQuery",Yr(pn),rt(Ut)),et("done","parseBQL",rt(Ut)),pt),preQuery:dt(sn,et("done","parseBQL",rt(Ut)),pt),parseBQL:dt(an,et("done","buildMutation",rt(en)),pt),buildMutation:dt(ln,et("done","runMutation",rt(rn)),pt),runMutation:dt(cn,et("done","parseMutation",rt(nn)),pt),parseMutation:dt(dn,et("done","success",rt(tn)),pt),success:He(),error:He()},e=>e),hn=async e=>new Promise((t,n)=>{Gr(un,p=>{p.machine.state.name==="success"&&t(p.context),p.machine.state.name==="error"&&n(p.context);},e);}),Ke=async(e,t,n,p)=>hn({bql:{raw:e,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:t,config:n,handles:p,depthLevel:0,error:null});enableMapSet();var Zt=class{schema;config;dbHandles;constructor({schema:t,config:n}){this.schema=t,this.config=n;}getDbHandles=()=>this.dbHandles;init=async()=>{let t={typeDB:new Map,surrealDB:new Map};await Promise.all(this.config.dbConnectors.map(async p=>{if(p.provider==="typeDB"&&p.dbName){let[a,d]=await tryit(TypeDB.coreDriver)(p.url);if(a){let s=`[BORM:${p.provider}:${p.dbName}:core] ${a.message??"Can't create TypeDB Client"}`;throw new Error(s)}try{let s=await d.session(p.dbName,SessionType.DATA);t.typeDB.set(p.id,{client:d,session:s});}catch(s){let B=`[BORM:${p.provider}:${p.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(B)}}if(p.provider==="typeDBCluster"&&p.dbName){let[a,d]=await tryit(TypeDB.cloudDriver)(p.addresses,p.credentials);if(a){let s=`[BORM:${p.provider}:${p.dbName}:core] ${a.message??"Can't create TypeDB Cluster Client"}`;throw new Error(s)}try{let s=await d.session(p.dbName,SessionType.DATA);t.typeDB.set(p.id,{client:d,session:s});}catch(s){let B=`[BORM:${p.provider}:${p.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(B)}}}));let n=ie(this.schema,t);this.schema=n,this.dbHandles=t;};#t=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#t(),this.schema);define=async()=>(await this.#t(),Xt(this.config,this.schema,this.dbHandles));query=async(t,n)=>{await this.#t();let p={...this.config,query:{...qt.query,...this.config.query,...n}};return Tt(t,p,this.schema,this.dbHandles)};mutate=async(t,n)=>{await this.#t();let p={...this.config,mutation:{...qt.mutation,...this.config.mutation,...n}},[a,d]=await tryit(Ke)(t,this.schema,p,this.dbHandles);if(a)throw console.error(a.error.stack.split(`
58
+ ;`,s){let m=s.filter(k=>k.$fieldType==="data");m&&m.length>0&&i(m,a);let E=s.filter(k=>k.$fieldType==="link");E&&E.length>0&&l(E,a,a);let $=s.filter(k=>k.$fieldType==="role");$&&$.length>0&&c($,a,a);}}})(t),e.tqlRequest=g?M:n;};var vt=e=>{let t=e.dataFields?.map(c=>c.path)||[],n=e.linkFields?.map(c=>c.path)||[],o=Object.keys(e.roles||{})||[];return [...t,...n,...o]},Ht=(e,t)=>Object.keys(e||{}).some(o=>{if(!Array.isArray(e[o])){let i=t.idFields?.includes(o),c=t.dataFields?.some(l=>(l.dbPath===o||l.path===o)&&l?.validations?.unique);return i||c}return !1}),Kt=(e,t)=>{let n=t.dataFields?.map(l=>({path:l.path,dbPath:l.dbPath}))||[],o=t.linkFields?.map(l=>({path:l.path,dbPath:l.dbPath}))||[],i=Object.keys(t.roles||{}).map(l=>({path:l,dbPath:l}))||[],c=[...n,...o,...i];return Object.entries(e||{}).reduce((l,[g,M])=>{let u=c.find(r=>r.path===g);return l[u?.dbPath||g]=M,l},{})},ye=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,d)=>typeof d=="string"?r.idFields?.includes(d):r.idFields?.includes(d.$path),i=(r,d,a,f,p)=>({$path:d,$dbPath:f,$thingType:"attribute",$as:r.$as||d,$var:d,$fieldType:"data",$excludedFields:r.$excludedFields,$justId:a,$id:r.$id,$filter:r.$filter,$isVirtual:p,$filterProcessed:!0}),c=(r,d,a,f,p)=>{let{target:s,oppositeLinkFieldsPlayedBy:h}=a;return h.map(m=>{let E=s==="role"?m.thingType:"relation",$=s==="role"?m.thing:a.relation,k={[`$${E}`]:$},P=S(n,k),C=r?.$fields?.filter(b=>o(P,b)).length===0,B=[];return typeof r!="string"?r.$fields?C?B=[...r.$fields,...P.idFields]:B=r.$fields:B=vt(P):B=["id"],r.$excludedFields&&(B=B.filter(b=>o(P,b)?!0:!r.$excludedFields.includes(b.$path))),{$thingType:E,$plays:a.plays,$playedBy:m,$path:m.path,$dbPath:p,$as:r.$as||d,$var:d,$thing:$,$fields:B,$excludedFields:r.$excludedFields,$fieldType:"link",$target:s,$intermediary:m.relation,$justId:f,$id:r.$id,$filter:Kt(r.$filter,P),$idNotIncluded:C,$filterByUnique:Ht(r.$filter,P),$filterProcessed:!0}})},l=(r,d,a,f,p)=>a.playedBy.map(s=>{let{thing:h,thingType:m,relation:E}=s,$={[`$${m}`]:h},k=S(n,$),P=r?.$fields?.filter(B=>k?.idFields?.includes(B)||k?.idFields?.includes(B.$path)).length===0,C=[];return typeof r!="string"?r.$fields?P?C=[...r.$fields,...k.idFields]:C=r.$fields:C=vt(k):C=["id"],r.$excludedFields&&(C=C.filter(B=>o(k,B)?!0:!r.$excludedFields.includes(B.$path))),{$thingType:m,$path:d,$dbPath:p,$as:r.$as||d,$var:d,$thing:h,$fields:C,$excludedFields:r.$excludedFields,$fieldType:"role",$intermediary:E,$justId:f,$id:r.$id,$filter:Kt(r.$filter,k),$idNotIncluded:P,$filterByUnique:Ht(r.$filter,k),$playedBy:s,$filterProcessed:!0}}),g=(r,d)=>{let a=typeof r=="string"?r:r.$path,f=typeof r=="string",p=d.dataFields?.find(m=>m.path===a),s=d.linkFields?.find(m=>m.path===a),h=d.roles?.[a];if(p){let m=p.isVirtual&&p.default;return i(r,a,f,p.dbPath,m)}else {if(s)return c(r,a,s,f,s.dbPath);if(h)return l(r,a,h,f,h.dbPath)}return null},u=(r=>produce(r,d=>traverse(d,a=>{let{value:f,meta:p}=a,s=f;if(isObject(s)){if(s.$id){let h=s.$entity||s.$relation?s:{[`$${s.$thingType}`]:s.$thing},m=S(n,h);if(!m?.name)throw new Error(`Schema not found for ${s.$thing}`);if(s.$path=m.name,Array.isArray(s.$id)||(s.$filterByUnique=!0),m?.idFields?.length===1){let[E]=m.idFields;s.$filter={...s.$filter,[E]:s.$id},delete s.$id;}else throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in s||"$relation"in s||"$thing"in s){let h=S(n,s);if(!h?.name)throw new Error(`Schema not found for ${s.$thing}`);s.$path=h.name;}if(s.$entity?(s.$thing=s.$entity,s.$thingType="entity",delete s.$entity):s.$relation&&(s.$thing=s.$relation,s.$thingType="relation",delete s.$relation),isObject(s)&&"$thing"in s){let h=s.$entity||s.$relation?s:{[`$${s.$thingType}`]:s.$thing};s[K]=p.nodePath;let m=S(n,h);if(s.$filter&&(s.$filterByUnique=Ht(s.$filter,m),s.$filterProcessed||(s.$filter=Kt(s.$filter,m))),s.$fields){s.$fields.filter(k=>m?.idFields?.includes(k)||m?.idFields?.includes(k.$path)).length>0||(s.$fields=[...s.$fields,...Array.isArray(m.idFields)?m.idFields:[]],s.$idNotIncluded=!0);let $=s.$fields?.flatMap(k=>{let P=g(k,m);return Array.isArray(P)?P:[P]}).filter(Boolean);s.$fields=$;}else {let $=vt(m)?.flatMap(k=>{let P=g(k,m);return Array.isArray(P)?P:[P]}).filter(Boolean);s.$fields=$;}s.$excludedFields&&(s.$fields=s.$fields.filter(E=>o(m,E)?!0:!s.$excludedFields.includes(E.$path)));}}})))(Array.isArray(t)?t:[t]);e.enrichedBqlQuery=u;};var Ft=async(e,t)=>{let n=t.dbConnectors[0].id,o=e.typeDB?.get(n)?.session,i=e.typeDB?.get(n)?.client;if(!o||!o.isOpen()){if(!i)throw new Error("Client not found");o=await i.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(n,{client:i,session:o});}return {client:i,session:o}};var Be=async(e,t)=>{let{dbHandles:n,enrichedBqlQuery:o,tqlRequest:i,config:c}=e;if(!o)throw new Error("BQL request not parsed");if(!i)throw new Error("TQL request not built");let l=new TypeDBOptions;if(l.infer=!0,Array.isArray(i)){let M=await parallel(i.length,i,async u=>{let{session:r}=await Ft(n,c),d=await r.transaction(TransactionType.READ,l);if(!d)throw new Error("Can't create transaction");let f=await d.query.fetch(u).collect();return await d.close(),f});t.rawTqlRes=M,t.isBatched=!0;}else {let{session:M}=await Ft(n,c),u=await M.transaction(TransactionType.READ,l);if(!u)throw new Error("Can't create transaction");let d=await u.query.fetch(i).collect();await u.close(),t.rawTqlRes=d;}};var Fe=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,n=/justId:([a-zA-Z0-9_\-·]+)/,o=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,i=/filterByUnique:([a-zA-Z0-9_\-·]+)/,c=e.match(t),l=e.match(n),g=e.match(o),M=e.match(i);return {as:c?c[1]:null,justId:l?l[1]:null,idNotIncluded:g?g[1]:null,filterByUnique:M?M[1]:null}},Sn=e=>{try{let n=(i=>{let c=i.replace("$metadata:","");return c=c.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),c=c.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(l,g,M)=>/^{.*}$/.test(M)?`:${M}`:`:${g}"${M}"`),c=c.replace(/\[([^\]]+)\]/g,(l,g)=>`[${g.split(",").map(M=>M.trim().startsWith("{")&&M.trim().endsWith("}")?M.trim():`"${M.trim()}"`).join(",")}]`),c})(e);return JSON.parse(n)}catch(t){return console.error(t),{as:[]}}},Ee=async(e,t)=>{let{enrichedBqlQuery:n,rawBqlRequest:o,schema:i,config:c}=e,{rawTqlRes:l,isBatched:g}=t;if(n){if(!l)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");let M=(s,h)=>{let{$metaData:m}=s,{as:E}=Sn(m),$=Object.entries(s).filter(([k])=>k!=="type"&&!k.includes("$")).map(([k,P])=>{let C=h.dataFields?.find(y=>y.path===k||y.dbPath===k),B=k==="id",b=Array.isArray(E)?E.find(y=>y[k])?.[k]:k,L;if(C?.cardinality==="ONE"){if(L=P[0]?P[0].value:c.query?.returnNulls?null:void 0,C.contentType==="DATE"&&(L=L&&`${L}Z`),B)return [[b,L],["$id",L]].filter(([y,I])=>I!==void 0)}else if(C?.cardinality==="MANY"){if(!isArray(P))throw new Error("Typedb fetch has changed its format");if(P.length===0)return c.query?.returnNulls?[[b,null]]:[];C.contentType==="DATE"?L=P.map(y=>`${y.value}Z`):L=P.map(y=>y.value);}return [[b,L]].filter(([y,I])=>I!==void 0)}).flat();return Object.fromEntries([...$])},u=s=>s.reduce((h,m)=>{let{$roleFields:E,$metaData:$,$cardinality:k}=m,{as:P,justId:C,idNotIncluded:B,filterByUnique:b}=Fe($),L=E.map(y=>{let{dataFields:I,currentSchema:T,linkFields:A,roleFields:F,schemaValue:w}=d(y),Q=M(I,T);if(C==="T")return Q.id;{let R=r(A),O=u(F),N={...Q};return B==="true"&&T?.idFields?.forEach(D=>delete N[D]),{...N,...R,...O,...w}}});return L.length>0?h[P]=k==="MANY"&&b==="false"?L:L[0]:c.query?.returnNulls&&(h[P]=null),h},{}),r=s=>s.reduce((h,m)=>{let{$linkFields:E,$metaData:$,$cardinality:k}=m,{as:P,justId:C,idNotIncluded:B,filterByUnique:b}=Fe($),L=E.map(y=>{let{dataFields:I,currentSchema:T,linkFields:A,roleFields:F,schemaValue:w}=d(y),Q=M(I,T);if(C==="T")return Q.id;{let R=r(A),O=u(F),N={...Q};return B==="true"&&T.idFields?.forEach(D=>delete N[D]),{...N,...R,...O,...w}}});return h[P]=L.length>0?k==="MANY"&&b==="false"?L:L[0]:c.query?.returnNulls?null:void 0,h},{}),d=s=>{let h=Object.keys(s),m=h.find(y=>y.endsWith(".$dataFields"));if(!m)throw new Error("No datafields");let E=s[m],$=m.split(".")[m.split(".").length-2];if(E.$metaData=$,E.length===0)throw new Error("No datafields");let k=E.type,P={$thing:k.label,$thingType:k.root,[K]:s.queryPath.value},C={[`$${P.$thingType}`]:P.$thing},B=S(i,C),b=h.filter(y=>!y.endsWith(".$dataFields")&&B.linkFields?.some(I=>I.path===y.split(".").pop())).map(y=>({$linkFields:s[y],$key:y.split(".").pop(),$metaData:y.split(".")[y.split(".").length-2],$cardinality:B?.linkFields?.find(I=>I.path===y.split(".").pop())?.cardinality})),L=h.filter(y=>!y.endsWith(".$dataFields")&&B.roles?.[y.split(".").pop()]).map(y=>({$roleFields:s[y],$key:y.split(".").pop(),$metaData:y.split(".")[y.split(".").length-2],$cardinality:B.roles[y.split(".").pop()].cardinality}));return {dataFields:E,schemaValue:P,currentSchema:B,linkFields:b,roleFields:L}},a=s=>s.map(h=>{let{dataFields:m,currentSchema:E,linkFields:$,roleFields:k,schemaValue:P}=d(h),C=M(m,E),B=r($),b=u(k),L=o?.$fields?.every(I=>!E?.idFields?.includes(I)&&!E?.idFields?.includes(I.$path));return {...B,...b,...P,...!c.query?.noMetadata&&o.$id?{$id:Array.isArray(o.$id)?C.id:o.$id}:{},...L?Object.fromEntries(Object.entries(C).filter(([I])=>!E?.idFields?.includes(I))):C}}),p=(s=>{let h=m=>{let E=a(m);return o.$id&&!Array.isArray(o.$id)||n[0].$filterByUnique?E[0]??null:E.length===0?null:E};return g?s.map(h):h(s)})(l);t.bqlRes=p;};var qn=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Dn=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,we=e=>{let n=e.toString().replace(qn,"").trim().split("=>")[0].split("{")[0].replace(Dn,"").trim(),o=n.substring(n.indexOf("(")+1,n.lastIndexOf(")")).trim();return o?(o.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(c=>c.includes("{")&&c.includes("}")?(c.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(g=>g.split(":")[0].trim().replace(/['"[\]]/g,"")):c.trim()).filter(Boolean):[]};var pt=({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:i}=t.default,l=we(i).filter(g=>!(g in e));if(l.length)throw new Error(`Virtual field: Missing arguments ${l.join(", ")}`)}return "default"in t?t.default?.fn(e):void 0};var be=async(e,t)=>{let{schema:n,enrichedBqlQuery:o}=e,{bqlRes:i}=t;if(!i)return;let l=(g=>produce(g,M=>traverse(M,({value:u})=>{if(isObject(u)){let r=u;if(!r.$thing)throw new Error("[Internal] Thing is missing");if(r.$thing){let d=S(n,r),{virtualFields:a}=d,f=r[K];if(!f)throw new Error("[Internal] QueryPath is missing");let p=getNodeByPath(o,f),s=p.$fields.map(m=>m.$path),h=p.$excludedFields;a.forEach(m=>{if(h?.includes(m)||s.length>0&&!s.includes(m))return;let E=d.dataFields?.find($=>$.path===m);if(E?.default){let $=pt({currentThing:r,fieldSchema:E,mandatoryDependencies:!0});r[m]=$;}else if(r[m]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${m}`)}),h&&h.forEach(m=>{if(typeof m!="string")throw new Error("[Internal] ExcludedField is not a string");delete r[m];});}}})))(i);t.bqlRes=l;};var Le=async(e,t)=>{let{config:n}=e,{bqlRes:o}=t;if(!o)return;let c=(M=>produce(M,u=>traverse(u,({value:r})=>{isObject(r);})))(o),g=(M=>produce(M,u=>traverse(u,({value:r})=>{if(isObject(r)){let d=r;Object.keys(d).forEach(a=>{d[a]===void 0&&delete d[a];}),Object.getOwnPropertySymbols(d).forEach(a=>{delete d[a];}),n.query?.noMetadata===!0&&Object.keys(d).forEach(a=>{a.startsWith("$")&&delete d[a];});}})))(c);t.bqlRes=g;};var _n={query:[ye,$e,Be,Ee,be,Le]},Qe=async(e,t,n={},o=!0)=>{for(let i of e){let c=await i(t,n);if(c&&Array.isArray(c))for(let l of c)await Qe(l.pipeline,l.req,l.res,!1);}return o&&t.config.query?.debugger===!0&&typeof n.bqlRes=="object"?{...n.bqlRes,$debugger:{tqlRequest:t.tqlRequest}}:n.bqlRes},Lt=(e,t,n,o)=>Qe(_n.query,{config:t,schema:n,rawBqlRequest:e,dbHandles:o},{});var ut=(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 Ie=(e,t,n)=>{let o=isArray(e[t])?e[t]:[e[t]];if(!o.every(i=>typeof i=="object"))if(o.every(i=>typeof i=="string")){let i=ut(t,n),[c]=i,l=e.$op==="create"?"link":"replace",g=c.thing,M=c.thingType;if(o.some(u=>u.startsWith("_:")))throw new Error("[Not supported] At least one child of a replace is a tempId");e[t]={$id:e[t],$op:l,$thing:g,$thingType:M,$bzId:`S_${v4()}`};}else throw new Error("[Mutation Error] Replace can only be used with a single id or an array of ids")};var Et=(e,t,n)=>{let o=S(n,t),{usedDataFields:i}=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"&&i.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&i.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var Qt=(e,t,n)=>{let o=S(n,t),{usedFields:i}=J(o,t);return t.$op?(Et(e,t,n),t.$op):t.$id||t.$filter?i.length>0?(Et(e,{...t,$op:"update"},n),"update"):(Et(e,{...t,$op:"link"},n),"link"):(Et(e,{...t,$op:"create"},n),"create")};var Ae=(e,t)=>{let o=(isArray(e.$root)?e.$root:[e.$root]).map(i=>{let c=Qt(i,i,t);return {...{...i.$thing?{}:{$thing:i.$entity||i.$relation},...i.$thingType?{}:{$thingType:ue(i,t)},...i.$op?{}:{$op:c},...i.$bzId?{}:{$bzId:`R_${v4()}`}},...i}});e.$root=isArray(e.$root)?o:o[0];};var It=(e,t)=>{let n=t[kt];return isSet(n)?n.has("clean")?(Reflect.set(t,kt,n.add("clean")),!0):!1:(Reflect.set(t,kt,new Set(["clean"])),!0)};var Ce=(e,t,n)=>{if(It("split_ids",e)){let o=(isArray(e[t])?e[t]:[e[t]]).flatMap(i=>{if(isObject(i)&&"$id"in i&&isArray(i.$id)){let c=i;if(S(n,c),!c.$bzId)throw new Error("[Internal Error] No bzId found");return c.$id.map((l,g)=>({...U(c),$id:l,$bzId:`${c.$bzId}_${g}`,...Z(c)}))}return i});(o.length>isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=o);}};var Oe=(e,t,n,o)=>{let i=(isArray(e[t])?e[t]:[e[t]]).map(c=>{let l=ut(t,n),[g]=l,M=Qt(e,{...c,$thing:g.thing,$thingType:g.thingType},o),u=c.$bzId?c.$bzId:c.$tempId?c.$tempId:`N_${v4()}`;return {...c,[rt]:n,$thing:g.thing,$thingType:g.thingType,$op:M,$bzId:u}});e[t]=isArray(e[t])?i:i[0];};var Se=(e,t,n)=>{let o=e[t];o&&(isArray(o)?o:[o]).forEach(i=>{let c=S(n,i),{unidentifiedFields:l}=J(c,i),{computedFields:g,virtualFields:M}=c,u=listify(i,(a,f)=>f!==void 0?a:void 0),r=u.filter(a=>M?.includes(a));if(r.length>0)throw new Error(`Virtual fields can't be sent to DB: "${r.join(",")}"`);if(g.filter(a=>!u.includes(a)).forEach(a=>{let f=c.dataFields?.find(E=>E.path===a),s=c.linkFields?.find(E=>E.path===a)?.oppositeLinkFieldsPlayedBy[0],h="roles"in c?de(c.roles,(E,$)=>E===a):void 0,m=f||s||h;if(!m)throw new Error(`no field Def for ${a}`);if(i.$op==="create"&&!i[a]){let E=pt({currentThing:i,fieldSchema:m,mandatoryDependencies:!0});i[a]=E;}}),l.length>0)throw new Error(`Unknown fields: [${l.join(",")}] in ${JSON.stringify(i)}`)});};var qe=(e,t,n)=>{let o=ut(t,n),[i]=o;e[t]={$thing:i.thing,$thingType:i.thingType,$op:"unlink",$bzId:`U_${v4()}`,[rt]:n};};var Pt=(e,t)=>{let n=S(t,e).hooks;if(n?.pre){let o=`on${he(e.$op)}`;return n.pre.filter(l=>l.triggers[o]?.()).flatMap(l=>l.actions)}return []};var je=(e,t,n)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(i=>{if("$thing"in i){let{requiredFields:c,enumFields:l,fnValidatedFields:g,dataFields:M}=S(n,i);if("$op"in i&&i.$op==="create"&&c.forEach(u=>{if(!(u in i))throw new Error(`[Validations] Required field "${u}" is missing.`)}),("$op"in i&&i.$op==="update"||i.$op==="create")&&l.forEach(u=>{if(u in i){let r=M?.find(d=>d.path===u)?.validations?.enum;if(!r)throw new Error(`[Validations] Enum field "${u}" is missing enum options.`);if(isArray(i[u]))i[u].some(d=>{if(!r.includes(d))throw new Error(`[Validations] Option "${d}" is not a valid option for field "${u}".`)});else if(r&&!r.includes(i[u]))throw new Error(`[Validations] Option "${i[u]}" is not a valid option for field "${u}".`)}}),("$op"in i&&i.$op==="update"||i.$op==="create")&&g.forEach(u=>{if(u in i)try{let r=M?.find(d=>d.path===u)?.validations?.fn;if(!r)throw new Error("Missing validation function.");if(!r(i[u]))throw new Error("Failed validation function.")}catch(r){throw new Error(`[Validations:attribute:${u}] ${r.message}`)}}),isObject(i)&&"$thing"in i){let u=i.$thing,r=i,d=clone(U(e)),a=clone(U(r));Pt(r,n).forEach(p=>{if(p.type==="validate"){if(p.severity!=="error")return;try{let s=p.fn(a,d);if(s===!1)throw new Error(`${p.message}.`);if(s!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(s){throw new Error(`[Validations:thing:${u}] ${s.message}`)}}});}}});};var _e=(e,t,n)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(i=>{if(Mt(i)){let c=Pt(i,n).filter(M=>M.type==="transform"),l=clone(U(e)),g=clone(U(i));return c.forEach(M=>{let u=M.fn(g,l);Object.keys(u).length!==0&&(i={...g,...u});}),i}});e[t]=isArray(e[t])?o:o[0];};var ir=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(It("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")},or=(e,t)=>{},Zt=(e,t)=>{let o=produce({$rootWrap:{$root:e}},i=>traverse(i,({value:c,parent:l,key:g,meta:M})=>{if(!(!l||!g)&&isObject(c)){if(!("$root"in c)){if(!("$thing"in c||"$entity"in c||"$relation"in c))throw g==="$root"?new Error("Root things must specify $entity or $relation"):new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(c)?current(c):c)}`)}let u=c;Object.keys(u).forEach(r=>{if(ir(u,r),r!=="$root"&&r.startsWith("$"))return;let d=r!=="$root"?_t(t,u,r):{fieldType:"rootField"};if(!d)throw new Error(`[Internal] Field ${r} not found in schema`);if("contentType"in d)return or();if(["rootField","linkField","roleField"].includes(d.fieldType)){if(["linkField","roleField"].includes(d.fieldType)&&Ie(u,r,d),d.fieldType==="rootField"){if(!("$root"in u))throw new Error(`[Internal] Field ${r} is a rootField but the object is not a root`);Ae(u,t);}let a=isArray(u[r])?u[r]:[u[r]],f=M.nodePath?.split(".").slice(1).join(".");a.forEach(s=>{if(s){if(d?.cardinality==="ONE"&&!s.$op&&!s.$id&&!s.$filter&&!s.$tempId&&u.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${f}.${r}`);if(s.$tempId&&!(s.$op===void 0||s.$op==="link"||s.$op==="create"||s.$op==="update"))throw new Error(`Invalid op ${s.$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(d.fieldType)&&(u[r]===null?qe(u,r,d):Oe(u,r,d,t)),Ce(u,r,t),["rootField","linkField","roleField"].includes(d.fieldType)&&Se(u,r,t),(isArray(u[r])?u[r]:[u[r]]).forEach(s=>{let h=S(t,s),{unidentifiedFields:m,usedLinkFields:E}=J(h,s);if(m.length>0)throw new Error(`Unknown fields: [${m.join(",")}] in ${JSON.stringify(c)}`);if(E.length>1){let $=h.linkFields?.filter(k=>E.includes(k.path));$?.some((k,P)=>$.some((C,B)=>{if(P!==B&&k.target!==C.target&&k.relation===C.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),_e(u,r,t),je(u,r,t);}});}}));return isArray(o.$rootWrap.$root),o.$rootWrap.$root};var We=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 Ft(t,n),i=await o.transaction(TransactionType.WRITE);if(!i)throw new Error("Can't create transaction");let c=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,l=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;c&&await i.query.delete(c);let g=l&&i.query.insert(l);try{let M=g?await g.collect():void 0;return await i.commit(),await i.close(),{insertions:M}}catch(M){throw await i.close(),new Error(`Transaction failed: ${M.message}`)}};var Ve=async(e,t,n,o)=>{let i=[...t,...n],c=i.map(l=>{let g=e.insertions?.find(M=>M.get(`${l.$bzId}`))?.get(`${l.$bzId}`);if(l.$op==="create"||l.$op==="update"||l.$op==="link"){if(l.$op!=="update"&&!g&&l.$id)return {$id:l.$id,$error:"Does not exist or it's not linked to the parent"};let M=g?.asThing().iid;if(o.mutation?.noMetadata)return Object.entries(l).filter(([d,a])=>!d.startsWith("$")).reduce((d,[a,f])=>{if(l.$thingType==="relation"){let p=i.filter(s=>s.$id&&s.$bzId===f);if(p.length>1)throw new Error(`Multiple things with the same bzId ${f}`);return p.length===1?(d[a]=p[0].$id,d):(d[a]=f,d)}return d[a]=f,d},{});let u=l.$tempId&&!l.$tempId.startsWith("_:")?{$tempId:`_:${l.$tempId}`}:{};return {$dbId:M,...l,[l.path]:l.$id,...u}}if(l.$op==="delete"||l.$op==="unlink")return l;if(l.$op!=="match")throw new Error(`Unsupported op ${l.$op}`)}).filter(l=>l);return clone(c)};var ve=e=>{let t=({value:n})=>(n&&typeof n=="object"&&"$id"in n&&(Object.keys(n).filter(c=>c.startsWith("$")).forEach(c=>delete n[c]),Object.keys(n).filter(c=>typeof c=="symbol").forEach(c=>delete n[c])),n);return produce(e,n=>traverse(n,t))};var Je=async(e,t)=>{let n=u=>{let r=[],d=[],a=h=>{if(h.$id)return h.$id;let m=S(t,h),{idFields:E}=m;if(!E)throw new Error(`no idFields: ${JSON.stringify(h)}`);let[$]=E;if(!$)throw new Error(`no idField: ${JSON.stringify(h)}`);let k=m.dataFields?.find(B=>B.path===$),P=pt({currentThing:h,fieldSchema:k,mandatoryDependencies:!0}),C=h[$]||h.$id||P;if(!C)throw new Error(`no idValue: ${JSON.stringify(h)}`);return C},f=h=>{if(h.$op==="create"){let m=a(h);if(r.find(E=>E.$id===m))throw new Error(`Duplicate id ${m} for node ${JSON.stringify(h)}`);if(d.find(E=>E.$bzId===h.$bzId))throw new Error(`Duplicate $bzid ${h.$bzId} for node ${JSON.stringify(h)}`);r.push({...h,$id:m});return}h.$tempId&&h.$op==="match"||r.push(h);},p=h=>{if(h.$op==="create"){let m=a(h);if(r.find(E=>E.$id===m),d.find(E=>E.$bzId===h.$bzId))throw new Error(`Duplicate %bzId ${h.$bzIdd} for edge ${JSON.stringify(h)}`);d.push({...h,$id:m});return}d.push(h);};return traverse(u,({value:h,parent:m,meta:E})=>{if(!isObject(h))return;let $=h;if($.$thing){if(!$.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify($)}`);if(!$.$bzId)throw new Error("[internal error] BzId not found");let k=S(t,$),{dataFields:P,roleFields:C,linkFields:B,usedFields:b}=J(k,$),L=()=>{if($.$op==="create"||$.$op==="delete")return $.$op;if($.$op==="update"){let T=b.filter(w=>P?.includes(w)),A=b.filter(w=>C?.includes(w)),F=b.filter(w=>B?.includes(w));if(T.length>0)return "update";if(A.length>0||F.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify($)}`)}return "match"},y={...$.$id&&{$id:$.$id},...$.$tempId&&{$tempId:$.$tempId},...$.$filter&&{$filter:$.$filter},$thing:$.$thing,...$.$thingType&&{$thingType:$.$thingType},...shake(pick($,P||[""])),$op:L(),$bzId:$.$tempId?$.$tempId:$.$bzId};f(y);let I=$[rt];if(I?.fieldType==="linkField"){if(($.$op==="link"||$.$op==="unlink")&&($.$id||$.$filter)){if($.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");r.push({...$,$op:"match"});}let T=I.relation===$.$thing,A=T?$.$bzId:`LT_${v4()}`,w=fe(u,m,E).$bzId;if(!w)throw new Error("No parent id found");if($[Symbol.for("relation")]==="$self")return;let Q=()=>{if($.$op==="delete")return T?"match":"delete";if($.$op==="unlink")return T?"unlink":"delete";if($.$op==="link"||$.$op==="create")return T?"link":"create";if($.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},R={$bzId:A,$thing:I.relation,$thingType:"relation",...$.$tempId?{$tempId:$.$tempId}:{},$op:Q(),...T?{}:{[I.path]:$.$bzId},[I.plays]:w,[rt]:I,[at]:"linkField"};p(R),($.$op==="unlink"||Q()==="unlink")&&T&&p({$thing:I.relation,$thingType:"relation",$bzId:A,$op:"match",[I.plays]:w,[rt]:I,[at]:"linkField"});}if($.$thingType==="relation"){let T=Bt($,(w,Q)=>C.includes(w)),A=mapEntries(T,(w,Q)=>isArray(Q)?[w,Q]:isObject(Q)?[w,Q.$bzId]:[w,Q]),F=Bt(h,(w,Q)=>w.startsWith("$")||w.startsWith("Symbol"));if(Object.keys(T).filter(w=>!w.startsWith("$")).length>0){if($.$op==="create"||$.$op==="delete"){let w=()=>{if($.$op==="create")return "link";if($.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},Q=S(t,$).roles,R=mapEntries(A,(N,D)=>{let z=Q[N]?.cardinality;if(!z)throw new Error(`Role ${N} not found in schema`);if(Array.isArray(D)){if(z==="ONE"){if(D.length>1)throw new Error(`[Error] Role ${N} is not a MANY relation`);return [N,D[0].$bzId||D[0]]}return [N,D.map(H=>H.$bzId||H)]}return [N,D.$bzId||D]}),O={...F,$thing:$.$thing,$thingType:"relation",$op:w(),...R,$bzId:$.$bzId,[at]:"roleField"};p(O);return}if($.$op==="match"||$.$op==="update"&&Object.keys(T).length>0){let w=0;Object.entries(T).forEach(([Q,R])=>{let O=isArray(R)?R:[R],N=D=>D==="create"||D==="replace"?"link":D;O.forEach(D=>{if(!D)return;let z=N(D.$op);if(z==="replace")throw new Error("Not supported yet: replace on roleFields");if(z==="unlink"&&w>0)throw w+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let H={...F,$thing:$.$thing,$thingType:"relation",$op:z==="delete"?"unlink":z,[Q]:D.$bzId,$bzId:$.$bzId,[at]:"roleField"};p(H);});});}}}}}),[r,d]},[o,i]=n(e),c=o.reduce((u,r)=>{if(!r.$bzId)return [...u,r];let d=u.findIndex(a=>a.$bzId===r.$bzId);if(d===-1)return [...u,r];if(u[d].$op==="create"&&r.$op==="match")return u;if(u[d].$op==="match"&&(r.$op==="create"||r.$op==="match"))return [...u.slice(0,d),r,...u.slice(d+1)];throw new Error(`[Wrong format] Wrong operation combination for $tempId "${r.$tempId}". Existing: ${u[d].$op}. Current: ${r.$op}`)},[]),l=i.reduce((u,r)=>{let d=u.find(a=>(a.$id&&a.$id===r.$id||a.$bzId&&a.$bzId===r.$bzId)&&a.$thing===r.$thing&&a.$op===r.$op);if(d){let a={...d};return Object.keys(r).forEach(p=>{if(typeof p=="symbol"||p.startsWith("$"))return;let s=d[p],h=r[p];Array.isArray(s)&&Array.isArray(h)?a[p]=Array.from(new Set([...s,...h])):!Array.isArray(s)&&Array.isArray(h)?s!==void 0?a[p]=Array.from(new Set([s,...h])):a[p]=h:Array.isArray(s)&&!Array.isArray(h)?h!==void 0&&(a[p]=Array.from(new Set([...s,h]))):s!==null&&h!==null&&s!==void 0&&h!==void 0?a[p]=Array.from(new Set([s,h])):s==null&&(a[p]=h);}),[...u.filter(p=>!((p.$id&&p.$id===r.$id||p.$bzId&&p.$bzId===r.$bzId)&&p.$thing===r.$thing&&p.$op===r.$op)),a]}return [...u,r]},[]);c.forEach(u=>{if((u.$thingType==="relation"||"relation"in u)&&l.filter(r=>r.$bzId===u.$bzId||r.$tempId&&r.$tempId===u.$tempId).length===0){if(u.$op==="delete"||u.$op==="match"||u.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(ve(u))}`)}});let g=[...c,...l];return new Set(g.filter(u=>u.$tempId).map(u=>u.$tempId)).forEach(u=>{if(g.filter(r=>r.$tempId===u&&r.$op==="create").length===0)throw new Error("Can't link a $tempId that has not been created in the current mutation.")}),{mergedThings:c,mergedEdges:l}};var Ze=async(e,t,n)=>{let o=a=>{let f=a.$op,p=`$${a.$bzId}`,s=S(n,a),{idFields:h,defaultDBConnector:m}=s,E=m?.path||a.$thing,$=a.$id,k=h?.[0],P=listify(a,(A,F)=>{if(A.startsWith("$")||A===k||F===void 0||F===null)return "";let w=s.dataFields?.find(O=>O.path===A);if(!w?.path)return "";let R=w.dbPath;if(["TEXT","ID","EMAIL"].includes(w.contentType))return `has ${R} '${F}'`;if(["NUMBER","BOOLEAN"].includes(w.contentType))return `has ${R} ${F}`;if(w.contentType==="DATE"){if(Number.isNaN(F.valueOf()))throw new Error("Invalid format, Nan Date");return F instanceof Date?`has ${R} ${F.toISOString().replace("Z","")}`:`has ${R} ${new Date(F).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${w.contentType}`)}).filter(A=>A),C=`${p}-atts`,B=listify(a,A=>{if(A.startsWith("$")||A===k)return "";let F=s.dataFields?.find(R=>R.path===A);if(!F?.path)return "";let Q=F.dbPath;return `{${C} isa ${Q};}`}).filter(A=>A),b=isArray($)?`like '${$.join("|")}'`:`'${$}'`,L=$?[`has ${k} ${b}`]:[],y=[...L,...P].filter(A=>A).join(","),I=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${p} isa ${[E,...L].filter(A=>A).join(",")};`;if(f==="update"){if(!B.length)throw new Error("update without attributes");return `${p} isa ${[E,...L].filter(A=>A).join(",")}, has ${C};
59
+ ${B.join(" or ")};`}return ""},T=()=>f==="update"||f==="link"||f==="match"?`${p} isa ${[E,...L].filter(A=>A).join(",")};`:"";if(Mt(a))return {op:f,deletionMatch:I(),insertionMatch:T(),insertion:f==="create"?`${p} isa ${[E,y].filter(A=>A).join(",")};`:f==="update"&&P.length?`${p} ${P.join(",")};`:"",deletion:f==="delete"?`${p} isa ${E};`:f==="update"&&B.length?`${p} has ${C};`:""};throw new Error("in attributes")},i=a=>{let f=a.$op,p=S(n,a),s=`$${a.$bzId}`,h=a.$id,m=p.defaultDBConnector?.path||a.$thing,E="roles"in p?listify(p.roles,F=>F):[],$="roles"in p?mapEntries(p.roles,(F,w)=>[F,w.dbConnector?.path||F]):{},k=listify(a,(F,w)=>{if(!E.includes(F))return null;if(!("roles"in p))throw new Error("This should have roles! ");let Q=$[F];return Array.isArray(w)?w.map(R=>({path:Q,id:R})):{path:Q,id:w}}).filter(F=>F).flat(),P=k.map(F=>{if(!F?.path)throw new Error("Object without path");return `${F.path}: $${F.id}`}),C=k.length>0?`( ${P.join(" , ")} )`:"",B=a[at];if(!B)throw new Error("[internal error] Symbol edgeType not defined");let b=C?`${s} ${C} ${B==="linkField"||f==="delete"||f==="unlink"?`isa ${m}`:""}`:"",L=`${s} ${B==="linkField"||f==="delete"?`isa ${m}`:""}`,y=()=>b?f==="link"?`${b};`:f==="create"?`${b}, has id '${h}';`:"":"",I=()=>b&&f==="match"?`${b};`:"",T=()=>b?f==="delete"?`${b};`:f==="match"?`${b};`:"":"",A=()=>b?f==="delete"?`${L};`:f==="unlink"?`${s} ${C};`:"":"";return {deletionMatch:T(),insertionMatch:I(),deletion:A(),insertion:y(),op:""}},c=(a,f)=>{let p=f==="edges"?i:o;if(Array.isArray(a))return a.map(k=>{let{preDeletionBatch:P,insertionMatch:C,deletionMatch:B,insertion:b,deletion:L}=p(k);return shake({preDeletionBatch:P,insertionMatch:C,deletionMatch:B,insertion:b,deletion:L},y=>!y)}).filter(k=>k);let{preDeletionBatch:s,insertionMatch:h,deletionMatch:m,insertion:E,deletion:$}=p(a);return shake({preDeletionBatch:s,insertionMatch:h,deletionMatch:m,insertion:E,deletion:$},k=>!k)},l=c(e),g=Array.isArray(l)?l:[l],M=c(t,"edges"),u=Array.isArray(M)?M:[M],r=[...g,...u];return shake({insertionMatches:r.map(a=>a.insertionMatch).join(" ").trim(),deletionMatches:r.map(a=>a.deletionMatch).join(" ").trim(),insertions:r.map(a=>a.insertion).join(" ").trim(),deletions:r.map(a=>a.deletion).join(" ").trim()},a=>!a)};var mr=Symbol.for("grandChildOfCreate"),Ye=async(e,t,n,o)=>{let i=(B,b)=>Object.keys(B).filter(L=>L.startsWith("$")?!1:b?!S(t,B).dataFields?.find(I=>I.path===L):!0);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(n.mutation?.preQuery===!1)return;let c=[];if(traverse(e,({parent:B,key:b,value:L})=>{B&&b&&!b.includes("$")&&isObject(B)?(Array.isArray(B[b])?B[b]:[B[b]]).forEach(I=>{if(isObject(I)){if(B.$op!=="create")c.includes(I.$op)||c.push(I.$op);else if(I.$op==="delete"||I.$op==="unlink")throw new Error(`Cannot ${I.$op} under a create`)}}):!B&&isObject(L)&&(c.includes(L.$op)||c.push(L.$op));}),!c.includes("delete")&&!c.includes("unlink")&&!c.includes("replace")&&!c.includes("update")&&!c.includes("link"))return;let g=(B=>{let b=(L,y)=>{let I=[],T={},A=["$op","$bzId","$parentKey"],F=["$relation","$entity","$id",...A];for(let w in L)if(!A.includes(w)&&!(F.includes(w)&&!y))if(!w.includes("$")&&(isObject(L[w])||Array.isArray(L[w]))){let Q=L[w];Array.isArray(Q)&&Q.length>0?Q.forEach(R=>{I.push({$path:w,...b(R)});}):I.push({$path:w,...b(Q)});}else T[w]=L[w];return {...T,$fields:I}};return B.map(L=>b(L,!0))})(Array.isArray(e)?e:[e]),M=await Lt(g,n,t,o),u=(B,b)=>{let L=B.$id||B.id||B.$bzId;if(B.$objectPath){let{$objectPath:y}=B,I=y?.beforePath||"root",T=Array.isArray(y.ids)?`[${y.ids}]`:y.ids;return {beforePath:`${I}.${T}___${y.key}`,ids:L,key:b}}else return {beforePath:"root",ids:L,key:b}},r=(B,b)=>{let L=B?.beforePath||"root",y=b||(Array.isArray(B?.ids)?`[${B?.ids}]`:B?.ids);return `${L}.${y}___${B?.key}`},d=B=>{if(B.includes("[")&&B.includes("]")){let[b,L,y]=B.split(/[[\]]/);return L.split(",").map(T=>`${b}${T}${y}`)}else return [B]},a={};(B=>produce(B,b=>traverse(b,L=>{let{key:y,parent:I}=L;if(I&&y&&I.$id&&!y.includes("$")){let T=u(I,y),A=r(T);if(Array.isArray(I[y])){let F=[];I[y].forEach(w=>{isObject(w)?(w.$objectPath=T,F.push(w.$id.toString())):w&&F.push(w.toString());}),a[A]={$objectPath:T,$ids:F};}else {let F=I[y];isObject(F)?(a[A]={$objectPath:T,$ids:[F.$id.toString()]},F.$objectPath=T):F&&(a[A]={$objectPath:T,$ids:[F.toString()]});}}})))(M||{});let p=B=>produce(B,b=>traverse(b,L=>{let{key:y,value:I,parent:T}=L;T&&y&&!y.includes("$")&&(Array.isArray(I)||isObject(I))&&!Array.isArray(T)&&(Array.isArray(T[y])?T[y].forEach(A=>{typeof A!="string"&&(A.$objectPath=u(T,y),A.$parentIsCreate=T.$op==="create",A[mr]=T.$parentIsCreate||T[Symbol.for("grandChildOfCreate")]);}):isObject(T[y])&&(T[y].$parentIsCreate=T.$op==="create",T[y][Symbol.for("grandChildOfCreate")]=T.$parentIsCreate||T[Symbol.for("grandChildOfCreate")],T[y].$objectPath=u(T,y)));})),s=p(e),m=(B=>{let b=(T,A)=>{let F=[];T.filter(O=>O).forEach(O=>{let N=Object.keys(O).filter(D=>!D.startsWith("$")).length;if(Array.isArray(O.$id)&&N>0){let D=O.$id.map(z=>({...O,$id:z}));F=[...F,...D];}else F.push({...O});});let w=[],Q=[],R=F.filter(O=>{let D=["delete","update","unlink"].includes(O.$op||""),z=i(O,!0).length;if((!O.$id||Array.isArray(O.$id)&&z>0||O.$filter)&&D)return !0;Q.push({...O});});return R.length>0?R.forEach(O=>{let D=(j=>{let $t=(()=>{let W={};for(let x in j){let nt=S(t,j);!x.startsWith("$")&&nt.dataFields?.find(dt=>dt.path===x)&&(W[x]=j[x]);}return W})(),mt=Object.keys(j),et=mt.filter(W=>!W.startsWith("$")),St=[],bt=(W,x)=>{if(W===et.length){let dt={...x};mt.forEach(V=>{V.startsWith("$")&&(dt[V]=j[V]);}),St.push(dt);return}let nt={...x,[et[W]]:j[et[W]],...Z(x),...$t};bt(W+1,nt),bt(W+1,x);};return bt(0,{...Z(j)}),St})(O).filter(j=>!(j.$op==="update"&&Object.keys(j).filter(ot=>!ot.startsWith("$")).length===0)),z=[],H=r(O.$objectPath),tt=a[H]?a[H].$ids:[],q=D.map((j,ot)=>{let $t=S(t,j),et=Object.keys(j).filter(x=>!x.includes("$")&&!$t.dataFields?.some(nt=>nt.path===x)).map(x=>(Array.isArray(j[x])?j[x].length>1?j[x].filter(V=>!V.$id||Array.isArray(V.$id)||V.$filter):j[x]:[j[x]]).map(V=>{let qt=r(V.$objectPath);return {idsToKey:(Dt=>{let ie=[],gt=Dt.split("."),Bn=gt.slice(0,gt.length-1).join("."),Fn=gt.slice(gt.length-1,gt.length)[0].split("___")[1];for(let xt in a)if(xt.startsWith(Bn)&&xt.endsWith(Fn)){let jt=xt.split("."),En=jt.slice(jt.length-1,jt.length)[0].split("___")[0];ie.push(En);}return ie})(qt),key:x,multiple:V}})).filter(x=>x!==void 0),W=(x=>{let nt=x.map(V=>V.map(st=>st.idsToKey));return (V=>V.length>0?V.reduce((st,yt)=>st.concat(yt),[]).reduce((st,yt)=>st?yt.filter(Dt=>st.includes(Dt)):yt):[])(nt)})(et).filter(x=>!z.includes(x));if(z=[...z,...W],tt=tt.filter(x=>!W.includes(x)),ot===D.length-1&&tt.length>0)return {...j,$id:tt,$bzId:`T1_${v4()}`,...Z(j)};if(W.length>0)return {...j,$id:W,$bzId:`T2_${v4()}`,...Z(j)}}).filter(j=>j!==void 0),gn=(()=>{if(q.length===0&&!A?.$id)return R;if(q.length===0&&A?.$id){let j=Array.isArray(A.$id)?A.$id:[A.$id],ot=[];return j.forEach($t=>{let mt=r({...O.$objectPath,ids:$t}),et=a[mt];et&&ot.push({...O,$id:et.$ids,...Z(O),$bzId:`T_${v4()}`});}),ot}else return q.filter(j=>j!==void 0)})();w=[...Q,...gn].map(L);}):w=F.map(L),w},L=T=>{let A={...T,$bzId:T.$tempId??`T3_${v4()}`,...Z(T)},F=S(t,T);return Object.keys(T).filter(w=>!w.includes("$")&&!F.dataFields?.some(Q=>Q.path===w)).forEach(w=>{let Q=Array.isArray(T[w])?T[w]:[T[w]],R=b(Q,T);A[w]=R.length>0?R:void 0;}),A},y=[];return B.forEach(T=>{y=[...y,...b([T])];}),y.map(T=>L(T))})(Array.isArray(s)?s:[s]),E=B=>B.map(b=>{let L=i(b,!0),y={...b};return L.forEach(I=>{let T=Array.isArray(b[I])?b[I]:[b[I]],A=[],F=[],w=[],Q={},R=Wt(t,b,I);T.filter(q=>q).forEach(q=>{q.$op==="replace"&&q.$id?(Q=q,Array.isArray(q.$id)?F=[...F,...q.$id]:F.push(q.$id)):q.$op==="create"&&R==="ONE"&&q.id?(Q=q,Array.isArray(q.id)?w=[...F,...q.id]:w.push(q.id)):A.push(q);});let O=r(Q.$objectPath),D=d(O).map(q=>a[q]),z=[];D.filter(q=>q!=null).forEach(q=>{z=[...z,...q.$ids];});let H=z.filter(q=>!F.includes(q)),Ot=F.filter(q=>!z.includes(q)),tt=Z(Q);H.length>0&&A.push({...Q,$op:"unlink",$id:H,$bzId:`T4_${v4()}`,id:void 0,...tt}),Ot.length>0&&Ot.forEach(q=>{A.push({...Q,$op:"link",$id:q,$bzId:`T5_${v4()}`,...tt});}),w.length>0&&w.forEach(q=>{A.push({...Q,$op:"create",id:q,$bzId:`T6_${v4()}`,...tt});}),y[I]=E(A);}),y}),$=p(E(p(m)));return (B=>produce(B,b=>traverse(b,L=>{let{key:y,value:I,parent:T}=L;y&&T&&!y?.includes("$")&&(Array.isArray(I)||isObject(I))&&!Array.isArray(T)&&(Array.isArray(I)?I:[I]).forEach(F=>{let w=a[r(F.$objectPath)],Q=(N,D)=>N.every(z=>D.includes(z)),R=F.$id?Array.isArray(F.$id)?Q(F.$id,w?w.$ids:[]):w?.$ids.includes(F.$id):w,O=Wt(t,T,F.$objectPath.key);if(F.$op==="link"&&R&&O==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${r(F.$objectPath)}" because it is already occupied.`);if(F.$op)switch(F.$op){case"delete":if(!R&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${F.$id}" because it is not linked to $id:"${T.$id}"`);break;case"update":if(!R&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${F.$id}" because it is not linked to $id:"${T.$id}"`);break;case"unlink":if(!R&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${F.$id}" because it is not linked to $id:"${T.$id}"`);break;case"link":if(R)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${F.$id}" because it is already linked to $id:"${T.$id}"`);break;}});})))($),(B=>produce(B,b=>traverse(b,L=>{let{value:y,meta:I}=L;isObject(y)&&(y[Symbol.for("path")]=I.nodePath,delete y.$objectPath,delete y.$parentIsCreate);})))($)};function _(e){return {enumerable:!0,value:e}}function Ge(e){return {enumerable:!0,writable:!0,value:e}}var ht={},yr=()=>!0,Xe=()=>({}),en=e=>e,gr=(e,t,n,o)=>e.apply(n,o)&&t.apply(n,o),Br=(e,t,n,[o,i])=>t.call(n,e.call(n,o,i),i),it=(e,t)=>Object.freeze(Object.create(e,t));function tn(e,t,n){return e.reduce((o,i)=>function(...c){return n(o,i,this,c)},t)}function nn(e){return it(this,{fn:_(e)})}var rn={},G=nn.bind(rn);var on={},sn=nn.bind(on);function Rt(e,t){return t.filter(n=>e.isPrototypeOf(n))}function an(e,t,...n){let o=tn(Rt(on,n).map(c=>c.fn),yr,gr),i=tn(Rt(rn,n).map(c=>c.fn),en,Br);return it(this,{from:_(e),to:_(t),guards:_(o),reducers:_(i)})}var ln={},cn={},X=an.bind(ln);an.bind(cn,null);function Fr(e,t,n){return Xt(t,e,n,this.immediates)||e}function dn(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 Er={enter:en};function pn(...e){let t=Rt(ln,e),n=Rt(cn,e),o={final:_(e.length===0),transitions:_(dn(t))};return n.length&&(o.immediates=_(n),o.enter=_(Fr)),it(Er,o)}var wr={enter(e,t,n){let o=this.fn.call(t,t.context,n);return Gt.isPrototypeOf(o)?it(un,{machine:_(o),transitions:_(this.transitions)}).enter(e,t,n):(o.then(i=>t.send({type:"done",data:i})).catch(i=>t.send({type:"error",error:i})),e)}},un={enter(e,t,n){if(t.child=te(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,Xt(t,e,{type:"done",data:o},this.transitions.get("done"))}return e}};function ct(e,...t){let n=_(dn(t));return Gt.isPrototypeOf(e)?it(un,{machine:_(e),transitions:n}):it(wr,{fn:_(e),transitions:n})}var Gt={get state(){return {name:this.current,value:this.states[this.current]}}};function hn(e,t,n=Xe){return typeof e!="string"&&(n=t||Xe,t=e,e=Object.keys(t)[0]),ht._create&&ht._create(e,t),it(Gt,{context:_(n),current:_(e),states:_(t)})}function Xt(e,t,n,o){let{context:i}=e;for(let{to:c,guards:l,reducers:g}of o)if(l(i,n)){e.context=g.call(e,i,n);let M=t.original||t,u=it(M,{current:_(c),original:{value:M}});ht._onEnter&&ht._onEnter(t,c,e.context,i,n);let r=u.state.value;return e.machine=u,e.onChange(e),r.enter(u,e,n)}}function br(e,t){let n=t.type||t,{machine:o}=e,{value:i,name:c}=o.state;return i.transitions.has(n)?Xt(e,o,t,i.transitions.get(n))||o:(ht._send&&ht._send(n,c),o)}var Tr={send(e){br(this,e);}};function te(e,t,n,o){let i=Object.create(Tr,{machine:Ge(e),context:Ge(e.context(n,o)),onChange:_(t)});return i.send=i.send.bind(i),i.machine=i.machine.state.value.enter(i.machine,i,o),i}var fn=pn,ee=(e,t)=>t.data?{...e,bql:{...e.bql,current:t.data}}:e,Mr=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),kr=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),Lr=(e,t)=>({...e,typeDB:{...e.typeDB,tqlMutation:t.data}}),Qr=(e,t)=>({...e,typeDB:{...e.typeDB,tqlRes:t.data}}),Ir=async e=>Object.keys(e.bql.current).length?Zt(e.bql.current,e.schema):Zt(e.bql.raw,e.schema),Pr=async e=>Ye(e.bql.current,e.schema,e.config,e.handles),Ar=async e=>Je(e.bql.current,e.schema),Cr=async e=>Ze(e.bql.things,e.bql.edges,e.schema),Rr=async e=>We(e.typeDB.tqlMutation,e.handles,e.config),Or=async e=>Ve(e.typeDB.tqlRes,e.bql.things,e.bql.edges,e.config),Sr=()=>!0,ft=X("error","error",G((e,t)=>({...e,error:t.error}))),qr=hn("enrich",{enrich:ct(Ir,X("done","preQuery",sn(Sr),G(ee)),X("done","parseBQL",G(ee)),ft),preQuery:ct(Pr,X("done","parseBQL",G(ee)),ft),parseBQL:ct(Ar,X("done","buildMutation",G(kr)),ft),buildMutation:ct(Cr,X("done","runMutation",G(Lr)),ft),runMutation:ct(Rr,X("done","parseMutation",G(Qr)),ft),parseMutation:ct(Or,X("done","success",G(Mr)),ft),success:fn(),error:fn()},e=>e),Dr=async e=>new Promise((t,n)=>{te(qr,o=>{o.machine.state.name==="success"&&t(o.context),o.machine.state.name==="error"&&n(o.context);},e);}),$n=async(e,t,n,o)=>Dr({bql:{raw:e,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:t,config:n,handles:o,depthLevel:0,error:null});enableMapSet();var re=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[i,c]=await tryit(TypeDB.coreDriver)(o.url);if(i){let l=`[BORM:${o.provider}:${o.dbName}:core] ${i.message??"Can't create TypeDB Client"}`;throw new Error(l)}try{let l=await c.session(o.dbName,SessionType.DATA);t.typeDB.set(o.id,{client:c,session:l});}catch(l){let g=`[BORM:${o.provider}:${o.dbName}:session] ${(l.messageTemplate?._messageBody()||l.message)??"Can't create TypeDB Session"}`;throw new Error(g)}}if(o.provider==="typeDBCluster"&&o.dbName){let[i,c]=await tryit(TypeDB.cloudDriver)(o.addresses,o.credentials);if(i){let l=`[BORM:${o.provider}:${o.dbName}:core] ${i.message??"Can't create TypeDB Cluster Client"}`;throw new Error(l)}try{let l=await c.session(o.dbName,SessionType.DATA);t.typeDB.set(o.id,{client:c,session:l});}catch(l){let g=`[BORM:${o.provider}:${o.dbName}:session] ${(l.messageTemplate?._messageBody()||l.message)??"Can't create TypeDB Session"}`;throw new Error(g)}}}));let n=pe(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(),se(this.config,this.schema,this.dbHandles));query=async(t,n)=>{await this.#t();let o={...this.config,query:{...Nt.query,...this.config.query,...n}};return Lt(t,o,this.schema,this.dbHandles)};mutate=async(t,n)=>{await this.#t();let o={...this.config,mutation:{...Nt.mutation,...this.config.mutation,...n}},[i,c]=await tryit($n)(t,this.schema,o,this.dbHandles);if(i)throw console.error(i.error.stack.split(`
61
60
  `).slice(0,4).join(`
62
- `)),new Error(a.error.message);return d.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:n})=>{n.isOpen()&&await n.close(),await t.close();});}},Es=Zt;//! Todo: delete when this works with the new $thing and $thingType fields
61
+ `)),new Error(i.error.message);return c.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:n})=>{n.isOpen()&&await n.close(),await t.close();});}},Hs=re;//! Todo: delete when this works with the new $thing and $thingType fields
63
62
  //! Todo: Sandbox the function in computeFunction()
64
63
  //! reads all the insertions and gets the first match. This means each id must be unique
65
64
  //!old
66
65
 
67
- export { Es as default };
66
+ export { Hs as default };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blitznocode/blitz-orm",
3
- "version": "0.9.6",
3
+ "version": "0.9.7",
4
4
  "main": "dist/index.cjs",
5
5
  "module": "./dist/index.mjs",
6
6
  "types": "dist/index.d.ts",
@@ -32,7 +32,6 @@
32
32
  "immer": "9.0.21",
33
33
  "object-traversal": "^1.0.1",
34
34
  "radash": "^11.0.0",
35
- "robot3": "^0.4.1",
36
35
  "typedb-driver": "2.26.6-rc1",
37
36
  "uuid": "^9.0.1"
38
37
  },