@verdant-web/common 2.3.0-next.0 → 2.3.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.
Files changed (40) hide show
  1. package/dist/esm/EventSubscriber.d.ts +18 -0
  2. package/dist/esm/baseline.d.ts +5 -0
  3. package/dist/esm/batching.d.ts +43 -0
  4. package/dist/esm/error.d.ts +22 -0
  5. package/dist/esm/files.d.ts +20 -0
  6. package/dist/esm/index.d.ts +21 -0
  7. package/dist/esm/indexes.d.ts +17 -0
  8. package/dist/esm/indexes.test.d.ts +1 -0
  9. package/dist/esm/memo.d.ts +6 -0
  10. package/dist/esm/memo.test.d.ts +1 -0
  11. package/dist/esm/migration.d.ts +174 -0
  12. package/dist/esm/oids.d.ts +101 -0
  13. package/dist/esm/oids.test.d.ts +1 -0
  14. package/dist/esm/operation.d.ts +142 -0
  15. package/dist/esm/operation.test.d.ts +1 -0
  16. package/dist/esm/patch.d.ts +28 -0
  17. package/dist/esm/presence.d.ts +29 -0
  18. package/dist/esm/protocol.d.ts +145 -0
  19. package/dist/esm/refs.d.ts +7 -0
  20. package/dist/esm/replica.d.ts +28 -0
  21. package/dist/esm/schema/children.d.ts +2 -0
  22. package/dist/esm/schema/defaults.test.d.ts +1 -0
  23. package/dist/esm/schema/fieldHelpers.d.ts +35 -0
  24. package/dist/esm/schema/fields.d.ts +10 -0
  25. package/dist/esm/schema/index.d.ts +54 -0
  26. package/dist/esm/schema/indexFilters.d.ts +6 -0
  27. package/dist/esm/schema/types/collection.d.ts +23 -0
  28. package/dist/esm/schema/types/compounds.d.ts +11 -0
  29. package/dist/esm/schema/types/fields.d.ts +55 -0
  30. package/dist/esm/schema/types/filters.d.ts +29 -0
  31. package/dist/esm/schema/types/shapes.d.ts +25 -0
  32. package/dist/esm/schema/types/synthetics.d.ts +37 -0
  33. package/dist/esm/schema/types.d.ts +18 -0
  34. package/dist/esm/schema/validation.d.ts +14 -0
  35. package/dist/esm/timestamp.d.ts +51 -0
  36. package/dist/esm/timestamp.test.d.ts +1 -0
  37. package/dist/esm/undo.d.ts +3 -0
  38. package/dist/esm/utils.d.ts +20 -0
  39. package/dist/esm/utils.test.d.ts +1 -0
  40. package/package.json +1 -1
