@blitznocode/blitz-orm 0.1.10 → 0.1.11

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.
Files changed (3) hide show
  1. package/dist/index.d.ts +255 -255
  2. package/dist/index.js +4 -4
  3. package/package.json +21 -21
package/dist/index.d.ts CHANGED
@@ -1,262 +1,262 @@
1
1
  import { TypeDBClient, TypeDBSession } from 'typedb-client';
2
2
 
3
- type BormConfig = {
4
- server: {
5
- provider: 'blitz-orm-js';
6
- };
7
- query?: {
8
- noMetadata?: boolean;
9
- simplifiedLinks?: boolean;
10
- debugger?: boolean;
11
- };
12
- mutation?: {
13
- noMetadata?: boolean;
14
- };
15
- dbConnectors: [ProviderObject, ...ProviderObject[]];
16
- };
17
- type ProviderObject = {
18
- id: string;
19
- provider: 'typeDB';
20
- dbName: string;
21
- url: string;
22
- };
23
- type DBConnector = {
24
- id: string;
25
- subs?: string;
26
- path?: string;
27
- as?: string;
28
- };
29
- type TypeDBHandles = Map<string, {
30
- client: TypeDBClient;
31
- session: TypeDBSession;
32
- }>;
33
- type DBHandles = {
34
- typeDB: TypeDBHandles;
35
- };
36
- type BormSchema = {
37
- entities: {
38
- [s: string]: BormEntity;
39
- };
40
- relations: {
41
- [s: string]: BormRelation;
42
- };
43
- };
44
- type EnrichedBormSchema = {
45
- entities: {
46
- [s: string]: EnrichedBormEntity;
47
- };
48
- relations: {
49
- [s: string]: EnrichedBormRelation;
50
- };
51
- };
52
- type BormEntity = {
53
- extends: string;
54
- idFields?: string[];
55
- defaultDBConnector: DBConnector;
56
- dataFields?: DataField[];
57
- linkFields?: LinkField[];
58
- } | {
59
- extends?: string;
60
- idFields: string[];
61
- defaultDBConnector: DBConnector;
62
- dataFields?: DataField[];
63
- linkFields?: LinkField[];
64
- };
65
- type BormRelation = BormEntity & {
66
- defaultDBConnector: DBConnector & {
67
- path: string;
68
- };
69
- roles?: {
70
- [key: string]: RoleField;
71
- };
72
- };
73
- type EnrichedBormEntity = Omit<BormEntity, 'linkFields' | 'idFields' | 'dataFields'> & {
74
- extends?: string;
75
- allExtends?: string[];
76
- idFields: string[];
77
- thingType: 'entity';
78
- name: string;
79
- computedFields: string[];
80
- linkFields?: EnrichedLinkField[];
81
- dataFields?: EnrichedDataField[];
82
- };
83
- type EnrichedBormRelation = Omit<BormRelation, 'linkFields' | 'dataFields'> & {
84
- thingType: 'relation';
85
- name: string;
86
- computedFields: string[];
87
- linkFields?: EnrichedLinkField[];
88
- dataFields?: EnrichedDataField[];
89
- roles: {
90
- [key: string]: EnrichedRoleField;
91
- };
92
- };
93
- type LinkField = BormField & {
94
- relation: string;
95
- plays: string;
96
- } & ({
97
- target: 'role';
98
- filter?: Filter | Filter[];
99
- } | {
100
- target: 'relation';
101
- });
102
- type LinkedFieldWithThing = LinkField & {
103
- thing: string;
104
- thingType: ThingType;
105
- };
106
- type RequireAtLeastOne<T> = {
107
- [K in keyof T]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<keyof T, K>>>;
108
- }[keyof T];
109
- type LinkFilter = {
110
- $thing?: string;
111
- $thingType?: string;
112
- $role?: string;
113
- [key: string]: string | number | Filter | undefined;
114
- };
115
- type Filter = DataFilter | LinkFilter | MiddleFilter;
116
- type MiddleFilter = {
117
- $and?: Filter[];
118
- $or?: Filter[];
119
- };
120
- type DataFilter = RequireAtLeastOne<{
121
- $eq?: any;
122
- $ge?: number | string;
123
- }>;
124
- type EnrichedLinkField = BormField & {
125
- name: string;
126
- relation: string;
127
- plays: string;
128
- } & ({
129
- target: 'role';
130
- filter?: Filter | Filter[];
131
- oppositeLinkFieldsPlayedBy: LinkedFieldWithThing[];
132
- } | {
133
- target: 'relation';
134
- oppositeLinkFieldsPlayedBy: Pick<LinkedFieldWithThing, 'thing' | 'thingType' | 'plays'>[];
135
- });
136
- type BormField = {
137
- path: string;
138
- cardinality: CardinalityType;
139
- ordered?: boolean;
140
- embedded?: boolean;
141
- rights?: RightType[];
142
- };
143
- type RoleField = {
144
- cardinality: CardinalityType;
145
- dbConnector?: DBConnector;
146
- };
147
- type EnrichedRoleField = RoleField & {
148
- playedBy?: LinkedFieldWithThing[];
149
- name: string;
150
- };
151
- type DataField = BormField & {
152
- shared?: boolean;
153
- default?: any;
154
- contentType: ContentType;
155
- validations?: any;
156
- dbConnectors?: [DBConnector, ...DBConnector[]];
157
- };
158
- type EnrichedDataField = DataField & {
159
- dbPath: string;
160
- };
161
- type ThingType = 'entity' | 'relation' | 'attribute';
162
- type RightType = 'CREATE' | 'DELETE' | 'UPDATE' | 'LINK' | 'UNLINK';
163
- type ContentType = 'ID' | 'JSON' | 'COLOR' | 'BOOLEAN' | 'POINT' | 'FILE' | 'EMAIL' | 'PHONE' | 'WEEK_DAY' | 'DURATION' | 'HOUR' | 'TIME' | 'DATE' | 'RATING' | 'CURRENCY' | 'PERCENTAGE' | 'NUMBER_DECIMAL' | 'NUMBER' | 'URL' | 'PASSWORD' | 'LANGUAGE_TEXT' | 'RICH_TEXT' | 'TEXT';
164
- type CardinalityType = 'ONE' | 'MANY' | 'INTERVAL';
165
- type RelationClassType = 'SYMMETRICAL' | 'OWNED';
166
- type RequiredKey<T, K extends keyof T> = T & {
167
- [P in K]-?: T[P];
168
- };
169
- type WithRequired<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>> & RequiredKey<T, K>;
170
- type BQLMutationBlock = {
171
- [key: string]: any;
172
- $id?: string | string[];
173
- $filter?: Filter | Filter[];
174
- $tempId?: string;
175
- $op?: string;
176
- } & ({
177
- $entity: string;
178
- } | {
179
- $relation: string;
180
- });
181
- type FilledBQLMutationBlock = WithRequired<BQLMutationBlock, '$tempId' | '$op'>;
182
- type BQLFieldObj = {
183
- $path: string;
184
- } & Omit<RawBQLQuery, '$entity' | '$relation'>;
185
- type BQLField = string | BQLFieldObj;
186
- type RawBQLQuery = {
187
- $id?: string | string[];
188
- $filter?: Record<string, any>;
189
- $fields?: BQLField[];
190
- $excludedFields?: BQLField[];
191
- } & ({
192
- $entity: string;
193
- } | {
194
- $relation: string;
195
- });
196
- type RawBQLMutation = ({
197
- $entity: string;
198
- } | {
199
- $relation: string;
200
- }) & Record<string, any>;
201
- type ParsedBQLQuery = Omit<RawBQLQuery, '$entity' | '$relation'> & {
202
- $localFilters?: Record<string, any>;
203
- $nestedFilters?: Record<string, any>;
204
- } & ({
205
- $entity: EnrichedBormEntity;
206
- } | {
207
- $relation: EnrichedBormRelation;
208
- });
209
- type ParsedBQLMutation = {
210
- things: BQLMutationBlock[];
211
- edges: BQLMutationBlock[];
212
- };
213
- type TQLRequest = {
214
- entity?: string;
215
- roles?: {
216
- path: string;
217
- request: string;
218
- owner: string;
219
- }[];
220
- relations?: {
221
- relation: string;
222
- entity: string;
223
- request: string;
224
- }[];
225
- insertionMatches?: string;
226
- deletionMatches?: string;
227
- insertions?: string;
228
- deletions?: string;
229
- };
230
- type TQLEntityMutation = {
231
- entity: string;
232
- relations?: {
233
- relation: string;
234
- entity: string;
235
- request: string;
236
- }[];
237
- };
238
- type BQLResponseSingle = (({
239
- $entity: string;
240
- $id: string;
241
- } | undefined) & Record<string, any>) | string | null;
242
- type BQLResponseMulti = BQLResponseSingle[];
3
+ type BormConfig = {
4
+ server: {
5
+ provider: 'blitz-orm-js';
6
+ };
7
+ query?: {
8
+ noMetadata?: boolean;
9
+ simplifiedLinks?: boolean;
10
+ debugger?: boolean;
11
+ };
12
+ mutation?: {
13
+ noMetadata?: boolean;
14
+ };
15
+ dbConnectors: [ProviderObject, ...ProviderObject[]];
16
+ };
17
+ type ProviderObject = {
18
+ id: string;
19
+ provider: 'typeDB';
20
+ dbName: string;
21
+ url: string;
22
+ };
23
+ type DBConnector = {
24
+ id: string;
25
+ subs?: string;
26
+ path?: string;
27
+ as?: string;
28
+ };
29
+ type TypeDBHandles = Map<string, {
30
+ client: TypeDBClient;
31
+ session: TypeDBSession;
32
+ }>;
33
+ type DBHandles = {
34
+ typeDB: TypeDBHandles;
35
+ };
36
+ type BormSchema = {
37
+ entities: {
38
+ [s: string]: BormEntity;
39
+ };
40
+ relations: {
41
+ [s: string]: BormRelation;
42
+ };
43
+ };
44
+ type EnrichedBormSchema = {
45
+ entities: {
46
+ [s: string]: EnrichedBormEntity;
47
+ };
48
+ relations: {
49
+ [s: string]: EnrichedBormRelation;
50
+ };
51
+ };
52
+ type BormEntity = {
53
+ extends: string;
54
+ idFields?: string[];
55
+ defaultDBConnector: DBConnector;
56
+ dataFields?: DataField[];
57
+ linkFields?: LinkField[];
58
+ } | {
59
+ extends?: string;
60
+ idFields: string[];
61
+ defaultDBConnector: DBConnector;
62
+ dataFields?: DataField[];
63
+ linkFields?: LinkField[];
64
+ };
65
+ type BormRelation = BormEntity & {
66
+ defaultDBConnector: DBConnector & {
67
+ path: string;
68
+ };
69
+ roles?: {
70
+ [key: string]: RoleField;
71
+ };
72
+ };
73
+ type EnrichedBormEntity = Omit<BormEntity, 'linkFields' | 'idFields' | 'dataFields'> & {
74
+ extends?: string;
75
+ allExtends?: string[];
76
+ idFields: string[];
77
+ thingType: 'entity';
78
+ name: string;
79
+ computedFields: string[];
80
+ linkFields?: EnrichedLinkField[];
81
+ dataFields?: EnrichedDataField[];
82
+ };
83
+ type EnrichedBormRelation = Omit<BormRelation, 'linkFields' | 'dataFields'> & {
84
+ thingType: 'relation';
85
+ name: string;
86
+ computedFields: string[];
87
+ linkFields?: EnrichedLinkField[];
88
+ dataFields?: EnrichedDataField[];
89
+ roles: {
90
+ [key: string]: EnrichedRoleField;
91
+ };
92
+ };
93
+ type LinkField = BormField & {
94
+ relation: string;
95
+ plays: string;
96
+ } & ({
97
+ target: 'role';
98
+ filter?: Filter | Filter[];
99
+ } | {
100
+ target: 'relation';
101
+ });
102
+ type LinkedFieldWithThing = LinkField & {
103
+ thing: string;
104
+ thingType: ThingType;
105
+ };
106
+ type RequireAtLeastOne<T> = {
107
+ [K in keyof T]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<keyof T, K>>>;
108
+ }[keyof T];
109
+ type LinkFilter = {
110
+ $thing?: string;
111
+ $thingType?: string;
112
+ $role?: string;
113
+ [key: string]: string | number | Filter | undefined;
114
+ };
115
+ type Filter = DataFilter | LinkFilter | MiddleFilter;
116
+ type MiddleFilter = {
117
+ $and?: Filter[];
118
+ $or?: Filter[];
119
+ };
120
+ type DataFilter = RequireAtLeastOne<{
121
+ $eq?: any;
122
+ $ge?: number | string;
123
+ }>;
124
+ type EnrichedLinkField = BormField & {
125
+ name: string;
126
+ relation: string;
127
+ plays: string;
128
+ } & ({
129
+ target: 'role';
130
+ filter?: Filter | Filter[];
131
+ oppositeLinkFieldsPlayedBy: LinkedFieldWithThing[];
132
+ } | {
133
+ target: 'relation';
134
+ oppositeLinkFieldsPlayedBy: Pick<LinkedFieldWithThing, 'thing' | 'thingType' | 'plays'>[];
135
+ });
136
+ type BormField = {
137
+ path: string;
138
+ cardinality: CardinalityType;
139
+ ordered?: boolean;
140
+ embedded?: boolean;
141
+ rights?: RightType[];
142
+ };
143
+ type RoleField = {
144
+ cardinality: CardinalityType;
145
+ dbConnector?: DBConnector;
146
+ };
147
+ type EnrichedRoleField = RoleField & {
148
+ playedBy?: LinkedFieldWithThing[];
149
+ name: string;
150
+ };
151
+ type DataField = BormField & {
152
+ shared?: boolean;
153
+ default?: any;
154
+ contentType: ContentType;
155
+ validations?: any;
156
+ dbConnectors?: [DBConnector, ...DBConnector[]];
157
+ };
158
+ type EnrichedDataField = DataField & {
159
+ dbPath: string;
160
+ };
161
+ type ThingType = 'entity' | 'relation' | 'attribute';
162
+ type RightType = 'CREATE' | 'DELETE' | 'UPDATE' | 'LINK' | 'UNLINK';
163
+ type ContentType = 'ID' | 'JSON' | 'COLOR' | 'BOOLEAN' | 'POINT' | 'FILE' | 'EMAIL' | 'PHONE' | 'WEEK_DAY' | 'DURATION' | 'HOUR' | 'TIME' | 'DATE' | 'RATING' | 'CURRENCY' | 'PERCENTAGE' | 'NUMBER_DECIMAL' | 'NUMBER' | 'URL' | 'PASSWORD' | 'LANGUAGE_TEXT' | 'RICH_TEXT' | 'TEXT';
164
+ type CardinalityType = 'ONE' | 'MANY' | 'INTERVAL';
165
+ type RelationClassType = 'SYMMETRICAL' | 'OWNED';
166
+ type RequiredKey<T, K extends keyof T> = T & {
167
+ [P in K]-?: T[P];
168
+ };
169
+ type WithRequired<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>> & RequiredKey<T, K>;
170
+ type BQLMutationBlock = {
171
+ [key: string]: any;
172
+ $id?: string | string[];
173
+ $filter?: Filter | Filter[];
174
+ $tempId?: string;
175
+ $op?: string;
176
+ } & ({
177
+ $entity: string;
178
+ } | {
179
+ $relation: string;
180
+ });
181
+ type FilledBQLMutationBlock = WithRequired<BQLMutationBlock, '$tempId' | '$op'>;
182
+ type BQLFieldObj = {
183
+ $path: string;
184
+ } & Omit<RawBQLQuery, '$entity' | '$relation'>;
185
+ type BQLField = string | BQLFieldObj;
186
+ type RawBQLQuery = {
187
+ $id?: string | string[];
188
+ $filter?: Record<string, any>;
189
+ $fields?: BQLField[];
190
+ $excludedFields?: BQLField[];
191
+ } & ({
192
+ $entity: string;
193
+ } | {
194
+ $relation: string;
195
+ });
196
+ type RawBQLMutation = ({
197
+ $entity: string;
198
+ } | {
199
+ $relation: string;
200
+ }) & Record<string, any>;
201
+ type ParsedBQLQuery = Omit<RawBQLQuery, '$entity' | '$relation'> & {
202
+ $localFilters?: Record<string, any>;
203
+ $nestedFilters?: Record<string, any>;
204
+ } & ({
205
+ $entity: EnrichedBormEntity;
206
+ } | {
207
+ $relation: EnrichedBormRelation;
208
+ });
209
+ type ParsedBQLMutation = {
210
+ things: BQLMutationBlock[];
211
+ edges: BQLMutationBlock[];
212
+ };
213
+ type TQLRequest = {
214
+ entity?: string;
215
+ roles?: {
216
+ path: string;
217
+ request: string;
218
+ owner: string;
219
+ }[];
220
+ relations?: {
221
+ relation: string;
222
+ entity: string;
223
+ request: string;
224
+ }[];
225
+ insertionMatches?: string;
226
+ deletionMatches?: string;
227
+ insertions?: string;
228
+ deletions?: string;
229
+ };
230
+ type TQLEntityMutation = {
231
+ entity: string;
232
+ relations?: {
233
+ relation: string;
234
+ entity: string;
235
+ request: string;
236
+ }[];
237
+ };
238
+ type BQLResponseSingle = (({
239
+ $entity: string;
240
+ $id: string;
241
+ } | undefined) & Record<string, any>) | string | null;
242
+ type BQLResponseMulti = BQLResponseSingle[];
243
243
  type BQLResponse = BQLResponseSingle | BQLResponseMulti;
