@roc-db/in-memory 0.2.0-pre.6 → 0.2.0-pre.60

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) => {
33
- return {
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);
91
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
+ }
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,110 +174,88 @@ 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;
184
+ }
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);
113
194
  }
114
- });
115
- return res;
116
- };
117
- // src/functions/pageMutations.ts
118
- var pageMutations = (txn, { size = 30, skip = 0 } = {}) => {
119
- return txn.engineOpts.mutations.values().drop(skip).take(size).toArray();
120
- };
121
- // src/functions/patchEntity.ts
122
- import { deepPatch, NotFoundError } from "roc-db";
123
-
124
- // src/functions/readEntity.ts
125
- import { DELETED_IN_CHANGE_SET_SYMBOL as DELETED_IN_CHANGE_SET_SYMBOL2 } from "roc-db";
126
- var readEntity = (txn, ref) => {
127
- if (txn.request.changeSetRef) {
128
- const doc = txn.engineOpts.changeSet.entities.get(ref);
129
- if (doc === DELETED_IN_CHANGE_SET_SYMBOL2)
130
- return;
131
- if (doc)
132
- return doc;
133
195
  }
134
- return txn.engineOpts.entities.get(ref);
196
+ return result;
135
197
  };
136
-
137
- // src/functions/patchEntity.ts
138
- var patchEntity = (txn, ref, { data = {}, children = {}, parents = {}, ancestors = {} }) => {
139
- const existingDocument = readEntity(txn, ref);
140
- if (!existingDocument)
141
- throw new NotFoundError(ref);
142
- const updatedDocument = {
143
- ...existingDocument,
144
- updated: {
145
- timestamp: txn.mutation.timestamp,
146
- mutationRef: txn.mutation.ref
147
- },
148
- data: deepPatch(existingDocument.data, data),
149
- children: deepPatch(existingDocument.children, children),
150
- parents: deepPatch(existingDocument.parents, parents),
151
- ancestors: deepPatch(existingDocument.ancestors, ancestors)
152
- };
153
- if (txn.request.changeSetRef) {
154
- txn.engineOpts.changeSet.entities.set(ref, updatedDocument);
155
- return updatedDocument;
156
- } else {
157
- txn.engineOpts.entities.set(ref, updatedDocument);
158
- return updatedDocument;
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));
204
+ };
205
+ // src/functions/pageMutations.ts
206
+ var pageMutations = (txn, {
207
+ size = 30,
208
+ skip = 0,
209
+ changeSetRef
210
+ } = {}) => {
211
+ const res = [];
212
+ const iterator = txn.engineOpts.mutations.values().drop(skip);
213
+ let next = iterator.next();
214
+ while (!next.done && res.length < size) {
215
+ if (changeSetRef) {
216
+ if (next.value.changeSetRef === changeSetRef) {
217
+ res.push(next.value);
218
+ }
219
+ } else {
220
+ res.push(next.value);
221
+ }
222
+ next = iterator.next();
159
223
  }
224
+ return res;
160
225
  };
161
226
  // src/functions/readMutation.ts
162
227
  var readMutation = (engineOpts, ref) => {
163
228
  return engineOpts.mutations.get(ref);
164
229
  };
165
- // src/functions/saveMutation.ts
166
- var saveMutation = (txn, finalizedMutation) => {
167
- txn.engineOpts.mutations.set(finalizedMutation.ref, finalizedMutation);
168
- return finalizedMutation;
169
- };
170
- // src/functions/updateEntity.ts
171
- import { NotFoundError as NotFoundError2 } from "roc-db";
172
- var updateEntity = (txn, ref, { data = {}, children = {}, parents = {}, ancestors = {} }) => {
173
- const currentEntity = readEntity(txn, ref);
174
- if (!currentEntity)
175
- throw new NotFoundError2(ref);
176
- const document = {
177
- ...currentEntity,
178
- updated: {
179
- mutationRef: txn.mutation.ref,
180
- timestamp: txn.mutation.timestamp
181
- },
182
- data,
183
- children,
184
- parents,
185
- ancestors
186
- };
187
- if (txn.request.changeSetRef) {
188
- throw new Error("TODO support changeSetRef");
189
- } else {
190
- txn.engineOpts.entities.set(ref, document);
191
- 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);
192
236
  }
193
237
  };
194
238
  // src/createInMemoryAdapter.ts
