@blitznocode/blitz-orm 0.9.19 → 0.10.4
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 +184 -60
- package/dist/index.d.ts +184 -60
- package/dist/index.js +38 -52
- package/dist/index.mjs +40 -54
- package/dist/magic-string.es-3CTDYLTI.mjs +15 -0
- package/package.json +20 -7
package/dist/index.mjs
CHANGED
|
@@ -1,66 +1,52 @@
|
|
|
1
|
-
import { isObject, isArray, clone, shake, tryit, listify, pick, mapEntries
|
|
2
|
-
import {
|
|
1
|
+
import { isObject, isArray, parallel, clone, shake, tryit, listify, pick, mapEntries } from 'radash';
|
|
2
|
+
import { TypeDBOptions, TransactionType, SessionType, TypeDB } from 'typedb-driver';
|
|
3
|
+
import { Surreal } from 'surrealdb.node';
|
|
3
4
|
import { enableMapSet, produce, isDraft, current } from 'immer';
|
|
4
5
|
import { traverse, getNodeByPath } from 'object-traversal';
|
|
5
6
|
import { v4 } from 'uuid';
|
|
6
|
-
import 'acorn';
|
|
7
7
|
import { isSet } from 'util/types';
|
|
8
|
+
import 'acorn';
|
|
8
9
|
|
|
9
|
-
var
|
|
10
|
-
`,Object.keys(t.entities).forEach(
|
|
11
|
-
`;let
|
|
12
|
-
`,
|
|
13
|
-
`),
|
|
14
|
-
`,
|
|
15
|
-
`),
|
|
16
|
-
`;}),Object.keys(t.relations).forEach(
|
|
17
|
-
`;let
|
|
18
|
-
`,
|
|
19
|
-
`),
|
|
20
|
-
`);}),
|
|
21
|
-
`,
|
|
22
|
-
`),
|
|
23
|
-
`;});let
|
|
10
|
+
var Je={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var ln=e=>{let t=[],r=new Map;return e.forEach(i=>{let{dbPath:o,contentType:n}=i,l=`${o}-${n}`;r.has(l)||(r.set(l,!0),t.push(i));}),t},Rt=async(e,t,r)=>{let o=(()=>{let g="",y=[];g+=`
|
|
11
|
+
`,Object.keys(t.entities).forEach(m=>{let D=t.entities[m],{idFields:R,dataFields:A,linkFields:x,name:j}=D,N=[],se=[],K=[];if("extends"in D){let B=t.entities[D.extends];B.dataFields&&B.dataFields.forEach(M=>{N.push(M.dbPath);}),B.linkFields&&B.linkFields.forEach(M=>{se.push(M.path);}),B.idFields&&B.idFields.forEach(M=>{K.push(M);});}g+=`${j} sub ${"extends"in D?D.extends:"entity"},
|
|
12
|
+
`;let S=[];if(R&&R.length>0){let B=new Set(R),F=Array.from(B).map(E=>`${E}`).join(", ");K.includes(F)||(g+=` owns ${F} @key,
|
|
13
|
+
`,S.push(F));}if(A&&A.length>0&&A.forEach(B=>{!N.includes(B.dbPath)&&!S.includes(B.dbPath)&&(g+=` owns ${B.dbPath},
|
|
14
|
+
`),y.push({dbPath:B.dbPath,contentType:B.contentType});}),x&&x.length>0){let B=[];x.forEach(M=>{let{relation:F,plays:E}=M;!se.includes(M.path)&&!B.includes(`${F}:${E}`)&&(g+=` plays ${F}:${E},
|
|
15
|
+
`,B.push(`${F}:${E}`));});}g=g.replace(/,\s*$/,`;
|
|
16
|
+
`),g+=`
|
|
17
|
+
`;}),Object.keys(t.relations).forEach(m=>{let D=t.relations[m],{idFields:R,dataFields:A,roles:x,name:j,linkFields:N}=D,se=[],K=[],S=[],B=[];if("extends"in D){let F=t.relations[D.extends];F.dataFields&&F.dataFields.forEach(E=>{se.push(E.dbPath);}),F.linkFields&&F.linkFields.forEach(E=>{K.push(E.dbPath);}),F.roles&&Object.values(F.roles).forEach(Q=>{S.push(Q.name);}),F.idFields&&F.idFields.forEach(E=>{B.push(E);});}g+=`${j} sub ${"extends"in D?D.extends:"relation"},
|
|
18
|
+
`;let M=[];if(R&&R.length>0){let F=new Set(R),Q=Array.from(F).map(L=>`${L}`).join(", ");B.includes(Q)||(g+=` owns ${Q} @key,
|
|
19
|
+
`,M.push(Q));}if(A&&A.length>0&&A.forEach(F=>{!se.includes(F.dbPath)&&!M.includes(F.dbPath)&&(g+=` owns ${F.dbPath},
|
|
20
|
+
`),y.push({dbPath:F.dbPath,contentType:F.contentType});}),x&&Object.keys(x).forEach(F=>{S.includes(F)||(g+=` relates ${F},
|
|
21
|
+
`);}),N&&N.length>0){let F=[];N.forEach(E=>{let{plays:Q}=E;!K.includes(E.path)&&!F.includes(`${D}:${Q}`)&&(g+=` plays ${E.relation}:${Q},
|
|
22
|
+
`,F.push(`${D}:${Q}`));});}g=g.replace(/,\s*$/,`;
|
|
23
|
+
`),g+=`
|
|
24
|
+
`;});let w=`define
|
|
24
25
|
|
|
25
|
-
`;return
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
`,
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
`)
|
|
26
|
+
`;return ln(y).forEach(m=>{if(w+=`${m.dbPath} sub attribute,
|
|
27
|
+
`,m.contentType==="TEXT"||m.contentType==="ID"||m.contentType==="JSON")w+=` value string;
|
|
28
|
+
`;else if(m.contentType==="EMAIL")w+=` value string,
|
|
29
|
+
`,w+=` regex '^(?=.{1,64}@)[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*@[^-][A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$';
|
|
30
|
+
`;else if(m.contentType==="DATE")w+=` value datetime;
|
|
31
|
+
`;else if(m.contentType==="BOOLEAN")w+=` value boolean;
|
|
32
|
+
`;else if(m.contentType==="NUMBER")w+=` value long;
|
|
33
|
+
`;else throw new Error(`Conversion of borm schema to TypeDB schema for data type "${m.contentType}" is not implemented`)}),`${w}
|
|
33
34
|
|
|
34
|
-
${m}`})(),a=e.dbConnectors[0].id,d=n.typeDB.get(a)?.session,h=n.typeDB.get(a)?.client;if(!d){console.log("Session Status: ","NO SESSION");return}await d.close();let[{dbName:T}]=e.dbConnectors;await(await h.databases.get(T)).delete(),await h.databases.create(T);let r=await h.session(e.dbConnectors[0].dbName,SessionType.SCHEMA),i=await r.transaction(TransactionType.WRITE);await i.query.define(l),await i.commit(),await i.close();let s=await r.transaction(TransactionType.READ);(await(await s.query.match("match $a sub thing;")).collect()).forEach(async m=>{m.get("a");}),await s.close();};var de={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var he=(e,t,n)=>n?t:`${e}\xB7${t}`;var fe=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([n,o])=>t(n,o))))[0],Ft=(e,t)=>Object.fromEntries(Object.entries(e).filter(([n,o])=>t(n,o))),$e=(e,t)=>{let n=[],o=produce(e,a=>traverse(a,({key:d,value:h,meta:T})=>{if(T.depth===2&&(d&&(h.dataFields=h.dataFields?.map(k=>({...k,cardinality:k.cardinality||"ONE",dbPath:he(d,k.path,k.shared)}))),h.extends)){if(!h.defaultDBConnector.as)throw new Error(`[Schema] ${d} is extending a thing but missing the "as" property in its defaultDBConnector`);let k=a.entities[h.extends]||a.relations[h.extends];if(h.allExtends=[h.extends,...k.allExtends||[]],h.idFields=k.idFields?(h.idFields||[]).concat(k.idFields):h.idFields,h.dataFields=k.dataFields?(h.dataFields||[]).concat(k.dataFields.map(r=>{let i=h.extends,s=e.entities[i]||e.relations[i];for(;!s.dataFields?.find(f=>f.path===r.path);)i="extends"in s?s.extends:void 0,s=e.entities[i]||e.relations[i];return {...r,dbPath:he(i,r.path,r.shared)}})):h.dataFields,h.linkFields=k.linkFields?(h.linkFields||[]).concat(k.linkFields):h.linkFields,"roles"in k){let r=h,i=k;r.roles=r.roles||{},r.roles={...r.roles,...i.roles},Object.keys(r.roles).length===0&&(r.roles={});}k?.hooks?.pre&&(h.hooks=h.hooks||{},h.hooks.pre=h.hooks.pre||[],h.hooks.pre=[...k?.hooks?.pre||[],...h?.hooks?.pre||[]]);}},{traversalType:"breadth-first"}));return traverse(e,({key:a,value:d,meta:h})=>{if(a==="linkFields"){let k=(()=>{if(!h.nodePath)throw new Error("No path");let[i,s]=h.nodePath.split(".");return {thing:s,thingType:i==="entities"?"entity":i==="relations"?"relation":""}})(),r=Array.isArray(d)?d.map(i=>({...i,...k})):[{...d,...k}];n.push(...r);}}),produce(o,a=>traverse(a,({value:d,key:h,meta:T})=>{if(T.depth===2&&d.idFields&&!d.id){d.name=h;let k=()=>{if(T.nodePath?.split(".")[0]==="entities")return "entity";if(T.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};d.thingType=k();let r=Object.keys(t).find(i=>t[i]?.get(d.defaultDBConnector.id));d.db=r,d.dbContext=de[r],d.computedFields=[],d.virtualFields=[],d.requiredFields=[],d.enumFields=[],d.fnValidatedFields=[],"roles"in d&&Object.entries(d.roles).forEach(([s,f])=>{f.fieldType="roleField",f.playedBy=n.filter(u=>u.relation===h&&u.plays===s)||[],f.name=s;}),"linkFields"in d&&d.linkFields&&d.linkFields?.forEach(s=>{if(s.fieldType="linkField",s.target==="relation"){s.oppositeLinkFieldsPlayedBy=[{plays:s.path,thing:s.relation,thingType:"relation"}];return}let f=n.filter(c=>c.relation===s.relation&&c.plays!==s.plays)||[];s.oppositeLinkFieldsPlayedBy=f;let{filter:u}=s;s.oppositeLinkFieldsPlayedBy=s.oppositeLinkFieldsPlayedBy.filter(c=>c.target==="role"),u&&Array.isArray(u)&&(s.oppositeLinkFieldsPlayedBy=s.oppositeLinkFieldsPlayedBy.filter(c=>u.some(m=>c.thing===m.$role)),s.oppositeLinkFieldsPlayedBy=s.oppositeLinkFieldsPlayedBy.filter(c=>u.some(m=>c.thing===m.$thing))),u&&!Array.isArray(u)&&(s.oppositeLinkFieldsPlayedBy=s.oppositeLinkFieldsPlayedBy.filter(c=>c.$role===u.$role),s.oppositeLinkFieldsPlayedBy=s.oppositeLinkFieldsPlayedBy.filter(c=>c.thing===u.$thing));});}if(typeof d=="object"&&"playedBy"in d){let k=[...new Set(d.playedBy.map(r=>r.thing))];if(k.length>1)throw new Error(`[Schema] roleFields can be only played by one thing. Role: ${h}, path:${T.nodePath}, played by: ${k.join(", ")}`);if(d.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${h}, path:${T.nodePath}`)}if(T.depth===4){let[k,r]=T.nodePath?.split(".")||[],i=a[k][r];d.validations&&(d.validations.required&&i.requiredFields.push(d.path),d.validations.enum&&i.enumFields.push(d.path),d.validations.fn&&i.fnValidatedFields.push(d.path)),d.default?d.isVirtual?i.virtualFields.push(d.path):i.computedFields.push(d.path):d.isVirtual&&i.virtualFields.push(d.path);}}))},kt=(e,t)=>{if(t in e.entities)return e.entities[t];if(t in e.relations)return e.relations[t];throw new Error(`${t} is not defined in the schema`)},A=(e,t)=>{if(!t)throw new Error("[Internal] No node for getCurrentSchema");if(t.$thing){if(t.$thingType==="entity"){if(!(t.$thing in e.entities))throw new Error(`Missing entity '${t.$thing}' in the schema`);return e.entities[t.$thing]}if(t.$thingType==="relation"){if(!(t.$thing in e.relations))throw new Error(`Missing relation '${t.$thing}' in the schema`);return e.relations[t.$thing]}if(t.$thing in e.entities&&t.$thing in e.relations)throw new Error(`Ambiguous $thing ${t.$thing}`);if(t.$thing in e.entities)return e.entities[t.$thing];if(t.$thing in e.relations)return e.relations[t.$thing];throw new Error(`Wrong schema or query for ${JSON.stringify(t,null,2)}`)}if(t.$entity){if(!(t.$entity in e.entities))throw new Error(`Missing entity '${t.$entity}' in the schema`);return e.entities[t.$entity]}if(t.$relation){if(!(t.$relation in e.relations))throw new Error(`Missing relation '${t.$relation}' in the schema`);return e.relations[t.$relation]}throw new Error(`Wrong schema or query for ${JSON.stringify(t,null,2)}`)},me=(e,t)=>{let n=e.$thing||e.$entity||e.$relation;if(!n)throw new Error("[Internal] No thing found");if(e.$entity)return "entity";if(e.$relation)return "relation";if(t.entities[n])return "entity";if(t.relations[n])return "relation";throw new Error("No thing found")},Kt=(e,t,n)=>{let o=A(e,t),l=o.linkFields?.find(h=>h.path===n);if(l)return l;let a=o.dataFields?.find(h=>h.path===n);if(a)return a;let d="roles"in o?o.roles?.[n]:void 0;if(d)return d},vt=(e,t,n)=>Kt(e,t,n)?.cardinality,J=(e,t)=>{let n=e.dataFields?.map(u=>u.path)||[],o=e.linkFields?.map(u=>u.path)||[],l="roles"in e?listify(e.roles,u=>u):[],a=[...n||[],...o||[],...l||[]],h=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...a];if(!t)return {fields:a,dataFields:n,roleFields:l,linkFields:o};let T=t.$fields?t.$fields.map(u=>{if(typeof u=="string"){if(u.startsWith("$")||u.startsWith("%"))return;if(!a.includes(u))throw new Error(`Field ${u} not found in the schema`);return u}if("$path"in u&&typeof u.$path=="string")return u.$path;throw new Error("[Wrong format] Wrongly structured query")}):listify(t,u=>{if(!(u.startsWith("$")||u.startsWith("%"))){if(!a.includes(u))throw new Error(`[Schema] Field ${u} not found in the schema`);return u}}).filter(u=>u!==void 0),k=t.$filter?listify(t.$filter,u=>u.toString().startsWith("$")?void 0:u.toString()).filter(u=>u&&n?.includes(u)):[],r=t.$filter?listify(t.$filter,u=>u.toString().startsWith("$")?void 0:u.toString()).filter(u=>u&&[...l||[],...o||[]].includes(u)):[],i=[...T,...k].filter(u=>!u?.startsWith("%")).filter(u=>!h.includes(u)).filter(u=>u),s=t.$filter?Ft(t.$filter,(u,c)=>k.includes(u)):{},f=t.$filter?Ft(t.$filter,(u,c)=>r.includes(u)):{};return {fields:a,dataFields:n,roleFields:l,linkFields:o,usedFields:T,usedLinkFields:o.filter(u=>T.includes(u)),usedRoleFields:l.filter(u=>T.includes(u)),usedDataFields:n.filter(u=>T.includes(u)),unidentifiedFields:i,...k.length?{localFilters:s}:{},...r.length?{nestedFilters:f}:{}}};var ye=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},ge=(e,t,n)=>{let l=(n.nodePath||"").split("."),a=isArray(t)?l.slice(0,-2).join("."):l.slice(0,-1).join(".");return t?getNodeByPath(e,a):{}},v=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,n)=>(t[n]=e[n],t),{});var Lt=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),rt=e=>{if(Array.isArray(e))return e.map(t=>current(t));if(e&&typeof e=="object"){let t=isDraft(e)?current(e):e,n={};return Object.entries(t).forEach(([o,l])=>{n[o]=isDraft(l)?current(l):l;}),n}else return e};var U=Symbol.for("queryPath"),Qt=Symbol.for("stepPrint"),ct=Symbol.for("edgeType"),it=Symbol.for("edgeSchema");var K="___",Be=async e=>{let{enrichedBqlQuery:t}=e;if(!t)throw new Error("BQL query not enriched");let n="",o=(r,i)=>{let s="",f="";for(let u in r){let c=r[u];if(Array.isArray(c))for(let m=0;m<c.length;m++)f+=`{$${i} has ${u} "${c[m]}";}`,m<c.length-1?f+="or":f+=";";else s+=`, has ${u} "${c}"`;}s+=`;
|
|
35
|
-
`,n+=s,n+=f;},l=(r,i)=>{let s=[],f=[],u="";for(let p=0;p<r.length;p++)r[p].$isVirtual||s.push(` ${r[p].$dbPath}`),f.push(`{${r[p].$dbPath}:${r[p].$as}}`);let c=`${s.join(",")};
|
|
36
|
-
|
|
37
|
-
`,n
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
`;}},
|
|
44
|
-
`,n
|
|
45
|
-
`,f.$filter&&(n+=` $${i}${K}${f.$var} isa ${f.$thing}`,o(f.$filter,`${i}${K}${f.$var}`)),f.$target==="role"?n+=` $${i}_intermediary (${f.$plays}: $${i}, ${S.plays}: $${i}${K}${f.$var}) isa ${f.$intermediary};
|
|
46
|
-
`:n+=` $${i}${K}${f.$var} (${f.$plays}: $${i}) isa ${f.$thing};
|
|
47
|
-
`,u){let C=`M_${v4()}`;n+=`?queryPath${C} = "${$}";
|
|
48
|
-
`,n+=` fetch
|
|
49
|
-
`,n+=`?queryPath${C} as "queryPath"
|
|
50
|
-
;`;let g=u?.filter(y=>y.$fieldType==="data");g&&g.length>0&&l(g,`${i}${K}${f.$var}`);let b=u?.filter(y=>y.$fieldType==="link");b&&b.length>0&&d(b,`${i}${K}${f.$var}`,`${i}.${f.$var}`);let F=u?.filter(y=>y.$fieldType==="role");F&&F.length>0&&a(F,`${i}${K}${f.$var}`,`${i}.${f.$var}`);}n+=`};
|
|
51
|
-
`;}},h=t.length>1,T=[];(r=>{if(h)for(let i of r){let{$path:s,$thing:f,$filter:u,$fields:c}=i;if(!s)throw new Error("Path is not defined");let m=i[U];n+=`match
|
|
52
|
-
$${s} isa ${f} `,u?o(u,s):n+="; ";let p=`M_${v4()}`;if(n+=`?queryPath${p} = "${m}";
|
|
53
|
-
`,n+=`fetch
|
|
54
|
-
`,n+=`?queryPath${p} as "queryPath"
|
|
55
|
-
;`,c){let B=c.filter(Q=>Q.$fieldType==="data");B&&B.length>0&&l(B,s);let S=c.filter(Q=>Q.$fieldType==="link");S&&S.length>0&&d(S,s,s);let $=c.filter(Q=>Q.$fieldType==="role");$&&$.length>0&&a($,s,s);}T.push(n),n="";}else for(let i of r){let{$path:s,$thing:f,$filter:u,$fields:c}=i;if(!s||s==="undefined")throw new Error("Path is not defined");let m=i[U];if(n+=`match
|
|
56
|
-
$${s} isa ${f} `,u?o(u,s):n+="; ",n+=`?queryPath = "${m}";
|
|
57
|
-
`,n+=`fetch
|
|
58
|
-
`,n+=`?queryPath as "queryPath"
|
|
59
|
-
;`,c){let p=c.filter($=>$.$fieldType==="data");p&&p.length>0&&l(p,s);let B=c.filter($=>$.$fieldType==="link");B&&B.length>0&&d(B,s,s);let S=c.filter($=>$.$fieldType==="role");S&&S.length>0&&a(S,s,s);}}})(t),e.tqlRequest=h?T:n;};var Jt=e=>{let t=e.dataFields?.map(a=>a.path)||[],n=e.linkFields?.map(a=>a.path)||[],o=Object.keys(e.roles||{})||[];return [...t,...n,...o]},Zt=(e,t)=>Object.keys(e||{}).some(o=>{if(!Array.isArray(e[o])){let l=t.idFields?.includes(o),a=t.dataFields?.some(d=>(d.dbPath===o||d.path===o)&&d?.validations?.unique);return l||a}return !1}),Yt=(e,t)=>{let n=t.dataFields?.map(d=>({path:d.path,dbPath:d.dbPath}))||[],o=t.linkFields?.map(d=>({path:d.path,dbPath:d.dbPath}))||[],l=Object.keys(t.roles||{}).map(d=>({path:d,dbPath:d}))||[],a=[...n,...o,...l];return Object.entries(e||{}).reduce((d,[h,T])=>{let k=a.find(r=>r.path===h);return d[k?.dbPath||h]=T,d},{})},Fe=async e=>{let{rawBqlRequest:t,schema:n}=e;if(Array.isArray(t)){for(let r of t)if(!("$entity"in r)&&!("$relation"in r)&&(!("$thing"in r)||!("$thingType"in r)))throw new Error("No entity specified in query")}else if(!("$entity"in t)&&!("$relation"in t)&&(!("$thing"in t)||!("$thingType"in t)))throw new Error("No entity specified in query");let o=(r,i)=>typeof i=="string"?r.idFields?.includes(i):r.idFields?.includes(i.$path),l=(r,i,s,f,u)=>({$path:i,$dbPath:f,$thingType:"attribute",$as:r.$as||i,$var:i,$fieldType:"data",$excludedFields:r.$excludedFields,$justId:s,$id:r.$id,$filter:r.$filter,$isVirtual:u,$filterProcessed:!0}),a=(r,i,s,f,u)=>{let{target:c,oppositeLinkFieldsPlayedBy:m}=s;return m.map(p=>{let B=c==="role"?p.thingType:"relation",S=c==="role"?p.thing:s.relation,$={[`$${B}`]:S},Q=A(n,$),C=r?.$fields?.filter(b=>o(Q,b)).length===0,g=[];return typeof r!="string"?r.$fields?C?g=[...r.$fields,...Q.idFields]:g=r.$fields:g=Jt(Q):g=["id"],r.$excludedFields&&(g=g.filter(b=>o(Q,b)?!0:!r.$excludedFields.includes(b.$path))),{$thingType:B,$plays:s.plays,$playedBy:p,$path:p.path,$dbPath:u,$as:r.$as||i,$var:i,$thing:S,$fields:g,$excludedFields:r.$excludedFields,$fieldType:"link",$target:c,$intermediary:p.relation,$justId:f,$id:r.$id,$filter:Yt(r.$filter,Q),$idNotIncluded:C,$filterByUnique:Zt(r.$filter,Q),$filterProcessed:!0}})},d=(r,i,s,f,u)=>s.playedBy.map(c=>{let{thing:m,thingType:p,relation:B}=c,S={[`$${p}`]:m},$=A(n,S),Q=r?.$fields?.filter(g=>$?.idFields?.includes(g)||$?.idFields?.includes(g.$path)).length===0,C=[];return typeof r!="string"?r.$fields?Q?C=[...r.$fields,...$.idFields]:C=r.$fields:C=Jt($):C=["id"],r.$excludedFields&&(C=C.filter(g=>o($,g)?!0:!r.$excludedFields.includes(g.$path))),{$thingType:p,$path:i,$dbPath:u,$as:r.$as||i,$var:i,$thing:m,$fields:C,$excludedFields:r.$excludedFields,$fieldType:"role",$intermediary:B,$justId:f,$id:r.$id,$filter:Yt(r.$filter,$),$idNotIncluded:Q,$filterByUnique:Zt(r.$filter,$),$playedBy:c,$filterProcessed:!0}}),h=(r,i)=>{let s=typeof r=="string"?r:r.$path,f=typeof r=="string",u=i.dataFields?.find(p=>p.path===s),c=i.linkFields?.find(p=>p.path===s),m=i.roles?.[s];if(u){let p=u.isVirtual&&u.default;return l(r,s,f,u.dbPath,p)}else {if(c)return a(r,s,c,f,c.dbPath);if(m)return d(r,s,m,f,m.dbPath)}return null},k=(r=>produce(r,i=>traverse(i,s=>{let{value:f,meta:u}=s,c=f;if(isObject(c)){if(c.$id){let m=c.$entity||c.$relation?c:{[`$${c.$thingType}`]:c.$thing},p=A(n,m);if(!p?.name)throw new Error(`Schema not found for ${c.$thing}`);if(c.$path=p.name,Array.isArray(c.$id)||(c.$filterByUnique=!0),p?.idFields?.length===1){let[B]=p.idFields;c.$filter={...c.$filter,[B]:c.$id},delete c.$id;}else throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in c||"$relation"in c||"$thing"in c){let m=A(n,c);if(!m?.name)throw new Error(`Schema not found for ${c.$thing}`);c.$path=m.name;}if(c.$entity?(c.$thing=c.$entity,c.$thingType="entity",delete c.$entity):c.$relation&&(c.$thing=c.$relation,c.$thingType="relation",delete c.$relation),isObject(c)&&"$thing"in c){let m=c.$entity||c.$relation?c:{[`$${c.$thingType}`]:c.$thing};c[U]=u.nodePath;let p=A(n,m);if(c.$filter&&(c.$filterByUnique=Zt(c.$filter,p),c.$filterProcessed||(c.$filter=Yt(c.$filter,p))),c.$fields){c.$fields.filter($=>p?.idFields?.includes($)||p?.idFields?.includes($.$path)).length>0||(c.$fields=[...c.$fields,...Array.isArray(p.idFields)?p.idFields:[]],c.$idNotIncluded=!0);let S=c.$fields?.flatMap($=>{let Q=h($,p);return Array.isArray(Q)?Q:[Q]}).filter(Boolean);c.$fields=S;}else {let S=Jt(p)?.flatMap($=>{let Q=h($,p);return Array.isArray(Q)?Q:[Q]}).filter(Boolean);c.$fields=S;}c.$excludedFields&&(c.$fields=c.$fields.filter(B=>o(p,B)?!0:!c.$excludedFields.includes(B.$path)));}}})))(Array.isArray(t)?t:[t]);e.enrichedBqlQuery=k;};var wt=async(e,t)=>{let n=t.dbConnectors[0].id,o=e.typeDB?.get(n)?.session,l=e.typeDB?.get(n)?.client;if(!o||!o.isOpen()){if(!l)throw new Error("Client not found");o=await l.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(n,{client:l,session:o});}return {client:l,session:o}};var be=async(e,t)=>{let{dbHandles:n,enrichedBqlQuery:o,tqlRequest:l,config:a}=e;if(!o)throw new Error("BQL request not parsed");if(!l)throw new Error("TQL request not built");let d=new TypeDBOptions;if(d.infer=!0,Array.isArray(l)){let T=await parallel(l.length,l,async k=>{let{session:r}=await wt(n,a),i=await r.transaction(TransactionType.READ,d);if(!i)throw new Error("Can't create transaction");let f=await i.query.fetch(k).collect();return await i.close(),f});t.rawTqlRes=T,t.isBatched=!0;}else {let{session:T}=await wt(n,a),k=await T.transaction(TransactionType.READ,d);if(!k)throw new Error("Can't create transaction");let i=await k.query.fetch(l).collect();await k.close(),t.rawTqlRes=i;}};var Te=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,n=/justId:([a-zA-Z0-9_\-·]+)/,o=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,l=/filterByUnique:([a-zA-Z0-9_\-·]+)/,a=e.match(t),d=e.match(n),h=e.match(o),T=e.match(l);return {as:a?a[1]:null,justId:d?d[1]:null,idNotIncluded:h?h[1]:null,filterByUnique:T?T[1]:null}},xn=e=>{try{let n=(l=>{let a=l.replace("$metadata:","");return a=a.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),a=a.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(d,h,T)=>/^{.*}$/.test(T)?`:${T}`:`:${h}"${T}"`),a=a.replace(/\[([^\]]+)\]/g,(d,h)=>`[${h.split(",").map(T=>T.trim().startsWith("{")&&T.trim().endsWith("}")?T.trim():`"${T.trim()}"`).join(",")}]`),a})(e);return JSON.parse(n)}catch(t){return console.error(t),{as:[]}}},Me=async(e,t)=>{let{enrichedBqlQuery:n,rawBqlRequest:o,schema:l,config:a}=e,{rawTqlRes:d,isBatched:h}=t;if(n){if(!d)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");let T=(c,m)=>{let{$metaData:p}=c,{as:B}=xn(p),S=Object.entries(c).filter(([$])=>$!=="type"&&!$.startsWith("$")).map(([$,Q])=>{let C=m.dataFields?.find(y=>y.path===$||y.dbPath===$),g=$==="id",b=Array.isArray(B)?B.find(y=>y[$])?.[$]:$,F;if(C?.cardinality==="ONE"){if(F=Q[0]?Q[0].value:a.query?.returnNulls?null:void 0,C.contentType==="DATE"?F=F&&`${F}Z`:C.contentType==="JSON"&&(F=F&&JSON.parse(F)),g)return [[b,F],["$id",F]].filter(([y,P])=>P!==void 0)}else if(C?.cardinality==="MANY"){if(!isArray(Q))throw new Error("Typedb fetch has changed its format");if(Q.length===0)return a.query?.returnNulls?[[b,null]]:[];C.contentType==="DATE"?F=Q.map(y=>`${y.value}Z`):C.contentType==="JSON"?F=Q.map(y=>y.value&&JSON.parse(y.value)):F=Q.map(y=>y.value);}return [[b,F]].filter(([y,P])=>P!==void 0)}).flat();return Object.fromEntries([...S])},k=c=>c.reduce((m,p)=>{let{$roleFields:B,$metaData:S,$cardinality:$}=p,{as:Q,justId:C,idNotIncluded:g,filterByUnique:b}=Te(S),F=B.map(y=>{let{dataFields:P,currentSchema:M,linkFields:L,roleFields:E,schemaValue:I}=i(y),w=T(P,M);if(C==="T")return w.id;{let O=r(L),R=k(E),z={...w};return g==="true"&&M?.idFields?.forEach(N=>delete z[N]),{...z,...O,...R,...I}}});return F.length>0?m[Q]=$==="MANY"&&b==="false"?F:F[0]:a.query?.returnNulls&&(m[Q]=null),m},{}),r=c=>c.reduce((m,p)=>{let{$linkFields:B,$metaData:S,$cardinality:$}=p,{as:Q,justId:C,idNotIncluded:g,filterByUnique:b}=Te(S),F=B.map(y=>{let{dataFields:P,currentSchema:M,linkFields:L,roleFields:E,schemaValue:I}=i(y),w=T(P,M);if(C==="T")return w.id;{let O=r(L),R=k(E),z={...w};return g==="true"&&M.idFields?.forEach(N=>delete z[N]),{...z,...O,...R,...I}}});return m[Q]=F.length>0?$==="MANY"&&b==="false"?F:F[0]:a.query?.returnNulls?null:void 0,m},{}),i=c=>{let m=Object.keys(c),p=m.find(y=>y.endsWith(".$dataFields"));if(!p)throw new Error("No datafields");let B=c[p],S=p.split(".")[p.split(".").length-2];if(B.$metaData=S,B.length===0)throw new Error("No datafields");let $=B.type,Q={$thing:$.label,$thingType:$.root,[U]:c.queryPath.value},C={[`$${Q.$thingType}`]:Q.$thing},g=A(l,C),b=m.filter(y=>!y.endsWith(".$dataFields")&&g.linkFields?.some(P=>P.path===y.split(".").pop())).map(y=>({$linkFields:c[y],$key:y.split(".").pop(),$metaData:y.split(".")[y.split(".").length-2],$cardinality:g?.linkFields?.find(P=>P.path===y.split(".").pop())?.cardinality})),F=m.filter(y=>!y.endsWith(".$dataFields")&&g.roles?.[y.split(".").pop()]).map(y=>({$roleFields:c[y],$key:y.split(".").pop(),$metaData:y.split(".")[y.split(".").length-2],$cardinality:g.roles[y.split(".").pop()].cardinality}));return {dataFields:B,schemaValue:Q,currentSchema:g,linkFields:b,roleFields:F}},s=c=>c.map(m=>{let{dataFields:p,currentSchema:B,linkFields:S,roleFields:$,schemaValue:Q}=i(m),C=T(p,B),g=r(S),b=k($),F=o?.$fields?.every(P=>!B?.idFields?.includes(P)&&!B?.idFields?.includes(P.$path));return {...g,...b,...Q,...!a.query?.noMetadata&&o.$id?{$id:Array.isArray(o.$id)?C.id:o.$id}:{},...F?Object.fromEntries(Object.entries(C).filter(([P])=>!B?.idFields?.includes(P))):C}}),u=(c=>{let m=p=>{let B=s(p);return o.$id&&!Array.isArray(o.$id)||n[0].$filterByUnique?B[0]??null:B.length===0?null:B};return h?c.map(m):m(c)})(d);t.bqlRes=u;};var jn=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Nn=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,ke=e=>{let n=e.toString().replace(jn,"").trim().split("=>")[0].split("{")[0].replace(Nn,"").trim(),o=n.substring(n.indexOf("(")+1,n.lastIndexOf(")")).trim();return o?(o.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(a=>a.includes("{")&&a.includes("}")?(a.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(h=>h.split(":")[0].trim().replace(/['"[\]]/g,"")):a.trim()).filter(Boolean):[]};var ft=({currentThing:e,fieldSchema:t,mandatoryDependencies:n=!1})=>{if(!t||!t.default||!("fn"in t.default||"value"in t.default))throw new Error(`[Internal] Virtual field: No field schema found, or wrongly configured. Field: ${JSON.stringify(t,null,3)}`);if(t.default.type==="value")return t.default.value;if(n){let{fn:l}=t.default,d=ke(l).filter(h=>!(h in e));if(d.length)throw new Error(`Virtual field: Missing arguments ${d.join(", ")}`)}if(!t.default.fn)throw new Error("[Schema] No fn in default field schema");return "default"in t?t.default?.fn(e):void 0};var Le=async(e,t)=>{let{schema:n,enrichedBqlQuery:o}=e,{bqlRes:l}=t;if(!l)return;let d=(h=>produce(h,T=>traverse(T,({value:k})=>{if(isObject(k)){let r=k;if(!r.$thing)return;if(r.$thing){let i=A(n,r),{virtualFields:s}=i,f=r[U];if(!f)throw new Error("[Internal] QueryPath is missing");let u=getNodeByPath(o,f),c=u.$fields.map(p=>p.$path),m=u.$excludedFields;s.forEach(p=>{if(m?.includes(p)||c.length>0&&!c.includes(p))return;let B=i.dataFields?.find(S=>S.path===p);if(B?.default){let S=ft({currentThing:r,fieldSchema:B,mandatoryDependencies:!0});r[p]=S;}else if(r[p]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${p}`)}),m&&m.forEach(p=>{if(typeof p!="string")throw new Error("[Internal] ExcludedField is not a string");delete r[p];});}}})))(l);t.bqlRes=d;};var Se=async(e,t)=>{let{config:n}=e,{bqlRes:o}=t;if(!o)return;let a=(T=>produce(T,k=>traverse(k,({value:r})=>{isObject(r);})))(o),h=(T=>produce(T,k=>traverse(k,({value:r})=>{if(isObject(r)){let i=r;Object.keys(i).forEach(s=>{i[s]===void 0&&delete i[s];}),Object.getOwnPropertySymbols(i).forEach(s=>{delete i[s];}),n.query?.noMetadata===!0&&Object.keys(i).forEach(s=>{s.startsWith("$")&&delete i[s];});}})))(a);t.bqlRes=h;};var Hn={query:[Fe,Be,be,Me,Le,Se]},Ce=async(e,t,n={},o=!0)=>{for(let l of e){let a=await l(t,n);if(a&&Array.isArray(a))for(let d of a)await Ce(d.pipeline,d.req,d.res,!1);}return o&&t.config.query?.debugger===!0&&typeof n.bqlRes=="object"?{...n.bqlRes,$debugger:{tqlRequest:t.tqlRequest}}:n.bqlRes},It=(e,t,n,o)=>Ce(Hn.query,{config:t,schema:n,rawBqlRequest:e,dbHandles:o},{});var $t=(e,t)=>{if(t.fieldType==="linkField"){let n=t.oppositeLinkFieldsPlayedBy;if(n?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!n?.length)throw new Error(`[Internal] Field ${e} should have a player`);return n}else if(t.fieldType==="roleField"){if([...new Set(t.playedBy?.map(n=>n.thing))].length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!t.playedBy?.length)throw new Error(`[Internal] Field ${e} should have a player`);return t.playedBy}else throw new Error(`[Internal] Field ${e} is not a linkField or roleField`)};var Oe=(e,t,n)=>{let o=isArray(e[t])?e[t]:[e[t]];if(!o.every(l=>typeof l=="object"))if(o.every(l=>typeof l=="string")){let l=$t(t,n),[a]=l,d=e.$op==="create"?"link":"replace",h=a.thing,T=a.thingType;if(o.some(k=>k.startsWith("_:")))throw new Error("[Not supported] At least one child of a replace is a tempId");e[t]={$id:e[t],$op:d,$thing:h,$thingType:T,$bzId:`S_${v4()}`};}else throw new Error(`[Mutation Error] Replace can only be used with a single id or an array of ids. (Field: ${t} Nodes: ${JSON.stringify(o)} Parent: ${JSON.stringify(e,null,2)})`)};var dt=(e,t,n)=>{let o=A(n,t),{usedDataFields:l}=J(o,t);if(t.$op){if(t.$op==="create"&&t.$id)throw new Error("[Wrong format] Can't write to computed field $id. Try writing to the id field directly.");if(["unlink","delete","update"].includes(t.$op)&&e.$op==="create")throw new Error(`[Wrong format] Cannot ${t.$op} under a create`);if(t.$op==="delete"&&l.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&l.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var Pt=(e,t,n)=>{let o=A(n,t),{usedFields:l}=J(o,t);return t.$op?(dt(e,t,n),t.$op):t.$id||t.$filter?l.length>0?(dt(e,{...t,$op:"update"},n),"update"):(dt(e,{...t,$op:"link"},n),"link"):t.$tempId?l.length>0?(dt(e,{...t,$op:"create"},n),"create"):(dt(e,{...t,$op:"create"},n),"link"):(dt(e,{...t,$op:"create"},n),"create")};var Ae=(e,t)=>{let o=(isArray(e.$root)?e.$root:[e.$root]).map(l=>{let a=Pt(l,l,t);return {...{...l.$thing?{}:{$thing:l.$entity||l.$relation},...l.$thingType?{}:{$thingType:me(l,t)},...l.$op?{}:{$op:a},...l.$bzId?{}:{$bzId:`R_${v4()}`}},...l}});e.$root=isArray(e.$root)?o:o[0];};var St=(e,t)=>{let n=t[Qt];return isSet(n)?n.has("clean")?(Reflect.set(t,Qt,n.add("clean")),!0):!1:(Reflect.set(t,Qt,new Set(["clean"])),!0)};var qe=(e,t,n)=>{if(St("split_ids",e)){let o=(isArray(e[t])?e[t]:[e[t]]).flatMap(l=>{if(isObject(l)&&"$id"in l&&isArray(l.$id)){let a=l;if(A(n,a),!a.$bzId)throw new Error("[Internal Error] No bzId found");return a.$id.map((d,h)=>({...rt(a),$id:d,$bzId:`${a.$bzId}_${h}`,...v(a)}))}return l});(o.length>isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=o);}};var xe=(e,t,n,o)=>{let l=(isArray(e[t])?e[t]:[e[t]]).map(a=>{let d=$t(t,n),[h]=d,T=Pt(e,{...a,$thing:h.thing,$thingType:h.thingType},o),k=a.$bzId?a.$bzId:a.$tempId?a.$tempId:`N_${v4()}`;if(!n)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(n)}`);return {...a,[it]:n,$thing:h.thing,$thingType:h.thingType,$op:T,$bzId:k}});e[t]=isArray(e[t])?l:l[0];};var je=(e,t,n)=>{let o=e[t];o&&(isArray(o)?o:[o]).forEach(l=>{let a=A(n,l),{unidentifiedFields:d}=J(a,l),{computedFields:h,virtualFields:T}=a,k=listify(l,(s,f)=>f!==void 0?s:void 0),r=k.filter(s=>T?.includes(s));if(r.length>0)throw new Error(`Virtual fields can't be sent to DB: "${r.join(",")}"`);if(h.filter(s=>!k.includes(s)).forEach(s=>{let f=a.dataFields?.find(B=>B.path===s),c=a.linkFields?.find(B=>B.path===s)?.oppositeLinkFieldsPlayedBy[0],m="roles"in a?fe(a.roles,(B,S)=>B===s):void 0,p=f||c||m;if(!p)throw new Error(`no field Def for ${s}`);if(l.$op==="create"&&!l[s]){let B=ft({currentThing:l,fieldSchema:p,mandatoryDependencies:!0});l[s]=B;}}),d.length>0)throw new Error(`Unknown fields: [${d.join(",")}] in ${JSON.stringify(l)}`)});};var Ct=(e,t)=>{let n=A(t,e).hooks;if(n?.pre){let o=`on${ye(e.$op)}`;return n.pre.filter(d=>!d.triggers||d.triggers[o]?.()).flatMap(d=>d.actions)}return []};var We=(e,t,n,o)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(a=>{if("$thing"in a){let{requiredFields:d,enumFields:h,fnValidatedFields:T,dataFields:k}=A(n,a);if("$op"in a&&a.$op==="create"&&d.forEach(r=>{if(!(r in a))throw new Error(`[Validations] Required field "${r}" is missing.`)}),("$op"in a&&a.$op==="update"||a.$op==="create")&&h.forEach(r=>{if(r in a){let i=k?.find(s=>s.path===r)?.validations?.enum;if(!i)throw new Error(`[Validations] Enum field "${r}" is missing enum options.`);if(isArray(a[r]))a[r].some(s=>{if(!i.includes(s))throw new Error(`[Validations] Option "${s}" is not a valid option for field "${r}".`)});else if(i&&!i.includes(a[r]))throw new Error(`[Validations] Option "${a[r]}" is not a valid option for field "${r}".`)}}),("$op"in a&&a.$op==="update"||a.$op==="create")&&T.forEach(r=>{if(r in a)try{let i=k?.find(s=>s.path===r)?.validations?.fn;if(!i)throw new Error("Missing validation function.");if(!i(a[r]))throw new Error("Failed validation function.")}catch(i){throw new Error(`[Validations:attribute:${r}] ${i.message}`)}}),isObject(a)&&"$thing"in a){let r=a.$thing,i=a,s=clone(rt(e)),f=clone(rt(i)),u=o.mutation?.context||{};Ct(i,n).forEach(m=>{if(m.type==="validate"){if(m.severity!=="error")return;try{let p=m.fn(f,s,u);if(p===!1)throw new Error(`${m.message}.`);if(p!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(p){throw new Error(`[Validations:thing:${r}] ${p.message}`)}}});}}});};var He=(e,t,n,o)=>{let l=(isArray(e[t])?e[t]:[e[t]]).map(a=>{if(Lt(a)){let d=Ct(a,n).filter(r=>r.type==="transform"),h=clone(rt(e)),T=clone(rt(a)),k=o.mutation?.context||{};return d.forEach(r=>{let i=r.fn(T,h,k);Object.keys(i).length!==0&&(a={...T,...i,...v(a)});}),a}});e[t]=isArray(e[t])?l:l[0];};var Ke=(e,t,n)=>{let o=$t(t,n),[l]=o;e[t]={$thing:l.thing,$thingType:l.thingType,$op:"unlink",$bzId:`U_${v4()}`,[it]:n};};var ar=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(St("set_tempId",e))if(e.$tempId?.startsWith("_:")){let n=e.$tempId.substring(2);e.$tempId=n,e.$bzId=n;}else throw new Error('[Wrong format] TempIds must start with "_:"');else throw new Error("[Internal] TempId already modified")},lr=(e,t)=>{},te=(e,t,n)=>{let l=produce({$rootWrap:{$root:e}},a=>traverse(a,({value:d,parent:h,key:T,meta:k})=>{if(!(!h||!T)&&isObject(d)){if(!("$root"in d)){if(!("$thing"in d||"$entity"in d||"$relation"in d))throw T==="$root"?new Error("Root things must specify $entity or $relation"):new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(d)?current(d):d)}`)}let r=d;Object.keys(r).forEach(i=>{if(ar(r,i),i!=="$root"&&(i.startsWith("$")||i.startsWith("%")))return;let s=i!=="$root"?Kt(t,r,i):{fieldType:"rootField"};if(!s)throw new Error(`[Internal] Field ${i} not found in schema`);if("contentType"in s)return lr();if(["rootField","linkField","roleField"].includes(s.fieldType)){if(["linkField","roleField"].includes(s.fieldType)&&(r[i]===null?Ke(r,i,s):Oe(r,i,s)),s.fieldType==="rootField"){if(!("$root"in r))throw new Error(`[Internal] Field ${i} is a rootField but the object is not a root`);Ae(r,t);}let f=isArray(r[i])?r[i]:[r[i]],u=k.nodePath?.split(".").slice(1).join(".");f.forEach(m=>{if(m){if(s?.cardinality==="ONE"&&!m.$op&&!m.$id&&!m.$filter&&!m.$tempId&&r.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${u}.${i}`);if(m.$tempId&&!(m.$op===void 0||m.$op==="link"||m.$op==="create"||m.$op==="update"))throw new Error(`Invalid op ${m.$op} for tempId. TempIds can be created, or when created in another part of the same mutation. In the future maybe we can use them to catch stuff in the DB as well and group them under the same tempId.`)}}),["linkField","roleField"].includes(s.fieldType)&&xe(r,i,s,t),qe(r,i,t),["rootField","linkField","roleField"].includes(s.fieldType)&&je(r,i,t),(isArray(r[i])?r[i]:[r[i]]).forEach(m=>{let p=A(t,m),{unidentifiedFields:B,usedLinkFields:S,usedFields:$,fields:Q}=J(p,m);if($.forEach(C=>{if(!Q.includes(C))throw new Error(`[Schema] Field ${C} not found in the schema`)}),B.length>0)throw new Error(`Unknown fields: [${B.join(",")}] in ${JSON.stringify(d)}`);if(S.length>1){let C=p.linkFields?.filter(g=>S.includes(g.path));C?.some((g,b)=>C.some((F,y)=>{if(b!==y&&g.target!==F.target&&g.relation===F.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),He(r,i,t,n),We(r,i,t,n);}});}}));return isArray(l.$rootWrap.$root),l.$rootWrap.$root};var ve=async(e,t,n)=>{if(!e)throw new Error("TQL request not built");if(!(e.deletions&&e.deletionMatches||e.insertions))throw new Error("TQL request error, no things");let{session:o}=await wt(t,n),l=await o.transaction(TransactionType.WRITE);if(!l)throw new Error("Can't create transaction");let a=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,d=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;a&&await l.query.delete(a);let h=d&&l.query.insert(d);try{let T=h?await h.collect():void 0;return await l.commit(),await l.close(),{insertions:T}}catch(T){throw await l.close(),new Error(`Transaction failed: ${T.message}`)}};var Ue=async(e,t,n,o,l)=>{let a=[...t,...n],d=a.map(h=>{let T=e.insertions?.find(i=>i.get(`${h.$bzId}`))?.get(`${h.$bzId}`),k=h.$thing||h.$relation||h.$entity,r=k?kt(o,k):void 0;if(h.$op==="create"||h.$op==="update"||h.$op==="link"){if(h.$op!=="update"&&!T&&h.$id)return {$id:h.$id,$error:"Does not exist or it's not linked to the parent"};let i=T?.asThing().iid,s=Object.entries(h).filter(([u,c])=>!u.startsWith("$")).reduce((u,[c,m])=>{if(r?.dataFields?.find(B=>B.path===c)?.contentType==="JSON")return u[c]=JSON.parse(m),u;if(h.$thingType==="relation"){let B=a.filter(S=>S.$id&&S.$bzId===m);if(B.length>1)throw new Error(`Multiple things with the same bzId ${m}`);return B.length===1?(u[c]=B[0].$id,u):(u[c]=m,u)}return u[c]=m,u},{});if(l.mutation?.noMetadata)return s;let f=h.$tempId&&!h.$tempId.startsWith("_:")?{$tempId:`_:${h.$tempId}`}:{};return {$dbId:i,...h,...s,[h.path]:h.$id,...f}}if(h.$op==="delete"||h.$op==="unlink")return h;if(h.$op!=="match")throw new Error(`Unsupported op ${h.$op}`)}).filter(h=>h);return clone(d)};var Je=e=>{let t=({value:n})=>(n&&typeof n=="object"&&"$id"in n&&(Object.keys(n).filter(a=>a.startsWith("$")).forEach(a=>delete n[a]),Object.keys(n).filter(a=>typeof a=="symbol").forEach(a=>delete n[a])),n);return produce(e,n=>traverse(n,t))};var Xe=async(e,t)=>{let n=r=>{let i=[],s=[],f=p=>{if(p.$id)return p.$id;let B=A(t,p),{idFields:S}=B;if(!S)throw new Error(`no idFields: ${JSON.stringify(p)}`);let[$]=S;if(!$)throw new Error(`no idField: ${JSON.stringify(p)}`);let Q=B.dataFields?.find(b=>b.path===$),C=ft({currentThing:p,fieldSchema:Q,mandatoryDependencies:!0}),g=p[$]||p.$id||C;if(!g)throw new Error(`no idValue: ${JSON.stringify(p)}`);return g},u=p=>{if(p.$op==="create"){let B=f(p);if(i.find(S=>S.$id===B&&S.$op==="create"))throw new Error(`Duplicate id ${B} for node ${JSON.stringify(p)}`);if(s.find(S=>S.$bzId===p.$bzId))throw new Error(`Duplicate $bzId ${p.$bzId} for node ${JSON.stringify(p)}`);i.push({...p,$id:B});return}p.$tempId&&p.$op==="match"||i.push(p);},c=p=>{if(p.$op==="create"){let B=f(p);if(i.find(S=>S.$id===B),s.find(S=>S.$bzId===p.$bzId))throw new Error(`Duplicate %bzId ${p.$bzIdd} for edge ${JSON.stringify(p)}`);s.push({...p,$id:B});return}s.push(p);};return traverse(r,({value:p,parent:B,meta:S})=>{if(!isObject(p))return;let $=p;if($.$thing){if(!$.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify($)}`);if(!$.$bzId)throw new Error("[internal error] BzId not found");let Q=A(t,$),{dataFields:C,roleFields:g,linkFields:b,usedFields:F}=J(Q,$),y=()=>{if($.$op==="create"||$.$op==="delete")return $.$op;if($.$op==="update"){let L=F.filter(w=>C?.includes(w)),E=F.filter(w=>g?.includes(w)),I=F.filter(w=>b?.includes(w));if(L.length>0)return "update";if(E.length>0||I.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify($)}`)}return "match"},P={...$.$id&&{$id:$.$id},...$.$tempId&&{$tempId:$.$tempId},...$.$filter&&{$filter:$.$filter},$thing:$.$thing,...$.$thingType&&{$thingType:$.$thingType},...shake(pick($,C||[""])),$op:y(),$bzId:$.$bzId};u(P);let M=$[it];if(M?.fieldType==="linkField"){if(($.$op==="link"||$.$op==="unlink")&&($.$id||$.$filter)){if($.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");i.push({...$,$op:"match"});}let L=M.relation===$.$thing,E=L?$.$bzId:`LT_${v4()}`,w=ge(r,B,S).$bzId;if(!w)throw new Error("No parent id found");let O=()=>{if($.$op==="delete")return L?"match":"delete";if($.$op==="unlink")return L?"unlink":"delete";if($.$op==="link"||$.$op==="create")return L?"link":"create";if($.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},R=A(t,{$thing:M.relation,$thingType:"relation"});if(!Object.keys(R.roles).includes(M.plays))throw new Error(`[Wrong format] Field ${M.plays} is not a role of relation ${M.relation}`);let N={$bzId:E,$thing:M.relation,$thingType:"relation",...$.$tempId?{$tempId:$.$tempId}:{},$op:O(),...L?{}:{[M.path]:$.$bzId},[M.plays]:w,[it]:M,[ct]:"linkField"};c(N),($.$op==="unlink"||O()==="unlink")&&L&&c({$thing:M.relation,$thingType:"relation",$bzId:E,$op:"match",[M.plays]:w,[it]:M,[ct]:"linkField"});}if($.$thingType==="relation"){let L=Ft($,(w,O)=>g.includes(w)),E=mapEntries(L,(w,O)=>isArray(O)?[w,O]:isObject(O)?[w,O.$bzId]:[w,O]),I=Ft(p,(w,O)=>w.startsWith("$")||w.startsWith("Symbol"));if(Object.keys(L).filter(w=>!w.startsWith("$")).length>0){if($.$op==="create"||$.$op==="delete"){let w=()=>{if($.$op==="create")return "link";if($.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},O=A(t,$).roles,R=mapEntries(E,(N,D)=>{let _=O[N]?.cardinality;if(!_)throw new Error(`Role ${N} not found in schema`);if(Array.isArray(D)){if(_==="ONE"){if(D.length>1)throw new Error(`[Error] Role ${N} is not a MANY relation`);return [N,D[0].$bzId||D[0]]}return [N,D.map(X=>X.$bzId||X)]}return [N,D.$bzId||D]}),z={...I,$thing:$.$thing,$thingType:"relation",$op:w(),...R,$bzId:$.$bzId,[ct]:"roleField"};c(z);return}if($.$op==="match"||$.$op==="update"&&Object.keys(L).length>0){let w=0;Object.entries(L).forEach(([O,R])=>{let z=isArray(R)?R:[R],N=D=>D==="create"||D==="replace"?"link":D;z.forEach(D=>{if(!D)return;let _=N(D.$op);if(_==="replace")throw new Error("Not supported yet: replace on roleFields");if(_==="unlink"&&w>0)throw w+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let X={...I,$thing:$.$thing,$thingType:"relation",$op:_==="delete"?"unlink":_,[O]:D.$bzId,$bzId:$.$bzId,[ct]:"roleField"};c(X);});});}}}}}),[i,s]},[o,l]=n(e),a=o.reduce((r,i)=>{if(!i.$bzId)return [...r,i];let s=r.findIndex(f=>f.$bzId===i.$bzId);if(s===-1)return [...r,i];if(r[s].$op==="create"&&i.$op==="match")return r;if(r[s].$op==="match"&&(i.$op==="create"||i.$op==="match"))return [...r.slice(0,s),i,...r.slice(s+1)];throw new Error(`[Wrong format] Wrong operation combination for $tempId "${i.$tempId}". Existing: ${r[s].$op}. Current: ${i.$op}`)},[]),d=l.reduce((r,i)=>{let s=r.find(f=>(f.$id&&f.$id===i.$id||f.$bzId&&f.$bzId===i.$bzId)&&f.$thing===i.$thing&&f.$op===i.$op);if(s){let f={...s};return Object.keys(i).forEach(c=>{if(typeof c=="symbol"||c.startsWith("$"))return;let m=s[c],p=i[c];Array.isArray(m)&&Array.isArray(p)?f[c]=Array.from(new Set([...m,...p])):!Array.isArray(m)&&Array.isArray(p)?m!==void 0?f[c]=Array.from(new Set([m,...p])):f[c]=p:Array.isArray(m)&&!Array.isArray(p)?p!==void 0&&(f[c]=Array.from(new Set([...m,p]))):m!==null&&p!==null&&m!==void 0&&p!==void 0?f[c]=Array.from(new Set([m,p])):m==null&&(f[c]=p);}),[...r.filter(c=>!((c.$id&&c.$id===i.$id||c.$bzId&&c.$bzId===i.$bzId)&&c.$thing===i.$thing&&c.$op===i.$op)),f]}return [...r,i]},[]);a.forEach(r=>{if((r.$thingType==="relation"||"relation"in r)&&d.filter(i=>i.$bzId===r.$bzId||i.$tempId&&i.$tempId===r.$tempId).length===0){if(r.$op==="delete"||r.$op==="match"||r.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(Je(r))}`)}});let h=[...a,...d],T=new Set(h.filter(r=>r.$tempId).map(r=>r.$tempId)),k=Array.from(T).filter(r=>!h.some(i=>i.$tempId===r&&i.$op==="create"));if(k.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${k.join(", ")}`);return {mergedThings:a,mergedEdges:d}};var tn=async(e,t,n)=>{let o=s=>{let f=s.$op,u=`$${s.$bzId}`,c=A(n,s),{idFields:m,defaultDBConnector:p}=c,B=p?.path||s.$thing,S=s.$id,$=m?.[0],Q=listify(s,(L,E)=>{if(L.startsWith("$")||L.startsWith("%")||L===$||E===void 0||E===null)return "";let I=c.dataFields?.find(R=>R.path===L);if(!I?.path)return "";let O=I.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(I.contentType))return `has ${O} '${E}'`;if(["NUMBER","BOOLEAN"].includes(I.contentType))return `has ${O} ${E}`;if(I.contentType==="DATE"){if(Number.isNaN(E.valueOf()))throw new Error("Invalid format, Nan Date");return E instanceof Date?`has ${O} ${E.toISOString().replace("Z","")}`:`has ${O} ${new Date(E).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${I.contentType}`)}).filter(L=>L),C=`${u}-atts`,g=listify(s,L=>{if(L.startsWith("$")||L.startsWith("%")||L===$)return "";let E=c.dataFields?.find(O=>O.path===L);if(!E?.path)return "";let w=E.dbPath;return `{${C} isa ${w};}`}).filter(L=>L),b=isArray(S)?`like '${S.join("|")}'`:`'${S}'`,F=S?[`has ${$} ${b}`]:[],y=[...F,...Q].filter(L=>L).join(","),P=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${u} isa ${[B,...F].filter(L=>L).join(",")};`;if(f==="update"){if(!g.length)throw new Error("update without attributes");return `${u} isa ${[B,...F].filter(L=>L).join(",")}, has ${C};
|
|
60
|
-
${g.join(" or ")};`}return ""},M=()=>f==="update"||f==="link"||f==="match"?`${u} isa ${[B,...F].filter(L=>L).join(",")};`:"";if(Lt(s))return {op:f,deletionMatch:P(),insertionMatch:M(),insertion:f==="create"?`${u} isa ${[B,y].filter(L=>L).join(",")};`:f==="update"&&Q.length?`${u} ${Q.join(",")};`:"",deletion:f==="delete"?`${u} isa ${B};`:f==="update"&&g.length?`${u} has ${C};`:""};throw new Error("in attributes")},l=s=>{let f=s.$op,u=A(n,s),c=`$${s.$bzId}`,m=s.$id,p=u.defaultDBConnector?.path||s.$thing,B="roles"in u?listify(u.roles,E=>E):[],S="roles"in u?mapEntries(u.roles,(E,I)=>[E,I.dbConnector?.path||E]):{},$=listify(s,(E,I)=>{if(!B.includes(E))return null;if(!("roles"in u))throw new Error("This should have roles! ");let w=S[E];return Array.isArray(I)?I.map(O=>({path:w,id:O})):{path:w,id:I}}).filter(E=>E).flat(),Q=$.map(E=>{if(!E?.path)throw new Error("Object without path");return `${E.path}: $${E.id}`}),C=$.length>0?`( ${Q.join(" , ")} )`:"",g=s[ct];if(!g)throw new Error("[internal error] Symbol edgeType not defined");let b=C?`${c} ${C} ${g==="linkField"||f==="delete"||f==="unlink"?`isa ${p}`:""}`:"",F=`${c} ${g==="linkField"||f==="delete"?`isa ${p}`:""}`,y=()=>b?f==="link"?`${b};`:f==="create"?`${b}, has id '${m}';`:"":"",P=()=>b&&f==="match"?`${b};`:"",M=()=>b?f==="delete"?`${b};`:f==="match"?`${b};`:"":"",L=()=>b?f==="delete"?`${F};`:f==="unlink"?`${c} ${C};`:"":"";return {deletionMatch:M(),insertionMatch:P(),deletion:L(),insertion:y(),op:""}},a=(s,f)=>{let u=f==="edges"?l:o;if(Array.isArray(s))return s.map($=>{let{preDeletionBatch:Q,insertionMatch:C,deletionMatch:g,insertion:b,deletion:F}=u($);return shake({preDeletionBatch:Q,insertionMatch:C,deletionMatch:g,insertion:b,deletion:F},y=>!y)}).filter($=>$);let{preDeletionBatch:c,insertionMatch:m,deletionMatch:p,insertion:B,deletion:S}=u(s);return shake({preDeletionBatch:c,insertionMatch:m,deletionMatch:p,insertion:B,deletion:S},$=>!$)},d=a(e),h=Array.isArray(d)?d:[d],T=a(t,"edges"),k=Array.isArray(T)?T:[T],r=[...h,...k];return shake({insertionMatches:r.map(s=>s.insertionMatch).join(" ").trim(),deletionMatches:r.map(s=>s.deletionMatch).join(" ").trim(),insertions:r.map(s=>s.insertion).join(" ").trim(),deletions:r.map(s=>s.deletion).join(" ").trim()},s=>!s)};var Br=Symbol.for("grandChildOfCreate"),en=async(e,t,n,o)=>{let l=(g,b)=>Object.keys(g).filter(F=>F.startsWith("$")?!1:b?!A(t,g).dataFields?.find(P=>P.path===F):!0);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(n.mutation?.preQuery===!1)return;let a=[];if(traverse(e,({parent:g,key:b,value:F})=>{g&&b&&!b.includes("$")&&isObject(g)?(Array.isArray(g[b])?g[b]:[g[b]]).forEach(P=>{if(isObject(P)){if(g.$op!=="create")a.includes(P.$op)||a.push(P.$op);else if(P.$op==="delete"||P.$op==="unlink")throw new Error(`Cannot ${P.$op} under a create`)}}):!g&&isObject(F)&&(a.includes(F.$op)||a.push(F.$op));}),!a.includes("delete")&&!a.includes("unlink")&&!a.includes("replace")&&!a.includes("update")&&!a.includes("link"))return;let h=(g=>{let b=(F,y)=>{let P=[],M={},L=["$op","$bzId","$parentKey"],E=["$relation","$entity","$id",...L];for(let I in F)if(!L.includes(I)&&!(E.includes(I)&&!y))if(!I.includes("$")&&(isObject(F[I])||Array.isArray(F[I]))){let w=F[I];Array.isArray(w)&&w.length>0?w.forEach(O=>{P.push({$path:I,...b(O)});}):P.push({$path:I,...b(w)});}else M[I]=F[I];return {...M,$fields:P}};return g.map(F=>b(F,!0))})(Array.isArray(e)?e:[e]),T=await It(h,n,t,o),k=(g,b)=>{let F=g.$id||g.id||g.$bzId;if(g.$objectPath){let{$objectPath:y}=g,P=y?.beforePath||"root",M=Array.isArray(y.ids)?`[${y.ids}]`:y.ids;return {beforePath:`${P}.${M}___${y.key}`,ids:F,key:b}}else return {beforePath:"root",ids:F,key:b}},r=(g,b)=>{let F=g?.beforePath||"root",y=b||(Array.isArray(g?.ids)?`[${g?.ids}]`:g?.ids);return `${F}.${y}___${g?.key}`},i=g=>{if(g.includes("[")&&g.includes("]")){let[b,F,y]=g.split(/[[\]]/);return F.split(",").map(M=>`${b}${M}${y}`)}else return [g]},s={};(g=>produce(g,b=>traverse(b,F=>{let{key:y,parent:P}=F;if(P&&y&&P.$id&&!y.includes("$")){let M=k(P,y),L=r(M);if(Array.isArray(P[y])){let E=[];P[y].forEach(I=>{isObject(I)?(I.$objectPath=M,E.push(I.$id.toString())):I&&E.push(I.toString());}),s[L]={$objectPath:M,$ids:E};}else {let E=P[y];isObject(E)?(s[L]={$objectPath:M,$ids:[E.$id.toString()]},E.$objectPath=M):E&&(s[L]={$objectPath:M,$ids:[E.toString()]});}}})))(T||{});let u=g=>produce(g,b=>traverse(b,F=>{let{key:y,value:P,parent:M}=F;M&&y&&!y.includes("$")&&(Array.isArray(P)||isObject(P))&&!Array.isArray(M)&&(Array.isArray(M[y])?M[y].forEach(L=>{typeof L!="string"&&(L.$objectPath=k(M,y),L.$parentIsCreate=M.$op==="create",L[Br]=M.$parentIsCreate||M[Symbol.for("grandChildOfCreate")]);}):isObject(M[y])&&(M[y].$parentIsCreate=M.$op==="create",M[y][Symbol.for("grandChildOfCreate")]=M.$parentIsCreate||M[Symbol.for("grandChildOfCreate")],M[y].$objectPath=k(M,y)));})),c=u(e),p=(g=>{let b=(M,L)=>{let E=[];M.filter(R=>R).forEach(R=>{let z=Object.keys(R).filter(N=>!N.startsWith("$")).length;if(Array.isArray(R.$id)&&z>0){let N=R.$id.map(D=>({...R,$id:D}));E=[...E,...N];}else E.push({...R});});let I=[],w=[],O=E.filter(R=>{let N=["delete","update","unlink"].includes(R.$op||""),D=l(R,!0).length;if((!R.$id||Array.isArray(R.$id)&&D>0||R.$filter)&&N)return !0;w.push({...R});});return O.length>0?O.forEach(R=>{let N=(j=>{let yt=(()=>{let V={};for(let x in j){let nt=A(t,j);!x.startsWith("$")&&nt.dataFields?.find(ht=>ht.path===x)&&(V[x]=j[x]);}return V})(),gt=Object.keys(j),et=gt.filter(V=>!V.startsWith("$")),xt=[],Tt=(V,x)=>{if(V===et.length){let ht={...x};gt.forEach(H=>{H.startsWith("$")&&(ht[H]=j[H]);}),xt.push(ht);return}let nt={...x,[et[V]]:j[et[V]],...v(x),...yt};Tt(V+1,nt),Tt(V+1,x);};return Tt(0,{...v(j)}),xt})(R).filter(j=>!(j.$op==="update"&&Object.keys(j).filter(at=>!at.startsWith("$")).length===0)),D=[],_=r(R.$objectPath),tt=s[_]?s[_].$ids:[],q=N.map((j,at)=>{let yt=A(t,j),et=Object.keys(j).filter(x=>!x.includes("$")&&!yt.dataFields?.some(nt=>nt.path===x)).map(x=>(Array.isArray(j[x])?j[x].length>1?j[x].filter(H=>!H.$id||Array.isArray(H.$id)||H.$filter):j[x]:[j[x]]).map(H=>{let jt=r(H.$objectPath);return {idsToKey:(Nt=>{let ae=[],Et=Nt.split("."),Tn=Et.slice(0,Et.length-1).join("."),Mn=Et.slice(Et.length-1,Et.length)[0].split("___")[1];for(let zt in s)if(zt.startsWith(Tn)&&zt.endsWith(Mn)){let Wt=zt.split("."),kn=Wt.slice(Wt.length-1,Wt.length)[0].split("___")[0];ae.push(kn);}return ae})(jt),key:x,multiple:H}})).filter(x=>x!==void 0),V=(x=>{let nt=x.map(H=>H.map(lt=>lt.idsToKey));return (H=>H.length>0?H.reduce((lt,Bt)=>lt.concat(Bt),[]).reduce((lt,Bt)=>lt?Bt.filter(Nt=>lt.includes(Nt)):Bt):[])(nt)})(et).filter(x=>!D.includes(x));if(D=[...D,...V],tt=tt.filter(x=>!V.includes(x)),at===N.length-1&&tt.length>0)return {...j,$id:tt,$bzId:`T1_${v4()}`,...v(j)};if(V.length>0)return {...j,$id:V,$bzId:`T2_${v4()}`,...v(j)}}).filter(j=>j!==void 0),bn=(()=>{if(q.length===0&&!L?.$id)return O;if(q.length===0&&L?.$id){let j=Array.isArray(L.$id)?L.$id:[L.$id],at=[];return j.forEach(yt=>{let gt=r({...R.$objectPath,ids:yt}),et=s[gt];et&&at.push({...R,$id:et.$ids,...v(R),$bzId:`T_${v4()}`});}),at}else return q.filter(j=>j!==void 0)})();I=[...w,...bn].map(F);}):I=E.map(F),I},F=M=>{let L={...M,$bzId:M.$tempId??`T3_${v4()}`,...v(M)},E=A(t,M);return Object.keys(M).filter(I=>!I.includes("$")&&!E.dataFields?.some(w=>w.path===I)).forEach(I=>{let w=Array.isArray(M[I])?M[I]:[M[I]],O=b(w,M);L[I]=O.length>0?O:void 0;}),L},y=[];return g.forEach(M=>{y=[...y,...b([M])];}),y.map(M=>F(M))})(Array.isArray(c)?c:[c]),B=g=>g.map(b=>{let F=l(b,!0),y={...b};return F.forEach(P=>{let M=Array.isArray(b[P])?b[P]:[b[P]],L=[],E=[],I=[],w={},O=vt(t,b,P);M.filter(q=>q).forEach(q=>{q.$op==="replace"&&q.$id?(w=q,Array.isArray(q.$id)?E=[...E,...q.$id]:E.push(q.$id)):q.$op==="create"&&O==="ONE"&&q.id?(w=q,Array.isArray(q.id)?I=[...E,...q.id]:I.push(q.id)):L.push(q);});let R=r(w.$objectPath),N=i(R).map(q=>s[q]),D=[];N.filter(q=>q!=null).forEach(q=>{D=[...D,...q.$ids];});let _=D.filter(q=>!E.includes(q)),X=E.filter(q=>!D.includes(q)),tt=v(w);_.length>0&&L.push({...w,$op:"unlink",$id:_,$bzId:`T4_${v4()}`,id:void 0,...tt}),X.length>0&&X.forEach(q=>{L.push({...w,$op:"link",$id:q,$bzId:`T5_${v4()}`,...tt});}),I.length>0&&I.forEach(q=>{L.push({...w,$op:"create",id:q,$bzId:`T6_${v4()}`,...tt});}),y[P]=B(L);}),y}),S=u(B(u(p)));return (g=>produce(g,b=>traverse(b,F=>{let{key:y,value:P,parent:M}=F;y&&M&&!y?.includes("$")&&(Array.isArray(P)||isObject(P))&&!Array.isArray(M)&&(Array.isArray(P)?P:[P]).forEach(E=>{let I=s[r(E.$objectPath)],w=(z,N)=>z.every(D=>N.includes(D)),O=E.$id?Array.isArray(E.$id)?w(E.$id,I?I.$ids:[]):I?.$ids.includes(E.$id):I,R=vt(t,M,E.$objectPath.key);if(E.$op==="link"&&O&&R==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${r(E.$objectPath)}" because it is already occupied.`);if(E.$op)switch(E.$op){case"delete":if(!O&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${E.$id}" because it is not linked to $id:"${M.$id}"`);break;case"update":if(!O&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${E.$id}" because it is not linked to $id:"${M.$id}"`);break;case"unlink":if(!O&&!n.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${E.$id}" because it is not linked to $id:"${M.$id}"`);break;case"link":if(O)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${E.$id}" because it is already linked to $id:"${M.$id}"`);break;}});})))(S),(g=>produce(g,b=>traverse(b,F=>{let{value:y,meta:P}=F;isObject(y)&&(y[Symbol.for("path")]=P.nodePath,delete y.$objectPath,delete y.$parentIsCreate);})))(S)};function W(e){return {enumerable:!0,value:e}}function nn(e){return {enumerable:!0,writable:!0,value:e}}var mt={},Er=()=>!0,rn=()=>({}),sn=e=>e,Fr=(e,t,n,o)=>e.apply(n,o)&&t.apply(n,o),wr=(e,t,n,[o,l])=>t.call(n,e.call(n,o,l),l),ot=(e,t)=>Object.freeze(Object.create(e,t));function on(e,t,n){return e.reduce((o,l)=>function(...a){return n(o,l,this,a)},t)}function an(e){return ot(this,{fn:W(e)})}var ln={},Y=an.bind(ln);var cn={},dn=an.bind(cn);function At(e,t){return t.filter(n=>e.isPrototypeOf(n))}function pn(e,t,...n){let o=on(At(cn,n).map(a=>a.fn),Er,Fr),l=on(At(ln,n).map(a=>a.fn),sn,wr);return ot(this,{from:W(e),to:W(t),guards:W(o),reducers:W(l)})}var un={},hn={},G=pn.bind(un);pn.bind(hn,null);function br(e,t,n){return re(t,e,n,this.immediates)||e}function fn(e){let t=new Map;for(let n of e)t.has(n.from)||t.set(n.from,[]),t.get(n.from).push(n);return t}var Tr={enter:sn};function $n(...e){let t=At(un,e),n=At(hn,e),o={final:W(e.length===0),transitions:W(fn(t))};return n.length&&(o.immediates=W(n),o.enter=W(br)),ot(Tr,o)}var Mr={enter(e,t,n){let o=this.fn.call(t,t.context,n);return ne.isPrototypeOf(o)?ot(mn,{machine:W(o),transitions:W(this.transitions)}).enter(e,t,n):(o.then(l=>t.send({type:"done",data:l})).catch(l=>t.send({type:"error",error:l})),e)}},mn={enter(e,t,n){if(t.child=ie(this.machine,o=>{t.onChange(o),t.child==o&&o.machine.state.value.final&&(delete t.child,t.send({type:"done",data:o.context}));},t.context,n),t.child.machine.state.value.final){let o=t.child.context;return delete t.child,re(t,e,{type:"done",data:o},this.transitions.get("done"))}return e}};function st(e,...t){let n=W(fn(t));return ne.isPrototypeOf(e)?ot(mn,{machine:W(e),transitions:n}):ot(Mr,{fn:W(e),transitions:n})}var ne={get state(){return {name:this.current,value:this.states[this.current]}}};function yn(e,t,n=rn){return typeof e!="string"&&(n=t||rn,t=e,e=Object.keys(t)[0]),mt._create&&mt._create(e,t),ot(ne,{context:W(n),current:W(e),states:W(t)})}function re(e,t,n,o){let{context:l}=e;for(let{to:a,guards:d,reducers:h}of o)if(d(l,n)){e.context=h.call(e,l,n);let T=t.original||t,k=ot(T,{current:W(a),original:{value:T}});mt._onEnter&&mt._onEnter(t,a,e.context,l,n);let r=k.state.value;return e.machine=k,e.onChange(e),r.enter(k,e,n)}}function kr(e,t){let n=t.type||t,{machine:o}=e,{value:l,name:a}=o.state;return l.transitions.has(n)?re(e,o,t,l.transitions.get(n))||o:(mt._send&&mt._send(n,a),o)}var Lr={send(e){kr(this,e);}};function ie(e,t,n,o){let l=Object.create(Lr,{machine:nn(e),context:nn(e.context(n,o)),onChange:W(t)});return l.send=l.send.bind(l),l.machine=l.machine.state.value.enter(l.machine,l,o),l}var gn=(e,t)=>produce(e,o=>qt(t,o)),qt=(e,t,n)=>{if(typeof t=="string")return;if(Array.isArray(t)){t.forEach(l=>qt(e,l,n));return}let o=kt(e,n||t.$entity||t.$relation||t.$thing);Object.entries(t).forEach(([l])=>{l.startsWith("$")||Ir(e,t,l,o);});},Ir=(e,t,n,o)=>{let l=t[n];if(!l)return;let a=o.dataFields?.find(h=>h.path===n);if(a){a.contentType==="JSON"&&l!=null&&(t[n]=JSON.stringify(l));return}let d=o.linkFields?.find(h=>h.path===n);if(d){let h=d.oppositeLinkFieldsPlayedBy[0]?.thing;qt(e,l,h);return}if(o.thingType==="relation"){let h=o.roles[n],[T]=h.playedBy||[];if(!T)throw new Error(`Role ${h.name} in ${o} is not played by anything`);qt(e,l,T.thing);}};var Bn=$n,Dt=(e,t)=>t.data?{...e,bql:{...e.bql,current:t.data}}:e,Pr=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Sr=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),Cr=(e,t)=>({...e,typeDB:{...e.typeDB,tqlMutation:t.data}}),Or=(e,t)=>({...e,typeDB:{...e.typeDB,tqlRes:t.data}}),Rr=async e=>Object.keys(e.bql.current).length?te(e.bql.current,e.schema,e.config):te(e.bql.raw,e.schema,e.config),Ar=async e=>en(e.bql.current,e.schema,e.config,e.handles),qr=async e=>Xe(e.bql.current,e.schema),Dr=async e=>tn(e.bql.things,e.bql.edges,e.schema),xr=async e=>ve(e.typeDB.tqlMutation,e.handles,e.config),jr=async e=>Ue(e.typeDB.tqlRes,e.bql.things,e.bql.edges,e.schema,e.config),Nr=()=>!0,ut=G("error","error",Y((e,t)=>({...e,error:t.error}))),zr=yn("stringify",{stringify:st(async e=>gn(e.bql.raw,e.schema),G("done","enrich",Y(Dt)),ut),enrich:st(Rr,G("done","preQuery",dn(Nr),Y(Dt)),G("done","parseBQL",Y(Dt)),ut),preQuery:st(Ar,G("done","parseBQL",Y(Dt)),ut),parseBQL:st(qr,G("done","buildMutation",Y(Sr)),ut),buildMutation:st(Dr,G("done","runMutation",Y(Cr)),ut),runMutation:st(xr,G("done","parseMutation",Y(Or)),ut),parseMutation:st(jr,G("done","success",Y(Pr)),ut),success:Bn(),error:Bn()},e=>e),Wr=async e=>new Promise((t,n)=>{ie(zr,o=>{o.machine.state.name==="success"&&t(o.context),o.machine.state.name==="error"&&n(o.context);},e);}),En=async(e,t,n,o)=>Wr({bql:{raw:e,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:t,config:n,handles:o,depthLevel:0,error:null});enableMapSet();var se=class{schema;config;dbHandles;constructor({schema:t,config:n}){this.schema=t,this.config=n;}getDbHandles=()=>this.dbHandles;init=async()=>{let t={typeDB:new Map,surrealDB:new Map};await Promise.all(this.config.dbConnectors.map(async o=>{if(o.provider==="typeDB"&&o.dbName){let[l,a]=await tryit(TypeDB.coreDriver)(o.url);if(l){let d=`[BORM:${o.provider}:${o.dbName}:core] ${l.message??"Can't create TypeDB Client"}`;throw new Error(d)}try{let d=await a.session(o.dbName,SessionType.DATA);t.typeDB.set(o.id,{client:a,session:d});}catch(d){let h=`[BORM:${o.provider}:${o.dbName}:session] ${(d.messageTemplate?._messageBody()||d.message)??"Can't create TypeDB Session"}`;throw new Error(h)}}if(o.provider==="typeDBCluster"&&o.dbName){let[l,a]=await tryit(TypeDB.cloudDriver)(o.addresses,o.credentials);if(l){let d=`[BORM:${o.provider}:${o.dbName}:core] ${l.message??"Can't create TypeDB Cluster Client"}`;throw new Error(d)}try{let d=await a.session(o.dbName,SessionType.DATA);t.typeDB.set(o.id,{client:a,session:d});}catch(d){let h=`[BORM:${o.provider}:${o.dbName}:session] ${(d.messageTemplate?._messageBody()||d.message)??"Can't create TypeDB Session"}`;throw new Error(h)}}}));let n=$e(this.schema,t);this.schema=n,this.dbHandles=t;};#t=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#t(),this.schema);define=async()=>(await this.#t(),ce(this.config,this.schema,this.dbHandles));query=async(t,n)=>{await this.#t();let o={...this.config,query:{..._t.query,...this.config.query,...n}};return It(t,o,this.schema,this.dbHandles)};mutate=async(t,n)=>{await this.#t();let o={...this.config,mutation:{..._t.mutation,...this.config.mutation,...n}},[l,a]=await tryit(En)(t,this.schema,o,this.dbHandles);if(l){let h=new Error(l.error.message);throw h.stack=l.error.stack,h}return a.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:n})=>{n.isOpen()&&await n.close(),await t.close();});}},ia=se;//! Todo: delete when this works with the new $thing and $thingType fields
|
|
35
|
+
${g}`})(),n=e.dbConnectors[0].id,l=r.typeDB.get(n)?.session,s=r.typeDB.get(n)?.client;if(!l){console.log("Session Status: ","NO SESSION");return}await l.close();let[{dbName:c}]=e.dbConnectors;await(await s.databases.get(c)).delete(),await s.databases.create(c);let u=await s.session(e.dbConnectors[0].dbName,SessionType.SCHEMA),h=await u.transaction(TransactionType.WRITE);await h.query.define(o),await h.commit(),await h.close();let a=await u.transaction(TransactionType.READ);(await(await a.query.match("match $a sub thing;")).collect()).forEach(async g=>{g.get("a");}),await a.close();};var Ct={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var Pt=(e,t,r)=>r?t:`${e}\xB7${t}`;var qt=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))))[0],Ce=(e,t)=>Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))),Ot=(e,t)=>{let r=[],i=produce(e,n=>traverse(n,({key:l,value:s,meta:c})=>{if(c.depth===2&&(l&&(s.dataFields=s.dataFields?.map(p=>({...p,cardinality:p.cardinality||"ONE",dbPath:Pt(l,p.path,p.shared)}))),s.extends)){if(!s.defaultDBConnector.as)throw new Error(`[Schema] ${l} is extending a thing but missing the "as" property in its defaultDBConnector`);let p=n.entities[s.extends]||n.relations[s.extends];if(s.allExtends=[s.extends,...p.allExtends||[]],s.idFields=p.idFields?(s.idFields||[]).concat(p.idFields):s.idFields,s.dataFields=p.dataFields?(s.dataFields||[]).concat(p.dataFields.map(u=>{let h=s.extends,a=e.entities[h]||e.relations[h];for(;!a.dataFields?.find(f=>f.path===u.path);)h="extends"in a?a.extends:void 0,a=e.entities[h]||e.relations[h];return {...u,dbPath:Pt(h,u.path,u.shared)}})):s.dataFields,s.linkFields=p.linkFields?(s.linkFields||[]).concat(p.linkFields):s.linkFields,"roles"in p){let u=s,h=p;u.roles=u.roles||{},u.roles={...u.roles,...h.roles},Object.keys(u.roles).length===0&&(u.roles={});}p?.hooks?.pre&&(s.hooks=s.hooks||{},s.hooks.pre=s.hooks.pre||[],s.hooks.pre=[...p?.hooks?.pre||[],...s?.hooks?.pre||[]]);}},{traversalType:"breadth-first"}));return traverse(e,({key:n,value:l,meta:s})=>{if(n==="linkFields"){let p=(()=>{if(!s.nodePath)throw new Error("No path");let[h,a]=s.nodePath.split(".");return {thing:a,thingType:h==="entities"?"entity":h==="relations"?"relation":""}})(),u=Array.isArray(l)?l.map(h=>({...h,...p})):[{...l,...p}];r.push(...u);}}),produce(i,n=>traverse(n,({value:l,key:s,meta:c})=>{if(c.depth===2&&l.idFields&&!l.id){l.name=s;let p=()=>{if(c.nodePath?.split(".")[0]==="entities")return "entity";if(c.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};l.thingType=p();let u=Object.keys(t).find(h=>t[h]?.get(l.defaultDBConnector.id));l.db=u,l.dbContext=Ct[u],l.computedFields=[],l.virtualFields=[],l.requiredFields=[],l.enumFields=[],l.fnValidatedFields=[],"roles"in l&&Object.entries(l.roles).forEach(([a,f])=>{f.fieldType="roleField",f.playedBy=r.filter(d=>d.relation===s&&d.plays===a)||[],f.name=a;}),"linkFields"in l&&l.linkFields&&l.linkFields?.forEach(a=>{if(a.fieldType="linkField",a.target==="relation"){a.oppositeLinkFieldsPlayedBy=[{plays:a.path,thing:a.relation,thingType:"relation"}];return}let f=r.filter($=>$.relation===a.relation&&$.plays!==a.plays)||[];a.oppositeLinkFieldsPlayedBy=f;let{filter:d}=a;a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter($=>$.target==="role"),d&&Array.isArray(d)&&(a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter($=>d.some(g=>$.thing===g.$role)),a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter($=>d.some(g=>$.thing===g.$thing))),d&&!Array.isArray(d)&&(a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter($=>$.$role===d.$role),a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter($=>$.thing===d.$thing));});}if(typeof l=="object"&&"playedBy"in l){let p=[...new Set(l.playedBy.map(u=>u.thing))];if(p.length>1)throw new Error(`[Schema] roleFields can be only played by one thing. Role: ${s}, path:${c.nodePath}, played by: ${p.join(", ")}`);if(l.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${s}, path:${c.nodePath}`)}if(c.depth===4){let[p,u]=c.nodePath?.split(".")||[],h=n[p][u];l.validations&&(l.validations.required&&h.requiredFields.push(l.path),l.validations.enum&&h.enumFields.push(l.path),l.validations.fn&&h.fnValidatedFields.push(l.path)),l.default?l.isVirtual?h.virtualFields.push(l.path):h.computedFields.push(l.path):l.isVirtual&&h.virtualFields.push(l.path);}}))},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`)},O=(e,t)=>{if(!t)throw new Error("[Internal] No node for getCurrentSchema");if(t.$thing){if(t.$thingType==="entity"){if(!(t.$thing in e.entities))throw new Error(`Missing entity '${t.$thing}' in the schema`);return e.entities[t.$thing]}if(t.$thingType==="relation"){if(!(t.$thing in e.relations))throw new Error(`Missing relation '${t.$thing}' in the schema`);return e.relations[t.$thing]}if(t.$thing in e.entities&&t.$thing in e.relations)throw new Error(`Ambiguous $thing ${t.$thing}`);if(t.$thing in e.entities)return e.entities[t.$thing];if(t.$thing in e.relations)return e.relations[t.$thing];throw new Error(`Wrong schema or query for ${JSON.stringify(t,null,2)}`)}if(t.$entity){if(!(t.$entity in e.entities))throw new Error(`Missing entity '${t.$entity}' in the schema`);return e.entities[t.$entity]}if(t.$relation){if(!(t.$relation in e.relations))throw new Error(`Missing relation '${t.$relation}' in the schema`);return e.relations[t.$relation]}throw new Error(`Wrong schema or query for ${JSON.stringify(t,null,2)}`)},xt=(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")},Ge=(e,t,r)=>{let i=O(e,t),o=i.linkFields?.find(s=>s.path===r);if(o)return o;let n=i.dataFields?.find(s=>s.path===r);if(n)return n;let l="roles"in i?i.roles?.[r]:void 0;if(l)return l},Xe=(e,t,r)=>Ge(e,t,r)?.cardinality,de=(e,t)=>{let r=e.dataFields?.map(d=>d.path)||[],i=e.linkFields?.map(d=>d.path)||[],o="roles"in e?listify(e.roles,d=>d):[],n=[...r||[],...i||[],...o||[]],s=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...n];if(!t)return {fields:n,dataFields:r,roleFields:o,linkFields:i};let c=t.$fields?t.$fields.map(d=>{if(typeof d=="string"){if(d.startsWith("$")||d.startsWith("%"))return;if(!n.includes(d))throw new Error(`Field ${d} not found in the schema`);return d}if("$path"in d&&typeof d.$path=="string")return d.$path;throw new Error("[Wrong format] Wrongly structured query")}):listify(t,d=>{if(!(d.startsWith("$")||d.startsWith("%"))){if(!n.includes(d))throw new Error(`[Schema] Field ${d} not found in the schema`);return d}}).filter(d=>d!==void 0),p=t.$filter?listify(t.$filter,d=>d.toString().startsWith("$")?void 0:d.toString()).filter(d=>d&&r?.includes(d)):[],u=t.$filter?listify(t.$filter,d=>d.toString().startsWith("$")?void 0:d.toString()).filter(d=>d&&[...o||[],...i||[]].includes(d)):[],h=[...c,...p].filter(d=>!d?.startsWith("%")).filter(d=>!s.includes(d)).filter(d=>d),a=t.$filter?Ce(t.$filter,(d,$)=>p.includes(d)):{},f=t.$filter?Ce(t.$filter,(d,$)=>u.includes(d)):{};return {fields:n,dataFields:r,roleFields:o,linkFields:i,usedFields:c,usedLinkFields:i.filter(d=>c.includes(d)),usedRoleFields:o.filter(d=>c.includes(d)),usedDataFields:r.filter(d=>c.includes(d)),unidentifiedFields:h,...p.length?{localFilters:a}:{},...u.length?{nestedFilters:f}:{}}};var jt=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},Nt=(e,t,r)=>{let o=(r.nodePath||"").split("."),n=isArray(t)?o.slice(0,-2).join("."):o.slice(0,-1).join(".");return t?getNodeByPath(e,n):{}},me=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var Pe=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),he=e=>{if(Array.isArray(e))return e.map(t=>current(t));if(e&&typeof e=="object"){let t=isDraft(e)?current(e):e,r={};return Object.entries(t).forEach(([i,o])=>{r[i]=isDraft(o)?current(o):o;}),r}else return e},oe=(e,t)=>{if(e===void 0)throw new Error("Value is undefined");return e},b=(e,t)=>{let r="";for(let i=0;i<t;i++)r+=" ";return `${r}${e}`};var Qe=(e,t)=>{if(t.fieldType==="linkField"){let r=t.oppositeLinkFieldsPlayedBy;if(r?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!r?.length)throw new Error(`[Internal] Field ${e} should have a player`);return r}else if(t.fieldType==="roleField"){if([...new Set(t.playedBy?.map(r=>r.thing))].length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!t.playedBy?.length)throw new Error(`[Internal] Field ${e} should have a player`);return t.playedBy}else throw new Error(`[Internal] Field ${e} is not a linkField or roleField`)};var _t=(e,t,r)=>{let i=isArray(e[t])?e[t]:[e[t]];if(!i.every(o=>typeof o=="object"))if(i.every(o=>typeof o=="string")){let o=Qe(t,r),[n]=o,l=e.$op==="create"?"link":"replace",s=n.thing,c=n.thingType;if(i.some(p=>p.startsWith("_:")))throw new Error("[Not supported] At least one child of a replace is a tempId");e[t]={$id:e[t],$op:l,$thing:s,$thingType:c,$bzId:`S_${v4()}`};}else throw new Error(`[Mutation Error] Replace can only be used with a single id or an array of ids. (Field: ${t} Nodes: ${JSON.stringify(i)} Parent: ${JSON.stringify(e,null,2)})`)};var be=(e,t,r)=>{let i=O(r,t),{usedDataFields:o}=de(i,t);if(t.$op){if(t.$op==="create"&&t.$id)throw new Error("[Wrong format] Can't write to computed field $id. Try writing to the id field directly.");if(["unlink","delete","update"].includes(t.$op)&&e.$op==="create")throw new Error(`[Wrong format] Cannot ${t.$op} under a create`);if(t.$op==="delete"&&o.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&o.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var qe=(e,t,r)=>{let i=O(r,t),{usedFields:o}=de(i,t);return t.$op?(be(e,t,r),t.$op):t.$id||t.$filter?o.length>0?(be(e,{...t,$op:"update"},r),"update"):(be(e,{...t,$op:"link"},r),"link"):t.$tempId?o.length>0?(be(e,{...t,$op:"create"},r),"create"):(be(e,{...t,$op:"create"},r),"link"):(be(e,{...t,$op:"create"},r),"create")};var Wt=(e,t)=>{let i=(isArray(e.$root)?e.$root:[e.$root]).map(o=>{let n=qe(o,o,t);return {...{...o.$thing?{}:{$thing:o.$entity||o.$relation},...o.$thingType?{}:{$thingType:xt(o,t)},...o.$op?{}:{$op:n},...o.$bzId?{}:{$bzId:`R_${v4()}`}},...o}});e.$root=isArray(e.$root)?i:i[0];};var ue=Symbol.for("queryPath"),Oe=Symbol.for("stepPrint"),we=Symbol.for("edgeType"),ye=Symbol.for("edgeSchema"),Te=Symbol.for("dbNode"),et=Symbol.for("isTransformed");var xe=(e,t)=>{let r=t[Oe];return isSet(r)?r.has("clean")?(Reflect.set(t,Oe,r.add("clean")),!0):!1:(Reflect.set(t,Oe,new Set(["clean"])),!0)};var Vt=(e,t,r)=>{if(xe("split_ids",e)){let i=(isArray(e[t])?e[t]:[e[t]]).flatMap(o=>{if(isObject(o)&&"$id"in o&&isArray(o.$id)){let n=o;if(O(r,n),!n.$bzId)throw new Error("[Internal Error] No bzId found");return n.$id.map((l,s)=>({...he(n),$id:l,$bzId:`${n.$bzId}_${s}`,...me(n)}))}return o});(i.length>isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=i);}};var Kt=(e,t,r,i)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(n=>{let l=Qe(t,r),[s]=l,c=qe(e,{...n,$thing:s.thing,$thingType:s.thingType},i),p=n.$bzId?n.$bzId:n.$tempId?n.$tempId:`N_${v4()}`;if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);return {...n,[ye]:r,$thing:s.thing,$thingType:s.thingType,$op:c,$bzId:p}});e[t]=isArray(e[t])?o:o[0];};var Bn=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,En=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,Ut=e=>{let r=e.toString().replace(Bn,"").trim().split("=>")[0].split("{")[0].replace(En,"").trim(),i=r.substring(r.indexOf("(")+1,r.lastIndexOf(")")).trim();return i?(i.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(n=>n.includes("{")&&n.includes("}")?(n.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(s=>s.split(":")[0].trim().replace(/['"[\]]/g,"")):n.trim()).filter(Boolean):[]};var Le=({currentThing:e,fieldSchema:t,mandatoryDependencies:r=!1})=>{if(!t||!t.default||!("fn"in t.default||"value"in t.default))throw new Error(`[Internal] Virtual field: No field schema found, or wrongly configured. Field: ${JSON.stringify(t,null,3)}`);if(t.default.type==="value")return t.default.value;if(r){let{fn:o}=t.default,l=Ut(o).filter(s=>!(s in e));if(l.length)throw new Error(`Virtual field: Missing arguments ${l.join(", ")}`)}if(!t.default.fn)throw new Error("[Schema] No fn in default field schema");return "default"in t?t.default?.fn(e):void 0};var vt=(e,t,r)=>{let i=e[t];i&&(isArray(i)?i:[i]).forEach(o=>{let n=O(r,o),{unidentifiedFields:l}=de(n,o),{computedFields:s,virtualFields:c}=n,p=listify(o,(a,f)=>f!==void 0?a:void 0),u=p.filter(a=>c?.includes(a));if(u.length>0)throw new Error(`Virtual fields can't be sent to DB: "${u.join(",")}"`);if(s.filter(a=>!p.includes(a)).forEach(a=>{let f=n.dataFields?.find(w=>w.path===a),$=n.linkFields?.find(w=>w.path===a)?.oppositeLinkFieldsPlayedBy[0],g="roles"in n?qt(n.roles,(w,T)=>w===a):void 0,y=f||$||g;if(!y)throw new Error(`no field Def for ${a}`);if(o.$op==="create"&&!o[a]){let w=Le({currentThing:o,fieldSchema:y,mandatoryDependencies:!0});o[a]=w;}}),l.length>0)throw new Error(`Unknown fields: [${l.join(",")}] in ${JSON.stringify(o)}`)});};var je=(e,t)=>{let r=O(t,e).hooks;if(r?.pre){let i=`on${jt(e.$op)}`;return r.pre.filter(l=>!l.triggers||l.triggers[i]?.()).flatMap(l=>l.actions)}return []};var Zt=(e,t,r,i)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(n=>{if("$thing"in n){if(n.$fields)return n;let{requiredFields:l,enumFields:s,fnValidatedFields:c,dataFields:p}=O(r,n);if("$op"in n&&n.$op==="create"&&l.forEach(u=>{if(!(u in n))throw new Error(`[Validations] Required field "${u}" is missing.`)}),("$op"in n&&n.$op==="update"||n.$op==="create")&&s.forEach(u=>{if(u in n){let h=p?.find(a=>a.path===u)?.validations?.enum;if(!h)throw new Error(`[Validations] Enum field "${u}" is missing enum options.`);if(isArray(n[u]))n[u].some(a=>{if(!h.includes(a))throw new Error(`[Validations] Option "${a}" is not a valid option for field "${u}".`)});else if(h&&!h.includes(n[u]))throw new Error(`[Validations] Option "${n[u]}" is not a valid option for field "${u}".`)}}),("$op"in n&&n.$op==="update"||n.$op==="create")&&c.forEach(u=>{if(u in n)try{let h=p?.find(a=>a.path===u)?.validations?.fn;if(!h)throw new Error("Missing validation function.");if(!h(n[u]))throw new Error("Failed validation function.")}catch(h){throw new Error(`[Validations:attribute:${u}] ${h.message}`)}}),isObject(n)&&"$thing"in n){let u=n.$thing,h=n,a=clone(he(e)),f=clone(he(h)),d=i.mutation?.context||{},$=clone(he(n[Te]||{}));je(h,r).forEach(y=>{if(y.type==="validate"){if(y.severity!=="error")return;try{let w=y.fn(f,a,d,$);if(w===!1)throw new Error(`${y.message}.`);if(w!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(w){throw new Error(`[Validations:thing:${u}] ${w.message}`)}}});}}});};var Gt=(e,t,r,i)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(n=>{if(Pe(n)){if(n.$fields||n[et])return n;let l=je(n,r).filter(h=>h.type==="transform"),s=clone(he(e)),c=clone(he(n)),p=i.mutation?.context||{},u=clone(he(n[Te]||n.$dbNode));return l.forEach(h=>{let a=h.fn(c,s,p,u||{});Object.keys(a).length!==0&&(n={...c,...a,...me(n),[et]:!0});}),n}});e[t]=isArray(e[t])?o:o[0];};var Xt=(e,t,r)=>{let i=Qe(t,r),[o]=i;e[t]={$thing:o.thing,$thingType:o.thingType,$op:"unlink",$bzId:`U_${v4()}`,[ye]:r};};var ke=e=>{if(Array.isArray(e)){for(let t of e)if(ke(t))return !0;return !1}if(e.$fields)return !0;for(let t in e){if(t.startsWith("$"))continue;let r=e[t];if(r&&typeof r=="object"&&ke(e[t]))return !0}return !1};var Dn=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(xe("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")},Rn=(e,t)=>{},ot=(e,t,r)=>{let i={$rootWrap:{$root:e}},o=ke(Array.isArray(e)?e:[e]),n=produce(i,l=>traverse(l,({value:s,parent:c,key:p,meta:u})=>{if(!(!c||!p)&&isObject(s)){let h=u.nodePath?.split(".")||[];if(!("$root"in s)){if(!("$thing"in s||"$entity"in s||"$relation"in s)){let d=["$fields","$dbNode","$filter"],$=h[h.length-1],g=h[h.length-2];if(p==="$root")throw new Error("Root things must specify $entity or $relation");if(!d.includes($)&&!d.includes(g))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(s)?current(s):s)}`)}}let a=s,f=h.includes("$filter");Object.keys(a).forEach(d=>{if(Dn(a,d),d!=="$root"&&f||d!=="$root"&&(d.startsWith("$")||d.startsWith("%")))return;let $=d!=="$root"?Ge(t,a,d):{fieldType:"rootField"};if(!$)throw new Error(`[Internal] Field ${d} not found in schema`);if("contentType"in $)return Rn();if(["rootField","linkField","roleField"].includes($.fieldType)){if(["linkField","roleField"].includes($.fieldType)&&(a[d]===null?Xt(a,d,$):_t(a,d,$)),$.fieldType==="rootField"){if(!("$root"in a))throw new Error(`[Internal] Field ${d} is a rootField but the object is not a root`);Wt(a,t);}let g=isArray(a[d])?a[d]:[a[d]],y=h.slice(1).join(".");g.forEach(T=>{if(T){if($?.cardinality==="ONE"&&!T.$op&&!T.$id&&!T.$filter&&!T.$tempId&&a.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${y}.${d}`);if(T.$tempId&&!(T.$op===void 0||T.$op==="link"||T.$op==="create"||T.$op==="update"))throw new Error(`Invalid op ${T.$op} for tempId. TempIds can be created, or when created in another part of the same mutation. In the future maybe we can use them to catch stuff in the DB as well and group them under the same tempId.`)}}),["linkField","roleField"].includes($.fieldType)&&Kt(a,d,$,t),Vt(a,d,t),["rootField","linkField","roleField"].includes($.fieldType)&&vt(a,d,t),(isArray(a[d])?a[d]:[a[d]]).forEach(T=>{let m=O(t,T),{unidentifiedFields:D,usedLinkFields:R,usedFields:A,fields:x}=de(m,T);if(A.forEach(j=>{if(!x.includes(j))throw new Error(`[Schema] Field ${j} not found in the schema`)}),D.length>0)throw new Error(`Unknown fields: [${D.join(",")}] in ${JSON.stringify(s)}`);if(R.length>1){let j=m.linkFields?.filter(N=>R.includes(N.path));j?.some((N,se)=>j.some((K,S)=>{if(se!==S&&N.target!==K.target&&N.relation===K.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),o||(Gt(a,d,t,r),Zt(a,d,t,r));}});}}));return isArray(n.$rootWrap.$root),n.$rootWrap.$root};var Ne=async(e,t)=>{let r=t.dbConnectors[0].id,i=e.typeDB?.get(r)?.session,o=e.typeDB?.get(r)?.client;if(!i||!i.isOpen()){if(!o)throw new Error("Client not found");i=await o.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(r,{client:o,session:i});}return {client:o,session:i}};var er=async(e,t,r)=>{if(!e)throw new Error("TQL request not built");if(!(e.deletions&&e.deletionMatches||e.insertions))throw new Error("TQL request error, no things");let{session:i}=await Ne(t,r),o=await i.transaction(TransactionType.WRITE);if(!o)throw new Error("Can't create transaction");let n=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,l=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;n&&await o.query.delete(n);let s=l&&o.query.insert(l);try{let c=s?await s.collect():void 0;return await o.commit(),await o.close(),{insertions:c}}catch(c){throw await o.close(),new Error(`Transaction failed: ${c.message}`)}};var tr=async(e,t,r,i,o)=>{let n=[...t,...r],l=n.map(s=>{let c=e.insertions?.find(h=>h.get(`${s.$bzId}`))?.get(`${s.$bzId}`),p=s.$thing||s.$relation||s.$entity,u=p?ee(i,p):void 0;if(s.$op==="create"||s.$op==="update"||s.$op==="link"){if(s.$op!=="update"&&!c&&s.$id)return {$id:s.$id,$error:"Does not exist or it's not linked to the parent"};let h=c?.asThing().iid,a=Object.entries(s).filter(([d,$])=>!d.startsWith("$")).reduce((d,[$,g])=>{if(u?.dataFields?.find(w=>w.path===$)?.contentType==="JSON")return d[$]=JSON.parse(g),d;if(s.$thingType==="relation"){let w=n.filter(T=>T.$id&&T.$bzId===g);if(w.length>1)throw new Error(`Multiple things with the same bzId ${g}`);return w.length===1?(d[$]=w[0].$id,d):(d[$]=g,d)}return d[$]=g,d},{});if(o.mutation?.noMetadata)return a;let f=s.$tempId&&!s.$tempId.startsWith("_:")?{$tempId:`_:${s.$tempId}`}:{};return {$dbId:h,...s,...a,[s.path]:s.$id,...f}}if(s.$op==="delete"||s.$op==="unlink")return s;if(s.$op!=="match")throw new Error(`Unsupported op ${s.$op}`)}).filter(s=>s);return clone(l)};var rr=e=>{let t=({value:r})=>(r&&typeof r=="object"&&"$id"in r&&(Object.keys(r).filter(n=>n.startsWith("$")).forEach(n=>delete r[n]),Object.keys(r).filter(n=>typeof n=="symbol").forEach(n=>delete r[n])),r);return produce(e,r=>traverse(r,t))};var sr=async(e,t)=>{let r=u=>{let h=[],a=[],f=y=>{if(y.$id)return y.$id;let w=O(t,y),{idFields:T}=w;if(!T)throw new Error(`no idFields: ${JSON.stringify(y)}`);let[m]=T;if(!m)throw new Error(`no idField: ${JSON.stringify(y)}`);let D=w.dataFields?.find(x=>x.path===m),R=Le({currentThing:y,fieldSchema:D,mandatoryDependencies:!0}),A=y[m]||y.$id||R;if(!A)throw new Error(`no idValue: ${JSON.stringify(y)}`);return A},d=y=>{if(y.$op==="create"){let w=f(y);if(h.find(T=>T.$id===w&&T.$op==="create"))throw new Error(`Duplicate id ${w} for node ${JSON.stringify(y)}`);if(a.find(T=>T.$bzId===y.$bzId))throw new Error(`Duplicate $bzId ${y.$bzId} for node ${JSON.stringify(y)}`);h.push({...y,$id:w});return}y.$tempId&&y.$op==="match"||h.push(y);},$=y=>{if(y.$op==="create"){let w=f(y);if(h.find(T=>T.$id===w),a.find(T=>T.$bzId===y.$bzId))throw new Error(`Duplicate %bzId ${y.$bzIdd} for edge ${JSON.stringify(y)}`);a.push({...y,$id:w});return}a.push(y);};return traverse(u,({value:y,parent:w,meta:T})=>{if(!isObject(y))return;let m=y;if(m.$thing){if(!m.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(m)}`);if(!m.$bzId)throw new Error("[internal error] BzId not found");let D=O(t,m),{dataFields:R,roleFields:A,linkFields:x,usedFields:j}=de(D,m),N=()=>{if(m.$op==="create"||m.$op==="delete")return m.$op;if(m.$op==="update"){let S=j.filter(F=>R?.includes(F)),B=j.filter(F=>A?.includes(F)),M=j.filter(F=>x?.includes(F));if(S.length>0)return "update";if(B.length>0||M.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(m)}`)}return "match"},se={...m.$id&&{$id:m.$id},...m.$tempId&&{$tempId:m.$tempId},...m.$filter&&{$filter:m.$filter},$thing:m.$thing,...m.$thingType&&{$thingType:m.$thingType},...shake(pick(m,R||[""])),$op:N(),$bzId:m.$bzId};d(se);let K=m[ye];if(K?.fieldType==="linkField"){if((m.$op==="link"||m.$op==="unlink")&&(m.$id||m.$filter)){if(m.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");h.push({...m,$op:"match"});}let S=K.relation===m.$thing,B=S?m.$bzId:`LT_${v4()}`,F=Nt(u,w,T).$bzId;if(!F)throw new Error("No parent id found");let E=()=>{if(m.$op==="delete")return S?"match":"delete";if(m.$op==="unlink")return S?"unlink":"delete";if(m.$op==="link"||m.$op==="create")return S?"link":"create";if(m.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},Q=O(t,{$thing:K.relation,$thingType:"relation"});if(!Object.keys(Q.roles).includes(K.plays))throw new Error(`[Wrong format] Field ${K.plays} is not a role of relation ${K.relation}`);let P={$bzId:B,$thing:K.relation,$thingType:"relation",...m.$tempId?{$tempId:m.$tempId}:{},$op:E(),...S?{}:{[K.path]:m.$bzId},[K.plays]:F,[ye]:K,[we]:"linkField"};$(P),(m.$op==="unlink"||E()==="unlink")&&S&&$({$thing:K.relation,$thingType:"relation",$bzId:B,$op:"match",[K.plays]:F,[ye]:K,[we]:"linkField"});}if(m.$thingType==="relation"){let S=Ce(m,(F,E)=>A.includes(F)),B=mapEntries(S,(F,E)=>isArray(E)?[F,E]:isObject(E)?[F,E.$bzId]:[F,E]),M=Ce(y,(F,E)=>F.startsWith("$")||F.startsWith("Symbol"));if(Object.keys(S).filter(F=>!F.startsWith("$")).length>0){if(m.$op==="create"||m.$op==="delete"){let F=()=>{if(m.$op==="create")return "link";if(m.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},E=O(t,m).roles,Q=mapEntries(B,(P,k)=>{let q=E[P]?.cardinality;if(!q)throw new Error(`Role ${P} not found in schema`);if(Array.isArray(k)){if(q==="ONE"){if(k.length>1)throw new Error(`[Error] Role ${P} is not a MANY relation`);return [P,k[0].$bzId||k[0]]}return [P,k.map(v=>v.$bzId||v)]}return [P,k.$bzId||k]}),L={...M,$thing:m.$thing,$thingType:"relation",$op:F(),...Q,$bzId:m.$bzId,[we]:"roleField"};$(L);return}if(m.$op==="match"||m.$op==="update"&&Object.keys(S).length>0){let F=0;Object.entries(S).forEach(([E,Q])=>{let L=isArray(Q)?Q:[Q],P=k=>k==="create"||k==="replace"?"link":k;L.forEach(k=>{if(!k)return;let q=P(k.$op);if(q==="replace")throw new Error("Not supported yet: replace on roleFields");if(q==="unlink"&&F>0)throw F+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let v={...M,$thing:m.$thing,$thingType:"relation",$op:q==="delete"?"unlink":q,[E]:k.$bzId,$bzId:m.$bzId,[we]:"roleField"};$(v);});});}}}}}),[h,a]},[i,o]=r(e),n=i.reduce((u,h)=>{if(!h.$bzId)return [...u,h];let a=u.findIndex(f=>f.$bzId===h.$bzId);if(a===-1)return [...u,h];if(u[a].$op==="create"&&h.$op==="match")return u;if(u[a].$op==="match"&&(h.$op==="create"||h.$op==="match"))return [...u.slice(0,a),h,...u.slice(a+1)];throw new Error(`[Wrong format] Wrong operation combination for $tempId "${h.$tempId}". Existing: ${u[a].$op}. Current: ${h.$op}`)},[]),l=o.reduce((u,h)=>{let a=u.find(f=>(f.$id&&f.$id===h.$id||f.$bzId&&f.$bzId===h.$bzId)&&f.$thing===h.$thing&&f.$op===h.$op);if(a){let f={...a};return Object.keys(h).forEach($=>{if(typeof $=="symbol"||$.startsWith("$"))return;let g=a[$],y=h[$];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);}),[...u.filter($=>!(($.$id&&$.$id===h.$id||$.$bzId&&$.$bzId===h.$bzId)&&$.$thing===h.$thing&&$.$op===h.$op)),f]}return [...u,h]},[]);n.forEach(u=>{if((u.$thingType==="relation"||"relation"in u)&&l.filter(h=>h.$bzId===u.$bzId||h.$tempId&&h.$tempId===u.$tempId).length===0){if(u.$op==="delete"||u.$op==="match"||u.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(rr(u))}`)}});let s=[...n,...l],c=new Set(s.filter(u=>u.$tempId).map(u=>u.$tempId)),p=Array.from(c).filter(u=>!s.some(h=>h.$tempId===u&&h.$op==="create"));if(p.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${p.join(", ")}`);return {mergedThings:n,mergedEdges:l}};var ar=async(e,t,r)=>{let i=a=>{let f=a.$op,d=`$${a.$bzId}`,$=O(r,a),{idFields:g,defaultDBConnector:y}=$,w=y?.path||a.$thing,T=a.$id,m=g?.[0],D=listify(a,(S,B)=>{if(S.startsWith("$")||S.startsWith("%")||S===m||B===void 0||B===null)return "";let M=$.dataFields?.find(Q=>Q.path===S);if(!M?.path)return "";let E=M.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(M.contentType))return `has ${E} '${B}'`;if(["NUMBER","BOOLEAN"].includes(M.contentType))return `has ${E} ${B}`;if(M.contentType==="DATE"){if(Number.isNaN(B.valueOf()))throw new Error("Invalid format, Nan Date");return B instanceof Date?`has ${E} ${B.toISOString().replace("Z","")}`:`has ${E} ${new Date(B).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${M.contentType}`)}).filter(S=>S),R=`${d}-atts`,A=listify(a,S=>{if(S.startsWith("$")||S.startsWith("%")||S===m)return "";let B=$.dataFields?.find(E=>E.path===S);if(!B?.path)return "";let F=B.dbPath;return `{${R} isa ${F};}`}).filter(S=>S),x=isArray(T)?`like '${T.join("|")}'`:`'${T}'`,j=T?[`has ${m} ${x}`]:[],N=[...j,...D].filter(S=>S).join(","),se=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${d} isa ${[w,...j].filter(S=>S).join(",")};`;if(f==="update"){if(!A.length)throw new Error("update without attributes");return `${d} isa ${[w,...j].filter(S=>S).join(",")}, has ${R};
|
|
36
|
+
${A.join(" or ")};`}return ""},K=()=>f==="update"||f==="link"||f==="match"?`${d} isa ${[w,...j].filter(S=>S).join(",")};`:"";if(Pe(a))return {op:f,deletionMatch:se(),insertionMatch:K(),insertion:f==="create"?`${d} isa ${[w,N].filter(S=>S).join(",")};`:f==="update"&&D.length?`${d} ${D.join(",")};`:"",deletion:f==="delete"?`${d} isa ${w};`:f==="update"&&A.length?`${d} has ${R};`:""};throw new Error("in attributes")},o=a=>{let f=a.$op,d=O(r,a),$=`$${a.$bzId}`,g=a.$id,y=d.defaultDBConnector?.path||a.$thing,w="roles"in d?listify(d.roles,B=>B):[],T="roles"in d?mapEntries(d.roles,(B,M)=>[B,M.dbConnector?.path||B]):{},m=listify(a,(B,M)=>{if(!w.includes(B))return null;if(!("roles"in d))throw new Error("This should have roles! ");let F=T[B];return Array.isArray(M)?M.map(E=>({path:F,id:E})):{path:F,id:M}}).filter(B=>B).flat(),D=m.map(B=>{if(!B?.path)throw new Error("Object without path");return `${B.path}: $${B.id}`}),R=m.length>0?`( ${D.join(" , ")} )`:"",A=a[we];if(!A)throw new Error("[internal error] Symbol edgeType not defined");let x=R?`${$} ${R} ${A==="linkField"||f==="delete"||f==="unlink"?`isa ${y}`:""}`:"",j=`${$} ${A==="linkField"||f==="delete"?`isa ${y}`:""}`,N=()=>x?f==="link"?`${x};`:f==="create"?`${x}, has id '${g}';`:"":"",se=()=>x&&f==="match"?`${x};`:"",K=()=>x?f==="delete"?`${x};`:f==="match"?`${x};`:"":"",S=()=>x?f==="delete"?`${j};`:f==="unlink"?`${$} ${R};`:"":"";return {deletionMatch:K(),insertionMatch:se(),deletion:S(),insertion:N(),op:""}},n=(a,f)=>{let d=f==="edges"?o:i;if(Array.isArray(a))return a.map(m=>{let{preDeletionBatch:D,insertionMatch:R,deletionMatch:A,insertion:x,deletion:j}=d(m);return shake({preDeletionBatch:D,insertionMatch:R,deletionMatch:A,insertion:x,deletion:j},N=>!N)}).filter(m=>m);let{preDeletionBatch:$,insertionMatch:g,deletionMatch:y,insertion:w,deletion:T}=d(a);return shake({preDeletionBatch:$,insertionMatch:g,deletionMatch:y,insertion:w,deletion:T},m=>!m)},l=n(e),s=Array.isArray(l)?l:[l],c=n(t,"edges"),p=Array.isArray(c)?c:[c],u=[...s,...p];return shake({insertionMatches:u.map(a=>a.insertionMatch).join(" ").trim(),deletionMatches:u.map(a=>a.deletionMatch).join(" ").trim(),insertions:u.map(a=>a.insertion).join(" ").trim(),deletions:u.map(a=>a.deletion).join(" ").trim()},a=>!a)};function G(e){return {enumerable:!0,value:e}}function lr(e){return {enumerable:!0,writable:!0,value:e}}var Se={},Wn=()=>!0,cr=()=>({}),hr=e=>e,Vn=(e,t,r,i)=>e.apply(r,i)&&t.apply(r,i),Hn=(e,t,r,[i,o])=>t.call(r,e.call(r,i,o),o),ge=(e,t)=>Object.freeze(Object.create(e,t));function dr(e,t,r){return e.reduce((i,o)=>function(...n){return r(i,o,this,n)},t)}function ur(e){return ge(this,{fn:G(e)})}var pr={},V=ur.bind(pr);var fr={},at=ur.bind(fr);function ze(e,t){return t.filter(r=>e.isPrototypeOf(r))}function $r(e,t,...r){let i=dr(ze(fr,r).map(n=>n.fn),Wn,Vn),o=dr(ze(pr,r).map(n=>n.fn),hr,Hn);return ge(this,{from:G(e),to:G(t),guards:G(i),reducers:G(o)})}var mr={},yr={},H=$r.bind(mr);$r.bind(yr,null);function Kn(e,t,r){return ct(t,e,r,this.immediates)||e}function gr(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 Un={enter:hr};function ce(...e){let t=ze(mr,e),r=ze(yr,e),i={final:G(e.length===0),transitions:G(gr(t))};return r.length&&(i.immediates=G(r),i.enter=G(Kn)),ge(Un,i)}var vn={enter(e,t,r){let i=this.fn.call(t,t.context,r);return lt.isPrototypeOf(i)?ge(Br,{machine:G(i),transitions:G(this.transitions)}).enter(e,t,r):(i.then(o=>t.send({type:"done",data:o})).catch(o=>t.send({type:"error",error:o})),e)}},Br={enter(e,t,r){if(t.child=fe(this.machine,i=>{t.onChange(i),t.child==i&&i.machine.state.value.final&&(delete t.child,t.send({type:"done",data:i.context}));},t.context,r),t.child.machine.state.value.final){let i=t.child.context;return delete t.child,ct(t,e,{type:"done",data:i},this.transitions.get("done"))}return e}};function Z(e,...t){let r=G(gr(t));return lt.isPrototypeOf(e)?ge(Br,{machine:G(e),transitions:r}):ge(vn,{fn:G(e),transitions:r})}var lt={get state(){return {name:this.current,value:this.states[this.current]}}};function Be(e,t,r=cr){return typeof e!="string"&&(r=t||cr,t=e,e=Object.keys(t)[0]),Se._create&&Se._create(e,t),ge(lt,{context:G(r),current:G(e),states:G(t)})}function ct(e,t,r,i){let{context:o}=e;for(let{to:n,guards:l,reducers:s}of i)if(l(o,r)){e.context=s.call(e,o,r);let c=t.original||t,p=ge(c,{current:G(n),original:{value:c}});Se._onEnter&&Se._onEnter(t,n,e.context,o,r);let u=p.state.value;return e.machine=p,e.onChange(e),u.enter(p,e,r)}}function Jn(e,t){let r=t.type||t,{machine:i}=e,{value:o,name:n}=i.state;return o.transitions.has(r)?ct(e,i,t,o.transitions.get(r))||i:(Se._send&&Se._send(r,n),i)}var Zn={send(e){Jn(this,e);}};function fe(e,t,r,i){let o=Object.create(Zn,{machine:lr(e),context:lr(e.context(r,i)),onChange:G(t)});return o.send=o.send.bind(o),o.machine=o.machine.state.value.enter(o.machine,o,i),o}var wr=(e,t)=>{if(!t)return;let r=Yn(t);return Gn(r,e.query?.noMetadata??!1)},Yn=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),Gn=(e,t)=>produce(e,r=>traverse(r,({value:i})=>{if(isObject(i)){let o=i;Object.keys(o).forEach(n=>{o[n]===void 0&&delete o[n];}),Object.getOwnPropertySymbols(o).forEach(n=>{delete o[n];}),t===!0&&Object.keys(o).forEach(n=>{n.startsWith("$")&&delete o[n];});}}));var Lr=(e,t)=>{for(let o of e)if(!("$entity"in o)&&!("$relation"in o)&&(!("$thing"in o)||!("$thingType"in o)))throw new Error("No entity specified in query");let r=Array.isArray(e)?e:[e];return produce(r,o=>traverse(o,n=>{let{value:l,meta:s}=n,c=l;if(isObject(c)){if(c.$id){let p=c.$entity||c.$relation?c:{[`$${c.$thingType}`]:c.$thing},u=O(t,p);if(!u?.name)throw new Error(`Schema not found for ${c.$thing}`);if(c.$path=u.name,Array.isArray(c.$id)||(c.$filterByUnique=!0),u?.idFields?.length===1){let[h]=u.idFields;c.$filter={...c.$filter,[h]:c.$id},delete c.$id;}else throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in c||"$relation"in c||"$thing"in c){let p=O(t,c);if(!p?.name)throw new Error(`Schema not found for ${c.$thing}`);c.$path=p.name;}if(c.$entity?(c.$thing=c.$entity,c.$thingType="entity",delete c.$entity):c.$relation&&(c.$thing=c.$relation,c.$thingType="relation",delete c.$relation),isObject(c)&&"$thing"in c){let p=c.$entity||c.$relation?c:{[`$${c.$thingType}`]:c.$thing};c[ue]=s.nodePath;let u=O(t,p);if(c.$filter&&(c.$filterByUnique=ht(c.$filter,u),c.$filterProcessed||(c.$filter=c.$filter&&ut(c.$filter,u))),c.$fields){c.$fields.some(f=>u?.idFields?.includes(f?.$path||f))||(c.$fields=[...c.$fields,...Array.isArray(u.idFields)?u.idFields:[]],c.$idNotIncluded=!0);let a=c.$fields?.flatMap(f=>{let d=Tr(f,u,t);return Array.isArray(d)?d:[d]}).filter(Boolean);c.$fields=a;}else {let a=dt(u)?.flatMap(f=>{let d=Tr(f,u,t);return Array.isArray(d)?d:[d]}).filter(Boolean);c.$fields=a;}c.$excludedFields&&(c.$fields=c.$fields.filter(h=>We(u,h)?!0:!c.$excludedFields.includes(h.$path)));}}}))},dt=e=>{let t=e.dataFields?.map(n=>n.path)||[],r=e.linkFields?.map(n=>n.path)||[],i=Object.keys(e.roles||{})||[];return [...t,...r,...i]},ht=(e,t)=>Object.keys(e||{}).some(i=>{if(!Array.isArray(e[i])){let o=t.idFields?.includes(i),n=t.dataFields?.some(l=>(l.dbPath===i||l.path===i)&&l?.validations?.unique);return o||n}return !1}),ut=(e,t)=>{let r={};if(t.dataFields?.forEach(l=>{l.path!==l.dbPath&&(r[l.path]=l.dbPath);}),Object.keys(r).length===0)return e;let{$not:i,...o}=e,n=Qr(o,r);return i&&(n.$not=Qr(i,r)),n},Qr=(e,t)=>{let r={};return Object.entries(e).forEach(([i,o])=>{let n=t[i]||i;r[n]=o;}),r},We=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),ti=e=>{let{field:t,fieldStr:r,$justId:i,dbPath:o,isVirtual:n}=e;return {$path:r,$dbPath:o,$thingType:"attribute",$as:t.$as||r,$var:r,$fieldType:"data",$justId:i,$id:t.$id,$isVirtual:n}},ri=e=>{let{field:t,fieldStr:r,linkField:i,$justId:o,dbPath:n,schema:l}=e,{target:s,oppositeLinkFieldsPlayedBy:c}=i;return c.map(p=>{let u=s==="role"?p.thingType:"relation",h=s==="role"?p.thing:i.relation,a={[`$${u}`]:h},f=O(l,a),d=t?.$fields?.filter(g=>We(f,g)).length===0,$=[];if(typeof t!="string")if(t.$fields)if(d){let g=f.idFields||[];$=[...t.$fields,...g];}else $=t.$fields;else $=dt(f);else $=["id"];return t.$excludedFields&&($=$.filter(g=>We(f,g)?!0:!t.$excludedFields.includes(g.$path))),{$thingType:u,$plays:i.plays,$playedBy:p,$path:p.path,$dbPath:n,$as:t.$as||r,$var:r,$thing:h,$fields:$,$excludedFields:t.$excludedFields,$fieldType:"link",$target:s,$intermediary:p.relation,$justId:o,$id:t.$id,$filter:t.$filter&&ut(t.$filter,f),$idNotIncluded:d,$filterByUnique:ht(t.$filter,f),$filterProcessed:!0,$sort:t.$sort,$offset:t.$offset,$limit:t.$limit}})},ni=e=>{let{field:t,fieldStr:r,roleField:i,$justId:o,dbPath:n,schema:l}=e;return i.playedBy.map(s=>{let{thing:c,thingType:p,relation:u}=s,h={[`$${p}`]:c},a=O(l,h),f=t?.$fields?.filter($=>a?.idFields?.includes($)||a?.idFields?.includes($.$path)).length===0,d=[];if(typeof t!="string")if(t.$fields)if(f){let $=a.idFields||[];d=[...t.$fields,...$];}else d=t.$fields;else d=dt(a);else d=["id"];return t.$excludedFields&&(d=d.filter($=>We(a,$)?!0:!t.$excludedFields.includes($.$path))),{$thingType:p,$path:r,$dbPath:n,$as:t.$as||r,$var:r,$thing:c,$fields:d,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:u,$justId:o,$id:t.$id,$filter:t.$filter&&ut(t.$filter,a),$idNotIncluded:f,$filterByUnique:ht(t.$filter,a),$playedBy:s,$filterProcessed:!0,$sort:t.$sort,$offset:t.$offset,$limit:t.$limit}})},Tr=(e,t,r)=>{let i=typeof e=="string"?e:e.$path,o=typeof e=="string",n=t.dataFields?.find(c=>c.path===i),l=t.linkFields?.find(c=>c.path===i),s=t.roles?.[i];if(n){let c=!!n.isVirtual&&!!n.default;return ti({field:e,fieldStr:i,$justId:o,dbPath:n.dbPath,isVirtual:c})}else {if(l)return ri({field:e,fieldStr:i,linkField:l,$justId:o,dbPath:l.path,schema:r});if(s)return ni({field:e,fieldStr:i,roleField:s,$justId:o,dbPath:i,schema:r})}return null};var kr=async(e,t,r)=>r?(n=>produce(n,l=>traverse(l,({value:s})=>{if(isObject(s)){let c=s;if(!c.$thing)return;if(c.$thing){let p=O(e,c),{virtualFields:u}=p,h=c[ue];if(!h)throw new Error("[Internal] QueryPath is missing");let a=getNodeByPath(t,h),f=a.$fields.map($=>$.$path),d=a.$excludedFields;u.forEach($=>{if(d?.includes($)||f.length>0&&!f.includes($))return;let g=p.dataFields?.find(y=>y.path===$);if(g?.default){let y=Le({currentThing:c,fieldSchema:g,mandatoryDependencies:!0});c[$]=y;}else if(c[$]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${$}`)}),d&&d.forEach($=>{if(typeof $!="string")throw new Error("[Internal] ExcludedField is not a string");delete c[$];});}}})))(r):void 0;var Dr=e=>{let{queries:t,schema:r}=e;return t.map(i=>li({query:i,schema:r}))},li=e=>{let{query:t,schema:r}=e;if(t.$fields.length===0)return null;let i=[];i.push("SELECT");let o=pt({queries:t.$fields,level:1,schema:r});o&&i.push(o);let n=t.$filter&&Rr(t.$filter,0)||[];return i.push(...n),i.push(`FROM ${t.$thing}`),i.join(`
|
|
37
|
+
`)},pt=e=>{let{queries:t,schema:r,level:i}=e,o=[];return t.forEach(n=>{let l=ci({query:n,level:i,schema:r});l&&o.push(l);}),o.length===0?null:o.join(`,
|
|
38
|
+
`)},ci=e=>{let{query:t,schema:r,level:i}=e;return t.$fieldType==="data"?di({query:t,level:i}):t.$fieldType==="link"?hi({query:t,level:i,schema:r}):t.$fieldType==="role"?ui({query:t,level:i,schema:r}):null},di=e=>{let{query:t,level:r}=e;return t.$isVirtual?null:t.$path==="id"?b(`meta::id(\`${t.$path}\`) AS ${t.$as}`,r):t.$path===t.$as?b(`\`${t.$path}\``,r):b(`\`${t.$path}\` AS \`${t.$as}\``,r)},hi=e=>{let{query:t,schema:r,level:i}=e;if(t.$fields.length===0)return null;let o=[];o.push(b("(",i));let n=i+1;o.push(b("SELECT",n));let l=n+1,s=pt({queries:t.$fields,level:l,schema:r});s&&o.push(s);let c=[t.$playedBy.thing,...Cr(r,t.$playedBy.thingType,t.$playedBy.thing)],p;return t.$target==="relation"?p=c.map(u=>`<-\`${t.$playedBy.thing}_${t.$plays}\`<-\`${u}\``).join(", "):p=c.map(u=>`<-\`${t.$playedBy.relation}_${t.$plays}\`<-\`${t.$playedBy.relation}\`->\`${t.$playedBy.relation}_${t.$playedBy.plays}\`->\`${u}\``).join(", "),o.push(b(`FROM ${p}`,n)),o.push(b(`) AS \`${t.$as}\``,i)),o.join(`
|
|
39
|
+
`)},ui=e=>{let{query:t,schema:r,level:i}=e;if(t.$fields.length===0)return null;let o=[];o.push(b("(",i));let n=i+1;o.push(b("SELECT",n));let l=n+1,s=pt({queries:t.$fields,level:l,schema:r});s&&o.push(s);let p=[t.$playedBy.thing,...Cr(r,t.$thingType,t.$thing)].map(u=>`->\`${t.$playedBy.relation}_${t.$playedBy.plays}\`->\`${u}\``).join(", ");return o.push(b(`FROM ${p}`,n)),t.$filter&&o.push(...Rr(t.$filter,n)),o.push(b(`) AS \`${t.$as}\``,i)),o.join(`
|
|
40
|
+
`)},Rr=(e,t)=>{let r=[],{$not:i,...o}=e,n=t+1;Object.entries(o).forEach(([c,p])=>{r.push(b(`${c}=${JSON.stringify(p)}`,n));}),i&&Object.entries(i).forEach(([c,p])=>{r.push(`${c}!=${JSON.stringify(p)}`);});let[l,...s]=r;return l?[b("WHERE (",t),b(l,n),...s.map(c=>b(`AND ${c}`,n)),b(")",t)]:r},Cr=(e,t,r)=>{let i=Sr(e,t,r),o=0;for(;i[o];)i.push(...Sr(e,t,i[o])),o++;return i},Sr=(e,t,r)=>Object.values(t==="entity"?e.entities:e.relations).filter(o=>o.extends===r).map(o=>o.name);var Ar=async e=>{let{client:t,queries:r}=e;return await Promise.all(r.map(i=>t.query(i)))};var Ir=e=>{let{res:t,queries:r}=e;return t.map((i,o)=>Pr(r[o],i))},Pr=(e,t)=>t.map(r=>qr(e,r)),qr=(e,t)=>{let r={};return e.$fields.forEach(i=>{let o=i.$as,n=t[o];i.$path==="id"&&e.$idNotIncluded||(r[o]=pi(i,n));}),r},pi=(e,t)=>e.$fieldType==="data"?t??null:e.$justId?e.$filterByUnique?t[0]?.id??null:t?.map(r=>r.id)??[]:e.$filterByUnique?qr(e,t[0]):Pr(e,t);var ft=H("error","error",V((e,t)=>({...e,error:t.error}))),fi=Be("build",{build:Z(async e=>Dr({queries:e.bql.queries,schema:e.schema}),H("done","run",V((e,t)=>({...e,surql:{...e.surql,queries:t.data}}))),ft),run:Z(async e=>Ar({client:e.client,queries:oe(e.surql.queries)}),H("done","parse",V((e,t)=>({...e,surql:{...e.surql,res:t.data}}))),ft),parse:Z(async e=>Ir({res:oe(e.surql.res),queries:e.bql.queries,schema:e.schema,config:e.config}),H("done","success",V((e,t)=>({...e,bql:{...e.bql,res:t.data}}))),ft),success:ce(),error:ce()},e=>e),$i=async e=>new Promise((t,r)=>{fe(fi,i=>{i.machine.state.name==="success"&&t(i.context.bql.res),i.machine.state.name==="error"&&r(i.context.error);},e);}),Or=async(e,t,r,i)=>$i({bql:{queries:e},surql:{},schema:t,config:r,client:i,error:null});var $t="___",xr=async e=>{let{queries:t,schema:r}=e;return t.map(i=>mi({query:i,schema:r}))},mi=e=>{let{query:t,schema:r}=e,{$path:i,$thing:o,$filter:n,$fields:l,$sort:s,$offset:c,$limit:p}=t;if(!i)throw new Error("Path is not defined");let u=[],h=t[ue];if(u.push("match"),u.push(`$${i} isa ${o};`),n){let d=Bt({$filter:n,$var:i,$thing:o,schema:r,depth:0});u.push(`
|
|
41
|
+
${d}`);}let a=Et({schema:r,$thing:o,$var:i,$sort:s,depth:0});a&&u.push(a.match);let f=`M_${v4()}`;if(u.push(`?queryPath${f} = "${h}";`),u.push("fetch"),u.push(`?queryPath${f} as "queryPath";`),l){let d=l.filter(y=>y.$fieldType==="data");d&&d.length>0&&u.push(...mt(d,i,0));let $=l.filter(y=>y.$fieldType==="link");$&&$.length>0&&u.push(...gt($,i,i,0,r));let g=l.filter(y=>y.$fieldType==="role");g&&g.length>0&&u.push(...yt(g,i,i,0,r));}return a&&u.push(a.sort),typeof c=="number"&&u.push(`
|
|
42
|
+
offset ${c};`),typeof p=="number"&&u.push(`
|
|
43
|
+
limit ${p};`),u.join(`
|
|
44
|
+
`)},mt=(e,t,r)=>{let i=[],o=[];for(let p=0;p<e.length;p++)e[p].$isVirtual||i.push(e[p].$dbPath),o.push(`{${e[p].$dbPath}:${e[p].$as}}`);let n=i.join(", "),s=`$metadata:{as:[${o.join(",")}]}`;return [b(`$${t} as "${t}.${s}.$dataFields": ${n};`,r)]},yt=(e,t,r,i,o)=>{let n=i+1,l=[];for(let s of e){let{$fields:c,$as:p,$justId:u,$idNotIncluded:h,$filterByUnique:a,$thing:f,$sort:d,$offset:$,$limit:g}=s,y=s[ue],w=`$metadata:{as:${p},justId:${u?"T":"F"},idNotIncluded:${h},filterByUnique:${a}}`;l.push(b(`"${r}.${w}.${s.$var}": {`,i)),l.push(b("match",n));let T=`${t}${$t}${s.$var}`;l.push(b(`$${T} isa ${s.$thing};`,n)),l.push(b(`$${t} (${s.$var}: $${t}${$t}${s.$var}) isa ${s.$intermediary};`,n)),s.$filter&&l.push(Bt({$filter:s.$filter,$var:T,$thing:s.$thing,schema:o,depth:n}));let m=Et({schema:o,$thing:f,$var:T,$sort:d,depth:n});if(m&&l.push(m.match),c){let D=`M_${v4()}`;l.push(b(`
|
|
45
|
+
?queryPath${D} = "${y}";`,n)),l.push(b("fetch",n)),l.push(b(`?queryPath${D} as "queryPath";`,n));let R=c?.filter(j=>j.$fieldType==="data");R&&R.length>0&&l.push(...mt(R,T,n));let A=c?.filter(j=>j.$fieldType==="link");A&&A.length>0&&l.push(...gt(A,T,`${t}.${s.$var}`,n,o));let x=c?.filter(j=>j.$fieldType==="role");x&&x.length>0&&l.push(...yt(x,T,`${t}.${s.$var}`,n,o));}m&&l.push(m.sort),typeof $=="number"&&l.push(b(`offset ${$};`,n)),typeof g=="number"&&l.push(b(`limit ${g};`,n)),l.push(b("};",i));}return l},gt=(e,t,r,i,o)=>{let n=i+1,l=[];for(let s of e){let{$fields:c,$as:p,$justId:u,$idNotIncluded:h,$filterByUnique:a,$playedBy:f,$thing:d,$sort:$,$offset:g,$limit:y}=s,w=s[ue],T=`$metadata:{as:${p},justId:${u?"T":"F"},idNotIncluded:${h},filterByUnique:${a}}`;l.push(b(`"${r}.${T}.${s.$var}": {`,i)),l.push(b("match",n));let m=`${t}${$t}${s.$var}`;l.push(b(`$${m} isa ${s.$thing};`,n)),s.$filter&&l.push(Bt({$filter:s.$filter,$var:m,$thing:s.$thing,schema:o,depth:n}));let D=Et({schema:o,$thing:d,$var:m,$sort:$,depth:n});if(D&&l.push(D.match),s.$target==="role"?l.push(b(`$${t}_intermediary (${s.$plays}: $${t}, ${f.plays}: $${m}) isa ${s.$intermediary};`,n)):l.push(b(`$${m} (${s.$plays}: $${t});`,n)),c){let R=`M_${v4()}`;l.push(b(`?queryPath${R} = "${w}";`,n)),l.push(b("fetch",n)),l.push(b(`?queryPath${R} as "queryPath";`,n));let A=c?.filter(N=>N.$fieldType==="data");A&&A.length>0&&l.push(...mt(A,m,n));let x=c?.filter(N=>N.$fieldType==="link");x&&x.length>0&&l.push(...gt(x,m,`${t}.${s.$var}`,n,o));let j=c?.filter(N=>N.$fieldType==="role");j&&j.length>0&&l.push(...yt(j,m,`${t}.${s.$var}`,n,o));}D&&l.push(D.sort),typeof g=="number"&&l.push(b(`offset ${g};`,n)),typeof y=="number"&&l.push(b(`limit ${y};`,n)),l.push(b("};",i));}return l},Bt=e=>{let{$filter:t,$var:r,$thing:i,schema:o,depth:n}=e,{$not:l,...s}=t,c=ee(o,i),p=[];return Object.entries(l||{}).forEach(([u,h])=>{if(c.dataFields?.find(d=>d.dbPath===u)){h===null?p.push(b(`$${r} has ${u} $${u}_${v4()};`,n)):Array.isArray(h)?h.forEach(d=>{p.push(b(`not { $${r} has ${u} ${ne(d)}; };`,n));}):p.push(b(`not { $${r} has ${u} ${ne(h)}; };`,n));return}let f=c.linkFields?.find(d=>d.path===u);if(f){let[d]=f.oppositeLinkFieldsPlayedBy,g=ee(o,d.thing).idFields?.[0];if(!g)throw new Error(`"${d.thing}" does not have an id field`);if(f.target==="relation")h===null?p.push(b(`(${f.plays}: $${r}) isa ${f.relation};`,n)):Array.isArray(h)?h.forEach(y=>{p.push(b(`not { (${f.plays}: $${r}) isa ${f.relation}, has ${g} ${ne(y)}; };`,n));}):p.push(b(`not { (${f.plays}: $${r}) isa ${f.relation}, has ${g} ${ne(h)}; };`,n));else {let y=`${d.thing}_${v4()}`;h===null?p.push(b(`$${y} isa ${d.thing}; (${f.plays}: $${r}, ${d.plays}: $${y}) isa ${f.relation};`,n)):Array.isArray(h)?h.forEach(w=>{p.push(b(`not { $${y} isa ${d.thing}, has ${g} ${ne(w)}; (${f.plays}: $${r}, ${d.plays}: $${y}) isa ${f.relation}; };`,n));}):p.push(b(`not { $${y} isa ${d.thing}, has ${g} ${ne(h)}; (${f.plays}: $${r}, ${d.plays}: $${y}) isa ${f.relation}; };`,n));}return}if(c.thingType==="relation"){let d=c.roles[u];if(d){let[$]=d.playedBy||[],y=ee(o,$.thing).idFields?.[0];if(!y)throw new Error(`"${$.thing}" does not have an id field`);let w=`${$.thing}_${v4()}`,T=v4(),m=`${r}_${T}`;h===null?(p.push(b(`$${m} isa ${i};`,n)),p.push(b(`$${m} (${$.plays}: ${w});`,n)),p.push(b(`$${r} is $${m};`,n))):Array.isArray(h)?h.forEach(D=>{p.push(b(`$${m} isa ${i};`,n)),p.push(b(`not { $${w} isa ${$.thing}, has ${y} ${ne(D)}; $${m} (${$.plays}: $${w}); };`,n)),p.push(b(`$${r} is $${m};`,n));}):(p.push(b(`$${m} isa ${i};`,n)),p.push(b(`not { $${w} isa ${$.thing}, has ${y} ${ne(h)}; $${m} (${$.plays}: $${w}); };`,n)),p.push(b(`$${r} is $${m};`,n)));return}}}),Object.entries(s).forEach(([u,h])=>{if(c.dataFields?.find(d=>d.dbPath===u)){if(h===null)p.push(b(`not { $${r} has ${u} $${u}_${v4()}; };`,n));else if(Array.isArray(h)){let d=h.map(g=>`$${r} has ${u} ${ne(g)};`),$=Ve(d);$&&p.push(b($,n));}else p.push(b(`$${r} has ${u} ${ne(h)};`,n));return}let f=c.linkFields?.find(d=>d.path===u);if(f){let[d]=f.oppositeLinkFieldsPlayedBy,g=ee(o,d.thing).idFields?.[0];if(!g)throw new Error(`"${d.thing}" does not have an id field`);if(f.target==="relation")if(h===null)p.push(b(`not { (${f.plays}: $${r}) isa ${f.relation}; };`,n));else if(Array.isArray(h)){let y=h.map(T=>`(${f.plays}: $${r}) isa ${f.relation}, has ${g} ${ne(T)};`),w=Ve(y);w&&p.push(b(w,n));}else p.push(b(`(${f.plays}: $${r}) isa ${f.relation}, has ${g} ${ne(h)};`,n));else {let y=`${d.thing}_${v4()}`;if(h===null)p.push(b(`not { $${y} isa ${d.thing}; (${f.plays}: $${r}, ${d.plays}: $${y}) isa ${f.relation}; };`,n));else if(Array.isArray(h)){let w=h.map(m=>`$${y} isa ${d.thing}, has ${g} ${ne(m)}; (${f.plays}: $${r}, ${d.plays}: $${y}) isa ${f.relation};`),T=Ve(w);T&&p.push(b(T,n));}else p.push(b(`$${y} isa ${d.thing}, has ${g} ${ne(h)}; (${f.plays}: $${r}, ${d.plays}: $${y}) isa ${f.relation};`,n));}return}if(c.thingType==="relation"){let d=c.roles[u];if(d){let[$]=d.playedBy||[],y=ee(o,$.thing).idFields?.[0];if(!y)throw new Error(`"${$.thing}" does not have an id field`);let w=`${$.thing}_${v4()}`,T=v4(),m=`${r}_${T}`;if(h===null)p.push(b(`$${m} isa ${i};`,n)),p.push(b(`not { $${m} (${$.plays}: ${w}); };`,n)),p.push(b(`$${r} is $${m};`,n));else if(Array.isArray(h)){let D=h.map(A=>`$${w} isa ${$.thing}, has ${y} ${ne(A)}; $${m} (${$.plays}: $${w});`),R=Ve(D);R&&(p.push(b(`$${m} isa ${i};`,n)),p.push(b(R,n)),p.push(b(`$${r} is $${m};`,n)));}else p.push(b(`$${m} isa ${i};`,n)),p.push(b(`$${w} isa ${$.thing}, has ${y} ${ne(h)}; $${m} (${$.plays}: $${w});`,n)),p.push(b(`$${r} is $${m};`,n));return}}throw new Error(`"${i}" does not have property "${u}"`)}),p.join(`
|
|
46
|
+
`)},Ve=e=>{if(e.length>1)return `{ ${e.join(" } or { ")} };`;let[t]=e;return t},ne=e=>typeof e=="string"?`'${e}'`:e instanceof Date?`'${e.toISOString().replace("Z","")}'`:`${e}`,yi=e=>typeof e=="string"?{field:e,desc:!1}:{...e,desc:e.desc??!1},Et=e=>{let{$var:t,$thing:r,schema:i,$sort:o,depth:n}=e,l=ee(i,r),s=[],c=[];if(o?.forEach(p=>{let u=yi(p),h=l.dataFields?.find(d=>d.path===u.field);if(!h)throw new Error(`"${r}" does not have data field "${u.field}"`);let a=`${u.field}_${v4()}`;s.push(b("{",n)),s.push(b(`$${t} has ${h.dbPath} $${a}_1;`,n+1)),s.push(b("not {",n+1)),s.push(b(`$${t} has ${h.dbPath} $${a}_2;`,n+2)),s.push(b(`$${a}_2 < $${a}_1;`,n+2)),s.push(b("};",n+1)),s.push(b(`?${a}_ = $${a}_1;`,n+1)),s.push(b("} or {",n)),s.push(b(`not { $${t} has ${h.dbPath} $${a}_1; };`,n+1)),s.push(b(`?${a}_ = "~";`,n+1)),s.push(b("};",n)),s.push(b(`?${a} = ?${a}_;`,n));let f=u.desc?"desc":"asc";c.push(`?${a} ${f}`);}),s.length!==0)return {match:s.join(""),sort:b(`sort ${c.join(", ")};`,n)}};var Nr=async e=>{let{enrichedBqlQuery:t,rawBqlRequest:r,schema:i,config:o,rawTqlRes:n}=e;if(t){if(!n)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");return n.map((l,s)=>{let c=r[s],p=t[s];return Bi(l,c,p,i,o)})},Bi=(e,t,r,i,o)=>e.length===0?null:r.$filterByUnique?jr(e[0],t,i,o):e.map(n=>jr(n,t,i,o)),jr=(e,t,r,i)=>{let{dataFields:o,currentSchema:n,linkFields:l,roleFields:s,schemaValue:c}=Ft(e,r),p=bt(o,n,i),u=Mt(l,r,i),h=wt(s,r,i),a=t?.$fields?.every(d=>!n?.idFields?.includes(typeof d=="string"?d:d.$path));return {...u,...h,...c,...!i.query?.noMetadata&&t.$id?{$id:Array.isArray(t.$id)?p.id:t.$id}:{},...a?Object.fromEntries(Object.entries(p).filter(([d])=>!n?.idFields?.includes(d))):p}},Ft=(e,t)=>{let r=Object.keys(e),i=r.find(a=>a.endsWith(".$dataFields"));if(!i)throw new Error("No datafields");let o=e[i],n=i.split(".")[i.split(".").length-2];if(o.$metaData=n,o.length===0)throw new Error("No datafields");let l=o.type,s={$thing:l.label,$thingType:l.root,[ue]:e.queryPath.value},c={[`$${s.$thingType}`]:s.$thing},p=O(t,c),u=r.filter(a=>{let f=oe(a.split(".").pop());return !a.endsWith(".$dataFields")&&p.linkFields?.some(d=>d.path===f)}).map(a=>{let f=oe(a.split(".").pop()),d=oe(p.linkFields?.find($=>$.path===f));return {$linkFields:e[a],$key:f,$metaData:a.split(".")[a.split(".").length-2],$cardinality:d.cardinality}}),h=r.filter(a=>{let f=a.split(".").pop();return f&&!a.endsWith(".$dataFields")&&p.thingType==="relation"&&p.roles?.[f]}).map(a=>{let f=oe(a.split(".").pop());return {$roleFields:e[a],$key:f,$metaData:a.split(".")[a.split(".").length-2],$cardinality:p.roles[f].cardinality}});return {dataFields:o,schemaValue:s,currentSchema:p,linkFields:u,roleFields:h}},bt=(e,t,r)=>{let{$metaData:i}=e,{as:o}=Ei(i),n=Object.entries(e).filter(([l])=>l!=="type"&&!l.startsWith("$")).map(([l,s])=>{let c=t.dataFields?.find(a=>a.path===l||a.dbPath===l),p=l==="id",u=Array.isArray(o)?o.find(a=>a[l])?.[l]:l,h;if(c?.cardinality==="ONE"){if(h=s[0]?s[0].value:r.query?.returnNulls?null:void 0,c.contentType==="DATE"?h=h&&`${h}Z`:c.contentType==="JSON"&&(h=h&&JSON.parse(h)),p)return [[u,h],["$id",h]].filter(([a,f])=>f!==void 0)}else if(c?.cardinality==="MANY"){if(!isArray(s))throw new Error("Typedb fetch has changed its format");if(s.length===0)return r.query?.returnNulls?[[u,null]]:[];c.contentType==="DATE"?h=s.map(a=>`${a.value}Z`):c.contentType==="JSON"?h=s.map(a=>a.value&&JSON.parse(a.value)):h=s.map(a=>a.value);}return [[u,h]].filter(([a,f])=>f!==void 0)}).flat();return Object.fromEntries([...n])},wt=(e,t,r)=>{let i={};return e.forEach(o=>{let{$roleFields:n,$metaData:l,$cardinality:s}=o,{as:c,justId:p,idNotIncluded:u,filterByUnique:h}=_r(l);if(c===null)return;let a=n.map(f=>{let{dataFields:d,currentSchema:$,linkFields:g,roleFields:y,schemaValue:w}=Ft(f,t),T=bt(d,$,r);if(p==="T")return T.id;{let m=Mt(g,t,r),D=wt(y,t,r),R={...T};return u==="true"&&$?.idFields?.forEach(A=>delete R[A]),{...R,...m,...D,...w}}});a.length>0?i[c]=s==="MANY"&&h==="false"?a:a[0]:r.query?.returnNulls&&(i[c]=null);}),i},Mt=(e,t,r)=>{let i={};return e.forEach(o=>{let{$linkFields:n,$metaData:l,$cardinality:s}=o,{as:c,justId:p,idNotIncluded:u,filterByUnique:h}=_r(l);if(c===null)return;let a=n.map(f=>{let{dataFields:d,currentSchema:$,linkFields:g,roleFields:y,schemaValue:w}=Ft(f,t),T=bt(d,$,r);if(p==="T")return T.id;{let m=Mt(g,t,r),D=wt(y,t,r),R={...T};return u==="true"&&$.idFields?.forEach(A=>delete R[A]),{...R,...m,...D,...w}}});i[c]=a.length>0?s==="MANY"&&h==="false"?a:a[0]:r.query?.returnNulls?null:void 0;}),i},_r=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,r=/justId:([a-zA-Z0-9_\-·]+)/,i=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,o=/filterByUnique:([a-zA-Z0-9_\-·]+)/,n=e.match(t),l=e.match(r),s=e.match(i),c=e.match(o);return {as:n?n[1]:null,justId:l?l[1]:null,idNotIncluded:s?s[1]:null,filterByUnique:c?c[1]:null}},Ei=e=>{try{let r=(o=>{let n=o.replace("$metadata:","");return n=n.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),n=n.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(l,s,c)=>/^{.*}$/.test(c)?`:${c}`:`:${s}"${c}"`),n=n.replace(/\[([^\]]+)\]/g,(l,s)=>`[${s.split(",").map(c=>c.trim().startsWith("{")&&c.trim().endsWith("}")?c.trim():`"${c.trim()}"`).join(",")}]`),n})(e);return JSON.parse(r)}catch(t){return console.error(t),{as:[]}}};var zr=async e=>{let{tqlRequest:t,dbHandles:r,config:i}=e,o=new TypeDBOptions;o.infer=!0;let{session:n}=await Ne(r,i),l=await n.transaction(TransactionType.READ,o);if(!l)throw new Error("Can't create transaction");return await parallel(t.length,t,async c=>await l.query.fetch(c).collect())};var Mi=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,Qi=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,Ti=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,Qt=H("error","error",V((e,t)=>({...e,error:t.error}))),Li=Be("build",{build:Z(async e=>xr({queries:e.bql.queries,schema:e.schema}),H("done","run",V(Qi)),Qt),run:Z(async e=>zr({dbHandles:e.handles,tqlRequest:oe(e.tql.queries),config:e.config}),H("done","parse",V(Ti)),Qt),parse:Z(async e=>Nr({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries,schema:e.schema,config:e.config,rawTqlRes:oe(e.tql.res)}),H("done","success",V(Mi)),Qt),success:ce(),error:ce()},e=>e),ki=async e=>new Promise((t,r)=>{fe(Li,i=>{i.machine.state.name==="success"&&t(i.context.bql.res),i.machine.state.name==="error"&&r(i.context.error);},e);}),Wr=async(e,t,r,i,o)=>ki({bql:{raw:e,queries:t},tql:{},schema:r,config:i,handles:o,error:null});var Si=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,Tt=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,He=H("error","error",V((e,t)=>({...e,error:t.error}))),Di=Be("enrich",{enrich:Z(async e=>Lr(e.bql.raw,e.schema),H("done","adapter",V(Si)),He),adapter:Z(async e=>{let t={};e.bql.queries?.forEach((s,c)=>{let p=e.bql.raw[c],u=ee(e.schema,s.$thing),{id:h}=u.defaultDBConnector;if(u.db==="typeDB"){if(!t[h]){let f=e.handles.typeDB?.get(h)?.client;if(!f)throw new Error(`TypeDB client with id "${u.defaultDBConnector.id}" does not exist`);t[h]={db:"typeDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else if(u.db==="surrealDB"){if(!t[h]){let f=e.handles.surrealDB?.get(h)?.client;if(!f)throw new Error(`SurrealDB client with id "${u.defaultDBConnector.id}" does not exist`);t[h]={db:"surrealDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else throw new Error(`Unsupported DB "${u.db}"`);let a=t[h];a.rawBql.push(p),a.bqlQueries.push(s),a.indices.push(c);});let r=Object.values(t),i=r.map(s=>s.db==="typeDB"?Wr(s.rawBql,s.bqlQueries,e.schema,e.config,e.handles):Or(s.bqlQueries,e.schema,e.config,s.client)),o=await Promise.all(i),n=r.flatMap((s,c)=>{let p=o[c];return s.indices.map((u,h)=>({index:u,result:p[h]}))});return n.sort((s,c)=>s.index<c.index?-1:s.index>c.index?1:0),n.map(({result:s})=>s)},H("done","postHooks",V(Tt)),He),postHooks:Z(async e=>kr(e.schema,oe(e.bql.queries),oe(e.bql.res)),H("done","clean",V(Tt)),He),clean:Z(async e=>wr(e.config,oe(e.bql.res)),H("done","success",V(Tt)),He),success:ce(),error:ce()},e=>e),Ri=async e=>new Promise((t,r)=>{fe(Di,i=>{i.machine.state.name==="success"&&t(i.context),i.machine.state.name==="error"&&r(i.context);},e);}),De=async(e,t,r,i)=>Ri({bql:{raw:e},schema:t,config:r,handles:i,error:null});var Lt="___",Ci=Symbol.for("grandChildOfCreate"),Vr=async(e,t,r,i)=>{let o=(B,M)=>Object.keys(B).filter(F=>!F.startsWith("$")&&B[F]!==void 0?M?!O(t,B).dataFields?.find(Q=>Q.path===F):!0:!1);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(r.mutation?.preQuery===!1)return;let n=[];if(traverse(e,({parent:B,key:M,value:F})=>{B&&M&&!M.includes("$")&&isObject(B)?(Array.isArray(B[M])?B[M]:[B[M]]).forEach(Q=>{if(isObject(Q)){if(B.$op!=="create")n.includes(Q.$op)||n.push(Q.$op);else if(Q.$op==="delete"||Q.$op==="unlink")throw new Error(`Cannot ${Q.$op} under a create`)}}):!B&&isObject(F)&&(n.includes(F.$op)||n.push(F.$op));}),!n.includes("delete")&&!n.includes("unlink")&&!n.includes("replace")&&!n.includes("update")&&!n.includes("link"))return;let s=(B=>{let M=(F,E)=>{let Q=[],L={},P=["$op","$bzId","$parentKey"],k=["$relation","$entity","$id",...P];for(let q in F)if(!P.includes(q)&&!(k.includes(q)&&!E))if(!q.includes("$")&&(isObject(F[q])||Array.isArray(F[q]))){let v=F[q];if(Array.isArray(v)&&v.length>0)v.forEach(ae=>{let Fe={$path:q,...M(ae),...ae.$filter&&{$as:ae.$bzId}};Q.find(U=>U.$path===Fe.$path&&!U.$filter)||(Q=[...Q,Fe]);});else {let ae={$path:q,...M(v),...!v.$filter&&{$as:v.$bzId}};Q=[...Q,ae];}}else L[q]=F[q];return {...L,$fields:Q}};return B.map(F=>M(F,!0))})(Array.isArray(e)?e:[e]),p=(await De(s,t,r,i)).bql.res,u=(B,M)=>{let F=B.$id||B.id||B.$bzId;if(B.$objectPath){let{$objectPath:E}=B,Q=E?.beforePath||"root",L=Array.isArray(E.ids)?`[${E.ids}]`:E.ids;return {beforePath:`${Q}.${L}___${E.key}`,ids:F,key:M}}else return {beforePath:"root",ids:F,key:M}},h=(B,M)=>{let F=B?.beforePath||"root",E=(Array.isArray(B?.ids)?`[${B?.ids}]`:B?.ids);return `${F}.${E}___${B?.key}`},a=B=>{if(B.includes("[")&&B.includes("]")){let[M,F,E]=B.split(/[[\]]/);return F.split(",").map(L=>`${M}${L}${E}`)}else return [B]},f={};(B=>produce(B,M=>traverse(M,F=>{let{key:E,parent:Q}=F;if(Q&&E&&Q.$id&&!E.includes("$")){let L=u(Q,E),P=h(L);if(Array.isArray(Q[E])){let k=[];Q[E].forEach(q=>{isObject(q)?(q.$objectPath=L,k.push(q.$id.toString())):q&&k.push(q.toString());}),f[P]={$objectPath:L,$ids:k};}else {let k=Q[E];isObject(k)?(f[P]={$objectPath:L,$ids:[k.$id.toString()]},k.$objectPath=L):k&&(f[P]={$objectPath:L,$ids:[k.toString()]});}}})))(p||{});let $=B=>produce(B,M=>traverse(M,F=>{let{key:E,value:Q,parent:L}=F;L&&E&&!E.includes("$")&&(Array.isArray(Q)||isObject(Q))&&!Array.isArray(L)&&(Array.isArray(L[E])?L[E].forEach(P=>{typeof P!="string"&&(P.$objectPath=u(L,E),P.$parentIsCreate=L.$op==="create",P[Ci]=L.$parentIsCreate||L[Symbol.for("grandChildOfCreate")]);}):isObject(L[E])&&(L[E].$parentIsCreate=L.$op==="create",L[E][Symbol.for("grandChildOfCreate")]=L.$parentIsCreate||L[Symbol.for("grandChildOfCreate")],L[E].$objectPath=u(L,E)));})),g=$(e),y=B=>{let M=[];return B.forEach(E=>{if(!E.$id&&!E.id&&!E.$tempId)if(E.$filter){let Q=h({...E.$objectPath,key:E.$bzId}),L=f[Q];L&&(Array.isArray(L.$ids)?L.$ids:[L.$ids]).forEach(k=>{let q={...E,$id:k,$bzId:`T4_${v4()}`,$filterBzId:E.$bzId};M.push(q);});}else {let Q=h(E.$objectPath),L=f[Q];L?L?.$ids.forEach(P=>{let k={...E,$id:P,$bzId:`T4_${v4()}`};M.push(k);}):M.push(E);}else M.push(E);}),M.map(E=>{let Q={...E};return o(Q,!0).forEach(L=>{let P=Array.isArray(Q[L])?Q[L]:[Q[L]],k=y(P);Q[L]=k;}),Q})},w=y(Array.isArray(g)?g:[g]),T=$(w),D=(B=>{let M=F=>{let E=U=>{let X=[],z=[],I=[];return U.forEach(W=>{let ie=o(W,!0);if(ie.length>0){let C=!1;ie.forEach(_=>{(Array.isArray(W[_])?W[_]:[W[_]]).filter(Y=>!Y.$id&&!Y.id&&typeof W=="object").length&&(C=!0);}),C?X.push(W):z.push(W);}else I.push({...W,$bzId:W.$tempId||`T_${v4()}`});}),{operationWithMultiples:X,operationWithoutMultiples:z,otherOps:I}},{operationWithMultiples:Q,operationWithoutMultiples:L,otherOps:P}=E(F),k=U=>{let z=(()=>{let _={};for(let te in U){let J=O(t,U);!te.startsWith("$")&&J.dataFields?.find(Y=>Y.path===te)&&(_[te]=U[te]);}return _})(),I=Object.keys(U),W=o(U,!0),ie=[],C=(_,te)=>{if(_===W.length){let Y={...te};I.forEach(re=>{re.startsWith("$")&&(Y[re]=U[re]);}),ie.push({...Y,...z});return}let J={...te,[W[_]]:U[W[_]],...me(te),...z};C(_+1,J),C(_+1,te);};return C(0,{...me(U)}),ie},q=[];return Q.forEach(U=>{let X=k(U),z=[];X.forEach(I=>{let W=o(I,!0);if(I.$op==="create")z.push(I);else if(I.$id){let ie=h(I.$objectPath),C=[];if(W.forEach(_=>{let te=`${ie.includes("undefined")?"root":ie}.${I.$id}${Lt}${_}`,J=f[te];I[_].filter(re=>re.$op==="unlink"||re.$op==="delete"||re.$op==="update").length>0?J&&C.push({key:_,ids:J.$ids}):C.push({key:_,ids:[""]});}),C.length===W.length&&!z.find(_=>_.$id===I.$id))z.push(I);else {let _={...I,$bzId:I.$tempId||`T4_${v4()}`};W.forEach(J=>{let Y=I[J].filter(re=>re.$id);Y.length>0?_[J]=Y:_[J]=void 0;}),o(_,!0).length>0&&z.push(_);}}else if(I.$objectPath){let ie=h(I.$objectPath),C=f[ie]?.$ids||[];C.forEach(_=>{let te=[];W.forEach(J=>{let Y=`${ie}.${_}${Lt}${J}`,re=f[Y];re&&te.push({key:J,ids:re.$ids});}),W.length===0?C.filter(Y=>!z.find(re=>re.$id===Y)).forEach(Y=>{z.push({...I,$id:Y,$bzId:I.$tempId||`T_${v4()}`});}):te.length===W.length&&!z.find(J=>J.$id===_)&&(W.forEach(J=>{let Y=`${h(I.$objectPath)}.${_}${Lt}${J}`,{$ids:re}=f[Y],on=I[J].find(Me=>!Me.$id),sn=[...re.map(Me=>({...on,$id:Me,$objectPath:{beforePath:I.$objectPath,ids:Me,key:J}})),...I[J].filter(Me=>Me.$id)];I[J]=sn;}),z.push({...I,$id:_,$bzId:I.$tempId||`T_${v4()}`}));});}else z.push(I);}),z.forEach(I=>{q.push(I);});}),[...q,...L,...P].filter(U=>o(U).length>0?!0:U.$op!=="update").map(U=>{let X={...U};return o(X,!0).forEach(z=>{let I=Array.isArray(X[z])?X[z]:[X[z]],W=M(I);X[z]=W;}),X})};return M(B)})(Array.isArray(T)?T:[T]),R=B=>B.map(M=>{let F=o(M,!0),E={...M};return F.forEach(Q=>{let L=Array.isArray(M[Q])?M[Q]:[M[Q]],P=[],k=[],q=[],v={},ae=Xe(t,M,Q);L.filter(C=>C).forEach(C=>{C.$op==="replace"&&C.$id?(v=C,Array.isArray(C.$id)?k=[...k,...C.$id]:k.push(C.$id)):C.$op==="create"&&ae==="ONE"&&C.id?(v=C,Array.isArray(C.id)?q=[...k,...C.id]:q.push(C.id)):P.push(C);});let Fe=h(v.$objectPath),X=a(Fe).map(C=>f[C]),z=[];X.filter(C=>C!=null).forEach(C=>{z=[...z,...C.$ids];});let I=z.filter(C=>!k.includes(C)),W=k.filter(C=>!z.includes(C)),ie=me(v);I.length>0&&P.push({...v,$op:"unlink",$id:I,$bzId:v.$tempId||`T4_${v4()}`,id:void 0,...ie}),W.length>0&&W.forEach(C=>{P.push({...v,$op:"link",$id:C,$bzId:v.$tempId||`T5_${v4()}`,...ie});}),q.length>0&&q.forEach(C=>{P.push({...v,$op:"create",id:C,$bzId:v.$tempId||`T6_${v4()}`,...ie});}),E[Q]=R(P);}),E}),A=$(R($(D)));(B=>produce(B,M=>traverse(M,F=>{let{key:E,value:Q,parent:L}=F;E&&L&&!E?.includes("$")&&(Array.isArray(Q)||isObject(Q))&&!Array.isArray(L)&&(Array.isArray(Q)?Q:[Q]).forEach(k=>{let q=k.$filter?{...k.$objectPath,key:k.$filterBzId}:k.$objectPath,v=h(q),ae=f[v],Fe=(z,I)=>z.every(W=>I.includes(W)),U=k.$id?Array.isArray(k.$id)?Fe(k.$id,ae?ae.$ids:[]):ae?.$ids.includes(k.$id):ae,X=Xe(t,L,k.$objectPath.key);if(k.$op==="link"&&U&&X==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${h(k.$objectPath)}" because it is already occupied.`);if(k.$op)switch(k.$op){case"delete":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${k.$id}" because it is not linked to $id:"${L.$id}"`);break;case"update":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${k.$id}" because it is not linked to $id:"${L.$id}"`);break;case"unlink":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${k.$id}" because it is not linked to $id:"${L.$id}"`);break;case"link":if(U)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${k.$id}" because it is already linked to $id:"${L.$id}"`);break;}});})))(A);let N=(B=>produce(B,M=>traverse(M,F=>{let{value:E,meta:Q}=F;isObject(E)&&(E[Symbol.for("path")]=Q.nodePath,delete E.$objectPath,delete E.$parentIsCreate);})))(A);return [...Array.isArray(N)?N:[N]].sort((B,M)=>B.$op==="create"&&M.$op!=="create"?-1:B.$op!=="create"&&M.$op==="create"?1:0)};var Hr=(e,t)=>produce(e,i=>Ue(t,i)),Ue=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){t.forEach(o=>Ue(e,o,r));return}let i=ee(e,r||t.$entity||t.$relation||t.$thing);Object.entries(t).forEach(([o])=>{o.startsWith("$")||Ii(e,t,o,i);});},Ii=(e,t,r,i)=>{let o=t[r];if(!o)return;let n=i.dataFields?.find(s=>s.path===r);if(n){n.contentType==="JSON"&&o!=null&&(t[r]=JSON.stringify(o));return}let l=i.linkFields?.find(s=>s.path===r);if(l){let s=l.oppositeLinkFieldsPlayedBy[0]?.thing;Ue(e,o,s);return}if(i.thingType==="relation"){let s=i.roles[r],[c]=s.playedBy||[];if(!c)throw new Error(`Role ${s.name} in ${i} is not played by anything`);Ue(e,o,c.thing);}};var Jr=async(e,t,r,i)=>{let o=Array.isArray(e)?e:[e],n=o.map(c=>kt(c,!0)),s=(await De(n,t,r,i)).bql.res;return o.map((c,p)=>{let u=ee(t,c.$thing);return Yr({mut:c,node:s[p],schema:t,thing:u})})},Zr=new Set(["$op","$bzId","$parentKey"]),qi=new Set(["$relation","$entity","$id",...Zr]),kt=(e,t)=>{let r={};e.$fields?.forEach(o=>{typeof o=="string"?r[o]=o:r[o.$path]=o;});let i={};for(let o in e){if(Zr.has(o)||qi.has(o)&&!t)continue;let n=e[o];o.startsWith("$")?i[o]=n:Array.isArray(n)?n[0]&&typeof n[0]=="object"&&(r[o]={$path:o,...kt(n[0],!1)}):isObject(n)&&(r[o]={$path:o,...kt(n,!1)});}return i.$fields=Object.values(r),i},Yr=e=>{let{mut:t,node:r,schema:i,thing:o}=e,n=Xr(o),l=xi(r);if(Array.isArray(t))return t.map(c=>{let p=l[c.$id];return p?Kr({mut:c,node:p,schema:i,thing:o,...n}):c});let s=l[t.$id];return Kr({mut:t,node:s,schema:i,thing:o,...n})},Kr=e=>{let{mut:t,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:l,roleFieldMap:s}=e,{$fields:c,...p}=t;if(!r)return p;let u=Gr({$fields:t.$fields,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:l,roleFieldMap:s}),h={...p,[Te]:u};for(let a in t){if(a.startsWith("$"))continue;let f=t[a];if(n[a]||!f||typeof f!="object"){h[a]=f;continue}let $=l[a]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||s[a]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${o.name}" does not have field "${a}"`);let g=ee(i,$);h[a]=Yr({mut:f,schema:i,node:r[a],thing:g});}return h},Gr=e=>{let{$fields:t,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:l,roleFieldMap:s}=e,c=t||Oi(o),p={$id:r.$id};return c.forEach(u=>{let h=typeof u!="string",a=h?u.$path:u,f=r[a];if(n[a]){p[a]=f;return}let $=l[a]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||s[a]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${o.name}" does not have field "${a}"`);if(!h){f&&(p[a]=Array.isArray(f)?f.map(Ur):Ur(f));return}let g=ee(i,$),y=Xr(g);p[a]=Array.isArray(f)?f.map(w=>vr({...y,$fields:u.$fields,value:w,schema:i,thing:g})):vr({...y,$fields:u.$fields,value:f,schema:i,thing:g});}),p},Oi=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},Ur=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},vr=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 Gr({...e,node:t})},Xr=e=>{let t=Object.fromEntries(e.dataFields?.map(o=>[o.path,o])||[]),r=Object.fromEntries(e.linkFields?.map(o=>[o.path,o])||[]),i=e.thingType==="relation"?e.roles||{}:{};return {dataFieldMap:t,linkFieldMap:r,roleFieldMap:i}},xi=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 en=ce,Re=(e,t)=>t.data?{...e,bql:{...e.bql,current:t.data}}:e,ji=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Ni=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),_i=(e,t)=>({...e,typeDB:{...e.typeDB,tqlMutation:t.data}}),zi=(e,t)=>({...e,typeDB:{...e.typeDB,tqlRes:t.data}}),Wi=async e=>Object.keys(e.bql.current).length?ot(e.bql.current,e.schema,e.config):ot(e.bql.raw,e.schema,e.config),Vi=async e=>Vr(e.bql.current,e.schema,e.config,e.handles),Hi=async e=>Jr(e.bql.current,e.schema,e.config,e.handles),Ki=async e=>sr(e.bql.current,e.schema),Ui=async e=>ar(e.bql.things,e.bql.edges,e.schema),vi=async e=>er(e.typeDB.tqlMutation,e.handles,e.config),Ji=async e=>tr(e.typeDB.tqlRes,e.bql.things,e.bql.edges,e.schema,e.config),Zi=()=>!0,Yi=e=>ke(e.bql.current),Ee=H("error","error",V((e,t)=>({...e,error:t.error}))),Gi=Be("stringify",{stringify:Z(async e=>Hr(e.bql.raw,e.schema),H("done","enrich",V(Re)),Ee),enrich:Z(Wi,H("done","preQuery",at(Zi),V(Re)),H("done","parseBQL",V(Re)),Ee),preHookDependencies:Z(Hi,H("done","enrich",V(Re)),Ee),preQuery:Z(Vi,H("done","preHookDependencies",at(Yi),V(Re)),H("done","parseBQL",V(Re)),Ee),parseBQL:Z(Ki,H("done","buildMutation",V(Ni)),Ee),buildMutation:Z(Ui,H("done","runMutation",V(_i)),Ee),runMutation:Z(vi,H("done","parseMutation",V(zi)),Ee),parseMutation:Z(Ji,H("done","success",V(ji)),Ee),success:en(),error:en()},e=>e),Xi=async e=>new Promise((t,r)=>{fe(Gi,i=>{i.machine.state.name==="success"&&t(i.context),i.machine.state.name==="error"&&r(i.context);},e);}),tn=async(e,t,r,i)=>Xi({bql:{raw:e,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:t,config:r,handles:i,depthLevel:0,error:null});enableMapSet();var St=class{schema;config;dbHandles;constructor({schema:t,config:r}){this.schema=t,this.config=r;}getDbHandles=()=>this.dbHandles;init=async()=>{let t={typeDB:new Map,surrealDB:new Map};await Promise.all(this.config.dbConnectors.map(async i=>{if(i.provider==="surrealDB"){let o=new Surreal;await o.connect(i.url),await o.signin({namespace:i.namespace,database:i.dbName,username:i.username,password:i.password}),t.surrealDB.set(i.id,{client:o});}if(i.provider==="typeDB"&&i.dbName){let[o,n]=await tryit(TypeDB.coreDriver)(i.url);if(o){let l=`[BORM:${i.provider}:${i.dbName}:core] ${o.message??"Can't create TypeDB Client"}`;throw new Error(l)}try{let l=await n.session(i.dbName,SessionType.DATA);t.typeDB.set(i.id,{client:n,session:l});}catch(l){let s=`[BORM:${i.provider}:${i.dbName}:session] ${(l.messageTemplate?._messageBody()||l.message)??"Can't create TypeDB Session"}`;throw new Error(s)}}if(i.provider==="typeDBCluster"&&i.dbName){let[o,n]=await tryit(TypeDB.cloudDriver)(i.addresses,i.credentials);if(o){let l=`[BORM:${i.provider}:${i.dbName}:core] ${o.message??"Can't create TypeDB Cluster Client"}`;throw new Error(l)}try{let l=await n.session(i.dbName,SessionType.DATA);t.typeDB.set(i.id,{client:n,session:l});}catch(l){let s=`[BORM:${i.provider}:${i.dbName}:session] ${(l.messageTemplate?._messageBody()||l.message)??"Can't create TypeDB Session"}`;throw new Error(s)}}}));let r=Ot(this.schema,t);this.schema=r,this.dbHandles=t;};#e=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#e(),this.schema);define=async()=>(await this.#e(),Rt(this.config,this.schema,this.dbHandles));query=async(t,r)=>{await this.#e();let i={...this.config,query:{...Je.query,...this.config.query,...r}},o=Array.isArray(t),n=o?t:[t],[l,s]=await tryit(De)(n,this.schema,i,this.dbHandles);if(l){let p=new Error(l.error);throw p.stack=l.error.stack,p}let c=s.bql.res;return o?c:c[0]};mutate=async(t,r)=>{await this.#e();let i={...this.config,mutation:{...Je.mutation,...this.config.mutation,...r}},[o,n]=await tryit(tn)(t,this.schema,i,this.dbHandles);if(o){let s=new Error(o.error.message);throw s.stack=o.error.stack,s}return n.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:r})=>{r.isOpen()&&await r.close(),await t.close();});}},Wl=St;//! Todo: delete when this works with the new $thing and $thingType fields
|
|
61
47
|
//! Todo: Sandbox the function in nodeCompute() instead of the existing fieldCompute()
|
|
62
48
|
//! Todo: Sandbox the function in computeFunction()
|
|
63
49
|
//! reads all the insertions and gets the first match. This means each id must be unique
|
|
64
50
|
//!old
|
|
65
51
|
|
|
66
|
-
export {
|
|
52
|
+
export { Wl as default };
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
var y="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",E=new Uint8Array(64),O=new Uint8Array(128);for(let l=0;l<y.length;l++){let t=y.charCodeAt(l);E[l]=t,O[t]=l;}var S=typeof TextDecoder<"u"?new TextDecoder:typeof Buffer<"u"?{decode(l){return Buffer.from(l.buffer,l.byteOffset,l.byteLength).toString()}}:{decode(l){let t="";for(let e=0;e<l.length;e++)t+=String.fromCharCode(l[e]);return t}};function v(l){let t=new Int32Array(5),e=1024*16,n=e-36,i=new Uint8Array(e),r=i.subarray(0,n),s=0,h="";for(let o=0;o<l.length;o++){let a=l[o];if(o>0&&(s===e&&(h+=S.decode(i),s=0),i[s++]=59),a.length!==0){t[0]=0;for(let u=0;u<a.length;u++){let c=a[u];s>n&&(h+=S.decode(r),i.copyWithin(0,n,s),s-=n),u>0&&(i[s++]=44),s=f(i,s,t,c,0),c.length!==1&&(s=f(i,s,t,c,1),s=f(i,s,t,c,2),s=f(i,s,t,c,3),c.length!==4&&(s=f(i,s,t,c,4)));}}}return h+S.decode(i.subarray(0,s))}function f(l,t,e,n,i){let r=n[i],s=r-e[i];e[i]=r,s=s<0?-s<<1|1:s<<1;do{let h=s&31;s>>>=5,s>0&&(h|=32),l[t++]=E[h];}while(s>0);return t}var p=class l{constructor(t){this.bits=t instanceof l?t.bits.slice():[];}add(t){this.bits[t>>5]|=1<<(t&31);}has(t){return !!(this.bits[t>>5]&1<<(t&31))}},w=class l{constructor(t,e,n){this.start=t,this.end=e,this.original=n,this.intro="",this.outro="",this.content=n,this.storeName=!1,this.edited=!1,this.previous=null,this.next=null;}appendLeft(t){this.outro+=t;}appendRight(t){this.intro=this.intro+t;}clone(){let t=new l(this.start,this.end,this.original);return t.intro=this.intro,t.outro=this.outro,t.content=this.content,t.storeName=this.storeName,t.edited=this.edited,t}contains(t){return this.start<t&&t<this.end}eachNext(t){let e=this;for(;e;)t(e),e=e.next;}eachPrevious(t){let e=this;for(;e;)t(e),e=e.previous;}edit(t,e,n){return this.content=t,n||(this.intro="",this.outro=""),this.storeName=e,this.edited=!0,this}prependLeft(t){this.outro=t+this.outro;}prependRight(t){this.intro=t+this.intro;}reset(){this.intro="",this.outro="",this.edited&&(this.content=this.original,this.storeName=!1,this.edited=!1);}split(t){let e=t-this.start,n=this.original.slice(0,e),i=this.original.slice(e);this.original=n;let r=new l(t,this.end,i);return r.outro=this.outro,this.outro="",this.end=t,this.edited?(r.edit("",!1),this.content=""):this.content=n,r.next=this.next,r.next&&(r.next.previous=r),r.previous=this,this.next=r,r}toString(){return this.intro+this.content+this.outro}trimEnd(t){if(this.outro=this.outro.replace(t,""),this.outro.length)return !0;let e=this.content.replace(t,"");if(e.length)return e!==this.content&&(this.split(this.start+e.length).edit("",void 0,!0),this.edited&&this.edit(e,this.storeName,!0)),!0;if(this.edit("",void 0,!0),this.intro=this.intro.replace(t,""),this.intro.length)return !0}trimStart(t){if(this.intro=this.intro.replace(t,""),this.intro.length)return !0;let e=this.content.replace(t,"");if(e.length){if(e!==this.content){let n=this.split(this.end-e.length);this.edited&&n.edit(e,this.storeName,!0),this.edit("",void 0,!0);}return !0}else if(this.edit("",void 0,!0),this.outro=this.outro.replace(t,""),this.outro.length)return !0}};function I(){return typeof globalThis<"u"&&typeof globalThis.btoa=="function"?l=>globalThis.btoa(unescape(encodeURIComponent(l))):typeof Buffer=="function"?l=>Buffer.from(l,"utf-8").toString("base64"):()=>{throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.")}}var N=I(),m=class{constructor(t){this.version=3,this.file=t.file,this.sources=t.sources,this.sourcesContent=t.sourcesContent,this.names=t.names,this.mappings=v(t.mappings),typeof t.x_google_ignoreList<"u"&&(this.x_google_ignoreList=t.x_google_ignoreList);}toString(){return JSON.stringify(this)}toUrl(){return "data:application/json;charset=utf-8;base64,"+N(this.toString())}};function A(l){let t=l.split(`
|
|
2
|
+
`),e=t.filter(r=>/^\t+/.test(r)),n=t.filter(r=>/^ {2,}/.test(r));if(e.length===0&&n.length===0)return null;if(e.length>=n.length)return " ";let i=n.reduce((r,s)=>{let h=/^ +/.exec(s)[0].length;return Math.min(h,r)},1/0);return new Array(i+1).join(" ")}function R(l,t){let e=l.split(/[/\\]/),n=t.split(/[/\\]/);for(e.pop();e[0]===n[0];)e.shift(),n.shift();if(e.length){let i=e.length;for(;i--;)e[i]="..";}return e.concat(n).join("/")}var j=Object.prototype.toString;function _(l){return j.call(l)==="[object Object]"}function x(l){let t=l.split(`
|
|
3
|
+
`),e=[];for(let n=0,i=0;n<t.length;n++)e.push(i),i+=t[n].length+1;return function(i){let r=0,s=e.length;for(;r<s;){let a=r+s>>1;i<e[a]?s=a:r=a+1;}let h=r-1,o=i-e[h];return {line:h,column:o}}}var $=/\w/,b=class{constructor(t){this.hires=t,this.generatedCodeLine=0,this.generatedCodeColumn=0,this.raw=[],this.rawSegments=this.raw[this.generatedCodeLine]=[],this.pending=null;}addEdit(t,e,n,i){if(e.length){let r=e.length-1,s=e.indexOf(`
|
|
4
|
+
`,0),h=-1;for(;s>=0&&r>s;){let a=[this.generatedCodeColumn,t,n.line,n.column];i>=0&&a.push(i),this.rawSegments.push(a),this.generatedCodeLine+=1,this.raw[this.generatedCodeLine]=this.rawSegments=[],this.generatedCodeColumn=0,h=s,s=e.indexOf(`
|
|
5
|
+
`,s+1);}let o=[this.generatedCodeColumn,t,n.line,n.column];i>=0&&o.push(i),this.rawSegments.push(o),this.advance(e.slice(h+1));}else this.pending&&(this.rawSegments.push(this.pending),this.advance(e));this.pending=null;}addUneditedChunk(t,e,n,i,r){let s=e.start,h=!0,o=!1;for(;s<e.end;){if(this.hires||h||r.has(s)){let a=[this.generatedCodeColumn,t,i.line,i.column];this.hires==="boundary"?$.test(n[s])?o||(this.rawSegments.push(a),o=!0):(this.rawSegments.push(a),o=!1):this.rawSegments.push(a);}n[s]===`
|
|
6
|
+
`?(i.line+=1,i.column=0,this.generatedCodeLine+=1,this.raw[this.generatedCodeLine]=this.rawSegments=[],this.generatedCodeColumn=0,h=!0):(i.column+=1,this.generatedCodeColumn+=1,h=!1),s+=1;}this.pending=null;}advance(t){if(!t)return;let e=t.split(`
|
|
7
|
+
`);if(e.length>1){for(let n=0;n<e.length-1;n++)this.generatedCodeLine++,this.raw[this.generatedCodeLine]=this.rawSegments=[];this.generatedCodeColumn=0;}this.generatedCodeColumn+=e[e.length-1].length;}},g=`
|
|
8
|
+
`,d={insertLeft:!1,insertRight:!1,storeName:!1},C=class l{constructor(t,e={}){let n=new w(0,t.length,t);Object.defineProperties(this,{original:{writable:!0,value:t},outro:{writable:!0,value:""},intro:{writable:!0,value:""},firstChunk:{writable:!0,value:n},lastChunk:{writable:!0,value:n},lastSearchedChunk:{writable:!0,value:n},byStart:{writable:!0,value:{}},byEnd:{writable:!0,value:{}},filename:{writable:!0,value:e.filename},indentExclusionRanges:{writable:!0,value:e.indentExclusionRanges},sourcemapLocations:{writable:!0,value:new p},storedNames:{writable:!0,value:{}},indentStr:{writable:!0,value:void 0},ignoreList:{writable:!0,value:e.ignoreList}}),this.byStart[0]=n,this.byEnd[t.length]=n;}addSourcemapLocation(t){this.sourcemapLocations.add(t);}append(t){if(typeof t!="string")throw new TypeError("outro content must be a string");return this.outro+=t,this}appendLeft(t,e){if(typeof e!="string")throw new TypeError("inserted content must be a string");this._split(t);let n=this.byEnd[t];return n?n.appendLeft(e):this.intro+=e,this}appendRight(t,e){if(typeof e!="string")throw new TypeError("inserted content must be a string");this._split(t);let n=this.byStart[t];return n?n.appendRight(e):this.outro+=e,this}clone(){let t=new l(this.original,{filename:this.filename}),e=this.firstChunk,n=t.firstChunk=t.lastSearchedChunk=e.clone();for(;e;){t.byStart[n.start]=n,t.byEnd[n.end]=n;let i=e.next,r=i&&i.clone();r&&(n.next=r,r.previous=n,n=r),e=i;}return t.lastChunk=n,this.indentExclusionRanges&&(t.indentExclusionRanges=this.indentExclusionRanges.slice()),t.sourcemapLocations=new p(this.sourcemapLocations),t.intro=this.intro,t.outro=this.outro,t}generateDecodedMap(t){t=t||{};let e=0,n=Object.keys(this.storedNames),i=new b(t.hires),r=x(this.original);return this.intro&&i.advance(this.intro),this.firstChunk.eachNext(s=>{let h=r(s.start);s.intro.length&&i.advance(s.intro),s.edited?i.addEdit(e,s.content,h,s.storeName?n.indexOf(s.original):-1):i.addUneditedChunk(e,s,this.original,h,this.sourcemapLocations),s.outro.length&&i.advance(s.outro);}),{file:t.file?t.file.split(/[/\\]/).pop():void 0,sources:[t.source?R(t.file||"",t.source):t.file||""],sourcesContent:t.includeContent?[this.original]:void 0,names:n,mappings:i.raw,x_google_ignoreList:this.ignoreList?[e]:void 0}}generateMap(t){return new m(this.generateDecodedMap(t))}_ensureindentStr(){this.indentStr===void 0&&(this.indentStr=A(this.original));}_getRawIndentString(){return this._ensureindentStr(),this.indentStr}getIndentString(){return this._ensureindentStr(),this.indentStr===null?" ":this.indentStr}indent(t,e){let n=/^[^\r\n]/gm;if(_(t)&&(e=t,t=void 0),t===void 0&&(this._ensureindentStr(),t=this.indentStr||" "),t==="")return this;e=e||{};let i={};e.exclude&&(typeof e.exclude[0]=="number"?[e.exclude]:e.exclude).forEach(u=>{for(let c=u[0];c<u[1];c+=1)i[c]=!0;});let r=e.indentStart!==!1,s=a=>r?`${t}${a}`:(r=!0,a);this.intro=this.intro.replace(n,s);let h=0,o=this.firstChunk;for(;o;){let a=o.end;if(o.edited)i[h]||(o.content=o.content.replace(n,s),o.content.length&&(r=o.content[o.content.length-1]===`
|
|
9
|
+
`));else for(h=o.start;h<a;){if(!i[h]){let u=this.original[h];u===`
|
|
10
|
+
`?r=!0:u!=="\r"&&r&&(r=!1,h===o.start||(this._splitChunk(o,h),o=o.next),o.prependRight(t));}h+=1;}h=o.end,o=o.next;}return this.outro=this.outro.replace(n,s),this}insert(){throw new Error("magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)")}insertLeft(t,e){return d.insertLeft||(console.warn("magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead"),d.insertLeft=!0),this.appendLeft(t,e)}insertRight(t,e){return d.insertRight||(console.warn("magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead"),d.insertRight=!0),this.prependRight(t,e)}move(t,e,n){if(n>=t&&n<=e)throw new Error("Cannot move a selection inside itself");this._split(t),this._split(e),this._split(n);let i=this.byStart[t],r=this.byEnd[e],s=i.previous,h=r.next,o=this.byStart[n];if(!o&&r===this.lastChunk)return this;let a=o?o.previous:this.lastChunk;return s&&(s.next=h),h&&(h.previous=s),a&&(a.next=i),o&&(o.previous=r),i.previous||(this.firstChunk=r.next),r.next||(this.lastChunk=i.previous,this.lastChunk.next=null),i.previous=a,r.next=o||null,a||(this.firstChunk=i),o||(this.lastChunk=r),this}overwrite(t,e,n,i){return i=i||{},this.update(t,e,n,{...i,overwrite:!i.contentOnly})}update(t,e,n,i){if(typeof n!="string")throw new TypeError("replacement content must be a string");for(;t<0;)t+=this.original.length;for(;e<0;)e+=this.original.length;if(e>this.original.length)throw new Error("end is out of bounds");if(t===e)throw new Error("Cannot overwrite a zero-length range \u2013 use appendLeft or prependRight instead");this._split(t),this._split(e),i===!0&&(d.storeName||(console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string"),d.storeName=!0),i={storeName:!0});let r=i!==void 0?i.storeName:!1,s=i!==void 0?i.overwrite:!1;if(r){let a=this.original.slice(t,e);Object.defineProperty(this.storedNames,a,{writable:!0,value:!0,enumerable:!0});}let h=this.byStart[t],o=this.byEnd[e];if(h){let a=h;for(;a!==o;){if(a.next!==this.byStart[a.end])throw new Error("Cannot overwrite across a split point");a=a.next,a.edit("",!1);}h.edit(n,r,!s);}else {let a=new w(t,e,"").edit(n,r);o.next=a,a.previous=o;}return this}prepend(t){if(typeof t!="string")throw new TypeError("outro content must be a string");return this.intro=t+this.intro,this}prependLeft(t,e){if(typeof e!="string")throw new TypeError("inserted content must be a string");this._split(t);let n=this.byEnd[t];return n?n.prependLeft(e):this.intro=e+this.intro,this}prependRight(t,e){if(typeof e!="string")throw new TypeError("inserted content must be a string");this._split(t);let n=this.byStart[t];return n?n.prependRight(e):this.outro=e+this.outro,this}remove(t,e){for(;t<0;)t+=this.original.length;for(;e<0;)e+=this.original.length;if(t===e)return this;if(t<0||e>this.original.length)throw new Error("Character is out of bounds");if(t>e)throw new Error("end must be greater than start");this._split(t),this._split(e);let n=this.byStart[t];for(;n;)n.intro="",n.outro="",n.edit(""),n=e>n.end?this.byStart[n.end]:null;return this}reset(t,e){for(;t<0;)t+=this.original.length;for(;e<0;)e+=this.original.length;if(t===e)return this;if(t<0||e>this.original.length)throw new Error("Character is out of bounds");if(t>e)throw new Error("end must be greater than start");this._split(t),this._split(e);let n=this.byStart[t];for(;n;)n.reset(),n=e>n.end?this.byStart[n.end]:null;return this}lastChar(){if(this.outro.length)return this.outro[this.outro.length-1];let t=this.lastChunk;do{if(t.outro.length)return t.outro[t.outro.length-1];if(t.content.length)return t.content[t.content.length-1];if(t.intro.length)return t.intro[t.intro.length-1]}while(t=t.previous);return this.intro.length?this.intro[this.intro.length-1]:""}lastLine(){let t=this.outro.lastIndexOf(g);if(t!==-1)return this.outro.substr(t+1);let e=this.outro,n=this.lastChunk;do{if(n.outro.length>0){if(t=n.outro.lastIndexOf(g),t!==-1)return n.outro.substr(t+1)+e;e=n.outro+e;}if(n.content.length>0){if(t=n.content.lastIndexOf(g),t!==-1)return n.content.substr(t+1)+e;e=n.content+e;}if(n.intro.length>0){if(t=n.intro.lastIndexOf(g),t!==-1)return n.intro.substr(t+1)+e;e=n.intro+e;}}while(n=n.previous);return t=this.intro.lastIndexOf(g),t!==-1?this.intro.substr(t+1)+e:this.intro+e}slice(t=0,e=this.original.length){for(;t<0;)t+=this.original.length;for(;e<0;)e+=this.original.length;let n="",i=this.firstChunk;for(;i&&(i.start>t||i.end<=t);){if(i.start<e&&i.end>=e)return n;i=i.next;}if(i&&i.edited&&i.start!==t)throw new Error(`Cannot use replaced character ${t} as slice start anchor.`);let r=i;for(;i;){i.intro&&(r!==i||i.start===t)&&(n+=i.intro);let s=i.start<e&&i.end>=e;if(s&&i.edited&&i.end!==e)throw new Error(`Cannot use replaced character ${e} as slice end anchor.`);let h=r===i?t-i.start:0,o=s?i.content.length+e-i.end:i.content.length;if(n+=i.content.slice(h,o),i.outro&&(!s||i.end===e)&&(n+=i.outro),s)break;i=i.next;}return n}snip(t,e){let n=this.clone();return n.remove(0,t),n.remove(e,n.original.length),n}_split(t){if(this.byStart[t]||this.byEnd[t])return;let e=this.lastSearchedChunk,n=t>e.end;for(;e;){if(e.contains(t))return this._splitChunk(e,t);e=n?this.byStart[e.end]:this.byEnd[e.start];}}_splitChunk(t,e){if(t.edited&&t.content.length){let i=x(this.original)(e);throw new Error(`Cannot split a chunk that has already been edited (${i.line}:${i.column} \u2013 "${t.original}")`)}let n=t.split(e);return this.byEnd[e]=t,this.byStart[e]=n,this.byEnd[n.end]=n,t===this.lastChunk&&(this.lastChunk=n),this.lastSearchedChunk=t,!0}toString(){let t=this.intro,e=this.firstChunk;for(;e;)t+=e.toString(),e=e.next;return t+this.outro}isEmpty(){let t=this.firstChunk;do if(t.intro.length&&t.intro.trim()||t.content.length&&t.content.trim()||t.outro.length&&t.outro.trim())return !1;while(t=t.next);return !0}length(){let t=this.firstChunk,e=0;do e+=t.intro.length+t.content.length+t.outro.length;while(t=t.next);return e}trimLines(){return this.trim("[\\r\\n]")}trim(t){return this.trimStart(t).trimEnd(t)}trimEndAborted(t){let e=new RegExp((t||"\\s")+"+$");if(this.outro=this.outro.replace(e,""),this.outro.length)return !0;let n=this.lastChunk;do{let i=n.end,r=n.trimEnd(e);if(n.end!==i&&(this.lastChunk===n&&(this.lastChunk=n.next),this.byEnd[n.end]=n,this.byStart[n.next.start]=n.next,this.byEnd[n.next.end]=n.next),r)return !0;n=n.previous;}while(n);return !1}trimEnd(t){return this.trimEndAborted(t),this}trimStartAborted(t){let e=new RegExp("^"+(t||"\\s")+"+");if(this.intro=this.intro.replace(e,""),this.intro.length)return !0;let n=this.firstChunk;do{let i=n.end,r=n.trimStart(e);if(n.end!==i&&(n===this.lastChunk&&(this.lastChunk=n.next),this.byEnd[n.end]=n,this.byStart[n.next.start]=n.next,this.byEnd[n.next.end]=n.next),r)return !0;n=n.next;}while(n);return !1}trimStart(t){return this.trimStartAborted(t),this}hasChanged(){return this.original!==this.toString()}_replaceRegexp(t,e){function n(r,s){return typeof e=="string"?e.replace(/\$(\$|&|\d+)/g,(h,o)=>o==="$"?"$":o==="&"?r[0]:+o<r.length?r[+o]:`$${o}`):e(...r,r.index,s,r.groups)}function i(r,s){let h,o=[];for(;h=r.exec(s);)o.push(h);return o}if(t.global)i(t,this.original).forEach(s=>{if(s.index!=null){let h=n(s,this.original);h!==s[0]&&this.overwrite(s.index,s.index+s[0].length,h);}});else {let r=this.original.match(t);if(r&&r.index!=null){let s=n(r,this.original);s!==r[0]&&this.overwrite(r.index,r.index+r[0].length,s);}}return this}_replaceString(t,e){let{original:n}=this,i=n.indexOf(t);return i!==-1&&this.overwrite(i,i+t.length,e),this}replace(t,e){return typeof t=="string"?this._replaceString(t,e):this._replaceRegexp(t,e)}_replaceAllString(t,e){let{original:n}=this,i=t.length;for(let r=n.indexOf(t);r!==-1;r=n.indexOf(t,r+i))n.slice(r,r+i)!==e&&this.overwrite(r,r+i,e);return this}replaceAll(t,e){if(typeof t=="string")return this._replaceAllString(t,e);if(!t.global)throw new TypeError("MagicString.prototype.replaceAll called with a non-global RegExp argument");return this._replaceRegexp(t,e)}},L=Object.prototype.hasOwnProperty,k=class l{constructor(t={}){this.intro=t.intro||"",this.separator=t.separator!==void 0?t.separator:`
|
|
11
|
+
`,this.sources=[],this.uniqueSources=[],this.uniqueSourceIndexByFilename={};}addSource(t){if(t instanceof C)return this.addSource({content:t,filename:t.filename,separator:this.separator});if(!_(t)||!t.content)throw new Error("bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`");if(["filename","ignoreList","indentExclusionRanges","separator"].forEach(e=>{L.call(t,e)||(t[e]=t.content[e]);}),t.separator===void 0&&(t.separator=this.separator),t.filename)if(!L.call(this.uniqueSourceIndexByFilename,t.filename))this.uniqueSourceIndexByFilename[t.filename]=this.uniqueSources.length,this.uniqueSources.push({filename:t.filename,content:t.content.original});else {let e=this.uniqueSources[this.uniqueSourceIndexByFilename[t.filename]];if(t.content.original!==e.content)throw new Error(`Illegal source: same filename (${t.filename}), different contents`)}return this.sources.push(t),this}append(t,e){return this.addSource({content:new C(t),separator:e&&e.separator||""}),this}clone(){let t=new l({intro:this.intro,separator:this.separator});return this.sources.forEach(e=>{t.addSource({filename:e.filename,content:e.content.clone(),separator:e.separator});}),t}generateDecodedMap(t={}){let e=[],n;this.sources.forEach(r=>{Object.keys(r.content.storedNames).forEach(s=>{~e.indexOf(s)||e.push(s);});});let i=new b(t.hires);return this.intro&&i.advance(this.intro),this.sources.forEach((r,s)=>{s>0&&i.advance(this.separator);let h=r.filename?this.uniqueSourceIndexByFilename[r.filename]:-1,o=r.content,a=x(o.original);o.intro&&i.advance(o.intro),o.firstChunk.eachNext(u=>{let c=a(u.start);u.intro.length&&i.advance(u.intro),r.filename?u.edited?i.addEdit(h,u.content,c,u.storeName?e.indexOf(u.original):-1):i.addUneditedChunk(h,u,o.original,c,o.sourcemapLocations):i.advance(u.content),u.outro.length&&i.advance(u.outro);}),o.outro&&i.advance(o.outro),r.ignoreList&&h!==-1&&(n===void 0&&(n=[]),n.push(h));}),{file:t.file?t.file.split(/[/\\]/).pop():void 0,sources:this.uniqueSources.map(r=>t.file?R(t.file,r.filename):r.filename),sourcesContent:this.uniqueSources.map(r=>t.includeContent?r.content:null),names:e,mappings:i.raw,x_google_ignoreList:n}}generateMap(t){return new m(this.generateDecodedMap(t))}getIndentString(){let t={};return this.sources.forEach(e=>{let n=e.content._getRawIndentString();n!==null&&(t[n]||(t[n]=0),t[n]+=1);}),Object.keys(t).sort((e,n)=>t[e]-t[n])[0]||" "}indent(t){if(arguments.length||(t=this.getIndentString()),t==="")return this;let e=!this.intro||this.intro.slice(-1)===`
|
|
12
|
+
`;return this.sources.forEach((n,i)=>{let r=n.separator!==void 0?n.separator:this.separator,s=e||i>0&&/\r?\n$/.test(r);n.content.indent(t,{exclude:n.indentExclusionRanges,indentStart:s}),e=n.content.lastChar()===`
|
|
13
|
+
`;}),this.intro&&(this.intro=t+this.intro.replace(/^[^\n]/gm,(n,i)=>i>0?t+n:n)),this}prepend(t){return this.intro=t+this.intro,this}toString(){let t=this.sources.map((e,n)=>{let i=e.separator!==void 0?e.separator:this.separator;return (n>0?i:"")+e.content.toString()}).join("");return this.intro+t}isEmpty(){return !(this.intro.length&&this.intro.trim()||this.sources.some(t=>!t.content.isEmpty()))}length(){return this.sources.reduce((t,e)=>t+e.content.length(),this.intro.length)}trimLines(){return this.trim("[\\r\\n]")}trim(t){return this.trimStart(t).trimEnd(t)}trimStart(t){let e=new RegExp("^"+(t||"\\s")+"+");if(this.intro=this.intro.replace(e,""),!this.intro){let n,i=0;do if(n=this.sources[i++],!n)break;while(!n.content.trimStartAborted(t))}return this}trimEnd(t){let e=new RegExp((t||"\\s")+"+$"),n,i=this.sources.length-1;do if(n=this.sources[i--],!n){this.intro=this.intro.replace(e,"");break}while(!n.content.trimEndAborted(t));return this}};
|
|
14
|
+
|
|
15
|
+
export { k as Bundle, m as SourceMap, C as default };
|