@roc-db/in-memory 0.2.0-pre.7 → 0.2.0-pre.71

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.js CHANGED
@@ -10,85 +10,157 @@ var __export = (target, all) => {
10
10
  };
11
11
 
12
12
  // src/createInMemoryAdapter.ts
13
- import { createAdapter, Snowflake } from "roc-db";
13
+ import {
14
+ createAdapter,
15
+ Snowflake
16
+ } from "roc-db";
14
17
 
15
18
  // src/functions/index.ts
16
19
  var exports_functions = {};
17
20
  __export(exports_functions, {
18
- updateEntity: () => updateEntity,
19
21
  saveMutation: () => saveMutation,
22
+ refByUniqueField: () => refByUniqueField,
20
23
  readMutation: () => readMutation,
21
24
  readEntity: () => readEntity,
22
- patchEntity: () => patchEntity,
23
25
  pageMutations: () => pageMutations,
26
+ pageEntitiesByIndex: () => pageEntitiesByIndex,
27
+ pageEntities: () => pageEntities,
24
28
  getChangeSetMutations: () => getChangeSetMutations,
25
29
  findDebounceMutation: () => findDebounceMutation,
26
- deleteEntity: () => deleteEntity,
27
- createEntity: () => createEntity,
28
- begin: () => begin
30
+ commit: () => commit,
31
+ batchReadEntities: () => batchReadEntities
29
32
  });
30
33
 