195
239
  var createInMemoryAdapter = ({
196
240
  operations,
197
241
  entities,
198
- snowflake = new Snowflake(1, 1)
242
+ snowflake = new Snowflake(1, 1),
243
+ optimistic = true,
244
+ session
199
245
  }) => {
200
246
  return createAdapter({
201
247
  name: "in-memory",
202
248
  operations,
203
249
  entities,
204
250
  functions: exports_functions,
205
- snowflake
251
+ snowflake,
252
+ optimistic,
253
+ session
206
254
  }, {
207
255
  entities: new Map,
208
- mutations: new Map
256
+ mutations: new Map,
257
+ entitiesUnique: new Map,
258
+ entitiesIndex: new Map
209
259
  });
210
260
  };
211
261
  export {
@@ -0,0 +1,13 @@
1
+ import { Snowflake, type Adapter, type Operation, type Session } from "roc-db";
2
+ import type { z } from "zod";
3
+ type Entity = z.ZodObject<{
4
+ entity: z.ZodLiteral<string>;
5
+ }>;
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
+ operations: Operations;
8
+ entities: Entities;
9
+ snowflake?: Snowflake;
10
+ optimistic?: boolean;
11
+ session: Session;
12
+ }) => Adapter;
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;
@@ -0,0 +1,3 @@
1
+ import type { WriteRequest } from "roc-db";
2
+ import type { InMemoryEngine } from "../types/InMemoryEngine";
3
+ export declare const findDebounceMutation: (request: WriteRequest, engine: InMemoryEngine, now: number, mutationName: string) => import("roc-db").Mutation | undefined;
@@ -0,0 +1 @@
1
+ export declare const getChangeSetMutations: (txn: any, changeSetRef: any) => any[];
@@ -0,0 +1,11 @@
1
+ export { batchReadEntities } from "./batchReadEntities";
2
+ export { commit } from "./commit";
3
+ export { findDebounceMutation } from "./findDebounceMutation";
4
+ export { getChangeSetMutations } from "./getChangeSetMutations";
5
+ export { pageEntities } from "./pageEntities";
6
+ export { pageEntitiesByIndex } from "./pageEntitiesByIndex";
7
+ export { pageMutations } from "./pageMutations";
8
+ export { readEntity } from "./readEntity";
9
+ export { readMutation } from "./readMutation";
10
+ export { refByUniqueField } from "./refByUniqueField";
11
+ export { saveMutation } from "./saveMutation";
@@ -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;
@@ -0,0 +1,7 @@
1
+ import type { ReadTransaction } from "roc-db";
2
+ import type { InMemoryEngine } from "../types/InMemoryEngine";
3
+ export declare const pageMutations: (txn: ReadTransaction<any, InMemoryEngine, any, any>, { size, skip, changeSetRef, }?: {
4
+ size?: number;
5
+ skip?: number;
6
+ changeSetRef?: string;
7
+ }) => any[];
@@ -0,0 +1,2 @@
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 readMutation: (engineOpts: any, ref: any) => any;
@@ -0,0 +1 @@
1
+ export declare const refByUniqueField: (txn: WriteTransaction, entity: string, field: string, fieldIndex: number, value: any) => any;
@@ -0,0 +1,2 @@
1
+ import type { InMemoryWriteTransaction } from "../types/InMemoryWriteTransaction";
2
+ export declare const saveMutation: (txn: InMemoryWriteTransaction, finalizedMutation: any) => any;
@@ -0,0 +1 @@
1
+ export { createInMemoryAdapter } from "./createInMemoryAdapter";
@@ -0,0 +1,5 @@
1
+ import type { Entity, Ref, Mutation } from "roc-db";
2
+ export type InMemoryEngine = {
3
+ entities: Map<Ref, Entity>;
4
+ mutations: Map<Ref, Mutation>;
5
+ };
@@ -0,0 +1,3 @@
1
+ import type { WriteTransaction } from "roc-db";
2
+ import type { InMemoryEngine } from "./InMemoryEngine";
3
+ export type InMemoryWriteTransaction = WriteTransaction<any, InMemoryEngine, 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.6",
3
+ "version": "0.2.0-pre.60",
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.6",
17
- "zod": "3.24.2"
16
+ "roc-db": "0.2.0-pre.60",
17
+ "zod": "^3.0.0"
18
18
  },
19
19
  "keywords": [],
20
20
  "author": "Eigil Sagafos",