@fluidframework/shared-object-base 2.0.0-dev.2.3.0.115467 → 2.0.0-dev.4.1.0.148229

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 (75) hide show
  1. package/.eslintrc.js +5 -8
  2. package/.mocharc.js +2 -2
  3. package/README.md +1 -1
  4. package/api-extractor.json +2 -2
  5. package/bench/src/index.ts +37 -33
  6. package/bench/src/util.ts +26 -26
  7. package/dist/handle.d.ts.map +1 -1
  8. package/dist/handle.js.map +1 -1
  9. package/dist/index.d.ts +2 -2
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js.map +1 -1
  12. package/dist/packageVersion.d.ts +1 -1
  13. package/dist/packageVersion.js +1 -1
  14. package/dist/packageVersion.js.map +1 -1
  15. package/dist/remoteObjectHandle.d.ts.map +1 -1
  16. package/dist/remoteObjectHandle.js +16 -8
  17. package/dist/remoteObjectHandle.js.map +1 -1
  18. package/dist/serializer.d.ts.map +1 -1
  19. package/dist/serializer.js +5 -7
  20. package/dist/serializer.js.map +1 -1
  21. package/dist/sharedObject.d.ts +3 -3
  22. package/dist/sharedObject.d.ts.map +1 -1
  23. package/dist/sharedObject.js +26 -9
  24. package/dist/sharedObject.js.map +1 -1
  25. package/dist/summarySerializer.d.ts.map +1 -1
  26. package/dist/summarySerializer.js.map +1 -1
  27. package/dist/types.d.ts.map +1 -1
  28. package/dist/types.js.map +1 -1
  29. package/dist/utils.d.ts.map +1 -1
  30. package/dist/utils.js +1 -3
  31. package/dist/utils.js.map +1 -1
  32. package/dist/valueType.d.ts.map +1 -1
  33. package/dist/valueType.js.map +1 -1
  34. package/lib/handle.d.ts.map +1 -1
  35. package/lib/handle.js.map +1 -1
  36. package/lib/index.d.ts +2 -2
  37. package/lib/index.d.ts.map +1 -1
  38. package/lib/index.js +2 -2
  39. package/lib/index.js.map +1 -1
  40. package/lib/packageVersion.d.ts +1 -1
  41. package/lib/packageVersion.js +1 -1
  42. package/lib/packageVersion.js.map +1 -1
  43. package/lib/remoteObjectHandle.d.ts.map +1 -1
  44. package/lib/remoteObjectHandle.js +17 -9
  45. package/lib/remoteObjectHandle.js.map +1 -1
  46. package/lib/serializer.d.ts.map +1 -1
  47. package/lib/serializer.js +5 -7
  48. package/lib/serializer.js.map +1 -1
  49. package/lib/sharedObject.d.ts +3 -3
  50. package/lib/sharedObject.d.ts.map +1 -1
  51. package/lib/sharedObject.js +26 -9
  52. package/lib/sharedObject.js.map +1 -1
  53. package/lib/summarySerializer.d.ts.map +1 -1
  54. package/lib/summarySerializer.js.map +1 -1
  55. package/lib/types.d.ts.map +1 -1
  56. package/lib/types.js.map +1 -1
  57. package/lib/utils.d.ts.map +1 -1
  58. package/lib/utils.js +1 -3
  59. package/lib/utils.js.map +1 -1
  60. package/lib/valueType.d.ts.map +1 -1
  61. package/lib/valueType.js.map +1 -1
  62. package/package.json +58 -58
  63. package/prettier.config.cjs +1 -1
  64. package/src/handle.ts +28 -28
  65. package/src/index.ts +12 -2
  66. package/src/packageVersion.ts +1 -1
  67. package/src/remoteObjectHandle.ts +70 -55
  68. package/src/serializer.ts +182 -187
  69. package/src/sharedObject.ts +709 -636
  70. package/src/summarySerializer.ts +8 -8
  71. package/src/types.ts +50 -32
  72. package/src/utils.ts +20 -26
  73. package/src/valueType.ts +9 -9
  74. package/tsconfig.esnext.json +6 -6
  75. package/tsconfig.json +8 -12
package/src/handle.ts CHANGED
@@ -19,34 +19,34 @@ import { ISharedObject } from "./types";
19
19
  * '/\<shared object id\>' and loads shared object.
20
20
  */
