@blitznocode/blitz-orm 0.13.4 → 0.13.6
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.mjs
CHANGED
|
@@ -1,36 +1,26 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import Ei from 'surrealdb';
|
|
5
|
-
import { traverse, getNodeByPath } from 'object-traversal';
|
|
6
|
-
import { customAlphabet } from 'nanoid';
|
|
7
|
-
import 'acorn';
|
|
8
|
-
import { isSet } from 'util/types';
|
|
9
|
-
import { v4 } from 'uuid';
|
|
10
|
-
|
|
11
|
-
var rt=class{url;username;password;namespace;database;constructor(t){this.url=t.url,this.username=t.username,this.password=t.password,this.namespace=t.namespace,this.database=t.database;}async run(t){let r=new Ei;try{return await r.connect(this.url,{namespace:this.namespace,database:this.database,auth:{username:this.username,password:this.password},versionCheck:!1}),await t(r)}finally{await r.close();}}async query(...t){return this.run(r=>r.query(...t))}async query_raw(...t){return this.run(r=>r.query_raw(...t))}};var bt={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var fr=e=>e.replace(/`/g,""),Bi=[" ","-","+","*","/","=","!","@","#","$","%","^","&","(",")","[","]","{","}","|","\\",";",":","'",'"',",","<",">",".","?","~","`"],te=e=>Bi.some(t=>e.includes(t))?`\u27E8${e}\u27E9`:e;var wt=e=>{if(typeof e=="string"&&!Number.isNaN(Date.parse(e))&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/.test(e))return `<datetime>"${e}"`;if(isDate(e))return `d"${e.toISOString()}"`;if(typeof e=="string")return JSON.stringify(e);if(["number","boolean"].includes(typeof e))return e;throw new Error(`Unsupported type ${typeof e}`)};var mr={TEXT:"string",RICH_TEXT:"string",LANGUAGE_TEXT:"string",PASSWORD:"string",URL:"string",PHONE:"string",ID:"string",EMAIL:"string",NUMBER:"number",NUMBER_DECIMAL:"decimal",BOOLEAN:"bool",DATE:"datetime",JSON:"object",FLEX:"bool|bytes|datetime|duration|geometry|number|object|string"},je=(e,t)=>{if(e===null)return "NONE";if(t)switch(t){case"TEXT":case"RICH_TEXT":case"LANGUAGE_TEXT":case"PASSWORD":case"URL":case"PHONE":case"ID":case"EMAIL":if(typeof e!="string")throw new Error(`Invalid value for TEXT type: ${e}`);return JSON.stringify(e);case"NUMBER":case"NUMBER_DECIMAL":case"BOOLEAN":case"JSON":return e;case"DATE":return typeof e=="string"&&!Number.isNaN(Date.parse(e))&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/.test(e)?`<datetime>"${e}"`:isDate(e)?`d"${e.toISOString()}"`:`<datetime>"${e}"`;case"FLEX":{let r=isArray(e)?e.map(n=>wt(n)):wt(e);return `${isArray(r)?r.map(n=>n):r}`}default:throw new Error(`Unsupported data field type ${t}.`)}throw new Error(`Failed parsing value ${e} with content type ${t}`)};var wi=" ",ke=e=>wi.repeat(e),nt=(e,t)=>e.split(`
|
|
12
|
-
`).map(r=>r.trim()?`${ke(t)}${r}`:r).join(`
|
|
13
|
-
`),Ti=e=>{let t=`USE NS test;
|
|
1
|
+
import {tryit,parallel,isObject,isArray,clone,shake,mapEntries,pick,listify,isDate,isSymbol}from'radash';import {TypeDBOptions,TransactionType,SessionType,TypeDB,TypeDBCredential}from'typedb-driver';import {produce,enableMapSet,current,isDraft}from'immer';import ti from'surrealdb';import {traverse,getNodeByPath}from'object-traversal';import {customAlphabet}from'nanoid';import'acorn';import {isSet}from'util/types';import {v4}from'uuid';import*as co from'robot3';var Ge=class{url;username;password;namespace;database;constructor(t){this.url=t.url,this.username=t.username,this.password=t.password,this.namespace=t.namespace,this.database=t.database;}async run(t){let r=new ti;try{return await r.connect(this.url,{namespace:this.namespace,database:this.database,auth:{username:this.username,password:this.password},versionCheck:!1}),await t(r)}finally{await r.close();}}async query(...t){return this.run(r=>r.query(...t))}async query_raw(...t){return this.run(r=>r.query_raw(...t))}};var gt={query:{noMetadata:false,simplifiedLinks:true,debugger:false,returnNulls:false},mutation:{noMetadata:false,preQuery:true,ignoreNonexistingThings:false}};var lr=e=>e.replace(/`/g,""),ri=[" ","-","+","*","/","=","!","@","#","$","%","^","&","(",")","[","]","{","}","|","\\",";",":","'",'"',",","<",">",".","?","~","`"],te=e=>ri.some(t=>e.includes(t))?`\u27E8${e}\u27E9`:e;var Et=e=>{if(typeof e=="string"&&!Number.isNaN(Date.parse(e))&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/.test(e))return `<datetime>"${e}"`;if(isDate(e))return `d"${e.toISOString()}"`;if(typeof e=="string")return JSON.stringify(e);if(["number","boolean"].includes(typeof e))return e;throw new Error(`Unsupported type ${typeof e}`)};var dr={TEXT:"string",RICH_TEXT:"string",LANGUAGE_TEXT:"string",PASSWORD:"string",URL:"string",PHONE:"string",ID:"string",EMAIL:"string",NUMBER:"number",NUMBER_DECIMAL:"decimal",BOOLEAN:"bool",DATE:"datetime",JSON:"object",FLEX:"bool|bytes|datetime|duration|geometry|number|object|string"},Pe=(e,t)=>{if(e===null)return "NONE";if(t)switch(t){case "TEXT":case "RICH_TEXT":case "LANGUAGE_TEXT":case "PASSWORD":case "URL":case "PHONE":case "ID":case "EMAIL":if(typeof e!="string")throw new Error(`Invalid value for TEXT type: ${e}`);return JSON.stringify(e);case "NUMBER":case "NUMBER_DECIMAL":case "BOOLEAN":case "JSON":return e;case "DATE":return typeof e=="string"&&!Number.isNaN(Date.parse(e))&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/.test(e)?`<datetime>"${e}"`:isDate(e)?`d"${e.toISOString()}"`:`<datetime>"${e}"`;case "FLEX":{let r=isArray(e)?e.map(n=>Et(n)):Et(e);return `${isArray(r)?r.map(n=>n):r}`}default:throw new Error(`Unsupported data field type ${t}.`)}throw new Error(`Failed parsing value ${e} with content type ${t}`)};var oi=" ",Ae=e=>oi.repeat(e),et=(e,t)=>e.split(`
|
|
2
|
+
`).map(r=>r.trim()?`${Ae(t)}${r}`:r).join(`
|
|
3
|
+
`),si=e=>{let t=`USE NS test;
|
|
14
4
|
USE DB test;
|
|
15
5
|
|
|
16
6
|
BEGIN TRANSACTION;
|
|
17
7
|
`,r=`-- ENTITIES
|
|
18
|
-
${
|
|
8
|
+
${ur(e.entities)}`,n=`
|
|
19
9
|
-- RELATIONS
|
|
20
|
-
${
|
|
10
|
+
${ur(e.relations)}`,o=pi();return `${t}${r}${n}${o}COMMIT TRANSACTION;`},ur=e=>Object.entries(e).map(([t,r])=>ai(te(t),r,1)).join(`
|
|
21
11
|
|
|
22
|
-
`),
|
|
23
|
-
${
|
|
12
|
+
`),ai=(e,t,r)=>{let n=`${Ae(r)}DEFINE TABLE ${e} SCHEMAFULL PERMISSIONS FULL;${"extends"in t&&t.extends?` //EXTENDS ${t.extends};`:""}`,o=et(`-- DATA FIELDS
|
|
13
|
+
${li(t.dataFields??[],e,r)}`,r+1),i=et(`
|
|
24
14
|
-- LINK FIELDS
|
|
25
|
-
${
|
|
15
|
+
${ci(t.linkFields??[],e,r)}`,r+1),a="roles"in t?et(`
|
|
26
16
|
-- ROLES
|
|
27
|
-
${
|
|
28
|
-
${
|
|
29
|
-
`),
|
|
30
|
-
`)}if(n.target==="relation")return `${`${
|
|
31
|
-
`),
|
|
17
|
+
${di(t.roles,e,r)}`,r+1):"";return `${n}
|
|
18
|
+
${o}${i}${a}`},li=(e,t,r)=>e.map(n=>{if(n.path==="id")return "";let o=hi(n.contentType,n.validations),i=`${Ae(r)}DEFINE FIELD ${n.path} ON TABLE ${t}${["FLEX","JSON"].includes(n.contentType)?" FLEXIBLE":""}`;if(n.isVirtual){let a=n.dbValue?.surrealDB;return a?`${i} VALUE ${a};`:""}return `${i} TYPE ${o};`}).filter(Boolean).join(`
|
|
19
|
+
`),ci=(e,t,r)=>e.map(n=>{let o=n.cardinality==="MANY"?`option<array<record<${n.$things.map(te).join("|")}>>>`:`option<record<${n.$things.map(te).join("|")}>>`,i=`${Ae(r)}DEFINE FIELD ${te(n.path)} ON TABLE ${t}`;if(n.isVirtual){let a=n.dbValue?.surrealDB;return a?`${i} VALUE ${a};`:""}if(n.target==="role"){let a=e.find(p=>p.target==="relation"&&p.relation===n.relation),l=(n.oppositeLinkFieldsPlayedBy?.[0]).plays;if(!l||n.oppositeLinkFieldsPlayedBy?.length!==1)throw new Error(`Invalid link field: ${n.path}`);let h=n.cardinality==="ONE"?`record<${te(n.relation)}>`:`array<record<${te(n.relation)}>>`,c=te(n.pathToRelation||""),u=`${c}.${l}`,d=n.cardinality==="ONE"?`${i} VALUE <future> {RETURN SELECT VALUE ${u} FROM ONLY $this};`:`${i} VALUE <future> {array::distinct(SELECT VALUE array::flatten(${u} || []) FROM ONLY $this)};`,f=a?.path?"":`${Ae(r+1)}DEFINE FIELD ${c} ON TABLE ${t} TYPE option<${h}>;`;return [d,f].join(`
|
|
20
|
+
`)}if(n.target==="relation")return `${`${Ae(r)}DEFINE FIELD ${te(n.path)} ON TABLE ${t} TYPE ${o};`}`;throw new Error(`Invalid link field: ${JSON.stringify(n)}`)}).join(`
|
|
21
|
+
`),di=(e,t,r)=>Object.entries(e).map(([n,o])=>{let i=o.cardinality==="MANY"?`array<record<${o.$things.map(te).join("|")}>>`:`record<${o.$things.map(te).join("|")}>`,a=`${Ae(r)}DEFINE FIELD ${n} ON TABLE ${t} TYPE option<${i}>;`,s=ui(n,t,o,r);return `${a}
|
|
32
22
|
${s}`}).join(`
|
|
33
|
-
`),
|
|
23
|
+
`),ui=(e,t,r,n)=>{let o=`update_${e}`,i=r.playedBy?.find(F=>F.target==="relation"),a=i?.pathToRelation,s=r.playedBy?.find(F=>F.target==="role"),l=s?.pathToRelation,h=i??s;if(!h)throw new Error(`Invalid link field: ${JSON.stringify(r)}`);let c=te(a??l),u=(F,E)=>F.map(({path:Q,cardinality:M})=>`${Q} ${E==="remove"?M==="ONE"?"=":"-=":M==="ONE"?"=":"+="} ${E==="remove"?M==="ONE"?"NONE":"$before.id":"$after.id"}`).join(", "),d=r.impactedLinkFields?.map(F=>({path:F.path,cardinality:F.cardinality}))||[],p=[{path:c,cardinality:h.cardinality},...d],$=u(p,"remove"),g=u(p,"add"),y=`
|
|
34
24
|
IF ($before.${e}) THEN {UPDATE $before.${e} SET ${$}} END;
|
|
35
25
|
IF ($after.${e}) THEN {UPDATE $after.${e} SET ${g}} END;`,m=`
|
|
36
26
|
LET $edges = fn::get_mutated_edges($before.${e}, $after.${e});
|
|
@@ -38,8 +28,8 @@ ${s}`}).join(`
|
|
|
38
28
|
FOR $link IN $edges.additions {${h.cardinality==="ONE"?`
|
|
39
29
|
IF ($link.${c}) THEN {UPDATE $link.${c} SET ${e} ${r.cardinality==="ONE"?"= NONE":"-= $link.id"}} END;`:""}
|
|
40
30
|
UPDATE $link SET ${g};
|
|
41
|
-
};`;return
|
|
42
|
-
};`,n+1)},
|
|
31
|
+
};`;return et(`DEFINE EVENT ${o} ON TABLE ${t} WHEN $before.${e} != $after.${e} THEN {${r.cardinality==="ONE"?y:m}
|
|
32
|
+
};`,n+1)},hi=(e,t)=>{let r=t?.enum?`${t.enum.map(n=>Pe(n,e)).join("|")}`:dr[e];if(!r)throw new Error(`Unknown content type: ${e}`);return t?.required?`${r}`:`option<${r}>`},pi=()=>`
|
|
43
33
|
-- BORM TOOLS
|
|
44
34
|
DEFINE FUNCTION fn::get_mutated_edges(
|
|
45
35
|
$before_relation: option<array|record>,
|
|
@@ -61,7 +51,7 @@ ${s}`}).join(`
|
|
|
61
51
|
DEFINE FUNCTION fn::as_array($var: option<array<record>|record>) {
|
|
62
52
|
RETURN (type::is::array($var) AND $var) OR [$var]
|
|
63
53
|
};
|
|
64
|
-
`,
|
|
54
|
+
`,hr=e=>si(e);var mi=e=>{let t=[],r=new Map;return e.forEach(n=>{let{dbPath:o,contentType:i}=n,a=`${o}-${i}`;r.has(a)||(r.set(a,true),t.push(n));}),t},yi=(e,t)=>{let r="",n=[];r+=`
|
|
65
55
|
`,Object.keys(t.entities).filter(s=>t.entities[s].defaultDBConnector.id===e).forEach(s=>{let l=t.entities[s],{dataFields:h,linkFields:c,name:u}=l;if(r+=`${u} sub ${"extends"in l?l.extends:"entity"},
|
|
66
56
|
`,h&&h.length>0&&h.forEach(d=>{d.contentType!=="REF"&&(d.inherited||(d.isIdField?r+=` owns ${d.dbPath} @key,
|
|
67
57
|
`:r+=` owns ${d.dbPath},
|
|
@@ -75,16 +65,16 @@ ${s}`}).join(`
|
|
|
75
65
|
`);}),d&&d.length>0){let f=[];d.forEach(p=>{let{plays:$,relation:g}=p;!t.relations[g].roles[$].inherited&&!p.inherited&&!f.includes(`${g}:${$}`)&&(r+=` plays ${p.relation}:${$},
|
|
76
66
|
`,f.push(`${g}:${$}`));});}r=r.replace(/,\s*$/,`;
|
|
77
67
|
`),r+=`
|
|
78
|
-
`;});let
|
|
68
|
+
`;});let o=`define
|
|
79
69
|
|
|
80
|
-
`;return
|
|
81
|
-
`;else if(s.contentType==="EMAIL")
|
|
82
|
-
`,
|
|
83
|
-
`;else if(s.contentType==="DATE")
|
|
84
|
-
`;else if(s.contentType==="BOOLEAN")
|
|
85
|
-
`;else if(s.contentType==="NUMBER")
|
|
86
|
-
`;else if(s.contentType==="FLEX")
|
|
87
|
-
`;else {if(s.contentType==="REF")return;throw new Error(`Conversion of borm schema to TypeDB schema for data type "${s.contentType}" is not implemented`)}}),`${
|
|
70
|
+
`;return mi(n).forEach(s=>{if(s.contentType==="TEXT"||s.contentType==="ID"||s.contentType==="JSON")o+=`${s.dbPath} sub attribute, value string;
|
|
71
|
+
`;else if(s.contentType==="EMAIL")o+=`${s.dbPath} sub attribute, value string,
|
|
72
|
+
`,o+=` regex '^(?=.{1,64}@)[A-Za-z0-9_-]+(\\\\.[A-Za-z0-9_-]+)*@[^-][A-Za-z0-9-]+(\\\\.[A-Za-z0-9-]+)*(\\\\.[A-Za-z]{2,})$';
|
|
73
|
+
`;else if(s.contentType==="DATE")o+=`${s.dbPath} sub attribute, value datetime;
|
|
74
|
+
`;else if(s.contentType==="BOOLEAN")o+=`${s.dbPath} sub attribute, value boolean;
|
|
75
|
+
`;else if(s.contentType==="NUMBER")o+=`${s.dbPath} sub attribute, value long;
|
|
76
|
+
`;else if(s.contentType==="FLEX")o+=`${s.dbPath} sub flexAttribute;
|
|
77
|
+
`;else {if(s.contentType==="REF")return;throw new Error(`Conversion of borm schema to TypeDB schema for data type "${s.contentType}" is not implemented`)}}),`${o}
|
|
88
78
|
|
|
89
79
|
${r}
|
|
90
80
|
#Tools, reserved for every schema using borm
|
|
@@ -100,26 +90,26 @@ flexAttribute sub attribute, abstract, value string,
|
|
|
100
90
|
owns doubleAttribute,
|
|
101
91
|
owns booleanAttribute,
|
|
102
92
|
owns datetimeAttribute;
|
|
103
|
-
`},Er=async(e,t,r,n)=>{if(!n.typeDB)throw new Error("No TypeDB handles found");let i=ki(e,r),o=n.typeDB.get(e)?.session,a=n.typeDB.get(e)?.client;if(!o){console.log("Session Status: ","NO SESSION");return}if(!a)throw new Error("No TypeDB client found");await o.close();let[{dbName:s}]=t.dbConnectors;await(await a.databases.get(s)).delete(),await a.databases.create(s);let c=await(await a.session(t.dbConnectors[0].dbName,SessionType.SCHEMA)).transaction(TransactionType.WRITE);return await c.query.define(i),await c.commit(),await c.close(),i};var Br=async(e,t,r)=>await(async()=>{let o=(await Promise.all([...r.typeDB||[]].map(async([l])=>[l,await Er(l,e,t,r)]))).map(l=>[l[0],l[1]]),s=(await Promise.all([...r.surrealDB||[]].map(async([l])=>[l,gr(t)]))).map(l=>[l[0],l[1]]);return {typeDB:Object.fromEntries(o),surrealDB:Object.fromEntries(s)}})();var Fr={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var ee=Symbol.for("queryPath"),it=Symbol.for("stepPrint"),qe=Symbol.for("edgeType"),Te=Symbol.for("edgeSchema"),_e=Symbol.for("dbNode"),Tt=Symbol.for("isTransformed"),ot=Symbol.for("parent"),ie=Symbol.for("fieldSchema"),K=Symbol.for("sharedMetadata"),Me=Symbol.for("suqlMetadata");var Mr=(e,t)=>{let r=br(e.entities),n=br(e.relations),i=Ni(e),o={entities:{},relations:{}};return r.forEach(a=>{let s=e.entities[a];if(!s)throw new Error(`Entity "${a}" does not exist`);let l="extends"in s?o.entities[s.extends]:void 0;l&&St(o,l.name,a);let h=wr({schema:e,enrichedSchema:o,extendedThing:l,name:a,thing:s,dbHandles:t,allLinkFields:i});o.entities[a]={...h,defaultDBConnector:s.defaultDBConnector,thingType:"entity"};}),n.forEach(a=>{let s=e.relations[a];if(!s)throw new Error(`Relation "${a}" does not exist`);let l="extends"in s?o.relations[s.extends]:void 0;l&&St(o,l.name,a);let h=wr({schema:e,enrichedSchema:o,extendedThing:l,name:a,thing:s,dbHandles:t,allLinkFields:i}),c={...h,defaultDBConnector:s.defaultDBConnector,roles:Object.fromEntries(Object.entries(s.roles??{}).map(([u,d])=>[u,Tr({role:d,roleName:u,relationName:a,relation:s,allExtends:h.allExtends,allLinkFields:i})])),thingType:"relation"};"extends"in s&&l&&Object.entries(l?.roles??{}).forEach(([u,d])=>{let f=Tr({role:d,roleName:u,relationName:a,relation:s,allExtends:h.allExtends,allLinkFields:i});c.roles[u]={...f,inherited:!0,[K]:{...d[K],inheritanceOrigin:d[K]?.inheritanceOrigin||s.extends}};}),o.relations[a]=c;}),Object.values(o.entities).forEach(a=>{a.linkFields?.forEach(s=>{s.$things=Mt(o,s.$things);});}),Object.values(o.relations).forEach(a=>{a.linkFields?.forEach(s=>{s.$things=Mt(o,s.$things);}),Object.values(a.roles??{}).forEach(s=>{s.$things=Mt(o,s.$things);});}),o},br=e=>{let t=[],r=new Set,n=new Set;return Object.keys(e).forEach(i=>Sr({thingMap:e,name:i,inProcess:n,seen:r,ordered:t})),t},Sr=e=>{let{thingMap:t,name:r,inProcess:n,seen:i,ordered:o}=e;if(i.has(r))return;if(n.has(r))throw new Error(`A list of thing extends each other that creates circular dependencies: ${[...n]}`);n.add(r);let a=t[r];if(!a)throw new Error(`Entity/relation "${r}" does not exist`);"extends"in a&&Sr({...e,name:a.extends}),n.delete(r),i.add(r),o.push(r);},qi=(e,t)=>{let r=t,n=[];for(;r;){let i=e.entities[r]||e.relations[r];if(!i)throw new Error(`Entity/relation "${r}" does not exist`);n.push(r),r="extends"in i?i.extends:void 0;}return n.length!==0?n:void 0},St=(e,t,r)=>{let n=e.entities[t]??e.relations[t];if(!n)throw new Error(`Entity/relation "${t}" does not exist`);n.subTypes=n.subTypes??[],n.subTypes.push(r),n.extends&&St(e,n.extends,r);},wr=e=>{let{schema:t,enrichedSchema:r,name:n,thing:i,dbHandles:o,extendedThing:a,allLinkFields:s}=e,[l]=Object.entries(o).find(([p,$])=>$.get(i.defaultDBConnector.id))??[];if(!l)throw new Error(`DB handle for ${i.defaultDBConnector.id} does not exist`);let h=[...i.idFields??a?.idFields??[]];if(h.length===0)throw new Error(`"${n}" does not have an id field`);let c={...i.hooks},u=i.dataFields?.map(p=>Pi(p,n,h))??[],d=i.linkFields?.map(p=>ji({linkField:p,thingName:n,thing:i,schema:t,allLinkFields:s}))??[],f=Object.fromEntries(Object.entries(i.refFields??{}).map(([p,$])=>[p,xi($,p)]));return "extends"in i&&a&&(a.hooks?.pre&&(c.pre=[...a.hooks.pre||[],...i.hooks?.pre||[]]),a.dataFields?.forEach(p=>{u.push({...p,inherited:!0,[K]:{...p[K],inheritanceOrigin:p[K]?.inheritanceOrigin||i.extends}});}),a.linkFields?.forEach(p=>{d.push({...p,inherited:!0,[K]:{...p[K],inheritanceOrigin:p[K]?.inheritanceOrigin||i.extends}});}),Object.entries(a.refFields??{}).forEach(([p,$])=>{f[p]={...$,inherited:!0,[K]:{...$[K],inheritanceOrigin:$[K]?.inheritanceOrigin||i.extends}};})),{...i,name:n,db:l,dbContext:Fr[l],idFields:h,hooks:c,dataFields:u,linkFields:d,refFields:f,enumFields:u?.filter(p=>p.validations?.enum).map(p=>p.path)??[],fnValidatedFields:u?.filter(p=>p.validations?.fn).map(p=>p.path)??[],virtualFields:u?.filter(p=>p.isVirtual).map(p=>p.path)??[],computedFields:u?.filter(p=>p.default&&!p.isVirtual).map(p=>p.path)??[],requiredFields:u?.filter(p=>p.validations?.required).map(p=>p.path)??[],allExtends:"extends"in i?qi(r,i.extends):void 0,dbProviderConfig:l==="surrealDB"?o[l]?.get(i.defaultDBConnector.id)?.providerConfig:void 0}},Ni=e=>{let t=[];return Object.entries(e.entities).forEach(([r,n])=>{n.linkFields?.forEach(i=>{t.push({...i,thing:r,thingType:"entity",pathToRelation:i.target==="relation"?i.path:i.relation.toLocaleLowerCase()});});}),Object.entries(e.relations).forEach(([r,n])=>{n.linkFields?.forEach(i=>{t.push({...i,thing:r,thingType:"relation",pathToRelation:i.target==="relation"?i.path:i.relation.toLocaleLowerCase()});});}),t},Pi=(e,t,r)=>({...e,cardinality:e.cardinality||"ONE",dbPath:"dbPath"in e&&typeof e.dbPath=="string"?e.dbPath:_i(t,e.path,e.shared),isIdField:!!r?.includes(e.path),inherited:!1,[K]:{fieldType:"dataField"},[Me]:{dbPath:e.path}}),xi=(e,t)=>({...e,cardinality:e.cardinality||"ONE",path:t,dbPath:e.dbPath||t,inherited:!1,[K]:{fieldType:"refField"}}),ji=e=>{let{linkField:t,thing:r,thingName:n,schema:i,allLinkFields:o}=e,a=i.relations[t.relation];if(!t.isVirtual){if(!a)throw new Error(`The relation ${t.relation} does not exist in the schema`);if(!Lr(i,t.relation,t.plays))throw new Error(`The role ${t.plays} is not defined in the relation ${t.relation} (linkField: ${t.path})`)}let s=t.cardinality==="MANY"?`$parent.[\`${t.path}\`]`:`$parent.\`${t.path}\``;if(t.target==="relation"){if(t.isVirtual)throw new Error(`[Schema] Virtual linkFields can't target a relation. Thing: "${n}" LinkField: "${t.path}."`);return {...t,$things:[t.relation],oppositeLinkFieldsPlayedBy:[{plays:t.path,thing:t.relation,thingType:"relation"}],fieldType:"linkField",inherited:!1,[K]:{fieldType:"linkField"},[Me]:{queryPath:s}}}let l=o.filter(h=>h.relation===t.relation&&h.plays!==t.plays&&h.target==="role");if(l.length===0)throw new Error(`[Schema] LinkFields require to have at least one opposite linkField playing an opposite role. Thing: "${n}" LinkField: "${t.path}."`);return l.length>1&&console.warn(`[Schema] LinkField ${t.path} in ${n} has multiple candidates ${l.map(h=>h.thing).join(",")} and this is not yet supported. Please target a single one using targetRoles with a single role`),{...t,fieldType:"linkField",pathToRelation:r.linkFields?.find(h=>h.target==="relation"&&h.relation===t.relation)?.path??t.relation.toLocaleLowerCase(),inherited:!1,$things:l.map(h=>h.thing),oppositeLinkFieldsPlayedBy:l,[K]:{fieldType:"linkField"},[Me]:{queryPath:s}}},Tr=e=>{let{role:t,roleName:r,relationName:n,relation:i,allExtends:o,allLinkFields:a}=e;if(i.dataFields?.find(h=>h.path===r)||i.linkFields?.find(h=>h.path===r))throw new Error(`[Schema] The path ${r} is already in use by a dataField or linkField in ${n}.`);let s=a.filter(h=>h.relation===n&&h.plays===r),l=a.filter(h=>h.target==="relation"&&h.plays===r&&o?.includes(h.relation));return {...t,fieldType:"roleField",inherited:!1,playedBy:s.map(h=>({...h,pathToRelation:h.target==="relation"?h.path:i.linkFields?.find(c=>c.target==="relation"&&c.relation===r&&c.plays===r)?.path??h.relation.toLocaleLowerCase()})),impactedLinkFields:l,path:r,$things:[...new Set(s.map(h=>h.thing))],[K]:{fieldType:"roleField"},[Me]:{queryPath:t.cardinality==="MANY"?`$parent.[\`${r}\`]`:`$parent.\`${r}\``}}},_i=(e,t,r)=>r?t:`${e}\xB7${t}`,Lr=(e,t,r)=>{let n=e.relations[t];if(!n)throw new Error(`Relation "${t}" does not exist`);return n.roles?.[r]?!0:"extends"in n?Lr(e,n.extends,r):!1},Mt=(e,t)=>t.flatMap(r=>[r,...(e.entities[r]??e.relations[r])?.subTypes??[]]);var Rr=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,n])=>t(r,n))))[0],ce=(e,t)=>{let r=Reflect.ownKeys(e).map(n=>[n,e[n]]);return Object.fromEntries(r.filter(([n,i])=>{let[o,a]=tryit(()=>t(n,i))();return o?!1:a}))},Y=(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`)},j=(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)}`)},st=(e,t)=>{let r=e.dataFields?.find(o=>o.path===t);if(e.idFields?.includes(t)){if(!r)throw new Error(`Field ${t} is an idField but not a dataField in schema`);return ["idField",r]}if(r)return ["dataField",r];let n=e.linkFields?.find(o=>o.path===t);if(n)return ["linkField",n];let i="roles"in e?e.roles[t]:void 0;if(i)return ["roleField",i];throw new Error(`Field ${t} not found in schema, Defined in $filter`)},at=(e,t)=>{let r=j(e,t);if(r?.idFields?.length&&r?.idFields?.length>1)throw new Error(`Multiple ids not yet enabled / composite ids: ${r?.idFields}`);let[n]=r.idFields;return n},Dr=(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")},Qt=(e,t,r)=>{let n=j(e,t),i=n.linkFields?.find(l=>l.path===r);if(i)return i;let o=n.dataFields?.find(l=>l.path===r);if(o)return o;let a="roles"in n?n.roles?.[r]:void 0;if(a)return a;let s="refFields"in n?n.refFields?.[r]:void 0;if(s)return s;throw new Error(`Field ${r} not found in schema`)},Rt=(e,t,r)=>Qt(e,t,r)?.cardinality,de=(e,t)=>{let r=e.dataFields?.map($=>$.path)||[],n=e.linkFields?.map($=>$.path)||[],i="refFields"in e?listify(e.refFields,$=>$):[],o="roles"in e?listify(e.roles,$=>$):[],a=[...r||[],...n||[],...o||[],...i||[]],l=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...a];if(!t)return {fields:a,dataFields:r,roleFields:o,linkFields:n};let h=t.$fields?t.$fields.map($=>{if(typeof $=="string"){if($.startsWith("$")||$.startsWith("%"))return;if(!a.includes($))throw new Error(`Field ${$} not found in the schema`);return $}if("$path"in $&&typeof $.$path=="string")return $.$path;throw new Error("[Wrong format] Wrongly structured query")}):listify(t,$=>{if(!($.startsWith("$")||$.startsWith("%"))){if(!a.includes($))throw new Error(`[Schema] Field ${$} not found in the schema`);return $}}).filter($=>$!==void 0),c=t.$filter?listify(t.$filter,$=>$.toString().startsWith("$")?void 0:$.toString()).filter($=>$&&r?.includes($)):[],u=t.$filter?listify(t.$filter,$=>$.toString().startsWith("$")?void 0:$.toString()).filter($=>$&&[...o||[],...n||[]].includes($)):[],d=[...h,...c].filter($=>!$?.startsWith("%")).filter($=>!l.includes($)).filter($=>$),f=t.$filter?ce(t.$filter,($,g)=>c.includes($)):{},p=t.$filter?ce(t.$filter,($,g)=>u.includes($)):{};return {fields:a,dataFields:r,roleFields:o,linkFields:n,refFields:i,usedFields:h,usedLinkFields:n.filter($=>h.includes($)),usedRoleFields:o.filter($=>h.includes($)),usedDataFields:r.filter($=>h.includes($)),usedRefFields:i.filter($=>h.includes($)),unidentifiedFields:d,...c.length?{localFilters:f}:{},...u.length?{nestedFilters:p}:{}}};var Ir=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},Or=(e,t,r)=>{let i=(r.nodePath||"").split("."),o=isArray(t)?i.slice(0,-2).join("."):i.slice(0,-1).join(".");return t?getNodeByPath(e,o):{}},De=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var lt=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),Se=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(([n,i])=>{r[n]=isDraft(i)?current(i):i;}),r}return e},$e=(e,t)=>{if(e===void 0)throw new Error("Value is undefined");return e},L=(e,t)=>{let r="";for(let n=0;n<t;n++)r+=" ";return `${r}${e}`},Ie=e=>customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",21)();var Ar=(e,t)=>{for(let i of e)if(!("$entity"in i)&&!("$relation"in i)&&(!("$thing"in i)||!("$thingType"in i)))throw new Error("No entity specified in query");let r=Array.isArray(e)?e:[e];return produce(r,i=>traverse(i,o=>{let{value:a,meta:s}=o,l=a;if(isObject(l)){if(s.nodePath?.includes(".$filter")||s.nodePath?.includes(".$playedBy"))return;if(l[ee]=s.nodePath,l.$id){let h=l.$entity||l.$relation?l:{[`$${l.$thingType}`]:l.$thing},c=j(t,h);if(!c?.name)throw new Error(`Schema not found for ${l.$thing}`);if(l.$path=c.name,Array.isArray(l.$id)||(l.$filterByUnique=!0),c.idFields.length===1){let[u]=c.idFields;l.$filter={...l.$filter,[u]:l.$id},l.$id=void 0;}else throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in l||"$relation"in l||"$thing"in l){let h=j(t,l);if(!h?.name)throw new Error(`Schema not found for ${l.$thing}`);l.$path=h.name;}if(l.$entity?(l.$thing=l.$entity,l.$thingType="entity",l.$entity=void 0):l.$relation&&(l.$thing=l.$relation,l.$thingType="relation",l.$relation=void 0),isObject(l)&&"$thing"in l&&l.$thing){let h=l.$entity||l.$relation?l:{[`$${l.$thingType}`]:l.$thing},c=j(t,h);if(l.$filter&&(Object.keys(l.$filter).length===0?l.$filter=void 0:(l.$filter=Oe(l.$filter,l.$thing,t),l.$filterByUnique=It(l.$filter,c))),l.$fields){l.$fields.some(f=>c?.idFields?.includes(f?.$path||f))||(l.$fields=[...l.$fields,...Array.isArray(c.idFields)?c.idFields:[]],l.$idNotIncluded=!0);let d=l.$fields?.flatMap(f=>{let p=Cr(f,c,t);return Array.isArray(p)?p:[p]}).filter(Boolean);l.$fields=d;}else {let d=Dt(c)?.flatMap(f=>{let p=Cr(f,c,t);return Array.isArray(p)?p:[p]}).filter(Boolean);l.$fields=d;}l.$excludedFields&&(l.$fields=l.$fields.filter(u=>ct(c,u)?!0:!l.$excludedFields.includes(u.$path)));}}}))},Dt=e=>{let t=e.dataFields?.map(a=>a.path)||[],r=e.linkFields?.map(a=>a.path)||[],n=Object.keys(e.roles||{})||[],i=Object.keys(e.refFields||{})||[];return [...t,...r,...n,...i]},It=(e,t)=>Object.keys(e||{}).some(n=>{let i=e[n];if(i!==null&&typeof i<"u"){let o=t.idFields?.includes(n),a=t.dataFields?.some(h=>(h.dbPath===n||h.path===n)&&h?.validations?.unique),s=n==="$id"&&!Array.isArray(i);if(o||a||s){if(typeof i!="object"||i===null||Array.isArray(i))return !Array.isArray(i);let h=Object.keys(i);if(h.length===1&&h[0]==="$eq"){let c=i.$eq;if(typeof c!="object"||c===null||!Array.isArray(c))return !0}return !1}}return !1}),ct=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),Ji=e=>{let{field:t,fieldStr:r,$justId:n,dbPath:i,isVirtual:o,fieldSchema:a}=e;return {$path:r,$dbPath:i,$thingType:"attribute",$as:t.$as||r,$var:r,$fieldType:"data",$justId:n,$id:t.$id,$isVirtual:o,[ie]:a}},Yi=e=>{let{field:t,fieldStr:r,linkField:n,$justId:i,dbPath:o,schema:a,fieldSchema:s}=e,{target:l,oppositeLinkFieldsPlayedBy:h}=n;return h.map(c=>{let u=l==="role"?c.thingType:"relation",d=l==="role"?c.thing:n.relation,f={[`$${u}`]:d},p=j(a,f),$=t?.$fields?.filter(m=>ct(p,m)).length===0,g=[];if(typeof t!="string")if(t.$fields)if($){let m=p.idFields||[];g=[...t.$fields,...m];}else g=t.$fields;else g=Dt(p);else g=["id"];t.$excludedFields&&(g=g.filter(m=>ct(p,m)?!0:!t.$excludedFields.includes(m.$path)));let y=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...t.$filter}:void 0;return {$thingType:u,$plays:n.plays,$playedBy:{...c,oppositeLinkFieldsPlayedBy:void 0},$path:c.path,$dbPath:o,$as:t.$as||r,$var:r,$thing:d,$fields:g,$excludedFields:t.$excludedFields,$fieldType:"link",$target:l,$intermediary:c.relation,$justId:i,$id:t.$id,$filter:y,$idNotIncluded:$,$filterByUnique:It(t.$filter,p),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ie]:s}})},Xi=e=>{let{field:t,fieldStr:r,$justId:n,dbPath:i,fieldSchema:o}=e;if("$filter"in e)throw new Error("Filter not supported in ref fields");return {$path:r,$dbPath:i,$contentType:o.contentType,$as:t.$as||r,$var:r,$fieldType:"ref",$justId:n,$fields:t.$fields,$id:t.$id,[ie]:o}},Gi=e=>{let{field:t,fieldStr:r,roleField:n,$justId:i,dbPath:o,schema:a,fieldSchema:s}=e;return n.playedBy.map(l=>{let{thing:h,thingType:c,relation:u}=l,d={[`$${c}`]:h},f=j(a,d),p=t?.$fields?.filter(y=>f?.idFields?.includes(y)||f?.idFields?.includes(y.$path)).length===0,$=[];if(typeof t!="string")if(t.$fields)if(p){let y=f.idFields||[];$=[...t.$fields,...y];}else $=t.$fields;else $=Dt(f);else $=["id"];t.$excludedFields&&($=$.filter(y=>ct(f,y)?!0:!t.$excludedFields.includes(y.$path)));let g=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...t.$filter}:void 0;return {$thingType:c,$path:r,$dbPath:o,$as:t.$as||r,$var:r,$thing:h,$fields:$,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:u,$justId:i,$id:t.$id,$filter:g,$idNotIncluded:p,$filterByUnique:It(t.$filter,f),$playedBy:{...l,oppositeLinkFieldsPlayedBy:void 0},$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ie]:s}})},Cr=(e,t,r)=>{let n=typeof e=="string"?e:e.$path,i=typeof e=="string",o=t.dataFields?.find(h=>h.path===n),a=t.linkFields?.find(h=>h.path===n),s=t.roles?.[n],l=t.refFields?.[n];if(o){let h=!!o.isVirtual&&!!o.default;return Ji({field:e,fieldStr:n,$justId:i,dbPath:o.dbPath,isVirtual:h,fieldSchema:o})}return a?Yi({field:e,fieldStr:n,linkField:a,$justId:i,dbPath:a.path,schema:r,fieldSchema:a}):s?Gi({field:e,fieldStr:n,roleField:s,$justId:i,dbPath:n,schema:r,fieldSchema:s}):l?Xi({field:e,fieldStr:n,$justId:i,dbPath:n,isVirtual:!1,fieldSchema:l}):null},Oe=(e,t,r)=>{if(e==null)return e;let n=isArray(e),o=(n?e:[e]).map(a=>Object.keys(a).reduce((h,c)=>{let u=a[c],d=isArray(u)?u:[u];if(c.startsWith("$"))if(["$id","$thing"].includes(c))h[c]=u;else if(["$not","$or","$and"].includes(c))h[c]=Oe(u,t,r);else if(["$eq","$in","$exists"].includes(c))h[c]=u;else throw new Error(`[Internal] Unknown filter operator ${c}`);else {let f=t in r.entities?r.entities[t]:r.relations[t],[p,$]=st(f,c);if(p==="idField")h[c]=u;else if(p==="dataField")isObject(u)||isArray(u)&&u.some(isObject)?h[c]=isArray(u)?{$or:Oe(u,t,r)}:Oe(u,t,r):isArray(u)?h[c]={$in:u}:h[c]={$eq:u};else if(p==="linkField"||p==="roleField"){let g=$,[y]=g.$things;d.every(m=>typeof m=="string")?h[c]={$id:d,$thing:y}:d.every(m=>isObject(m))&&(h[c]=isArray(u)?{$or:Oe(u,y,r)}:Oe(u,y,r));}else throw new Error(`Field ${c} not found in schema of ${t}`)}return h},{}));return !n||o.length===1?o[0]:{$or:o}};var eo=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,to=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,kr=e=>{let r=e.toString().replace(eo,"").trim().split("=>")[0].split("{")[0].replace(to,"").trim(),n=r.substring(r.indexOf("(")+1,r.lastIndexOf(")")).trim();return n?(n.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(o=>o.includes("{")&&o.includes("}")?(o.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(s=>s.split(":")[0].trim().replace(/['"[\]]/g,"")):o.trim()).filter(Boolean):[]};var ve=({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:n}=t.default,o=kr(n).filter(a=>!(a in e));if(o.length)throw new Error(`Virtual field: Missing arguments ${o.join(", ")}`)}if(!t.default.fn)throw new Error("[Schema] No fn in default field schema");if("default"in t){if(t.default.type==="value")return t.default.value;if(t.default.type==="fn")return t.default.fn(e);throw new Error("[Schema] No default field definition")}};var qr=(e,t,r)=>{let n=e[t];if(n)return (isArray(n)?n:[n]).forEach(i=>{if(i.$op!=="create")return;let o=j(r,i),{unidentifiedFields:a}=de(o,i),{computedFields:s,virtualFields:l}=o,h=listify(i,(d,f)=>f!==void 0?d:void 0),c=h.filter(d=>l?.includes(d));if(c.length>0)throw new Error(`Virtual fields can't be sent to DB: "${c.join(",")}"`);if(s.filter(d=>!h.includes(d)).forEach(d=>{let f=o.dataFields?.find(m=>m.path===d),$=o.linkFields?.find(m=>m.path===d)?.oppositeLinkFieldsPlayedBy[0],g="roles"in o?Rr(o.roles,(m,F)=>m===d):void 0,y=f||$||g;if(!y)throw new Error(`no field Def for ${d}`);if(!i[d]){let m=ve({currentThing:i,fieldSchema:y,mandatoryDependencies:!0});i[d]=m;}}),a.length>0)throw new Error(`Unknown fields: [${a.join(",")}] in ${JSON.stringify(i)}`)}),e};var Ot=(e,t)=>e.$bzId?e.$bzId:e.$tempId?e.$tempId:e.$id&&!isArray(e.$id)?t?`SN_ONE_${t}_${e.$id}`:`SN_ONE_${e.$id}`:e.$id&&isArray(e.$id)?t?`SN_MANY_${t}_${Ie()}`:`SN_MANY_${Ie()}`:`SM_${Ie()}`;var Ce=(e,t,r)=>{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`);let n=j(r,t),{usedDataFields:i}=de(n,t);if(t.$op==="delete"&&i.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&i.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}},Pr=(e,t,r)=>{(isArray(t)?t:[t]).forEach(i=>{Ce(e,i,r);});};var xr=e=>{let t=Object.keys(e).filter(r=>!(r.startsWith("$")||r.startsWith("%")));return e.$op?e.$op:e.$id||e.$filter?t.length>0?"update":"link":e.$tempId?t.length>0?"create":"link":"create"},jr=(e,t,r)=>{let n=j(r,t),{usedFields:i}=de(n,t);return t.$op?(Ce(e,t,r),t.$op):t.$id||t.$filter?i.length>0?(Ce(e,{...t,$op:"update"},r),"update"):(Ce(e,{...t,$op:"link"},r),"link"):t.$tempId?i.length>0?(Ce(e,{...t,$op:"create"},r),"create"):(Ce(e,{...t,$op:"create"},r),"link"):(Ce(e,{...t,$op:"create"},r),"create")};var dt=(e,t)=>{if(t[K].fieldType==="linkField"){let n=t.oppositeLinkFieldsPlayedBy;if(n?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!n?.length)throw new Error(`[Internal] Field ${e} should have a player`);return n}if(t[K].fieldType==="roleField"){let r=t;if([...new Set(r.playedBy?.map(n=>n.thing))].length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!r.playedBy?.length)throw new Error(`[Internal] Field ${e} should have a player`);return r.playedBy}throw new Error(`[Internal] Field ${e} is not a linkField or roleField`)};var _r=(e,t,r,n)=>{let i=(isArray(e[t])?e[t]:[e[t]]).flatMap(o=>{if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);let a=xr(o),s=Ot(o);if(r[K].fieldType==="refField"){let c=r;if(!isObject(o)){if(c.contentType==="FLEX")return o;throw new Error(`[Wrong format] The refField ${t} must receive an object`)}if(!o.$thing)throw new Error("[Wrong format] The field $thing is required in refFields");return {...o,$op:a,$bzId:s}}let l=r;if(l.$things.length===0)throw new Error(`[Internal error] The field ${t} can't be played by any thing.`);let h=r;if(h.$things.length===1){let c=dt(t,l),[u]=c;if(o.$thing&&o.$thing!==u.thing)throw new Error(`[Wrong format] The field ${t} can only be played by ${u.thing}.`);return {...o,[Te]:h,$thing:u.thing,$thingType:u.thing in n.entities?"entity":"relation",$op:a,$bzId:s}}if(h.$things.length>1){if(o.$thing)return [{...o,[Te]:h,$thing:o.$thing,$thingType:o.$thing in n.entities?"entity":"relation",$op:a,$bzId:s}];if(!o.$thing){if(o.$tempId)throw new Error("[Unsupported] Objects with $tempId and multiple potential players require to explicitly indicate the $thing type.");if(a==="create")throw new Error(`[Wrong format] The field ${t} can be played by multiple things, please specify one on creation.`);return h.$things.map(c=>({...o,[Te]:h,$thing:c,$thingType:c in n.entities?"entity":"relation",$op:a,$bzId:Ot(o,c)}))}}});isArray(e[t])||i.length>1?e[t]=i:e[t]=i[0],e[t]=isArray(e[t])?i:i[0];};var ut=(e,t)=>{let r=j(t,e).hooks;if(r?.pre){let n=`on${Ir(e.$op)}`;return r.pre.filter(a=>!a.triggers||a.triggers[n]?.()).flatMap(a=>a.actions)}return []};var zr=(e,t,r,n)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(o=>{if(!lt(o)||o.$fields||o[Tt])return;let a=ut(o,r).filter(u=>u.type==="transform"),s=clone(Se(e)),l=clone(Se(o)),h=n.mutation?.context||{},c=clone(Se(o[_e]||o.$dbNode));a.forEach(u=>{let d=u.fn(l,s,h,c||{});Object.keys(d).length!==0&&(l={...l,...d,...De(o),[Tt]:!0},Object.assign(o,l));});});};var Ur=(e,t,r,n)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(o=>{if("$thing"in o){if(o.$fields)return o;let{requiredFields:a,enumFields:s,fnValidatedFields:l,dataFields:h}=j(r,o);if("$op"in o&&o.$op==="create"&&a.forEach(c=>{if(!(c in o))throw new Error(`[Validations] Required field "${c}" is missing.`)}),("$op"in o&&o.$op==="update"||o.$op==="create")&&s.forEach(c=>{if(c in o){let u=h?.find(d=>d.path===c)?.validations?.enum;if(!u)throw new Error(`[Validations] Enum field "${c}" is missing enum options.`);if(isArray(o[c]))o[c].some(d=>{if(d!==null&&!u.includes(d))throw new Error(`[Validations] Option "${d}" is not a valid option for field "${c}".`)});else if(u&&!u.includes(o[c])&&o[c]!==null)throw new Error(`[Validations] Option "${o[c]}" is not a valid option for field "${c}".`)}}),("$op"in o&&o.$op==="update"||o.$op==="create")&&l.forEach(c=>{if(c in o)try{let u=h?.find(d=>d.path===c)?.validations?.fn;if(!u)throw new Error("Missing validation function.");if(!u(o[c]))throw new Error("Failed validation function.")}catch(u){throw new Error(`[Validations:attribute:${c}] ${u.message}`)}}),isObject(o)&&"$thing"in o){let c=o.$thing,u=o,d=clone(Se(e)),f=clone(Se(u)),p=n.mutation?.context||{},$=clone(Se(o[_e]||{}));ut(u,r).forEach(y=>{if(y.type==="validate"){if(y.severity!=="error")return;try{let m=y.fn(f,d,p,$);if(m===!1)throw new Error(`${y.message}.`);if(m!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(m){throw new Error(`[Validations:thing:${c}] ${m.message}`)}}});}}});};var Wr=(e,t,r,n)=>{let i=isArray(e[t])?e[t]:[e[t]],o=n.slice(1).join(".");i.forEach(a=>{if(a){if(r?.cardinality==="ONE"&&!a.$op&&!a.$id&&!a.$filter&&!a.$tempId&&e.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${o}.${t}`);if(a.$tempId&&!(a.$op===void 0||a.$op==="link"||a.$op==="create"||a.$op==="update"||a.$op==="replace"))throw new Error(`Invalid op ${a.$op} for tempId. TempIds can be created, or linked when created in another part of the same mutation.`)}});};var Hr=e=>{if(typeof e!="string")return {isPrefixed:!1,obj:e};let t=e.match(/^([^:]+):([^:].*)$/);if(t){let[,r,n]=t;return {isPrefixed:!0,obj:{$thing:r,...n.startsWith("_:")?{$tempId:n}:{$id:n}}}}return {isPrefixed:!1,obj:e}},Kr=(e,t)=>{let r=isArray(e[t])?e[t]:[e[t]];if(r.every(i=>typeof i=="object"))return;if(!r.every(i=>typeof i=="string"||isObject(i)&&"$op"in i&&i.$op==="replace"))throw new Error(`[Mutation Error] Replace can only be used with a single id, an array of ids, or objects with $op: replace. (Field: ${t} Nodes: ${JSON.stringify(r)})`);let n=e.$op==="create"?"link":"replace";e[t]=r.map(i=>{if(typeof i=="string"){if(i.startsWith("_:"))return {$tempId:i,$op:n};let{isPrefixed:o,obj:a}=Hr(i);return o?{...a,$op:n}:{$id:i,$op:n}}return i});},Jr=(e,t,r)=>{let n=isArray(e[t])?e[t]:[e[t]],i=e.$op==="create"?"link":"replace";return e[t]=n.map(o=>{if(typeof o=="string"){if(o.startsWith("_:"))return {$tempId:o,$op:i};let{isPrefixed:a,obj:s}=Hr(o);if(a)return {...s,$op:i};if(r.contentType==="FLEX")return o;throw new Error("[Wrong format] Field of contentType REF can't use strings as references unless they follow the format `$thing:$id`")}if(typeof o=="object"&&"$thing"in o||r.contentType==="FLEX")return o;throw new Error("[Wrong format] Field of contentType REF can use prefixed id strings, tempIds or objects indicating their $thing")}),e[t]};var Xr=(e,t)=>{let n=(isArray(e.$root)?e.$root:[e.$root]).map(i=>{let o=jr(i,i,t);return {...{...i.$thing?{}:{$thing:i.$entity||i.$relation},...i.$thingType?{}:{$thingType:Dr(i,t)},...i.$op?{}:{$op:o},...i.$bzId?{}:{$bzId:`R_${Ie()}`}},...i}});e.$root=isArray(e.$root)?n:n[0];};var ht=(e,t)=>{let r=t[it];return isSet(r)?r.has("clean")?(Reflect.set(t,it,r.add("clean")),!0):!1:(Reflect.set(t,it,new Set(["clean"])),!0)};var Gr=(e,t,r)=>{if(ht("split_ids",e)){let n=(isArray(e[t])?e[t]:[e[t]]).flatMap(i=>{if(isObject(i)&&"$id"in i&&isArray(i.$id)){let o=i;if(j(r,o),!o.$bzId)throw new Error("[Internal Error] No bzId found");return o.$id.map((a,s)=>({...Se(o),$id:a,$bzId:`${o.$bzId}_${s}`,...De(o)}))}return i});(n.length>0&&isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=n);}};var Zr=(e,t,r)=>{let n=dt(t,r),[i]=n;e[t]={$thing:i.thing,$thingType:i.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Te]:r};};var Ue=e=>{if(Array.isArray(e)){for(let t of e)if(Ue(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"&&Ue(e[t]))return !0}return !1};var Eo=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(ht("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");t==="$filter"&&e.$filter&&Object.keys(e.$filter).length===0&&(e.$filter=void 0);},Bo=(e,t)=>{},Nt=(e,t,r)=>{let n={$rootWrap:{$root:e}},i=Ue(Array.isArray(e)?e:[e]),o=produce(n,a=>traverse(a,({value:s,parent:l,key:h,meta:c})=>{if(!(!l||!h)&&isObject(s)){let u=c.nodePath?.split(".")||[];if(u.some(p=>p.startsWith("%")))return;if(!("$root"in s)){if(!("$thing"in s||"$entity"in s||"$relation"in s)){let p=["$fields","$dbNode","$filter"],$=u.at(-1),g=u.at(-2);if(h==="$root")throw new Error("Root things must specify $entity or $relation");if(!p.includes($||"")&&!p.includes(g||"")&&!$?.startsWith("%")&&!g?.startsWith("%"))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(s)?current(s):s)}`)}}let d=s,f=u.includes("$filter");"$filter"in d&&d.$filter&&(d.$filter=Oe(d.$filter,d.$thing,t)),Object.keys(d).forEach(p=>{if(Eo(d,p),p!=="$root"&&f||p!=="$root"&&(p.startsWith("$")||p.startsWith("%")))return;let $=p!=="$root"?Qt(t,d,p):{[K]:{fieldType:"rootField"}};if(!$)throw new Error(`[Internal] Field ${p} not found in schema`);let{fieldType:g}=$[K],y=["linkField","roleField"].includes(g),m=g==="refField",F=g==="rootField";if(g==="dataField")return Bo();if((y||m)&&(d[p]===null?y&&Zr(d,p,$):y?Kr(d,p):Jr(d,p,$)),F){if(!("$root"in d))throw new Error(`[Internal] Field ${p} is a rootField but the object is not a root`);Xr(d,t);}(y||m)&&Wr(d,p,$,u),(y||m)&&(_r(d,p,$,t),Pr(d,d[p],t)),(y||F)&&(Gr(d,p,t),qr(d,p,t),(isArray(d[p])?d[p]:[d[p]]).forEach(Q=>{let M=j(t,Q),{unidentifiedFields:R,usedLinkFields:I,usedFields:x,fields:J}=de(M,Q);if(x.forEach(re=>{if(!J.includes(re))throw new Error(`[Schema] Field ${re} not found in the schema`)}),R.length>0)throw new Error(`Unknown fields: [${R.join(",")}] in ${JSON.stringify(s)}`);if(I.length>1){let re=M.linkFields?.filter(fe=>I.includes(fe.path));re?.some((fe,A)=>re.some((D,S)=>{if(A!==S&&fe.target!==D.target&&fe.relation===D.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),i||(zr(d,p,t,r),Ur(d,p,t,r)));});}}));return isArray(o.$rootWrap.$root),o.$rootWrap.$root};var tn=e=>{let t=({value:r})=>(r&&typeof r=="object"&&"$id"in r&&(Object.keys(r).filter(o=>o.startsWith("$")).forEach(o=>delete r[o]),Object.keys(r).filter(o=>typeof o=="symbol").forEach(o=>delete r[o])),r);return produce(e,r=>traverse(r,t))};var sn=async(e,t)=>{let r=c=>{let u=[],d=[],f=y=>{if(y.$id)return y.$id;let m=j(t,y),{idFields:F}=m;if(!F)throw new Error(`no idFields: ${JSON.stringify(y)}`);let[E]=F;if(!E)throw new Error(`no idField: ${JSON.stringify(y)}`);let Q=m.dataFields?.find(I=>I.path===E),M=ve({currentThing:y,fieldSchema:Q,mandatoryDependencies:!0}),R=y[E]||y.$id||M;if(!R)throw new Error(`no idValue: ${JSON.stringify(y)}`);return R},p=y=>{if(y.$op==="create"){let m=f(y);if(u.find(F=>F.$id===m&&F.$op==="create"))throw new Error(`Duplicate id ${m} for node ${JSON.stringify(y)}`);u.push({...y,$id:m});return}y.$tempId&&y.$op==="match"||u.push(y);},$=y=>{if(y.$op==="create"){let m=f(y);if(u.find(F=>F.$id===m&&F.$op==="create"))throw new Error(`Duplicate id ${m} for edge ${JSON.stringify(y)}`);d.push({...y,$id:m});return}d.push(y);};return traverse(c,({value:y,parent:m,meta:F})=>{if(!isObject(y))return;let E=y;if(!F.nodePath?.includes(".$filter")&&E.$thing){if(!E.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(E)}`);if(!E.$bzId)throw new Error(`[internal error] BzId not found ${JSON.stringify(E)}`);let Q=j(t,E),{dataFields:M,roleFields:R,linkFields:I,refFields:x,usedFields:J}=de(Q,E),re=()=>{if(E.$op==="create"||E.$op==="delete")return E.$op;if(E.$op==="update"){let D=J.filter(T=>M?.includes(T)),S=J.filter(T=>R?.includes(T)),b=J.filter(T=>I?.includes(T)),B=J.filter(T=>x?.includes(T));if(D.length>0)return "update";if(S.length>0||b.length>0||B.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(E)}`)}return "match"},fe={...E.$id&&{$id:E.$id},...E.$tempId&&{$tempId:E.$tempId},...E.$filter&&{$filter:E.$filter},$thing:E.$thing,...E.$thingType&&{$thingType:E.$thingType},...shake(pick(E,M||[""])),$op:re(),$bzId:E.$bzId};p(fe);let A=E[Te];if(A?.[K].fieldType==="linkField"){if((E.$op==="link"||E.$op==="unlink")&&(E.$id||E.$filter)){if(E.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");u.push({...E,$op:"match"});}let D=A.$things.includes(E.$thing),S=D?E.$bzId:`LT_${v4()}`,B=Or(c,m,F).$bzId;if(!B)throw new Error("No parent id found");let T=()=>E.$op==="delete"?D?"match":"delete":E.$op==="unlink"?D?"unlink":"delete":E.$op==="link"||E.$op==="create"?D?"link":"create":E.$op==="replace"?"replace":"match",w=j(t,{$thing:A.relation,$thingType:"relation"});if(!Object.keys(w.roles).includes(A.plays))throw new Error(`[Wrong format] Field ${A.plays} is not a role of relation ${A.relation}`);let N={$bzId:S,$thing:D?E.$thing:A.relation,$thingType:"relation",...E.$tempId?{$tempId:E.$tempId}:{},$op:T(),...D?{}:{[A.path]:E.$bzId},[A.plays]:B,[Te]:A,[qe]:"linkField"};$(N),(E.$op==="unlink"||T()==="unlink")&&D&&$({$thing:A.relation,$thingType:"relation",$bzId:S,$op:"match",[A.plays]:B,[Te]:A,[qe]:"linkField"});}if(E.$thingType==="relation"){let D=ce(E,(B,T)=>R.includes(B)),S=mapEntries(D,(B,T)=>isArray(T)?[B,T]:isObject(T)?[B,T.$bzId]:[B,T]),b=ce(y,(B,T)=>B.startsWith("$")||B.startsWith("Symbol"));if(Object.keys(D).filter(B=>!B.startsWith("$")).length>0){if(E.$op==="create"||E.$op==="delete"){let B=()=>{if(E.$op==="create")return "link";if(E.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},T=j(t,E).roles,w=mapEntries(S,(N,q)=>{let C=T[N]?.cardinality;if(!C)throw new Error(`Role ${N} not found in schema`);return Array.isArray(q)?C==="ONE"?q.length>1?[N,q.map(V=>V.$bzId||V)]:[N,q[0].$bzId||q[0]]:[N,q.map(V=>V.$bzId||V)]:[N,q.$bzId||q]}),O={...b,$thing:E.$thing,$thingType:"relation",$op:B(),...w,$bzId:E.$bzId,[qe]:"roleField"};$(O);return}if(E.$op==="match"||E.$op==="update"&&Object.keys(D).length>0){let B=0;Object.entries(D).forEach(([T,w])=>{let O=isArray(w)?w:[w],N=q=>q==="create"||q==="replace"?"link":q;O.forEach(q=>{if(!q)return;let C=N(q.$op);if(C==="replace")throw new Error("Not supported yet: replace on roleFields");if(C==="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 V={...b,$thing:E.$thing,$thingType:"relation",$op:C==="delete"?"unlink":C,[T]:q.$bzId,$bzId:E.$bzId,[qe]:"roleField"};$(V);});});}}}}}),[u,d]},[n,i]=r(e),o=n.reduce((c,u)=>{if(!u.$bzId)return [...c,u];let d=c.findIndex(f=>f.$bzId===u.$bzId);if(d===-1)return [...c,u];if(c[d].$op==="create"&&u.$op==="match")return c;if(c[d].$op==="match"&&(u.$op==="create"||u.$op==="match"))return [...c.slice(0,d),u,...c.slice(d+1)];if(c[d].$op==="update"&&u.$op==="update")return [...c.slice(0,d),{...c[d],...u},...c.slice(d+1)];if(c[d].$op==="update"&&u.$op==="match"||c[d].$op==="match"&&u.$op==="update")return [...c.slice(0,d),{...c[d],...u,$op:"update"},...c.slice(d+1)];if(c[d].$op==="delete"&&u.$op==="delete"){if(JSON.stringify(c[d].$filter)===JSON.stringify(u.$filter))return c;throw new Error(`[Wrong format] Can't delete the same thing with different filters. Existing: ${c[d].$filter}. Current: ${u.$filter}`)}throw new Error(`[Wrong format] Wrong operation combination for $tempId/$id "${u.$tempId||u.$id}". Existing: ${c[d].$op}. Current: ${u.$op}`)},[]),a=i.reduce((c,u)=>{let d=c.find(f=>(f.$id&&f.$id===u.$id||f.$bzId&&f.$bzId===u.$bzId)&&f.$thing===u.$thing&&f.$op===u.$op);if(d){let f={...d};return Object.keys(u).forEach($=>{if(typeof $=="symbol"||$.startsWith("$"))return;let g=d[$],y=u[$];Array.isArray(g)&&Array.isArray(y)?f[$]=Array.from(new Set([...g,...y])):!Array.isArray(g)&&Array.isArray(y)?g!==void 0?f[$]=Array.from(new Set([g,...y])):f[$]=y:Array.isArray(g)&&!Array.isArray(y)?y!==void 0&&(f[$]=Array.from(new Set([...g,y]))):g!==null&&y!==null&&g!==void 0&&y!==void 0?f[$]=Array.from(new Set([g,y])):g==null&&(f[$]=y);}),[...c.filter($=>!(($.$id&&$.$id===u.$id||$.$bzId&&$.$bzId===u.$bzId)&&$.$thing===u.$thing&&$.$op===u.$op)),f]}return [...c,u]},[]);o.forEach(c=>{if((c.$thingType==="relation"||"relation"in c)&&a.filter(u=>u.$bzId===c.$bzId||u.$tempId&&u.$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(tn(c))}`)}});let s=[...o,...a],l=new Set(s.filter(c=>c.$tempId).map(c=>c.$tempId)),h=Array.from(l).filter(c=>!s.some(u=>u.$tempId===c&&u.$op==="create"));if(h.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${h.join(", ")}`);return {mergedThings:o,mergedEdges:a}};var an=new Set((process.env.BORM_LOG_LEVEL||"").split(",").map(e=>e.trim()).filter(e=>!!e)),Lo=(e,...t)=>{(Array.isArray(e)?e.some(n=>an.has(n)):an.has(e))&&console.log(...t);},se=(...e)=>Lo("debug",...e);var ae="0.13.4";var We={};function oe(e){return {enumerable:!0,value:e}}function ln(e){return {enumerable:!0,writable:!0,value:e}}var Qo=()=>!0,cn=()=>({}),un=e=>e,Ro=(e,t,r,n)=>e.apply(r,n)&&t.apply(r,n),Do=(e,t,r,[n,i])=>t.call(r,e.call(r,n,i),i),Ae=(e,t)=>Object.freeze(Object.create(e,t));function dn(e,t,r){return e.reduce((n,i)=>function(...o){return r(n,i,this,o)},t)}function hn(e){return Ae(this,{fn:oe(e)})}var pn={},_=hn.bind(pn);var fn={},Pt=hn.bind(fn);function pt(e,t){return t.filter(r=>e.isPrototypeOf(r))}function $n(e,t,...r){let n=dn(pt(fn,r).map(o=>o.fn),Qo,Ro),i=dn(pt(pn,r).map(o=>o.fn),un,Do);return Ae(this,{from:oe(e),to:oe(t),guards:oe(n),reducers:oe(i)})}var mn={},yn={},z=$n.bind(mn);$n.bind(yn,null);function Io(e,t,r){return jt(t,e,r,this.immediates)||e}function gn(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 Oo={enter:un};function ue(...e){let t=pt(mn,e),r=pt(yn,e),n={final:oe(e.length===0),transitions:oe(gn(t))};return r.length&&(n.immediates=oe(r),n.enter=oe(Io)),Ae(Oo,n)}var Co={enter(e,t,r){let n=this.fn.call(t,t.context,r);return xt.isPrototypeOf(n)?Ae(En,{machine:oe(n),transitions:oe(this.transitions)}).enter(e,t,r):(n.then(i=>t.send({type:"done",data:i})).catch(i=>t.send({type:"error",error:i})),e)}},En={enter(e,t,r){if(t.child=ye(this.machine,n=>{t.onChange(n),t.child==n&&n.machine.state.value.final&&(delete t.child,t.send({type:"done",data:n.context}));},t.context,r),t.child.machine.state.value.final){let n=t.child.context;return delete t.child,jt(t,e,{type:"done",data:n},this.transitions.get("done"))}return e}};function W(e,...t){let r=oe(gn(t));return xt.isPrototypeOf(e)?Ae(En,{machine:oe(e),transitions:r}):Ae(Co,{fn:oe(e),transitions:r})}var xt={get state(){return {name:this.current,value:this.states[this.current]}}};function Ee(e,t,r=cn){return typeof e!="string"&&(r=t||cn,t=e,e=Object.keys(t)[0]),We._create&&We._create(e,t),Ae(xt,{context:oe(r),current:oe(e),states:oe(t)})}function jt(e,t,r,n){let{context:i}=e;for(let{to:o,guards:a,reducers:s}of n)if(a(i,r)){e.context=s.call(e,i,r);let l=t.original||t,h=Ae(l,{current:oe(o),original:{value:l}});We._onEnter&&We._onEnter(t,o,e.context,i,r);let c=h.state.value;return e.machine=h,e.onChange(e),c.enter(h,e,r)}}function Ao(e,t){let r=t.type||t,{machine:n}=e,{value:i,name:o}=n.state;return i.transitions.has(r)?jt(e,n,t,i.transitions.get(r))||n:(We._send&&We._send(r,o),n)}var ko={send(e){Ao(this,e);}};function ye(e,t,r,n){let i=Object.create(ko,{machine:ln(e),context:ln(e.context(r,n)),onChange:oe(t)});return i.send=i.send.bind(i),i.machine=i.machine.state.value.enter(i.machine,i,n),i}var wn=(e,t)=>{if(!t)return;let r=No(t);return Po(r,e.query)},No=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),Po=(e,t)=>produce(e,r=>traverse(r,({value:n})=>{if(isObject(n)){let i=n;Object.keys(i).forEach(o=>{(i[o]===void 0||i[o]===null||isArray(i[o])&&i[o].length===0)&&(t?.returnNulls?i[o]=null:delete i[o]),i[o]===void 0&&delete i[o];}),Object.getOwnPropertySymbols(i).forEach(o=>{delete i[o];}),t?.noMetadata===!0&&Object.keys(i).forEach(o=>{o.startsWith("$")&&delete i[o];});}}));var Tn=async(e,t,r)=>r?(o=>produce(o,a=>traverse(a,({value:s})=>{if(isObject(s)){let l=s;if(!l.$thing)return;if(l.$thing){let h=j(e,l),{virtualFields:c}=h,u=l[ee];if(!u)throw new Error(`[Internal] QueryPath is missing. Value: ${JSON.stringify(l)}`);let d=getNodeByPath(t,u);if(d.$fieldType==="ref")return;let f=d.$fields.map($=>$.$path),p=d.$excludedFields;c.forEach($=>{if(p?.includes($)||f.length>0&&!f.includes($))return;let g=h.dataFields?.find(y=>y.path===$);if(g?.default){let y=ve({currentThing:l,fieldSchema:g,mandatoryDependencies:!0});l[$]=y;}else if(l[$]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${$}`)}),p&&p.forEach($=>{if(typeof $!="string")throw new Error("[Internal] ExcludedField is not a string");delete l[$];});}}})))(r):void 0;var Ge={$eq:"$=",$not:"$!",$or:"$OR",$and:"$AND",$in:"$IN",$id:"record::id(id)",$exists:"$exists"},Be=(e,t,r)=>{if(e==null)return e;let n=isArray(e),o=(n?e:[e]).map(a=>{let l=Object.keys(a).reduce((h,c)=>{let u=a[c];if(c.startsWith("$")){if(["$or","$and","$not"].includes(c))return {...h,[c]:void 0,[Ge[c]]:Be(u,t,r)};if(c==="$id")return {...h,$id:void 0,[Ge[c]]:{$IN:isArray(u)?u:[u]}};if(c==="$thing")return h;if(c==="$exists")return {...h,$exists:void 0,[Ge[c]]:u};if(c==="$eq")return {...h,$eq:void 0,[Ge[c]]:u};if(c==="$in")return {...h,$in:void 0,[Ge[c]]:u};throw new Error(`Unknown filter operator ${c}`)}let d=t in r.entities?r.entities[t]:r.relations[t],[f,p]=st(d,c);if(f==="idField"){if(d.idFields.length>1)throw new Error("Multiple id fields not supported");return {...h,"record::id(id)":{$IN:isArray(u)?u:[u]}}}if(f==="dataField")return {...h,[c]:Be(u,t,r)};if(f==="linkField"||f==="roleField"){let g=p[Me].queryPath;return {...h,[g]:Be(u,t,r)}}throw new Error(`Field ${c} not found in schema, Defined in $filter`)},{});return shake(l)});return n?o:o[0]},me=e=>{if(e==null)return "";let t=Object.entries(e),r=[];return t.forEach(([n,i])=>{if(["$OR","$AND","$!"].includes(n)){let o=n.replace("$",""),a=Array.isArray(i)?i.map(s=>me(s)):[me(i)];o==="!"?r.push(`!(${a.join(" AND ")})`):r.push(`(${a.join(` ${o} `)})`);return}if(isObject(i))if(n.includes("<-")||n.includes("->")){let o=me(i);r.push(`${n}[WHERE ${o}]`);}else if(n.startsWith("$parent.[")){let o=me(i),a=n.replace("$parent.","").replace(/^\[(.*)\]$/,"$1");r.push(`fn::as_array(${a})[WHERE id && ${o}]`);}else if(n.startsWith("$parent")){let o=me(i),a=n.replace("$parent.","");r.push(`fn::as_array(${a})[WHERE id && ${o}]`);}else {if(n.startsWith("$"))throw new Error(`Invalid key ${n}`);{let o=Object.keys(i);if(o.length===1&&o[0].startsWith("$")){let[a]=o,s=i[a];if(a==="$exists")if(s===!0)r.push(`${n} IS NOT NONE`);else if(s===!1)r.push(`${n} IS NONE`);else throw new Error(`Invalid value for $exists: ${s}`);else {let l=a.replace("$","");if(Array.isArray(s))r.push(`${n} ${l} [${s.map(h=>h===null?"NONE":`'${h}'`).join(", ")}]`);else if(isObject(s)){let h=me(s);r.push(`${n} ${l} ${h}`);}else r.push(`${n} ${l} ${s===null?"NONE":`'${s}'`}`);}}else throw new Error(`Invalid key ${n}`)}}else if(Array.isArray(i)){let o=n.startsWith("$")?n.replace("$",""):"IN";r.push(`${n} ${o} [${i.map(a=>a===null?"NONE":`'${a}'`).join(", ")}]`);}else {let o=n.startsWith("$")?n.replace("$",""):"=";r.push(`${n} ${o} ${i===null?"NONE":`'${i}'`}`);}}),r.join(" AND ")},Ve=e=>`ORDER BY ${e.map(r=>{if(typeof r=="string")return r;let{field:n,desc:i}=r;return `${n}${i?" DESC":" ASC"}`}).join(", ")}`;var Sn=e=>{let{queries:t,schema:r}=e;return t.map(n=>Wo({query:n,schema:r}))},Wo=e=>{let{query:t,schema:r}=e,{$thing:n,$fields:i,$filter:o,$offset:a,$limit:s,$sort:l}=t;if(i.length===0)return null;let h=[];h.push("SELECT");let c=zt({parentQuery:t,queries:i,level:1,schema:r});c&&h.push(c);let u=r.entities[n]||r.relations[n];if(!u)throw new Error(`Schema for ${n} not found`);let f=(u.subTypes?[n,...u.subTypes]:[n]).map(p=>te(p));if(t.$id)if(typeof t.$id=="string")h.push(`FROM ${f.map(p=>`${p}:\u27E8${t.$id}\u27E9`).join(",")}`);else if(isArray(t.$id)){let p=t.$id,$=f.flatMap(g=>p?.map(y=>`${g}:\u27E8${y}\u27E9`));h.push(`FROM ${$.join(",")}`);}else throw new Error("Invalid $id");else h.push(`FROM ${f.join(",")}`);if(o){let p=Be(o,n,r),$=me(p);h.push(`WHERE ${$}`);}return l&&h.push(Ve(l)),typeof s=="number"&&h.push(`LIMIT ${s}`),typeof a=="number"&&h.push(`START ${a}`),h.join(`
|
|
104
|
-
`)},
|
|
105
|
-
`)},
|
|
106
|
-
`)},
|
|
107
|
-
`)};var
|
|
108
|
-
`),g=
|
|
109
|
-
`),l=`FROM $parent.\`${r[ie].path}\`[*]`,h=r.$filter&&Object.keys(r.$filter).length>0?`WHERE id AND(${
|
|
110
|
-
`),
|
|
93
|
+
`},pr=async(e,t,r,n)=>{if(!n.typeDB)throw new Error("No TypeDB handles found");let o=yi(e,r),i=n.typeDB.get(e)?.session,a=n.typeDB.get(e)?.client;if(!i){console.log("Session Status: ","NO SESSION");return}if(!a)throw new Error("No TypeDB client found");await i.close();let[{dbName:s}]=t.dbConnectors;await(await a.databases.get(s)).delete(),await a.databases.create(s);let c=await(await a.session(t.dbConnectors[0].dbName,SessionType.SCHEMA)).transaction(TransactionType.WRITE);return await c.query.define(o),await c.commit(),await c.close(),o};var fr=async(e,t,r)=>await(async()=>{let i=(await Promise.all([...r.typeDB||[]].map(async([l])=>[l,await pr(l,e,t,r)]))).map(l=>[l[0],l[1]]),s=(await Promise.all([...r.surrealDB||[]].map(async([l])=>[l,hr(t)]))).map(l=>[l[0],l[1]]);return {typeDB:Object.fromEntries(i),surrealDB:Object.fromEntries(s)}})();var $r={typeDB:{mutation:{splitArray$Ids:true,requiresParseBQL:true}},surrealDB:{mutation:{splitArray$Ids:false,requiresParseBQL:false}}};var ee=Symbol.for("queryPath"),tt=Symbol.for("stepPrint"),ke=Symbol.for("edgeType"),we=Symbol.for("edgeSchema"),xe=Symbol.for("dbNode"),Bt=Symbol.for("isTransformed"),rt=Symbol.for("parent"),ie=Symbol.for("fieldSchema"),K=Symbol.for("sharedMetadata"),Te=Symbol.for("suqlMetadata");var Er=(e,t)=>{let r=mr(e.entities),n=mr(e.relations),o=Ei(e),i={entities:{},relations:{}};return r.forEach(a=>{let s=e.entities[a];if(!s)throw new Error(`Entity "${a}" does not exist`);let l="extends"in s?i.entities[s.extends]:void 0;l&&bt(i,l.name,a);let h=yr({schema:e,enrichedSchema:i,extendedThing:l,name:a,thing:s,dbHandles:t,allLinkFields:o});i.entities[a]={...h,defaultDBConnector:s.defaultDBConnector,thingType:"entity"};}),n.forEach(a=>{let s=e.relations[a];if(!s)throw new Error(`Relation "${a}" does not exist`);let l="extends"in s?i.relations[s.extends]:void 0;l&&bt(i,l.name,a);let h=yr({schema:e,enrichedSchema:i,extendedThing:l,name:a,thing:s,dbHandles:t,allLinkFields:o}),c={...h,defaultDBConnector:s.defaultDBConnector,roles:Object.fromEntries(Object.entries(s.roles??{}).map(([u,d])=>[u,gr({role:d,roleName:u,relationName:a,relation:s,allExtends:h.allExtends,allLinkFields:o})])),thingType:"relation"};"extends"in s&&l&&Object.entries(l?.roles??{}).forEach(([u,d])=>{let f=gr({role:d,roleName:u,relationName:a,relation:s,allExtends:h.allExtends,allLinkFields:o});c.roles[u]={...f,inherited:true,[K]:{...d[K],inheritanceOrigin:d[K]?.inheritanceOrigin||s.extends}};}),i.relations[a]=c;}),Object.values(i.entities).forEach(a=>{a.linkFields?.forEach(s=>{s.$things=Ft(i,s.$things);});}),Object.values(i.relations).forEach(a=>{a.linkFields?.forEach(s=>{s.$things=Ft(i,s.$things);}),Object.values(a.roles??{}).forEach(s=>{s.$things=Ft(i,s.$things);});}),i},mr=e=>{let t=[],r=new Set,n=new Set;return Object.keys(e).forEach(o=>Br({thingMap:e,name:o,inProcess:n,seen:r,ordered:t})),t},Br=e=>{let{thingMap:t,name:r,inProcess:n,seen:o,ordered:i}=e;if(o.has(r))return;if(n.has(r))throw new Error(`A list of thing extends each other that creates circular dependencies: ${[...n]}`);n.add(r);let a=t[r];if(!a)throw new Error(`Entity/relation "${r}" does not exist`);"extends"in a&&Br({...e,name:a.extends}),n.delete(r),o.add(r),i.push(r);},gi=(e,t)=>{let r=t,n=[];for(;r;){let o=e.entities[r]||e.relations[r];if(!o)throw new Error(`Entity/relation "${r}" does not exist`);n.push(r),r="extends"in o?o.extends:void 0;}return n.length!==0?n:void 0},bt=(e,t,r)=>{let n=e.entities[t]??e.relations[t];if(!n)throw new Error(`Entity/relation "${t}" does not exist`);n.subTypes=n.subTypes??[],n.subTypes.push(r),n.extends&&bt(e,n.extends,r);},yr=e=>{let{schema:t,enrichedSchema:r,name:n,thing:o,dbHandles:i,extendedThing:a,allLinkFields:s}=e,[l]=Object.entries(i).find(([p,$])=>$.get(o.defaultDBConnector.id))??[];if(!l)throw new Error(`DB handle for ${o.defaultDBConnector.id} does not exist`);let h=[...o.idFields??a?.idFields??[]];if(h.length===0)throw new Error(`"${n}" does not have an id field`);let c={...o.hooks},u=o.dataFields?.map(p=>Bi(p,n,h))??[],d=o.linkFields?.map(p=>bi({linkField:p,thingName:n,thing:o,schema:t,allLinkFields:s}))??[],f=Object.fromEntries(Object.entries(o.refFields??{}).map(([p,$])=>[p,Fi($,p)]));return "extends"in o&&a&&(a.hooks?.pre&&(c.pre=[...a.hooks.pre||[],...o.hooks?.pre||[]]),a.dataFields?.forEach(p=>{u.push({...p,inherited:true,[K]:{...p[K],inheritanceOrigin:p[K]?.inheritanceOrigin||o.extends}});}),a.linkFields?.forEach(p=>{d.push({...p,inherited:true,[K]:{...p[K],inheritanceOrigin:p[K]?.inheritanceOrigin||o.extends}});}),Object.entries(a.refFields??{}).forEach(([p,$])=>{f[p]={...$,inherited:true,[K]:{...$[K],inheritanceOrigin:$[K]?.inheritanceOrigin||o.extends}};})),{...o,name:n,db:l,dbContext:$r[l],idFields:h,hooks:c,dataFields:u,linkFields:d,refFields:f,enumFields:u?.filter(p=>p.validations?.enum).map(p=>p.path)??[],fnValidatedFields:u?.filter(p=>p.validations?.fn).map(p=>p.path)??[],virtualFields:u?.filter(p=>p.isVirtual).map(p=>p.path)??[],computedFields:u?.filter(p=>p.default&&!p.isVirtual).map(p=>p.path)??[],requiredFields:u?.filter(p=>p.validations?.required).map(p=>p.path)??[],allExtends:"extends"in o?gi(r,o.extends):void 0,dbProviderConfig:l==="surrealDB"?i[l]?.get(o.defaultDBConnector.id)?.providerConfig:void 0}},Ei=e=>{let t=[];return Object.entries(e.entities).forEach(([r,n])=>{n.linkFields?.forEach(o=>{t.push({...o,thing:r,thingType:"entity",pathToRelation:o.target==="relation"?o.path:o.relation.toLocaleLowerCase()});});}),Object.entries(e.relations).forEach(([r,n])=>{n.linkFields?.forEach(o=>{t.push({...o,thing:r,thingType:"relation",pathToRelation:o.target==="relation"?o.path:o.relation.toLocaleLowerCase()});});}),t},Bi=(e,t,r)=>({...e,cardinality:e.cardinality||"ONE",dbPath:"dbPath"in e&&typeof e.dbPath=="string"?e.dbPath:wi(t,e.path,e.shared),isIdField:!!r?.includes(e.path),inherited:false,[K]:{fieldType:"dataField"},[Te]:{dbPath:e.path}}),Fi=(e,t)=>({...e,cardinality:e.cardinality||"ONE",path:t,dbPath:e.dbPath||t,inherited:false,[K]:{fieldType:"refField"}}),bi=e=>{let{linkField:t,thing:r,thingName:n,schema:o,allLinkFields:i}=e,a=o.relations[t.relation];if(!t.isVirtual){if(!a)throw new Error(`The relation ${t.relation} does not exist in the schema`);if(!Fr(o,t.relation,t.plays))throw new Error(`The role ${t.plays} is not defined in the relation ${t.relation} (linkField: ${t.path})`)}let s=t.cardinality==="MANY"?`$parent.[\`${t.path}\`]`:`$parent.\`${t.path}\``;if(t.target==="relation"){if(t.isVirtual)throw new Error(`[Schema] Virtual linkFields can't target a relation. Thing: "${n}" LinkField: "${t.path}."`);return {...t,$things:[t.relation],oppositeLinkFieldsPlayedBy:[{plays:t.path,thing:t.relation,thingType:"relation"}],fieldType:"linkField",inherited:false,[K]:{fieldType:"linkField"},[Te]:{queryPath:s}}}let l=i.filter(h=>h.relation===t.relation&&h.plays!==t.plays&&h.target==="role");if(l.length===0)throw new Error(`[Schema] LinkFields require to have at least one opposite linkField playing an opposite role. Thing: "${n}" LinkField: "${t.path}."`);return l.length>1&&console.warn(`[Schema] LinkField ${t.path} in ${n} has multiple candidates ${l.map(h=>h.thing).join(",")} and this is not yet supported. Please target a single one using targetRoles with a single role`),{...t,fieldType:"linkField",pathToRelation:r.linkFields?.find(h=>h.target==="relation"&&h.relation===t.relation)?.path??t.relation.toLocaleLowerCase(),inherited:false,$things:l.map(h=>h.thing),oppositeLinkFieldsPlayedBy:l,[K]:{fieldType:"linkField"},[Te]:{queryPath:s}}},gr=e=>{let{role:t,roleName:r,relationName:n,relation:o,allExtends:i,allLinkFields:a}=e;if(o.dataFields?.find(h=>h.path===r)||o.linkFields?.find(h=>h.path===r))throw new Error(`[Schema] The path ${r} is already in use by a dataField or linkField in ${n}.`);let s=a.filter(h=>h.relation===n&&h.plays===r),l=a.filter(h=>h.target==="relation"&&h.plays===r&&i?.includes(h.relation));return {...t,fieldType:"roleField",inherited:false,playedBy:s.map(h=>({...h,pathToRelation:h.target==="relation"?h.path:o.linkFields?.find(c=>c.target==="relation"&&c.relation===r&&c.plays===r)?.path??h.relation.toLocaleLowerCase()})),impactedLinkFields:l,path:r,$things:[...new Set(s.map(h=>h.thing))],[K]:{fieldType:"roleField"},[Te]:{queryPath:t.cardinality==="MANY"?`$parent.[\`${r}\`]`:`$parent.\`${r}\``}}},wi=(e,t,r)=>r?t:`${e}\xB7${t}`,Fr=(e,t,r)=>{let n=e.relations[t];if(!n)throw new Error(`Relation "${t}" does not exist`);return n.roles?.[r]?true:"extends"in n?Fr(e,n.extends,r):false},Ft=(e,t)=>t.flatMap(r=>[r,...(e.entities[r]??e.relations[r])?.subTypes??[]]);var wr=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,n])=>t(r,n))))[0],le=(e,t)=>{let r=Reflect.ownKeys(e).map(n=>[n,e[n]]);return Object.fromEntries(r.filter(([n,o])=>{let[i,a]=tryit(()=>t(n,o))();return i?false:a}))},Y=(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`)},j=(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)}`)},nt=(e,t)=>{let r=e.dataFields?.find(i=>i.path===t);if(e.idFields?.includes(t)){if(!r)throw new Error(`Field ${t} is an idField but not a dataField in schema`);return ["idField",r]}if(r)return ["dataField",r];let n=e.linkFields?.find(i=>i.path===t);if(n)return ["linkField",n];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`)},it=(e,t)=>{let r=j(e,t);if(r?.idFields?.length&&r?.idFields?.length>1)throw new Error(`Multiple ids not yet enabled / composite ids: ${r?.idFields}`);let[n]=r.idFields;return n},Tr=(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")},Tt=(e,t,r)=>{let n=j(e,t),o=n.linkFields?.find(l=>l.path===r);if(o)return o;let i=n.dataFields?.find(l=>l.path===r);if(i)return i;let a="roles"in n?n.roles?.[r]:void 0;if(a)return a;let s="refFields"in n?n.refFields?.[r]:void 0;if(s)return s;throw new Error(`Field ${r} not found in schema`)},Mt=(e,t,r)=>Tt(e,t,r)?.cardinality,ce=(e,t)=>{let r=e.dataFields?.map($=>$.path)||[],n=e.linkFields?.map($=>$.path)||[],o="refFields"in e?listify(e.refFields,$=>$):[],i="roles"in e?listify(e.roles,$=>$):[],a=[...r||[],...n||[],...i||[],...o||[]],l=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...a];if(!t)return {fields:a,dataFields:r,roleFields:i,linkFields:n};let h=t.$fields?t.$fields.map($=>{if(typeof $=="string"){if($.startsWith("$")||$.startsWith("%"))return;if(!a.includes($))throw new Error(`Field ${$} not found in the schema`);return $}if("$path"in $&&typeof $.$path=="string")return $.$path;throw new Error("[Wrong format] Wrongly structured query")}):listify(t,$=>{if(!($.startsWith("$")||$.startsWith("%"))){if(!a.includes($))throw new Error(`[Schema] Field ${$} not found in the schema`);return $}}).filter($=>$!==void 0),c=t.$filter?listify(t.$filter,$=>$.toString().startsWith("$")?void 0:$.toString()).filter($=>$&&r?.includes($)):[],u=t.$filter?listify(t.$filter,$=>$.toString().startsWith("$")?void 0:$.toString()).filter($=>$&&[...i||[],...n||[]].includes($)):[],d=[...h,...c].filter($=>!$?.startsWith("%")).filter($=>!l.includes($)).filter($=>$),f=t.$filter?le(t.$filter,($,g)=>c.includes($)):{},p=t.$filter?le(t.$filter,($,g)=>u.includes($)):{};return {fields:a,dataFields:r,roleFields:i,linkFields:n,refFields:o,usedFields:h,usedLinkFields:n.filter($=>h.includes($)),usedRoleFields:i.filter($=>h.includes($)),usedDataFields:r.filter($=>h.includes($)),usedRefFields:o.filter($=>h.includes($)),unidentifiedFields:d,...c.length?{localFilters:f}:{},...u.length?{nestedFilters:p}:{}}};var Mr=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},Sr=(e,t,r)=>{let o=(r.nodePath||"").split("."),i=isArray(t)?o.slice(0,-2).join("."):o.slice(0,-1).join(".");return t?getNodeByPath(e,i):{}},Re=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var ot=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),Me=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(([n,o])=>{r[n]=isDraft(o)?current(o):o;}),r}return e},fe=(e,t)=>{if(e===void 0)throw new Error("Value is undefined");return e},L=(e,t)=>{let r="";for(let n=0;n<t;n++)r+=" ";return `${r}${e}`},De=e=>customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",21)();var Qr=(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,i=>{let{value:a,meta:s}=i,l=a;if(isObject(l)){if(s.nodePath?.includes(".$filter")||s.nodePath?.includes(".$playedBy"))return;if(l[ee]=s.nodePath,l.$id){let h=l.$entity||l.$relation?l:{[`$${l.$thingType}`]:l.$thing},c=j(t,h);if(!c?.name)throw new Error(`Schema not found for ${l.$thing}`);if(l.$path=c.name,Array.isArray(l.$id)||(l.$filterByUnique=true),c.idFields.length===1){let[u]=c.idFields;l.$filter={...l.$filter,[u]:l.$id},l.$id=void 0;}else throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in l||"$relation"in l||"$thing"in l){let h=j(t,l);if(!h?.name)throw new Error(`Schema not found for ${l.$thing}`);l.$path=h.name;}if(l.$entity?(l.$thing=l.$entity,l.$thingType="entity",l.$entity=void 0):l.$relation&&(l.$thing=l.$relation,l.$thingType="relation",l.$relation=void 0),isObject(l)&&"$thing"in l&&l.$thing){let h=l.$entity||l.$relation?l:{[`$${l.$thingType}`]:l.$thing},c=j(t,h);if(l.$filter&&(Object.keys(l.$filter).length===0?l.$filter=void 0:(l.$filter=Ie(l.$filter,l.$thing,t),l.$filterByUnique=Lt(l.$filter,c))),l.$fields){l.$fields.some(f=>c?.idFields?.includes(f?.$path||f))||(l.$fields=[...l.$fields,...Array.isArray(c.idFields)?c.idFields:[]],l.$idNotIncluded=true);let d=l.$fields?.flatMap(f=>{let p=Lr(f,c,t);return Array.isArray(p)?p:[p]}).filter(Boolean);l.$fields=d;}else {let d=St(c)?.flatMap(f=>{let p=Lr(f,c,t);return Array.isArray(p)?p:[p]}).filter(Boolean);l.$fields=d;}l.$excludedFields&&(l.$fields=l.$fields.filter(u=>st(c,u)?true:!l.$excludedFields.includes(u.$path)));}}}))},St=e=>{let t=e.dataFields?.map(a=>a.path)||[],r=e.linkFields?.map(a=>a.path)||[],n=Object.keys(e.roles||{})||[],o=Object.keys(e.refFields||{})||[];return [...t,...r,...n,...o]},Lt=(e,t)=>Object.keys(e||{}).some(n=>{let o=e[n];if(o!==null&&typeof o<"u"){let i=t.idFields?.includes(n),a=t.dataFields?.some(h=>(h.dbPath===n||h.path===n)&&h?.validations?.unique),s=n==="$id"&&!Array.isArray(o);if(i||a||s){if(typeof o!="object"||o===null||Array.isArray(o))return !Array.isArray(o);let h=Object.keys(o);if(h.length===1&&h[0]==="$eq"){let c=o.$eq;if(typeof c!="object"||c===null||!Array.isArray(c))return true}return false}}return false}),st=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),Ii=e=>{let{field:t,fieldStr:r,$justId:n,dbPath:o,isVirtual:i,fieldSchema:a}=e;return {$path:r,$dbPath:o,$thingType:"attribute",$as:t.$as||r,$var:r,$fieldType:"data",$justId:n,$id:t.$id,$isVirtual:i,[ie]:a}},Oi=e=>{let{field:t,fieldStr:r,linkField:n,$justId:o,dbPath:i,schema:a,fieldSchema:s}=e,{target:l,oppositeLinkFieldsPlayedBy:h}=n;return h.map(c=>{let u=l==="role"?c.thingType:"relation",d=l==="role"?c.thing:n.relation,f={[`$${u}`]:d},p=j(a,f),$=t?.$fields?.filter(m=>st(p,m)).length===0,g=[];if(typeof t!="string")if(t.$fields)if($){let m=p.idFields||[];g=[...t.$fields,...m];}else g=t.$fields;else g=St(p);else g=["id"];t.$excludedFields&&(g=g.filter(m=>st(p,m)?true:!t.$excludedFields.includes(m.$path)));let y=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...t.$filter}:void 0;return {$thingType:u,$plays:n.plays,$playedBy:{...c,oppositeLinkFieldsPlayedBy:void 0},$path:c.path,$dbPath:i,$as:t.$as||r,$var:r,$thing:d,$fields:g,$excludedFields:t.$excludedFields,$fieldType:"link",$target:l,$intermediary:c.relation,$justId:o,$id:t.$id,$filter:y,$idNotIncluded:$,$filterByUnique:Lt(t.$filter,p),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ie]:s}})},Ai=e=>{let{field:t,fieldStr:r,$justId:n,dbPath:o,fieldSchema:i}=e;if("$filter"in e)throw new Error("Filter not supported in ref fields");return {$path:r,$dbPath:o,$contentType:i.contentType,$as:t.$as||r,$var:r,$fieldType:"ref",$justId:n,$fields:t.$fields,$id:t.$id,[ie]:i}},ki=e=>{let{field:t,fieldStr:r,roleField:n,$justId:o,dbPath:i,schema:a,fieldSchema:s}=e;return n.playedBy.map(l=>{let{thing:h,thingType:c,relation:u}=l,d={[`$${c}`]:h},f=j(a,d),p=t?.$fields?.filter(y=>f?.idFields?.includes(y)||f?.idFields?.includes(y.$path)).length===0,$=[];if(typeof t!="string")if(t.$fields)if(p){let y=f.idFields||[];$=[...t.$fields,...y];}else $=t.$fields;else $=St(f);else $=["id"];t.$excludedFields&&($=$.filter(y=>st(f,y)?true:!t.$excludedFields.includes(y.$path)));let g=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...t.$filter}:void 0;return {$thingType:c,$path:r,$dbPath:i,$as:t.$as||r,$var:r,$thing:h,$fields:$,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:u,$justId:o,$id:t.$id,$filter:g,$idNotIncluded:p,$filterByUnique:Lt(t.$filter,f),$playedBy:{...l,oppositeLinkFieldsPlayedBy:void 0},$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ie]:s}})},Lr=(e,t,r)=>{let n=typeof e=="string"?e:e.$path,o=typeof e=="string",i=t.dataFields?.find(h=>h.path===n),a=t.linkFields?.find(h=>h.path===n),s=t.roles?.[n],l=t.refFields?.[n];if(i){let h=!!i.isVirtual&&!!i.default;return Ii({field:e,fieldStr:n,$justId:o,dbPath:i.dbPath,isVirtual:h,fieldSchema:i})}return a?Oi({field:e,fieldStr:n,linkField:a,$justId:o,dbPath:a.path,schema:r,fieldSchema:a}):s?ki({field:e,fieldStr:n,roleField:s,$justId:o,dbPath:n,schema:r,fieldSchema:s}):l?Ai({field:e,fieldStr:n,$justId:o,dbPath:n,isVirtual:false,fieldSchema:l}):null},Ie=(e,t,r)=>{if(e==null)return e;let n=isArray(e),i=(n?e:[e]).map(a=>Object.keys(a).reduce((h,c)=>{let u=a[c],d=isArray(u)?u:[u];if(c.startsWith("$"))if(["$id","$thing"].includes(c))h[c]=u;else if(["$not","$or","$and"].includes(c))h[c]=Ie(u,t,r);else if(["$eq","$in","$exists"].includes(c))h[c]=u;else throw new Error(`[Internal] Unknown filter operator ${c}`);else {let f=t in r.entities?r.entities[t]:r.relations[t],[p,$]=nt(f,c);if(p==="idField")h[c]=u;else if(p==="dataField")isObject(u)||isArray(u)&&u.some(isObject)?h[c]=isArray(u)?{$or:Ie(u,t,r)}:Ie(u,t,r):isArray(u)?h[c]={$in:u}:h[c]={$eq:u};else if(p==="linkField"||p==="roleField"){let g=$,[y]=g.$things;d.every(m=>typeof m=="string")?h[c]={$id:d,$thing:y}:d.every(m=>isObject(m))&&(h[c]=isArray(u)?{$or:Ie(u,y,r)}:Ie(u,y,r));}else throw new Error(`Field ${c} not found in schema of ${t}`)}return h},{}));return !n||i.length===1?i[0]:{$or:i}};var qi=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Ni=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,Rr=e=>{let r=e.toString().replace(qi,"").trim().split("=>")[0].split("{")[0].replace(Ni,"").trim(),n=r.substring(r.indexOf("(")+1,r.lastIndexOf(")")).trim();return n?(n.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(i=>i.includes("{")&&i.includes("}")?(i.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(s=>s.split(":")[0].trim().replace(/['"[\]]/g,"")):i.trim()).filter(Boolean):[]};var _e=({currentThing:e,fieldSchema:t,mandatoryDependencies:r=false})=>{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:n}=t.default,i=Rr(n).filter(a=>!(a in e));if(i.length)throw new Error(`Virtual field: Missing arguments ${i.join(", ")}`)}if(!t.default.fn)throw new Error("[Schema] No fn in default field schema");if("default"in t){if(t.default.type==="value")return t.default.value;if(t.default.type==="fn")return t.default.fn(e);throw new Error("[Schema] No default field definition")}};var Dr=(e,t,r)=>{let n=e[t];if(n)return (isArray(n)?n:[n]).forEach(o=>{if(o.$op!=="create")return;let i=j(r,o),{unidentifiedFields:a}=ce(i,o),{computedFields:s,virtualFields:l}=i,h=listify(o,(d,f)=>f!==void 0?d:void 0),c=h.filter(d=>l?.includes(d));if(c.length>0)throw new Error(`Virtual fields can't be sent to DB: "${c.join(",")}"`);if(s.filter(d=>!h.includes(d)).forEach(d=>{let f=i.dataFields?.find(m=>m.path===d),$=i.linkFields?.find(m=>m.path===d)?.oppositeLinkFieldsPlayedBy[0],g="roles"in i?wr(i.roles,(m,F)=>m===d):void 0,y=f||$||g;if(!y)throw new Error(`no field Def for ${d}`);if(!o[d]){let m=_e({currentThing:o,fieldSchema:y,mandatoryDependencies:true});o[d]=m;}}),a.length>0)throw new Error(`Unknown fields: [${a.join(",")}] in ${JSON.stringify(o)}`)}),e};var Qt=(e,t)=>e.$bzId?e.$bzId:e.$tempId?e.$tempId:e.$id&&!isArray(e.$id)?t?`SN_ONE_${t}_${e.$id}`:`SN_ONE_${e.$id}`:e.$id&&isArray(e.$id)?t?`SN_MANY_${t}_${De()}`:`SN_MANY_${De()}`:`SM_${De()}`;var Oe=(e,t,r)=>{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`);let n=j(r,t),{usedDataFields:o}=ce(n,t);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}},Or=(e,t,r)=>{(isArray(t)?t:[t]).forEach(o=>{Oe(e,o,r);});};var Ar=e=>{let t=Object.keys(e).filter(r=>!(r.startsWith("$")||r.startsWith("%")));return e.$op?e.$op:e.$id||e.$filter?t.length>0?"update":"link":e.$tempId?t.length>0?"create":"link":"create"},kr=(e,t,r)=>{let n=j(r,t),{usedFields:o}=ce(n,t);return t.$op?(Oe(e,t,r),t.$op):t.$id||t.$filter?o.length>0?(Oe(e,{...t,$op:"update"},r),"update"):(Oe(e,{...t,$op:"link"},r),"link"):t.$tempId?o.length>0?(Oe(e,{...t,$op:"create"},r),"create"):(Oe(e,{...t,$op:"create"},r),"link"):(Oe(e,{...t,$op:"create"},r),"create")};var at=(e,t)=>{if(t[K].fieldType==="linkField"){let n=t.oppositeLinkFieldsPlayedBy;if(n?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!n?.length)throw new Error(`[Internal] Field ${e} should have a player`);return n}if(t[K].fieldType==="roleField"){let r=t;if([...new Set(r.playedBy?.map(n=>n.thing))].length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!r.playedBy?.length)throw new Error(`[Internal] Field ${e} should have a player`);return r.playedBy}throw new Error(`[Internal] Field ${e} is not a linkField or roleField`)};var Cr=(e,t,r,n)=>{let o=(isArray(e[t])?e[t]:[e[t]]).flatMap(i=>{if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);let a=Ar(i),s=Qt(i);if(r[K].fieldType==="refField"){let c=r;if(!isObject(i)){if(c.contentType==="FLEX")return i;throw new Error(`[Wrong format] The refField ${t} must receive an object`)}if(!i.$thing)throw new Error("[Wrong format] The field $thing is required in refFields");return {...i,$op:a,$bzId:s}}let l=r;if(l.$things.length===0)throw new Error(`[Internal error] The field ${t} can't be played by any thing.`);let h=r;if(h.$things.length===1){let c=at(t,l),[u]=c;if(i.$thing&&i.$thing!==u.thing)throw new Error(`[Wrong format] The field ${t} can only be played by ${u.thing}.`);return {...i,[we]:h,$thing:u.thing,$thingType:u.thing in n.entities?"entity":"relation",$op:a,$bzId:s}}if(h.$things.length>1){if(i.$thing)return [{...i,[we]:h,$thing:i.$thing,$thingType:i.$thing in n.entities?"entity":"relation",$op:a,$bzId:s}];if(!i.$thing){if(i.$tempId)throw new Error("[Unsupported] Objects with $tempId and multiple potential players require to explicitly indicate the $thing type.");if(a==="create")throw new Error(`[Wrong format] The field ${t} can be played by multiple things, please specify one on creation.`);return h.$things.map(c=>({...i,[we]:h,$thing:c,$thingType:c in n.entities?"entity":"relation",$op:a,$bzId:Qt(i,c)}))}}});isArray(e[t])||o.length>1?e[t]=o:e[t]=o[0],e[t]=isArray(e[t])?o:o[0];};var lt=(e,t)=>{let r=j(t,e).hooks;if(r?.pre){let n=`on${Mr(e.$op)}`;return r.pre.filter(a=>!a.triggers||a.triggers[n]?.()).flatMap(a=>a.actions)}return []};var qr=(e,t,r,n)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(i=>{if(!ot(i)||i.$fields||i[Bt])return;let a=lt(i,r).filter(u=>u.type==="transform"),s=clone(Me(e)),l=clone(Me(i)),h=n.mutation?.context||{},c=clone(Me(i[xe]||i.$dbNode));a.forEach(u=>{let d=u.fn(l,s,h,c||{});Object.keys(d).length!==0&&(l={...l,...d,...Re(i),[Bt]:true},Object.assign(i,l));});});};var Pr=(e,t,r,n)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(i=>{if("$thing"in i){if(i.$fields)return i;let{requiredFields:a,enumFields:s,fnValidatedFields:l,dataFields:h}=j(r,i);if("$op"in i&&i.$op==="create"&&a.forEach(c=>{if(!(c in i))throw new Error(`[Validations] Required field "${c}" is missing.`)}),("$op"in i&&i.$op==="update"||i.$op==="create")&&s.forEach(c=>{if(c in i){let u=h?.find(d=>d.path===c)?.validations?.enum;if(!u)throw new Error(`[Validations] Enum field "${c}" is missing enum options.`);if(isArray(i[c]))i[c].some(d=>{if(d!==null&&!u.includes(d))throw new Error(`[Validations] Option "${d}" is not a valid option for field "${c}".`)});else if(u&&!u.includes(i[c])&&i[c]!==null)throw new Error(`[Validations] Option "${i[c]}" is not a valid option for field "${c}".`)}}),("$op"in i&&i.$op==="update"||i.$op==="create")&&l.forEach(c=>{if(c in i)try{let u=h?.find(d=>d.path===c)?.validations?.fn;if(!u)throw new Error("Missing validation function.");if(!u(i[c]))throw new Error("Failed validation function.")}catch(u){throw new Error(`[Validations:attribute:${c}] ${u.message}`)}}),isObject(i)&&"$thing"in i){let c=i.$thing,u=i,d=clone(Me(e)),f=clone(Me(u)),p=n.mutation?.context||{},$=clone(Me(i[xe]||{}));lt(u,r).forEach(y=>{if(y.type==="validate"){if(y.severity!=="error")return;try{let m=y.fn(f,d,p,$);if(m===!1)throw new Error(`${y.message}.`);if(m!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(m){throw new Error(`[Validations:thing:${c}] ${m.message}`)}}});}}});};var xr=(e,t,r,n)=>{let o=isArray(e[t])?e[t]:[e[t]],i=n.slice(1).join(".");o.forEach(a=>{if(a){if(r?.cardinality==="ONE"&&!a.$op&&!a.$id&&!a.$filter&&!a.$tempId&&e.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${i}.${t}`);if(a.$tempId&&!(a.$op===void 0||a.$op==="link"||a.$op==="create"||a.$op==="update"||a.$op==="replace"))throw new Error(`Invalid op ${a.$op} for tempId. TempIds can be created, or linked when created in another part of the same mutation.`)}});};var _r=e=>{if(typeof e!="string")return {isPrefixed:false,obj:e};let t=e.match(/^([^:]+):([^:].*)$/);if(t){let[,r,n]=t;return {isPrefixed:true,obj:{$thing:r,...n.startsWith("_:")?{$tempId:n}:{$id:n}}}}return {isPrefixed:false,obj:e}},zr=(e,t)=>{let r=isArray(e[t])?e[t]:[e[t]];if(r.every(o=>typeof o=="object"))return;if(!r.every(o=>typeof o=="string"||isObject(o)&&"$op"in o&&o.$op==="replace"))throw new Error(`[Mutation Error] Replace can only be used with a single id, an array of ids, or objects with $op: replace. (Field: ${t} Nodes: ${JSON.stringify(r)})`);let n=e.$op==="create"?"link":"replace";e[t]=r.map(o=>{if(typeof o=="string"){if(o.startsWith("_:"))return {$tempId:o,$op:n};let{isPrefixed:i,obj:a}=_r(o);return i?{...a,$op:n}:{$id:o,$op:n}}return o});},Ur=(e,t,r)=>{let n=isArray(e[t])?e[t]:[e[t]],o=e.$op==="create"?"link":"replace";return e[t]=n.map(i=>{if(typeof i=="string"){if(i.startsWith("_:"))return {$tempId:i,$op:o};let{isPrefixed:a,obj:s}=_r(i);if(a)return {...s,$op:o};if(r.contentType==="FLEX")return i;throw new Error("[Wrong format] Field of contentType REF can't use strings as references unless they follow the format `$thing:$id`")}if(typeof i=="object"&&"$thing"in i||r.contentType==="FLEX")return i;throw new Error("[Wrong format] Field of contentType REF can use prefixed id strings, tempIds or objects indicating their $thing")}),e[t]};var Vr=(e,t)=>{let n=(isArray(e.$root)?e.$root:[e.$root]).map(o=>{let i=kr(o,o,t);return {...{...o.$thing?{}:{$thing:o.$entity||o.$relation},...o.$thingType?{}:{$thingType:Tr(o,t)},...o.$op?{}:{$op:i},...o.$bzId?{}:{$bzId:`R_${De()}`}},...o}});e.$root=isArray(e.$root)?n:n[0];};var ct=(e,t)=>{let r=t[tt];return isSet(r)?r.has("clean")?(Reflect.set(t,tt,r.add("clean")),true):false:(Reflect.set(t,tt,new Set(["clean"])),true)};var vr=(e,t,r)=>{if(ct("split_ids",e)){let n=(isArray(e[t])?e[t]:[e[t]]).flatMap(o=>{if(isObject(o)&&"$id"in o&&isArray(o.$id)){let i=o;if(j(r,i),!i.$bzId)throw new Error("[Internal Error] No bzId found");return i.$id.map((a,s)=>({...Me(i),$id:a,$bzId:`${i.$bzId}_${s}`,...Re(i)}))}return o});(n.length>0&&isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=n);}};var Hr=(e,t,r)=>{let n=at(t,r),[o]=n;e[t]={$thing:o.thing,$thingType:o.thingType,$op:"unlink",$bzId:`U_${v4()}`,[we]:r};};var ze=e=>{if(Array.isArray(e)){for(let t of e)if(ze(t))return true;return false}if(e.$fields)return true;for(let t in e){if(t.startsWith("$"))continue;let r=e[t];if(r&&typeof r=="object"&&ze(e[t]))return true}return false};var eo=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(ct("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");t==="$filter"&&e.$filter&&Object.keys(e.$filter).length===0&&(e.$filter=void 0);},to=(e,t)=>{},At=(e,t,r)=>{let n={$rootWrap:{$root:e}},o=ze(Array.isArray(e)?e:[e]),i=produce(n,a=>traverse(a,({value:s,parent:l,key:h,meta:c})=>{if(!(!l||!h)&&isObject(s)){let u=c.nodePath?.split(".")||[];if(u.some(p=>p.startsWith("%")))return;if(!("$root"in s)){if(!("$thing"in s||"$entity"in s||"$relation"in s)){let p=["$fields","$dbNode","$filter"],$=u.at(-1),g=u.at(-2);if(h==="$root")throw new Error("Root things must specify $entity or $relation");if(!p.includes($||"")&&!p.includes(g||"")&&!$?.startsWith("%")&&!g?.startsWith("%"))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(s)?current(s):s)}`)}}let d=s,f=u.includes("$filter");"$filter"in d&&d.$filter&&(d.$filter=Ie(d.$filter,d.$thing,t)),Object.keys(d).forEach(p=>{if(eo(d,p),p!=="$root"&&f||p!=="$root"&&(p.startsWith("$")||p.startsWith("%")))return;let $=p!=="$root"?Tt(t,d,p):{[K]:{fieldType:"rootField"}};if(!$)throw new Error(`[Internal] Field ${p} not found in schema`);let{fieldType:g}=$[K],y=["linkField","roleField"].includes(g),m=g==="refField",F=g==="rootField";if(g==="dataField")return to();if((y||m)&&(d[p]===null?y&&Hr(d,p,$):y?zr(d,p):Ur(d,p,$)),F){if(!("$root"in d))throw new Error(`[Internal] Field ${p} is a rootField but the object is not a root`);Vr(d,t);}(y||m)&&xr(d,p,$,u),(y||m)&&(Cr(d,p,$,t),Or(d,d[p],t)),(y||F)&&(vr(d,p,t),Dr(d,p,t),(isArray(d[p])?d[p]:[d[p]]).forEach(Q=>{let M=j(t,Q),{unidentifiedFields:R,usedLinkFields:I,usedFields:x,fields:J}=ce(M,Q);if(x.forEach(re=>{if(!J.includes(re))throw new Error(`[Schema] Field ${re} not found in the schema`)}),R.length>0)throw new Error(`Unknown fields: [${R.join(",")}] in ${JSON.stringify(s)}`);if(I.length>1){let re=M.linkFields?.filter(pe=>I.includes(pe.path));re?.some((pe,k)=>re.some((D,S)=>{if(k!==S&&pe.target!==D.target&&pe.relation===D.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||(qr(d,p,t,r),Pr(d,p,t,r)));});}}));return isArray(i.$rootWrap.$root),i.$rootWrap.$root};var Jr=e=>{let t=({value:r})=>(r&&typeof r=="object"&&"$id"in r&&(Object.keys(r).filter(i=>i.startsWith("$")).forEach(i=>delete r[i]),Object.keys(r).filter(i=>typeof i=="symbol").forEach(i=>delete r[i])),r);return produce(e,r=>traverse(r,t))};var Gr=async(e,t)=>{let r=c=>{let u=[],d=[],f=y=>{if(y.$id)return y.$id;let m=j(t,y),{idFields:F}=m;if(!F)throw new Error(`no idFields: ${JSON.stringify(y)}`);let[E]=F;if(!E)throw new Error(`no idField: ${JSON.stringify(y)}`);let Q=m.dataFields?.find(I=>I.path===E),M=_e({currentThing:y,fieldSchema:Q,mandatoryDependencies:true}),R=y[E]||y.$id||M;if(!R)throw new Error(`no idValue: ${JSON.stringify(y)}`);return R},p=y=>{if(y.$op==="create"){let m=f(y);if(u.find(F=>F.$id===m&&F.$op==="create"))throw new Error(`Duplicate id ${m} for node ${JSON.stringify(y)}`);u.push({...y,$id:m});return}y.$tempId&&y.$op==="match"||u.push(y);},$=y=>{if(y.$op==="create"){let m=f(y);if(u.find(F=>F.$id===m&&F.$op==="create"))throw new Error(`Duplicate id ${m} for edge ${JSON.stringify(y)}`);d.push({...y,$id:m});return}d.push(y);};return traverse(c,({value:y,parent:m,meta:F})=>{if(!isObject(y))return;let E=y;if(!F.nodePath?.includes(".$filter")&&E.$thing){if(!E.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(E)}`);if(!E.$bzId)throw new Error(`[internal error] BzId not found ${JSON.stringify(E)}`);let Q=j(t,E),{dataFields:M,roleFields:R,linkFields:I,refFields:x,usedFields:J}=ce(Q,E),re=()=>{if(E.$op==="create"||E.$op==="delete")return E.$op;if(E.$op==="update"){let D=J.filter(T=>M?.includes(T)),S=J.filter(T=>R?.includes(T)),b=J.filter(T=>I?.includes(T)),B=J.filter(T=>x?.includes(T));if(D.length>0)return "update";if(S.length>0||b.length>0||B.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(E)}`)}return "match"},pe={...E.$id&&{$id:E.$id},...E.$tempId&&{$tempId:E.$tempId},...E.$filter&&{$filter:E.$filter},$thing:E.$thing,...E.$thingType&&{$thingType:E.$thingType},...shake(pick(E,M||[""])),$op:re(),$bzId:E.$bzId};p(pe);let k=E[we];if(k?.[K].fieldType==="linkField"){if((E.$op==="link"||E.$op==="unlink")&&(E.$id||E.$filter)){if(E.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");u.push({...E,$op:"match"});}let D=k.$things.includes(E.$thing),S=D?E.$bzId:`LT_${v4()}`,B=Sr(c,m,F).$bzId;if(!B)throw new Error("No parent id found");let T=()=>E.$op==="delete"?D?"match":"delete":E.$op==="unlink"?D?"unlink":"delete":E.$op==="link"||E.$op==="create"?D?"link":"create":E.$op==="replace"?"replace":"match",w=j(t,{$thing:k.relation,$thingType:"relation"});if(!Object.keys(w.roles).includes(k.plays))throw new Error(`[Wrong format] Field ${k.plays} is not a role of relation ${k.relation}`);let N={$bzId:S,$thing:D?E.$thing:k.relation,$thingType:"relation",...E.$tempId?{$tempId:E.$tempId}:{},$op:T(),...D?{}:{[k.path]:E.$bzId},[k.plays]:B,[we]:k,[ke]:"linkField"};$(N),(E.$op==="unlink"||T()==="unlink")&&D&&$({$thing:k.relation,$thingType:"relation",$bzId:S,$op:"match",[k.plays]:B,[we]:k,[ke]:"linkField"});}if(E.$thingType==="relation"){let D=le(E,(B,T)=>R.includes(B)),S=mapEntries(D,(B,T)=>isArray(T)?[B,T]:isObject(T)?[B,T.$bzId]:[B,T]),b=le(y,(B,T)=>B.startsWith("$")||B.startsWith("Symbol"));if(Object.keys(D).filter(B=>!B.startsWith("$")).length>0){if(E.$op==="create"||E.$op==="delete"){let B=()=>{if(E.$op==="create")return "link";if(E.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},T=j(t,E).roles,w=mapEntries(S,(N,q)=>{let A=T[N]?.cardinality;if(!A)throw new Error(`Role ${N} not found in schema`);return Array.isArray(q)?A==="ONE"?q.length>1?[N,q.map(v=>v.$bzId||v)]:[N,q[0].$bzId||q[0]]:[N,q.map(v=>v.$bzId||v)]:[N,q.$bzId||q]}),O={...b,$thing:E.$thing,$thingType:"relation",$op:B(),...w,$bzId:E.$bzId,[ke]:"roleField"};$(O);return}if(E.$op==="match"||E.$op==="update"&&Object.keys(D).length>0){Object.entries(D).forEach(([T,w])=>{let O=isArray(w)?w:[w],N=q=>q==="create"||q==="replace"?"link":q;O.forEach(q=>{if(!q)return;let A=N(q.$op);if(A==="replace")throw new Error("Not supported yet: replace on roleFields");let v={...b,$thing:E.$thing,$thingType:"relation",$op:A==="delete"?"unlink":A,[T]:q.$bzId,$bzId:E.$bzId,[ke]:"roleField"};$(v);});});}}}}}),[u,d]},[n,o]=r(e),i=n.reduce((c,u)=>{if(!u.$bzId)return [...c,u];let d=c.findIndex(f=>f.$bzId===u.$bzId);if(d===-1)return [...c,u];if(c[d].$op==="create"&&u.$op==="match")return c;if(c[d].$op==="match"&&(u.$op==="create"||u.$op==="match"))return [...c.slice(0,d),u,...c.slice(d+1)];if(c[d].$op==="update"&&u.$op==="update")return [...c.slice(0,d),{...c[d],...u},...c.slice(d+1)];if(c[d].$op==="update"&&u.$op==="match"||c[d].$op==="match"&&u.$op==="update")return [...c.slice(0,d),{...c[d],...u,$op:"update"},...c.slice(d+1)];if(c[d].$op==="delete"&&u.$op==="delete"){if(JSON.stringify(c[d].$filter)===JSON.stringify(u.$filter))return c;throw new Error(`[Wrong format] Can't delete the same thing with different filters. Existing: ${c[d].$filter}. Current: ${u.$filter}`)}throw new Error(`[Wrong format] Wrong operation combination for $tempId/$id "${u.$tempId||u.$id}". Existing: ${c[d].$op}. Current: ${u.$op}`)},[]),a=o.reduce((c,u)=>{let d=c.find(f=>(f.$id&&f.$id===u.$id||f.$bzId&&f.$bzId===u.$bzId)&&f.$thing===u.$thing&&f.$op===u.$op);if(d){let f={...d};return Object.keys(u).forEach($=>{if(typeof $=="symbol"||$.startsWith("$"))return;let g=d[$],y=u[$];Array.isArray(g)&&Array.isArray(y)?f[$]=Array.from(new Set([...g,...y])):!Array.isArray(g)&&Array.isArray(y)?g!==void 0?f[$]=Array.from(new Set([g,...y])):f[$]=y:Array.isArray(g)&&!Array.isArray(y)?y!==void 0&&(f[$]=Array.from(new Set([...g,y]))):g!==null&&y!==null&&g!==void 0&&y!==void 0?f[$]=Array.from(new Set([g,y])):g==null&&(f[$]=y);}),[...c.filter($=>!(($.$id&&$.$id===u.$id||$.$bzId&&$.$bzId===u.$bzId)&&$.$thing===u.$thing&&$.$op===u.$op)),f]}return [...c,u]},[]);i.forEach(c=>{if((c.$thingType==="relation"||"relation"in c)&&a.filter(u=>u.$bzId===c.$bzId||u.$tempId&&u.$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(Jr(c))}`)}});let s=[...i,...a],l=new Set(s.filter(c=>c.$tempId).map(c=>c.$tempId)),h=Array.from(l).filter(c=>!s.some(u=>u.$tempId===c&&u.$op==="create"));if(h.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${h.join(", ")}`);return {mergedThings:i,mergedEdges:a}};var en=new Set((process.env.BORM_LOG_LEVEL||"").split(",").map(e=>e.trim()).filter(e=>!!e)),lo=(e,...t)=>{(Array.isArray(e)?e.some(n=>en.has(n)):en.has(e))&&console.log(...t);},oe=(...e)=>lo("debug",...e);var se="0.13.6";var{createMachine:ye,guard:kt,interpret:ge,invoke:V,reduce:_,state:de,transition:z}=co;var on=(e,t)=>{if(!t)return;let r=ho(t);return po(r,e.query)},ho=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),po=(e,t)=>produce(e,r=>traverse(r,({value:n})=>{if(isObject(n)){let o=n;Object.keys(o).forEach(i=>{(o[i]===void 0||o[i]===null||isArray(o[i])&&o[i].length===0)&&(t?.returnNulls?o[i]=null:delete o[i]),o[i]===void 0&&delete o[i];}),Object.getOwnPropertySymbols(o).forEach(i=>{delete o[i];}),t?.noMetadata===true&&Object.keys(o).forEach(i=>{i.startsWith("$")&&delete o[i];});}}));var sn=async(e,t,r)=>r?(i=>produce(i,a=>traverse(a,({value:s})=>{if(isObject(s)){let l=s;if(!l.$thing)return;if(l.$thing){let h=j(e,l),{virtualFields:c}=h,u=l[ee];if(!u)throw new Error(`[Internal] QueryPath is missing. Value: ${JSON.stringify(l)}`);let d=getNodeByPath(t,u);if(d.$fieldType==="ref")return;let f=d.$fields.map($=>$.$path),p=d.$excludedFields;c.forEach($=>{if(p?.includes($)||f.length>0&&!f.includes($))return;let g=h.dataFields?.find(y=>y.path===$);if(g?.default){let y=_e({currentThing:l,fieldSchema:g,mandatoryDependencies:true});l[$]=y;}else if(l[$]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${$}`)}),p&&p.forEach($=>{if(typeof $!="string")throw new Error("[Internal] ExcludedField is not a string");delete l[$];});}}})))(r):void 0;var Je={$eq:"$=",$not:"$!",$or:"$OR",$and:"$AND",$in:"$IN",$id:"record::id(id)",$exists:"$exists"},Ee=(e,t,r)=>{if(e==null)return e;let n=isArray(e),i=(n?e:[e]).map(a=>{let l=Object.keys(a).reduce((h,c)=>{let u=a[c];if(c.startsWith("$")){if(["$or","$and","$not"].includes(c))return {...h,[c]:void 0,[Je[c]]:Ee(u,t,r)};if(c==="$id")return {...h,$id:void 0,[Je[c]]:{$IN:isArray(u)?u:[u]}};if(c==="$thing")return h;if(c==="$exists")return {...h,$exists:void 0,[Je[c]]:u};if(c==="$eq")return {...h,$eq:void 0,[Je[c]]:u};if(c==="$in")return {...h,$in:void 0,[Je[c]]:u};throw new Error(`Unknown filter operator ${c}`)}let d=t in r.entities?r.entities[t]:r.relations[t],[f,p]=nt(d,c);if(f==="idField"){if(d.idFields.length>1)throw new Error("Multiple id fields not supported");return {...h,"record::id(id)":{$IN:isArray(u)?u:[u]}}}if(f==="dataField")return {...h,[c]:Ee(u,t,r)};if(f==="linkField"||f==="roleField"){let g=p[Te].queryPath;return {...h,[g]:Ee(u,t,r)}}throw new Error(`Field ${c} not found in schema, Defined in $filter`)},{});return shake(l)});return n?i:i[0]},$e=e=>{if(e==null)return "";let t=Object.entries(e),r=[];return t.forEach(([n,o])=>{if(["$OR","$AND","$!"].includes(n)){let i=n.replace("$",""),a=Array.isArray(o)?o.map(s=>$e(s)):[$e(o)];i==="!"?r.push(`!(${a.join(" AND ")})`):r.push(`(${a.join(` ${i} `)})`);return}if(isObject(o))if(n.includes("<-")||n.includes("->")){let i=$e(o);r.push(`${n}[WHERE ${i}]`);}else if(n.startsWith("$parent.[")){let i=$e(o),a=n.replace("$parent.","").replace(/^\[(.*)\]$/,"$1");r.push(`fn::as_array(${a})[WHERE id && ${i}]`);}else if(n.startsWith("$parent")){let i=$e(o),a=n.replace("$parent.","");r.push(`fn::as_array(${a})[WHERE id && ${i}]`);}else {if(n.startsWith("$"))throw new Error(`Invalid key ${n}`);{let i=Object.keys(o);if(i.length===1&&i[0].startsWith("$")){let[a]=i,s=o[a];if(a==="$exists")if(s===true)r.push(`${n} IS NOT NONE`);else if(s===false)r.push(`${n} IS NONE`);else throw new Error(`Invalid value for $exists: ${s}`);else {let l=a.replace("$","");if(Array.isArray(s))r.push(`${n} ${l} [${s.map(h=>h===null?"NONE":`'${h}'`).join(", ")}]`);else if(isObject(s)){let h=$e(s);r.push(`${n} ${l} ${h}`);}else r.push(`${n} ${l} ${s===null?"NONE":`'${s}'`}`);}}else throw new Error(`Invalid key ${n}`)}}else if(Array.isArray(o)){let i=n.startsWith("$")?n.replace("$",""):"IN";r.push(`${n} ${i} [${o.map(a=>a===null?"NONE":`'${a}'`).join(", ")}]`);}else {let i=n.startsWith("$")?n.replace("$",""):"=";r.push(`${n} ${i} ${o===null?"NONE":`'${o}'`}`);}}),r.join(" AND ")},Ue=e=>`ORDER BY ${e.map(r=>{if(typeof r=="string")return r;let{field:n,desc:o}=r;return `${n}${o?" DESC":" ASC"}`}).join(", ")}`;var ln=e=>{let{queries:t,schema:r}=e;return t.map(n=>Bo({query:n,schema:r}))},Bo=e=>{let{query:t,schema:r}=e,{$thing:n,$fields:o,$filter:i,$offset:a,$limit:s,$sort:l}=t;if(o.length===0)return null;let h=[];h.push("SELECT");let c=qt({parentQuery:t,queries:o,level:1,schema:r});c&&h.push(c);let u=r.entities[n]||r.relations[n];if(!u)throw new Error(`Schema for ${n} not found`);let f=(u.subTypes?[n,...u.subTypes]:[n]).map(p=>te(p));if(t.$id)if(typeof t.$id=="string")h.push(`FROM ${f.map(p=>`${p}:\u27E8${t.$id}\u27E9`).join(",")}`);else if(isArray(t.$id)){let p=t.$id,$=f.flatMap(g=>p?.map(y=>`${g}:\u27E8${y}\u27E9`));h.push(`FROM ${$.join(",")}`);}else throw new Error("Invalid $id");else h.push(`FROM ${f.join(",")}`);if(i){let p=Ee(i,n,r),$=$e(p);h.push(`WHERE ${$}`);}return l&&h.push(Ue(l)),typeof s=="number"&&h.push(`LIMIT ${s}`),typeof a=="number"&&h.push(`START ${a}`),h.join(`
|
|
94
|
+
`)},qt=e=>{let{queries:t,schema:r,level:n,parentQuery:o}=e,i=[],a=o[ee];return i.push(L(`"${a}" as \`$$queryPath\``,n)),i.push(L("record::id(id) as `$id`",n)),i.push(L("record::tb(id) as `$thing`",n)),t.forEach(s=>{let l=Fo({query:s,level:n,schema:r});l&&i.push(l);}),i.length===0?null:i.join(`,
|
|
95
|
+
`)},Fo=e=>{let{query:t,schema:r,level:n}=e;if(t.$fieldType==="data")return bo({query:t,level:n});if(t.$fieldType==="ref")throw new Error("Ref fields are not supported in this context");return t.$fieldType==="link"?wo({query:t,level:n,schema:r}):t.$fieldType==="role"?To({query:t,level:n,schema:r}):null},bo=e=>{let{query:t,level:r}=e;return t.$isVirtual?null:t.$path==="id"?L(`record::id(${t.$path}) AS ${t.$as}`,r):t.$path===t.$as?L(`\`${t.$path}\``,r):L(`\`${t.$path}\` AS \`${t.$as}\``,r)},wo=e=>{let{query:t,schema:r,level:n}=e,{$fields:o,$filter:i,$offset:a,$limit:s,$sort:l}=t;if(o.length===0)return null;let h=[];h.push(L("(",n));let c=n+1;h.push(L("SELECT",c));let u=qt({parentQuery:t,queries:o,level:c+1,schema:r});u&&h.push(u);let d=t[ie][Te].queryPath;if(h.push(L(`FROM ${d}`,c)),i){let f=Ee(i,t.$thing,r),p=$e(f);h.push(`WHERE ${p}`);}return l&&h.push(L(Ue(l),c)),typeof s=="number"&&h.push(L(`LIMIT ${s}`,c)),typeof a=="number"&&h.push(L(`START ${a}`,c)),h.push(L(`) AS \`${t.$as}\``,n)),h.join(`
|
|
96
|
+
`)},To=e=>{let{query:t,schema:r,level:n}=e;if(t.$fields.length===0)return null;let o=[];o.push(L("(",n));let i=n+1;o.push(L("SELECT",i));let a=i+1,s=qt({parentQuery:t,queries:t.$fields,level:a,schema:r});s&&o.push(s);let l=t[ie][Te].queryPath;if(o.push(L(`FROM ${l}`,i)),t.$filter){let h=Ee(t.$filter,t.$playedBy.thing,r),c=$e(h);o.push(`WHERE ${c}`);}return o.push(L(`) AS \`${t.$as}\``,n)),o.join(`
|
|
97
|
+
`)};var cn=e=>{let{queries:t,schema:r}=e;return t.map(n=>So({query:n,schema:r}))},So=e=>{let{query:t,schema:r}=e,{$thing:n,$fields:o,$filter:i,$offset:a,$limit:s,$sort:l}=t;if(o.length===0)return null;let h=r.entities[n]||r.relations[n];if(!h)throw new Error(`Schema for ${n} not found`);let c=t[ee],u=Nt(c),d=dn(o.filter(Q=>Q.$fieldType==="data")),f=un(o.filter(Q=>Q.$fieldType==="link"||Q.$fieldType==="role"),r),p=hn(o.filter(Q=>Q.$fieldType==="ref")),$=[...u,...d,...f,...p].join(`,
|
|
98
|
+
`),g=Lo(t,h),y=i?`WHERE id AND (${$e(Ee(i,n,r))})`:"WHERE id",m=l?Ue(l):"",F=typeof s=="number"?`LIMIT ${s}`:"",E=typeof a=="number"?`START ${a}`:"";return `SELECT ${$} ${g} ${y} ${m} ${F} ${E}`},Lo=(e,t)=>{let n=(t.subTypes?[e.$thing,...t.subTypes]:[e.$thing]).map(a=>te(a)),o=(a,s)=>`${a}:\`${s}\``,i=a=>n.flatMap(s=>a.map(l=>o(s,l))).join(",");if(!e.$id)return `FROM ${n.join(",")}`;if(typeof e.$id=="string")return `FROM ${i([e.$id])}`;if(Array.isArray(e.$id))return `FROM ${i(e.$id)}`;throw new Error("Invalid $id")},Nt=e=>[`"${e}" as \`$$queryPath\``,"id && record::id(id) || null as `$id`","id && record::tb(id) || null as `$thing`"],dn=e=>e.map(t=>t.$path==="id"?`record::id(${t.$path}) AS ${t.$as}`:t.$path===t.$as?`\`${t.$path}\``:`\`${t.$path}\` AS \`${t.$as}\``),un=(e,t)=>e.map(r=>{if(!r[ee])throw new Error(`[Internal] QueryPath is missing. Value: ${JSON.stringify(r)}`);let n=Nt(r[ee]),o=dn(r.$fields.filter(f=>f.$fieldType==="data")),i=un(r.$fields.filter(f=>f.$fieldType==="link"||f.$fieldType==="role"),t),a=hn(r.$fields.filter(f=>f.$fieldType==="ref")),s=[...n,...o,...i,...a].filter(Boolean).join(`,
|
|
99
|
+
`),l=`FROM $parent.\`${r[ie].path}\`[*]`,h=r.$filter&&Object.keys(r.$filter).length>0?`WHERE id AND(${$e(Ee(r.$filter,r.$thing,t))})`:"WHERE id",c=r.$sort?Ue(r.$sort):"",u=typeof r.$limit=="number"?`LIMIT ${r.$limit}`:"",d=typeof r.$offset=="number"?`START ${r.$offset}`:"";return `( SELECT ${s} ${l} ${h} ${c} ${u} ${d} ) AS \`${r.$as}\``}).filter(r=>r),hn=e=>e.map(t=>{if(!t[ee])throw new Error(`[Internal] QueryPath is missing. Value: ${JSON.stringify(t)}`);let r=Nt(t[ee]);if(t.$fields?.some(a=>isObject(a)))throw new Error("[Unsupported]: Can't query nested ref fields yet");let o=[...r,"id && null || $this as `$value`",...t.$justId?"":t.$fields?.map(a=>`\u27E8${a}\u27E9`)||["*"]].join(`,
|
|
100
|
+
`),i=`FROM $parent.\`${t[ie].dbPath}\``;return `( SELECT ${o} ${i}) AS \`${t.$as}\``});var fn=e=>{let{res:t,queries:r,schema:n}=e;return t.map((i,a)=>$n(r[a],i,n))},$n=(e,t,r)=>{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 Pt(e,t[0],r)}if(t.length>=1)return t.map(n=>Pt(e,n,r))}else throw new Error("res is unexpectedly not an array")},Pt=(e,t,r)=>{let n=t.$thing||t.tb,o=n in r.entities?"entity":n in r.relations?"relation":"error";if(o==="error")throw new Error(`[Internal] The $thing ${n} is not defined in the schema.`);let i={[ee]:t.$$queryPath,$id:t.$id,$thing:lr(n),$thingType:o};return e.$fields.forEach(a=>{let s=a.$as,l=t[s];a.$path==="id"&&e.$idNotIncluded||(i[s]=Do(a,l,r));}),i},Do=(e,t,r)=>{if(t==null||isArray(t)&&t.length===0)return null;if(e.$fieldType==="data"){let{contentType:n}=e[ie];return pn(t,n)??null}if(e.$fieldType==="ref"){let o=(isArray(t)?t:[t]).map(a=>{if(a.$thing){let s=Y(r,a.$thing),[l]=s.idFields;if(e.$justId)return a.$id;let h=u=>u&&typeof u=="object"&&"id"in u&&"tb"in u?u.id:u;return {...mapEntries(a,(u,d)=>isArray(d)?[u,d.map(f=>h(f))]:[u,h(d)]),[ee]:a.$$queryPath,[l]:a.$id}}return a.$value?pn(a.$value,"FLEX"):a}),{cardinality:i}=e[ie];return i==="ONE"?o[0]:o}return e.$justId?e.$filterByUnique||e[ie].cardinality==="ONE"?t[0]?.$id??null:t?.map(n=>n.$id)??[]:e.$filterByUnique||e[ie].cardinality==="ONE"?Pt(e,t[0],r):$n(e,t,r)},pn=(e,t)=>{let r=isArray(e)?e:[e];if(t==="DATE"){let n=r.map(o=>new Date(o).toISOString());return isArray(e)?n:n[0]}if(t==="FLEX"){let n=r.map(o=>isDate(o)?new Date(o).toISOString():o);return isArray(e)?n:n[0]}return e};var mn=async e=>{let{client:t,queries:r,config:n}=e,o=`
|
|
111
101
|
BEGIN TRANSACTION;
|
|
112
102
|
${r.join(";")};
|
|
113
103
|
COMMIT TRANSACTION;
|
|
114
|
-
`;return n.query?.debugger&&
|
|
115
|
-
`)},
|
|
104
|
+
`;return n.query?.debugger&&oe(`batchedQuery[${se}]`,JSON.stringify({batchedQuery:o})),await t.query(o)};var xt=z("error","error",_((e,t)=>({...e,error:t.error}))),Io=ye("build",{build:V(async e=>{let{linkMode:t}=e.config.dbConnectors.find(r=>r.provider==="surrealDB").providerConfig;if(t==="edges")return ln({queries:e.bql.queries,schema:e.schema});if(t==="refs")return cn({queries:e.bql.queries,schema:e.schema})},z("done","run",_((e,t)=>({...e,surql:{...e.surql,queries:t.data}}))),xt),run:V(async e=>mn({client:e.client,queries:fe(e.surql.queries),config:e.config}),z("done","parse",_((e,t)=>({...e,surql:{...e.surql,res:t.data}}))),xt),parse:V(async e=>fn({res:fe(e.surql.res),queries:e.bql.queries,schema:e.schema,config:e.config}),z("done","success",_((e,t)=>({...e,bql:{...e.bql,res:t.data}}))),xt),success:de(),error:de()},e=>e),Oo=async e=>new Promise((t,r)=>{ge(Io,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),yn=async(e,t,r,n)=>Oo({bql:{queries:e},surql:{},schema:t,config:r,client:n,error:null});var dt=e=>{let{$filter:t,$var:r,$thing:n,schema:o,depth:i}=e,a=qo(t,Y(o,n)),{$not:s,...l}=a,h=[];if(_t(s)){let u=jt(s,r,n,o,i,true);h.push(...u);}else if(s!==void 0)throw new Error("$not must be a PositiveFilter object");let c=jt(l,r,n,o,i,false);return h.push(...c),h.join(`
|
|
105
|
+
`)},jt=(e,t,r,n,o,i)=>{let a=Y(n,r),s=[];for(let[l,h]of Object.entries(e)){if(l.startsWith("$")){let d=l.toLowerCase();if(d==="$and"||d==="$or"){let p=(isArray(h)?h:[h]).map(g=>{if(_t(g))return jt(g,t,r,n,o+1,i).join(`
|
|
116
106
|
`);throw new Error(`Invalid subfilter in ${d}: ${JSON.stringify(g)}`)}),$=p.join(d==="$and"?`
|
|
117
|
-
`:" } or { ");d==="$or"&&p.length>1?s.push(L(`{ ${$} };`,
|
|
118
|
-
${y}`);}let f=
|
|
107
|
+
`:" } or { ");d==="$or"&&p.length>1?s.push(L(`{ ${$} };`,o)):s.push(L($,o));continue}continue}if(a.dataFields?.find(d=>d.dbPath===l||d.path===l)){let d=Ao(l,h,t,o,i);s.push(...d);continue}let u=a.linkFields?.find(d=>d.path===l);if(u){let d=ko(u,h,t,n,o,i);s.push(...d);continue}if(a.thingType==="relation"){let d=a.roles[l];if(d){let f=Co(d,h,t,r,n,o,i);s.push(...f);continue}}throw new Error(`"${r}" does not have property "${l}"`)}return s},Ao=(e,t,r,n,o)=>{let i=[];if(isObject(t)&&!isArray(t))for(let[a,s]of Object.entries(t)){let l=a.toLowerCase(),h="";switch(l){case "$eq":h=`$${r} has ${e} ${me(s)};`;break;case "$ne":h=`not { $${r} has ${e} ${me(s)}; };`;break;case "$in":{if(!isArray(s))throw new Error("Value for $in operator must be an array");let c=s.map(u=>`$${r} has ${e} ${me(u)};`);h=Xe(c),o&&(h=`not { ${h} };`);break}case "$nin":if(!isArray(s))throw new Error("Value for $nin operator must be an array");for(let c of s){let u=`not { $${r} has ${e} ${me(c)}; };`;i.push(L(u,n));}continue;case "$exists":if(s===true)h=`$${r} has ${e} $${e}_${v4()};`;else if(s===false)h=`not { $${r} has ${e} $${e}_${v4()}; };`;else throw new Error(`Invalid value for $exists: ${s}`);break;default:throw new Error(`Unsupported operator "${a}" for data field "${e}"`)}o&&(h=`not { ${h} };`),i.push(L(h,n));}else if(isArray(t)){let a=t.map(l=>`$${r} has ${e} ${me(l)};`),s=Xe(a);s&&(o&&(s=`not { ${s} };`),i.push(L(s,n)));}else {let a=`$${r} has ${e} ${me(t)};`;o&&(a=`not { ${a} };`),i.push(L(a,n));}return i},ko=(e,t,r,n,o,i)=>{let a=[],[s]=e.oppositeLinkFieldsPlayedBy,h=Y(n,s.thing).idFields?.[0];if(!h)throw new Error(`"${s.thing}" does not have an id field`);let c=`${s.thing}_${v4()}`,u="";if(e.target==="relation")if(t===null)u=i?`(${e.plays}: $${r}) isa ${e.relation};`:`not { (${e.plays}: $${r}) isa ${e.relation}; };`;else if(isArray(t)){let d=t.map(f=>`(${e.plays}: $${r}) isa ${e.relation}, has ${h} ${me(f)};`);u=Xe(d),i&&(u=`not { ${u} };`);}else u=`(${e.plays}: $${r}) isa ${e.relation}, has ${h} ${me(t)};`,i&&(u=`not { ${u} };`);else if(t===null)u=i?`$${c} isa ${s.thing}; (${e.plays}: $${r}, ${s.plays}: $${c}) isa ${e.relation};`:`not { $${c} isa ${s.thing}; (${e.plays}: $${r}, ${s.plays}: $${c}) isa ${e.relation}; };`;else if(isArray(t)){let d=t.map(f=>`$${c} isa ${s.thing}, has ${h} ${me(f)}; (${e.plays}: $${r}, ${s.plays}: $${c}) isa ${e.relation};`);u=Xe(d),i&&(u=`not { ${u} };`);}else u=`$${c} isa ${s.thing}, has ${h} ${me(t)}; (${e.plays}: $${r}, ${s.plays}: $${c}) isa ${e.relation};`,i&&(u=`not { ${u} };`);return a.push(L(u,o)),a},Co=(e,t,r,n,o,i,a)=>{let s=[],[l]=e.playedBy||[],c=Y(o,l.thing).idFields?.[0];if(!c)throw new Error(`"${l.thing}" does not have an id field`);let u=`${l.thing}_${v4()}`,d=v4(),f=`${r}_${d}`;s.push(L(`$${f} isa ${n};`,i));let p="";if(t===null)p=`$${f} (${l.plays}: ${u});`,a?s.push(L(p,i)):s.push(L(`not { ${p} };`,i));else if(isArray(t)){let $=t.map(g=>`$${u} isa ${l.thing}, has ${c} ${me(g)}; $${f} (${l.plays}: $${u});`);p=Xe($),a?s.push(L(`not { ${p} };`,i)):s.push(L(p,i));}else p=`$${u} isa ${l.thing}, has ${c} ${me(t)}; $${f} (${l.plays}: $${u});`,a?s.push(L(`not { ${p} };`,i)):s.push(L(p,i));return s.push(L(`$${r} is $${f};`,i)),s},Xe=e=>{if(e.length>1)return `{ ${e.join(" } or { ")} };`;if(e.length===1)return e[0];throw new Error("No alternatives provided to joinAlt")},me=e=>{if(typeof e=="string")return `'${e}'`;if(typeof e=="number"||typeof e=="boolean")return `${e}`;if(e instanceof Date)return `'${e.toISOString().replace("Z","")}'`;if(isObject(e)){if("$id"in e){let t=e.$id;return isArray(t)?`like "^(${t.join("|")})$"`:me(t)}throw new Error("Cannot serialize complex object values in filter")}throw new Error(`Unsupported value type: ${typeof e}`)},qo=(e,t)=>{let r={};if(t.dataFields?.forEach(a=>{a.path!==a.dbPath&&(r[a.path]=a.dbPath);}),Object.keys(r).length===0)return e;let{$not:n,...o}=e,i=gn(o,r);return n&&_t(n)&&(i.$not=gn(n,r)),i},gn=(e,t)=>{let r={};return Object.entries(e).forEach(([n,o])=>{let i=t[n]||n;r[i]=o;}),r},_t=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);var zt="___",Bn=async e=>{let{queries:t,schema:r}=e;return t.map(n=>No({query:n,schema:r}))},No=e=>{let{query:t,schema:r}=e,{$path:n,$thing:o,$filter:i,$fields:a,$sort:s,$offset:l,$limit:h,$id:c}=t;if(!n)throw new Error("Path is not defined");let u=[],d=t[ee];if(u.push("match"),u.push(`$${n} isa ${o};`),i||c){let $=it(r,t),g={...i,...c?{[$]:c}:{}},y=dt({$filter:g,$var:n,$thing:o,schema:r,depth:0});u.push(`
|
|
108
|
+
${y}`);}let f=vt({schema:r,$thing:o,$var:n,$sort:s,depth:0});f&&u.push(f.match);let p=`M_${v4()}`;if(u.push(`?queryPath${p} = "${d}";`),u.push("fetch"),u.push(`?queryPath${p} as "queryPath";`),a){let $=a.filter(m=>m.$fieldType==="data");$&&$.length>0&&u.push(...Ut($,n,0));let g=a.filter(m=>m.$fieldType==="link");g&&g.length>0&&u.push(...Vt(g,n,n,0,r));let y=a.filter(m=>m.$fieldType==="role");y&&y.length>0&&u.push(...Wt(y,n,n,0,r));}return f&&u.push(f.sort),typeof l=="number"&&u.push(`
|
|
119
109
|
offset ${l};`),typeof h=="number"&&u.push(`
|
|
120
110
|
limit ${h};`),u.join(`
|
|
121
|
-
`)},
|
|
122
|
-
?queryPath${Q} = "${y}";`,o)),a.push(L("fetch",o)),a.push(L(`?queryPath${Q} as "queryPath";`,o));let M=l?.filter(x=>x.$fieldType==="data");M&&M.length>0&&a.push(...Jt(M,F,o));let R=l?.filter(x=>x.$fieldType==="link");R&&R.length>0&&a.push(...Xt(R,F,`${t}.${s.$var}`,o,i));let I=l?.filter(x=>x.$fieldType==="role");I&&I.length>0&&a.push(...Yt(I,F,`${t}.${s.$var}`,o,i));}E&&a.push(E.sort),typeof $=="number"&&a.push(L(`offset ${$};`,o)),typeof g=="number"&&a.push(L(`limit ${g};`,o)),a.push(L("};",n));}return a},Xt=(e,t,r,n,i)=>{let o=n+1,a=[];for(let s of e){let{$fields:l,$as:h,$justId:c,$idNotIncluded:u,$filterByUnique:d,$playedBy:f,$thing:p,$sort:$,$offset:g,$limit:y}=s,m=s[ee],F=`$metadata:{as:${h},justId:${c?"T":"F"},idNotIncluded:${u},filterByUnique:${d}}`;a.push(L(`"${r}.${F}.${s.$var}": {`,n)),a.push(L("match",o));let E=`${t}${Kt}${s.$var}`;if(a.push(L(`$${E} isa ${s.$thing};`,o)),s.$filter||s.$id){let M=at(i,s),R=s.$id?{[M]:s.$id}:{},I={...s.$filter,...R};a.push(ft({$filter:I,$var:E,$thing:s.$thing,schema:i,depth:o}));}let Q=Gt({schema:i,$thing:p,$var:E,$sort:$,depth:o});if(Q&&a.push(Q.match),s.$target==="role"?a.push(L(`$${t}_intermediary (${s.$plays}: $${t}, ${f.plays}: $${E}) isa ${s.$intermediary};`,o)):a.push(L(`$${E} (${s.$plays}: $${t});`,o)),l){let M=`M_${v4()}`;a.push(L(`?queryPath${M} = "${m}";`,o)),a.push(L("fetch",o)),a.push(L(`?queryPath${M} as "queryPath";`,o));let R=l?.filter(J=>J.$fieldType==="data");R&&R.length>0&&a.push(...Jt(R,E,o));let I=l?.filter(J=>J.$fieldType==="link");I&&I.length>0&&a.push(...Xt(I,E,`${t}.${s.$var}`,o,i));let x=l?.filter(J=>J.$fieldType==="role");x&&x.length>0&&a.push(...Yt(x,E,`${t}.${s.$var}`,o,i));}Q&&a.push(Q.sort),typeof g=="number"&&a.push(L(`offset ${g};`,o)),typeof y=="number"&&a.push(L(`limit ${y};`,o)),a.push(L("};",n));}return a},cs=e=>typeof e=="string"?{field:e,desc:!1}:{...e,desc:e.desc??!1},Gt=e=>{let{$var:t,$thing:r,schema:n,$sort:i,depth:o}=e,a=Y(n,r),s=[],l=[];if(i?.forEach(h=>{let c=cs(h),u=a.dataFields?.find(p=>p.path===c.field);if(!u)throw new Error(`"${r}" does not have data field "${c.field}"`);let d=`${c.field}_${v4()}`;s.push(L("{",o)),s.push(L(`$${t} has ${u.dbPath} $${d}_1;`,o+1)),s.push(L("not {",o+1)),s.push(L(`$${t} has ${u.dbPath} $${d}_2;`,o+2)),s.push(L(`$${d}_2 < $${d}_1;`,o+2)),s.push(L("};",o+1)),s.push(L(`?${d}_ = $${d}_1;`,o+1)),s.push(L("} or {",o)),s.push(L(`not { $${t} has ${u.dbPath} $${d}_1; };`,o+1)),s.push(L(`?${d}_ = "~";`,o+1)),s.push(L("};",o)),s.push(L(`?${d} = ?${d}_;`,o));let f=c.desc?"desc":"asc";l.push(`?${d} ${f}`);}),s.length!==0)return {match:s.join(""),sort:L(`sort ${l.join(", ")};`,o)}};var jn=async e=>{let{enrichedBqlQuery:t,rawBqlRequest:r,schema:n,config:i,rawTqlRes:o}=e;if(!t)throw new Error("BQL request not enriched");if(!o)throw new Error("TQL query not executed");return o.map((a,s)=>{let l=r[s],h=t[s];return us(a,l,h,n,i)})},us=(e,t,r,n,i)=>e.length===0?null:r.$filterByUnique?xn(e[0],t,n,i):e.map(o=>xn(o,t,n,i)),xn=(e,t,r,n)=>{let{dataFields:i,currentSchema:o,linkFields:a,roleFields:s,schemaValue:l}=Zt(e,r),h=er(i,o,n),c=rr(a,r,n),u=tr(s,r,n),d=t?.$fields?.every(p=>!o?.idFields?.includes(typeof p=="string"?p:p.$path));return {...c,...u,...l,...!n.query?.noMetadata&&t.$id?{$id:Array.isArray(t.$id)?h.id:t.$id}:{},...d?Object.fromEntries(Object.entries(h).filter(([p])=>!o?.idFields?.includes(p))):h}},Zt=(e,t)=>{let r=Object.keys(e),n=r.find(f=>f.endsWith(".$dataFields")),i=r.filter(f=>f.endsWith(".$multiVal"));if(!n)throw new Error("No dataFields");i?.length>0&&i.forEach(f=>{let p=f.replace(/\.\$multiVal$/,""),$=e[f][0][p].attribute;e[n][p]=$;});let o=e[n],a=n.split(".")[n.split(".").length-2];if(o.$metaData=a,o.length===0)throw new Error("No dataFields");let s=o.type,l={$thing:s.label,$thingType:s.root,[ee]:e.queryPath.value},h={[`$${l.$thingType}`]:l.$thing},c=j(t,h),u=r.filter(f=>{let p=$e(f.split(".").pop());return !f.endsWith(".$dataFields")&&c.linkFields?.some($=>$.path===p)}).map(f=>{let p=$e(f.split(".").pop()),$=$e(c.linkFields?.find(g=>g.path===p));return {$linkFields:e[f],$key:p,$metaData:f.split(".")[f.split(".").length-2],$cardinality:$.cardinality}}),d=r.filter(f=>{let p=f.split(".").pop();return p&&!f.endsWith(".$dataFields")&&c.thingType==="relation"&&c.roles?.[p]}).map(f=>{let p=$e(f.split(".").pop());return {$roleFields:e[f],$key:p,$metaData:f.split(".")[f.split(".").length-2],$cardinality:c.roles[p].cardinality}});return {dataFields:o,schemaValue:l,currentSchema:c,linkFields:u,roleFields:d}},er=(e,t,r)=>{let{$metaData:n}=e,{as:i}=hs(n),o=Object.entries(e).filter(([a])=>a!=="type"&&!a.startsWith("$")).flatMap(([a,s])=>{let l=t.dataFields?.find(d=>d.path===a||d.dbPath===a),h=a==="id",c=Array.isArray(i)?i.find(d=>d[a])?.[a]:a,u;if(l?.cardinality==="ONE"){if(u=s[0]?s[0].value:r.query?.returnNulls?null:void 0,l.contentType==="DATE"||l.contentType==="FLEX"&&s[0].type.value_type==="datetime"?u=u&&`${u}Z`:l.contentType==="JSON"&&(u=u&&JSON.parse(u)),h)return [[c,u],["$id",u]].filter(([d,f])=>f!==void 0)}else if(l?.cardinality==="MANY"){if(!isArray(s))throw new Error("Typedb fetch has changed its format");if(s.length===0)return r.query?.returnNulls?[[c,null]]:[];l.contentType==="DATE"?u=s.map(d=>`${d.value}Z`):l.contentType==="FLEX"?u=s.map(d=>d.type.value_type==="datetime"?`${d.value}Z`:d.value):l.contentType==="JSON"?u=s.map(d=>d.value&&JSON.parse(d.value)):u=s.map(d=>d.value);}return [[c,u]].filter(([d,f])=>f!==void 0)});return Object.fromEntries([...o])},tr=(e,t,r)=>{let n={};return e.forEach(i=>{let{$roleFields:o,$metaData:a,$cardinality:s}=i,{as:l,justId:h,idNotIncluded:c,filterByUnique:u}=_n(a);if(l===null)return;let d=o.map(f=>{let{dataFields:p,currentSchema:$,linkFields:g,roleFields:y,schemaValue:m}=Zt(f,t),F=er(p,$,r);if(h==="T")return F.id;let E=rr(g,t,r),Q=tr(y,t,r),M={...F};return c==="true"&&$?.idFields?.forEach(R=>delete M[R]),{...M,...E,...Q,...m}});d.length>0?n[l]=s==="MANY"&&u==="false"?d:d[0]:r.query?.returnNulls&&(n[l]=null);}),n},rr=(e,t,r)=>{let n={};return e.forEach(i=>{let{$linkFields:o,$metaData:a,$cardinality:s}=i,{as:l,justId:h,idNotIncluded:c,filterByUnique:u}=_n(a);if(l===null)return;let d=o.map(f=>{let{dataFields:p,currentSchema:$,linkFields:g,roleFields:y,schemaValue:m}=Zt(f,t),F=er(p,$,r);if(h==="T")return F.id;let E=rr(g,t,r),Q=tr(y,t,r),M={...F};return c==="true"&&$.idFields?.forEach(R=>delete M[R]),{...M,...E,...Q,...m}});n[l]=d.length>0?s==="MANY"&&u==="false"?d:d[0]:r.query?.returnNulls?null:void 0;}),n},_n=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,r=/justId:([a-zA-Z0-9_\-·]+)/,n=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,i=/filterByUnique:([a-zA-Z0-9_\-·]+)/,o=e.match(t),a=e.match(r),s=e.match(n),l=e.match(i);return {as:o?o[1]:null,justId:a?a[1]:null,idNotIncluded:s?s[1]:null,filterByUnique:l?l[1]:null}},hs=e=>{try{let r=(i=>{let o=i.replace("$metadata:","");return o=o.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),o=o.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(a,s,l)=>/^{.*}$/.test(l)?`:${l}`:`:${s}"${l}"`),o=o.replace(/\[([^\]]+)\]/g,(a,s)=>`[${s.split(",").map(l=>l.trim().startsWith("{")&&l.trim().endsWith("}")?l.trim():`"${l.trim()}"`).join(",")}]`),o})(e);return JSON.parse(r)}catch(t){return console.error(t),{as:[]}}};var mt=async(e,t)=>{let r=t.dbConnectors[0].id,n=e.typeDB?.get(r)?.session,i=e.typeDB?.get(r)?.client;if(!n||!n.isOpen()){if(!i)throw new Error("Client not found");n=await i.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(r,{client:i,session:n});}return {client:i,session:n}};var zn=async e=>{let{tqlRequest:t,dbHandles:r,config:n}=e,i=new TypeDBOptions;i.infer=!0;let{session:o}=await mt(r,n),a=await o.transaction(TransactionType.READ,i),[s,l]=await tryit(parallel)(t.length,t,async h=>await a.query.fetch(h).collect());if(s){await a.rollback();let h=s;throw new Error(`Error running TQL query: ${h.errors}`)}return await a.close(),l};var gs=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,Es=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,Bs=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,nr=z("error","error",_((e,t)=>({...e,error:t.error}))),Fs=Ee("build",{build:W(async e=>Pn({queries:e.bql.queries,schema:e.schema}),z("done","run",_(Es)),nr),run:W(async e=>zn({dbHandles:e.handles,tqlRequest:$e(e.tql.queries),config:e.config}),z("done","parse",_(Bs)),nr),parse:W(async e=>jn({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries,schema:e.schema,config:e.config,rawTqlRes:$e(e.tql.res)}),z("done","success",_(gs)),nr),success:ue(),error:ue()},e=>e),bs=async e=>new Promise((t,r)=>{ye(Fs,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),vn=async(e,t,r,n,i)=>bs({bql:{raw:e,queries:t},tql:{},schema:r,config:n,handles:i,error:null});var ws=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,ir=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,yt=z("error","error",_((e,t)=>({...e,error:t.error}))),Ts=Ee("enrich",{enrich:W(async e=>(se(`originalBQLQuery[${ae}]`,JSON.stringify(e.bql.raw)),Ar(e.bql.raw,e.schema)),z("done","adapter",_(ws)),yt),adapter:W(async e=>{let t={};e.bql.queries?.forEach((s,l)=>{let h=e.bql.raw[l],c=Y(e.schema,s.$thing),{id:u}=c.defaultDBConnector;if(c.db==="typeDB"){if(!t[u]){let f=e.handles.typeDB?.get(u)?.client;if(!f)throw new Error(`TypeDB client with id "${c.defaultDBConnector.id}" does not exist`);t[u]={db:"typeDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else if(c.db==="surrealDB"){if(!t[u]){let f=e.handles.surrealDB?.get(u)?.client;if(!f)throw new Error(`SurrealDB client with id "${c.defaultDBConnector.id}" does not exist`);t[u]={db:"surrealDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else throw new Error(`Unsupported DB "${c.db}"`);let d=t[u];d.rawBql.push(h),d.bqlQueries.push(s),d.indices.push(l);});let r=Object.values(t),n=r.map(s=>{if(s.db==="typeDB")return vn(s.rawBql,s.bqlQueries,e.schema,e.config,e.handles);if(s.db==="surrealDB")return kn(s.bqlQueries,e.schema,e.config,s.client);throw new Error(`Unsupported DB "${JSON.stringify(s,null,2)}"`)}),i=await Promise.all(n),o=r.flatMap((s,l)=>{let h=i[l];return s.indices.map((c,u)=>({index:c,result:h[u]}))});return o.sort((s,l)=>s.index<l.index?-1:s.index>l.index?1:0),o.map(({result:s})=>s)},z("done","postHooks",_(ir)),yt),postHooks:W(async e=>Tn(e.schema,$e(e.bql.queries),$e(e.bql.res)),z("done","clean",_(ir)),yt),clean:W(async e=>wn(e.config,$e(e.bql.res)),z("done","success",_(ir)),yt),success:ue(),error:ue()},e=>e),Ms=async e=>new Promise((t,r)=>{ye(Ts,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),He=async(e,t,r,n)=>Ms({bql:{raw:e},schema:t,config:r,handles:n,error:null});var or="___",Ls=Symbol.for("grandChildOfCreate"),Un=async(e,t,r,n)=>{let i=["$eq","$ne","$in","$nin","$gt","$gte","$lt","$lte","$exists"],o=(S,b)=>Object.keys(S).filter(B=>!B.startsWith("$")&&!i.includes(B)&&S[B]!==void 0?b?!j(t,S).dataFields?.find(w=>w.path===B):!0:!1);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(r.mutation?.preQuery===!1)return;let a=[];if(traverse(e,({parent:S,key:b,value:B})=>{S&&b&&!b.includes("$")&&!i.includes(b)&&isObject(S)?(Array.isArray(S[b])?S[b]:[S[b]]).forEach(w=>{if(isObject(w)){if(S.$op!=="create")a.includes(w.$op)||a.push(w.$op);else if(w.$op==="delete"||w.$op==="unlink")throw new Error(`Cannot ${w.$op} under a create`)}}):!S&&isObject(B)&&(a.includes(B.$op)||a.push(B.$op));}),!a.includes("delete")&&!a.includes("unlink")&&!a.includes("replace")&&!a.includes("update")&&!a.includes("link"))return;let l=(S=>{let b=(B,T)=>{let w=[],O={},N=["$op","$bzId","$parentKey"],q=["$relation","$entity","$id",...N];for(let C in B)if(!N.includes(C)&&!(q.includes(C)&&!T))if(!C.includes("$")&&(isObject(B[C])||Array.isArray(B[C]))){let V=Qs(B[C]);if(Array.isArray(V)&&V.length>0)V.forEach(be=>{let we={$path:C,...b(be),...be.$filter&&{$as:be.$bzId}};w.find(X=>X.$path===we.$path&&!X.$filter)||(w=[...w,we]);});else {let be={$path:C,...b(V),...!V.$filter&&{$as:V.$bzId}};w=[...w,be];}}else O[C]=B[C];return {...O,$fields:w}};return S.map(B=>b(B,!0))})(Array.isArray(e)?e:[e]),c=(await He(l,t,{...r,query:{...r.query,returnNulls:!0}},n)).bql.res,u=(S,b)=>{let B=S.$id||S.id||S.$bzId;if(S.$objectPath){let{$objectPath:T}=S,w=T?.beforePath||"root",O=Array.isArray(T.ids)?`[${T.ids}]`:T.ids;return {beforePath:`${w}.${O}___${T.key}`,ids:B,key:b}}return {beforePath:"root",ids:B,key:b}},d=(S,b)=>{let B=S?.beforePath||"root";if(typeof B!="string")throw new Error("[PQ]objectPathToKey: root is not a string");let T=(Array.isArray(S?.ids)?`[${S?.ids}]`:S?.ids);return `${B}.${T}___${S?.key}`},f=S=>{if(S.includes("[")&&S.includes("]")){let[b,B,T]=S.split(/[[\]]/);return B.split(",").map(O=>`${b}${O}${T}`)}return [S]},p={};(S=>produce(S,b=>traverse(b,({key:B,parent:T})=>{if(T&&B&&T.$id&&!B.includes("$")){let w=u(T,B),O=d(w);if(Array.isArray(T[B])){let N=[];T[B].forEach(q=>{isObject(q)?(q.$objectPath=w,N.push(q.$id.toString())):q&&N.push(q.toString());}),p[O]={$objectPath:w,$ids:N};}else {let N=T[B];isObject(N)?(p[O]={$objectPath:w,$ids:[N.$id.toString()]},N.$objectPath=w):N?p[O]={$objectPath:w,$ids:[N.toString()]}:N===null&&(p[O]=null);}}})))(c||{});let g=S=>produce(S,b=>traverse(b,({key:B,value:T,parent:w})=>{w&&B&&!B.includes("$")&&(Array.isArray(T)||isObject(T))&&!Array.isArray(w)&&(Array.isArray(w[B])?w[B].forEach(O=>{typeof O!="string"&&(O.$objectPath=u(w,B),O.$parentIsCreate=w.$op==="create",O[Ls]=w.$parentIsCreate||w[Symbol.for("grandChildOfCreate")]);}):isObject(w[B])&&(w[B].$parentIsCreate=w.$op==="create",w[B][Symbol.for("grandChildOfCreate")]=w.$parentIsCreate||w[Symbol.for("grandChildOfCreate")],w[B].$objectPath=u(w,B)));})),y=g(e),m=S=>{let b=[];return S.forEach(T=>{if(!T.$id&&!T.id&&!T.$tempId)if(T.$filter){let w=d({...T.$objectPath,key:T.$bzId}),O=p[w];O&&(Array.isArray(O.$ids)?O.$ids:[O.$ids]).forEach(q=>{let C={...T,$id:q,$bzId:`T4_${v4()}`,$filterBzId:T.$bzId};b.push(C);});}else {let w=d(T.$objectPath),O=p[w];O?O?.$ids?.forEach(N=>{let q={...T,$id:N,$bzId:`T4_${v4()}`};b.push(q);}):b.push(T);}else b.push(T);}),b.map(T=>{let w={...T};return o(w,!0).forEach(O=>{let N=Array.isArray(w[O])?w[O]:[w[O]],q=m(N);w[O]=q;}),w})},F=m(Array.isArray(y)?y:[y]),E=g(F),M=(S=>{let b=B=>{let T=X=>{let Z=[],H=[],P=[];return X.forEach(v=>{let le=o(v,!0);if(le.length>0){let k=!1;le.forEach(U=>{(Array.isArray(v[U])?v[U]:[v[U]]).filter(ne=>!ne.$id&&!ne.id&&typeof v=="object").length&&(k=!0);}),k?Z.push(v):H.push(v);}else v.$id?P.push({...v,$bzId:v.$tempId||v.$bzId}):P.push({...v,$bzId:v.$tempId||`PQ1_${v4()}`});}),{operationWithMultiples:Z,operationWithoutMultiples:H,otherOps:P}},{operationWithMultiples:w,operationWithoutMultiples:O,otherOps:N}=T(B),q=X=>{let H=(()=>{let U={};for(let he in X){let G=j(t,X);!he.startsWith("$")&&G.dataFields?.find(ne=>ne.path===he)&&(U[he]=X[he]);}return U})(),P=Object.keys(X),v=o(X,!0),le=[],k=(U,he)=>{if(U===v.length){let ne={...he};P.forEach(pe=>{pe.startsWith("$")&&(ne[pe]=X[pe]);}),le.push({...ne,...H});return}let G={...he,[v[U]]:X[v[U]],...De(he),...H};k(U+1,G),k(U+1,he);};return k(0,{...De(X)}),le},C=[];return w.forEach(X=>{let Z=q(X),H=[];Z.forEach(P=>{let v=o(P,!0);if(P.$op==="create")H.push(P);else if(P.$id){let le=d(P.$objectPath),k=[];if(v.forEach(U=>{let he=`${le.includes("undefined")?"root":le}.${P.$id}${or}${U}`,G=p[he];P[U].filter(pe=>pe.$op==="unlink"||pe.$op==="delete"||pe.$op==="update").length>0?G?.$ids&&k.push({key:U,ids:G.$ids}):k.push({key:U,ids:[""]});}),k.length===v.length&&!H.find(U=>U.$id===P.$id))H.push(P);else {let U={...P,$bzId:P.$tempId||`T4_${v4()}`};v.forEach(G=>{let ne=P[G].filter(pe=>pe.$id);ne.length>0?U[G]=ne:U[G]=void 0;}),o(U,!0).length>0&&H.push(U);}}else if(P.$objectPath){let le=d(P.$objectPath),k=p[le]?.$ids||[];k.forEach(U=>{let he=[];v.forEach(G=>{let ne=`${le}.${U}${or}${G}`,pe=p[ne];pe&&he.push({key:G,ids:pe.$ids});}),v.length===0?k.filter(ne=>!H.find(pe=>pe.$id===ne)).forEach(ne=>{H.push({...P,$id:ne,$bzId:P.$tempId||`PQT2_${v4()}`});}):he.length===v.length&&!H.find(G=>G.$id===U)&&(v.forEach(G=>{let ne=`${d(P.$objectPath)}.${U}${or}${G}`,pe=p[ne]?.$ids||[],gi=P[G].find(xe=>!xe.$id),pr=[...pe.map(xe=>({...gi,$id:xe,$objectPath:{beforePath:P.$objectPath.beforePath,ids:xe,key:G}})),...P[G].filter(xe=>xe.$id)];pr.length>0&&(P[G]=pr);}),H.push({...P,$id:U,$bzId:P.$tempId||`PQ3_${v4()}`}));});}else H.push(P);}),H.forEach(P=>{C.push(P);});}),[...C,...O,...N].filter(X=>o(X).length>0?!0:X.$op!=="update").map(X=>{let Z={...X};return o(Z,!0).forEach(H=>{let P=Array.isArray(Z[H])?Z[H]:[Z[H]],v=b(P);Z[H]=v;}),Z})};return b(S)})(Array.isArray(E)?E:[E]),R=S=>S.map(b=>{let B=o(b,!0),T={...b};return B.forEach(w=>{let O=Array.isArray(b[w])?b[w]:[b[w]],N=[],q=[],C=[],V={},be=Rt(t,b,w);O.filter(k=>k).forEach(k=>{k.$op==="replace"&&k.$id?(V=k,Array.isArray(k.$id)?q=[...q,...k.$id]:q.push(k.$id)):k.$op==="create"&&be==="ONE"&&k.id?(V=k,Array.isArray(k.id)?C=[...q,...k.id]:C.push(k.id)):N.push(k);});let we=d(V.$objectPath),Z=f(we).map(k=>p[k]),H=[];Z.filter(k=>k!=null).forEach(k=>{H=[...H,...k?.$ids||[]];});let P=H.filter(k=>!q.includes(k)),v=q.filter(k=>!H.includes(k)),le=De(V);P.length>0&&N.push({...V,$op:"unlink",$id:P,$bzId:V.$tempId||`T4_${v4()}`,id:void 0,...le}),v.length>0&&v.forEach(k=>{N.push({...V,$op:"link",$id:k,$bzId:V.$tempId||`T5_${v4()}`,...le});}),C.length>0&&C.forEach(k=>{N.push({...V,$op:"create",id:k,$bzId:V.$tempId||`T6_${v4()}`,...le});}),T[w]=R(N);}),T}),I=g(R(g(M)));(S=>produce(S,b=>traverse(b,B=>{let{key:T,value:w,parent:O,meta:N}=B;T&&O&&!T?.includes("$")&&T!=="$filter"&&!N.nodePath?.includes(".$filter.")&&(Array.isArray(w)||isObject(w))&&!Array.isArray(O)&&(Array.isArray(w)?w:[w]).forEach(C=>{let V=C.$filter?{...C.$objectPath,key:C.$filterBzId}:C.$objectPath,be=d(V),we=p[be],X=(P,v)=>P.every(le=>v.includes(le)),Z=C.$id?Array.isArray(C.$id)?X(C.$id,we?.$ids?we.$ids:[]):we?.$ids?.includes(C.$id):we,H=Rt(t,O,C.$objectPath.key);if(C.$op==="link"&&Z&&H==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${d(C.$objectPath)}" because it is already occupied.`);if(C.$op)switch(C.$op){case"delete":if(!Z&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${C.$id}" because it is not linked to $id:"${O.$id}"`);break;case"update":if(!Z&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${C.$id}" because it is not linked to $id:"${O.$id}"`);break;case"unlink":if(!Z&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${C.$id}" because it is not linked to $id:"${O.$id}"`);break;case"link":if(Z)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${C.$id}" because it is already linked to $id:"${O.$id}"`);break;}});})))(I);let re=(S=>produce(S,b=>traverse(b,B=>{let{value:T,meta:w}=B;isObject(T)&&(T[Symbol.for("path")]=w.nodePath,T.$objectPath=void 0,T.$parentIsCreate=void 0);})))(I);return [...Array.isArray(re)?re:[re]].sort((S,b)=>S.$op==="create"&&b.$op!=="create"?-1:S.$op!=="create"&&b.$op==="create"?1:0)},Qs=e=>isObject(e)&&!isArray(e)&&"$eq"in e?e.$eq:e;var Kn=async(e,t,r,n)=>{let i=Array.isArray(e)?e:[e],o=i.map(l=>sr(l,!0)),s=(await He(o,t,r,n)).bql.res;return i.map((l,h)=>{let c=Y(t,l.$thing);return Yn({mut:l,node:s[h],schema:t,thing:c})})},Jn=new Set(["$op","$bzId","$parentKey"]),Ds=new Set(["$relation","$entity","$id",...Jn]),sr=(e,t)=>{let r={};e.$fields?.forEach(i=>{typeof i=="string"?r[i]=i:r[i.$path]=i;});let n={};for(let i in e){if(Jn.has(i)||Ds.has(i)&&!t)continue;let o=e[i];i.startsWith("$")?n[i]=o:Array.isArray(o)?o[0]&&typeof o[0]=="object"&&(r[i]={$path:i,...sr(o[0],!1)}):isObject(o)&&(r[i]={$path:i,...sr(o,!1)});}return n.$fields=Object.values(r),n},Yn=e=>{let{mut:t,node:r,schema:n,thing:i}=e,o=Gn(i),a=Os(r);if(Array.isArray(t))return t.map(l=>{let h=a[l.$id];return h?Wn({mut:l,node:h,schema:n,thing:i,...o}):l});let s=a[t.$id];return Wn({mut:t,node:s,schema:n,thing:i,...o})},Wn=e=>{let{mut:t,node:r,schema:n,thing:i,dataFieldMap:o,linkFieldMap:a,roleFieldMap:s}=e,{$fields:l,...h}=t;if(!r)return h;let c=Xn({$fields:t.$fields,node:r,schema:n,thing:i,dataFieldMap:o,linkFieldMap:a,roleFieldMap:s}),u={...h,[_e]:c};for(let d in t){if(d.startsWith("$"))continue;let f=t[d];if(o[d]||!f||typeof f!="object"){u[d]=f;continue}let $=a[d]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||s[d]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${i.name}" does not have field "${d}"`);let g=Y(n,$);u[d]=Yn({mut:f,schema:n,node:r[d],thing:g});}return u},Xn=e=>{let{$fields:t,node:r,schema:n,thing:i,dataFieldMap:o,linkFieldMap:a,roleFieldMap:s}=e,l=t||Is(i),h={$id:r.$id};return l.forEach(c=>{let u=typeof c!="string",d=u?c.$path:c,f=r[d];if(o[d]){h[d]=f;return}let $=a[d]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||s[d]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${i.name}" does not have field "${d}"`);if(!u){f&&(h[d]=Array.isArray(f)?f.map(Vn):Vn(f));return}let g=Y(n,$),y=Gn(g);h[d]=Array.isArray(f)?f.map(m=>Hn({...y,$fields:c.$fields,value:m,schema:n,thing:g})):Hn({...y,$fields:c.$fields,value:f,schema:n,thing:g});}),h},Is=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},Vn=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},Hn=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 Xn({...e,node:t})},Gn=e=>{let t=Object.fromEntries(e.dataFields?.map(i=>[i.path,i])||[]),r=Object.fromEntries(e.linkFields?.map(i=>[i.path,i])||[]),n=e.thingType==="relation"?e.roles||{}:{};return {dataFieldMap:t,linkFieldMap:r,roleFieldMap:n}},Os=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 Zn=(e,t)=>{let r={things:[],edges:[],arcs:[],references:[]},n=(a,s)=>{if(!a?.$thing)return;let{$op:l,$bzId:h,$tempId:c}=a,u=t.relations[a.$thing]||t.entities[a.$thing];if(!u)throw new Error(`[Internal] No schema found for ${a.$thing}`);let d=s?.bzId?s:{bzId:"",edgeField:"root"},{usedDataFields:f,usedLinkFields:p,usedRoleFields:$,usedRefFields:g}=de(u,a);if(["create","update","delete","link","unlink","match","replace"].includes(l)){let m={...ce(a,F=>![...$,...p,...g].includes(F)),...l==="link"||l==="unlink"||l==="replace"||l==="update"&&f.length===0?{$op:"match"}:{},...l==="link"||l==="replace"?{}:{[ot]:d}};r.things.push(m);}let y={link:["link","create"],unlink:["unlink","delete"],replace:["replace"]};if($){let m=ce(a,F=>isSymbol(F)||F.startsWith("$"));$.forEach(F=>{isArray(a[F])?a[F].forEach(Q=>n(Q,{bzId:h,edgeField:F,tempId:c})):n(a[F],{bzId:h,edgeField:F,tempId:c});let E=(isArray(a[F])?a[F]:[a[F]]).filter(Boolean);Object.entries(y).forEach(([Q,M])=>{let R=E.filter(I=>M.includes(I.$op)).map(I=>I.$bzId);R.length>0&&r.edges.push({...m,[F]:R,$op:Q});});});}p&&p.forEach(m=>{isArray(a[m])?a[m].forEach(Q=>n(Q,{bzId:h,edgeField:m,tempId:c})):n(a[m],{bzId:h,edgeField:m,tempId:c});let F=u.linkFields?.find(Q=>Q.path===m),E=isArray(a[m])?a[m]:[a[m]];F.target==="relation"&&Object.entries(y).forEach(([Q,M])=>{E.filter(I=>M.includes(I.$op)).forEach(I=>{let x=ce(I,J=>isSymbol(J)||J.startsWith("$"));r.edges.push({...x,[F.plays]:h,$op:Q});});}),F.target==="role"&&Object.entries({create:["link","create"],delete:["unlink","delete"],replace:["replace"]}).forEach(([M,R])=>{let I=E.filter(x=>R.includes(x.$op));I.length!==0&&I.forEach(x=>{let J={$thing:F.relation,$thingType:"relation",$bzId:`arc_${x.$bzId}`,[F.plays]:h,[F.oppositeLinkFieldsPlayedBy[0].plays]:x.$bzId,$op:M};r.arcs.push(J);});});}),g&&g.forEach(m=>{isArray(a[m])?a[m].forEach(M=>n(M,{bzId:h,edgeField:m,tempId:c})):n(a[m],{bzId:h,edgeField:m,tempId:c});let F=(isArray(a[m])?a[m]:[a[m]]).filter(M=>M!=null),E=ce(a,M=>isSymbol(M)||M.startsWith("$")),Q=F.map(M=>M.$op?`$\u27E8${M.$bzId}\u27E9`:je(M,"FLEX"));Q.length>0&&r.references.push({...E,[m]:Q,$op:"replace"});});};(Array.isArray(e)?e:[e]).forEach(a=>n(a));let o=[...r.edges].sort((a,s)=>{let l=["unlink","link"];return l.indexOf(a.$op)-l.indexOf(s.$op)});return {...r,edges:o}};var ei=(e,t)=>produce(e,n=>Et(t,n)),Et=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){t.forEach(i=>Et(e,i,r));return}let n=Y(e,r||t.$entity||t.$relation||t.$thing);Object.entries(t).forEach(([i])=>{i.startsWith("$")||i.startsWith("%")||As(e,t,i,n);});},As=(e,t,r,n)=>{let i=t[r];if(!i)return;let o=n.dataFields?.find(l=>l.path===r);if(o){o.contentType==="JSON"&&i!=null&&(t[r]=JSON.stringify(i));return}let a=n.linkFields?.find(l=>l.path===r);if(a){let l=a.oppositeLinkFieldsPlayedBy[0]?.thing;Et(e,i,l);return}if(!("refFields"in n&&n.refFields[r])&&n.thingType==="relation"){let l=n.roles[r];if(!l)throw new Error(`[Schema] Role ${r} in ${n.name} is not defined`);let[h]=l.playedBy||[];if(!h)throw new Error(`Role ${l.path} in ${n} is not played by anything`);Et(e,i,h.thing);}};var ti=async(e,t)=>{let r=s=>{let{$filter:l,$thing:h,$bzId:c,$op:u,$id:d,$tempId:f}=s,p=Y(t,h),{usedDataFields:$}=de(p,s),{idFields:g}=p,y=d||s[g[0]],m=(isArray(h)?h:[h]).map(te),F=ce(s,b=>b.startsWith("$")),E=ce(s,b=>!b.startsWith("$")),Q=JSON.stringify(E),M=Object.entries(F).map(([b,B])=>b==="$tempId"?`'$tempId': '_:${B}'`:`'${b}': '${B}'`).join(","),R=s[ot],I=$.filter(b=>!g.includes(b)).map(b=>{let B=p.dataFields?.find(w=>w.path===b||w.dbPath===b);if(!B)throw new Error(`Data field schema not found for ${b}`);let T=s[b];return T===null?`${b} = NONE`:`${b} = ${je(T,B.contentType)}`}).filter(Boolean),x=`$\u27E8${f||c}\u27E9`,J=R?.bzId?`array::flatten($\u27E8${R.bzId}\u27E9.\u27E8${R.edgeField}\u27E9 || []).filter(|$v| $v != NONE).len`:y?isArray(y)?m.flatMap(b=>y.map(B=>`${b}:\u27E8${B}\u27E9`)).join(", "):m.map(b=>`${b}:\u27E8${y}\u27E9`).join(", "):!0,re=(()=>{if(R?.bzId){let b=`array::flatten($\u27E8${R.bzId}\u27E9.\u27E8${R.edgeField}\u27E9 || []).filter(|$v| $v != NONE)`;return y?isArray(y)?`${b}[? $this.id() IN [${y.map(B=>`'${B}'`).join(", ")}] ]`:`${b}[? $this.id() IN ['${y}'] ]`:b}return y?isArray(y)?m.flatMap(b=>y.map(B=>`${b}:\u27E8${B}\u27E9`)).join(", "):m.map(b=>`${b}:\u27E8${y}\u27E9`).join(", "):m.join(", ")})(),fe=l?`WHERE ${me(Be(l,h,t))}`:"",A=I.length>0?`SET ${I.join(", ")}`:"",D=`VALUE (CREATE ONLY Delta SET input = ${Q}, meta = {${M}, "$sid": $parent.id, "$id": record::id($parent.id)}, after = $after, before = $before RETURN VALUE $parent.id )`,S="BEFORE";if(["link","unlink","replace"].includes(u))throw new Error("Edge ops don't belong to things");if(s.$op==="match")return f?"":`LET ${x} = (SELECT VALUE id FROM ${re} ${fe});`;if(s.$op==="create"){if(isArray(y))throw new Error("Cannot create multiple things at once");let b=te(h);return `LET ${x} = (CREATE ONLY ${b}:\u27E8${y}\u27E9 ${A} RETURN ${D});`}if(s.$op==="update")return `LET ${x} = IF (${J}) THEN (UPDATE ${re} ${A} ${fe} RETURN ${D}) END;`;if(s.$op==="delete")return `LET ${x} = IF (${J}) THEN (DELETE ${re} ${fe} RETURN ${S}) END;`;throw new Error(`Unsupported operation ${s.$op}`)},n=s=>{let{$thing:l,$bzId:h,$op:c,$tempId:u}=s,d=Y(t,l),{usedRoleFields:f}=de(d,s),p=`$\u27E8${u||h}\u27E9`,$="roles"in d?f.flatMap(m=>{let F=d.roles[m];if(!F)throw new Error(`Role field schema not found for ${m}`);let{cardinality:E}=F,Q=isArray(s[m])?s[m].map(M=>`$\u27E8${M}\u27E9`):[`$\u27E8${s[m]}\u27E9`];if(E==="ONE"){if(Q.length>1){let M=`array::filter(array::flatten([${Q}]), |$v| !!$v)`;switch(c){case"link":case"replace":return `${m} = ((array::len(${M})==1) && ${M}[0]) || ${M}`;case"unlink":return `${m} = NONE`;default:throw new Error(`Unsupported operation ${c} for ONE cardinality`)}}switch(c){case"link":case"replace":return `${m} = ((type::is::array(${Q[0]}) && array::len(${Q[0]})==1) && ${Q[0]}[0]) || ${Q[0]}`;case"unlink":return `${m} = NONE`;default:throw new Error(`Unsupported operation ${c} for ONE cardinality`)}}if(E==="MANY"){let M=`array::flatten([${Q}])`;switch(c){case"link":return `${m} += ${M}`;case"unlink":return `${m} -= ${M}`;case"replace":return `${m} = ${M}`;default:throw new Error(`Unsupported operation ${c} for MANY cardinality`)}}throw new Error(`Unsupported cardinality ${E}`)}):[],g=$.length>0?`${$.join(", ")}`:"",y=g?`SET ${g}`:"";return `IF ${p} THEN (UPDATE ${p} ${y} RETURN VALUE id) END; ${p};`},i=s=>{let{$thing:l,$op:h}=s,c=Y(t,l),u=te(l),{usedRoleFields:d}=de(c,s);if(!["create","delete"].includes(h))throw new Error("Arcs can only be created or deleted");let[f,p]=d,$=isArray(s[f])?s[f]:[s[f]],g=isArray(s[p])?s[p]:[s[p]];if(h==="create"){if(d.length!==2)throw new Error("Not supported: Arcs must have exactly 2 roles");let y=ce(s,x=>!x.startsWith("$")),F=`(CREATE ONLY Delta SET input = ${JSON.stringify(y)}, meta = {"$sid": $parent.id, "$id": record::id($parent.id)}, after = $after, before = $before RETURN VALUE $parent.id )`,Q=c.roles[f].cardinality==="MANY",R=c.roles[p].cardinality==="MANY";return [`
|
|
111
|
+
`)},Ut=(e,t,r)=>{let n=[],o=[],i=[];for(let c=0;c<e.length;c++)e[c].$isVirtual||n.push(e[c].$dbPath),e[c][ie].contentType==="FLEX"&&i.push({path:e[c][ie].dbPath}),o.push(`{${e[c].$dbPath}:${e[c].$as}}`);let a=n.join(", "),l=`$metadata:{as:[${o.join(",")}]}`,h=[L(`$${t} as "${t}.${l}.$dataFields": ${a};`,r)];return i.length>0&&i.forEach(c=>{h.push(L(`"${c.path}.$multiVal": {match $${t} has ${c.path} $${c.path}; fetch $${c.path}: attribute;};`,r));}),h},Wt=(e,t,r,n,o)=>{let i=n+1,a=[];for(let s of e){let{$fields:l,$as:h,$justId:c,$idNotIncluded:u,$filterByUnique:d,$thing:f,$sort:p,$offset:$,$limit:g}=s,y=s[ee],m=`$metadata:{as:${h},justId:${c?"T":"F"},idNotIncluded:${u},filterByUnique:${d}}`;a.push(L(`"${r}.${m}.${s.$var}": {`,n)),a.push(L("match",i));let F=`${t}${zt}${s.$var}`;if(a.push(L(`$${F} isa ${s.$thing};`,i)),a.push(L(`$${t} (${s.$var}: $${t}${zt}${s.$var}) isa ${s.$intermediary};`,i)),s.$filter||s.$id){let Q=it(o,s),M=s.$id?{[Q]:s.$id}:{},R={...s.$filter,...M};a.push(dt({$filter:R,$var:F,$thing:s.$thing,schema:o,depth:i}));}let E=vt({schema:o,$thing:f,$var:F,$sort:p,depth:i});if(E&&a.push(E.match),l){let Q=`M_${v4()}`;a.push(L(`
|
|
112
|
+
?queryPath${Q} = "${y}";`,i)),a.push(L("fetch",i)),a.push(L(`?queryPath${Q} as "queryPath";`,i));let M=l?.filter(x=>x.$fieldType==="data");M&&M.length>0&&a.push(...Ut(M,F,i));let R=l?.filter(x=>x.$fieldType==="link");R&&R.length>0&&a.push(...Vt(R,F,`${t}.${s.$var}`,i,o));let I=l?.filter(x=>x.$fieldType==="role");I&&I.length>0&&a.push(...Wt(I,F,`${t}.${s.$var}`,i,o));}E&&a.push(E.sort),typeof $=="number"&&a.push(L(`offset ${$};`,i)),typeof g=="number"&&a.push(L(`limit ${g};`,i)),a.push(L("};",n));}return a},Vt=(e,t,r,n,o)=>{let i=n+1,a=[];for(let s of e){let{$fields:l,$as:h,$justId:c,$idNotIncluded:u,$filterByUnique:d,$playedBy:f,$thing:p,$sort:$,$offset:g,$limit:y}=s,m=s[ee],F=`$metadata:{as:${h},justId:${c?"T":"F"},idNotIncluded:${u},filterByUnique:${d}}`;a.push(L(`"${r}.${F}.${s.$var}": {`,n)),a.push(L("match",i));let E=`${t}${zt}${s.$var}`;if(a.push(L(`$${E} isa ${s.$thing};`,i)),s.$filter||s.$id){let M=it(o,s),R=s.$id?{[M]:s.$id}:{},I={...s.$filter,...R};a.push(dt({$filter:I,$var:E,$thing:s.$thing,schema:o,depth:i}));}let Q=vt({schema:o,$thing:p,$var:E,$sort:$,depth:i});if(Q&&a.push(Q.match),s.$target==="role"?a.push(L(`$${t}_intermediary (${s.$plays}: $${t}, ${f.plays}: $${E}) isa ${s.$intermediary};`,i)):a.push(L(`$${E} (${s.$plays}: $${t});`,i)),l){let M=`M_${v4()}`;a.push(L(`?queryPath${M} = "${m}";`,i)),a.push(L("fetch",i)),a.push(L(`?queryPath${M} as "queryPath";`,i));let R=l?.filter(J=>J.$fieldType==="data");R&&R.length>0&&a.push(...Ut(R,E,i));let I=l?.filter(J=>J.$fieldType==="link");I&&I.length>0&&a.push(...Vt(I,E,`${t}.${s.$var}`,i,o));let x=l?.filter(J=>J.$fieldType==="role");x&&x.length>0&&a.push(...Wt(x,E,`${t}.${s.$var}`,i,o));}Q&&a.push(Q.sort),typeof g=="number"&&a.push(L(`offset ${g};`,i)),typeof y=="number"&&a.push(L(`limit ${y};`,i)),a.push(L("};",n));}return a},Po=e=>typeof e=="string"?{field:e,desc:false}:{...e,desc:e.desc??false},vt=e=>{let{$var:t,$thing:r,schema:n,$sort:o,depth:i}=e,a=Y(n,r),s=[],l=[];if(o?.forEach(h=>{let c=Po(h),u=a.dataFields?.find(p=>p.path===c.field);if(!u)throw new Error(`"${r}" does not have data field "${c.field}"`);let d=`${c.field}_${v4()}`;s.push(L("{",i)),s.push(L(`$${t} has ${u.dbPath} $${d}_1;`,i+1)),s.push(L("not {",i+1)),s.push(L(`$${t} has ${u.dbPath} $${d}_2;`,i+2)),s.push(L(`$${d}_2 < $${d}_1;`,i+2)),s.push(L("};",i+1)),s.push(L(`?${d}_ = $${d}_1;`,i+1)),s.push(L("} or {",i)),s.push(L(`not { $${t} has ${u.dbPath} $${d}_1; };`,i+1)),s.push(L(`?${d}_ = "~";`,i+1)),s.push(L("};",i)),s.push(L(`?${d} = ?${d}_;`,i));let f=c.desc?"desc":"asc";l.push(`?${d} ${f}`);}),s.length!==0)return {match:s.join(""),sort:L(`sort ${l.join(", ")};`,i)}};var bn=async e=>{let{enrichedBqlQuery:t,rawBqlRequest:r,schema:n,config:o,rawTqlRes:i}=e;if(!t)throw new Error("BQL request not enriched");if(!i)throw new Error("TQL query not executed");return i.map((a,s)=>{let l=r[s],h=t[s];return jo(a,l,h,n,o)})},jo=(e,t,r,n,o)=>e.length===0?null:r.$filterByUnique?Fn(e[0],t,n,o):e.map(i=>Fn(i,t,n,o)),Fn=(e,t,r,n)=>{let{dataFields:o,currentSchema:i,linkFields:a,roleFields:s,schemaValue:l}=Ht(e,r),h=Kt(o,i,n),c=Yt(a,r,n),u=Jt(s,r,n),d=t?.$fields?.every(p=>!i?.idFields?.includes(typeof p=="string"?p:p.$path));return {...c,...u,...l,...!n.query?.noMetadata&&t.$id?{$id:Array.isArray(t.$id)?h.id:t.$id}:{},...d?Object.fromEntries(Object.entries(h).filter(([p])=>!i?.idFields?.includes(p))):h}},Ht=(e,t)=>{let r=Object.keys(e),n=r.find(f=>f.endsWith(".$dataFields")),o=r.filter(f=>f.endsWith(".$multiVal"));if(!n)throw new Error("No dataFields");o?.length>0&&o.forEach(f=>{let p=f.replace(/\.\$multiVal$/,""),$=e[f][0][p].attribute;e[n][p]=$;});let i=e[n],a=n.split(".")[n.split(".").length-2];if(i.$metaData=a,i.length===0)throw new Error("No dataFields");let s=i.type,l={$thing:s.label,$thingType:s.root,[ee]:e.queryPath.value},h={[`$${l.$thingType}`]:l.$thing},c=j(t,h),u=r.filter(f=>{let p=fe(f.split(".").pop());return !f.endsWith(".$dataFields")&&c.linkFields?.some($=>$.path===p)}).map(f=>{let p=fe(f.split(".").pop()),$=fe(c.linkFields?.find(g=>g.path===p));return {$linkFields:e[f],$key:p,$metaData:f.split(".")[f.split(".").length-2],$cardinality:$.cardinality}}),d=r.filter(f=>{let p=f.split(".").pop();return p&&!f.endsWith(".$dataFields")&&c.thingType==="relation"&&c.roles?.[p]}).map(f=>{let p=fe(f.split(".").pop());return {$roleFields:e[f],$key:p,$metaData:f.split(".")[f.split(".").length-2],$cardinality:c.roles[p].cardinality}});return {dataFields:i,schemaValue:l,currentSchema:c,linkFields:u,roleFields:d}},Kt=(e,t,r)=>{let{$metaData:n}=e,{as:o}=_o(n),i=Object.entries(e).filter(([a])=>a!=="type"&&!a.startsWith("$")).flatMap(([a,s])=>{let l=t.dataFields?.find(d=>d.path===a||d.dbPath===a),h=a==="id",c=Array.isArray(o)?o.find(d=>d[a])?.[a]:a,u;if(l?.cardinality==="ONE"){if(u=s[0]?s[0].value:r.query?.returnNulls?null:void 0,l.contentType==="DATE"||l.contentType==="FLEX"&&s[0].type.value_type==="datetime"?u=u&&`${u}Z`:l.contentType==="JSON"&&(u=u&&JSON.parse(u)),h)return [[c,u],["$id",u]].filter(([d,f])=>f!==void 0)}else if(l?.cardinality==="MANY"){if(!isArray(s))throw new Error("Typedb fetch has changed its format");if(s.length===0)return r.query?.returnNulls?[[c,null]]:[];l.contentType==="DATE"?u=s.map(d=>`${d.value}Z`):l.contentType==="FLEX"?u=s.map(d=>d.type.value_type==="datetime"?`${d.value}Z`:d.value):l.contentType==="JSON"?u=s.map(d=>d.value&&JSON.parse(d.value)):u=s.map(d=>d.value);}return [[c,u]].filter(([d,f])=>f!==void 0)});return Object.fromEntries([...i])},Jt=(e,t,r)=>{let n={};return e.forEach(o=>{let{$roleFields:i,$metaData:a,$cardinality:s}=o,{as:l,justId:h,idNotIncluded:c,filterByUnique:u}=wn(a);if(l===null)return;let d=i.map(f=>{let{dataFields:p,currentSchema:$,linkFields:g,roleFields:y,schemaValue:m}=Ht(f,t),F=Kt(p,$,r);if(h==="T")return F.id;let E=Yt(g,t,r),Q=Jt(y,t,r),M={...F};return c==="true"&&$?.idFields?.forEach(R=>delete M[R]),{...M,...E,...Q,...m}});d.length>0?n[l]=s==="MANY"&&u==="false"?d:d[0]:r.query?.returnNulls&&(n[l]=null);}),n},Yt=(e,t,r)=>{let n={};return e.forEach(o=>{let{$linkFields:i,$metaData:a,$cardinality:s}=o,{as:l,justId:h,idNotIncluded:c,filterByUnique:u}=wn(a);if(l===null)return;let d=i.map(f=>{let{dataFields:p,currentSchema:$,linkFields:g,roleFields:y,schemaValue:m}=Ht(f,t),F=Kt(p,$,r);if(h==="T")return F.id;let E=Yt(g,t,r),Q=Jt(y,t,r),M={...F};return c==="true"&&$.idFields?.forEach(R=>delete M[R]),{...M,...E,...Q,...m}});n[l]=d.length>0?s==="MANY"&&u==="false"?d:d[0]:r.query?.returnNulls?null:void 0;}),n},wn=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,r=/justId:([a-zA-Z0-9_\-·]+)/,n=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,o=/filterByUnique:([a-zA-Z0-9_\-·]+)/,i=e.match(t),a=e.match(r),s=e.match(n),l=e.match(o);return {as:i?i[1]:null,justId:a?a[1]:null,idNotIncluded:s?s[1]:null,filterByUnique:l?l[1]:null}},_o=e=>{try{let r=(o=>{let i=o.replace("$metadata:","");return i=i.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),i=i.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(a,s,l)=>/^{.*}$/.test(l)?`:${l}`:`:${s}"${l}"`),i=i.replace(/\[([^\]]+)\]/g,(a,s)=>`[${s.split(",").map(l=>l.trim().startsWith("{")&&l.trim().endsWith("}")?l.trim():`"${l.trim()}"`).join(",")}]`),i})(e);return JSON.parse(r)}catch(t){return console.error(t),{as:[]}}};var ht=async(e,t)=>{let r=t.dbConnectors[0].id,n=e.typeDB?.get(r)?.session,o=e.typeDB?.get(r)?.client;if(!n||!n.isOpen()){if(!o)throw new Error("Client not found");n=await o.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(r,{client:o,session:n});}return {client:o,session:n}};var Tn=async e=>{let{tqlRequest:t,dbHandles:r,config:n}=e,o=new TypeDBOptions;o.infer=true;let{session:i}=await ht(r,n),a=await i.transaction(TransactionType.READ,o),[s,l]=await tryit(parallel)(t.length,t,async h=>await a.query.fetch(h).collect());if(s){await a.rollback();let h=s;throw new Error(`Error running TQL query: ${h.errors}`)}return await a.close(),l};var Ho=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,Ko=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,Jo=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,Xt=z("error","error",_((e,t)=>({...e,error:t.error}))),Yo=ye("build",{build:V(async e=>Bn({queries:e.bql.queries,schema:e.schema}),z("done","run",_(Ko)),Xt),run:V(async e=>Tn({dbHandles:e.handles,tqlRequest:fe(e.tql.queries),config:e.config}),z("done","parse",_(Jo)),Xt),parse:V(async e=>bn({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries,schema:e.schema,config:e.config,rawTqlRes:fe(e.tql.res)}),z("done","success",_(Ho)),Xt),success:de(),error:de()},e=>e),Xo=async e=>new Promise((t,r)=>{ge(Yo,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),Mn=async(e,t,r,n,o)=>Xo({bql:{raw:e,queries:t},tql:{},schema:r,config:n,handles:o,error:null});var Zo=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,Zt=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,pt=z("error","error",_((e,t)=>({...e,error:t.error}))),Go=ye("enrich",{enrich:V(async e=>(oe(`originalBQLQuery[${se}]`,JSON.stringify(e.bql.raw)),Qr(e.bql.raw,e.schema)),z("done","adapter",_(Zo)),pt),adapter:V(async e=>{let t={};e.bql.queries?.forEach((s,l)=>{let h=e.bql.raw[l],c=Y(e.schema,s.$thing),{id:u}=c.defaultDBConnector;if(c.db==="typeDB"){if(!t[u]){let f=e.handles.typeDB?.get(u)?.client;if(!f)throw new Error(`TypeDB client with id "${c.defaultDBConnector.id}" does not exist`);t[u]={db:"typeDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else if(c.db==="surrealDB"){if(!t[u]){let f=e.handles.surrealDB?.get(u)?.client;if(!f)throw new Error(`SurrealDB client with id "${c.defaultDBConnector.id}" does not exist`);t[u]={db:"surrealDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else throw new Error(`Unsupported DB "${c.db}"`);let d=t[u];d.rawBql.push(h),d.bqlQueries.push(s),d.indices.push(l);});let r=Object.values(t),n=r.map(s=>{if(s.db==="typeDB")return Mn(s.rawBql,s.bqlQueries,e.schema,e.config,e.handles);if(s.db==="surrealDB")return yn(s.bqlQueries,e.schema,e.config,s.client);throw new Error(`Unsupported DB "${JSON.stringify(s,null,2)}"`)}),o=await Promise.all(n),i=r.flatMap((s,l)=>{let h=o[l];return s.indices.map((c,u)=>({index:c,result:h[u]}))});return i.sort((s,l)=>s.index<l.index?-1:s.index>l.index?1:0),i.map(({result:s})=>s)},z("done","postHooks",_(Zt)),pt),postHooks:V(async e=>sn(e.schema,fe(e.bql.queries),fe(e.bql.res)),z("done","clean",_(Zt)),pt),clean:V(async e=>on(e.config,fe(e.bql.res)),z("done","success",_(Zt)),pt),success:de(),error:de()},e=>e),es=async e=>new Promise((t,r)=>{ge(Go,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),We=async(e,t,r,n)=>es({bql:{raw:e},schema:t,config:r,handles:n,error:null});var Gt="___",rs=Symbol.for("grandChildOfCreate"),Sn=async(e,t,r,n)=>{let o=["$eq","$ne","$in","$nin","$gt","$gte","$lt","$lte","$exists"],i=(S,b)=>Object.keys(S).filter(B=>!B.startsWith("$")&&!o.includes(B)&&S[B]!==void 0?b?!j(t,S).dataFields?.find(w=>w.path===B):true:false);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(r.mutation?.preQuery===false)return;let a=[];if(traverse(e,({parent:S,key:b,value:B})=>{S&&b&&!b.includes("$")&&!o.includes(b)&&isObject(S)?(Array.isArray(S[b])?S[b]:[S[b]]).forEach(w=>{if(isObject(w)){if(S.$op!=="create")a.includes(w.$op)||a.push(w.$op);else if(w.$op==="delete"||w.$op==="unlink")throw new Error(`Cannot ${w.$op} under a create`)}}):!S&&isObject(B)&&(a.includes(B.$op)||a.push(B.$op));}),!a.includes("delete")&&!a.includes("unlink")&&!a.includes("replace")&&!a.includes("update")&&!a.includes("link"))return;let l=(S=>{let b=(B,T)=>{let w=[],O={},N=["$op","$bzId","$parentKey"],q=["$relation","$entity","$id",...N];for(let A in B)if(!N.includes(A)&&!(q.includes(A)&&!T))if(!A.includes("$")&&(isObject(B[A])||Array.isArray(B[A]))){let v=ns(B[A]);if(Array.isArray(v)&&v.length>0)v.forEach(Fe=>{let be={$path:A,...b(Fe),...Fe.$filter&&{$as:Fe.$bzId}};w.find(X=>X.$path===be.$path&&!X.$filter)||(w=[...w,be]);});else {let Fe={$path:A,...b(v),...!v.$filter&&{$as:v.$bzId}};w=[...w,Fe];}}else O[A]=B[A];return {...O,$fields:w}};return S.map(B=>b(B,true))})(Array.isArray(e)?e:[e]),c=(await We(l,t,{...r,query:{...r.query,returnNulls:true}},n)).bql.res,u=(S,b)=>{let B=S.$id||S.id||S.$bzId;if(S.$objectPath){let{$objectPath:T}=S,w=T?.beforePath||"root",O=Array.isArray(T.ids)?`[${T.ids}]`:T.ids;return {beforePath:`${w}.${O}___${T.key}`,ids:B,key:b}}return {beforePath:"root",ids:B,key:b}},d=(S,b)=>{let B=S?.beforePath||"root";if(typeof B!="string")throw new Error("[PQ]objectPathToKey: root is not a string");let T=(Array.isArray(S?.ids)?`[${S?.ids}]`:S?.ids);return `${B}.${T}___${S?.key}`},f=S=>{if(S.includes("[")&&S.includes("]")){let[b,B,T]=S.split(/[[\]]/);return B.split(",").map(O=>`${b}${O}${T}`)}return [S]},p={};(S=>produce(S,b=>traverse(b,({key:B,parent:T})=>{if(T&&B&&T.$id&&!B.includes("$")){let w=u(T,B),O=d(w);if(Array.isArray(T[B])){let N=[];T[B].forEach(q=>{isObject(q)?(q.$objectPath=w,N.push(q.$id.toString())):q&&N.push(q.toString());}),p[O]={$objectPath:w,$ids:N};}else {let N=T[B];isObject(N)?(p[O]={$objectPath:w,$ids:[N.$id.toString()]},N.$objectPath=w):N?p[O]={$objectPath:w,$ids:[N.toString()]}:N===null&&(p[O]=null);}}})))(c||{});let g=S=>produce(S,b=>traverse(b,({key:B,value:T,parent:w})=>{w&&B&&!B.includes("$")&&(Array.isArray(T)||isObject(T))&&!Array.isArray(w)&&(Array.isArray(w[B])?w[B].forEach(O=>{typeof O!="string"&&(O.$objectPath=u(w,B),O.$parentIsCreate=w.$op==="create",O[rs]=w.$parentIsCreate||w[Symbol.for("grandChildOfCreate")]);}):isObject(w[B])&&(w[B].$parentIsCreate=w.$op==="create",w[B][Symbol.for("grandChildOfCreate")]=w.$parentIsCreate||w[Symbol.for("grandChildOfCreate")],w[B].$objectPath=u(w,B)));})),y=g(e),m=S=>{let b=[];return S.forEach(T=>{if(!T.$id&&!T.id&&!T.$tempId)if(T.$filter){let w=d({...T.$objectPath,key:T.$bzId}),O=p[w];O&&(Array.isArray(O.$ids)?O.$ids:[O.$ids]).forEach(q=>{let A={...T,$id:q,$bzId:`T4_${v4()}`,$filterBzId:T.$bzId};b.push(A);});}else {let w=d(T.$objectPath),O=p[w];O?O?.$ids?.forEach(N=>{let q={...T,$id:N,$bzId:`T4_${v4()}`};b.push(q);}):b.push(T);}else b.push(T);}),b.map(T=>{let w={...T};return i(w,true).forEach(O=>{let N=Array.isArray(w[O])?w[O]:[w[O]],q=m(N);w[O]=q;}),w})},F=m(Array.isArray(y)?y:[y]),E=g(F),M=(S=>{let b=B=>{let T=X=>{let G=[],H=[],P=[];return X.forEach(U=>{let ae=i(U,true);if(ae.length>0){let C=false;ae.forEach(W=>{(Array.isArray(U[W])?U[W]:[U[W]]).filter(ne=>!ne.$id&&!ne.id&&typeof U=="object").length&&(C=true);}),C?G.push(U):H.push(U);}else U.$id?P.push({...U,$bzId:U.$tempId||U.$bzId}):P.push({...U,$bzId:U.$tempId||`PQ1_${v4()}`});}),{operationWithMultiples:G,operationWithoutMultiples:H,otherOps:P}},{operationWithMultiples:w,operationWithoutMultiples:O,otherOps:N}=T(B),q=X=>{let H=(()=>{let W={};for(let ue in X){let Z=j(t,X);!ue.startsWith("$")&&Z.dataFields?.find(ne=>ne.path===ue)&&(W[ue]=X[ue]);}return W})(),P=Object.keys(X),U=i(X,true),ae=[],C=(W,ue)=>{if(W===U.length){let ne={...ue};P.forEach(he=>{he.startsWith("$")&&(ne[he]=X[he]);}),ae.push({...ne,...H});return}let Z={...ue,[U[W]]:X[U[W]],...Re(ue),...H};C(W+1,Z),C(W+1,ue);};return C(0,{...Re(X)}),ae},A=[];return w.forEach(X=>{let G=q(X),H=[];G.forEach(P=>{let U=i(P,true);if(P.$op==="create")H.push(P);else if(P.$id){let ae=d(P.$objectPath),C=[];if(U.forEach(W=>{let ue=`${ae.includes("undefined")?"root":ae}.${P.$id}${Gt}${W}`,Z=p[ue];P[W].filter(he=>he.$op==="unlink"||he.$op==="delete"||he.$op==="update").length>0?Z?.$ids&&C.push({key:W,ids:Z.$ids}):C.push({key:W,ids:[""]});}),C.length===U.length&&!H.find(W=>W.$id===P.$id))H.push(P);else {let W={...P,$bzId:P.$tempId||`T4_${v4()}`};U.forEach(Z=>{let ne=P[Z].filter(he=>he.$id);ne.length>0?W[Z]=ne:W[Z]=void 0;}),i(W,true).length>0&&H.push(W);}}else if(P.$objectPath){let ae=d(P.$objectPath),C=p[ae]?.$ids||[];C.forEach(W=>{let ue=[];U.forEach(Z=>{let ne=`${ae}.${W}${Gt}${Z}`,he=p[ne];he&&ue.push({key:Z,ids:he.$ids});}),U.length===0?C.filter(ne=>!H.find(he=>he.$id===ne)).forEach(ne=>{H.push({...P,$id:ne,$bzId:P.$tempId||`PQT2_${v4()}`});}):ue.length===U.length&&!H.find(Z=>Z.$id===W)&&(U.forEach(Z=>{let ne=`${d(P.$objectPath)}.${W}${Gt}${Z}`,he=p[ne]?.$ids||[],ei=P[Z].find(Ne=>!Ne.$id),ar=[...he.map(Ne=>({...ei,$id:Ne,$objectPath:{beforePath:P.$objectPath.beforePath,ids:Ne,key:Z}})),...P[Z].filter(Ne=>Ne.$id)];ar.length>0&&(P[Z]=ar);}),H.push({...P,$id:W,$bzId:P.$tempId||`PQ3_${v4()}`}));});}else H.push(P);}),H.forEach(P=>{A.push(P);});}),[...A,...O,...N].filter(X=>i(X).length>0?true:X.$op!=="update").map(X=>{let G={...X};return i(G,true).forEach(H=>{let P=Array.isArray(G[H])?G[H]:[G[H]],U=b(P);G[H]=U;}),G})};return b(S)})(Array.isArray(E)?E:[E]),R=S=>S.map(b=>{let B=i(b,true),T={...b};return B.forEach(w=>{let O=Array.isArray(b[w])?b[w]:[b[w]],N=[],q=[],A=[],v={},Fe=Mt(t,b,w);O.filter(C=>C).forEach(C=>{C.$op==="replace"&&C.$id?(v=C,Array.isArray(C.$id)?q=[...q,...C.$id]:q.push(C.$id)):C.$op==="create"&&Fe==="ONE"&&C.id?(v=C,Array.isArray(C.id)?A=[...q,...C.id]:A.push(C.id)):N.push(C);});let be=d(v.$objectPath),G=f(be).map(C=>p[C]),H=[];G.filter(C=>C!=null).forEach(C=>{H=[...H,...C?.$ids||[]];});let P=H.filter(C=>!q.includes(C)),U=q.filter(C=>!H.includes(C)),ae=Re(v);P.length>0&&N.push({...v,$op:"unlink",$id:P,$bzId:v.$tempId||`T4_${v4()}`,id:void 0,...ae}),U.length>0&&U.forEach(C=>{N.push({...v,$op:"link",$id:C,$bzId:v.$tempId||`T5_${v4()}`,...ae});}),A.length>0&&A.forEach(C=>{N.push({...v,$op:"create",id:C,$bzId:v.$tempId||`T6_${v4()}`,...ae});}),T[w]=R(N);}),T}),I=g(R(g(M)));(S=>produce(S,b=>traverse(b,B=>{let{key:T,value:w,parent:O,meta:N}=B;T&&O&&!T?.includes("$")&&T!=="$filter"&&!N.nodePath?.includes(".$filter.")&&(Array.isArray(w)||isObject(w))&&!Array.isArray(O)&&(Array.isArray(w)?w:[w]).forEach(A=>{let v=A.$filter?{...A.$objectPath,key:A.$filterBzId}:A.$objectPath,Fe=d(v),be=p[Fe],X=(P,U)=>P.every(ae=>U.includes(ae)),G=A.$id?Array.isArray(A.$id)?X(A.$id,be?.$ids?be.$ids:[]):be?.$ids?.includes(A.$id):be,H=Mt(t,O,A.$objectPath.key);if(A.$op==="link"&&G&&H==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${d(A.$objectPath)}" because it is already occupied.`);if(A.$op)switch(A.$op){case "delete":if(!G&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${A.$id}" because it is not linked to $id:"${O.$id}"`);break;case "update":if(!G&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${A.$id}" because it is not linked to $id:"${O.$id}"`);break;case "unlink":if(!G&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${A.$id}" because it is not linked to $id:"${O.$id}"`);break;case "link":if(G)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${A.$id}" because it is already linked to $id:"${O.$id}"`);break;}});})))(I);let re=(S=>produce(S,b=>traverse(b,B=>{let{value:T,meta:w}=B;isObject(T)&&(T[Symbol.for("path")]=w.nodePath,T.$objectPath=void 0,T.$parentIsCreate=void 0);})))(I);return [...Array.isArray(re)?re:[re]].sort((S,b)=>S.$op==="create"&&b.$op!=="create"?-1:S.$op!=="create"&&b.$op==="create"?1:0)},ns=e=>isObject(e)&&!isArray(e)&&"$eq"in e?e.$eq:e;var Dn=async(e,t,r,n)=>{let o=Array.isArray(e)?e:[e],i=o.map(l=>er(l,true)),s=(await We(i,t,r,n)).bql.res;return o.map((l,h)=>{let c=Y(t,l.$thing);return On({mut:l,node:s[h],schema:t,thing:c})})},In=new Set(["$op","$bzId","$parentKey"]),os=new Set(["$relation","$entity","$id",...In]),er=(e,t)=>{let r={};e.$fields?.forEach(o=>{typeof o=="string"?r[o]=o:r[o.$path]=o;});let n={};for(let o in e){if(In.has(o)||os.has(o)&&!t)continue;let i=e[o];o.startsWith("$")?n[o]=i:Array.isArray(i)?i[0]&&typeof i[0]=="object"&&(r[o]={$path:o,...er(i[0],false)}):isObject(i)&&(r[o]={$path:o,...er(i,false)});}return n.$fields=Object.values(r),n},On=e=>{let{mut:t,node:r,schema:n,thing:o}=e,i=kn(o),a=as(r);if(Array.isArray(t))return t.map(l=>{let h=a[l.$id];return h?Ln({mut:l,node:h,schema:n,thing:o,...i}):l});let s=a[t.$id];return Ln({mut:t,node:s,schema:n,thing:o,...i})},Ln=e=>{let{mut:t,node:r,schema:n,thing:o,dataFieldMap:i,linkFieldMap:a,roleFieldMap:s}=e,{$fields:l,...h}=t;if(!r)return h;let c=An({$fields:t.$fields,node:r,schema:n,thing:o,dataFieldMap:i,linkFieldMap:a,roleFieldMap:s}),u={...h,[xe]:c};for(let d in t){if(d.startsWith("$"))continue;let f=t[d];if(i[d]||!f||typeof f!="object"){u[d]=f;continue}let $=a[d]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||s[d]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${o.name}" does not have field "${d}"`);let g=Y(n,$);u[d]=On({mut:f,schema:n,node:r[d],thing:g});}return u},An=e=>{let{$fields:t,node:r,schema:n,thing:o,dataFieldMap:i,linkFieldMap:a,roleFieldMap:s}=e,l=t||ss(o),h={$id:r.$id};return l.forEach(c=>{let u=typeof c!="string",d=u?c.$path:c,f=r[d];if(i[d]){h[d]=f;return}let $=a[d]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||s[d]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${o.name}" does not have field "${d}"`);if(!u){f&&(h[d]=Array.isArray(f)?f.map(Qn):Qn(f));return}let g=Y(n,$),y=kn(g);h[d]=Array.isArray(f)?f.map(m=>Rn({...y,$fields:c.$fields,value:m,schema:n,thing:g})):Rn({...y,$fields:c.$fields,value:f,schema:n,thing:g});}),h},ss=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},Qn=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},Rn=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 An({...e,node:t})},kn=e=>{let t=Object.fromEntries(e.dataFields?.map(o=>[o.path,o])||[]),r=Object.fromEntries(e.linkFields?.map(o=>[o.path,o])||[]),n=e.thingType==="relation"?e.roles||{}:{};return {dataFieldMap:t,linkFieldMap:r,roleFieldMap:n}},as=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 Cn=(e,t)=>{let r={things:[],edges:[],arcs:[],references:[]},n=(a,s)=>{if(!a?.$thing)return;let{$op:l,$bzId:h,$tempId:c}=a,u=t.relations[a.$thing]||t.entities[a.$thing];if(!u)throw new Error(`[Internal] No schema found for ${a.$thing}`);let d=s?.bzId?s:{bzId:"",edgeField:"root"},{usedDataFields:f,usedLinkFields:p,usedRoleFields:$,usedRefFields:g}=ce(u,a);if(["create","update","delete","link","unlink","match","replace"].includes(l)){let m={...le(a,F=>![...$,...p,...g].includes(F)),...l==="link"||l==="unlink"||l==="replace"||l==="update"&&f.length===0?{$op:"match"}:{},...l==="link"||l==="replace"?{}:{[rt]:d}};r.things.push(m);}let y={link:["link","create"],unlink:["unlink","delete"],replace:["replace"]};if($){let m=le(a,F=>isSymbol(F)||F.startsWith("$"));$.forEach(F=>{isArray(a[F])?a[F].forEach(Q=>n(Q,{bzId:h,edgeField:F,tempId:c})):n(a[F],{bzId:h,edgeField:F,tempId:c});let E=(isArray(a[F])?a[F]:[a[F]]).filter(Boolean);Object.entries(y).forEach(([Q,M])=>{let R=E.filter(I=>M.includes(I.$op)).map(I=>I.$bzId);R.length>0&&r.edges.push({...m,[F]:R,$op:Q});});});}p&&p.forEach(m=>{isArray(a[m])?a[m].forEach(Q=>n(Q,{bzId:h,edgeField:m,tempId:c})):n(a[m],{bzId:h,edgeField:m,tempId:c});let F=u.linkFields?.find(Q=>Q.path===m),E=isArray(a[m])?a[m]:[a[m]];F.target==="relation"&&Object.entries(y).forEach(([Q,M])=>{E.filter(I=>M.includes(I.$op)).forEach(I=>{let x=le(I,J=>isSymbol(J)||J.startsWith("$"));r.edges.push({...x,[F.plays]:h,$op:Q});});}),F.target==="role"&&Object.entries({create:["link","create"],delete:["unlink","delete"],replace:["replace"]}).forEach(([M,R])=>{let I=E.filter(x=>R.includes(x.$op));I.length!==0&&I.forEach(x=>{let J={$thing:F.relation,$thingType:"relation",$bzId:`arc_${x.$bzId}`,[F.plays]:h,[F.oppositeLinkFieldsPlayedBy[0].plays]:x.$bzId,$op:M};r.arcs.push(J);});});}),g&&g.forEach(m=>{isArray(a[m])?a[m].forEach(M=>n(M,{bzId:h,edgeField:m,tempId:c})):n(a[m],{bzId:h,edgeField:m,tempId:c});let F=(isArray(a[m])?a[m]:[a[m]]).filter(M=>M!=null),E=le(a,M=>isSymbol(M)||M.startsWith("$")),Q=F.map(M=>M.$op?`$\u27E8${M.$bzId}\u27E9`:Pe(M,"FLEX"));Q.length>0&&r.references.push({...E,[m]:Q,$op:"replace"});});};(Array.isArray(e)?e:[e]).forEach(a=>n(a));let i=[...r.edges].sort((a,s)=>{let l=["unlink","link"];return l.indexOf(a.$op)-l.indexOf(s.$op)});return {...r,edges:i}};var qn=(e,t)=>produce(e,n=>$t(t,n)),$t=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){t.forEach(o=>$t(e,o,r));return}let n=Y(e,r||t.$entity||t.$relation||t.$thing);Object.entries(t).forEach(([o])=>{o.startsWith("$")||o.startsWith("%")||cs(e,t,o,n);});},cs=(e,t,r,n)=>{let o=t[r];if(!o)return;let i=n.dataFields?.find(l=>l.path===r);if(i){i.contentType==="JSON"&&o!=null&&(t[r]=JSON.stringify(o));return}let a=n.linkFields?.find(l=>l.path===r);if(a){let l=a.oppositeLinkFieldsPlayedBy[0]?.thing;$t(e,o,l);return}if(!("refFields"in n&&n.refFields[r])&&n.thingType==="relation"){let l=n.roles[r];if(!l)throw new Error(`[Schema] Role ${r} in ${n.name} is not defined`);let[h]=l.playedBy||[];if(!h)throw new Error(`Role ${l.path} in ${n} is not played by anything`);$t(e,o,h.thing);}};var Nn=async(e,t)=>{let r=s=>{let{$filter:l,$thing:h,$bzId:c,$op:u,$id:d,$tempId:f}=s,p=Y(t,h),{usedDataFields:$}=ce(p,s),{idFields:g}=p,y=d||s[g[0]],m=(isArray(h)?h:[h]).map(te),F=le(s,b=>b.startsWith("$")),E=le(s,b=>!b.startsWith("$")),Q=JSON.stringify(E),M=Object.entries(F).map(([b,B])=>b==="$tempId"?`'$tempId': '_:${B}'`:`'${b}': '${B}'`).join(","),R=s[rt],I=$.filter(b=>!g.includes(b)).map(b=>{let B=p.dataFields?.find(w=>w.path===b||w.dbPath===b);if(!B)throw new Error(`Data field schema not found for ${b}`);let T=s[b];return T===null?`${b} = NONE`:`${b} = ${Pe(T,B.contentType)}`}).filter(Boolean),x=`$\u27E8${f||c}\u27E9`,J=R?.bzId?`array::flatten($\u27E8${R.bzId}\u27E9.\u27E8${R.edgeField}\u27E9 || []).filter(|$v| $v != NONE).len`:y?isArray(y)?m.flatMap(b=>y.map(B=>`${b}:\u27E8${B}\u27E9`)).join(", "):m.map(b=>`${b}:\u27E8${y}\u27E9`).join(", "):true,re=(()=>{if(R?.bzId){let b=`array::flatten($\u27E8${R.bzId}\u27E9.\u27E8${R.edgeField}\u27E9 || []).filter(|$v| $v != NONE)`;return y?isArray(y)?`${b}[? $this.id() IN [${y.map(B=>`'${B}'`).join(", ")}] ]`:`${b}[? $this.id() IN ['${y}'] ]`:b}return y?isArray(y)?m.flatMap(b=>y.map(B=>`${b}:\u27E8${B}\u27E9`)).join(", "):m.map(b=>`${b}:\u27E8${y}\u27E9`).join(", "):m.join(", ")})(),pe=l?`WHERE ${$e(Ee(l,h,t))}`:"",k=I.length>0?`SET ${I.join(", ")}`:"",D=`VALUE (CREATE ONLY Delta SET input = ${Q}, meta = {${M}, "$sid": $parent.id, "$id": record::id($parent.id)}, after = $after, before = $before RETURN VALUE $parent.id )`,S="BEFORE";if(["link","unlink","replace"].includes(u))throw new Error("Edge ops don't belong to things");if(s.$op==="match")return f?"":`LET ${x} = (SELECT VALUE id FROM ${re} ${pe});`;if(s.$op==="create"){if(isArray(y))throw new Error("Cannot create multiple things at once");let b=te(h);return `LET ${x} = (CREATE ONLY ${b}:\u27E8${y}\u27E9 ${k} RETURN ${D});`}if(s.$op==="update")return `LET ${x} = IF (${J}) THEN (UPDATE ${re} ${k} ${pe} RETURN ${D}) END;`;if(s.$op==="delete")return `LET ${x} = IF (${J}) THEN (DELETE ${re} ${pe} RETURN ${S}) END;`;throw new Error(`Unsupported operation ${s.$op}`)},n=s=>{let{$thing:l,$bzId:h,$op:c,$tempId:u}=s,d=Y(t,l),{usedRoleFields:f}=ce(d,s),p=`$\u27E8${u||h}\u27E9`,$="roles"in d?f.flatMap(m=>{let F=d.roles[m];if(!F)throw new Error(`Role field schema not found for ${m}`);let{cardinality:E}=F,Q=isArray(s[m])?s[m].map(M=>`$\u27E8${M}\u27E9`):[`$\u27E8${s[m]}\u27E9`];if(E==="ONE"){if(Q.length>1){let M=`array::filter(array::flatten([${Q}]), |$v| !!$v)`;switch(c){case "link":case "replace":return `${m} = ((array::len(${M})==1) && ${M}[0]) || ${M}`;case "unlink":return `${m} = NONE`;default:throw new Error(`Unsupported operation ${c} for ONE cardinality`)}}switch(c){case "link":case "replace":return `${m} = ((type::is::array(${Q[0]}) && array::len(${Q[0]})==1) && ${Q[0]}[0]) || ${Q[0]}`;case "unlink":return `${m} = NONE`;default:throw new Error(`Unsupported operation ${c} for ONE cardinality`)}}if(E==="MANY"){let M=`array::flatten([${Q}])`;switch(c){case "link":return `${m} += ${M}`;case "unlink":return `${m} -= ${M}`;case "replace":return `${m} = ${M}`;default:throw new Error(`Unsupported operation ${c} for MANY cardinality`)}}throw new Error(`Unsupported cardinality ${E}`)}):[],g=$.length>0?`${$.join(", ")}`:"",y=g?`SET ${g}`:"";return `IF ${p} THEN (UPDATE ${p} ${y} RETURN VALUE id) END; ${p};`},o=s=>{let{$thing:l,$op:h}=s,c=Y(t,l),u=te(l),{usedRoleFields:d}=ce(c,s);if(!["create","delete"].includes(h))throw new Error("Arcs can only be created or deleted");let[f,p]=d,$=isArray(s[f])?s[f]:[s[f]],g=isArray(s[p])?s[p]:[s[p]];if(h==="create"){if(d.length!==2)throw new Error("Not supported: Arcs must have exactly 2 roles");let y=le(s,x=>!x.startsWith("$")),F=`(CREATE ONLY Delta SET input = ${JSON.stringify(y)}, meta = {"$sid": $parent.id, "$id": record::id($parent.id)}, after = $after, before = $before RETURN VALUE $parent.id )`,Q=c.roles[f].cardinality==="MANY",R=c.roles[p].cardinality==="MANY";return [`
|
|
123
113
|
${Q?"":`IF array::len(array::filter(array::flatten([$\u27E8${$}\u27E9]), |$v| !!$v))>1 { THROW "[Validation] Cardinality constraint: ${f} is cardinality one and can link a single thing." + <string>$\u27E8${$}\u27E9; };`}
|
|
124
114
|
${R?"":`IF array::len(array::filter(array::flatten([$\u27E8${g}\u27E9]), |$v| !!$v))>1 { THROW "[Validation] Cardinality constraint: ${p} is cardinality one and can link a single thing." + <string>$\u27E8${g}\u27E9; };`}
|
|
125
115
|
FOR $node1 IN array::flatten([$\u27E8${$}\u27E9]) {
|
|
@@ -133,7 +123,7 @@ limit ${h};`),u.join(`
|
|
|
133
123
|
}
|
|
134
124
|
}
|
|
135
125
|
}
|
|
136
|
-
}`]}if(h==="delete")return `DELETE FROM ${u} WHERE fn::as_array(${f}) CONTAINSANY $\u27E8${$}\u27E9 AND fn::as_array(${p}) CONTAINSANY $\u27E8${g}\u27E9 RETURN BEFORE`},
|
|
126
|
+
}`]}if(h==="delete")return `DELETE FROM ${u} WHERE fn::as_array(${f}) CONTAINSANY $\u27E8${$}\u27E9 AND fn::as_array(${p}) CONTAINSANY $\u27E8${g}\u27E9 RETURN BEFORE`},i=s=>{let{$thing:l,$bzId:h,$op:c,$tempId:u}=s,d=Y(t,l),{usedRefFields:f}=ce(d,s),p=`$\u27E8${u||h}\u27E9`,$=f.flatMap(m=>{let F=d.refFields[m];if(!F)throw new Error(`ReferenceField schema not found for ${m}`);let{cardinality:E,contentType:Q}=F;if(Q==="REF"){let M=isArray(s[m])?s[m]:[`${s[m]}`];if(E==="ONE"){if(M.length>1){let R=`array::filter(array::flatten([${M}]), |$v| !!$v)`;switch(c){case "link":case "replace":return `${m} = ((array::len(${R})==1) && ${R}[0]) || ${R}`;case "unlink":return `${m} = NONE`;default:throw new Error(`Unsupported operation ${c} for ONE cardinality`)}}switch(c){case "link":case "replace":return `${m} = ((type::is::array(${M[0]}) && array::len(${M[0]})==1) && ${M[0]}[0]) || ${M[0]}`;case "unlink":return `${m} = NONE`;default:throw new Error(`Unsupported operation ${c} for ONE cardinality`)}}if(E==="MANY"){let R=`array::flatten([${M}])`;switch(c){case "link":return `${m} += ${R}`;case "unlink":return `${m} -= ${R}`;case "replace":return `${m} = ${R}`;default:throw new Error(`Unsupported operation ${c} for MANY cardinality`)}}throw new Error(`Unsupported cardinality ${E}`)}if(Q==="FLEX")return `${m} = ${E==="ONE"?`array::flatten([${s[m]}])[0]`:`array::flatten([${s[m]}])`}`}),g=$.length>0?`${$.join(", ")}`:"",y=g?`SET ${g}`:"";return `IF ${p} THEN (UPDATE ${p} ${y} RETURN VALUE id) END; ${p};`};return [...e.things.map(r),...e.edges.map(n),...e.arcs.flatMap(o),...e.references.map(i)]};var _n=e=>{let{res:t,config:r}=e;return t.flat().filter(Boolean).flatMap(o=>{if(isArray(o))return o.map(i=>{if(!isObject(i)||!("meta"in i))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(i)}`);return xn(i,r)});if(!isObject(o)||!("meta"in o))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(o)}`);return xn(o,r)})},xn=(e,t)=>{let r=mapEntries(e.after||{},(i,a)=>[i,i==="id"?a.id:isArray(a)&&a.length===0?void 0:a]),n=le(e.input||{},(i,a)=>a===null),o={...r,...e.meta,...n};return t.mutation?.noMetadata?le(o,i=>!i.startsWith("$")):o};var zn=async(e,t)=>{let r=`
|
|
137
127
|
BEGIN TRANSACTION;
|
|
138
128
|
${t.join(";")};
|
|
139
129
|
LET $DELTAS = SELECT * FROM Delta;
|
|
@@ -143,13 +133,11 @@ limit ${h};`),u.join(`
|
|
|
143
133
|
LET $LOGS = SELECT * FROM LOG;
|
|
144
134
|
RETURN $LOGS;
|
|
145
135
|
COMMIT TRANSACTION;
|
|
146
|
-
`;
|
|
147
|
-
${R.join(" or ")};`}return ""},fe=()=>f==="update"||f==="link"||f==="match"?`${p} isa ${[m,...x].filter(A=>A).join(",")};`:"";if(lt(d))return {op:f,deletionMatch:re(),insertionMatch:fe(),insertion:f==="create"?`${p} isa ${[m,J].filter(A=>A).join(",")};`:f==="update"&&Q.length?`${p} ${Q.join(",")};`:"",deletion:f==="delete"?`${p} isa ${m};`:f==="update"&&R.length?`${p} has ${M};`:""};throw new Error("in attributes")},i=d=>{let f=d.$op,p=j(r,d),$=`$${d.$bzId}`,g=d.$id,y=p.defaultDBConnector?.path||d.$thing,m="roles"in p?listify(p.roles,D=>D):[],F="roles"in p?mapEntries(p.roles,(D,S)=>[D,S.dbConnector?.path||D]):{},E=listify(d,(D,S)=>{if(!m.includes(D))return null;if(!("roles"in p))throw new Error("This should have roles! ");let b=F[D];return Array.isArray(S)?S.map(B=>({path:b,id:B})):{path:b,id:S}}).filter(D=>D).flat(),Q=E.map(D=>{if(!D?.path)throw new Error("Object without path");return `${D.path}: $${D.id}`}),M=E.length>0?`( ${Q.join(" , ")} )`:"",R=d[qe];if(!R)throw new Error("[internal error] Symbol edgeType not defined");let I=M?`${$} ${M} ${R==="linkField"||f==="delete"||f==="unlink"?`isa ${y}`:""}`:"",x=`${$} ${R==="linkField"||f==="delete"?`isa ${y}`:""}`,J=()=>I?f==="link"?`${I};`:f==="create"?`${I}, has id '${g}';`:"":"",re=()=>I&&f==="match"?`${I};`:"",fe=()=>I?f==="delete"?`${I};`:f==="match"?`${I};`:"":"",A=()=>I?f==="delete"?`${x};`:f==="unlink"?`${$} ${M};`:"":"";return {deletionMatch:fe(),insertionMatch:re(),deletion:A(),insertion:J(),op:""}},o=(d,f)=>{let p=f==="edges"?i:n;if(Array.isArray(d))return d.map(E=>{let{preDeletionBatch:Q,insertionMatch:M,deletionMatch:R,insertion:I,deletion:x}=p(E);return shake({preDeletionBatch:Q,insertionMatch:M,deletionMatch:R,insertion:I,deletion:x},J=>!J)}).filter(E=>E);let{preDeletionBatch:$,insertionMatch:g,deletionMatch:y,insertion:m,deletion:F}=p(d);return shake({preDeletionBatch:$,insertionMatch:g,deletionMatch:y,insertion:m,deletion:F},E=>!E)},a=o(e),s=Array.isArray(a)?a:[a],l=o(t,"edges"),h=Array.isArray(l)?l:[l],c=[...s,...h];return shake({insertionMatches:c.map(d=>d.insertionMatch).join(" ").trim(),deletionMatches:c.map(d=>d.deletionMatch).join(" ").trim(),insertions:c.map(d=>d.insertion).join(" ").trim(),deletions:c.map(d=>d.deletion).join(" ").trim()},d=>!d)};var ui=async(e,t,r,n,i)=>{let o=[...t,...r],a=o.map(s=>{let l=e.insertions?.find(u=>u.get(`${s.$bzId}`))?.get(`${s.$bzId}`),h=s.$thing||s.$relation||s.$entity,c=h?Y(n,h):void 0;if(s.$op==="create"||s.$op==="update"||s.$op==="link"){if(s.$op!=="update"&&!l&&s.$id)return {$id:s.$id,$error:"Does not exist or it's not linked to the parent"};let u=l?.asThing().iid,d=Object.entries(s).filter(([p,$])=>!p.startsWith("$")).reduce((p,[$,g])=>{if(c?.dataFields?.find(m=>m.path===$)?.contentType==="JSON")return p[$]=JSON.parse(g),p;if(s.$thingType==="relation"){let m=o.filter(F=>F.$id&&F.$bzId===g);return m.length===1?(p[$]=m[0].$id,p):(p[$]=g,p)}return p[$]=g,p},{});if(i.mutation?.noMetadata)return d;let f=s.$tempId&&!s.$tempId.startsWith("_:")?{$tempId:`_:${s.$tempId}`}:{};return {$dbId:u,...s,...d,[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(a)};var hi=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:n}=await mt(t,r),i=await n.transaction(TransactionType.WRITE),o=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,a=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;try{o&&await i.query.delete(o);let s=a&&i.query.insert(a),l=s?await s.collect():void 0;return await i.commit(),{insertions:l}}catch(s){throw new Error(`Transaction failed: ${s.message}`)}finally{await i.close();}};var Ws=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Vs=(e,t)=>({...e,tql:{...e.tql,mutation:t.data}}),Hs=(e,t)=>({...e,tql:{...e.tql,res:t.data}}),ur=z("error","error",_((e,t)=>({...e,error:t.error}))),Ks=Ee("buildMutation",{buildMutation:W(async e=>di(e.bql.things,e.bql.edges,e.schema),z("done","runMutation",_(Vs)),ur),runMutation:W(async e=>hi(e.tql.mutation,e.handles,e.config),z("done","parseMutation",_(Hs)),ur),parseMutation:W(async e=>ui(e.tql.res,e.bql.things,e.bql.edges,e.schema,e.config),z("done","success",_(Ws)),ur),success:ue(),error:ue()},e=>e),Js=async e=>new Promise((t,r)=>{ye(Ks,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),pi=async(e,t,r,n,i,o,a)=>Js({bql:{raw:e,enriched:t,things:r,edges:n,flat:{things:[],edges:[],arcs:[],references:[]},res:[]},tql:{},schema:i,config:o,handles:a,error:null});var fi=ue,Je=(e,t)=>t.data?{...e,bql:{...e.bql,enriched:t.data}}:e,Ys=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),Xs=(e,t)=>({...e,bql:{...e.bql,flat:t.data||"test"}}),Gs=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Zs=async e=>(se(`>>> mutationMachine/enrich[${ae}]`,JSON.stringify(Object.keys(e.bql.enriched).length?e.bql.enriched:e.bql.raw)),Object.keys(e.bql.enriched).length?Nt(e.bql.enriched,e.schema,e.config):Nt(e.bql.raw,e.schema,e.config)),ea=async e=>(se(`>>> mutationMachine/preQuery[${ae}]`,JSON.stringify(e.bql.enriched)),Un(e.bql.enriched,e.schema,e.config,e.handles)),ta=async e=>(se(`>>> mutationMachine/preQueryDependencies[${ae}]`,JSON.stringify(e.bql.enriched)),Kn(e.bql.enriched,e.schema,e.config,e.handles)),ra=async e=>(se(`>>> mutationMachine/parseBQL[${ae}]`,JSON.stringify(e.bql.enriched)),sn(e.bql.enriched,e.schema)),na=async e=>(se(`>>> mutationMachine/flattenBQL[${ae}]`,JSON.stringify(e.bql.enriched)),Zn(e.bql.enriched,e.schema)),ia=e=>{let{dbConnectors:t}=e.config;if(t.length!==1)throw new Error("Multiple providers not supported yet in mutations");let[{provider:r}]=t;if(r==="typeDB")return !0;if(r==="surrealDB")return !1;throw new Error(`Unsupported provider ${r}.`)},oa=e=>Ue(e.bql.enriched),Pe=z("error","error",_((e,t)=>({...e,error:t.error}))),sa=Ee("stringify",{stringify:W(async e=>(se(`>>> mutationMachine/stringify[${ae}]`,JSON.stringify(e.bql.raw)),ei(e.bql.raw,e.schema)),z("done","enrich",_(Je)),Pe),enrich:W(Zs,z("done","preQuery",Pt(ia),_(Je)),z("done","parseBQL",_(Je)),Pe),preQuery:W(ea,z("done","preHookDependencies",Pt(oa),_(Je)),z("done","parseBQL",_(Je)),Pe),preHookDependencies:W(ta,z("done","enrich",_(Je)),Pe),parseBQL:W(ra,z("done","flattenBQL",_(Ys)),Pe),flattenBQL:W(na,z("done","adapter",_(Xs)),Pe),adapter:W(async e=>{se(`>>> mutationMachine/adapter[${ae}]`,JSON.stringify({enriched:e.bql.enriched,flat:e.bql.flat}));let{dbConnectors:t}=e.config;if(t.length!==1)throw new Error("Multiple providers not supported yet in mutations");let[{provider:r}]=t;if(r==="typeDB")return pi(e.bql.raw,e.bql.enriched,e.bql.things,e.bql.edges,e.schema,e.config,e.handles);if(r==="surrealDB")return li(e.bql.raw,e.bql.enriched,e.bql.flat,e.schema,e.config,e.handles);throw new Error(`Unsupported provider ${r}.`)},z("done","success",_(Gs)),Pe),success:fi(),error:fi()},e=>e),aa=async e=>new Promise((t,r)=>{ye(sa,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),$i=async(e,t,r,n)=>aa({bql:{raw:e,enriched:{},things:[],edges:[],flat:{things:[],edges:[],arcs:[],references:[]},res:[]},schema:t,config:r,handles:n,depthLevel:0,error:null});enableMapSet();var hr=class{schema;config;initializing=!1;subscribers=[];initialized=null;constructor({schema:t,config:r}){this.schema=t,this.config=r;}getDbHandles=()=>this.initialized?.dbHandles;getInitialized=async()=>{if(this.initialized)return this.initialized;if(await this.init(),this.initialized)return this.initialized;throw new Error("Client is not initialized")};init=async()=>{if(this.initializing)return new Promise((r,n)=>{this.subscribers.push(i=>{i?n(i):r();});});this.initializing=!0;let t={typeDB:new Map,surrealDB:new Map};try{await Promise.all(this.config.dbConnectors.map(async n=>{if(n.provider==="surrealDB"){let i=new rt({url:n.url,username:n.username,password:n.password,namespace:n.namespace,database:n.dbName});t.surrealDB.set(n.id,{client:i,providerConfig:n.providerConfig});}else if(n.provider==="typeDB"&&n.dbName){let[i,o]=await tryit(TypeDB.coreDriver)(n.url);if(i){let a=`[BORM:${n.provider}:${n.dbName}:core] ${i.message??"Can't create TypeDB Client"}`;throw new Error(a)}try{let a=await o.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:o,session:a});}catch(a){let s=`[BORM:${n.provider}:${n.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(s)}}else if(n.provider==="typeDBCluster"&&n.dbName){let i=new TypeDBCredential(n.username,n.password,n.tlsRootCAPath),[o,a]=await tryit(TypeDB.cloudDriver)(n.addresses,i);if(o){let s=`[BORM:${n.provider}:${n.dbName}:core] ${o.message??"Can't create TypeDB Cluster Client"}`;throw new Error(s)}try{let s=await a.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:a,session:s});}catch(s){let l=`[BORM:${n.provider}:${n.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(l)}}})),this.initialized={enrichedSchema:Mr(this.schema,t),dbHandles:t};let r=this.subscribers;this.subscribers=[],r.forEach(n=>n());}catch(r){let n=this.subscribers;this.subscribers=[],n.forEach(i=>i(r));}finally{this.initializing=!1;}};introspect=async()=>(await this.getInitialized()).enrichedSchema;define=async()=>{let t=await this.getInitialized();return await Br(this.config,t.enrichedSchema,t.dbHandles)};query=async(t,r)=>{let n=await this.getInitialized(),i={...this.config,query:{...bt.query,...this.config.query,...r}},o=Array.isArray(t),a=o?t:[t],[s,l]=await tryit(He)(a,n.enrichedSchema,i,n.dbHandles);if(s){let c=new Error(s.error);throw c.stack=s.error.stack,c}let h=l.bql.res;return o?h:h[0]};mutate=async(t,r)=>{let n=await this.getInitialized(),i={...this.config,mutation:{...bt.mutation,...this.config.mutation,...r}},[o,a]=await tryit($i)(t,n.enrichedSchema,i,n.dbHandles);if(o){let l=new Error(o.error.message);throw l.stack=o.error.stack,l}return a.bql.res};close=async()=>{if(this.initialized)try{await Promise.all([...this.initialized.dbHandles.typeDB?.values()??[]].map(async({client:t,session:r})=>{r.isOpen()&&await r.close(),await t.close();}));}finally{this.initialized=null;}}},kh=hr;//! TO-DO Rule: Everything that can be changed or defined by the user should use $ prefix, but the rest is metadata and should be packed in symbols, depending on their origin. extension inside the schema and schema or query inside the query. Probably no more categories are necessary
|
|
136
|
+
`;oe(`>>> batchedMutation[${se}]`,JSON.stringify({batchedMutation:r}));try{return (await e.query(r)).filter(Boolean)}catch(n){let i=(await e.query_raw(r)).filter(a=>a.result!=="The query was not executed due to a failed transaction"&&a.result!=="There was an error when starting a new datastore transaction"&&a.status==="ERR");throw i.length>0?new Error(`Error running SURQL mutation: ${JSON.stringify(i)}`):n}};var us=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),hs=(e,t)=>{if(!t.data||!isArray(t.data)||t.data.some(r=>typeof r!="string"))throw new Error("Invalid event data");return {...e,surql:{...e.surql,mutations:t.data}}},ps=(e,t)=>{if(!t.data||!isArray(t.data))throw new Error("Invalid event data");return {...e,surql:{...e.surql,res:t.data}}},rr=z("error","error",_((e,t)=>({...e,error:t.error}))),fs=ye("buildMutation",{buildMutation:V(async e=>(oe(`>>> surqlMachine/buildMutation[${se}]`,JSON.stringify(e.bql.flat)),Nn(e.bql.flat,e.schema)),z("done","runMutation",_(hs)),rr),runMutation:V(async e=>(oe(`>>> surqlMachine/runMutation[${se}]`,JSON.stringify(e.surql.mutations)),zn(e.handles.surrealDB?.get(e.handles.surrealDB?.keys().next().value)?.client,e.surql.mutations)),z("done","parseMutation",_(ps)),rr),parseMutation:V(async e=>(oe(`>>> surqlMachine/parseMutation[${se}]`,JSON.stringify(e.surql.res)),_n({res:e.surql.res,config:e.config,schema:e.schema})),z("done","success",_(us)),rr),success:de(),error:de()},e=>e),$s=async e=>new Promise((t,r)=>{ge(fs,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),Wn=async(e,t,r,n,o,i)=>$s({bql:{raw:e,enriched:t,flat:r,things:[],edges:[],res:[]},surql:{mutations:[],res:[]},schema:n,config:o,handles:i,error:null});var nr=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 vn=async(e,t,r)=>{if(!e&&!t||!e.length&&!t.length)throw new Error("TQL request error, no things");if(!r)throw new Error("No schema provided");let n=d=>{let f=d.$op,p=`$${d.$bzId}`,$=j(r,d),{idFields:g,defaultDBConnector:y}=$,m=y?.path||d.$thing,F=d.$id,E=g?.[0],Q=listify(d,(k,D)=>{if(k.startsWith("$")||k.startsWith("%")||k===E||D===void 0||D===null)return "";let S=$.dataFields?.find(T=>T.path===k);if(!S?.path)return "";let B=S.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(S.contentType))return `has ${B} '${D}'`;if(["NUMBER","BOOLEAN"].includes(S.contentType))return `has ${B} ${D}`;if(S.contentType==="DATE"){if(Number.isNaN(D.valueOf()))throw new Error("Invalid format, Nan Date");return D instanceof Date?`has ${B} ${D.toISOString().replace("Z","")}`:`has ${B} ${new Date(D).toISOString().replace("Z","")}`}if(S.contentType==="FLEX"){let T=`bza${De()}`,w=isArray(D)?D.map(O=>nr(O)):nr(D);if(Array.isArray(w))throw new Error("Array in FLEX fields not supported yet");return `has ${B} $${T}; $${T} '${T}' isa ${B}, has ${w.type}Attribute ${w.value}`}throw new Error(`Unsupported contentType ${S.contentType}`)}).filter(k=>k),M=`${p}-atts`,R=listify(d,k=>{if(k.startsWith("$")||k.startsWith("%")||k===E)return "";let D=$.dataFields?.find(B=>B.path===k);if(!D?.path)return "";let b=D.dbPath;return `{${M} isa ${b};}`}).filter(k=>k),I=isArray(F)?`like '${F.join("|")}'`:`'${F}'`,x=F?[`has ${E} ${I}`]:[],J=[...x,...Q].filter(k=>k).join(","),re=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${p} isa ${[m,...x].filter(k=>k).join(",")};`;if(f==="update"){if(!R.length)throw new Error("update without attributes");return `${p} isa ${[m,...x].filter(k=>k).join(",")}, has ${M};
|
|
137
|
+
${R.join(" or ")};`}return ""},pe=()=>f==="update"||f==="link"||f==="match"?`${p} isa ${[m,...x].filter(k=>k).join(",")};`:"";if(ot(d))return {op:f,deletionMatch:re(),insertionMatch:pe(),insertion:f==="create"?`${p} isa ${[m,J].filter(k=>k).join(",")};`:f==="update"&&Q.length?`${p} ${Q.join(",")};`:"",deletion:f==="delete"?`${p} isa ${m};`:f==="update"&&R.length?`${p} has ${M};`:""};throw new Error("in attributes")},o=d=>{let f=d.$op,p=j(r,d),$=`$${d.$bzId}`,g=d.$id,y=p.defaultDBConnector?.path||d.$thing,m="roles"in p?listify(p.roles,D=>D):[],F="roles"in p?mapEntries(p.roles,(D,S)=>[D,S.dbConnector?.path||D]):{},E=listify(d,(D,S)=>{if(!m.includes(D))return null;if(!("roles"in p))throw new Error("This should have roles! ");let b=F[D];return Array.isArray(S)?S.map(B=>({path:b,id:B})):{path:b,id:S}}).filter(D=>D).flat(),Q=E.map(D=>{if(!D?.path)throw new Error("Object without path");return `${D.path}: $${D.id}`}),M=E.length>0?`( ${Q.join(" , ")} )`:"",R=d[ke];if(!R)throw new Error("[internal error] Symbol edgeType not defined");let I=M?`${$} ${M} ${R==="linkField"||f==="delete"||f==="unlink"?`isa ${y}`:""}`:"",x=`${$} ${R==="linkField"||f==="delete"?`isa ${y}`:""}`,J=()=>I?f==="link"?`${I};`:f==="create"?`${I}, has id '${g}';`:"":"",re=()=>I&&f==="match"?`${I};`:"",pe=()=>I?f==="delete"?`${I};`:f==="match"?`${I};`:"":"",k=()=>I?f==="delete"?`${x};`:f==="unlink"?`${$} ${M};`:"":"";return {deletionMatch:pe(),insertionMatch:re(),deletion:k(),insertion:J(),op:""}},i=(d,f)=>{let p=f==="edges"?o:n;if(Array.isArray(d))return d.map(E=>{let{preDeletionBatch:Q,insertionMatch:M,deletionMatch:R,insertion:I,deletion:x}=p(E);return shake({preDeletionBatch:Q,insertionMatch:M,deletionMatch:R,insertion:I,deletion:x},J=>!J)}).filter(E=>E);let{preDeletionBatch:$,insertionMatch:g,deletionMatch:y,insertion:m,deletion:F}=p(d);return shake({preDeletionBatch:$,insertionMatch:g,deletionMatch:y,insertion:m,deletion:F},E=>!E)},a=i(e),s=Array.isArray(a)?a:[a],l=i(t,"edges"),h=Array.isArray(l)?l:[l],c=[...s,...h];return shake({insertionMatches:c.map(d=>d.insertionMatch).join(" ").trim(),deletionMatches:c.map(d=>d.deletionMatch).join(" ").trim(),insertions:c.map(d=>d.insertion).join(" ").trim(),deletions:c.map(d=>d.deletion).join(" ").trim()},d=>!d)};var Hn=async(e,t,r,n,o)=>{let i=[...t,...r],a=i.map(s=>{let l=e.insertions?.find(u=>u.get(`${s.$bzId}`))?.get(`${s.$bzId}`),h=s.$thing||s.$relation||s.$entity,c=h?Y(n,h):void 0;if(s.$op==="create"||s.$op==="update"||s.$op==="link"){if(s.$op!=="update"&&!l&&s.$id)return {$id:s.$id,$error:"Does not exist or it's not linked to the parent"};let u=l?.asThing().iid,d=Object.entries(s).filter(([p,$])=>!p.startsWith("$")).reduce((p,[$,g])=>{if(c?.dataFields?.find(m=>m.path===$)?.contentType==="JSON")return p[$]=JSON.parse(g),p;if(s.$thingType==="relation"){let m=i.filter(F=>F.$id&&F.$bzId===g);return m.length===1?(p[$]=m[0].$id,p):(p[$]=g,p)}return p[$]=g,p},{});if(o.mutation?.noMetadata)return d;let f=s.$tempId&&!s.$tempId.startsWith("_:")?{$tempId:`_:${s.$tempId}`}:{};return {$dbId:u,...s,...d,[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(a)};var Kn=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:n}=await ht(t,r),o=await n.transaction(TransactionType.WRITE),i=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,a=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;try{i&&await o.query.delete(i);let s=a&&o.query.insert(a),l=s?await s.collect():void 0;return await o.commit(),{insertions:l}}catch(s){throw new Error(`Transaction failed: ${s.message}`)}finally{await o.close();}};var Bs=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Fs=(e,t)=>({...e,tql:{...e.tql,mutation:t.data}}),bs=(e,t)=>({...e,tql:{...e.tql,res:t.data}}),or=z("error","error",_((e,t)=>({...e,error:t.error}))),ws=ye("buildMutation",{buildMutation:V(async e=>vn(e.bql.things,e.bql.edges,e.schema),z("done","runMutation",_(Fs)),or),runMutation:V(async e=>Kn(e.tql.mutation,e.handles,e.config),z("done","parseMutation",_(bs)),or),parseMutation:V(async e=>Hn(e.tql.res,e.bql.things,e.bql.edges,e.schema,e.config),z("done","success",_(Bs)),or),success:de(),error:de()},e=>e),Ts=async e=>new Promise((t,r)=>{ge(ws,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),Jn=async(e,t,r,n,o,i,a)=>Ts({bql:{raw:e,enriched:t,things:r,edges:n,flat:{things:[],edges:[],arcs:[],references:[]},res:[]},tql:{},schema:o,config:i,handles:a,error:null});var Yn=de,ve=(e,t)=>t.data?{...e,bql:{...e.bql,enriched:t.data}}:e,Ms=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),Ss=(e,t)=>({...e,bql:{...e.bql,flat:t.data||"test"}}),Ls=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Qs=async e=>(oe(`>>> mutationMachine/enrich[${se}]`,JSON.stringify(Object.keys(e.bql.enriched).length?e.bql.enriched:e.bql.raw)),Object.keys(e.bql.enriched).length?At(e.bql.enriched,e.schema,e.config):At(e.bql.raw,e.schema,e.config)),Rs=async e=>(oe(`>>> mutationMachine/preQuery[${se}]`,JSON.stringify(e.bql.enriched)),Sn(e.bql.enriched,e.schema,e.config,e.handles)),Ds=async e=>(oe(`>>> mutationMachine/preQueryDependencies[${se}]`,JSON.stringify(e.bql.enriched)),Dn(e.bql.enriched,e.schema,e.config,e.handles)),Is=async e=>(oe(`>>> mutationMachine/parseBQL[${se}]`,JSON.stringify(e.bql.enriched)),Gr(e.bql.enriched,e.schema)),Os=async e=>(oe(`>>> mutationMachine/flattenBQL[${se}]`,JSON.stringify(e.bql.enriched)),Cn(e.bql.enriched,e.schema)),As=e=>{let{dbConnectors:t}=e.config;if(t.length!==1)throw new Error("Multiple providers not supported yet in mutations");let[{provider:r}]=t;if(r==="typeDB")return true;if(r==="surrealDB")return false;throw new Error(`Unsupported provider ${r}.`)},ks=e=>ze(e.bql.enriched),qe=z("error","error",_((e,t)=>({...e,error:t.error}))),Cs=ye("stringify",{stringify:V(async e=>(oe(`>>> mutationMachine/stringify[${se}]`,JSON.stringify(e.bql.raw)),qn(e.bql.raw,e.schema)),z("done","enrich",_(ve)),qe),enrich:V(Qs,z("done","preQuery",kt(As),_(ve)),z("done","parseBQL",_(ve)),qe),preQuery:V(Rs,z("done","preHookDependencies",kt(ks),_(ve)),z("done","parseBQL",_(ve)),qe),preHookDependencies:V(Ds,z("done","enrich",_(ve)),qe),parseBQL:V(Is,z("done","flattenBQL",_(Ms)),qe),flattenBQL:V(Os,z("done","adapter",_(Ss)),qe),adapter:V(async e=>{oe(`>>> mutationMachine/adapter[${se}]`,JSON.stringify({enriched:e.bql.enriched,flat:e.bql.flat}));let{dbConnectors:t}=e.config;if(t.length!==1)throw new Error("Multiple providers not supported yet in mutations");let[{provider:r}]=t;if(r==="typeDB")return Jn(e.bql.raw,e.bql.enriched,e.bql.things,e.bql.edges,e.schema,e.config,e.handles);if(r==="surrealDB")return Wn(e.bql.raw,e.bql.enriched,e.bql.flat,e.schema,e.config,e.handles);throw new Error(`Unsupported provider ${r}.`)},z("done","success",_(Ls)),qe),success:Yn(),error:Yn()},e=>e),qs=async e=>new Promise((t,r)=>{ge(Cs,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),Xn=async(e,t,r,n)=>qs({bql:{raw:e,enriched:{},things:[],edges:[],flat:{things:[],edges:[],arcs:[],references:[]},res:[]},schema:t,config:r,handles:n,depthLevel:0,error:null});enableMapSet();var sr=class{schema;config;initializing=false;subscribers=[];initialized=null;constructor({schema:t,config:r}){this.schema=t,this.config=r;}getDbHandles=()=>this.initialized?.dbHandles;getInitialized=async()=>{if(this.initialized)return this.initialized;if(await this.init(),this.initialized)return this.initialized;throw new Error("Client is not initialized")};init=async()=>{if(this.initializing)return new Promise((r,n)=>{this.subscribers.push(o=>{o?n(o):r();});});this.initializing=true;let t={typeDB:new Map,surrealDB:new Map};try{await Promise.all(this.config.dbConnectors.map(async n=>{if(n.provider==="surrealDB"){let o=new Ge({url:n.url,username:n.username,password:n.password,namespace:n.namespace,database:n.dbName});t.surrealDB.set(n.id,{client:o,providerConfig:n.providerConfig});}else if(n.provider==="typeDB"&&n.dbName){let[o,i]=await tryit(TypeDB.coreDriver)(n.url);if(o){let a=`[BORM:${n.provider}:${n.dbName}:core] ${o.message??"Can't create TypeDB Client"}`;throw new Error(a)}try{let a=await i.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:i,session:a});}catch(a){let s=`[BORM:${n.provider}:${n.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(s)}}else if(n.provider==="typeDBCluster"&&n.dbName){let o=new TypeDBCredential(n.username,n.password,n.tlsRootCAPath),[i,a]=await tryit(TypeDB.cloudDriver)(n.addresses,o);if(i){let s=`[BORM:${n.provider}:${n.dbName}:core] ${i.message??"Can't create TypeDB Cluster Client"}`;throw new Error(s)}try{let s=await a.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:a,session:s});}catch(s){let l=`[BORM:${n.provider}:${n.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(l)}}})),this.initialized={enrichedSchema:Er(this.schema,t),dbHandles:t};let r=this.subscribers;this.subscribers=[],r.forEach(n=>n());}catch(r){let n=this.subscribers;this.subscribers=[],n.forEach(o=>o(r));}finally{this.initializing=false;}};introspect=async()=>(await this.getInitialized()).enrichedSchema;define=async()=>{let t=await this.getInitialized();return await fr(this.config,t.enrichedSchema,t.dbHandles)};query=async(t,r)=>{let n=await this.getInitialized(),o={...this.config,query:{...gt.query,...this.config.query,...r}},i=Array.isArray(t),a=i?t:[t],[s,l]=await tryit(We)(a,n.enrichedSchema,o,n.dbHandles);if(s){let c=new Error(s.error);throw c.stack=s.error.stack,c}let h=l.bql.res;return i?h:h[0]};mutate=async(t,r)=>{let n=await this.getInitialized(),o={...this.config,mutation:{...gt.mutation,...this.config.mutation,...r}},[i,a]=await tryit(Xn)(t,n.enrichedSchema,o,n.dbHandles);if(i){let l=new Error(i.error.message);throw l.stack=i.error.stack,l}return a.bql.res};close=async()=>{if(this.initialized)try{await Promise.all([...this.initialized.dbHandles.typeDB?.values()??[]].map(async({client:t,session:r})=>{r.isOpen()&&await r.close(),await t.close();}));}finally{this.initialized=null;}}},ch=sr;//! TO-DO Rule: Everything that can be changed or defined by the user should use $ prefix, but the rest is metadata and should be packed in symbols, depending on their origin. extension inside the schema and schema or query inside the query. Probably no more categories are necessary
|
|
148
138
|
//! Todo: delete when this works with the new $thing and $thingType fields
|
|
149
139
|
//! Todo: Sandbox the function in nodeCompute() instead of the existing fieldCompute()
|
|
150
140
|
//! reads all the insertions and gets the first match. This means each id must be unique
|
|
151
141
|
//!old
|
|
152
|
-
|
|
153
|
-
export { kh as default };
|
|
154
|
-
//# sourceMappingURL=index.mjs.map
|
|
142
|
+
export{ch as default};//# sourceMappingURL=index.mjs.map
|
|
155
143
|
//# sourceMappingURL=index.mjs.map
|