@blitznocode/blitz-orm 0.10.13 → 0.10.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { TypeDBDriver, TypeDBSession } from 'typedb-driver';
2
- import { Surreal } from 'surrealdb.node';
2
+ import { Surreal } from 'surrealdb.js';
3
3
 
4
4
  interface TypeDBProvider extends CommonProvider {
5
5
  provider: 'typeDB';
@@ -178,6 +178,7 @@ type LinkField = BormField & {
178
178
  relation: string;
179
179
  cardinality: DiscreteCardinality;
180
180
  plays: string;
181
+ isVirtual?: boolean;
181
182
  } & ({
182
183
  target: 'role';
183
184
  filter?: Filter | Filter[];
@@ -188,6 +189,21 @@ type LinkedFieldWithThing = LinkField & {
188
189
  thing: string;
189
190
  thingType: ThingType;
190
191
  };
192
+ type MultiField = BormField & {
193
+ contentType: 'FLEX';
194
+ default?: {
195
+ type: 'fn';
196
+ fn: (currentNode: BQLMutationBlock) => unknown;
197
+ } | {
198
+ type: 'value';
199
+ value: unknown;
200
+ };
201
+ validations?: {
202
+ enum?: unknown[];
203
+ unique?: boolean;
204
+ fn?: (value: unknown) => boolean;
205
+ };
206
+ };
191
207
  type StringField = BormField & {
192
208
  contentType: 'ID' | 'COLOR' | 'DATE' | 'FILE' | 'EMAIL' | 'PHONE' | 'URL' | 'PASSWORD' | 'LANGUAGE_TEXT' | 'RICH_TEXT' | 'TEXT' | 'JSON';
193
209
  default?: {
@@ -246,7 +262,7 @@ type BooleanField = BormField & {
246
262
  fn?: (value: boolean) => boolean;
247
263
  };
248
264
  };
249
- type AllDataField = StringField | NumberField | DateField | BooleanField;
265
+ type AllDataField = StringField | NumberField | DateField | BooleanField | MultiField;
250
266
  type DataField = BormField & {
251
267
  cardinality?: Cardinality;
252
268
  shared?: boolean;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { TypeDBDriver, TypeDBSession } from 'typedb-driver';
2
- import { Surreal } from 'surrealdb.node';
2
+ import { Surreal } from 'surrealdb.js';
3
3
 
4
4
  interface TypeDBProvider extends CommonProvider {
5
5
  provider: 'typeDB';
@@ -178,6 +178,7 @@ type LinkField = BormField & {
178
178
  relation: string;
179
179
  cardinality: DiscreteCardinality;
180
180
  plays: string;
181
+ isVirtual?: boolean;
181
182
  } & ({
182
183
  target: 'role';
183
184
  filter?: Filter | Filter[];
@@ -188,6 +189,21 @@ type LinkedFieldWithThing = LinkField & {
188
189
  thing: string;
189
190
  thingType: ThingType;
190
191
  };
192
+ type MultiField = BormField & {
193
+ contentType: 'FLEX';
194
+ default?: {
195
+ type: 'fn';
196
+ fn: (currentNode: BQLMutationBlock) => unknown;
197
+ } | {
198
+ type: 'value';
199
+ value: unknown;
200
+ };
201
+ validations?: {
202
+ enum?: unknown[];
203
+ unique?: boolean;
204
+ fn?: (value: unknown) => boolean;
205
+ };
206
+ };
191
207
  type StringField = BormField & {
192
208
  contentType: 'ID' | 'COLOR' | 'DATE' | 'FILE' | 'EMAIL' | 'PHONE' | 'URL' | 'PASSWORD' | 'LANGUAGE_TEXT' | 'RICH_TEXT' | 'TEXT' | 'JSON';
193
209
  default?: {
@@ -246,7 +262,7 @@ type BooleanField = BormField & {
246
262
  fn?: (value: boolean) => boolean;
247
263
  };
248
264
  };
249
- type AllDataField = StringField | NumberField | DateField | BooleanField;
265
+ type AllDataField = StringField | NumberField | DateField | BooleanField | MultiField;
250
266
  type DataField = BormField & {
251
267
  cardinality?: Cardinality;
252
268
  shared?: boolean;
package/dist/index.js CHANGED
@@ -2,14 +2,15 @@
2
2
 
3
3
  var radash = require('radash');
4
4
  var typedbDriver = require('typedb-driver');
5
- var surrealdb_node = require('surrealdb.node');
5
+ var surrealdb_js = require('surrealdb.js');
6
6
  var immer = require('immer');
7
7
  var objectTraversal = require('object-traversal');
8
8
  var uuid = require('uuid');
9
9
  var types = require('util/types');
10
10
  require('acorn');
11
+ var nanoid = require('nanoid');
11
12
 
12
- var it={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var Fn=e=>{let t=[],r=new Map;return e.forEach(i=>{let{dbPath:o,contentType:n}=i,l=`${o}-${n}`;r.has(l)||(r.set(l,!0),t.push(i));}),t},_t=async(e,t,r)=>{let o=(()=>{let y="",m=[];y+=`
13
+ var it={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var wn=e=>{let t=[],r=new Map;return e.forEach(i=>{let{dbPath:o,contentType:n}=i,l=`${o}-${n}`;r.has(l)||(r.set(l,!0),t.push(i));}),t},Vt=async(e,t,r)=>{let o=(()=>{let y="",m=[];y+=`
13
14
  `,Object.keys(t.entities).forEach(g=>{let L=t.entities[g],{idFields:D,dataFields:A,linkFields:C,name:j}=L,N=[],se=[],K=[];if("extends"in L){let E=t.entities[L.extends];E.dataFields&&E.dataFields.forEach(Q=>{N.push(Q.dbPath);}),E.linkFields&&E.linkFields.forEach(Q=>{se.push(Q.path);}),E.idFields&&E.idFields.forEach(Q=>{K.push(Q);});}y+=`${j} sub ${"extends"in L?L.extends:"entity"},
14
15
  `;let R=[];if(D&&D.length>0){let E=new Set(D),b=Array.from(E).map(F=>`${F}`).join(", ");K.includes(b)||(y+=` owns ${b} @key,
15
16
  `,R.push(b));}if(A&&A.length>0&&A.forEach(E=>{!N.includes(E.dbPath)&&!R.includes(E.dbPath)&&(y+=` owns ${E.dbPath},
@@ -25,7 +26,7 @@ var it={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},muta
25
26
  `),y+=`
26
27
  `;});let B=`define
27
28
 
28
- `;return Fn(m).forEach(g=>{if(B+=`${g.dbPath} sub attribute,
29
+ `;return wn(m).forEach(g=>{if(B+=`${g.dbPath} sub attribute,
29
30
  `,g.contentType==="TEXT"||g.contentType==="ID"||g.contentType==="JSON")B+=` value string;
30
31
  `;else if(g.contentType==="EMAIL")B+=` value string,
31
32
  `,B+=` regex '^(?=.{1,64}@)[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*@[^-][A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$';
@@ -34,21 +35,25 @@ var it={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},muta
34
35
  `;else if(g.contentType==="NUMBER")B+=` value long;
35
36
  `;else throw new Error(`Conversion of borm schema to TypeDB schema for data type "${g.contentType}" is not implemented`)}),`${B}
36
37
 
37
- ${y}`})(),n=e.dbConnectors[0].id,l=r.typeDB.get(n)?.session,s=r.typeDB.get(n)?.client;if(!l){console.log("Session Status: ","NO SESSION");return}await l.close();let[{dbName:h}]=e.dbConnectors;await(await s.databases.get(h)).delete(),await s.databases.create(h);let d=await s.session(e.dbConnectors[0].dbName,typedbDriver.SessionType.SCHEMA),c=await d.transaction(typedbDriver.TransactionType.WRITE);await c.query.define(o),await c.commit(),await c.close();let a=await d.transaction(typedbDriver.TransactionType.READ);(await(await a.query.match("match $a sub thing;")).collect()).forEach(async y=>{y.get("a");}),await a.close();};var ae=Symbol.for("queryPath"),We=Symbol.for("stepPrint"),Qe=Symbol.for("edgeType"),Be=Symbol.for("edgeSchema"),De=Symbol.for("dbNode"),ot=Symbol.for("isTransformed"),de=Symbol.for("fieldSchema"),$e=Symbol.for("sharedMetadata"),Te=Symbol.for("suqlMetadata");var Vt={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var Ht=({linkField:e,originalRelation:t,withExtensionsSchema:r})=>{let i=r.relations[e.relation].subTypes||[],o=[e.relation,...i],n=`<-\`${t}_${e.plays}\`<-(\`${o.join("`,`")}\`)`;if(e.target==="relation")return n;if(e.target==="role"){let[l]=e.oppositeLinkFieldsPlayedBy,s=r.entities[l.thing]?.subTypes||r.relations[l.thing]?.subTypes||[],h=[l.thing,...s],p=`->\`${t}_${l.plays}\`->(\`${h.join("`,`")}\`)`;return `${n}${p}`}else throw new Error("Unsupported linkField target")};var Jt=(e,t,r)=>r?t:`${e}\xB7${t}`;var vt=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))))[0],xe=(e,t)=>Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))),Yt=(e,t)=>{let r=[],i=immer.produce(e,n=>objectTraversal.traverse(n,({key:l,value:s,meta:h})=>{if(h.depth===2&&(l&&(s.dataFields=s.dataFields?.map(p=>({...p,cardinality:p.cardinality||"ONE",dbPath:Jt(l,p.path,p.shared)}))),s.extends)){if(!s.defaultDBConnector.as)throw new Error(`[Schema] ${l} is extending a thing but missing the "as" property in its defaultDBConnector`);let p=n.entities[s.extends]||n.relations[s.extends],d=[s.extends,...p.allExtends||[]];if(s.allExtends=d,d.forEach(c=>{if(n.entities[c])n.entities[c].subTypes=[l,...n.entities[c].subTypes||[]];else if(n.relations[c])n.relations[c].subTypes=[l,...n.relations[c].subTypes||[]];else throw new Error(`[Schema] ${l} is extending a thing that does not exist in the schema: ${c}`)}),s.idFields=p.idFields?Array.from(new Set((s.idFields||[]).concat(p.idFields))):s.idFields,s.dataFields=p.dataFields?(s.dataFields||[]).concat(p.dataFields.map(c=>{let a=s.extends,f=e.entities[a]||e.relations[a];for(;!f.dataFields?.find(u=>u.path===c.path);)a="extends"in f?f.extends:void 0,f=e.entities[a]||e.relations[a];return {...c,dbPath:Jt(a,c.path,c.shared),[$e]:{inheritanceOrigin:c[$e]?.inheritanceOrigin||s.extends}}})):s.dataFields,"roles"in p){let c=s,a=p;if(a.roles){let f=radash.mapEntries(a.roles,(u,$)=>[u,{...$,[$e]:{inheritanceOrigin:$[$e]?.inheritanceOrigin||s.extends}}]);c.roles={...c.roles||{},...f};}}s.linkFields=p.linkFields?(s.linkFields||[]).concat(p.linkFields.map(c=>({...c,[$e]:{inheritanceOrigin:c[$e]?.inheritanceOrigin||s.extends}}))):s.linkFields,p?.hooks?.pre&&(s.hooks=s.hooks||{},s.hooks.pre=s.hooks.pre||[],s.hooks.pre=[...p?.hooks?.pre||[],...s?.hooks?.pre||[]]);}},{traversalType:"breadth-first"}));return objectTraversal.traverse(e,({key:n,value:l,meta:s})=>{if(n==="linkFields"){let p=(()=>{if(!s.nodePath)throw new Error("No path");let[c,a]=s.nodePath.split(".");return {thing:a,thingType:c==="entities"?"entity":c==="relations"?"relation":""}})(),d=Array.isArray(l)?l.map(c=>({...c,...p})):[{...l,...p}];r.push(...d);}}),immer.produce(i,n=>objectTraversal.traverse(n,({value:l,key:s,meta:h})=>{if(h.depth===2&&l.idFields&&!l.id){l.name=s;let p=()=>{if(h.nodePath?.split(".")[0]==="entities")return "entity";if(h.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};l.thingType=p();let d=Object.keys(t).find(c=>t[c]?.get(l.defaultDBConnector.id));if(l.db=d,l.dbContext=Vt[d],l.computedFields=[],l.virtualFields=[],l.requiredFields=[],l.enumFields=[],l.fnValidatedFields=[],"roles"in l&&Object.entries(l.roles).forEach(([a,f])=>{f.fieldType="roleField";let u=r.filter(w=>w.relation===s&&w.plays===a)||[];f.playedBy=u,f.name=a;let $=[...new Set(u.map(w=>w.thing))];f.$things=$;let y=f[$e]?.inheritanceOrigin||l.name;if($.length>1)throw new Error(`Not supported yet: Role ${a} in ${l.name} is played by multiple things: ${$.join(", ")}`);let m=$.flatMap(w=>{let L=G(e,w)?.subTypes||[];return [w,...L]}),B=`->\`${y}_${a}\`->(\`${m.join("`,`")}\`)`;f[Te]={queryPath:B};}),"linkFields"in l&&l.linkFields){let c=l;c.linkFields?.forEach(a=>{a.fieldType="linkField";let f=i.relations[a.relation];if(f.roles?.[a.plays]===void 0)throw new Error(`The role ${a.plays} is not defined in the relation ${a.relation} (linkField: ${a.path})`);if(a.target==="relation"&&(a.$things=[a.relation],a.oppositeLinkFieldsPlayedBy=[{plays:a.path,thing:a.relation,thingType:"relation"}]),a.target==="role"){let y=r.filter(m=>m.relation===a.relation&&m.plays!==a.plays)||[];if(a.oppositeLinkFieldsPlayedBy=y,a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter(m=>m.target==="role"),a.$things=a.oppositeLinkFieldsPlayedBy.map(m=>m.thing),a.oppositeLinkFieldsPlayedBy.length>1)throw new Error(`Not supported: LinkField ${a.path} in ${c.name} has multiple candidates ${a.oppositeLinkFieldsPlayedBy.map(m=>m.thing).join(",")} and this is not yet supported. Please target a single one using targetRoles with a single role`)}let u=f.roles?.[a.plays][$e]?.inheritanceOrigin??a.relation,$=Ht({linkField:a,originalRelation:u,withExtensionsSchema:i});a[Te]={queryPath:$};});}}if(typeof l=="object"&&"playedBy"in l){let p=[...new Set(l.playedBy.map(d=>d.thing))];if(p.length>1)throw new Error(`[Schema] roleFields can be only played by one thing. Role: ${s}, path:${h.nodePath}, played by: ${p.join(", ")}`);if(l.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${s}, path:${h.nodePath}`)}if(h.depth===4){let[p,d]=h.nodePath?.split(".")||[],c=n[p][d];!radash.isArray(l)&&typeof l=="object"&&(l.validations&&(l.validations.required&&c.requiredFields.push(l.path),l.validations.enum&&c.enumFields.push(l.path),l.validations.fn&&c.fnValidatedFields.push(l.path)),l.default?l.isVirtual?c.virtualFields.push(l.path):c.computedFields.push(l.path):l.isVirtual&&c.virtualFields.push(l.path));}}))},G=(e,t)=>{if(t in e.entities)return e.entities[t];if(t in e.relations)return e.relations[t];throw new Error(`${t} is not defined in the schema`)},x=(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)}`)},_e=(e,t)=>{let r=e.dataFields?.find(n=>n.path===t);if(r)return ["dataField",r];let i=e.linkFields?.find(n=>n.path===t);if(i)return ["linkField",i];let o="roles"in e?e.roles[t]:void 0;if(o)return ["roleField",o];throw new Error(`Field ${t} not found in schema, Defined in $filter`)},Ve=(e,t)=>{let r=x(e,t);if(r?.idFields?.length&&r?.idFields?.length>1)throw new Error(`Multiple ids not yet enabled / composite ids: ${r?.idFields}`);let[i]=r.idFields;return i},Gt=(e,t)=>{let r=e.$thing||e.$entity||e.$relation;if(!r)throw new Error("[Internal] No thing found");if(e.$entity)return "entity";if(e.$relation)return "relation";if(t.entities[r])return "entity";if(t.relations[r])return "relation";throw new Error("No thing found")},lt=(e,t,r)=>{let i=x(e,t),o=i.linkFields?.find(s=>s.path===r);if(o)return o;let n=i.dataFields?.find(s=>s.path===r);if(n)return n;let l="roles"in i?i.roles?.[r]:void 0;if(l)return l;throw new Error(`Field ${r} not found in schema`)},ct=(e,t,r)=>lt(e,t,r)?.cardinality,ue=(e,t)=>{let r=e.dataFields?.map(u=>u.path)||[],i=e.linkFields?.map(u=>u.path)||[],o="roles"in e?radash.listify(e.roles,u=>u):[],n=[...r||[],...i||[],...o||[]],s=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...n];if(!t)return {fields:n,dataFields:r,roleFields:o,linkFields:i};let h=t.$fields?t.$fields.map(u=>{if(typeof u=="string"){if(u.startsWith("$")||u.startsWith("%"))return;if(!n.includes(u))throw new Error(`Field ${u} not found in the schema`);return u}if("$path"in u&&typeof u.$path=="string")return u.$path;throw new Error("[Wrong format] Wrongly structured query")}):radash.listify(t,u=>{if(!(u.startsWith("$")||u.startsWith("%"))){if(!n.includes(u))throw new Error(`[Schema] Field ${u} not found in the schema`);return u}}).filter(u=>u!==void 0),p=t.$filter?radash.listify(t.$filter,u=>u.toString().startsWith("$")?void 0:u.toString()).filter(u=>u&&r?.includes(u)):[],d=t.$filter?radash.listify(t.$filter,u=>u.toString().startsWith("$")?void 0:u.toString()).filter(u=>u&&[...o||[],...i||[]].includes(u)):[],c=[...h,...p].filter(u=>!u?.startsWith("%")).filter(u=>!s.includes(u)).filter(u=>u),a=t.$filter?xe(t.$filter,(u,$)=>p.includes(u)):{},f=t.$filter?xe(t.$filter,(u,$)=>d.includes(u)):{};return {fields:n,dataFields:r,roleFields:o,linkFields:i,usedFields:h,usedLinkFields:i.filter(u=>h.includes(u)),usedRoleFields:o.filter(u=>h.includes(u)),usedDataFields:r.filter(u=>h.includes(u)),unidentifiedFields:c,...p.length?{localFilters:a}:{},...d.length?{nestedFilters:f}:{}}};var Xt=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},er=(e,t,r)=>{let o=(r.nodePath||"").split("."),n=radash.isArray(t)?o.slice(0,-2).join("."):o.slice(0,-1).join(".");return t?objectTraversal.getNodeByPath(e,n):{}},Ee=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var He=e=>radash.isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),pe=e=>{if(Array.isArray(e))return e.map(t=>immer.current(t));if(e&&typeof e=="object"){let t=immer.isDraft(e)?immer.current(e):e,r={};return Object.entries(t).forEach(([i,o])=>{r[i]=immer.isDraft(o)?immer.current(o):o;}),r}else return e},oe=(e,t)=>{if(e===void 0)throw new Error("Value is undefined");return e},M=(e,t)=>{let r="";for(let i=0;i<t;i++)r+=" ";return `${r}${e}`};var Re=(e,t)=>{if(t.fieldType==="linkField"){let r=t.oppositeLinkFieldsPlayedBy;if(r?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!r?.length)throw new Error(`[Internal] Field ${e} should have a player`);return r}else if(t.fieldType==="roleField"){if([...new Set(t.playedBy?.map(r=>r.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 tr=(e,t,r)=>{let i=radash.isArray(e[t])?e[t]:[e[t]];if(!i.every(o=>typeof o=="object"))if(i.every(o=>typeof o=="string")){let o=Re(t,r),[n]=o,l=e.$op==="create"?"link":"replace",s=n.thing,h=n.thingType;if(i.some(p=>p.startsWith("_:")))throw new Error("[Not supported] At least one child of a replace is a tempId");e[t]={$id:e[t],$op:l,$thing:s,$thingType:h,$bzId:`S_${uuid.v4()}`};}else throw new Error(`[Mutation Error] Replace can only be used with a single id or an array of ids. (Field: ${t} Nodes: ${JSON.stringify(i)} Parent: ${JSON.stringify(e,null,2)})`)};var Le=(e,t,r)=>{let i=x(r,t),{usedDataFields:o}=ue(i,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"&&o.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&o.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var Ke=(e,t,r)=>{let i=x(r,t),{usedFields:o}=ue(i,t);return t.$op?(Le(e,t,r),t.$op):t.$id||t.$filter?o.length>0?(Le(e,{...t,$op:"update"},r),"update"):(Le(e,{...t,$op:"link"},r),"link"):t.$tempId?o.length>0?(Le(e,{...t,$op:"create"},r),"create"):(Le(e,{...t,$op:"create"},r),"link"):(Le(e,{...t,$op:"create"},r),"create")};var nr=(e,t)=>{let i=(radash.isArray(e.$root)?e.$root:[e.$root]).map(o=>{let n=Ke(o,o,t);return {...{...o.$thing?{}:{$thing:o.$entity||o.$relation},...o.$thingType?{}:{$thingType:Gt(o,t)},...o.$op?{}:{$op:n},...o.$bzId?{}:{$bzId:`R_${uuid.v4()}`}},...o}});e.$root=radash.isArray(e.$root)?i:i[0];};var Ue=(e,t)=>{let r=t[We];return types.isSet(r)?r.has("clean")?(Reflect.set(t,We,r.add("clean")),!0):!1:(Reflect.set(t,We,new Set(["clean"])),!0)};var ir=(e,t,r)=>{if(Ue("split_ids",e)){let i=(radash.isArray(e[t])?e[t]:[e[t]]).flatMap(o=>{if(radash.isObject(o)&&"$id"in o&&radash.isArray(o.$id)){let n=o;if(x(r,n),!n.$bzId)throw new Error("[Internal Error] No bzId found");return n.$id.map((l,s)=>({...pe(n),$id:l,$bzId:`${n.$bzId}_${s}`,...Ee(n)}))}return o});(i.length>radash.isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=i);}};var sr=(e,t,r,i)=>{let o=(radash.isArray(e[t])?e[t]:[e[t]]).map(n=>{let l=Re(t,r),[s]=l,h=Ke(e,{...n,$thing:s.thing,$thingType:s.thingType},i),p=n.$bzId?n.$bzId:n.$tempId?n.$tempId:`N_${uuid.v4()}`;if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);return {...n,[Be]:r,$thing:s.thing,$thingType:s.thingType,$op:h,$bzId:p}});e[t]=radash.isArray(e[t])?o:o[0];};var An=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,In=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,ar=e=>{let r=e.toString().replace(An,"").trim().split("=>")[0].split("{")[0].replace(In,"").trim(),i=r.substring(r.indexOf("(")+1,r.lastIndexOf(")")).trim();return i?(i.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(n=>n.includes("{")&&n.includes("}")?(n.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(s=>s.split(":")[0].trim().replace(/['"[\]]/g,"")):n.trim()).filter(Boolean):[]};var Ae=({currentThing:e,fieldSchema:t,mandatoryDependencies:r=!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(r){let{fn:o}=t.default,l=ar(o).filter(s=>!(s in e));if(l.length)throw new Error(`Virtual field: Missing arguments ${l.join(", ")}`)}if(!t.default.fn)throw new Error("[Schema] No fn in default field schema");return "default"in t?t.default?.fn(e):void 0};var lr=(e,t,r)=>{let i=e[t];i&&(radash.isArray(i)?i:[i]).forEach(o=>{let n=x(r,o),{unidentifiedFields:l}=ue(n,o),{computedFields:s,virtualFields:h}=n,p=radash.listify(o,(a,f)=>f!==void 0?a:void 0),d=p.filter(a=>h?.includes(a));if(d.length>0)throw new Error(`Virtual fields can't be sent to DB: "${d.join(",")}"`);if(s.filter(a=>!p.includes(a)).forEach(a=>{let f=n.dataFields?.find(B=>B.path===a),$=n.linkFields?.find(B=>B.path===a)?.oppositeLinkFieldsPlayedBy[0],y="roles"in n?vt(n.roles,(B,w)=>B===a):void 0,m=f||$||y;if(!m)throw new Error(`no field Def for ${a}`);if(o.$op==="create"&&!o[a]){let B=Ae({currentThing:o,fieldSchema:m,mandatoryDependencies:!0});o[a]=B;}}),l.length>0)throw new Error(`Unknown fields: [${l.join(",")}] in ${JSON.stringify(o)}`)});};var Je=(e,t)=>{let r=x(t,e).hooks;if(r?.pre){let i=`on${Xt(e.$op)}`;return r.pre.filter(l=>!l.triggers||l.triggers[i]?.()).flatMap(l=>l.actions)}return []};var dr=(e,t,r,i)=>{(radash.isArray(e[t])?e[t]:[e[t]]).forEach(n=>{if("$thing"in n){if(n.$fields)return n;let{requiredFields:l,enumFields:s,fnValidatedFields:h,dataFields:p}=x(r,n);if("$op"in n&&n.$op==="create"&&l.forEach(d=>{if(!(d in n))throw new Error(`[Validations] Required field "${d}" is missing.`)}),("$op"in n&&n.$op==="update"||n.$op==="create")&&s.forEach(d=>{if(d in n){let c=p?.find(a=>a.path===d)?.validations?.enum;if(!c)throw new Error(`[Validations] Enum field "${d}" is missing enum options.`);if(radash.isArray(n[d]))n[d].some(a=>{if(!c.includes(a))throw new Error(`[Validations] Option "${a}" is not a valid option for field "${d}".`)});else if(c&&!c.includes(n[d]))throw new Error(`[Validations] Option "${n[d]}" is not a valid option for field "${d}".`)}}),("$op"in n&&n.$op==="update"||n.$op==="create")&&h.forEach(d=>{if(d in n)try{let c=p?.find(a=>a.path===d)?.validations?.fn;if(!c)throw new Error("Missing validation function.");if(!c(n[d]))throw new Error("Failed validation function.")}catch(c){throw new Error(`[Validations:attribute:${d}] ${c.message}`)}}),radash.isObject(n)&&"$thing"in n){let d=n.$thing,c=n,a=radash.clone(pe(e)),f=radash.clone(pe(c)),u=i.mutation?.context||{},$=radash.clone(pe(n[De]||{}));Je(c,r).forEach(m=>{if(m.type==="validate"){if(m.severity!=="error")return;try{let B=m.fn(f,a,u,$);if(B===!1)throw new Error(`${m.message}.`);if(B!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(B){throw new Error(`[Validations:thing:${d}] ${B.message}`)}}});}}});};var ur=(e,t,r,i)=>{let o=(radash.isArray(e[t])?e[t]:[e[t]]).map(n=>{if(He(n)){if(n.$fields||n[ot])return n;let l=Je(n,r).filter(c=>c.type==="transform"),s=radash.clone(pe(e)),h=radash.clone(pe(n)),p=i.mutation?.context||{},d=radash.clone(pe(n[De]||n.$dbNode));return l.forEach(c=>{let a=c.fn(h,s,p,d||{});Object.keys(a).length!==0&&(n={...h,...a,...Ee(n),[ot]:!0});}),n}});e[t]=radash.isArray(e[t])?o:o[0];};var pr=(e,t,r)=>{let i=Re(t,r),[o]=i;e[t]={$thing:o.thing,$thingType:o.thingType,$op:"unlink",$bzId:`U_${uuid.v4()}`,[Be]:r};};var Ie=e=>{if(Array.isArray(e)){for(let t of e)if(Ie(t))return !0;return !1}if(e.$fields)return !0;for(let t in e){if(t.startsWith("$"))continue;let r=e[t];if(r&&typeof r=="object"&&Ie(e[t]))return !0}return !1};var _n=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(Ue("set_tempId",e))if(e.$tempId?.startsWith("_:")){let r=e.$tempId.substring(2);e.$tempId=r,e.$bzId=r;}else throw new Error('[Wrong format] TempIds must start with "_:"');else throw new Error("[Internal] TempId already modified")},Vn=(e,t)=>{},ft=(e,t,r)=>{let i={$rootWrap:{$root:e}},o=Ie(Array.isArray(e)?e:[e]),n=immer.produce(i,l=>objectTraversal.traverse(l,({value:s,parent:h,key:p,meta:d})=>{if(!(!h||!p)&&radash.isObject(s)){let c=d.nodePath?.split(".")||[];if(!("$root"in s)){if(!("$thing"in s||"$entity"in s||"$relation"in s)){let u=["$fields","$dbNode","$filter"],$=c[c.length-1],y=c[c.length-2];if(p==="$root")throw new Error("Root things must specify $entity or $relation");if(!u.includes($)&&!u.includes(y))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(immer.isDraft(s)?immer.current(s):s)}`)}}let a=s,f=c.includes("$filter");Object.keys(a).forEach(u=>{if(_n(a,u),u!=="$root"&&f||u!=="$root"&&(u.startsWith("$")||u.startsWith("%")))return;let $=u!=="$root"?lt(t,a,u):{fieldType:"rootField"};if(!$)throw new Error(`[Internal] Field ${u} not found in schema`);if("contentType"in $)return Vn();if(["rootField","linkField","roleField"].includes($.fieldType)){if(["linkField","roleField"].includes($.fieldType)&&(a[u]===null?pr(a,u,$):tr(a,u,$)),$.fieldType==="rootField"){if(!("$root"in a))throw new Error(`[Internal] Field ${u} is a rootField but the object is not a root`);nr(a,t);}let y=radash.isArray(a[u])?a[u]:[a[u]],m=c.slice(1).join(".");y.forEach(w=>{if(w){if($?.cardinality==="ONE"&&!w.$op&&!w.$id&&!w.$filter&&!w.$tempId&&a.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${m}.${u}`);if(w.$tempId&&!(w.$op===void 0||w.$op==="link"||w.$op==="create"||w.$op==="update"))throw new Error(`Invalid op ${w.$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($.fieldType)&&sr(a,u,$,t),ir(a,u,t),["rootField","linkField","roleField"].includes($.fieldType)&&lr(a,u,t),(radash.isArray(a[u])?a[u]:[a[u]]).forEach(w=>{let g=x(t,w),{unidentifiedFields:L,usedLinkFields:D,usedFields:A,fields:C}=ue(g,w);if(A.forEach(j=>{if(!C.includes(j))throw new Error(`[Schema] Field ${j} not found in the schema`)}),L.length>0)throw new Error(`Unknown fields: [${L.join(",")}] in ${JSON.stringify(s)}`);if(D.length>1){let j=g.linkFields?.filter(N=>D.includes(N.path));j?.some((N,se)=>j.some((K,R)=>{if(se!==R&&N.target!==K.target&&N.relation===K.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),o||(ur(a,u,t,r),dr(a,u,t,r));}});}}));return radash.isArray(n.$rootWrap.$root),n.$rootWrap.$root};var Ze=async(e,t)=>{let r=t.dbConnectors[0].id,i=e.typeDB?.get(r)?.session,o=e.typeDB?.get(r)?.client;if(!i||!i.isOpen()){if(!o)throw new Error("Client not found");i=await o.session(t.dbConnectors[0].dbName,typedbDriver.SessionType.DATA),e.typeDB?.set(r,{client:o,session:i});}return {client:o,session:i}};var fr=async(e,t,r)=>{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:i}=await Ze(t,r),o=await i.transaction(typedbDriver.TransactionType.WRITE),n=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,l=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;try{n&&await o.query.delete(n);let s=l&&o.query.insert(l),h=s?await s.collect():void 0;return await o.commit(),{insertions:h}}catch(s){throw new Error(`Transaction failed: ${s.message}`)}finally{await o.close();}};var $r=async(e,t,r,i,o)=>{let n=[...t,...r],l=n.map(s=>{let h=e.insertions?.find(c=>c.get(`${s.$bzId}`))?.get(`${s.$bzId}`),p=s.$thing||s.$relation||s.$entity,d=p?G(i,p):void 0;if(s.$op==="create"||s.$op==="update"||s.$op==="link"){if(s.$op!=="update"&&!h&&s.$id)return {$id:s.$id,$error:"Does not exist or it's not linked to the parent"};let c=h?.asThing().iid,a=Object.entries(s).filter(([u,$])=>!u.startsWith("$")).reduce((u,[$,y])=>{if(d?.dataFields?.find(B=>B.path===$)?.contentType==="JSON")return u[$]=JSON.parse(y),u;if(s.$thingType==="relation"){let B=n.filter(w=>w.$id&&w.$bzId===y);return B.length===1?(u[$]=B[0].$id,u):(u[$]=y,u)}return u[$]=y,u},{});if(o.mutation?.noMetadata)return a;let f=s.$tempId&&!s.$tempId.startsWith("_:")?{$tempId:`_:${s.$tempId}`}:{};return {$dbId:c,...s,...a,[s.path]:s.$id,...f}}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(l)};var mr=e=>{let t=({value:r})=>(r&&typeof r=="object"&&"$id"in r&&(Object.keys(r).filter(n=>n.startsWith("$")).forEach(n=>delete r[n]),Object.keys(r).filter(n=>typeof n=="symbol").forEach(n=>delete r[n])),r);return immer.produce(e,r=>objectTraversal.traverse(r,t))};var Er=async(e,t)=>{let r=d=>{let c=[],a=[],f=m=>{if(m.$id)return m.$id;let B=x(t,m),{idFields:w}=B;if(!w)throw new Error(`no idFields: ${JSON.stringify(m)}`);let[g]=w;if(!g)throw new Error(`no idField: ${JSON.stringify(m)}`);let L=B.dataFields?.find(C=>C.path===g),D=Ae({currentThing:m,fieldSchema:L,mandatoryDependencies:!0}),A=m[g]||m.$id||D;if(!A)throw new Error(`no idValue: ${JSON.stringify(m)}`);return A},u=m=>{if(m.$op==="create"){let B=f(m);if(c.find(w=>w.$id===B&&w.$op==="create"))throw new Error(`Duplicate id ${B} for node ${JSON.stringify(m)}`);if(a.find(w=>w.$bzId===m.$bzId))throw new Error(`Duplicate $bzId ${m.$bzId} for node ${JSON.stringify(m)}`);c.push({...m,$id:B});return}m.$tempId&&m.$op==="match"||c.push(m);},$=m=>{if(m.$op==="create"){let B=f(m);if(c.find(w=>w.$id===B),a.find(w=>w.$bzId===m.$bzId))throw new Error(`Duplicate %bzId ${m.$bzIdd} for edge ${JSON.stringify(m)}`);a.push({...m,$id:B});return}a.push(m);};return objectTraversal.traverse(d,({value:m,parent:B,meta:w})=>{if(!radash.isObject(m))return;let g=m;if(g.$thing){if(!g.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(g)}`);if(!g.$bzId)throw new Error("[internal error] BzId not found");let L=x(t,g),{dataFields:D,roleFields:A,linkFields:C,usedFields:j}=ue(L,g),N=()=>{if(g.$op==="create"||g.$op==="delete")return g.$op;if(g.$op==="update"){let R=j.filter(b=>D?.includes(b)),E=j.filter(b=>A?.includes(b)),Q=j.filter(b=>C?.includes(b));if(R.length>0)return "update";if(E.length>0||Q.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(g)}`)}return "match"},se={...g.$id&&{$id:g.$id},...g.$tempId&&{$tempId:g.$tempId},...g.$filter&&{$filter:g.$filter},$thing:g.$thing,...g.$thingType&&{$thingType:g.$thingType},...radash.shake(radash.pick(g,D||[""])),$op:N(),$bzId:g.$bzId};u(se);let K=g[Be];if(K?.fieldType==="linkField"){if((g.$op==="link"||g.$op==="unlink")&&(g.$id||g.$filter)){if(g.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");c.push({...g,$op:"match"});}let R=K.relation===g.$thing,E=R?g.$bzId:`LT_${uuid.v4()}`,b=er(d,B,w).$bzId;if(!b)throw new Error("No parent id found");let F=()=>{if(g.$op==="delete")return R?"match":"delete";if(g.$op==="unlink")return R?"unlink":"delete";if(g.$op==="link"||g.$op==="create")return R?"link":"create";if(g.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},T=x(t,{$thing:K.relation,$thingType:"relation"});if(!Object.keys(T.roles).includes(K.plays))throw new Error(`[Wrong format] Field ${K.plays} is not a role of relation ${K.relation}`);let q={$bzId:E,$thing:K.relation,$thingType:"relation",...g.$tempId?{$tempId:g.$tempId}:{},$op:F(),...R?{}:{[K.path]:g.$bzId},[K.plays]:b,[Be]:K,[Qe]:"linkField"};$(q),(g.$op==="unlink"||F()==="unlink")&&R&&$({$thing:K.relation,$thingType:"relation",$bzId:E,$op:"match",[K.plays]:b,[Be]:K,[Qe]:"linkField"});}if(g.$thingType==="relation"){let R=xe(g,(b,F)=>A.includes(b)),E=radash.mapEntries(R,(b,F)=>radash.isArray(F)?[b,F]:radash.isObject(F)?[b,F.$bzId]:[b,F]),Q=xe(m,(b,F)=>b.startsWith("$")||b.startsWith("Symbol"));if(Object.keys(R).filter(b=>!b.startsWith("$")).length>0){if(g.$op==="create"||g.$op==="delete"){let b=()=>{if(g.$op==="create")return "link";if(g.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},F=x(t,g).roles,T=radash.mapEntries(E,(q,k)=>{let P=F[q]?.cardinality;if(!P)throw new Error(`Role ${q} not found in schema`);if(Array.isArray(k)){if(P==="ONE"){if(k.length>1)throw new Error(`[Error] Role ${q} is not a MANY relation`);return [q,k[0].$bzId||k[0]]}return [q,k.map(J=>J.$bzId||J)]}return [q,k.$bzId||k]}),S={...Q,$thing:g.$thing,$thingType:"relation",$op:b(),...T,$bzId:g.$bzId,[Qe]:"roleField"};$(S);return}if(g.$op==="match"||g.$op==="update"&&Object.keys(R).length>0){let b=0;Object.entries(R).forEach(([F,T])=>{let S=radash.isArray(T)?T:[T],q=k=>k==="create"||k==="replace"?"link":k;S.forEach(k=>{if(!k)return;let P=q(k.$op);if(P==="replace")throw new Error("Not supported yet: replace on roleFields");if(P==="unlink"&&b>0)throw b+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let J={...Q,$thing:g.$thing,$thingType:"relation",$op:P==="delete"?"unlink":P,[F]:k.$bzId,$bzId:g.$bzId,[Qe]:"roleField"};$(J);});});}}}}}),[c,a]},[i,o]=r(e),n=i.reduce((d,c)=>{if(!c.$bzId)return [...d,c];let a=d.findIndex(f=>f.$bzId===c.$bzId);if(a===-1)return [...d,c];if(d[a].$op==="create"&&c.$op==="match")return d;if(d[a].$op==="match"&&(c.$op==="create"||c.$op==="match"))return [...d.slice(0,a),c,...d.slice(a+1)];throw new Error(`[Wrong format] Wrong operation combination for $tempId "${c.$tempId}". Existing: ${d[a].$op}. Current: ${c.$op}`)},[]),l=o.reduce((d,c)=>{let a=d.find(f=>(f.$id&&f.$id===c.$id||f.$bzId&&f.$bzId===c.$bzId)&&f.$thing===c.$thing&&f.$op===c.$op);if(a){let f={...a};return Object.keys(c).forEach($=>{if(typeof $=="symbol"||$.startsWith("$"))return;let y=a[$],m=c[$];Array.isArray(y)&&Array.isArray(m)?f[$]=Array.from(new Set([...y,...m])):!Array.isArray(y)&&Array.isArray(m)?y!==void 0?f[$]=Array.from(new Set([y,...m])):f[$]=m:Array.isArray(y)&&!Array.isArray(m)?m!==void 0&&(f[$]=Array.from(new Set([...y,m]))):y!==null&&m!==null&&y!==void 0&&m!==void 0?f[$]=Array.from(new Set([y,m])):y==null&&(f[$]=m);}),[...d.filter($=>!(($.$id&&$.$id===c.$id||$.$bzId&&$.$bzId===c.$bzId)&&$.$thing===c.$thing&&$.$op===c.$op)),f]}return [...d,c]},[]);n.forEach(d=>{if((d.$thingType==="relation"||"relation"in d)&&l.filter(c=>c.$bzId===d.$bzId||c.$tempId&&c.$tempId===d.$tempId).length===0){if(d.$op==="delete"||d.$op==="match"||d.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(mr(d))}`)}});let s=[...n,...l],h=new Set(s.filter(d=>d.$tempId).map(d=>d.$tempId)),p=Array.from(h).filter(d=>!s.some(c=>c.$tempId===d&&c.$op==="create"));if(p.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${p.join(", ")}`);return {mergedThings:n,mergedEdges:l}};var Fr=async(e,t,r)=>{let i=a=>{let f=a.$op,u=`$${a.$bzId}`,$=x(r,a),{idFields:y,defaultDBConnector:m}=$,B=m?.path||a.$thing,w=a.$id,g=y?.[0],L=radash.listify(a,(R,E)=>{if(R.startsWith("$")||R.startsWith("%")||R===g||E===void 0||E===null)return "";let Q=$.dataFields?.find(T=>T.path===R);if(!Q?.path)return "";let F=Q.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(Q.contentType))return `has ${F} '${E}'`;if(["NUMBER","BOOLEAN"].includes(Q.contentType))return `has ${F} ${E}`;if(Q.contentType==="DATE"){if(Number.isNaN(E.valueOf()))throw new Error("Invalid format, Nan Date");return E instanceof Date?`has ${F} ${E.toISOString().replace("Z","")}`:`has ${F} ${new Date(E).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${Q.contentType}`)}).filter(R=>R),D=`${u}-atts`,A=radash.listify(a,R=>{if(R.startsWith("$")||R.startsWith("%")||R===g)return "";let E=$.dataFields?.find(F=>F.path===R);if(!E?.path)return "";let b=E.dbPath;return `{${D} isa ${b};}`}).filter(R=>R),C=radash.isArray(w)?`like '${w.join("|")}'`:`'${w}'`,j=w?[`has ${g} ${C}`]:[],N=[...j,...L].filter(R=>R).join(","),se=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${u} isa ${[B,...j].filter(R=>R).join(",")};`;if(f==="update"){if(!A.length)throw new Error("update without attributes");return `${u} isa ${[B,...j].filter(R=>R).join(",")}, has ${D};
38
- ${A.join(" or ")};`}return ""},K=()=>f==="update"||f==="link"||f==="match"?`${u} isa ${[B,...j].filter(R=>R).join(",")};`:"";if(He(a))return {op:f,deletionMatch:se(),insertionMatch:K(),insertion:f==="create"?`${u} isa ${[B,N].filter(R=>R).join(",")};`:f==="update"&&L.length?`${u} ${L.join(",")};`:"",deletion:f==="delete"?`${u} isa ${B};`:f==="update"&&A.length?`${u} has ${D};`:""};throw new Error("in attributes")},o=a=>{let f=a.$op,u=x(r,a),$=`$${a.$bzId}`,y=a.$id,m=u.defaultDBConnector?.path||a.$thing,B="roles"in u?radash.listify(u.roles,E=>E):[],w="roles"in u?radash.mapEntries(u.roles,(E,Q)=>[E,Q.dbConnector?.path||E]):{},g=radash.listify(a,(E,Q)=>{if(!B.includes(E))return null;if(!("roles"in u))throw new Error("This should have roles! ");let b=w[E];return Array.isArray(Q)?Q.map(F=>({path:b,id:F})):{path:b,id:Q}}).filter(E=>E).flat(),L=g.map(E=>{if(!E?.path)throw new Error("Object without path");return `${E.path}: $${E.id}`}),D=g.length>0?`( ${L.join(" , ")} )`:"",A=a[Qe];if(!A)throw new Error("[internal error] Symbol edgeType not defined");let C=D?`${$} ${D} ${A==="linkField"||f==="delete"||f==="unlink"?`isa ${m}`:""}`:"",j=`${$} ${A==="linkField"||f==="delete"?`isa ${m}`:""}`,N=()=>C?f==="link"?`${C};`:f==="create"?`${C}, has id '${y}';`:"":"",se=()=>C&&f==="match"?`${C};`:"",K=()=>C?f==="delete"?`${C};`:f==="match"?`${C};`:"":"",R=()=>C?f==="delete"?`${j};`:f==="unlink"?`${$} ${D};`:"":"";return {deletionMatch:K(),insertionMatch:se(),deletion:R(),insertion:N(),op:""}},n=(a,f)=>{let u=f==="edges"?o:i;if(Array.isArray(a))return a.map(g=>{let{preDeletionBatch:L,insertionMatch:D,deletionMatch:A,insertion:C,deletion:j}=u(g);return radash.shake({preDeletionBatch:L,insertionMatch:D,deletionMatch:A,insertion:C,deletion:j},N=>!N)}).filter(g=>g);let{preDeletionBatch:$,insertionMatch:y,deletionMatch:m,insertion:B,deletion:w}=u(a);return radash.shake({preDeletionBatch:$,insertionMatch:y,deletionMatch:m,insertion:B,deletion:w},g=>!g)},l=n(e),s=Array.isArray(l)?l:[l],h=n(t,"edges"),p=Array.isArray(h)?h:[h],d=[...s,...p];return radash.shake({insertionMatches:d.map(a=>a.insertionMatch).join(" ").trim(),deletionMatches:d.map(a=>a.deletionMatch).join(" ").trim(),insertions:d.map(a=>a.insertion).join(" ").trim(),deletions:d.map(a=>a.deletion).join(" ").trim()},a=>!a)};function X(e){return {enumerable:!0,value:e}}function br(e){return {enumerable:!0,writable:!0,value:e}}var Ce={},ri=()=>!0,wr=()=>({}),Qr=e=>e,ni=(e,t,r,i)=>e.apply(r,i)&&t.apply(r,i),ii=(e,t,r,[i,o])=>t.call(r,e.call(r,i,o),o),Fe=(e,t)=>Object.freeze(Object.create(e,t));function Mr(e,t,r){return e.reduce((i,o)=>function(...n){return r(i,o,this,n)},t)}function Tr(e){return Fe(this,{fn:X(e)})}var Lr={},V=Tr.bind(Lr);var Sr={},mt=Tr.bind(Sr);function Ye(e,t){return t.filter(r=>e.isPrototypeOf(r))}function kr(e,t,...r){let i=Mr(Ye(Sr,r).map(n=>n.fn),ri,ni),o=Mr(Ye(Lr,r).map(n=>n.fn),Qr,ii);return Fe(this,{from:X(e),to:X(t),guards:X(i),reducers:X(o)})}var Dr={},Rr={},H=kr.bind(Dr);kr.bind(Rr,null);function oi(e,t,r){return gt(t,e,r,this.immediates)||e}function Ar(e){let t=new Map;for(let r of e)t.has(r.from)||t.set(r.from,[]),t.get(r.from).push(r);return t}var si={enter:Qr};function he(...e){let t=Ye(Dr,e),r=Ye(Rr,e),i={final:X(e.length===0),transitions:X(Ar(t))};return r.length&&(i.immediates=X(r),i.enter=X(oi)),Fe(si,i)}var ai={enter(e,t,r){let i=this.fn.call(t,t.context,r);return yt.isPrototypeOf(i)?Fe(Ir,{machine:X(i),transitions:X(this.transitions)}).enter(e,t,r):(i.then(o=>t.send({type:"done",data:o})).catch(o=>t.send({type:"error",error:o})),e)}},Ir={enter(e,t,r){if(t.child=me(this.machine,i=>{t.onChange(i),t.child==i&&i.machine.state.value.final&&(delete t.child,t.send({type:"done",data:i.context}));},t.context,r),t.child.machine.state.value.final){let i=t.child.context;return delete t.child,gt(t,e,{type:"done",data:i},this.transitions.get("done"))}return e}};function v(e,...t){let r=X(Ar(t));return yt.isPrototypeOf(e)?Fe(Ir,{machine:X(e),transitions:r}):Fe(ai,{fn:X(e),transitions:r})}var yt={get state(){return {name:this.current,value:this.states[this.current]}}};function be(e,t,r=wr){return typeof e!="string"&&(r=t||wr,t=e,e=Object.keys(t)[0]),Ce._create&&Ce._create(e,t),Fe(yt,{context:X(r),current:X(e),states:X(t)})}function gt(e,t,r,i){let{context:o}=e;for(let{to:n,guards:l,reducers:s}of i)if(l(o,r)){e.context=s.call(e,o,r);let h=t.original||t,p=Fe(h,{current:X(n),original:{value:h}});Ce._onEnter&&Ce._onEnter(t,n,e.context,o,r);let d=p.state.value;return e.machine=p,e.onChange(e),d.enter(p,e,r)}}function li(e,t){let r=t.type||t,{machine:i}=e,{value:o,name:n}=i.state;return o.transitions.has(r)?gt(e,i,t,o.transitions.get(r))||i:(Ce._send&&Ce._send(r,n),i)}var ci={send(e){li(this,e);}};function me(e,t,r,i){let o=Object.create(ci,{machine:br(e),context:br(e.context(r,i)),onChange:X(t)});return o.send=o.send.bind(o),o.machine=o.machine.state.value.enter(o.machine,o,i),o}var Pr=(e,t)=>{if(!t)return;let r=hi(t);return ui(r,e.query)},hi=e=>immer.produce(e,t=>objectTraversal.traverse(t,({value:r})=>{radash.isObject(r);})),ui=(e,t)=>immer.produce(e,r=>objectTraversal.traverse(r,({value:i})=>{if(radash.isObject(i)){let o=i;Object.keys(o).forEach(n=>{(o[n]===void 0||o[n]===null||radash.isArray(o[n])&&o[n].length===0)&&(t?.returnNulls?o[n]=null:delete o[n]),o[n]===void 0&&delete o[n];}),Object.getOwnPropertySymbols(o).forEach(n=>{delete o[n];}),t?.noMetadata===!0&&Object.keys(o).forEach(n=>{n.startsWith("$")&&delete o[n];});}}));var jr=(e,t)=>{for(let o of e)if(!("$entity"in o)&&!("$relation"in o)&&(!("$thing"in o)||!("$thingType"in o)))throw new Error("No entity specified in query");let r=Array.isArray(e)?e:[e];return immer.produce(r,o=>objectTraversal.traverse(o,n=>{let{value:l,meta:s}=n,h=l;if(radash.isObject(h)){if(h.$id){if(s.nodePath?.includes(".$filter"))return;let p=h.$entity||h.$relation?h:{[`$${h.$thingType}`]:h.$thing},d=x(t,p);if(!d?.name)throw new Error(`Schema not found for ${h.$thing}`);if(h.$path=d.name,Array.isArray(h.$id)||(h.$filterByUnique=!0),d?.idFields?.length!==1)throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in h||"$relation"in h||"$thing"in h){let p=x(t,h);if(!p?.name)throw new Error(`Schema not found for ${h.$thing}`);h.$path=p.name;}if(h.$entity?(h.$thing=h.$entity,h.$thingType="entity",delete h.$entity):h.$relation&&(h.$thing=h.$relation,h.$thingType="relation",delete h.$relation),radash.isObject(h)&&"$thing"in h&&h.$thing){let p=h.$entity||h.$relation?h:{[`$${h.$thingType}`]:h.$thing};h[ae]=s.nodePath;let d=x(t,p);if(h.$filter&&(h.$filterByUnique=bt(h.$filter,d),h.$filter=Oe(h.$filter,h.$thing,t)),h.$fields){h.$fields.some(f=>d?.idFields?.includes(f?.$path||f))||(h.$fields=[...h.$fields,...Array.isArray(d.idFields)?d.idFields:[]],h.$idNotIncluded=!0);let a=h.$fields?.flatMap(f=>{let u=xr(f,d,t);return Array.isArray(u)?u:[u]}).filter(Boolean);h.$fields=a;}else {let a=Ft(d)?.flatMap(f=>{let u=xr(f,d,t);return Array.isArray(u)?u:[u]}).filter(Boolean);h.$fields=a;}h.$excludedFields&&(h.$fields=h.$fields.filter(c=>Ge(d,c)?!0:!h.$excludedFields.includes(c.$path)));}}}))},Ft=e=>{let t=e.dataFields?.map(n=>n.path)||[],r=e.linkFields?.map(n=>n.path)||[],i=Object.keys(e.roles||{})||[];return [...t,...r,...i]},bt=(e,t)=>Object.keys(e||{}).some(i=>{if(!Array.isArray(e[i])){let o=t.idFields?.includes(i),n=t.dataFields?.some(s=>(s.dbPath===i||s.path===i)&&s?.validations?.unique),l=i==="$id"&&!Array.isArray(e[i]);return o||n||l}return !1}),Ge=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),$i=e=>{let{field:t,fieldStr:r,$justId:i,dbPath:o,isVirtual:n,fieldSchema:l}=e;return {$path:r,$dbPath:o,$thingType:"attribute",$as:t.$as||r,$var:r,$fieldType:"data",$justId:i,$id:t.$id,$isVirtual:n,[de]:l}},mi=e=>{let{field:t,fieldStr:r,linkField:i,$justId:o,dbPath:n,schema:l,fieldSchema:s}=e,{target:h,oppositeLinkFieldsPlayedBy:p}=i;return p.map(d=>{let c=h==="role"?d.thingType:"relation",a=h==="role"?d.thing:i.relation,f={[`$${c}`]:a},u=x(l,f),$=t?.$fields?.filter(B=>Ge(u,B)).length===0,y=[];if(typeof t!="string")if(t.$fields)if($){let B=u.idFields||[];y=[...t.$fields,...B];}else y=t.$fields;else y=Ft(u);else y=["id"];t.$excludedFields&&(y=y.filter(B=>Ge(u,B)?!0:!t.$excludedFields.includes(B.$path)));let m=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...Oe(t.$filter,a,l)}:void 0;return {$thingType:c,$plays:i.plays,$playedBy:d,$path:d.path,$dbPath:n,$as:t.$as||r,$var:r,$thing:a,$fields:y,$excludedFields:t.$excludedFields,$fieldType:"link",$target:h,$intermediary:d.relation,$justId:o,$id:t.$id,$filter:m,$idNotIncluded:$,$filterByUnique:bt(t.$filter,u),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[de]:s}})},yi=e=>{let{field:t,fieldStr:r,roleField:i,$justId:o,dbPath:n,schema:l,fieldSchema:s}=e;return i.playedBy.map(h=>{let{thing:p,thingType:d,relation:c}=h,a={[`$${d}`]:p},f=x(l,a),u=t?.$fields?.filter(m=>f?.idFields?.includes(m)||f?.idFields?.includes(m.$path)).length===0,$=[];if(typeof t!="string")if(t.$fields)if(u){let m=f.idFields||[];$=[...t.$fields,...m];}else $=t.$fields;else $=Ft(f);else $=["id"];t.$excludedFields&&($=$.filter(m=>Ge(f,m)?!0:!t.$excludedFields.includes(m.$path)));let y=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...Oe(t.$filter,p,l)}:void 0;return {$thingType:d,$path:r,$dbPath:n,$as:t.$as||r,$var:r,$thing:p,$fields:$,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:c,$justId:o,$id:t.$id,$filter:y,$idNotIncluded:u,$filterByUnique:bt(t.$filter,f),$playedBy:h,$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[de]:s}})},xr=(e,t,r)=>{let i=typeof e=="string"?e:e.$path,o=typeof e=="string",n=t.dataFields?.find(h=>h.path===i),l=t.linkFields?.find(h=>h.path===i),s=t.roles?.[i];if(n){let h=!!n.isVirtual&&!!n.default;return $i({field:e,fieldStr:i,$justId:o,dbPath:n.dbPath,isVirtual:h,fieldSchema:n})}else {if(l)return mi({field:e,fieldStr:i,linkField:l,$justId:o,dbPath:l.path,schema:r,fieldSchema:l});if(s)return yi({field:e,fieldStr:i,roleField:s,$justId:o,dbPath:i,schema:r,fieldSchema:s})}return null},Oe=(e,t,r)=>{if(e==null)return e;let i=radash.isArray(e),n=(i?e:[e]).map(l=>Object.keys(l).reduce((p,d)=>{let c=l[d],a=radash.isArray(c)?c:[c];if(d.startsWith("$"))["$id","$thing"].includes(d)?p[d]=c:p[d]=Oe(c,t,r);else {let f=t in r.entities?r.entities[t]:r.relations[t],[u,$]=_e(f,d);if(u==="dataField")p[d]=c;else if(u==="linkField"||u==="roleField"){let y=$,[m]=y.$things;return a.every(B=>typeof B=="string")?p[d]={$id:a,$thing:m}:a.every(B=>radash.isObject(B))&&(p[d]=radash.isArray(c)?{$or:Oe(c,m,r)}:Oe(c,m,r)),p}else throw new Error(`Field ${d} not found in schema of ${t}`)}return p},{}));return i?n.length===1?n[0]:{$or:n}:n[0]};var Nr=async(e,t,r)=>r?(n=>immer.produce(n,l=>objectTraversal.traverse(l,({value:s})=>{if(radash.isObject(s)){let h=s;if(!h.$thing)return;if(h.$thing){let p=x(e,h),{virtualFields:d}=p,c=h[ae];if(!c)throw new Error("[Internal] QueryPath is missing");let a=objectTraversal.getNodeByPath(t,c),f=a.$fields.map($=>$.$path),u=a.$excludedFields;d.forEach($=>{if(u?.includes($)||f.length>0&&!f.includes($))return;let y=p.dataFields?.find(m=>m.path===$);if(y?.default){let m=Ae({currentThing:h,fieldSchema:y,mandatoryDependencies:!0});h[$]=m;}else if(h[$]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${$}`)}),u&&u.forEach($=>{if(typeof $!="string")throw new Error("[Internal] ExcludedField is not a string");delete h[$];});}}})))(r):void 0;var Wr=e=>e.replace(/`/g,""),bi=[" ","-","+","*","/","=","!","@","#","$","%","^","&","(",")","[","]","{","}","|","\\",";",":","'",'"',",","<",">",".","?","~","`"],zr=e=>bi.some(t=>e.includes(t))?`\u27E8\`${e}\`\u27E9`:e;var Vr=e=>{let{queries:t,schema:r}=e;return t.map(i=>Mi({query:i,schema:r}))},Mi=e=>{let{query:t,schema:r}=e,{$thing:i,$fields:o,$filter:n,$offset:l,$limit:s,$sort:h}=t;if(o.length===0)return null;let p=[];p.push("SELECT");let d=wt({parentQuery:t,queries:o,level:1,schema:r});d&&p.push(d);let c=r.entities[i]||r.relations[i];if(!c)throw new Error(`Schema for ${i} not found`);let f=(c.subTypes?[i,...c.subTypes]:[i]).map(u=>zr(u));if(t.$id)if(typeof t.$id=="string")p.push(`FROM ${f.map(u=>`${u}:\`${t.$id}\``).join(",")}`);else if(radash.isArray(t.$id)){let u=t.$id,$=f.flatMap(y=>u?.map(m=>`${y}:\`${m}\``));p.push(`FROM ${$.join(",")}`);}else throw new Error("Invalid $id");else p.push(`FROM ${f.join(",")}`);if(n){let u=ye(n,i,r),$=Se(u);p.push(`WHERE ${$}`);}return h&&p.push(Hr(h)),typeof s=="number"&&p.push(`LIMIT ${s}`),typeof l=="number"&&p.push(`START ${l}`),p.join(`
39
- `)},wt=e=>{let{queries:t,schema:r,level:i,parentQuery:o}=e,n=[],l=o[ae];return n.push(M(`"${l}" as \`$$queryPath\``,i)),n.push(M("meta::id(id) as `$id`",i)),n.push(M("meta::tb(id) as `$thing`",i)),t.forEach(s=>{let h=Qi({query:s,level:i,schema:r});h&&n.push(h);}),n.length===0?null:n.join(`,
40
- `)},Qi=e=>{let{query:t,schema:r,level:i}=e;return t.$fieldType==="data"?Ti({query:t,level:i}):t.$fieldType==="link"?Li({query:t,level:i,schema:r}):t.$fieldType==="role"?Si({query:t,level:i,schema:r}):null},Ti=e=>{let{query:t,level:r}=e;return t.$isVirtual?null:t.$path==="id"?M(`meta::id(${t.$path}) AS ${t.$as}`,r):t.$path===t.$as?M(`\`${t.$path}\``,r):M(`\`${t.$path}\` AS \`${t.$as}\``,r)},Li=e=>{let{query:t,schema:r,level:i}=e,{$fields:o,$filter:n,$offset:l,$limit:s,$sort:h}=t;if(o.length===0)return null;let p=[];p.push(M("(",i));let d=i+1;p.push(M("SELECT",d));let c=wt({parentQuery:t,queries:o,level:d+1,schema:r});c&&p.push(c);let a=t[de][Te].queryPath;if(p.push(M(`FROM ${a}`,d)),n){let f=ye(n,t.$thing,r),u=Se(f);p.push(`WHERE ${u}`);}return h&&p.push(M(Hr(h),d)),typeof s=="number"&&p.push(M(`LIMIT ${s}`,d)),typeof l=="number"&&p.push(M(`START ${l}`,d)),p.push(M(`) AS \`${t.$as}\``,i)),p.join(`
41
- `)},Si=e=>{let{query:t,schema:r,level:i}=e;if(t.$fields.length===0)return null;let o=[];o.push(M("(",i));let n=i+1;o.push(M("SELECT",n));let l=n+1,s=wt({parentQuery:t,queries:t.$fields,level:l,schema:r});s&&o.push(s);let h=t[de][Te].queryPath;if(o.push(M(`FROM ${h}`,n)),t.$filter){let p=ye(t.$filter,t.$playedBy.thing,r),d=Se(p);o.push(`WHERE ${d}`);}return o.push(M(`) AS \`${t.$as}\``,i)),o.join(`
42
- `)},ye=(e,t,r)=>{if(e==null)return e;let i=radash.isArray(e),n=(i?e:[e]).map(l=>{let h=Object.keys(l).reduce((p,d)=>{let c=l[d];if(d.startsWith("$"))return d==="$not"?{...p,$not:void 0,"$!":ye(c,t,r)}:d==="$or"?{...p,$or:void 0,$OR:ye(c,t,r)}:d==="$and"?{...p,$and:void 0,$AND:ye(c,t,r)}:d==="$eq"?{...p,$nor:void 0,"$=":ye(c,t,r)}:d==="$id"?{...p,$id:void 0,"meta::id(id)":{$IN:radash.isArray(c)?c:[c]}}:d==="$thing"?p:{...p,[d]:ye(c,t,r)};let a=t in r.entities?r.entities[t]:r.relations[t],[f,u]=_e(a,d);if(f==="dataField"){if(a.idFields.length>1)throw new Error("Multiple id fields not supported");return d===a.idFields[0]?{...p,"meta::id(id)":{$IN:radash.isArray(c)?c:[c]}}:{...p,[d]:c}}if(f==="linkField"||f==="roleField"){let $=u,[y]=$.$things,m=$[Te].queryPath;return {...p,[m]:ye(c,y,r)}}throw new Error(`Field ${d} not found in schema, Defined in $filter`)},{});return radash.shake(h)});return i?n:n[0]},Se=e=>{if(e==null)return "";let t=Object.entries(e),r=[];return t.forEach(([i,o])=>{if(["$OR","$AND","$!"].includes(i)){let n=i.replace("$",""),l=Array.isArray(o)?o.map(s=>Se(s)):[Se(o)];n==="!"?r.push(`!(${l.join(` ${n} `)})`):r.push(`(${l.join(` ${n} `)})`);return}if(radash.isObject(o))if(i.includes("<-")||i.includes("->")){let n=Se(o);r.push(`${i}[WHERE ${n}]`);}else {if(i.startsWith("$"))throw new Error(`Invalid key ${i}`);if(Object.keys.length===1&&Object.keys(o)[0].startsWith("$")){let[n]=Object.keys(o),l=o[n];if(radash.isArray(l))r.push(`${i} ${n.replace("$","")} [${l.map(s=>`'${s}'`).join(", ")}]`);else if(radash.isObject(l)){let s=Se(l);r.push(`${i} ${n.replace("$","")} ${s}`);}else r.push(`${i} ${n.replace("$","")} '${l}'`);}else throw new Error(`Invalid key ${i}`)}else if(Array.isArray(o)){let n=i.startsWith("$")?i.replace("$",""):"IN";r.push(`${i} ${n} [${o.map(l=>`'${l}'`).join(", ")}]`);}else {let n=i.startsWith("$")?i.replace("$",""):"=";r.push(`${i} ${n} '${o}'`);}}),r.join(" AND ")},Hr=e=>`ORDER BY ${e.map(r=>{if(typeof r=="string")return r;let{field:i,desc:o}=r;return `${i}${o?" DESC":" ASC"}`}).join(", ")}`;var Kr=async e=>{let{client:t,queries:r}=e;return await Promise.all(r.map(i=>t.query(i)))};var Ur=e=>{let{res:t,queries:r}=e;return t.map((o,n)=>Jr(r[n],o))},Jr=(e,t)=>{if(radash.isArray(t)){if(t.length===0)return null;if(e.$filterByUnique){if(t.length>1)throw new Error("Multiple results found for unique query");return Qt(e,t[0])}if(t.length>=1)return t.map(r=>Qt(e,r))}else throw new Error("res is unexpectedly not an array")},Qt=(e,t)=>{let r={[ae]:t.$$queryPath,$id:t.$id,$thing:Wr(t.$thing),$thingType:e.$thingType};return e.$fields.forEach(i=>{let o=i.$as,n=t[o];i.$path==="id"&&e.$idNotIncluded||(r[o]=ki(i,n));}),r},ki=(e,t)=>t==null||radash.isArray(t)&&t.length===0?null:e.$fieldType==="data"?(e[de].cardinality==="ONE"&&radash.isArray(t)&&t[0],t??null):e.$justId?e.$filterByUnique||e[de].cardinality==="ONE"?t[0]?.id??null:t?.map(r=>r.id)??[]:e.$filterByUnique||e[de].cardinality==="ONE"?Qt(e,t[0]):Jr(e,t);var Tt=H("error","error",V((e,t)=>({...e,error:t.error}))),Di=be("build",{build:v(async e=>Vr({queries:e.bql.queries,schema:e.schema}),H("done","run",V((e,t)=>({...e,surql:{...e.surql,queries:t.data}}))),Tt),run:v(async e=>Kr({client:e.client,queries:oe(e.surql.queries)}),H("done","parse",V((e,t)=>({...e,surql:{...e.surql,res:t.data}}))),Tt),parse:v(async e=>Ur({res:oe(e.surql.res),queries:e.bql.queries,schema:e.schema,config:e.config}),H("done","success",V((e,t)=>({...e,bql:{...e.bql,res:t.data}}))),Tt),success:he(),error:he()},e=>e),Ri=async e=>new Promise((t,r)=>{me(Di,i=>{i.machine.state.name==="success"&&t(i.context.bql.res),i.machine.state.name==="error"&&r(i.context.error);},e);}),Zr=async(e,t,r,i)=>Ri({bql:{queries:e},surql:{},schema:t,config:r,client:i,error:null});var Lt="___",Yr=async e=>{let{queries:t,schema:r}=e;return t.map(i=>Ci({query:i,schema:r}))},Ci=e=>{let{query:t,schema:r}=e,{$path:i,$thing:o,$filter:n,$fields:l,$sort:s,$offset:h,$limit:p,$id:d}=t;if(!i)throw new Error("Path is not defined");let c=[],a=t[ae];if(c.push("match"),c.push(`$${i} isa ${o};`),n||d){let $=Ve(r,t),y={...n,...d?{[$]:d}:{}},m=Rt({$filter:y,$var:i,$thing:o,schema:r,depth:0});c.push(`
43
- ${m}`);}let f=At({schema:r,$thing:o,$var:i,$sort:s,depth:0});f&&c.push(f.match);let u=`M_${uuid.v4()}`;if(c.push(`?queryPath${u} = "${a}";`),c.push("fetch"),c.push(`?queryPath${u} as "queryPath";`),l){let $=l.filter(B=>B.$fieldType==="data");$&&$.length>0&&c.push(...St($,i,0));let y=l.filter(B=>B.$fieldType==="link");y&&y.length>0&&c.push(...Dt(y,i,i,0,r));let m=l.filter(B=>B.$fieldType==="role");m&&m.length>0&&c.push(...kt(m,i,i,0,r));}return f&&c.push(f.sort),typeof h=="number"&&c.push(`
44
- offset ${h};`),typeof p=="number"&&c.push(`
45
- limit ${p};`),c.join(`
46
- `)},St=(e,t,r)=>{let i=[],o=[];for(let p=0;p<e.length;p++)e[p].$isVirtual||i.push(e[p].$dbPath),o.push(`{${e[p].$dbPath}:${e[p].$as}}`);let n=i.join(", "),s=`$metadata:{as:[${o.join(",")}]}`;return [M(`$${t} as "${t}.${s}.$dataFields": ${n};`,r)]},kt=(e,t,r,i,o)=>{let n=i+1,l=[];for(let s of e){let{$fields:h,$as:p,$justId:d,$idNotIncluded:c,$filterByUnique:a,$thing:f,$sort:u,$offset:$,$limit:y}=s,m=s[ae],B=`$metadata:{as:${p},justId:${d?"T":"F"},idNotIncluded:${c},filterByUnique:${a}}`;l.push(M(`"${r}.${B}.${s.$var}": {`,i)),l.push(M("match",n));let w=`${t}${Lt}${s.$var}`;if(l.push(M(`$${w} isa ${s.$thing};`,n)),l.push(M(`$${t} (${s.$var}: $${t}${Lt}${s.$var}) isa ${s.$intermediary};`,n)),s.$filter||s.$id){let L=Ve(o,s),D=s.$id?{[L]:s.$id}:{},A={...s.$filter,...D};l.push(Rt({$filter:A,$var:w,$thing:s.$thing,schema:o,depth:n}));}let g=At({schema:o,$thing:f,$var:w,$sort:u,depth:n});if(g&&l.push(g.match),h){let L=`M_${uuid.v4()}`;l.push(M(`
47
- ?queryPath${L} = "${m}";`,n)),l.push(M("fetch",n)),l.push(M(`?queryPath${L} as "queryPath";`,n));let D=h?.filter(j=>j.$fieldType==="data");D&&D.length>0&&l.push(...St(D,w,n));let A=h?.filter(j=>j.$fieldType==="link");A&&A.length>0&&l.push(...Dt(A,w,`${t}.${s.$var}`,n,o));let C=h?.filter(j=>j.$fieldType==="role");C&&C.length>0&&l.push(...kt(C,w,`${t}.${s.$var}`,n,o));}g&&l.push(g.sort),typeof $=="number"&&l.push(M(`offset ${$};`,n)),typeof y=="number"&&l.push(M(`limit ${y};`,n)),l.push(M("};",i));}return l},Dt=(e,t,r,i,o)=>{let n=i+1,l=[];for(let s of e){let{$fields:h,$as:p,$justId:d,$idNotIncluded:c,$filterByUnique:a,$playedBy:f,$thing:u,$sort:$,$offset:y,$limit:m}=s,B=s[ae],w=`$metadata:{as:${p},justId:${d?"T":"F"},idNotIncluded:${c},filterByUnique:${a}}`;l.push(M(`"${r}.${w}.${s.$var}": {`,i)),l.push(M("match",n));let g=`${t}${Lt}${s.$var}`;if(l.push(M(`$${g} isa ${s.$thing};`,n)),s.$filter||s.$id){let D=Ve(o,s),A=s.$id?{[D]:s.$id}:{},C={...s.$filter,...A};l.push(Rt({$filter:C,$var:g,$thing:s.$thing,schema:o,depth:n}));}let L=At({schema:o,$thing:u,$var:g,$sort:$,depth:n});if(L&&l.push(L.match),s.$target==="role"?l.push(M(`$${t}_intermediary (${s.$plays}: $${t}, ${f.plays}: $${g}) isa ${s.$intermediary};`,n)):l.push(M(`$${g} (${s.$plays}: $${t});`,n)),h){let D=`M_${uuid.v4()}`;l.push(M(`?queryPath${D} = "${B}";`,n)),l.push(M("fetch",n)),l.push(M(`?queryPath${D} as "queryPath";`,n));let A=h?.filter(N=>N.$fieldType==="data");A&&A.length>0&&l.push(...St(A,g,n));let C=h?.filter(N=>N.$fieldType==="link");C&&C.length>0&&l.push(...Dt(C,g,`${t}.${s.$var}`,n,o));let j=h?.filter(N=>N.$fieldType==="role");j&&j.length>0&&l.push(...kt(j,g,`${t}.${s.$var}`,n,o));}L&&l.push(L.sort),typeof y=="number"&&l.push(M(`offset ${y};`,n)),typeof m=="number"&&l.push(M(`limit ${m};`,n)),l.push(M("};",i));}return l},Oi=(e,t)=>{let r={};if(t.dataFields?.forEach(l=>{l.path!==l.dbPath&&(r[l.path]=l.dbPath);}),Object.keys(r).length===0)return e;let{$not:i,...o}=e,n=vr(o,r);return i&&(n.$not=vr(i,r)),n},vr=(e,t)=>{let r={};return Object.entries(e).forEach(([i,o])=>{let n=t[i]||i;r[n]=o;}),r},Rt=e=>{let{$filter:t,$var:r,$thing:i,schema:o,depth:n}=e,l=Oi(t,G(o,i)),{$not:s,...h}=l,p=G(o,i),d=[];return Object.entries(s||{}).forEach(([c,a])=>{if(c.startsWith("$"))return;if(p.dataFields?.find($=>$.dbPath===c)){a===null?d.push(M(`$${r} has ${c} $${c}_${uuid.v4()};`,n)):Array.isArray(a)?a.forEach($=>{d.push(M(`not { $${r} has ${c} ${ne($)}; };`,n));}):d.push(M(`not { $${r} has ${c} ${ne(a)}; };`,n));return}let u=p.linkFields?.find($=>$.path===c);if(u){let[$]=u.oppositeLinkFieldsPlayedBy,m=G(o,$.thing).idFields?.[0];if(!m)throw new Error(`"${$.thing}" does not have an id field`);if(u.target==="relation")a===null?d.push(M(`(${u.plays}: $${r}) isa ${u.relation};`,n)):Array.isArray(a)?a.forEach(B=>{d.push(M(`not { (${u.plays}: $${r}) isa ${u.relation}, has ${m} ${ne(B)}; };`,n));}):d.push(M(`not { (${u.plays}: $${r}) isa ${u.relation}, has ${m} ${ne(a)}; };`,n));else {let B=`${$.thing}_${uuid.v4()}`;a===null?d.push(M(`$${B} isa ${$.thing}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation};`,n)):Array.isArray(a)?a.forEach(w=>{d.push(M(`not { $${B} isa ${$.thing}, has ${m} ${ne(w)}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation}; };`,n));}):d.push(M(`not { $${B} isa ${$.thing}, has ${m} ${ne(a)}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation}; };`,n));}return}if(p.thingType==="relation"){let $=p.roles[c];if($){let[y]=$.playedBy||[],B=G(o,y.thing).idFields?.[0];if(!B)throw new Error(`"${y.thing}" does not have an id field`);let w=`${y.thing}_${uuid.v4()}`,g=uuid.v4(),L=`${r}_${g}`;a===null?(d.push(M(`$${L} isa ${i};`,n)),d.push(M(`$${L} (${y.plays}: ${w});`,n)),d.push(M(`$${r} is $${L};`,n))):Array.isArray(a)?a.forEach(D=>{d.push(M(`$${L} isa ${i};`,n)),d.push(M(`not { $${w} isa ${y.thing}, has ${B} ${ne(D)}; $${L} (${y.plays}: $${w}); };`,n)),d.push(M(`$${r} is $${L};`,n));}):(d.push(M(`$${L} isa ${i};`,n)),d.push(M(`not { $${w} isa ${y.thing}, has ${B} ${ne(a)}; $${L} (${y.plays}: $${w}); };`,n)),d.push(M(`$${r} is $${L};`,n)));return}}}),Object.entries(h).forEach(([c,a])=>{if(c.startsWith("$"))return;if(p.dataFields?.find($=>$.dbPath===c)){if(a===null)d.push(M(`not { $${r} has ${c} $${c}_${uuid.v4()}; };`,n));else if(Array.isArray(a)){let $=a.map(m=>`$${r} has ${c} ${ne(m)};`),y=Xe($);y&&d.push(M(y,n));}else d.push(M(`$${r} has ${c} ${ne(a)};`,n));return}let u=p.linkFields?.find($=>$.path===c);if(u){let[$]=u.oppositeLinkFieldsPlayedBy,m=G(o,$.thing).idFields?.[0];if(!m)throw new Error(`"${$.thing}" does not have an id field`);if(u.target==="relation")if(a===null)d.push(M(`not { (${u.plays}: $${r}) isa ${u.relation}; };`,n));else if(Array.isArray(a)){let B=a.map(g=>`(${u.plays}: $${r}) isa ${u.relation}, has ${m} ${ne(g)};`),w=Xe(B);w&&d.push(M(w,n));}else d.push(M(`(${u.plays}: $${r}) isa ${u.relation}, has ${m} ${ne(a)};`,n));else {let B=`${$.thing}_${uuid.v4()}`;if(a===null)d.push(M(`not { $${B} isa ${$.thing}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation}; };`,n));else if(Array.isArray(a)){let w=a.map(L=>`$${B} isa ${$.thing}, has ${m} ${ne(L)}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation};`),g=Xe(w);g&&d.push(M(g,n));}else d.push(M(`$${B} isa ${$.thing}, has ${m} ${ne(a)}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation};`,n));}return}if(p.thingType==="relation"){let $=p.roles[c];if($){let[y]=$.playedBy||[],B=G(o,y.thing).idFields?.[0];if(!B)throw new Error(`"${y.thing}" does not have an id field`);let w=`${y.thing}_${uuid.v4()}`,g=uuid.v4(),L=`${r}_${g}`;if(a===null)d.push(M(`$${L} isa ${i};`,n)),d.push(M(`not { $${L} (${y.plays}: ${w}); };`,n)),d.push(M(`$${r} is $${L};`,n));else if(Array.isArray(a)){let D=a.map(C=>`$${w} isa ${y.thing}, has ${B} ${ne(C)}; $${L} (${y.plays}: $${w});`),A=Xe(D);A&&(d.push(M(`$${L} isa ${i};`,n)),d.push(M(A,n)),d.push(M(`$${r} is $${L};`,n)));}else d.push(M(`$${L} isa ${i};`,n)),d.push(M(`$${w} isa ${y.thing}, has ${B} ${ne(a)}; $${L} (${y.plays}: $${w});`,n)),d.push(M(`$${r} is $${L};`,n));return}}throw new Error(`"${i}" does not have property "${c}"`)}),d.join(`
48
- `)},Xe=e=>{if(e.length>1)return `{ ${e.join(" } or { ")} };`;let[t]=e;return t},ne=e=>typeof e=="string"?`'${e}'`:e instanceof Date?`'${e.toISOString().replace("Z","")}'`:radash.isObject(e)&&"$id"in e?radash.isArray(e.$id)?`like "^(${e.$id.join("|")})$"`:`"${e.$id}"`:`${e}`,qi=e=>typeof e=="string"?{field:e,desc:!1}:{...e,desc:e.desc??!1},At=e=>{let{$var:t,$thing:r,schema:i,$sort:o,depth:n}=e,l=G(i,r),s=[],h=[];if(o?.forEach(p=>{let d=qi(p),c=l.dataFields?.find(u=>u.path===d.field);if(!c)throw new Error(`"${r}" does not have data field "${d.field}"`);let a=`${d.field}_${uuid.v4()}`;s.push(M("{",n)),s.push(M(`$${t} has ${c.dbPath} $${a}_1;`,n+1)),s.push(M("not {",n+1)),s.push(M(`$${t} has ${c.dbPath} $${a}_2;`,n+2)),s.push(M(`$${a}_2 < $${a}_1;`,n+2)),s.push(M("};",n+1)),s.push(M(`?${a}_ = $${a}_1;`,n+1)),s.push(M("} or {",n)),s.push(M(`not { $${t} has ${c.dbPath} $${a}_1; };`,n+1)),s.push(M(`?${a}_ = "~";`,n+1)),s.push(M("};",n)),s.push(M(`?${a} = ?${a}_;`,n));let f=d.desc?"desc":"asc";h.push(`?${a} ${f}`);}),s.length!==0)return {match:s.join(""),sort:M(`sort ${h.join(", ")};`,n)}};var Xr=async e=>{let{enrichedBqlQuery:t,rawBqlRequest:r,schema:i,config:o,rawTqlRes:n}=e;if(t){if(!n)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");return n.map((l,s)=>{let h=r[s],p=t[s];return xi(l,h,p,i,o)})},xi=(e,t,r,i,o)=>e.length===0?null:r.$filterByUnique?Gr(e[0],t,i,o):e.map(n=>Gr(n,t,i,o)),Gr=(e,t,r,i)=>{let{dataFields:o,currentSchema:n,linkFields:l,roleFields:s,schemaValue:h}=It(e,r),p=Ct(o,n,i),d=qt(l,r,i),c=Ot(s,r,i),a=t?.$fields?.every(u=>!n?.idFields?.includes(typeof u=="string"?u:u.$path));return {...d,...c,...h,...!i.query?.noMetadata&&t.$id?{$id:Array.isArray(t.$id)?p.id:t.$id}:{},...a?Object.fromEntries(Object.entries(p).filter(([u])=>!n?.idFields?.includes(u))):p}},It=(e,t)=>{let r=Object.keys(e),i=r.find(a=>a.endsWith(".$dataFields"));if(!i)throw new Error("No datafields");let o=e[i],n=i.split(".")[i.split(".").length-2];if(o.$metaData=n,o.length===0)throw new Error("No datafields");let l=o.type,s={$thing:l.label,$thingType:l.root,[ae]:e.queryPath.value},h={[`$${s.$thingType}`]:s.$thing},p=x(t,h),d=r.filter(a=>{let f=oe(a.split(".").pop());return !a.endsWith(".$dataFields")&&p.linkFields?.some(u=>u.path===f)}).map(a=>{let f=oe(a.split(".").pop()),u=oe(p.linkFields?.find($=>$.path===f));return {$linkFields:e[a],$key:f,$metaData:a.split(".")[a.split(".").length-2],$cardinality:u.cardinality}}),c=r.filter(a=>{let f=a.split(".").pop();return f&&!a.endsWith(".$dataFields")&&p.thingType==="relation"&&p.roles?.[f]}).map(a=>{let f=oe(a.split(".").pop());return {$roleFields:e[a],$key:f,$metaData:a.split(".")[a.split(".").length-2],$cardinality:p.roles[f].cardinality}});return {dataFields:o,schemaValue:s,currentSchema:p,linkFields:d,roleFields:c}},Ct=(e,t,r)=>{let{$metaData:i}=e,{as:o}=ji(i),n=Object.entries(e).filter(([l])=>l!=="type"&&!l.startsWith("$")).map(([l,s])=>{let h=t.dataFields?.find(a=>a.path===l||a.dbPath===l),p=l==="id",d=Array.isArray(o)?o.find(a=>a[l])?.[l]:l,c;if(h?.cardinality==="ONE"){if(c=s[0]?s[0].value:r.query?.returnNulls?null:void 0,h.contentType==="DATE"?c=c&&`${c}Z`:h.contentType==="JSON"&&(c=c&&JSON.parse(c)),p)return [[d,c],["$id",c]].filter(([a,f])=>f!==void 0)}else if(h?.cardinality==="MANY"){if(!radash.isArray(s))throw new Error("Typedb fetch has changed its format");if(s.length===0)return r.query?.returnNulls?[[d,null]]:[];h.contentType==="DATE"?c=s.map(a=>`${a.value}Z`):h.contentType==="JSON"?c=s.map(a=>a.value&&JSON.parse(a.value)):c=s.map(a=>a.value);}return [[d,c]].filter(([a,f])=>f!==void 0)}).flat();return Object.fromEntries([...n])},Ot=(e,t,r)=>{let i={};return e.forEach(o=>{let{$roleFields:n,$metaData:l,$cardinality:s}=o,{as:h,justId:p,idNotIncluded:d,filterByUnique:c}=en(l);if(h===null)return;let a=n.map(f=>{let{dataFields:u,currentSchema:$,linkFields:y,roleFields:m,schemaValue:B}=It(f,t),w=Ct(u,$,r);if(p==="T")return w.id;{let g=qt(y,t,r),L=Ot(m,t,r),D={...w};return d==="true"&&$?.idFields?.forEach(A=>delete D[A]),{...D,...g,...L,...B}}});a.length>0?i[h]=s==="MANY"&&c==="false"?a:a[0]:r.query?.returnNulls&&(i[h]=null);}),i},qt=(e,t,r)=>{let i={};return e.forEach(o=>{let{$linkFields:n,$metaData:l,$cardinality:s}=o,{as:h,justId:p,idNotIncluded:d,filterByUnique:c}=en(l);if(h===null)return;let a=n.map(f=>{let{dataFields:u,currentSchema:$,linkFields:y,roleFields:m,schemaValue:B}=It(f,t),w=Ct(u,$,r);if(p==="T")return w.id;{let g=qt(y,t,r),L=Ot(m,t,r),D={...w};return d==="true"&&$.idFields?.forEach(A=>delete D[A]),{...D,...g,...L,...B}}});i[h]=a.length>0?s==="MANY"&&c==="false"?a:a[0]:r.query?.returnNulls?null:void 0;}),i},en=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,r=/justId:([a-zA-Z0-9_\-·]+)/,i=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,o=/filterByUnique:([a-zA-Z0-9_\-·]+)/,n=e.match(t),l=e.match(r),s=e.match(i),h=e.match(o);return {as:n?n[1]:null,justId:l?l[1]:null,idNotIncluded:s?s[1]:null,filterByUnique:h?h[1]:null}},ji=e=>{try{let r=(o=>{let n=o.replace("$metadata:","");return n=n.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),n=n.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(l,s,h)=>/^{.*}$/.test(h)?`:${h}`:`:${s}"${h}"`),n=n.replace(/\[([^\]]+)\]/g,(l,s)=>`[${s.split(",").map(h=>h.trim().startsWith("{")&&h.trim().endsWith("}")?h.trim():`"${h.trim()}"`).join(",")}]`),n})(e);return JSON.parse(r)}catch(t){return console.error(t),{as:[]}}};var tn=async e=>{let{tqlRequest:t,dbHandles:r,config:i}=e,o=new typedbDriver.TypeDBOptions;o.infer=!0;let{session:n}=await Ze(r,i),l=await n.transaction(typedbDriver.TransactionType.READ,o),[s,h]=await radash.tryit(radash.parallel)(t.length,t,async p=>await l.query.fetch(p).collect());if(s){await l.rollback();let p=s;throw new Error(`Error running TQL query: ${p.errors}`)}return await l.close(),h};var Vi=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,Hi=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,Ki=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,Pt=H("error","error",V((e,t)=>({...e,error:t.error}))),Ui=be("build",{build:v(async e=>Yr({queries:e.bql.queries,schema:e.schema}),H("done","run",V(Hi)),Pt),run:v(async e=>tn({dbHandles:e.handles,tqlRequest:oe(e.tql.queries),config:e.config}),H("done","parse",V(Ki)),Pt),parse:v(async e=>Xr({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries,schema:e.schema,config:e.config,rawTqlRes:oe(e.tql.res)}),H("done","success",V(Vi)),Pt),success:he(),error:he()},e=>e),Ji=async e=>new Promise((t,r)=>{me(Ui,i=>{i.machine.state.name==="success"&&t(i.context.bql.res),i.machine.state.name==="error"&&r(i.context.error);},e);}),rn=async(e,t,r,i,o)=>Ji({bql:{raw:e,queries:t},tql:{},schema:r,config:i,handles:o,error:null});var Zi=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,xt=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,et=H("error","error",V((e,t)=>({...e,error:t.error}))),vi=be("enrich",{enrich:v(async e=>jr(e.bql.raw,e.schema),H("done","adapter",V(Zi)),et),adapter:v(async e=>{let t={};e.bql.queries?.forEach((s,h)=>{let p=e.bql.raw[h],d=G(e.schema,s.$thing),{id:c}=d.defaultDBConnector;if(d.db==="typeDB"){if(!t[c]){let f=e.handles.typeDB?.get(c)?.client;if(!f)throw new Error(`TypeDB client with id "${d.defaultDBConnector.id}" does not exist`);t[c]={db:"typeDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else if(d.db==="surrealDB"){if(!t[c]){let f=e.handles.surrealDB?.get(c)?.client;if(!f)throw new Error(`SurrealDB client with id "${d.defaultDBConnector.id}" does not exist`);t[c]={db:"surrealDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else throw new Error(`Unsupported DB "${d.db}"`);let a=t[c];a.rawBql.push(p),a.bqlQueries.push(s),a.indices.push(h);});let r=Object.values(t),i=r.map(s=>s.db==="typeDB"?rn(s.rawBql,s.bqlQueries,e.schema,e.config,e.handles):Zr(s.bqlQueries,e.schema,e.config,s.client)),o=await Promise.all(i),n=r.flatMap((s,h)=>{let p=o[h];return s.indices.map((d,c)=>({index:d,result:p[c]}))});return n.sort((s,h)=>s.index<h.index?-1:s.index>h.index?1:0),n.map(({result:s})=>s)},H("done","postHooks",V(xt)),et),postHooks:v(async e=>Nr(e.schema,oe(e.bql.queries),oe(e.bql.res)),H("done","clean",V(xt)),et),clean:v(async e=>Pr(e.config,oe(e.bql.res)),H("done","success",V(xt)),et),success:he(),error:he()},e=>e),Yi=async e=>new Promise((t,r)=>{me(vi,i=>{i.machine.state.name==="success"&&t(i.context),i.machine.state.name==="error"&&r(i.context);},e);}),qe=async(e,t,r,i)=>Yi({bql:{raw:e},schema:t,config:r,handles:i,error:null});var jt="___",Gi=Symbol.for("grandChildOfCreate"),nn=async(e,t,r,i)=>{let o=(E,Q)=>Object.keys(E).filter(b=>!b.startsWith("$")&&E[b]!==void 0?Q?!x(t,E).dataFields?.find(T=>T.path===b):!0:!1);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(r.mutation?.preQuery===!1)return;let n=[];if(objectTraversal.traverse(e,({parent:E,key:Q,value:b})=>{E&&Q&&!Q.includes("$")&&radash.isObject(E)?(Array.isArray(E[Q])?E[Q]:[E[Q]]).forEach(T=>{if(radash.isObject(T)){if(E.$op!=="create")n.includes(T.$op)||n.push(T.$op);else if(T.$op==="delete"||T.$op==="unlink")throw new Error(`Cannot ${T.$op} under a create`)}}):!E&&radash.isObject(b)&&(n.includes(b.$op)||n.push(b.$op));}),!n.includes("delete")&&!n.includes("unlink")&&!n.includes("replace")&&!n.includes("update")&&!n.includes("link"))return;let s=(E=>{let Q=(b,F)=>{let T=[],S={},q=["$op","$bzId","$parentKey"],k=["$relation","$entity","$id",...q];for(let P in b)if(!q.includes(P)&&!(k.includes(P)&&!F))if(!P.includes("$")&&(radash.isObject(b[P])||Array.isArray(b[P]))){let J=b[P];if(Array.isArray(J)&&J.length>0)J.forEach(le=>{let Me={$path:P,...Q(le),...le.$filter&&{$as:le.$bzId}};T.find(U=>U.$path===Me.$path&&!U.$filter)||(T=[...T,Me]);});else {let le={$path:P,...Q(J),...!J.$filter&&{$as:J.$bzId}};T=[...T,le];}}else S[P]=b[P];return {...S,$fields:T}};return E.map(b=>Q(b,!0))})(Array.isArray(e)?e:[e]),p=(await qe(s,t,r,i)).bql.res,d=(E,Q)=>{let b=E.$id||E.id||E.$bzId;if(E.$objectPath){let{$objectPath:F}=E,T=F?.beforePath||"root",S=Array.isArray(F.ids)?`[${F.ids}]`:F.ids;return {beforePath:`${T}.${S}___${F.key}`,ids:b,key:Q}}else return {beforePath:"root",ids:b,key:Q}},c=(E,Q)=>{let b=E?.beforePath||"root",F=(Array.isArray(E?.ids)?`[${E?.ids}]`:E?.ids);return `${b}.${F}___${E?.key}`},a=E=>{if(E.includes("[")&&E.includes("]")){let[Q,b,F]=E.split(/[[\]]/);return b.split(",").map(S=>`${Q}${S}${F}`)}else return [E]},f={};(E=>immer.produce(E,Q=>objectTraversal.traverse(Q,b=>{let{key:F,parent:T}=b;if(T&&F&&T.$id&&!F.includes("$")){let S=d(T,F),q=c(S);if(Array.isArray(T[F])){let k=[];T[F].forEach(P=>{radash.isObject(P)?(P.$objectPath=S,k.push(P.$id.toString())):P&&k.push(P.toString());}),f[q]={$objectPath:S,$ids:k};}else {let k=T[F];radash.isObject(k)?(f[q]={$objectPath:S,$ids:[k.$id.toString()]},k.$objectPath=S):k&&(f[q]={$objectPath:S,$ids:[k.toString()]});}}})))(p||{});let $=E=>immer.produce(E,Q=>objectTraversal.traverse(Q,b=>{let{key:F,value:T,parent:S}=b;S&&F&&!F.includes("$")&&(Array.isArray(T)||radash.isObject(T))&&!Array.isArray(S)&&(Array.isArray(S[F])?S[F].forEach(q=>{typeof q!="string"&&(q.$objectPath=d(S,F),q.$parentIsCreate=S.$op==="create",q[Gi]=S.$parentIsCreate||S[Symbol.for("grandChildOfCreate")]);}):radash.isObject(S[F])&&(S[F].$parentIsCreate=S.$op==="create",S[F][Symbol.for("grandChildOfCreate")]=S.$parentIsCreate||S[Symbol.for("grandChildOfCreate")],S[F].$objectPath=d(S,F)));})),y=$(e),m=E=>{let Q=[];return E.forEach(F=>{if(!F.$id&&!F.id&&!F.$tempId)if(F.$filter){let T=c({...F.$objectPath,key:F.$bzId}),S=f[T];S&&(Array.isArray(S.$ids)?S.$ids:[S.$ids]).forEach(k=>{let P={...F,$id:k,$bzId:`T4_${uuid.v4()}`,$filterBzId:F.$bzId};Q.push(P);});}else {let T=c(F.$objectPath),S=f[T];S?S?.$ids.forEach(q=>{let k={...F,$id:q,$bzId:`T4_${uuid.v4()}`};Q.push(k);}):Q.push(F);}else Q.push(F);}),Q.map(F=>{let T={...F};return o(T,!0).forEach(S=>{let q=Array.isArray(T[S])?T[S]:[T[S]],k=m(q);T[S]=k;}),T})},B=m(Array.isArray(y)?y:[y]),w=$(B),L=(E=>{let Q=b=>{let F=U=>{let ee=[],z=[],O=[];return U.forEach(_=>{let ie=o(_,!0);if(ie.length>0){let I=!1;ie.forEach(W=>{(Array.isArray(_[W])?_[W]:[_[W]]).filter(Y=>!Y.$id&&!Y.id&&typeof _=="object").length&&(I=!0);}),I?ee.push(_):z.push(_);}else O.push({..._,$bzId:_.$tempId||`T_${uuid.v4()}`});}),{operationWithMultiples:ee,operationWithoutMultiples:z,otherOps:O}},{operationWithMultiples:T,operationWithoutMultiples:S,otherOps:q}=F(b),k=U=>{let z=(()=>{let W={};for(let te in U){let Z=x(t,U);!te.startsWith("$")&&Z.dataFields?.find(Y=>Y.path===te)&&(W[te]=U[te]);}return W})(),O=Object.keys(U),_=o(U,!0),ie=[],I=(W,te)=>{if(W===_.length){let Y={...te};O.forEach(re=>{re.startsWith("$")&&(Y[re]=U[re]);}),ie.push({...Y,...z});return}let Z={...te,[_[W]]:U[_[W]],...Ee(te),...z};I(W+1,Z),I(W+1,te);};return I(0,{...Ee(U)}),ie},P=[];return T.forEach(U=>{let ee=k(U),z=[];ee.forEach(O=>{let _=o(O,!0);if(O.$op==="create")z.push(O);else if(O.$id){let ie=c(O.$objectPath),I=[];if(_.forEach(W=>{let te=`${ie.includes("undefined")?"root":ie}.${O.$id}${jt}${W}`,Z=f[te];O[W].filter(re=>re.$op==="unlink"||re.$op==="delete"||re.$op==="update").length>0?Z&&I.push({key:W,ids:Z.$ids}):I.push({key:W,ids:[""]});}),I.length===_.length&&!z.find(W=>W.$id===O.$id))z.push(O);else {let W={...O,$bzId:O.$tempId||`T4_${uuid.v4()}`};_.forEach(Z=>{let Y=O[Z].filter(re=>re.$id);Y.length>0?W[Z]=Y:W[Z]=void 0;}),o(W,!0).length>0&&z.push(W);}}else if(O.$objectPath){let ie=c(O.$objectPath),I=f[ie]?.$ids||[];I.forEach(W=>{let te=[];_.forEach(Z=>{let Y=`${ie}.${W}${jt}${Z}`,re=f[Y];re&&te.push({key:Z,ids:re.$ids});}),_.length===0?I.filter(Y=>!z.find(re=>re.$id===Y)).forEach(Y=>{z.push({...O,$id:Y,$bzId:O.$tempId||`T_${uuid.v4()}`});}):te.length===_.length&&!z.find(Z=>Z.$id===W)&&(_.forEach(Z=>{let Y=`${c(O.$objectPath)}.${W}${jt}${Z}`,{$ids:re}=f[Y],gn=O[Z].find(ke=>!ke.$id),Bn=[...re.map(ke=>({...gn,$id:ke,$objectPath:{beforePath:O.$objectPath,ids:ke,key:Z}})),...O[Z].filter(ke=>ke.$id)];O[Z]=Bn;}),z.push({...O,$id:W,$bzId:O.$tempId||`T_${uuid.v4()}`}));});}else z.push(O);}),z.forEach(O=>{P.push(O);});}),[...P,...S,...q].filter(U=>o(U).length>0?!0:U.$op!=="update").map(U=>{let ee={...U};return o(ee,!0).forEach(z=>{let O=Array.isArray(ee[z])?ee[z]:[ee[z]],_=Q(O);ee[z]=_;}),ee})};return Q(E)})(Array.isArray(w)?w:[w]),D=E=>E.map(Q=>{let b=o(Q,!0),F={...Q};return b.forEach(T=>{let S=Array.isArray(Q[T])?Q[T]:[Q[T]],q=[],k=[],P=[],J={},le=ct(t,Q,T);S.filter(I=>I).forEach(I=>{I.$op==="replace"&&I.$id?(J=I,Array.isArray(I.$id)?k=[...k,...I.$id]:k.push(I.$id)):I.$op==="create"&&le==="ONE"&&I.id?(J=I,Array.isArray(I.id)?P=[...k,...I.id]:P.push(I.id)):q.push(I);});let Me=c(J.$objectPath),ee=a(Me).map(I=>f[I]),z=[];ee.filter(I=>I!=null).forEach(I=>{z=[...z,...I.$ids];});let O=z.filter(I=>!k.includes(I)),_=k.filter(I=>!z.includes(I)),ie=Ee(J);O.length>0&&q.push({...J,$op:"unlink",$id:O,$bzId:J.$tempId||`T4_${uuid.v4()}`,id:void 0,...ie}),_.length>0&&_.forEach(I=>{q.push({...J,$op:"link",$id:I,$bzId:J.$tempId||`T5_${uuid.v4()}`,...ie});}),P.length>0&&P.forEach(I=>{q.push({...J,$op:"create",id:I,$bzId:J.$tempId||`T6_${uuid.v4()}`,...ie});}),F[T]=D(q);}),F}),A=$(D($(L)));(E=>immer.produce(E,Q=>objectTraversal.traverse(Q,b=>{let{key:F,value:T,parent:S}=b;F&&S&&!F?.includes("$")&&(Array.isArray(T)||radash.isObject(T))&&!Array.isArray(S)&&(Array.isArray(T)?T:[T]).forEach(k=>{let P=k.$filter?{...k.$objectPath,key:k.$filterBzId}:k.$objectPath,J=c(P),le=f[J],Me=(z,O)=>z.every(_=>O.includes(_)),U=k.$id?Array.isArray(k.$id)?Me(k.$id,le?le.$ids:[]):le?.$ids.includes(k.$id):le,ee=ct(t,S,k.$objectPath.key);if(k.$op==="link"&&U&&ee==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${c(k.$objectPath)}" because it is already occupied.`);if(k.$op)switch(k.$op){case"delete":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${k.$id}" because it is not linked to $id:"${S.$id}"`);break;case"update":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${k.$id}" because it is not linked to $id:"${S.$id}"`);break;case"unlink":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${k.$id}" because it is not linked to $id:"${S.$id}"`);break;case"link":if(U)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${k.$id}" because it is already linked to $id:"${S.$id}"`);break;}});})))(A);let N=(E=>immer.produce(E,Q=>objectTraversal.traverse(Q,b=>{let{value:F,meta:T}=b;radash.isObject(F)&&(F[Symbol.for("path")]=T.nodePath,delete F.$objectPath,delete F.$parentIsCreate);})))(A);return [...Array.isArray(N)?N:[N]].sort((E,Q)=>E.$op==="create"&&Q.$op!=="create"?-1:E.$op!=="create"&&Q.$op==="create"?1:0)};var on=(e,t)=>immer.produce(e,i=>rt(t,i)),rt=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){t.forEach(o=>rt(e,o,r));return}let i=G(e,r||t.$entity||t.$relation||t.$thing);Object.entries(t).forEach(([o])=>{o.startsWith("$")||eo(e,t,o,i);});},eo=(e,t,r,i)=>{let o=t[r];if(!o)return;let n=i.dataFields?.find(s=>s.path===r);if(n){n.contentType==="JSON"&&o!=null&&(t[r]=JSON.stringify(o));return}let l=i.linkFields?.find(s=>s.path===r);if(l){let s=l.oppositeLinkFieldsPlayedBy[0]?.thing;rt(e,o,s);return}if(i.thingType==="relation"){let s=i.roles[r],[h]=s.playedBy||[];if(!h)throw new Error(`Role ${s.name} in ${i} is not played by anything`);rt(e,o,h.thing);}};var cn=async(e,t,r,i)=>{let o=Array.isArray(e)?e:[e],n=o.map(h=>Nt(h,!0)),s=(await qe(n,t,r,i)).bql.res;return o.map((h,p)=>{let d=G(t,h.$thing);return hn({mut:h,node:s[p],schema:t,thing:d})})},dn=new Set(["$op","$bzId","$parentKey"]),ro=new Set(["$relation","$entity","$id",...dn]),Nt=(e,t)=>{let r={};e.$fields?.forEach(o=>{typeof o=="string"?r[o]=o:r[o.$path]=o;});let i={};for(let o in e){if(dn.has(o)||ro.has(o)&&!t)continue;let n=e[o];o.startsWith("$")?i[o]=n:Array.isArray(n)?n[0]&&typeof n[0]=="object"&&(r[o]={$path:o,...Nt(n[0],!1)}):radash.isObject(n)&&(r[o]={$path:o,...Nt(n,!1)});}return i.$fields=Object.values(r),i},hn=e=>{let{mut:t,node:r,schema:i,thing:o}=e,n=pn(o),l=io(r);if(Array.isArray(t))return t.map(h=>{let p=l[h.$id];return p?sn({mut:h,node:p,schema:i,thing:o,...n}):h});let s=l[t.$id];return sn({mut:t,node:s,schema:i,thing:o,...n})},sn=e=>{let{mut:t,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:l,roleFieldMap:s}=e,{$fields:h,...p}=t;if(!r)return p;let d=un({$fields:t.$fields,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:l,roleFieldMap:s}),c={...p,[De]:d};for(let a in t){if(a.startsWith("$"))continue;let f=t[a];if(n[a]||!f||typeof f!="object"){c[a]=f;continue}let $=l[a]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||s[a]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${o.name}" does not have field "${a}"`);let y=G(i,$);c[a]=hn({mut:f,schema:i,node:r[a],thing:y});}return c},un=e=>{let{$fields:t,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:l,roleFieldMap:s}=e,h=t||no(o),p={$id:r.$id};return h.forEach(d=>{let c=typeof d!="string",a=c?d.$path:d,f=r[a];if(n[a]){p[a]=f;return}let $=l[a]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||s[a]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${o.name}" does not have field "${a}"`);if(!c){f&&(p[a]=Array.isArray(f)?f.map(an):an(f));return}let y=G(i,$),m=pn(y);p[a]=Array.isArray(f)?f.map(B=>ln({...m,$fields:d.$fields,value:B,schema:i,thing:y})):ln({...m,$fields:d.$fields,value:f,schema:i,thing:y});}),p},no=e=>{let t=[];return e.dataFields?.forEach(r=>{t.push(r.path);}),e.linkFields?.forEach(r=>{t.push(r.path);}),e.thingType==="relation"&&t.push(...Object.keys(e.roles)),t},an=e=>{if(typeof e=="string")return e;if(!e||typeof e!="object")throw new Error(`"${JSON.stringify(e)}" is neither an id nor an object with prop "$id"`);if(typeof e.$id!="string")throw new Error(`"${JSON.stringify(e)}" is does not have prop "$id"`);return e.$id},ln=e=>{let{value:t}=e;if(!t||typeof t!="object"||!t.$id)throw new Error(`"${JSON.stringify(e)}" is neither an id nor an object with prop "$id"`);return un({...e,node:t})},pn=e=>{let t=Object.fromEntries(e.dataFields?.map(o=>[o.path,o])||[]),r=Object.fromEntries(e.linkFields?.map(o=>[o.path,o])||[]),i=e.thingType==="relation"?e.roles||{}:{};return {dataFieldMap:t,linkFieldMap:r,roleFieldMap:i}},io=e=>{if(!Array.isArray(e))return e&&typeof e=="object"&&e.$id?{[e.$id]:e}:{};let t={};return e.forEach(r=>{!r||typeof r!="object"||!r.$id||(t[r.$id]=r);}),t};var fn=he,Pe=(e,t)=>t.data?{...e,bql:{...e.bql,current:t.data}}:e,oo=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),so=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),ao=(e,t)=>({...e,typeDB:{...e.typeDB,tqlMutation:t.data}}),lo=(e,t)=>({...e,typeDB:{...e.typeDB,tqlRes:t.data}}),co=async e=>Object.keys(e.bql.current).length?ft(e.bql.current,e.schema,e.config):ft(e.bql.raw,e.schema,e.config),ho=async e=>nn(e.bql.current,e.schema,e.config,e.handles),uo=async e=>cn(e.bql.current,e.schema,e.config,e.handles),po=async e=>Er(e.bql.current,e.schema),fo=async e=>Fr(e.bql.things,e.bql.edges,e.schema),$o=async e=>fr(e.typeDB.tqlMutation,e.handles,e.config),mo=async e=>$r(e.typeDB.tqlRes,e.bql.things,e.bql.edges,e.schema,e.config),yo=()=>!0,go=e=>Ie(e.bql.current),we=H("error","error",V((e,t)=>({...e,error:t.error}))),Bo=be("stringify",{stringify:v(async e=>on(e.bql.raw,e.schema),H("done","enrich",V(Pe)),we),enrich:v(co,H("done","preQuery",mt(yo),V(Pe)),H("done","parseBQL",V(Pe)),we),preHookDependencies:v(uo,H("done","enrich",V(Pe)),we),preQuery:v(ho,H("done","preHookDependencies",mt(go),V(Pe)),H("done","parseBQL",V(Pe)),we),parseBQL:v(po,H("done","buildMutation",V(so)),we),buildMutation:v(fo,H("done","runMutation",V(ao)),we),runMutation:v($o,H("done","parseMutation",V(lo)),we),parseMutation:v(mo,H("done","success",V(oo)),we),success:fn(),error:fn()},e=>e),Eo=async e=>new Promise((t,r)=>{me(Bo,i=>{i.machine.state.name==="success"&&t(i.context),i.machine.state.name==="error"&&r(i.context);},e);}),$n=async(e,t,r,i)=>Eo({bql:{raw:e,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:t,config:r,handles:i,depthLevel:0,error:null});immer.enableMapSet();var Wt=class{schema;config;dbHandles;constructor({schema:t,config:r}){this.schema=t,this.config=r;}getDbHandles=()=>this.dbHandles;init=async()=>{let t={typeDB:new Map,surrealDB:new Map};await Promise.all(this.config.dbConnectors.map(async i=>{if(i.provider==="surrealDB"){let o=new surrealdb_node.Surreal;await o.connect(i.url),await o.signin({namespace:i.namespace,database:i.dbName,username:i.username,password:i.password}),t.surrealDB.set(i.id,{client:o});}if(i.provider==="typeDB"&&i.dbName){let[o,n]=await radash.tryit(typedbDriver.TypeDB.coreDriver)(i.url);if(o){let l=`[BORM:${i.provider}:${i.dbName}:core] ${o.message??"Can't create TypeDB Client"}`;throw new Error(l)}try{let l=await n.session(i.dbName,typedbDriver.SessionType.DATA);t.typeDB.set(i.id,{client:n,session:l});}catch(l){let s=`[BORM:${i.provider}:${i.dbName}:session] ${(l.messageTemplate?._messageBody()||l.message)??"Can't create TypeDB Session"}`;throw new Error(s)}}if(i.provider==="typeDBCluster"&&i.dbName){let o=new typedbDriver.TypeDBCredential(i.username,i.password,i.tlsRootCAPath),[n,l]=await radash.tryit(typedbDriver.TypeDB.cloudDriver)(i.addresses,o);if(n){let s=`[BORM:${i.provider}:${i.dbName}:core] ${n.message??"Can't create TypeDB Cluster Client"}`;throw new Error(s)}try{let s=await l.session(i.dbName,typedbDriver.SessionType.DATA);t.typeDB.set(i.id,{client:l,session:s});}catch(s){let h=`[BORM:${i.provider}:${i.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(h)}}}));let r=Yt(this.schema,t);this.schema=r,this.dbHandles=t;};#e=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#e(),this.schema);define=async()=>(await this.#e(),_t(this.config,this.schema,this.dbHandles));query=async(t,r)=>{await this.#e();let i={...this.config,query:{...it.query,...this.config.query,...r}},o=Array.isArray(t),n=o?t:[t],[l,s]=await radash.tryit(qe)(n,this.schema,i,this.dbHandles);if(l){let p=new Error(l.error);throw p.stack=l.error.stack,p}let h=s.bql.res;return o?h:h[0]};mutate=async(t,r)=>{await this.#e();let i={...this.config,mutation:{...it.mutation,...this.config.mutation,...r}},[o,n]=await radash.tryit($n)(t,this.schema,i,this.dbHandles);if(o){let s=new Error(o.error.message);throw s.stack=o.error.stack,s}return n.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:r})=>{r.isOpen()&&await r.close(),await t.close();});}},Fc=Wt;//! Todo: delete when this works with the new $thing and $thingType fields
38
+ ${y}`})(),n=e.dbConnectors[0].id,l=r.typeDB.get(n)?.session,s=r.typeDB.get(n)?.client;if(!l){console.log("Session Status: ","NO SESSION");return}await l.close();let[{dbName:u}]=e.dbConnectors;await(await s.databases.get(u)).delete(),await s.databases.create(u);let c=await s.session(e.dbConnectors[0].dbName,typedbDriver.SessionType.SCHEMA),d=await c.transaction(typedbDriver.TransactionType.WRITE);await d.query.define(o),await d.commit(),await d.close();let a=await c.transaction(typedbDriver.TransactionType.READ);(await(await a.query.match("match $a sub thing;")).collect()).forEach(async y=>{y.get("a");}),await a.close();};var ae=Symbol.for("queryPath"),We=Symbol.for("stepPrint"),Qe=Symbol.for("edgeType"),Be=Symbol.for("edgeSchema"),De=Symbol.for("dbNode"),ot=Symbol.for("isTransformed"),le=Symbol.for("fieldSchema"),$e=Symbol.for("sharedMetadata"),Te=Symbol.for("suqlMetadata");var Ht={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var Kt=({linkField:e,originalRelation:t,withExtensionsSchema:r})=>{if(e.isVirtual)return `$this.${e.path}.id`;let i=r.relations[e.relation].subTypes||[],o=[e.relation,...i],n=`<-\`${t}_${e.plays}\`<-(\`${o.join("`,`")}\`)`;if(e.target==="relation")return n;if(e.target==="role"){let[l]=e.oppositeLinkFieldsPlayedBy,s=r.entities[l.thing]?.subTypes||r.relations[l.thing]?.subTypes||[],u=[l.thing,...s],f=`->\`${t}_${l.plays}\`->(\`${u.join("`,`")}\`)`;return `${n}${f}`}else throw new Error("Unsupported linkField target")};var Zt=(e,t,r)=>r?t:`${e}\xB7${t}`;var Xt=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))))[0],xe=(e,t)=>Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))),vt=(e,t)=>{let r=[],i=immer.produce(e,n=>objectTraversal.traverse(n,({key:l,value:s,meta:u})=>{if(u.depth===2&&(l&&(s.dataFields=s.dataFields?.map(f=>({...f,cardinality:f.cardinality||"ONE",dbPath:Zt(l,f.path,f.shared)}))),s.extends)){if(!s.defaultDBConnector.as)throw new Error(`[Schema] ${l} is extending a thing but missing the "as" property in its defaultDBConnector`);let f=n.entities[s.extends]||n.relations[s.extends],c=[s.extends,...f.allExtends||[]];if(s.allExtends=c,c.forEach(d=>{if(n.entities[d])n.entities[d].subTypes=[l,...n.entities[d].subTypes||[]];else if(n.relations[d])n.relations[d].subTypes=[l,...n.relations[d].subTypes||[]];else throw new Error(`[Schema] ${l} is extending a thing that does not exist in the schema: ${d}`)}),s.idFields=f.idFields?Array.from(new Set((s.idFields||[]).concat(f.idFields))):s.idFields,s.dataFields=f.dataFields?(s.dataFields||[]).concat(f.dataFields.map(d=>{let a=s.extends,p=e.entities[a]||e.relations[a];for(;!p.dataFields?.find(h=>h.path===d.path);)a="extends"in p?p.extends:void 0,p=e.entities[a]||e.relations[a];return {...d,dbPath:Zt(a,d.path,d.shared),[$e]:{inheritanceOrigin:d[$e]?.inheritanceOrigin||s.extends}}})):s.dataFields,"roles"in f){let d=s,a=f;if(a.roles){let p=radash.mapEntries(a.roles,(h,$)=>[h,{...$,[$e]:{inheritanceOrigin:$[$e]?.inheritanceOrigin||s.extends}}]);d.roles={...d.roles||{},...p};}}s.linkFields=f.linkFields?(s.linkFields||[]).concat(f.linkFields.map(d=>({...d,[$e]:{inheritanceOrigin:d[$e]?.inheritanceOrigin||s.extends}}))):s.linkFields,f?.hooks?.pre&&(s.hooks=s.hooks||{},s.hooks.pre=s.hooks.pre||[],s.hooks.pre=[...f?.hooks?.pre||[],...s?.hooks?.pre||[]]);}},{traversalType:"breadth-first"}));return objectTraversal.traverse(e,({key:n,value:l,meta:s})=>{if(n==="linkFields"){let f=(()=>{if(!s.nodePath)throw new Error("No path");let[d,a]=s.nodePath.split(".");return {thing:a,thingType:d==="entities"?"entity":d==="relations"?"relation":""}})(),c=Array.isArray(l)?l.map(d=>({...d,...f})):[{...l,...f}];r.push(...c);}}),immer.produce(i,n=>objectTraversal.traverse(n,({value:l,key:s,meta:u})=>{if(u.depth===2&&l.idFields&&!l.id){l.name=s;let f=()=>{if(u.nodePath?.split(".")[0]==="entities")return "entity";if(u.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};l.thingType=f();let c=Object.keys(t).find(d=>t[d]?.get(l.defaultDBConnector.id));if(l.db=c,l.dbContext=Ht[c],l.computedFields=[],l.virtualFields=[],l.requiredFields=[],l.enumFields=[],l.fnValidatedFields=[],"roles"in l&&Object.entries(l.roles).forEach(([a,p])=>{p.fieldType="roleField";let h=r.filter(M=>M.relation===s&&M.plays===a)||[];p.playedBy=h,p.name=a;let $=[...new Set(h.map(M=>M.thing))];p.$things=$;let y=p[$e]?.inheritanceOrigin||l.name;if($.length>1)throw new Error(`Not supported yet: Role ${a} in ${l.name} is played by multiple things: ${$.join(", ")}`);let m=$.flatMap(M=>{let L=v(e,M)?.subTypes||[];return [M,...L]}),B=`->\`${y}_${a}\`->(\`${m.join("`,`")}\`)`;p[Te]={queryPath:B};}),"linkFields"in l&&l.linkFields){let d=l;d.linkFields?.forEach(a=>{a.fieldType="linkField";let p=i.relations[a.relation];if(p.roles?.[a.plays]===void 0)throw new Error(`The role ${a.plays} is not defined in the relation ${a.relation} (linkField: ${a.path})`);if(a.target==="relation"&&(a.$things=[a.relation],a.oppositeLinkFieldsPlayedBy=[{plays:a.path,thing:a.relation,thingType:"relation"}]),a.target==="role"){let y=r.filter(m=>m.relation===a.relation&&m.plays!==a.plays)||[];if(a.oppositeLinkFieldsPlayedBy=y,a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter(m=>m.target==="role"),a.$things=a.oppositeLinkFieldsPlayedBy.map(m=>m.thing),a.oppositeLinkFieldsPlayedBy.length>1)throw new Error(`Not supported: LinkField ${a.path} in ${d.name} has multiple candidates ${a.oppositeLinkFieldsPlayedBy.map(m=>m.thing).join(",")} and this is not yet supported. Please target a single one using targetRoles with a single role`)}let h=p.roles?.[a.plays][$e]?.inheritanceOrigin??a.relation,$=Kt({linkField:a,originalRelation:h,withExtensionsSchema:i});a[Te]={queryPath:$};});}}if(typeof l=="object"&&"playedBy"in l){let f=[...new Set(l.playedBy.map(c=>c.thing))];if(f.length>1)throw new Error(`[Schema] roleFields can be only played by one thing. Role: ${s}, path:${u.nodePath}, played by: ${f.join(", ")}`);if(l.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${s}, path:${u.nodePath}`)}if(u.depth===4){let[f,c]=u.nodePath?.split(".")||[],d=n[f][c];!radash.isArray(l)&&typeof l=="object"&&(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));}}))},v=(e,t)=>{if(t in e.entities)return e.entities[t];if(t in e.relations)return e.relations[t];throw new Error(`${t} is not defined in the schema`)},x=(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)}`)},_e=(e,t)=>{let r=e.dataFields?.find(n=>n.path===t);if(r)return ["dataField",r];let i=e.linkFields?.find(n=>n.path===t);if(i)return ["linkField",i];let o="roles"in e?e.roles[t]:void 0;if(o)return ["roleField",o];throw new Error(`Field ${t} not found in schema, Defined in $filter`)},Ve=(e,t)=>{let r=x(e,t);if(r?.idFields?.length&&r?.idFields?.length>1)throw new Error(`Multiple ids not yet enabled / composite ids: ${r?.idFields}`);let[i]=r.idFields;return i},Gt=(e,t)=>{let r=e.$thing||e.$entity||e.$relation;if(!r)throw new Error("[Internal] No thing found");if(e.$entity)return "entity";if(e.$relation)return "relation";if(t.entities[r])return "entity";if(t.relations[r])return "relation";throw new Error("No thing found")},lt=(e,t,r)=>{let i=x(e,t),o=i.linkFields?.find(s=>s.path===r);if(o)return o;let n=i.dataFields?.find(s=>s.path===r);if(n)return n;let l="roles"in i?i.roles?.[r]:void 0;if(l)return l;throw new Error(`Field ${r} not found in schema`)},ct=(e,t,r)=>lt(e,t,r)?.cardinality,ue=(e,t)=>{let r=e.dataFields?.map(h=>h.path)||[],i=e.linkFields?.map(h=>h.path)||[],o="roles"in e?radash.listify(e.roles,h=>h):[],n=[...r||[],...i||[],...o||[]],s=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...n];if(!t)return {fields:n,dataFields:r,roleFields:o,linkFields:i};let u=t.$fields?t.$fields.map(h=>{if(typeof h=="string"){if(h.startsWith("$")||h.startsWith("%"))return;if(!n.includes(h))throw new Error(`Field ${h} not found in the schema`);return h}if("$path"in h&&typeof h.$path=="string")return h.$path;throw new Error("[Wrong format] Wrongly structured query")}):radash.listify(t,h=>{if(!(h.startsWith("$")||h.startsWith("%"))){if(!n.includes(h))throw new Error(`[Schema] Field ${h} not found in the schema`);return h}}).filter(h=>h!==void 0),f=t.$filter?radash.listify(t.$filter,h=>h.toString().startsWith("$")?void 0:h.toString()).filter(h=>h&&r?.includes(h)):[],c=t.$filter?radash.listify(t.$filter,h=>h.toString().startsWith("$")?void 0:h.toString()).filter(h=>h&&[...o||[],...i||[]].includes(h)):[],d=[...u,...f].filter(h=>!h?.startsWith("%")).filter(h=>!s.includes(h)).filter(h=>h),a=t.$filter?xe(t.$filter,(h,$)=>f.includes(h)):{},p=t.$filter?xe(t.$filter,(h,$)=>c.includes(h)):{};return {fields:n,dataFields:r,roleFields:o,linkFields:i,usedFields:u,usedLinkFields:i.filter(h=>u.includes(h)),usedRoleFields:o.filter(h=>u.includes(h)),usedDataFields:r.filter(h=>u.includes(h)),unidentifiedFields:d,...f.length?{localFilters:a}:{},...c.length?{nestedFilters:p}:{}}};var er=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},tr=(e,t,r)=>{let o=(r.nodePath||"").split("."),n=radash.isArray(t)?o.slice(0,-2).join("."):o.slice(0,-1).join(".");return t?objectTraversal.getNodeByPath(e,n):{}},Ee=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var He=e=>radash.isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),pe=e=>{if(Array.isArray(e))return e.map(t=>immer.current(t));if(e&&typeof e=="object"){let t=immer.isDraft(e)?immer.current(e):e,r={};return Object.entries(t).forEach(([i,o])=>{r[i]=immer.isDraft(o)?immer.current(o):o;}),r}else return e},oe=(e,t)=>{if(e===void 0)throw new Error("Value is undefined");return e},w=(e,t)=>{let r="";for(let i=0;i<t;i++)r+=" ";return `${r}${e}`};var Re=(e,t)=>{if(t.fieldType==="linkField"){let r=t.oppositeLinkFieldsPlayedBy;if(r?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!r?.length)throw new Error(`[Internal] Field ${e} should have a player`);return r}else if(t.fieldType==="roleField"){if([...new Set(t.playedBy?.map(r=>r.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 rr=(e,t,r)=>{let i=radash.isArray(e[t])?e[t]:[e[t]];if(!i.every(o=>typeof o=="object"))if(i.every(o=>typeof o=="string")){let o=Re(t,r),[n]=o,l=e.$op==="create"?"link":"replace",s=n.thing,u=n.thingType;if(i.some(f=>f.startsWith("_:")))throw new Error("[Not supported] At least one child of a replace is a tempId");e[t]={$id:e[t],$op:l,$thing:s,$thingType:u,$bzId:`S_${uuid.v4()}`};}else throw new Error(`[Mutation Error] Replace can only be used with a single id or an array of ids. (Field: ${t} Nodes: ${JSON.stringify(i)} Parent: ${JSON.stringify(e,null,2)})`)};var Le=(e,t,r)=>{let i=x(r,t),{usedDataFields:o}=ue(i,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"&&o.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&o.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var Ke=(e,t,r)=>{let i=x(r,t),{usedFields:o}=ue(i,t);return t.$op?(Le(e,t,r),t.$op):t.$id||t.$filter?o.length>0?(Le(e,{...t,$op:"update"},r),"update"):(Le(e,{...t,$op:"link"},r),"link"):t.$tempId?o.length>0?(Le(e,{...t,$op:"create"},r),"create"):(Le(e,{...t,$op:"create"},r),"link"):(Le(e,{...t,$op:"create"},r),"create")};var ir=(e,t)=>{let i=(radash.isArray(e.$root)?e.$root:[e.$root]).map(o=>{let n=Ke(o,o,t);return {...{...o.$thing?{}:{$thing:o.$entity||o.$relation},...o.$thingType?{}:{$thingType:Gt(o,t)},...o.$op?{}:{$op:n},...o.$bzId?{}:{$bzId:`R_${uuid.v4()}`}},...o}});e.$root=radash.isArray(e.$root)?i:i[0];};var Ue=(e,t)=>{let r=t[We];return types.isSet(r)?r.has("clean")?(Reflect.set(t,We,r.add("clean")),!0):!1:(Reflect.set(t,We,new Set(["clean"])),!0)};var or=(e,t,r)=>{if(Ue("split_ids",e)){let i=(radash.isArray(e[t])?e[t]:[e[t]]).flatMap(o=>{if(radash.isObject(o)&&"$id"in o&&radash.isArray(o.$id)){let n=o;if(x(r,n),!n.$bzId)throw new Error("[Internal Error] No bzId found");return n.$id.map((l,s)=>({...pe(n),$id:l,$bzId:`${n.$bzId}_${s}`,...Ee(n)}))}return o});(i.length>radash.isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=i);}};var ar=(e,t,r,i)=>{let o=(radash.isArray(e[t])?e[t]:[e[t]]).map(n=>{let l=Re(t,r),[s]=l,u=Ke(e,{...n,$thing:s.thing,$thingType:s.thingType},i),f=n.$bzId?n.$bzId:n.$tempId?n.$tempId:`N_${uuid.v4()}`;if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);return {...n,[Be]:r,$thing:s.thing,$thingType:s.thingType,$op:u,$bzId:f}});e[t]=radash.isArray(e[t])?o:o[0];};var Cn=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,On=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,lr=e=>{let r=e.toString().replace(Cn,"").trim().split("=>")[0].split("{")[0].replace(On,"").trim(),i=r.substring(r.indexOf("(")+1,r.lastIndexOf(")")).trim();return i?(i.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(n=>n.includes("{")&&n.includes("}")?(n.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(s=>s.split(":")[0].trim().replace(/['"[\]]/g,"")):n.trim()).filter(Boolean):[]};var Ae=({currentThing:e,fieldSchema:t,mandatoryDependencies:r=!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(r){let{fn:o}=t.default,l=lr(o).filter(s=>!(s in e));if(l.length)throw new Error(`Virtual field: Missing arguments ${l.join(", ")}`)}if(!t.default.fn)throw new Error("[Schema] No fn in default field schema");return "default"in t?t.default?.fn(e):void 0};var cr=(e,t,r)=>{let i=e[t];i&&(radash.isArray(i)?i:[i]).forEach(o=>{let n=x(r,o),{unidentifiedFields:l}=ue(n,o),{computedFields:s,virtualFields:u}=n,f=radash.listify(o,(a,p)=>p!==void 0?a:void 0),c=f.filter(a=>u?.includes(a));if(c.length>0)throw new Error(`Virtual fields can't be sent to DB: "${c.join(",")}"`);if(s.filter(a=>!f.includes(a)).forEach(a=>{let p=n.dataFields?.find(B=>B.path===a),$=n.linkFields?.find(B=>B.path===a)?.oppositeLinkFieldsPlayedBy[0],y="roles"in n?Xt(n.roles,(B,M)=>B===a):void 0,m=p||$||y;if(!m)throw new Error(`no field Def for ${a}`);if(o.$op==="create"&&!o[a]){let B=Ae({currentThing:o,fieldSchema:m,mandatoryDependencies:!0});o[a]=B;}}),l.length>0)throw new Error(`Unknown fields: [${l.join(",")}] in ${JSON.stringify(o)}`)});};var Je=(e,t)=>{let r=x(t,e).hooks;if(r?.pre){let i=`on${er(e.$op)}`;return r.pre.filter(l=>!l.triggers||l.triggers[i]?.()).flatMap(l=>l.actions)}return []};var hr=(e,t,r,i)=>{(radash.isArray(e[t])?e[t]:[e[t]]).forEach(n=>{if("$thing"in n){if(n.$fields)return n;let{requiredFields:l,enumFields:s,fnValidatedFields:u,dataFields:f}=x(r,n);if("$op"in n&&n.$op==="create"&&l.forEach(c=>{if(!(c in n))throw new Error(`[Validations] Required field "${c}" is missing.`)}),("$op"in n&&n.$op==="update"||n.$op==="create")&&s.forEach(c=>{if(c in n){let d=f?.find(a=>a.path===c)?.validations?.enum;if(!d)throw new Error(`[Validations] Enum field "${c}" is missing enum options.`);if(radash.isArray(n[c]))n[c].some(a=>{if(!d.includes(a))throw new Error(`[Validations] Option "${a}" is not a valid option for field "${c}".`)});else if(d&&!d.includes(n[c]))throw new Error(`[Validations] Option "${n[c]}" is not a valid option for field "${c}".`)}}),("$op"in n&&n.$op==="update"||n.$op==="create")&&u.forEach(c=>{if(c in n)try{let d=f?.find(a=>a.path===c)?.validations?.fn;if(!d)throw new Error("Missing validation function.");if(!d(n[c]))throw new Error("Failed validation function.")}catch(d){throw new Error(`[Validations:attribute:${c}] ${d.message}`)}}),radash.isObject(n)&&"$thing"in n){let c=n.$thing,d=n,a=radash.clone(pe(e)),p=radash.clone(pe(d)),h=i.mutation?.context||{},$=radash.clone(pe(n[De]||{}));Je(d,r).forEach(m=>{if(m.type==="validate"){if(m.severity!=="error")return;try{let B=m.fn(p,a,h,$);if(B===!1)throw new Error(`${m.message}.`);if(B!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(B){throw new Error(`[Validations:thing:${c}] ${B.message}`)}}});}}});};var pr=(e,t,r,i)=>{let o=(radash.isArray(e[t])?e[t]:[e[t]]).map(n=>{if(He(n)){if(n.$fields||n[ot])return n;let l=Je(n,r).filter(d=>d.type==="transform"),s=radash.clone(pe(e)),u=radash.clone(pe(n)),f=i.mutation?.context||{},c=radash.clone(pe(n[De]||n.$dbNode));return l.forEach(d=>{let a=d.fn(u,s,f,c||{});Object.keys(a).length!==0&&(n={...u,...a,...Ee(n),[ot]:!0});}),n}});e[t]=radash.isArray(e[t])?o:o[0];};var fr=(e,t,r)=>{let i=Re(t,r),[o]=i;e[t]={$thing:o.thing,$thingType:o.thingType,$op:"unlink",$bzId:`U_${uuid.v4()}`,[Be]:r};};var Ie=e=>{if(Array.isArray(e)){for(let t of e)if(Ie(t))return !0;return !1}if(e.$fields)return !0;for(let t in e){if(t.startsWith("$"))continue;let r=e[t];if(r&&typeof r=="object"&&Ie(e[t]))return !0}return !1};var Hn=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(Ue("set_tempId",e))if(e.$tempId?.startsWith("_:")){let r=e.$tempId.substring(2);e.$tempId=r,e.$bzId=r;}else throw new Error('[Wrong format] TempIds must start with "_:"');else throw new Error("[Internal] TempId already modified")},Kn=(e,t)=>{},ft=(e,t,r)=>{let i={$rootWrap:{$root:e}},o=Ie(Array.isArray(e)?e:[e]),n=immer.produce(i,l=>objectTraversal.traverse(l,({value:s,parent:u,key:f,meta:c})=>{if(!(!u||!f)&&radash.isObject(s)){let d=c.nodePath?.split(".")||[];if(!("$root"in s)){if(!("$thing"in s||"$entity"in s||"$relation"in s)){let h=["$fields","$dbNode","$filter"],$=d[d.length-1],y=d[d.length-2];if(f==="$root")throw new Error("Root things must specify $entity or $relation");if(!h.includes($)&&!h.includes(y))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(immer.isDraft(s)?immer.current(s):s)}`)}}let a=s,p=d.includes("$filter");Object.keys(a).forEach(h=>{if(Hn(a,h),h!=="$root"&&p||h!=="$root"&&(h.startsWith("$")||h.startsWith("%")))return;let $=h!=="$root"?lt(t,a,h):{fieldType:"rootField"};if(!$)throw new Error(`[Internal] Field ${h} not found in schema`);if("contentType"in $)return Kn();if(["rootField","linkField","roleField"].includes($.fieldType)){if(["linkField","roleField"].includes($.fieldType)&&(a[h]===null?fr(a,h,$):rr(a,h,$)),$.fieldType==="rootField"){if(!("$root"in a))throw new Error(`[Internal] Field ${h} is a rootField but the object is not a root`);ir(a,t);}let y=radash.isArray(a[h])?a[h]:[a[h]],m=d.slice(1).join(".");y.forEach(M=>{if(M){if($?.cardinality==="ONE"&&!M.$op&&!M.$id&&!M.$filter&&!M.$tempId&&a.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${m}.${h}`);if(M.$tempId&&!(M.$op===void 0||M.$op==="link"||M.$op==="create"||M.$op==="update"))throw new Error(`Invalid op ${M.$op} for tempId. TempIds can be created, or when created in another part of the same mutation. In the future maybe we can use them to catch stuff in the DB as well and group them under the same tempId.`)}}),["linkField","roleField"].includes($.fieldType)&&ar(a,h,$,t),or(a,h,t),["rootField","linkField","roleField"].includes($.fieldType)&&cr(a,h,t),(radash.isArray(a[h])?a[h]:[a[h]]).forEach(M=>{let g=x(t,M),{unidentifiedFields:L,usedLinkFields:D,usedFields:A,fields:C}=ue(g,M);if(A.forEach(j=>{if(!C.includes(j))throw new Error(`[Schema] Field ${j} not found in the schema`)}),L.length>0)throw new Error(`Unknown fields: [${L.join(",")}] in ${JSON.stringify(s)}`);if(D.length>1){let j=g.linkFields?.filter(N=>D.includes(N.path));j?.some((N,se)=>j.some((K,R)=>{if(se!==R&&N.target!==K.target&&N.relation===K.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),o||(pr(a,h,t,r),hr(a,h,t,r));}});}}));return radash.isArray(n.$rootWrap.$root),n.$rootWrap.$root};var Ze=async(e,t)=>{let r=t.dbConnectors[0].id,i=e.typeDB?.get(r)?.session,o=e.typeDB?.get(r)?.client;if(!i||!i.isOpen()){if(!o)throw new Error("Client not found");i=await o.session(t.dbConnectors[0].dbName,typedbDriver.SessionType.DATA),e.typeDB?.set(r,{client:o,session:i});}return {client:o,session:i}};var $r=async(e,t,r)=>{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:i}=await Ze(t,r),o=await i.transaction(typedbDriver.TransactionType.WRITE),n=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,l=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;try{n&&await o.query.delete(n);let s=l&&o.query.insert(l),u=s?await s.collect():void 0;return await o.commit(),{insertions:u}}catch(s){throw new Error(`Transaction failed: ${s.message}`)}finally{await o.close();}};var mr=async(e,t,r,i,o)=>{let n=[...t,...r],l=n.map(s=>{let u=e.insertions?.find(d=>d.get(`${s.$bzId}`))?.get(`${s.$bzId}`),f=s.$thing||s.$relation||s.$entity,c=f?v(i,f):void 0;if(s.$op==="create"||s.$op==="update"||s.$op==="link"){if(s.$op!=="update"&&!u&&s.$id)return {$id:s.$id,$error:"Does not exist or it's not linked to the parent"};let d=u?.asThing().iid,a=Object.entries(s).filter(([h,$])=>!h.startsWith("$")).reduce((h,[$,y])=>{if(c?.dataFields?.find(B=>B.path===$)?.contentType==="JSON")return h[$]=JSON.parse(y),h;if(s.$thingType==="relation"){let B=n.filter(M=>M.$id&&M.$bzId===y);return B.length===1?(h[$]=B[0].$id,h):(h[$]=y,h)}return h[$]=y,h},{});if(o.mutation?.noMetadata)return a;let p=s.$tempId&&!s.$tempId.startsWith("_:")?{$tempId:`_:${s.$tempId}`}:{};return {$dbId:d,...s,...a,[s.path]:s.$id,...p}}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(l)};var yr=e=>{let t=({value:r})=>(r&&typeof r=="object"&&"$id"in r&&(Object.keys(r).filter(n=>n.startsWith("$")).forEach(n=>delete r[n]),Object.keys(r).filter(n=>typeof n=="symbol").forEach(n=>delete r[n])),r);return immer.produce(e,r=>objectTraversal.traverse(r,t))};var Fr=async(e,t)=>{let r=c=>{let d=[],a=[],p=m=>{if(m.$id)return m.$id;let B=x(t,m),{idFields:M}=B;if(!M)throw new Error(`no idFields: ${JSON.stringify(m)}`);let[g]=M;if(!g)throw new Error(`no idField: ${JSON.stringify(m)}`);let L=B.dataFields?.find(C=>C.path===g),D=Ae({currentThing:m,fieldSchema:L,mandatoryDependencies:!0}),A=m[g]||m.$id||D;if(!A)throw new Error(`no idValue: ${JSON.stringify(m)}`);return A},h=m=>{if(m.$op==="create"){let B=p(m);if(d.find(M=>M.$id===B&&M.$op==="create"))throw new Error(`Duplicate id ${B} for node ${JSON.stringify(m)}`);if(a.find(M=>M.$bzId===m.$bzId))throw new Error(`Duplicate $bzId ${m.$bzId} for node ${JSON.stringify(m)}`);d.push({...m,$id:B});return}m.$tempId&&m.$op==="match"||d.push(m);},$=m=>{if(m.$op==="create"){let B=p(m);if(d.find(M=>M.$id===B),a.find(M=>M.$bzId===m.$bzId))throw new Error(`Duplicate %bzId ${m.$bzIdd} for edge ${JSON.stringify(m)}`);a.push({...m,$id:B});return}a.push(m);};return objectTraversal.traverse(c,({value:m,parent:B,meta:M})=>{if(!radash.isObject(m))return;let g=m;if(g.$thing){if(!g.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(g)}`);if(!g.$bzId)throw new Error("[internal error] BzId not found");let L=x(t,g),{dataFields:D,roleFields:A,linkFields:C,usedFields:j}=ue(L,g),N=()=>{if(g.$op==="create"||g.$op==="delete")return g.$op;if(g.$op==="update"){let R=j.filter(b=>D?.includes(b)),E=j.filter(b=>A?.includes(b)),Q=j.filter(b=>C?.includes(b));if(R.length>0)return "update";if(E.length>0||Q.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(g)}`)}return "match"},se={...g.$id&&{$id:g.$id},...g.$tempId&&{$tempId:g.$tempId},...g.$filter&&{$filter:g.$filter},$thing:g.$thing,...g.$thingType&&{$thingType:g.$thingType},...radash.shake(radash.pick(g,D||[""])),$op:N(),$bzId:g.$bzId};h(se);let K=g[Be];if(K?.fieldType==="linkField"){if((g.$op==="link"||g.$op==="unlink")&&(g.$id||g.$filter)){if(g.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");d.push({...g,$op:"match"});}let R=K.relation===g.$thing,E=R?g.$bzId:`LT_${uuid.v4()}`,b=tr(c,B,M).$bzId;if(!b)throw new Error("No parent id found");let F=()=>{if(g.$op==="delete")return R?"match":"delete";if(g.$op==="unlink")return R?"unlink":"delete";if(g.$op==="link"||g.$op==="create")return R?"link":"create";if(g.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},T=x(t,{$thing:K.relation,$thingType:"relation"});if(!Object.keys(T.roles).includes(K.plays))throw new Error(`[Wrong format] Field ${K.plays} is not a role of relation ${K.relation}`);let O={$bzId:E,$thing:K.relation,$thingType:"relation",...g.$tempId?{$tempId:g.$tempId}:{},$op:F(),...R?{}:{[K.path]:g.$bzId},[K.plays]:b,[Be]:K,[Qe]:"linkField"};$(O),(g.$op==="unlink"||F()==="unlink")&&R&&$({$thing:K.relation,$thingType:"relation",$bzId:E,$op:"match",[K.plays]:b,[Be]:K,[Qe]:"linkField"});}if(g.$thingType==="relation"){let R=xe(g,(b,F)=>A.includes(b)),E=radash.mapEntries(R,(b,F)=>radash.isArray(F)?[b,F]:radash.isObject(F)?[b,F.$bzId]:[b,F]),Q=xe(m,(b,F)=>b.startsWith("$")||b.startsWith("Symbol"));if(Object.keys(R).filter(b=>!b.startsWith("$")).length>0){if(g.$op==="create"||g.$op==="delete"){let b=()=>{if(g.$op==="create")return "link";if(g.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},F=x(t,g).roles,T=radash.mapEntries(E,(O,k)=>{let P=F[O]?.cardinality;if(!P)throw new Error(`Role ${O} not found in schema`);if(Array.isArray(k)){if(P==="ONE"){if(k.length>1)throw new Error(`[Error] Role ${O} is not a MANY relation`);return [O,k[0].$bzId||k[0]]}return [O,k.map(J=>J.$bzId||J)]}return [O,k.$bzId||k]}),S={...Q,$thing:g.$thing,$thingType:"relation",$op:b(),...T,$bzId:g.$bzId,[Qe]:"roleField"};$(S);return}if(g.$op==="match"||g.$op==="update"&&Object.keys(R).length>0){let b=0;Object.entries(R).forEach(([F,T])=>{let S=radash.isArray(T)?T:[T],O=k=>k==="create"||k==="replace"?"link":k;S.forEach(k=>{if(!k)return;let P=O(k.$op);if(P==="replace")throw new Error("Not supported yet: replace on roleFields");if(P==="unlink"&&b>0)throw b+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let J={...Q,$thing:g.$thing,$thingType:"relation",$op:P==="delete"?"unlink":P,[F]:k.$bzId,$bzId:g.$bzId,[Qe]:"roleField"};$(J);});});}}}}}),[d,a]},[i,o]=r(e),n=i.reduce((c,d)=>{if(!d.$bzId)return [...c,d];let a=c.findIndex(p=>p.$bzId===d.$bzId);if(a===-1)return [...c,d];if(c[a].$op==="create"&&d.$op==="match")return c;if(c[a].$op==="match"&&(d.$op==="create"||d.$op==="match"))return [...c.slice(0,a),d,...c.slice(a+1)];throw new Error(`[Wrong format] Wrong operation combination for $tempId "${d.$tempId}". Existing: ${c[a].$op}. Current: ${d.$op}`)},[]),l=o.reduce((c,d)=>{let a=c.find(p=>(p.$id&&p.$id===d.$id||p.$bzId&&p.$bzId===d.$bzId)&&p.$thing===d.$thing&&p.$op===d.$op);if(a){let p={...a};return Object.keys(d).forEach($=>{if(typeof $=="symbol"||$.startsWith("$"))return;let y=a[$],m=d[$];Array.isArray(y)&&Array.isArray(m)?p[$]=Array.from(new Set([...y,...m])):!Array.isArray(y)&&Array.isArray(m)?y!==void 0?p[$]=Array.from(new Set([y,...m])):p[$]=m:Array.isArray(y)&&!Array.isArray(m)?m!==void 0&&(p[$]=Array.from(new Set([...y,m]))):y!==null&&m!==null&&y!==void 0&&m!==void 0?p[$]=Array.from(new Set([y,m])):y==null&&(p[$]=m);}),[...c.filter($=>!(($.$id&&$.$id===d.$id||$.$bzId&&$.$bzId===d.$bzId)&&$.$thing===d.$thing&&$.$op===d.$op)),p]}return [...c,d]},[]);n.forEach(c=>{if((c.$thingType==="relation"||"relation"in c)&&l.filter(d=>d.$bzId===c.$bzId||d.$tempId&&d.$tempId===c.$tempId).length===0){if(c.$op==="delete"||c.$op==="match"||c.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(yr(c))}`)}});let s=[...n,...l],u=new Set(s.filter(c=>c.$tempId).map(c=>c.$tempId)),f=Array.from(u).filter(c=>!s.some(d=>d.$tempId===c&&d.$op==="create"));if(f.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${f.join(", ")}`);return {mergedThings:n,mergedEdges:l}};var $t=e=>{if(radash.isDate(e))return {type:"datetime",value:e.toISOString().replace("Z","")};if(typeof e=="string")return {type:"string",value:`"${e}"`};if(typeof e=="number")return e%1!==0?{type:"double",value:e}:{type:"long",value:e};if(typeof e=="boolean")return {type:"boolean",value:e};throw new Error(`Unsupported type ${typeof e}`)};var wr=async(e,t,r)=>{let i=a=>{let p=a.$op,h=`$${a.$bzId}`,$=x(r,a),{idFields:y,defaultDBConnector:m}=$,B=m?.path||a.$thing,M=a.$id,g=y?.[0],L=radash.listify(a,(R,E)=>{if(R.startsWith("$")||R.startsWith("%")||R===g||E===void 0||E===null)return "";let Q=$.dataFields?.find(T=>T.path===R);if(!Q?.path)return "";let F=Q.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(Q.contentType))return `has ${F} '${E}'`;if(["NUMBER","BOOLEAN"].includes(Q.contentType))return `has ${F} ${E}`;if(Q.contentType==="DATE"){if(Number.isNaN(E.valueOf()))throw new Error("Invalid format, Nan Date");return E instanceof Date?`has ${F} ${E.toISOString().replace("Z","")}`:`has ${F} ${new Date(E).toISOString().replace("Z","")}`}if(Q.contentType==="FLEX"){let T=`bza${nanoid.nanoid()}`,S=radash.isArray(E)?E.map(O=>$t(O)):$t(E);if(Array.isArray(S))throw new Error("Array in FLEX fields not supported yet");return `has ${F} $${T}; $${T} '${T}' isa ${F}, has ${S.type}Attribute ${S.value}`}throw new Error(`Unsupported contentType ${Q.contentType}`)}).filter(R=>R),D=`${h}-atts`,A=radash.listify(a,R=>{if(R.startsWith("$")||R.startsWith("%")||R===g)return "";let E=$.dataFields?.find(F=>F.path===R);if(!E?.path)return "";let b=E.dbPath;return `{${D} isa ${b};}`}).filter(R=>R),C=radash.isArray(M)?`like '${M.join("|")}'`:`'${M}'`,j=M?[`has ${g} ${C}`]:[],N=[...j,...L].filter(R=>R).join(","),se=()=>{if(p==="delete"||p==="unlink"||p==="match")return `${h} isa ${[B,...j].filter(R=>R).join(",")};`;if(p==="update"){if(!A.length)throw new Error("update without attributes");return `${h} isa ${[B,...j].filter(R=>R).join(",")}, has ${D};
39
+ ${A.join(" or ")};`}return ""},K=()=>p==="update"||p==="link"||p==="match"?`${h} isa ${[B,...j].filter(R=>R).join(",")};`:"";if(He(a))return {op:p,deletionMatch:se(),insertionMatch:K(),insertion:p==="create"?`${h} isa ${[B,N].filter(R=>R).join(",")};`:p==="update"&&L.length?`${h} ${L.join(",")};`:"",deletion:p==="delete"?`${h} isa ${B};`:p==="update"&&A.length?`${h} has ${D};`:""};throw new Error("in attributes")},o=a=>{let p=a.$op,h=x(r,a),$=`$${a.$bzId}`,y=a.$id,m=h.defaultDBConnector?.path||a.$thing,B="roles"in h?radash.listify(h.roles,E=>E):[],M="roles"in h?radash.mapEntries(h.roles,(E,Q)=>[E,Q.dbConnector?.path||E]):{},g=radash.listify(a,(E,Q)=>{if(!B.includes(E))return null;if(!("roles"in h))throw new Error("This should have roles! ");let b=M[E];return Array.isArray(Q)?Q.map(F=>({path:b,id:F})):{path:b,id:Q}}).filter(E=>E).flat(),L=g.map(E=>{if(!E?.path)throw new Error("Object without path");return `${E.path}: $${E.id}`}),D=g.length>0?`( ${L.join(" , ")} )`:"",A=a[Qe];if(!A)throw new Error("[internal error] Symbol edgeType not defined");let C=D?`${$} ${D} ${A==="linkField"||p==="delete"||p==="unlink"?`isa ${m}`:""}`:"",j=`${$} ${A==="linkField"||p==="delete"?`isa ${m}`:""}`,N=()=>C?p==="link"?`${C};`:p==="create"?`${C}, has id '${y}';`:"":"",se=()=>C&&p==="match"?`${C};`:"",K=()=>C?p==="delete"?`${C};`:p==="match"?`${C};`:"":"",R=()=>C?p==="delete"?`${j};`:p==="unlink"?`${$} ${D};`:"":"";return {deletionMatch:K(),insertionMatch:se(),deletion:R(),insertion:N(),op:""}},n=(a,p)=>{let h=p==="edges"?o:i;if(Array.isArray(a))return a.map(g=>{let{preDeletionBatch:L,insertionMatch:D,deletionMatch:A,insertion:C,deletion:j}=h(g);return radash.shake({preDeletionBatch:L,insertionMatch:D,deletionMatch:A,insertion:C,deletion:j},N=>!N)}).filter(g=>g);let{preDeletionBatch:$,insertionMatch:y,deletionMatch:m,insertion:B,deletion:M}=h(a);return radash.shake({preDeletionBatch:$,insertionMatch:y,deletionMatch:m,insertion:B,deletion:M},g=>!g)},l=n(e),s=Array.isArray(l)?l:[l],u=n(t,"edges"),f=Array.isArray(u)?u:[u],c=[...s,...f];return radash.shake({insertionMatches:c.map(a=>a.insertionMatch).join(" ").trim(),deletionMatches:c.map(a=>a.deletionMatch).join(" ").trim(),insertions:c.map(a=>a.insertion).join(" ").trim(),deletions:c.map(a=>a.deletion).join(" ").trim()},a=>!a)};function G(e){return {enumerable:!0,value:e}}function Mr(e){return {enumerable:!0,writable:!0,value:e}}var Ce={},oi=()=>!0,Qr=()=>({}),Lr=e=>e,si=(e,t,r,i)=>e.apply(r,i)&&t.apply(r,i),ai=(e,t,r,[i,o])=>t.call(r,e.call(r,i,o),o),Fe=(e,t)=>Object.freeze(Object.create(e,t));function Tr(e,t,r){return e.reduce((i,o)=>function(...n){return r(i,o,this,n)},t)}function Sr(e){return Fe(this,{fn:G(e)})}var kr={},V=Sr.bind(kr);var Dr={},yt=Sr.bind(Dr);function Xe(e,t){return t.filter(r=>e.isPrototypeOf(r))}function Rr(e,t,...r){let i=Tr(Xe(Dr,r).map(n=>n.fn),oi,si),o=Tr(Xe(kr,r).map(n=>n.fn),Lr,ai);return Fe(this,{from:G(e),to:G(t),guards:G(i),reducers:G(o)})}var Ar={},Ir={},H=Rr.bind(Ar);Rr.bind(Ir,null);function li(e,t,r){return Bt(t,e,r,this.immediates)||e}function Cr(e){let t=new Map;for(let r of e)t.has(r.from)||t.set(r.from,[]),t.get(r.from).push(r);return t}var ci={enter:Lr};function he(...e){let t=Xe(Ar,e),r=Xe(Ir,e),i={final:G(e.length===0),transitions:G(Cr(t))};return r.length&&(i.immediates=G(r),i.enter=G(li)),Fe(ci,i)}var di={enter(e,t,r){let i=this.fn.call(t,t.context,r);return gt.isPrototypeOf(i)?Fe(Or,{machine:G(i),transitions:G(this.transitions)}).enter(e,t,r):(i.then(o=>t.send({type:"done",data:o})).catch(o=>t.send({type:"error",error:o})),e)}},Or={enter(e,t,r){if(t.child=me(this.machine,i=>{t.onChange(i),t.child==i&&i.machine.state.value.final&&(delete t.child,t.send({type:"done",data:i.context}));},t.context,r),t.child.machine.state.value.final){let i=t.child.context;return delete t.child,Bt(t,e,{type:"done",data:i},this.transitions.get("done"))}return e}};function Y(e,...t){let r=G(Cr(t));return gt.isPrototypeOf(e)?Fe(Or,{machine:G(e),transitions:r}):Fe(di,{fn:G(e),transitions:r})}var gt={get state(){return {name:this.current,value:this.states[this.current]}}};function be(e,t,r=Qr){return typeof e!="string"&&(r=t||Qr,t=e,e=Object.keys(t)[0]),Ce._create&&Ce._create(e,t),Fe(gt,{context:G(r),current:G(e),states:G(t)})}function Bt(e,t,r,i){let{context:o}=e;for(let{to:n,guards:l,reducers:s}of i)if(l(o,r)){e.context=s.call(e,o,r);let u=t.original||t,f=Fe(u,{current:G(n),original:{value:u}});Ce._onEnter&&Ce._onEnter(t,n,e.context,o,r);let c=f.state.value;return e.machine=f,e.onChange(e),c.enter(f,e,r)}}function hi(e,t){let r=t.type||t,{machine:i}=e,{value:o,name:n}=i.state;return o.transitions.has(r)?Bt(e,i,t,o.transitions.get(r))||i:(Ce._send&&Ce._send(r,n),i)}var ui={send(e){hi(this,e);}};function me(e,t,r,i){let o=Object.create(ui,{machine:Mr(e),context:Mr(e.context(r,i)),onChange:G(t)});return o.send=o.send.bind(o),o.machine=o.machine.state.value.enter(o.machine,o,i),o}var jr=(e,t)=>{if(!t)return;let r=fi(t);return $i(r,e.query)},fi=e=>immer.produce(e,t=>objectTraversal.traverse(t,({value:r})=>{radash.isObject(r);})),$i=(e,t)=>immer.produce(e,r=>objectTraversal.traverse(r,({value:i})=>{if(radash.isObject(i)){let o=i;Object.keys(o).forEach(n=>{(o[n]===void 0||o[n]===null||radash.isArray(o[n])&&o[n].length===0)&&(t?.returnNulls?o[n]=null:delete o[n]),o[n]===void 0&&delete o[n];}),Object.getOwnPropertySymbols(o).forEach(n=>{delete o[n];}),t?.noMetadata===!0&&Object.keys(o).forEach(n=>{n.startsWith("$")&&delete o[n];});}}));var Wr=(e,t)=>{for(let o of e)if(!("$entity"in o)&&!("$relation"in o)&&(!("$thing"in o)||!("$thingType"in o)))throw new Error("No entity specified in query");let r=Array.isArray(e)?e:[e];return immer.produce(r,o=>objectTraversal.traverse(o,n=>{let{value:l,meta:s}=n,u=l;if(radash.isObject(u)){if(u.$id){if(s.nodePath?.includes(".$filter"))return;let f=u.$entity||u.$relation?u:{[`$${u.$thingType}`]:u.$thing},c=x(t,f);if(!c?.name)throw new Error(`Schema not found for ${u.$thing}`);if(u.$path=c.name,Array.isArray(u.$id)||(u.$filterByUnique=!0),c?.idFields?.length!==1)throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in u||"$relation"in u||"$thing"in u){let f=x(t,u);if(!f?.name)throw new Error(`Schema not found for ${u.$thing}`);u.$path=f.name;}if(u.$entity?(u.$thing=u.$entity,u.$thingType="entity",delete u.$entity):u.$relation&&(u.$thing=u.$relation,u.$thingType="relation",delete u.$relation),radash.isObject(u)&&"$thing"in u&&u.$thing){let f=u.$entity||u.$relation?u:{[`$${u.$thingType}`]:u.$thing};u[ae]=s.nodePath;let c=x(t,f);if(u.$filter&&(u.$filterByUnique=wt(u.$filter,c),u.$filter=Oe(u.$filter,u.$thing,t)),u.$fields){u.$fields.some(p=>c?.idFields?.includes(p?.$path||p))||(u.$fields=[...u.$fields,...Array.isArray(c.idFields)?c.idFields:[]],u.$idNotIncluded=!0);let a=u.$fields?.flatMap(p=>{let h=Nr(p,c,t);return Array.isArray(h)?h:[h]}).filter(Boolean);u.$fields=a;}else {let a=bt(c)?.flatMap(p=>{let h=Nr(p,c,t);return Array.isArray(h)?h:[h]}).filter(Boolean);u.$fields=a;}u.$excludedFields&&(u.$fields=u.$fields.filter(d=>ve(c,d)?!0:!u.$excludedFields.includes(d.$path)));}}}))},bt=e=>{let t=e.dataFields?.map(n=>n.path)||[],r=e.linkFields?.map(n=>n.path)||[],i=Object.keys(e.roles||{})||[];return [...t,...r,...i]},wt=(e,t)=>Object.keys(e||{}).some(i=>{if(!Array.isArray(e[i])){let o=t.idFields?.includes(i),n=t.dataFields?.some(s=>(s.dbPath===i||s.path===i)&&s?.validations?.unique),l=i==="$id"&&!Array.isArray(e[i]);return o||n||l}return !1}),ve=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),gi=e=>{let{field:t,fieldStr:r,$justId:i,dbPath:o,isVirtual:n,fieldSchema:l}=e;return {$path:r,$dbPath:o,$thingType:"attribute",$as:t.$as||r,$var:r,$fieldType:"data",$justId:i,$id:t.$id,$isVirtual:n,[le]:l}},Bi=e=>{let{field:t,fieldStr:r,linkField:i,$justId:o,dbPath:n,schema:l,fieldSchema:s}=e,{target:u,oppositeLinkFieldsPlayedBy:f}=i;return f.map(c=>{let d=u==="role"?c.thingType:"relation",a=u==="role"?c.thing:i.relation,p={[`$${d}`]:a},h=x(l,p),$=t?.$fields?.filter(B=>ve(h,B)).length===0,y=[];if(typeof t!="string")if(t.$fields)if($){let B=h.idFields||[];y=[...t.$fields,...B];}else y=t.$fields;else y=bt(h);else y=["id"];t.$excludedFields&&(y=y.filter(B=>ve(h,B)?!0:!t.$excludedFields.includes(B.$path)));let m=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...Oe(t.$filter,a,l)}:void 0;return {$thingType:d,$plays:i.plays,$playedBy:c,$path:c.path,$dbPath:n,$as:t.$as||r,$var:r,$thing:a,$fields:y,$excludedFields:t.$excludedFields,$fieldType:"link",$target:u,$intermediary:c.relation,$justId:o,$id:t.$id,$filter:m,$idNotIncluded:$,$filterByUnique:wt(t.$filter,h),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[le]:s}})},Ei=e=>{let{field:t,fieldStr:r,roleField:i,$justId:o,dbPath:n,schema:l,fieldSchema:s}=e;return i.playedBy.map(u=>{let{thing:f,thingType:c,relation:d}=u,a={[`$${c}`]:f},p=x(l,a),h=t?.$fields?.filter(m=>p?.idFields?.includes(m)||p?.idFields?.includes(m.$path)).length===0,$=[];if(typeof t!="string")if(t.$fields)if(h){let m=p.idFields||[];$=[...t.$fields,...m];}else $=t.$fields;else $=bt(p);else $=["id"];t.$excludedFields&&($=$.filter(m=>ve(p,m)?!0:!t.$excludedFields.includes(m.$path)));let y=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...Oe(t.$filter,f,l)}:void 0;return {$thingType:c,$path:r,$dbPath:n,$as:t.$as||r,$var:r,$thing:f,$fields:$,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:d,$justId:o,$id:t.$id,$filter:y,$idNotIncluded:h,$filterByUnique:wt(t.$filter,p),$playedBy:u,$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[le]:s}})},Nr=(e,t,r)=>{let i=typeof e=="string"?e:e.$path,o=typeof e=="string",n=t.dataFields?.find(u=>u.path===i),l=t.linkFields?.find(u=>u.path===i),s=t.roles?.[i];if(n){let u=!!n.isVirtual&&!!n.default;return gi({field:e,fieldStr:i,$justId:o,dbPath:n.dbPath,isVirtual:u,fieldSchema:n})}else {if(l)return Bi({field:e,fieldStr:i,linkField:l,$justId:o,dbPath:l.path,schema:r,fieldSchema:l});if(s)return Ei({field:e,fieldStr:i,roleField:s,$justId:o,dbPath:i,schema:r,fieldSchema:s})}return null},Oe=(e,t,r)=>{if(e==null)return e;let i=radash.isArray(e),n=(i?e:[e]).map(l=>Object.keys(l).reduce((f,c)=>{let d=l[c],a=radash.isArray(d)?d:[d];if(c.startsWith("$"))["$id","$thing"].includes(c)?f[c]=d:f[c]=Oe(d,t,r);else {let p=t in r.entities?r.entities[t]:r.relations[t],[h,$]=_e(p,c);if(h==="dataField")f[c]=d;else if(h==="linkField"||h==="roleField"){let y=$,[m]=y.$things;return a.every(B=>typeof B=="string")?f[c]={$id:a,$thing:m}:a.every(B=>radash.isObject(B))&&(f[c]=radash.isArray(d)?{$or:Oe(d,m,r)}:Oe(d,m,r)),f}else throw new Error(`Field ${c} not found in schema of ${t}`)}return f},{}));return i?n.length===1?n[0]:{$or:n}:n[0]};var zr=async(e,t,r)=>r?(n=>immer.produce(n,l=>objectTraversal.traverse(l,({value:s})=>{if(radash.isObject(s)){let u=s;if(!u.$thing)return;if(u.$thing){let f=x(e,u),{virtualFields:c}=f,d=u[ae];if(!d)throw new Error("[Internal] QueryPath is missing");let a=objectTraversal.getNodeByPath(t,d),p=a.$fields.map($=>$.$path),h=a.$excludedFields;c.forEach($=>{if(h?.includes($)||p.length>0&&!p.includes($))return;let y=f.dataFields?.find(m=>m.path===$);if(y?.default){let m=Ae({currentThing:u,fieldSchema:y,mandatoryDependencies:!0});u[$]=m;}else if(u[$]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${$}`)}),h&&h.forEach($=>{if(typeof $!="string")throw new Error("[Internal] ExcludedField is not a string");delete u[$];});}}})))(r):void 0;var _r=e=>e.replace(/`/g,""),Qi=[" ","-","+","*","/","=","!","@","#","$","%","^","&","(",")","[","]","{","}","|","\\",";",":","'",'"',",","<",">",".","?","~","`"],Vr=e=>Qi.some(t=>e.includes(t))?`\u27E8\`${e}\`\u27E9`:e;var Kr=e=>{let{queries:t,schema:r}=e;return t.map(i=>Li({query:i,schema:r}))},Li=e=>{let{query:t,schema:r}=e,{$thing:i,$fields:o,$filter:n,$offset:l,$limit:s,$sort:u}=t;if(o.length===0)return null;let f=[];f.push("SELECT");let c=Mt({parentQuery:t,queries:o,level:1,schema:r});c&&f.push(c);let d=r.entities[i]||r.relations[i];if(!d)throw new Error(`Schema for ${i} not found`);let p=(d.subTypes?[i,...d.subTypes]:[i]).map(h=>Vr(h));if(t.$id)if(typeof t.$id=="string")f.push(`FROM ${p.map(h=>`${h}:\`${t.$id}\``).join(",")}`);else if(radash.isArray(t.$id)){let h=t.$id,$=p.flatMap(y=>h?.map(m=>`${y}:\`${m}\``));f.push(`FROM ${$.join(",")}`);}else throw new Error("Invalid $id");else f.push(`FROM ${p.join(",")}`);if(n){let h=ye(n,i,r),$=Se(h);f.push(`WHERE ${$}`);}return u&&f.push(Ur(u)),typeof s=="number"&&f.push(`LIMIT ${s}`),typeof l=="number"&&f.push(`START ${l}`),f.join(`
40
+ `)},Mt=e=>{let{queries:t,schema:r,level:i,parentQuery:o}=e,n=[],l=o[ae];return n.push(w(`"${l}" as \`$$queryPath\``,i)),n.push(w("meta::id(id) as `$id`",i)),n.push(w("meta::tb(id) as `$thing`",i)),t.forEach(s=>{let u=Si({query:s,level:i,schema:r});u&&n.push(u);}),n.length===0?null:n.join(`,
41
+ `)},Si=e=>{let{query:t,schema:r,level:i}=e;return t.$fieldType==="data"?ki({query:t,level:i}):t.$fieldType==="link"?Di({query:t,level:i,schema:r}):t.$fieldType==="role"?Ri({query:t,level:i,schema:r}):null},ki=e=>{let{query:t,level:r}=e;return t.$isVirtual?null:t.$path==="id"?w(`meta::id(${t.$path}) AS ${t.$as}`,r):t.$path===t.$as?w(`\`${t.$path}\``,r):w(`\`${t.$path}\` AS \`${t.$as}\``,r)},Di=e=>{let{query:t,schema:r,level:i}=e,{$fields:o,$filter:n,$offset:l,$limit:s,$sort:u}=t;if(o.length===0)return null;let f=[];f.push(w("(",i));let c=i+1;f.push(w("SELECT",c));let d=Mt({parentQuery:t,queries:o,level:c+1,schema:r});d&&f.push(d);let a=t[le][Te].queryPath;if(f.push(w(`FROM ${a}`,c)),n){let p=ye(n,t.$thing,r),h=Se(p);f.push(`WHERE ${h}`);}return u&&f.push(w(Ur(u),c)),typeof s=="number"&&f.push(w(`LIMIT ${s}`,c)),typeof l=="number"&&f.push(w(`START ${l}`,c)),f.push(w(`) AS \`${t.$as}\``,i)),f.join(`
42
+ `)},Ri=e=>{let{query:t,schema:r,level:i}=e;if(t.$fields.length===0)return null;let o=[];o.push(w("(",i));let n=i+1;o.push(w("SELECT",n));let l=n+1,s=Mt({parentQuery:t,queries:t.$fields,level:l,schema:r});s&&o.push(s);let u=t[le][Te].queryPath;if(o.push(w(`FROM ${u}`,n)),t.$filter){let f=ye(t.$filter,t.$playedBy.thing,r),c=Se(f);o.push(`WHERE ${c}`);}return o.push(w(`) AS \`${t.$as}\``,i)),o.join(`
43
+ `)},ye=(e,t,r)=>{if(e==null)return e;let i=radash.isArray(e),n=(i?e:[e]).map(l=>{let u=Object.keys(l).reduce((f,c)=>{let d=l[c];if(c.startsWith("$"))return c==="$not"?{...f,$not:void 0,"$!":ye(d,t,r)}:c==="$or"?{...f,$or:void 0,$OR:ye(d,t,r)}:c==="$and"?{...f,$and:void 0,$AND:ye(d,t,r)}:c==="$eq"?{...f,$nor:void 0,"$=":ye(d,t,r)}:c==="$id"?{...f,$id:void 0,"meta::id(id)":{$IN:radash.isArray(d)?d:[d]}}:c==="$thing"?f:{...f,[c]:ye(d,t,r)};let a=t in r.entities?r.entities[t]:r.relations[t],[p,h]=_e(a,c);if(p==="dataField"){if(a.idFields.length>1)throw new Error("Multiple id fields not supported");return c===a.idFields[0]?{...f,"meta::id(id)":{$IN:radash.isArray(d)?d:[d]}}:{...f,[c]:d}}if(p==="linkField"||p==="roleField"){let $=h,[y]=$.$things,m=$[Te].queryPath;return {...f,[m]:ye(d,y,r)}}throw new Error(`Field ${c} not found in schema, Defined in $filter`)},{});return radash.shake(u)});return i?n:n[0]},Se=e=>{if(e==null)return "";let t=Object.entries(e),r=[];return t.forEach(([i,o])=>{if(["$OR","$AND","$!"].includes(i)){let n=i.replace("$",""),l=Array.isArray(o)?o.map(s=>Se(s)):[Se(o)];n==="!"?r.push(`!(${l.join(` ${n} `)})`):r.push(`(${l.join(` ${n} `)})`);return}if(radash.isObject(o))if(i.includes("<-")||i.includes("->")){let n=Se(o);r.push(`${i}[WHERE ${n}]`);}else {if(i.startsWith("$"))throw new Error(`Invalid key ${i}`);if(Object.keys.length===1&&Object.keys(o)[0].startsWith("$")){let[n]=Object.keys(o),l=o[n];if(radash.isArray(l))r.push(`${i} ${n.replace("$","")} [${l.map(s=>`'${s}'`).join(", ")}]`);else if(radash.isObject(l)){let s=Se(l);r.push(`${i} ${n.replace("$","")} ${s}`);}else r.push(`${i} ${n.replace("$","")} '${l}'`);}else throw new Error(`Invalid key ${i}`)}else if(Array.isArray(o)){let n=i.startsWith("$")?i.replace("$",""):"IN";r.push(`${i} ${n} [${o.map(l=>`'${l}'`).join(", ")}]`);}else {let n=i.startsWith("$")?i.replace("$",""):"=";r.push(`${i} ${n} '${o}'`);}}),r.join(" AND ")},Ur=e=>`ORDER BY ${e.map(r=>{if(typeof r=="string")return r;let{field:i,desc:o}=r;return `${i}${o?" DESC":" ASC"}`}).join(", ")}`;var Jr=async e=>{let{client:t,queries:r}=e,i=`
44
+ BEGIN TRANSACTION;
45
+ ${r.join(";")};
46
+ COMMIT TRANSACTION;
47
+ `;return await t.query(i)};var Zr=e=>{let{res:t,queries:r}=e;return t.map((o,n)=>Yr(r[n],o))},Yr=(e,t)=>{if(radash.isArray(t)){if(t.length===0)return null;if(e.$filterByUnique){if(t.length>1)throw new Error("Multiple results found for unique query");return Tt(e,t[0])}if(t.length>=1)return t.map(r=>Tt(e,r))}else throw new Error("res is unexpectedly not an array")},Tt=(e,t)=>{let r={[ae]:t.$$queryPath,$id:t.$id,$thing:_r(t.$thing),$thingType:e.$thingType};return e.$fields.forEach(i=>{let o=i.$as,n=t[o];i.$path==="id"&&e.$idNotIncluded||(r[o]=Ai(i,n));}),r},Ai=(e,t)=>t==null||radash.isArray(t)&&t.length===0?null:e.$fieldType==="data"?(e[le].cardinality==="ONE"&&radash.isArray(t)&&t[0],t??null):e.$justId?e.$filterByUnique||e[le].cardinality==="ONE"?t[0]?.id??null:t?.map(r=>r.id)??[]:e.$filterByUnique||e[le].cardinality==="ONE"?Tt(e,t[0]):Yr(e,t);var Lt=H("error","error",V((e,t)=>({...e,error:t.error}))),Ii=be("build",{build:Y(async e=>Kr({queries:e.bql.queries,schema:e.schema}),H("done","run",V((e,t)=>({...e,surql:{...e.surql,queries:t.data}}))),Lt),run:Y(async e=>Jr({client:e.client,queries:oe(e.surql.queries)}),H("done","parse",V((e,t)=>({...e,surql:{...e.surql,res:t.data}}))),Lt),parse:Y(async e=>Zr({res:oe(e.surql.res),queries:e.bql.queries,schema:e.schema,config:e.config}),H("done","success",V((e,t)=>({...e,bql:{...e.bql,res:t.data}}))),Lt),success:he(),error:he()},e=>e),Ci=async e=>new Promise((t,r)=>{me(Ii,i=>{i.machine.state.name==="success"&&t(i.context.bql.res),i.machine.state.name==="error"&&r(i.context.error);},e);}),Xr=async(e,t,r,i)=>Ci({bql:{queries:e},surql:{},schema:t,config:r,client:i,error:null});var St="___",Gr=async e=>{let{queries:t,schema:r}=e;return t.map(i=>Pi({query:i,schema:r}))},Pi=e=>{let{query:t,schema:r}=e,{$path:i,$thing:o,$filter:n,$fields:l,$sort:s,$offset:u,$limit:f,$id:c}=t;if(!i)throw new Error("Path is not defined");let d=[],a=t[ae];if(d.push("match"),d.push(`$${i} isa ${o};`),n||c){let $=Ve(r,t),y={...n,...c?{[$]:c}:{}},m=At({$filter:y,$var:i,$thing:o,schema:r,depth:0});d.push(`
48
+ ${m}`);}let p=It({schema:r,$thing:o,$var:i,$sort:s,depth:0});p&&d.push(p.match);let h=`M_${uuid.v4()}`;if(d.push(`?queryPath${h} = "${a}";`),d.push("fetch"),d.push(`?queryPath${h} as "queryPath";`),l){let $=l.filter(B=>B.$fieldType==="data");$&&$.length>0&&d.push(...kt($,i,0));let y=l.filter(B=>B.$fieldType==="link");y&&y.length>0&&d.push(...Rt(y,i,i,0,r));let m=l.filter(B=>B.$fieldType==="role");m&&m.length>0&&d.push(...Dt(m,i,i,0,r));}return p&&d.push(p.sort),typeof u=="number"&&d.push(`
49
+ offset ${u};`),typeof f=="number"&&d.push(`
50
+ limit ${f};`),d.join(`
51
+ `)},kt=(e,t,r)=>{let i=[],o=[],n=[];for(let c=0;c<e.length;c++)e[c].$isVirtual||i.push(e[c].$dbPath),e[c][le].contentType==="FLEX"&&n.push({path:e[c][le].dbPath}),o.push(`{${e[c].$dbPath}:${e[c].$as}}`);let l=i.join(", "),u=`$metadata:{as:[${o.join(",")}]}`,f=[w(`$${t} as "${t}.${u}.$dataFields": ${l};`,r)];return n.length>0&&n.forEach(c=>{f.push(w(`"${c.path}.$multiVal": {match $${t} has ${c.path} $${c.path}; fetch $${c.path}: attribute;};`,r));}),f},Dt=(e,t,r,i,o)=>{let n=i+1,l=[];for(let s of e){let{$fields:u,$as:f,$justId:c,$idNotIncluded:d,$filterByUnique:a,$thing:p,$sort:h,$offset:$,$limit:y}=s,m=s[ae],B=`$metadata:{as:${f},justId:${c?"T":"F"},idNotIncluded:${d},filterByUnique:${a}}`;l.push(w(`"${r}.${B}.${s.$var}": {`,i)),l.push(w("match",n));let M=`${t}${St}${s.$var}`;if(l.push(w(`$${M} isa ${s.$thing};`,n)),l.push(w(`$${t} (${s.$var}: $${t}${St}${s.$var}) isa ${s.$intermediary};`,n)),s.$filter||s.$id){let L=Ve(o,s),D=s.$id?{[L]:s.$id}:{},A={...s.$filter,...D};l.push(At({$filter:A,$var:M,$thing:s.$thing,schema:o,depth:n}));}let g=It({schema:o,$thing:p,$var:M,$sort:h,depth:n});if(g&&l.push(g.match),u){let L=`M_${uuid.v4()}`;l.push(w(`
52
+ ?queryPath${L} = "${m}";`,n)),l.push(w("fetch",n)),l.push(w(`?queryPath${L} as "queryPath";`,n));let D=u?.filter(j=>j.$fieldType==="data");D&&D.length>0&&l.push(...kt(D,M,n));let A=u?.filter(j=>j.$fieldType==="link");A&&A.length>0&&l.push(...Rt(A,M,`${t}.${s.$var}`,n,o));let C=u?.filter(j=>j.$fieldType==="role");C&&C.length>0&&l.push(...Dt(C,M,`${t}.${s.$var}`,n,o));}g&&l.push(g.sort),typeof $=="number"&&l.push(w(`offset ${$};`,n)),typeof y=="number"&&l.push(w(`limit ${y};`,n)),l.push(w("};",i));}return l},Rt=(e,t,r,i,o)=>{let n=i+1,l=[];for(let s of e){let{$fields:u,$as:f,$justId:c,$idNotIncluded:d,$filterByUnique:a,$playedBy:p,$thing:h,$sort:$,$offset:y,$limit:m}=s,B=s[ae],M=`$metadata:{as:${f},justId:${c?"T":"F"},idNotIncluded:${d},filterByUnique:${a}}`;l.push(w(`"${r}.${M}.${s.$var}": {`,i)),l.push(w("match",n));let g=`${t}${St}${s.$var}`;if(l.push(w(`$${g} isa ${s.$thing};`,n)),s.$filter||s.$id){let D=Ve(o,s),A=s.$id?{[D]:s.$id}:{},C={...s.$filter,...A};l.push(At({$filter:C,$var:g,$thing:s.$thing,schema:o,depth:n}));}let L=It({schema:o,$thing:h,$var:g,$sort:$,depth:n});if(L&&l.push(L.match),s.$target==="role"?l.push(w(`$${t}_intermediary (${s.$plays}: $${t}, ${p.plays}: $${g}) isa ${s.$intermediary};`,n)):l.push(w(`$${g} (${s.$plays}: $${t});`,n)),u){let D=`M_${uuid.v4()}`;l.push(w(`?queryPath${D} = "${B}";`,n)),l.push(w("fetch",n)),l.push(w(`?queryPath${D} as "queryPath";`,n));let A=u?.filter(N=>N.$fieldType==="data");A&&A.length>0&&l.push(...kt(A,g,n));let C=u?.filter(N=>N.$fieldType==="link");C&&C.length>0&&l.push(...Rt(C,g,`${t}.${s.$var}`,n,o));let j=u?.filter(N=>N.$fieldType==="role");j&&j.length>0&&l.push(...Dt(j,g,`${t}.${s.$var}`,n,o));}L&&l.push(L.sort),typeof y=="number"&&l.push(w(`offset ${y};`,n)),typeof m=="number"&&l.push(w(`limit ${m};`,n)),l.push(w("};",i));}return l},xi=(e,t)=>{let r={};if(t.dataFields?.forEach(l=>{l.path!==l.dbPath&&(r[l.path]=l.dbPath);}),Object.keys(r).length===0)return e;let{$not:i,...o}=e,n=vr(o,r);return i&&(n.$not=vr(i,r)),n},vr=(e,t)=>{let r={};return Object.entries(e).forEach(([i,o])=>{let n=t[i]||i;r[n]=o;}),r},At=e=>{let{$filter:t,$var:r,$thing:i,schema:o,depth:n}=e,l=xi(t,v(o,i)),{$not:s,...u}=l,f=v(o,i),c=[];return Object.entries(s||{}).forEach(([d,a])=>{if(d.startsWith("$"))return;if(f.dataFields?.find($=>$.dbPath===d)){a===null?c.push(w(`$${r} has ${d} $${d}_${uuid.v4()};`,n)):Array.isArray(a)?a.forEach($=>{c.push(w(`not { $${r} has ${d} ${ne($)}; };`,n));}):c.push(w(`not { $${r} has ${d} ${ne(a)}; };`,n));return}let h=f.linkFields?.find($=>$.path===d);if(h){let[$]=h.oppositeLinkFieldsPlayedBy,m=v(o,$.thing).idFields?.[0];if(!m)throw new Error(`"${$.thing}" does not have an id field`);if(h.target==="relation")a===null?c.push(w(`(${h.plays}: $${r}) isa ${h.relation};`,n)):Array.isArray(a)?a.forEach(B=>{c.push(w(`not { (${h.plays}: $${r}) isa ${h.relation}, has ${m} ${ne(B)}; };`,n));}):c.push(w(`not { (${h.plays}: $${r}) isa ${h.relation}, has ${m} ${ne(a)}; };`,n));else {let B=`${$.thing}_${uuid.v4()}`;a===null?c.push(w(`$${B} isa ${$.thing}; (${h.plays}: $${r}, ${$.plays}: $${B}) isa ${h.relation};`,n)):Array.isArray(a)?a.forEach(M=>{c.push(w(`not { $${B} isa ${$.thing}, has ${m} ${ne(M)}; (${h.plays}: $${r}, ${$.plays}: $${B}) isa ${h.relation}; };`,n));}):c.push(w(`not { $${B} isa ${$.thing}, has ${m} ${ne(a)}; (${h.plays}: $${r}, ${$.plays}: $${B}) isa ${h.relation}; };`,n));}return}if(f.thingType==="relation"){let $=f.roles[d];if($){let[y]=$.playedBy||[],B=v(o,y.thing).idFields?.[0];if(!B)throw new Error(`"${y.thing}" does not have an id field`);let M=`${y.thing}_${uuid.v4()}`,g=uuid.v4(),L=`${r}_${g}`;a===null?(c.push(w(`$${L} isa ${i};`,n)),c.push(w(`$${L} (${y.plays}: ${M});`,n)),c.push(w(`$${r} is $${L};`,n))):Array.isArray(a)?a.forEach(D=>{c.push(w(`$${L} isa ${i};`,n)),c.push(w(`not { $${M} isa ${y.thing}, has ${B} ${ne(D)}; $${L} (${y.plays}: $${M}); };`,n)),c.push(w(`$${r} is $${L};`,n));}):(c.push(w(`$${L} isa ${i};`,n)),c.push(w(`not { $${M} isa ${y.thing}, has ${B} ${ne(a)}; $${L} (${y.plays}: $${M}); };`,n)),c.push(w(`$${r} is $${L};`,n)));return}}}),Object.entries(u).forEach(([d,a])=>{if(d.startsWith("$"))return;if(f.dataFields?.find($=>$.dbPath===d)){if(a===null)c.push(w(`not { $${r} has ${d} $${d}_${uuid.v4()}; };`,n));else if(Array.isArray(a)){let $=a.map(m=>`$${r} has ${d} ${ne(m)};`),y=Ge($);y&&c.push(w(y,n));}else c.push(w(`$${r} has ${d} ${ne(a)};`,n));return}let h=f.linkFields?.find($=>$.path===d);if(h){let[$]=h.oppositeLinkFieldsPlayedBy,m=v(o,$.thing).idFields?.[0];if(!m)throw new Error(`"${$.thing}" does not have an id field`);if(h.target==="relation")if(a===null)c.push(w(`not { (${h.plays}: $${r}) isa ${h.relation}; };`,n));else if(Array.isArray(a)){let B=a.map(g=>`(${h.plays}: $${r}) isa ${h.relation}, has ${m} ${ne(g)};`),M=Ge(B);M&&c.push(w(M,n));}else c.push(w(`(${h.plays}: $${r}) isa ${h.relation}, has ${m} ${ne(a)};`,n));else {let B=`${$.thing}_${uuid.v4()}`;if(a===null)c.push(w(`not { $${B} isa ${$.thing}; (${h.plays}: $${r}, ${$.plays}: $${B}) isa ${h.relation}; };`,n));else if(Array.isArray(a)){let M=a.map(L=>`$${B} isa ${$.thing}, has ${m} ${ne(L)}; (${h.plays}: $${r}, ${$.plays}: $${B}) isa ${h.relation};`),g=Ge(M);g&&c.push(w(g,n));}else c.push(w(`$${B} isa ${$.thing}, has ${m} ${ne(a)}; (${h.plays}: $${r}, ${$.plays}: $${B}) isa ${h.relation};`,n));}return}if(f.thingType==="relation"){let $=f.roles[d];if($){let[y]=$.playedBy||[],B=v(o,y.thing).idFields?.[0];if(!B)throw new Error(`"${y.thing}" does not have an id field`);let M=`${y.thing}_${uuid.v4()}`,g=uuid.v4(),L=`${r}_${g}`;if(a===null)c.push(w(`$${L} isa ${i};`,n)),c.push(w(`not { $${L} (${y.plays}: ${M}); };`,n)),c.push(w(`$${r} is $${L};`,n));else if(Array.isArray(a)){let D=a.map(C=>`$${M} isa ${y.thing}, has ${B} ${ne(C)}; $${L} (${y.plays}: $${M});`),A=Ge(D);A&&(c.push(w(`$${L} isa ${i};`,n)),c.push(w(A,n)),c.push(w(`$${r} is $${L};`,n)));}else c.push(w(`$${L} isa ${i};`,n)),c.push(w(`$${M} isa ${y.thing}, has ${B} ${ne(a)}; $${L} (${y.plays}: $${M});`,n)),c.push(w(`$${r} is $${L};`,n));return}}throw new Error(`"${i}" does not have property "${d}"`)}),c.join(`
53
+ `)},Ge=e=>{if(e.length>1)return `{ ${e.join(" } or { ")} };`;let[t]=e;return t},ne=e=>typeof e=="string"?`'${e}'`:e instanceof Date?`'${e.toISOString().replace("Z","")}'`:radash.isObject(e)&&"$id"in e?radash.isArray(e.$id)?`like "^(${e.$id.join("|")})$"`:`"${e.$id}"`:`${e}`,ji=e=>typeof e=="string"?{field:e,desc:!1}:{...e,desc:e.desc??!1},It=e=>{let{$var:t,$thing:r,schema:i,$sort:o,depth:n}=e,l=v(i,r),s=[],u=[];if(o?.forEach(f=>{let c=ji(f),d=l.dataFields?.find(h=>h.path===c.field);if(!d)throw new Error(`"${r}" does not have data field "${c.field}"`);let a=`${c.field}_${uuid.v4()}`;s.push(w("{",n)),s.push(w(`$${t} has ${d.dbPath} $${a}_1;`,n+1)),s.push(w("not {",n+1)),s.push(w(`$${t} has ${d.dbPath} $${a}_2;`,n+2)),s.push(w(`$${a}_2 < $${a}_1;`,n+2)),s.push(w("};",n+1)),s.push(w(`?${a}_ = $${a}_1;`,n+1)),s.push(w("} or {",n)),s.push(w(`not { $${t} has ${d.dbPath} $${a}_1; };`,n+1)),s.push(w(`?${a}_ = "~";`,n+1)),s.push(w("};",n)),s.push(w(`?${a} = ?${a}_;`,n));let p=c.desc?"desc":"asc";u.push(`?${a} ${p}`);}),s.length!==0)return {match:s.join(""),sort:w(`sort ${u.join(", ")};`,n)}};var tn=async e=>{let{enrichedBqlQuery:t,rawBqlRequest:r,schema:i,config:o,rawTqlRes:n}=e;if(t){if(!n)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");return n.map((l,s)=>{let u=r[s],f=t[s];return Wi(l,u,f,i,o)})},Wi=(e,t,r,i,o)=>e.length===0?null:r.$filterByUnique?en(e[0],t,i,o):e.map(n=>en(n,t,i,o)),en=(e,t,r,i)=>{let{dataFields:o,currentSchema:n,linkFields:l,roleFields:s,schemaValue:u}=Ct(e,r),f=Ot(o,n,i),c=Pt(l,r,i),d=qt(s,r,i),a=t?.$fields?.every(h=>!n?.idFields?.includes(typeof h=="string"?h:h.$path));return {...c,...d,...u,...!i.query?.noMetadata&&t.$id?{$id:Array.isArray(t.$id)?f.id:t.$id}:{},...a?Object.fromEntries(Object.entries(f).filter(([h])=>!n?.idFields?.includes(h))):f}},Ct=(e,t)=>{let r=Object.keys(e),i=r.find(p=>p.endsWith(".$dataFields")),o=r.filter(p=>p.endsWith(".$multiVal"));if(!i)throw new Error("No dataFields");o?.length>0&&o.forEach(p=>{let h=p.replace(/\.\$multiVal$/,""),$=e[p][0][h].attribute;e[i][h]=$;});let n=e[i],l=i.split(".")[i.split(".").length-2];if(n.$metaData=l,n.length===0)throw new Error("No dataFields");let s=n.type,u={$thing:s.label,$thingType:s.root,[ae]:e.queryPath.value},f={[`$${u.$thingType}`]:u.$thing},c=x(t,f),d=r.filter(p=>{let h=oe(p.split(".").pop());return !p.endsWith(".$dataFields")&&c.linkFields?.some($=>$.path===h)}).map(p=>{let h=oe(p.split(".").pop()),$=oe(c.linkFields?.find(y=>y.path===h));return {$linkFields:e[p],$key:h,$metaData:p.split(".")[p.split(".").length-2],$cardinality:$.cardinality}}),a=r.filter(p=>{let h=p.split(".").pop();return h&&!p.endsWith(".$dataFields")&&c.thingType==="relation"&&c.roles?.[h]}).map(p=>{let h=oe(p.split(".").pop());return {$roleFields:e[p],$key:h,$metaData:p.split(".")[p.split(".").length-2],$cardinality:c.roles[h].cardinality}});return {dataFields:n,schemaValue:u,currentSchema:c,linkFields:d,roleFields:a}},Ot=(e,t,r)=>{let{$metaData:i}=e,{as:o}=zi(i),n=Object.entries(e).filter(([l])=>l!=="type"&&!l.startsWith("$")).map(([l,s])=>{let u=t.dataFields?.find(a=>a.path===l||a.dbPath===l),f=l==="id",c=Array.isArray(o)?o.find(a=>a[l])?.[l]:l,d;if(u?.cardinality==="ONE"){if(d=s[0]?s[0].value:r.query?.returnNulls?null:void 0,u.contentType==="DATE"||u.contentType==="FLEX"&&s[0].type.value_type==="datetime"?d=d&&`${d}Z`:u.contentType==="JSON"&&(d=d&&JSON.parse(d)),f)return [[c,d],["$id",d]].filter(([a,p])=>p!==void 0)}else if(u?.cardinality==="MANY"){if(!radash.isArray(s))throw new Error("Typedb fetch has changed its format");if(s.length===0)return r.query?.returnNulls?[[c,null]]:[];u.contentType==="DATE"?d=s.map(a=>`${a.value}Z`):u.contentType==="FLEX"?d=s.map(a=>a.type.value_type==="datetime"?`${a.value}Z`:a.value):u.contentType==="JSON"?d=s.map(a=>a.value&&JSON.parse(a.value)):d=s.map(a=>a.value);}return [[c,d]].filter(([a,p])=>p!==void 0)}).flat();return Object.fromEntries([...n])},qt=(e,t,r)=>{let i={};return e.forEach(o=>{let{$roleFields:n,$metaData:l,$cardinality:s}=o,{as:u,justId:f,idNotIncluded:c,filterByUnique:d}=rn(l);if(u===null)return;let a=n.map(p=>{let{dataFields:h,currentSchema:$,linkFields:y,roleFields:m,schemaValue:B}=Ct(p,t),M=Ot(h,$,r);if(f==="T")return M.id;{let g=Pt(y,t,r),L=qt(m,t,r),D={...M};return c==="true"&&$?.idFields?.forEach(A=>delete D[A]),{...D,...g,...L,...B}}});a.length>0?i[u]=s==="MANY"&&d==="false"?a:a[0]:r.query?.returnNulls&&(i[u]=null);}),i},Pt=(e,t,r)=>{let i={};return e.forEach(o=>{let{$linkFields:n,$metaData:l,$cardinality:s}=o,{as:u,justId:f,idNotIncluded:c,filterByUnique:d}=rn(l);if(u===null)return;let a=n.map(p=>{let{dataFields:h,currentSchema:$,linkFields:y,roleFields:m,schemaValue:B}=Ct(p,t),M=Ot(h,$,r);if(f==="T")return M.id;{let g=Pt(y,t,r),L=qt(m,t,r),D={...M};return c==="true"&&$.idFields?.forEach(A=>delete D[A]),{...D,...g,...L,...B}}});i[u]=a.length>0?s==="MANY"&&d==="false"?a:a[0]:r.query?.returnNulls?null:void 0;}),i},rn=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,r=/justId:([a-zA-Z0-9_\-·]+)/,i=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,o=/filterByUnique:([a-zA-Z0-9_\-·]+)/,n=e.match(t),l=e.match(r),s=e.match(i),u=e.match(o);return {as:n?n[1]:null,justId:l?l[1]:null,idNotIncluded:s?s[1]:null,filterByUnique:u?u[1]:null}},zi=e=>{try{let r=(o=>{let n=o.replace("$metadata:","");return n=n.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),n=n.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(l,s,u)=>/^{.*}$/.test(u)?`:${u}`:`:${s}"${u}"`),n=n.replace(/\[([^\]]+)\]/g,(l,s)=>`[${s.split(",").map(u=>u.trim().startsWith("{")&&u.trim().endsWith("}")?u.trim():`"${u.trim()}"`).join(",")}]`),n})(e);return JSON.parse(r)}catch(t){return console.error(t),{as:[]}}};var nn=async e=>{let{tqlRequest:t,dbHandles:r,config:i}=e,o=new typedbDriver.TypeDBOptions;o.infer=!0;let{session:n}=await Ze(r,i),l=await n.transaction(typedbDriver.TransactionType.READ,o),[s,u]=await radash.tryit(radash.parallel)(t.length,t,async f=>await l.query.fetch(f).collect());if(s){await l.rollback();let f=s;throw new Error(`Error running TQL query: ${f.errors}`)}return await l.close(),u};var Ui=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,Ji=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,Zi=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,xt=H("error","error",V((e,t)=>({...e,error:t.error}))),Yi=be("build",{build:Y(async e=>Gr({queries:e.bql.queries,schema:e.schema}),H("done","run",V(Ji)),xt),run:Y(async e=>nn({dbHandles:e.handles,tqlRequest:oe(e.tql.queries),config:e.config}),H("done","parse",V(Zi)),xt),parse:Y(async e=>tn({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries,schema:e.schema,config:e.config,rawTqlRes:oe(e.tql.res)}),H("done","success",V(Ui)),xt),success:he(),error:he()},e=>e),Xi=async e=>new Promise((t,r)=>{me(Yi,i=>{i.machine.state.name==="success"&&t(i.context.bql.res),i.machine.state.name==="error"&&r(i.context.error);},e);}),on=async(e,t,r,i,o)=>Xi({bql:{raw:e,queries:t},tql:{},schema:r,config:i,handles:o,error:null});var vi=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,jt=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,et=H("error","error",V((e,t)=>({...e,error:t.error}))),Gi=be("enrich",{enrich:Y(async e=>Wr(e.bql.raw,e.schema),H("done","adapter",V(vi)),et),adapter:Y(async e=>{let t={};e.bql.queries?.forEach((s,u)=>{let f=e.bql.raw[u],c=v(e.schema,s.$thing),{id:d}=c.defaultDBConnector;if(c.db==="typeDB"){if(!t[d]){let p=e.handles.typeDB?.get(d)?.client;if(!p)throw new Error(`TypeDB client with id "${c.defaultDBConnector.id}" does not exist`);t[d]={db:"typeDB",client:p,rawBql:[],bqlQueries:[],indices:[]};}}else if(c.db==="surrealDB"){if(!t[d]){let p=e.handles.surrealDB?.get(d)?.client;if(!p)throw new Error(`SurrealDB client with id "${c.defaultDBConnector.id}" does not exist`);t[d]={db:"surrealDB",client:p,rawBql:[],bqlQueries:[],indices:[]};}}else throw new Error(`Unsupported DB "${c.db}"`);let a=t[d];a.rawBql.push(f),a.bqlQueries.push(s),a.indices.push(u);});let r=Object.values(t),i=r.map(s=>s.db==="typeDB"?on(s.rawBql,s.bqlQueries,e.schema,e.config,e.handles):Xr(s.bqlQueries,e.schema,e.config,s.client)),o=await Promise.all(i),n=r.flatMap((s,u)=>{let f=o[u];return s.indices.map((c,d)=>({index:c,result:f[d]}))});return n.sort((s,u)=>s.index<u.index?-1:s.index>u.index?1:0),n.map(({result:s})=>s)},H("done","postHooks",V(jt)),et),postHooks:Y(async e=>zr(e.schema,oe(e.bql.queries),oe(e.bql.res)),H("done","clean",V(jt)),et),clean:Y(async e=>jr(e.config,oe(e.bql.res)),H("done","success",V(jt)),et),success:he(),error:he()},e=>e),eo=async e=>new Promise((t,r)=>{me(Gi,i=>{i.machine.state.name==="success"&&t(i.context),i.machine.state.name==="error"&&r(i.context);},e);}),qe=async(e,t,r,i)=>eo({bql:{raw:e},schema:t,config:r,handles:i,error:null});var Nt="___",to=Symbol.for("grandChildOfCreate"),sn=async(e,t,r,i)=>{let o=(E,Q)=>Object.keys(E).filter(b=>!b.startsWith("$")&&E[b]!==void 0?Q?!x(t,E).dataFields?.find(T=>T.path===b):!0:!1);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(r.mutation?.preQuery===!1)return;let n=[];if(objectTraversal.traverse(e,({parent:E,key:Q,value:b})=>{E&&Q&&!Q.includes("$")&&radash.isObject(E)?(Array.isArray(E[Q])?E[Q]:[E[Q]]).forEach(T=>{if(radash.isObject(T)){if(E.$op!=="create")n.includes(T.$op)||n.push(T.$op);else if(T.$op==="delete"||T.$op==="unlink")throw new Error(`Cannot ${T.$op} under a create`)}}):!E&&radash.isObject(b)&&(n.includes(b.$op)||n.push(b.$op));}),!n.includes("delete")&&!n.includes("unlink")&&!n.includes("replace")&&!n.includes("update")&&!n.includes("link"))return;let s=(E=>{let Q=(b,F)=>{let T=[],S={},O=["$op","$bzId","$parentKey"],k=["$relation","$entity","$id",...O];for(let P in b)if(!O.includes(P)&&!(k.includes(P)&&!F))if(!P.includes("$")&&(radash.isObject(b[P])||Array.isArray(b[P]))){let J=b[P];if(Array.isArray(J)&&J.length>0)J.forEach(ce=>{let Me={$path:P,...Q(ce),...ce.$filter&&{$as:ce.$bzId}};T.find(U=>U.$path===Me.$path&&!U.$filter)||(T=[...T,Me]);});else {let ce={$path:P,...Q(J),...!J.$filter&&{$as:J.$bzId}};T=[...T,ce];}}else S[P]=b[P];return {...S,$fields:T}};return E.map(b=>Q(b,!0))})(Array.isArray(e)?e:[e]),f=(await qe(s,t,r,i)).bql.res,c=(E,Q)=>{let b=E.$id||E.id||E.$bzId;if(E.$objectPath){let{$objectPath:F}=E,T=F?.beforePath||"root",S=Array.isArray(F.ids)?`[${F.ids}]`:F.ids;return {beforePath:`${T}.${S}___${F.key}`,ids:b,key:Q}}else return {beforePath:"root",ids:b,key:Q}},d=(E,Q)=>{let b=E?.beforePath||"root",F=(Array.isArray(E?.ids)?`[${E?.ids}]`:E?.ids);return `${b}.${F}___${E?.key}`},a=E=>{if(E.includes("[")&&E.includes("]")){let[Q,b,F]=E.split(/[[\]]/);return b.split(",").map(S=>`${Q}${S}${F}`)}else return [E]},p={};(E=>immer.produce(E,Q=>objectTraversal.traverse(Q,b=>{let{key:F,parent:T}=b;if(T&&F&&T.$id&&!F.includes("$")){let S=c(T,F),O=d(S);if(Array.isArray(T[F])){let k=[];T[F].forEach(P=>{radash.isObject(P)?(P.$objectPath=S,k.push(P.$id.toString())):P&&k.push(P.toString());}),p[O]={$objectPath:S,$ids:k};}else {let k=T[F];radash.isObject(k)?(p[O]={$objectPath:S,$ids:[k.$id.toString()]},k.$objectPath=S):k&&(p[O]={$objectPath:S,$ids:[k.toString()]});}}})))(f||{});let $=E=>immer.produce(E,Q=>objectTraversal.traverse(Q,b=>{let{key:F,value:T,parent:S}=b;S&&F&&!F.includes("$")&&(Array.isArray(T)||radash.isObject(T))&&!Array.isArray(S)&&(Array.isArray(S[F])?S[F].forEach(O=>{typeof O!="string"&&(O.$objectPath=c(S,F),O.$parentIsCreate=S.$op==="create",O[to]=S.$parentIsCreate||S[Symbol.for("grandChildOfCreate")]);}):radash.isObject(S[F])&&(S[F].$parentIsCreate=S.$op==="create",S[F][Symbol.for("grandChildOfCreate")]=S.$parentIsCreate||S[Symbol.for("grandChildOfCreate")],S[F].$objectPath=c(S,F)));})),y=$(e),m=E=>{let Q=[];return E.forEach(F=>{if(!F.$id&&!F.id&&!F.$tempId)if(F.$filter){let T=d({...F.$objectPath,key:F.$bzId}),S=p[T];S&&(Array.isArray(S.$ids)?S.$ids:[S.$ids]).forEach(k=>{let P={...F,$id:k,$bzId:`T4_${uuid.v4()}`,$filterBzId:F.$bzId};Q.push(P);});}else {let T=d(F.$objectPath),S=p[T];S?S?.$ids.forEach(O=>{let k={...F,$id:O,$bzId:`T4_${uuid.v4()}`};Q.push(k);}):Q.push(F);}else Q.push(F);}),Q.map(F=>{let T={...F};return o(T,!0).forEach(S=>{let O=Array.isArray(T[S])?T[S]:[T[S]],k=m(O);T[S]=k;}),T})},B=m(Array.isArray(y)?y:[y]),M=$(B),L=(E=>{let Q=b=>{let F=U=>{let ee=[],z=[],q=[];return U.forEach(_=>{let ie=o(_,!0);if(ie.length>0){let I=!1;ie.forEach(W=>{(Array.isArray(_[W])?_[W]:[_[W]]).filter(X=>!X.$id&&!X.id&&typeof _=="object").length&&(I=!0);}),I?ee.push(_):z.push(_);}else q.push({..._,$bzId:_.$tempId||`T_${uuid.v4()}`});}),{operationWithMultiples:ee,operationWithoutMultiples:z,otherOps:q}},{operationWithMultiples:T,operationWithoutMultiples:S,otherOps:O}=F(b),k=U=>{let z=(()=>{let W={};for(let te in U){let Z=x(t,U);!te.startsWith("$")&&Z.dataFields?.find(X=>X.path===te)&&(W[te]=U[te]);}return W})(),q=Object.keys(U),_=o(U,!0),ie=[],I=(W,te)=>{if(W===_.length){let X={...te};q.forEach(re=>{re.startsWith("$")&&(X[re]=U[re]);}),ie.push({...X,...z});return}let Z={...te,[_[W]]:U[_[W]],...Ee(te),...z};I(W+1,Z),I(W+1,te);};return I(0,{...Ee(U)}),ie},P=[];return T.forEach(U=>{let ee=k(U),z=[];ee.forEach(q=>{let _=o(q,!0);if(q.$op==="create")z.push(q);else if(q.$id){let ie=d(q.$objectPath),I=[];if(_.forEach(W=>{let te=`${ie.includes("undefined")?"root":ie}.${q.$id}${Nt}${W}`,Z=p[te];q[W].filter(re=>re.$op==="unlink"||re.$op==="delete"||re.$op==="update").length>0?Z&&I.push({key:W,ids:Z.$ids}):I.push({key:W,ids:[""]});}),I.length===_.length&&!z.find(W=>W.$id===q.$id))z.push(q);else {let W={...q,$bzId:q.$tempId||`T4_${uuid.v4()}`};_.forEach(Z=>{let X=q[Z].filter(re=>re.$id);X.length>0?W[Z]=X:W[Z]=void 0;}),o(W,!0).length>0&&z.push(W);}}else if(q.$objectPath){let ie=d(q.$objectPath),I=p[ie]?.$ids||[];I.forEach(W=>{let te=[];_.forEach(Z=>{let X=`${ie}.${W}${Nt}${Z}`,re=p[X];re&&te.push({key:Z,ids:re.$ids});}),_.length===0?I.filter(X=>!z.find(re=>re.$id===X)).forEach(X=>{z.push({...q,$id:X,$bzId:q.$tempId||`T_${uuid.v4()}`});}):te.length===_.length&&!z.find(Z=>Z.$id===W)&&(_.forEach(Z=>{let X=`${d(q.$objectPath)}.${W}${Nt}${Z}`,{$ids:re}=p[X],En=q[Z].find(ke=>!ke.$id),Fn=[...re.map(ke=>({...En,$id:ke,$objectPath:{beforePath:q.$objectPath,ids:ke,key:Z}})),...q[Z].filter(ke=>ke.$id)];q[Z]=Fn;}),z.push({...q,$id:W,$bzId:q.$tempId||`T_${uuid.v4()}`}));});}else z.push(q);}),z.forEach(q=>{P.push(q);});}),[...P,...S,...O].filter(U=>o(U).length>0?!0:U.$op!=="update").map(U=>{let ee={...U};return o(ee,!0).forEach(z=>{let q=Array.isArray(ee[z])?ee[z]:[ee[z]],_=Q(q);ee[z]=_;}),ee})};return Q(E)})(Array.isArray(M)?M:[M]),D=E=>E.map(Q=>{let b=o(Q,!0),F={...Q};return b.forEach(T=>{let S=Array.isArray(Q[T])?Q[T]:[Q[T]],O=[],k=[],P=[],J={},ce=ct(t,Q,T);S.filter(I=>I).forEach(I=>{I.$op==="replace"&&I.$id?(J=I,Array.isArray(I.$id)?k=[...k,...I.$id]:k.push(I.$id)):I.$op==="create"&&ce==="ONE"&&I.id?(J=I,Array.isArray(I.id)?P=[...k,...I.id]:P.push(I.id)):O.push(I);});let Me=d(J.$objectPath),ee=a(Me).map(I=>p[I]),z=[];ee.filter(I=>I!=null).forEach(I=>{z=[...z,...I.$ids];});let q=z.filter(I=>!k.includes(I)),_=k.filter(I=>!z.includes(I)),ie=Ee(J);q.length>0&&O.push({...J,$op:"unlink",$id:q,$bzId:J.$tempId||`T4_${uuid.v4()}`,id:void 0,...ie}),_.length>0&&_.forEach(I=>{O.push({...J,$op:"link",$id:I,$bzId:J.$tempId||`T5_${uuid.v4()}`,...ie});}),P.length>0&&P.forEach(I=>{O.push({...J,$op:"create",id:I,$bzId:J.$tempId||`T6_${uuid.v4()}`,...ie});}),F[T]=D(O);}),F}),A=$(D($(L)));(E=>immer.produce(E,Q=>objectTraversal.traverse(Q,b=>{let{key:F,value:T,parent:S}=b;F&&S&&!F?.includes("$")&&(Array.isArray(T)||radash.isObject(T))&&!Array.isArray(S)&&(Array.isArray(T)?T:[T]).forEach(k=>{let P=k.$filter?{...k.$objectPath,key:k.$filterBzId}:k.$objectPath,J=d(P),ce=p[J],Me=(z,q)=>z.every(_=>q.includes(_)),U=k.$id?Array.isArray(k.$id)?Me(k.$id,ce?ce.$ids:[]):ce?.$ids.includes(k.$id):ce,ee=ct(t,S,k.$objectPath.key);if(k.$op==="link"&&U&&ee==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${d(k.$objectPath)}" because it is already occupied.`);if(k.$op)switch(k.$op){case"delete":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${k.$id}" because it is not linked to $id:"${S.$id}"`);break;case"update":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${k.$id}" because it is not linked to $id:"${S.$id}"`);break;case"unlink":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${k.$id}" because it is not linked to $id:"${S.$id}"`);break;case"link":if(U)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${k.$id}" because it is already linked to $id:"${S.$id}"`);break;}});})))(A);let N=(E=>immer.produce(E,Q=>objectTraversal.traverse(Q,b=>{let{value:F,meta:T}=b;radash.isObject(F)&&(F[Symbol.for("path")]=T.nodePath,delete F.$objectPath,delete F.$parentIsCreate);})))(A);return [...Array.isArray(N)?N:[N]].sort((E,Q)=>E.$op==="create"&&Q.$op!=="create"?-1:E.$op!=="create"&&Q.$op==="create"?1:0)};var an=(e,t)=>immer.produce(e,i=>rt(t,i)),rt=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){t.forEach(o=>rt(e,o,r));return}let i=v(e,r||t.$entity||t.$relation||t.$thing);Object.entries(t).forEach(([o])=>{o.startsWith("$")||no(e,t,o,i);});},no=(e,t,r,i)=>{let o=t[r];if(!o)return;let n=i.dataFields?.find(s=>s.path===r);if(n){n.contentType==="JSON"&&o!=null&&(t[r]=JSON.stringify(o));return}let l=i.linkFields?.find(s=>s.path===r);if(l){let s=l.oppositeLinkFieldsPlayedBy[0]?.thing;rt(e,o,s);return}if(i.thingType==="relation"){let s=i.roles[r],[u]=s.playedBy||[];if(!u)throw new Error(`Role ${s.name} in ${i} is not played by anything`);rt(e,o,u.thing);}};var hn=async(e,t,r,i)=>{let o=Array.isArray(e)?e:[e],n=o.map(u=>Wt(u,!0)),s=(await qe(n,t,r,i)).bql.res;return o.map((u,f)=>{let c=v(t,u.$thing);return pn({mut:u,node:s[f],schema:t,thing:c})})},un=new Set(["$op","$bzId","$parentKey"]),oo=new Set(["$relation","$entity","$id",...un]),Wt=(e,t)=>{let r={};e.$fields?.forEach(o=>{typeof o=="string"?r[o]=o:r[o.$path]=o;});let i={};for(let o in e){if(un.has(o)||oo.has(o)&&!t)continue;let n=e[o];o.startsWith("$")?i[o]=n:Array.isArray(n)?n[0]&&typeof n[0]=="object"&&(r[o]={$path:o,...Wt(n[0],!1)}):radash.isObject(n)&&(r[o]={$path:o,...Wt(n,!1)});}return i.$fields=Object.values(r),i},pn=e=>{let{mut:t,node:r,schema:i,thing:o}=e,n=$n(o),l=ao(r);if(Array.isArray(t))return t.map(u=>{let f=l[u.$id];return f?ln({mut:u,node:f,schema:i,thing:o,...n}):u});let s=l[t.$id];return ln({mut:t,node:s,schema:i,thing:o,...n})},ln=e=>{let{mut:t,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:l,roleFieldMap:s}=e,{$fields:u,...f}=t;if(!r)return f;let c=fn({$fields:t.$fields,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:l,roleFieldMap:s}),d={...f,[De]:c};for(let a in t){if(a.startsWith("$"))continue;let p=t[a];if(n[a]||!p||typeof p!="object"){d[a]=p;continue}let $=l[a]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||s[a]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${o.name}" does not have field "${a}"`);let y=v(i,$);d[a]=pn({mut:p,schema:i,node:r[a],thing:y});}return d},fn=e=>{let{$fields:t,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:l,roleFieldMap:s}=e,u=t||so(o),f={$id:r.$id};return u.forEach(c=>{let d=typeof c!="string",a=d?c.$path:c,p=r[a];if(n[a]){f[a]=p;return}let $=l[a]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||s[a]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${o.name}" does not have field "${a}"`);if(!d){p&&(f[a]=Array.isArray(p)?p.map(cn):cn(p));return}let y=v(i,$),m=$n(y);f[a]=Array.isArray(p)?p.map(B=>dn({...m,$fields:c.$fields,value:B,schema:i,thing:y})):dn({...m,$fields:c.$fields,value:p,schema:i,thing:y});}),f},so=e=>{let t=[];return e.dataFields?.forEach(r=>{t.push(r.path);}),e.linkFields?.forEach(r=>{t.push(r.path);}),e.thingType==="relation"&&t.push(...Object.keys(e.roles)),t},cn=e=>{if(typeof e=="string")return e;if(!e||typeof e!="object")throw new Error(`"${JSON.stringify(e)}" is neither an id nor an object with prop "$id"`);if(typeof e.$id!="string")throw new Error(`"${JSON.stringify(e)}" is does not have prop "$id"`);return e.$id},dn=e=>{let{value:t}=e;if(!t||typeof t!="object"||!t.$id)throw new Error(`"${JSON.stringify(e)}" is neither an id nor an object with prop "$id"`);return fn({...e,node:t})},$n=e=>{let t=Object.fromEntries(e.dataFields?.map(o=>[o.path,o])||[]),r=Object.fromEntries(e.linkFields?.map(o=>[o.path,o])||[]),i=e.thingType==="relation"?e.roles||{}:{};return {dataFieldMap:t,linkFieldMap:r,roleFieldMap:i}},ao=e=>{if(!Array.isArray(e))return e&&typeof e=="object"&&e.$id?{[e.$id]:e}:{};let t={};return e.forEach(r=>{!r||typeof r!="object"||!r.$id||(t[r.$id]=r);}),t};var mn=he,Pe=(e,t)=>t.data?{...e,bql:{...e.bql,current:t.data}}:e,lo=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),co=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),ho=(e,t)=>({...e,typeDB:{...e.typeDB,tqlMutation:t.data}}),uo=(e,t)=>({...e,typeDB:{...e.typeDB,tqlRes:t.data}}),po=async e=>Object.keys(e.bql.current).length?ft(e.bql.current,e.schema,e.config):ft(e.bql.raw,e.schema,e.config),fo=async e=>sn(e.bql.current,e.schema,e.config,e.handles),$o=async e=>hn(e.bql.current,e.schema,e.config,e.handles),mo=async e=>Fr(e.bql.current,e.schema),yo=async e=>wr(e.bql.things,e.bql.edges,e.schema),go=async e=>$r(e.typeDB.tqlMutation,e.handles,e.config),Bo=async e=>mr(e.typeDB.tqlRes,e.bql.things,e.bql.edges,e.schema,e.config),Eo=()=>!0,Fo=e=>Ie(e.bql.current),we=H("error","error",V((e,t)=>({...e,error:t.error}))),bo=be("stringify",{stringify:Y(async e=>an(e.bql.raw,e.schema),H("done","enrich",V(Pe)),we),enrich:Y(po,H("done","preQuery",yt(Eo),V(Pe)),H("done","parseBQL",V(Pe)),we),preHookDependencies:Y($o,H("done","enrich",V(Pe)),we),preQuery:Y(fo,H("done","preHookDependencies",yt(Fo),V(Pe)),H("done","parseBQL",V(Pe)),we),parseBQL:Y(mo,H("done","buildMutation",V(co)),we),buildMutation:Y(yo,H("done","runMutation",V(ho)),we),runMutation:Y(go,H("done","parseMutation",V(uo)),we),parseMutation:Y(Bo,H("done","success",V(lo)),we),success:mn(),error:mn()},e=>e),wo=async e=>new Promise((t,r)=>{me(bo,i=>{i.machine.state.name==="success"&&t(i.context),i.machine.state.name==="error"&&r(i.context);},e);}),yn=async(e,t,r,i)=>wo({bql:{raw:e,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:t,config:r,handles:i,depthLevel:0,error:null});immer.enableMapSet();var zt=class{schema;config;dbHandles;constructor({schema:t,config:r}){this.schema=t,this.config=r;}getDbHandles=()=>this.dbHandles;init=async()=>{let t={typeDB:new Map,surrealDB:new Map};await Promise.all(this.config.dbConnectors.map(async i=>{if(i.provider==="surrealDB"){let o=new surrealdb_js.Surreal;await o.connect(i.url,{namespace:i.namespace,database:i.dbName,auth:{namespace:i.namespace,database:i.dbName,username:i.username,password:i.password}}),t.surrealDB.set(i.id,{client:o});}if(i.provider==="typeDB"&&i.dbName){let[o,n]=await radash.tryit(typedbDriver.TypeDB.coreDriver)(i.url);if(o){let l=`[BORM:${i.provider}:${i.dbName}:core] ${o.message??"Can't create TypeDB Client"}`;throw new Error(l)}try{let l=await n.session(i.dbName,typedbDriver.SessionType.DATA);t.typeDB.set(i.id,{client:n,session:l});}catch(l){let s=`[BORM:${i.provider}:${i.dbName}:session] ${(l.messageTemplate?._messageBody()||l.message)??"Can't create TypeDB Session"}`;throw new Error(s)}}if(i.provider==="typeDBCluster"&&i.dbName){let o=new typedbDriver.TypeDBCredential(i.username,i.password,i.tlsRootCAPath),[n,l]=await radash.tryit(typedbDriver.TypeDB.cloudDriver)(i.addresses,o);if(n){let s=`[BORM:${i.provider}:${i.dbName}:core] ${n.message??"Can't create TypeDB Cluster Client"}`;throw new Error(s)}try{let s=await l.session(i.dbName,typedbDriver.SessionType.DATA);t.typeDB.set(i.id,{client:l,session:s});}catch(s){let u=`[BORM:${i.provider}:${i.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(u)}}}));let r=vt(this.schema,t);this.schema=r,this.dbHandles=t;};#e=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#e(),this.schema);define=async()=>(await this.#e(),Vt(this.config,this.schema,this.dbHandles));query=async(t,r)=>{await this.#e();let i={...this.config,query:{...it.query,...this.config.query,...r}},o=Array.isArray(t),n=o?t:[t],[l,s]=await radash.tryit(qe)(n,this.schema,i,this.dbHandles);if(l){let f=new Error(l.error);throw f.stack=l.error.stack,f}let u=s.bql.res;return o?u:u[0]};mutate=async(t,r)=>{await this.#e();let i={...this.config,mutation:{...it.mutation,...this.config.mutation,...r}},[o,n]=await radash.tryit(yn)(t,this.schema,i,this.dbHandles);if(o){let s=new Error(o.error.message);throw s.stack=o.error.stack,s}return n.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:r})=>{r.isOpen()&&await r.close(),await t.close();});}},Sc=zt;//! Todo: delete when this works with the new $thing and $thingType fields
49
54
  //! Todo: Sandbox the function in nodeCompute() instead of the existing fieldCompute()
50
55
  //! Todo: Sandbox the function in computeFunction()
51
56
  //! reads all the insertions and gets the first match. This means each id must be unique
52
57
  //!old
53
58
 
54
- module.exports = Fc;
59
+ module.exports = Sc;
package/dist/index.mjs CHANGED
@@ -1,13 +1,14 @@
1
- import { isObject, isArray, shake, tryit, parallel, clone, mapEntries, listify, pick } from 'radash';
1
+ import { isObject, isArray, shake, tryit, parallel, clone, mapEntries, listify, pick, isDate } from 'radash';
2
2
  import { TypeDBOptions, TransactionType, SessionType, TypeDB, TypeDBCredential } from 'typedb-driver';
3
- import { Surreal } from 'surrealdb.node';
3
+ import { Surreal } from 'surrealdb.js';
4
4
  import { enableMapSet, produce, isDraft, current } from 'immer';
5
5
  import { traverse, getNodeByPath } from 'object-traversal';
6
6
  import { v4 } from 'uuid';
7
7
  import { isSet } from 'util/types';
8
8
  import 'acorn';
9
+ import { nanoid } from 'nanoid';
9
10
 
10
- var it={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var Fn=e=>{let t=[],r=new Map;return e.forEach(i=>{let{dbPath:o,contentType:n}=i,l=`${o}-${n}`;r.has(l)||(r.set(l,!0),t.push(i));}),t},_t=async(e,t,r)=>{let o=(()=>{let y="",m=[];y+=`
11
+ var it={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var wn=e=>{let t=[],r=new Map;return e.forEach(i=>{let{dbPath:o,contentType:n}=i,l=`${o}-${n}`;r.has(l)||(r.set(l,!0),t.push(i));}),t},Vt=async(e,t,r)=>{let o=(()=>{let y="",m=[];y+=`
11
12
  `,Object.keys(t.entities).forEach(g=>{let L=t.entities[g],{idFields:D,dataFields:A,linkFields:C,name:j}=L,N=[],se=[],K=[];if("extends"in L){let E=t.entities[L.extends];E.dataFields&&E.dataFields.forEach(Q=>{N.push(Q.dbPath);}),E.linkFields&&E.linkFields.forEach(Q=>{se.push(Q.path);}),E.idFields&&E.idFields.forEach(Q=>{K.push(Q);});}y+=`${j} sub ${"extends"in L?L.extends:"entity"},
12
13
  `;let R=[];if(D&&D.length>0){let E=new Set(D),b=Array.from(E).map(F=>`${F}`).join(", ");K.includes(b)||(y+=` owns ${b} @key,
13
14
  `,R.push(b));}if(A&&A.length>0&&A.forEach(E=>{!N.includes(E.dbPath)&&!R.includes(E.dbPath)&&(y+=` owns ${E.dbPath},
@@ -23,7 +24,7 @@ var it={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},muta
23
24
  `),y+=`
24
25
  `;});let B=`define
25
26
 
26
- `;return Fn(m).forEach(g=>{if(B+=`${g.dbPath} sub attribute,
27
+ `;return wn(m).forEach(g=>{if(B+=`${g.dbPath} sub attribute,
27
28
  `,g.contentType==="TEXT"||g.contentType==="ID"||g.contentType==="JSON")B+=` value string;
28
29
  `;else if(g.contentType==="EMAIL")B+=` value string,
29
30
  `,B+=` regex '^(?=.{1,64}@)[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*@[^-][A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$';
@@ -32,21 +33,25 @@ var it={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},muta
32
33
  `;else if(g.contentType==="NUMBER")B+=` value long;
33
34
  `;else throw new Error(`Conversion of borm schema to TypeDB schema for data type "${g.contentType}" is not implemented`)}),`${B}
34
35
 
35
- ${y}`})(),n=e.dbConnectors[0].id,l=r.typeDB.get(n)?.session,s=r.typeDB.get(n)?.client;if(!l){console.log("Session Status: ","NO SESSION");return}await l.close();let[{dbName:h}]=e.dbConnectors;await(await s.databases.get(h)).delete(),await s.databases.create(h);let d=await s.session(e.dbConnectors[0].dbName,SessionType.SCHEMA),c=await d.transaction(TransactionType.WRITE);await c.query.define(o),await c.commit(),await c.close();let a=await d.transaction(TransactionType.READ);(await(await a.query.match("match $a sub thing;")).collect()).forEach(async y=>{y.get("a");}),await a.close();};var ae=Symbol.for("queryPath"),We=Symbol.for("stepPrint"),Qe=Symbol.for("edgeType"),Be=Symbol.for("edgeSchema"),De=Symbol.for("dbNode"),ot=Symbol.for("isTransformed"),de=Symbol.for("fieldSchema"),$e=Symbol.for("sharedMetadata"),Te=Symbol.for("suqlMetadata");var Vt={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var Ht=({linkField:e,originalRelation:t,withExtensionsSchema:r})=>{let i=r.relations[e.relation].subTypes||[],o=[e.relation,...i],n=`<-\`${t}_${e.plays}\`<-(\`${o.join("`,`")}\`)`;if(e.target==="relation")return n;if(e.target==="role"){let[l]=e.oppositeLinkFieldsPlayedBy,s=r.entities[l.thing]?.subTypes||r.relations[l.thing]?.subTypes||[],h=[l.thing,...s],p=`->\`${t}_${l.plays}\`->(\`${h.join("`,`")}\`)`;return `${n}${p}`}else throw new Error("Unsupported linkField target")};var Jt=(e,t,r)=>r?t:`${e}\xB7${t}`;var vt=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))))[0],xe=(e,t)=>Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))),Yt=(e,t)=>{let r=[],i=produce(e,n=>traverse(n,({key:l,value:s,meta:h})=>{if(h.depth===2&&(l&&(s.dataFields=s.dataFields?.map(p=>({...p,cardinality:p.cardinality||"ONE",dbPath:Jt(l,p.path,p.shared)}))),s.extends)){if(!s.defaultDBConnector.as)throw new Error(`[Schema] ${l} is extending a thing but missing the "as" property in its defaultDBConnector`);let p=n.entities[s.extends]||n.relations[s.extends],d=[s.extends,...p.allExtends||[]];if(s.allExtends=d,d.forEach(c=>{if(n.entities[c])n.entities[c].subTypes=[l,...n.entities[c].subTypes||[]];else if(n.relations[c])n.relations[c].subTypes=[l,...n.relations[c].subTypes||[]];else throw new Error(`[Schema] ${l} is extending a thing that does not exist in the schema: ${c}`)}),s.idFields=p.idFields?Array.from(new Set((s.idFields||[]).concat(p.idFields))):s.idFields,s.dataFields=p.dataFields?(s.dataFields||[]).concat(p.dataFields.map(c=>{let a=s.extends,f=e.entities[a]||e.relations[a];for(;!f.dataFields?.find(u=>u.path===c.path);)a="extends"in f?f.extends:void 0,f=e.entities[a]||e.relations[a];return {...c,dbPath:Jt(a,c.path,c.shared),[$e]:{inheritanceOrigin:c[$e]?.inheritanceOrigin||s.extends}}})):s.dataFields,"roles"in p){let c=s,a=p;if(a.roles){let f=mapEntries(a.roles,(u,$)=>[u,{...$,[$e]:{inheritanceOrigin:$[$e]?.inheritanceOrigin||s.extends}}]);c.roles={...c.roles||{},...f};}}s.linkFields=p.linkFields?(s.linkFields||[]).concat(p.linkFields.map(c=>({...c,[$e]:{inheritanceOrigin:c[$e]?.inheritanceOrigin||s.extends}}))):s.linkFields,p?.hooks?.pre&&(s.hooks=s.hooks||{},s.hooks.pre=s.hooks.pre||[],s.hooks.pre=[...p?.hooks?.pre||[],...s?.hooks?.pre||[]]);}},{traversalType:"breadth-first"}));return traverse(e,({key:n,value:l,meta:s})=>{if(n==="linkFields"){let p=(()=>{if(!s.nodePath)throw new Error("No path");let[c,a]=s.nodePath.split(".");return {thing:a,thingType:c==="entities"?"entity":c==="relations"?"relation":""}})(),d=Array.isArray(l)?l.map(c=>({...c,...p})):[{...l,...p}];r.push(...d);}}),produce(i,n=>traverse(n,({value:l,key:s,meta:h})=>{if(h.depth===2&&l.idFields&&!l.id){l.name=s;let p=()=>{if(h.nodePath?.split(".")[0]==="entities")return "entity";if(h.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};l.thingType=p();let d=Object.keys(t).find(c=>t[c]?.get(l.defaultDBConnector.id));if(l.db=d,l.dbContext=Vt[d],l.computedFields=[],l.virtualFields=[],l.requiredFields=[],l.enumFields=[],l.fnValidatedFields=[],"roles"in l&&Object.entries(l.roles).forEach(([a,f])=>{f.fieldType="roleField";let u=r.filter(w=>w.relation===s&&w.plays===a)||[];f.playedBy=u,f.name=a;let $=[...new Set(u.map(w=>w.thing))];f.$things=$;let y=f[$e]?.inheritanceOrigin||l.name;if($.length>1)throw new Error(`Not supported yet: Role ${a} in ${l.name} is played by multiple things: ${$.join(", ")}`);let m=$.flatMap(w=>{let L=G(e,w)?.subTypes||[];return [w,...L]}),B=`->\`${y}_${a}\`->(\`${m.join("`,`")}\`)`;f[Te]={queryPath:B};}),"linkFields"in l&&l.linkFields){let c=l;c.linkFields?.forEach(a=>{a.fieldType="linkField";let f=i.relations[a.relation];if(f.roles?.[a.plays]===void 0)throw new Error(`The role ${a.plays} is not defined in the relation ${a.relation} (linkField: ${a.path})`);if(a.target==="relation"&&(a.$things=[a.relation],a.oppositeLinkFieldsPlayedBy=[{plays:a.path,thing:a.relation,thingType:"relation"}]),a.target==="role"){let y=r.filter(m=>m.relation===a.relation&&m.plays!==a.plays)||[];if(a.oppositeLinkFieldsPlayedBy=y,a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter(m=>m.target==="role"),a.$things=a.oppositeLinkFieldsPlayedBy.map(m=>m.thing),a.oppositeLinkFieldsPlayedBy.length>1)throw new Error(`Not supported: LinkField ${a.path} in ${c.name} has multiple candidates ${a.oppositeLinkFieldsPlayedBy.map(m=>m.thing).join(",")} and this is not yet supported. Please target a single one using targetRoles with a single role`)}let u=f.roles?.[a.plays][$e]?.inheritanceOrigin??a.relation,$=Ht({linkField:a,originalRelation:u,withExtensionsSchema:i});a[Te]={queryPath:$};});}}if(typeof l=="object"&&"playedBy"in l){let p=[...new Set(l.playedBy.map(d=>d.thing))];if(p.length>1)throw new Error(`[Schema] roleFields can be only played by one thing. Role: ${s}, path:${h.nodePath}, played by: ${p.join(", ")}`);if(l.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${s}, path:${h.nodePath}`)}if(h.depth===4){let[p,d]=h.nodePath?.split(".")||[],c=n[p][d];!isArray(l)&&typeof l=="object"&&(l.validations&&(l.validations.required&&c.requiredFields.push(l.path),l.validations.enum&&c.enumFields.push(l.path),l.validations.fn&&c.fnValidatedFields.push(l.path)),l.default?l.isVirtual?c.virtualFields.push(l.path):c.computedFields.push(l.path):l.isVirtual&&c.virtualFields.push(l.path));}}))},G=(e,t)=>{if(t in e.entities)return e.entities[t];if(t in e.relations)return e.relations[t];throw new Error(`${t} is not defined in the schema`)},x=(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)}`)},_e=(e,t)=>{let r=e.dataFields?.find(n=>n.path===t);if(r)return ["dataField",r];let i=e.linkFields?.find(n=>n.path===t);if(i)return ["linkField",i];let o="roles"in e?e.roles[t]:void 0;if(o)return ["roleField",o];throw new Error(`Field ${t} not found in schema, Defined in $filter`)},Ve=(e,t)=>{let r=x(e,t);if(r?.idFields?.length&&r?.idFields?.length>1)throw new Error(`Multiple ids not yet enabled / composite ids: ${r?.idFields}`);let[i]=r.idFields;return i},Gt=(e,t)=>{let r=e.$thing||e.$entity||e.$relation;if(!r)throw new Error("[Internal] No thing found");if(e.$entity)return "entity";if(e.$relation)return "relation";if(t.entities[r])return "entity";if(t.relations[r])return "relation";throw new Error("No thing found")},lt=(e,t,r)=>{let i=x(e,t),o=i.linkFields?.find(s=>s.path===r);if(o)return o;let n=i.dataFields?.find(s=>s.path===r);if(n)return n;let l="roles"in i?i.roles?.[r]:void 0;if(l)return l;throw new Error(`Field ${r} not found in schema`)},ct=(e,t,r)=>lt(e,t,r)?.cardinality,ue=(e,t)=>{let r=e.dataFields?.map(u=>u.path)||[],i=e.linkFields?.map(u=>u.path)||[],o="roles"in e?listify(e.roles,u=>u):[],n=[...r||[],...i||[],...o||[]],s=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...n];if(!t)return {fields:n,dataFields:r,roleFields:o,linkFields:i};let h=t.$fields?t.$fields.map(u=>{if(typeof u=="string"){if(u.startsWith("$")||u.startsWith("%"))return;if(!n.includes(u))throw new Error(`Field ${u} not found in the schema`);return u}if("$path"in u&&typeof u.$path=="string")return u.$path;throw new Error("[Wrong format] Wrongly structured query")}):listify(t,u=>{if(!(u.startsWith("$")||u.startsWith("%"))){if(!n.includes(u))throw new Error(`[Schema] Field ${u} not found in the schema`);return u}}).filter(u=>u!==void 0),p=t.$filter?listify(t.$filter,u=>u.toString().startsWith("$")?void 0:u.toString()).filter(u=>u&&r?.includes(u)):[],d=t.$filter?listify(t.$filter,u=>u.toString().startsWith("$")?void 0:u.toString()).filter(u=>u&&[...o||[],...i||[]].includes(u)):[],c=[...h,...p].filter(u=>!u?.startsWith("%")).filter(u=>!s.includes(u)).filter(u=>u),a=t.$filter?xe(t.$filter,(u,$)=>p.includes(u)):{},f=t.$filter?xe(t.$filter,(u,$)=>d.includes(u)):{};return {fields:n,dataFields:r,roleFields:o,linkFields:i,usedFields:h,usedLinkFields:i.filter(u=>h.includes(u)),usedRoleFields:o.filter(u=>h.includes(u)),usedDataFields:r.filter(u=>h.includes(u)),unidentifiedFields:c,...p.length?{localFilters:a}:{},...d.length?{nestedFilters:f}:{}}};var Xt=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},er=(e,t,r)=>{let o=(r.nodePath||"").split("."),n=isArray(t)?o.slice(0,-2).join("."):o.slice(0,-1).join(".");return t?getNodeByPath(e,n):{}},Ee=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var He=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),pe=e=>{if(Array.isArray(e))return e.map(t=>current(t));if(e&&typeof e=="object"){let t=isDraft(e)?current(e):e,r={};return Object.entries(t).forEach(([i,o])=>{r[i]=isDraft(o)?current(o):o;}),r}else return e},oe=(e,t)=>{if(e===void 0)throw new Error("Value is undefined");return e},M=(e,t)=>{let r="";for(let i=0;i<t;i++)r+=" ";return `${r}${e}`};var Re=(e,t)=>{if(t.fieldType==="linkField"){let r=t.oppositeLinkFieldsPlayedBy;if(r?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!r?.length)throw new Error(`[Internal] Field ${e} should have a player`);return r}else if(t.fieldType==="roleField"){if([...new Set(t.playedBy?.map(r=>r.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 tr=(e,t,r)=>{let i=isArray(e[t])?e[t]:[e[t]];if(!i.every(o=>typeof o=="object"))if(i.every(o=>typeof o=="string")){let o=Re(t,r),[n]=o,l=e.$op==="create"?"link":"replace",s=n.thing,h=n.thingType;if(i.some(p=>p.startsWith("_:")))throw new Error("[Not supported] At least one child of a replace is a tempId");e[t]={$id:e[t],$op:l,$thing:s,$thingType:h,$bzId:`S_${v4()}`};}else throw new Error(`[Mutation Error] Replace can only be used with a single id or an array of ids. (Field: ${t} Nodes: ${JSON.stringify(i)} Parent: ${JSON.stringify(e,null,2)})`)};var Le=(e,t,r)=>{let i=x(r,t),{usedDataFields:o}=ue(i,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"&&o.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&o.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var Ke=(e,t,r)=>{let i=x(r,t),{usedFields:o}=ue(i,t);return t.$op?(Le(e,t,r),t.$op):t.$id||t.$filter?o.length>0?(Le(e,{...t,$op:"update"},r),"update"):(Le(e,{...t,$op:"link"},r),"link"):t.$tempId?o.length>0?(Le(e,{...t,$op:"create"},r),"create"):(Le(e,{...t,$op:"create"},r),"link"):(Le(e,{...t,$op:"create"},r),"create")};var nr=(e,t)=>{let i=(isArray(e.$root)?e.$root:[e.$root]).map(o=>{let n=Ke(o,o,t);return {...{...o.$thing?{}:{$thing:o.$entity||o.$relation},...o.$thingType?{}:{$thingType:Gt(o,t)},...o.$op?{}:{$op:n},...o.$bzId?{}:{$bzId:`R_${v4()}`}},...o}});e.$root=isArray(e.$root)?i:i[0];};var Ue=(e,t)=>{let r=t[We];return isSet(r)?r.has("clean")?(Reflect.set(t,We,r.add("clean")),!0):!1:(Reflect.set(t,We,new Set(["clean"])),!0)};var ir=(e,t,r)=>{if(Ue("split_ids",e)){let i=(isArray(e[t])?e[t]:[e[t]]).flatMap(o=>{if(isObject(o)&&"$id"in o&&isArray(o.$id)){let n=o;if(x(r,n),!n.$bzId)throw new Error("[Internal Error] No bzId found");return n.$id.map((l,s)=>({...pe(n),$id:l,$bzId:`${n.$bzId}_${s}`,...Ee(n)}))}return o});(i.length>isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=i);}};var sr=(e,t,r,i)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(n=>{let l=Re(t,r),[s]=l,h=Ke(e,{...n,$thing:s.thing,$thingType:s.thingType},i),p=n.$bzId?n.$bzId:n.$tempId?n.$tempId:`N_${v4()}`;if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);return {...n,[Be]:r,$thing:s.thing,$thingType:s.thingType,$op:h,$bzId:p}});e[t]=isArray(e[t])?o:o[0];};var An=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,In=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,ar=e=>{let r=e.toString().replace(An,"").trim().split("=>")[0].split("{")[0].replace(In,"").trim(),i=r.substring(r.indexOf("(")+1,r.lastIndexOf(")")).trim();return i?(i.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(n=>n.includes("{")&&n.includes("}")?(n.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(s=>s.split(":")[0].trim().replace(/['"[\]]/g,"")):n.trim()).filter(Boolean):[]};var Ae=({currentThing:e,fieldSchema:t,mandatoryDependencies:r=!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(r){let{fn:o}=t.default,l=ar(o).filter(s=>!(s in e));if(l.length)throw new Error(`Virtual field: Missing arguments ${l.join(", ")}`)}if(!t.default.fn)throw new Error("[Schema] No fn in default field schema");return "default"in t?t.default?.fn(e):void 0};var lr=(e,t,r)=>{let i=e[t];i&&(isArray(i)?i:[i]).forEach(o=>{let n=x(r,o),{unidentifiedFields:l}=ue(n,o),{computedFields:s,virtualFields:h}=n,p=listify(o,(a,f)=>f!==void 0?a:void 0),d=p.filter(a=>h?.includes(a));if(d.length>0)throw new Error(`Virtual fields can't be sent to DB: "${d.join(",")}"`);if(s.filter(a=>!p.includes(a)).forEach(a=>{let f=n.dataFields?.find(B=>B.path===a),$=n.linkFields?.find(B=>B.path===a)?.oppositeLinkFieldsPlayedBy[0],y="roles"in n?vt(n.roles,(B,w)=>B===a):void 0,m=f||$||y;if(!m)throw new Error(`no field Def for ${a}`);if(o.$op==="create"&&!o[a]){let B=Ae({currentThing:o,fieldSchema:m,mandatoryDependencies:!0});o[a]=B;}}),l.length>0)throw new Error(`Unknown fields: [${l.join(",")}] in ${JSON.stringify(o)}`)});};var Je=(e,t)=>{let r=x(t,e).hooks;if(r?.pre){let i=`on${Xt(e.$op)}`;return r.pre.filter(l=>!l.triggers||l.triggers[i]?.()).flatMap(l=>l.actions)}return []};var dr=(e,t,r,i)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(n=>{if("$thing"in n){if(n.$fields)return n;let{requiredFields:l,enumFields:s,fnValidatedFields:h,dataFields:p}=x(r,n);if("$op"in n&&n.$op==="create"&&l.forEach(d=>{if(!(d in n))throw new Error(`[Validations] Required field "${d}" is missing.`)}),("$op"in n&&n.$op==="update"||n.$op==="create")&&s.forEach(d=>{if(d in n){let c=p?.find(a=>a.path===d)?.validations?.enum;if(!c)throw new Error(`[Validations] Enum field "${d}" is missing enum options.`);if(isArray(n[d]))n[d].some(a=>{if(!c.includes(a))throw new Error(`[Validations] Option "${a}" is not a valid option for field "${d}".`)});else if(c&&!c.includes(n[d]))throw new Error(`[Validations] Option "${n[d]}" is not a valid option for field "${d}".`)}}),("$op"in n&&n.$op==="update"||n.$op==="create")&&h.forEach(d=>{if(d in n)try{let c=p?.find(a=>a.path===d)?.validations?.fn;if(!c)throw new Error("Missing validation function.");if(!c(n[d]))throw new Error("Failed validation function.")}catch(c){throw new Error(`[Validations:attribute:${d}] ${c.message}`)}}),isObject(n)&&"$thing"in n){let d=n.$thing,c=n,a=clone(pe(e)),f=clone(pe(c)),u=i.mutation?.context||{},$=clone(pe(n[De]||{}));Je(c,r).forEach(m=>{if(m.type==="validate"){if(m.severity!=="error")return;try{let B=m.fn(f,a,u,$);if(B===!1)throw new Error(`${m.message}.`);if(B!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(B){throw new Error(`[Validations:thing:${d}] ${B.message}`)}}});}}});};var ur=(e,t,r,i)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(n=>{if(He(n)){if(n.$fields||n[ot])return n;let l=Je(n,r).filter(c=>c.type==="transform"),s=clone(pe(e)),h=clone(pe(n)),p=i.mutation?.context||{},d=clone(pe(n[De]||n.$dbNode));return l.forEach(c=>{let a=c.fn(h,s,p,d||{});Object.keys(a).length!==0&&(n={...h,...a,...Ee(n),[ot]:!0});}),n}});e[t]=isArray(e[t])?o:o[0];};var pr=(e,t,r)=>{let i=Re(t,r),[o]=i;e[t]={$thing:o.thing,$thingType:o.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Be]:r};};var Ie=e=>{if(Array.isArray(e)){for(let t of e)if(Ie(t))return !0;return !1}if(e.$fields)return !0;for(let t in e){if(t.startsWith("$"))continue;let r=e[t];if(r&&typeof r=="object"&&Ie(e[t]))return !0}return !1};var _n=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(Ue("set_tempId",e))if(e.$tempId?.startsWith("_:")){let r=e.$tempId.substring(2);e.$tempId=r,e.$bzId=r;}else throw new Error('[Wrong format] TempIds must start with "_:"');else throw new Error("[Internal] TempId already modified")},Vn=(e,t)=>{},ft=(e,t,r)=>{let i={$rootWrap:{$root:e}},o=Ie(Array.isArray(e)?e:[e]),n=produce(i,l=>traverse(l,({value:s,parent:h,key:p,meta:d})=>{if(!(!h||!p)&&isObject(s)){let c=d.nodePath?.split(".")||[];if(!("$root"in s)){if(!("$thing"in s||"$entity"in s||"$relation"in s)){let u=["$fields","$dbNode","$filter"],$=c[c.length-1],y=c[c.length-2];if(p==="$root")throw new Error("Root things must specify $entity or $relation");if(!u.includes($)&&!u.includes(y))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(s)?current(s):s)}`)}}let a=s,f=c.includes("$filter");Object.keys(a).forEach(u=>{if(_n(a,u),u!=="$root"&&f||u!=="$root"&&(u.startsWith("$")||u.startsWith("%")))return;let $=u!=="$root"?lt(t,a,u):{fieldType:"rootField"};if(!$)throw new Error(`[Internal] Field ${u} not found in schema`);if("contentType"in $)return Vn();if(["rootField","linkField","roleField"].includes($.fieldType)){if(["linkField","roleField"].includes($.fieldType)&&(a[u]===null?pr(a,u,$):tr(a,u,$)),$.fieldType==="rootField"){if(!("$root"in a))throw new Error(`[Internal] Field ${u} is a rootField but the object is not a root`);nr(a,t);}let y=isArray(a[u])?a[u]:[a[u]],m=c.slice(1).join(".");y.forEach(w=>{if(w){if($?.cardinality==="ONE"&&!w.$op&&!w.$id&&!w.$filter&&!w.$tempId&&a.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${m}.${u}`);if(w.$tempId&&!(w.$op===void 0||w.$op==="link"||w.$op==="create"||w.$op==="update"))throw new Error(`Invalid op ${w.$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($.fieldType)&&sr(a,u,$,t),ir(a,u,t),["rootField","linkField","roleField"].includes($.fieldType)&&lr(a,u,t),(isArray(a[u])?a[u]:[a[u]]).forEach(w=>{let g=x(t,w),{unidentifiedFields:L,usedLinkFields:D,usedFields:A,fields:C}=ue(g,w);if(A.forEach(j=>{if(!C.includes(j))throw new Error(`[Schema] Field ${j} not found in the schema`)}),L.length>0)throw new Error(`Unknown fields: [${L.join(",")}] in ${JSON.stringify(s)}`);if(D.length>1){let j=g.linkFields?.filter(N=>D.includes(N.path));j?.some((N,se)=>j.some((K,R)=>{if(se!==R&&N.target!==K.target&&N.relation===K.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),o||(ur(a,u,t,r),dr(a,u,t,r));}});}}));return isArray(n.$rootWrap.$root),n.$rootWrap.$root};var Ze=async(e,t)=>{let r=t.dbConnectors[0].id,i=e.typeDB?.get(r)?.session,o=e.typeDB?.get(r)?.client;if(!i||!i.isOpen()){if(!o)throw new Error("Client not found");i=await o.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(r,{client:o,session:i});}return {client:o,session:i}};var fr=async(e,t,r)=>{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:i}=await Ze(t,r),o=await i.transaction(TransactionType.WRITE),n=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,l=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;try{n&&await o.query.delete(n);let s=l&&o.query.insert(l),h=s?await s.collect():void 0;return await o.commit(),{insertions:h}}catch(s){throw new Error(`Transaction failed: ${s.message}`)}finally{await o.close();}};var $r=async(e,t,r,i,o)=>{let n=[...t,...r],l=n.map(s=>{let h=e.insertions?.find(c=>c.get(`${s.$bzId}`))?.get(`${s.$bzId}`),p=s.$thing||s.$relation||s.$entity,d=p?G(i,p):void 0;if(s.$op==="create"||s.$op==="update"||s.$op==="link"){if(s.$op!=="update"&&!h&&s.$id)return {$id:s.$id,$error:"Does not exist or it's not linked to the parent"};let c=h?.asThing().iid,a=Object.entries(s).filter(([u,$])=>!u.startsWith("$")).reduce((u,[$,y])=>{if(d?.dataFields?.find(B=>B.path===$)?.contentType==="JSON")return u[$]=JSON.parse(y),u;if(s.$thingType==="relation"){let B=n.filter(w=>w.$id&&w.$bzId===y);return B.length===1?(u[$]=B[0].$id,u):(u[$]=y,u)}return u[$]=y,u},{});if(o.mutation?.noMetadata)return a;let f=s.$tempId&&!s.$tempId.startsWith("_:")?{$tempId:`_:${s.$tempId}`}:{};return {$dbId:c,...s,...a,[s.path]:s.$id,...f}}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(l)};var mr=e=>{let t=({value:r})=>(r&&typeof r=="object"&&"$id"in r&&(Object.keys(r).filter(n=>n.startsWith("$")).forEach(n=>delete r[n]),Object.keys(r).filter(n=>typeof n=="symbol").forEach(n=>delete r[n])),r);return produce(e,r=>traverse(r,t))};var Er=async(e,t)=>{let r=d=>{let c=[],a=[],f=m=>{if(m.$id)return m.$id;let B=x(t,m),{idFields:w}=B;if(!w)throw new Error(`no idFields: ${JSON.stringify(m)}`);let[g]=w;if(!g)throw new Error(`no idField: ${JSON.stringify(m)}`);let L=B.dataFields?.find(C=>C.path===g),D=Ae({currentThing:m,fieldSchema:L,mandatoryDependencies:!0}),A=m[g]||m.$id||D;if(!A)throw new Error(`no idValue: ${JSON.stringify(m)}`);return A},u=m=>{if(m.$op==="create"){let B=f(m);if(c.find(w=>w.$id===B&&w.$op==="create"))throw new Error(`Duplicate id ${B} for node ${JSON.stringify(m)}`);if(a.find(w=>w.$bzId===m.$bzId))throw new Error(`Duplicate $bzId ${m.$bzId} for node ${JSON.stringify(m)}`);c.push({...m,$id:B});return}m.$tempId&&m.$op==="match"||c.push(m);},$=m=>{if(m.$op==="create"){let B=f(m);if(c.find(w=>w.$id===B),a.find(w=>w.$bzId===m.$bzId))throw new Error(`Duplicate %bzId ${m.$bzIdd} for edge ${JSON.stringify(m)}`);a.push({...m,$id:B});return}a.push(m);};return traverse(d,({value:m,parent:B,meta:w})=>{if(!isObject(m))return;let g=m;if(g.$thing){if(!g.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(g)}`);if(!g.$bzId)throw new Error("[internal error] BzId not found");let L=x(t,g),{dataFields:D,roleFields:A,linkFields:C,usedFields:j}=ue(L,g),N=()=>{if(g.$op==="create"||g.$op==="delete")return g.$op;if(g.$op==="update"){let R=j.filter(b=>D?.includes(b)),E=j.filter(b=>A?.includes(b)),Q=j.filter(b=>C?.includes(b));if(R.length>0)return "update";if(E.length>0||Q.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(g)}`)}return "match"},se={...g.$id&&{$id:g.$id},...g.$tempId&&{$tempId:g.$tempId},...g.$filter&&{$filter:g.$filter},$thing:g.$thing,...g.$thingType&&{$thingType:g.$thingType},...shake(pick(g,D||[""])),$op:N(),$bzId:g.$bzId};u(se);let K=g[Be];if(K?.fieldType==="linkField"){if((g.$op==="link"||g.$op==="unlink")&&(g.$id||g.$filter)){if(g.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");c.push({...g,$op:"match"});}let R=K.relation===g.$thing,E=R?g.$bzId:`LT_${v4()}`,b=er(d,B,w).$bzId;if(!b)throw new Error("No parent id found");let F=()=>{if(g.$op==="delete")return R?"match":"delete";if(g.$op==="unlink")return R?"unlink":"delete";if(g.$op==="link"||g.$op==="create")return R?"link":"create";if(g.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},T=x(t,{$thing:K.relation,$thingType:"relation"});if(!Object.keys(T.roles).includes(K.plays))throw new Error(`[Wrong format] Field ${K.plays} is not a role of relation ${K.relation}`);let q={$bzId:E,$thing:K.relation,$thingType:"relation",...g.$tempId?{$tempId:g.$tempId}:{},$op:F(),...R?{}:{[K.path]:g.$bzId},[K.plays]:b,[Be]:K,[Qe]:"linkField"};$(q),(g.$op==="unlink"||F()==="unlink")&&R&&$({$thing:K.relation,$thingType:"relation",$bzId:E,$op:"match",[K.plays]:b,[Be]:K,[Qe]:"linkField"});}if(g.$thingType==="relation"){let R=xe(g,(b,F)=>A.includes(b)),E=mapEntries(R,(b,F)=>isArray(F)?[b,F]:isObject(F)?[b,F.$bzId]:[b,F]),Q=xe(m,(b,F)=>b.startsWith("$")||b.startsWith("Symbol"));if(Object.keys(R).filter(b=>!b.startsWith("$")).length>0){if(g.$op==="create"||g.$op==="delete"){let b=()=>{if(g.$op==="create")return "link";if(g.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},F=x(t,g).roles,T=mapEntries(E,(q,k)=>{let P=F[q]?.cardinality;if(!P)throw new Error(`Role ${q} not found in schema`);if(Array.isArray(k)){if(P==="ONE"){if(k.length>1)throw new Error(`[Error] Role ${q} is not a MANY relation`);return [q,k[0].$bzId||k[0]]}return [q,k.map(J=>J.$bzId||J)]}return [q,k.$bzId||k]}),S={...Q,$thing:g.$thing,$thingType:"relation",$op:b(),...T,$bzId:g.$bzId,[Qe]:"roleField"};$(S);return}if(g.$op==="match"||g.$op==="update"&&Object.keys(R).length>0){let b=0;Object.entries(R).forEach(([F,T])=>{let S=isArray(T)?T:[T],q=k=>k==="create"||k==="replace"?"link":k;S.forEach(k=>{if(!k)return;let P=q(k.$op);if(P==="replace")throw new Error("Not supported yet: replace on roleFields");if(P==="unlink"&&b>0)throw b+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let J={...Q,$thing:g.$thing,$thingType:"relation",$op:P==="delete"?"unlink":P,[F]:k.$bzId,$bzId:g.$bzId,[Qe]:"roleField"};$(J);});});}}}}}),[c,a]},[i,o]=r(e),n=i.reduce((d,c)=>{if(!c.$bzId)return [...d,c];let a=d.findIndex(f=>f.$bzId===c.$bzId);if(a===-1)return [...d,c];if(d[a].$op==="create"&&c.$op==="match")return d;if(d[a].$op==="match"&&(c.$op==="create"||c.$op==="match"))return [...d.slice(0,a),c,...d.slice(a+1)];throw new Error(`[Wrong format] Wrong operation combination for $tempId "${c.$tempId}". Existing: ${d[a].$op}. Current: ${c.$op}`)},[]),l=o.reduce((d,c)=>{let a=d.find(f=>(f.$id&&f.$id===c.$id||f.$bzId&&f.$bzId===c.$bzId)&&f.$thing===c.$thing&&f.$op===c.$op);if(a){let f={...a};return Object.keys(c).forEach($=>{if(typeof $=="symbol"||$.startsWith("$"))return;let y=a[$],m=c[$];Array.isArray(y)&&Array.isArray(m)?f[$]=Array.from(new Set([...y,...m])):!Array.isArray(y)&&Array.isArray(m)?y!==void 0?f[$]=Array.from(new Set([y,...m])):f[$]=m:Array.isArray(y)&&!Array.isArray(m)?m!==void 0&&(f[$]=Array.from(new Set([...y,m]))):y!==null&&m!==null&&y!==void 0&&m!==void 0?f[$]=Array.from(new Set([y,m])):y==null&&(f[$]=m);}),[...d.filter($=>!(($.$id&&$.$id===c.$id||$.$bzId&&$.$bzId===c.$bzId)&&$.$thing===c.$thing&&$.$op===c.$op)),f]}return [...d,c]},[]);n.forEach(d=>{if((d.$thingType==="relation"||"relation"in d)&&l.filter(c=>c.$bzId===d.$bzId||c.$tempId&&c.$tempId===d.$tempId).length===0){if(d.$op==="delete"||d.$op==="match"||d.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(mr(d))}`)}});let s=[...n,...l],h=new Set(s.filter(d=>d.$tempId).map(d=>d.$tempId)),p=Array.from(h).filter(d=>!s.some(c=>c.$tempId===d&&c.$op==="create"));if(p.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${p.join(", ")}`);return {mergedThings:n,mergedEdges:l}};var Fr=async(e,t,r)=>{let i=a=>{let f=a.$op,u=`$${a.$bzId}`,$=x(r,a),{idFields:y,defaultDBConnector:m}=$,B=m?.path||a.$thing,w=a.$id,g=y?.[0],L=listify(a,(R,E)=>{if(R.startsWith("$")||R.startsWith("%")||R===g||E===void 0||E===null)return "";let Q=$.dataFields?.find(T=>T.path===R);if(!Q?.path)return "";let F=Q.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(Q.contentType))return `has ${F} '${E}'`;if(["NUMBER","BOOLEAN"].includes(Q.contentType))return `has ${F} ${E}`;if(Q.contentType==="DATE"){if(Number.isNaN(E.valueOf()))throw new Error("Invalid format, Nan Date");return E instanceof Date?`has ${F} ${E.toISOString().replace("Z","")}`:`has ${F} ${new Date(E).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${Q.contentType}`)}).filter(R=>R),D=`${u}-atts`,A=listify(a,R=>{if(R.startsWith("$")||R.startsWith("%")||R===g)return "";let E=$.dataFields?.find(F=>F.path===R);if(!E?.path)return "";let b=E.dbPath;return `{${D} isa ${b};}`}).filter(R=>R),C=isArray(w)?`like '${w.join("|")}'`:`'${w}'`,j=w?[`has ${g} ${C}`]:[],N=[...j,...L].filter(R=>R).join(","),se=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${u} isa ${[B,...j].filter(R=>R).join(",")};`;if(f==="update"){if(!A.length)throw new Error("update without attributes");return `${u} isa ${[B,...j].filter(R=>R).join(",")}, has ${D};
36
- ${A.join(" or ")};`}return ""},K=()=>f==="update"||f==="link"||f==="match"?`${u} isa ${[B,...j].filter(R=>R).join(",")};`:"";if(He(a))return {op:f,deletionMatch:se(),insertionMatch:K(),insertion:f==="create"?`${u} isa ${[B,N].filter(R=>R).join(",")};`:f==="update"&&L.length?`${u} ${L.join(",")};`:"",deletion:f==="delete"?`${u} isa ${B};`:f==="update"&&A.length?`${u} has ${D};`:""};throw new Error("in attributes")},o=a=>{let f=a.$op,u=x(r,a),$=`$${a.$bzId}`,y=a.$id,m=u.defaultDBConnector?.path||a.$thing,B="roles"in u?listify(u.roles,E=>E):[],w="roles"in u?mapEntries(u.roles,(E,Q)=>[E,Q.dbConnector?.path||E]):{},g=listify(a,(E,Q)=>{if(!B.includes(E))return null;if(!("roles"in u))throw new Error("This should have roles! ");let b=w[E];return Array.isArray(Q)?Q.map(F=>({path:b,id:F})):{path:b,id:Q}}).filter(E=>E).flat(),L=g.map(E=>{if(!E?.path)throw new Error("Object without path");return `${E.path}: $${E.id}`}),D=g.length>0?`( ${L.join(" , ")} )`:"",A=a[Qe];if(!A)throw new Error("[internal error] Symbol edgeType not defined");let C=D?`${$} ${D} ${A==="linkField"||f==="delete"||f==="unlink"?`isa ${m}`:""}`:"",j=`${$} ${A==="linkField"||f==="delete"?`isa ${m}`:""}`,N=()=>C?f==="link"?`${C};`:f==="create"?`${C}, has id '${y}';`:"":"",se=()=>C&&f==="match"?`${C};`:"",K=()=>C?f==="delete"?`${C};`:f==="match"?`${C};`:"":"",R=()=>C?f==="delete"?`${j};`:f==="unlink"?`${$} ${D};`:"":"";return {deletionMatch:K(),insertionMatch:se(),deletion:R(),insertion:N(),op:""}},n=(a,f)=>{let u=f==="edges"?o:i;if(Array.isArray(a))return a.map(g=>{let{preDeletionBatch:L,insertionMatch:D,deletionMatch:A,insertion:C,deletion:j}=u(g);return shake({preDeletionBatch:L,insertionMatch:D,deletionMatch:A,insertion:C,deletion:j},N=>!N)}).filter(g=>g);let{preDeletionBatch:$,insertionMatch:y,deletionMatch:m,insertion:B,deletion:w}=u(a);return shake({preDeletionBatch:$,insertionMatch:y,deletionMatch:m,insertion:B,deletion:w},g=>!g)},l=n(e),s=Array.isArray(l)?l:[l],h=n(t,"edges"),p=Array.isArray(h)?h:[h],d=[...s,...p];return shake({insertionMatches:d.map(a=>a.insertionMatch).join(" ").trim(),deletionMatches:d.map(a=>a.deletionMatch).join(" ").trim(),insertions:d.map(a=>a.insertion).join(" ").trim(),deletions:d.map(a=>a.deletion).join(" ").trim()},a=>!a)};function X(e){return {enumerable:!0,value:e}}function br(e){return {enumerable:!0,writable:!0,value:e}}var Ce={},ri=()=>!0,wr=()=>({}),Qr=e=>e,ni=(e,t,r,i)=>e.apply(r,i)&&t.apply(r,i),ii=(e,t,r,[i,o])=>t.call(r,e.call(r,i,o),o),Fe=(e,t)=>Object.freeze(Object.create(e,t));function Mr(e,t,r){return e.reduce((i,o)=>function(...n){return r(i,o,this,n)},t)}function Tr(e){return Fe(this,{fn:X(e)})}var Lr={},V=Tr.bind(Lr);var Sr={},mt=Tr.bind(Sr);function Ye(e,t){return t.filter(r=>e.isPrototypeOf(r))}function kr(e,t,...r){let i=Mr(Ye(Sr,r).map(n=>n.fn),ri,ni),o=Mr(Ye(Lr,r).map(n=>n.fn),Qr,ii);return Fe(this,{from:X(e),to:X(t),guards:X(i),reducers:X(o)})}var Dr={},Rr={},H=kr.bind(Dr);kr.bind(Rr,null);function oi(e,t,r){return gt(t,e,r,this.immediates)||e}function Ar(e){let t=new Map;for(let r of e)t.has(r.from)||t.set(r.from,[]),t.get(r.from).push(r);return t}var si={enter:Qr};function he(...e){let t=Ye(Dr,e),r=Ye(Rr,e),i={final:X(e.length===0),transitions:X(Ar(t))};return r.length&&(i.immediates=X(r),i.enter=X(oi)),Fe(si,i)}var ai={enter(e,t,r){let i=this.fn.call(t,t.context,r);return yt.isPrototypeOf(i)?Fe(Ir,{machine:X(i),transitions:X(this.transitions)}).enter(e,t,r):(i.then(o=>t.send({type:"done",data:o})).catch(o=>t.send({type:"error",error:o})),e)}},Ir={enter(e,t,r){if(t.child=me(this.machine,i=>{t.onChange(i),t.child==i&&i.machine.state.value.final&&(delete t.child,t.send({type:"done",data:i.context}));},t.context,r),t.child.machine.state.value.final){let i=t.child.context;return delete t.child,gt(t,e,{type:"done",data:i},this.transitions.get("done"))}return e}};function v(e,...t){let r=X(Ar(t));return yt.isPrototypeOf(e)?Fe(Ir,{machine:X(e),transitions:r}):Fe(ai,{fn:X(e),transitions:r})}var yt={get state(){return {name:this.current,value:this.states[this.current]}}};function be(e,t,r=wr){return typeof e!="string"&&(r=t||wr,t=e,e=Object.keys(t)[0]),Ce._create&&Ce._create(e,t),Fe(yt,{context:X(r),current:X(e),states:X(t)})}function gt(e,t,r,i){let{context:o}=e;for(let{to:n,guards:l,reducers:s}of i)if(l(o,r)){e.context=s.call(e,o,r);let h=t.original||t,p=Fe(h,{current:X(n),original:{value:h}});Ce._onEnter&&Ce._onEnter(t,n,e.context,o,r);let d=p.state.value;return e.machine=p,e.onChange(e),d.enter(p,e,r)}}function li(e,t){let r=t.type||t,{machine:i}=e,{value:o,name:n}=i.state;return o.transitions.has(r)?gt(e,i,t,o.transitions.get(r))||i:(Ce._send&&Ce._send(r,n),i)}var ci={send(e){li(this,e);}};function me(e,t,r,i){let o=Object.create(ci,{machine:br(e),context:br(e.context(r,i)),onChange:X(t)});return o.send=o.send.bind(o),o.machine=o.machine.state.value.enter(o.machine,o,i),o}var Pr=(e,t)=>{if(!t)return;let r=hi(t);return ui(r,e.query)},hi=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),ui=(e,t)=>produce(e,r=>traverse(r,({value:i})=>{if(isObject(i)){let o=i;Object.keys(o).forEach(n=>{(o[n]===void 0||o[n]===null||isArray(o[n])&&o[n].length===0)&&(t?.returnNulls?o[n]=null:delete o[n]),o[n]===void 0&&delete o[n];}),Object.getOwnPropertySymbols(o).forEach(n=>{delete o[n];}),t?.noMetadata===!0&&Object.keys(o).forEach(n=>{n.startsWith("$")&&delete o[n];});}}));var jr=(e,t)=>{for(let o of e)if(!("$entity"in o)&&!("$relation"in o)&&(!("$thing"in o)||!("$thingType"in o)))throw new Error("No entity specified in query");let r=Array.isArray(e)?e:[e];return produce(r,o=>traverse(o,n=>{let{value:l,meta:s}=n,h=l;if(isObject(h)){if(h.$id){if(s.nodePath?.includes(".$filter"))return;let p=h.$entity||h.$relation?h:{[`$${h.$thingType}`]:h.$thing},d=x(t,p);if(!d?.name)throw new Error(`Schema not found for ${h.$thing}`);if(h.$path=d.name,Array.isArray(h.$id)||(h.$filterByUnique=!0),d?.idFields?.length!==1)throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in h||"$relation"in h||"$thing"in h){let p=x(t,h);if(!p?.name)throw new Error(`Schema not found for ${h.$thing}`);h.$path=p.name;}if(h.$entity?(h.$thing=h.$entity,h.$thingType="entity",delete h.$entity):h.$relation&&(h.$thing=h.$relation,h.$thingType="relation",delete h.$relation),isObject(h)&&"$thing"in h&&h.$thing){let p=h.$entity||h.$relation?h:{[`$${h.$thingType}`]:h.$thing};h[ae]=s.nodePath;let d=x(t,p);if(h.$filter&&(h.$filterByUnique=bt(h.$filter,d),h.$filter=Oe(h.$filter,h.$thing,t)),h.$fields){h.$fields.some(f=>d?.idFields?.includes(f?.$path||f))||(h.$fields=[...h.$fields,...Array.isArray(d.idFields)?d.idFields:[]],h.$idNotIncluded=!0);let a=h.$fields?.flatMap(f=>{let u=xr(f,d,t);return Array.isArray(u)?u:[u]}).filter(Boolean);h.$fields=a;}else {let a=Ft(d)?.flatMap(f=>{let u=xr(f,d,t);return Array.isArray(u)?u:[u]}).filter(Boolean);h.$fields=a;}h.$excludedFields&&(h.$fields=h.$fields.filter(c=>Ge(d,c)?!0:!h.$excludedFields.includes(c.$path)));}}}))},Ft=e=>{let t=e.dataFields?.map(n=>n.path)||[],r=e.linkFields?.map(n=>n.path)||[],i=Object.keys(e.roles||{})||[];return [...t,...r,...i]},bt=(e,t)=>Object.keys(e||{}).some(i=>{if(!Array.isArray(e[i])){let o=t.idFields?.includes(i),n=t.dataFields?.some(s=>(s.dbPath===i||s.path===i)&&s?.validations?.unique),l=i==="$id"&&!Array.isArray(e[i]);return o||n||l}return !1}),Ge=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),$i=e=>{let{field:t,fieldStr:r,$justId:i,dbPath:o,isVirtual:n,fieldSchema:l}=e;return {$path:r,$dbPath:o,$thingType:"attribute",$as:t.$as||r,$var:r,$fieldType:"data",$justId:i,$id:t.$id,$isVirtual:n,[de]:l}},mi=e=>{let{field:t,fieldStr:r,linkField:i,$justId:o,dbPath:n,schema:l,fieldSchema:s}=e,{target:h,oppositeLinkFieldsPlayedBy:p}=i;return p.map(d=>{let c=h==="role"?d.thingType:"relation",a=h==="role"?d.thing:i.relation,f={[`$${c}`]:a},u=x(l,f),$=t?.$fields?.filter(B=>Ge(u,B)).length===0,y=[];if(typeof t!="string")if(t.$fields)if($){let B=u.idFields||[];y=[...t.$fields,...B];}else y=t.$fields;else y=Ft(u);else y=["id"];t.$excludedFields&&(y=y.filter(B=>Ge(u,B)?!0:!t.$excludedFields.includes(B.$path)));let m=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...Oe(t.$filter,a,l)}:void 0;return {$thingType:c,$plays:i.plays,$playedBy:d,$path:d.path,$dbPath:n,$as:t.$as||r,$var:r,$thing:a,$fields:y,$excludedFields:t.$excludedFields,$fieldType:"link",$target:h,$intermediary:d.relation,$justId:o,$id:t.$id,$filter:m,$idNotIncluded:$,$filterByUnique:bt(t.$filter,u),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[de]:s}})},yi=e=>{let{field:t,fieldStr:r,roleField:i,$justId:o,dbPath:n,schema:l,fieldSchema:s}=e;return i.playedBy.map(h=>{let{thing:p,thingType:d,relation:c}=h,a={[`$${d}`]:p},f=x(l,a),u=t?.$fields?.filter(m=>f?.idFields?.includes(m)||f?.idFields?.includes(m.$path)).length===0,$=[];if(typeof t!="string")if(t.$fields)if(u){let m=f.idFields||[];$=[...t.$fields,...m];}else $=t.$fields;else $=Ft(f);else $=["id"];t.$excludedFields&&($=$.filter(m=>Ge(f,m)?!0:!t.$excludedFields.includes(m.$path)));let y=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...Oe(t.$filter,p,l)}:void 0;return {$thingType:d,$path:r,$dbPath:n,$as:t.$as||r,$var:r,$thing:p,$fields:$,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:c,$justId:o,$id:t.$id,$filter:y,$idNotIncluded:u,$filterByUnique:bt(t.$filter,f),$playedBy:h,$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[de]:s}})},xr=(e,t,r)=>{let i=typeof e=="string"?e:e.$path,o=typeof e=="string",n=t.dataFields?.find(h=>h.path===i),l=t.linkFields?.find(h=>h.path===i),s=t.roles?.[i];if(n){let h=!!n.isVirtual&&!!n.default;return $i({field:e,fieldStr:i,$justId:o,dbPath:n.dbPath,isVirtual:h,fieldSchema:n})}else {if(l)return mi({field:e,fieldStr:i,linkField:l,$justId:o,dbPath:l.path,schema:r,fieldSchema:l});if(s)return yi({field:e,fieldStr:i,roleField:s,$justId:o,dbPath:i,schema:r,fieldSchema:s})}return null},Oe=(e,t,r)=>{if(e==null)return e;let i=isArray(e),n=(i?e:[e]).map(l=>Object.keys(l).reduce((p,d)=>{let c=l[d],a=isArray(c)?c:[c];if(d.startsWith("$"))["$id","$thing"].includes(d)?p[d]=c:p[d]=Oe(c,t,r);else {let f=t in r.entities?r.entities[t]:r.relations[t],[u,$]=_e(f,d);if(u==="dataField")p[d]=c;else if(u==="linkField"||u==="roleField"){let y=$,[m]=y.$things;return a.every(B=>typeof B=="string")?p[d]={$id:a,$thing:m}:a.every(B=>isObject(B))&&(p[d]=isArray(c)?{$or:Oe(c,m,r)}:Oe(c,m,r)),p}else throw new Error(`Field ${d} not found in schema of ${t}`)}return p},{}));return i?n.length===1?n[0]:{$or:n}:n[0]};var Nr=async(e,t,r)=>r?(n=>produce(n,l=>traverse(l,({value:s})=>{if(isObject(s)){let h=s;if(!h.$thing)return;if(h.$thing){let p=x(e,h),{virtualFields:d}=p,c=h[ae];if(!c)throw new Error("[Internal] QueryPath is missing");let a=getNodeByPath(t,c),f=a.$fields.map($=>$.$path),u=a.$excludedFields;d.forEach($=>{if(u?.includes($)||f.length>0&&!f.includes($))return;let y=p.dataFields?.find(m=>m.path===$);if(y?.default){let m=Ae({currentThing:h,fieldSchema:y,mandatoryDependencies:!0});h[$]=m;}else if(h[$]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${$}`)}),u&&u.forEach($=>{if(typeof $!="string")throw new Error("[Internal] ExcludedField is not a string");delete h[$];});}}})))(r):void 0;var Wr=e=>e.replace(/`/g,""),bi=[" ","-","+","*","/","=","!","@","#","$","%","^","&","(",")","[","]","{","}","|","\\",";",":","'",'"',",","<",">",".","?","~","`"],zr=e=>bi.some(t=>e.includes(t))?`\u27E8\`${e}\`\u27E9`:e;var Vr=e=>{let{queries:t,schema:r}=e;return t.map(i=>Mi({query:i,schema:r}))},Mi=e=>{let{query:t,schema:r}=e,{$thing:i,$fields:o,$filter:n,$offset:l,$limit:s,$sort:h}=t;if(o.length===0)return null;let p=[];p.push("SELECT");let d=wt({parentQuery:t,queries:o,level:1,schema:r});d&&p.push(d);let c=r.entities[i]||r.relations[i];if(!c)throw new Error(`Schema for ${i} not found`);let f=(c.subTypes?[i,...c.subTypes]:[i]).map(u=>zr(u));if(t.$id)if(typeof t.$id=="string")p.push(`FROM ${f.map(u=>`${u}:\`${t.$id}\``).join(",")}`);else if(isArray(t.$id)){let u=t.$id,$=f.flatMap(y=>u?.map(m=>`${y}:\`${m}\``));p.push(`FROM ${$.join(",")}`);}else throw new Error("Invalid $id");else p.push(`FROM ${f.join(",")}`);if(n){let u=ye(n,i,r),$=Se(u);p.push(`WHERE ${$}`);}return h&&p.push(Hr(h)),typeof s=="number"&&p.push(`LIMIT ${s}`),typeof l=="number"&&p.push(`START ${l}`),p.join(`
37
- `)},wt=e=>{let{queries:t,schema:r,level:i,parentQuery:o}=e,n=[],l=o[ae];return n.push(M(`"${l}" as \`$$queryPath\``,i)),n.push(M("meta::id(id) as `$id`",i)),n.push(M("meta::tb(id) as `$thing`",i)),t.forEach(s=>{let h=Qi({query:s,level:i,schema:r});h&&n.push(h);}),n.length===0?null:n.join(`,
38
- `)},Qi=e=>{let{query:t,schema:r,level:i}=e;return t.$fieldType==="data"?Ti({query:t,level:i}):t.$fieldType==="link"?Li({query:t,level:i,schema:r}):t.$fieldType==="role"?Si({query:t,level:i,schema:r}):null},Ti=e=>{let{query:t,level:r}=e;return t.$isVirtual?null:t.$path==="id"?M(`meta::id(${t.$path}) AS ${t.$as}`,r):t.$path===t.$as?M(`\`${t.$path}\``,r):M(`\`${t.$path}\` AS \`${t.$as}\``,r)},Li=e=>{let{query:t,schema:r,level:i}=e,{$fields:o,$filter:n,$offset:l,$limit:s,$sort:h}=t;if(o.length===0)return null;let p=[];p.push(M("(",i));let d=i+1;p.push(M("SELECT",d));let c=wt({parentQuery:t,queries:o,level:d+1,schema:r});c&&p.push(c);let a=t[de][Te].queryPath;if(p.push(M(`FROM ${a}`,d)),n){let f=ye(n,t.$thing,r),u=Se(f);p.push(`WHERE ${u}`);}return h&&p.push(M(Hr(h),d)),typeof s=="number"&&p.push(M(`LIMIT ${s}`,d)),typeof l=="number"&&p.push(M(`START ${l}`,d)),p.push(M(`) AS \`${t.$as}\``,i)),p.join(`
39
- `)},Si=e=>{let{query:t,schema:r,level:i}=e;if(t.$fields.length===0)return null;let o=[];o.push(M("(",i));let n=i+1;o.push(M("SELECT",n));let l=n+1,s=wt({parentQuery:t,queries:t.$fields,level:l,schema:r});s&&o.push(s);let h=t[de][Te].queryPath;if(o.push(M(`FROM ${h}`,n)),t.$filter){let p=ye(t.$filter,t.$playedBy.thing,r),d=Se(p);o.push(`WHERE ${d}`);}return o.push(M(`) AS \`${t.$as}\``,i)),o.join(`
40
- `)},ye=(e,t,r)=>{if(e==null)return e;let i=isArray(e),n=(i?e:[e]).map(l=>{let h=Object.keys(l).reduce((p,d)=>{let c=l[d];if(d.startsWith("$"))return d==="$not"?{...p,$not:void 0,"$!":ye(c,t,r)}:d==="$or"?{...p,$or:void 0,$OR:ye(c,t,r)}:d==="$and"?{...p,$and:void 0,$AND:ye(c,t,r)}:d==="$eq"?{...p,$nor:void 0,"$=":ye(c,t,r)}:d==="$id"?{...p,$id:void 0,"meta::id(id)":{$IN:isArray(c)?c:[c]}}:d==="$thing"?p:{...p,[d]:ye(c,t,r)};let a=t in r.entities?r.entities[t]:r.relations[t],[f,u]=_e(a,d);if(f==="dataField"){if(a.idFields.length>1)throw new Error("Multiple id fields not supported");return d===a.idFields[0]?{...p,"meta::id(id)":{$IN:isArray(c)?c:[c]}}:{...p,[d]:c}}if(f==="linkField"||f==="roleField"){let $=u,[y]=$.$things,m=$[Te].queryPath;return {...p,[m]:ye(c,y,r)}}throw new Error(`Field ${d} not found in schema, Defined in $filter`)},{});return shake(h)});return i?n:n[0]},Se=e=>{if(e==null)return "";let t=Object.entries(e),r=[];return t.forEach(([i,o])=>{if(["$OR","$AND","$!"].includes(i)){let n=i.replace("$",""),l=Array.isArray(o)?o.map(s=>Se(s)):[Se(o)];n==="!"?r.push(`!(${l.join(` ${n} `)})`):r.push(`(${l.join(` ${n} `)})`);return}if(isObject(o))if(i.includes("<-")||i.includes("->")){let n=Se(o);r.push(`${i}[WHERE ${n}]`);}else {if(i.startsWith("$"))throw new Error(`Invalid key ${i}`);if(Object.keys.length===1&&Object.keys(o)[0].startsWith("$")){let[n]=Object.keys(o),l=o[n];if(isArray(l))r.push(`${i} ${n.replace("$","")} [${l.map(s=>`'${s}'`).join(", ")}]`);else if(isObject(l)){let s=Se(l);r.push(`${i} ${n.replace("$","")} ${s}`);}else r.push(`${i} ${n.replace("$","")} '${l}'`);}else throw new Error(`Invalid key ${i}`)}else if(Array.isArray(o)){let n=i.startsWith("$")?i.replace("$",""):"IN";r.push(`${i} ${n} [${o.map(l=>`'${l}'`).join(", ")}]`);}else {let n=i.startsWith("$")?i.replace("$",""):"=";r.push(`${i} ${n} '${o}'`);}}),r.join(" AND ")},Hr=e=>`ORDER BY ${e.map(r=>{if(typeof r=="string")return r;let{field:i,desc:o}=r;return `${i}${o?" DESC":" ASC"}`}).join(", ")}`;var Kr=async e=>{let{client:t,queries:r}=e;return await Promise.all(r.map(i=>t.query(i)))};var Ur=e=>{let{res:t,queries:r}=e;return t.map((o,n)=>Jr(r[n],o))},Jr=(e,t)=>{if(isArray(t)){if(t.length===0)return null;if(e.$filterByUnique){if(t.length>1)throw new Error("Multiple results found for unique query");return Qt(e,t[0])}if(t.length>=1)return t.map(r=>Qt(e,r))}else throw new Error("res is unexpectedly not an array")},Qt=(e,t)=>{let r={[ae]:t.$$queryPath,$id:t.$id,$thing:Wr(t.$thing),$thingType:e.$thingType};return e.$fields.forEach(i=>{let o=i.$as,n=t[o];i.$path==="id"&&e.$idNotIncluded||(r[o]=ki(i,n));}),r},ki=(e,t)=>t==null||isArray(t)&&t.length===0?null:e.$fieldType==="data"?(e[de].cardinality==="ONE"&&isArray(t)&&t[0],t??null):e.$justId?e.$filterByUnique||e[de].cardinality==="ONE"?t[0]?.id??null:t?.map(r=>r.id)??[]:e.$filterByUnique||e[de].cardinality==="ONE"?Qt(e,t[0]):Jr(e,t);var Tt=H("error","error",V((e,t)=>({...e,error:t.error}))),Di=be("build",{build:v(async e=>Vr({queries:e.bql.queries,schema:e.schema}),H("done","run",V((e,t)=>({...e,surql:{...e.surql,queries:t.data}}))),Tt),run:v(async e=>Kr({client:e.client,queries:oe(e.surql.queries)}),H("done","parse",V((e,t)=>({...e,surql:{...e.surql,res:t.data}}))),Tt),parse:v(async e=>Ur({res:oe(e.surql.res),queries:e.bql.queries,schema:e.schema,config:e.config}),H("done","success",V((e,t)=>({...e,bql:{...e.bql,res:t.data}}))),Tt),success:he(),error:he()},e=>e),Ri=async e=>new Promise((t,r)=>{me(Di,i=>{i.machine.state.name==="success"&&t(i.context.bql.res),i.machine.state.name==="error"&&r(i.context.error);},e);}),Zr=async(e,t,r,i)=>Ri({bql:{queries:e},surql:{},schema:t,config:r,client:i,error:null});var Lt="___",Yr=async e=>{let{queries:t,schema:r}=e;return t.map(i=>Ci({query:i,schema:r}))},Ci=e=>{let{query:t,schema:r}=e,{$path:i,$thing:o,$filter:n,$fields:l,$sort:s,$offset:h,$limit:p,$id:d}=t;if(!i)throw new Error("Path is not defined");let c=[],a=t[ae];if(c.push("match"),c.push(`$${i} isa ${o};`),n||d){let $=Ve(r,t),y={...n,...d?{[$]:d}:{}},m=Rt({$filter:y,$var:i,$thing:o,schema:r,depth:0});c.push(`
41
- ${m}`);}let f=At({schema:r,$thing:o,$var:i,$sort:s,depth:0});f&&c.push(f.match);let u=`M_${v4()}`;if(c.push(`?queryPath${u} = "${a}";`),c.push("fetch"),c.push(`?queryPath${u} as "queryPath";`),l){let $=l.filter(B=>B.$fieldType==="data");$&&$.length>0&&c.push(...St($,i,0));let y=l.filter(B=>B.$fieldType==="link");y&&y.length>0&&c.push(...Dt(y,i,i,0,r));let m=l.filter(B=>B.$fieldType==="role");m&&m.length>0&&c.push(...kt(m,i,i,0,r));}return f&&c.push(f.sort),typeof h=="number"&&c.push(`
42
- offset ${h};`),typeof p=="number"&&c.push(`
43
- limit ${p};`),c.join(`
44
- `)},St=(e,t,r)=>{let i=[],o=[];for(let p=0;p<e.length;p++)e[p].$isVirtual||i.push(e[p].$dbPath),o.push(`{${e[p].$dbPath}:${e[p].$as}}`);let n=i.join(", "),s=`$metadata:{as:[${o.join(",")}]}`;return [M(`$${t} as "${t}.${s}.$dataFields": ${n};`,r)]},kt=(e,t,r,i,o)=>{let n=i+1,l=[];for(let s of e){let{$fields:h,$as:p,$justId:d,$idNotIncluded:c,$filterByUnique:a,$thing:f,$sort:u,$offset:$,$limit:y}=s,m=s[ae],B=`$metadata:{as:${p},justId:${d?"T":"F"},idNotIncluded:${c},filterByUnique:${a}}`;l.push(M(`"${r}.${B}.${s.$var}": {`,i)),l.push(M("match",n));let w=`${t}${Lt}${s.$var}`;if(l.push(M(`$${w} isa ${s.$thing};`,n)),l.push(M(`$${t} (${s.$var}: $${t}${Lt}${s.$var}) isa ${s.$intermediary};`,n)),s.$filter||s.$id){let L=Ve(o,s),D=s.$id?{[L]:s.$id}:{},A={...s.$filter,...D};l.push(Rt({$filter:A,$var:w,$thing:s.$thing,schema:o,depth:n}));}let g=At({schema:o,$thing:f,$var:w,$sort:u,depth:n});if(g&&l.push(g.match),h){let L=`M_${v4()}`;l.push(M(`
45
- ?queryPath${L} = "${m}";`,n)),l.push(M("fetch",n)),l.push(M(`?queryPath${L} as "queryPath";`,n));let D=h?.filter(j=>j.$fieldType==="data");D&&D.length>0&&l.push(...St(D,w,n));let A=h?.filter(j=>j.$fieldType==="link");A&&A.length>0&&l.push(...Dt(A,w,`${t}.${s.$var}`,n,o));let C=h?.filter(j=>j.$fieldType==="role");C&&C.length>0&&l.push(...kt(C,w,`${t}.${s.$var}`,n,o));}g&&l.push(g.sort),typeof $=="number"&&l.push(M(`offset ${$};`,n)),typeof y=="number"&&l.push(M(`limit ${y};`,n)),l.push(M("};",i));}return l},Dt=(e,t,r,i,o)=>{let n=i+1,l=[];for(let s of e){let{$fields:h,$as:p,$justId:d,$idNotIncluded:c,$filterByUnique:a,$playedBy:f,$thing:u,$sort:$,$offset:y,$limit:m}=s,B=s[ae],w=`$metadata:{as:${p},justId:${d?"T":"F"},idNotIncluded:${c},filterByUnique:${a}}`;l.push(M(`"${r}.${w}.${s.$var}": {`,i)),l.push(M("match",n));let g=`${t}${Lt}${s.$var}`;if(l.push(M(`$${g} isa ${s.$thing};`,n)),s.$filter||s.$id){let D=Ve(o,s),A=s.$id?{[D]:s.$id}:{},C={...s.$filter,...A};l.push(Rt({$filter:C,$var:g,$thing:s.$thing,schema:o,depth:n}));}let L=At({schema:o,$thing:u,$var:g,$sort:$,depth:n});if(L&&l.push(L.match),s.$target==="role"?l.push(M(`$${t}_intermediary (${s.$plays}: $${t}, ${f.plays}: $${g}) isa ${s.$intermediary};`,n)):l.push(M(`$${g} (${s.$plays}: $${t});`,n)),h){let D=`M_${v4()}`;l.push(M(`?queryPath${D} = "${B}";`,n)),l.push(M("fetch",n)),l.push(M(`?queryPath${D} as "queryPath";`,n));let A=h?.filter(N=>N.$fieldType==="data");A&&A.length>0&&l.push(...St(A,g,n));let C=h?.filter(N=>N.$fieldType==="link");C&&C.length>0&&l.push(...Dt(C,g,`${t}.${s.$var}`,n,o));let j=h?.filter(N=>N.$fieldType==="role");j&&j.length>0&&l.push(...kt(j,g,`${t}.${s.$var}`,n,o));}L&&l.push(L.sort),typeof y=="number"&&l.push(M(`offset ${y};`,n)),typeof m=="number"&&l.push(M(`limit ${m};`,n)),l.push(M("};",i));}return l},Oi=(e,t)=>{let r={};if(t.dataFields?.forEach(l=>{l.path!==l.dbPath&&(r[l.path]=l.dbPath);}),Object.keys(r).length===0)return e;let{$not:i,...o}=e,n=vr(o,r);return i&&(n.$not=vr(i,r)),n},vr=(e,t)=>{let r={};return Object.entries(e).forEach(([i,o])=>{let n=t[i]||i;r[n]=o;}),r},Rt=e=>{let{$filter:t,$var:r,$thing:i,schema:o,depth:n}=e,l=Oi(t,G(o,i)),{$not:s,...h}=l,p=G(o,i),d=[];return Object.entries(s||{}).forEach(([c,a])=>{if(c.startsWith("$"))return;if(p.dataFields?.find($=>$.dbPath===c)){a===null?d.push(M(`$${r} has ${c} $${c}_${v4()};`,n)):Array.isArray(a)?a.forEach($=>{d.push(M(`not { $${r} has ${c} ${ne($)}; };`,n));}):d.push(M(`not { $${r} has ${c} ${ne(a)}; };`,n));return}let u=p.linkFields?.find($=>$.path===c);if(u){let[$]=u.oppositeLinkFieldsPlayedBy,m=G(o,$.thing).idFields?.[0];if(!m)throw new Error(`"${$.thing}" does not have an id field`);if(u.target==="relation")a===null?d.push(M(`(${u.plays}: $${r}) isa ${u.relation};`,n)):Array.isArray(a)?a.forEach(B=>{d.push(M(`not { (${u.plays}: $${r}) isa ${u.relation}, has ${m} ${ne(B)}; };`,n));}):d.push(M(`not { (${u.plays}: $${r}) isa ${u.relation}, has ${m} ${ne(a)}; };`,n));else {let B=`${$.thing}_${v4()}`;a===null?d.push(M(`$${B} isa ${$.thing}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation};`,n)):Array.isArray(a)?a.forEach(w=>{d.push(M(`not { $${B} isa ${$.thing}, has ${m} ${ne(w)}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation}; };`,n));}):d.push(M(`not { $${B} isa ${$.thing}, has ${m} ${ne(a)}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation}; };`,n));}return}if(p.thingType==="relation"){let $=p.roles[c];if($){let[y]=$.playedBy||[],B=G(o,y.thing).idFields?.[0];if(!B)throw new Error(`"${y.thing}" does not have an id field`);let w=`${y.thing}_${v4()}`,g=v4(),L=`${r}_${g}`;a===null?(d.push(M(`$${L} isa ${i};`,n)),d.push(M(`$${L} (${y.plays}: ${w});`,n)),d.push(M(`$${r} is $${L};`,n))):Array.isArray(a)?a.forEach(D=>{d.push(M(`$${L} isa ${i};`,n)),d.push(M(`not { $${w} isa ${y.thing}, has ${B} ${ne(D)}; $${L} (${y.plays}: $${w}); };`,n)),d.push(M(`$${r} is $${L};`,n));}):(d.push(M(`$${L} isa ${i};`,n)),d.push(M(`not { $${w} isa ${y.thing}, has ${B} ${ne(a)}; $${L} (${y.plays}: $${w}); };`,n)),d.push(M(`$${r} is $${L};`,n)));return}}}),Object.entries(h).forEach(([c,a])=>{if(c.startsWith("$"))return;if(p.dataFields?.find($=>$.dbPath===c)){if(a===null)d.push(M(`not { $${r} has ${c} $${c}_${v4()}; };`,n));else if(Array.isArray(a)){let $=a.map(m=>`$${r} has ${c} ${ne(m)};`),y=Xe($);y&&d.push(M(y,n));}else d.push(M(`$${r} has ${c} ${ne(a)};`,n));return}let u=p.linkFields?.find($=>$.path===c);if(u){let[$]=u.oppositeLinkFieldsPlayedBy,m=G(o,$.thing).idFields?.[0];if(!m)throw new Error(`"${$.thing}" does not have an id field`);if(u.target==="relation")if(a===null)d.push(M(`not { (${u.plays}: $${r}) isa ${u.relation}; };`,n));else if(Array.isArray(a)){let B=a.map(g=>`(${u.plays}: $${r}) isa ${u.relation}, has ${m} ${ne(g)};`),w=Xe(B);w&&d.push(M(w,n));}else d.push(M(`(${u.plays}: $${r}) isa ${u.relation}, has ${m} ${ne(a)};`,n));else {let B=`${$.thing}_${v4()}`;if(a===null)d.push(M(`not { $${B} isa ${$.thing}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation}; };`,n));else if(Array.isArray(a)){let w=a.map(L=>`$${B} isa ${$.thing}, has ${m} ${ne(L)}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation};`),g=Xe(w);g&&d.push(M(g,n));}else d.push(M(`$${B} isa ${$.thing}, has ${m} ${ne(a)}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation};`,n));}return}if(p.thingType==="relation"){let $=p.roles[c];if($){let[y]=$.playedBy||[],B=G(o,y.thing).idFields?.[0];if(!B)throw new Error(`"${y.thing}" does not have an id field`);let w=`${y.thing}_${v4()}`,g=v4(),L=`${r}_${g}`;if(a===null)d.push(M(`$${L} isa ${i};`,n)),d.push(M(`not { $${L} (${y.plays}: ${w}); };`,n)),d.push(M(`$${r} is $${L};`,n));else if(Array.isArray(a)){let D=a.map(C=>`$${w} isa ${y.thing}, has ${B} ${ne(C)}; $${L} (${y.plays}: $${w});`),A=Xe(D);A&&(d.push(M(`$${L} isa ${i};`,n)),d.push(M(A,n)),d.push(M(`$${r} is $${L};`,n)));}else d.push(M(`$${L} isa ${i};`,n)),d.push(M(`$${w} isa ${y.thing}, has ${B} ${ne(a)}; $${L} (${y.plays}: $${w});`,n)),d.push(M(`$${r} is $${L};`,n));return}}throw new Error(`"${i}" does not have property "${c}"`)}),d.join(`
46
- `)},Xe=e=>{if(e.length>1)return `{ ${e.join(" } or { ")} };`;let[t]=e;return t},ne=e=>typeof e=="string"?`'${e}'`:e instanceof Date?`'${e.toISOString().replace("Z","")}'`:isObject(e)&&"$id"in e?isArray(e.$id)?`like "^(${e.$id.join("|")})$"`:`"${e.$id}"`:`${e}`,qi=e=>typeof e=="string"?{field:e,desc:!1}:{...e,desc:e.desc??!1},At=e=>{let{$var:t,$thing:r,schema:i,$sort:o,depth:n}=e,l=G(i,r),s=[],h=[];if(o?.forEach(p=>{let d=qi(p),c=l.dataFields?.find(u=>u.path===d.field);if(!c)throw new Error(`"${r}" does not have data field "${d.field}"`);let a=`${d.field}_${v4()}`;s.push(M("{",n)),s.push(M(`$${t} has ${c.dbPath} $${a}_1;`,n+1)),s.push(M("not {",n+1)),s.push(M(`$${t} has ${c.dbPath} $${a}_2;`,n+2)),s.push(M(`$${a}_2 < $${a}_1;`,n+2)),s.push(M("};",n+1)),s.push(M(`?${a}_ = $${a}_1;`,n+1)),s.push(M("} or {",n)),s.push(M(`not { $${t} has ${c.dbPath} $${a}_1; };`,n+1)),s.push(M(`?${a}_ = "~";`,n+1)),s.push(M("};",n)),s.push(M(`?${a} = ?${a}_;`,n));let f=d.desc?"desc":"asc";h.push(`?${a} ${f}`);}),s.length!==0)return {match:s.join(""),sort:M(`sort ${h.join(", ")};`,n)}};var Xr=async e=>{let{enrichedBqlQuery:t,rawBqlRequest:r,schema:i,config:o,rawTqlRes:n}=e;if(t){if(!n)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");return n.map((l,s)=>{let h=r[s],p=t[s];return xi(l,h,p,i,o)})},xi=(e,t,r,i,o)=>e.length===0?null:r.$filterByUnique?Gr(e[0],t,i,o):e.map(n=>Gr(n,t,i,o)),Gr=(e,t,r,i)=>{let{dataFields:o,currentSchema:n,linkFields:l,roleFields:s,schemaValue:h}=It(e,r),p=Ct(o,n,i),d=qt(l,r,i),c=Ot(s,r,i),a=t?.$fields?.every(u=>!n?.idFields?.includes(typeof u=="string"?u:u.$path));return {...d,...c,...h,...!i.query?.noMetadata&&t.$id?{$id:Array.isArray(t.$id)?p.id:t.$id}:{},...a?Object.fromEntries(Object.entries(p).filter(([u])=>!n?.idFields?.includes(u))):p}},It=(e,t)=>{let r=Object.keys(e),i=r.find(a=>a.endsWith(".$dataFields"));if(!i)throw new Error("No datafields");let o=e[i],n=i.split(".")[i.split(".").length-2];if(o.$metaData=n,o.length===0)throw new Error("No datafields");let l=o.type,s={$thing:l.label,$thingType:l.root,[ae]:e.queryPath.value},h={[`$${s.$thingType}`]:s.$thing},p=x(t,h),d=r.filter(a=>{let f=oe(a.split(".").pop());return !a.endsWith(".$dataFields")&&p.linkFields?.some(u=>u.path===f)}).map(a=>{let f=oe(a.split(".").pop()),u=oe(p.linkFields?.find($=>$.path===f));return {$linkFields:e[a],$key:f,$metaData:a.split(".")[a.split(".").length-2],$cardinality:u.cardinality}}),c=r.filter(a=>{let f=a.split(".").pop();return f&&!a.endsWith(".$dataFields")&&p.thingType==="relation"&&p.roles?.[f]}).map(a=>{let f=oe(a.split(".").pop());return {$roleFields:e[a],$key:f,$metaData:a.split(".")[a.split(".").length-2],$cardinality:p.roles[f].cardinality}});return {dataFields:o,schemaValue:s,currentSchema:p,linkFields:d,roleFields:c}},Ct=(e,t,r)=>{let{$metaData:i}=e,{as:o}=ji(i),n=Object.entries(e).filter(([l])=>l!=="type"&&!l.startsWith("$")).map(([l,s])=>{let h=t.dataFields?.find(a=>a.path===l||a.dbPath===l),p=l==="id",d=Array.isArray(o)?o.find(a=>a[l])?.[l]:l,c;if(h?.cardinality==="ONE"){if(c=s[0]?s[0].value:r.query?.returnNulls?null:void 0,h.contentType==="DATE"?c=c&&`${c}Z`:h.contentType==="JSON"&&(c=c&&JSON.parse(c)),p)return [[d,c],["$id",c]].filter(([a,f])=>f!==void 0)}else if(h?.cardinality==="MANY"){if(!isArray(s))throw new Error("Typedb fetch has changed its format");if(s.length===0)return r.query?.returnNulls?[[d,null]]:[];h.contentType==="DATE"?c=s.map(a=>`${a.value}Z`):h.contentType==="JSON"?c=s.map(a=>a.value&&JSON.parse(a.value)):c=s.map(a=>a.value);}return [[d,c]].filter(([a,f])=>f!==void 0)}).flat();return Object.fromEntries([...n])},Ot=(e,t,r)=>{let i={};return e.forEach(o=>{let{$roleFields:n,$metaData:l,$cardinality:s}=o,{as:h,justId:p,idNotIncluded:d,filterByUnique:c}=en(l);if(h===null)return;let a=n.map(f=>{let{dataFields:u,currentSchema:$,linkFields:y,roleFields:m,schemaValue:B}=It(f,t),w=Ct(u,$,r);if(p==="T")return w.id;{let g=qt(y,t,r),L=Ot(m,t,r),D={...w};return d==="true"&&$?.idFields?.forEach(A=>delete D[A]),{...D,...g,...L,...B}}});a.length>0?i[h]=s==="MANY"&&c==="false"?a:a[0]:r.query?.returnNulls&&(i[h]=null);}),i},qt=(e,t,r)=>{let i={};return e.forEach(o=>{let{$linkFields:n,$metaData:l,$cardinality:s}=o,{as:h,justId:p,idNotIncluded:d,filterByUnique:c}=en(l);if(h===null)return;let a=n.map(f=>{let{dataFields:u,currentSchema:$,linkFields:y,roleFields:m,schemaValue:B}=It(f,t),w=Ct(u,$,r);if(p==="T")return w.id;{let g=qt(y,t,r),L=Ot(m,t,r),D={...w};return d==="true"&&$.idFields?.forEach(A=>delete D[A]),{...D,...g,...L,...B}}});i[h]=a.length>0?s==="MANY"&&c==="false"?a:a[0]:r.query?.returnNulls?null:void 0;}),i},en=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,r=/justId:([a-zA-Z0-9_\-·]+)/,i=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,o=/filterByUnique:([a-zA-Z0-9_\-·]+)/,n=e.match(t),l=e.match(r),s=e.match(i),h=e.match(o);return {as:n?n[1]:null,justId:l?l[1]:null,idNotIncluded:s?s[1]:null,filterByUnique:h?h[1]:null}},ji=e=>{try{let r=(o=>{let n=o.replace("$metadata:","");return n=n.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),n=n.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(l,s,h)=>/^{.*}$/.test(h)?`:${h}`:`:${s}"${h}"`),n=n.replace(/\[([^\]]+)\]/g,(l,s)=>`[${s.split(",").map(h=>h.trim().startsWith("{")&&h.trim().endsWith("}")?h.trim():`"${h.trim()}"`).join(",")}]`),n})(e);return JSON.parse(r)}catch(t){return console.error(t),{as:[]}}};var tn=async e=>{let{tqlRequest:t,dbHandles:r,config:i}=e,o=new TypeDBOptions;o.infer=!0;let{session:n}=await Ze(r,i),l=await n.transaction(TransactionType.READ,o),[s,h]=await tryit(parallel)(t.length,t,async p=>await l.query.fetch(p).collect());if(s){await l.rollback();let p=s;throw new Error(`Error running TQL query: ${p.errors}`)}return await l.close(),h};var Vi=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,Hi=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,Ki=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,Pt=H("error","error",V((e,t)=>({...e,error:t.error}))),Ui=be("build",{build:v(async e=>Yr({queries:e.bql.queries,schema:e.schema}),H("done","run",V(Hi)),Pt),run:v(async e=>tn({dbHandles:e.handles,tqlRequest:oe(e.tql.queries),config:e.config}),H("done","parse",V(Ki)),Pt),parse:v(async e=>Xr({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries,schema:e.schema,config:e.config,rawTqlRes:oe(e.tql.res)}),H("done","success",V(Vi)),Pt),success:he(),error:he()},e=>e),Ji=async e=>new Promise((t,r)=>{me(Ui,i=>{i.machine.state.name==="success"&&t(i.context.bql.res),i.machine.state.name==="error"&&r(i.context.error);},e);}),rn=async(e,t,r,i,o)=>Ji({bql:{raw:e,queries:t},tql:{},schema:r,config:i,handles:o,error:null});var Zi=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,xt=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,et=H("error","error",V((e,t)=>({...e,error:t.error}))),vi=be("enrich",{enrich:v(async e=>jr(e.bql.raw,e.schema),H("done","adapter",V(Zi)),et),adapter:v(async e=>{let t={};e.bql.queries?.forEach((s,h)=>{let p=e.bql.raw[h],d=G(e.schema,s.$thing),{id:c}=d.defaultDBConnector;if(d.db==="typeDB"){if(!t[c]){let f=e.handles.typeDB?.get(c)?.client;if(!f)throw new Error(`TypeDB client with id "${d.defaultDBConnector.id}" does not exist`);t[c]={db:"typeDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else if(d.db==="surrealDB"){if(!t[c]){let f=e.handles.surrealDB?.get(c)?.client;if(!f)throw new Error(`SurrealDB client with id "${d.defaultDBConnector.id}" does not exist`);t[c]={db:"surrealDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else throw new Error(`Unsupported DB "${d.db}"`);let a=t[c];a.rawBql.push(p),a.bqlQueries.push(s),a.indices.push(h);});let r=Object.values(t),i=r.map(s=>s.db==="typeDB"?rn(s.rawBql,s.bqlQueries,e.schema,e.config,e.handles):Zr(s.bqlQueries,e.schema,e.config,s.client)),o=await Promise.all(i),n=r.flatMap((s,h)=>{let p=o[h];return s.indices.map((d,c)=>({index:d,result:p[c]}))});return n.sort((s,h)=>s.index<h.index?-1:s.index>h.index?1:0),n.map(({result:s})=>s)},H("done","postHooks",V(xt)),et),postHooks:v(async e=>Nr(e.schema,oe(e.bql.queries),oe(e.bql.res)),H("done","clean",V(xt)),et),clean:v(async e=>Pr(e.config,oe(e.bql.res)),H("done","success",V(xt)),et),success:he(),error:he()},e=>e),Yi=async e=>new Promise((t,r)=>{me(vi,i=>{i.machine.state.name==="success"&&t(i.context),i.machine.state.name==="error"&&r(i.context);},e);}),qe=async(e,t,r,i)=>Yi({bql:{raw:e},schema:t,config:r,handles:i,error:null});var jt="___",Gi=Symbol.for("grandChildOfCreate"),nn=async(e,t,r,i)=>{let o=(E,Q)=>Object.keys(E).filter(b=>!b.startsWith("$")&&E[b]!==void 0?Q?!x(t,E).dataFields?.find(T=>T.path===b):!0:!1);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(r.mutation?.preQuery===!1)return;let n=[];if(traverse(e,({parent:E,key:Q,value:b})=>{E&&Q&&!Q.includes("$")&&isObject(E)?(Array.isArray(E[Q])?E[Q]:[E[Q]]).forEach(T=>{if(isObject(T)){if(E.$op!=="create")n.includes(T.$op)||n.push(T.$op);else if(T.$op==="delete"||T.$op==="unlink")throw new Error(`Cannot ${T.$op} under a create`)}}):!E&&isObject(b)&&(n.includes(b.$op)||n.push(b.$op));}),!n.includes("delete")&&!n.includes("unlink")&&!n.includes("replace")&&!n.includes("update")&&!n.includes("link"))return;let s=(E=>{let Q=(b,F)=>{let T=[],S={},q=["$op","$bzId","$parentKey"],k=["$relation","$entity","$id",...q];for(let P in b)if(!q.includes(P)&&!(k.includes(P)&&!F))if(!P.includes("$")&&(isObject(b[P])||Array.isArray(b[P]))){let J=b[P];if(Array.isArray(J)&&J.length>0)J.forEach(le=>{let Me={$path:P,...Q(le),...le.$filter&&{$as:le.$bzId}};T.find(U=>U.$path===Me.$path&&!U.$filter)||(T=[...T,Me]);});else {let le={$path:P,...Q(J),...!J.$filter&&{$as:J.$bzId}};T=[...T,le];}}else S[P]=b[P];return {...S,$fields:T}};return E.map(b=>Q(b,!0))})(Array.isArray(e)?e:[e]),p=(await qe(s,t,r,i)).bql.res,d=(E,Q)=>{let b=E.$id||E.id||E.$bzId;if(E.$objectPath){let{$objectPath:F}=E,T=F?.beforePath||"root",S=Array.isArray(F.ids)?`[${F.ids}]`:F.ids;return {beforePath:`${T}.${S}___${F.key}`,ids:b,key:Q}}else return {beforePath:"root",ids:b,key:Q}},c=(E,Q)=>{let b=E?.beforePath||"root",F=(Array.isArray(E?.ids)?`[${E?.ids}]`:E?.ids);return `${b}.${F}___${E?.key}`},a=E=>{if(E.includes("[")&&E.includes("]")){let[Q,b,F]=E.split(/[[\]]/);return b.split(",").map(S=>`${Q}${S}${F}`)}else return [E]},f={};(E=>produce(E,Q=>traverse(Q,b=>{let{key:F,parent:T}=b;if(T&&F&&T.$id&&!F.includes("$")){let S=d(T,F),q=c(S);if(Array.isArray(T[F])){let k=[];T[F].forEach(P=>{isObject(P)?(P.$objectPath=S,k.push(P.$id.toString())):P&&k.push(P.toString());}),f[q]={$objectPath:S,$ids:k};}else {let k=T[F];isObject(k)?(f[q]={$objectPath:S,$ids:[k.$id.toString()]},k.$objectPath=S):k&&(f[q]={$objectPath:S,$ids:[k.toString()]});}}})))(p||{});let $=E=>produce(E,Q=>traverse(Q,b=>{let{key:F,value:T,parent:S}=b;S&&F&&!F.includes("$")&&(Array.isArray(T)||isObject(T))&&!Array.isArray(S)&&(Array.isArray(S[F])?S[F].forEach(q=>{typeof q!="string"&&(q.$objectPath=d(S,F),q.$parentIsCreate=S.$op==="create",q[Gi]=S.$parentIsCreate||S[Symbol.for("grandChildOfCreate")]);}):isObject(S[F])&&(S[F].$parentIsCreate=S.$op==="create",S[F][Symbol.for("grandChildOfCreate")]=S.$parentIsCreate||S[Symbol.for("grandChildOfCreate")],S[F].$objectPath=d(S,F)));})),y=$(e),m=E=>{let Q=[];return E.forEach(F=>{if(!F.$id&&!F.id&&!F.$tempId)if(F.$filter){let T=c({...F.$objectPath,key:F.$bzId}),S=f[T];S&&(Array.isArray(S.$ids)?S.$ids:[S.$ids]).forEach(k=>{let P={...F,$id:k,$bzId:`T4_${v4()}`,$filterBzId:F.$bzId};Q.push(P);});}else {let T=c(F.$objectPath),S=f[T];S?S?.$ids.forEach(q=>{let k={...F,$id:q,$bzId:`T4_${v4()}`};Q.push(k);}):Q.push(F);}else Q.push(F);}),Q.map(F=>{let T={...F};return o(T,!0).forEach(S=>{let q=Array.isArray(T[S])?T[S]:[T[S]],k=m(q);T[S]=k;}),T})},B=m(Array.isArray(y)?y:[y]),w=$(B),L=(E=>{let Q=b=>{let F=U=>{let ee=[],z=[],O=[];return U.forEach(_=>{let ie=o(_,!0);if(ie.length>0){let I=!1;ie.forEach(W=>{(Array.isArray(_[W])?_[W]:[_[W]]).filter(Y=>!Y.$id&&!Y.id&&typeof _=="object").length&&(I=!0);}),I?ee.push(_):z.push(_);}else O.push({..._,$bzId:_.$tempId||`T_${v4()}`});}),{operationWithMultiples:ee,operationWithoutMultiples:z,otherOps:O}},{operationWithMultiples:T,operationWithoutMultiples:S,otherOps:q}=F(b),k=U=>{let z=(()=>{let W={};for(let te in U){let Z=x(t,U);!te.startsWith("$")&&Z.dataFields?.find(Y=>Y.path===te)&&(W[te]=U[te]);}return W})(),O=Object.keys(U),_=o(U,!0),ie=[],I=(W,te)=>{if(W===_.length){let Y={...te};O.forEach(re=>{re.startsWith("$")&&(Y[re]=U[re]);}),ie.push({...Y,...z});return}let Z={...te,[_[W]]:U[_[W]],...Ee(te),...z};I(W+1,Z),I(W+1,te);};return I(0,{...Ee(U)}),ie},P=[];return T.forEach(U=>{let ee=k(U),z=[];ee.forEach(O=>{let _=o(O,!0);if(O.$op==="create")z.push(O);else if(O.$id){let ie=c(O.$objectPath),I=[];if(_.forEach(W=>{let te=`${ie.includes("undefined")?"root":ie}.${O.$id}${jt}${W}`,Z=f[te];O[W].filter(re=>re.$op==="unlink"||re.$op==="delete"||re.$op==="update").length>0?Z&&I.push({key:W,ids:Z.$ids}):I.push({key:W,ids:[""]});}),I.length===_.length&&!z.find(W=>W.$id===O.$id))z.push(O);else {let W={...O,$bzId:O.$tempId||`T4_${v4()}`};_.forEach(Z=>{let Y=O[Z].filter(re=>re.$id);Y.length>0?W[Z]=Y:W[Z]=void 0;}),o(W,!0).length>0&&z.push(W);}}else if(O.$objectPath){let ie=c(O.$objectPath),I=f[ie]?.$ids||[];I.forEach(W=>{let te=[];_.forEach(Z=>{let Y=`${ie}.${W}${jt}${Z}`,re=f[Y];re&&te.push({key:Z,ids:re.$ids});}),_.length===0?I.filter(Y=>!z.find(re=>re.$id===Y)).forEach(Y=>{z.push({...O,$id:Y,$bzId:O.$tempId||`T_${v4()}`});}):te.length===_.length&&!z.find(Z=>Z.$id===W)&&(_.forEach(Z=>{let Y=`${c(O.$objectPath)}.${W}${jt}${Z}`,{$ids:re}=f[Y],gn=O[Z].find(ke=>!ke.$id),Bn=[...re.map(ke=>({...gn,$id:ke,$objectPath:{beforePath:O.$objectPath,ids:ke,key:Z}})),...O[Z].filter(ke=>ke.$id)];O[Z]=Bn;}),z.push({...O,$id:W,$bzId:O.$tempId||`T_${v4()}`}));});}else z.push(O);}),z.forEach(O=>{P.push(O);});}),[...P,...S,...q].filter(U=>o(U).length>0?!0:U.$op!=="update").map(U=>{let ee={...U};return o(ee,!0).forEach(z=>{let O=Array.isArray(ee[z])?ee[z]:[ee[z]],_=Q(O);ee[z]=_;}),ee})};return Q(E)})(Array.isArray(w)?w:[w]),D=E=>E.map(Q=>{let b=o(Q,!0),F={...Q};return b.forEach(T=>{let S=Array.isArray(Q[T])?Q[T]:[Q[T]],q=[],k=[],P=[],J={},le=ct(t,Q,T);S.filter(I=>I).forEach(I=>{I.$op==="replace"&&I.$id?(J=I,Array.isArray(I.$id)?k=[...k,...I.$id]:k.push(I.$id)):I.$op==="create"&&le==="ONE"&&I.id?(J=I,Array.isArray(I.id)?P=[...k,...I.id]:P.push(I.id)):q.push(I);});let Me=c(J.$objectPath),ee=a(Me).map(I=>f[I]),z=[];ee.filter(I=>I!=null).forEach(I=>{z=[...z,...I.$ids];});let O=z.filter(I=>!k.includes(I)),_=k.filter(I=>!z.includes(I)),ie=Ee(J);O.length>0&&q.push({...J,$op:"unlink",$id:O,$bzId:J.$tempId||`T4_${v4()}`,id:void 0,...ie}),_.length>0&&_.forEach(I=>{q.push({...J,$op:"link",$id:I,$bzId:J.$tempId||`T5_${v4()}`,...ie});}),P.length>0&&P.forEach(I=>{q.push({...J,$op:"create",id:I,$bzId:J.$tempId||`T6_${v4()}`,...ie});}),F[T]=D(q);}),F}),A=$(D($(L)));(E=>produce(E,Q=>traverse(Q,b=>{let{key:F,value:T,parent:S}=b;F&&S&&!F?.includes("$")&&(Array.isArray(T)||isObject(T))&&!Array.isArray(S)&&(Array.isArray(T)?T:[T]).forEach(k=>{let P=k.$filter?{...k.$objectPath,key:k.$filterBzId}:k.$objectPath,J=c(P),le=f[J],Me=(z,O)=>z.every(_=>O.includes(_)),U=k.$id?Array.isArray(k.$id)?Me(k.$id,le?le.$ids:[]):le?.$ids.includes(k.$id):le,ee=ct(t,S,k.$objectPath.key);if(k.$op==="link"&&U&&ee==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${c(k.$objectPath)}" because it is already occupied.`);if(k.$op)switch(k.$op){case"delete":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${k.$id}" because it is not linked to $id:"${S.$id}"`);break;case"update":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${k.$id}" because it is not linked to $id:"${S.$id}"`);break;case"unlink":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${k.$id}" because it is not linked to $id:"${S.$id}"`);break;case"link":if(U)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${k.$id}" because it is already linked to $id:"${S.$id}"`);break;}});})))(A);let N=(E=>produce(E,Q=>traverse(Q,b=>{let{value:F,meta:T}=b;isObject(F)&&(F[Symbol.for("path")]=T.nodePath,delete F.$objectPath,delete F.$parentIsCreate);})))(A);return [...Array.isArray(N)?N:[N]].sort((E,Q)=>E.$op==="create"&&Q.$op!=="create"?-1:E.$op!=="create"&&Q.$op==="create"?1:0)};var on=(e,t)=>produce(e,i=>rt(t,i)),rt=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){t.forEach(o=>rt(e,o,r));return}let i=G(e,r||t.$entity||t.$relation||t.$thing);Object.entries(t).forEach(([o])=>{o.startsWith("$")||eo(e,t,o,i);});},eo=(e,t,r,i)=>{let o=t[r];if(!o)return;let n=i.dataFields?.find(s=>s.path===r);if(n){n.contentType==="JSON"&&o!=null&&(t[r]=JSON.stringify(o));return}let l=i.linkFields?.find(s=>s.path===r);if(l){let s=l.oppositeLinkFieldsPlayedBy[0]?.thing;rt(e,o,s);return}if(i.thingType==="relation"){let s=i.roles[r],[h]=s.playedBy||[];if(!h)throw new Error(`Role ${s.name} in ${i} is not played by anything`);rt(e,o,h.thing);}};var cn=async(e,t,r,i)=>{let o=Array.isArray(e)?e:[e],n=o.map(h=>Nt(h,!0)),s=(await qe(n,t,r,i)).bql.res;return o.map((h,p)=>{let d=G(t,h.$thing);return hn({mut:h,node:s[p],schema:t,thing:d})})},dn=new Set(["$op","$bzId","$parentKey"]),ro=new Set(["$relation","$entity","$id",...dn]),Nt=(e,t)=>{let r={};e.$fields?.forEach(o=>{typeof o=="string"?r[o]=o:r[o.$path]=o;});let i={};for(let o in e){if(dn.has(o)||ro.has(o)&&!t)continue;let n=e[o];o.startsWith("$")?i[o]=n:Array.isArray(n)?n[0]&&typeof n[0]=="object"&&(r[o]={$path:o,...Nt(n[0],!1)}):isObject(n)&&(r[o]={$path:o,...Nt(n,!1)});}return i.$fields=Object.values(r),i},hn=e=>{let{mut:t,node:r,schema:i,thing:o}=e,n=pn(o),l=io(r);if(Array.isArray(t))return t.map(h=>{let p=l[h.$id];return p?sn({mut:h,node:p,schema:i,thing:o,...n}):h});let s=l[t.$id];return sn({mut:t,node:s,schema:i,thing:o,...n})},sn=e=>{let{mut:t,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:l,roleFieldMap:s}=e,{$fields:h,...p}=t;if(!r)return p;let d=un({$fields:t.$fields,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:l,roleFieldMap:s}),c={...p,[De]:d};for(let a in t){if(a.startsWith("$"))continue;let f=t[a];if(n[a]||!f||typeof f!="object"){c[a]=f;continue}let $=l[a]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||s[a]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${o.name}" does not have field "${a}"`);let y=G(i,$);c[a]=hn({mut:f,schema:i,node:r[a],thing:y});}return c},un=e=>{let{$fields:t,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:l,roleFieldMap:s}=e,h=t||no(o),p={$id:r.$id};return h.forEach(d=>{let c=typeof d!="string",a=c?d.$path:d,f=r[a];if(n[a]){p[a]=f;return}let $=l[a]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||s[a]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${o.name}" does not have field "${a}"`);if(!c){f&&(p[a]=Array.isArray(f)?f.map(an):an(f));return}let y=G(i,$),m=pn(y);p[a]=Array.isArray(f)?f.map(B=>ln({...m,$fields:d.$fields,value:B,schema:i,thing:y})):ln({...m,$fields:d.$fields,value:f,schema:i,thing:y});}),p},no=e=>{let t=[];return e.dataFields?.forEach(r=>{t.push(r.path);}),e.linkFields?.forEach(r=>{t.push(r.path);}),e.thingType==="relation"&&t.push(...Object.keys(e.roles)),t},an=e=>{if(typeof e=="string")return e;if(!e||typeof e!="object")throw new Error(`"${JSON.stringify(e)}" is neither an id nor an object with prop "$id"`);if(typeof e.$id!="string")throw new Error(`"${JSON.stringify(e)}" is does not have prop "$id"`);return e.$id},ln=e=>{let{value:t}=e;if(!t||typeof t!="object"||!t.$id)throw new Error(`"${JSON.stringify(e)}" is neither an id nor an object with prop "$id"`);return un({...e,node:t})},pn=e=>{let t=Object.fromEntries(e.dataFields?.map(o=>[o.path,o])||[]),r=Object.fromEntries(e.linkFields?.map(o=>[o.path,o])||[]),i=e.thingType==="relation"?e.roles||{}:{};return {dataFieldMap:t,linkFieldMap:r,roleFieldMap:i}},io=e=>{if(!Array.isArray(e))return e&&typeof e=="object"&&e.$id?{[e.$id]:e}:{};let t={};return e.forEach(r=>{!r||typeof r!="object"||!r.$id||(t[r.$id]=r);}),t};var fn=he,Pe=(e,t)=>t.data?{...e,bql:{...e.bql,current:t.data}}:e,oo=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),so=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),ao=(e,t)=>({...e,typeDB:{...e.typeDB,tqlMutation:t.data}}),lo=(e,t)=>({...e,typeDB:{...e.typeDB,tqlRes:t.data}}),co=async e=>Object.keys(e.bql.current).length?ft(e.bql.current,e.schema,e.config):ft(e.bql.raw,e.schema,e.config),ho=async e=>nn(e.bql.current,e.schema,e.config,e.handles),uo=async e=>cn(e.bql.current,e.schema,e.config,e.handles),po=async e=>Er(e.bql.current,e.schema),fo=async e=>Fr(e.bql.things,e.bql.edges,e.schema),$o=async e=>fr(e.typeDB.tqlMutation,e.handles,e.config),mo=async e=>$r(e.typeDB.tqlRes,e.bql.things,e.bql.edges,e.schema,e.config),yo=()=>!0,go=e=>Ie(e.bql.current),we=H("error","error",V((e,t)=>({...e,error:t.error}))),Bo=be("stringify",{stringify:v(async e=>on(e.bql.raw,e.schema),H("done","enrich",V(Pe)),we),enrich:v(co,H("done","preQuery",mt(yo),V(Pe)),H("done","parseBQL",V(Pe)),we),preHookDependencies:v(uo,H("done","enrich",V(Pe)),we),preQuery:v(ho,H("done","preHookDependencies",mt(go),V(Pe)),H("done","parseBQL",V(Pe)),we),parseBQL:v(po,H("done","buildMutation",V(so)),we),buildMutation:v(fo,H("done","runMutation",V(ao)),we),runMutation:v($o,H("done","parseMutation",V(lo)),we),parseMutation:v(mo,H("done","success",V(oo)),we),success:fn(),error:fn()},e=>e),Eo=async e=>new Promise((t,r)=>{me(Bo,i=>{i.machine.state.name==="success"&&t(i.context),i.machine.state.name==="error"&&r(i.context);},e);}),$n=async(e,t,r,i)=>Eo({bql:{raw:e,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:t,config:r,handles:i,depthLevel:0,error:null});enableMapSet();var Wt=class{schema;config;dbHandles;constructor({schema:t,config:r}){this.schema=t,this.config=r;}getDbHandles=()=>this.dbHandles;init=async()=>{let t={typeDB:new Map,surrealDB:new Map};await Promise.all(this.config.dbConnectors.map(async i=>{if(i.provider==="surrealDB"){let o=new Surreal;await o.connect(i.url),await o.signin({namespace:i.namespace,database:i.dbName,username:i.username,password:i.password}),t.surrealDB.set(i.id,{client:o});}if(i.provider==="typeDB"&&i.dbName){let[o,n]=await tryit(TypeDB.coreDriver)(i.url);if(o){let l=`[BORM:${i.provider}:${i.dbName}:core] ${o.message??"Can't create TypeDB Client"}`;throw new Error(l)}try{let l=await n.session(i.dbName,SessionType.DATA);t.typeDB.set(i.id,{client:n,session:l});}catch(l){let s=`[BORM:${i.provider}:${i.dbName}:session] ${(l.messageTemplate?._messageBody()||l.message)??"Can't create TypeDB Session"}`;throw new Error(s)}}if(i.provider==="typeDBCluster"&&i.dbName){let o=new TypeDBCredential(i.username,i.password,i.tlsRootCAPath),[n,l]=await tryit(TypeDB.cloudDriver)(i.addresses,o);if(n){let s=`[BORM:${i.provider}:${i.dbName}:core] ${n.message??"Can't create TypeDB Cluster Client"}`;throw new Error(s)}try{let s=await l.session(i.dbName,SessionType.DATA);t.typeDB.set(i.id,{client:l,session:s});}catch(s){let h=`[BORM:${i.provider}:${i.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(h)}}}));let r=Yt(this.schema,t);this.schema=r,this.dbHandles=t;};#e=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#e(),this.schema);define=async()=>(await this.#e(),_t(this.config,this.schema,this.dbHandles));query=async(t,r)=>{await this.#e();let i={...this.config,query:{...it.query,...this.config.query,...r}},o=Array.isArray(t),n=o?t:[t],[l,s]=await tryit(qe)(n,this.schema,i,this.dbHandles);if(l){let p=new Error(l.error);throw p.stack=l.error.stack,p}let h=s.bql.res;return o?h:h[0]};mutate=async(t,r)=>{await this.#e();let i={...this.config,mutation:{...it.mutation,...this.config.mutation,...r}},[o,n]=await tryit($n)(t,this.schema,i,this.dbHandles);if(o){let s=new Error(o.error.message);throw s.stack=o.error.stack,s}return n.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:r})=>{r.isOpen()&&await r.close(),await t.close();});}},Fc=Wt;//! Todo: delete when this works with the new $thing and $thingType fields
36
+ ${y}`})(),n=e.dbConnectors[0].id,l=r.typeDB.get(n)?.session,s=r.typeDB.get(n)?.client;if(!l){console.log("Session Status: ","NO SESSION");return}await l.close();let[{dbName:u}]=e.dbConnectors;await(await s.databases.get(u)).delete(),await s.databases.create(u);let c=await s.session(e.dbConnectors[0].dbName,SessionType.SCHEMA),d=await c.transaction(TransactionType.WRITE);await d.query.define(o),await d.commit(),await d.close();let a=await c.transaction(TransactionType.READ);(await(await a.query.match("match $a sub thing;")).collect()).forEach(async y=>{y.get("a");}),await a.close();};var ae=Symbol.for("queryPath"),We=Symbol.for("stepPrint"),Qe=Symbol.for("edgeType"),Be=Symbol.for("edgeSchema"),De=Symbol.for("dbNode"),ot=Symbol.for("isTransformed"),le=Symbol.for("fieldSchema"),$e=Symbol.for("sharedMetadata"),Te=Symbol.for("suqlMetadata");var Ht={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var Kt=({linkField:e,originalRelation:t,withExtensionsSchema:r})=>{if(e.isVirtual)return `$this.${e.path}.id`;let i=r.relations[e.relation].subTypes||[],o=[e.relation,...i],n=`<-\`${t}_${e.plays}\`<-(\`${o.join("`,`")}\`)`;if(e.target==="relation")return n;if(e.target==="role"){let[l]=e.oppositeLinkFieldsPlayedBy,s=r.entities[l.thing]?.subTypes||r.relations[l.thing]?.subTypes||[],u=[l.thing,...s],f=`->\`${t}_${l.plays}\`->(\`${u.join("`,`")}\`)`;return `${n}${f}`}else throw new Error("Unsupported linkField target")};var Zt=(e,t,r)=>r?t:`${e}\xB7${t}`;var Xt=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))))[0],xe=(e,t)=>Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))),vt=(e,t)=>{let r=[],i=produce(e,n=>traverse(n,({key:l,value:s,meta:u})=>{if(u.depth===2&&(l&&(s.dataFields=s.dataFields?.map(f=>({...f,cardinality:f.cardinality||"ONE",dbPath:Zt(l,f.path,f.shared)}))),s.extends)){if(!s.defaultDBConnector.as)throw new Error(`[Schema] ${l} is extending a thing but missing the "as" property in its defaultDBConnector`);let f=n.entities[s.extends]||n.relations[s.extends],c=[s.extends,...f.allExtends||[]];if(s.allExtends=c,c.forEach(d=>{if(n.entities[d])n.entities[d].subTypes=[l,...n.entities[d].subTypes||[]];else if(n.relations[d])n.relations[d].subTypes=[l,...n.relations[d].subTypes||[]];else throw new Error(`[Schema] ${l} is extending a thing that does not exist in the schema: ${d}`)}),s.idFields=f.idFields?Array.from(new Set((s.idFields||[]).concat(f.idFields))):s.idFields,s.dataFields=f.dataFields?(s.dataFields||[]).concat(f.dataFields.map(d=>{let a=s.extends,p=e.entities[a]||e.relations[a];for(;!p.dataFields?.find(h=>h.path===d.path);)a="extends"in p?p.extends:void 0,p=e.entities[a]||e.relations[a];return {...d,dbPath:Zt(a,d.path,d.shared),[$e]:{inheritanceOrigin:d[$e]?.inheritanceOrigin||s.extends}}})):s.dataFields,"roles"in f){let d=s,a=f;if(a.roles){let p=mapEntries(a.roles,(h,$)=>[h,{...$,[$e]:{inheritanceOrigin:$[$e]?.inheritanceOrigin||s.extends}}]);d.roles={...d.roles||{},...p};}}s.linkFields=f.linkFields?(s.linkFields||[]).concat(f.linkFields.map(d=>({...d,[$e]:{inheritanceOrigin:d[$e]?.inheritanceOrigin||s.extends}}))):s.linkFields,f?.hooks?.pre&&(s.hooks=s.hooks||{},s.hooks.pre=s.hooks.pre||[],s.hooks.pre=[...f?.hooks?.pre||[],...s?.hooks?.pre||[]]);}},{traversalType:"breadth-first"}));return traverse(e,({key:n,value:l,meta:s})=>{if(n==="linkFields"){let f=(()=>{if(!s.nodePath)throw new Error("No path");let[d,a]=s.nodePath.split(".");return {thing:a,thingType:d==="entities"?"entity":d==="relations"?"relation":""}})(),c=Array.isArray(l)?l.map(d=>({...d,...f})):[{...l,...f}];r.push(...c);}}),produce(i,n=>traverse(n,({value:l,key:s,meta:u})=>{if(u.depth===2&&l.idFields&&!l.id){l.name=s;let f=()=>{if(u.nodePath?.split(".")[0]==="entities")return "entity";if(u.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};l.thingType=f();let c=Object.keys(t).find(d=>t[d]?.get(l.defaultDBConnector.id));if(l.db=c,l.dbContext=Ht[c],l.computedFields=[],l.virtualFields=[],l.requiredFields=[],l.enumFields=[],l.fnValidatedFields=[],"roles"in l&&Object.entries(l.roles).forEach(([a,p])=>{p.fieldType="roleField";let h=r.filter(M=>M.relation===s&&M.plays===a)||[];p.playedBy=h,p.name=a;let $=[...new Set(h.map(M=>M.thing))];p.$things=$;let y=p[$e]?.inheritanceOrigin||l.name;if($.length>1)throw new Error(`Not supported yet: Role ${a} in ${l.name} is played by multiple things: ${$.join(", ")}`);let m=$.flatMap(M=>{let L=v(e,M)?.subTypes||[];return [M,...L]}),B=`->\`${y}_${a}\`->(\`${m.join("`,`")}\`)`;p[Te]={queryPath:B};}),"linkFields"in l&&l.linkFields){let d=l;d.linkFields?.forEach(a=>{a.fieldType="linkField";let p=i.relations[a.relation];if(p.roles?.[a.plays]===void 0)throw new Error(`The role ${a.plays} is not defined in the relation ${a.relation} (linkField: ${a.path})`);if(a.target==="relation"&&(a.$things=[a.relation],a.oppositeLinkFieldsPlayedBy=[{plays:a.path,thing:a.relation,thingType:"relation"}]),a.target==="role"){let y=r.filter(m=>m.relation===a.relation&&m.plays!==a.plays)||[];if(a.oppositeLinkFieldsPlayedBy=y,a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter(m=>m.target==="role"),a.$things=a.oppositeLinkFieldsPlayedBy.map(m=>m.thing),a.oppositeLinkFieldsPlayedBy.length>1)throw new Error(`Not supported: LinkField ${a.path} in ${d.name} has multiple candidates ${a.oppositeLinkFieldsPlayedBy.map(m=>m.thing).join(",")} and this is not yet supported. Please target a single one using targetRoles with a single role`)}let h=p.roles?.[a.plays][$e]?.inheritanceOrigin??a.relation,$=Kt({linkField:a,originalRelation:h,withExtensionsSchema:i});a[Te]={queryPath:$};});}}if(typeof l=="object"&&"playedBy"in l){let f=[...new Set(l.playedBy.map(c=>c.thing))];if(f.length>1)throw new Error(`[Schema] roleFields can be only played by one thing. Role: ${s}, path:${u.nodePath}, played by: ${f.join(", ")}`);if(l.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${s}, path:${u.nodePath}`)}if(u.depth===4){let[f,c]=u.nodePath?.split(".")||[],d=n[f][c];!isArray(l)&&typeof l=="object"&&(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));}}))},v=(e,t)=>{if(t in e.entities)return e.entities[t];if(t in e.relations)return e.relations[t];throw new Error(`${t} is not defined in the schema`)},x=(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)}`)},_e=(e,t)=>{let r=e.dataFields?.find(n=>n.path===t);if(r)return ["dataField",r];let i=e.linkFields?.find(n=>n.path===t);if(i)return ["linkField",i];let o="roles"in e?e.roles[t]:void 0;if(o)return ["roleField",o];throw new Error(`Field ${t} not found in schema, Defined in $filter`)},Ve=(e,t)=>{let r=x(e,t);if(r?.idFields?.length&&r?.idFields?.length>1)throw new Error(`Multiple ids not yet enabled / composite ids: ${r?.idFields}`);let[i]=r.idFields;return i},Gt=(e,t)=>{let r=e.$thing||e.$entity||e.$relation;if(!r)throw new Error("[Internal] No thing found");if(e.$entity)return "entity";if(e.$relation)return "relation";if(t.entities[r])return "entity";if(t.relations[r])return "relation";throw new Error("No thing found")},lt=(e,t,r)=>{let i=x(e,t),o=i.linkFields?.find(s=>s.path===r);if(o)return o;let n=i.dataFields?.find(s=>s.path===r);if(n)return n;let l="roles"in i?i.roles?.[r]:void 0;if(l)return l;throw new Error(`Field ${r} not found in schema`)},ct=(e,t,r)=>lt(e,t,r)?.cardinality,ue=(e,t)=>{let r=e.dataFields?.map(h=>h.path)||[],i=e.linkFields?.map(h=>h.path)||[],o="roles"in e?listify(e.roles,h=>h):[],n=[...r||[],...i||[],...o||[]],s=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...n];if(!t)return {fields:n,dataFields:r,roleFields:o,linkFields:i};let u=t.$fields?t.$fields.map(h=>{if(typeof h=="string"){if(h.startsWith("$")||h.startsWith("%"))return;if(!n.includes(h))throw new Error(`Field ${h} not found in the schema`);return h}if("$path"in h&&typeof h.$path=="string")return h.$path;throw new Error("[Wrong format] Wrongly structured query")}):listify(t,h=>{if(!(h.startsWith("$")||h.startsWith("%"))){if(!n.includes(h))throw new Error(`[Schema] Field ${h} not found in the schema`);return h}}).filter(h=>h!==void 0),f=t.$filter?listify(t.$filter,h=>h.toString().startsWith("$")?void 0:h.toString()).filter(h=>h&&r?.includes(h)):[],c=t.$filter?listify(t.$filter,h=>h.toString().startsWith("$")?void 0:h.toString()).filter(h=>h&&[...o||[],...i||[]].includes(h)):[],d=[...u,...f].filter(h=>!h?.startsWith("%")).filter(h=>!s.includes(h)).filter(h=>h),a=t.$filter?xe(t.$filter,(h,$)=>f.includes(h)):{},p=t.$filter?xe(t.$filter,(h,$)=>c.includes(h)):{};return {fields:n,dataFields:r,roleFields:o,linkFields:i,usedFields:u,usedLinkFields:i.filter(h=>u.includes(h)),usedRoleFields:o.filter(h=>u.includes(h)),usedDataFields:r.filter(h=>u.includes(h)),unidentifiedFields:d,...f.length?{localFilters:a}:{},...c.length?{nestedFilters:p}:{}}};var er=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},tr=(e,t,r)=>{let o=(r.nodePath||"").split("."),n=isArray(t)?o.slice(0,-2).join("."):o.slice(0,-1).join(".");return t?getNodeByPath(e,n):{}},Ee=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var He=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),pe=e=>{if(Array.isArray(e))return e.map(t=>current(t));if(e&&typeof e=="object"){let t=isDraft(e)?current(e):e,r={};return Object.entries(t).forEach(([i,o])=>{r[i]=isDraft(o)?current(o):o;}),r}else return e},oe=(e,t)=>{if(e===void 0)throw new Error("Value is undefined");return e},w=(e,t)=>{let r="";for(let i=0;i<t;i++)r+=" ";return `${r}${e}`};var Re=(e,t)=>{if(t.fieldType==="linkField"){let r=t.oppositeLinkFieldsPlayedBy;if(r?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!r?.length)throw new Error(`[Internal] Field ${e} should have a player`);return r}else if(t.fieldType==="roleField"){if([...new Set(t.playedBy?.map(r=>r.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 rr=(e,t,r)=>{let i=isArray(e[t])?e[t]:[e[t]];if(!i.every(o=>typeof o=="object"))if(i.every(o=>typeof o=="string")){let o=Re(t,r),[n]=o,l=e.$op==="create"?"link":"replace",s=n.thing,u=n.thingType;if(i.some(f=>f.startsWith("_:")))throw new Error("[Not supported] At least one child of a replace is a tempId");e[t]={$id:e[t],$op:l,$thing:s,$thingType:u,$bzId:`S_${v4()}`};}else throw new Error(`[Mutation Error] Replace can only be used with a single id or an array of ids. (Field: ${t} Nodes: ${JSON.stringify(i)} Parent: ${JSON.stringify(e,null,2)})`)};var Le=(e,t,r)=>{let i=x(r,t),{usedDataFields:o}=ue(i,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"&&o.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&o.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var Ke=(e,t,r)=>{let i=x(r,t),{usedFields:o}=ue(i,t);return t.$op?(Le(e,t,r),t.$op):t.$id||t.$filter?o.length>0?(Le(e,{...t,$op:"update"},r),"update"):(Le(e,{...t,$op:"link"},r),"link"):t.$tempId?o.length>0?(Le(e,{...t,$op:"create"},r),"create"):(Le(e,{...t,$op:"create"},r),"link"):(Le(e,{...t,$op:"create"},r),"create")};var ir=(e,t)=>{let i=(isArray(e.$root)?e.$root:[e.$root]).map(o=>{let n=Ke(o,o,t);return {...{...o.$thing?{}:{$thing:o.$entity||o.$relation},...o.$thingType?{}:{$thingType:Gt(o,t)},...o.$op?{}:{$op:n},...o.$bzId?{}:{$bzId:`R_${v4()}`}},...o}});e.$root=isArray(e.$root)?i:i[0];};var Ue=(e,t)=>{let r=t[We];return isSet(r)?r.has("clean")?(Reflect.set(t,We,r.add("clean")),!0):!1:(Reflect.set(t,We,new Set(["clean"])),!0)};var or=(e,t,r)=>{if(Ue("split_ids",e)){let i=(isArray(e[t])?e[t]:[e[t]]).flatMap(o=>{if(isObject(o)&&"$id"in o&&isArray(o.$id)){let n=o;if(x(r,n),!n.$bzId)throw new Error("[Internal Error] No bzId found");return n.$id.map((l,s)=>({...pe(n),$id:l,$bzId:`${n.$bzId}_${s}`,...Ee(n)}))}return o});(i.length>isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=i);}};var ar=(e,t,r,i)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(n=>{let l=Re(t,r),[s]=l,u=Ke(e,{...n,$thing:s.thing,$thingType:s.thingType},i),f=n.$bzId?n.$bzId:n.$tempId?n.$tempId:`N_${v4()}`;if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);return {...n,[Be]:r,$thing:s.thing,$thingType:s.thingType,$op:u,$bzId:f}});e[t]=isArray(e[t])?o:o[0];};var Cn=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,On=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,lr=e=>{let r=e.toString().replace(Cn,"").trim().split("=>")[0].split("{")[0].replace(On,"").trim(),i=r.substring(r.indexOf("(")+1,r.lastIndexOf(")")).trim();return i?(i.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(n=>n.includes("{")&&n.includes("}")?(n.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(s=>s.split(":")[0].trim().replace(/['"[\]]/g,"")):n.trim()).filter(Boolean):[]};var Ae=({currentThing:e,fieldSchema:t,mandatoryDependencies:r=!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(r){let{fn:o}=t.default,l=lr(o).filter(s=>!(s in e));if(l.length)throw new Error(`Virtual field: Missing arguments ${l.join(", ")}`)}if(!t.default.fn)throw new Error("[Schema] No fn in default field schema");return "default"in t?t.default?.fn(e):void 0};var cr=(e,t,r)=>{let i=e[t];i&&(isArray(i)?i:[i]).forEach(o=>{let n=x(r,o),{unidentifiedFields:l}=ue(n,o),{computedFields:s,virtualFields:u}=n,f=listify(o,(a,p)=>p!==void 0?a:void 0),c=f.filter(a=>u?.includes(a));if(c.length>0)throw new Error(`Virtual fields can't be sent to DB: "${c.join(",")}"`);if(s.filter(a=>!f.includes(a)).forEach(a=>{let p=n.dataFields?.find(B=>B.path===a),$=n.linkFields?.find(B=>B.path===a)?.oppositeLinkFieldsPlayedBy[0],y="roles"in n?Xt(n.roles,(B,M)=>B===a):void 0,m=p||$||y;if(!m)throw new Error(`no field Def for ${a}`);if(o.$op==="create"&&!o[a]){let B=Ae({currentThing:o,fieldSchema:m,mandatoryDependencies:!0});o[a]=B;}}),l.length>0)throw new Error(`Unknown fields: [${l.join(",")}] in ${JSON.stringify(o)}`)});};var Je=(e,t)=>{let r=x(t,e).hooks;if(r?.pre){let i=`on${er(e.$op)}`;return r.pre.filter(l=>!l.triggers||l.triggers[i]?.()).flatMap(l=>l.actions)}return []};var hr=(e,t,r,i)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(n=>{if("$thing"in n){if(n.$fields)return n;let{requiredFields:l,enumFields:s,fnValidatedFields:u,dataFields:f}=x(r,n);if("$op"in n&&n.$op==="create"&&l.forEach(c=>{if(!(c in n))throw new Error(`[Validations] Required field "${c}" is missing.`)}),("$op"in n&&n.$op==="update"||n.$op==="create")&&s.forEach(c=>{if(c in n){let d=f?.find(a=>a.path===c)?.validations?.enum;if(!d)throw new Error(`[Validations] Enum field "${c}" is missing enum options.`);if(isArray(n[c]))n[c].some(a=>{if(!d.includes(a))throw new Error(`[Validations] Option "${a}" is not a valid option for field "${c}".`)});else if(d&&!d.includes(n[c]))throw new Error(`[Validations] Option "${n[c]}" is not a valid option for field "${c}".`)}}),("$op"in n&&n.$op==="update"||n.$op==="create")&&u.forEach(c=>{if(c in n)try{let d=f?.find(a=>a.path===c)?.validations?.fn;if(!d)throw new Error("Missing validation function.");if(!d(n[c]))throw new Error("Failed validation function.")}catch(d){throw new Error(`[Validations:attribute:${c}] ${d.message}`)}}),isObject(n)&&"$thing"in n){let c=n.$thing,d=n,a=clone(pe(e)),p=clone(pe(d)),h=i.mutation?.context||{},$=clone(pe(n[De]||{}));Je(d,r).forEach(m=>{if(m.type==="validate"){if(m.severity!=="error")return;try{let B=m.fn(p,a,h,$);if(B===!1)throw new Error(`${m.message}.`);if(B!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(B){throw new Error(`[Validations:thing:${c}] ${B.message}`)}}});}}});};var pr=(e,t,r,i)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(n=>{if(He(n)){if(n.$fields||n[ot])return n;let l=Je(n,r).filter(d=>d.type==="transform"),s=clone(pe(e)),u=clone(pe(n)),f=i.mutation?.context||{},c=clone(pe(n[De]||n.$dbNode));return l.forEach(d=>{let a=d.fn(u,s,f,c||{});Object.keys(a).length!==0&&(n={...u,...a,...Ee(n),[ot]:!0});}),n}});e[t]=isArray(e[t])?o:o[0];};var fr=(e,t,r)=>{let i=Re(t,r),[o]=i;e[t]={$thing:o.thing,$thingType:o.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Be]:r};};var Ie=e=>{if(Array.isArray(e)){for(let t of e)if(Ie(t))return !0;return !1}if(e.$fields)return !0;for(let t in e){if(t.startsWith("$"))continue;let r=e[t];if(r&&typeof r=="object"&&Ie(e[t]))return !0}return !1};var Hn=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(Ue("set_tempId",e))if(e.$tempId?.startsWith("_:")){let r=e.$tempId.substring(2);e.$tempId=r,e.$bzId=r;}else throw new Error('[Wrong format] TempIds must start with "_:"');else throw new Error("[Internal] TempId already modified")},Kn=(e,t)=>{},ft=(e,t,r)=>{let i={$rootWrap:{$root:e}},o=Ie(Array.isArray(e)?e:[e]),n=produce(i,l=>traverse(l,({value:s,parent:u,key:f,meta:c})=>{if(!(!u||!f)&&isObject(s)){let d=c.nodePath?.split(".")||[];if(!("$root"in s)){if(!("$thing"in s||"$entity"in s||"$relation"in s)){let h=["$fields","$dbNode","$filter"],$=d[d.length-1],y=d[d.length-2];if(f==="$root")throw new Error("Root things must specify $entity or $relation");if(!h.includes($)&&!h.includes(y))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(s)?current(s):s)}`)}}let a=s,p=d.includes("$filter");Object.keys(a).forEach(h=>{if(Hn(a,h),h!=="$root"&&p||h!=="$root"&&(h.startsWith("$")||h.startsWith("%")))return;let $=h!=="$root"?lt(t,a,h):{fieldType:"rootField"};if(!$)throw new Error(`[Internal] Field ${h} not found in schema`);if("contentType"in $)return Kn();if(["rootField","linkField","roleField"].includes($.fieldType)){if(["linkField","roleField"].includes($.fieldType)&&(a[h]===null?fr(a,h,$):rr(a,h,$)),$.fieldType==="rootField"){if(!("$root"in a))throw new Error(`[Internal] Field ${h} is a rootField but the object is not a root`);ir(a,t);}let y=isArray(a[h])?a[h]:[a[h]],m=d.slice(1).join(".");y.forEach(M=>{if(M){if($?.cardinality==="ONE"&&!M.$op&&!M.$id&&!M.$filter&&!M.$tempId&&a.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${m}.${h}`);if(M.$tempId&&!(M.$op===void 0||M.$op==="link"||M.$op==="create"||M.$op==="update"))throw new Error(`Invalid op ${M.$op} for tempId. TempIds can be created, or when created in another part of the same mutation. In the future maybe we can use them to catch stuff in the DB as well and group them under the same tempId.`)}}),["linkField","roleField"].includes($.fieldType)&&ar(a,h,$,t),or(a,h,t),["rootField","linkField","roleField"].includes($.fieldType)&&cr(a,h,t),(isArray(a[h])?a[h]:[a[h]]).forEach(M=>{let g=x(t,M),{unidentifiedFields:L,usedLinkFields:D,usedFields:A,fields:C}=ue(g,M);if(A.forEach(j=>{if(!C.includes(j))throw new Error(`[Schema] Field ${j} not found in the schema`)}),L.length>0)throw new Error(`Unknown fields: [${L.join(",")}] in ${JSON.stringify(s)}`);if(D.length>1){let j=g.linkFields?.filter(N=>D.includes(N.path));j?.some((N,se)=>j.some((K,R)=>{if(se!==R&&N.target!==K.target&&N.relation===K.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),o||(pr(a,h,t,r),hr(a,h,t,r));}});}}));return isArray(n.$rootWrap.$root),n.$rootWrap.$root};var Ze=async(e,t)=>{let r=t.dbConnectors[0].id,i=e.typeDB?.get(r)?.session,o=e.typeDB?.get(r)?.client;if(!i||!i.isOpen()){if(!o)throw new Error("Client not found");i=await o.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(r,{client:o,session:i});}return {client:o,session:i}};var $r=async(e,t,r)=>{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:i}=await Ze(t,r),o=await i.transaction(TransactionType.WRITE),n=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,l=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;try{n&&await o.query.delete(n);let s=l&&o.query.insert(l),u=s?await s.collect():void 0;return await o.commit(),{insertions:u}}catch(s){throw new Error(`Transaction failed: ${s.message}`)}finally{await o.close();}};var mr=async(e,t,r,i,o)=>{let n=[...t,...r],l=n.map(s=>{let u=e.insertions?.find(d=>d.get(`${s.$bzId}`))?.get(`${s.$bzId}`),f=s.$thing||s.$relation||s.$entity,c=f?v(i,f):void 0;if(s.$op==="create"||s.$op==="update"||s.$op==="link"){if(s.$op!=="update"&&!u&&s.$id)return {$id:s.$id,$error:"Does not exist or it's not linked to the parent"};let d=u?.asThing().iid,a=Object.entries(s).filter(([h,$])=>!h.startsWith("$")).reduce((h,[$,y])=>{if(c?.dataFields?.find(B=>B.path===$)?.contentType==="JSON")return h[$]=JSON.parse(y),h;if(s.$thingType==="relation"){let B=n.filter(M=>M.$id&&M.$bzId===y);return B.length===1?(h[$]=B[0].$id,h):(h[$]=y,h)}return h[$]=y,h},{});if(o.mutation?.noMetadata)return a;let p=s.$tempId&&!s.$tempId.startsWith("_:")?{$tempId:`_:${s.$tempId}`}:{};return {$dbId:d,...s,...a,[s.path]:s.$id,...p}}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(l)};var yr=e=>{let t=({value:r})=>(r&&typeof r=="object"&&"$id"in r&&(Object.keys(r).filter(n=>n.startsWith("$")).forEach(n=>delete r[n]),Object.keys(r).filter(n=>typeof n=="symbol").forEach(n=>delete r[n])),r);return produce(e,r=>traverse(r,t))};var Fr=async(e,t)=>{let r=c=>{let d=[],a=[],p=m=>{if(m.$id)return m.$id;let B=x(t,m),{idFields:M}=B;if(!M)throw new Error(`no idFields: ${JSON.stringify(m)}`);let[g]=M;if(!g)throw new Error(`no idField: ${JSON.stringify(m)}`);let L=B.dataFields?.find(C=>C.path===g),D=Ae({currentThing:m,fieldSchema:L,mandatoryDependencies:!0}),A=m[g]||m.$id||D;if(!A)throw new Error(`no idValue: ${JSON.stringify(m)}`);return A},h=m=>{if(m.$op==="create"){let B=p(m);if(d.find(M=>M.$id===B&&M.$op==="create"))throw new Error(`Duplicate id ${B} for node ${JSON.stringify(m)}`);if(a.find(M=>M.$bzId===m.$bzId))throw new Error(`Duplicate $bzId ${m.$bzId} for node ${JSON.stringify(m)}`);d.push({...m,$id:B});return}m.$tempId&&m.$op==="match"||d.push(m);},$=m=>{if(m.$op==="create"){let B=p(m);if(d.find(M=>M.$id===B),a.find(M=>M.$bzId===m.$bzId))throw new Error(`Duplicate %bzId ${m.$bzIdd} for edge ${JSON.stringify(m)}`);a.push({...m,$id:B});return}a.push(m);};return traverse(c,({value:m,parent:B,meta:M})=>{if(!isObject(m))return;let g=m;if(g.$thing){if(!g.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(g)}`);if(!g.$bzId)throw new Error("[internal error] BzId not found");let L=x(t,g),{dataFields:D,roleFields:A,linkFields:C,usedFields:j}=ue(L,g),N=()=>{if(g.$op==="create"||g.$op==="delete")return g.$op;if(g.$op==="update"){let R=j.filter(b=>D?.includes(b)),E=j.filter(b=>A?.includes(b)),Q=j.filter(b=>C?.includes(b));if(R.length>0)return "update";if(E.length>0||Q.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(g)}`)}return "match"},se={...g.$id&&{$id:g.$id},...g.$tempId&&{$tempId:g.$tempId},...g.$filter&&{$filter:g.$filter},$thing:g.$thing,...g.$thingType&&{$thingType:g.$thingType},...shake(pick(g,D||[""])),$op:N(),$bzId:g.$bzId};h(se);let K=g[Be];if(K?.fieldType==="linkField"){if((g.$op==="link"||g.$op==="unlink")&&(g.$id||g.$filter)){if(g.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");d.push({...g,$op:"match"});}let R=K.relation===g.$thing,E=R?g.$bzId:`LT_${v4()}`,b=tr(c,B,M).$bzId;if(!b)throw new Error("No parent id found");let F=()=>{if(g.$op==="delete")return R?"match":"delete";if(g.$op==="unlink")return R?"unlink":"delete";if(g.$op==="link"||g.$op==="create")return R?"link":"create";if(g.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},T=x(t,{$thing:K.relation,$thingType:"relation"});if(!Object.keys(T.roles).includes(K.plays))throw new Error(`[Wrong format] Field ${K.plays} is not a role of relation ${K.relation}`);let O={$bzId:E,$thing:K.relation,$thingType:"relation",...g.$tempId?{$tempId:g.$tempId}:{},$op:F(),...R?{}:{[K.path]:g.$bzId},[K.plays]:b,[Be]:K,[Qe]:"linkField"};$(O),(g.$op==="unlink"||F()==="unlink")&&R&&$({$thing:K.relation,$thingType:"relation",$bzId:E,$op:"match",[K.plays]:b,[Be]:K,[Qe]:"linkField"});}if(g.$thingType==="relation"){let R=xe(g,(b,F)=>A.includes(b)),E=mapEntries(R,(b,F)=>isArray(F)?[b,F]:isObject(F)?[b,F.$bzId]:[b,F]),Q=xe(m,(b,F)=>b.startsWith("$")||b.startsWith("Symbol"));if(Object.keys(R).filter(b=>!b.startsWith("$")).length>0){if(g.$op==="create"||g.$op==="delete"){let b=()=>{if(g.$op==="create")return "link";if(g.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},F=x(t,g).roles,T=mapEntries(E,(O,k)=>{let P=F[O]?.cardinality;if(!P)throw new Error(`Role ${O} not found in schema`);if(Array.isArray(k)){if(P==="ONE"){if(k.length>1)throw new Error(`[Error] Role ${O} is not a MANY relation`);return [O,k[0].$bzId||k[0]]}return [O,k.map(J=>J.$bzId||J)]}return [O,k.$bzId||k]}),S={...Q,$thing:g.$thing,$thingType:"relation",$op:b(),...T,$bzId:g.$bzId,[Qe]:"roleField"};$(S);return}if(g.$op==="match"||g.$op==="update"&&Object.keys(R).length>0){let b=0;Object.entries(R).forEach(([F,T])=>{let S=isArray(T)?T:[T],O=k=>k==="create"||k==="replace"?"link":k;S.forEach(k=>{if(!k)return;let P=O(k.$op);if(P==="replace")throw new Error("Not supported yet: replace on roleFields");if(P==="unlink"&&b>0)throw b+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let J={...Q,$thing:g.$thing,$thingType:"relation",$op:P==="delete"?"unlink":P,[F]:k.$bzId,$bzId:g.$bzId,[Qe]:"roleField"};$(J);});});}}}}}),[d,a]},[i,o]=r(e),n=i.reduce((c,d)=>{if(!d.$bzId)return [...c,d];let a=c.findIndex(p=>p.$bzId===d.$bzId);if(a===-1)return [...c,d];if(c[a].$op==="create"&&d.$op==="match")return c;if(c[a].$op==="match"&&(d.$op==="create"||d.$op==="match"))return [...c.slice(0,a),d,...c.slice(a+1)];throw new Error(`[Wrong format] Wrong operation combination for $tempId "${d.$tempId}". Existing: ${c[a].$op}. Current: ${d.$op}`)},[]),l=o.reduce((c,d)=>{let a=c.find(p=>(p.$id&&p.$id===d.$id||p.$bzId&&p.$bzId===d.$bzId)&&p.$thing===d.$thing&&p.$op===d.$op);if(a){let p={...a};return Object.keys(d).forEach($=>{if(typeof $=="symbol"||$.startsWith("$"))return;let y=a[$],m=d[$];Array.isArray(y)&&Array.isArray(m)?p[$]=Array.from(new Set([...y,...m])):!Array.isArray(y)&&Array.isArray(m)?y!==void 0?p[$]=Array.from(new Set([y,...m])):p[$]=m:Array.isArray(y)&&!Array.isArray(m)?m!==void 0&&(p[$]=Array.from(new Set([...y,m]))):y!==null&&m!==null&&y!==void 0&&m!==void 0?p[$]=Array.from(new Set([y,m])):y==null&&(p[$]=m);}),[...c.filter($=>!(($.$id&&$.$id===d.$id||$.$bzId&&$.$bzId===d.$bzId)&&$.$thing===d.$thing&&$.$op===d.$op)),p]}return [...c,d]},[]);n.forEach(c=>{if((c.$thingType==="relation"||"relation"in c)&&l.filter(d=>d.$bzId===c.$bzId||d.$tempId&&d.$tempId===c.$tempId).length===0){if(c.$op==="delete"||c.$op==="match"||c.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(yr(c))}`)}});let s=[...n,...l],u=new Set(s.filter(c=>c.$tempId).map(c=>c.$tempId)),f=Array.from(u).filter(c=>!s.some(d=>d.$tempId===c&&d.$op==="create"));if(f.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${f.join(", ")}`);return {mergedThings:n,mergedEdges:l}};var $t=e=>{if(isDate(e))return {type:"datetime",value:e.toISOString().replace("Z","")};if(typeof e=="string")return {type:"string",value:`"${e}"`};if(typeof e=="number")return e%1!==0?{type:"double",value:e}:{type:"long",value:e};if(typeof e=="boolean")return {type:"boolean",value:e};throw new Error(`Unsupported type ${typeof e}`)};var wr=async(e,t,r)=>{let i=a=>{let p=a.$op,h=`$${a.$bzId}`,$=x(r,a),{idFields:y,defaultDBConnector:m}=$,B=m?.path||a.$thing,M=a.$id,g=y?.[0],L=listify(a,(R,E)=>{if(R.startsWith("$")||R.startsWith("%")||R===g||E===void 0||E===null)return "";let Q=$.dataFields?.find(T=>T.path===R);if(!Q?.path)return "";let F=Q.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(Q.contentType))return `has ${F} '${E}'`;if(["NUMBER","BOOLEAN"].includes(Q.contentType))return `has ${F} ${E}`;if(Q.contentType==="DATE"){if(Number.isNaN(E.valueOf()))throw new Error("Invalid format, Nan Date");return E instanceof Date?`has ${F} ${E.toISOString().replace("Z","")}`:`has ${F} ${new Date(E).toISOString().replace("Z","")}`}if(Q.contentType==="FLEX"){let T=`bza${nanoid()}`,S=isArray(E)?E.map(O=>$t(O)):$t(E);if(Array.isArray(S))throw new Error("Array in FLEX fields not supported yet");return `has ${F} $${T}; $${T} '${T}' isa ${F}, has ${S.type}Attribute ${S.value}`}throw new Error(`Unsupported contentType ${Q.contentType}`)}).filter(R=>R),D=`${h}-atts`,A=listify(a,R=>{if(R.startsWith("$")||R.startsWith("%")||R===g)return "";let E=$.dataFields?.find(F=>F.path===R);if(!E?.path)return "";let b=E.dbPath;return `{${D} isa ${b};}`}).filter(R=>R),C=isArray(M)?`like '${M.join("|")}'`:`'${M}'`,j=M?[`has ${g} ${C}`]:[],N=[...j,...L].filter(R=>R).join(","),se=()=>{if(p==="delete"||p==="unlink"||p==="match")return `${h} isa ${[B,...j].filter(R=>R).join(",")};`;if(p==="update"){if(!A.length)throw new Error("update without attributes");return `${h} isa ${[B,...j].filter(R=>R).join(",")}, has ${D};
37
+ ${A.join(" or ")};`}return ""},K=()=>p==="update"||p==="link"||p==="match"?`${h} isa ${[B,...j].filter(R=>R).join(",")};`:"";if(He(a))return {op:p,deletionMatch:se(),insertionMatch:K(),insertion:p==="create"?`${h} isa ${[B,N].filter(R=>R).join(",")};`:p==="update"&&L.length?`${h} ${L.join(",")};`:"",deletion:p==="delete"?`${h} isa ${B};`:p==="update"&&A.length?`${h} has ${D};`:""};throw new Error("in attributes")},o=a=>{let p=a.$op,h=x(r,a),$=`$${a.$bzId}`,y=a.$id,m=h.defaultDBConnector?.path||a.$thing,B="roles"in h?listify(h.roles,E=>E):[],M="roles"in h?mapEntries(h.roles,(E,Q)=>[E,Q.dbConnector?.path||E]):{},g=listify(a,(E,Q)=>{if(!B.includes(E))return null;if(!("roles"in h))throw new Error("This should have roles! ");let b=M[E];return Array.isArray(Q)?Q.map(F=>({path:b,id:F})):{path:b,id:Q}}).filter(E=>E).flat(),L=g.map(E=>{if(!E?.path)throw new Error("Object without path");return `${E.path}: $${E.id}`}),D=g.length>0?`( ${L.join(" , ")} )`:"",A=a[Qe];if(!A)throw new Error("[internal error] Symbol edgeType not defined");let C=D?`${$} ${D} ${A==="linkField"||p==="delete"||p==="unlink"?`isa ${m}`:""}`:"",j=`${$} ${A==="linkField"||p==="delete"?`isa ${m}`:""}`,N=()=>C?p==="link"?`${C};`:p==="create"?`${C}, has id '${y}';`:"":"",se=()=>C&&p==="match"?`${C};`:"",K=()=>C?p==="delete"?`${C};`:p==="match"?`${C};`:"":"",R=()=>C?p==="delete"?`${j};`:p==="unlink"?`${$} ${D};`:"":"";return {deletionMatch:K(),insertionMatch:se(),deletion:R(),insertion:N(),op:""}},n=(a,p)=>{let h=p==="edges"?o:i;if(Array.isArray(a))return a.map(g=>{let{preDeletionBatch:L,insertionMatch:D,deletionMatch:A,insertion:C,deletion:j}=h(g);return shake({preDeletionBatch:L,insertionMatch:D,deletionMatch:A,insertion:C,deletion:j},N=>!N)}).filter(g=>g);let{preDeletionBatch:$,insertionMatch:y,deletionMatch:m,insertion:B,deletion:M}=h(a);return shake({preDeletionBatch:$,insertionMatch:y,deletionMatch:m,insertion:B,deletion:M},g=>!g)},l=n(e),s=Array.isArray(l)?l:[l],u=n(t,"edges"),f=Array.isArray(u)?u:[u],c=[...s,...f];return shake({insertionMatches:c.map(a=>a.insertionMatch).join(" ").trim(),deletionMatches:c.map(a=>a.deletionMatch).join(" ").trim(),insertions:c.map(a=>a.insertion).join(" ").trim(),deletions:c.map(a=>a.deletion).join(" ").trim()},a=>!a)};function G(e){return {enumerable:!0,value:e}}function Mr(e){return {enumerable:!0,writable:!0,value:e}}var Ce={},oi=()=>!0,Qr=()=>({}),Lr=e=>e,si=(e,t,r,i)=>e.apply(r,i)&&t.apply(r,i),ai=(e,t,r,[i,o])=>t.call(r,e.call(r,i,o),o),Fe=(e,t)=>Object.freeze(Object.create(e,t));function Tr(e,t,r){return e.reduce((i,o)=>function(...n){return r(i,o,this,n)},t)}function Sr(e){return Fe(this,{fn:G(e)})}var kr={},V=Sr.bind(kr);var Dr={},yt=Sr.bind(Dr);function Xe(e,t){return t.filter(r=>e.isPrototypeOf(r))}function Rr(e,t,...r){let i=Tr(Xe(Dr,r).map(n=>n.fn),oi,si),o=Tr(Xe(kr,r).map(n=>n.fn),Lr,ai);return Fe(this,{from:G(e),to:G(t),guards:G(i),reducers:G(o)})}var Ar={},Ir={},H=Rr.bind(Ar);Rr.bind(Ir,null);function li(e,t,r){return Bt(t,e,r,this.immediates)||e}function Cr(e){let t=new Map;for(let r of e)t.has(r.from)||t.set(r.from,[]),t.get(r.from).push(r);return t}var ci={enter:Lr};function he(...e){let t=Xe(Ar,e),r=Xe(Ir,e),i={final:G(e.length===0),transitions:G(Cr(t))};return r.length&&(i.immediates=G(r),i.enter=G(li)),Fe(ci,i)}var di={enter(e,t,r){let i=this.fn.call(t,t.context,r);return gt.isPrototypeOf(i)?Fe(Or,{machine:G(i),transitions:G(this.transitions)}).enter(e,t,r):(i.then(o=>t.send({type:"done",data:o})).catch(o=>t.send({type:"error",error:o})),e)}},Or={enter(e,t,r){if(t.child=me(this.machine,i=>{t.onChange(i),t.child==i&&i.machine.state.value.final&&(delete t.child,t.send({type:"done",data:i.context}));},t.context,r),t.child.machine.state.value.final){let i=t.child.context;return delete t.child,Bt(t,e,{type:"done",data:i},this.transitions.get("done"))}return e}};function Y(e,...t){let r=G(Cr(t));return gt.isPrototypeOf(e)?Fe(Or,{machine:G(e),transitions:r}):Fe(di,{fn:G(e),transitions:r})}var gt={get state(){return {name:this.current,value:this.states[this.current]}}};function be(e,t,r=Qr){return typeof e!="string"&&(r=t||Qr,t=e,e=Object.keys(t)[0]),Ce._create&&Ce._create(e,t),Fe(gt,{context:G(r),current:G(e),states:G(t)})}function Bt(e,t,r,i){let{context:o}=e;for(let{to:n,guards:l,reducers:s}of i)if(l(o,r)){e.context=s.call(e,o,r);let u=t.original||t,f=Fe(u,{current:G(n),original:{value:u}});Ce._onEnter&&Ce._onEnter(t,n,e.context,o,r);let c=f.state.value;return e.machine=f,e.onChange(e),c.enter(f,e,r)}}function hi(e,t){let r=t.type||t,{machine:i}=e,{value:o,name:n}=i.state;return o.transitions.has(r)?Bt(e,i,t,o.transitions.get(r))||i:(Ce._send&&Ce._send(r,n),i)}var ui={send(e){hi(this,e);}};function me(e,t,r,i){let o=Object.create(ui,{machine:Mr(e),context:Mr(e.context(r,i)),onChange:G(t)});return o.send=o.send.bind(o),o.machine=o.machine.state.value.enter(o.machine,o,i),o}var jr=(e,t)=>{if(!t)return;let r=fi(t);return $i(r,e.query)},fi=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),$i=(e,t)=>produce(e,r=>traverse(r,({value:i})=>{if(isObject(i)){let o=i;Object.keys(o).forEach(n=>{(o[n]===void 0||o[n]===null||isArray(o[n])&&o[n].length===0)&&(t?.returnNulls?o[n]=null:delete o[n]),o[n]===void 0&&delete o[n];}),Object.getOwnPropertySymbols(o).forEach(n=>{delete o[n];}),t?.noMetadata===!0&&Object.keys(o).forEach(n=>{n.startsWith("$")&&delete o[n];});}}));var Wr=(e,t)=>{for(let o of e)if(!("$entity"in o)&&!("$relation"in o)&&(!("$thing"in o)||!("$thingType"in o)))throw new Error("No entity specified in query");let r=Array.isArray(e)?e:[e];return produce(r,o=>traverse(o,n=>{let{value:l,meta:s}=n,u=l;if(isObject(u)){if(u.$id){if(s.nodePath?.includes(".$filter"))return;let f=u.$entity||u.$relation?u:{[`$${u.$thingType}`]:u.$thing},c=x(t,f);if(!c?.name)throw new Error(`Schema not found for ${u.$thing}`);if(u.$path=c.name,Array.isArray(u.$id)||(u.$filterByUnique=!0),c?.idFields?.length!==1)throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in u||"$relation"in u||"$thing"in u){let f=x(t,u);if(!f?.name)throw new Error(`Schema not found for ${u.$thing}`);u.$path=f.name;}if(u.$entity?(u.$thing=u.$entity,u.$thingType="entity",delete u.$entity):u.$relation&&(u.$thing=u.$relation,u.$thingType="relation",delete u.$relation),isObject(u)&&"$thing"in u&&u.$thing){let f=u.$entity||u.$relation?u:{[`$${u.$thingType}`]:u.$thing};u[ae]=s.nodePath;let c=x(t,f);if(u.$filter&&(u.$filterByUnique=wt(u.$filter,c),u.$filter=Oe(u.$filter,u.$thing,t)),u.$fields){u.$fields.some(p=>c?.idFields?.includes(p?.$path||p))||(u.$fields=[...u.$fields,...Array.isArray(c.idFields)?c.idFields:[]],u.$idNotIncluded=!0);let a=u.$fields?.flatMap(p=>{let h=Nr(p,c,t);return Array.isArray(h)?h:[h]}).filter(Boolean);u.$fields=a;}else {let a=bt(c)?.flatMap(p=>{let h=Nr(p,c,t);return Array.isArray(h)?h:[h]}).filter(Boolean);u.$fields=a;}u.$excludedFields&&(u.$fields=u.$fields.filter(d=>ve(c,d)?!0:!u.$excludedFields.includes(d.$path)));}}}))},bt=e=>{let t=e.dataFields?.map(n=>n.path)||[],r=e.linkFields?.map(n=>n.path)||[],i=Object.keys(e.roles||{})||[];return [...t,...r,...i]},wt=(e,t)=>Object.keys(e||{}).some(i=>{if(!Array.isArray(e[i])){let o=t.idFields?.includes(i),n=t.dataFields?.some(s=>(s.dbPath===i||s.path===i)&&s?.validations?.unique),l=i==="$id"&&!Array.isArray(e[i]);return o||n||l}return !1}),ve=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),gi=e=>{let{field:t,fieldStr:r,$justId:i,dbPath:o,isVirtual:n,fieldSchema:l}=e;return {$path:r,$dbPath:o,$thingType:"attribute",$as:t.$as||r,$var:r,$fieldType:"data",$justId:i,$id:t.$id,$isVirtual:n,[le]:l}},Bi=e=>{let{field:t,fieldStr:r,linkField:i,$justId:o,dbPath:n,schema:l,fieldSchema:s}=e,{target:u,oppositeLinkFieldsPlayedBy:f}=i;return f.map(c=>{let d=u==="role"?c.thingType:"relation",a=u==="role"?c.thing:i.relation,p={[`$${d}`]:a},h=x(l,p),$=t?.$fields?.filter(B=>ve(h,B)).length===0,y=[];if(typeof t!="string")if(t.$fields)if($){let B=h.idFields||[];y=[...t.$fields,...B];}else y=t.$fields;else y=bt(h);else y=["id"];t.$excludedFields&&(y=y.filter(B=>ve(h,B)?!0:!t.$excludedFields.includes(B.$path)));let m=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...Oe(t.$filter,a,l)}:void 0;return {$thingType:d,$plays:i.plays,$playedBy:c,$path:c.path,$dbPath:n,$as:t.$as||r,$var:r,$thing:a,$fields:y,$excludedFields:t.$excludedFields,$fieldType:"link",$target:u,$intermediary:c.relation,$justId:o,$id:t.$id,$filter:m,$idNotIncluded:$,$filterByUnique:wt(t.$filter,h),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[le]:s}})},Ei=e=>{let{field:t,fieldStr:r,roleField:i,$justId:o,dbPath:n,schema:l,fieldSchema:s}=e;return i.playedBy.map(u=>{let{thing:f,thingType:c,relation:d}=u,a={[`$${c}`]:f},p=x(l,a),h=t?.$fields?.filter(m=>p?.idFields?.includes(m)||p?.idFields?.includes(m.$path)).length===0,$=[];if(typeof t!="string")if(t.$fields)if(h){let m=p.idFields||[];$=[...t.$fields,...m];}else $=t.$fields;else $=bt(p);else $=["id"];t.$excludedFields&&($=$.filter(m=>ve(p,m)?!0:!t.$excludedFields.includes(m.$path)));let y=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...Oe(t.$filter,f,l)}:void 0;return {$thingType:c,$path:r,$dbPath:n,$as:t.$as||r,$var:r,$thing:f,$fields:$,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:d,$justId:o,$id:t.$id,$filter:y,$idNotIncluded:h,$filterByUnique:wt(t.$filter,p),$playedBy:u,$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[le]:s}})},Nr=(e,t,r)=>{let i=typeof e=="string"?e:e.$path,o=typeof e=="string",n=t.dataFields?.find(u=>u.path===i),l=t.linkFields?.find(u=>u.path===i),s=t.roles?.[i];if(n){let u=!!n.isVirtual&&!!n.default;return gi({field:e,fieldStr:i,$justId:o,dbPath:n.dbPath,isVirtual:u,fieldSchema:n})}else {if(l)return Bi({field:e,fieldStr:i,linkField:l,$justId:o,dbPath:l.path,schema:r,fieldSchema:l});if(s)return Ei({field:e,fieldStr:i,roleField:s,$justId:o,dbPath:i,schema:r,fieldSchema:s})}return null},Oe=(e,t,r)=>{if(e==null)return e;let i=isArray(e),n=(i?e:[e]).map(l=>Object.keys(l).reduce((f,c)=>{let d=l[c],a=isArray(d)?d:[d];if(c.startsWith("$"))["$id","$thing"].includes(c)?f[c]=d:f[c]=Oe(d,t,r);else {let p=t in r.entities?r.entities[t]:r.relations[t],[h,$]=_e(p,c);if(h==="dataField")f[c]=d;else if(h==="linkField"||h==="roleField"){let y=$,[m]=y.$things;return a.every(B=>typeof B=="string")?f[c]={$id:a,$thing:m}:a.every(B=>isObject(B))&&(f[c]=isArray(d)?{$or:Oe(d,m,r)}:Oe(d,m,r)),f}else throw new Error(`Field ${c} not found in schema of ${t}`)}return f},{}));return i?n.length===1?n[0]:{$or:n}:n[0]};var zr=async(e,t,r)=>r?(n=>produce(n,l=>traverse(l,({value:s})=>{if(isObject(s)){let u=s;if(!u.$thing)return;if(u.$thing){let f=x(e,u),{virtualFields:c}=f,d=u[ae];if(!d)throw new Error("[Internal] QueryPath is missing");let a=getNodeByPath(t,d),p=a.$fields.map($=>$.$path),h=a.$excludedFields;c.forEach($=>{if(h?.includes($)||p.length>0&&!p.includes($))return;let y=f.dataFields?.find(m=>m.path===$);if(y?.default){let m=Ae({currentThing:u,fieldSchema:y,mandatoryDependencies:!0});u[$]=m;}else if(u[$]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${$}`)}),h&&h.forEach($=>{if(typeof $!="string")throw new Error("[Internal] ExcludedField is not a string");delete u[$];});}}})))(r):void 0;var _r=e=>e.replace(/`/g,""),Qi=[" ","-","+","*","/","=","!","@","#","$","%","^","&","(",")","[","]","{","}","|","\\",";",":","'",'"',",","<",">",".","?","~","`"],Vr=e=>Qi.some(t=>e.includes(t))?`\u27E8\`${e}\`\u27E9`:e;var Kr=e=>{let{queries:t,schema:r}=e;return t.map(i=>Li({query:i,schema:r}))},Li=e=>{let{query:t,schema:r}=e,{$thing:i,$fields:o,$filter:n,$offset:l,$limit:s,$sort:u}=t;if(o.length===0)return null;let f=[];f.push("SELECT");let c=Mt({parentQuery:t,queries:o,level:1,schema:r});c&&f.push(c);let d=r.entities[i]||r.relations[i];if(!d)throw new Error(`Schema for ${i} not found`);let p=(d.subTypes?[i,...d.subTypes]:[i]).map(h=>Vr(h));if(t.$id)if(typeof t.$id=="string")f.push(`FROM ${p.map(h=>`${h}:\`${t.$id}\``).join(",")}`);else if(isArray(t.$id)){let h=t.$id,$=p.flatMap(y=>h?.map(m=>`${y}:\`${m}\``));f.push(`FROM ${$.join(",")}`);}else throw new Error("Invalid $id");else f.push(`FROM ${p.join(",")}`);if(n){let h=ye(n,i,r),$=Se(h);f.push(`WHERE ${$}`);}return u&&f.push(Ur(u)),typeof s=="number"&&f.push(`LIMIT ${s}`),typeof l=="number"&&f.push(`START ${l}`),f.join(`
38
+ `)},Mt=e=>{let{queries:t,schema:r,level:i,parentQuery:o}=e,n=[],l=o[ae];return n.push(w(`"${l}" as \`$$queryPath\``,i)),n.push(w("meta::id(id) as `$id`",i)),n.push(w("meta::tb(id) as `$thing`",i)),t.forEach(s=>{let u=Si({query:s,level:i,schema:r});u&&n.push(u);}),n.length===0?null:n.join(`,
39
+ `)},Si=e=>{let{query:t,schema:r,level:i}=e;return t.$fieldType==="data"?ki({query:t,level:i}):t.$fieldType==="link"?Di({query:t,level:i,schema:r}):t.$fieldType==="role"?Ri({query:t,level:i,schema:r}):null},ki=e=>{let{query:t,level:r}=e;return t.$isVirtual?null:t.$path==="id"?w(`meta::id(${t.$path}) AS ${t.$as}`,r):t.$path===t.$as?w(`\`${t.$path}\``,r):w(`\`${t.$path}\` AS \`${t.$as}\``,r)},Di=e=>{let{query:t,schema:r,level:i}=e,{$fields:o,$filter:n,$offset:l,$limit:s,$sort:u}=t;if(o.length===0)return null;let f=[];f.push(w("(",i));let c=i+1;f.push(w("SELECT",c));let d=Mt({parentQuery:t,queries:o,level:c+1,schema:r});d&&f.push(d);let a=t[le][Te].queryPath;if(f.push(w(`FROM ${a}`,c)),n){let p=ye(n,t.$thing,r),h=Se(p);f.push(`WHERE ${h}`);}return u&&f.push(w(Ur(u),c)),typeof s=="number"&&f.push(w(`LIMIT ${s}`,c)),typeof l=="number"&&f.push(w(`START ${l}`,c)),f.push(w(`) AS \`${t.$as}\``,i)),f.join(`
40
+ `)},Ri=e=>{let{query:t,schema:r,level:i}=e;if(t.$fields.length===0)return null;let o=[];o.push(w("(",i));let n=i+1;o.push(w("SELECT",n));let l=n+1,s=Mt({parentQuery:t,queries:t.$fields,level:l,schema:r});s&&o.push(s);let u=t[le][Te].queryPath;if(o.push(w(`FROM ${u}`,n)),t.$filter){let f=ye(t.$filter,t.$playedBy.thing,r),c=Se(f);o.push(`WHERE ${c}`);}return o.push(w(`) AS \`${t.$as}\``,i)),o.join(`
41
+ `)},ye=(e,t,r)=>{if(e==null)return e;let i=isArray(e),n=(i?e:[e]).map(l=>{let u=Object.keys(l).reduce((f,c)=>{let d=l[c];if(c.startsWith("$"))return c==="$not"?{...f,$not:void 0,"$!":ye(d,t,r)}:c==="$or"?{...f,$or:void 0,$OR:ye(d,t,r)}:c==="$and"?{...f,$and:void 0,$AND:ye(d,t,r)}:c==="$eq"?{...f,$nor:void 0,"$=":ye(d,t,r)}:c==="$id"?{...f,$id:void 0,"meta::id(id)":{$IN:isArray(d)?d:[d]}}:c==="$thing"?f:{...f,[c]:ye(d,t,r)};let a=t in r.entities?r.entities[t]:r.relations[t],[p,h]=_e(a,c);if(p==="dataField"){if(a.idFields.length>1)throw new Error("Multiple id fields not supported");return c===a.idFields[0]?{...f,"meta::id(id)":{$IN:isArray(d)?d:[d]}}:{...f,[c]:d}}if(p==="linkField"||p==="roleField"){let $=h,[y]=$.$things,m=$[Te].queryPath;return {...f,[m]:ye(d,y,r)}}throw new Error(`Field ${c} not found in schema, Defined in $filter`)},{});return shake(u)});return i?n:n[0]},Se=e=>{if(e==null)return "";let t=Object.entries(e),r=[];return t.forEach(([i,o])=>{if(["$OR","$AND","$!"].includes(i)){let n=i.replace("$",""),l=Array.isArray(o)?o.map(s=>Se(s)):[Se(o)];n==="!"?r.push(`!(${l.join(` ${n} `)})`):r.push(`(${l.join(` ${n} `)})`);return}if(isObject(o))if(i.includes("<-")||i.includes("->")){let n=Se(o);r.push(`${i}[WHERE ${n}]`);}else {if(i.startsWith("$"))throw new Error(`Invalid key ${i}`);if(Object.keys.length===1&&Object.keys(o)[0].startsWith("$")){let[n]=Object.keys(o),l=o[n];if(isArray(l))r.push(`${i} ${n.replace("$","")} [${l.map(s=>`'${s}'`).join(", ")}]`);else if(isObject(l)){let s=Se(l);r.push(`${i} ${n.replace("$","")} ${s}`);}else r.push(`${i} ${n.replace("$","")} '${l}'`);}else throw new Error(`Invalid key ${i}`)}else if(Array.isArray(o)){let n=i.startsWith("$")?i.replace("$",""):"IN";r.push(`${i} ${n} [${o.map(l=>`'${l}'`).join(", ")}]`);}else {let n=i.startsWith("$")?i.replace("$",""):"=";r.push(`${i} ${n} '${o}'`);}}),r.join(" AND ")},Ur=e=>`ORDER BY ${e.map(r=>{if(typeof r=="string")return r;let{field:i,desc:o}=r;return `${i}${o?" DESC":" ASC"}`}).join(", ")}`;var Jr=async e=>{let{client:t,queries:r}=e,i=`
42
+ BEGIN TRANSACTION;
43
+ ${r.join(";")};
44
+ COMMIT TRANSACTION;
45
+ `;return await t.query(i)};var Zr=e=>{let{res:t,queries:r}=e;return t.map((o,n)=>Yr(r[n],o))},Yr=(e,t)=>{if(isArray(t)){if(t.length===0)return null;if(e.$filterByUnique){if(t.length>1)throw new Error("Multiple results found for unique query");return Tt(e,t[0])}if(t.length>=1)return t.map(r=>Tt(e,r))}else throw new Error("res is unexpectedly not an array")},Tt=(e,t)=>{let r={[ae]:t.$$queryPath,$id:t.$id,$thing:_r(t.$thing),$thingType:e.$thingType};return e.$fields.forEach(i=>{let o=i.$as,n=t[o];i.$path==="id"&&e.$idNotIncluded||(r[o]=Ai(i,n));}),r},Ai=(e,t)=>t==null||isArray(t)&&t.length===0?null:e.$fieldType==="data"?(e[le].cardinality==="ONE"&&isArray(t)&&t[0],t??null):e.$justId?e.$filterByUnique||e[le].cardinality==="ONE"?t[0]?.id??null:t?.map(r=>r.id)??[]:e.$filterByUnique||e[le].cardinality==="ONE"?Tt(e,t[0]):Yr(e,t);var Lt=H("error","error",V((e,t)=>({...e,error:t.error}))),Ii=be("build",{build:Y(async e=>Kr({queries:e.bql.queries,schema:e.schema}),H("done","run",V((e,t)=>({...e,surql:{...e.surql,queries:t.data}}))),Lt),run:Y(async e=>Jr({client:e.client,queries:oe(e.surql.queries)}),H("done","parse",V((e,t)=>({...e,surql:{...e.surql,res:t.data}}))),Lt),parse:Y(async e=>Zr({res:oe(e.surql.res),queries:e.bql.queries,schema:e.schema,config:e.config}),H("done","success",V((e,t)=>({...e,bql:{...e.bql,res:t.data}}))),Lt),success:he(),error:he()},e=>e),Ci=async e=>new Promise((t,r)=>{me(Ii,i=>{i.machine.state.name==="success"&&t(i.context.bql.res),i.machine.state.name==="error"&&r(i.context.error);},e);}),Xr=async(e,t,r,i)=>Ci({bql:{queries:e},surql:{},schema:t,config:r,client:i,error:null});var St="___",Gr=async e=>{let{queries:t,schema:r}=e;return t.map(i=>Pi({query:i,schema:r}))},Pi=e=>{let{query:t,schema:r}=e,{$path:i,$thing:o,$filter:n,$fields:l,$sort:s,$offset:u,$limit:f,$id:c}=t;if(!i)throw new Error("Path is not defined");let d=[],a=t[ae];if(d.push("match"),d.push(`$${i} isa ${o};`),n||c){let $=Ve(r,t),y={...n,...c?{[$]:c}:{}},m=At({$filter:y,$var:i,$thing:o,schema:r,depth:0});d.push(`
46
+ ${m}`);}let p=It({schema:r,$thing:o,$var:i,$sort:s,depth:0});p&&d.push(p.match);let h=`M_${v4()}`;if(d.push(`?queryPath${h} = "${a}";`),d.push("fetch"),d.push(`?queryPath${h} as "queryPath";`),l){let $=l.filter(B=>B.$fieldType==="data");$&&$.length>0&&d.push(...kt($,i,0));let y=l.filter(B=>B.$fieldType==="link");y&&y.length>0&&d.push(...Rt(y,i,i,0,r));let m=l.filter(B=>B.$fieldType==="role");m&&m.length>0&&d.push(...Dt(m,i,i,0,r));}return p&&d.push(p.sort),typeof u=="number"&&d.push(`
47
+ offset ${u};`),typeof f=="number"&&d.push(`
48
+ limit ${f};`),d.join(`
49
+ `)},kt=(e,t,r)=>{let i=[],o=[],n=[];for(let c=0;c<e.length;c++)e[c].$isVirtual||i.push(e[c].$dbPath),e[c][le].contentType==="FLEX"&&n.push({path:e[c][le].dbPath}),o.push(`{${e[c].$dbPath}:${e[c].$as}}`);let l=i.join(", "),u=`$metadata:{as:[${o.join(",")}]}`,f=[w(`$${t} as "${t}.${u}.$dataFields": ${l};`,r)];return n.length>0&&n.forEach(c=>{f.push(w(`"${c.path}.$multiVal": {match $${t} has ${c.path} $${c.path}; fetch $${c.path}: attribute;};`,r));}),f},Dt=(e,t,r,i,o)=>{let n=i+1,l=[];for(let s of e){let{$fields:u,$as:f,$justId:c,$idNotIncluded:d,$filterByUnique:a,$thing:p,$sort:h,$offset:$,$limit:y}=s,m=s[ae],B=`$metadata:{as:${f},justId:${c?"T":"F"},idNotIncluded:${d},filterByUnique:${a}}`;l.push(w(`"${r}.${B}.${s.$var}": {`,i)),l.push(w("match",n));let M=`${t}${St}${s.$var}`;if(l.push(w(`$${M} isa ${s.$thing};`,n)),l.push(w(`$${t} (${s.$var}: $${t}${St}${s.$var}) isa ${s.$intermediary};`,n)),s.$filter||s.$id){let L=Ve(o,s),D=s.$id?{[L]:s.$id}:{},A={...s.$filter,...D};l.push(At({$filter:A,$var:M,$thing:s.$thing,schema:o,depth:n}));}let g=It({schema:o,$thing:p,$var:M,$sort:h,depth:n});if(g&&l.push(g.match),u){let L=`M_${v4()}`;l.push(w(`
50
+ ?queryPath${L} = "${m}";`,n)),l.push(w("fetch",n)),l.push(w(`?queryPath${L} as "queryPath";`,n));let D=u?.filter(j=>j.$fieldType==="data");D&&D.length>0&&l.push(...kt(D,M,n));let A=u?.filter(j=>j.$fieldType==="link");A&&A.length>0&&l.push(...Rt(A,M,`${t}.${s.$var}`,n,o));let C=u?.filter(j=>j.$fieldType==="role");C&&C.length>0&&l.push(...Dt(C,M,`${t}.${s.$var}`,n,o));}g&&l.push(g.sort),typeof $=="number"&&l.push(w(`offset ${$};`,n)),typeof y=="number"&&l.push(w(`limit ${y};`,n)),l.push(w("};",i));}return l},Rt=(e,t,r,i,o)=>{let n=i+1,l=[];for(let s of e){let{$fields:u,$as:f,$justId:c,$idNotIncluded:d,$filterByUnique:a,$playedBy:p,$thing:h,$sort:$,$offset:y,$limit:m}=s,B=s[ae],M=`$metadata:{as:${f},justId:${c?"T":"F"},idNotIncluded:${d},filterByUnique:${a}}`;l.push(w(`"${r}.${M}.${s.$var}": {`,i)),l.push(w("match",n));let g=`${t}${St}${s.$var}`;if(l.push(w(`$${g} isa ${s.$thing};`,n)),s.$filter||s.$id){let D=Ve(o,s),A=s.$id?{[D]:s.$id}:{},C={...s.$filter,...A};l.push(At({$filter:C,$var:g,$thing:s.$thing,schema:o,depth:n}));}let L=It({schema:o,$thing:h,$var:g,$sort:$,depth:n});if(L&&l.push(L.match),s.$target==="role"?l.push(w(`$${t}_intermediary (${s.$plays}: $${t}, ${p.plays}: $${g}) isa ${s.$intermediary};`,n)):l.push(w(`$${g} (${s.$plays}: $${t});`,n)),u){let D=`M_${v4()}`;l.push(w(`?queryPath${D} = "${B}";`,n)),l.push(w("fetch",n)),l.push(w(`?queryPath${D} as "queryPath";`,n));let A=u?.filter(N=>N.$fieldType==="data");A&&A.length>0&&l.push(...kt(A,g,n));let C=u?.filter(N=>N.$fieldType==="link");C&&C.length>0&&l.push(...Rt(C,g,`${t}.${s.$var}`,n,o));let j=u?.filter(N=>N.$fieldType==="role");j&&j.length>0&&l.push(...Dt(j,g,`${t}.${s.$var}`,n,o));}L&&l.push(L.sort),typeof y=="number"&&l.push(w(`offset ${y};`,n)),typeof m=="number"&&l.push(w(`limit ${m};`,n)),l.push(w("};",i));}return l},xi=(e,t)=>{let r={};if(t.dataFields?.forEach(l=>{l.path!==l.dbPath&&(r[l.path]=l.dbPath);}),Object.keys(r).length===0)return e;let{$not:i,...o}=e,n=vr(o,r);return i&&(n.$not=vr(i,r)),n},vr=(e,t)=>{let r={};return Object.entries(e).forEach(([i,o])=>{let n=t[i]||i;r[n]=o;}),r},At=e=>{let{$filter:t,$var:r,$thing:i,schema:o,depth:n}=e,l=xi(t,v(o,i)),{$not:s,...u}=l,f=v(o,i),c=[];return Object.entries(s||{}).forEach(([d,a])=>{if(d.startsWith("$"))return;if(f.dataFields?.find($=>$.dbPath===d)){a===null?c.push(w(`$${r} has ${d} $${d}_${v4()};`,n)):Array.isArray(a)?a.forEach($=>{c.push(w(`not { $${r} has ${d} ${ne($)}; };`,n));}):c.push(w(`not { $${r} has ${d} ${ne(a)}; };`,n));return}let h=f.linkFields?.find($=>$.path===d);if(h){let[$]=h.oppositeLinkFieldsPlayedBy,m=v(o,$.thing).idFields?.[0];if(!m)throw new Error(`"${$.thing}" does not have an id field`);if(h.target==="relation")a===null?c.push(w(`(${h.plays}: $${r}) isa ${h.relation};`,n)):Array.isArray(a)?a.forEach(B=>{c.push(w(`not { (${h.plays}: $${r}) isa ${h.relation}, has ${m} ${ne(B)}; };`,n));}):c.push(w(`not { (${h.plays}: $${r}) isa ${h.relation}, has ${m} ${ne(a)}; };`,n));else {let B=`${$.thing}_${v4()}`;a===null?c.push(w(`$${B} isa ${$.thing}; (${h.plays}: $${r}, ${$.plays}: $${B}) isa ${h.relation};`,n)):Array.isArray(a)?a.forEach(M=>{c.push(w(`not { $${B} isa ${$.thing}, has ${m} ${ne(M)}; (${h.plays}: $${r}, ${$.plays}: $${B}) isa ${h.relation}; };`,n));}):c.push(w(`not { $${B} isa ${$.thing}, has ${m} ${ne(a)}; (${h.plays}: $${r}, ${$.plays}: $${B}) isa ${h.relation}; };`,n));}return}if(f.thingType==="relation"){let $=f.roles[d];if($){let[y]=$.playedBy||[],B=v(o,y.thing).idFields?.[0];if(!B)throw new Error(`"${y.thing}" does not have an id field`);let M=`${y.thing}_${v4()}`,g=v4(),L=`${r}_${g}`;a===null?(c.push(w(`$${L} isa ${i};`,n)),c.push(w(`$${L} (${y.plays}: ${M});`,n)),c.push(w(`$${r} is $${L};`,n))):Array.isArray(a)?a.forEach(D=>{c.push(w(`$${L} isa ${i};`,n)),c.push(w(`not { $${M} isa ${y.thing}, has ${B} ${ne(D)}; $${L} (${y.plays}: $${M}); };`,n)),c.push(w(`$${r} is $${L};`,n));}):(c.push(w(`$${L} isa ${i};`,n)),c.push(w(`not { $${M} isa ${y.thing}, has ${B} ${ne(a)}; $${L} (${y.plays}: $${M}); };`,n)),c.push(w(`$${r} is $${L};`,n)));return}}}),Object.entries(u).forEach(([d,a])=>{if(d.startsWith("$"))return;if(f.dataFields?.find($=>$.dbPath===d)){if(a===null)c.push(w(`not { $${r} has ${d} $${d}_${v4()}; };`,n));else if(Array.isArray(a)){let $=a.map(m=>`$${r} has ${d} ${ne(m)};`),y=Ge($);y&&c.push(w(y,n));}else c.push(w(`$${r} has ${d} ${ne(a)};`,n));return}let h=f.linkFields?.find($=>$.path===d);if(h){let[$]=h.oppositeLinkFieldsPlayedBy,m=v(o,$.thing).idFields?.[0];if(!m)throw new Error(`"${$.thing}" does not have an id field`);if(h.target==="relation")if(a===null)c.push(w(`not { (${h.plays}: $${r}) isa ${h.relation}; };`,n));else if(Array.isArray(a)){let B=a.map(g=>`(${h.plays}: $${r}) isa ${h.relation}, has ${m} ${ne(g)};`),M=Ge(B);M&&c.push(w(M,n));}else c.push(w(`(${h.plays}: $${r}) isa ${h.relation}, has ${m} ${ne(a)};`,n));else {let B=`${$.thing}_${v4()}`;if(a===null)c.push(w(`not { $${B} isa ${$.thing}; (${h.plays}: $${r}, ${$.plays}: $${B}) isa ${h.relation}; };`,n));else if(Array.isArray(a)){let M=a.map(L=>`$${B} isa ${$.thing}, has ${m} ${ne(L)}; (${h.plays}: $${r}, ${$.plays}: $${B}) isa ${h.relation};`),g=Ge(M);g&&c.push(w(g,n));}else c.push(w(`$${B} isa ${$.thing}, has ${m} ${ne(a)}; (${h.plays}: $${r}, ${$.plays}: $${B}) isa ${h.relation};`,n));}return}if(f.thingType==="relation"){let $=f.roles[d];if($){let[y]=$.playedBy||[],B=v(o,y.thing).idFields?.[0];if(!B)throw new Error(`"${y.thing}" does not have an id field`);let M=`${y.thing}_${v4()}`,g=v4(),L=`${r}_${g}`;if(a===null)c.push(w(`$${L} isa ${i};`,n)),c.push(w(`not { $${L} (${y.plays}: ${M}); };`,n)),c.push(w(`$${r} is $${L};`,n));else if(Array.isArray(a)){let D=a.map(C=>`$${M} isa ${y.thing}, has ${B} ${ne(C)}; $${L} (${y.plays}: $${M});`),A=Ge(D);A&&(c.push(w(`$${L} isa ${i};`,n)),c.push(w(A,n)),c.push(w(`$${r} is $${L};`,n)));}else c.push(w(`$${L} isa ${i};`,n)),c.push(w(`$${M} isa ${y.thing}, has ${B} ${ne(a)}; $${L} (${y.plays}: $${M});`,n)),c.push(w(`$${r} is $${L};`,n));return}}throw new Error(`"${i}" does not have property "${d}"`)}),c.join(`
51
+ `)},Ge=e=>{if(e.length>1)return `{ ${e.join(" } or { ")} };`;let[t]=e;return t},ne=e=>typeof e=="string"?`'${e}'`:e instanceof Date?`'${e.toISOString().replace("Z","")}'`:isObject(e)&&"$id"in e?isArray(e.$id)?`like "^(${e.$id.join("|")})$"`:`"${e.$id}"`:`${e}`,ji=e=>typeof e=="string"?{field:e,desc:!1}:{...e,desc:e.desc??!1},It=e=>{let{$var:t,$thing:r,schema:i,$sort:o,depth:n}=e,l=v(i,r),s=[],u=[];if(o?.forEach(f=>{let c=ji(f),d=l.dataFields?.find(h=>h.path===c.field);if(!d)throw new Error(`"${r}" does not have data field "${c.field}"`);let a=`${c.field}_${v4()}`;s.push(w("{",n)),s.push(w(`$${t} has ${d.dbPath} $${a}_1;`,n+1)),s.push(w("not {",n+1)),s.push(w(`$${t} has ${d.dbPath} $${a}_2;`,n+2)),s.push(w(`$${a}_2 < $${a}_1;`,n+2)),s.push(w("};",n+1)),s.push(w(`?${a}_ = $${a}_1;`,n+1)),s.push(w("} or {",n)),s.push(w(`not { $${t} has ${d.dbPath} $${a}_1; };`,n+1)),s.push(w(`?${a}_ = "~";`,n+1)),s.push(w("};",n)),s.push(w(`?${a} = ?${a}_;`,n));let p=c.desc?"desc":"asc";u.push(`?${a} ${p}`);}),s.length!==0)return {match:s.join(""),sort:w(`sort ${u.join(", ")};`,n)}};var tn=async e=>{let{enrichedBqlQuery:t,rawBqlRequest:r,schema:i,config:o,rawTqlRes:n}=e;if(t){if(!n)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");return n.map((l,s)=>{let u=r[s],f=t[s];return Wi(l,u,f,i,o)})},Wi=(e,t,r,i,o)=>e.length===0?null:r.$filterByUnique?en(e[0],t,i,o):e.map(n=>en(n,t,i,o)),en=(e,t,r,i)=>{let{dataFields:o,currentSchema:n,linkFields:l,roleFields:s,schemaValue:u}=Ct(e,r),f=Ot(o,n,i),c=Pt(l,r,i),d=qt(s,r,i),a=t?.$fields?.every(h=>!n?.idFields?.includes(typeof h=="string"?h:h.$path));return {...c,...d,...u,...!i.query?.noMetadata&&t.$id?{$id:Array.isArray(t.$id)?f.id:t.$id}:{},...a?Object.fromEntries(Object.entries(f).filter(([h])=>!n?.idFields?.includes(h))):f}},Ct=(e,t)=>{let r=Object.keys(e),i=r.find(p=>p.endsWith(".$dataFields")),o=r.filter(p=>p.endsWith(".$multiVal"));if(!i)throw new Error("No dataFields");o?.length>0&&o.forEach(p=>{let h=p.replace(/\.\$multiVal$/,""),$=e[p][0][h].attribute;e[i][h]=$;});let n=e[i],l=i.split(".")[i.split(".").length-2];if(n.$metaData=l,n.length===0)throw new Error("No dataFields");let s=n.type,u={$thing:s.label,$thingType:s.root,[ae]:e.queryPath.value},f={[`$${u.$thingType}`]:u.$thing},c=x(t,f),d=r.filter(p=>{let h=oe(p.split(".").pop());return !p.endsWith(".$dataFields")&&c.linkFields?.some($=>$.path===h)}).map(p=>{let h=oe(p.split(".").pop()),$=oe(c.linkFields?.find(y=>y.path===h));return {$linkFields:e[p],$key:h,$metaData:p.split(".")[p.split(".").length-2],$cardinality:$.cardinality}}),a=r.filter(p=>{let h=p.split(".").pop();return h&&!p.endsWith(".$dataFields")&&c.thingType==="relation"&&c.roles?.[h]}).map(p=>{let h=oe(p.split(".").pop());return {$roleFields:e[p],$key:h,$metaData:p.split(".")[p.split(".").length-2],$cardinality:c.roles[h].cardinality}});return {dataFields:n,schemaValue:u,currentSchema:c,linkFields:d,roleFields:a}},Ot=(e,t,r)=>{let{$metaData:i}=e,{as:o}=zi(i),n=Object.entries(e).filter(([l])=>l!=="type"&&!l.startsWith("$")).map(([l,s])=>{let u=t.dataFields?.find(a=>a.path===l||a.dbPath===l),f=l==="id",c=Array.isArray(o)?o.find(a=>a[l])?.[l]:l,d;if(u?.cardinality==="ONE"){if(d=s[0]?s[0].value:r.query?.returnNulls?null:void 0,u.contentType==="DATE"||u.contentType==="FLEX"&&s[0].type.value_type==="datetime"?d=d&&`${d}Z`:u.contentType==="JSON"&&(d=d&&JSON.parse(d)),f)return [[c,d],["$id",d]].filter(([a,p])=>p!==void 0)}else if(u?.cardinality==="MANY"){if(!isArray(s))throw new Error("Typedb fetch has changed its format");if(s.length===0)return r.query?.returnNulls?[[c,null]]:[];u.contentType==="DATE"?d=s.map(a=>`${a.value}Z`):u.contentType==="FLEX"?d=s.map(a=>a.type.value_type==="datetime"?`${a.value}Z`:a.value):u.contentType==="JSON"?d=s.map(a=>a.value&&JSON.parse(a.value)):d=s.map(a=>a.value);}return [[c,d]].filter(([a,p])=>p!==void 0)}).flat();return Object.fromEntries([...n])},qt=(e,t,r)=>{let i={};return e.forEach(o=>{let{$roleFields:n,$metaData:l,$cardinality:s}=o,{as:u,justId:f,idNotIncluded:c,filterByUnique:d}=rn(l);if(u===null)return;let a=n.map(p=>{let{dataFields:h,currentSchema:$,linkFields:y,roleFields:m,schemaValue:B}=Ct(p,t),M=Ot(h,$,r);if(f==="T")return M.id;{let g=Pt(y,t,r),L=qt(m,t,r),D={...M};return c==="true"&&$?.idFields?.forEach(A=>delete D[A]),{...D,...g,...L,...B}}});a.length>0?i[u]=s==="MANY"&&d==="false"?a:a[0]:r.query?.returnNulls&&(i[u]=null);}),i},Pt=(e,t,r)=>{let i={};return e.forEach(o=>{let{$linkFields:n,$metaData:l,$cardinality:s}=o,{as:u,justId:f,idNotIncluded:c,filterByUnique:d}=rn(l);if(u===null)return;let a=n.map(p=>{let{dataFields:h,currentSchema:$,linkFields:y,roleFields:m,schemaValue:B}=Ct(p,t),M=Ot(h,$,r);if(f==="T")return M.id;{let g=Pt(y,t,r),L=qt(m,t,r),D={...M};return c==="true"&&$.idFields?.forEach(A=>delete D[A]),{...D,...g,...L,...B}}});i[u]=a.length>0?s==="MANY"&&d==="false"?a:a[0]:r.query?.returnNulls?null:void 0;}),i},rn=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,r=/justId:([a-zA-Z0-9_\-·]+)/,i=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,o=/filterByUnique:([a-zA-Z0-9_\-·]+)/,n=e.match(t),l=e.match(r),s=e.match(i),u=e.match(o);return {as:n?n[1]:null,justId:l?l[1]:null,idNotIncluded:s?s[1]:null,filterByUnique:u?u[1]:null}},zi=e=>{try{let r=(o=>{let n=o.replace("$metadata:","");return n=n.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),n=n.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(l,s,u)=>/^{.*}$/.test(u)?`:${u}`:`:${s}"${u}"`),n=n.replace(/\[([^\]]+)\]/g,(l,s)=>`[${s.split(",").map(u=>u.trim().startsWith("{")&&u.trim().endsWith("}")?u.trim():`"${u.trim()}"`).join(",")}]`),n})(e);return JSON.parse(r)}catch(t){return console.error(t),{as:[]}}};var nn=async e=>{let{tqlRequest:t,dbHandles:r,config:i}=e,o=new TypeDBOptions;o.infer=!0;let{session:n}=await Ze(r,i),l=await n.transaction(TransactionType.READ,o),[s,u]=await tryit(parallel)(t.length,t,async f=>await l.query.fetch(f).collect());if(s){await l.rollback();let f=s;throw new Error(`Error running TQL query: ${f.errors}`)}return await l.close(),u};var Ui=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,Ji=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,Zi=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,xt=H("error","error",V((e,t)=>({...e,error:t.error}))),Yi=be("build",{build:Y(async e=>Gr({queries:e.bql.queries,schema:e.schema}),H("done","run",V(Ji)),xt),run:Y(async e=>nn({dbHandles:e.handles,tqlRequest:oe(e.tql.queries),config:e.config}),H("done","parse",V(Zi)),xt),parse:Y(async e=>tn({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries,schema:e.schema,config:e.config,rawTqlRes:oe(e.tql.res)}),H("done","success",V(Ui)),xt),success:he(),error:he()},e=>e),Xi=async e=>new Promise((t,r)=>{me(Yi,i=>{i.machine.state.name==="success"&&t(i.context.bql.res),i.machine.state.name==="error"&&r(i.context.error);},e);}),on=async(e,t,r,i,o)=>Xi({bql:{raw:e,queries:t},tql:{},schema:r,config:i,handles:o,error:null});var vi=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,jt=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,et=H("error","error",V((e,t)=>({...e,error:t.error}))),Gi=be("enrich",{enrich:Y(async e=>Wr(e.bql.raw,e.schema),H("done","adapter",V(vi)),et),adapter:Y(async e=>{let t={};e.bql.queries?.forEach((s,u)=>{let f=e.bql.raw[u],c=v(e.schema,s.$thing),{id:d}=c.defaultDBConnector;if(c.db==="typeDB"){if(!t[d]){let p=e.handles.typeDB?.get(d)?.client;if(!p)throw new Error(`TypeDB client with id "${c.defaultDBConnector.id}" does not exist`);t[d]={db:"typeDB",client:p,rawBql:[],bqlQueries:[],indices:[]};}}else if(c.db==="surrealDB"){if(!t[d]){let p=e.handles.surrealDB?.get(d)?.client;if(!p)throw new Error(`SurrealDB client with id "${c.defaultDBConnector.id}" does not exist`);t[d]={db:"surrealDB",client:p,rawBql:[],bqlQueries:[],indices:[]};}}else throw new Error(`Unsupported DB "${c.db}"`);let a=t[d];a.rawBql.push(f),a.bqlQueries.push(s),a.indices.push(u);});let r=Object.values(t),i=r.map(s=>s.db==="typeDB"?on(s.rawBql,s.bqlQueries,e.schema,e.config,e.handles):Xr(s.bqlQueries,e.schema,e.config,s.client)),o=await Promise.all(i),n=r.flatMap((s,u)=>{let f=o[u];return s.indices.map((c,d)=>({index:c,result:f[d]}))});return n.sort((s,u)=>s.index<u.index?-1:s.index>u.index?1:0),n.map(({result:s})=>s)},H("done","postHooks",V(jt)),et),postHooks:Y(async e=>zr(e.schema,oe(e.bql.queries),oe(e.bql.res)),H("done","clean",V(jt)),et),clean:Y(async e=>jr(e.config,oe(e.bql.res)),H("done","success",V(jt)),et),success:he(),error:he()},e=>e),eo=async e=>new Promise((t,r)=>{me(Gi,i=>{i.machine.state.name==="success"&&t(i.context),i.machine.state.name==="error"&&r(i.context);},e);}),qe=async(e,t,r,i)=>eo({bql:{raw:e},schema:t,config:r,handles:i,error:null});var Nt="___",to=Symbol.for("grandChildOfCreate"),sn=async(e,t,r,i)=>{let o=(E,Q)=>Object.keys(E).filter(b=>!b.startsWith("$")&&E[b]!==void 0?Q?!x(t,E).dataFields?.find(T=>T.path===b):!0:!1);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(r.mutation?.preQuery===!1)return;let n=[];if(traverse(e,({parent:E,key:Q,value:b})=>{E&&Q&&!Q.includes("$")&&isObject(E)?(Array.isArray(E[Q])?E[Q]:[E[Q]]).forEach(T=>{if(isObject(T)){if(E.$op!=="create")n.includes(T.$op)||n.push(T.$op);else if(T.$op==="delete"||T.$op==="unlink")throw new Error(`Cannot ${T.$op} under a create`)}}):!E&&isObject(b)&&(n.includes(b.$op)||n.push(b.$op));}),!n.includes("delete")&&!n.includes("unlink")&&!n.includes("replace")&&!n.includes("update")&&!n.includes("link"))return;let s=(E=>{let Q=(b,F)=>{let T=[],S={},O=["$op","$bzId","$parentKey"],k=["$relation","$entity","$id",...O];for(let P in b)if(!O.includes(P)&&!(k.includes(P)&&!F))if(!P.includes("$")&&(isObject(b[P])||Array.isArray(b[P]))){let J=b[P];if(Array.isArray(J)&&J.length>0)J.forEach(ce=>{let Me={$path:P,...Q(ce),...ce.$filter&&{$as:ce.$bzId}};T.find(U=>U.$path===Me.$path&&!U.$filter)||(T=[...T,Me]);});else {let ce={$path:P,...Q(J),...!J.$filter&&{$as:J.$bzId}};T=[...T,ce];}}else S[P]=b[P];return {...S,$fields:T}};return E.map(b=>Q(b,!0))})(Array.isArray(e)?e:[e]),f=(await qe(s,t,r,i)).bql.res,c=(E,Q)=>{let b=E.$id||E.id||E.$bzId;if(E.$objectPath){let{$objectPath:F}=E,T=F?.beforePath||"root",S=Array.isArray(F.ids)?`[${F.ids}]`:F.ids;return {beforePath:`${T}.${S}___${F.key}`,ids:b,key:Q}}else return {beforePath:"root",ids:b,key:Q}},d=(E,Q)=>{let b=E?.beforePath||"root",F=(Array.isArray(E?.ids)?`[${E?.ids}]`:E?.ids);return `${b}.${F}___${E?.key}`},a=E=>{if(E.includes("[")&&E.includes("]")){let[Q,b,F]=E.split(/[[\]]/);return b.split(",").map(S=>`${Q}${S}${F}`)}else return [E]},p={};(E=>produce(E,Q=>traverse(Q,b=>{let{key:F,parent:T}=b;if(T&&F&&T.$id&&!F.includes("$")){let S=c(T,F),O=d(S);if(Array.isArray(T[F])){let k=[];T[F].forEach(P=>{isObject(P)?(P.$objectPath=S,k.push(P.$id.toString())):P&&k.push(P.toString());}),p[O]={$objectPath:S,$ids:k};}else {let k=T[F];isObject(k)?(p[O]={$objectPath:S,$ids:[k.$id.toString()]},k.$objectPath=S):k&&(p[O]={$objectPath:S,$ids:[k.toString()]});}}})))(f||{});let $=E=>produce(E,Q=>traverse(Q,b=>{let{key:F,value:T,parent:S}=b;S&&F&&!F.includes("$")&&(Array.isArray(T)||isObject(T))&&!Array.isArray(S)&&(Array.isArray(S[F])?S[F].forEach(O=>{typeof O!="string"&&(O.$objectPath=c(S,F),O.$parentIsCreate=S.$op==="create",O[to]=S.$parentIsCreate||S[Symbol.for("grandChildOfCreate")]);}):isObject(S[F])&&(S[F].$parentIsCreate=S.$op==="create",S[F][Symbol.for("grandChildOfCreate")]=S.$parentIsCreate||S[Symbol.for("grandChildOfCreate")],S[F].$objectPath=c(S,F)));})),y=$(e),m=E=>{let Q=[];return E.forEach(F=>{if(!F.$id&&!F.id&&!F.$tempId)if(F.$filter){let T=d({...F.$objectPath,key:F.$bzId}),S=p[T];S&&(Array.isArray(S.$ids)?S.$ids:[S.$ids]).forEach(k=>{let P={...F,$id:k,$bzId:`T4_${v4()}`,$filterBzId:F.$bzId};Q.push(P);});}else {let T=d(F.$objectPath),S=p[T];S?S?.$ids.forEach(O=>{let k={...F,$id:O,$bzId:`T4_${v4()}`};Q.push(k);}):Q.push(F);}else Q.push(F);}),Q.map(F=>{let T={...F};return o(T,!0).forEach(S=>{let O=Array.isArray(T[S])?T[S]:[T[S]],k=m(O);T[S]=k;}),T})},B=m(Array.isArray(y)?y:[y]),M=$(B),L=(E=>{let Q=b=>{let F=U=>{let ee=[],z=[],q=[];return U.forEach(_=>{let ie=o(_,!0);if(ie.length>0){let I=!1;ie.forEach(W=>{(Array.isArray(_[W])?_[W]:[_[W]]).filter(X=>!X.$id&&!X.id&&typeof _=="object").length&&(I=!0);}),I?ee.push(_):z.push(_);}else q.push({..._,$bzId:_.$tempId||`T_${v4()}`});}),{operationWithMultiples:ee,operationWithoutMultiples:z,otherOps:q}},{operationWithMultiples:T,operationWithoutMultiples:S,otherOps:O}=F(b),k=U=>{let z=(()=>{let W={};for(let te in U){let Z=x(t,U);!te.startsWith("$")&&Z.dataFields?.find(X=>X.path===te)&&(W[te]=U[te]);}return W})(),q=Object.keys(U),_=o(U,!0),ie=[],I=(W,te)=>{if(W===_.length){let X={...te};q.forEach(re=>{re.startsWith("$")&&(X[re]=U[re]);}),ie.push({...X,...z});return}let Z={...te,[_[W]]:U[_[W]],...Ee(te),...z};I(W+1,Z),I(W+1,te);};return I(0,{...Ee(U)}),ie},P=[];return T.forEach(U=>{let ee=k(U),z=[];ee.forEach(q=>{let _=o(q,!0);if(q.$op==="create")z.push(q);else if(q.$id){let ie=d(q.$objectPath),I=[];if(_.forEach(W=>{let te=`${ie.includes("undefined")?"root":ie}.${q.$id}${Nt}${W}`,Z=p[te];q[W].filter(re=>re.$op==="unlink"||re.$op==="delete"||re.$op==="update").length>0?Z&&I.push({key:W,ids:Z.$ids}):I.push({key:W,ids:[""]});}),I.length===_.length&&!z.find(W=>W.$id===q.$id))z.push(q);else {let W={...q,$bzId:q.$tempId||`T4_${v4()}`};_.forEach(Z=>{let X=q[Z].filter(re=>re.$id);X.length>0?W[Z]=X:W[Z]=void 0;}),o(W,!0).length>0&&z.push(W);}}else if(q.$objectPath){let ie=d(q.$objectPath),I=p[ie]?.$ids||[];I.forEach(W=>{let te=[];_.forEach(Z=>{let X=`${ie}.${W}${Nt}${Z}`,re=p[X];re&&te.push({key:Z,ids:re.$ids});}),_.length===0?I.filter(X=>!z.find(re=>re.$id===X)).forEach(X=>{z.push({...q,$id:X,$bzId:q.$tempId||`T_${v4()}`});}):te.length===_.length&&!z.find(Z=>Z.$id===W)&&(_.forEach(Z=>{let X=`${d(q.$objectPath)}.${W}${Nt}${Z}`,{$ids:re}=p[X],En=q[Z].find(ke=>!ke.$id),Fn=[...re.map(ke=>({...En,$id:ke,$objectPath:{beforePath:q.$objectPath,ids:ke,key:Z}})),...q[Z].filter(ke=>ke.$id)];q[Z]=Fn;}),z.push({...q,$id:W,$bzId:q.$tempId||`T_${v4()}`}));});}else z.push(q);}),z.forEach(q=>{P.push(q);});}),[...P,...S,...O].filter(U=>o(U).length>0?!0:U.$op!=="update").map(U=>{let ee={...U};return o(ee,!0).forEach(z=>{let q=Array.isArray(ee[z])?ee[z]:[ee[z]],_=Q(q);ee[z]=_;}),ee})};return Q(E)})(Array.isArray(M)?M:[M]),D=E=>E.map(Q=>{let b=o(Q,!0),F={...Q};return b.forEach(T=>{let S=Array.isArray(Q[T])?Q[T]:[Q[T]],O=[],k=[],P=[],J={},ce=ct(t,Q,T);S.filter(I=>I).forEach(I=>{I.$op==="replace"&&I.$id?(J=I,Array.isArray(I.$id)?k=[...k,...I.$id]:k.push(I.$id)):I.$op==="create"&&ce==="ONE"&&I.id?(J=I,Array.isArray(I.id)?P=[...k,...I.id]:P.push(I.id)):O.push(I);});let Me=d(J.$objectPath),ee=a(Me).map(I=>p[I]),z=[];ee.filter(I=>I!=null).forEach(I=>{z=[...z,...I.$ids];});let q=z.filter(I=>!k.includes(I)),_=k.filter(I=>!z.includes(I)),ie=Ee(J);q.length>0&&O.push({...J,$op:"unlink",$id:q,$bzId:J.$tempId||`T4_${v4()}`,id:void 0,...ie}),_.length>0&&_.forEach(I=>{O.push({...J,$op:"link",$id:I,$bzId:J.$tempId||`T5_${v4()}`,...ie});}),P.length>0&&P.forEach(I=>{O.push({...J,$op:"create",id:I,$bzId:J.$tempId||`T6_${v4()}`,...ie});}),F[T]=D(O);}),F}),A=$(D($(L)));(E=>produce(E,Q=>traverse(Q,b=>{let{key:F,value:T,parent:S}=b;F&&S&&!F?.includes("$")&&(Array.isArray(T)||isObject(T))&&!Array.isArray(S)&&(Array.isArray(T)?T:[T]).forEach(k=>{let P=k.$filter?{...k.$objectPath,key:k.$filterBzId}:k.$objectPath,J=d(P),ce=p[J],Me=(z,q)=>z.every(_=>q.includes(_)),U=k.$id?Array.isArray(k.$id)?Me(k.$id,ce?ce.$ids:[]):ce?.$ids.includes(k.$id):ce,ee=ct(t,S,k.$objectPath.key);if(k.$op==="link"&&U&&ee==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${d(k.$objectPath)}" because it is already occupied.`);if(k.$op)switch(k.$op){case"delete":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${k.$id}" because it is not linked to $id:"${S.$id}"`);break;case"update":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${k.$id}" because it is not linked to $id:"${S.$id}"`);break;case"unlink":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${k.$id}" because it is not linked to $id:"${S.$id}"`);break;case"link":if(U)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${k.$id}" because it is already linked to $id:"${S.$id}"`);break;}});})))(A);let N=(E=>produce(E,Q=>traverse(Q,b=>{let{value:F,meta:T}=b;isObject(F)&&(F[Symbol.for("path")]=T.nodePath,delete F.$objectPath,delete F.$parentIsCreate);})))(A);return [...Array.isArray(N)?N:[N]].sort((E,Q)=>E.$op==="create"&&Q.$op!=="create"?-1:E.$op!=="create"&&Q.$op==="create"?1:0)};var an=(e,t)=>produce(e,i=>rt(t,i)),rt=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){t.forEach(o=>rt(e,o,r));return}let i=v(e,r||t.$entity||t.$relation||t.$thing);Object.entries(t).forEach(([o])=>{o.startsWith("$")||no(e,t,o,i);});},no=(e,t,r,i)=>{let o=t[r];if(!o)return;let n=i.dataFields?.find(s=>s.path===r);if(n){n.contentType==="JSON"&&o!=null&&(t[r]=JSON.stringify(o));return}let l=i.linkFields?.find(s=>s.path===r);if(l){let s=l.oppositeLinkFieldsPlayedBy[0]?.thing;rt(e,o,s);return}if(i.thingType==="relation"){let s=i.roles[r],[u]=s.playedBy||[];if(!u)throw new Error(`Role ${s.name} in ${i} is not played by anything`);rt(e,o,u.thing);}};var hn=async(e,t,r,i)=>{let o=Array.isArray(e)?e:[e],n=o.map(u=>Wt(u,!0)),s=(await qe(n,t,r,i)).bql.res;return o.map((u,f)=>{let c=v(t,u.$thing);return pn({mut:u,node:s[f],schema:t,thing:c})})},un=new Set(["$op","$bzId","$parentKey"]),oo=new Set(["$relation","$entity","$id",...un]),Wt=(e,t)=>{let r={};e.$fields?.forEach(o=>{typeof o=="string"?r[o]=o:r[o.$path]=o;});let i={};for(let o in e){if(un.has(o)||oo.has(o)&&!t)continue;let n=e[o];o.startsWith("$")?i[o]=n:Array.isArray(n)?n[0]&&typeof n[0]=="object"&&(r[o]={$path:o,...Wt(n[0],!1)}):isObject(n)&&(r[o]={$path:o,...Wt(n,!1)});}return i.$fields=Object.values(r),i},pn=e=>{let{mut:t,node:r,schema:i,thing:o}=e,n=$n(o),l=ao(r);if(Array.isArray(t))return t.map(u=>{let f=l[u.$id];return f?ln({mut:u,node:f,schema:i,thing:o,...n}):u});let s=l[t.$id];return ln({mut:t,node:s,schema:i,thing:o,...n})},ln=e=>{let{mut:t,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:l,roleFieldMap:s}=e,{$fields:u,...f}=t;if(!r)return f;let c=fn({$fields:t.$fields,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:l,roleFieldMap:s}),d={...f,[De]:c};for(let a in t){if(a.startsWith("$"))continue;let p=t[a];if(n[a]||!p||typeof p!="object"){d[a]=p;continue}let $=l[a]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||s[a]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${o.name}" does not have field "${a}"`);let y=v(i,$);d[a]=pn({mut:p,schema:i,node:r[a],thing:y});}return d},fn=e=>{let{$fields:t,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:l,roleFieldMap:s}=e,u=t||so(o),f={$id:r.$id};return u.forEach(c=>{let d=typeof c!="string",a=d?c.$path:c,p=r[a];if(n[a]){f[a]=p;return}let $=l[a]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||s[a]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${o.name}" does not have field "${a}"`);if(!d){p&&(f[a]=Array.isArray(p)?p.map(cn):cn(p));return}let y=v(i,$),m=$n(y);f[a]=Array.isArray(p)?p.map(B=>dn({...m,$fields:c.$fields,value:B,schema:i,thing:y})):dn({...m,$fields:c.$fields,value:p,schema:i,thing:y});}),f},so=e=>{let t=[];return e.dataFields?.forEach(r=>{t.push(r.path);}),e.linkFields?.forEach(r=>{t.push(r.path);}),e.thingType==="relation"&&t.push(...Object.keys(e.roles)),t},cn=e=>{if(typeof e=="string")return e;if(!e||typeof e!="object")throw new Error(`"${JSON.stringify(e)}" is neither an id nor an object with prop "$id"`);if(typeof e.$id!="string")throw new Error(`"${JSON.stringify(e)}" is does not have prop "$id"`);return e.$id},dn=e=>{let{value:t}=e;if(!t||typeof t!="object"||!t.$id)throw new Error(`"${JSON.stringify(e)}" is neither an id nor an object with prop "$id"`);return fn({...e,node:t})},$n=e=>{let t=Object.fromEntries(e.dataFields?.map(o=>[o.path,o])||[]),r=Object.fromEntries(e.linkFields?.map(o=>[o.path,o])||[]),i=e.thingType==="relation"?e.roles||{}:{};return {dataFieldMap:t,linkFieldMap:r,roleFieldMap:i}},ao=e=>{if(!Array.isArray(e))return e&&typeof e=="object"&&e.$id?{[e.$id]:e}:{};let t={};return e.forEach(r=>{!r||typeof r!="object"||!r.$id||(t[r.$id]=r);}),t};var mn=he,Pe=(e,t)=>t.data?{...e,bql:{...e.bql,current:t.data}}:e,lo=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),co=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),ho=(e,t)=>({...e,typeDB:{...e.typeDB,tqlMutation:t.data}}),uo=(e,t)=>({...e,typeDB:{...e.typeDB,tqlRes:t.data}}),po=async e=>Object.keys(e.bql.current).length?ft(e.bql.current,e.schema,e.config):ft(e.bql.raw,e.schema,e.config),fo=async e=>sn(e.bql.current,e.schema,e.config,e.handles),$o=async e=>hn(e.bql.current,e.schema,e.config,e.handles),mo=async e=>Fr(e.bql.current,e.schema),yo=async e=>wr(e.bql.things,e.bql.edges,e.schema),go=async e=>$r(e.typeDB.tqlMutation,e.handles,e.config),Bo=async e=>mr(e.typeDB.tqlRes,e.bql.things,e.bql.edges,e.schema,e.config),Eo=()=>!0,Fo=e=>Ie(e.bql.current),we=H("error","error",V((e,t)=>({...e,error:t.error}))),bo=be("stringify",{stringify:Y(async e=>an(e.bql.raw,e.schema),H("done","enrich",V(Pe)),we),enrich:Y(po,H("done","preQuery",yt(Eo),V(Pe)),H("done","parseBQL",V(Pe)),we),preHookDependencies:Y($o,H("done","enrich",V(Pe)),we),preQuery:Y(fo,H("done","preHookDependencies",yt(Fo),V(Pe)),H("done","parseBQL",V(Pe)),we),parseBQL:Y(mo,H("done","buildMutation",V(co)),we),buildMutation:Y(yo,H("done","runMutation",V(ho)),we),runMutation:Y(go,H("done","parseMutation",V(uo)),we),parseMutation:Y(Bo,H("done","success",V(lo)),we),success:mn(),error:mn()},e=>e),wo=async e=>new Promise((t,r)=>{me(bo,i=>{i.machine.state.name==="success"&&t(i.context),i.machine.state.name==="error"&&r(i.context);},e);}),yn=async(e,t,r,i)=>wo({bql:{raw:e,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:t,config:r,handles:i,depthLevel:0,error:null});enableMapSet();var zt=class{schema;config;dbHandles;constructor({schema:t,config:r}){this.schema=t,this.config=r;}getDbHandles=()=>this.dbHandles;init=async()=>{let t={typeDB:new Map,surrealDB:new Map};await Promise.all(this.config.dbConnectors.map(async i=>{if(i.provider==="surrealDB"){let o=new Surreal;await o.connect(i.url,{namespace:i.namespace,database:i.dbName,auth:{namespace:i.namespace,database:i.dbName,username:i.username,password:i.password}}),t.surrealDB.set(i.id,{client:o});}if(i.provider==="typeDB"&&i.dbName){let[o,n]=await tryit(TypeDB.coreDriver)(i.url);if(o){let l=`[BORM:${i.provider}:${i.dbName}:core] ${o.message??"Can't create TypeDB Client"}`;throw new Error(l)}try{let l=await n.session(i.dbName,SessionType.DATA);t.typeDB.set(i.id,{client:n,session:l});}catch(l){let s=`[BORM:${i.provider}:${i.dbName}:session] ${(l.messageTemplate?._messageBody()||l.message)??"Can't create TypeDB Session"}`;throw new Error(s)}}if(i.provider==="typeDBCluster"&&i.dbName){let o=new TypeDBCredential(i.username,i.password,i.tlsRootCAPath),[n,l]=await tryit(TypeDB.cloudDriver)(i.addresses,o);if(n){let s=`[BORM:${i.provider}:${i.dbName}:core] ${n.message??"Can't create TypeDB Cluster Client"}`;throw new Error(s)}try{let s=await l.session(i.dbName,SessionType.DATA);t.typeDB.set(i.id,{client:l,session:s});}catch(s){let u=`[BORM:${i.provider}:${i.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(u)}}}));let r=vt(this.schema,t);this.schema=r,this.dbHandles=t;};#e=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#e(),this.schema);define=async()=>(await this.#e(),Vt(this.config,this.schema,this.dbHandles));query=async(t,r)=>{await this.#e();let i={...this.config,query:{...it.query,...this.config.query,...r}},o=Array.isArray(t),n=o?t:[t],[l,s]=await tryit(qe)(n,this.schema,i,this.dbHandles);if(l){let f=new Error(l.error);throw f.stack=l.error.stack,f}let u=s.bql.res;return o?u:u[0]};mutate=async(t,r)=>{await this.#e();let i={...this.config,mutation:{...it.mutation,...this.config.mutation,...r}},[o,n]=await tryit(yn)(t,this.schema,i,this.dbHandles);if(o){let s=new Error(o.error.message);throw s.stack=o.error.stack,s}return n.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:r})=>{r.isOpen()&&await r.close(),await t.close();});}},Sc=zt;//! Todo: delete when this works with the new $thing and $thingType fields
47
52
  //! Todo: Sandbox the function in nodeCompute() instead of the existing fieldCompute()
48
53
  //! Todo: Sandbox the function in computeFunction()
49
54
  //! reads all the insertions and gets the first match. This means each id must be unique
50
55
  //!old
51
56
 
52
- export { Fc as default };
57
+ export { Sc as default };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blitznocode/blitz-orm",
3
- "version": "0.10.13",
3
+ "version": "0.10.15",
4
4
  "main": "dist/index.cjs",
5
5
  "module": "./dist/index.mjs",
6
6
  "types": "dist/index.d.ts",
@@ -37,7 +37,7 @@
37
37
  "object-traversal": "^1.0.1",
38
38
  "radash": "^12.1.0",
39
39
  "robot3": "^0.4.1",
40
- "surrealdb.node": "^0.3.0",
40
+ "surrealdb.js": "1.0.0-beta.8",
41
41
  "typedb-driver": "2.28.2-rc1",
42
42
  "uuid": "^9.0.1"
43
43
  },
@@ -85,11 +85,12 @@
85
85
  "preinstall": "npx only-allow pnpm",
86
86
  "pub": "pnpm build && pnpm publish",
87
87
  "test": "./tests/test.sh --coverage",
88
- "test:ignoreTodo": "./tests/test.sh -t \"^(?!.*TODO:).*\"",
88
+ "test:ignoreTodo": "pnpm test:surrealdb-ignoreTodo && pnpm test:typedb-ignoreTodo",
89
89
  "test:multidb": "./tests/test.sh multidb",
90
90
  "test:query": "./tests/test.sh query.test.ts",
91
+ "test:surrealdb-ignoreTodo": "./tests/test.sh surrealdb/unit/queries -t \"^(?!.*TODO{.*[S].*}:).*\" ",
91
92
  "test:surrealdb-query": "./tests/test.sh surrealdb/unit/queries/query.test.ts",
92
- "test:typedb-ignoreTodo": "vitest run typedb -t \"^(?!.*TODO:).*\" ",
93
+ "test:typedb-ignoreTodo": "vitest run typedb -t \"^(?!.*TODO{.*[T].*}:).*\" ",
93
94
  "test:typedb-mutation": "vitest run typedb/unit/mutations",
94
95
  "test:typedb-query": "vitest run typedb/unit/queries --watch",
95
96
  "test:typedb-schema": "vitest run typedb/unit/schema",