244
244
 
245
- type BormProps = {
246
- schema: BormSchema;
247
- config: BormConfig;
248
- };
249
- declare class BormClient {
250
- #private;
251
- private schema;
252
- private config;
253
- private dbHandles?;
254
- constructor({ schema, config }: BormProps);
255
- init: () => Promise<void>;
256
- introspect: () => Promise<BormSchema>;
257
- query: (query: RawBQLQuery, queryConfig?: any) => Promise<void | BQLResponse>;
258
- mutate: (mutation: RawBQLMutation | RawBQLMutation[], mutationConfig?: any) => Promise<void | BQLResponse>;
259
- close: () => Promise<void>;
245
+ type BormProps = {
246
+ schema: BormSchema;
247
+ config: BormConfig;
248
+ };
249
+ declare class BormClient {
250
+ #private;
251
+ private schema;
252
+ private config;
253
+ private dbHandles?;
254
+ constructor({ schema, config }: BormProps);
255
+ init: () => Promise<void>;
256
+ introspect: () => Promise<BormSchema>;
257
+ query: (query: RawBQLQuery, queryConfig?: any) => Promise<void | BQLResponse>;
258
+ mutate: (mutation: RawBQLMutation | RawBQLMutation[], mutationConfig?: any) => Promise<void | BQLResponse>;
259
+ close: () => Promise<void>;
260
260
  }
261
261
 
262
262
  export { BQLField, BQLFieldObj, BQLMutationBlock, BQLResponse, BQLResponseMulti, BQLResponseSingle, BormConfig, BormEntity, BormField, BormRelation, BormSchema, CardinalityType, ContentType, DBConnector, DBHandles, DataField, DataFilter, EnrichedBormEntity, EnrichedBormRelation, EnrichedBormSchema, EnrichedDataField, EnrichedLinkField, EnrichedRoleField, FilledBQLMutationBlock, Filter, LinkField, LinkFilter, LinkedFieldWithThing, MiddleFilter, ParsedBQLMutation, ParsedBQLQuery, ProviderObject, RawBQLMutation, RawBQLQuery, RelationClassType, RightType, RoleField, TQLEntityMutation, TQLRequest, ThingType, BormClient as default };
package/dist/index.js CHANGED
@@ -2,13 +2,13 @@
2
2
 
3
3
  var radash = require('radash');
4
4
  var typedbClient = require('typedb-client');
5
- var dt = require('immer');
5
+ var immer = require('immer');
6
6
  var objectTraversal = require('object-traversal');
7
7
  var uuid = require('uuid');
8
8
 
9
- var et={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1},mutation:{}};var pt=(f,r,l)=>l?r:`${f}\xB7${r}`,ct=f=>{let r=f.split("\xB7");return r[r.length-1]},J=(f,r)=>Object.values(Object.fromEntries(Object.entries(f).filter(([l,n])=>r(l,n))))[0],x=(f,r)=>Object.fromEntries(Object.entries(f).filter(([l,n])=>r(l,n))),ft=f=>{let r=[],l=dt(f,h=>objectTraversal.traverse(h,({key:p,value:a,meta:$})=>{if($.depth===2&&(p&&(a.dataFields=a.dataFields?.map(y=>({...y,dbPath:pt(p,y.path,y.shared)}))),a.extends)){let y=h.entities[a.extends]||h.relations[a.extends];if(a.allExtends=[a.extends,...y.allExtends||[]],a.idFields=y.idFields?(a.idFields||[]).concat(y.idFields):a.idFields,a.dataFields=y.dataFields?(a.dataFields||[]).concat(y.dataFields.map(g=>{let d=a.extends,c=f.entities[d]||f.relations[d];for(;!c.dataFields?.find(o=>o.path===g.path);)d=c.extends,c=f.entities[d]||f.relations[d];return {...g,dbPath:pt(d,g.path,g.shared)}})):a.dataFields,a.linkFields=y.linkFields?(a.linkFields||[]).concat(y.linkFields):a.linkFields,"roles"in y){let g=a,d=y;g.roles=g.roles||{},g.roles={...g.roles,...d.roles},Object.keys(g.roles).length===0&&(g.roles={});}}},{traversalType:"breadth-first"}));return objectTraversal.traverse(f,({key:h,value:p,meta:a})=>{if(h==="linkFields"){let y=(()=>{if(!a.nodePath)throw new Error("No path");let[d,c]=a.nodePath.split(".");return {thing:c,thingType:d==="entities"?"entity":d==="relations"?"relation":""}})(),g=Array.isArray(p)?p.map(d=>({...d,...y})):[{...p,...y}];r.push(...g);}}),dt(l,h=>objectTraversal.traverse(h,({value:p,key:a,meta:$})=>{if($.depth===2&&p.idFields&&!p.id){p.name=a;let y=()=>{if($.nodePath?.split(".")[0]==="entities")return "entity";if($.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};p.thingType=y(),p.computedFields=[],"roles"in p&&Object.entries(p.roles).forEach(([d,c])=>{c.playedBy=r.filter(o=>o.relation===a&&o.plays===d)||[],c.name=d;}),"linkFields"in p&&p.linkFields&&p.linkFields?.forEach(d=>{if(d.target==="relation"){d.oppositeLinkFieldsPlayedBy=[{plays:d.path,thing:d.relation,thingType:"relation"}];return}let c=r.filter(t=>t.relation===d.relation&&t.plays!==d.plays)||[];d.oppositeLinkFieldsPlayedBy=c;let{filter:o}=d;d.oppositeLinkFieldsPlayedBy=d.oppositeLinkFieldsPlayedBy.filter(t=>t.target==="role"),o&&Array.isArray(o)&&(d.oppositeLinkFieldsPlayedBy=d.oppositeLinkFieldsPlayedBy.filter(t=>o.some(i=>t.thing===i.$role)),d.oppositeLinkFieldsPlayedBy=d.oppositeLinkFieldsPlayedBy.filter(t=>o.some(i=>t.thing===i.$thing))),o&&!Array.isArray(o)&&(d.oppositeLinkFieldsPlayedBy=d.oppositeLinkFieldsPlayedBy.filter(t=>t.$role===o.$role),d.oppositeLinkFieldsPlayedBy=d.oppositeLinkFieldsPlayedBy.filter(t=>t.thing===o.$thing));});}if(typeof p=="object"&&"playedBy"in p){if([...new Set(p.playedBy?.map(y=>y.thing))].length>1)throw new Error(`Unsupported: roleFields can be only played by one thing. Role: ${a} path:${$.nodePath}`);if(p.playedBy.length===0)throw new Error(`Unsupported: roleFields should be played at least by one thing. Role: ${a}, path:${$.nodePath}`)}if($.depth===4&&(p.default||p.computedValue)){let[y,g]=$.nodePath?.split(".")||[];h[y][g].computedFields.push(p.path);}}))},N=(f,r)=>{if(r.$entity){if(!(r.$entity in f.entities))throw new Error(`Missing entity '${r.$entity}' in the schema`);return f.entities[r.$entity]}if(r.$relation){if(!(r.$relation in f.relations))throw new Error(`Missing relation '${r.$relation}' in the schema`);return f.relations[r.$relation]}throw new Error(`Wrong schema or query for ${JSON.stringify(r)}`)},W=(f,r)=>{let l=f.dataFields?.map(i=>i.path)||[],n=f.linkFields?.map(i=>i.path)||[],h="roles"in f?radash.listify(f.roles,i=>i):[],p=[...l||[],...n||[],...h||[]],$=[...["$entity","$op","$id","$tempId","$relation","$parentKey","$filter","$fields","$excludedFields"],...p];if(!r)return {fields:p,dataFields:l,roleFields:h,linkFields:n};let y=r.$fields?r.$fields.map(i=>{if(typeof i=="string")return i;if("$path"in i&&typeof i.$path=="string")return i.$path;throw new Error(" Wrongly structured query")}):radash.listify(r,i=>i),g=r.$filter?radash.listify(r.$filter,i=>i.toString().startsWith("$")?void 0:i.toString()).filter(i=>i&&l?.includes(i)):[],d=r.$filter?radash.listify(r.$filter,i=>i.toString().startsWith("$")?void 0:i.toString()).filter(i=>i&&[...h||[],...n||[]].includes(i)):[],c=[...y,...g].filter(i=>!$.includes(i)).filter(i=>i),o=r.$filter?x(r.$filter,(i,s)=>g.includes(i)):{},t=r.$filter?x(r.$filter,(i,s)=>d.includes(i)):{};return {fields:p,dataFields:l,roleFields:h,linkFields:n,usedFields:y,usedLinkFields:n.filter(i=>y.includes(i)),usedRoleFields:h.filter(i=>y.includes(i)),unidentifiedFields:c,...g.length?{localFilters:o}:{},...d.length?{nestedFilters:t}:{}}},ht=(f,r)=>{let l=r.$localFilters&&radash.listify(r.$localFilters,(h,p)=>`has ${f.dataFields?.find($=>$.path===h)?.dbPath} '${p}'`);return l?.length?`, ${l.join(",")}`:""};function H(f){return f!==null}var z=(f,r)=>Object.values(f).reduce((l,n)=>(n.extends===r&&l.push(n.name),l),[]);function nt(f){return typeof f=="string"||!!f.$show}var Nt=(f,r)=>f.map(n=>{let h=[...n.conceptMaps],a=n.owner.asThing().type.label.name,$=r.entities[a]?r.entities[a]:r.relations[a];if(!$.idFields)throw new Error(`No idFields defined for ${a}`);let y=r.entities[a]?"entity":"relation",g=h.map(c=>{let o=c.get("attribute")?.asAttribute();return o?[ct(o.type.label.name),o.value]:[]}),d=Object.fromEntries(g);return {...d,[`$${y}`]:a,$id:d[$.idFields[0]]}}),Dt=(f,r,l)=>f.flatMap(h=>h.conceptMaps.map(a=>{let $=new Map;return r.forEach(y=>{let g=a.get(`${y}_id`)?.asAttribute().value.toString(),d=a.get(y),c=d?.isEntity()?d.asEntity().type.label.name:d?.asRelation().type.label.name,t={id:g,entityName:(()=>c?(l.entities[c]??l.relations[c]).allExtends?.includes(y)?y:c:y)()};g&&$.set(y,t);}),$})),jt=(f,r,l)=>f.flatMap(h=>h.conceptMaps.map(a=>{let $=a.get(`${r}_id`)?.asAttribute().value.toString(),y=a.get(`${l}_id`)?.asAttribute().value.toString();return {ownerId:$,path:l,roleId:y}})),xt=(f,r)=>{let l=radash.listify(f.roles,(n,h)=>{if([...new Set(h.playedBy?.map($=>$.thing))].length!==1)throw new Error("a role can be played by two entities throws the same relation");if(!h.playedBy)throw new Error("Role not being played by nobody");let p=h.playedBy[0].plays,a=z(r.entities,p);return [p,...a]});return radash.unique(radash.flat(l))},V=async(f,r)=>{let{schema:l,bqlRequest:n,config:h,tqlRequest:p}=f,{rawTqlRes:a}=r;if(n){if(!a)throw new Error("TQL query not executed")}else throw new Error("BQL request not parsed");let{query:$}=n;if(!$){if(a.insertions?.length===0&&!p?.deletions){r.bqlRes={};return}let{mutation:o}=n;if(!o)throw new Error("TQL mutation not executed");let i=[...o.things,...o.edges].map(s=>{let e=a.insertions?.find(m=>m.get(`${s.$tempId||s.$id}`))?.get(`${s.$tempId||s.$id}`);if(s.$op==="create"||s.$op==="update"||s.$op==="link"){if(!e?.asThing().iid)throw new Error(`Thing not received on mutation: ${JSON.stringify(s)}`);let m=e?.asThing().iid;return h.mutation?.noMetadata?radash.mapEntries(s,(u,O)=>[u.toString().startsWith("$")?Symbol.for(u):u,O]):{$dbId:m,...s}}if(s.$op==="delete"||s.$op==="unlink")return s;if(s.$op!=="match")throw new Error(`Unsupported op ${s.$op}`)}).filter(s=>s);r.bqlRes=i.length>1?i:i[0];return}if(!a.entity)throw new Error("TQL query not executed");let y=Nt(a.entity,l),g=a.relations?.map(o=>{let t=l.relations[o.relation],i=xt(t,l),s=Dt(o.conceptMapGroups,[...i,t.name],l);return {name:o.relation,links:s}}),d=a.roles?.map(o=>({name:o.ownerPath,links:jt(o.conceptMapGroups,o.ownerPath,o.path)})),c=r.cache||{entities:new Map,relations:new Map,roleLinks:new Map};y.forEach(o=>{let t=o.$entity||o.$relation,i=o.$id,s=c.entities.get(t)||new Map;s.set(i,{...o,$show:!0}),c.entities.set(t,s);}),g?.forEach(o=>{let t=o.name,i=c.relations.get(t)||[];i.push(...o.links),c.relations.set(t,i),o.links.forEach(s=>{[...s.entries()].forEach(([e,{entityName:m,id:u}])=>{let O=c.entities.get(m)||new Map,k={[l.entities[m]?.thingType||l.relations[m].thingType]:m,$id:u,...O.get(u)};O.set(u,k),c.entities.set(m,O);});});}),d?.forEach(o=>{let t=l.relations[o.name]||l.entities[o.name];o.links.forEach(i=>{let s=c.roleLinks.get(i.ownerId)||{},e=s[i.path];e?radash.isArray(e)?e.push(i.roleId):radash.isString(e)&&e!==i.roleId&&(e=[e,i.roleId]):e=i.roleId,s[i.path]=e,c.roleLinks.set(i.ownerId,s),t.roles[i.path].playedBy?.forEach(m=>{let u=c.entities.get(m.thing)||new Map,O={$entity:m.thing,$id:i.roleId,...u.get(i.roleId)};u.set(i.roleId,O),c.entities.set(m.thing,u);});});}),r.cache=c;};var ut=(f,r)=>dt(f,l=>objectTraversal.traverse(l,({value:n})=>{if(Array.isArray(n)||typeof n!="object")return;n.$fields&&delete n.$fields,n.$filter&&delete n.$filter,n.$show&&delete n.$show,r.query?.noMetadata&&(n.$entity||n.$relation)&&(delete n.$entity,delete n.$relation,delete n.$id),Object.getOwnPropertySymbols(f).forEach(p=>{delete n[p];}),n.$excludedFields&&(n.$excludedFields.forEach(p=>{delete n[p];}),delete n.$excludedFields);})),rt=(f,r,l,n)=>f.map(([h,p])=>{if(!r||!r.includes(h))return null;if(!l.$fields||l.$fields.includes(n))return h;let a=l.$fields.find($=>radash.isObject($)&&$.$path===n);if(a){let $={...x(p,(g,d)=>g.startsWith("$"))},y=a.$fields?{...$,$fields:a.$fields}:$;if(a.$id){if(Array.isArray(a.$id))return a.$id.includes(h)?y:null;if(a.$id===h)return y}return y}return null}).filter(h=>h),gt=async(f,r)=>{let{bqlRequest:l,config:n,schema:h}=f,{cache:p}=r;if(!l)throw new Error("BQL request not parsed");let{query:a}=l;if(!a){r.bqlRes=ut(r.bqlRes,n);return}if(!p)return;let $="$entity"in a?a.$entity:a.$relation,y=p.entities.get($.name);if(!y){r.bqlRes=null;return}let d=radash.listify(a.$filter,e=>e).some(e=>$.dataFields?.find(m=>m.path===e)?.validations?.unique),c=!Array.isArray(l.query)&&(l.query?.$id&&!Array.isArray(l.query?.$id)||d);if(Array.isArray(f.rawBqlRequest))throw new Error("Query arrays not implemented yet");let o=y,t=[...o].length?[...o].map(([e,m])=>({...f.rawBqlRequest,$id:e})):f.rawBqlRequest,i=dt(t,e=>objectTraversal.traverse(e,({value:m})=>{let u=m;if(!u?.$entity&&!u?.$relation)return;let O="$entity"in u?u.$entity:u.$relation;if(O){let P=Array.isArray(u.$id)?u.$id:[u.$id],k="$relation"in u?h.relations[u.$relation]:h.entities[u.$entity],{dataFields:E,roleFields:R}=W(k),w=p.entities.get(O);if(!w)return;[...w].forEach(([T,M])=>{if(P.includes(T)){let A=u.$fields?u.$fields:E;radash.listify(M,(F,B)=>{F.startsWith("$")||!A?.includes(F)||(u[F]=B);});let S=p.roleLinks.get(T),q=u.$fields?u.$fields.filter(F=>typeof F=="string"):R,L=u.$fields?.filter(F=>typeof F=="object")?.map(F=>F.$path)||[];Object.entries(S||{}).forEach(([F,B])=>{if(![...q,...L].includes(F))return;if(!("roles"in k))throw new Error("No roles in schema");let b=Array.isArray(B)?[...new Set(B)]:[B],{cardinality:Q,playedBy:C}=k.roles[F],G=[...new Set(C?.map(D=>D.thing))]?.flatMap(D=>{let U=p.entities.get(D);return U?rt([...U],b,u,F):[]});if(G?.length){if(G.length===1&&G[0]===u.$id)return;if(Q==="ONE"){u[F]=G[0];return}u[F]=G.filter(D=>typeof D=="string"||typeof D=="object"&&D?.$show);}});}});let I=k.linkFields;I&&I.forEach(T=>{let M=p.relations.get(T.relation),A=T.oppositeLinkFieldsPlayedBy;if(!M)return null;if(T.target==="relation"){let S=[...M].reduce((q,L)=>{let F=L.get(T.plays)?.id;if(F&&F===P[0]){let B=L.get(T.relation);if(!B)return q;q[B.entityName]||(q[B.entityName]=new Set),q[B.entityName].add(B.id);}return q},{});return Object.entries(S).map(([q,L])=>{let F=p.entities.get(q);if(!F)return null;let B=rt([...F],[...L.values()],u,T.path).filter(H).filter(nt);if(B.length===0)return null;if(B&&B.length){if(T.cardinality==="ONE")return u[T.path]=B[0],null;u[T.path]=B;}return null}),null}return T.target==="role"&&A.forEach(S=>{if(!M)return;let q=[...M].reduce((L,F)=>{let B=F.get(T.plays)?.id;if(B&&B===P[0]){let b=F.get(S.plays);if(!b)return L;L[b.entityName]||(L[b.entityName]=new Set),L[b.entityName].add(b.id);}return L},{});Object.entries(q).forEach(([L,F])=>{let B=p.entities.get(L);if(!B)return;let b=rt([...B],[...F.values()],u,T.path).filter(H).filter(nt);if(b.length!==0&&b&&b.length){if(T.cardinality==="ONE"){u[T.path]=b[0];return}u[T.path]=b;}});}),null});}})),s=ut(i,n);r.bqlRes=c?s[0]:s;};var K=async f=>{let{schema:r,bqlRequest:l}=f;if(!l?.query)throw new Error("BQL query not parsed");let{query:n}=l,h="$entity"in n?n.$entity:n.$relation,p=h.defaultDBConnector.path||h.name;if(!p)throw new Error(`No thing path in ${JSON.stringify(h)}`);if(!h.idFields)throw new Error("No id fields");let[a]=h.idFields,$=`$${p}_id`,y=`, has ${a} ${$};`;n.$id&&(Array.isArray(n.$id)?y+=` ${$} like "${n.$id.join("|")}";`:y+=` ${$} "${n.$id}";`);let g=ht(h,n),d="roles"in h?radash.listify(h.roles,(i,s)=>({path:i,var:`$${i}`,schema:s})):[],c=`match $${p} isa ${p}, has attribute $attribute ${g} ${y} group $${p};`,o=d.map(i=>{if(!i.schema.playedBy||[...new Set(i.schema.playedBy?.map(e=>e.thing))].length!==1)throw new Error("Unsupported: Role played by multiple linkfields or none");let s=i.schema.playedBy[0].thing;return {path:i.path,owner:p,request:`match $${p} (${i.path}: ${i.var} ) isa ${p} ${y} ${i.var} isa ${s}, has id ${i.var}_id; group $${p};`}}),t=h.linkFields?.flatMap(i=>{let s=`$${i.plays}_id`,e=`, has ${a} ${s};`;n.$id&&(Array.isArray(n.$id)?e+=` ${s} like "${n.$id.join("|")}";`:e+=` ${s} "${n.$id}";`);let m=`match $${i.plays} isa ${p}${g} ${e}`,u=i.target==="relation",P=`$${i.relation}`,k=`${u?P:""} (${i.plays}: $${i.plays}`,E=i.oppositeLinkFieldsPlayedBy.map(S=>u?null:`${S.plays}: $${S.plays}`),R=[k,...E].filter(S=>S).join(",");if(r.relations[i.relation]===void 0)throw new Error(`Relation ${i.relation} not found in schema`);let w=r.relations[i.relation].defaultDBConnector.path||i.relation,I=`) isa ${w};`,T=i.oppositeLinkFieldsPlayedBy.map(S=>`$${u?S.thing:S.plays} isa ${S.thing}, has id $${u?S.thing:S.plays}_id;`).join(" "),M=`group $${i.plays};`,A=`${m} ${R} ${I} ${T} ${M}`;return {relation:w,entity:p,request:A}});f.tqlRequest={entity:c,...o?.length?{roles:o}:{},...t?.length?{relations:t}:{}};};var Bt=async f=>{let{rawBqlRequest:r,schema:l}=f;if(!("$entity"in r)&&!("$relation"in r))throw new Error("No entity specified in query");let n=N(l,r);if(!n)throw new Error(`Thing '${r}' not found in schema`);let{unidentifiedFields:h,localFilters:p,nestedFilters:a}=W(n,r);if(h&&h.length>0)throw new Error(`Unknown fields: [${h.join(",")}] in ${JSON.stringify(r)}`);f.bqlRequest={query:{...f.rawBqlRequest,...n.thingType==="entity"?{$entity:n}:{},...n.thingType==="relation"?{$relation:n}:{},...p?{$localFilters:p}:{},...a?{$nestedFilters:a}:{}}};};var Y=async(f,r)=>{let{dbHandles:l,bqlRequest:n,tqlRequest:h,config:p}=f;if(!n)throw new Error("BQL request not parsed");if(!h)throw new Error("TQL request not built");if(!h.entity)throw new Error("BQL request error, no entities");let{query:a}=n;if(!a)throw new Error("BQL request is not a query");let $=p.dbConnectors[0].id,y=l.typeDB.get($)?.session;if(!y?.isOpen())throw new Error("Session is closed");let g=await y.transaction(typedbClient.TransactionType.READ);if(!g)throw new Error("Can't create transaction");let d=g.query.matchGroup(h.entity),c=h.roles?.map(e=>({...e,stream:g.query.matchGroup(e.request)})),o=h.relations?.map(e=>({...e,stream:g.query.matchGroup(e.request)})),t=await d.collect(),i=await Promise.all(c?.map(async e=>({path:e.path,ownerPath:e.owner,conceptMapGroups:await e.stream.collect()}))||[]),s=await Promise.all(o?.map(async e=>({relation:e.relation,entity:e.entity,conceptMapGroups:await e.stream.collect()}))||[]);await g.close(),r.rawTqlRes={entity:t,...i?.length&&{roles:i},...s?.length&&{relations:s}};};var ot=async(f,r)=>{let{bqlRequest:l,schema:n}=f,{cache:h}=r;if(!l)throw new Error("BQL request not parsed");if(!h)throw new Error("Cache not initialized");let{query:p}=l;if(!p)return;let{$fields:a}=p;if(!("$entity"in p)&&!("$relation"in p))throw new Error("Node attributes not supported");let $="$entity"in p?p.$entity:p.$relation;if(!a||!Array.isArray(a))return;let y=a.filter(t=>typeof t!="string"&&t.$path),g=$.linkFields?.filter(t=>y.findIndex(i=>i.$path===t.path)!==-1).flatMap(t=>t.oppositeLinkFieldsPlayedBy)||[],d="roles"in $?radash.listify($.roles,(t,i)=>y.findIndex(s=>s.$path===t)!==-1?i:null).flatMap(t=>t?.playedBy).filter(t=>t):[],o=[...g,...d]?.map(t=>{if(!t)return null;let{thing:i}=t,s=z(n.entities,i);return [i,...s].map(e=>{let m=h.entities.get(e);if(!m)return null;let u=Array.from(m.values()).reduce((T,M)=>("$show"in M||T.push(M.$id),T),[]);if(u.length===0)return null;let O=n.entities[e]?{...n.entities[e],thingType:"entity"}:{...n.relations[e],thingType:"relation"},P=a.find(T=>typeof T=="object"&&T.$path===t.plays),k=P?.$id,E=k?Array.isArray(k)?k:[k]:[],R=P?.$filter,I={query:{$id:E.length?E.filter(T=>u.includes(T)):u,$fields:P?.$fields,...O.thingType==="entity"?{$entity:O}:{},...O.thingType==="relation"?{$relation:O}:{},...R?{$localFilters:R}:{}}};return {req:{...f,bqlRequest:I},res:r,pipeline:[K,Y,V,ot]}}).filter(H)}).filter(H);if(o?.length)return radash.flat(o)};var wt=async f=>{let{bqlRequest:r,schema:l}=f;if(!r)throw new Error("BQL request not parsed");let{mutation:n}=r;if(!n)throw new Error("BQL request is not a mutation");let h=t=>{let i=t.$op,s=t.$tempId||t.$id,e=N(l,t),m=e.defaultDBConnector?.path||t.$entity||t.$relation,{idFields:u}=e;if(!u)throw new Error("no idFields");let O=u[0],P=radash.listify(t,(L,F)=>{if(L.startsWith("$")||L===O||!F)return "";let B=e.dataFields?.find(C=>C.path===L);if(!B?.path)return "";let Q=B.dbPath;if(["TEXT","ID","EMAIL"].includes(B.contentType))return `has ${Q} '${F}'`;if(["NUMBER"].includes(B.contentType))return `has ${Q} ${F}`;if(B.contentType==="DATE"){if(Number.isNaN(F.valueOf()))throw new Error("Invalid format, Nan Date");return F instanceof Date?`has ${Q} ${F.toISOString().replace("Z","")}`:`has ${Q} ${new Date(F).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${B.contentType}`)}).filter(L=>L),k=`$${s}-atts`,E=radash.listify(t,(L,F)=>{if(L.startsWith("$")||L===O||!F)return "";let B=e.dataFields?.find(C=>C.path===L);if(!B?.path)return "";let Q=B.dbPath;return `{${k} isa ${Q};}`}).filter(L=>L),R=t[O]||t.$id,w=e.dataFields?.find(L=>L.path===O),I=t.$op==="create"?w?.default?.value():null,T=R||I,M=T?[`has ${O} '${T}'`]:[],A=[...M,...P].filter(L=>L).join(","),S=()=>{if(i==="delete"||i==="unlink"||i==="match")return `$${s} isa ${[m,...M].filter(L=>L).join(",")};`;if(i==="update"){if(!E.length)throw new Error("update without attributes");return `$${s} isa ${[m,...M].filter(L=>L).join(",")}, has ${k};
9
+ var et={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1},mutation:{}};var pt=(f,r,l)=>l?r:`${f}\xB7${r}`,ct=f=>{let r=f.split("\xB7");return r[r.length-1]},J=(f,r)=>Object.values(Object.fromEntries(Object.entries(f).filter(([l,n])=>r(l,n))))[0],x=(f,r)=>Object.fromEntries(Object.entries(f).filter(([l,n])=>r(l,n))),ft=f=>{let r=[],l=immer.produce(f,h=>objectTraversal.traverse(h,({key:p,value:a,meta:$})=>{if($.depth===2&&(p&&(a.dataFields=a.dataFields?.map(y=>({...y,dbPath:pt(p,y.path,y.shared)}))),a.extends)){let y=h.entities[a.extends]||h.relations[a.extends];if(a.allExtends=[a.extends,...y.allExtends||[]],a.idFields=y.idFields?(a.idFields||[]).concat(y.idFields):a.idFields,a.dataFields=y.dataFields?(a.dataFields||[]).concat(y.dataFields.map(g=>{let d=a.extends,c=f.entities[d]||f.relations[d];for(;!c.dataFields?.find(o=>o.path===g.path);)d=c.extends,c=f.entities[d]||f.relations[d];return {...g,dbPath:pt(d,g.path,g.shared)}})):a.dataFields,a.linkFields=y.linkFields?(a.linkFields||[]).concat(y.linkFields):a.linkFields,"roles"in y){let g=a,d=y;g.roles=g.roles||{},g.roles={...g.roles,...d.roles},Object.keys(g.roles).length===0&&(g.roles={});}}},{traversalType:"breadth-first"}));return objectTraversal.traverse(f,({key:h,value:p,meta:a})=>{if(h==="linkFields"){let y=(()=>{if(!a.nodePath)throw new Error("No path");let[d,c]=a.nodePath.split(".");return {thing:c,thingType:d==="entities"?"entity":d==="relations"?"relation":""}})(),g=Array.isArray(p)?p.map(d=>({...d,...y})):[{...p,...y}];r.push(...g);}}),immer.produce(l,h=>objectTraversal.traverse(h,({value:p,key:a,meta:$})=>{if($.depth===2&&p.idFields&&!p.id){p.name=a;let y=()=>{if($.nodePath?.split(".")[0]==="entities")return "entity";if($.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};p.thingType=y(),p.computedFields=[],"roles"in p&&Object.entries(p.roles).forEach(([d,c])=>{c.playedBy=r.filter(o=>o.relation===a&&o.plays===d)||[],c.name=d;}),"linkFields"in p&&p.linkFields&&p.linkFields?.forEach(d=>{if(d.target==="relation"){d.oppositeLinkFieldsPlayedBy=[{plays:d.path,thing:d.relation,thingType:"relation"}];return}let c=r.filter(t=>t.relation===d.relation&&t.plays!==d.plays)||[];d.oppositeLinkFieldsPlayedBy=c;let{filter:o}=d;d.oppositeLinkFieldsPlayedBy=d.oppositeLinkFieldsPlayedBy.filter(t=>t.target==="role"),o&&Array.isArray(o)&&(d.oppositeLinkFieldsPlayedBy=d.oppositeLinkFieldsPlayedBy.filter(t=>o.some(i=>t.thing===i.$role)),d.oppositeLinkFieldsPlayedBy=d.oppositeLinkFieldsPlayedBy.filter(t=>o.some(i=>t.thing===i.$thing))),o&&!Array.isArray(o)&&(d.oppositeLinkFieldsPlayedBy=d.oppositeLinkFieldsPlayedBy.filter(t=>t.$role===o.$role),d.oppositeLinkFieldsPlayedBy=d.oppositeLinkFieldsPlayedBy.filter(t=>t.thing===o.$thing));});}if(typeof p=="object"&&"playedBy"in p){if([...new Set(p.playedBy?.map(y=>y.thing))].length>1)throw new Error(`Unsupported: roleFields can be only played by one thing. Role: ${a} path:${$.nodePath}`);if(p.playedBy.length===0)throw new Error(`Unsupported: roleFields should be played at least by one thing. Role: ${a}, path:${$.nodePath}`)}if($.depth===4&&(p.default||p.computedValue)){let[y,g]=$.nodePath?.split(".")||[];h[y][g].computedFields.push(p.path);}}))},N=(f,r)=>{if(r.$entity){if(!(r.$entity in f.entities))throw new Error(`Missing entity '${r.$entity}' in the schema`);return f.entities[r.$entity]}if(r.$relation){if(!(r.$relation in f.relations))throw new Error(`Missing relation '${r.$relation}' in the schema`);return f.relations[r.$relation]}throw new Error(`Wrong schema or query for ${JSON.stringify(r)}`)},W=(f,r)=>{let l=f.dataFields?.map(i=>i.path)||[],n=f.linkFields?.map(i=>i.path)||[],h="roles"in f?radash.listify(f.roles,i=>i):[],p=[...l||[],...n||[],...h||[]],$=[...["$entity","$op","$id","$tempId","$relation","$parentKey","$filter","$fields","$excludedFields"],...p];if(!r)return {fields:p,dataFields:l,roleFields:h,linkFields:n};let y=r.$fields?r.$fields.map(i=>{if(typeof i=="string")return i;if("$path"in i&&typeof i.$path=="string")return i.$path;throw new Error(" Wrongly structured query")}):radash.listify(r,i=>i),g=r.$filter?radash.listify(r.$filter,i=>i.toString().startsWith("$")?void 0:i.toString()).filter(i=>i&&l?.includes(i)):[],d=r.$filter?radash.listify(r.$filter,i=>i.toString().startsWith("$")?void 0:i.toString()).filter(i=>i&&[...h||[],...n||[]].includes(i)):[],c=[...y,...g].filter(i=>!$.includes(i)).filter(i=>i),o=r.$filter?x(r.$filter,(i,s)=>g.includes(i)):{},t=r.$filter?x(r.$filter,(i,s)=>d.includes(i)):{};return {fields:p,dataFields:l,roleFields:h,linkFields:n,usedFields:y,usedLinkFields:n.filter(i=>y.includes(i)),usedRoleFields:h.filter(i=>y.includes(i)),unidentifiedFields:c,...g.length?{localFilters:o}:{},...d.length?{nestedFilters:t}:{}}},ht=(f,r)=>{let l=r.$localFilters&&radash.listify(r.$localFilters,(h,p)=>`has ${f.dataFields?.find($=>$.path===h)?.dbPath} '${p}'`);return l?.length?`, ${l.join(",")}`:""};function H(f){return f!==null}var z=(f,r)=>Object.values(f).reduce((l,n)=>(n.extends===r&&l.push(n.name),l),[]);function nt(f){return typeof f=="string"||!!f.$show}var Nt=(f,r)=>f.map(n=>{let h=[...n.conceptMaps],a=n.owner.asThing().type.label.name,$=r.entities[a]?r.entities[a]:r.relations[a];if(!$.idFields)throw new Error(`No idFields defined for ${a}`);let y=r.entities[a]?"entity":"relation",g=h.map(c=>{let o=c.get("attribute")?.asAttribute();return o?[ct(o.type.label.name),o.value]:[]}),d=Object.fromEntries(g);return {...d,[`$${y}`]:a,$id:d[$.idFields[0]]}}),Dt=(f,r,l)=>f.flatMap(h=>h.conceptMaps.map(a=>{let $=new Map;return r.forEach(y=>{let g=a.get(`${y}_id`)?.asAttribute().value.toString(),d=a.get(y),c=d?.isEntity()?d.asEntity().type.label.name:d?.asRelation().type.label.name,t={id:g,entityName:(()=>c?(l.entities[c]??l.relations[c]).allExtends?.includes(y)?y:c:y)()};g&&$.set(y,t);}),$})),jt=(f,r,l)=>f.flatMap(h=>h.conceptMaps.map(a=>{let $=a.get(`${r}_id`)?.asAttribute().value.toString(),y=a.get(`${l}_id`)?.asAttribute().value.toString();return {ownerId:$,path:l,roleId:y}})),xt=(f,r)=>{let l=radash.listify(f.roles,(n,h)=>{if([...new Set(h.playedBy?.map($=>$.thing))].length!==1)throw new Error("a role can be played by two entities throws the same relation");if(!h.playedBy)throw new Error("Role not being played by nobody");let p=h.playedBy[0].plays,a=z(r.entities,p);return [p,...a]});return radash.unique(radash.flat(l))},V=async(f,r)=>{let{schema:l,bqlRequest:n,config:h,tqlRequest:p}=f,{rawTqlRes:a}=r;if(n){if(!a)throw new Error("TQL query not executed")}else throw new Error("BQL request not parsed");let{query:$}=n;if(!$){if(a.insertions?.length===0&&!p?.deletions){r.bqlRes={};return}let{mutation:o}=n;if(!o)throw new Error("TQL mutation not executed");let i=[...o.things,...o.edges].map(s=>{let e=a.insertions?.find(m=>m.get(`${s.$tempId||s.$id}`))?.get(`${s.$tempId||s.$id}`);if(s.$op==="create"||s.$op==="update"||s.$op==="link"){if(!e?.asThing().iid)throw new Error(`Thing not received on mutation: ${JSON.stringify(s)}`);let m=e?.asThing().iid;return h.mutation?.noMetadata?radash.mapEntries(s,(u,O)=>[u.toString().startsWith("$")?Symbol.for(u):u,O]):{$dbId:m,...s}}if(s.$op==="delete"||s.$op==="unlink")return s;if(s.$op!=="match")throw new Error(`Unsupported op ${s.$op}`)}).filter(s=>s);r.bqlRes=i.length>1?i:i[0];return}if(!a.entity)throw new Error("TQL query not executed");let y=Nt(a.entity,l),g=a.relations?.map(o=>{let t=l.relations[o.relation],i=xt(t,l),s=Dt(o.conceptMapGroups,[...i,t.name],l);return {name:o.relation,links:s}}),d=a.roles?.map(o=>({name:o.ownerPath,links:jt(o.conceptMapGroups,o.ownerPath,o.path)})),c=r.cache||{entities:new Map,relations:new Map,roleLinks:new Map};y.forEach(o=>{let t=o.$entity||o.$relation,i=o.$id,s=c.entities.get(t)||new Map;s.set(i,{...o,$show:!0}),c.entities.set(t,s);}),g?.forEach(o=>{let t=o.name,i=c.relations.get(t)||[];i.push(...o.links),c.relations.set(t,i),o.links.forEach(s=>{[...s.entries()].forEach(([e,{entityName:m,id:u}])=>{let O=c.entities.get(m)||new Map,k={[l.entities[m]?.thingType||l.relations[m].thingType]:m,$id:u,...O.get(u)};O.set(u,k),c.entities.set(m,O);});});}),d?.forEach(o=>{let t=l.relations[o.name]||l.entities[o.name];o.links.forEach(i=>{let s=c.roleLinks.get(i.ownerId)||{},e=s[i.path];e?radash.isArray(e)?e.push(i.roleId):radash.isString(e)&&e!==i.roleId&&(e=[e,i.roleId]):e=i.roleId,s[i.path]=e,c.roleLinks.set(i.ownerId,s),t.roles[i.path].playedBy?.forEach(m=>{let u=c.entities.get(m.thing)||new Map,O={$entity:m.thing,$id:i.roleId,...u.get(i.roleId)};u.set(i.roleId,O),c.entities.set(m.thing,u);});});}),r.cache=c;};var ut=(f,r)=>immer.produce(f,l=>objectTraversal.traverse(l,({value:n})=>{if(Array.isArray(n)||typeof n!="object")return;n.$fields&&delete n.$fields,n.$filter&&delete n.$filter,n.$show&&delete n.$show,r.query?.noMetadata&&(n.$entity||n.$relation)&&(delete n.$entity,delete n.$relation,delete n.$id),Object.getOwnPropertySymbols(f).forEach(p=>{delete n[p];}),n.$excludedFields&&(n.$excludedFields.forEach(p=>{delete n[p];}),delete n.$excludedFields);})),rt=(f,r,l,n)=>f.map(([h,p])=>{if(!r||!r.includes(h))return null;if(!l.$fields||l.$fields.includes(n))return h;let a=l.$fields.find($=>radash.isObject($)&&$.$path===n);if(a){let $={...x(p,(g,d)=>g.startsWith("$"))},y=a.$fields?{...$,$fields:a.$fields}:$;if(a.$id){if(Array.isArray(a.$id))return a.$id.includes(h)?y:null;if(a.$id===h)return y}return y}return null}).filter(h=>h),gt=async(f,r)=>{let{bqlRequest:l,config:n,schema:h}=f,{cache:p}=r;if(!l)throw new Error("BQL request not parsed");let{query:a}=l;if(!a){r.bqlRes=ut(r.bqlRes,n);return}if(!p)return;let $="$entity"in a?a.$entity:a.$relation,y=p.entities.get($.name);if(!y){r.bqlRes=null;return}let d=radash.listify(a.$filter,e=>e).some(e=>$.dataFields?.find(m=>m.path===e)?.validations?.unique),c=!Array.isArray(l.query)&&(l.query?.$id&&!Array.isArray(l.query?.$id)||d);if(Array.isArray(f.rawBqlRequest))throw new Error("Query arrays not implemented yet");let o=y,t=[...o].length?[...o].map(([e,m])=>({...f.rawBqlRequest,$id:e})):f.rawBqlRequest,i=immer.produce(t,e=>objectTraversal.traverse(e,({value:m})=>{let u=m;if(!u?.$entity&&!u?.$relation)return;let O="$entity"in u?u.$entity:u.$relation;if(O){let P=Array.isArray(u.$id)?u.$id:[u.$id],k="$relation"in u?h.relations[u.$relation]:h.entities[u.$entity],{dataFields:E,roleFields:R}=W(k),w=p.entities.get(O);if(!w)return;[...w].forEach(([T,M])=>{if(P.includes(T)){let A=u.$fields?u.$fields:E;radash.listify(M,(F,B)=>{F.startsWith("$")||A?.includes(F)&&(u[F]=B);});let S=p.roleLinks.get(T),q=u.$fields?u.$fields.filter(F=>typeof F=="string"):R,L=u.$fields?.filter(F=>typeof F=="object")?.map(F=>F.$path)||[];Object.entries(S||{}).forEach(([F,B])=>{if(![...q,...L].includes(F))return;if(!("roles"in k))throw new Error("No roles in schema");let b=Array.isArray(B)?[...new Set(B)]:[B],{cardinality:Q,playedBy:C}=k.roles[F],G=[...new Set(C?.map(D=>D.thing))]?.flatMap(D=>{let U=p.entities.get(D);return U?rt([...U],b,u,F):[]});if(G?.length){if(G.length===1&&G[0]===u.$id)return;if(Q==="ONE"){u[F]=G[0];return}u[F]=G.filter(D=>typeof D=="string"||typeof D=="object"&&D?.$show);}});}});let I=k.linkFields;I&&I.forEach(T=>{let M=p.relations.get(T.relation),A=T.oppositeLinkFieldsPlayedBy;if(!M)return null;if(T.target==="relation"){let S=[...M].reduce((q,L)=>{let F=L.get(T.plays)?.id;if(F&&F===P[0]){let B=L.get(T.relation);if(!B)return q;q[B.entityName]||(q[B.entityName]=new Set),q[B.entityName].add(B.id);}return q},{});return Object.entries(S).map(([q,L])=>{let F=p.entities.get(q);if(!F)return null;let B=rt([...F],[...L.values()],u,T.path).filter(H).filter(nt);if(B.length===0)return null;if(B&&B.length){if(T.cardinality==="ONE")return u[T.path]=B[0],null;u[T.path]=B;}return null}),null}return T.target==="role"&&A.forEach(S=>{if(!M)return;let q=[...M].reduce((L,F)=>{let B=F.get(T.plays)?.id;if(B&&B===P[0]){let b=F.get(S.plays);if(!b)return L;L[b.entityName]||(L[b.entityName]=new Set),L[b.entityName].add(b.id);}return L},{});Object.entries(q).forEach(([L,F])=>{let B=p.entities.get(L);if(!B)return;let b=rt([...B],[...F.values()],u,T.path).filter(H).filter(nt);if(b.length!==0&&b&&b.length){if(T.cardinality==="ONE"){u[T.path]=b[0];return}u[T.path]=b;}});}),null});}})),s=ut(i,n);r.bqlRes=c?s[0]:s;};var K=async f=>{let{schema:r,bqlRequest:l}=f;if(!l?.query)throw new Error("BQL query not parsed");let{query:n}=l,h="$entity"in n?n.$entity:n.$relation,p=h.defaultDBConnector.path||h.name;if(!p)throw new Error(`No thing path in ${JSON.stringify(h)}`);if(!h.idFields)throw new Error("No id fields");let[a]=h.idFields,$=`$${p}_id`,y=`, has ${a} ${$};`;n.$id&&(Array.isArray(n.$id)?y+=` ${$} like "${n.$id.join("|")}";`:y+=` ${$} "${n.$id}";`);let g=ht(h,n),d="roles"in h?radash.listify(h.roles,(i,s)=>({path:i,var:`$${i}`,schema:s})):[],c=`match $${p} isa ${p}, has attribute $attribute ${g} ${y} group $${p};`,o=d.map(i=>{if(!i.schema.playedBy||[...new Set(i.schema.playedBy?.map(e=>e.thing))].length!==1)throw new Error("Unsupported: Role played by multiple linkfields or none");let s=i.schema.playedBy[0].thing;return {path:i.path,owner:p,request:`match $${p} (${i.path}: ${i.var} ) isa ${p} ${y} ${i.var} isa ${s}, has id ${i.var}_id; group $${p};`}}),t=h.linkFields?.flatMap(i=>{let s=`$${i.plays}_id`,e=`, has ${a} ${s};`;n.$id&&(Array.isArray(n.$id)?e+=` ${s} like "${n.$id.join("|")}";`:e+=` ${s} "${n.$id}";`);let m=`match $${i.plays} isa ${p}${g} ${e}`,u=i.target==="relation",P=`$${i.relation}`,k=`${u?P:""} (${i.plays}: $${i.plays}`,E=i.oppositeLinkFieldsPlayedBy.map(S=>u?null:`${S.plays}: $${S.plays}`),R=[k,...E].filter(S=>S).join(",");if(r.relations[i.relation]===void 0)throw new Error(`Relation ${i.relation} not found in schema`);let w=r.relations[i.relation].defaultDBConnector.path||i.relation,I=`) isa ${w};`,T=i.oppositeLinkFieldsPlayedBy.map(S=>`$${u?S.thing:S.plays} isa ${S.thing}, has id $${u?S.thing:S.plays}_id;`).join(" "),M=`group $${i.plays};`,A=`${m} ${R} ${I} ${T} ${M}`;return {relation:w,entity:p,request:A}});f.tqlRequest={entity:c,...o?.length?{roles:o}:{},...t?.length?{relations:t}:{}};};var Bt=async f=>{let{rawBqlRequest:r,schema:l}=f;if(!("$entity"in r)&&!("$relation"in r))throw new Error("No entity specified in query");let n=N(l,r);if(!n)throw new Error(`Thing '${r}' not found in schema`);let{unidentifiedFields:h,localFilters:p,nestedFilters:a}=W(n,r);if(h&&h.length>0)throw new Error(`Unknown fields: [${h.join(",")}] in ${JSON.stringify(r)}`);f.bqlRequest={query:{...f.rawBqlRequest,...n.thingType==="entity"?{$entity:n}:{},...n.thingType==="relation"?{$relation:n}:{},...p?{$localFilters:p}:{},...a?{$nestedFilters:a}:{}}};};var Y=async(f,r)=>{let{dbHandles:l,bqlRequest:n,tqlRequest:h,config:p}=f;if(!n)throw new Error("BQL request not parsed");if(!h)throw new Error("TQL request not built");if(!h.entity)throw new Error("BQL request error, no entities");let{query:a}=n;if(!a)throw new Error("BQL request is not a query");let $=p.dbConnectors[0].id,y=l.typeDB.get($)?.session;if(!y?.isOpen())throw new Error("Session is closed");let g=await y.transaction(typedbClient.TransactionType.READ);if(!g)throw new Error("Can't create transaction");let d=g.query.matchGroup(h.entity),c=h.roles?.map(e=>({...e,stream:g.query.matchGroup(e.request)})),o=h.relations?.map(e=>({...e,stream:g.query.matchGroup(e.request)})),t=await d.collect(),i=await Promise.all(c?.map(async e=>({path:e.path,ownerPath:e.owner,conceptMapGroups:await e.stream.collect()}))||[]),s=await Promise.all(o?.map(async e=>({relation:e.relation,entity:e.entity,conceptMapGroups:await e.stream.collect()}))||[]);await g.close(),r.rawTqlRes={entity:t,...i?.length&&{roles:i},...s?.length&&{relations:s}};};var ot=async(f,r)=>{let{bqlRequest:l,schema:n}=f,{cache:h}=r;if(!l)throw new Error("BQL request not parsed");if(!h)throw new Error("Cache not initialized");let{query:p}=l;if(!p)return;let{$fields:a}=p;if(!("$entity"in p)&&!("$relation"in p))throw new Error("Node attributes not supported");let $="$entity"in p?p.$entity:p.$relation;if(!a||!Array.isArray(a))return;let y=a.filter(t=>typeof t!="string"&&t.$path),g=$.linkFields?.filter(t=>y.findIndex(i=>i.$path===t.path)!==-1).flatMap(t=>t.oppositeLinkFieldsPlayedBy)||[],d="roles"in $?radash.listify($.roles,(t,i)=>y.findIndex(s=>s.$path===t)!==-1?i:null).flatMap(t=>t?.playedBy).filter(t=>t):[],o=[...g,...d]?.map(t=>{if(!t)return null;let{thing:i}=t,s=z(n.entities,i);return [i,...s].map(e=>{let m=h.entities.get(e);if(!m)return null;let u=Array.from(m.values()).reduce((T,M)=>("$show"in M||T.push(M.$id),T),[]);if(u.length===0)return null;let O=n.entities[e]?{...n.entities[e],thingType:"entity"}:{...n.relations[e],thingType:"relation"},P=a.find(T=>typeof T=="object"&&T.$path===t.plays),k=P?.$id,E=k?Array.isArray(k)?k:[k]:[],R=P?.$filter,I={query:{$id:E.length?E.filter(T=>u.includes(T)):u,$fields:P?.$fields,...O.thingType==="entity"?{$entity:O}:{},...O.thingType==="relation"?{$relation:O}:{},...R?{$localFilters:R}:{}}};return {req:{...f,bqlRequest:I},res:r,pipeline:[K,Y,V,ot]}}).filter(H)}).filter(H);if(o?.length)return radash.flat(o)};var wt=async f=>{let{bqlRequest:r,schema:l}=f;if(!r)throw new Error("BQL request not parsed");let{mutation:n}=r;if(!n)throw new Error("BQL request is not a mutation");let h=t=>{let i=t.$op,s=t.$tempId||t.$id,e=N(l,t),m=e.defaultDBConnector?.path||t.$entity||t.$relation,{idFields:u}=e;if(!u)throw new Error("no idFields");let O=u[0],P=radash.listify(t,(L,F)=>{if(L.startsWith("$")||L===O||!F)return "";let B=e.dataFields?.find(C=>C.path===L);if(!B?.path)return "";let Q=B.dbPath;if(["TEXT","ID","EMAIL"].includes(B.contentType))return `has ${Q} '${F}'`;if(["NUMBER"].includes(B.contentType))return `has ${Q} ${F}`;if(B.contentType==="DATE"){if(Number.isNaN(F.valueOf()))throw new Error("Invalid format, Nan Date");return F instanceof Date?`has ${Q} ${F.toISOString().replace("Z","")}`:`has ${Q} ${new Date(F).toISOString().replace("Z","")}`}throw new Error(`Unsupported contentType ${B.contentType}`)}).filter(L=>L),k=`$${s}-atts`,E=radash.listify(t,(L,F)=>{if(L.startsWith("$")||L===O||!F)return "";let B=e.dataFields?.find(C=>C.path===L);if(!B?.path)return "";let Q=B.dbPath;return `{${k} isa ${Q};}`}).filter(L=>L),R=t[O]||t.$id,w=e.dataFields?.find(L=>L.path===O),I=t.$op==="create"?w?.default?.value():null,T=R||I,M=T?[`has ${O} '${T}'`]:[],A=[...M,...P].filter(L=>L).join(","),S=()=>{if(i==="delete"||i==="unlink"||i==="match")return `$${s} isa ${[m,...M].filter(L=>L).join(",")};`;if(i==="update"){if(!E.length)throw new Error("update without attributes");return `$${s} isa ${[m,...M].filter(L=>L).join(",")}, has ${k};
10
10
  ${E.join(" or ")};
11
- `}return ""},q=()=>i==="update"||i==="link"||i==="match"?`$${s} isa ${[m,...M].filter(L=>L).join(",")};`:"";if(t.$entity||t.$relation)return {op:i,deletionMatch:S(),insertionMatch:q(),insertion:i==="create"?`$${s} isa ${[m,A].filter(L=>L).join(",")};`:i==="update"&&P.length?`$${s} ${P.join(",")};`:"",deletion:i==="delete"?`$${s} isa ${m};`:i==="update"&&E.length?`$${s} has ${k};`:""};throw new Error("in attributes")},p=t=>{let i=t.$op,s=t.$tempId||t.$id,e=N(l,t),m=e.defaultDBConnector?.path||t.$relation,u="roles"in e?radash.listify(e.roles,S=>S):[],O=t.$relation&&"roles"in e&&radash.mapEntries(e.roles,(S,q)=>[S,q.dbConnector?.path||S]),P=radash.listify(t,(S,q)=>{if(!u.includes(S))return null;if(!("roles"in e))throw new Error("This should have roles! ");let L=O[S];return Array.isArray(q)?q.map(F=>({path:L,id:F})):{path:L,id:q}}).filter(S=>S).flat(),k=P.map(S=>{if(!S?.path)throw new Error("Object without path");return `${S.path}: $${S.id}`}),E=P.length>0?`( ${k.join(" , ")} )`:"",R=E?`$${s} ${E} ${t[Symbol.for("edgeType")]==="linkField"||i==="delete"||i==="unlink"?`isa ${m}`:""}`:"",w=`$${s} ${t[Symbol.for("edgeType")]==="linkField"||i==="delete"?`isa ${m}`:""}`,I=()=>R?i==="link"?`${R};`:i==="create"?`${R}, has id '${s}';`:"":"",T=()=>R&&i==="match"?`${R};`:"",M=()=>R?i==="delete"?`${R};`:i==="match"?`${R};`:"":"",A=()=>R?i==="delete"?`${w};`:i==="unlink"?`$${s} ${E};`:"":"";return {deletionMatch:M(),insertionMatch:T(),deletion:A(),insertion:I(),op:""}},a=(t,i)=>{let s=i==="edges"?p:h;if(Array.isArray(t))return t.map(k=>{let{preDeletionBatch:E,insertionMatch:R,deletionMatch:w,insertion:I,deletion:T}=s(k);return radash.shake({preDeletionBatch:E,insertionMatch:R,deletionMatch:w,insertion:I,deletion:T},M=>!M)}).filter(k=>k);let{preDeletionBatch:e,insertionMatch:m,deletionMatch:u,insertion:O,deletion:P}=s(t);return radash.shake({preDeletionBatch:e,insertionMatch:m,deletionMatch:u,insertion:O,deletion:P},k=>!k)},$=a(n.things),y=Array.isArray($)?$:[$],g=a(n.edges,"edges"),d=Array.isArray(g)?g:[g],c=[...y,...d],o=radash.shake({insertionMatches:c.map(t=>t.insertionMatch).join(" ").trim(),deletionMatches:c.map(t=>t.deletionMatch).join(" ").trim(),insertions:c.map(t=>t.insertion).join(" ").trim(),deletions:c.map(t=>t.deletion).join(" ").trim()},t=>!t);f.tqlRequest=o;};var Lt=async f=>{let{rawBqlRequest:r,schema:l}=f,h=($=>dt($,y=>objectTraversal.traverse(y,({value:g,meta:d,key:c})=>{if(radash.isObject(g)){if(g.$arrayOp)throw new Error("Array op not supported yet");if(c==="$filter"||d.nodePath?.includes(".$filter."))return;let o=g;if(o.$op==="create"&&o.$id)throw new Error("Can't write to computed field $id. Try writing to the id field directly.");let t=N(l,g),s=d.nodePath?.split(".")?.filter(E=>Number.isNaN(parseInt(E,10))).join(".");if(!t)throw new Error(`Schema not found for ${g.$entity||g.$relation}`);o[Symbol.for("bzId")]=uuid.v4(),o[Symbol.for("schema")]=t,o[Symbol.for("dbId")]=t.defaultDBConnector.id;let{usedLinkFields:e,usedRoleFields:m}=W(t,o),u=e.map(E=>({fieldType:"linkField",path:E,schema:t.linkFields.find(R=>R.path===E)})),O=t.thingType==="relation"?m.map(E=>({fieldType:"roleField",path:E,schema:J(t.roles,R=>R===E)})):[];if(u.some(E=>E.schema?.target==="role")&&u.some(E=>E.schema?.target==="relation"))throw new Error("Unsupported: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.");let P=O.filter(E=>[...new Set(E.schema.playedBy?.map(R=>R.thing))].length!==1);if(P.length>1)throw new Error(`Field: ${P[0].path} - If a role can be played by multiple things, you must specify the thing in the mutation: ${JSON.stringify(P[0].schema.playedBy)}. Schema: ${JSON.stringify(P[0].schema)}`);let k=d.nodePath;if([...u,...O].forEach(E=>{let R=o[E.path];if(R===void 0)return;let w=(E.fieldType==="roleField",E.schema);if(!w)throw new Error(`Field ${E.path} not found in schema`);let I=E.fieldType==="roleField"?w?.playedBy[0]:w,M=(()=>w&&"relation"in w&&I?.relation===o.$relation?"$self":I?.relation?I?.relation:"$self")(),A=M==="$self"?t:l.relations[M];if(J(A.roles,(b,Q)=>b===E.path)?.playedBy?.length===0)throw new Error(`unused role: ${k}.${E.path}`);if(!w)throw new Error(`Field ${E.path} not found in schema`);let q=E.fieldType==="linkField"?w?.oppositeLinkFieldsPlayedBy:w?.playedBy;if(!q)throw new Error(`No opposite fields found for ${JSON.stringify(w)}`);if([...new Set(q?.map(b=>b.thing))].length>1)throw new Error(`Field: ${E.path} - If a role can be played by multiple things, you must specify the thing in the mutation: ${JSON.stringify(q)}. Schema: ${JSON.stringify(w)}`);if(w.cardinality==="ONE"&&Array.isArray(R))throw new Error("Can't have an array in a cardinality === ONE link field");if(w.cardinality==="MANY"&&R!==null&&!Array.isArray(R)&&!R.$arrayOp)throw new Error(`${E.fieldType==="linkField"?w.path:w.name} is a cardinality === MANY thing. Use an array or a $arrayOp object`);if(R?.$entity||R?.$relation)return;let L=q[0],F="plays"in w?"linkField":"roleField",B={[`$${L.thingType}`]:L.thing,[Symbol.for("relation")]:M,[Symbol.for("edgeType")]:F,[Symbol.for("parent")]:{path:k,...o.$id?{$id:o.$id}:{},...o.$tempId?{$tempId:o.$tempId}:{},...o.filter?{filter:o.filter}:{},links:q},[Symbol.for("role")]:L.plays,[Symbol.for("oppositeRole")]:"plays"in w?w.plays:void 0,[Symbol.for("relFieldSchema")]:w};if(radash.isObject(R)&&(t.thingType==="relation"&&R.$tempId&&F==="roleField"?o[E.path]=R.$tempId:o[E.path]={...B,...R}),Array.isArray(R))if(R.every(b=>radash.isObject(b)))o[E.path]=R.map(b=>b.$tempId&&t.thingType==="relation"&&(b.$op==="link"||!b.$op)?b.$tempId:{...B,...b});else if(R.every(b=>typeof b=="string"))o[E.path]=R.map(b=>({...B,$op:o.$op==="create"?"link":"replace",$id:b}));else throw new Error(`Invalid array value for ${E.path}`);if(typeof R=="string"&&(o[E.path]={...B,$op:o.$op==="create"?"link":"replace",$id:R}),R===null){let b={...B,$op:"unlink"};o[E.path]=w.cardinality==="MANY"?[b]:b;}}),!s&&!o.$entity&&!o.$relation)throw new Error("Root things must specify $entity or $relation")}})))(r),a=($=>dt($,y=>objectTraversal.traverse(y,({parent:g,key:d,value:c,meta:o})=>{if(radash.isObject(c)){if(Object.keys(c).length===0)throw new Error("Empty object!");if(d==="$filter"||o.nodePath?.includes(".$filter."))return;let t=c,i=o.nodePath?.split("."),s=i?.filter(Q=>Number.isNaN(parseInt(Q,10))).join("."),e=s?Array.isArray(g)?i?.slice(0,-1).join("."):o.nodePath:o.nodePath||"",m=N(l,t),{unidentifiedFields:u,dataFields:O,roleFields:P,linkFields:k}=W(m,t),E=dt.current(t)[Symbol.for("parent")],R=s&&E.path,I=(R?objectTraversal.getNodeByPath(y,R):y)?.$op;if(s&&!I)throw new Error("Error: Parent $op not detected");let T=t[Symbol.for("relFieldSchema")];if(t.$op==="replace"){if(I!=="create")throw new Error("Unsupported: For replaces, please do an unlink + a link instead");t.$op="link";}let M=Object.keys(t).some(Q=>O?.includes(Q)),A=Object.keys(t).some(Q=>[...P,...k].includes(Q)),S=()=>{if(t.$op)return t.$op;if(s&&!t.$id&&!t.$tempId&&I!=="create"&&T.cardinality==="ONE")throw new Error(`Please specify if it is a create or an update: ${JSON.stringify(t)} `);if(t.$tempId&&s)return "link";if(t.$tempId&&!s)return "create";if((t.$id||t.$filter)&&M)return "update";if((t.$id||t.$filter)&&s&&!M&&!A)return "link";if(!t.$filter&&!t.$id&&!t.$tempId)return "create";if((t.$id||t.$filter)&&!M&&A)return "match";throw new Error("Wrong op")};if(t.$op||(t.$op=S()),g||(t.$parentKey=""),typeof g=="object"&&(Array.isArray(g)&&(t[Symbol.for("index")]=d),t[Symbol.for("path")]=e,t[Symbol.for("isRoot")]=!s,t[Symbol.for("depth")]=s?.split(".").length),!t.$entity&&!t.$relation)throw new Error(`Node ${JSON.stringify(t)} without $entity/$relation`);let{idFields:q,computedFields:L}=m;if(!q)throw new Error("No idFields found");let F=q[0],B=radash.listify(t,(Q,C)=>C?Q:void 0);if(L.filter(Q=>!B.includes(Q)).forEach(Q=>{let C=m.dataFields?.find(j=>j.path===Q),G=m.linkFields?.find(j=>j.path===Q)?.oppositeLinkFieldsPlayedBy[0],D="roles"in m?J(m.roles,(j,oe)=>j===Q):void 0,U=C||G||D;if(!U)throw new Error(`no field Def for ${Q}`);if(Q===F&&t.$op==="create"&&!t[Q]){let j="default"in U?U.default?.value():void 0;if(!j)throw new Error(`No default value for ${Q}`);t[Q]=j,t.$id=j;}}),!t.$id)if(t[F])t.$id=t[F];else {if(t.$op==="create")throw new Error(`No id found for ${JSON.stringify(t)}`);t.$tempId||(t.$tempId=`all-${uuid.v4()}`);}if(u.length>0)throw new Error(`Unknown fields: [${u.join(",")}] in ${JSON.stringify(t)}`)}})))(h);f.filledBqlRequest=a;};var Ft=async f=>{let{filledBqlRequest:r,schema:l}=f,n=d=>{let c=[],o=[],t=e=>{if(e.$op==="create"&&c.find(m=>m.$id===e.$id))throw new Error(`Duplicate id ${e.$id}`);c.push(e);},i=e=>{if(e.$op==="create"&&o.find(m=>m.$id===e.$id))throw new Error(`Duplicate id ${e.$id}`);o.push(e);};return objectTraversal.traverse(d,({value:e})=>{if(e.$entity||e.$relation){if(!e.$id&&!e.$tempId&&!["link","unlink"].includes(e.$op))throw new Error("An id must be specified either in the mutation or has tu have a default value in the schema");let m=N(l,e),{dataFields:u,roleFields:O,linkFields:P,usedFields:k}=W(m,e),E=()=>{if(e.$op==="create"||e.$op==="delete")return e.$op;if(e.$op==="update"){let w=k.filter(M=>u?.includes(M)),I=k.filter(M=>O?.includes(M)),T=k.filter(M=>P?.includes(M));if(w.length>0)return "update";if(I.length>0||T.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(e)}`)}return "match"},R={...e.$entity&&{$entity:e.$entity},...e.$relation&&{$relation:e.$relation},...e.$id&&{$id:e.$id},...e.$tempId&&{$tempId:e.$tempId},...e.$filter&&{$filter:e.$filter},...radash.shake(radash.pick(e,u||[""])),$op:E(),[Symbol.for("bzId")]:e[Symbol.for("bzId")],[Symbol.for("dbId")]:m.defaultDBConnector.id,[Symbol.for("path")]:e[Symbol.for("path")],[Symbol.for("parent")]:e[Symbol.for("parent")],[Symbol.for("isRoot")]:e[Symbol.for("isRoot")]};if(Array.isArray(R.$id)?R.$id.forEach(w=>{t({...R,$id:w});}):t(R),e[Symbol.for("relation")]&&e[Symbol.for("edgeType")]==="linkField"){if((e.$op==="link"||e.$op==="unlink")&&(e.$id||e.$filter)){if(e.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");c.push({...e,$op:"match"});}let w=e[Symbol.for("relation")]===e.$relation;if(w&&!(e.$id||e.$tempId))throw new Error("No id or tempId found for complex link");let I=w?e.$id||e.$tempId:uuid.v4(),M=e[Symbol.for("parent")].path,A=M?objectTraversal.getNodeByPath(d,M):d,S=A.$tempId||A.$id;if(!S)throw new Error("No parent id found");if(e[Symbol.for("relation")]==="$self")return;let q=()=>{if(e.$op==="unlink"||e.$op==="delete")return w?"unlink":"delete";if(e.$op==="link"||e.$op==="create")return w?"link":"create";if(e.$op==="replace")throw new Error("Unsupported: Replaces not implemented yet");return "match"},L={$relation:e[Symbol.for("relation")],$op:q(),...e.$op==="unlink"?{$tempId:I}:{$id:I},...w&&e.$op==="link"&&e.$tempId?{$tempId:e.$tempId}:{},...w?{}:{[e[Symbol.for("role")]]:e.$tempId||e.$id},[e[Symbol.for("oppositeRole")]]:S,[Symbol.for("bzId")]:uuid.v4(),[Symbol.for("dbId")]:l.relations[e[Symbol.for("relation")]].defaultDBConnector.id,[Symbol.for("edgeType")]:"linkField",[Symbol.for("path")]:e[Symbol.for("path")],[Symbol.for("parent")]:e[Symbol.for("parent")]};i(L),(e.$op==="unlink"||q()==="unlink")&&w&&i({$relation:e[Symbol.for("relation")],$op:"match",...e.$op==="unlink"?{$tempId:I}:{$id:I},[e[Symbol.for("oppositeRole")]]:S,[Symbol.for("bzId")]:uuid.v4(),[Symbol.for("dbId")]:l.relations[e[Symbol.for("relation")]].defaultDBConnector.id,[Symbol.for("edgeType")]:"linkField",[Symbol.for("path")]:e[Symbol.for("path")],[Symbol.for("parent")]:e[Symbol.for("parent")]});}if(e.$relation){let w=e,I=x(w,(A,S)=>O.includes(A)),T=radash.mapEntries(I,(A,S)=>[A,S]),M=x(w,(A,S)=>A.startsWith("$")||A.startsWith("Symbol"));if(Object.keys(I).filter(A=>!A.startsWith("$")).length>0){if(w.$op==="create"||w.$op==="delete"){let A=()=>{if(w.$op==="create")return "link";if(w.$op==="delete")return "unlink";throw new Error("Unsupported parent of edge op")},S=radash.mapEntries(T,(L,F)=>Array.isArray(F)?[L,F.map(B=>B.$tempId||B.$id||B)]:[L,F.$id||F]),q={...M,$relation:w.$relation,$op:A(),...S,[Symbol.for("dbId")]:m.defaultDBConnector.id,[Symbol.for("path")]:e[Symbol.for("path")],[Symbol.for("info")]:"coming from created or deleted relation",[Symbol.for("edgeType")]:"roleField on C/D"};i(q);return}if(w.$op==="match"||w.$op==="update"&&Object.keys(I).length>0){let A=x(T,(B,b)=>(Array.isArray(b)?b:[b]).some(C=>C.$op==="link"||C.$op==="create")),S=radash.mapEntries(A,(B,b)=>{let Q=Array.isArray(b)?b:[b];return [B,Q.filter(C=>C.$op==="link"||C.$op==="create").flatMap(C=>C.$id||C.$tempId)]}),q=x(T,(B,b)=>(Array.isArray(b)?b:[b]).some(C=>C.$op==="unlink"||C.$op==="delete")),L=radash.mapEntries(q,(B,b)=>{let Q=Array.isArray(b)?b:[b];return [B,Q.filter(C=>C.$op==="unlink"||C.$op==="delete").flatMap(C=>C.$id||C.$tempId)]});[{op:"link",obj:S},{op:"unlink",obj:L},{op:"replace",obj:{}}].forEach(B=>{if(Object.keys(B.obj).length){if(B.op==="unlink"&&Object.keys(B.obj).length>1)throw new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let b={...M,$relation:w.$relation,$op:B.op,...B.obj,[Symbol.for("dbId")]:m.defaultDBConnector.id,[Symbol.for("parent")]:e[Symbol.for("parent")],[Symbol.for("path")]:e[Symbol.for("path")],[Symbol.for("info")]:"updating roleFields",[Symbol.for("edgeType")]:"roleField on L/U/R"};i(b),b.$op==="unlink"&&i({...b,$op:"match"});}});}}}}}),[c,o]};if(!r)throw new Error("Undefined filledBqlRequest");let[h,p]=n(r),a=h.reduce((d,c)=>{if(!c.$tempId)return [...d,c];let o=d.findIndex(t=>t.$tempId===c.$tempId);if(o===-1)return [...d,c];if(d[o].$op==="create"&&c.$op==="match")return d;if(d[o].$op==="match"&&(c.$op==="create"||c.$op==="match"))return [...d.slice(0,o),c,...d.slice(o+1)];throw new Error(`Unsupported operation combination for $tempId "${c.$tempId}"`)},[]),$=p.reduce((d,c)=>{let o=d.find(t=>(t.$id&&t.$id===c.$id||t.$tempId&&t.$tempId===c.$tempId)&&t.$relation===c.$relation&&t.$op===c.$op);if(o){let t={...o};return Object.keys(c).forEach(s=>{if(typeof s=="symbol"||s.startsWith("$"))return;let e=o[s],m=c[s];Array.isArray(e)&&Array.isArray(m)?t[s]=Array.from(new Set([...e,...m])):!Array.isArray(e)&&Array.isArray(m)?e!==void 0?t[s]=Array.from(new Set([e,...m])):t[s]=m:Array.isArray(e)&&!Array.isArray(m)?m!==void 0&&(t[s]=Array.from(new Set([...e,m]))):e||(t[s]=m);}),[...d.filter(s=>!((s.$id&&s.$id===c.$id||s.$tempId&&s.$tempId===c.$tempId)&&s.$relation===c.$relation&&s.$op===c.$op)),t]}return [...d,c]},[]),y=[...new Set($.map(d=>d.$relation))];(()=>{let d={};if(y.forEach(c=>{Object.keys(l.relations[c].roles).filter(t=>l.relations[c].roles[t].cardinality==="ONE").forEach(t=>{let i={};$.forEach(s=>{if(s.$relation===c&&s[t]){let e=s[t],m=Object.keys(s).find(u=>u!=="$relation"&&u!=="$op"&&u!=="$id"&&u!==t);if(m){let u=s[m];i[u]||(i[u]=new Set),i[u].add(e);}}}),Object.entries(i).forEach(([s,e])=>{e.size>1&&(d[s]=d[s]||new Set,d[s].add(`Entity with ID: ${s} in relation "${c}" linked to multiple ${e.size} entities in role "${t}".`));});});}),Object.keys(d).length>0){let c="";throw Object.entries(d).forEach(([o,t])=>{c+=`Account "${o}" is connected to many entities. ${Array.from(t).join(" ")}The relation's role is of cardinality ONE.
12
- `;}),new Error(c)}})(),f.bqlRequest={mutation:{things:a,edges:$}};};var St=async(f,r)=>{let{dbHandles:l,tqlRequest:n,bqlRequest:h,config:p}=f;if(!n)throw new Error("TQL request not built");if(!(n.deletions&&n.deletionMatches||n.insertions))throw new Error("TQL request error, no things");if(!h?.mutation)throw new Error("BQL mutation not parsed");let a=p.dbConnectors[0].id,$=l.typeDB.get(a)?.session;if(!$?.isOpen())throw new Error("Session is closed");let y=await $.transaction(typedbClient.TransactionType.WRITE);if(!y)throw new Error("Can't create transaction");let g=n.deletionMatches&&n.deletions&&`match ${n.deletionMatches} delete ${n.deletions}`,d=n.insertions&&`${n.insertionMatches?`match ${n.insertionMatches}`:""} insert ${n.insertions}`;g&&y.query.delete(g);let c=d&&y.query.insert(d),o=c?await c.collect():void 0;await y.commit(),await y.close(),r.rawTqlRes={insertions:o};};var Tt={query:[Bt,K,Y,V,ot],mutation:[Lt,Ft,wt,St,V]},ee=[gt],tt=async(f,r,l={},n=!0)=>{for(let h of f){let p=await h(r,l);if(p&&Array.isArray(p))for(let a of p)await tt(a.pipeline,a.req,a.res,!1);}if(n)return await tt(ee,r,l,!1),r.config.query?.debugger===!0&&typeof l.bqlRes=="object"?{...l.bqlRes,$debugger:{tqlRequest:r.tqlRequest}}:l.bqlRes},Mt=(f,r,l,n)=>tt(Tt.query,{config:r,schema:l,rawBqlRequest:f,dbHandles:n},{}),qt=(f,r,l,n)=>tt(Tt.mutation,{config:r,schema:l,rawBqlRequest:f,dbHandles:n},{});var lt=class{schema;config;dbHandles;constructor({schema:r,config:l}){this.schema=r,this.config=l;}init=async()=>{let r={typeDB:new Map},l=ft(this.schema);await Promise.all(this.config.dbConnectors.map(async n=>{if(n.provider==="typeDB"&&n.dbName){let[h,p]=await radash.tryit(typedbClient.TypeDB.coreClient)(n.url);if(h){let a=`[BORM:${n.provider}:${n.dbName}] ${h.message??"Can't create TypeDB Client"}`;throw new Error(a)}try{let a=await p.session(n.dbName,typedbClient.SessionType.DATA);r.typeDB.set(n.id,{client:p,session:a});}catch(a){let $=`[BORM:${n.provider}:${n.dbName}] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error($)}}})),this.schema=l,this.dbHandles=r;};#t=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#t(),this.schema);query=async(r,l)=>{await this.#t();let n={...this.config,query:{...et.query,...this.config.query,...l}};return Mt(r,n,this.schema,this.dbHandles)};mutate=async(r,l)=>{await this.#t();let n={...this.config,mutation:{...et.mutation,...this.config.mutation,...l}};return qt(r,n,this.schema,this.dbHandles)};close=async()=>{!this.dbHandles||this.dbHandles.typeDB.forEach(async({client:r,session:l})=>{console.log("Closing session"),await l.close(),console.log("Closing client"),await r.close();});}},Mi=lt;//! reads all the insertions and gets the first match. This means each id must be unique
11
+ `}return ""},q=()=>i==="update"||i==="link"||i==="match"?`$${s} isa ${[m,...M].filter(L=>L).join(",")};`:"";if(t.$entity||t.$relation)return {op:i,deletionMatch:S(),insertionMatch:q(),insertion:i==="create"?`$${s} isa ${[m,A].filter(L=>L).join(",")};`:i==="update"&&P.length?`$${s} ${P.join(",")};`:"",deletion:i==="delete"?`$${s} isa ${m};`:i==="update"&&E.length?`$${s} has ${k};`:""};throw new Error("in attributes")},p=t=>{let i=t.$op,s=t.$tempId||t.$id,e=N(l,t),m=e.defaultDBConnector?.path||t.$relation,u="roles"in e?radash.listify(e.roles,S=>S):[],O=t.$relation&&"roles"in e&&radash.mapEntries(e.roles,(S,q)=>[S,q.dbConnector?.path||S]),P=radash.listify(t,(S,q)=>{if(!u.includes(S))return null;if(!("roles"in e))throw new Error("This should have roles! ");let L=O[S];return Array.isArray(q)?q.map(F=>({path:L,id:F})):{path:L,id:q}}).filter(S=>S).flat(),k=P.map(S=>{if(!S?.path)throw new Error("Object without path");return `${S.path}: $${S.id}`}),E=P.length>0?`( ${k.join(" , ")} )`:"",R=E?`$${s} ${E} ${t[Symbol.for("edgeType")]==="linkField"||i==="delete"||i==="unlink"?`isa ${m}`:""}`:"",w=`$${s} ${t[Symbol.for("edgeType")]==="linkField"||i==="delete"?`isa ${m}`:""}`,I=()=>R?i==="link"?`${R};`:i==="create"?`${R}, has id '${s}';`:"":"",T=()=>R&&i==="match"?`${R};`:"",M=()=>R?i==="delete"?`${R};`:i==="match"?`${R};`:"":"",A=()=>R?i==="delete"?`${w};`:i==="unlink"?`$${s} ${E};`:"":"";return {deletionMatch:M(),insertionMatch:T(),deletion:A(),insertion:I(),op:""}},a=(t,i)=>{let s=i==="edges"?p:h;if(Array.isArray(t))return t.map(k=>{let{preDeletionBatch:E,insertionMatch:R,deletionMatch:w,insertion:I,deletion:T}=s(k);return radash.shake({preDeletionBatch:E,insertionMatch:R,deletionMatch:w,insertion:I,deletion:T},M=>!M)}).filter(k=>k);let{preDeletionBatch:e,insertionMatch:m,deletionMatch:u,insertion:O,deletion:P}=s(t);return radash.shake({preDeletionBatch:e,insertionMatch:m,deletionMatch:u,insertion:O,deletion:P},k=>!k)},$=a(n.things),y=Array.isArray($)?$:[$],g=a(n.edges,"edges"),d=Array.isArray(g)?g:[g],c=[...y,...d],o=radash.shake({insertionMatches:c.map(t=>t.insertionMatch).join(" ").trim(),deletionMatches:c.map(t=>t.deletionMatch).join(" ").trim(),insertions:c.map(t=>t.insertion).join(" ").trim(),deletions:c.map(t=>t.deletion).join(" ").trim()},t=>!t);f.tqlRequest=o;};var Lt=async f=>{let{rawBqlRequest:r,schema:l}=f,h=($=>immer.produce($,y=>objectTraversal.traverse(y,({value:g,meta:d,key:c})=>{if(radash.isObject(g)){if(g.$arrayOp)throw new Error("Array op not supported yet");if(c==="$filter"||d.nodePath?.includes(".$filter."))return;let o=g;if(o.$op==="create"&&o.$id)throw new Error("Can't write to computed field $id. Try writing to the id field directly.");let t=N(l,g),s=d.nodePath?.split(".")?.filter(E=>Number.isNaN(parseInt(E,10))).join(".");if(!t)throw new Error(`Schema not found for ${g.$entity||g.$relation}`);o[Symbol.for("bzId")]=uuid.v4(),o[Symbol.for("schema")]=t,o[Symbol.for("dbId")]=t.defaultDBConnector.id;let{usedLinkFields:e,usedRoleFields:m}=W(t,o),u=e.map(E=>({fieldType:"linkField",path:E,schema:t.linkFields.find(R=>R.path===E)})),O=t.thingType==="relation"?m.map(E=>({fieldType:"roleField",path:E,schema:J(t.roles,R=>R===E)})):[];if(u.some(E=>E.schema?.target==="role")&&u.some(E=>E.schema?.target==="relation"))throw new Error("Unsupported: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.");let P=O.filter(E=>[...new Set(E.schema.playedBy?.map(R=>R.thing))].length!==1);if(P.length>1)throw new Error(`Field: ${P[0].path} - If a role can be played by multiple things, you must specify the thing in the mutation: ${JSON.stringify(P[0].schema.playedBy)}. Schema: ${JSON.stringify(P[0].schema)}`);let k=d.nodePath;if([...u,...O].forEach(E=>{let R=o[E.path];if(R===void 0)return;let w=(E.fieldType==="roleField",E.schema);if(!w)throw new Error(`Field ${E.path} not found in schema`);let I=E.fieldType==="roleField"?w?.playedBy[0]:w,M=(()=>w&&"relation"in w&&I?.relation===o.$relation?"$self":I?.relation?I?.relation:"$self")(),A=M==="$self"?t:l.relations[M];if(J(A.roles,(b,Q)=>b===E.path)?.playedBy?.length===0)throw new Error(`unused role: ${k}.${E.path}`);if(!w)throw new Error(`Field ${E.path} not found in schema`);let q=E.fieldType==="linkField"?w?.oppositeLinkFieldsPlayedBy:w?.playedBy;if(!q)throw new Error(`No opposite fields found for ${JSON.stringify(w)}`);if([...new Set(q?.map(b=>b.thing))].length>1)throw new Error(`Field: ${E.path} - If a role can be played by multiple things, you must specify the thing in the mutation: ${JSON.stringify(q)}. Schema: ${JSON.stringify(w)}`);if(w.cardinality==="ONE"&&Array.isArray(R))throw new Error("Can't have an array in a cardinality === ONE link field");if(w.cardinality==="MANY"&&R!==null&&!Array.isArray(R)&&!R.$arrayOp)throw new Error(`${E.fieldType==="linkField"?w.path:w.name} is a cardinality === MANY thing. Use an array or a $arrayOp object`);if(R?.$entity||R?.$relation)return;let L=q[0],F="plays"in w?"linkField":"roleField",B={[`$${L.thingType}`]:L.thing,[Symbol.for("relation")]:M,[Symbol.for("edgeType")]:F,[Symbol.for("parent")]:{path:k,...o.$id?{$id:o.$id}:{},...o.$tempId?{$tempId:o.$tempId}:{},...o.filter?{filter:o.filter}:{},links:q},[Symbol.for("role")]:L.plays,[Symbol.for("oppositeRole")]:"plays"in w?w.plays:void 0,[Symbol.for("relFieldSchema")]:w};if(radash.isObject(R)&&(t.thingType==="relation"&&R.$tempId&&F==="roleField"?o[E.path]=R.$tempId:o[E.path]={...B,...R}),Array.isArray(R))if(R.every(b=>radash.isObject(b)))o[E.path]=R.map(b=>b.$tempId&&t.thingType==="relation"&&(b.$op==="link"||!b.$op)?b.$tempId:{...B,...b});else if(R.every(b=>typeof b=="string"))o[E.path]=R.map(b=>({...B,$op:o.$op==="create"?"link":"replace",$id:b}));else throw new Error(`Invalid array value for ${E.path}`);if(typeof R=="string"&&(o[E.path]={...B,$op:o.$op==="create"?"link":"replace",$id:R}),R===null){let b={...B,$op:"unlink"};o[E.path]=w.cardinality==="MANY"?[b]:b;}}),!s&&!o.$entity&&!o.$relation)throw new Error("Root things must specify $entity or $relation")}})))(r),a=($=>immer.produce($,y=>objectTraversal.traverse(y,({parent:g,key:d,value:c,meta:o})=>{if(radash.isObject(c)){if(Object.keys(c).length===0)throw new Error("Empty object!");if(d==="$filter"||o.nodePath?.includes(".$filter."))return;let t=c,i=o.nodePath?.split("."),s=i?.filter(Q=>Number.isNaN(parseInt(Q,10))).join("."),e=s?Array.isArray(g)?i?.slice(0,-1).join("."):o.nodePath:o.nodePath||"",m=N(l,t),{unidentifiedFields:u,dataFields:O,roleFields:P,linkFields:k}=W(m,t),E=immer.current(t)[Symbol.for("parent")],R=s&&E.path,I=(R?objectTraversal.getNodeByPath(y,R):y)?.$op;if(s&&!I)throw new Error("Error: Parent $op not detected");let T=t[Symbol.for("relFieldSchema")];if(t.$op==="replace"){if(I!=="create")throw new Error("Unsupported: For replaces, please do an unlink + a link instead");t.$op="link";}let M=Object.keys(t).some(Q=>O?.includes(Q)),A=Object.keys(t).some(Q=>[...P,...k].includes(Q)),S=()=>{if(t.$op)return t.$op;if(s&&!t.$id&&!t.$tempId&&I!=="create"&&T.cardinality==="ONE")throw new Error(`Please specify if it is a create or an update: ${JSON.stringify(t)} `);if(t.$tempId&&s)return "link";if(t.$tempId&&!s)return "create";if((t.$id||t.$filter)&&M)return "update";if((t.$id||t.$filter)&&s&&!M&&!A)return "link";if(!t.$filter&&!t.$id&&!t.$tempId)return "create";if((t.$id||t.$filter)&&!M&&A)return "match";throw new Error("Wrong op")};if(t.$op||(t.$op=S()),g||(t.$parentKey=""),typeof g=="object"&&(Array.isArray(g)&&(t[Symbol.for("index")]=d),t[Symbol.for("path")]=e,t[Symbol.for("isRoot")]=!s,t[Symbol.for("depth")]=s?.split(".").length),!t.$entity&&!t.$relation)throw new Error(`Node ${JSON.stringify(t)} without $entity/$relation`);let{idFields:q,computedFields:L}=m;if(!q)throw new Error("No idFields found");let F=q[0],B=radash.listify(t,(Q,C)=>C?Q:void 0);if(L.filter(Q=>!B.includes(Q)).forEach(Q=>{let C=m.dataFields?.find(j=>j.path===Q),G=m.linkFields?.find(j=>j.path===Q)?.oppositeLinkFieldsPlayedBy[0],D="roles"in m?J(m.roles,(j,oe)=>j===Q):void 0,U=C||G||D;if(!U)throw new Error(`no field Def for ${Q}`);if(Q===F&&t.$op==="create"&&!t[Q]){let j="default"in U?U.default?.value():void 0;if(!j)throw new Error(`No default value for ${Q}`);t[Q]=j,t.$id=j;}}),!t.$id)if(t[F])t.$id=t[F];else {if(t.$op==="create")throw new Error(`No id found for ${JSON.stringify(t)}`);t.$tempId||(t.$tempId=`all-${uuid.v4()}`);}if(u.length>0)throw new Error(`Unknown fields: [${u.join(",")}] in ${JSON.stringify(t)}`)}})))(h);f.filledBqlRequest=a;};var Ft=async f=>{let{filledBqlRequest:r,schema:l}=f,n=d=>{let c=[],o=[],t=e=>{if(e.$op==="create"&&c.find(m=>m.$id===e.$id))throw new Error(`Duplicate id ${e.$id}`);c.push(e);},i=e=>{if(e.$op==="create"&&o.find(m=>m.$id===e.$id))throw new Error(`Duplicate id ${e.$id}`);o.push(e);};return objectTraversal.traverse(d,({value:e})=>{if(e.$entity||e.$relation){if(!e.$id&&!e.$tempId&&!["link","unlink"].includes(e.$op))throw new Error("An id must be specified either in the mutation or has tu have a default value in the schema");let m=N(l,e),{dataFields:u,roleFields:O,linkFields:P,usedFields:k}=W(m,e),E=()=>{if(e.$op==="create"||e.$op==="delete")return e.$op;if(e.$op==="update"){let w=k.filter(M=>u?.includes(M)),I=k.filter(M=>O?.includes(M)),T=k.filter(M=>P?.includes(M));if(w.length>0)return "update";if(I.length>0||T.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(e)}`)}return "match"},R={...e.$entity&&{$entity:e.$entity},...e.$relation&&{$relation:e.$relation},...e.$id&&{$id:e.$id},...e.$tempId&&{$tempId:e.$tempId},...e.$filter&&{$filter:e.$filter},...radash.shake(radash.pick(e,u||[""])),$op:E(),[Symbol.for("bzId")]:e[Symbol.for("bzId")],[Symbol.for("dbId")]:m.defaultDBConnector.id,[Symbol.for("path")]:e[Symbol.for("path")],[Symbol.for("parent")]:e[Symbol.for("parent")],[Symbol.for("isRoot")]:e[Symbol.for("isRoot")]};if(Array.isArray(R.$id)?R.$id.forEach(w=>{t({...R,$id:w});}):t(R),e[Symbol.for("relation")]&&e[Symbol.for("edgeType")]==="linkField"){if((e.$op==="link"||e.$op==="unlink")&&(e.$id||e.$filter)){if(e.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");c.push({...e,$op:"match"});}let w=e[Symbol.for("relation")]===e.$relation;if(w&&!(e.$id||e.$tempId))throw new Error("No id or tempId found for complex link");let I=w?e.$id||e.$tempId:uuid.v4(),M=e[Symbol.for("parent")].path,A=M?objectTraversal.getNodeByPath(d,M):d,S=A.$tempId||A.$id;if(!S)throw new Error("No parent id found");if(e[Symbol.for("relation")]==="$self")return;let q=()=>{if(e.$op==="unlink"||e.$op==="delete")return w?"unlink":"delete";if(e.$op==="link"||e.$op==="create")return w?"link":"create";if(e.$op==="replace")throw new Error("Unsupported: Replaces not implemented yet");return "match"},L={$relation:e[Symbol.for("relation")],$op:q(),...e.$op==="unlink"?{$tempId:I}:{$id:I},...w&&e.$op==="link"&&e.$tempId?{$tempId:e.$tempId}:{},...w?{}:{[e[Symbol.for("role")]]:e.$tempId||e.$id},[e[Symbol.for("oppositeRole")]]:S,[Symbol.for("bzId")]:uuid.v4(),[Symbol.for("dbId")]:l.relations[e[Symbol.for("relation")]].defaultDBConnector.id,[Symbol.for("edgeType")]:"linkField",[Symbol.for("path")]:e[Symbol.for("path")],[Symbol.for("parent")]:e[Symbol.for("parent")]};i(L),(e.$op==="unlink"||q()==="unlink")&&w&&i({$relation:e[Symbol.for("relation")],$op:"match",...e.$op==="unlink"?{$tempId:I}:{$id:I},[e[Symbol.for("oppositeRole")]]:S,[Symbol.for("bzId")]:uuid.v4(),[Symbol.for("dbId")]:l.relations[e[Symbol.for("relation")]].defaultDBConnector.id,[Symbol.for("edgeType")]:"linkField",[Symbol.for("path")]:e[Symbol.for("path")],[Symbol.for("parent")]:e[Symbol.for("parent")]});}if(e.$relation){let w=e,I=x(w,(A,S)=>O.includes(A)),T=radash.mapEntries(I,(A,S)=>[A,S]),M=x(w,(A,S)=>A.startsWith("$")||A.startsWith("Symbol"));if(Object.keys(I).filter(A=>!A.startsWith("$")).length>0){if(w.$op==="create"||w.$op==="delete"){let A=()=>{if(w.$op==="create")return "link";if(w.$op==="delete")return "unlink";throw new Error("Unsupported parent of edge op")},S=radash.mapEntries(T,(L,F)=>Array.isArray(F)?[L,F.map(B=>B.$tempId||B.$id||B)]:[L,F.$id||F]),q={...M,$relation:w.$relation,$op:A(),...S,[Symbol.for("dbId")]:m.defaultDBConnector.id,[Symbol.for("path")]:e[Symbol.for("path")],[Symbol.for("info")]:"coming from created or deleted relation",[Symbol.for("edgeType")]:"roleField on C/D"};i(q);return}if(w.$op==="match"||w.$op==="update"&&Object.keys(I).length>0){let A=x(T,(B,b)=>(Array.isArray(b)?b:[b]).some(C=>C.$op==="link"||C.$op==="create")),S=radash.mapEntries(A,(B,b)=>{let Q=Array.isArray(b)?b:[b];return [B,Q.filter(C=>C.$op==="link"||C.$op==="create").flatMap(C=>C.$id||C.$tempId)]}),q=x(T,(B,b)=>(Array.isArray(b)?b:[b]).some(C=>C.$op==="unlink"||C.$op==="delete")),L=radash.mapEntries(q,(B,b)=>{let Q=Array.isArray(b)?b:[b];return [B,Q.filter(C=>C.$op==="unlink"||C.$op==="delete").flatMap(C=>C.$id||C.$tempId)]});[{op:"link",obj:S},{op:"unlink",obj:L},{op:"replace",obj:{}}].forEach(B=>{if(Object.keys(B.obj).length){if(B.op==="unlink"&&Object.keys(B.obj).length>1)throw new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let b={...M,$relation:w.$relation,$op:B.op,...B.obj,[Symbol.for("dbId")]:m.defaultDBConnector.id,[Symbol.for("parent")]:e[Symbol.for("parent")],[Symbol.for("path")]:e[Symbol.for("path")],[Symbol.for("info")]:"updating roleFields",[Symbol.for("edgeType")]:"roleField on L/U/R"};i(b),b.$op==="unlink"&&i({...b,$op:"match"});}});}}}}}),[c,o]};if(!r)throw new Error("Undefined filledBqlRequest");let[h,p]=n(r),a=h.reduce((d,c)=>{if(!c.$tempId)return [...d,c];let o=d.findIndex(t=>t.$tempId===c.$tempId);if(o===-1)return [...d,c];if(d[o].$op==="create"&&c.$op==="match")return d;if(d[o].$op==="match"&&(c.$op==="create"||c.$op==="match"))return [...d.slice(0,o),c,...d.slice(o+1)];throw new Error(`Unsupported operation combination for $tempId "${c.$tempId}"`)},[]),$=p.reduce((d,c)=>{let o=d.find(t=>(t.$id&&t.$id===c.$id||t.$tempId&&t.$tempId===c.$tempId)&&t.$relation===c.$relation&&t.$op===c.$op);if(o){let t={...o};return Object.keys(c).forEach(s=>{if(typeof s=="symbol"||s.startsWith("$"))return;let e=o[s],m=c[s];Array.isArray(e)&&Array.isArray(m)?t[s]=Array.from(new Set([...e,...m])):!Array.isArray(e)&&Array.isArray(m)?e!==void 0?t[s]=Array.from(new Set([e,...m])):t[s]=m:Array.isArray(e)&&!Array.isArray(m)?m!==void 0&&(t[s]=Array.from(new Set([...e,m]))):e||(t[s]=m);}),[...d.filter(s=>!((s.$id&&s.$id===c.$id||s.$tempId&&s.$tempId===c.$tempId)&&s.$relation===c.$relation&&s.$op===c.$op)),t]}return [...d,c]},[]),y=[...new Set($.map(d=>d.$relation))];(()=>{let d={};if(y.forEach(c=>{Object.keys(l.relations[c].roles).filter(t=>l.relations[c].roles[t].cardinality==="ONE").forEach(t=>{let i={};$.forEach(s=>{if(s.$relation===c&&s[t]){let e=s[t],m=Object.keys(s).find(u=>u!=="$relation"&&u!=="$op"&&u!=="$id"&&u!==t);if(m){let u=s[m];i[u]||(i[u]=new Set),i[u].add(e);}}}),Object.entries(i).forEach(([s,e])=>{e.size>1&&(d[s]=d[s]||new Set,d[s].add(`Entity with ID: ${s} in relation "${c}" linked to multiple ${e.size} entities in role "${t}".`));});});}),Object.keys(d).length>0){let c="";throw Object.entries(d).forEach(([o,t])=>{c+=`Account "${o}" is connected to many entities. ${Array.from(t).join(" ")}The relation's role is of cardinality ONE.
12
+ `;}),new Error(c)}})(),f.bqlRequest={mutation:{things:a,edges:$}};};var St=async(f,r)=>{let{dbHandles:l,tqlRequest:n,bqlRequest:h,config:p}=f;if(!n)throw new Error("TQL request not built");if(!(n.deletions&&n.deletionMatches||n.insertions))throw new Error("TQL request error, no things");if(!h?.mutation)throw new Error("BQL mutation not parsed");let a=p.dbConnectors[0].id,$=l.typeDB.get(a)?.session;if(!$?.isOpen())throw new Error("Session is closed");let y=await $.transaction(typedbClient.TransactionType.WRITE);if(!y)throw new Error("Can't create transaction");let g=n.deletionMatches&&n.deletions&&`match ${n.deletionMatches} delete ${n.deletions}`,d=n.insertions&&`${n.insertionMatches?`match ${n.insertionMatches}`:""} insert ${n.insertions}`;g&&y.query.delete(g);let c=d&&y.query.insert(d),o=c?await c.collect():void 0;await y.commit(),await y.close(),r.rawTqlRes={insertions:o};};var Tt={query:[Bt,K,Y,V,ot],mutation:[Lt,Ft,wt,St,V]},ee=[gt],tt=async(f,r,l={},n=!0)=>{for(let h of f){let p=await h(r,l);if(p&&Array.isArray(p))for(let a of p)await tt(a.pipeline,a.req,a.res,!1);}if(n)return await tt(ee,r,l,!1),r.config.query?.debugger===!0&&typeof l.bqlRes=="object"?{...l.bqlRes,$debugger:{tqlRequest:r.tqlRequest}}:l.bqlRes},Mt=(f,r,l,n)=>tt(Tt.query,{config:r,schema:l,rawBqlRequest:f,dbHandles:n},{}),qt=(f,r,l,n)=>tt(Tt.mutation,{config:r,schema:l,rawBqlRequest:f,dbHandles:n},{});var lt=class{schema;config;dbHandles;constructor({schema:r,config:l}){this.schema=r,this.config=l;}init=async()=>{let r={typeDB:new Map},l=ft(this.schema);await Promise.all(this.config.dbConnectors.map(async n=>{if(n.provider==="typeDB"&&n.dbName){let[h,p]=await radash.tryit(typedbClient.TypeDB.coreClient)(n.url);if(h){let a=`[BORM:${n.provider}:${n.dbName}] ${h.message??"Can't create TypeDB Client"}`;throw new Error(a)}try{let a=await p.session(n.dbName,typedbClient.SessionType.DATA);r.typeDB.set(n.id,{client:p,session:a});}catch(a){let $=`[BORM:${n.provider}:${n.dbName}] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error($)}}})),this.schema=l,this.dbHandles=r;};#t=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#t(),this.schema);query=async(r,l)=>{await this.#t();let n={...this.config,query:{...et.query,...this.config.query,...l}};return Mt(r,n,this.schema,this.dbHandles)};mutate=async(r,l)=>{await this.#t();let n={...this.config,mutation:{...et.mutation,...this.config.mutation,...l}};return qt(r,n,this.schema,this.dbHandles)};close=async()=>{this.dbHandles&&this.dbHandles.typeDB.forEach(async({client:r,session:l})=>{console.log("Closing session"),await l.close(),console.log("Closing client"),await r.close();});}},Mi=lt;//! reads all the insertions and gets the first match. This means each id must be unique
13
13
 
