@blitznocode/blitz-orm 0.13.10 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +103 -84
- package/dist/index.mjs +72 -64
- package/dist/index.mjs.map +1 -1
- package/package.json +8 -2
- package/dist/chunk-HZWWJL43.mjs +0 -2
- package/dist/chunk-HZWWJL43.mjs.map +0 -1
- package/dist/magic-string.es-ZVOSFRK2.mjs +0 -14
- package/dist/magic-string.es-ZVOSFRK2.mjs.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,35 +1,35 @@
|
|
|
1
|
-
import {
|
|
2
|
-
`).map(r=>r.trim()?`${
|
|
3
|
-
`),
|
|
1
|
+
import {produce,enableMapSet,current,isDraft}from'immer';import {isObject,tryit,parallel,isArray,clone,shake,mapEntries,pick,listify,isDate,isSymbol,isEqual}from'radash';import {TypeDBOptions,TransactionType,SessionType,TypeDB,TypeDBCredential}from'typedb-driver';import Do from'surrealdb';import {traverse,getNodeByPath}from'object-traversal';import {customAlphabet}from'nanoid';import'acorn';import {isSet}from'util/types';import {v4}from'uuid';import Nt,{z}from'zod/v4';var Mo=Object.defineProperty;var Qo=(e,t)=>{for(var r in t)Mo(e,r,{get:t[r],enumerable:true});};var gt=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 Do;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 zt={query:{noMetadata:false,simplifiedLinks:true,debugger:false,returnNulls:false},mutation:{noMetadata:false,preQuery:true,ignoreNonexistingThings:false}};var jr=e=>e.replace(/`/g,""),Ao=[" ","-","+","*","/","=","!","@","#","$","%","^","&","(",")","[","]","{","}","|","\\",";",":","'",'"',",","<",">",".","?","~","`"],le=e=>Ao.some(t=>e.includes(t))?`\u27E8${e}\u27E9`:e;var Ut=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 Vr={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"},Xe=(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=>Ut(n)):Ut(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 Io=" ",ze=e=>Io.repeat(e),Et=(e,t)=>e.split(`
|
|
2
|
+
`).map(r=>r.trim()?`${ze(t)}${r}`:r).join(`
|
|
3
|
+
`),ko=e=>{let t=`USE NS test;
|
|
4
4
|
USE DB test;
|
|
5
5
|
|
|
6
6
|
BEGIN TRANSACTION;
|
|
7
7
|
`,r=`-- ENTITIES
|
|
8
|
-
${
|
|
8
|
+
${zr(e.entities)}`,n=`
|
|
9
9
|
-- RELATIONS
|
|
10
|
-
${
|
|
10
|
+
${zr(e.relations)}`,i=Vo();return `${t}${r}${n}${i}COMMIT TRANSACTION;`},zr=e=>Object.entries(e).map(([t,r])=>Co(le(t),r,1)).join(`
|
|
11
11
|
|
|
12
|
-
`),
|
|
13
|
-
${
|
|
12
|
+
`),Co=(e,t,r)=>{let n=`${ze(r)}DEFINE TABLE ${e} SCHEMAFULL PERMISSIONS FULL;${"extends"in t&&t.extends?` //EXTENDS ${t.extends};`:""}`,i=Et(`-- DATA FIELDS
|
|
13
|
+
${qo(t.dataFields??[],e,r)}`,r+1),o=Et(`
|
|
14
14
|
-- LINK FIELDS
|
|
15
|
-
${
|
|
15
|
+
${Po(t.linkFields??[],e,r)}`,r+1),s="roles"in t?Et(`
|
|
16
16
|
-- ROLES
|
|
17
|
-
${
|
|
18
|
-
${i}${o}${
|
|
19
|
-
`),
|
|
20
|
-
`)}if(n.target==="relation")return `${`${
|
|
21
|
-
`),
|
|
22
|
-
${
|
|
23
|
-
`),
|
|
17
|
+
${xo(t.roles,e,r)}`,r+1):"";return `${n}
|
|
18
|
+
${i}${o}${s}`},qo=(e,t,r)=>e.map(n=>{if(n.path==="id")return "";let i=_o(n.contentType,n.validations),o=`${ze(r)}DEFINE FIELD ${n.path} ON TABLE ${t}${["FLEX","JSON"].includes(n.contentType)?" FLEXIBLE":""}`;if(n.isVirtual){let s=n.dbValue?.surrealDB;return s?`${o} VALUE ${s};`:""}return `${o} TYPE ${i};`}).filter(Boolean).join(`
|
|
19
|
+
`),Po=(e,t,r)=>e.map(n=>{let i=n.cardinality==="MANY"?`option<array<record<${n.$things.map(le).join("|")}>>>`:`option<record<${n.$things.map(le).join("|")}>>`,o=`${ze(r)}DEFINE FIELD ${le(n.path)} ON TABLE ${t}`;if(n.isVirtual){let s=n.dbValue?.surrealDB;return s?`${o} VALUE ${s};`:""}if(n.target==="role"){let s=e.find(h=>h.target==="relation"&&h.relation===n.relation),l=(n.oppositeLinkFieldsPlayedBy?.[0]).plays;if(!l||n.oppositeLinkFieldsPlayedBy?.length!==1)throw new Error(`Invalid link field: ${n.path}`);let d=n.cardinality==="ONE"?`record<${le(n.relation)}>`:`array<record<${le(n.relation)}>>`,c=le(n.pathToRelation||""),u=`${c}.${l}`,p=n.cardinality==="ONE"?`${o} VALUE <future> {RETURN SELECT VALUE ${u} FROM ONLY $this};`:`${o} VALUE <future> {array::distinct(SELECT VALUE array::flatten(${u} || []) FROM ONLY $this)};`,f=s?.path?"":`${ze(r+1)}DEFINE FIELD ${c} ON TABLE ${t} TYPE option<${d}>;`;return [p,f].join(`
|
|
20
|
+
`)}if(n.target==="relation")return `${`${ze(r)}DEFINE FIELD ${le(n.path)} ON TABLE ${t} TYPE ${i};`}`;throw new Error(`Invalid link field: ${JSON.stringify(n)}`)}).join(`
|
|
21
|
+
`),xo=(e,t,r)=>Object.entries(e).map(([n,i])=>{let o=i.cardinality==="MANY"?`array<record<${i.$things.map(le).join("|")}>>`:`record<${i.$things.map(le).join("|")}>`,s=`${ze(r)}DEFINE FIELD ${n} ON TABLE ${t} TYPE option<${o}>;`,a=jo(n,t,i,r);return `${s}
|
|
22
|
+
${a}`}).join(`
|
|
23
|
+
`),jo=(e,t,r,n)=>{let i=`update_${e}`,o=r.playedBy?.find(B=>B.target==="relation"),s=o?.pathToRelation,a=r.playedBy?.find(B=>B.target==="role"),l=a?.pathToRelation,d=o??a;if(!d)throw new Error(`Invalid link field: ${JSON.stringify(r)}`);let c=le(s??l),u=(B,g)=>B.map(({path:T,cardinality:S})=>`${T} ${g==="remove"?S==="ONE"?"=":"-=":S==="ONE"?"=":"+="} ${g==="remove"?S==="ONE"?"NONE":"$before.id":"$after.id"}`).join(", "),p=r.impactedLinkFields?.map(B=>({path:B.path,cardinality:B.cardinality}))||[],h=[{path:c,cardinality:d.cardinality},...p],$=u(h,"remove"),E=u(h,"add"),m=`
|
|
24
24
|
IF ($before.${e}) THEN {UPDATE $before.${e} SET ${$}} END;
|
|
25
|
-
IF ($after.${e}) THEN {UPDATE $after.${e} SET ${
|
|
25
|
+
IF ($after.${e}) THEN {UPDATE $after.${e} SET ${E}} END;`,y=`
|
|
26
26
|
LET $edges = fn::get_mutated_edges($before.${e}, $after.${e});
|
|
27
27
|
FOR $unlink IN $edges.deletions {UPDATE $unlink SET ${$};};
|
|
28
|
-
FOR $link IN $edges.additions {${
|
|
28
|
+
FOR $link IN $edges.additions {${d.cardinality==="ONE"?`
|
|
29
29
|
IF ($link.${c}) THEN {UPDATE $link.${c} SET ${e} ${r.cardinality==="ONE"?"= NONE":"-= $link.id"}} END;`:""}
|
|
30
|
-
UPDATE $link SET ${
|
|
31
|
-
};`;return
|
|
32
|
-
};`,n+1)},
|
|
30
|
+
UPDATE $link SET ${E};
|
|
31
|
+
};`;return Et(`DEFINE EVENT ${i} ON TABLE ${t} WHEN $before.${e} != $after.${e} THEN {${r.cardinality==="ONE"?m:y}
|
|
32
|
+
};`,n+1)},_o=(e,t)=>{let r=t?.enum?`${t.enum.map(n=>Xe(n,e)).join("|")}`:Vr[e];if(!r)throw new Error(`Unknown content type: ${e}`);return t?.required?`${r}`:`option<${r}>`},Vo=()=>`
|
|
33
33
|
-- BORM TOOLS
|
|
34
34
|
DEFINE FUNCTION fn::get_mutated_edges(
|
|
35
35
|
$before_relation: option<array|record>,
|
|
@@ -51,30 +51,30 @@ ${s}`}).join(`
|
|
|
51
51
|
DEFINE FUNCTION fn::as_array($var: option<array<record>|record>) {
|
|
52
52
|
RETURN (type::is::array($var) AND $var) OR [$var]
|
|
53
53
|
};
|
|
54
|
-
`,
|
|
55
|
-
`;for(let
|
|
56
|
-
`,
|
|
57
|
-
`:r+=` owns ${
|
|
58
|
-
`,n.push({dbPath:
|
|
59
|
-
`,
|
|
54
|
+
`,Ur=e=>ko(e);var vo=e=>{let t=[],r=new Map;for(let n of e){let{dbPath:i,contentType:o}=n,s=`${i}-${o}`;r.has(s)||(r.set(s,true),t.push(n));}return t},Wo=(e,t)=>{let r="",n=[];r+=`
|
|
55
|
+
`;for(let a of Object.keys(t.entities).filter(l=>t.entities[l].defaultDBConnector.id===e)){let l=t.entities[a],{dataFields:d,linkFields:c,name:u}=l;if(r+=`${u} sub ${"extends"in l?l.extends:"entity"},
|
|
56
|
+
`,d&&d.length>0)for(let p of d)p.contentType!=="REF"&&(p.inherited||(p.isIdField?r+=` owns ${p.dbPath} @key,
|
|
57
|
+
`:r+=` owns ${p.dbPath},
|
|
58
|
+
`,n.push({dbPath:p.dbPath,contentType:p.contentType})));if(c&&c.length>0){let p=[];for(let f of c){let{relation:h,plays:$,inherited:E}=f;if(E)continue;!t.relations[h].roles[$].inherited&&!p.includes(`${h}:${$}`)&&(r+=` plays ${h}:${$},
|
|
59
|
+
`,p.push(`${h}:${$}`));}}r=r.replace(/,\s*$/,`;
|
|
60
60
|
`),r+=`
|
|
61
|
-
`;}for(let
|
|
62
|
-
`,
|
|
61
|
+
`;}for(let a of Object.keys(t.relations).filter(l=>t.relations[l].defaultDBConnector.id===e)){let l=t.relations[a],{dataFields:d,roles:c,name:u,linkFields:p}=l;if(r+=`${u} sub ${"extends"in l?l.extends:"relation"},
|
|
62
|
+
`,d&&d.length>0)for(let f of d)f.inherited||(f.isIdField?r+=` owns ${f.dbPath} @key,
|
|
63
63
|
`:r+=` owns ${f.dbPath},
|
|
64
64
|
`,n.push({dbPath:f.dbPath,contentType:f.contentType}));if(c)for(let f of Object.keys(c))c[f].inherited||(r+=` relates ${f},
|
|
65
|
-
`);if(
|
|
66
|
-
`,f.push(`${
|
|
65
|
+
`);if(p&&p.length>0){let f=[];for(let h of p){let{plays:$,relation:E}=h;!t.relations[E].roles[$].inherited&&!h.inherited&&!f.includes(`${E}:${$}`)&&(r+=` plays ${h.relation}:${$},
|
|
66
|
+
`,f.push(`${E}:${$}`));}}r=r.replace(/,\s*$/,`;
|
|
67
67
|
`),r+=`
|
|
68
68
|
`;}let i=`define
|
|
69
69
|
|
|
70
|
-
`,o=
|
|
71
|
-
`;else if(
|
|
70
|
+
`,o=vo(n);for(let a of o)if(a.contentType==="TEXT"||a.contentType==="ID"||a.contentType==="JSON")i+=`${a.dbPath} sub attribute, value string;
|
|
71
|
+
`;else if(a.contentType==="EMAIL")i+=`${a.dbPath} sub attribute, value string,
|
|
72
72
|
`,i+=` 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(
|
|
74
|
-
`;else if(
|
|
75
|
-
`;else if(
|
|
76
|
-
`;else if(
|
|
77
|
-
`;else if(
|
|
73
|
+
`;else if(a.contentType==="DATE")i+=`${a.dbPath} sub attribute, value datetime;
|
|
74
|
+
`;else if(a.contentType==="BOOLEAN")i+=`${a.dbPath} sub attribute, value boolean;
|
|
75
|
+
`;else if(a.contentType==="NUMBER")i+=`${a.dbPath} sub attribute, value long;
|
|
76
|
+
`;else if(a.contentType==="FLEX")i+=`${a.dbPath} sub flexAttribute;
|
|
77
|
+
`;else if(a.contentType!=="REF")throw new Error(`Conversion of borm schema to TypeDB schema for data type "${a.contentType}" is not implemented`);return `${i}
|
|
78
78
|
|
|
79
79
|
${r}
|
|
80
80
|
#Tools, reserved for every schema using borm
|
|
@@ -90,40 +90,48 @@ flexAttribute sub attribute, abstract, value string,
|
|
|
90
90
|
owns doubleAttribute,
|
|
91
91
|
owns booleanAttribute,
|
|
92
92
|
owns datetimeAttribute;
|
|
93
|
-
`},Br=async(e,t,r,n)=>{if(!n.typeDB)throw new Error("No TypeDB handles found");let i=xi(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 Fr=async(e,t,r)=>await(async()=>{let o=(await Promise.all([...r.typeDB||[]].map(async([l])=>[l,await Br(l,e,t,r)]))).map(l=>[l[0],l[1]]),s=(await Promise.all([...r.surrealDB||[]].map(async([l])=>[l,Er(t)]))).map(l=>[l[0],l[1]]);return {typeDB:Object.fromEntries(o),surrealDB:Object.fromEntries(s)}})();var br={typeDB:{mutation:{splitArray$Ids:true,requiresParseBQL:true}},surrealDB:{mutation:{splitArray$Ids:false,requiresParseBQL:false}}};var ee=Symbol.for("queryPath"),it=Symbol.for("stepPrint"),qe=Symbol.for("edgeType"),Te=Symbol.for("edgeSchema"),ze=Symbol.for("dbNode"),Tt=Symbol.for("isTransformed"),ot=Symbol.for("parent"),ie=Symbol.for("fieldSchema"),K=Symbol.for("sharedMetadata"),Me=Symbol.for("suqlMetadata");var Sr=(e,t)=>{let r=wr(e.entities),n=wr(e.relations),i=_i(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=Tr({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=Tr({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,Mr({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=Mr({role:d,roleName:u,relationName:a,relation:s,allExtends:h.allExtends,allLinkFields:i});c.roles[u]={...f,inherited:true,[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},wr=e=>{let t=[],r=new Set,n=new Set;return Object.keys(e).forEach(i=>Lr({thingMap:e,name:i,inProcess:n,seen:r,ordered:t})),t},Lr=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&&Lr({...e,name:a.extends}),n.delete(r),i.add(r),o.push(r);},ji=(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);},Tr=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=>zi(p,n,h))??[],d=i.linkFields?.map(p=>Wi({linkField:p,thingName:n,thing:i,schema:t,allLinkFields:s}))??[],f=Object.fromEntries(Object.entries(i.refFields??{}).map(([p,$])=>[p,Ui($,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:true,[K]:{...p[K],inheritanceOrigin:p[K]?.inheritanceOrigin||i.extends}});}),a.linkFields?.forEach(p=>{d.push({...p,inherited:true,[K]:{...p[K],inheritanceOrigin:p[K]?.inheritanceOrigin||i.extends}});}),Object.entries(a.refFields??{}).forEach(([p,$])=>{f[p]={...$,inherited:true,[K]:{...$[K],inheritanceOrigin:$[K]?.inheritanceOrigin||i.extends}};})),{...i,name:n,db:l,dbContext:br[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?ji(r,i.extends):void 0,dbProviderConfig:l==="surrealDB"?o[l]?.get(i.defaultDBConnector.id)?.providerConfig:void 0}},_i=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},zi=(e,t,r)=>({...e,cardinality:e.cardinality||"ONE",dbPath:"dbPath"in e&&typeof e.dbPath=="string"?e.dbPath:Vi(t,e.path,e.shared),isIdField:!!r?.includes(e.path),inherited:false,[K]:{fieldType:"dataField"},[Me]:{dbPath:e.path}}),Ui=(e,t)=>({...e,cardinality:e.cardinality||"ONE",path:t,dbPath:e.dbPath||t,inherited:false,[K]:{fieldType:"refField"}}),Wi=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(!Qr(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:false,[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:false,$things:l.map(h=>h.thing),oppositeLinkFieldsPlayedBy:l,[K]:{fieldType:"linkField"},[Me]:{queryPath:s}}},Mr=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:false,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}\``}}},Vi=(e,t,r)=>r?t:`${e}\xB7${t}`,Qr=(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?Qr(e,n.extends,r):false},Mt=(e,t)=>t.flatMap(r=>[r,...(e.entities[r]??e.relations[r])?.subTypes??[]]);var Rr=new Set((process.env.BORM_LOG_LEVEL||"").split(",").map(e=>e.trim()).filter(e=>!!e)),vi=(e,...t)=>{(Array.isArray(e)?e.some(n=>Rr.has(n)):Rr.has(e))&&console.log(...t);},se=(...e)=>vi("debug",...e);var Rt={};a(Rt,{action:()=>Yi,createMachine:()=>oo,d:()=>Ne,guard:()=>Xi,immediate:()=>Gi,interpret:()=>Ur,invoke:()=>io,reduce:()=>qr,state:()=>ro,transition:()=>Zi});function oe(e){return {enumerable:true,value:e}}function Dr(e){return {enumerable:true,writable:true,value:e}}var Ne={},Hi=()=>true,Ir=()=>({}),kr=e=>e,Ki=(e,t,r,n)=>e.apply(r,n)&&t.apply(r,n),Ji=(e,t,r,[n,i])=>t.call(r,e.call(r,n,i),i),De=(e,t)=>Object.freeze(Object.create(e,t));function Or(e,t,r){return e.reduce((n,i)=>function(...o){return r(n,i,this,o)},t)}function Ar(e){return De(this,{fn:oe(e)})}var Cr={},qr=Ar.bind(Cr),Yi=e=>qr((t,r)=>!!~e(t,r)&&t),Nr={},Xi=Ar.bind(Nr);function st(e,t){return t.filter(r=>e.isPrototypeOf(r))}function Pr(e,t,...r){let n=Or(st(Nr,r).map(o=>o.fn),Hi,Ki),i=Or(st(Cr,r).map(o=>o.fn),kr,Ji);return De(this,{from:oe(e),to:oe(t),guards:oe(n),reducers:oe(i)})}var xr={},jr={},Zi=Pr.bind(xr),Gi=Pr.bind(jr,null);function eo(e,t,r){return Qt(t,e,r,this.immediates)||e}function _r(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 to={enter:kr};function ro(...e){let t=st(xr,e),r=st(jr,e),n={final:oe(e.length===0),transitions:oe(_r(t))};return r.length&&(n.immediates=oe(r),n.enter=oe(eo)),De(to,n)}var no={enter(e,t,r){let n=this.fn.call(t,t.context,r);return Lt.isPrototypeOf(n)?De(zr,{machine:oe(n),transitions:oe(this.transitions)}).enter(e,t,r):(n.then(i=>{if(e===t.machine)return t.send({type:"done",data:i})}).catch(i=>{if(e===t.machine)return t.send({type:"error",error:i})}),e)}},zr={enter(e,t,r){if(t.child=Ur(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,Qt(t,e,{type:"done",data:n},this.transitions.get("done"))}return e}};function io(e,...t){let r=oe(_r(t));return Lt.isPrototypeOf(e)?De(zr,{machine:oe(e),transitions:r}):De(no,{fn:oe(e),transitions:r})}var Lt={get state(){return {name:this.current,value:this.states[this.current]}}};function oo(e,t,r=Ir){return typeof e!="string"&&(r=t||Ir,t=e,e=Object.keys(t)[0]),Ne._create&&Ne._create(e,t),De(Lt,{context:oe(r),current:oe(e),states:oe(t)})}function Qt(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=De(l,{current:oe(o),original:{value:l}});Ne._onEnter&&Ne._onEnter(t,o,e.context,i,r);let c=h.state.value;e.machine=h;let u=c.enter(h,e,r);return e.onChange(e),u}}function so(e,t){let r=t.type||t,{machine:n}=e,{value:i,name:o}=n.state;return i.transitions.has(r)?Qt(e,n,t,i.transitions.get(r))||n:(Ne._send&&Ne._send(r,o),n)}var ao={send(e){so(this,e);}};function Ur(e,t,r,n){let i=Object.create(ao,{machine:Dr(e),context:Dr(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{createMachine:ge,guard:Dt,interpret:Ee,invoke:V,reduce:j,state:ce,transition:_}=Rt;var ae="0.13.10";var Vr=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,n])=>t(r,n))))[0],de=(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?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`)},z=(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)}`)},at=(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`)},lt=(e,t)=>{let r=z(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},vr=(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")},Ot=(e,t,r)=>{let n=z(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`)},kt=(e,t,r)=>Ot(e,t,r)?.cardinality,ue=(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?de(t.$filter,($,g)=>c.includes($)):{},p=t.$filter?de(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 Hr=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},Kr=(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):{}},Ie=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var ct=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={};for(let[n,i]of Object.entries(t))r[n]=isDraft(i)?current(i):i;return 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}`},Oe=e=>customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",21)();var Yr=(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=z(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=z(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=z(t,h);if(l.$filter&&(Object.keys(l.$filter).length===0?l.$filter=void 0:(l.$filter=ke(l.$filter,l.$thing,t),l.$filterByUnique=Ct(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=Jr(f,c,t);return Array.isArray(p)?p:[p]}).filter(Boolean);l.$fields=d;}else {let d=At(c)?.flatMap(f=>{let p=Jr(f,c,t);return Array.isArray(p)?p:[p]}).filter(Boolean);l.$fields=d;}l.$excludedFields&&(l.$fields=l.$fields.filter(u=>dt(c,u)?true:!l.$excludedFields.includes(u.$path)));}}}))},At=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]},Ct=(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 true}return false}}return false}),dt=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),mo=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}},yo=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=z(a,f),$=t?.$fields?.filter(m=>dt(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=At(p);else g=["id"];t.$excludedFields&&(g=g.filter(m=>dt(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: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:Ct(t.$filter,p),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ie]:s}})},go=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}},Eo=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=z(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 $=At(f);else $=["id"];t.$excludedFields&&($=$.filter(y=>dt(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: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:Ct(t.$filter,f),$playedBy:{...l,oppositeLinkFieldsPlayedBy:void 0},$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ie]:s}})},Jr=(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 mo({field:e,fieldStr:n,$justId:i,dbPath:o.dbPath,isVirtual:h,fieldSchema:o})}return a?yo({field:e,fieldStr:n,linkField:a,$justId:i,dbPath:a.path,schema:r,fieldSchema:a}):s?Eo({field:e,fieldStr:n,roleField:s,$justId:i,dbPath:n,schema:r,fieldSchema:s}):l?go({field:e,fieldStr:n,$justId:i,dbPath:n,isVirtual:false,fieldSchema:l}):null},ke=(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]=ke(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,$]=at(f,c);if(p==="idField")h[c]=u;else if(p==="dataField")isObject(u)||isArray(u)&&u.some(isObject)?h[c]=isArray(u)?{$or:ke(u,t,r)}:ke(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:ke(u,y,r)}:ke(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 Fo=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,bo=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,Xr=e=>{let r=e.toString().replace(Fo,"").trim().split("=>")[0].split("{")[0].replace(bo,"").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 We=({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,o=Xr(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 Zr=(e,t,r)=>{let n=e[t];if(n)return (isArray(n)?n:[n]).forEach(i=>{if(i.$op!=="create")return;let o=z(r,i),{unidentifiedFields:a}=ue(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?Vr(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=We({currentThing:i,fieldSchema:y,mandatoryDependencies:true});i[d]=m;}}),a.length>0)throw new Error(`Unknown fields: [${a.join(",")}] in ${JSON.stringify(i)}`)}),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}_${Oe()}`:`SN_MANY_${Oe()}`:`SM_${Oe()}`;var Ae=(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=z(r,t),{usedDataFields:i}=ue(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}},en=(e,t,r)=>{(isArray(t)?t:[t]).forEach(i=>{Ae(e,i,r);});};var tn=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"},rn=(e,t,r)=>{let n=z(r,t),{usedFields:i}=ue(n,t);return t.$op?(Ae(e,t,r),t.$op):t.$id||t.$filter?i.length>0?(Ae(e,{...t,$op:"update"},r),"update"):(Ae(e,{...t,$op:"link"},r),"link"):t.$tempId?i.length>0?(Ae(e,{...t,$op:"create"},r),"create"):(Ae(e,{...t,$op:"create"},r),"link"):(Ae(e,{...t,$op:"create"},r),"create")};var ut=(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 nn=(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=tn(o),s=qt(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=ut(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:qt(o,c)}))}}});isArray(e[t])||i.length>1?e[t]=i:e[t]=i[0],e[t]=isArray(e[t])?i:i[0];};var ht=(e,t)=>{let r=z(t,e).hooks;if(r?.pre){let n=`on${Hr(e.$op)}`;return r.pre.filter(a=>!a.triggers||a.triggers[n]?.()).flatMap(a=>a.actions)}return []};var on=(e,t,r,n)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(o=>{if(!ct(o)||o.$fields||o[Tt])return;let a=ht(o,r).filter(u=>u.type==="transform"),s=clone(Se(e)),l=clone(Se(o)),h=n.mutation?.context||{},c=clone(Se(o[ze]||o.$dbNode));a.forEach(u=>{let d=u.fn(l,s,h,c||{});Object.keys(d).length!==0&&(l={...l,...d,...Ie(o),[Tt]:true},Object.assign(o,l));});});};var an=(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}=z(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[ze]||{}));ht(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 ln=(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 dn=e=>{if(typeof e!="string")return {isPrefixed:false,obj:e};let t=e.match(/^([^:]+):([^:]+)$/),r=e.match(/^([^:]+):_:([^:]+)$/);if(t&&!e.includes(" ")){let[,n,i]=t;return {isPrefixed:true,obj:{$thing:n,$id:i}}}if(r&&!e.includes(" ")){let[,n,i]=r;return {isPrefixed:true,obj:{$thing:n,$tempId:`_:${i}`}}}return {isPrefixed:false,obj:e}},un=(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}=dn(i);return o?{...a,$op:n}:{$id:i,$op:n}}return i});},hn=(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}=dn(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 fn=(e,t)=>{let n=(isArray(e.$root)?e.$root:[e.$root]).map(i=>{let o=rn(i,i,t);return {...{...i.$thing?{}:{$thing:i.$entity||i.$relation},...i.$thingType?{}:{$thingType:vr(i,t)},...i.$op?{}:{$op:o},...i.$bzId?{}:{$bzId:`R_${Oe()}`}},...i}});e.$root=isArray(e.$root)?n:n[0];};var pt=(e,t)=>{let r=t[it];return isSet(r)?r.has("clean")?(Reflect.set(t,it,r.add("clean")),true):false:(Reflect.set(t,it,new Set(["clean"])),true)};var $n=(e,t,r)=>{if(pt("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(z(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}`,...Ie(o)}))}return i});(n.length>0&&isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=n);}};var mn=(e,t,r)=>{let n=ut(t,r),[i]=n;e[t]={$thing:i.thing,$thingType:i.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Te]:r};};var Ve=e=>{if(Array.isArray(e)){for(let t of e)if(Ve(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"&&Ve(e[t]))return true}return false};var xo=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(pt("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);},jo=(e,t)=>{},_t=(e,t,r)=>{let n={$rootWrap:{$root:e}},i=Ve(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=ke(d.$filter,d.$thing,t)),Object.keys(d).forEach(p=>{if(xo(d,p),p!=="$root"&&f||p!=="$root"&&(p.startsWith("$")||p.startsWith("%")))return;let $=p!=="$root"?Ot(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 jo();if((y||m)&&(d[p]===null?y&&mn(d,p,$):y?un(d,p):hn(d,p,$)),F){if(!("$root"in d))throw new Error(`[Internal] Field ${p} is a rootField but the object is not a root`);fn(d,t);}(y||m)&&ln(d,p,$,u),(y||m)&&(nn(d,p,$,t),en(d,d[p],t)),(y||F)&&($n(d,p,t),Zr(d,p,t),(isArray(d[p])?d[p]:[d[p]]).forEach(Q=>{let M=z(t,Q),{unidentifiedFields:R,usedLinkFields:I,usedFields:x,fields:J}=ue(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||(on(d,p,t,r),an(d,p,t,r)));});}}));return isArray(o.$rootWrap.$root),o.$rootWrap.$root};var Fn=(e,t)=>{if(!t)return;let r=zo(t);return Uo(r,e.query)},zo=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),Uo=(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===true&&Object.keys(i).forEach(o=>{o.startsWith("$")&&delete i[o];});}}));var bn=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=z(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=We({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 Ze={$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,[Ze[c]]:Be(u,t,r)};if(c==="$id")return {...h,$id:void 0,[Ze[c]]:{$IN:isArray(u)?u:[u]}};if(c==="$thing")return h;if(c==="$exists")return {...h,$exists:void 0,[Ze[c]]:u};if(c==="$eq")return {...h,$eq:void 0,[Ze[c]]:u};if(c==="$in")return {...h,$in:void 0,[Ze[c]]:u};throw new Error(`Unknown filter operator ${c}`)}let d=t in r.entities?r.entities[t]:r.relations[t],[f,p]=at(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=[];for(let[n,i]of t){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} `)})`);continue}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===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=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}'`}`);}}return 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 Tn=e=>{let{queries:t,schema:r}=e;return t.map(n=>Yo({query:n,schema:r}))},Yo=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=Ut({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(`
|
|
94
|
-
`)},
|
|
95
|
-
`)}
|
|
96
|
-
`)},
|
|
97
|
-
`)};var
|
|
98
|
-
`),
|
|
99
|
-
`),l=`FROM $parent.\`${r[
|
|
100
|
-
`),o=`FROM $parent.\`${t[
|
|
93
|
+
`},vr=async(e,t,r,n)=>{if(!n.typeDB)throw new Error("No TypeDB handles found");let i=Wo(e,r),o=n.typeDB.get(e)?.session,s=n.typeDB.get(e)?.client;if(!o){console.log("Session Status: ","NO SESSION");return}if(!s)throw new Error("No TypeDB client found");await o.close();let[{dbName:a}]=t.dbConnectors;await(await s.databases.get(a)).delete(),await s.databases.create(a);let c=await(await s.session(t.dbConnectors[0].dbName,SessionType.SCHEMA)).transaction(TransactionType.WRITE);return await c.query.define(i),await c.commit(),await c.close(),i};var Wr=async(e,t,r)=>await(async()=>{let o=(await Promise.all([...r.typeDB||[]].map(async([l])=>[l,await vr(l,e,t,r)]))).map(l=>[l[0],l[1]]),a=(await Promise.all([...r.surrealDB||[]].map(async([l])=>[l,Ur(t)]))).map(l=>[l[0],l[1]]);return {typeDB:Object.fromEntries(o),surrealDB:Object.fromEntries(a)}})();var Hr={typeDB:{mutation:{splitArray$Ids:true,requiresParseBQL:true}},surrealDB:{mutation:{splitArray$Ids:false,requiresParseBQL:false}}};var oe=Symbol.for("queryPath"),Bt=Symbol.for("stepPrint"),Ue=Symbol.for("edgeType"),Ae=Symbol.for("edgeSchema");var Ze=Symbol.for("dbNode"),vt=Symbol.for("isTransformed"),Ft=Symbol.for("parent"),ue=Symbol.for("fieldSchema"),J=Symbol.for("sharedMetadata"),Ne=Symbol.for("suqlMetadata");var Xr=(e,t)=>{let r=Jr(e.entities),n=Jr(e.relations),i=Jo(e),o={entities:{},relations:{}};return r.forEach(s=>{let a=e.entities[s];if(!a)throw new Error(`Entity "${s}" does not exist`);let l="extends"in a?o.entities[a.extends]:void 0;l&&Ht(o,l.name,s);let d=Kr({schema:e,enrichedSchema:o,extendedThing:l,name:s,thing:a,dbHandles:t,allLinkFields:i});o.entities[s]={...d,defaultDBConnector:a.defaultDBConnector,thingType:"entity"};}),n.forEach(s=>{let a=e.relations[s];if(!a)throw new Error(`Relation "${s}" does not exist`);let l="extends"in a?o.relations[a.extends]:void 0;l&&Ht(o,l.name,s);let d=Kr({schema:e,enrichedSchema:o,extendedThing:l,name:s,thing:a,dbHandles:t,allLinkFields:i}),c={...d,defaultDBConnector:a.defaultDBConnector,roles:Object.fromEntries(Object.entries(a.roles??{}).map(([u,p])=>[u,Yr({role:p,roleName:u,relationName:s,relation:a,allExtends:d.allExtends,allLinkFields:i})])),thingType:"relation"};"extends"in a&&l&&Object.entries(l?.roles??{}).forEach(([u,p])=>{let f=Yr({role:p,roleName:u,relationName:s,relation:a,allExtends:d.allExtends,allLinkFields:i});c.roles[u]={...f,inherited:true,[J]:{...p[J],inheritanceOrigin:p[J]?.inheritanceOrigin||a.extends}};}),o.relations[s]=c;}),Object.values(o.entities).forEach(s=>{s.linkFields?.forEach(a=>{a.$things=Wt(o,a.$things);});}),Object.values(o.relations).forEach(s=>{s.linkFields?.forEach(a=>{a.$things=Wt(o,a.$things);}),Object.values(s.roles??{}).forEach(a=>{a.$things=Wt(o,a.$things);});}),o},Jr=e=>{let t=[],r=new Set,n=new Set;for(let i of Object.keys(e))Zr({thingMap:e,name:i,inProcess:n,seen:r,ordered:t});return t},Zr=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 s=t[r];if(!s)throw new Error(`Entity/relation "${r}" does not exist`);"extends"in s&&Zr({...e,name:s.extends}),n.delete(r),i.add(r),o.push(r);},Ho=(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},Ht=(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&&Ht(e,n.extends,r);},Kr=e=>{let{schema:t,enrichedSchema:r,name:n,thing:i,dbHandles:o,extendedThing:s,allLinkFields:a}=e,[l]=Object.entries(o).find(([h,$])=>$.get(i.defaultDBConnector.id))??[];if(!l)throw new Error(`DB handle for ${i.defaultDBConnector.id} does not exist`);let d=[...i.idFields??s?.idFields??[]];if(d.length===0)throw new Error(`"${n}" does not have an id field`);let c={...i.hooks},u=i.dataFields?.map(h=>Ko(h,n,d))??[],p=i.linkFields?.map(h=>Xo({linkField:h,thingName:n,thing:i,schema:t,allLinkFields:a}))??[],f=Object.fromEntries(Object.entries(i.refFields??{}).map(([h,$])=>[h,Yo($,h)]));return "extends"in i&&s&&(s.hooks?.pre&&(c.pre=[...s.hooks.pre||[],...i.hooks?.pre||[]]),s.dataFields?.forEach(h=>{u.push({...h,inherited:true,[J]:{...h[J],inheritanceOrigin:h[J]?.inheritanceOrigin||i.extends}});}),s.linkFields?.forEach(h=>{p.push({...h,inherited:true,[J]:{...h[J],inheritanceOrigin:h[J]?.inheritanceOrigin||i.extends}});}),Object.entries(s.refFields??{}).forEach(([h,$])=>{f[h]={...$,inherited:true,[J]:{...$[J],inheritanceOrigin:$[J]?.inheritanceOrigin||i.extends}};})),{...i,name:n,db:l,dbContext:Hr[l],idFields:d,hooks:c,dataFields:u,linkFields:p,refFields:f,enumFields:u?.filter(h=>h.validations?.enum).map(h=>h.path)??[],fnValidatedFields:u?.filter(h=>h.validations?.fn).map(h=>h.path)??[],virtualFields:u?.filter(h=>h.isVirtual).map(h=>h.path)??[],computedFields:u?.filter(h=>h.default&&!h.isVirtual).map(h=>h.path)??[],requiredFields:u?.filter(h=>h.validations?.required).map(h=>h.path)??[],allExtends:"extends"in i?Ho(r,i.extends):void 0,dbProviderConfig:l==="surrealDB"?o[l]?.get(i.defaultDBConnector.id)?.providerConfig:void 0}},Jo=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},Ko=(e,t,r)=>({...e,cardinality:e.cardinality||"ONE",dbPath:"dbPath"in e&&typeof e.dbPath=="string"?e.dbPath:Zo(t,e.path,e.shared),isIdField:!!r?.includes(e.path),inherited:false,[J]:{fieldType:"dataField"},[Ne]:{dbPath:e.path}}),Yo=(e,t)=>({...e,cardinality:e.cardinality||"ONE",path:t,dbPath:e.dbPath||t,inherited:false,[J]:{fieldType:"refField"}}),Xo=e=>{let{linkField:t,thing:r,thingName:n,schema:i,allLinkFields:o}=e,s=i.relations[t.relation];if(!t.isVirtual){if(!s)throw new Error(`The relation ${t.relation} does not exist in the schema`);if(!Gr(i,t.relation,t.plays))throw new Error(`The role ${t.plays} is not defined in the relation ${t.relation} (linkField: ${t.path})`)}let a=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,[J]:{fieldType:"linkField"},[Ne]:{queryPath:a}}}let l=o.filter(d=>d.relation===t.relation&&d.plays!==t.plays&&d.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(d=>d.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(d=>d.target==="relation"&&d.relation===t.relation)?.path??t.relation.toLocaleLowerCase(),inherited:false,$things:l.map(d=>d.thing),oppositeLinkFieldsPlayedBy:l,[J]:{fieldType:"linkField"},[Ne]:{queryPath:a}}},Yr=e=>{let{role:t,roleName:r,relationName:n,relation:i,allExtends:o,allLinkFields:s}=e;if(i.dataFields?.find(d=>d.path===r)||i.linkFields?.find(d=>d.path===r))throw new Error(`[Schema] The path ${r} is already in use by a dataField or linkField in ${n}.`);let a=s.filter(d=>d.relation===n&&d.plays===r),l=s.filter(d=>d.target==="relation"&&d.plays===r&&o?.includes(d.relation));return {...t,fieldType:"roleField",inherited:false,playedBy:a.map(d=>({...d,pathToRelation:d.target==="relation"?d.path:i.linkFields?.find(c=>c.target==="relation"&&c.relation===r&&c.plays===r)?.path??d.relation.toLocaleLowerCase()})),impactedLinkFields:l,path:r,$things:[...new Set(a.map(d=>d.thing))],[J]:{fieldType:"roleField"},[Ne]:{queryPath:t.cardinality==="MANY"?`$parent.[\`${r}\`]`:`$parent.\`${r}\``}}},Zo=(e,t,r)=>r?t:`${e}\xB7${t}`,Gr=(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?Gr(e,n.extends,r):false},Wt=(e,t)=>t.flatMap(r=>[r,...(e.entities[r]??e.relations[r])?.subTypes??[]]);var tn=e=>{let t=ls(e),r={},n=os(t);for(let i in t.entities)Jt("entity",i,r,t,n);for(let i in t.relations)Jt("relation",i,r,t,n);return r},Jt=(e,t,r,n,i)=>{let o=r[t];if(o){if(o.type===e)return o;throw new Error(`Found entity and relation with the same name: ${t}`)}let s=e==="entity"?n.entities[t]:n.relations[t];if(!s)throw new Error(`${e==="entity"?"Entity":"Relation"} "${t}" not found`);let a="extends"in s&&s.extends?Jt(e,s.extends,r,n,i):void 0;a&&es(a.name,t,r);let l={},d=a?a.idFields:as(t,s);if(ts(l,s.dataFields??[],t),rs(l,s.refFields??{},t),ns(l,s.linkFields??[],t,n,i),e==="entity"){let u={type:"entity",name:t,idFields:d,extends:a?a.name:void 0,subTypes:[],indexes:s.indexes??[],fields:l};return r[t]=u,u}"roles"in s&&s.roles&&is(l,s.roles??{},t,i);let c={type:"relation",name:t,idFields:d,extends:a?a.name:void 0,subTypes:[],indexes:s.indexes??[],fields:l};return r[t]=c,c},es=(e,t,r)=>{let n=e;for(;n;){let i=r[n];if(!i)throw new Error(`Thing "${n}" not found`);i.subTypes.push(t),n=i.extends;}},ts=(e,t,r)=>{for(let n of t??[]){let i=e[n.path];if(n.isVirtual){if(n.default?.type==="fn"&&typeof n.default.fn=="function"){let s={type:"computed",name:n.path,contentType:n.contentType,cardinality:n.cardinality??"ONE",fn:n.default.fn};ve(r,s,i),e[n.path]=s;continue}if(n.default?.type==="value"){let s={type:"constant",name:n.path,contentType:n.contentType,cardinality:n.cardinality??"ONE",value:n.default.value};ve(r,s,i),e[n.path]=s;continue}}let o={type:"data",name:n.path,contentType:n.contentType,cardinality:n.cardinality??"ONE",unique:n.validations?.unique??false};ve(r,o,i),e[n.path]=o;}},rs=(e,t,r)=>{for(let[n,i]of Object.entries(t??{})){let o=e[n],s={type:"ref",name:n,contentType:i.contentType,cardinality:i.cardinality??"ONE"};ve(r,s,o),e[n]=s;}},ns=(e,t,r,n,i)=>{for(let o of t??[]){let s=n.relations[o.relation];if(!s)throw new Error(`Relation ${o.relation} not found`);let a=s.roles?.[o.plays];if(!a)throw new Error(`Role ${o.plays} not found in relation ${o.relation}`);let l=e[o.path];if(o.target==="relation"){let p={type:"link",name:o.path,cardinality:o.cardinality,target:"relation",opposite:{thing:o.relation,path:o.plays,cardinality:a.cardinality}};ve(r,p,l),e[o.path]=p;continue}let d=i[o.relation]?.[o.targetRole];if(!d)throw new Error(`Role ${o.targetRole} in relation ${o.relation} does not exist`);let c=d.targetingRole;if(!c)throw new Error(`Role "${o.targetRole}" in relation "${o.relation}" is not played by any other thing that targets role "${o.plays}"`);let u={type:"link",name:o.path,cardinality:o.cardinality,target:"role",opposite:c};ve(r,u,l),e[o.path]=u;}},is=(e,t,r,n)=>{for(let[i,o]of Object.entries(t)){let s=n[r]?.[i]?.targetingRelation??n[r]?.[i]?.targetingRole;if(!s)throw new Error(`Role ${i} in relation ${r} is not played by any other thing`);let a=e[i],l={type:"role",name:i,cardinality:o.cardinality??"ONE",opposite:s};ve(r,l,a),e[i]=l;}},ve=(e,t,r)=>{if(r&&!isEqual(t,r))throw new Error(`Duplicate field name "${t.name}" in "${e}"`)},os=e=>{let t={};for(let[r,n]of [...Object.entries(e.relations),...Object.entries(e.entities)])for(let i of n.linkFields??[]){let o=t[i.relation]??{};t[i.relation]=o;let s=o[i.plays]??{};o[i.plays]=s;let a=i.target==="relation"?s.targetingRelation:s.targetingRole;if(a){if(a.thing===r||en(r,a.thing,e))continue;if(!en(a.thing,r,e))throw new Error(`Found multiple players for role ${i.plays} in relation ${i.relation}`)}i.target==="relation"?s.targetingRelation={thing:r,path:i.path,cardinality:i.cardinality}:s.targetingRole={thing:r,path:i.path,cardinality:i.cardinality};}return t},en=(e,t,r)=>ss(e,r).includes(t),ss=(e,t)=>{let r=[],n=e;for(;n;){let i=t.entities[n]??t.relations[n];if(!i)throw new Error(`Thing "${n}" not found`);if(!("extends"in i)||!i.extends)break;r.push(i.extends),n=i.extends;}return r.reverse()},as=(e,t)=>{if(t.idFields&&t.idFields.length>0)return [t.idFields[0],...t.idFields.slice(1)];let r=t.dataFields?.find(n=>n.contentType==="ID");if(r)return [r.path];throw new Error(`No id field found for entity "${e}"`)},ls=e=>{let t={entities:{},relations:{}};for(let r in e.entities)rn(r,e,t);for(let r in e.relations)nn(r,e,t);return t},rn=(e,t,r)=>{let n=t.entities[e];if(!n)throw new Error(`Entity "${e}" not found`);if("extends"in n&&n.extends){let i=rn(n.extends,t,r),o={...n,idFields:n.idFields??i.idFields,dataFields:on(i,n),linkFields:sn(i,n),refFields:an(i,n)};return r.entities[e]=o,o}return r.entities[e]=n,n},nn=(e,t,r)=>{let n=t.relations[e];if(!n)throw new Error(`Relation "${e}" not found`);if("extends"in n&&n.extends){let i=nn(n.extends,t,r),o={...n,idFields:n.idFields??i.idFields,dataFields:on(i,n),linkFields:sn(i,n),refFields:an(i,n),roles:cs(i,n)};return r.relations[e]=o,o}return r.relations[e]=n,n},on=(e,t)=>{let r=new Set(t.dataFields?.map(i=>i.path)??[]);return [...e.dataFields?.filter(i=>!r.has(i.path))??[],...t.dataFields??[]]},sn=(e,t)=>{let r=new Set(t.linkFields?.map(i=>i.path)??[]);return [...e.linkFields?.filter(i=>!r.has(i.path))??[],...t.linkFields??[]]},an=(e,t)=>({...Object.fromEntries(Object.entries(e.refFields??{}).filter(([n])=>!t.refFields?.[n])),...t.refFields??{}}),cs=(e,t)=>({...Object.fromEntries(Object.entries(e.roles??{}).filter(([n])=>!t.roles?.[n])),...t.roles??{}});var ln=new Set((process.env.BORM_LOG_LEVEL||"").split(",").map(e=>e.trim()).filter(e=>!!e)),ds=(e,...t)=>{(Array.isArray(e)?e.some(n=>ln.has(n)):ln.has(e))&&console.log(...t);},Z=(...e)=>ds("debug",...e);var Xt={};Qo(Xt,{action:()=>fs,createMachine:()=>Ts,d:()=>We,guard:()=>$s,immediate:()=>ys,interpret:()=>bn,invoke:()=>bs,reduce:()=>$n,state:()=>Bs,transition:()=>ms});function pe(e){return {enumerable:true,value:e}}function cn(e){return {enumerable:true,writable:true,value:e}}var We={},us=()=>true,dn=()=>({}),pn=e=>e,ps=(e,t,r,n)=>e.apply(r,n)&&t.apply(r,n),hs=(e,t,r,[n,i])=>t.call(r,e.call(r,n,i),i),qe=(e,t)=>Object.freeze(Object.create(e,t));function un(e,t,r){return e.reduce((n,i)=>function(...o){return r(n,i,this,o)},t)}function hn(e){return qe(this,{fn:pe(e)})}var fn={},$n=hn.bind(fn),fs=e=>$n((t,r)=>!!~e(t,r)&&t),mn={},$s=hn.bind(mn);function bt(e,t){return t.filter(r=>e.isPrototypeOf(r))}function yn(e,t,...r){let n=un(bt(mn,r).map(o=>o.fn),us,ps),i=un(bt(fn,r).map(o=>o.fn),pn,hs);return qe(this,{from:pe(e),to:pe(t),guards:pe(n),reducers:pe(i)})}var gn={},En={},ms=yn.bind(gn),ys=yn.bind(En,null);function gs(e,t,r){return Yt(t,e,r,this.immediates)||e}function Bn(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 Es={enter:pn};function Bs(...e){let t=bt(gn,e),r=bt(En,e),n={final:pe(e.length===0),transitions:pe(Bn(t))};return r.length&&(n.immediates=pe(r),n.enter=pe(gs)),qe(Es,n)}var Fs={enter(e,t,r){let n=this.fn.call(t,t.context,r);return Kt.isPrototypeOf(n)?qe(Fn,{machine:pe(n),transitions:pe(this.transitions)}).enter(e,t,r):(n.then(i=>{if(e===t.machine)return t.send({type:"done",data:i})}).catch(i=>{if(e===t.machine)return t.send({type:"error",error:i})}),e)}},Fn={enter(e,t,r){if(t.child=bn(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,Yt(t,e,{type:"done",data:n},this.transitions.get("done"))}return e}};function bs(e,...t){let r=pe(Bn(t));return Kt.isPrototypeOf(e)?qe(Fn,{machine:pe(e),transitions:r}):qe(Fs,{fn:pe(e),transitions:r})}var Kt={get state(){return {name:this.current,value:this.states[this.current]}}};function Ts(e,t,r=dn){return typeof e!="string"&&(r=t||dn,t=e,e=Object.keys(t)[0]),We._create&&We._create(e,t),qe(Kt,{context:pe(r),current:pe(e),states:pe(t)})}function Yt(e,t,r,n){let{context:i}=e;for(let{to:o,guards:s,reducers:a}of n)if(s(i,r)){e.context=a.call(e,i,r);let l=t.original||t,d=qe(l,{current:pe(o),original:{value:l}});We._onEnter&&We._onEnter(t,o,e.context,i,r);let c=d.state.value;e.machine=d;let u=c.enter(d,e,r);return e.onChange(e),u}}function ws(e,t){let r=t.type||t,{machine:n}=e,{value:i,name:o}=n.state;return i.transitions.has(r)?Yt(e,n,t,i.transitions.get(r))||n:(We._send&&We._send(r,o),n)}var Ss={send(e){ws(this,e);}};function bn(e,t,r,n){let i=Object.create(Ss,{machine:cn(e),context:cn(e.context(r,n)),onChange:pe(t)});return i.send=i.send.bind(i),i.machine=i.machine.state.value.enter(i.machine,i,n),i}var{createMachine:we,guard:Zt,interpret:Se,invoke:U,reduce:P,state:$e,transition:x}=Xt;var G="0.14.0";var Sn=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,n])=>t(r,n))))[0],me=(e,t)=>{let r=Reflect.ownKeys(e).map(n=>[n,e[n]]);return Object.fromEntries(r.filter(([n,i])=>{let[o,s]=tryit(()=>t(n,i))();return o?false:s}))},ee=(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`)},V=(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)}`)},Tt=(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`)},wt=(e,t)=>{let r=V(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},Rn=(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")},er=(e,t,r)=>{let n=V(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 s="roles"in n?n.roles?.[r]:void 0;if(s)return s;let a="refFields"in n?n.refFields?.[r]:void 0;if(a)return a;throw new Error(`Field ${r} not found in schema`)},tr=(e,t,r)=>er(e,t,r)?.cardinality,ye=(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,$=>$):[],s=[...r||[],...n||[],...o||[],...i||[]],l=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...s];if(!t)return {fields:s,dataFields:r,roleFields:o,linkFields:n};let d=t.$fields?t.$fields.map($=>{if(typeof $=="string"){if($.startsWith("$")||$.startsWith("%"))return;if(!s.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(!s.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($)):[],p=[...d,...c].filter($=>!$?.startsWith("%")).filter($=>!l.includes($)).filter($=>$),f=t.$filter?me(t.$filter,($,E)=>c.includes($)):{},h=t.$filter?me(t.$filter,($,E)=>u.includes($)):{};return {fields:s,dataFields:r,roleFields:o,linkFields:n,refFields:i,usedFields:d,usedLinkFields:n.filter($=>d.includes($)),usedRoleFields:o.filter($=>d.includes($)),usedDataFields:r.filter($=>d.includes($)),usedRefFields:i.filter($=>d.includes($)),unidentifiedFields:p,...c.length?{localFilters:f}:{},...u.length?{nestedFilters:h}:{}}};var Ln=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},Mn=(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):{}},Pe=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var St=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),Oe=e=>{if(Array.isArray(e))return e.map(t=>current(t));if(e&&typeof e=="object"){let t=isDraft(e)?current(e):e,r={};for(let[n,i]of Object.entries(t))r[n]=isDraft(i)?current(i):i;return r}return e},ge=(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}`},xe=e=>customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",21)(),rr=(e=5)=>customAlphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",e)(),Qn=e=>{let t=({value:r})=>{if(r&&typeof r=="object"&&"$id"in r){let n=Object.keys(r).filter(i=>i.startsWith("$"));for(let i of n)delete r[i];}return r};return produce(e,r=>traverse(r,t))};var et=(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:s,meta:a}=o,l=s;if(isObject(l)){if(a.nodePath?.includes(".$filter")||a.nodePath?.includes(".$playedBy"))return;if(l[oe]=a.nodePath,l.$id){let d=l.$entity||l.$relation?l:{[`$${l.$thingType}`]:l.$thing},c=V(t,d);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 d=V(t,l);if(!d?.name)throw new Error(`Schema not found for ${l.$thing}`);l.$path=d.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 d=l.$entity||l.$relation?l:{[`$${l.$thingType}`]:l.$thing},c=V(t,d);if(l.$filter&&(Object.keys(l.$filter).length===0?l.$filter=void 0:(l.$filter=je(l.$filter,l.$thing,t),l.$filterByUnique=ir(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 p=l.$fields?.flatMap(f=>{let h=Dn(f,c,t);return Array.isArray(h)?h:[h]}).filter(Boolean);l.$fields=p;}else {let p=nr(c)?.flatMap(f=>{let h=Dn(f,c,t);return Array.isArray(h)?h:[h]}).filter(Boolean);l.$fields=p;}l.$excludedFields&&(l.$fields=l.$fields.filter(u=>Rt(c,u)?true:!l.$excludedFields.includes(u.$path)));}}}))},nr=e=>{let t=e.dataFields?.map(s=>s.path)||[],r=e.linkFields?.map(s=>s.path)||[],n=Object.keys(e.roles||{})||[],i=Object.keys(e.refFields||{})||[];return [...t,...r,...n,...i]},ir=(e,t)=>Object.keys(e||{}).some(n=>{let i=e[n];if(i!==null&&typeof i<"u"){let o=t.idFields?.includes(n),s=t.dataFields?.some(d=>(d.dbPath===n||d.path===n)&&d?.validations?.unique),a=n==="$id"&&!Array.isArray(i);if(o||s||a){if(typeof i!="object"||i===null||Array.isArray(i))return !Array.isArray(i);let d=Object.keys(i);if(d.length===1&&d[0]==="$eq"){let c=i.$eq;if(typeof c!="object"||c===null||!Array.isArray(c))return true}return false}}return false}),Rt=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),Is=e=>{let{field:t,fieldStr:r,$justId:n,dbPath:i,isVirtual:o,fieldSchema:s}=e;return {$path:r,$dbPath:i,$thingType:"attribute",$as:t.$as||r,$var:r,$fieldType:"data",$justId:n,$id:t.$id,$isVirtual:o,[ue]:s}},ks=e=>{let{field:t,fieldStr:r,linkField:n,$justId:i,dbPath:o,schema:s,fieldSchema:a}=e,{target:l,oppositeLinkFieldsPlayedBy:d}=n;return d.map(c=>{let u=l==="role"?c.thingType:"relation",p=l==="role"?c.thing:n.relation,f={[`$${u}`]:p},h=V(s,f),$=t?.$fields?.filter(y=>Rt(h,y)).length===0,E=[];if(typeof t!="string")if(t.$fields)if($){let y=h.idFields||[];E=[...t.$fields,...y];}else E=t.$fields;else E=nr(h);else E=["id"];t.$excludedFields&&(E=E.filter(y=>Rt(h,y)?true:!t.$excludedFields.includes(y.$path)));let m=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:p,$fields:E,$excludedFields:t.$excludedFields,$fieldType:"link",$target:l,$intermediary:c.relation,$justId:i,$id:t.$id,$filter:m,$idNotIncluded:$,$filterByUnique:ir(t.$filter,h),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ue]:a}})},Cs=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,[ue]:o}},qs=e=>{let{field:t,fieldStr:r,roleField:n,$justId:i,dbPath:o,schema:s,fieldSchema:a}=e;return n.playedBy.map(l=>{let{thing:d,thingType:c,relation:u}=l,p={[`$${c}`]:d},f=V(s,p),h=t?.$fields?.filter(m=>f?.idFields?.includes(m)||f?.idFields?.includes(m.$path)).length===0,$=[];if(typeof t!="string")if(t.$fields)if(h){let m=f.idFields||[];$=[...t.$fields,...m];}else $=t.$fields;else $=nr(f);else $=["id"];t.$excludedFields&&($=$.filter(m=>Rt(f,m)?true:!t.$excludedFields.includes(m.$path)));let E=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:d,$fields:$,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:u,$justId:i,$id:t.$id,$filter:E,$idNotIncluded:h,$filterByUnique:ir(t.$filter,f),$playedBy:{...l,oppositeLinkFieldsPlayedBy:void 0},$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ue]:a}})},Dn=(e,t,r)=>{let n=typeof e=="string"?e:e.$path,i=typeof e=="string",o=t.dataFields?.find(d=>d.path===n),s=t.linkFields?.find(d=>d.path===n),a=t.roles?.[n],l=t.refFields?.[n];if(o){let d=!!o.isVirtual&&!!o.default;return Is({field:e,fieldStr:n,$justId:i,dbPath:o.dbPath,isVirtual:d,fieldSchema:o})}return s?ks({field:e,fieldStr:n,linkField:s,$justId:i,dbPath:s.path,schema:r,fieldSchema:s}):a?qs({field:e,fieldStr:n,roleField:a,$justId:i,dbPath:n,schema:r,fieldSchema:a}):l?Cs({field:e,fieldStr:n,$justId:i,dbPath:n,isVirtual:false,fieldSchema:l}):null},je=(e,t,r)=>{if(e==null)return e;let n=isArray(e),o=(n?e:[e]).map(s=>Object.keys(s).reduce((d,c)=>{let u=s[c],p=isArray(u)?u:[u];if(c.startsWith("$"))if(["$id","$thing"].includes(c))d[c]=u;else if(["$not","$or","$and"].includes(c))d[c]=je(u,t,r);else if(["$eq","$in","$exists"].includes(c))d[c]=u;else throw new Error(`[Internal] Unknown filter operator ${c}`);else {let f=t in r.entities?r.entities[t]:r.relations[t],[h,$]=Tt(f,c);if(h==="idField")d[c]=u;else if(h==="dataField")isObject(u)||isArray(u)&&u.some(isObject)?d[c]=isArray(u)?{$or:je(u,t,r)}:je(u,t,r):isArray(u)?d[c]={$in:u}:d[c]={$eq:u};else if(h==="linkField"||h==="roleField"){let E=$,[m]=E.$things;p.every(y=>typeof y=="string")?d[c]={$id:p,$thing:m}:p.every(y=>isObject(y))&&(d[c]=isArray(u)?{$or:je(u,m,r)}:je(u,m,r));}else throw new Error(`Field ${c} not found in schema of ${t}`)}return d},{}));return !n||o.length===1?o[0]:{$or:o}};var xs=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,js=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,An=e=>{let r=e.toString().replace(xs,"").trim().split("=>")[0].split("{")[0].replace(js,"").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(a=>a.split(":")[0].trim().replace(/['"[\]]/g,"")):o.trim()).filter(Boolean):[]};var tt=({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,o=An(n).filter(s=>!(s 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 Nn=(e,t,r)=>{let n=e[t];if(n)return (isArray(n)?n:[n]).forEach(i=>{if(i.$op!=="create")return;let o=V(r,i),{unidentifiedFields:s}=ye(o,i),{computedFields:a,virtualFields:l}=o,d=listify(i,(p,f)=>f!==void 0?p:void 0),c=d.filter(p=>l?.includes(p));if(c.length>0)throw new Error(`Virtual fields can't be sent to DB: "${c.join(",")}"`);if(a.filter(p=>!d.includes(p)).forEach(p=>{let f=o.dataFields?.find(y=>y.path===p),$=o.linkFields?.find(y=>y.path===p)?.oppositeLinkFieldsPlayedBy[0],E="roles"in o?Sn(o.roles,(y,B)=>y===p):void 0,m=f||$||E;if(!m)throw new Error(`no field Def for ${p}`);if(!i[p]){let y=tt({currentThing:i,fieldSchema:m,mandatoryDependencies:true});i[p]=y;}}),s.length>0)throw new Error(`Unknown fields: [${s.join(",")}] in ${JSON.stringify(i)}`)}),e};var or=(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}_${xe()}`:`SN_MANY_${xe()}`:`SM_${xe()}`;var _e=(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=V(r,t),{usedDataFields:i}=ye(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}},In=(e,t,r)=>{(isArray(t)?t:[t]).forEach(i=>{_e(e,i,r);});};var kn=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"},Cn=(e,t,r)=>{let n=V(r,t),{usedFields:i}=ye(n,t);return t.$op?(_e(e,t,r),t.$op):t.$id||t.$filter?i.length>0?(_e(e,{...t,$op:"update"},r),"update"):(_e(e,{...t,$op:"link"},r),"link"):t.$tempId?i.length>0?(_e(e,{...t,$op:"create"},r),"create"):(_e(e,{...t,$op:"create"},r),"link"):(_e(e,{...t,$op:"create"},r),"create")};var Lt=(e,t)=>{if(t[J].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[J].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 qn=(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 s=kn(o),a=or(o);if(r[J].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:s,$bzId:a}}let l=r;if(l.$things.length===0)throw new Error(`[Internal error] The field ${t} can't be played by any thing.`);let d=r;if(d.$things.length===1){let c=Lt(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,[Ae]:d,$thing:u.thing,$thingType:u.thing in n.entities?"entity":"relation",$op:s,$bzId:a}}if(o.$thing)return [{...o,[Ae]:d,$thing:o.$thing,$thingType:o.$thing in n.entities?"entity":"relation",$op:s,$bzId:a}];if(o.$tempId)throw new Error("[Unsupported] Objects with $tempId and multiple potential players require to explicitly indicate the $thing type.");if(s==="create")throw new Error(`[Wrong format] The field ${t} can be played by multiple things, please specify one on creation.`);return d.$things.map(c=>({...o,[Ae]:d,$thing:c,$thingType:c in n.entities?"entity":"relation",$op:s,$bzId:or(o,c)}))});isArray(e[t])||i.length>1?e[t]=i:e[t]=i[0],e[t]=isArray(e[t])?i:i[0];};var Mt=(e,t)=>{let r=V(t,e).hooks;if(r?.pre){let n=`on${Ln(e.$op)}`;return r.pre.filter(s=>!s.triggers||s.triggers[n]?.()).flatMap(s=>s.actions)}return []};var Pn=(e,t,r,n)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(o=>{if(!St(o)||o.$fields||o[vt])return;let s=Mt(o,r).filter(u=>u.type==="transform"),a=clone(Oe(e)),l=clone(Oe(o)),d=n.mutation?.context||{},c=clone(Oe(o[Ze]||o.$dbNode));s.forEach(u=>{let p=u.fn(l,a,d,c||{});Object.keys(p).length!==0&&(l={...l,...p,...Pe(o),[vt]:true},Object.assign(o,l));});});};var jn=(e,t,r,n)=>{let i=isArray(e[t])?e[t]:[e[t]];for(let o of i)if("$thing"in o){if(o.$fields)continue;let{requiredFields:s,enumFields:a,fnValidatedFields:l,dataFields:d}=V(r,o);if("$op"in o&&o.$op==="create"){for(let c of s)if(!(c in o))throw new Error(`[Validations] Required field "${c}" is missing.`)}if("$op"in o&&o.$op==="update"||o.$op==="create"){for(let c of a)if(c in o){let u=d?.find(p=>p.path===c)?.validations?.enum;if(!u)throw new Error(`[Validations] Enum field "${c}" is missing enum options.`);if(isArray(o[c])){for(let p of o[c])if(p!==null&&!u.includes(p))throw new Error(`[Validations] Option "${p}" 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}".`)}}if("$op"in o&&o.$op==="update"||o.$op==="create"){for(let c of l)if(c in o)try{let u=d?.find(p=>p.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}`)}}if(isObject(o)&&"$thing"in o){let c=o.$thing,u=o,p=clone(Oe(e)),f=clone(Oe(u)),h=n.mutation?.context||{},$=clone(Oe(o[Ze]||{})),E=Mt(u,r);for(let m of E)if(m.type==="validate"){if(m.severity!=="error")continue;try{let y=m.fn(f,p,h,$);if(y===!1)throw new Error(`${m.message}.`);if(y!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(y){throw new Error(`[Validations:thing:${c}] ${y.message}`)}}}}};var _n=(e,t,r,n)=>{let i=isArray(e[t])?e[t]:[e[t]],o=n.slice(1).join(".");i.forEach(s=>{if(s){if(r?.cardinality==="ONE"&&!s.$op&&!s.$id&&!s.$filter&&!s.$tempId&&e.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${o}.${t}`);if(s.$tempId&&!(s.$op===void 0||s.$op==="link"||s.$op==="create"||s.$op==="update"||s.$op==="replace"))throw new Error(`Invalid op ${s.$op} for tempId. TempIds can be created, or linked when created in another part of the same mutation.`)}});};var zn=e=>{if(typeof e!="string")return {isPrefixed:false,obj:e};let t=e.match(/^([^:]+):([^:]+)$/),r=e.match(/^([^:]+):_:([^:]+)$/);if(t&&!e.includes(" ")){let[,n,i]=t;return {isPrefixed:true,obj:{$thing:n,$id:i}}}if(r&&!e.includes(" ")){let[,n,i]=r;return {isPrefixed:true,obj:{$thing:n,$tempId:`_:${i}`}}}return {isPrefixed:false,obj:e}},Un=(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:s}=zn(i);return o?{...s,$op:n}:{$id:i,$op:n}}return i});},vn=(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:s,obj:a}=zn(o);if(s)return {...a,$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 Hn=(e,t)=>{let n=(isArray(e.$root)?e.$root:[e.$root]).map(i=>{let o=Cn(i,i,t);return {...{...i.$thing?{}:{$thing:i.$entity||i.$relation},...i.$thingType?{}:{$thingType:Rn(i,t)},...i.$op?{}:{$op:o},...i.$bzId?{}:{$bzId:`R_${xe()}`}},...i}});e.$root=isArray(e.$root)?n:n[0];};var Qt=(e,t)=>{let r=t[Bt];return isSet(r)?r.has("clean")?(Reflect.set(t,Bt,r.add("clean")),true):false:(Reflect.set(t,Bt,new Set(["clean"])),true)};var Jn=(e,t,r)=>{if(Qt("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(V(r,o),!o.$bzId)throw new Error("[Internal Error] No bzId found");return o.$id.map((s,a)=>({...Oe(o),$id:s,$bzId:`${o.$bzId}_${a}`,...Pe(o)}))}return i});(n.length>0&&isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=n);}};var Kn=(e,t,r)=>{let n=Lt(t,r),[i]=n;e[t]={$thing:i.thing,$thingType:i.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Ae]:r};};var rt=e=>{if(Array.isArray(e)){for(let t of e)if(rt(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"&&rt(e[t]))return true}return false};var na=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(Qt("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);},dr=(e,t,r)=>{let n={$rootWrap:{$root:e}},i=rt(Array.isArray(e)?e:[e]),o=produce(n,s=>traverse(s,({value:a,parent:l,key:d,meta:c})=>{if(!(!l||!d)&&isObject(a)){let u=c.nodePath?.split(".")||[];if(u.some(h=>h.startsWith("%")))return;if(!("$root"in a)){if(!("$thing"in a||"$entity"in a||"$relation"in a)){let h=["$fields","$dbNode","$filter"],$=u.at(-1),E=u.at(-2);if(d==="$root")throw new Error("Root things must specify $entity or $relation");if(!h.includes($||"")&&!h.includes(E||"")&&!$?.startsWith("%")&&!E?.startsWith("%"))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(a)?current(a):a)}`)}}let p=a,f=u.includes("$filter");"$filter"in p&&p.$filter&&(p.$filter=je(p.$filter,p.$thing,t));for(let h of Object.keys(p)){if(na(p,h),h!=="$root"&&f||h!=="$root"&&(h.startsWith("$")||h.startsWith("%")))continue;let $=h!=="$root"?er(t,p,h):{[J]:{fieldType:"rootField"}};if(!$)throw new Error(`[Internal] Field ${h} not found in schema`);let{fieldType:E}=$[J],m=["linkField","roleField"].includes(E),y=E==="refField",B=E==="rootField";if(E==="dataField"){continue}if((m||y)&&(p[h]===null?m&&Kn(p,h,$):m?Un(p,h):vn(p,h,$)),B){if(!("$root"in p))throw new Error(`[Internal] Field ${h} is a rootField but the object is not a root`);Hn(p,t);}if((m||y)&&_n(p,h,$,u),(m||y)&&(qn(p,h,$,t),In(p,p[h],t)),m||B){Jn(p,h,t),Nn(p,h,t);let g=isArray(p[h])?p[h]:[p[h]];for(let T of g){let S=V(t,T),{unidentifiedFields:Q,usedLinkFields:N,usedFields:j,fields:K}=ye(S,T);for(let ce of j)if(!K.includes(ce))throw new Error(`[Schema] Field ${ce} not found in the schema`);if(Q.length>0)throw new Error(`Unknown fields: [${Q.join(",")}] in ${JSON.stringify(a)}`);if(N.length>1){let ce=S.linkFields?.filter(se=>N.includes(se.path));if(ce)for(let se=0;se<ce.length;se++){let I=ce[se];for(let D=0;D<ce.length;D++){let Y=ce[D];if(se!==D&&I.target!==Y.target&&I.relation===Y.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||(Pn(p,h,t,r),jn(p,h,t,r));}}}}));return isArray(o.$rootWrap.$root),o.$rootWrap.$root};var Dt=(e,t)=>{if(!t)return;let r=sa(t);return aa(r,e.query)},sa=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),aa=(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===true&&Object.keys(i).forEach(o=>{o.startsWith("$")&&delete i[o];});}}));var At=async(e,t,r)=>r?(o=>produce(o,s=>traverse(s,({value:a})=>{if(isObject(a)){let l=a;if(!l.$thing)return;if(l.$thing){let d=V(e,l),{virtualFields:c}=d,u=l[oe];if(!u)throw new Error(`[Internal] QueryPath is missing. Value: ${JSON.stringify(l)}`);let p=getNodeByPath(t,u);if(p.$fieldType==="ref")return;let f=p.$fields.map($=>$.$path),h=p.$excludedFields;c.forEach($=>{if(h?.includes($)||f.length>0&&!f.includes($))return;let E=d.dataFields?.find(m=>m.path===$);if(E?.default){let m=tt({currentThing:l,fieldSchema:E,mandatoryDependencies:true});l[$]=m;}else if(l[$]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${$}`)}),h&&h.forEach($=>{if(typeof $!="string")throw new Error("[Internal] ExcludedField is not a string");delete l[$];});}}})))(r):void 0;var ht={$eq:"$=",$not:"$!",$or:"$OR",$and:"$AND",$in:"$IN",$id:"record::id(id)",$exists:"$exists"},Re=(e,t,r)=>{if(e==null)return e;let n=isArray(e),o=(n?e:[e]).map(s=>{let l=Object.keys(s).reduce((d,c)=>{let u=s[c];if(c.startsWith("$")){if(["$or","$and","$not"].includes(c))return {...d,[c]:void 0,[ht[c]]:Re(u,t,r)};if(c==="$id")return {...d,$id:void 0,[ht[c]]:{$IN:isArray(u)?u:[u]}};if(c==="$thing")return d;if(c==="$exists")return {...d,$exists:void 0,[ht[c]]:u};if(c==="$eq")return {...d,$eq:void 0,[ht[c]]:u};if(c==="$in")return {...d,$in:void 0,[ht[c]]:u};throw new Error(`Unknown filter operator ${c}`)}let p=t in r.entities?r.entities[t]:r.relations[t],[f,h]=Tt(p,c);if(f==="idField"){if(p.idFields.length>1)throw new Error("Multiple id fields not supported");return {...d,"record::id(id)":{$IN:isArray(u)?u:[u]}}}if(f==="dataField")return {...d,[c]:Re(u,t,r)};if(f==="linkField"||f==="roleField"){let E=h[Ne].queryPath;return {...d,[E]:Re(u,t,r)}}throw new Error(`Field ${c} not found in schema, Defined in $filter`)},{});return shake(l)});return n?o:o[0]},Fe=e=>{if(e==null)return "";let t=Object.entries(e),r=[];for(let[n,i]of t){if(["$OR","$AND","$!"].includes(n)){let o=n.replace("$",""),s=Array.isArray(i)?i.map(a=>Fe(a)):[Fe(i)];o==="!"?r.push(`!(${s.join(" AND ")})`):r.push(`(${s.join(` ${o} `)})`);continue}if(isObject(i))if(n.includes("<-")||n.includes("->")){let o=Fe(i);r.push(`${n}[WHERE ${o}]`);}else if(n.startsWith("$parent.[")){let o=Fe(i),s=n.replace("$parent.","").replace(/^\[(.*)\]$/,"$1");r.push(`fn::as_array(${s})[WHERE id && ${o}]`);}else if(n.startsWith("$parent")){let o=Fe(i),s=n.replace("$parent.","");r.push(`fn::as_array(${s})[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[s]=o,a=i[s];if(s==="$exists")if(a===true)r.push(`${n} IS NOT NONE`);else if(a===false)r.push(`${n} IS NONE`);else throw new Error(`Invalid value for $exists: ${a}`);else {let l=s.replace("$","");if(Array.isArray(a))r.push(`${n} ${l} [${a.map(d=>d===null?"NONE":`'${d}'`).join(", ")}]`);else if(isObject(a)){let d=Fe(a);r.push(`${n} ${l} ${d}`);}else r.push(`${n} ${l} ${a===null?"NONE":`'${a}'`}`);}}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(s=>s===null?"NONE":`'${s}'`).join(", ")}]`);}else {let o=n.startsWith("$")?n.replace("$",""):"=";r.push(`${n} ${o} ${i===null?"NONE":`'${i}'`}`);}}return r.join(" AND ")},nt=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 ti=e=>{let{queries:t,schema:r}=e;return t.map(n=>fa({query:n,schema:r}))},fa=e=>{let{query:t,schema:r}=e,{$thing:n,$fields:i,$filter:o,$offset:s,$limit:a,$sort:l}=t;if(i.length===0)return null;let d=[];d.push("SELECT");let c=pr({parentQuery:t,queries:i,level:1,schema:r});c&&d.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(h=>le(h));if(t.$id)if(typeof t.$id=="string")d.push(`FROM ${f.map(h=>`${h}:\u27E8${t.$id}\u27E9`).join(",")}`);else if(isArray(t.$id)){let h=t.$id,$=f.flatMap(E=>h?.map(m=>`${E}:\u27E8${m}\u27E9`));d.push(`FROM ${$.join(",")}`);}else throw new Error("Invalid $id");else d.push(`FROM ${f.join(",")}`);if(o){let h=Re(o,n,r),$=Fe(h);d.push(`WHERE ${$}`);}return l&&d.push(nt(l)),typeof a=="number"&&d.push(`LIMIT ${a}`),typeof s=="number"&&d.push(`START ${s}`),d.join(`
|
|
94
|
+
`)},pr=e=>{let{queries:t,schema:r,level:n,parentQuery:i}=e,o=[],s=i[oe];return o.push(L(`"${s}" as \`$$queryPath\``,n)),o.push(L("record::id(id) as `$id`",n)),o.push(L("record::tb(id) as `$thing`",n)),t.forEach(a=>{let l=$a({query:a,level:n,schema:r});l&&o.push(l);}),o.length===0?null:o.join(`,
|
|
95
|
+
`)},$a=e=>{let{query:t,schema:r,level:n}=e;if(t.$fieldType==="data")return ma({query:t,level:n});if(t.$fieldType==="ref")throw new Error("Ref fields are not supported in this context");return t.$fieldType==="link"?ya({query:t,level:n,schema:r}):t.$fieldType==="role"?ga({query:t,level:n,schema:r}):null},ma=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)},ya=e=>{let{query:t,schema:r,level:n}=e,{$fields:i,$filter:o,$offset:s,$limit:a,$sort:l}=t;if(i.length===0)return null;let d=[];d.push(L("(",n));let c=n+1;d.push(L("SELECT",c));let u=pr({parentQuery:t,queries:i,level:c+1,schema:r});u&&d.push(u);let p=t[ue][Ne].queryPath;if(d.push(L(`FROM ${p}`,c)),o){let f=Re(o,t.$thing,r),h=Fe(f);d.push(`WHERE ${h}`);}return l&&d.push(L(nt(l),c)),typeof a=="number"&&d.push(L(`LIMIT ${a}`,c)),typeof s=="number"&&d.push(L(`START ${s}`,c)),d.push(L(`) AS \`${t.$as}\``,n)),d.join(`
|
|
96
|
+
`)},ga=e=>{let{query:t,schema:r,level:n}=e;if(t.$fields.length===0)return null;let i=[];i.push(L("(",n));let o=n+1;i.push(L("SELECT",o));let s=o+1,a=pr({parentQuery:t,queries:t.$fields,level:s,schema:r});a&&i.push(a);let l=t[ue][Ne].queryPath;if(i.push(L(`FROM ${l}`,o)),t.$filter){let d=Re(t.$filter,t.$playedBy.thing,r),c=Fe(d);i.push(`WHERE ${c}`);}return i.push(L(`) AS \`${t.$as}\``,n)),i.join(`
|
|
97
|
+
`)};var ri=e=>{let{queries:t,schema:r}=e;return t.map(n=>Ba({query:n,schema:r}))},Ba=e=>{let{query:t,schema:r}=e,{$thing:n,$fields:i,$filter:o,$offset:s,$limit:a,$sort:l}=t;if(i.length===0)return null;let d=r.entities[n]||r.relations[n];if(!d)throw new Error(`Schema for ${n} not found`);let c=t[oe],u=hr(c),p=ni(i.filter(T=>T.$fieldType==="data")),f=ii(i.filter(T=>T.$fieldType==="link"||T.$fieldType==="role"),r),h=oi(i.filter(T=>T.$fieldType==="ref")),$=[...u,...p,...f,...h].join(`,
|
|
98
|
+
`),E=Fa(t,d),m=o?`WHERE id AND (${Fe(Re(o,n,r))})`:"WHERE id",y=l?nt(l):"",B=typeof a=="number"?`LIMIT ${a}`:"",g=typeof s=="number"?`START ${s}`:"";return `SELECT ${$} ${E} ${m} ${y} ${B} ${g}`},Fa=(e,t)=>{let n=(t.subTypes?[e.$thing,...t.subTypes]:[e.$thing]).map(s=>le(s)),i=(s,a)=>`${s}:\`${a}\``,o=s=>n.flatMap(a=>s.map(l=>i(a,l))).join(",");if(!e.$id)return `FROM ${n.join(",")}`;if(typeof e.$id=="string")return `FROM ${o([e.$id])}`;if(Array.isArray(e.$id))return `FROM ${o(e.$id)}`;throw new Error("Invalid $id")},hr=e=>[`"${e}" as \`$$queryPath\``,"id && record::id(id) || null as `$id`","id && record::tb(id) || null as `$thing`"],ni=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}\``),ii=(e,t)=>e.map(r=>{if(!r[oe])throw new Error(`[Internal] QueryPath is missing. Value: ${JSON.stringify(r)}`);let n=hr(r[oe]),i=ni(r.$fields.filter(f=>f.$fieldType==="data")),o=ii(r.$fields.filter(f=>f.$fieldType==="link"||f.$fieldType==="role"),t),s=oi(r.$fields.filter(f=>f.$fieldType==="ref")),a=[...n,...i,...o,...s].filter(Boolean).join(`,
|
|
99
|
+
`),l=`FROM $parent.\`${r[ue].path}\`[*]`,d=r.$filter&&Object.keys(r.$filter).length>0?`WHERE id AND(${Fe(Re(r.$filter,r.$thing,t))})`:"WHERE id",c=r.$sort?nt(r.$sort):"",u=typeof r.$limit=="number"?`LIMIT ${r.$limit}`:"",p=typeof r.$offset=="number"?`START ${r.$offset}`:"";return `( SELECT ${a} ${l} ${d} ${c} ${u} ${p} ) AS \`${r.$as}\``}).filter(r=>r),oi=e=>e.map(t=>{if(!t[oe])throw new Error(`[Internal] QueryPath is missing. Value: ${JSON.stringify(t)}`);let r=hr(t[oe]);if(t.$fields?.some(s=>isObject(s)))throw new Error("[Unsupported]: Can't query nested ref fields yet");let i=[...r,"id && null || $this as `$value`",...t.$justId?"":t.$fields?.map(s=>`\u27E8${s}\u27E9`)||["*"]].join(`,
|
|
100
|
+
`),o=`FROM $parent.\`${t[ue].dbPath}\``;return `( SELECT ${i} ${o}) AS \`${t.$as}\``});var ai=e=>{let{res:t,queries:r,schema:n}=e;return t.map((o,s)=>li(r[s],o,n))},li=(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 fr(e,t[0],r)}if(t.length>=1)return t.map(n=>fr(e,n,r))}else throw new Error("res is unexpectedly not an array")},fr=(e,t,r)=>{let n=t.$thing||t.tb,i=n in r.entities?"entity":n in r.relations?"relation":"error";if(i==="error")throw new Error(`[Internal] The $thing ${n} is not defined in the schema.`);let o={[oe]:t.$$queryPath,$id:t.$id,$thing:jr(n),$thingType:i};return e.$fields.forEach(s=>{let a=s.$as,l=t[a];s.$path==="id"&&e.$idNotIncluded||(o[a]=wa(s,l,r));}),o},wa=(e,t,r)=>{if(t==null||isArray(t)&&t.length===0)return null;if(e.$fieldType==="data"){let{contentType:n}=e[ue];return si(t,n)??null}if(e.$fieldType==="ref"){let i=(isArray(t)?t:[t]).map(s=>{if(s.$thing){let a=ee(r,s.$thing),[l]=a.idFields;if(e.$justId)return s.$id;let d=u=>u&&typeof u=="object"&&"id"in u&&"tb"in u?u.id:u;return {...mapEntries(s,(u,p)=>isArray(p)?[u,p.map(f=>d(f))]:[u,d(p)]),[oe]:s.$$queryPath,[l]:s.$id}}return s.$value?si(s.$value,"FLEX"):s}),{cardinality:o}=e[ue];return o==="ONE"?i[0]:i}return e.$justId?e.$filterByUnique||e[ue].cardinality==="ONE"?t[0]?.$id??null:t?.map(n=>n.$id)??[]:e.$filterByUnique||e[ue].cardinality==="ONE"?fr(e,t[0],r):li(e,t,r)},si=(e,t)=>{let r=isArray(e)?e:[e];if(t==="DATE"){let n=r.map(i=>new Date(i).toISOString());return isArray(e)?n:n[0]}if(t==="FLEX"){let n=r.map(i=>isDate(i)?new Date(i).toISOString():i);return isArray(e)?n:n[0]}return e};var ci=async e=>{let{client:t,queries:r,config:n}=e,i=`
|
|
101
101
|
BEGIN TRANSACTION;
|
|
102
102
|
${r.join(";")};
|
|
103
103
|
COMMIT TRANSACTION;
|
|
104
|
-
`;return n.query?.debugger&&se(`batchedQuery[${ae}]`,JSON.stringify({batchedQuery:i})),await t.query(i)};var vt=_("error","error",j((e,t)=>({...e,error:t.error}))),as=ge("build",{build:V(async e=>{let{linkMode:t}=e.config.dbConnectors.find(r=>r.provider==="surrealDB").providerConfig;if(t==="edges")return Tn({queries:e.bql.queries,schema:e.schema});if(t==="refs")return Mn({queries:e.bql.queries,schema:e.schema})},_("done","run",j((e,t)=>({...e,surql:{...e.surql,queries:t.data}}))),vt),run:V(async e=>On({client:e.client,queries:$e(e.surql.queries),config:e.config}),_("done","parse",j((e,t)=>({...e,surql:{...e.surql,res:t.data}}))),vt),parse:V(async e=>Dn({res:$e(e.surql.res),queries:e.bql.queries,schema:e.schema,config:e.config}),_("done","success",j((e,t)=>({...e,bql:{...e.bql,res:t.data}}))),vt),success:ce(),error:ce()},e=>e),ls=async e=>new Promise((t,r)=>{Ee(as,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),kn=async(e,t,r,n)=>ls({bql:{queries:e},surql:{},schema:t,config:r,client:n,error:null});var ft=e=>{let{$filter:t,$var:r,$thing:n,schema:i,depth:o}=e,a=hs(t,Y(i,n)),{$not:s,...l}=a,h=[];if(Kt(s)){let u=Ht(s,r,n,i,o,true);h.push(...u);}else if(s!==void 0)throw new Error("$not must be a PositiveFilter object");let c=Ht(l,r,n,i,o,false);return h.push(...c),h.join(`
|
|
105
|
-
`)},
|
|
106
|
-
`)
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
offset ${l};`),typeof h=="number"&&u.push(`
|
|
110
|
-
|
|
111
|
-
`)}
|
|
112
|
-
?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(...Yt(M,F,o));let R=l?.filter(x=>x.$fieldType==="link");R&&R.length>0&&a.push(...Zt(R,F,`${t}.${s.$var}`,o,i));let I=l?.filter(x=>x.$fieldType==="role");I&&I.length>0&&a.push(...Xt(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},Zt=(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}${Jt}${s.$var}`;if(a.push(L(`$${E} isa ${s.$thing};`,o)),s.$filter||s.$id){let M=lt(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(...Yt(R,E,o));let I=l?.filter(J=>J.$fieldType==="link");I&&I.length>0&&a.push(...Zt(I,E,`${t}.${s.$var}`,o,i));let x=l?.filter(J=>J.$fieldType==="role");x&&x.length>0&&a.push(...Xt(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},fs=e=>typeof e=="string"?{field:e,desc:false}:{...e,desc:e.desc??false},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=fs(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 Pn=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 ms(a,l,h,n,i)})},ms=(e,t,r,n,i)=>e.length===0?null:r.$filterByUnique?Nn(e[0],t,n,i):e.map(o=>Nn(o,t,n,i)),Nn=(e,t,r,n)=>{let{dataFields:i,currentSchema:o,linkFields:a,roleFields:s,schemaValue:l}=er(e,r),h=tr(i,o,n),c=nr(a,r,n),u=rr(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}},er=(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=z(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}},tr=(e,t,r)=>{let{$metaData:n}=e,{as:i}=ys(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])},rr=(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}=xn(a);if(l===null)return;let d=o.map(f=>{let{dataFields:p,currentSchema:$,linkFields:g,roleFields:y,schemaValue:m}=er(f,t),F=tr(p,$,r);if(h==="T")return F.id;let E=nr(g,t,r),Q=rr(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},nr=(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}=xn(a);if(l===null)return;let d=o.map(f=>{let{dataFields:p,currentSchema:$,linkFields:g,roleFields:y,schemaValue:m}=er(f,t),F=tr(p,$,r);if(h==="T")return F.id;let E=nr(g,t,r),Q=rr(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},xn=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}},ys=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 jn=async e=>{let{tqlRequest:t,dbHandles:r,config:n}=e,i=new TypeDBOptions;i.infer=true;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 ws=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,Ts=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,Ms=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,ir=_("error","error",j((e,t)=>({...e,error:t.error}))),Ss=ge("build",{build:V(async e=>qn({queries:e.bql.queries,schema:e.schema}),_("done","run",j(Ts)),ir),run:V(async e=>jn({dbHandles:e.handles,tqlRequest:$e(e.tql.queries),config:e.config}),_("done","parse",j(Ms)),ir),parse:V(async e=>Pn({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries,schema:e.schema,config:e.config,rawTqlRes:$e(e.tql.res)}),_("done","success",j(ws)),ir),success:ce(),error:ce()},e=>e),Ls=async e=>new Promise((t,r)=>{Ee(Ss,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),_n=async(e,t,r,n,i)=>Ls({bql:{raw:e,queries:t},tql:{},schema:r,config:n,handles:i,error:null});var Qs=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,or=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,yt=_("error","error",j((e,t)=>({...e,error:t.error}))),Rs=ge("enrich",{enrich:V(async e=>(se(`originalBQLQuery[${ae}]`,JSON.stringify(e.bql.raw)),Yr(e.bql.raw,e.schema)),_("done","adapter",j(Qs)),yt),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 _n(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)},_("done","postHooks",j(or)),yt),postHooks:V(async e=>bn(e.schema,$e(e.bql.queries),$e(e.bql.res)),_("done","clean",j(or)),yt),clean:V(async e=>Fn(e.config,$e(e.bql.res)),_("done","success",j(or)),yt),success:ce(),error:ce()},e=>e),Ds=async e=>new Promise((t,r)=>{Ee(Rs,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),He=async(e,t,r,n)=>Ds({bql:{raw:e},schema:t,config:r,handles:n,error:null});var Vn=async(e,t,r,n)=>{let i=Array.isArray(e)?e:[e],o=i.map(l=>sr(l,true)),s=(await He(o,t,r,n)).bql.res;return i.map((l,h)=>{let c=Y(t,l.$thing);return Hn({mut:l,node:s[h],schema:t,thing:c})})},vn=new Set(["$op","$bzId","$parentKey"]),Os=new Set(["$relation","$entity","$id",...vn]),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(vn.has(i)||Os.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],false)}):isObject(o)&&(r[i]={$path:i,...sr(o,false)});}return n.$fields=Object.values(r),n},Hn=e=>{let{mut:t,node:r,schema:n,thing:i}=e,o=Jn(i),a=As(r);if(Array.isArray(t))return t.map(l=>{let h=a[l.$id];return h?zn({mut:l,node:h,schema:n,thing:i,...o}):l});let s=a[t.$id];return zn({mut:t,node:s,schema:n,thing:i,...o})},zn=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=Kn({$fields:t.$fields,node:r,schema:n,thing:i,dataFieldMap:o,linkFieldMap:a,roleFieldMap:s}),u={...h,[ze]: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]=Hn({mut:f,schema:n,node:r[d],thing:g});}return u},Kn=e=>{let{$fields:t,node:r,schema:n,thing:i,dataFieldMap:o,linkFieldMap:a,roleFieldMap:s}=e,l=t||ks(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(Un):Un(f));return}let g=Y(n,$),y=Jn(g);h[d]=Array.isArray(f)?f.map(m=>Wn({...y,$fields:c.$fields,value:m,schema:n,thing:g})):Wn({...y,$fields:c.$fields,value:f,schema:n,thing:g});}),h},ks=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},Un=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},Wn=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 Kn({...e,node:t})},Jn=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}},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 Yn=(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}=ue(u,a);if(["create","update","delete","link","unlink","match","replace"].includes(l)){let m={...de(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=de(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=de(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=de(a,M=>isSymbol(M)||M.startsWith("$")),Q=F.map(M=>M.$op?`$\u27E8${M.$bzId}\u27E9`:_e(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 Xn=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 ti=async(e,t)=>{let r=c=>{let u=[],d=[],f=y=>{if(y.$id)return y.$id;let m=z(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=We({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=z(t,E),{dataFields:M,roleFields:R,linkFields:I,refFields:x,usedFields:J}=ue(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=Kr(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=z(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=de(E,(B,T)=>R.includes(B)),S=mapEntries(D,(B,T)=>isArray(T)?[B,T]:isObject(T)?[B,T.$bzId]:[B,T]),b=de(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=z(t,E).roles,w=mapEntries(S,(N,q)=>{let k=T[N]?.cardinality;if(!k)throw new Error(`Role ${N} not found in schema`);return Array.isArray(q)?k==="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){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 k=N(q.$op);if(k==="replace")throw new Error("Not supported yet: replace on roleFields");let v={...b,$thing:E.$thing,$thingType:"relation",$op:k==="delete"?"unlink":k,[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(Xn(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 lr="___",zs=Symbol.for("grandChildOfCreate"),ri=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?!z(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("$")&&!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 k in B)if(!N.includes(k)&&!(q.includes(k)&&!T))if(!k.includes("$")&&(isObject(B[k])||Array.isArray(B[k]))){let v=Us(B[k]);if(Array.isArray(v)&&v.length>0)v.forEach(be=>{let we={$path:k,...b(be),...be.$filter&&{$as:be.$bzId}};w.find(X=>X.$path===we.$path&&!X.$filter)||(w=[...w,we]);});else {let be={$path:k,...b(v),...!v.$filter&&{$as:v.$bzId}};w=[...w,be];}}else O[k]=B[k];return {...O,$fields:w}};return S.map(B=>b(B,true))})(Array.isArray(e)?e:[e]),c=(await He(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[zs]=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 k={...T,$id:q,$bzId:`T4_${v4()}`,$filterBzId:T.$bzId};b.push(k);});}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,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 le=o(U,true);if(le.length>0){let C=false;le.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 he in X){let Z=z(t,X);!he.startsWith("$")&&Z.dataFields?.find(ne=>ne.path===he)&&(W[he]=X[he]);}return W})(),P=Object.keys(X),U=o(X,true),le=[],C=(W,he)=>{if(W===U.length){let ne={...he};P.forEach(pe=>{pe.startsWith("$")&&(ne[pe]=X[pe]);}),le.push({...ne,...H});return}let Z={...he,[U[W]]:X[U[W]],...Ie(he),...H};C(W+1,Z),C(W+1,he);};return C(0,{...Ie(X)}),le},k=[];return w.forEach(X=>{let G=q(X),H=[];G.forEach(P=>{let U=o(P,true);if(P.$op==="create")H.push(P);else if(P.$id){let le=d(P.$objectPath),C=[];if(U.forEach(W=>{let he=`${le.includes("undefined")?"root":le}.${P.$id}${lr}${W}`,Z=p[he];P[W].filter(pe=>pe.$op==="unlink"||pe.$op==="delete"||pe.$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(pe=>pe.$id);ne.length>0?W[Z]=ne:W[Z]=void 0;}),o(W,true).length>0&&H.push(W);}}else if(P.$objectPath){let le=d(P.$objectPath),C=p[le]?.$ids||[];C.forEach(W=>{let he=[];U.forEach(Z=>{let ne=`${le}.${W}${lr}${Z}`,pe=p[ne];pe&&he.push({key:Z,ids:pe.$ids});}),U.length===0?C.filter(ne=>!H.find(pe=>pe.$id===ne)).forEach(ne=>{H.push({...P,$id:ne,$bzId:P.$tempId||`PQT2_${v4()}`});}):he.length===U.length&&!H.find(Z=>Z.$id===W)&&(U.forEach(Z=>{let ne=`${d(P.$objectPath)}.${W}${lr}${Z}`,pe=p[ne]?.$ids||[],Fi=P[Z].find(je=>!je.$id),fr=[...pe.map(je=>({...Fi,$id:je,$objectPath:{beforePath:P.$objectPath.beforePath,ids:je,key:Z}})),...P[Z].filter(je=>je.$id)];fr.length>0&&(P[Z]=fr);}),H.push({...P,$id:W,$bzId:P.$tempId||`PQ3_${v4()}`}));});}else H.push(P);}),H.forEach(P=>{k.push(P);});}),[...k,...O,...N].filter(X=>o(X).length>0?true:X.$op!=="update").map(X=>{let G={...X};return o(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=o(b,true),T={...b};return B.forEach(w=>{let O=Array.isArray(b[w])?b[w]:[b[w]],N=[],q=[],k=[],v={},be=kt(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"&&be==="ONE"&&C.id?(v=C,Array.isArray(C.id)?k=[...q,...C.id]:k.push(C.id)):N.push(C);});let we=d(v.$objectPath),G=f(we).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)),le=Ie(v);P.length>0&&N.push({...v,$op:"unlink",$id:P,$bzId:v.$tempId||`T4_${v4()}`,id:void 0,...le}),U.length>0&&U.forEach(C=>{N.push({...v,$op:"link",$id:C,$bzId:v.$tempId||`T5_${v4()}`,...le});}),k.length>0&&k.forEach(C=>{N.push({...v,$op:"create",id:C,$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(k=>{let v=k.$filter?{...k.$objectPath,key:k.$filterBzId}:k.$objectPath,be=d(v),we=p[be],X=(P,U)=>P.every(le=>U.includes(le)),G=k.$id?Array.isArray(k.$id)?X(k.$id,we?.$ids?we.$ids:[]):we?.$ids?.includes(k.$id):we,H=kt(t,O,k.$objectPath.key);if(k.$op==="link"&&G&&H==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${d(k.$objectPath)}" because it is already occupied.`);if(k.$op)switch(k.$op){case "delete":if(!G&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${k.$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:"${k.$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:"${k.$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:"${k.$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)},Us=e=>isObject(e)&&!isArray(e)&&"$eq"in e?e.$eq:e;var ni=(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("%")||Vs(e,t,i,n);});},Vs=(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 ii=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:$}=ue(p,s),{idFields:g}=p,y=d||s[g[0]],m=(isArray(h)?h:[h]).map(te),F=de(s,b=>b.startsWith("$")),E=de(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} = ${_e(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(", ")})(),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}=ue(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}=ue(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=de(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 [`
|
|
113
|
-
|
|
114
|
-
|
|
104
|
+
`;return n.query?.debugger&&Z(`batchedQuery[${G}]`,JSON.stringify({batchedQuery:i})),await t.query(i)};var Sa=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,di=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,it=x("error","error",P((e,t)=>({...e,error:t.error}))),Ra=we("enrich",{enrich:U(async e=>(Z(`originalBQLQuery[${G}]`,JSON.stringify(e.bql.raw)),et(e.bql.raw,e.schema)),x("done","build",P(Sa)),it),build:U(async e=>{let{linkMode:t}=e.config.dbConnectors.find(r=>r.provider==="surrealDB").providerConfig;if(t==="edges")return ti({queries:e.bql.queries??[],schema:e.schema});if(t==="refs")return ri({queries:e.bql.queries??[],schema:e.schema})},x("done","run",P((e,t)=>({...e,surql:{...e.surql,queries:t.data}}))),it),run:U(async e=>ci({client:e.client,queries:ge(e.surql.queries),config:e.config}),x("done","parse",P((e,t)=>({...e,surql:{...e.surql,res:t.data}}))),it),parse:U(async e=>ai({res:ge(e.surql.res),queries:e.bql.queries??[],schema:e.schema,config:e.config}),x("done","postHooks",P((e,t)=>({...e,bql:{...e.bql,res:t.data}}))),it),postHooks:U(async e=>At(e.schema,ge(e.bql.queries),ge(e.bql.res)),x("done","clean",P(di)),it),clean:U(async e=>Dt(e.config,ge(e.bql.res)),x("done","success",P(di)),it),success:$e(),error:$e()},e=>e),La=async e=>new Promise((t,r)=>{Se(Ra,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),ui=async(e,t,r,n)=>La({bql:{raw:e},surql:{},schema:t,config:r,client:n,error:null});var he=z.json(),Le=z.array(he),pi=z.strictObject({$exists:z.boolean().optional(),$eq:he.optional(),$neq:he.optional(),$gt:he.optional(),$lt:he.optional(),$gte:he.optional(),$lte:he.optional(),$contains:he.optional(),$containsNot:he.optional(),$in:Le.optional(),$nin:Le.optional(),$containsAll:Le.optional(),$containsAny:Le.optional(),$containsNone:Le.optional()}),ot=z.lazy(()=>z.object({$or:z.array(z.lazy(()=>ot)).optional(),$not:z.lazy(()=>ot).optional()}).catchall(z.union([he,Le,z.lazy(()=>z.union([Je,z.array(Je)]))]))),Je=z.lazy(()=>z.object({$or:z.array(z.lazy(()=>ot)).optional(),$not:z.lazy(()=>ot).optional(),$exists:z.boolean().optional(),$eq:he.optional(),$neq:he.optional(),$gt:he.optional(),$lt:he.optional(),$gte:he.optional(),$lte:he.optional(),$contains:he.optional(),$containsNot:he.optional(),$in:Le.optional(),$nin:Le.optional(),$containsAll:Le.optional(),$containsAny:Le.optional(),$containsNone:Le.optional()}).catchall(z.union([he,Le,z.lazy(()=>z.union([Je,z.array(Je)]))]))),hi=z.object({$id:z.union([z.string(),z.array(z.string())]).optional(),$filter:z.union([ot,z.array(ot)]).optional(),$fields:z.array(z.union([z.string(),z.lazy(()=>Ma)])).optional(),$excludedFields:z.array(z.string()).optional(),$limit:z.number().optional(),$offset:z.number().optional(),$sort:z.array(z.union([z.object({field:z.string(),desc:z.boolean().optional()}),z.string()])).optional()}),Ma=hi.extend({$path:z.string(),$as:z.string().optional()}),fi=hi.extend({$thing:z.string().optional(),$entity:z.string().optional(),$relation:z.string().optional()}).superRefine((e,t)=>{!e.$thing&&!e.$entity&&!e.$relation&&t.addIssue({code:"custom",message:"Query must contain at least one of: $thing, $entity, or $relation",path:["$thing"]});}).transform(e=>{let{$thing:t,$entity:r,$relation:n,...i}=e;return {...i,$thing:t??r??n}});var $i=(e,t,r)=>{let n=t[e.$thing],i=mi({fields:e.$fields,thing:n,schema:t,metadata:r}),o=e.$filter?st(e.$filter,n,t):void 0,s=Array.isArray(e.$id)?e.$id:e.$id?[e.$id]:[],a=s.length===1||mr(n,o)?"ONE":"MANY";return {source:s.length>0?{type:"record_pointer",thing:[n.name,...n.subTypes],ids:s}:{type:"table_scan",thing:[n.name,...n.subTypes]},projection:i,filter:o,limit:Bi(e.$limit),offset:Fi(e.$offset),sort:bi(i,gi(e.$sort)),cardinality:a}},mi=e=>{let{fields:t,thing:r,schema:n,metadata:i}=e,o=[];if(i&&(o.push({type:"metadata",path:"$id"}),o.push({type:"metadata",path:"$thing"})),!t){for(let s of Object.values(r.fields))o.push($r(s));return {fields:o}}for(let s of t){if(typeof s=="string"){if(s==="$id"||s==="$thing"){o.push({type:"metadata",path:s});continue}let p=r.fields[s];if(!p)throw new Error(`Field ${s} not found in ${r.name}`);o.push($r(p));continue}let a=ka(s.$as);if(s.$path==="$id"||s.$path==="$thing"){o.push({type:"metadata",path:s.$path,alias:a});continue}let l=r.fields[s.$path];if(!l)throw new Error(`Field ${s} not found in ${r.name}`);if(l.type==="constant"||l.type==="computed")continue;if(l.type==="data"||l.type==="ref"){o.push($r(l,a));continue}let d=n[l.opposite.thing],c=mi({fields:s.$fields,thing:d,schema:n,metadata:i}),u="$filter"in s&&s.$filter?st(s.$filter,d,n):void 0;o.push({type:"nested_reference",path:s.$path,projection:c,cardinality:typeof s.$id=="string"||mr(d,u)?"ONE":l.cardinality,alias:a,ids:typeof s.$id=="string"?[s.$id]:s.$id,filter:u,limit:Bi(s.$limit),offset:Fi(s.$offset),sort:bi(c,gi(s.$sort))});}return {fields:o}},$r=(e,t)=>e.type==="data"?{type:"data",path:e.name,alias:t}:e.type==="ref"&&e.contentType==="FLEX"?{type:"flex",path:e.name,cardinality:e.cardinality,alias:t}:{type:"reference",path:e.name,cardinality:e.cardinality,alias:t},st=(e,t,r)=>Array.isArray(e)?{type:"or",filters:e.map(o=>st(o,t,r)).filter(o=>!!o)}:{type:"and",filters:Qa(e,t,r)},Qa=(e,t,r)=>Object.entries(e).map(([n,i])=>{if(n==="$not"&&e.$not)return Da(e.$not,t,r);if(n==="$or"&&e.$or)return Aa(e.$or,t,r);let o=t.fields[n];if(!o)throw new Error(`Field ${n} not found in ${t.name}`);if(o.type==="constant"||o.type==="computed")throw new Error(`Filtering on constant or computed field ${n} is not supported`);if(i!==void 0)return o.type==="data"?Na(o,i):o.type==="ref"?Oa(o,i):yi(o,i,r)}).filter(n=>n!==void 0),Da=(e,t,r)=>{let n=st(e,t,r);return n?{type:"not",filter:n}:void 0},Aa=(e,t,r)=>st(e,t,r),Na=(e,t)=>{let r=pi.safeParse(t);if(r.success){let n=[];for(let[i,o]of Object.entries(r.data)){if(i==="$exists"){n.push({type:"null",op:o?"IS NOT":"IS",left:e.name,tunnel:false});continue}if((i==="$eq"||i==="$ne")&&o===null){n.push({type:"null",op:i==="$eq"?"IS":"IS NOT",left:e.name,tunnel:false});continue}let s=Ia[i];if(s){n.push({type:"scalar",op:s,left:e.name,right:o});continue}let a=Ei[i];if(a){n.push({type:"list",op:a,left:e.name,right:o});continue}throw new Error(`Invalid filter operation: ${i}`)}return {type:"and",filters:n}}return Array.isArray(t)?e.cardinality==="ONE"?{type:"list",op:"IN",left:e.name,right:t}:{type:"list",op:"CONTAINSANY",left:e.name,right:t}:e.cardinality==="ONE"?t===null?{type:"null",op:"IS",left:e.name,tunnel:false}:{type:"scalar",op:"=",left:e.name,right:t}:{type:"scalar",op:"CONTAINS",left:e.name,right:t}},Oa=(e,t)=>{if(e.contentType==="REF"){if(e.cardinality==="ONE"){if(typeof t=="string")return {type:"ref",op:"IN",left:e.name,right:[t],tunnel:false};if(Ot.safeParse(t).success)return {type:"ref",op:"IN",left:e.name,right:t,tunnel:false};throw new Error(`Invalid filter value for ref field ${e.name}: ${JSON.stringify(t)}`)}if(typeof t=="string")return {type:"ref",op:"CONTAINSANY",left:e.name,right:[t],tunnel:false};if(Ot.safeParse(t).success)return {type:"ref",op:"CONTAINSANY",left:e.name,right:t,tunnel:false};throw new Error(`Invalid filter value for ref field ${e.name}: ${JSON.stringify(t)}`)}throw new Error("Filtering by FLEX reference is not supported")},yi=(e,t,r)=>{let n=e.type==="link"&&e.target==="role";if(t===null)return {type:"null",op:"IS",left:e.name,tunnel:n};if(typeof t=="string")return {type:"ref",op:e.cardinality==="ONE"?"IN":"CONTAINSANY",left:e.name,right:[t],tunnel:n};if(Ot.safeParse(t).success)return {type:"ref",op:e.cardinality==="ONE"?"IN":"CONTAINSANY",left:e.name,right:t,tunnel:n};let i=Nt.union([Je,Nt.array(Je)]).safeParse(t);if(i.error)throw new Error(`Invalid nested filter: ${i.error.message}`);let o=r[e.opposite.thing];if(!o)throw new Error(`Opposite thing ${e.opposite.thing} not found`);let s=[e.opposite.thing,...o.subTypes];if(Array.isArray(i.data))return {type:"or",filters:i.data.map(T=>yi(e,T,r))};let{$eq:a,$ne:l,$contains:d,$containsNot:c,$in:u,$nin:p,$containsAll:f,$containsAny:h,$containsNone:$,...E}=i.data;for(let g of ["$gt","$lt","$gte","$lte"])if(E[g])throw new Error(`Filtering ${e.type} field with ${g} operator is not supported`);let m=[];for(let g of ["$exists","$eq","$ne","$contains","$containsNot"]){let T=i.data[g];if(T!==void 0){if(g==="$exists"){m.push({type:"null",op:T?"IS NOT":"IS",left:e.name,tunnel:n});continue}if((g==="$eq"||g==="$ne")&&T===null){m.push({type:"null",op:g==="$eq"?"IS":"IS NOT",left:e.name,tunnel:n});continue}if(typeof T!="string")throw new Error(`Filter value for ${e.type} field with operator ${g} must be a string`);m.push({type:"ref",op:g==="$eq"||g==="$contains"?"IN":"NOT IN",left:e.name,right:[T],thing:s,tunnel:n});}}for(let g of ["$in","$nin","$containsAll","$containsAny","$containsNone"]){let T=i.data[g];if(T===void 0)continue;let S=Ot.safeParse(T);if(!S.success)throw new Error(`Filter value for ${e.type} field with operator ${g} must be a string array`);let Q=Ei[g];if(!Q)throw new Error(`Invalid list operator: ${g}`);m.push({type:"ref",op:Q,left:e.name,right:S.data,thing:s,tunnel:n});}let y=r[e.opposite.thing];if(!y)throw new Error(`Unknown thing: ${e.opposite.thing}`);let B=st(E,y,r);return B&&m.push({type:"nested",path:e.name,filter:B,cardinality:e.cardinality}),{type:"and",filters:m}},mr=(e,t)=>{if(!t)return false;if(t.type==="scalar"){if(t.op!=="=")return false;let r=e.fields[t.left];if(!r)throw new Error(`Field ${t.left} not found in ${e.name}`);return r.type==="data"&&r.unique}if(t.type==="list"){if(t.op!=="IN"||t.right.length>1)return false;let r=e.fields[t.left];if(!r)throw new Error(`Field ${t.left} not found in ${e.name}`);return r.type==="data"&&r.unique}return t.type==="and"?t.filters.some(r=>mr(e,r)):false},gi=e=>{if(!(!e||e.length===0))return e.map(t=>typeof t=="string"?{field:t,desc:false}:{field:t.field,desc:t.desc??false})},Ia={$eq:"=",$ne:"!=",$gt:">",$lt:"<",$gte:">=",$lte:"<=",$contains:"CONTAINS",$containsNot:"CONTAINSNOT"},Ei={$in:"IN",$nin:"NOT IN",$containsAll:"CONTAINSALL",$containsAny:"CONTAINSANY",$containsNone:"CONTAINSNONE"},Ot=Nt.array(Nt.string()),ka=e=>{if(e!==void 0&&!/^[a-zA-Z0-9_-]+$/.test(e))throw new Error(`Invalid alias: ${e}`);return e},Bi=e=>{if(e!==void 0&&(typeof e!="number"||e<0))throw new Error(`Invalid limit: ${e}`);return e},Fi=e=>{if(e!==void 0&&(typeof e!="number"||e<0))throw new Error(`Invalid offset: ${e}`);return e},bi=(e,t)=>{if(!t||t.length===0)return;let r=new Set(e.fields.map(n=>n.type==="metadata"?n.path:n.alias??n.path));for(let n of t)if(!r.has(n.field))throw new Error(`Missing sorter field in the selected fields: ${n.field}`);return t};var Ti=(e,t)=>{let r=[],n=e.cardinality==="MANY"?0:1;e.cardinality==="ONE"&&r.push("array::first("),r.push(wi(e.projection,n,t)),r.push(Si(e.source,n,t));let i=e.filter&&Ve(e.filter,t);return i&&r.push(X(`WHERE ${i}`,n)),e.sort&&e.sort.length>0&&r.push(Ri(e.sort,n)),e.limit!==void 0&&r.push(X(`LIMIT ${e.limit}`,n)),e.offset!==void 0&&r.push(X(`START ${e.offset}`,n)),e.cardinality==="ONE"&&r.push(")"),r.join(`
|
|
105
|
+
`)},wi=(e,t,r)=>{let n=[],i=t+1;for(let s of e.fields)s.type==="metadata"?n.push(Ca(s,i)):s.type==="data"?n.push(qa(s,i)):s.type==="reference"?n.push(Pa(s,i)):s.type==="nested_reference"?n.push(xa(s,i,r)):s.type==="flex"&&n.push(ja(s,i));let o=[];return o.push(X("SELECT",t)),o.push(n.join(`,
|
|
106
|
+
`)),o.join(`
|
|
107
|
+
`)},Ca=(e,t)=>{if(e.path==="$id")return X(`record::id(id) AS ${te(e.alias??"$id")}`,t);if(e.path==="$thing")return X(`record::tb(id) AS ${te(e.alias??"$thing")}`,t);throw new Error(`Unsupported metadata field: ${e.path}`)},qa=(e,t)=>{if(e.path==="id")return X(`record::id(id) AS ${te(e.alias??"id")}`,t);let r=te(e.path);return e.alias?X(`${r} AS ${te(e.alias)}`,t):X(r,t)},Pa=(e,t)=>{let{path:r,alias:n,cardinality:i}=e,o=te(r),s=te(n||r);return X(i==="ONE"?`array::first(SELECT VALUE record::id(id) FROM $this.${o}[*]) AS ${s}`:`(SELECT VALUE record::id(id) FROM $this.${o}[*]) AS ${s}`,t)},xa=(e,t,r)=>{let n=[];e.cardinality==="MANY"?n.push(X("(",t)):n.push(X("array::first(",t)),n.push(wi(e.projection,t+1,r));let i=e.filter?Ve(e.filter,r):void 0;n.push(X(`FROM $this.${te(e.path)}[*]`,t+1));let o=[];if(e.ids&&e.ids.length>0){let s=e.ids.map(a=>`$${be(r,a)}`);s.length===1?o.push(`record::id(id) = ${s[0]}`):o.push(`record::id(id) IN [${s.join(", ")}]`);}return i&&o.push(i),o.length>0&&n.push(X(`WHERE ${o.join(" AND ")}`,t+1)),e.sort&&e.sort.length>0&&n.push(Ri(e.sort,t+1)),e.limit!==void 0&&n.push(X(`LIMIT ${e.limit}`,t+1)),e.offset!==void 0&&n.push(X(`START ${e.offset}`,t+1)),n.push(X(`) AS ${te(e.alias||e.path)}`,t)),n.join(`
|
|
108
|
+
`)},ja=(e,t)=>{let{path:r,alias:n,cardinality:i}=e,o=te(r),s=te(n||r);return X(i==="ONE"?`${o} && IF type::is::record(${o}) { record::id(${o}) } ELSE { ${o} } AS ${s}`:`${o} && ${o}.map(|$i| IF type::is::record($i) { record::id($i)} ELSE { $i }) AS ${s}`,t)},Si=(e,t,r)=>{let n=[];switch(e.type){case "table_scan":{n.push(X(`FROM ${e.thing.map(te)}`,t));break}case "record_pointer":{let i=e.thing.flatMap(o=>e.ids.map(s=>`${te(o)}:${te(s)}`)).map(o=>`type::record($${be(r,o)})`).join(", ");n.push(X(`FROM ${i}`,t));break}case "subquery":{n.push(X(e.cardinality==="MANY"?"FROM array::distinct(array::flatten(":"FROM (",t)),e.oppositePath,n.push(X(`SELECT VALUE ${te(e.oppositePath)}`,t+1)),n.push(Si(e.source,t+1,r));let i=e.filter?Ve(e.filter,r):void 0;i&&n.push(X(`WHERE ${i}`,t+1)),n.push(X(e.cardinality==="MANY"?"))":")",t));break}}return n.join(`
|
|
109
|
+
`)},Ve=(e,t,r)=>{let n=r??"";switch(e.type){case "scalar":{let i=e.left==="id"?`record::id(${n}id)`:`${n}${te(e.left)}`,o=be(t,e.right);return `${i} ${e.op} $${o}`}case "list":{let i=e.right.map(s=>`$${be(t,s)}`).join(", ");return `${`${n}${te(e.left)}`} ${e.op} [${i}]`}case "ref":{let i=e.left==="id"?`record::id(${n}id)`:`${n}${te(e.left)}`;if(e.thing){let o=e.thing.flatMap(s=>e.right.map(a=>{let l=`${te(s)}:${te(a)}`;return `type::record($${be(t,l)})`}));if(o.length===1){let s=o[0];if(e.op==="IN")return `${i} = ${s}`;if(e.op==="NOT IN")return `${i} != ${s}`;if(e.op==="CONTAINSANY")return `${s} IN ${i}`;if(e.op==="CONTAINSNONE")return `${s} NOT IN ${i}`}return `${i} ${e.op} [${o.join(", ")}]`}if(e.right.length===1){if(e.op==="IN")return e.tunnel?`(array::first(${i}) && record::id(array::first(${i})) = $${be(t,e.right[0])})`:`${i} && record::id(${i}) = $${be(t,e.right[0])}`;if(e.op==="NOT IN")return e.tunnel?`(!array::first(${i}) || record::id(array::first(${i})) != $${be(t,e.right[0])})`:`${i} && record::id(${i}) != $${be(t,e.right[0])}`;if(e.op==="CONTAINSANY")return e.tunnel?`$${be(t,e.right[0])} IN ${i}.map(|$i| record::id($i))`:`$${be(t,e.right[0])} IN (${i} ?: []).map(|$i| record::id($i))`;if(e.op==="CONTAINSNONE")return e.tunnel?`$${be(t,e.right[0])} NOT IN ${i}.map(|$i| record::id($i))`:`$${be(t,e.right[0])} NOT IN (${i} ?: []).map(|$i| record::id($i))`}return e.tunnel?`${i}.map(|$i| record::id($i)) ${e.op} [${e.right.map(o=>`$${be(t,o)}`).join(", ")}]`:`(${i} ?: []).map(|$i| record::id($i)) ${e.op} [${e.right.map(o=>`$${be(t,o)}`).join(", ")}]`}case "null":return e.tunnel?`array::len(${n}${te(e.left)}) = 0`:`${n}${te(e.left)} ${e.op} NONE`;case "and":{let i=e.filters.map(o=>{let s=Ve(o,t,r);return s?`(${s})`:void 0}).filter(o=>!!o);return i.length>0?i.join(" AND "):void 0}case "or":{let i=e.filters.map(o=>{let s=Ve(o,t,r);return s?`(${s})`:void 0}).filter(o=>!!o);return i.length>0?i.join(" OR "):void 0}case "not":{let i=Ve(e.filter,t,r);return i?`NOT(${i})`:void 0}case "nested":{let i=`${n}${te(e.path)}`;if(e.cardinality==="ONE")return Ve(e.filter,t,`${i}.`);let o=Ve(e.filter,t);return o?`${i}[WHERE ${o}]`:void 0}}},Ri=(e,t)=>{let r=e.map(n=>`${te(n.field)} ${n.desc?"DESC":"ASC"}`).join(", ");return X(`ORDER BY ${r}`,t)},X=(e,t)=>`${" ".repeat(t*2)}${e}`,be=(e,t)=>{let r=rr();for(;e[r]!==void 0;)r=rr();return e[r]=t,r},te=e=>{let t=e.replace(/⟩/g,"\\\u27E9");return /^[^a-zA-Z]/.test(t)||/[^a-zA-Z0-9_]/.test(t)?`\u27E8${e}\u27E9`:e};var Qi=(e,t)=>{let r=Oi(e.source,t),n=e.filter?ft(e.filter):void 0,{source:i,filter:o}=Di({source:e.source,filter:n,schema:t,thing:r});return {source:i,projection:Ni(e.projection,t,r),filter:o,cardinality:e.cardinality,limit:e.limit,offset:e.offset,sort:e.sort}},Di=e=>{let{source:t,filter:r,schema:n,thing:i}=e;if(t.type!=="table_scan")return {source:t,filter:r};let o=r?.type==="and"?r.filters:r?[r]:[];for(let s=0;s<o.length;s++){let a=o[s];if(a?.type!=="scalar"&&a?.type!=="list")continue;let l=_a(a,t);if(l)return {source:l,filter:yr(o.filter((d,c)=>c!==s))}}for(let s=0;s<o.length;s++){let a=o[s];if(a?.type!=="ref")continue;let l=Va(a,n,i);if(l)return {source:l,filter:yr(o.filter((d,c)=>c!==s))}}for(let s=0;s<o.length;s++){let a=o[s];if(a?.type!=="nested")continue;let l=za(a,n,i);if(l)return {source:l,filter:yr(o.filter((d,c)=>c!==s))}}return {source:t,filter:r?va(r,i):void 0}},_a=(e,t)=>{if(e.left==="id"){if(e.op==="="&&typeof e.right=="string")return {type:"record_pointer",thing:[t.thing[0],...t.thing.slice(1)],ids:[e.right]};if(e.op==="IN"&&Nt.array(Nt.string()).safeParse(e.right).success)return {type:"record_pointer",thing:[t.thing[0],...t.thing.slice(1)],ids:e.right}}},Va=(e,t,r)=>{let n=r.fields[e.left];if(!n)throw new Error(`Field ${e.left} not found in ${r.name}`);let i=Ai(n,t,r);if(!i)return;let{thing:o,path:s,cardinality:a}=i,l=gr(o,t);return {type:"subquery",source:{type:"record_pointer",thing:[o,...l.subTypes],ids:e.right},oppositePath:s,cardinality:a}},za=(e,t,r)=>{let n=r.fields[e.path];if(!n)throw new Error(`Field ${e.path} not found in ${r.name}`);let i=Ai(n,t,r);if(!i)return;let{thing:o,path:s,cardinality:a}=i,l=gr(o,t),d={type:"table_scan",thing:[o,...l.subTypes]},c=Di({source:d,filter:e.filter,schema:t,thing:l});return {type:"subquery",source:c.source,oppositePath:s,cardinality:a,filter:c.filter}},Ai=(e,t,r)=>{if(!(e.type!=="link"&&e.type!=="role")){if(e.type==="role"){let n=t[e.opposite.thing]?.fields?.[e.opposite.path];if(n?.type!=="link")throw new Error(`Role field ${e.name} in relation ${r.name} is not played by a link field`);if(n.target!=="relation")return}return e.opposite}},Ni=(e,t,r)=>({fields:e.fields.map(n=>Ua(n,t,r))}),Ua=(e,t,r)=>{if(e.type==="metadata"||e.type==="data"||e.type==="flex"||e.type==="reference")return e;let n=r.fields[e.path];if(!n)throw new Error(`Field ${e.path} not found in ${r.name}`);if(n.type!=="link"&&n.type!=="role")throw new Error(`Field ${e.path} is not a link or role field and can't be projected as nested reference`);let i=t[n.opposite.thing];if(!i)throw new Error(`Thing ${n.opposite.thing} not found in schema`);return {type:"nested_reference",path:e.path,projection:Ni(e.projection,t,i),ids:e.ids,filter:e.filter?ft(e.filter):void 0,alias:e.alias,cardinality:e.cardinality,limit:e.limit,offset:e.offset,sort:e.sort}},ft=e=>{if(e.type==="list"){if(e.right.length===0)return e.op==="IN"||e.op==="CONTAINSANY"?{type:"falsy"}:void 0;if(e.right.length===1)switch(e.op){case "IN":return {type:"scalar",op:"=",left:e.left,right:e.right[0]};case "NOT IN":return {type:"scalar",op:"!=",left:e.left,right:e.right[0]};case "CONTAINSALL":case "CONTAINSANY":return {type:"scalar",op:"CONTAINS",left:e.left,right:e.right[0]};case "CONTAINSNONE":return {type:"scalar",op:"CONTAINSNOT",left:e.left,right:e.right[0]}}}if(e.type==="ref"&&e.right.length===0)return e.op==="IN"||e.op==="CONTAINSALL"||e.op==="CONTAINSANY"?{type:"falsy"}:void 0;if(e.type==="and"||e.type==="or"){let t=e.filters.flatMap(i=>{let o=ft(i);return o===void 0?[]:o.type===e.type?o.filters:[o]});if(e.type==="and"&&t.some(i=>i.type==="falsy"))return {type:"falsy"};if(e.type==="or"&&(t=t.filter(i=>i.type!=="falsy")),t.length===0)return;if(t.length===1)return t[0];let n=t.map(i=>{if(i.type==="scalar")return {filter:i,score:It[i.op]??0};if(i.type==="list"){let o=It[i.op]??0;return {filter:i,score:o**i.right.length}}if(i.type==="ref"){let o=It[i.op]??0;return i.thing?{filter:i,score:o**(i.right.length*i.thing.length)}:{filter:i,score:o**i.right.length*.9}}return {filter:i,score:0}}).sort((i,o)=>o.score-i.score);return {type:e.type,filters:n.map(i=>i.filter)}}if(e.type==="not"){let t=ft(e.filter);if(t===void 0)return;if(t.type==="not")return t.filter;if(t.type==="scalar"){if(t.op==="=")return {type:"scalar",op:"!=",left:t.left,right:t.right};if(t.op==="!=")return {type:"scalar",op:"=",left:t.left,right:t.right}}return {type:"not",filter:t}}if(e.type==="nested"){let t=ft(e.filter);return t?{type:"nested",filter:t,path:e.path,cardinality:e.cardinality}:void 0}return e},It={"=":.9,">":.5,"<":.5,">=":.5,"<=":.5,IN:.5,"NOT IN":.5,CONTAINSALL:.3,CONTAINSANY:.4,CONTAINSNONE:.3},va=(e,t)=>{if(e.type==="and"){let r=Object.fromEntries(e.filters.map((i,o)=>{if(i.type!=="scalar")return;let s=It[i.op];if(s)return [i.left,{filter:i,index:o,score:s}]}).filter(i=>i!==void 0)),n=t.indexes.filter(i=>i.type!=="single").sort((i,o)=>o.fields.length-i.fields.length);if(n.length>0){let i=[];for(let s of n){let a=[];for(let l of s.fields){let d=r[l];if(!d||a.some(c=>c.index===d.index))break;a.push(d);}a.length>0&&i.push({filters:a,score:a.reduce((l,d)=>l+l*d.score,1)});}i.sort((s,a)=>a.score-s.score);let[o]=i;if(o&&o.score>1)return {type:"and",filters:[...o.filters.map(s=>s.filter),...e.filters.filter((s,a)=>!o.filters.some(l=>l.index===a))]}}}if(e.type==="and"||e.type==="or"){let n=e.filters.map((a,l)=>{if(a.type==="scalar"&&a.op==="="){let d=t.fields[a.left];if(Mi(d,t.indexes))return {filter:a,score:1,index:l}}else if(a.type==="list"&&a.op==="IN"){let d=t.fields[a.left];if(Mi(d,t.indexes)){let c=.5**(a.right.length-1);return {filter:a,score:c,index:l}}}return {filter:a,score:0,index:l}}).sort((a,l)=>l.score-a.score),[i]=n,o=i&&i.score!==0?i.filter:void 0,s=o?.type==="list"&&o.op==="IN"?{type:"or",filters:o.right.map(a=>({type:"scalar",op:"=",left:o.left,right:a}))}:o;return {type:e.type,filters:s?[s,...e.filters.filter((a,l)=>l!==i.index)]:e.filters}}return e},yr=e=>{if(e.length!==0)return e.length===1?e[0]:{type:"and",filters:e}},Mi=(e,t)=>e.type==="role"||e.type==="link"||t.some(r=>r.type==="single"&&r.field===e.name||r.type==="composite"&&r.fields.includes(e.name)),gr=(e,t)=>{let r=t[e];if(!r)throw new Error(`Thing ${e} not found in schema`);return r},Oi=(e,t)=>{if(e.type==="table_scan"||e.type==="record_pointer")return gr(e.thing[0],t);let r=Oi(e.source,t),n=r.fields[e.oppositePath];if(!n)throw new Error(`Field ${e.oppositePath} not found in ${r.name}`);if(n.type==="constant"||n.type==="computed"||n.type==="data"||n.type==="ref")throw new Error(`Invalid source: ${JSON.stringify(e)}`);let i=t[n.opposite.thing];if(!i)throw new Error(`Thing ${n.opposite.thing} not found in schema`);return i};var Wa=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ii=e=>e==null,ki=e=>Array.isArray(e)&&e.length===0,Ci=e=>{let{batch:t,results:r,schema:n,metadata:i,returnNulls:o}=e;return t.map((s,a)=>Ha({query:s,result:r[a],schema:n,metadata:i,returnNulls:o}))},Ha=e=>{let{query:t,result:r,schema:n,metadata:i,returnNulls:o}=e;if(!r)return r??null;let s=n[t.$thing];if(!s)throw new Error(`Thing ${t.$thing} not found in schema`);return Array.isArray(r)?r.map(a=>kt({query:t,result:a,thing:s,schema:n,metadata:i,returnNulls:o})):kt({query:t,result:r,thing:s,schema:n,metadata:i,returnNulls:o})},Ja=e=>{let{query:t,result:r,thing:n,schema:i,metadata:o,returnNulls:s}=e;return Array.isArray(r)?r.length===0?null:r.map(a=>kt({query:t,result:a,thing:n,schema:i,metadata:o,returnNulls:s})):kt({query:t,result:r,thing:n,schema:i,metadata:o,returnNulls:s})},kt=e=>{let{query:t,result:r,thing:n,schema:i,metadata:o,returnNulls:s}=e;if(!Wa(r))return null;let a={};o&&(a.$thing=r.$thing??null,a.$id=r.$id??null,a.$thingType=n.type);let l=t.$fields??Object.keys(n.fields);for(let d of l){let c=typeof d=="string"?d:d.$path,u=typeof d=="string"?d:d.$as??c;if(t.$excludedFields?.includes(c))continue;if(c==="$id"||c==="$thing"){a[u]=r[u]??null;continue}let p=n.fields[c];if(!p)throw new Error(`Field ${c} not found in ${n.name}`);if(p.type==="constant"){a[u]=p.value;continue}if(p.type==="computed"){a[u]=p.fn(r);continue}let f=r[u];if(p.type==="data"){if(!s&&Ii(f))continue;a[u]=f??null;continue}if(!s&&(Ii(f)||ki(f)))continue;if(typeof d=="string"||p.type==="ref"){a[u]=ki(f)?null:f??null;continue}let h=i[p.opposite.thing];a[u]=Ja({query:d,result:f,thing:h,schema:i,metadata:o,returnNulls:s});}return a};var qi=async e=>{let{client:t,queries:r,config:n,params:i}=e,o=`BEGIN TRANSACTION;
|
|
110
|
+
${r.join(`;
|
|
111
|
+
`)};
|
|
112
|
+
COMMIT TRANSACTION;`;return n.query?.debugger&&Z(`batchedQuery[${G}]`,JSON.stringify({batchedQuery:o})),await t.query(o,i)};var Pi=async(e,t,r,n)=>{if(e.length===0)return [];let i=e.map(u=>fi.parse(u)),s=i.map(u=>$i(u,t,!r.query?.noMetadata)).map(u=>Qi(u,t)),a={},l=s.map(u=>Ti(u,a)),d=await qi({client:n,queries:l,config:r,params:a});return Ci({batch:i,results:d,schema:t,metadata:!r.query?.noMetadata,returnNulls:!!r.query?.returnNulls})};var Ct=e=>{let{$filter:t,$var:r,$thing:n,schema:i,depth:o}=e,s=Za(t,ee(i,n)),{$not:a,...l}=s,d=[];if(Br(a)){let u=Er(a,r,n,i,o,true);d.push(...u);}else if(a!==void 0)throw new Error("$not must be a PositiveFilter object");let c=Er(l,r,n,i,o,false);return d.push(...c),d.join(`
|
|
113
|
+
`)},Er=(e,t,r,n,i,o)=>{let s=ee(n,r),a=[];for(let[l,d]of Object.entries(e)){if(l.startsWith("$")){let p=l.toLowerCase();if(p==="$and"||p==="$or"){let h=(isArray(d)?d:[d]).map(E=>{if(Br(E))return Er(E,t,r,n,i+1,o).join(`
|
|
114
|
+
`);throw new Error(`Invalid subfilter in ${p}: ${JSON.stringify(E)}`)}),$=h.join(p==="$and"?`
|
|
115
|
+
`:" } or { ");p==="$or"&&h.length>1?a.push(L(`{ ${$} };`,i)):a.push(L($,i));continue}continue}if(s.dataFields?.find(p=>p.dbPath===l||p.path===l)){let p=Ka(l,d,t,i,o);a.push(...p);continue}let u=s.linkFields?.find(p=>p.path===l);if(u){let p=Ya(u,d,t,n,i,o);a.push(...p);continue}if(s.thingType==="relation"){let p=s.roles[l];if(p){let f=Xa(p,d,t,r,n,i,o);a.push(...f);continue}}throw new Error(`"${r}" does not have property "${l}"`)}return a},Ka=(e,t,r,n,i)=>{let o=[];if(isObject(t)&&!isArray(t))for(let[s,a]of Object.entries(t)){let l=s.toLowerCase(),d="";switch(l){case "$eq":d=`$${r} has ${e} ${Te(a)};`;break;case "$ne":d=`not { $${r} has ${e} ${Te(a)}; };`;break;case "$in":{if(!isArray(a))throw new Error("Value for $in operator must be an array");let c=a.map(u=>`$${r} has ${e} ${Te(u)};`);d=mt(c),i&&(d=`not { ${d} };`);break}case "$nin":if(!isArray(a))throw new Error("Value for $nin operator must be an array");for(let c of a){let u=`not { $${r} has ${e} ${Te(c)}; };`;o.push(L(u,n));}continue;case "$exists":if(a===true)d=`$${r} has ${e} $${e}_${v4()};`;else if(a===false)d=`not { $${r} has ${e} $${e}_${v4()}; };`;else throw new Error(`Invalid value for $exists: ${a}`);break;default:throw new Error(`Unsupported operator "${s}" for data field "${e}"`)}i&&(d=`not { ${d} };`),o.push(L(d,n));}else if(isArray(t)){let s=t.map(l=>`$${r} has ${e} ${Te(l)};`),a=mt(s);a&&(i&&(a=`not { ${a} };`),o.push(L(a,n)));}else {let s=`$${r} has ${e} ${Te(t)};`;i&&(s=`not { ${s} };`),o.push(L(s,n));}return o},Ya=(e,t,r,n,i,o)=>{let s=[],[a]=e.oppositeLinkFieldsPlayedBy,d=ee(n,a.thing).idFields?.[0];if(!d)throw new Error(`"${a.thing}" does not have an id field`);let c=`${a.thing}_${v4()}`,u="";if(e.target==="relation")if(t===null)u=o?`(${e.plays}: $${r}) isa ${e.relation};`:`not { (${e.plays}: $${r}) isa ${e.relation}; };`;else if(isArray(t)){let p=t.map(f=>`(${e.plays}: $${r}) isa ${e.relation}, has ${d} ${Te(f)};`);u=mt(p),o&&(u=`not { ${u} };`);}else u=`(${e.plays}: $${r}) isa ${e.relation}, has ${d} ${Te(t)};`,o&&(u=`not { ${u} };`);else if(t===null)u=o?`$${c} isa ${a.thing}; (${e.plays}: $${r}, ${a.plays}: $${c}) isa ${e.relation};`:`not { $${c} isa ${a.thing}; (${e.plays}: $${r}, ${a.plays}: $${c}) isa ${e.relation}; };`;else if(isArray(t)){let p=t.map(f=>`$${c} isa ${a.thing}, has ${d} ${Te(f)}; (${e.plays}: $${r}, ${a.plays}: $${c}) isa ${e.relation};`);u=mt(p),o&&(u=`not { ${u} };`);}else u=`$${c} isa ${a.thing}, has ${d} ${Te(t)}; (${e.plays}: $${r}, ${a.plays}: $${c}) isa ${e.relation};`,o&&(u=`not { ${u} };`);return s.push(L(u,i)),s},Xa=(e,t,r,n,i,o,s)=>{let a=[],[l]=e.playedBy||[],c=ee(i,l.thing).idFields?.[0];if(!c)throw new Error(`"${l.thing}" does not have an id field`);let u=`${l.thing}_${v4()}`,p=v4(),f=`${r}_${p}`;a.push(L(`$${f} isa ${n};`,o));let h="";if(t===null)h=`$${f} (${l.plays}: ${u});`,s?a.push(L(h,o)):a.push(L(`not { ${h} };`,o));else if(isArray(t)){let $=t.map(E=>`$${u} isa ${l.thing}, has ${c} ${Te(E)}; $${f} (${l.plays}: $${u});`);h=mt($),s?a.push(L(`not { ${h} };`,o)):a.push(L(h,o));}else h=`$${u} isa ${l.thing}, has ${c} ${Te(t)}; $${f} (${l.plays}: $${u});`,s?a.push(L(`not { ${h} };`,o)):a.push(L(h,o));return a.push(L(`$${r} is $${f};`,o)),a},mt=e=>{if(e.length>1)return `{ ${e.join(" } or { ")} };`;if(e.length===1)return e[0];throw new Error("No alternatives provided to joinAlt")},Te=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("|")})$"`:Te(t)}throw new Error("Cannot serialize complex object values in filter")}throw new Error(`Unsupported value type: ${typeof e}`)},Za=(e,t)=>{let r={};if(t.dataFields?.forEach(s=>{s.path!==s.dbPath&&(r[s.path]=s.dbPath);}),Object.keys(r).length===0)return e;let{$not:n,...i}=e,o=xi(i,r);return n&&Br(n)&&(o.$not=xi(n,r)),o},xi=(e,t)=>{let r={};return Object.entries(e).forEach(([n,i])=>{let o=t[n]||n;r[o]=i;}),r},Br=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);var Fr="___",_i=async e=>{let{queries:t,schema:r}=e;return t.map(n=>Ga({query:n,schema:r}))},Ga=e=>{let{query:t,schema:r}=e,{$path:n,$thing:i,$filter:o,$fields:s,$sort:a,$offset:l,$limit:d,$id:c}=t;if(!n)throw new Error("Path is not defined");let u=[],p=t[oe];if(u.push("match"),u.push(`$${n} isa ${i};`),o||c){let $=wt(r,t),E={...o,...c?{[$]:c}:{}},m=Ct({$filter:E,$var:n,$thing:i,schema:r,depth:0});u.push(`
|
|
116
|
+
${m}`);}let f=Sr({schema:r,$thing:i,$var:n,$sort:a,depth:0});f&&u.push(f.match);let h=`M_${v4()}`;if(u.push(`?queryPath${h} = "${p}";`),u.push("fetch"),u.push(`?queryPath${h} as "queryPath";`),s){let $=s.filter(y=>y.$fieldType==="data");$&&$.length>0&&u.push(...br($,n,0));let E=s.filter(y=>y.$fieldType==="link");E&&E.length>0&&u.push(...wr(E,n,n,0,r));let m=s.filter(y=>y.$fieldType==="role");m&&m.length>0&&u.push(...Tr(m,n,n,0,r));}return f&&u.push(f.sort),typeof l=="number"&&u.push(`
|
|
117
|
+
offset ${l};`),typeof d=="number"&&u.push(`
|
|
118
|
+
limit ${d};`),u.join(`
|
|
119
|
+
`)},br=(e,t,r)=>{let n=[],i=[],o=[];for(let c=0;c<e.length;c++)e[c].$isVirtual||n.push(e[c].$dbPath),e[c][ue].contentType==="FLEX"&&o.push({path:e[c][ue].dbPath}),i.push(`{${e[c].$dbPath}:${e[c].$as}}`);let s=n.join(", "),l=`$metadata:{as:[${i.join(",")}]}`,d=[L(`$${t} as "${t}.${l}.$dataFields": ${s};`,r)];return o.length>0&&o.forEach(c=>{d.push(L(`"${c.path}.$multiVal": {match $${t} has ${c.path} $${c.path}; fetch $${c.path}: attribute;};`,r));}),d},Tr=(e,t,r,n,i)=>{let o=n+1,s=[];for(let a of e){let{$fields:l,$as:d,$justId:c,$idNotIncluded:u,$filterByUnique:p,$thing:f,$sort:h,$offset:$,$limit:E}=a,m=a[oe],y=`$metadata:{as:${d},justId:${c?"T":"F"},idNotIncluded:${u},filterByUnique:${p}}`;s.push(L(`"${r}.${y}.${a.$var}": {`,n)),s.push(L("match",o));let B=`${t}${Fr}${a.$var}`;if(s.push(L(`$${B} isa ${a.$thing};`,o)),s.push(L(`$${t} (${a.$var}: $${t}${Fr}${a.$var}) isa ${a.$intermediary};`,o)),a.$filter||a.$id){let T=wt(i,a),S=a.$id?{[T]:a.$id}:{},Q={...a.$filter,...S};s.push(Ct({$filter:Q,$var:B,$thing:a.$thing,schema:i,depth:o}));}let g=Sr({schema:i,$thing:f,$var:B,$sort:h,depth:o});if(g&&s.push(g.match),l){let T=`M_${v4()}`;s.push(L(`
|
|
120
|
+
?queryPath${T} = "${m}";`,o)),s.push(L("fetch",o)),s.push(L(`?queryPath${T} as "queryPath";`,o));let S=l?.filter(j=>j.$fieldType==="data");S&&S.length>0&&s.push(...br(S,B,o));let Q=l?.filter(j=>j.$fieldType==="link");Q&&Q.length>0&&s.push(...wr(Q,B,`${t}.${a.$var}`,o,i));let N=l?.filter(j=>j.$fieldType==="role");N&&N.length>0&&s.push(...Tr(N,B,`${t}.${a.$var}`,o,i));}g&&s.push(g.sort),typeof $=="number"&&s.push(L(`offset ${$};`,o)),typeof E=="number"&&s.push(L(`limit ${E};`,o)),s.push(L("};",n));}return s},wr=(e,t,r,n,i)=>{let o=n+1,s=[];for(let a of e){let{$fields:l,$as:d,$justId:c,$idNotIncluded:u,$filterByUnique:p,$playedBy:f,$thing:h,$sort:$,$offset:E,$limit:m}=a,y=a[oe],B=`$metadata:{as:${d},justId:${c?"T":"F"},idNotIncluded:${u},filterByUnique:${p}}`;s.push(L(`"${r}.${B}.${a.$var}": {`,n)),s.push(L("match",o));let g=`${t}${Fr}${a.$var}`;if(s.push(L(`$${g} isa ${a.$thing};`,o)),a.$filter||a.$id){let S=wt(i,a),Q=a.$id?{[S]:a.$id}:{},N={...a.$filter,...Q};s.push(Ct({$filter:N,$var:g,$thing:a.$thing,schema:i,depth:o}));}let T=Sr({schema:i,$thing:h,$var:g,$sort:$,depth:o});if(T&&s.push(T.match),a.$target==="role"?s.push(L(`$${t}_intermediary (${a.$plays}: $${t}, ${f.plays}: $${g}) isa ${a.$intermediary};`,o)):s.push(L(`$${g} (${a.$plays}: $${t});`,o)),l){let S=`M_${v4()}`;s.push(L(`?queryPath${S} = "${y}";`,o)),s.push(L("fetch",o)),s.push(L(`?queryPath${S} as "queryPath";`,o));let Q=l?.filter(K=>K.$fieldType==="data");Q&&Q.length>0&&s.push(...br(Q,g,o));let N=l?.filter(K=>K.$fieldType==="link");N&&N.length>0&&s.push(...wr(N,g,`${t}.${a.$var}`,o,i));let j=l?.filter(K=>K.$fieldType==="role");j&&j.length>0&&s.push(...Tr(j,g,`${t}.${a.$var}`,o,i));}T&&s.push(T.sort),typeof E=="number"&&s.push(L(`offset ${E};`,o)),typeof m=="number"&&s.push(L(`limit ${m};`,o)),s.push(L("};",n));}return s},el=e=>typeof e=="string"?{field:e,desc:false}:{...e,desc:e.desc??false},Sr=e=>{let{$var:t,$thing:r,schema:n,$sort:i,depth:o}=e,s=ee(n,r),a=[],l=[];if(i?.forEach(d=>{let c=el(d),u=s.dataFields?.find(h=>h.path===c.field);if(!u)throw new Error(`"${r}" does not have data field "${c.field}"`);let p=`${c.field}_${v4()}`;a.push(L("{",o)),a.push(L(`$${t} has ${u.dbPath} $${p}_1;`,o+1)),a.push(L("not {",o+1)),a.push(L(`$${t} has ${u.dbPath} $${p}_2;`,o+2)),a.push(L(`$${p}_2 < $${p}_1;`,o+2)),a.push(L("};",o+1)),a.push(L(`?${p}_ = $${p}_1;`,o+1)),a.push(L("} or {",o)),a.push(L(`not { $${t} has ${u.dbPath} $${p}_1; };`,o+1)),a.push(L(`?${p}_ = "~";`,o+1)),a.push(L("};",o)),a.push(L(`?${p} = ?${p}_;`,o));let f=c.desc?"desc":"asc";l.push(`?${p} ${f}`);}),a.length!==0)return {match:a.join(""),sort:L(`sort ${l.join(", ")};`,o)}};var zi=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((s,a)=>{let l=r[a],d=t[a];return rl(s,l,d,n,i)})},rl=(e,t,r,n,i)=>e.length===0?null:r.$filterByUnique?Vi(e[0],t,n,i):e.map(o=>Vi(o,t,n,i)),Vi=(e,t,r,n)=>{let{dataFields:i,currentSchema:o,linkFields:s,roleFields:a,schemaValue:l}=Rr(e,r),d=Lr(i,o,n),c=Qr(s,r,n),u=Mr(a,r,n),p=t?.$fields?.every(h=>!o?.idFields?.includes(typeof h=="string"?h:h.$path));return {...c,...u,...l,...!n.query?.noMetadata&&t.$id?{$id:Array.isArray(t.$id)?d.id:t.$id}:{},...p?Object.fromEntries(Object.entries(d).filter(([h])=>!o?.idFields?.includes(h))):d}},Rr=(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");if(i?.length>0)for(let f of i){let h=f.replace(/\.\$multiVal$/,""),$=e[f][0][h].attribute;e[n][h]=$;}let o=e[n],s=n.split(".")[n.split(".").length-2];if(o.$metaData=s,o.length===0)throw new Error("No dataFields");let a=o.type,l={$thing:a.label,$thingType:a.root,[oe]:e.queryPath.value},d={[`$${l.$thingType}`]:l.$thing},c=V(t,d),u=r.filter(f=>{let h=ge(f.split(".").pop());return !f.endsWith(".$dataFields")&&c.linkFields?.some($=>$.path===h)}).map(f=>{let h=ge(f.split(".").pop()),$=ge(c.linkFields?.find(E=>E.path===h));return {$linkFields:e[f],$key:h,$metaData:f.split(".")[f.split(".").length-2],$cardinality:$.cardinality}}),p=r.filter(f=>{let h=f.split(".").pop();return h&&!f.endsWith(".$dataFields")&&c.thingType==="relation"&&c.roles?.[h]}).map(f=>{let h=ge(f.split(".").pop());return {$roleFields:e[f],$key:h,$metaData:f.split(".")[f.split(".").length-2],$cardinality:c.roles[h].cardinality}});return {dataFields:o,schemaValue:l,currentSchema:c,linkFields:u,roleFields:p}},Lr=(e,t,r)=>{let{$metaData:n}=e,{as:i}=nl(n),o=Object.entries(e).filter(([s])=>s!=="type"&&!s.startsWith("$")).flatMap(([s,a])=>{let l=t.dataFields?.find(p=>p.path===s||p.dbPath===s),d=s==="id",c=Array.isArray(i)?i.find(p=>p[s])?.[s]:s,u;if(l?.cardinality==="ONE"){if(u=a[0]?a[0].value:r.query?.returnNulls?null:void 0,l.contentType==="DATE"||l.contentType==="FLEX"&&a[0].type.value_type==="datetime"?u=u&&`${u}Z`:l.contentType==="JSON"&&(u=u&&JSON.parse(u)),d)return [[c,u],["$id",u]].filter(([p,f])=>f!==void 0)}else if(l?.cardinality==="MANY"){if(!isArray(a))throw new Error("Typedb fetch has changed its format");if(a.length===0)return r.query?.returnNulls?[[c,null]]:[];l.contentType==="DATE"?u=a.map(p=>`${p.value}Z`):l.contentType==="FLEX"?u=a.map(p=>p.type.value_type==="datetime"?`${p.value}Z`:p.value):l.contentType==="JSON"?u=a.map(p=>p.value&&JSON.parse(p.value)):u=a.map(p=>p.value);}return [[c,u]].filter(([p,f])=>f!==void 0)});return Object.fromEntries([...o])},Mr=(e,t,r)=>{let n={};for(let i of e){let{$roleFields:o,$metaData:s,$cardinality:a}=i,{as:l,justId:d,idNotIncluded:c,filterByUnique:u}=Ui(s);if(l===null)continue;let p=o.map(f=>{let{dataFields:h,currentSchema:$,linkFields:E,roleFields:m,schemaValue:y}=Rr(f,t),B=Lr(h,$,r);if(d==="T")return B.id;let g=Qr(E,t,r),T=Mr(m,t,r),S={...B};if(c==="true"&&$?.idFields)for(let Q of $.idFields)delete S[Q];return {...S,...g,...T,...y}});p.length>0?n[l]=a==="MANY"&&u==="false"?p:p[0]:r.query?.returnNulls&&(n[l]=null);}return n},Qr=(e,t,r)=>{let n={};for(let i of e){let{$linkFields:o,$metaData:s,$cardinality:a}=i,{as:l,justId:d,idNotIncluded:c,filterByUnique:u}=Ui(s);if(l===null)continue;let p=o.map(f=>{let{dataFields:h,currentSchema:$,linkFields:E,roleFields:m,schemaValue:y}=Rr(f,t),B=Lr(h,$,r);if(d==="T")return B.id;let g=Qr(E,t,r),T=Mr(m,t,r),S={...B};if(c==="true")for(let Q of $.idFields??[])delete S[Q];return {...S,...g,...T,...y}});n[l]=p.length>0?a==="MANY"&&u==="false"?p:p[0]:r.query?.returnNulls?null:void 0;}return n},Ui=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),s=e.match(r),a=e.match(n),l=e.match(i);return {as:o?o[1]:null,justId:s?s[1]:null,idNotIncluded:a?a[1]:null,filterByUnique:l?l[1]:null}},nl=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,(s,a,l)=>/^{.*}$/.test(l)?`:${l}`:`:${a}"${l}"`),o=o.replace(/\[([^\]]+)\]/g,(s,a)=>`[${a.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 Pt=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 vi=async e=>{let{tqlRequest:t,dbHandles:r,config:n}=e,i=new TypeDBOptions;i.infer=true;let{session:o}=await Pt(r,n),s=await o.transaction(TransactionType.READ,i),[a,l]=await tryit(parallel)(t.length,t,async d=>await s.query.fetch(d).collect());if(a){await s.rollback();let d=a;throw new Error(`Error running TQL query: ${d.errors}`)}return await s.close(),l};var cl=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,Dr=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,dl=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,ul=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,at=x("error","error",P((e,t)=>({...e,error:t.error}))),pl=we("enrich",{enrich:U(async e=>(Z(`originalBQLQuery[${G}]`,JSON.stringify(e.bql.raw)),et(e.bql.raw,e.schema)),x("done","build",P(cl)),at),build:U(async e=>_i({queries:e.bql.queries??[],schema:e.schema}),x("done","run",P(dl)),at),run:U(async e=>vi({dbHandles:e.handles,tqlRequest:ge(e.tql.queries),config:e.config}),x("done","parse",P(ul)),at),parse:U(async e=>zi({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries??[],schema:e.schema,config:e.config,rawTqlRes:ge(e.tql.res)}),x("done","postHooks",P(Dr)),at),postHooks:U(async e=>At(e.schema,ge(e.bql.queries),ge(e.bql.res)),x("done","clean",P(Dr)),at),clean:U(async e=>Dt(e.config,ge(e.bql.res)),x("done","success",P(Dr)),at),success:$e(),error:$e()},e=>e),hl=async e=>new Promise((t,r)=>{Se(pl,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),Wi=async(e,t,r,n)=>hl({bql:{raw:e},tql:{},schema:t,config:r,handles:n,error:null});var fl=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,$l=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,Hi=x("error","error",P((e,t)=>({...e,error:t.error}))),ml=we("enrich",{enrich:U(async e=>(Z(`originalBQLQuery[${G}]`,JSON.stringify(e.bql.raw)),et(e.bql.raw,e.schema)),x("done","adapter",P(fl)),Hi),adapter:U(async e=>{let t={};e.bql.raw?.forEach((a,l)=>{let d=e.bql.raw[l],c="$thing"in a?a.$thing:"$entity"in a?a.$entity:"$relation"in a?a.$relation:void 0;if(!c)throw new Error(`No $thing found in query ${JSON.stringify(a,null,2)}`);let u=ee(e.schema,c),{id:p}=u.defaultDBConnector;if(u.db==="typeDB"){if(!t[p]){let h=e.handles.typeDB?.get(p)?.client;if(!h)throw new Error(`TypeDB client with id "${u.defaultDBConnector.id}" does not exist`);t[p]={db:"typeDB",client:h,rawBql:[],indices:[]};}}else if(u.db==="surrealDB"){if(!t[p]){let h=e.handles.surrealDB?.get(p)?.client;if(!h)throw new Error(`SurrealDB client with id "${u.defaultDBConnector.id}" does not exist`);t[p]={db:"surrealDB",client:h,rawBql:[],indices:[]};}}else throw new Error(`Unsupported DB "${u.db}"`);let f=t[p];f.rawBql.push(d),f.indices.push(l);});let r=Object.values(t),n=r.map(a=>{if(a.db==="typeDB")return Wi(a.rawBql,e.schema,e.config,e.handles);if(a.db==="surrealDB")return e.config.query?.legacySurrealDBAdapter?ui(a.rawBql,e.schema,e.config,a.client):Pi(a.rawBql,e.draftSchema,e.config,a.client);throw new Error(`Unsupported DB "${JSON.stringify(a,null,2)}"`)}),i=await Promise.all(n),o=r.flatMap((a,l)=>{let d=i[l];return a.indices.map((c,u)=>({index:c,result:d[u]}))});return o.sort((a,l)=>a.index<l.index?-1:a.index>l.index?1:0),o.map(({result:a})=>a)},x("done","success",P($l)),Hi),success:$e(),error:$e()},e=>e),yl=async e=>new Promise((t,r)=>{Se(ml,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),lt=async(e,t,r,n,i)=>yl({bql:{raw:e},schema:t,draftSchema:r,config:n,handles:i,error:null});var Xi=async(e,t,r,n,i)=>{let o=Array.isArray(e)?e:[e],s=o.map(d=>Ar(d,true)),l=(await lt(s,t,r,n,i)).bql.res;return o.map((d,c)=>{let u=ee(t,d.$thing);return Gi({mut:d,node:l[c],schema:t,thing:u})})},Zi=new Set(["$op","$bzId","$parentKey"]),El=new Set(["$relation","$entity","$id",...Zi]),Ar=(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(Zi.has(i)||El.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,...Ar(o[0],false)}):isObject(o)&&(r[i]={$path:i,...Ar(o,false)});}return n.$fields=Object.values(r),n},Gi=e=>{let{mut:t,node:r,schema:n,thing:i}=e,o=to(i),s=Fl(r);if(Array.isArray(t))return t.map(l=>{let d=s[l.$id];return d?Ji({mut:l,node:d,schema:n,thing:i,...o}):l});let a=s[t.$id];return Ji({mut:t,node:a,schema:n,thing:i,...o})},Ji=e=>{let{mut:t,node:r,schema:n,thing:i,dataFieldMap:o,linkFieldMap:s,roleFieldMap:a}=e,{$fields:l,...d}=t;if(!r)return d;let c=eo({$fields:t.$fields,node:r,schema:n,thing:i,dataFieldMap:o,linkFieldMap:s,roleFieldMap:a}),u={...d,[Ze]:c};for(let p in t){if(p.startsWith("$"))continue;let f=t[p];if(o[p]||!f||typeof f!="object"){u[p]=f;continue}let $=s[p]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||a[p]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${i.name}" does not have field "${p}"`);let E=ee(n,$);u[p]=Gi({mut:f,schema:n,node:r[p],thing:E});}return u},eo=e=>{let{$fields:t,node:r,schema:n,thing:i,dataFieldMap:o,linkFieldMap:s,roleFieldMap:a}=e,l=t||Bl(i),d={$id:r.$id};return l.forEach(c=>{let u=typeof c!="string",p=u?c.$path:c,f=r[p];if(o[p]){d[p]=f;return}let $=s[p]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||a[p]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${i.name}" does not have field "${p}"`);if(!u){f&&(d[p]=Array.isArray(f)?f.map(Ki):Ki(f));return}let E=ee(n,$),m=to(E);d[p]=Array.isArray(f)?f.map(y=>Yi({...m,$fields:c.$fields,value:y,schema:n,thing:E})):Yi({...m,$fields:c.$fields,value:f,schema:n,thing:E});}),d},Bl=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},Ki=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},Yi=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 eo({...e,node:t})},to=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}},Fl=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 ro=(e,t)=>{let r={things:[],edges:[],arcs:[],references:[]},n=(s,a)=>{if(!s?.$thing)return;let{$op:l,$bzId:d,$tempId:c}=s,u=t.relations[s.$thing]||t.entities[s.$thing];if(!u)throw new Error(`[Internal] No schema found for ${s.$thing}`);let p=a?.bzId?a:{bzId:"",edgeField:"root"},{usedDataFields:f,usedLinkFields:h,usedRoleFields:$,usedRefFields:E}=ye(u,s);if(["create","update","delete","link","unlink","match","replace"].includes(l)){let y={...me(s,B=>![...$,...h,...E].includes(B)),...l==="link"||l==="unlink"||l==="replace"||l==="update"&&f.length===0?{$op:"match"}:{},...l==="link"||l==="replace"?{}:{[Ft]:p}};r.things.push(y);}let m={link:["link","create"],unlink:["unlink","delete"],replace:["replace"]};if($){let y=me(s,B=>isSymbol(B)||B.startsWith("$"));for(let B of $){if(isArray(s[B]))for(let T of s[B])n(T,{bzId:d,edgeField:B,tempId:c});else n(s[B],{bzId:d,edgeField:B,tempId:c});let g=(isArray(s[B])?s[B]:[s[B]]).filter(Boolean);for(let[T,S]of Object.entries(m)){let Q=g.filter(N=>S.includes(N.$op)).map(N=>N.$bzId);Q.length>0&&r.edges.push({...y,[B]:Q,$op:T});}}}if(h)for(let y of h){if(isArray(s[y]))for(let T of s[y])n(T,{bzId:d,edgeField:y,tempId:c});else n(s[y],{bzId:d,edgeField:y,tempId:c});let B=u.linkFields?.find(T=>T.path===y),g=isArray(s[y])?s[y]:[s[y]];if(B.target==="relation")for(let[T,S]of Object.entries(m)){let Q=g.filter(N=>S.includes(N.$op));for(let N of Q){let j=me(N,K=>isSymbol(K)||K.startsWith("$"));r.edges.push({...j,[B.plays]:d,$op:T});}}if(B.target==="role"){let T={create:["link","create"],delete:["unlink","delete"],replace:["replace"]};for(let[S,Q]of Object.entries(T)){let N=g.filter(j=>Q.includes(j.$op));if(N.length!==0)for(let j of N){let K={$thing:B.relation,$thingType:"relation",$bzId:`arc_${j.$bzId}`,[B.plays]:d,[B.oppositeLinkFieldsPlayedBy[0].plays]:j.$bzId,$op:S};r.arcs.push(K);}}}}if(E)for(let y of E){if(isArray(s[y]))for(let S of s[y])n(S,{bzId:d,edgeField:y,tempId:c});else n(s[y],{bzId:d,edgeField:y,tempId:c});let B=(isArray(s[y])?s[y]:[s[y]]).filter(S=>S!=null),g=me(s,S=>isSymbol(S)||S.startsWith("$")),T=B.map(S=>S.$op?`$\u27E8${S.$bzId}\u27E9`:Xe(S,"FLEX"));T.length>0&&r.references.push({...g,[y]:T,$op:"replace"});}},i=Array.isArray(e)?e:[e];for(let s of i)n(s);let o=[...r.edges].sort((s,a)=>{let l=["unlink","link"];return l.indexOf(s.$op)-l.indexOf(a.$op)});return {...r,edges:o}};var so=async(e,t)=>{let r=c=>{let u=[],p=[],f=m=>{if(m.$id)return m.$id;let y=V(t,m),{idFields:B}=y;if(!B)throw new Error(`no idFields: ${JSON.stringify(m)}`);let[g]=B;if(!g)throw new Error(`no idField: ${JSON.stringify(m)}`);let T=y.dataFields?.find(N=>N.path===g),S=tt({currentThing:m,fieldSchema:T,mandatoryDependencies:true}),Q=m[g]||m.$id||S;if(!Q)throw new Error(`no idValue: ${JSON.stringify(m)}`);return Q},h=m=>{if(m.$op==="create"){let y=f(m);if(u.find(B=>B.$id===y&&B.$op==="create"))throw new Error(`Duplicate id ${y} for node ${JSON.stringify(m)}`);u.push({...m,$id:y});return}m.$tempId&&m.$op==="match"||u.push(m);},$=m=>{if(m.$op==="create"){let y=f(m);if(u.find(B=>B.$id===y&&B.$op==="create"))throw new Error(`Duplicate id ${y} for edge ${JSON.stringify(m)}`);p.push({...m,$id:y});return}p.push(m);};return traverse(c,({value:m,parent:y,meta:B})=>{if(!isObject(m))return;let g=m;if(!B.nodePath?.includes(".$filter")&&g.$thing){if(!g.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(g)}`);if(!g.$bzId)throw new Error(`[internal error] BzId not found ${JSON.stringify(g)}`);let T=V(t,g),{dataFields:S,roleFields:Q,linkFields:N,refFields:j,usedFields:K}=ye(T,g),ce=()=>{if(g.$op==="create"||g.$op==="delete")return g.$op;if(g.$op==="update"){let D=K.filter(w=>S?.includes(w)),Y=K.filter(w=>Q?.includes(w)),b=K.filter(w=>N?.includes(w)),F=K.filter(w=>j?.includes(w));if(D.length>0)return "update";if(Y.length>0||b.length>0||F.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(g)}`)}return "match"},se={...g.$id&&{$id:g.$id},...g.$tempId&&{$tempId:g.$tempId},...g.$filter&&{$filter:g.$filter},$thing:g.$thing,...g.$thingType&&{$thingType:g.$thingType},...shake(pick(g,S||[""])),$op:ce(),$bzId:g.$bzId};h(se);let I=g[Ae];if(I?.[J].fieldType==="linkField"){if((g.$op==="link"||g.$op==="unlink")&&(g.$id||g.$filter)){if(g.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");u.push({...g,$op:"match"});}let D=I.$things.includes(g.$thing),Y=D?g.$bzId:`LT_${v4()}`,F=Mn(c,y,B).$bzId;if(!F)throw new Error("No parent id found");let w=()=>g.$op==="delete"?D?"match":"delete":g.$op==="unlink"?D?"unlink":"delete":g.$op==="link"||g.$op==="create"?D?"link":"create":g.$op==="replace"?"replace":"match",M=V(t,{$thing:I.relation,$thingType:"relation"});if(!Object.keys(M.roles).includes(I.plays))throw new Error(`[Wrong format] Field ${I.plays} is not a role of relation ${I.relation}`);let A={$bzId:Y,$thing:D?g.$thing:I.relation,$thingType:"relation",...g.$tempId?{$tempId:g.$tempId}:{},$op:w(),...D?{}:{[I.path]:g.$bzId},[I.plays]:F,[Ae]:I,[Ue]:"linkField"};$(A),(g.$op==="unlink"||w()==="unlink")&&D&&$({$thing:I.relation,$thingType:"relation",$bzId:Y,$op:"match",[I.plays]:F,[Ae]:I,[Ue]:"linkField"});}if(g.$thingType==="relation"){let D=me(g,(F,w)=>Q.includes(F)),Y=mapEntries(D,(F,w)=>isArray(w)?[F,w]:isObject(w)?[F,w.$bzId]:[F,w]),b=me(m,(F,w)=>F.startsWith("$")||F.startsWith("Symbol"));if(Object.keys(D).filter(F=>!F.startsWith("$")).length>0){if(g.$op==="create"||g.$op==="delete"){let F=()=>{if(g.$op==="create")return "link";if(g.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},w=V(t,g).roles,M=mapEntries(Y,(A,k)=>{let z=w[A]?.cardinality;if(!z)throw new Error(`Role ${A} not found in schema`);return Array.isArray(k)?z==="ONE"?k.length>1?[A,k.map(C=>C.$bzId||C)]:[A,k[0].$bzId||k[0]]:[A,k.map(C=>C.$bzId||C)]:[A,k.$bzId||k]}),R={...b,$thing:g.$thing,$thingType:"relation",$op:F(),...M,$bzId:g.$bzId,[Ue]:"roleField"};$(R);return}if(g.$op==="match"||g.$op==="update"&&Object.keys(D).length>0){Object.entries(D).forEach(([w,M])=>{let R=isArray(M)?M:[M],A=k=>k==="create"||k==="replace"?"link":k;R.forEach(k=>{if(!k)return;let z=A(k.$op);if(z==="replace")throw new Error("Not supported yet: replace on roleFields");let C={...b,$thing:g.$thing,$thingType:"relation",$op:z==="delete"?"unlink":z,[w]:k.$bzId,$bzId:g.$bzId,[Ue]:"roleField"};$(C);});});}}}}}),[u,p]},[n,i]=r(e),o=n.reduce((c,u)=>{if(!u.$bzId)return [...c,u];let p=c.findIndex(f=>f.$bzId===u.$bzId);if(p===-1)return [...c,u];if(c[p].$op==="create"&&u.$op==="match")return c;if(c[p].$op==="match"&&(u.$op==="create"||u.$op==="match"))return [...c.slice(0,p),u,...c.slice(p+1)];if(c[p].$op==="update"&&u.$op==="update")return [...c.slice(0,p),{...c[p],...u},...c.slice(p+1)];if(c[p].$op==="update"&&u.$op==="match"||c[p].$op==="match"&&u.$op==="update")return [...c.slice(0,p),{...c[p],...u,$op:"update"},...c.slice(p+1)];if(c[p].$op==="delete"&&u.$op==="delete"){if(JSON.stringify(c[p].$filter)===JSON.stringify(u.$filter))return c;throw new Error(`[Wrong format] Can't delete the same thing with different filters. Existing: ${c[p].$filter}. Current: ${u.$filter}`)}throw new Error(`[Wrong format] Wrong operation combination for $tempId/$id "${u.$tempId||u.$id}". Existing: ${c[p].$op}. Current: ${u.$op}`)},[]),s=i.reduce((c,u)=>{let p=c.find(f=>(f.$id&&f.$id===u.$id||f.$bzId&&f.$bzId===u.$bzId)&&f.$thing===u.$thing&&f.$op===u.$op);if(p){let f={...p};return Object.keys(u).forEach($=>{if(typeof $=="symbol"||$.startsWith("$"))return;let E=p[$],m=u[$];Array.isArray(E)&&Array.isArray(m)?f[$]=Array.from(new Set([...E,...m])):!Array.isArray(E)&&Array.isArray(m)?E!==void 0?f[$]=Array.from(new Set([E,...m])):f[$]=m:Array.isArray(E)&&!Array.isArray(m)?m!==void 0&&(f[$]=Array.from(new Set([...E,m]))):E!==null&&m!==null&&E!==void 0&&m!==void 0?f[$]=Array.from(new Set([E,m])):E==null&&(f[$]=m);}),[...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)&&s.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(Qn(c))}`)}});let a=[...o,...s],l=new Set(a.filter(c=>c.$tempId).map(c=>c.$tempId)),d=Array.from(l).filter(c=>!a.some(u=>u.$tempId===c&&u.$op==="create"));if(d.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${d.join(", ")}`);return {mergedThings:o,mergedEdges:s}};var Or="___",Ll=Symbol.for("grandChildOfCreate"),ao=async(e,t,r,n,i)=>{let o=["$eq","$ne","$in","$nin","$gt","$gte","$lt","$lte","$exists"],s=(b,F)=>Object.keys(b).filter(w=>!w.startsWith("$")&&!o.includes(w)&&b[w]!==void 0?F?!V(t,b).dataFields?.find(R=>R.path===w):true:false);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(n.mutation?.preQuery===false)return;let a=[];if(traverse(e,({parent:b,key:F,value:w})=>{b&&F&&!F.includes("$")&&!o.includes(F)&&isObject(b)?(Array.isArray(b[F])?b[F]:[b[F]]).forEach(R=>{if(isObject(R)){if(b.$op!=="create")a.includes(R.$op)||a.push(R.$op);else if(R.$op==="delete"||R.$op==="unlink")throw new Error(`Cannot ${R.$op} under a create`)}}):!b&&isObject(w)&&(a.includes(w.$op)||a.push(w.$op));}),!a.includes("delete")&&!a.includes("unlink")&&!a.includes("replace")&&!a.includes("update")&&!a.includes("link"))return;let d=(b=>{let F=(w,M)=>{let R=[],A={},k=["$op","$bzId","$parentKey"],z=["$relation","$entity","$id",...k];for(let C in w)if(!k.includes(C)&&!(z.includes(C)&&!M))if(!C.includes("$")&&(isObject(w[C])||Array.isArray(w[C]))){let ae=Ml(w[C]);if(Array.isArray(ae)&&ae.length>0)ae.forEach(Qe=>{let De={$path:C,...F(Qe),...Qe.$filter&&{$as:Qe.$bzId}};R.find(re=>re.$path===De.$path&&!re.$filter)||(R=[...R,De]);});else {let Qe={$path:C,...F(ae),...!ae.$filter&&{$as:ae.$bzId}};R=[...R,Qe];}}else A[C]=w[C];return {...A,$fields:R}};return b.map(w=>F(w,true))})(Array.isArray(e)?e:[e]),u=(await lt(d,t,r,{...n,query:{...n.query,returnNulls:true}},i)).bql.res,p=(b,F)=>{let w=b.$id||b.id||b.$bzId;if(b.$objectPath){let{$objectPath:M}=b,R=M?.beforePath||"root",A=Array.isArray(M.ids)?`[${M.ids}]`:M.ids;return {beforePath:`${R}.${A}___${M.key}`,ids:w,key:F}}return {beforePath:"root",ids:w,key:F}},f=(b,F)=>{let w=b?.beforePath||"root";if(typeof w!="string")throw new Error("[PQ]objectPathToKey: root is not a string");let M=(Array.isArray(b?.ids)?`[${b?.ids}]`:b?.ids);return `${w}.${M}___${b?.key}`},h=b=>{if(b.includes("[")&&b.includes("]")){let[F,w,M]=b.split(/[[\]]/);return w.split(",").map(A=>`${F}${A}${M}`)}return [b]},$={};(b=>produce(b,F=>traverse(F,({key:w,parent:M})=>{if(M&&w&&M.$id&&!w.includes("$")){let R=p(M,w),A=f(R);if(Array.isArray(M[w])){let k=[];M[w].forEach(z=>{isObject(z)?(z.$objectPath=R,k.push(z.$id.toString())):z&&k.push(z.toString());}),$[A]={$objectPath:R,$ids:k};}else {let k=M[w];isObject(k)?($[A]={$objectPath:R,$ids:[k.$id.toString()]},k.$objectPath=R):k?$[A]={$objectPath:R,$ids:[k.toString()]}:k===null&&($[A]=null);}}})))(u||{});let m=b=>produce(b,F=>traverse(F,({key:w,value:M,parent:R})=>{R&&w&&!w.includes("$")&&(Array.isArray(M)||isObject(M))&&!Array.isArray(R)&&(Array.isArray(R[w])?R[w].forEach(A=>{typeof A!="string"&&(A.$objectPath=p(R,w),A.$parentIsCreate=R.$op==="create",A[Ll]=R.$parentIsCreate||R[Symbol.for("grandChildOfCreate")]);}):isObject(R[w])&&(R[w].$parentIsCreate=R.$op==="create",R[w][Symbol.for("grandChildOfCreate")]=R.$parentIsCreate||R[Symbol.for("grandChildOfCreate")],R[w].$objectPath=p(R,w)));})),y=m(e),B=b=>{let F=[];return b.forEach(M=>{if(!M.$id&&!M.id&&!M.$tempId)if(M.$filter){let R=f({...M.$objectPath,key:M.$bzId}),A=$[R];A&&(Array.isArray(A.$ids)?A.$ids:[A.$ids]).forEach(z=>{let C={...M,$id:z,$bzId:`T4_${v4()}`,$filterBzId:M.$bzId};F.push(C);});}else {let R=f(M.$objectPath),A=$[R];A?A?.$ids?.forEach(k=>{let z={...M,$id:k,$bzId:`T4_${v4()}`};F.push(z);}):F.push(M);}else F.push(M);}),F.map(M=>{let R={...M};return s(R,true).forEach(A=>{let k=Array.isArray(R[A])?R[A]:[R[A]],z=B(k);R[A]=z;}),R})},g=B(Array.isArray(y)?y:[y]),T=m(g),Q=(b=>{let F=w=>{let M=re=>{let ie=[],H=[],_=[];return re.forEach(v=>{let fe=s(v,true);if(fe.length>0){let q=false;fe.forEach(W=>{(Array.isArray(v[W])?v[W]:[v[W]]).filter(de=>!de.$id&&!de.id&&typeof v=="object").length&&(q=true);}),q?ie.push(v):H.push(v);}else v.$id?_.push({...v,$bzId:v.$tempId||v.$bzId}):_.push({...v,$bzId:v.$tempId||`PQ1_${v4()}`});}),{operationWithMultiples:ie,operationWithoutMultiples:H,otherOps:_}},{operationWithMultiples:R,operationWithoutMultiples:A,otherOps:k}=M(w),z=re=>{let H=(()=>{let W={};for(let Ee in re){let ne=V(t,re);!Ee.startsWith("$")&&ne.dataFields?.find(de=>de.path===Ee)&&(W[Ee]=re[Ee]);}return W})(),_=Object.keys(re),v=s(re,true),fe=[],q=(W,Ee)=>{if(W===v.length){let de={...Ee};_.forEach(Be=>{Be.startsWith("$")&&(de[Be]=re[Be]);}),fe.push({...de,...H});return}let ne={...Ee,[v[W]]:re[v[W]],...Pe(Ee),...H};q(W+1,ne),q(W+1,Ee);};return q(0,{...Pe(re)}),fe},C=[];return R.forEach(re=>{let ie=z(re),H=[];ie.forEach(_=>{let v=s(_,true);if(_.$op==="create")H.push(_);else if(_.$id){let fe=f(_.$objectPath),q=[];if(v.forEach(W=>{let Ee=`${fe.includes("undefined")?"root":fe}.${_.$id}${Or}${W}`,ne=$[Ee];_[W].filter(Be=>Be.$op==="unlink"||Be.$op==="delete"||Be.$op==="update").length>0?ne?.$ids&&q.push({key:W,ids:ne.$ids}):q.push({key:W,ids:[""]});}),q.length===v.length&&!H.find(W=>W.$id===_.$id))H.push(_);else {let W={..._,$bzId:_.$tempId||`T4_${v4()}`};v.forEach(ne=>{let de=_[ne].filter(Be=>Be.$id);de.length>0?W[ne]=de:W[ne]=void 0;}),s(W,true).length>0&&H.push(W);}}else if(_.$objectPath){let fe=f(_.$objectPath),q=$[fe]?.$ids||[];q.forEach(W=>{let Ee=[];v.forEach(ne=>{let de=`${fe}.${W}${Or}${ne}`,Be=$[de];Be&&Ee.push({key:ne,ids:Be.$ids});}),v.length===0?q.filter(de=>!H.find(Be=>Be.$id===de)).forEach(de=>{H.push({..._,$id:de,$bzId:_.$tempId||`PQT2_${v4()}`});}):Ee.length===v.length&&!H.find(ne=>ne.$id===W)&&(v.forEach(ne=>{let de=`${f(_.$objectPath)}.${W}${Or}${ne}`,Be=$[de]?.$ids||[],Lo=_[ne].find(Ye=>!Ye.$id),xr=[...Be.map(Ye=>({...Lo,$id:Ye,$objectPath:{beforePath:_.$objectPath.beforePath,ids:Ye,key:ne}})),..._[ne].filter(Ye=>Ye.$id)];xr.length>0&&(_[ne]=xr);}),H.push({..._,$id:W,$bzId:_.$tempId||`PQ3_${v4()}`}));});}else H.push(_);}),H.forEach(_=>{C.push(_);});}),[...C,...A,...k].filter(re=>s(re).length>0?true:re.$op!=="update").map(re=>{let ie={...re};return s(ie,true).forEach(H=>{let _=Array.isArray(ie[H])?ie[H]:[ie[H]],v=F(_);ie[H]=v;}),ie})};return F(b)})(Array.isArray(T)?T:[T]),N=b=>b.map(F=>{let w=s(F,true),M={...F};return w.forEach(R=>{let A=Array.isArray(F[R])?F[R]:[F[R]],k=[],z=[],C=[],ae={},Qe=tr(t,F,R);A.filter(q=>q).forEach(q=>{q.$op==="replace"&&q.$id?(ae=q,Array.isArray(q.$id)?z=[...z,...q.$id]:z.push(q.$id)):q.$op==="create"&&Qe==="ONE"&&q.id?(ae=q,Array.isArray(q.id)?C=[...z,...q.id]:C.push(q.id)):k.push(q);});let De=f(ae.$objectPath),ie=h(De).map(q=>$[q]),H=[];ie.filter(q=>q!=null).forEach(q=>{H=[...H,...q?.$ids||[]];});let _=H.filter(q=>!z.includes(q)),v=z.filter(q=>!H.includes(q)),fe=Pe(ae);_.length>0&&k.push({...ae,$op:"unlink",$id:_,$bzId:ae.$tempId||`T4_${v4()}`,id:void 0,...fe}),v.length>0&&v.forEach(q=>{k.push({...ae,$op:"link",$id:q,$bzId:ae.$tempId||`T5_${v4()}`,...fe});}),C.length>0&&C.forEach(q=>{k.push({...ae,$op:"create",id:q,$bzId:ae.$tempId||`T6_${v4()}`,...fe});}),M[R]=N(k);}),M}),j=m(N(m(Q)));(b=>produce(b,F=>traverse(F,w=>{let{key:M,value:R,parent:A,meta:k}=w;M&&A&&!M?.includes("$")&&M!=="$filter"&&!k.nodePath?.includes(".$filter.")&&(Array.isArray(R)||isObject(R))&&!Array.isArray(A)&&(Array.isArray(R)?R:[R]).forEach(C=>{let ae=C.$filter?{...C.$objectPath,key:C.$filterBzId}:C.$objectPath,Qe=f(ae),De=$[Qe],re=(_,v)=>_.every(fe=>v.includes(fe)),ie=C.$id?Array.isArray(C.$id)?re(C.$id,De?.$ids?De.$ids:[]):De?.$ids?.includes(C.$id):De,H=tr(t,A,C.$objectPath.key);if(C.$op==="link"&&ie&&H==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${f(C.$objectPath)}" because it is already occupied.`);if(C.$op)switch(C.$op){case "delete":if(!ie&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${C.$id}" because it is not linked to $id:"${A.$id}"`);break;case "update":if(!ie&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${C.$id}" because it is not linked to $id:"${A.$id}"`);break;case "unlink":if(!ie&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${C.$id}" because it is not linked to $id:"${A.$id}"`);break;case "link":if(ie)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${C.$id}" because it is already linked to $id:"${A.$id}"`);break;}});})))(j);let se=(b=>produce(b,F=>traverse(F,w=>{let{value:M,meta:R}=w;isObject(M)&&(M[Symbol.for("path")]=R.nodePath,M.$objectPath=void 0,M.$parentIsCreate=void 0);})))(j);return [...Array.isArray(se)?se:[se]].sort((b,F)=>b.$op==="create"&&F.$op!=="create"?-1:b.$op!=="create"&&F.$op==="create"?1:0)},Ml=e=>isObject(e)&&!isArray(e)&&"$eq"in e?e.$eq:e;var lo=(e,t)=>produce(e,n=>jt(t,n)),jt=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){for(let i of t)jt(e,i,r);return}let n=ee(e,r||t.$entity||t.$relation||t.$thing);for(let[i]of Object.entries(t))i.startsWith("$")||i.startsWith("%")||Dl(e,t,i,n);},Dl=(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 s=n.linkFields?.find(l=>l.path===r);if(s){let l=s.oppositeLinkFieldsPlayedBy[0]?.thing;jt(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[d]=l.playedBy||[];if(!d)throw new Error(`Role ${l.path} in ${n} is not played by anything`);jt(e,i,d.thing);}};var co=async(e,t)=>{let r=a=>{let{$filter:l,$thing:d,$bzId:c,$op:u,$id:p,$tempId:f}=a,h=ee(t,d),{usedDataFields:$}=ye(h,a),{idFields:E}=h,m=p||a[E[0]],y=(isArray(d)?d:[d]).map(le),B=me(a,b=>b.startsWith("$")),g=me(a,b=>!b.startsWith("$")),T=JSON.stringify(g),S=Object.entries(B).map(([b,F])=>b==="$tempId"?`'$tempId': '_:${F}'`:`'${b}': '${F}'`).join(","),Q=a[Ft],N=$.filter(b=>!E.includes(b)).map(b=>{let F=h.dataFields?.find(M=>M.path===b||M.dbPath===b);if(!F)throw new Error(`Data field schema not found for ${b}`);let w=a[b];return w===null?`${b} = NONE`:`${b} = ${Xe(w,F.contentType)}`}).filter(Boolean),j=`$\u27E8${f||c}\u27E9`,K=Q?.bzId?`array::flatten($\u27E8${Q.bzId}\u27E9.\u27E8${Q.edgeField}\u27E9 || []).filter(|$v| $v != NONE).len`:m?isArray(m)?y.flatMap(b=>m.map(F=>`${b}:\u27E8${F}\u27E9`)).join(", "):y.map(b=>`${b}:\u27E8${m}\u27E9`).join(", "):true,ce=(()=>{if(Q?.bzId){let b=`array::flatten($\u27E8${Q.bzId}\u27E9.\u27E8${Q.edgeField}\u27E9 || []).filter(|$v| $v != NONE)`;return m?isArray(m)?`${b}[? $this.id() IN [${m.map(F=>`'${F}'`).join(", ")}] ]`:`${b}[? $this.id() IN ['${m}'] ]`:b}return m?isArray(m)?y.flatMap(b=>m.map(F=>`${b}:\u27E8${F}\u27E9`)).join(", "):y.map(b=>`${b}:\u27E8${m}\u27E9`).join(", "):y.join(", ")})(),se=l?`WHERE ${Fe(Re(l,d,t))}`:"",I=N.length>0?`SET ${N.join(", ")}`:"",D=`VALUE (CREATE ONLY Delta SET input = ${T}, meta = {${S}, "$sid": $parent.id, "$id": record::id($parent.id)}, after = $after, before = $before RETURN VALUE $parent.id )`,Y="BEFORE";if(["link","unlink","replace"].includes(u))throw new Error("Edge ops don't belong to things");if(a.$op==="match")return f?"":`LET ${j} = (SELECT VALUE id FROM ${ce} ${se});`;if(a.$op==="create"){if(isArray(m))throw new Error("Cannot create multiple things at once");let b=le(d);return `LET ${j} = (CREATE ONLY ${b}:\u27E8${m}\u27E9 ${I} RETURN ${D});`}if(a.$op==="update")return `LET ${j} = IF (${K}) THEN (UPDATE ${ce} ${I} ${se} RETURN ${D}) END;`;if(a.$op==="delete")return `LET ${j} = IF (${K}) THEN (DELETE ${ce} ${se} RETURN ${Y}) END;`;throw new Error(`Unsupported operation ${a.$op}`)},n=a=>{let{$thing:l,$bzId:d,$op:c,$tempId:u}=a,p=ee(t,l),{usedRoleFields:f}=ye(p,a),h=`$\u27E8${u||d}\u27E9`,$="roles"in p?f.flatMap(y=>{let B=p.roles[y];if(!B)throw new Error(`Role field schema not found for ${y}`);let{cardinality:g}=B,T=isArray(a[y])?a[y].map(S=>`$\u27E8${S}\u27E9`):[`$\u27E8${a[y]}\u27E9`];if(g==="ONE"){if(T.length>1){let S=`array::filter(array::flatten([${T}]), |$v| !!$v)`;switch(c){case "link":case "replace":return `${y} = ((array::len(${S})==1) && ${S}[0]) || ${S}`;case "unlink":return `${y} = NONE`;default:throw new Error(`Unsupported operation ${c} for ONE cardinality`)}}switch(c){case "link":case "replace":return `${y} = ((type::is::array(${T[0]}) && array::len(${T[0]})==1) && ${T[0]}[0]) || ${T[0]}`;case "unlink":return `${y} = NONE`;default:throw new Error(`Unsupported operation ${c} for ONE cardinality`)}}if(g==="MANY"){let S=`array::flatten([${T}])`;switch(c){case "link":return `${y} += ${S}`;case "unlink":return `${y} -= ${S}`;case "replace":return `${y} = ${S}`;default:throw new Error(`Unsupported operation ${c} for MANY cardinality`)}}throw new Error(`Unsupported cardinality ${g}`)}):[],E=$.length>0?`${$.join(", ")}`:"",m=E?`SET ${E}`:"";return `IF ${h} THEN (UPDATE ${h} ${m} RETURN VALUE id) END; ${h};`},i=a=>{let{$thing:l,$op:d}=a,c=ee(t,l),u=le(l),{usedRoleFields:p}=ye(c,a);if(!["create","delete"].includes(d))throw new Error("Arcs can only be created or deleted");let[f,h]=p,$=isArray(a[f])?a[f]:[a[f]],E=isArray(a[h])?a[h]:[a[h]];if(d==="create"){if(p.length!==2)throw new Error("Not supported: Arcs must have exactly 2 roles");let m=me(a,j=>!j.startsWith("$")),B=`(CREATE ONLY Delta SET input = ${JSON.stringify(m)}, meta = {"$sid": $parent.id, "$id": record::id($parent.id)}, after = $after, before = $before RETURN VALUE $parent.id )`,T=c.roles[f].cardinality==="MANY",Q=c.roles[h].cardinality==="MANY";return [`
|
|
121
|
+
${T?"":`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; };`}
|
|
122
|
+
${Q?"":`IF array::len(array::filter(array::flatten([$\u27E8${E}\u27E9]), |$v| !!$v))>1 { THROW "[Validation] Cardinality constraint: ${h} is cardinality one and can link a single thing." + <string>$\u27E8${E}\u27E9; };`}
|
|
115
123
|
FOR $node1 IN array::flatten([$\u27E8${$}\u27E9]) {
|
|
116
124
|
IF $node1 {
|
|
117
|
-
FOR $node2 IN array::flatten([$\u27E8${
|
|
125
|
+
FOR $node2 IN array::flatten([$\u27E8${E}\u27E9]) {
|
|
118
126
|
IF $node2 {
|
|
119
127
|
CREATE ONLY ${u} SET
|
|
120
|
-
${f} = ${
|
|
121
|
-
${
|
|
122
|
-
RETURN ${
|
|
128
|
+
${f} = ${T?"array::flatten([$node1])":"$node1"},
|
|
129
|
+
${h} = ${Q?"array::flatten([$node2])":"$node2"}
|
|
130
|
+
RETURN ${B};
|
|
123
131
|
}
|
|
124
132
|
}
|
|
125
133
|
}
|
|
126
|
-
}`]}if(
|
|
134
|
+
}`]}if(d==="delete")return `DELETE FROM ${u} WHERE fn::as_array(${f}) CONTAINSANY $\u27E8${$}\u27E9 AND fn::as_array(${h}) CONTAINSANY $\u27E8${E}\u27E9 RETURN BEFORE`},o=a=>{let{$thing:l,$bzId:d,$op:c,$tempId:u}=a,p=ee(t,l),{usedRefFields:f}=ye(p,a),h=`$\u27E8${u||d}\u27E9`,$=f.flatMap(y=>{let B=p.refFields[y];if(!B)throw new Error(`ReferenceField schema not found for ${y}`);let{cardinality:g,contentType:T}=B;if(T==="REF"){let S=isArray(a[y])?a[y]:[`${a[y]}`];if(g==="ONE"){if(S.length>1){let Q=`array::filter(array::flatten([${S}]), |$v| !!$v)`;switch(c){case "link":case "replace":return `${y} = ((array::len(${Q})==1) && ${Q}[0]) || ${Q}`;case "unlink":return `${y} = NONE`;default:throw new Error(`Unsupported operation ${c} for ONE cardinality`)}}switch(c){case "link":case "replace":return `${y} = ((type::is::array(${S[0]}) && array::len(${S[0]})==1) && ${S[0]}[0]) || ${S[0]}`;case "unlink":return `${y} = NONE`;default:throw new Error(`Unsupported operation ${c} for ONE cardinality`)}}if(g==="MANY"){let Q=`array::flatten([${S}])`;switch(c){case "link":return `${y} += ${Q}`;case "unlink":return `${y} -= ${Q}`;case "replace":return `${y} = ${Q}`;default:throw new Error(`Unsupported operation ${c} for MANY cardinality`)}}throw new Error(`Unsupported cardinality ${g}`)}if(T==="FLEX")return `${y} = ${g==="ONE"?`array::flatten([${a[y]}])[0]`:`array::flatten([${a[y]}])`}`;throw new Error(`Unsupported contentType ${T}`)}),E=$.length>0?`${$.join(", ")}`:"",m=E?`SET ${E}`:"";return `IF ${h} THEN (UPDATE ${h} ${m} RETURN VALUE id) END; ${h};`};return [...e.things.map(r),...e.edges.map(n),...e.arcs.flatMap(i),...e.references.map(o)]};var fo=e=>{let{res:t,config:r}=e;return t.flat().filter(Boolean).flatMap(i=>{if(isArray(i))return i.map(o=>{if(!isObject(o)||!("meta"in o))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(o)}`);return po(o,r)});if(!isObject(i)||!("meta"in i))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(i)}`);return po(i,r)})},po=(e,t)=>{let r=mapEntries(e.after||{},(o,s)=>[o,o==="id"?s.id:isArray(s)&&s.length===0?void 0:s]),n=me(e.input||{},(o,s)=>s===null),i={...r,...e.meta,...n};return t.mutation?.noMetadata?me(i,o=>!o.startsWith("$")):i};var $o=async(e,t)=>{let r=`
|
|
127
135
|
BEGIN TRANSACTION;
|
|
128
136
|
${t.join(";")};
|
|
129
137
|
LET $DELTAS = SELECT * FROM Delta;
|
|
@@ -133,11 +141,11 @@ limit ${h};`),u.join(`
|
|
|
133
141
|
LET $LOGS = SELECT * FROM LOG;
|
|
134
142
|
RETURN $LOGS;
|
|
135
143
|
COMMIT TRANSACTION;
|
|
136
|
-
`;
|
|
137
|
-
${R.join(" or ")};`}return ""},fe=()=>f==="update"||f==="link"||f==="match"?`${p} isa ${[m,...x].filter(A=>A).join(",")};`:"";if(ct(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=z(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 fi=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 $i=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 ra=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),na=(e,t)=>({...e,tql:{...e.tql,mutation:t.data}}),ia=(e,t)=>({...e,tql:{...e.tql,res:t.data}}),hr=_("error","error",j((e,t)=>({...e,error:t.error}))),oa=ge("buildMutation",{buildMutation:V(async e=>pi(e.bql.things,e.bql.edges,e.schema),_("done","runMutation",j(na)),hr),runMutation:V(async e=>$i(e.tql.mutation,e.handles,e.config),_("done","parseMutation",j(ia)),hr),parseMutation:V(async e=>fi(e.tql.res,e.bql.things,e.bql.edges,e.schema,e.config),_("done","success",j(ra)),hr),success:ce(),error:ce()},e=>e),sa=async e=>new Promise((t,r)=>{Ee(oa,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),mi=async(e,t,r,n,i,o,a)=>sa({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 yi=ce,Je=(e,t)=>t.data?{...e,bql:{...e.bql,enriched:t.data}}:e,aa=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),la=(e,t)=>({...e,bql:{...e.bql,flat:t.data||"test"}}),ca=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),da=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?_t(e.bql.enriched,e.schema,e.config):_t(e.bql.raw,e.schema,e.config)),ua=async e=>(se(`>>> mutationMachine/preQuery[${ae}]`,JSON.stringify(e.bql.enriched)),ri(e.bql.enriched,e.schema,e.config,e.handles)),ha=async e=>(se(`>>> mutationMachine/preQueryDependencies[${ae}]`,JSON.stringify(e.bql.enriched)),Vn(e.bql.enriched,e.schema,e.config,e.handles)),pa=async e=>(se(`>>> mutationMachine/parseBQL[${ae}]`,JSON.stringify(e.bql.enriched)),ti(e.bql.enriched,e.schema)),fa=async e=>(se(`>>> mutationMachine/flattenBQL[${ae}]`,JSON.stringify(e.bql.enriched)),Yn(e.bql.enriched,e.schema)),$a=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}.`)},ma=e=>Ve(e.bql.enriched),xe=_("error","error",j((e,t)=>({...e,error:t.error}))),ya=ge("stringify",{stringify:V(async e=>(se(`>>> mutationMachine/stringify[${ae}]`,JSON.stringify(e.bql.raw)),ni(e.bql.raw,e.schema)),_("done","enrich",j(Je)),xe),enrich:V(da,_("done","preQuery",Dt($a),j(Je)),_("done","parseBQL",j(Je)),xe),preQuery:V(ua,_("done","preHookDependencies",Dt(ma),j(Je)),_("done","parseBQL",j(Je)),xe),preHookDependencies:V(ha,_("done","enrich",j(Je)),xe),parseBQL:V(pa,_("done","flattenBQL",j(aa)),xe),flattenBQL:V(fa,_("done","adapter",j(la)),xe),adapter:V(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 mi(e.bql.raw,e.bql.enriched,e.bql.things,e.bql.edges,e.schema,e.config,e.handles);if(r==="surrealDB")return ui(e.bql.raw,e.bql.enriched,e.bql.flat,e.schema,e.config,e.handles);throw new Error(`Unsupported provider ${r}.`)},_("done","success",j(ca)),xe),success:yi(),error:yi()},e=>e),ga=async e=>new Promise((t,r)=>{Ee(ya,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),gi=async(e,t,r,n)=>ga({bql:{raw:e,enriched:{},things:[],edges:[],flat:{things:[],edges:[],arcs:[],references:[]},res:[]},schema:t,config:r,handles:n,depthLevel:0,error:null});enableMapSet();var pr=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(i=>{i?n(i):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 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:Sr(this.schema,t),dbHandles:t};let r=this.subscribers;this.subscribers=[];for(let n of r)n();}catch(r){let n=this.subscribers;this.subscribers=[];for(let i of n)i(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(),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(gi)(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;}}},Vh=pr;//! 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
|
|
144
|
+
`;Z(`>>> batchedMutation[${G}]`,JSON.stringify({batchedMutation:r}));try{return (await e.query(r)).filter(Boolean)}catch(n){let o=(await e.query_raw(r)).filter(s=>s.result!=="The query was not executed due to a failed transaction"&&s.result!=="There was an error when starting a new datastore transaction"&&s.status==="ERR");throw o.length>0?new Error(`Error running SURQL mutation: ${JSON.stringify(o)}`):n}};var Nl=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Ol=(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}}},Il=(e,t)=>{if(!t.data||!isArray(t.data))throw new Error("Invalid event data");return {...e,surql:{...e.surql,res:t.data}}},Ir=x("error","error",P((e,t)=>({...e,error:t.error}))),kl=we("buildMutation",{buildMutation:U(async e=>(Z(`>>> surqlMachine/buildMutation[${G}]`,JSON.stringify(e.bql.flat)),co(e.bql.flat,e.schema)),x("done","runMutation",P(Ol)),Ir),runMutation:U(async e=>(Z(`>>> surqlMachine/runMutation[${G}]`,JSON.stringify(e.surql.mutations)),$o(e.handles.surrealDB?.get(e.handles.surrealDB?.keys().next().value)?.client,e.surql.mutations)),x("done","parseMutation",P(Il)),Ir),parseMutation:U(async e=>(Z(`>>> surqlMachine/parseMutation[${G}]`,JSON.stringify(e.surql.res)),fo({res:e.surql.res,config:e.config,schema:e.schema})),x("done","success",P(Nl)),Ir),success:$e(),error:$e()},e=>e),Cl=async e=>new Promise((t,r)=>{Se(kl,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),yo=async(e,t,r,n,i,o)=>Cl({bql:{raw:e,enriched:t,flat:r,things:[],edges:[],res:[]},surql:{mutations:[],res:[]},schema:n,config:i,handles:o,error:null});var kr=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 Eo=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=p=>{let f=p.$op,h=`$${p.$bzId}`,$=V(r,p),{idFields:E,defaultDBConnector:m}=$,y=m?.path||p.$thing,B=p.$id,g=E?.[0],T=listify(p,(I,D)=>{if(I.startsWith("$")||I.startsWith("%")||I===g||D===void 0||D===null)return "";let Y=$.dataFields?.find(w=>w.path===I);if(!Y?.path)return "";let F=Y.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(Y.contentType))return `has ${F} '${D}'`;if(["NUMBER","BOOLEAN"].includes(Y.contentType))return `has ${F} ${D}`;if(Y.contentType==="DATE"){if(Number.isNaN(D.valueOf()))throw new Error("Invalid format, Nan Date");return D instanceof Date?`has ${F} ${D.toISOString().replace("Z","")}`:`has ${F} ${new Date(D).toISOString().replace("Z","")}`}if(Y.contentType==="FLEX"){let w=`bza${xe()}`,M=isArray(D)?D.map(R=>kr(R)):kr(D);if(Array.isArray(M))throw new Error("Array in FLEX fields not supported yet");return `has ${F} $${w}; $${w} '${w}' isa ${F}, has ${M.type}Attribute ${M.value}`}throw new Error(`Unsupported contentType ${Y.contentType}`)}).filter(I=>I),S=`${h}-atts`,Q=listify(p,I=>{if(I.startsWith("$")||I.startsWith("%")||I===g)return "";let D=$.dataFields?.find(F=>F.path===I);if(!D?.path)return "";let b=D.dbPath;return `{${S} isa ${b};}`}).filter(I=>I),N=isArray(B)?`like '${B.join("|")}'`:`'${B}'`,j=B?[`has ${g} ${N}`]:[],K=[...j,...T].filter(I=>I).join(","),ce=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${h} isa ${[y,...j].filter(I=>I).join(",")};`;if(f==="update"){if(!Q.length)throw new Error("update without attributes");return `${h} isa ${[y,...j].filter(I=>I).join(",")}, has ${S};
|
|
145
|
+
${Q.join(" or ")};`}return ""},se=()=>f==="update"||f==="link"||f==="match"?`${h} isa ${[y,...j].filter(I=>I).join(",")};`:"";if(St(p))return {op:f,deletionMatch:ce(),insertionMatch:se(),insertion:f==="create"?`${h} isa ${[y,K].filter(I=>I).join(",")};`:f==="update"&&T.length?`${h} ${T.join(",")};`:"",deletion:f==="delete"?`${h} isa ${y};`:f==="update"&&Q.length?`${h} has ${S};`:""};throw new Error("in attributes")},i=p=>{let f=p.$op,h=V(r,p),$=`$${p.$bzId}`,E=p.$id,m=h.defaultDBConnector?.path||p.$thing,y="roles"in h?listify(h.roles,D=>D):[],B="roles"in h?mapEntries(h.roles,(D,Y)=>[D,Y.dbConnector?.path||D]):{},g=listify(p,(D,Y)=>{if(!y.includes(D))return null;if(!("roles"in h))throw new Error("This should have roles! ");let b=B[D];return Array.isArray(Y)?Y.map(F=>({path:b,id:F})):{path:b,id:Y}}).filter(D=>D).flat(),T=g.map(D=>{if(!D?.path)throw new Error("Object without path");return `${D.path}: $${D.id}`}),S=g.length>0?`( ${T.join(" , ")} )`:"",Q=p[Ue];if(!Q)throw new Error("[internal error] Symbol edgeType not defined");let N=S?`${$} ${S} ${Q==="linkField"||f==="delete"||f==="unlink"?`isa ${m}`:""}`:"",j=`${$} ${Q==="linkField"||f==="delete"?`isa ${m}`:""}`,K=()=>N?f==="link"?`${N};`:f==="create"?`${N}, has id '${E}';`:"":"",ce=()=>N&&f==="match"?`${N};`:"",se=()=>N?f==="delete"?`${N};`:f==="match"?`${N};`:"":"",I=()=>N?f==="delete"?`${j};`:f==="unlink"?`${$} ${S};`:"":"";return {deletionMatch:se(),insertionMatch:ce(),deletion:I(),insertion:K(),op:""}},o=(p,f)=>{let h=f==="edges"?i:n;if(Array.isArray(p))return p.map(g=>{let{preDeletionBatch:T,insertionMatch:S,deletionMatch:Q,insertion:N,deletion:j}=h(g);return shake({preDeletionBatch:T,insertionMatch:S,deletionMatch:Q,insertion:N,deletion:j},K=>!K)}).filter(g=>g);let{preDeletionBatch:$,insertionMatch:E,deletionMatch:m,insertion:y,deletion:B}=h(p);return shake({preDeletionBatch:$,insertionMatch:E,deletionMatch:m,insertion:y,deletion:B},g=>!g)},s=o(e),a=Array.isArray(s)?s:[s],l=o(t,"edges"),d=Array.isArray(l)?l:[l],c=[...a,...d];return shake({insertionMatches:c.map(p=>p.insertionMatch).join(" ").trim(),deletionMatches:c.map(p=>p.deletionMatch).join(" ").trim(),insertions:c.map(p=>p.insertion).join(" ").trim(),deletions:c.map(p=>p.deletion).join(" ").trim()},p=>!p)};var Bo=async(e,t,r,n,i)=>{let o=[...t,...r],s=o.map(a=>{let l=e.insertions?.find(u=>u.get(`${a.$bzId}`))?.get(`${a.$bzId}`),d=a.$thing||a.$relation||a.$entity,c=d?ee(n,d):void 0;if(a.$op==="create"||a.$op==="update"||a.$op==="link"){if(a.$op!=="update"&&!l&&a.$id)return {$id:a.$id,$error:"Does not exist or it's not linked to the parent"};let u=l?.asThing().iid,p=Object.entries(a).filter(([h,$])=>!h.startsWith("$")).reduce((h,[$,E])=>{if(c?.dataFields?.find(y=>y.path===$)?.contentType==="JSON")return h[$]=JSON.parse(E),h;if(a.$thingType==="relation"){let y=o.filter(B=>B.$id&&B.$bzId===E);return y.length===1?(h[$]=y[0].$id,h):(h[$]=E,h)}return h[$]=E,h},{});if(i.mutation?.noMetadata)return p;let f=a.$tempId&&!a.$tempId.startsWith("_:")?{$tempId:`_:${a.$tempId}`}:{};return {$dbId:u,...a,...p,[a.path]:a.$id,...f}}if(a.$op==="delete"||a.$op==="unlink")return a;if(a.$op!=="match")throw new Error(`Unsupported op ${a.$op}`)}).filter(a=>a);return clone(s)};var Fo=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 Pt(t,r),i=await n.transaction(TransactionType.WRITE),o=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,s=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;try{o&&await i.query.delete(o);let a=s&&i.query.insert(s),l=a?await a.collect():void 0;return await i.commit(),{insertions:l}}catch(a){throw new Error(`Transaction failed: ${a.message}`)}finally{await i.close();}};var _l=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Vl=(e,t)=>({...e,tql:{...e.tql,mutation:t.data}}),zl=(e,t)=>({...e,tql:{...e.tql,res:t.data}}),qr=x("error","error",P((e,t)=>({...e,error:t.error}))),Ul=we("buildMutation",{buildMutation:U(async e=>Eo(e.bql.things,e.bql.edges,e.schema),x("done","runMutation",P(Vl)),qr),runMutation:U(async e=>Fo(e.tql.mutation,e.handles,e.config),x("done","parseMutation",P(zl)),qr),parseMutation:U(async e=>Bo(e.tql.res,e.bql.things,e.bql.edges,e.schema,e.config),x("done","success",P(_l)),qr),success:$e(),error:$e()},e=>e),vl=async e=>new Promise((t,r)=>{Se(Ul,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),bo=async(e,t,r,n,i,o,s)=>vl({bql:{raw:e,enriched:t,things:r,edges:n,flat:{things:[],edges:[],arcs:[],references:[]},res:[]},tql:{},schema:i,config:o,handles:s,error:null});var To=$e,dt=(e,t)=>t.data?{...e,bql:{...e.bql,enriched:t.data}}:e,Wl=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),Hl=(e,t)=>({...e,bql:{...e.bql,flat:t.data||"test"}}),Jl=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Kl=async e=>(Z(`>>> mutationMachine/enrich[${G}]`,JSON.stringify(Object.keys(e.bql.enriched).length?e.bql.enriched:e.bql.raw)),Object.keys(e.bql.enriched).length?dr(e.bql.enriched,e.schema,e.config):dr(e.bql.raw,e.schema,e.config)),Yl=async e=>(Z(`>>> mutationMachine/preQuery[${G}]`,JSON.stringify(e.bql.enriched)),ao(e.bql.enriched,e.schema,e.draftSchema,e.config,e.handles)),Xl=async e=>(Z(`>>> mutationMachine/preQueryDependencies[${G}]`,JSON.stringify(e.bql.enriched)),Xi(e.bql.enriched,e.schema,e.draftSchema,e.config,e.handles)),Zl=async e=>(Z(`>>> mutationMachine/parseBQL[${G}]`,JSON.stringify(e.bql.enriched)),so(e.bql.enriched,e.schema)),Gl=async e=>(Z(`>>> mutationMachine/flattenBQL[${G}]`,JSON.stringify(e.bql.enriched)),ro(e.bql.enriched,e.schema)),ec=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}.`)},tc=e=>rt(e.bql.enriched),Ke=x("error","error",P((e,t)=>({...e,error:t.error}))),rc=we("stringify",{stringify:U(async e=>(Z(`>>> mutationMachine/stringify[${G}]`,JSON.stringify(e.bql.raw)),lo(e.bql.raw,e.schema)),x("done","enrich",P(dt)),Ke),enrich:U(Kl,x("done","preQuery",Zt(ec),P(dt)),x("done","parseBQL",P(dt)),Ke),preQuery:U(Yl,x("done","preHookDependencies",Zt(tc),P(dt)),x("done","parseBQL",P(dt)),Ke),preHookDependencies:U(Xl,x("done","enrich",P(dt)),Ke),parseBQL:U(Zl,x("done","flattenBQL",P(Wl)),Ke),flattenBQL:U(Gl,x("done","adapter",P(Hl)),Ke),adapter:U(async e=>{Z(`>>> mutationMachine/adapter[${G}]`,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 bo(e.bql.raw,e.bql.enriched,e.bql.things,e.bql.edges,e.schema,e.config,e.handles);if(r==="surrealDB")return yo(e.bql.raw,e.bql.enriched,e.bql.flat,e.schema,e.config,e.handles);throw new Error(`Unsupported provider ${r}.`)},x("done","success",P(Jl)),Ke),success:To(),error:To()},e=>e),nc=async e=>new Promise((t,r)=>{Se(rc,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),wo=async(e,t,r,n,i)=>nc({bql:{raw:e,enriched:{},things:[],edges:[],flat:{things:[],edges:[],arcs:[],references:[]},res:[]},schema:t,draftSchema:r,config:n,handles:i,depthLevel:0,error:null});enableMapSet();var Pr=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(i=>{i?n(i):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 i=new gt({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 s=`[BORM:${n.provider}:${n.dbName}:core] ${i.message??"Can't create TypeDB Client"}`;throw new Error(s)}try{let s=await o.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:o,session:s});}catch(s){let a=`[BORM:${n.provider}:${n.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(a)}}else if(n.provider==="typeDBCluster"&&n.dbName){let i=new TypeDBCredential(n.username,n.password,n.tlsRootCAPath),[o,s]=await tryit(TypeDB.cloudDriver)(n.addresses,i);if(o){let a=`[BORM:${n.provider}:${n.dbName}:core] ${o.message??"Can't create TypeDB Cluster Client"}`;throw new Error(a)}try{let a=await s.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:s,session:a});}catch(a){let l=`[BORM:${n.provider}:${n.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(l)}}})),this.initialized={draftSchema:tn(this.schema),enrichedSchema:Xr(this.schema,t),dbHandles:t};let r=this.subscribers;this.subscribers=[];for(let n of r)n();}catch(r){let n=this.subscribers;this.subscribers=[];for(let i of n)i(r);}finally{this.initializing=false;}};introspect=async()=>(await this.getInitialized()).enrichedSchema;define=async()=>{let t=await this.getInitialized();return await Wr(this.config,t.enrichedSchema,t.dbHandles)};query=async(t,r)=>{let n=await this.getInitialized(),i={...this.config,query:{...zt.query,...this.config.query,...r}},o=Array.isArray(t),s=o?t:[t],[a,l]=await tryit(lt)(s,n.enrichedSchema,n.draftSchema,i,n.dbHandles);if(a){let c=new Error(a.error);throw c.stack=a.error.stack,c}let d=l.bql.res;return o?d:d[0]};mutate=async(t,r)=>{let n=await this.getInitialized(),i={...this.config,mutation:{...zt.mutation,...this.config.mutation,...r}},[o,s]=await tryit(wo)(t,n.enrichedSchema,n.draftSchema,i,n.dbHandles);if(o){let l=new Error(o.error.message);throw l.stack=o.error.stack,l}return s.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;}}},n$=Pr;//! 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
|
|
138
146
|
//! Todo: delete when this works with the new $thing and $thingType fields
|
|
139
147
|
//! Todo: Sandbox the function in nodeCompute() instead of the existing fieldCompute()
|
|
140
148
|
//! reads all the insertions and gets the first match. This means each id must be unique
|
|
141
149
|
//!old
|
|
142
|
-
export{
|
|
150
|
+
export{n$ as default};//# sourceMappingURL=index.mjs.map
|
|
143
151
|
//# sourceMappingURL=index.mjs.map
|