21
21
  export class SharedObjectHandle extends FluidObjectHandle<ISharedObject> {
22
- /**
23
- * Whether services have been attached for the associated shared object.
24
- */
25
- public get isAttached(): boolean {
26
- return this.value.isAttached();
27
- }
22
+ /**
23
+ * Whether services have been attached for the associated shared object.
24
+ */
25
+ public get isAttached(): boolean {
26
+ return this.value.isAttached();
27
+ }
28
28
 
29
- /**
30
- * Creates a new SharedObjectHandle.
31
- * @param value - The shared object this handle is for.
32
- * @param path - The id of the shared object. It is also the path to this object relative to the routeContext.
33
- * @param routeContext - The parent {@link @fluidframework/core-interfaces#IFluidHandleContext} that has a route
34
- * to this handle.
35
- */
36
- constructor(
37
- protected readonly value: ISharedObject,
38
- path: string,
39
- routeContext: IFluidHandleContext,
40
- ) {
41
- super(value, path, routeContext);
42
- }
29
+ /**
30
+ * Creates a new SharedObjectHandle.
31
+ * @param value - The shared object this handle is for.
32
+ * @param path - The id of the shared object. It is also the path to this object relative to the routeContext.
33
+ * @param routeContext - The parent {@link @fluidframework/core-interfaces#IFluidHandleContext} that has a route
34
+ * to this handle.
35
+ */
36
+ constructor(
37
+ protected readonly value: ISharedObject,
38
+ path: string,
39
+ routeContext: IFluidHandleContext,
40
+ ) {
41
+ super(value, path, routeContext);
42
+ }
43
43
 
44
- /**
45
- * Attaches all bound handles first (which may in turn attach further handles), then attaches this handle.
46
- * When attaching the handle, it registers the associated shared object.
47
- */
48
- public attachGraph(): void {
49
- this.value.bindToContext();
50
- super.attachGraph();
51
- }
44
+ /**
45
+ * Attaches all bound handles first (which may in turn attach further handles), then attaches this handle.
46
+ * When attaching the handle, it registers the associated shared object.
47
+ */
48
+ public attachGraph(): void {
49
+ this.value.bindToContext();
50
+ super.attachGraph();
51
+ }
52
52
  }
package/src/index.ts CHANGED
@@ -3,9 +3,19 @@
3
3
  * Licensed under the MIT License.
4
4
  */
5
5
 
6
- export { FluidSerializer, IFluidSerializer, ISerializedHandle, isSerializedHandle } from "./serializer";
6
+ export {
7
+ FluidSerializer,
8
+ IFluidSerializer,
9
+ ISerializedHandle,
10
+ isSerializedHandle,
11
+ } from "./serializer";
7
12
  export { SharedObject, SharedObjectCore } from "./sharedObject";
8
13
  export { SummarySerializer } from "./summarySerializer";
9
14
  export { ISharedObject, ISharedObjectEvents } from "./types";
10
- export { createSingleBlobSummary, makeHandlesSerializable, parseHandles, serializeHandles } from "./utils";
15
+ export {
16
+ createSingleBlobSummary,
17
+ makeHandlesSerializable,
18
+ parseHandles,
19
+ serializeHandles,
20
+ } from "./utils";
11
21
  export { ValueType } from "./valueType";
@@ -6,4 +6,4 @@
6
6
  */
7
7
 
8
8
  export const pkgName = "@fluidframework/shared-object-base";
9
- export const pkgVersion = "2.0.0-dev.2.3.0.115467";
9
+ export const pkgVersion = "2.0.0-dev.4.1.0.148229";
@@ -6,14 +6,18 @@
6
6
  import { assert } from "@fluidframework/common-utils";
7
7
  import { RuntimeHeaders } from "@fluidframework/container-runtime";
8
8
  import {
9
- IFluidHandle,
10
- IFluidHandleContext,
11
- IRequest,
12
- IResponse,
13
- FluidObject,
14
- IFluidRouter,
9
+ IFluidHandle,
10
+ IFluidHandleContext,
11
+ IRequest,
12
+ IResponse,
13
+ FluidObject,
14
+ IFluidRouter,
15
15
  } from "@fluidframework/core-interfaces";
16
- import { create404Response, exceptionToResponse, responseToException } from "@fluidframework/runtime-utils";
16
+ import {
17
+ create404Response,
18
+ exceptionToResponse,
19
+ responseToException,
20
+ } from "@fluidframework/runtime-utils";
17
21
 
