@n-dream/builders-sdk 1.0.0-next.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,276 @@
1
+ // The storage of the data engine in memory: the local mode of the SDK
2
+ // (8.4) and the tests of the data service. It keeps the rules of
3
+ // Firestore that the engine needs: a commit time per write (in
4
+ // microseconds, always later than the last one), reads that see every
5
+ // commit up to their read time, all-or-nothing transactions, and the
6
+ // order of mixed sort values. As in Firestore, SERVER_TIME stores a time
7
+ // to the millisecond that can be a little earlier than the commit (here 1
8
+ // ms, as the emulator), and a listener gets the doc's update time in
9
+ // microseconds.
10
+ import { compareSort } from "./rules.js";
11
+ import { DELETE_FIELD, SERVER_TIME, TIME_FIELDS } from "./engine.js";
12
+ const copy = (v) => (v === null || v === undefined ? v : structuredClone(v));
13
+ function split(path) {
14
+ const p = path.split("/");
15
+ if (p.length !== 4 || p[0] !== "spaces" || !p[1] || !p[2] || !p[3])
16
+ throw new Error(`Not a storage path: ${path}`);
17
+ return [p[1], p[2], p[3]];
18
+ }
19
+ export class MemoryStorage {
20
+ clock;
21
+ // spaces -> sub-collection -> doc id -> data
22
+ spaces = new Map();
23
+ listeners = new Map();
24
+ // The update time of each doc (microseconds), as Firestore keeps it.
25
+ updated = new Map();
26
+ last = 0;
27
+ lock = Promise.resolve();
28
+ // Called after each commit with its writes (the local mode sends them to
29
+ // the other tabs).
30
+ onCommit = null;
31
+ constructor(clock = () => Date.now() * 1000) {
32
+ this.clock = clock;
33
+ }
34
+ // The time of the next commit: never the same as or before the last.
35
+ tick() {
36
+ this.last = Math.max(this.last + 1, Math.floor(this.clock()));
37
+ return this.last;
38
+ }
39
+ get readUs() {
40
+ return this.last;
41
+ }
42
+ sub(space, name, make = false) {
43
+ let s = this.spaces.get(space);
44
+ if (!s && make)
45
+ this.spaces.set(space, (s = new Map()));
46
+ let c = s?.get(name);
47
+ if (s && !c && make)
48
+ s.set(name, (c = new Map()));
49
+ return c;
50
+ }
51
+ read(path) {
52
+ const [space, name, id] = split(path);
53
+ return copy(this.sub(space, name)?.get(id) ?? null);
54
+ }
55
+ // Applies writes at one commit time.
56
+ commit(writes) {
57
+ const t = this.tick();
58
+ const applied = [];
59
+ for (const w of writes) {
60
+ const [space, name, id] = split(w.path);
61
+ const c = this.sub(space, name, true);
62
+ if (w.data === null) {
63
+ c.delete(id);
64
+ this.updated.delete(w.path);
65
+ applied.push({ path: w.path, data: null });
66
+ continue;
67
+ }
68
+ const data = w.merge ? { ...(c.get(id) ?? {}) } : {};
69
+ for (const [k, v] of Object.entries(w.data)) {
70
+ if (v === DELETE_FIELD)
71
+ delete data[k];
72
+ else
73
+ data[k] = v === SERVER_TIME ? serverTimeOf(t) : copy(v);
74
+ }
75
+ c.set(id, data);
76
+ this.updated.set(w.path, t);
77
+ applied.push({ path: w.path, data: copy(data) });
78
+ }
79
+ this.notify(applied);
80
+ this.onCommit?.(applied);
81
+ return t;
82
+ }
83
+ // Writes of another tab, with their own commit times.
84
+ apply(writes) {
85
+ for (const w of writes) {
86
+ const [space, name, id] = split(w.path);
87
+ const c = this.sub(space, name, true);
88
+ if (w.data === null) {
89
+ c.delete(id);
90
+ this.updated.delete(w.path);
91
+ }
92
+ else {
93
+ c.set(id, copy(w.data));
94
+ let at = 0;
95
+ for (const f of TIME_FIELDS)
96
+ if (typeof w.data[f] === "number")
97
+ at = Math.max(at, w.data[f]);
98
+ this.last = Math.max(this.last + 1, at);
99
+ this.updated.set(w.path, this.last);
100
+ }
101
+ }
102
+ this.notify(writes);
103
+ }
104
+ // All data, for a new tab (8.4).
105
+ dump() {
106
+ const out = [];
107
+ for (const [space, subs] of this.spaces)
108
+ for (const [name, docs] of subs)
109
+ for (const [id, data] of docs)
110
+ out.push({ path: `spaces/${space}/${name}/${id}`, data: copy(data) });
111
+ return out;
112
+ }
113
+ clear() {
114
+ this.spaces.clear();
115
+ this.updated.clear();
116
+ }
117
+ notify(writes) {
118
+ for (const w of writes) {
119
+ const ls = this.listeners.get(w.path);
120
+ if (!ls)
121
+ continue;
122
+ const m = w.data ? this.markerOf(w.path, w.data) : null;
123
+ for (const l of [...ls])
124
+ queueMicrotask(() => l(m));
125
+ }
126
+ }
127
+ async transaction(fn) {
128
+ const run = async () => {
129
+ const writes = [];
130
+ const tx = {
131
+ get: async (path) => {
132
+ if (writes.length)
133
+ throw new Error("A transaction reads before it writes.");
134
+ return this.read(path);
135
+ },
136
+ // A shallow copy keeps SERVER_TIME (the engine gives new objects).
137
+ set: (path, data, opts) => void writes.push({ path, data: { ...data }, merge: !!opts?.merge }),
138
+ delete: (path) => void writes.push({ path, data: null }),
139
+ };
140
+ const value = await fn(tx);
141
+ if (writes.length)
142
+ this.commit(writes);
143
+ return value;
144
+ };
145
+ const p = this.lock.then(run, run);
146
+ this.lock = p.catch(() => { });
147
+ return p;
148
+ }
149
+ async get(path) {
150
+ return this.read(path);
151
+ }
152
+ docs(space) {
153
+ return [...(this.sub(space, "docs")?.entries() ?? [])];
154
+ }
155
+ async query(space, q) {
156
+ const dir = q.direction === "asc" ? 1 : -1;
157
+ const rows = this.docs(space)
158
+ .filter(([, d]) => matches(d, q) && d[q.order] !== undefined)
159
+ .sort(([ia, a], [ib, b]) => dir * (compareSort(a[q.order], b[q.order]) || (ia < ib ? -1 : ia > ib ? 1 : 0)))
160
+ .filter(([id, d]) => !q.after || dir * (compareSort(d[q.order], q.after[0]) || (id < q.after[1] ? -1 : id > q.after[1] ? 1 : 0)) > 0)
161
+ .slice(0, q.limit)
162
+ .map(([id, data]) => ({ id, data: copy(data) }));
163
+ return { rows, readUs: this.last };
164
+ }
165
+ async count(space, q, max) {
166
+ return Math.min(max, this.docs(space).filter(([, d]) => matches(d, q)).length);
167
+ }
168
+ async changes(space, ns, scope, sinceUs, limit) {
169
+ const rows = this.docs(space)
170
+ .filter(([, d]) => d.ns === ns && d.scope === scope && d.updatedAt > sinceUs)
171
+ .sort(([, a], [, b]) => a.updatedAt - b.updatedAt)
172
+ .slice(0, limit)
173
+ .map(([id, data]) => ({ id, data: copy(data) }));
174
+ const removed = [...(this.sub(space, "removed")?.entries() ?? [])]
175
+ .filter(([, d]) => d.scope === scope && d.at > sinceUs)
176
+ .sort(([, a], [, b]) => a.at - b.at)
177
+ .map(([id, data]) => ({ id, data: copy(data) }));
178
+ return { rows, removed, readUs: this.last };
179
+ }
180
+ async setMarker(path, removed) {
181
+ return this.commit([{ path, data: removed ? { at: SERVER_TIME, removedAt: SERVER_TIME, resetAt: DELETE_FIELD } : { at: SERVER_TIME, resetAt: DELETE_FIELD }, merge: true }]);
182
+ }
183
+ async docsByPrefix(space, prefix, after, limit, sub = "docs") {
184
+ return [...(this.sub(space, sub)?.entries() ?? [])]
185
+ .filter(([id]) => id.startsWith(prefix) && (after === null || id > after))
186
+ .sort(([a], [b]) => (a < b ? -1 : 1))
187
+ .slice(0, limit)
188
+ .map(([id, data]) => ({ id, data: copy(data) }));
189
+ }
190
+ async countByPrefix(space, prefix, max, sub = "docs") {
191
+ return Math.min(max, [...(this.sub(space, sub)?.keys() ?? [])].filter((id) => id.startsWith(prefix)).length);
192
+ }
193
+ async docsOfUser(space, uid, after, limit, sub = "docs") {
194
+ const field = sub === "docs" ? "createdBy" : "owner";
195
+ return [...(this.sub(space, sub)?.entries() ?? [])]
196
+ .filter(([id, d]) => d[field] === uid && (after === null || id > after))
197
+ .sort(([a], [b]) => (a < b ? -1 : 1))
198
+ .slice(0, limit)
199
+ .map(([id, data]) => ({ id, data: copy(data) }));
200
+ }
201
+ async listSub(space, sub, after, limit) {
202
+ return [...(this.sub(space, sub)?.entries() ?? [])]
203
+ .filter(([id]) => after === null || id > after)
204
+ .sort(([a], [b]) => (a < b ? -1 : 1))
205
+ .slice(0, limit)
206
+ .map(([id, data]) => ({ id, data: copy(data) }));
207
+ }
208
+ // Deletes the docs of some sub-collections of a space at one commit time.
209
+ dropSubs(space, names) {
210
+ const subs = this.spaces.get(space);
211
+ if (!subs)
212
+ return;
213
+ const writes = [];
214
+ for (const [name, docs] of subs) {
215
+ if (!names(name))
216
+ continue;
217
+ for (const id of [...docs.keys()]) {
218
+ writes.push({ path: `spaces/${space}/${name}/${id}`, data: null });
219
+ docs.delete(id);
220
+ }
221
+ }
222
+ if (!writes.length)
223
+ return;
224
+ for (const w of writes)
225
+ this.updated.delete(w.path);
226
+ this.tick();
227
+ this.notify(writes);
228
+ this.onCommit?.(writes);
229
+ }
230
+ async resetSpace(space) {
231
+ const marks = [...(this.sub(space, "marks")?.keys() ?? [])];
232
+ this.dropSubs(space, (name) => name === "removed" || name === "colls");
233
+ if (marks.length)
234
+ this.commit(marks.map((id) => ({ path: `spaces/${space}/marks/${id}`, data: { at: SERVER_TIME, resetAt: SERVER_TIME } })));
235
+ }
236
+ async purgeSpace(space) {
237
+ this.dropSubs(space, () => true);
238
+ this.spaces.delete(space);
239
+ }
240
+ // The update time of a doc in microseconds (0: no doc).
241
+ updateUs(path) {
242
+ return this.updated.get(path) ?? 0;
243
+ }
244
+ // A marker as a listener sees it: atUs is the update time of the doc.
245
+ markerOf(path, d) {
246
+ return { atUs: this.updated.get(path) ?? null, data: copy(d) };
247
+ }
248
+ // A listener on one marker doc (as a Firestore listener, 9.4): the value
249
+ // at once, then at each change.
250
+ listen(path, onValue, _onError) {
251
+ let set = this.listeners.get(path);
252
+ if (!set)
253
+ this.listeners.set(path, (set = new Set()));
254
+ set.add(onValue);
255
+ const now = this.read(path);
256
+ const m = now ? this.markerOf(path, now) : null;
257
+ queueMicrotask(() => onValue(m));
258
+ return () => {
259
+ set.delete(onValue);
260
+ if (set.size === 0)
261
+ this.listeners.delete(path);
262
+ };
263
+ }
264
+ // Any marker write (the long-poll test routes of LD-a).
265
+ async writeMarker(path, data) {
266
+ return this.commit([{ path, data: { ...data, at: SERVER_TIME } }]);
267
+ }
268
+ async removeDoc(path) {
269
+ this.commit([{ path, data: null }]);
270
+ }
271
+ }
272
+ function matches(d, q) {
273
+ return d.ns === q.ns && d.scope === q.scope && (q.owner === undefined || d.owner === q.owner) && (q.f1 === undefined || d.f1 === q.f1) && (q.f2 === undefined || d.f2 === q.f2);
274
+ }
275
+ // The stored server time of a commit at t (microseconds).
276
+ const serverTimeOf = (t) => Math.floor(t / 1000) * 1000 - 1000;
@@ -0,0 +1,219 @@
1
+ export type RuleCode = "sign-in-required" | "not-allowed" | "not-declared" | "not-supported" | "too-large" | "quota" | "rate-limit" | "conflict" | "preparing" | "invalid" | "user-changed";
2
+ export interface RuleError {
3
+ code: RuleCode;
4
+ status: number;
5
+ message: string;
6
+ }
7
+ export declare function ruleError(code: RuleCode, message: string, status?: number): RuleError;
8
+ export declare function isRuleError(v: unknown): v is RuleError;
9
+ export declare const MESSAGES: {
10
+ readonly notDeclared: (c: string) => string;
11
+ readonly noDeclaration: () => string;
12
+ readonly onlyPresets: () => string;
13
+ readonly mineSignIn: (c: string) => string;
14
+ readonly publicAddSignIn: (c: string) => string;
15
+ readonly publicChangeSignIn: (c: string) => string;
16
+ readonly publicReadSignIn: (c: string) => string;
17
+ readonly notOwn: (c: string) => string;
18
+ readonly dotInId: () => string;
19
+ readonly badId: () => string;
20
+ readonly noItem: (c: string, id: string) => string;
21
+ readonly notFilter: (c: string, f: string, access: Preset) => string;
22
+ readonly range: (f: string) => string;
23
+ readonly notSort: (c: string, f: string, access: Preset) => string;
24
+ readonly mineOnlyPublic: (c: string) => string;
25
+ readonly mineNoWhere: () => string;
26
+ readonly mineSignIn2: (c: string) => string;
27
+ readonly queryKeys: (call: string, keys: string) => string;
28
+ readonly limit: (max: number) => string;
29
+ readonly direction: () => string;
30
+ readonly badCursor: () => string;
31
+ readonly filterValue: (f: string) => string;
32
+ readonly dataObject: () => string;
33
+ readonly notJson: () => string;
34
+ readonly tooDeep: (n: number) => string;
35
+ readonly tooLarge: (kb: number) => string;
36
+ readonly userFull: () => string;
37
+ readonly appFull: () => string;
38
+ readonly appBusy: () => string;
39
+ readonly rate: () => string;
40
+ readonly conflict: (c: string) => string;
41
+ readonly ifRev: () => string;
42
+ readonly preparing: () => string;
43
+ readonly readOnly: () => string;
44
+ readonly userChanged: () => string;
45
+ readonly collectionName: () => string;
46
+ readonly fileSetNotDeclared: (s: string) => string;
47
+ readonly fileSignIn: (s: string) => string;
48
+ readonly fileSetName: () => string;
49
+ readonly fileType: () => string;
50
+ readonly fileContent: (type: string) => string;
51
+ readonly fileTooLarge: (mb: number) => string;
52
+ readonly fileName: () => string;
53
+ readonly fileId: () => string;
54
+ readonly fileNone: () => string;
55
+ readonly fileGone: () => string;
56
+ readonly fileUserFull: () => string;
57
+ readonly fileNotBlob: () => string;
58
+ readonly fileLength: () => string;
59
+ readonly fileDownloads: () => string;
60
+ readonly userDownloads: () => string;
61
+ readonly userUploads: () => string;
62
+ };
63
+ export declare const NOT_SUPPORTED: Record<string, string>;
64
+ export declare const USER_HEADER = "x-builders-user";
65
+ export declare const NO_USER = "-";
66
+ export declare function userGuard(claimed: string | null | undefined, sessionUid: string | null): RuleError | null;
67
+ export interface DataLimits {
68
+ itemBytes: number;
69
+ depth: number;
70
+ collections: number;
71
+ filterFields: number;
72
+ fileSets: number;
73
+ mineItemsPerUser: number;
74
+ mineBytesPerUser: number;
75
+ publicItemsPerUser: number;
76
+ publicBytesPerUser: number;
77
+ mineBytesPerApp: number;
78
+ publicItemsPerApp: number;
79
+ publicBytesPerApp: number;
80
+ pointsPerMinute: number;
81
+ requestsPerAppPerSecond: number;
82
+ readsPerAppPerMonth: number;
83
+ writesPerAppPerMonth: number;
84
+ waitsPerUser: number;
85
+ waitsPerApp: number;
86
+ fileBytes: number;
87
+ filesPerUser: number;
88
+ fileBytesPerUser: number;
89
+ fileBytesPerApp: number;
90
+ fileBytesPerOwner: number;
91
+ downloadBytesPerAppPerMonth: number;
92
+ downloadBytesPerUserPerDay: number;
93
+ uploadBytesPerUserPerDay: number;
94
+ }
95
+ export declare const DATA_LIMITS: Readonly<DataLimits>;
96
+ export declare function spaceLimits(space: "live" | "test", base?: Readonly<DataLimits>): DataLimits;
97
+ export declare const DATA_LIMIT_OVERRIDES: ReadonlyArray<keyof DataLimits>;
98
+ export declare function appDataLimits(overrides: Readonly<Record<string, number>> | null | undefined, base?: Readonly<DataLimits>): DataLimits;
99
+ export declare const LIST_MAX = 100;
100
+ export declare const LIST_DEFAULT = 50;
101
+ export declare const COUNT_MAX = 10000;
102
+ export declare const WATCH_LISTS_MAX = 10;
103
+ export declare const CHANGES_MAX = 200;
104
+ export declare const CURSOR_MAX_AGE_MS: number;
105
+ export declare const SLOT_BYTES_MAX = 1400;
106
+ export declare const DECLARATION_FILE = "builders.data.json";
107
+ export declare const DECLARATION_SCHEMA = "https://builders.n-dream.com/schema/data-v1.json";
108
+ export declare const PRESETS: readonly ["mine", "public"];
109
+ export type Preset = (typeof PRESETS)[number];
110
+ export type Ns = "m" | "p";
111
+ export declare const NS_OF: Readonly<Record<Preset, Ns>>;
112
+ export interface CollectionRule {
113
+ access: Preset;
114
+ filter: string[];
115
+ sort: string | null;
116
+ }
117
+ export interface DataDeclaration {
118
+ schemaVersion: 1;
119
+ collections: Record<string, CollectionRule>;
120
+ files: Record<string, "mine">;
121
+ }
122
+ export declare function isCollectionName(v: unknown): v is string;
123
+ export declare function parseDeclaration(raw: unknown, limits?: Pick<DataLimits, "collections" | "filterFields" | "fileSets">): {
124
+ ok: true;
125
+ value: DataDeclaration;
126
+ } | {
127
+ ok: false;
128
+ problems: string[];
129
+ };
130
+ export declare function ruleOf(decl: DataDeclaration | null, coll: string): CollectionRule | RuleError;
131
+ export declare function declarationText(decl: DataDeclaration | null): string[];
132
+ export declare function declarationChanges(before: DataDeclaration | null, after: DataDeclaration | null): {
133
+ warnings: string[];
134
+ publicChanged: string[];
135
+ };
136
+ export declare const ITEM_ID: RegExp;
137
+ export declare const USER_ID: RegExp;
138
+ export interface ItemRef {
139
+ owner: string | null;
140
+ id: string;
141
+ }
142
+ export declare function itemRef(access: Preset, raw: unknown, viewer: string | null): ItemRef | RuleError;
143
+ export declare function scopeOf(access: Preset, coll: string, owner: string): string;
144
+ export declare function docIdOf(access: Preset, coll: string, owner: string, id: string): string;
145
+ export declare function isDocId(v: unknown): v is string;
146
+ export declare function publicIdOf(access: Preset, docId: string): string;
147
+ export type LoginMode = "anyone" | "domains" | "emails";
148
+ export type Access = "read" | "add" | "change" | "remove";
149
+ export interface Viewer {
150
+ uid: string;
151
+ developer: boolean;
152
+ }
153
+ export declare function accessError(coll: string, rule: CollectionRule, op: Access, viewer: Viewer | null, loginMode: LoginMode, owner?: string | null): RuleError | null;
154
+ export declare function checkData(data: unknown, limits?: Pick<DataLimits, "itemBytes" | "depth">): {
155
+ text: string;
156
+ size: number;
157
+ value: Record<string, unknown>;
158
+ } | RuleError;
159
+ export declare function slotOf(field: string, v: unknown): string | null;
160
+ export declare function cutUtf8(s: string, max: number): string;
161
+ export interface Slots {
162
+ f1?: string;
163
+ f2?: string;
164
+ s?: number | string;
165
+ }
166
+ export declare function slotsOf(rule: CollectionRule, value: Record<string, unknown>): Slots;
167
+ export declare function compareSort(a: unknown, b: unknown): number;
168
+ export type Order = "createdAt" | "updatedAt" | "s";
169
+ export interface PlannedQuery {
170
+ where: {
171
+ f1?: string;
172
+ f2?: string;
173
+ };
174
+ order: Order;
175
+ direction: "asc" | "desc";
176
+ limit: number;
177
+ after: [number | string, string] | null;
178
+ mine: boolean;
179
+ usesSlots: boolean;
180
+ }
181
+ export declare function encodeCursor(value: number | string, docId: string): string;
182
+ export declare function decodeCursor(raw: unknown): [number | string, string] | null;
183
+ export declare function planQuery(coll: string, rule: CollectionRule, raw: unknown, call: "list" | "count" | "watch"): PlannedQuery | RuleError;
184
+ export interface ItemOut<T = unknown> {
185
+ id: string;
186
+ data: T;
187
+ createdAt: string;
188
+ updatedAt: string;
189
+ createdBy: string;
190
+ mine: boolean;
191
+ rev: number;
192
+ }
193
+ export declare function isoOfUs(us: number): string;
194
+ export type FileKind = "image" | "audio" | "video" | "pdf";
195
+ export declare const FILE_TYPES: Readonly<Record<string, {
196
+ kind: FileKind;
197
+ ext: string;
198
+ label: string;
199
+ }>>;
200
+ export declare const FILE_HEAD_BYTES = 64;
201
+ export declare function fileTypeOf(raw: unknown): string | null;
202
+ export declare function sniffFileTypes(b: Uint8Array): string[];
203
+ export declare function checkFileType(declared: string, head: Uint8Array): string | RuleError;
204
+ export declare function fileSetOf(decl: DataDeclaration | null, set: string): RuleError | null;
205
+ export declare const FILE_ID: RegExp;
206
+ export declare function fileIdOf(nowMs: number, random: string): string;
207
+ export declare function fileDocIdOf(set: string, uid: string, id: string): string;
208
+ export declare function fileObjectOf(appId: string, space: "live" | "test", uid: string, id: string): string;
209
+ export declare function fileUrlOf(set: string, id: string): string;
210
+ export declare function checkFileName(raw: unknown): string | RuleError;
211
+ export declare function downloadNameOf(name: string, type: string): string;
212
+ export interface FileOut {
213
+ id: string;
214
+ name: string;
215
+ type: string;
216
+ size: number;
217
+ createdAt: string;
218
+ url: string;
219
+ }