@@ -0,0 +1,18 @@
1
+ export declare class EventSubscriber<Events extends {
2
+ [key: string]: (...args: any[]) => void;
3
+ }> {
4
+ private _onAllUnsubscribed?;
5
+ protected subscribers: Record<string, Record<string, (...args: any[]) => void>>;
6
+ protected counts: Record<string, number>;
7
+ private _disabled;
8
+ protected disposed: boolean;
9
+ constructor(_onAllUnsubscribed?: ((event: keyof Events) => void) | undefined);
10
+ get disabled(): boolean;
11
+ subscriberCount: (event: Extract<keyof Events, string>) => number;
12
+ totalSubscriberCount: () => number;
13
+ subscribe: <K extends Extract<keyof Events, string>>(event: K, callback: Events[K]) => () => void;
14
+ emit: <K extends Extract<keyof Events, string>>(event: K, ...args: Parameters<Events[K]>) => void;
15
+ dispose: () => void;
16
+ disable: () => void;
17
+ }
18
+ export type EventsOf<T extends EventSubscriber<any>> = T extends EventSubscriber<infer E> ? keyof E : never;
@@ -0,0 +1,5 @@
1
+ export type DocumentBaseline<T extends any = any> = {
2
+ oid: string;
3
+ snapshot: T;
4
+ timestamp: string;
5
+ };
@@ -0,0 +1,43 @@
1
+ /// <reference types="node" resolution-mode="require"/>
2
+ export declare class Batcher<T, UserData = any> {
3
+ private flusher;
4
+ private batches;
5
+ constructor(flusher: (items: T[], batchKey: string, userData: UserData) => any);
6
+ add({ key, userData, items, max, timeout, }: {
7
+ key: string;
8
+ userData?: UserData;
9
+ items: T[];
10
+ max?: number | null;
11
+ timeout?: number | null;
12
+ }): Batch<T, UserData>;
13
+ flush: (key: string) => any;
14
+ discard: (key: string) => void;
15
+ flushAll: () => any[];
16
+ getSize: (key: string) => number;
17
+ }
18
+ export declare class Batch<T, UserData = any> {
19
+ items: Array<T>;
20
+ max: number | null;
21
+ startedAt: number;
22
+ timeout: number | null;
23
+ flushTimeout?: NodeJS.Timeout;
24
+ userData?: any;
25
+ flusher: (items: T[], batchKey: string, userData: UserData) => any;
26
+ key: string;
27
+ constructor({ max, startedAt, timeout, userData, flusher, key, }: {
28
+ key: string;
29
+ max: number | null;
30
+ startedAt: number;
31
+ timeout: number | null;
32
+ userData?: UserData;
33
+ flusher: (items: T[], batchKey: string, userData: UserData) => any;
34
+ });
35
+ update: ({ items, max, timeout, userData, }: {
36
+ items: Array<T>;
37
+ max?: number | null | undefined;
38
+ timeout?: number | null | undefined;
39
+ userData?: UserData | undefined;
40
+ }) => void;
41
+ flush: () => any;
42
+ discard: () => void;
43
+ }
@@ -0,0 +1,22 @@
1
+ export declare enum VerdantErrorCode {
2
+ InvalidRequest = 4000,
3
+ BodyRequired = 4001,
4
+ NoToken = 4010,
5
+ InvalidToken = 4011,
6
+ TokenExpired = 4012,
7
+ Forbidden = 4030,
8
+ NotFound = 4040,
9
+ Unexpected = 5000,
10
+ ConfigurationError = 5010,
11
+ NoFileStorage = 5011
12
+ }
13
+ export declare class VerdantError extends Error {
14
+ code: VerdantErrorCode;
15
+ static Code: typeof VerdantErrorCode;
16
+ constructor(code: VerdantErrorCode, cause?: Error | undefined, message?: string);
17
+ get httpStatus(): number;
18
+ toResponse: () => string;
19
+ }
20
+ export declare function isVerdantErrorResponse(body: any): body is {
21
+ code: number;
22
+ };
@@ -0,0 +1,20 @@
1
+ /// <reference types="node" resolution-mode="require"/>
2
+ export type FileRef = {
3
+ '@@type': 'file';
4
+ id: string;
5
+ };
6
+ export declare function isFileRef(value: any): value is FileRef;
7
+ export declare function createFileRef(id: string): FileRef;
8
+ export type FileData = {
9
+ id: string;
10
+ /**
11
+ * For locally created files, this starts false, until it's uploaded
12
+ * Remote files this is always true
13
+ */
14
+ remote: boolean;
15
+ name: string;
16
+ type: string;
17
+ file?: Blob;
18
+ url?: string;
19
+ };
20
+ export declare function getAllFileFields(snapshot: any): [string, FileRef][];
@@ -0,0 +1,21 @@
1
+ export * from './protocol.js';
2
+ export * from './timestamp.js';
3
+ export * from './operation.js';
4
+ export * from './baseline.js';
5
+ export * from './replica.js';
6
+ export * from './schema/index.js';
7
+ export * from './utils.js';
8
+ export * from './indexes.js';
9
+ export { migrate, migrationRange, createDefaultMigration, createMigration, } from './migration.js';
10
+ export type { Migration, MigrationIndexDescription, MigrationEngine, } from './migration.js';
11
+ export type { UserInfo } from './presence.js';
12
+ export * from './patch.js';
13
+ export * from './oids.js';
14
+ export * from './EventSubscriber.js';
15
+ export * from './undo.js';
16
+ export * from './batching.js';
17
+ export * from './files.js';
18
+ export type { Ref } from './refs.js';
19
+ export { makeObjectRef, makeFileRef, isRef, compareRefs } from './refs.js';
20
+ export * from './memo.js';
21
+ export * from './error.js';
@@ -0,0 +1,17 @@
1
+ import { StorageCollectionSchema, StorageDirectSyntheticSchema } from './index.js';
2
+ export declare const COMPOUND_INDEX_SEPARATOR = "\uFFFFFE";
3
+ export declare const COMPOUND_INDEX_LOWER_BOUND_SEPARATOR = "\0";
4
+ export declare const COMPOUND_INDEX_UPPER_BOUND_SEPARATOR = "\uFFFFFF";
5
+ type IndexableFieldValue = string | number | boolean | any[];
6
+ export type CompoundIndexValue = string | string[];
7
+ export declare function createCompoundIndexValue(...fields: IndexableFieldValue[]): CompoundIndexValue;
8
+ export declare function createUpperBoundIndexValue(...fields: IndexableFieldValue[]): string;
9
+ export declare function createLowerBoundIndexValue(...fields: IndexableFieldValue[]): string;
10
+ export declare function isDirectSynthetic(index: any): index is StorageDirectSyntheticSchema<any>;
11
+ export declare function computeSynthetics(schema: StorageCollectionSchema, obj: any): Record<string, any>;
12
+ export declare function computeCompoundIndices(schema: StorageCollectionSchema<any, any, any>, doc: any): any;
13
+ export declare function getIndexValues(schema: StorageCollectionSchema<any, any, any>, doc: any): any;
14
+ export declare function assignIndexValues(schema: StorageCollectionSchema<any, any, any>, doc: any): any;
15
+ export declare const NULL_INDEX_VALUE = "null";
16
+ export declare function sanitizeIndexValue(value: unknown): string | number | (string | number)[];
17
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Memoizes the last invocation of a function with the same memo keys.
3
+ * As long as key identity and set doesn't change, the last computed
4
+ * value will be returned.
5
+ */
6
+ export declare function memoByKeys<TRet, TKeys extends any[]>(fn: (...args: unknown[]) => TRet, getKeys: () => TKeys): (...args: unknown[]) => TRet;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,174 @@
1
+ import { StorageCollectionSchema, StorageSchema, StorageDocument, CollectionFilter, StorageDocumentInit } from './index.js';
2
+ /**@deprecated */
3
+ export interface DroppedCollectionMigrationStrategy<Old extends StorageCollectionSchema<any, any, any>> {
4
+ (old: Old): void | Promise<void>;
5
+ }
6
+ /**@deprecated */
7
+ export interface PreservedCollectionMigrationStrategy<Old extends StorageCollectionSchema<any, any, any>, New extends StorageCollectionSchema<any, any, any>> {
8
+ (old: StorageDocument<Old>): StorageDocument<New> | Promise<StorageDocument<New>>;
9
+ }
10
+ /** @deprecated */
11
+ export type MigrationsKeyedOnCollection<Old extends StorageSchema<any>, New extends StorageSchema<any>> = PreservedCollectionMigrations<Old, New> | DroppedCollectionMigrations<Old, New>;
12
+ /**@deprecated */
13
+ type NotInSchema<Name extends string | number | symbol, Schema extends StorageSchema<any>> = Name extends keyof Schema['collections'] ? never : Name;
14
+ /** @deprecated */
15
+ type InSchema<Name extends string | number | symbol, Schema extends StorageSchema<any>> = Name extends keyof Schema['collections'] ? Name : never;
16
+ /** @deprecated */
17
+ type DroppedCollections<Old extends StorageSchema<any>, New extends StorageSchema<any>> = {
18
+ [Key in keyof Old['collections'] as NotInSchema<Key, New>]: StorageCollectionSchema<any, any, any>;
19
+ };
20
+ /** @deprecated */
21
+ type PreservedCollections<Old extends StorageSchema<any>, New extends StorageSchema<any>> = {
22
+ [Key in keyof Old['collections'] as InSchema<Key, New>]: StorageCollectionSchema<any, any, any>;
23
+ };
24
+ /** @deprecated */
25
+ type DroppedCollectionMigrations<Old extends StorageSchema<any>, New extends StorageSchema<any>> = {
26
+ [Key in keyof DroppedCollections<Old, New>]: DroppedCollectionMigrationStrategy<Old['collections'][Key]>;
27
+ };
28
+ /** @deprecated */
29
+ type PreservedCollectionMigrations<Old extends StorageSchema<any>, New extends StorageSchema<any>> = {
30
+ [Key in keyof PreservedCollections<Old, New>]: PreservedCollectionMigrationStrategy<Old['collections'][Key], New['collections'][Key]>;
31
+ };
32
+ /** @deprecated */
33
+ type StrategyFor<Key extends string, Old extends StorageSchema<any>, New extends StorageSchema<any>> = Key extends keyof New['collections'] ? PreservedCollectionMigrationStrategy<Old['collections'][Key], New['collections'][Key]> : DroppedCollectionMigrationStrategy<Old['collections'][Key]>;
34
+ /** @deprecated */
35
+ type DeprecatedMigrationRunner<Old extends StorageSchema<any>, New extends StorageSchema<any>> = <Collection extends Extract<keyof Old['collections'], string>>(collection: Collection, strategy: StrategyFor<Collection, Old, New>) => Promise<void>;
36
+ /** @deprecated */
37
+ type DeprecatedMigrationQueryMaker<Collection extends StorageCollectionSchema<any, any, any>> = {
38
+ get(primaryKey: string): Promise<StorageDocument<Collection> | undefined>;
39
+ findOne(query: CollectionFilter): Promise<StorageDocument<Collection> | undefined>;
40
+ findAll(query?: CollectionFilter): Promise<StorageDocument<Collection>[]>;
41
+ };
42
+ /** @deprecated */
43
+ type DeprecatedMigrationQueries<Old extends StorageSchema<any>> = {
44
+ [Key in keyof Old['collections']]: DeprecatedMigrationQueryMaker<Old['collections'][Key]>;
45
+ };
46
+ /** @deprecated */
47
+ type DeprecatedMigrationMutations<New extends StorageSchema> = {
48
+ [Key in keyof New['collections']]: {
49
+ put(document: StorageDocumentInit<New['collections'][Key]>): Promise<StorageDocument<New['collections'][Key]>>;
50
+ delete(primaryKey: string): Promise<void>;
51
+ };
52
+ };
53
+ /** @deprecated */
54
+ export interface DeprecatedMigrationTools<Old extends StorageSchema<any>, New extends StorageSchema<any>> {
55
+ migrate: DeprecatedMigrationRunner<Old, New>;
56
+ identity: <T>(val: T) => T;
57
+ /**
58
+ * @deprecated - default field values are automatically
59
+ * applied during migration, you don't need to use this.
60
+ * Please remove it from your migrations - even old ones
61
+ * (old migrations can be updated!)
62
+ */
63
+ withDefaults: (collectionName: string, value: any) => any;
64
+ queries: DeprecatedMigrationQueries<Old>;
65
+ mutations: DeprecatedMigrationMutations<New>;
66
+ info: {
67
+ changedCollections: keyof Old['collections'][];
68
+ addedCollections: keyof New['collections'][];
69
+ removedCollections: keyof Old['collections'][];
70
+ };
71
+ }
72
+ export interface MigrationEngine {
73
+ migrate: (collection: string, strategy: (val: any) => any) => Promise<void>;
74
+ queries: MigrationQueries<any>;
75
+ mutations: MigrationMutations<any>;
76
+ /** OIDs of any new documents created during the migration */
77
+ newOids: string[];
78
+ /** Promises that should be resolved before completing the migration */
79
+ awaitables: Promise<any>[];
80
+ /** Deletes all documents in a collection - used for removed collections */
81
+ deleteCollection: (collection: string) => Promise<void>;
82
+ log: (...messages: any[]) => void;
83
+ }
84
+ /** @deprecated */
85
+ type DeprecatedMigrationProcedure<Old extends StorageSchema, New extends StorageSchema> = (tools: DeprecatedMigrationTools<Old, New>) => Promise<void>;
86
+ type EmptySchema = {
87
+ version: 0;
88
+ collections: {};
89
+ };
90
+ /** @deprecated - use createMigration */
91
+ export declare function migrate<Schema extends StorageSchema>(schema: Schema, procedure: DeprecatedMigrationProcedure<EmptySchema, Schema>): Migration<EmptySchema, Schema>;
92
+ /** @deprecated = use createMigration */
93
+ export declare function migrate<Old extends StorageSchema, New extends StorageSchema>(oldSchema: Old, newSchema: New, procedure: DeprecatedMigrationProcedure<Old, New>): Migration<Old, New>;
94
+ export interface MigrationIndexDescription {
95
+ name: string;
96
+ multiEntry: boolean;
97
+ synthetic: boolean;
98
+ compound: boolean;
99
+ }
100
+ export interface Migration<Old extends StorageSchema = any, New extends StorageSchema = any> {
101
+ version: number;
102
+ oldSchema: Old;
103
+ newSchema: New;
104
+ migrate: (engine: MigrationEngine) => Promise<void>;
105
+ /** Collections which are added in the new schema and not present in the old */
106
+ addedCollections: string[];
107
+ /** Collections which were removed from the old schema */
108
+ removedCollections: string[];
109
+ /** All collections which exist after the migration has completed - i.e. the ones in the new schema */
110
+ allCollections: string[];
111
+ /** Only the collections which were in the old schema */
112
+ oldCollections: string[];
113
+ /** Collections whose fields or indexes changed between schemas */
114
+ changedCollections: string[];
115
+ addedIndexes: Record<string, MigrationIndexDescription[]>;
116
+ removedIndexes: Record<string, MigrationIndexDescription[]>;
117
+ }
118
+ export declare function migrationRange(from: number, to: number): number[];
119
+ /** @deprecated - use createMigration with no procedure function */
120
+ export declare function createDefaultMigration(schema: StorageSchema): Migration<{
121
+ version: 0;
122
+ collections: {};
123
+ }>;
124
+ /** @deprecated - use createMigration with no procedure function */
125
+ export declare function createDefaultMigration<Old extends StorageSchema>(oldSchema: Old, newSchema: StorageSchema): Migration<Old>;
126
+ /** New, simpler type-safety migration tools */
127
+ type DocumentShape<Init = any, Snapshot = any> = {
128
+ init: Init;
129
+ snapshot: Snapshot;
130
+ };
131
+ type SchemaDocuments = Record<string, DocumentShape>;
132
+ type CollectionProcedure<OldSnapshot, NewInit> = {
133
+ (old: OldSnapshot): NewInit | Promise<NewInit>;
134
+ };
135
+ type MigrationQueries<Old extends SchemaDocuments> = {
136
+ [Key in keyof Old]: {
137
+ get(primaryKey: string): Promise<Old[Key]['snapshot'] | undefined>;
138
+ findOne(query: CollectionFilter): Promise<Old[Key]['snapshot'] | undefined>;
139
+ findAll(query?: CollectionFilter): Promise<Old[Key]['snapshot'][]>;
140
+ };
141
+ };
142
+ type MigrationMutations<New extends SchemaDocuments> = {
143
+ [Key in keyof New]: {
144
+ put(document: New[Key]['init']): Promise<New[Key]['snapshot']>;
145
+ delete(primaryKey: string): Promise<void>;
146
+ };
147
+ };
148
+ type MigrationTools<Old extends SchemaDocuments, New extends SchemaDocuments> = {
149
+ /**
150
+ * Process a change in a collection's documents by taking in each existing
151
+ * document and returning its new shape. This is typed so you can be
152
+ * confident the proper transformations are made.
153
+ */
154
+ migrate: <Collection extends keyof Old & keyof New>(collection: Collection, strategy: CollectionProcedure<Old[Collection]['snapshot'], New[Collection]['init']>) => Promise<void>;
155
+ mutations: MigrationMutations<New>;
156
+ queries: MigrationQueries<Old>;
157
+ info: {
158
+ changedCollections: (keyof Old & keyof New)[];
159
+ addedCollections: (keyof New)[];
160
+ removedCollections: (keyof Old)[];
161
+ };
162
+ };
163
+ type MigrationProcedure<Old extends SchemaDocuments, New extends SchemaDocuments> = {
164
+ (tools: MigrationTools<Old, New>): Promise<void>;
165
+ };
166
+ type InitialMigrationTools<New extends SchemaDocuments> = {
167
+ mutations: MigrationMutations<New>;
168
+ };
169
+ type InitialMigrationProcedure<New extends SchemaDocuments> = {
170
+ (tools: InitialMigrationTools<New>): Promise<void>;
171
+ };
172
+ export declare function createMigration<New extends SchemaDocuments>(newSchema: StorageSchema, procedure?: InitialMigrationProcedure<New>): any;
173
+ export declare function createMigration<Old extends SchemaDocuments, New extends SchemaDocuments>(oldSchema: StorageSchema, newSchema: StorageSchema, procedure?: MigrationProcedure<Old, New>): any;
174
+ export {};
@@ -0,0 +1,101 @@
1
+ import { ObjectRef } from './operation.js';
2
+ /**
3
+ * OIDs
4
+ *
5
+ * OIDs are used to identify objects in the document. They also encode
6
+ * information about the object useful to identifying an object found
7
+ * on its own and associating it back to its parent.
8
+ *
9
+ * An OID is structured as such:
10
+ * <collection>/<root id>[/<key paths>]:<random>
11
+ *
12
+ * OIDs have a few characteristics:
13
+ * - They include the collection name of the parent document
14
+ * - They include the primary key of the parent document
15
+ * - They include the key path of the object within the document
16
+ * - They include a random sequence to identify different objects which
17
+ * exist at the same key path
18
+ *
19
+ * Collection name and document key are used to link any isolated
20
+ * object back to its parent document.
21
+ *
22
+ * The key path is used for authorization - to associate the object
23
+ * (or an operation related to it by OID) with the field it inhabits
24
+ * to utilize authorization rules from that field in the schema.
25
+ *
26
+ * The random sequence allows the application to encode different
27
+ * identities for objects at the same position in a document for
28
+ * conflict resolution purposes
29
+ */
30
+ export type ObjectIdentifier = string;
31
+ export declare const LEGACY_OID_KEY = "__@@oid_do_not_use";
32
+ export declare const OID_KEY = "@@id";
33
+ export declare function getOid(obj: any): string;
34
+ export declare function maybeGetOid(obj: any): ObjectIdentifier | undefined;
35
+ export declare function assignOid(obj: any, oid: ObjectIdentifier): any;
36
+ export declare function hasOid(obj: any): boolean;
37
+ export declare function removeOid(obj: any): any;
38
+ export declare function isOidKey(key: string): boolean;
39
+ /**
40
+ * For sub-objects, assign a random sub-OID if no OID
41
+ * is already assigned.
42
+ */
43
+ export declare function ensureOid(obj: any, rootOid: ObjectIdentifier, createSubId?: () => string): string;
44
+ export declare function ensureCompatibleOid(obj: any, rootOid: ObjectIdentifier, createSubId?: () => string): string;
45
+ export declare function createOid(collection: string, documentId: string, subId?: string): string;
46
+ export declare function createSubOid(root: ObjectIdentifier, createSubId?: () => string): string;
47
+ export declare function decomposeOid(oid: ObjectIdentifier): {
48
+ collection: string;
49
+ id: string;
50
+ subId?: string;
51
+ };
52
+ export declare function assertAllLevelsHaveOids(obj: any, root?: any): void;
53
+ export declare function assignOidsToAllSubObjects(obj: any, createSubId?: () => string): void;
54
+ export declare function assignOidProperty(obj: any, oid: ObjectIdentifier): any;
55
+ export declare function maybeGetOidProperty(obj: any): any;
56
+ /**
57
+ * Assigns a special property to all objects in the given object
58
+ * which have an OID
59
+ */
60
+ export declare function assignOidPropertiesToAllSubObjects(obj: any): void;
61
+ /**
62
+ *
63
+ * Removes the special property from all objects in the given object
64
+ * which have an OID, transferring the OID from the property to the OID
65
+ * system in-memory.
66
+ */
67
+ export declare function removeOidPropertiesFromAllSubObjects(obj: any): void;
68
+ export declare function removeOidsFromAllSubObjects(obj: any): void;
69
+ export declare function createOidSubId(): string;
70
+ export declare function createRef(oid: ObjectIdentifier): ObjectRef;
71
+ export declare function normalize(obj: any, refs?: Map<ObjectIdentifier, any>): Map<ObjectIdentifier, any>;
72
+ /**
73
+ * Only normalizes direct children. The created map
74
+ * of objects will still have nested objects.
75
+ */
76
+ export declare function normalizeFirstLevel(obj: any): {
77
+ refs: Map<string, any>;
78
+ oidKeyPairs: Map<string, string | number>;
79
+ };
80
+ export declare function getOidRoot(oid: ObjectIdentifier): string;
81
+ /**
82
+ * Returns an inclusive range of OIDs that represent
83
+ * all of an OID's possible sub-objects.
84
+ */
85
+ export declare function getOidSubIdRange(oid: ObjectIdentifier): string[];
86
+ export declare function getLegacyDotOidSubIdRange(oid: ObjectIdentifier): string[];
87
+ export declare function getRoots(oids: ObjectIdentifier[]): string[];
88
+ export declare function areOidsRelated(oidA: ObjectIdentifier, oidB: ObjectIdentifier): boolean;
89
+ /**
90
+ * Recursively rewrites any OIDs in an object which are 'foreign' -
91
+ * i.e. relate to some other object/entity - to be local to the
92
+ * current object. This is deterministic, so it can be done
93
+ * on multiple clients independently with predictable results.
94
+ */
95
+ export declare function fixForeignOids(obj: any): void;
96
+ export declare function isLegacyDotOid(oid: ObjectIdentifier): boolean;
97
+ export declare function convertLegacyOid(oid: ObjectIdentifier): string;
98
+ export declare const MATCH_LEGACY_OID_JSON_STRING: RegExp;
99
+ export declare function replaceLegacyOidsInJsonString(string: string): string;
100
+ export declare function replaceLegacyOidsInObject(obj: any): any;
101
+ export declare function isRootOid(oid: ObjectIdentifier): boolean;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,142 @@
1
+ import { DocumentBaseline } from './baseline.js';
2
+ import { FileRef } from './files.js';
3
+ import { ObjectIdentifier } from './oids.js';
4
+ export type ObjectRef = {
5
+ '@@type': 'ref';
6
+ id: ObjectIdentifier;
7
+ };
8
+ export declare function isObjectRef(obj: any): obj is ObjectRef;
9
+ export type Normalized<T> = {
10
+ [key in keyof T]: T[key] extends Object ? ObjectRef : T[key];
11
+ };
12
+ export type PropertyName = string | number;
13
+ /**
14
+ * List patches can target a particular child list or
15
+ * nested lists. The first path item is the property path
16
+ * of the first child list, any subsequent values are nested
17
+ * list indices.
18
+ */
19
+ export type PropertyValue = string | number | boolean | null | undefined | ObjectRef | FileRef;
20
+ interface BaseOperationPatch {
21
+ }
22
+ export interface OperationPatchInitialize extends BaseOperationPatch {
23
+ op: 'initialize';
24
+ value: any;
25
+ }
26
+ export interface OperationPatchSet extends BaseOperationPatch {
27
+ op: 'set';
28
+ name: PropertyName;
29
+ value: PropertyValue;
30
+ }
31
+ export interface OperationPatchRemove extends BaseOperationPatch {
32
+ op: 'remove';
33
+ name: PropertyName;
34
+ }
35
+ export interface OperationPatchListPush extends BaseOperationPatch {
36
+ op: 'list-push';
37
+ value: PropertyValue;
38
+ }
39
+ export interface OperationPatchListInsert extends BaseOperationPatch {
40
+ op: 'list-insert';
41
+ index: number;
42
+ value?: PropertyValue;
43
+ values?: PropertyValue[];
44
+ }
45
+ export interface OperationPatchListDelete extends BaseOperationPatch {
46
+ op: 'list-delete';
47
+ index: number;
48
+ count: number;
49
+ }
50
+ /**
51
+ * Optimal for lists of object references. Moves
52
+ * the selected item to the target index even if it
53
+ * is not at the original index anymore.
54
+ */
55
+ export interface OperationPatchListMoveByRef extends BaseOperationPatch {
56
+ op: 'list-move-by-ref';
57
+ value: ObjectRef | FileRef;
58
+ index: number;
59
+ }
60
+ /**
61
+ * Suitable for any list move, whether object lists
62
+ * or primitive lists.
63
+ */
64
+ export interface OperationPatchListMoveByIndex extends BaseOperationPatch {
65
+ op: 'list-move-by-index';
66
+ from: number;
67
+ to: number;
68
+ }
69
+ /**
70
+ * Removes all instances of the value from
71
+ * the list. Good for set behavior or removing
72
+ * a specific item even if it changes index
73
+ * from conflicts.
74
+ */
75
+ export interface OperationPatchListRemove extends BaseOperationPatch {
76
+ op: 'list-remove';
77
+ value: PropertyValue;
78
+ only?: 'first' | 'last';
79
+ }
80
+ export interface OperationPatchListAdd extends BaseOperationPatch {
81
+ op: 'list-add';
82
+ value: PropertyValue;
83
+ }
84
+ export interface OperationPatchDelete extends BaseOperationPatch {
85
+ op: 'delete';
86
+ }
87
+ export interface OperationPatchTouch extends BaseOperationPatch {
88
+ op: 'touch';
89
+ }
90
+ export type OperationPatch = OperationPatchInitialize | OperationPatchSet | OperationPatchRemove | OperationPatchListPush | OperationPatchListInsert | OperationPatchListDelete | OperationPatchListMoveByRef | OperationPatchListMoveByIndex | OperationPatchListRemove | OperationPatchDelete | OperationPatchListAdd | OperationPatchTouch;
91
+ export type Operation = {
92
+ oid: ObjectIdentifier;
93
+ timestamp: string;
94
+ data: OperationPatch;
95
+ };
96
+ export declare function diffToPatches<T extends {
97
+ [key: string]: any;
98
+ } | any[]>(from: T, to: T, getNow: () => string, createSubId?: () => string, patches?: Operation[], options?: {
99
+ /**
100
+ * If an object is merged with another and the new one does not
101
+ * have an OID assigned, assume it is the same identity as previous
102
+ */
103
+ mergeUnknownObjects?: boolean;
104
+ /**
105
+ * If an incoming value is not assigned on the new object, use the previous value.
106
+ * If false, undefined properties will erase the previous value.
107
+ */
108
+ defaultUndefined?: boolean;
109
+ }): Operation[];
110
+ export declare function shallowDiffToPatches(from: any, to: any, getNow: () => string, patches?: Operation[]): Operation[];
111
+ /**
112
+ * Takes a basic object and constructs a patch list to create it and
113
+ * all of its nested objects.
114
+ */
115
+ export declare function initialToPatches(initial: any, rootOid: ObjectIdentifier, getNow: () => string, createSubId?: () => string, patches?: Operation[]): Operation[];
116
+ export declare function shallowInitialToPatches(initial: any, rootOid: ObjectIdentifier, getNow: () => string, patches?: Operation[]): Operation[];
117
+ export declare function groupPatchesByOid(patches: Operation[]): Record<string, Operation[]>;
118
+ export declare function groupPatchesByRootOid(patches: Operation[]): Record<string, Operation[]>;
119
+ export declare function groupBaselinesByRootOid(baselines: DocumentBaseline[]): Record<string, DocumentBaseline[]>;
120
+ export type NormalizedObject = {
121
+ [key: PropertyName]: PropertyValue;
122
+ } | Array<PropertyValue>;
123
+ /**
124
+ * The incoming object should already be normalized!
125
+ * This function will mutate the base object.
126
+ */
127
+ export declare function applyPatch<T extends NormalizedObject>(base: T | undefined, patch: OperationPatch,
128
+ /**
129
+ * Optionally supply a list to which any refs which
130
+ * are removed during the patch will be appended.
131
+ */
132
+ deletedRefs?: (FileRef | ObjectRef)[]): T | undefined;
133
+ export declare function applyOperations<T extends NormalizedObject>(base: T | undefined, operations: Operation[], deletedRefs?: (ObjectRef | FileRef)[]): T | undefined;
134
+ /**
135
+ * Mutates the original object in place. Returns all referenced
136
+ * objects oids.
137
+ */
138
+ export declare function substituteRefsWithObjects(base: any, refs: Map<ObjectIdentifier, any>, used?: ObjectIdentifier[]): ObjectIdentifier[];
139
+ export declare function substituteFirstLevelObjectsWithRefs<Base extends {
140
+ [key: string]: any;
141
+ } | any[]>(base: Base, refObjects?: Map<ObjectIdentifier, any>): Map<ObjectIdentifier, any>;
142
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,28 @@
1
+ /**
2
+ * High-level patch creation for use with complex nested objects.
3
+ */
4
+ import { FileRef } from './files.js';
5
+ import { ObjectIdentifier } from './oids.js';
6
+ import { ObjectRef, Operation, PropertyName } from './operation.js';
7
+ export declare class PatchCreator {
8
+ private getNow;
9
+ private createSubId?;
10
+ constructor(getNow: () => string, createSubId?: (() => string) | undefined);
11
+ isPrimitive: (value: any) => boolean;
12
+ createDiff: (from: any, to: any, options?: {
13
+ mergeUnknownObjects?: boolean;
14
+ defaultUndefined?: boolean;
15
+ }) => Operation[];
16
+ createInitialize: (obj: any, oid: ObjectIdentifier) => Operation[];
17
+ createSet: (oid: ObjectIdentifier, key: PropertyName, value: any) => Operation[];
18
+ createRemove: (oid: ObjectIdentifier, key: PropertyName) => Operation[];
19
+ createListPush: (oid: ObjectIdentifier, value: any) => Operation[];
20
+ createListAdd: (oid: ObjectIdentifier, value: any) => Operation[];
21
+ createListInsert: (oid: ObjectIdentifier, index: number, value: any) => Operation[];
22
+ createListRemove: (oid: ObjectIdentifier, value: any, only?: 'first' | 'last') => Operation[];
23
+ createListDelete: (oid: ObjectIdentifier, index: number, count?: number) => Operation[];
24
+ createListMoveByRef: (oid: ObjectIdentifier, value: ObjectRef | FileRef, index: number) => Operation[];
25
+ createListMoveByIndex: (oid: ObjectIdentifier, fromIndex: number, toIndex: number) => Operation[];
26
+ createDelete: (oid: ObjectIdentifier) => Operation[];
27
+ createDeleteAll: (oids: ObjectIdentifier[]) => Operation[];
28
+ }
@@ -0,0 +1,29 @@
1
+ export interface UserInfo<Profile, Presence> {
2
+ /**
3
+ * @deprecated - include the ID in your Profile data instead.
4
+ *
5
+ * This is the ID representing the user who is utilizing a
6
+ * replica client to connect to the storage network.
7
+ * One user may have multiple replica clients active at once,
8
+ * but their presence will only reflect the most recent
9
+ * replica used.
10
+ */
11
+ id: string;
12
+ /**
13
+ * This is the ID representing the replica client that is
14
+ * connected to the storage network. This is used to
15
+ * identify the client when sending messages to it.
16
+ */
17
+ replicaId: string;
18
+ /**
19
+ * This is the user's server profile. This data is associated
20
+ * with the logged in user of the app and cannot be modified
21
+ * by the local replica directly.
22
+ */
23
+ profile: Profile;
24
+ /**
25
+ * Presence info which can update frequently as a replica
26
+ * makes changes. The shape of presence is up to you.
27
+ */
28
+ presence: Presence;
29
+ }