18
22
  /**
19
23
  * This handle is used to dynamically load a Fluid object on a remote client and is created on parsing a serialized
@@ -23,59 +27,70 @@ import { create404Response, exceptionToResponse, responseToException } from "@fl
23
27
  * IFluidHandle can be retrieved by calling `get` on it.
24
28
  */
25
29
  export class RemoteFluidObjectHandle implements IFluidHandle {
26
- public get IFluidRouter() { return this; }
27
- public get IFluidHandleContext() { return this; }
28
- public get IFluidHandle() { return this; }
30
+ public get IFluidRouter() {
31
+ return this;
32
+ }
33
+ public get IFluidHandleContext() {
34
+ return this;
35
+ }
36
+ public get IFluidHandle() {
37
+ return this;
38
+ }
29
39
 
30
- public readonly isAttached = true;
31
- private objectP: Promise<FluidObject> | undefined;
40
+ public readonly isAttached = true;
41
+ private objectP: Promise<FluidObject> | undefined;
32
42
 
33
- /**
34
- * Creates a new RemoteFluidObjectHandle when parsing an IFluidHandle.
35
- * @param absolutePath - The absolute path to the handle from the container runtime.
36
- * @param routeContext - The root IFluidHandleContext that has a route to this handle.
37
- */
38
- constructor(
39
- public readonly absolutePath: string,
40
- public readonly routeContext: IFluidHandleContext,
41
- ) {
42
- assert(absolutePath.startsWith("/"), 0x19d /* "Handles should always have absolute paths" */);
43
- }
43
+ /**
44
+ * Creates a new RemoteFluidObjectHandle when parsing an IFluidHandle.
45
+ * @param absolutePath - The absolute path to the handle from the container runtime.
46
+ * @param routeContext - The root IFluidHandleContext that has a route to this handle.
47
+ */
48
+ constructor(
49
+ public readonly absolutePath: string,
50
+ public readonly routeContext: IFluidHandleContext,
51
+ ) {
52
+ assert(
53
+ absolutePath.startsWith("/"),
54
+ 0x19d /* "Handles should always have absolute paths" */,
55
+ );
56
+ }
44
57
 
45
- public async get(): Promise<any> {
46
- if (this.objectP === undefined) {
47
- // Add `viaHandle` header to distinguish from requests from non-handle paths.
48
- const request: IRequest = { url: this.absolutePath, headers: { [RuntimeHeaders.viaHandle]: true } };
49
- this.objectP = this.routeContext.resolveHandle(request)
50
- .then<FluidObject>((response) => {
51
- if (response.mimeType === "fluid/object") {
52
- const fluidObject: FluidObject = response.value;
53
- return fluidObject;
54
- }
55
- throw responseToException(response, request);
56
- });
57
- }
58
- return this.objectP;
59
- }
58
+ public async get(): Promise<any> {
59
+ if (this.objectP === undefined) {
60
+ // Add `viaHandle` header to distinguish from requests from non-handle paths.
61
+ const request: IRequest = {
62
+ url: this.absolutePath,
63
+ headers: { [RuntimeHeaders.viaHandle]: true },
64
+ };
65
+ this.objectP = this.routeContext
66
+ .resolveHandle(request)
67
+ .then<FluidObject>((response) => {
68
+ if (response.mimeType === "fluid/object") {
69
+ const fluidObject: FluidObject = response.value;
70
+ return fluidObject;
71
+ }
72
+ throw responseToException(response, request);
73
+ });
74
+ }
75
+ return this.objectP;
76
+ }
60
77
 
61
- public attachGraph(): void {
62
- return;
63
- }
78
+ public attachGraph(): void {
79
+ return;
80
+ }
64
81
 
65
- public bind(handle: IFluidHandle): void {
66
- handle.attachGraph();
67
- }
82
+ public bind(handle: IFluidHandle): void {
83
+ handle.attachGraph();
84
+ }
68
85
 
69
- public async request(request: IRequest): Promise<IResponse> {
70
- try {
71
- const object: FluidObject<IFluidRouter> = await this.get();
72
- const router = object.IFluidRouter;
86
+ public async request(request: IRequest): Promise<IResponse> {
87
+ try {
88
+ const object: FluidObject<IFluidRouter> = await this.get();
89
+ const router = object.IFluidRouter;
73
90
 
74
- return router !== undefined
75
- ? router.request(request)
76
- : create404Response(request);
77
- } catch (error) {
78
- return exceptionToResponse(error);
79
- }
80
- }
91
+ return router !== undefined ? router.request(request) : create404Response(request);
92
+ } catch (error) {
93
+ return exceptionToResponse(error);
94
+ }
95
+ }
81
96
  }