31
- // src/functions/begin.ts
32
- var begin = (request, engineOpts, callback) => {
33
- return callback({
34
- ...engineOpts,
35
- changeSet: request.changeSetRef ? {
36
- entities: new Map([]),
37
- mutations: new Map([])
38
- } : null
39
- });
34
+ // src/functions/readEntity.ts
35
+ var readEntity = (txn, ref) => txn.engineOpts.entities.get(ref);
36
+
37
+ // src/functions/batchReadEntities.ts
38
+ var batchReadEntities = (txn, refs) => {
39
+ return refs.map((ref) => readEntity(txn, ref));
40
+ };
41
+ // src/functions/commit.ts
42
+ import {
43
+ createUniqueConstraintConflictError
44
+ } from "roc-db";
45
+
46
+ // src/functions/saveMutation.ts
47
+ var saveMutation = (txn, finalizedMutation) => {
48
+ txn.engineOpts.mutations.set(finalizedMutation.ref, finalizedMutation);
49
+ return finalizedMutation;
50
+ };
51
+
52
+ // src/functions/commit.ts
53
+ var findAddedAndRemovedEntries = (oldArr, newArr) => {
54
+ const removed = newArr?.filter(([k1, v1]) => !oldArr.some(([k2, v2]) => k1 === k2 && v1 === v2));
55
+ const added = oldArr?.filter(([k1, v1]) => !newArr.some(([k2, v2]) => k1 === k2 && v1 === v2));
56
+ return [added, removed];
40
57
  };
41
- // src/functions/createEntity.ts
42
- import { entityFromRef } from "roc-db";
43
- var createEntity = (txn, ref, {
44
- data = {},
45
- indexedData = {},
46
- children = {},
47
- parents = {},
48
- ancestors = {}
58
+ var commit = (txn, mutation, {
59
+ created,
60
+ updated,
61
+ deleted
49
62
  }) => {
50
- const entity = entityFromRef(ref);
51
- const document = {
52
- ref,
53
- entity,
54
- created: {
55
- timestamp: txn.mutation.timestamp,
56
- mutationRef: txn.mutation.ref
57
- },
58
- updated: {
59
- timestamp: txn.mutation.timestamp,
60
- mutationRef: txn.mutation.ref
61
- },
62
- data: {
63
- ...data,
64
- ...indexedData
65
- },
66
- children,
67
- parents,
68
- ancestors
69
- };
70
- if (txn.request.changeSetRef) {
71
- if (txn.engineOpts.changeSet.entities.has(ref)) {
72
- throw new Error("Entity already exists in changeSet");
63
+ const { mutations } = txn.engineOpts;
64
+ const currentMutation = mutations.get(txn.mutation.ref);
65
+ if (currentMutation) {
66
+ if (currentMutation && mutation.appliedAt === txn.timestamp) {
67
+ saveMutation(txn, mutation);
68
+ } else if (currentMutation && mutation.debounceCount > currentMutation.debounceCount) {
69
+ saveMutation(txn, mutation);
73
70
  } else {
74
- txn.engineOpts.changeSet.entities.set(ref, document);
75
- return document;
71
+ throw new Error("Mutation already exists");
76
72
  }
77
73
  } else {
78
- txn.engineOpts.entities.set(ref, document);
79
- return document;
74
+ saveMutation(txn, mutation);
80
75
  }
81
- };
82
- // src/functions/deleteEntity.ts
83
- import { DELETED_IN_CHANGE_SET_SYMBOL } from "roc-db";
84
- var deleteEntity = (txn, ref) => {
85
- if (txn.request.changeSetRef) {
86
- txn.engineOpts.changeSet.entities.set(ref, DELETED_IN_CHANGE_SET_SYMBOL);
87
- return true;
88
- } else {
89
- txn.engineOpts.entities.delete(ref);
90
- return true;
76
+ if (txn.request.changeSetRef)
77
+ return mutation;
78
+ for (const doc of created) {
79
+ if (doc.__.unique?.length) {
80
+ doc.__.unique.forEach(([key, value]) => {
81
+ const uniqueKey = `${doc.entity}:${key}:${JSON.stringify(value)}`;
82
+ if (txn.engineOpts.entitiesUnique.has(uniqueKey))
83
+ throw createUniqueConstraintConflictError(doc.entity);
84
+ txn.engineOpts.entitiesUnique.set(uniqueKey, doc.ref);
85
+ });
86
+ }
87
+ if (doc.__.index?.length) {
88
+ doc.__.index.forEach(([key, value]) => {
89
+ const indexKey = `${doc.entity}:${key}:${JSON.stringify(value)}`;
90
+ const arr = txn.engineOpts.entitiesIndex.get(indexKey) ?? [];
91
+ txn.engineOpts.entitiesIndex.set(indexKey, [...arr, doc.ref]);
92
+ });
93
+ }
94
+ txn.engineOpts.entities.set(doc.ref, doc);
95
+ }
96
+ for (const updatedDocument of updated) {
97
+ const existingDocument = txn.engineOpts.entities.get(updatedDocument.ref);
98
+ if (updatedDocument.__.unique?.length || existingDocument.__.unique?.length) {
99
+ const { ref, entity } = updatedDocument;
100
+ const [added, removed] = findAddedAndRemovedEntries(updatedDocument.__.unique, existingDocument.__.unique);
101
+ removed.forEach(([key, value]) => {
102
+ const uniqueKey = `${updatedDocument.entity}:${key}:${JSON.stringify(value)}`;
103
+ txn.engineOpts.entitiesUnique.delete(uniqueKey);
104
+ });
105
+ added.forEach(([key, value]) => {
106
+ const uniqueKey = `${updatedDocument.entity}:${key}:${JSON.stringify(value)}`;
107
+ if (txn.engineOpts.entitiesUnique.has(uniqueKey))
108
+ throw createUniqueConstraintConflictError(entity);
109
+ txn.engineOpts.entitiesUnique.set(uniqueKey, ref);
110
+ });
111
+ }
112
+ if (updatedDocument.__.index?.length || existingDocument.__.index?.length) {
113
+ const { ref, entity } = updatedDocument;
114
+ const [added, removed] = findAddedAndRemovedEntries(updatedDocument.__.index, existingDocument.__.index);
115
+ removed.forEach(([key, value]) => {
116
+ const indexKey = `${updatedDocument.entity}:${key}:${JSON.stringify(value)}`;
117
+ const arr = txn.engineOpts.entitiesIndex.get(indexKey);
118
+ txn.engineOpts.entitiesIndex.set(indexKey, arr.filter((ref2) => ref2 !== updatedDocument.ref));
119
+ });
120
+ added.forEach(([key, value]) => {
121
+ const indexKey = `${updatedDocument.entity}:${key}:${JSON.stringify(value)}`;
122
+ const arr = txn.engineOpts.entitiesIndex.get(indexKey) ?? [];
123
+ txn.engineOpts.entitiesIndex.set(indexKey, [
124
+ ...arr,
125
+ updatedDocument.ref
126
+ ]);
127
+ });
128
+ }
129
+ txn.engineOpts.entities.set(updatedDocument.ref, updatedDocument);
130
+ }
131
+ for (const ref of deleted) {
132
+ if (ref.startsWith("Mutation/")) {
133
+ txn.engineOpts.mutations.delete(ref);
134
+ } else {
135
+ const existingDocument = txn.engineOpts.entities.get(ref);
136
+ if (existingDocument.__.unique?.length) {
137
+ existingDocument.__.unique.forEach(([key, value]) => {
138
+ const uniqueKey = `${existingDocument.entity}:${key}:${JSON.stringify(value)}`;
139
+ txn.engineOpts.entitiesUnique.delete(uniqueKey);
140
+ });
141
+ }
142
+ if (existingDocument.__.index?.length) {
143
+ existingDocument.__.index.forEach(([key, value]) => {
144
+ const indexKey = `${existingDocument.entity}:${key}:${JSON.stringify(value)}`;
145
+ const arr = txn.engineOpts.entitiesIndex.get(indexKey) ?? [];
146
+ txn.engineOpts.entitiesIndex.set(indexKey, arr.filter((ref2) => ref2 !== existingDocument.ref));
147
+ });
148
+ }
149
+ txn.engineOpts.entities.delete(ref);
150
+ }
91
151
  }
152
+ return mutation;
153
+ };
154
+ // src/functions/findDebounceMutation.ts
155
+ var findDebounceMutation = (request, engine, now, mutationName) => {
156
+ const debounceTime = request.operation.debounce;
157
+ const thresholdTime = new Date(now - debounceTime * 1000).toISOString();
158
+ const res = engine.mutations.values().find((mutation) => {
159
+ if (mutation.operation.name === mutationName && mutation.timestamp > thresholdTime && mutation.payload.ref === request.payload.ref) {
160
+ return true;
161
+ }
162
+ });
163
+ return res;
92
164
  };
93
165
  // src/functions/getChangeSetMutations.ts
94
166
  var getChangeSetMutations = (txn, changeSetRef) => {
@@ -102,17 +174,33 @@ var getChangeSetMutations = (txn, changeSetRef) => {
102
174
  });
103
175
  return res;
104
176
  };
105
- // src/functions/findDebounceMutation.ts
106
- var findDebounceMutation = (request, engine, now) => {
107
- const debounceTime = request.settings.debounce;
108
- const mutationName = request.schema.shape.name.value;
109
- const thresholdTime = new Date(now - debounceTime * 1000).toISOString();
110
- const res = engine.mutations.values().find((mutation) => {
111
- if (mutation.name === mutationName && mutation.timestamp > thresholdTime && mutation.payload.ref === request.payload.ref) {
112
- return true;
177
+ // src/functions/pageEntities.ts
178
+ var pageEntities = (txn, args) => {
179
+ const { size, entities, childrenOf } = args;
180
+ const result = [];
181
+ for (const [, doc] of txn.engineOpts.entities) {
182
+ if (size && result.length >= size) {
183
+ break;
113
184
  }
114
- });
115
- return res;
185
+ if (entities && entities !== "*" && !entities.includes(doc.entity)) {
186
+ continue;
187
+ } else {
188
+ if (childrenOf && childrenOf.length > 0) {
189
+ if (!childrenOf.some((childRef) => doc.__.parentRefs.includes(childRef))) {
190
+ continue;
191
+ }
192
+ }
193
+ result.push(doc);
194
+ }
195
+ }
196
+ return result;
197
+ };
198
+ // src/functions/pageEntitiesByIndex.ts
199
+ var pageEntitiesByIndex = (txn, entity, field, value) => {
200
+ const { entitiesIndex } = txn.engineOpts;
201
+ const indexKey = `${entity}:${field}:${JSON.stringify(value)}`;
202
+ const refs = entitiesIndex.get(indexKey) ?? [];
203
+ return refs.map((ref) => txn.engineOpts.entities.get(ref));
116
204
  };
117
205
  // src/functions/pageMutations.ts
118
206
  var pageMutations = (txn, {
@@ -135,94 +223,39 @@ var pageMutations = (txn, {
135
223
  }
136
224
  return res;
137
225
  };
138
- // src/functions/patchEntity.ts
139
- import { deepPatch, NotFoundError } from "roc-db";
140
-
141
- // src/functions/readEntity.ts
142
- import { DELETED_IN_CHANGE_SET_SYMBOL as DELETED_IN_CHANGE_SET_SYMBOL2 } from "roc-db";
143
- var readEntity = (txn, ref) => {
144
- if (txn.request.changeSetRef) {
145
- const doc = txn.engineOpts.changeSet.entities.get(ref);
146
- if (doc === DELETED_IN_CHANGE_SET_SYMBOL2)
147
- return;
148
- if (doc)
149
- return doc;
150
- }
151
- return txn.engineOpts.entities.get(ref);
152
- };
153
-
154
- // src/functions/patchEntity.ts
155
- var patchEntity = (txn, ref, { data = {}, children = {}, parents = {}, ancestors = {} }) => {
156
- const existingDocument = readEntity(txn, ref);
157
- if (!existingDocument)
158
- throw new NotFoundError(ref);
159
- const updatedDocument = {
160
- ...existingDocument,
161
- updated: {
162
- timestamp: txn.mutation.timestamp,
163
- mutationRef: txn.mutation.ref
164
- },
165
- data: deepPatch(existingDocument.data, data),
166
- children: deepPatch(existingDocument.children, children),
167
- parents: deepPatch(existingDocument.parents, parents),
168
- ancestors: deepPatch(existingDocument.ancestors, ancestors)
169
- };
170
- if (txn.request.changeSetRef) {
171
- txn.engineOpts.changeSet.entities.set(ref, updatedDocument);
172
- return updatedDocument;
173
- } else {
174
- txn.engineOpts.entities.set(ref, updatedDocument);
175
- return updatedDocument;
176
- }
177
- };
178
226
  // src/functions/readMutation.ts
179
227
  var readMutation = (engineOpts, ref) => {
180
228
  return engineOpts.mutations.get(ref);
181
229
  };
182
- // src/functions/saveMutation.ts
183
- var saveMutation = (txn, finalizedMutation) => {
184
- txn.engineOpts.mutations.set(finalizedMutation.ref, finalizedMutation);
185
- return finalizedMutation;
186
- };
187
- // src/functions/updateEntity.ts
188
- import { NotFoundError as NotFoundError2 } from "roc-db";
189
- var updateEntity = (txn, ref, { data = {}, children = {}, parents = {}, ancestors = {} }) => {
190
- const currentEntity = readEntity(txn, ref);
191
- if (!currentEntity)
192
- throw new NotFoundError2(ref);
193
- const document = {
194
- ...currentEntity,
195
- updated: {
196
- mutationRef: txn.mutation.ref,
197
- timestamp: txn.mutation.timestamp
198
- },
199
- data,
200
- children,
201
- parents,
202
- ancestors
203
- };
204
- if (txn.request.changeSetRef) {
205
- throw new Error("TODO support changeSetRef");
206
- } else {
207
- txn.engineOpts.entities.set(ref, document);
208
- return document;
230
+ // src/functions/refByUniqueField.ts
231
+ var refByUniqueField = (txn, entity, field, fieldIndex, value) => {
232
+ const key = `${entity}:${field}:${JSON.stringify(value)}`;
233
+ const { entitiesUnique } = txn.engineOpts;
234
+ if (entitiesUnique.has(key)) {
235
+ return entitiesUnique.get(key);
209
236
  }
210
237
  };
211
238
  // src/createInMemoryAdapter.ts
212
239
  var createInMemoryAdapter = ({
213
240
  operations,
214
241
  entities,
215
- snowflake = new Snowflake(1, 1)
242
+ snowflake = new Snowflake(1, 1),
243
+ optimistic = true,
244
+ session
216
245
  }) => {
217
246
  return createAdapter({
218
247
  name: "in-memory",
219
248
  operations,
220
249
  entities,
221
250
  functions: exports_functions,
222
- snowflake
251
+ snowflake,
252
+ optimistic,
253
+ session
223
254
  }, {
224
255
  entities: new Map,
225
- mutations: new Map
256
+ mutations: new Map,
257
+ entitiesUnique: new Map,
258
+ entitiesIndex: new Map
226
259
  });
227
260
  };
228
261
  export {
@@ -1,11 +1,13 @@
1
- import { Snowflake, type Adapter, type Operation } from "roc-db";
1
+ import { Snowflake, type Adapter, type Operation, type Session } from "roc-db";
2
2
  import type { z } from "zod";
3
3
  type Entity = z.ZodObject<{
4
4
  entity: z.ZodLiteral<string>;
5
5
  }>;
6
- export declare const createInMemoryAdapter: <const Name extends string, const Operations extends readonly Operation[], const Entities extends readonly Entity[]>({ operations, entities, snowflake, }: {
6
+ export declare const createInMemoryAdapter: <const Name extends string, const Operations extends readonly Operation[], const Entities extends readonly Entity[]>({ operations, entities, snowflake, optimistic, session, }: {
7
7
  operations: Operations;
8
8
  entities: Entities;
9
9
  snowflake?: Snowflake;
10
+ optimistic?: boolean;
11
+ session: Session;
10
12
  }) => Adapter;
11
13
  export {};
@@ -0,0 +1,2 @@
1
+ import type { Ref } from "roc-db";
2
+ export declare const batchReadEntities: (txn: any, refs: Ref[]) => any[];
@@ -0,0 +1,6 @@
1
+ import { type Entity, type Mutation, type Ref, type WriteTransaction } from "roc-db";
2
+ export declare const commit: (txn: WriteTransaction, mutation: Mutation, { created, updated, deleted, }: {
3
+ created: Entity[];
4
+ updated: Entity[];
5
+ deleted: Ref[];
6
+ }) => Mutation;
@@ -1,3 +1,3 @@
1
- import type { WriteOperation } from "roc-db";
1
+ import type { WriteRequest } from "roc-db";
2
2
  import type { InMemoryEngine } from "../types/InMemoryEngine";
3
- export declare const findDebounceMutation: (request: WriteOperation, engine: InMemoryEngine, now: any) => import("roc-db").Mutation | undefined;
3
+ export declare const findDebounceMutation: (request: WriteRequest, engine: InMemoryEngine, now: number, mutationName: string) => import("roc-db").Mutation | undefined;
@@ -1,11 +1,11 @@
1
- export { begin } from "./begin";
2
- export { createEntity } from "./createEntity";
3
- export { deleteEntity } from "./deleteEntity";
4
- export { getChangeSetMutations } from "./getChangeSetMutations";
1
+ export { batchReadEntities } from "./batchReadEntities";
2
+ export { commit } from "./commit";
5
3
  export { findDebounceMutation } from "./findDebounceMutation";
4
+ export { getChangeSetMutations } from "./getChangeSetMutations";
5
+ export { pageEntities } from "./pageEntities";
6
+ export { pageEntitiesByIndex } from "./pageEntitiesByIndex";
6
7
  export { pageMutations } from "./pageMutations";
7
- export { patchEntity } from "./patchEntity";
8
8
  export { readEntity } from "./readEntity";
9
9
  export { readMutation } from "./readMutation";
10
+ export { refByUniqueField } from "./refByUniqueField";
10
11
  export { saveMutation } from "./saveMutation";
11
- export { updateEntity } from "./updateEntity";
@@ -0,0 +1 @@
1
+ export declare const pageEntities: (txn: any, args: any) => any[];
@@ -0,0 +1 @@
1
+ export declare const pageEntitiesByIndex: (txn: any, entity: any, field: any, value: any) => any;
@@ -4,4 +4,4 @@ export declare const pageMutations: (txn: ReadTransaction<any, InMemoryEngine, a
4
4
  size?: number;
5
5
  skip?: number;
6
6
  changeSetRef?: string;
7
- }) => import("roc-db").Mutation[];
7
+ }) => any[];
@@ -1 +1,2 @@
1
- export declare const readEntity: (txn: any, ref: any) => any;
1
+ import type { Ref, Transaction } from "roc-db";
2
+ export declare const readEntity: (txn: Transaction, ref: Ref) => any;
@@ -0,0 +1 @@
1
+ export declare const refByUniqueField: (txn: WriteTransaction, entity: string, field: string, fieldIndex: number, value: any) => any;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@roc-db/in-memory",
3
- "version": "0.2.0-pre.7",
3
+ "version": "0.2.0-pre.71",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -13,8 +13,8 @@
13
13
  ],
14
14
  "sideEffects": false,
15
15
  "peerDependencies": {
16
- "roc-db": "0.2.0-pre.7",
17
- "zod": "3.24.2"
16
+ "roc-db": "0.2.0-pre.71",
17
+ "zod": "^3.0.0"
18
18
  },
19
19
  "keywords": [],
20
20
  "author": "Eigil Sagafos",
@@ -1 +0,0 @@
1
- export declare const begin: (request: any, engineOpts: any, callback: any) => any;
@@ -1,24 +0,0 @@
1
- import { type Ref } from "roc-db";
2
- import type { InMemoryWriteTransaction } from "../types/InMemoryWriteTransaction";
3
- export declare const createEntity: (txn: InMemoryWriteTransaction, ref: Ref, { data, indexedData, children, parents, ancestors, }: {
4
- data?: {} | undefined;
5
- indexedData?: {} | undefined;
6
- children?: {} | undefined;
7
- parents?: {} | undefined;
8
- ancestors?: {} | undefined;
9
- }) => {
10
- ref: `${string}/${string}`;
11
- entity: string;
12
- created: {
13
- timestamp: any;
14
- mutationRef: any;
15
- };
16
- updated: {
17
- timestamp: any;
18
- mutationRef: any;
19
- };
20
- data: {};
21
- children: {};
22
- parents: {};
23
- ancestors: {};
24
- };
@@ -1 +0,0 @@
1
- export declare const deleteEntity: (txn: any, ref: any) => boolean;
@@ -1,6 +0,0 @@
1
- export declare const patchEntity: (txn: any, ref: any, { data, children, parents, ancestors }: {
2
- data?: {} | undefined;
3
- children?: {} | undefined;
4
- parents?: {} | undefined;
5
- ancestors?: {} | undefined;
6
- }) => any;
@@ -1,6 +0,0 @@
1
- export declare const updateEntity: (txn: any, ref: any, { data, children, parents, ancestors }: {
2
- data?: {} | undefined;
3
- children?: {} | undefined;
4
- parents?: {} | undefined;
5
- ancestors?: {} | undefined;
6
- }) => any;