14
14
  module.exports = Mi;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blitznocode/blitz-orm",
3
- "version": "0.1.10",
3
+ "version": "0.1.11",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "scripts": {
@@ -30,31 +30,31 @@
30
30
  "registry": "https://registry.npmjs.org/"
31
31
  },
32
32
  "dependencies": {
33
- "immer": "^9.0.19",
34
- "nanoid": "^4.0.1",
33
+ "immer": "^10.0.2",
34
+ "nanoid": "^4.0.2",
35
35
  "object-traversal": "^1.0.1",
36
- "radash": "^10.7.0",
37
- "typedb-client": "^2.17.0",
36
+ "radash": "^11.0.0",
37
+ "typedb-client": "2.17.0",
38
38
  "uuid": "^9.0.0"
39
39
  },
40
40
  "devDependencies": {
41
- "@types/jest": "^29.2.5",
42
- "@types/node": "^18.11.18",
43
- "@types/uuid": "^9.0.0",
44
- "@typescript-eslint/eslint-plugin": "^5.50.0",
45
- "@typescript-eslint/parser": "^5.50.0",
46
- "eslint": "^8.33.0",
41
+ "@types/jest": "^29.5.3",
42
+ "@types/node": "^20.4.5",
43
+ "@types/uuid": "^9.0.2",
44
+ "@typescript-eslint/eslint-plugin": "^6.2.1",
45
+ "@typescript-eslint/parser": "^6.2.1",
46
+ "eslint": "^8.46.0",
47
47
  "eslint-config-airbnb-base": "^15.0.0",
48
- "eslint-config-airbnb-typescript": "^17.0.0",
49
- "eslint-config-prettier": "^8.6.0",
50
- "eslint-plugin-import": "^2.27.5",
51
- "eslint-plugin-prettier": "^4.2.1",
52
- "eslint-plugin-unused-imports": "^2.0.0",
53
- "jest": "^29.3.1",
54
- "prettier": "^2.8.3",
55
- "ts-jest": "^29.0.3",
56
- "tsup": "^6.5.0",
57
- "typescript": "^4.9.5"
48
+ "eslint-config-airbnb-typescript": "^17.1.0",
49
+ "eslint-config-prettier": "^8.9.0",
50
+ "eslint-plugin-import": "^2.28.0",
51
+ "eslint-plugin-prettier": "^5.0.0",
52
+ "eslint-plugin-unused-imports": "^3.0.0",
53
+ "jest": "^29.6.2",
54
+ "prettier": "^3.0.0",
55
+ "ts-jest": "^29.1.1",
56
+ "tsup": "^7.1.0",
57
+ "typescript": "^5.1.6"
58
58
  },
59
59
  "description": "Blitz-orm is a public package that can be open-sourced",
60
60
  "bugs": {