package/src/serializer.ts CHANGED
@@ -13,203 +13,198 @@ import { RemoteFluidObjectHandle } from "./remoteObjectHandle";
13
13
  /**
14
14
  * JSON serialized form of an IFluidHandle
15
15
  */
16
- export interface ISerializedHandle {
17
- // Marker to indicate to JSON.parse that the object is a Fluid handle
18
- type: "__fluid_handle__";
16
+ export interface ISerializedHandle {
17
+ // Marker to indicate to JSON.parse that the object is a Fluid handle
18
+ type: "__fluid_handle__";
19
19
 
20
- // URL to the object. Relative URLs are relative to the handle context passed to the stringify.
21
- url: string;
20
+ // URL to the object. Relative URLs are relative to the handle context passed to the stringify.
21
+ url: string;
22
22
  }
23
23
 
24
24
  export const isSerializedHandle = (value: any): value is ISerializedHandle =>
25
- value?.type === "__fluid_handle__";
25
+ value?.type === "__fluid_handle__";
26
26
 
27
27
  export interface IFluidSerializer {
28
- /**
29
- * Given a mostly-plain object that may have handle objects embedded within, will return a fully-plain object
30
- * where any embedded IFluidHandles have been replaced with a serializable form.
31
- *
32
- * The original `input` object is not mutated. This method will shallowly clones all objects in the path from
33
- * the root to any replaced handles. (If no handles are found, returns the original object.)
34
- */
35
- encode(value: any, bind: IFluidHandle): any;
36
-
37
- /**
38
- * Given a fully-jsonable object tree that may have encoded handle objects embedded within, will return an
39
- * equivalent object tree where any encoded IFluidHandles have been replaced with their decoded form.
40
- *
41
- * The original `input` object is not mutated. This method will shallowly clone all objects in the path from
42
- * the root to any replaced handles. (If no handles are found, returns the original object.)
43
- *
44
- * The decoded handles are implicitly bound to the handle context of this serializer.
45
- */
46
- decode(input: any): any;
47
-
48
- /**
49
- * Stringifies a given value. Converts any IFluidHandle to its stringified equivalent.
50
- */
51
- stringify(value: any, bind: IFluidHandle): string;
52
-
53
- /**
54
- * Parses the given JSON input string and returns the JavaScript object defined by it. Any Fluid
55
- * handles will be realized as part of the parse
56
- */
57
- parse(value: string): any;
28
+ /**
29
+ * Given a mostly-plain object that may have handle objects embedded within, will return a fully-plain object
30
+ * where any embedded IFluidHandles have been replaced with a serializable form.
31
+ *
32
+ * The original `input` object is not mutated. This method will shallowly clones all objects in the path from
33
+ * the root to any replaced handles. (If no handles are found, returns the original object.)
34
+ */
35
+ encode(value: any, bind: IFluidHandle): any;
36
+
37
+ /**
38
+ * Given a fully-jsonable object tree that may have encoded handle objects embedded within, will return an
39
+ * equivalent object tree where any encoded IFluidHandles have been replaced with their decoded form.
40
+ *
41
+ * The original `input` object is not mutated. This method will shallowly clone all objects in the path from
42
+ * the root to any replaced handles. (If no handles are found, returns the original object.)
43
+ *
44
+ * The decoded handles are implicitly bound to the handle context of this serializer.
45
+ */
46
+ decode(input: any): any;
47
+
48
+ /**
49
+ * Stringifies a given value. Converts any IFluidHandle to its stringified equivalent.
50
+ */
51
+ stringify(value: any, bind: IFluidHandle): string;
52
+
53
+ /**
54
+ * Parses the given JSON input string and returns the JavaScript object defined by it. Any Fluid
55
+ * handles will be realized as part of the parse
56
+ */
57
+ parse(value: string): any;
58
58
  }
59
59
 
60
60
  /**
61
61
  * Data Store serializer implementation
62
62
  */
63
63
  export class FluidSerializer implements IFluidSerializer {
64
- private readonly root: IFluidHandleContext;
65
-
66
- public constructor(
67
- private readonly context: IFluidHandleContext,
68
- // To be called whenever a handle is parsed by this serializer.
69
- private readonly handleParsedCb: (handle: IFluidHandle) => void,
70
- ) {
71
- this.root = this.context;
72
- while (this.root.routeContext !== undefined) {
73
- this.root = this.root.routeContext;
74
- }
75
- }
76
-
77
- public get IFluidSerializer() { return this; }
78
-
79
- /**
80
- * Given a mostly-jsonable object tree that may have handle objects embedded within, will return a
81
- * fully-jsonable object tree where any embedded IFluidHandles have been replaced with a serializable form.
82
- *
83
- * The original `input` object is not mutated. This method will shallowly clone all objects in the path from
84
- * the root to any replaced handles. (If no handles are found, returns the original object.)
85
- *
86
- * Any unbound handles encountered are bound to the provided IFluidHandle.
87
- */
88
- public encode(
89
- input: any,
90
- bind: IFluidHandle,
91
- ) {
92
- // If the given 'input' cannot contain handles, return it immediately. Otherwise,
93
- // return the result of 'recursivelyReplace()'.
94
- // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
95
- return !!input && typeof input === "object"
96
- ? this.recursivelyReplace(input, this.encodeValue, bind)
97
- : input;
98
- }
99
-
100
- /**
101
- * Given a fully-jsonable object tree that may have encoded handle objects embedded within, will return an
102
- * equivalent object tree where any encoded IFluidHandles have been replaced with their decoded form.
103
- *
104
- * The original `input` object is not mutated. This method will shallowly clone all objects in the path from
105
- * the root to any replaced handles. (If no handles are found, returns the original object.)
106
- *
107
- * The decoded handles are implicitly bound to the handle context of this serializer.
108
- */
109
- public decode(input: any) {
110
- // If the given 'input' cannot contain handles, return it immediately. Otherwise,
111
- // return the result of 'recursivelyReplace()'.
112
- // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
113
- return !!input && typeof input === "object"
114
- ? this.recursivelyReplace(input, this.decodeValue)
115
- : input;
116
- }
117
-
118
- public stringify(input: any, bind: IFluidHandle) {
119
- return JSON.stringify(input, (key, value) => this.encodeValue(value, bind));
120
- }
121
-
122
- // Parses the serialized data - context must match the context with which the JSON was stringified
123
- public parse(input: string) {
124
- return JSON.parse(input, (key, value) => this.decodeValue(value));
125
- }
126
-
127
- // If the given 'value' is an IFluidHandle, returns the encoded IFluidHandle.
128
- // Otherwise returns the original 'value'. Used by 'encode()' and 'stringify()'.
129
- private readonly encodeValue = (value: any, bind: IFluidHandle) => {
130
- // Detect if 'value' is an IFluidHandle.
131
- const handle = value?.IFluidHandle;
132
-
133
- // If 'value' is an IFluidHandle return its encoded form.
134
- return handle !== undefined
135
- ? this.serializeHandle(handle, bind)
136
- : value;
137
- };
138
-
139
- // If the given 'value' is an encoded IFluidHandle, returns the decoded IFluidHandle.
140
- // Otherwise returns the original 'value'. Used by 'decode()' and 'parse()'.
141
- private readonly decodeValue = (value: any) => {
142
- // If 'value' is a serialized IFluidHandle return the deserialized result.
143
- if (isSerializedHandle(value)) {
144
- // Old documents may have handles with relative path in their summaries. Convert these to absolute
145
- // paths. This will ensure that future summaries will have absolute paths for these handles.
146
- const absolutePath = value.url.startsWith("/")
147
- ? value.url
148
- : generateHandleContextPath(value.url, this.context);
149
-
150
- const parsedHandle = new RemoteFluidObjectHandle(absolutePath, this.root);
151
- this.handleParsedCb(parsedHandle);
152
- return parsedHandle;
153
- } else {
154
- return value;
155
- }
156
- };
157
-
158
- // Invoked for non-null objects to recursively replace references to IFluidHandles.
159
- // Clones as-needed to avoid mutating the `input` object. If no IFluidHandes are present,
160
- // returns the original `input`.
161
- private recursivelyReplace(
162
- input: any,
163
- replacer: (input: any, context: any) => any,
164
- context?: any,
165
- ) {
166
- // Note: Caller is responsible for ensuring that `input` is defined / non-null.
167
- // (Required for Object.keys() below.)
168
-
169
- // Execute the `replace` on the current input. Note that Caller is responsible for ensuring that `input`
170
- // is a non-null object.
171
- const maybeReplaced = replacer(input, context);
172
-
173
- // If the replacer made a substitution there is no need to decscend further. IFluidHandles are always
174
- // leaves in the object graph.
175
- if (maybeReplaced !== input) {
176
- return maybeReplaced;
177
- }
178
-
179
- // Otherwise descend into the object graph looking for IFluidHandle instances.
180
- let clone: object | undefined;
181
- for (const key of Object.keys(input)) {
182
- const value = input[key];
183
- // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
184
- if (!!value && typeof value === "object") {
185
- // Note: Except for IFluidHandle, `input` must not contain circular references (as object must
186
- // be JSON serializable.) Therefore, guarding against infinite recursion here would only
187
- // lead to a later error when attempting to stringify().
188
- const replaced = this.recursivelyReplace(value, replacer, context);
189
-
190
- // If the `replaced` object is different than the original `value` then the subgraph contained one
191
- // or more handles. If this happens, we need to return a clone of the `input` object where the
192
- // current property is replaced by the `replaced` value.
193
- if (replaced !== value) {
194
- // Lazily create a shallow clone of the `input` object if we haven't done so already.
195
- clone = clone ?? (Array.isArray(input)
196
- ? [...input]
197
- : { ...input });
198
-
199
- // Overwrite the current property `key` in the clone with the `replaced` value.
200
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
201
- clone![key] = replaced;
202
- }
203
- }
204
- }
205
- return clone ?? input;
206
- }
207
-
208
- protected serializeHandle(handle: IFluidHandle, bind: IFluidHandle) {
209
- bind.bind(handle);
210
- return {
211
- type: "__fluid_handle__",
212
- url: handle.absolutePath,
213
- };
214
- }
64
+ private readonly root: IFluidHandleContext;
65
+
66
+ public constructor(
67
+ private readonly context: IFluidHandleContext,
68
+ // To be called whenever a handle is parsed by this serializer.
69
+ private readonly handleParsedCb: (handle: IFluidHandle) => void,
70
+ ) {
71
+ this.root = this.context;
72
+ while (this.root.routeContext !== undefined) {
73
+ this.root = this.root.routeContext;
74
+ }
75
+ }
76
+
77
+ public get IFluidSerializer() {
78
+ return this;
79
+ }
80
+
81
+ /**
82
+ * Given a mostly-jsonable object tree that may have handle objects embedded within, will return a
83
+ * fully-jsonable object tree where any embedded IFluidHandles have been replaced with a serializable form.
84
+ *
85
+ * The original `input` object is not mutated. This method will shallowly clone all objects in the path from
86
+ * the root to any replaced handles. (If no handles are found, returns the original object.)
87
+ *
88
+ * Any unbound handles encountered are bound to the provided IFluidHandle.
89
+ */
90
+ public encode(input: any, bind: IFluidHandle) {
91
+ // If the given 'input' cannot contain handles, return it immediately. Otherwise,
92
+ // return the result of 'recursivelyReplace()'.
93
+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
94
+ return !!input && typeof input === "object"
95
+ ? this.recursivelyReplace(input, this.encodeValue, bind)
96
+ : input;
97
+ }
98
+
99
+ /**
100
+ * Given a fully-jsonable object tree that may have encoded handle objects embedded within, will return an
101
+ * equivalent object tree where any encoded IFluidHandles have been replaced with their decoded form.
102
+ *
103
+ * The original `input` object is not mutated. This method will shallowly clone all objects in the path from
104
+ * the root to any replaced handles. (If no handles are found, returns the original object.)
105
+ *
106
+ * The decoded handles are implicitly bound to the handle context of this serializer.
107
+ */
108
+ public decode(input: any) {
109
+ // If the given 'input' cannot contain handles, return it immediately. Otherwise,
110
+ // return the result of 'recursivelyReplace()'.
111
+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
112
+ return !!input && typeof input === "object"
113
+ ? this.recursivelyReplace(input, this.decodeValue)
114
+ : input;
115
+ }
116
+
117
+ public stringify(input: any, bind: IFluidHandle) {
118
+ return JSON.stringify(input, (key, value) => this.encodeValue(value, bind));
119
+ }
120
+
121
+ // Parses the serialized data - context must match the context with which the JSON was stringified
122
+ public parse(input: string) {
123
+ return JSON.parse(input, (key, value) => this.decodeValue(value));
124
+ }
125
+
126
+ // If the given 'value' is an IFluidHandle, returns the encoded IFluidHandle.
127
+ // Otherwise returns the original 'value'. Used by 'encode()' and 'stringify()'.
128
+ private readonly encodeValue = (value: any, bind: IFluidHandle) => {
129
+ // Detect if 'value' is an IFluidHandle.
130
+ const handle = value?.IFluidHandle;
131
+
132
+ // If 'value' is an IFluidHandle return its encoded form.
133
+ return handle !== undefined ? this.serializeHandle(handle, bind) : value;
134
+ };
135
+
136
+ // If the given 'value' is an encoded IFluidHandle, returns the decoded IFluidHandle.
137
+ // Otherwise returns the original 'value'. Used by 'decode()' and 'parse()'.
138
+ private readonly decodeValue = (value: any) => {
139
+ // If 'value' is a serialized IFluidHandle return the deserialized result.
140
+ if (isSerializedHandle(value)) {
141
+ // Old documents may have handles with relative path in their summaries. Convert these to absolute
142
+ // paths. This will ensure that future summaries will have absolute paths for these handles.
143
+ const absolutePath = value.url.startsWith("/")
144
+ ? value.url
145
+ : generateHandleContextPath(value.url, this.context);
146
+
147
+ const parsedHandle = new RemoteFluidObjectHandle(absolutePath, this.root);
148
+ this.handleParsedCb(parsedHandle);
149
+ return parsedHandle;
150
+ } else {
151
+ return value;
152
+ }
153
+ };
154
+
155
+ // Invoked for non-null objects to recursively replace references to IFluidHandles.
156
+ // Clones as-needed to avoid mutating the `input` object. If no IFluidHandes are present,
157
+ // returns the original `input`.
158
+ private recursivelyReplace(
159
+ input: any,
160
+ replacer: (input: any, context: any) => any,
161
+ context?: any,
162
+ ) {
163
+ // Note: Caller is responsible for ensuring that `input` is defined / non-null.
164
+ // (Required for Object.keys() below.)
165
+
166
+ // Execute the `replace` on the current input. Note that Caller is responsible for ensuring that `input`
167
+ // is a non-null object.
168
+ const maybeReplaced = replacer(input, context);
169
+
170
+ // If the replacer made a substitution there is no need to decscend further. IFluidHandles are always
171
+ // leaves in the object graph.
172
+ if (maybeReplaced !== input) {
173
+ return maybeReplaced;
174
+ }
175
+
176
+ // Otherwise descend into the object graph looking for IFluidHandle instances.
177
+ let clone: object | undefined;
178
+ for (const key of Object.keys(input)) {
179
+ const value = input[key];
180
+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
181
+ if (!!value && typeof value === "object") {
182
+ // Note: Except for IFluidHandle, `input` must not contain circular references (as object must
183
+ // be JSON serializable.) Therefore, guarding against infinite recursion here would only
184
+ // lead to a later error when attempting to stringify().
185
+ const replaced = this.recursivelyReplace(value, replacer, context);
186
+
187
+ // If the `replaced` object is different than the original `value` then the subgraph contained one
188
+ // or more handles. If this happens, we need to return a clone of the `input` object where the
189
+ // current property is replaced by the `replaced` value.
190
+ if (replaced !== value) {
191
+ // Lazily create a shallow clone of the `input` object if we haven't done so already.
192
+ clone = clone ?? (Array.isArray(input) ? [...input] : { ...input });
193
+
194
+ // Overwrite the current property `key` in the clone with the `replaced` value.
195
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
196
+ clone![key] = replaced;
197
+ }
198
+ }
199
+ }
200
+ return clone ?? input;
201
+ }
202
+
203
+ protected serializeHandle(handle: IFluidHandle, bind: IFluidHandle) {
204
+ bind.bind(handle);
205
+ return {
206
+ type: "__fluid_handle__",
207
+ url: handle.absolutePath,
208
+ };
209
+ }
215
210
  }