@open-pioneer/local-storage 0.1.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # @open-pioneer/local-storage
2
+
3
+ ## 0.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 3ca8a25: Initial release
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,13 @@
1
+ import { ServiceOptions } from "@open-pioneer/runtime";
2
+ import { LocalStorageNamespace, LocalStorageService } from "./api";
3
+ export declare class LocalStorageServiceImpl implements LocalStorageService {
4
+ #private;
5
+ constructor(options: ServiceOptions);
6
+ destroy(): void;
7
+ get isSupported(): boolean;
8
+ get(key: string): unknown;
9
+ set(key: string, value: unknown): void;
10
+ remove(key: string): void;
11
+ removeAll(): void;
12
+ getNamespace(key: string): LocalStorageNamespace;
13
+ }
@@ -0,0 +1,270 @@
1
+ import { createLogger, Error } from '@open-pioneer/core';
2
+
3
+ const LOG = createLogger("local-storage");
4
+ const SAVE_TIMEOUT = 0;
5
+ const ERROR_IDS = {
6
+ CORRUPTED_DATA: "local-storage:corrupted-data",
7
+ INVALID_PATH: "local-storage:invalid-path",
8
+ INVALID_VALUE: "local-storage:invalid-value",
9
+ NOT_SUPPORTED: "local-storage:not-supported",
10
+ INTERNAL: "local-storage:internal-error"
11
+ };
12
+ class LocalStorageServiceImpl {
13
+ // Key in local storage.
14
+ #rootKey;
15
+ // Root value. A (possibly nested) JSON structure that is persisted into local storage.
16
+ // This value (or its children) are modified via the various `get` / `set` / `clear` / etc. methods
17
+ // on the service itself and on the namespace objects obtained through the service.
18
+ #rootValue = {};
19
+ // Reference to the local storage (if supported).
20
+ #localStorage;
21
+ // The root namespace works on `rootValue` directly.
22
+ #rootNamespace;
23
+ constructor(options) {
24
+ this.#rootKey = getRootKey(options.properties);
25
+ this.#localStorage = getLocalStorage();
26
+ if (this.#localStorage) {
27
+ this.#load();
28
+ this.#rootNamespace = this.#createRootNamespace();
29
+ }
30
+ }
31
+ destroy() {
32
+ if (this.#saveTimeout) {
33
+ clearTimeout(this.#saveTimeout);
34
+ this.#saveTimeout = void 0;
35
+ }
36
+ if (this.#localStorage) {
37
+ this.#save();
38
+ }
39
+ }
40
+ get isSupported() {
41
+ return !!this.#rootNamespace;
42
+ }
43
+ get(key) {
44
+ return this.#getRootNamespace().get(key);
45
+ }
46
+ set(key, value) {
47
+ return this.#getRootNamespace().set(key, value);
48
+ }
49
+ remove(key) {
50
+ return this.#getRootNamespace().remove(key);
51
+ }
52
+ removeAll() {
53
+ return this.#getRootNamespace().removeAll();
54
+ }
55
+ getNamespace(key) {
56
+ return this.#getRootNamespace().getNamespace(key);
57
+ }
58
+ // Debounce save() calls to avoid saving after every 'set'.
59
+ // This gives us some improved performance when there are multiple sets
60
+ // in quick succession.
61
+ #saveTimeout;
62
+ #triggerSave() {
63
+ if (this.#saveTimeout) {
64
+ clearTimeout(this.#saveTimeout);
65
+ }
66
+ this.#saveTimeout = setTimeout(() => {
67
+ this.#saveTimeout = void 0;
68
+ this.#save();
69
+ }, SAVE_TIMEOUT);
70
+ }
71
+ /**
72
+ * Loads persisted data from local storage.
73
+ * If the data is invalid (e.g. bad json), this will revert to the default (an empty object).
74
+ *
75
+ * This method is called during service startup to load the initial state.
76
+ */
77
+ #load() {
78
+ try {
79
+ const storage = this.#localStorage;
80
+ if (!storage) {
81
+ throw new Error(ERROR_IDS.INTERNAL, "Local storage is not available.");
82
+ }
83
+ const json = storage.getItem(this.#rootKey);
84
+ if (json == null) {
85
+ this.#rootValue = {};
86
+ this.#save();
87
+ return;
88
+ }
89
+ try {
90
+ const data = JSON.parse(json);
91
+ if (!isObject(data)) {
92
+ throw new Error(
93
+ ERROR_IDS.CORRUPTED_DATA,
94
+ "Persisted value should be an object."
95
+ );
96
+ }
97
+ this.#rootValue = data;
98
+ } catch (jsonError) {
99
+ LOG.warn("Invalid persisted data, reverting to default.", jsonError);
100
+ this.#rootValue = {};
101
+ this.#save();
102
+ }
103
+ } catch (e) {
104
+ LOG.error(`Failed to load from local storage`, e);
105
+ }
106
+ }
107
+ /**
108
+ * Persists the current state of `rootValue` to local storage.
109
+ * This method is called whenever the state was modified.
110
+ */
111
+ #save() {
112
+ try {
113
+ const storage = this.#localStorage;
114
+ if (!storage) {
115
+ throw new Error(ERROR_IDS.INTERNAL, "Local storage is not available.");
116
+ }
117
+ const json = JSON.stringify(this.#rootValue);
118
+ storage.setItem(this.#rootKey, json);
119
+ } catch (e) {
120
+ LOG.error(`Failed to save to local storage`, e);
121
+ }
122
+ }
123
+ #getRootNamespace() {
124
+ const root = this.#rootNamespace;
125
+ if (!root) {
126
+ throw new Error(
127
+ ERROR_IDS.NOT_SUPPORTED,
128
+ "Local storage is not supported by this browser."
129
+ );
130
+ }
131
+ return root;
132
+ }
133
+ #createRootNamespace() {
134
+ const storageAccess = {
135
+ getByPath: (path) => {
136
+ return cloneJSON(getPath(this.#rootValue, path));
137
+ },
138
+ setByPath: (path, value) => {
139
+ if (!isSupportedValue(value)) {
140
+ throw new Error(
141
+ ERROR_IDS.INVALID_VALUE,
142
+ "The value is not supported by local storage."
143
+ );
144
+ }
145
+ value = cloneJSON(value);
146
+ if (path.length === 0) {
147
+ if (!isObject(value)) {
148
+ throw new Error(
149
+ ERROR_IDS.INVALID_VALUE,
150
+ "The root value must be a plain object."
151
+ );
152
+ }
153
+ this.#rootValue = value;
154
+ } else {
155
+ setPath(this.#rootValue, path, value);
156
+ }
157
+ this.#triggerSave();
158
+ }
159
+ };
160
+ return new StorageNamespaceImpl([], storageAccess);
161
+ }
162
+ }
163
+ class StorageNamespaceImpl {
164
+ path;
165
+ access;
166
+ constructor(path, access) {
167
+ this.path = path;
168
+ this.access = access;
169
+ }
170
+ get(key) {
171
+ return this.access.getByPath([...this.path, key]);
172
+ }
173
+ set(key, value) {
174
+ this.access.setByPath([...this.path, key], value);
175
+ }
176
+ remove(key) {
177
+ this.access.setByPath([...this.path, key], void 0);
178
+ }
179
+ removeAll() {
180
+ this.access.setByPath(this.path, {});
181
+ }
182
+ getNamespace(key) {
183
+ const existingValue = this.get(key);
184
+ if (existingValue === void 0) {
185
+ this.set(key, {});
186
+ } else if (!isObject(existingValue)) {
187
+ throw new Error(
188
+ ERROR_IDS.INVALID_PATH,
189
+ `Cannot use '${key}' as a namespace because it is not associated with an object.`
190
+ );
191
+ }
192
+ return new StorageNamespaceImpl(this.path.concat([key]), this.access);
193
+ }
194
+ }
195
+ const DEFAULT_KEY = "trails-state";
196
+ function getPath(object, path) {
197
+ let current = object;
198
+ for (const p of path) {
199
+ if (!isObject(current)) {
200
+ throw new Error(
201
+ ERROR_IDS.INVALID_PATH,
202
+ `Cannot get nested property '${p}' because the parent is no object.`
203
+ );
204
+ }
205
+ current = current[p];
206
+ }
207
+ return current;
208
+ }
209
+ function setPath(object, path, value) {
210
+ if (!path.length) {
211
+ throw new Error(ERROR_IDS.INTERNAL, "Path must not be empty.");
212
+ }
213
+ let current = object;
214
+ for (let i = 0, n = path.length - 1; i < n; ++i) {
215
+ const p = path[i];
216
+ const next = current[p];
217
+ if (!isObject(next)) {
218
+ throw new Error(
219
+ ERROR_IDS.INVALID_PATH,
220
+ `Cannot set property on '${p}' because it is no object.`
221
+ );
222
+ }
223
+ current = next;
224
+ }
225
+ const prop = path[path.length - 1];
226
+ current[prop] = value;
227
+ }
228
+ function isObject(object) {
229
+ return !!(object && typeof object === "object" && !Array.isArray(object));
230
+ }
231
+ function isSupportedValue(value) {
232
+ const type = typeof value;
233
+ return type === "boolean" || type === "number" || type === "string" || type === "undefined" || value === null || Array.isArray(value) || isObject(value);
234
+ }
235
+ function getRootKey(properties) {
236
+ const storageId = properties.storageId;
237
+ if (!storageId || typeof storageId !== "string") {
238
+ LOG.warn(
239
+ `The 'storageId' property of the 'local-storage' package should be set to a valid string to avoid collisions with other applications. Defaulting to '${DEFAULT_KEY}'.`
240
+ );
241
+ return DEFAULT_KEY;
242
+ }
243
+ return storageId;
244
+ }
245
+ function getLocalStorage() {
246
+ if (typeof Storage === "undefined") {
247
+ LOG.warn("Local storage is not supported by this browser.");
248
+ return void 0;
249
+ }
250
+ try {
251
+ const storage = globalThis.localStorage;
252
+ if (!storage) {
253
+ LOG.warn("Local storage is not supported by this browser.");
254
+ return void 0;
255
+ }
256
+ return storage;
257
+ } catch (e) {
258
+ LOG.warn("Local storage is not supported by this browser.", e);
259
+ return void 0;
260
+ }
261
+ }
262
+ function cloneJSON(value) {
263
+ if (value != null) {
264
+ value = JSON.parse(JSON.stringify(value));
265
+ }
266
+ return value;
267
+ }
268
+
269
+ export { LocalStorageServiceImpl };
270
+ //# sourceMappingURL=LocalStorageServiceImpl.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"LocalStorageServiceImpl.js","sources":["LocalStorageServiceImpl.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2023 Open Pioneer project (https://github.com/open-pioneer)\n// SPDX-License-Identifier: Apache-2.0\nimport { ServiceOptions } from \"@open-pioneer/runtime\";\nimport { LocalStorageNamespace, LocalStorageProperties, LocalStorageService } from \"./api\";\nimport { createLogger, Error } from \"@open-pioneer/core\";\n\nconst LOG = createLogger(\"local-storage\");\n\nconst SAVE_TIMEOUT = 0;\n\nconst ERROR_IDS = {\n CORRUPTED_DATA: \"local-storage:corrupted-data\",\n INVALID_PATH: \"local-storage:invalid-path\",\n INVALID_VALUE: \"local-storage:invalid-value\",\n NOT_SUPPORTED: \"local-storage:not-supported\",\n INTERNAL: \"local-storage:internal-error\"\n} as const;\n\nexport class LocalStorageServiceImpl implements LocalStorageService {\n // Key in local storage.\n #rootKey: string;\n\n // Root value. A (possibly nested) JSON structure that is persisted into local storage.\n // This value (or its children) are modified via the various `get` / `set` / `clear` / etc. methods\n // on the service itself and on the namespace objects obtained through the service.\n #rootValue: Record<string, unknown> = {};\n\n // Reference to the local storage (if supported).\n #localStorage: Storage | undefined;\n\n // The root namespace works on `rootValue` directly.\n #rootNamespace: StorageNamespaceImpl | undefined;\n\n constructor(options: ServiceOptions) {\n this.#rootKey = getRootKey(options.properties);\n this.#localStorage = getLocalStorage();\n if (this.#localStorage) {\n this.#load();\n this.#rootNamespace = this.#createRootNamespace();\n }\n }\n\n destroy() {\n if (this.#saveTimeout) {\n clearTimeout(this.#saveTimeout);\n this.#saveTimeout = undefined;\n }\n if (this.#localStorage) {\n this.#save();\n }\n }\n\n get isSupported(): boolean {\n return !!this.#rootNamespace;\n }\n\n get(key: string): unknown {\n return this.#getRootNamespace().get(key);\n }\n\n set(key: string, value: unknown): void {\n return this.#getRootNamespace().set(key, value);\n }\n\n remove(key: string): void {\n return this.#getRootNamespace().remove(key);\n }\n\n removeAll(): void {\n return this.#getRootNamespace().removeAll();\n }\n\n getNamespace(key: string): LocalStorageNamespace {\n return this.#getRootNamespace().getNamespace(key);\n }\n\n // Debounce save() calls to avoid saving after every 'set'.\n // This gives us some improved performance when there are multiple sets\n // in quick succession.\n #saveTimeout: ReturnType<(typeof globalThis)[\"setTimeout\"]> | undefined;\n #triggerSave(): void {\n if (this.#saveTimeout) {\n clearTimeout(this.#saveTimeout);\n }\n this.#saveTimeout = setTimeout(() => {\n this.#saveTimeout = undefined;\n this.#save();\n }, SAVE_TIMEOUT);\n }\n\n /**\n * Loads persisted data from local storage.\n * If the data is invalid (e.g. bad json), this will revert to the default (an empty object).\n *\n * This method is called during service startup to load the initial state.\n */\n #load() {\n try {\n const storage = this.#localStorage;\n if (!storage) {\n // Should not happen (load is called only when storage is available).\n throw new Error(ERROR_IDS.INTERNAL, \"Local storage is not available.\");\n }\n\n const json = storage.getItem(this.#rootKey);\n if (json == null) {\n // No previous value\n this.#rootValue = {};\n this.#save();\n return;\n }\n\n try {\n const data = JSON.parse(json);\n if (!isObject(data)) {\n throw new Error(\n ERROR_IDS.CORRUPTED_DATA,\n \"Persisted value should be an object.\"\n );\n }\n this.#rootValue = data;\n } catch (jsonError) {\n LOG.warn(\"Invalid persisted data, reverting to default.\", jsonError);\n this.#rootValue = {};\n this.#save();\n }\n } catch (e) {\n LOG.error(`Failed to load from local storage`, e);\n }\n }\n\n /**\n * Persists the current state of `rootValue` to local storage.\n * This method is called whenever the state was modified.\n */\n #save() {\n try {\n const storage = this.#localStorage;\n if (!storage) {\n // Should not happen (setting values is only possible if supported).\n throw new Error(ERROR_IDS.INTERNAL, \"Local storage is not available.\");\n }\n\n const json = JSON.stringify(this.#rootValue);\n storage.setItem(this.#rootKey, json);\n } catch (e) {\n LOG.error(`Failed to save to local storage`, e);\n }\n }\n\n #getRootNamespace(): StorageNamespaceImpl {\n const root = this.#rootNamespace;\n if (!root) {\n throw new Error(\n ERROR_IDS.NOT_SUPPORTED,\n \"Local storage is not supported by this browser.\"\n );\n }\n return root;\n }\n\n #createRootNamespace(): StorageNamespaceImpl {\n const storageAccess: StorageAccess = {\n getByPath: (path) => {\n // Clone to protect against side effects on internal value\n return cloneJSON(getPath(this.#rootValue, path));\n },\n setByPath: (path, value) => {\n if (!isSupportedValue(value)) {\n throw new Error(\n ERROR_IDS.INVALID_VALUE,\n \"The value is not supported by local storage.\"\n );\n }\n\n // Clone to protect against side effects on original value\n value = cloneJSON(value);\n\n // Rewrite root object if path is empty.\n if (path.length === 0) {\n if (!isObject(value)) {\n throw new Error(\n ERROR_IDS.INVALID_VALUE,\n \"The root value must be a plain object.\"\n );\n }\n this.#rootValue = value;\n } else {\n setPath(this.#rootValue, path, value);\n }\n\n this.#triggerSave();\n }\n };\n return new StorageNamespaceImpl([], storageAccess);\n }\n}\n\ninterface StorageAccess {\n getByPath(path: string[]): unknown;\n setByPath(path: string[], value: unknown): void;\n}\n\nclass StorageNamespaceImpl implements LocalStorageNamespace {\n private path: string[];\n private access: StorageAccess;\n\n constructor(path: string[], access: StorageAccess) {\n this.path = path;\n this.access = access;\n }\n\n get(key: string): unknown {\n return this.access.getByPath([...this.path, key]);\n }\n\n set(key: string, value: unknown): void {\n this.access.setByPath([...this.path, key], value);\n }\n\n remove(key: string): void {\n this.access.setByPath([...this.path, key], undefined);\n }\n\n removeAll(): void {\n this.access.setByPath(this.path, {});\n }\n\n getNamespace(key: string): StorageNamespaceImpl {\n const existingValue = this.get(key);\n if (existingValue === undefined) {\n this.set(key, {});\n } else if (!isObject(existingValue)) {\n throw new Error(\n ERROR_IDS.INVALID_PATH,\n `Cannot use '${key}' as a namespace because it is not associated with an object.`\n );\n }\n\n return new StorageNamespaceImpl(this.path.concat([key]), this.access);\n }\n}\n\nconst DEFAULT_KEY = \"trails-state\";\n\n/**\n * Retrieves the property at `path` from the nested `object`.\n * Returns `object` if path is empty.\n */\nfunction getPath(object: Record<string, unknown>, path: string[]): unknown {\n let current: unknown = object;\n for (const p of path) {\n if (!isObject(current)) {\n throw new Error(\n ERROR_IDS.INVALID_PATH,\n `Cannot get nested property '${p}' because the parent is no object.`\n );\n }\n current = current[p];\n }\n return current;\n}\n\n/**\n * Sets the property at `path` in the nested `object` to `value`.\n * Throws an error if the path is empty.\n */\nfunction setPath(object: Record<string, unknown>, path: string[], value: unknown): void {\n if (!path.length) {\n throw new Error(ERROR_IDS.INTERNAL, \"Path must not be empty.\");\n }\n\n let current = object;\n for (let i = 0, n = path.length - 1; i < n; ++i) {\n const p = path[i]!;\n\n const next = current[p];\n if (!isObject(next)) {\n throw new Error(\n ERROR_IDS.INVALID_PATH,\n `Cannot set property on '${p}' because it is no object.`\n );\n }\n current = next;\n }\n\n const prop = path[path.length - 1]!;\n current[prop] = value;\n}\n\n/**\n * Returns true if `object` is a plain object (or record).\n */\nfunction isObject(object: unknown): object is Record<string, unknown> {\n return !!(object && typeof object === \"object\" && !Array.isArray(object));\n}\n\n/**\n * Returns true if `value` looks like a JSON value.\n */\nfunction isSupportedValue(value: unknown) {\n const type = typeof value;\n return (\n type === \"boolean\" ||\n type === \"number\" ||\n type === \"string\" ||\n type === \"undefined\" ||\n value === null ||\n Array.isArray(value) ||\n isObject(value)\n );\n}\n\nfunction getRootKey(properties: Partial<LocalStorageProperties>): string {\n const storageId = properties.storageId;\n if (!storageId || typeof storageId !== \"string\") {\n LOG.warn(\n `The 'storageId' property of the 'local-storage' package should be set to a valid string to avoid collisions with other applications.` +\n ` Defaulting to '${DEFAULT_KEY}'.`\n );\n return DEFAULT_KEY;\n }\n return storageId;\n}\n\nfunction getLocalStorage(): Storage | undefined {\n if (typeof Storage === \"undefined\") {\n LOG.warn(\"Local storage is not supported by this browser.\");\n return undefined;\n }\n\n try {\n const storage = globalThis.localStorage;\n if (!storage) {\n LOG.warn(\"Local storage is not supported by this browser.\");\n return undefined;\n }\n return storage;\n } catch (e) {\n LOG.warn(\"Local storage is not supported by this browser.\", e);\n return undefined;\n }\n}\n\nfunction cloneJSON(value: unknown): unknown {\n if (value != null) {\n value = JSON.parse(JSON.stringify(value));\n }\n return value;\n}\n"],"names":[],"mappings":";;AAMA,MAAM,GAAA,GAAM,aAAa,eAAe,CAAA,CAAA;AAExC,MAAM,YAAe,GAAA,CAAA,CAAA;AAErB,MAAM,SAAY,GAAA;AAAA,EACd,cAAgB,EAAA,8BAAA;AAAA,EAChB,YAAc,EAAA,4BAAA;AAAA,EACd,aAAe,EAAA,6BAAA;AAAA,EACf,aAAe,EAAA,6BAAA;AAAA,EACf,QAAU,EAAA,8BAAA;AACd,CAAA,CAAA;AAEO,MAAM,uBAAuD,CAAA;AAAA;AAAA,EAEhE,QAAA,CAAA;AAAA;AAAA;AAAA;AAAA,EAKA,aAAsC,EAAC,CAAA;AAAA;AAAA,EAGvC,aAAA,CAAA;AAAA;AAAA,EAGA,cAAA,CAAA;AAAA,EAEA,YAAY,OAAyB,EAAA;AACjC,IAAK,IAAA,CAAA,QAAA,GAAW,UAAW,CAAA,OAAA,CAAQ,UAAU,CAAA,CAAA;AAC7C,IAAA,IAAA,CAAK,gBAAgB,eAAgB,EAAA,CAAA;AACrC,IAAA,IAAI,KAAK,aAAe,EAAA;AACpB,MAAA,IAAA,CAA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,KAAK,CAAA,IACnB,SAAS,KAAK,CAAA,CAAA;AAEtB,CAAA;AAEA,SAAS,WAAW,UAAqD,EAAA;AACrE,EAAA,MAAM,YAAY,UAAW,CAAA,SAAA,CAAA;AAC7B,EAAA,IAAI,CAAC,SAAA,IAAa,OAAO,SAAA,KAAc,QAAU,EAAA;AAC7C,IAAI,GAAA,CAAA,IAAA;AAAA,MACA,uJACuB,WAAW,CAAA,EAAA,CAAA;AAAA,KACtC,CAAA;AACA,IAAO,OAAA,WAAA,CAAA;AAAA,GACX;AACA,EAAO,OAAA,SAAA,CAAA;AACX,CAAA;AAEA,SAAS,eAAuC,GAAA;AAC5C,EAAI,IAAA,OAAO,YAAY,WAAa,EAAA;AAChC,IAAA,GAAA,CAAI,KAAK,iDAAiD,CAAA,CAAA;AAC1D,IAAO,OAAA,KAAA,CAAA,CAAA;AAAA,GACX;AAEA,EAAI,IAAA;AACA,IAAA,MAAM,UAAU,UAAW,CAAA,YAAA,CAAA;AAC3B,IAAA,IAAI,CAAC,OAAS,EAAA;AACV,MAAA,GAAA,CAAI,KAAK,iDAAiD,CAAA,CAAA;AAC1D,MAAO,OAAA,KAAA,CAAA,CAAA;AAAA,KACX;AACA,IAAO,OAAA,OAAA,CAAA;AAAA,WACF,CAAG,EAAA;AACR,IAAI,GAAA,CAAA,IAAA,CAAK,mDAAmD,CAAC,CAAA,CAAA;AAC7D,IAAO,OAAA,KAAA,CAAA,CAAA;AAAA,GACX;AACJ,CAAA;AAEA,SAAS,UAAU,KAAyB,EAAA;AACxC,EAAA,IAAI,SAAS,IAAM,EAAA;AACf,IAAA,KAAA,GAAQ,IAAK,CAAA,KAAA,CAAM,IAAK,CAAA,SAAA,CAAU,KAAK,CAAC,CAAA,CAAA;AAAA,GAC5C;AACA,EAAO,OAAA,KAAA,CAAA;AACX;;;;"}
package/README.md ADDED
@@ -0,0 +1,103 @@
1
+ # @open-pioneer/local-storage
2
+
3
+ This package provides access to the browser's [local storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage).
4
+
5
+ A single local storage key (configurable, see [Configuration](#configuration)) is used to keep track of the application's persistent data.
6
+ Packages using the `LocalStorageService` can work with arbitrary values (including nested data structures) through a convenient API.
7
+
8
+ > NOTE: The `LocalStorageService` will read the persistent data from the browser's local storage on application startup.
9
+ > Changes to that data made via the `LocalStorageService` will be reflected in the browser's local storage immediately.
10
+ > Concurrent changes made to the browser's local storage **will not** be reflected by the `LocalStorageService`.
11
+ > In other words, there is no two-way synchronization between the two systems while the application is running.
12
+ >
13
+ > You should not attempt to modify the local storage value managed by the `LocalStorageService` (see `storageId` in [Configuration](#configuration)) through the "raw" Browser APIs while the application is running.
14
+ > Other keys are safe to use.
15
+
16
+ ## Usage
17
+
18
+ Reference the interface name `local-storage.LocalStorageService` to inject an instance of `LocalStorageService`.
19
+
20
+ ### Checking for local storage support
21
+
22
+ Not all browsers implement or enable support for local storage.
23
+ Use the `.isSupported` property to check whether local storage can be used at all:
24
+
25
+ ```js
26
+ const storageService = ...; // injected
27
+ console.log(storageService.isSupported);
28
+ ```
29
+
30
+ If local storage is not supported, other methods (such as `get()` and `set()`) will throw an error.
31
+
32
+ ### Reading and writing values
33
+
34
+ In its most basic form, you can use the `LocalStorageService` similar to a map.
35
+ In the background, changes to the service will always be persisted into local storage.
36
+
37
+ All keys and values used in the `LocalStorageService` will be serialized to JSON via `JSON.stringify()`.
38
+ Thus, only values supported by JSON can be used.
39
+
40
+ Example:
41
+
42
+ ```js
43
+ const storageService = ...; // injected
44
+ storageService.set("foo", "bar");
45
+ storageService.set("foo", ["array"]);
46
+ storageService.set("foo", {
47
+ nested: {
48
+ object: "hello world"
49
+ }
50
+ });
51
+ storageService.get("foo"); // returns (copy of) previous value
52
+ storageService.remove("foo");
53
+ storageService.clear();
54
+ ```
55
+
56
+ ### Namespaces
57
+
58
+ You can use the `LocalStorageService` to manage hierarchical data, including objects and arrays (see above).
59
+ _Namespaces_ can help you treat an object as a group of (nested) properties.
60
+ Getting or setting entries in the namespace will update an object behind the scenes.
61
+
62
+ To use a namespace, call `getNamespace(key)` on either the `LocalStorageService` or another `LocalStorageNamespace` object.
63
+ The `key` used in `getNamespace(key)` should either already be associated with an object or it should not be set to a value at all.
64
+ If `key` is not yet associated with an existing object, a new empty object will be created.
65
+
66
+ Example:
67
+
68
+ ```js
69
+ const storageService = ...; // injected
70
+ const namespace = storageService.getNamespace("my-key");
71
+ namespace.set("foo", "bar"); // actually sets `"my-key" -> "foo"`
72
+ ```
73
+
74
+ `getNamespace("my-key")` returns a `LocalStorageNamespace` instance that manipulates the object at `"my-key"`.
75
+
76
+ Namespaces provide a convenient way to scope your component's persistent values, avoiding conflicts with other packages.
77
+ For example, you can use your package name as the namespace key:
78
+
79
+ ```js
80
+ const storageService = ...; // injected
81
+ const namespace = storageService.getNamespace("my-package-name");
82
+ namespace.set("my-state", "some-value-to-save");
83
+ ```
84
+
85
+ > NOTE: Multiple namespace instances using the same `key` will manipulate the same object and see each other's effects.
86
+
87
+ ### Configuration
88
+
89
+ | Name | Type | Description |
90
+ | ----------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
91
+ | `storageId` | String | The key under which the persistent data will be saved. This value should be configured to a reasonably unique value to avoid clashes with other applications at the same origin. Defaults to `trails-state` (with a warning). |
92
+
93
+ ### Implementation notes
94
+
95
+ The `LocalStorageService` manages the persistent data as a single, hierarchical JSON object.
96
+ This JSON object is loaded from and saved to the browser's local storage using the `storageId` key.
97
+
98
+ The top level value is always an object; its properties are manipulated when calling `get`, `set` etc. on the `LocalStorageService`.
99
+ Nested values can be arbitrary (JSON-compatible) values.
100
+
101
+ ## License
102
+
103
+ Apache-2.0 (see `LICENSE` file)
package/api.d.ts ADDED
@@ -0,0 +1,89 @@
1
+ import { DeclaredService } from "@open-pioneer/runtime";
2
+ /**
3
+ * Provides access to the browser's local storage for trails packages through a convenient API.
4
+ * Use the interface name `"local-storage.LocalStorageService"` to inject an instance of this interface.
5
+ */
6
+ export interface LocalStorageService extends LocalStorageAPI, DeclaredService<"local-storage.LocalStorageService"> {
7
+ /**
8
+ * Whether local storage is supported by the current environment.
9
+ *
10
+ * Getters and setters working on local storage will throw if this value is `false`.
11
+ */
12
+ readonly isSupported: boolean;
13
+ }
14
+ /**
15
+ * A namespace provides access to the properties of an object in local storage.
16
+ * This can be used to manage groups of related values under a common name.
17
+ */
18
+ export type LocalStorageNamespace = LocalStorageAPI;
19
+ /**
20
+ * Provides basic operations to interact with the browser's local storage.
21
+ *
22
+ * The operations provided by this interface always act on an object in local storage:
23
+ * either the root value or a nested object.
24
+ */
25
+ export interface LocalStorageAPI {
26
+ /**
27
+ * Returns the value associated with the given `key`, or `undefined` if
28
+ * no such value exists.
29
+ */
30
+ get(key: string): unknown;
31
+ /**
32
+ * Associates the given `value` with `key`.
33
+ *
34
+ * This method supports arbitrary [JSON](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) compatible values,
35
+ * including objects and arrays.
36
+ * If you store an object, you can later access (or modify) its individual properties using {@link getNamespace}.
37
+ *
38
+ * > NOTE: This function creates a clone of the original value to protect against accidental side effects.
39
+ * > Updating the original value after `set()` will have no effect on the stored value.
40
+ */
41
+ set(key: string, value: unknown): void;
42
+ /**
43
+ * Removes any value associated with `key`.
44
+ */
45
+ remove(key: string): void;
46
+ /**
47
+ * Removes all entries associated managed by this instance.
48
+ *
49
+ * If `this` represents the root object, _all_ entries will be removed.
50
+ * If `this` represents a (possibly nested) namespace, only the contents of that
51
+ * namespace will be removed.
52
+ */
53
+ removeAll(): void;
54
+ /**
55
+ * Returns a storage namespace operating on the given `key` that can be used to group
56
+ * multiple related properties.
57
+ * `key` should either be associated with an object or it's value should be undefined.
58
+ * If `key` is not associated with a value, a new empty object will be created.
59
+ *
60
+ * Namespaces allow you to treat an object in local storage as a group of properties.
61
+ * Getting (or setting) a key using a {@link LocalStorageNamespace | Namespace} object
62
+ * will simply read (or update) properties on the managed object instead.
63
+ *
64
+ * If `key` has already been set to something that is _not_ an object, you will receive an error
65
+ * if you attempt to call this method.
66
+ *
67
+ * Example:
68
+ *
69
+ * ```js
70
+ * const storageService = ...; // injected
71
+ *
72
+ * // Namespace operates on the "my-package-name" object (which may not exist yet)
73
+ * const packageNamespace = storageService.getNamespace("my-package-name");
74
+ *
75
+ * // Setting the first value will ensure that the object exists
76
+ * packageNamespace.set("foo", "bar"); // actually sets `"my-package-name" -> "foo"`
77
+ *
78
+ * // Retrieving the same object ("my-package-name") via get():
79
+ * const backingObject = storageService.get("my-package-name"); // {"foo": "bar"}
80
+ * console.log(backingObject);
81
+ * ```
82
+ */
83
+ getNamespace(key: string): LocalStorageNamespace;
84
+ }
85
+ /** Package properties of the `"local-storage"` package. */
86
+ export interface LocalStorageProperties {
87
+ /** The root local storage key used to store application state. */
88
+ storageId: string | null;
89
+ }
package/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "./api";
package/index.js ADDED
@@ -0,0 +1,2 @@
1
+
2
+ //# sourceMappingURL=index.js.map
package/index.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "type": "module",
3
+ "name": "@open-pioneer/local-storage",
4
+ "version": "0.1.0",
5
+ "license": "Apache-2.0",
6
+ "peerDependencies": {
7
+ "@open-pioneer/core": "^1.2.1",
8
+ "@open-pioneer/runtime": "^2.0.2"
9
+ },
10
+ "exports": {
11
+ "./package.json": "./package.json",
12
+ ".": {
13
+ "import": "./index.js",
14
+ "types": "./index.d.ts"
15
+ },
16
+ "./services": {
17
+ "import": "./services.js",
18
+ "types": "./services.d.ts"
19
+ }
20
+ },
21
+ "openPioneerFramework": {
22
+ "services": [
23
+ {
24
+ "serviceName": "LocalStorageServiceImpl",
25
+ "provides": [
26
+ {
27
+ "interfaceName": "local-storage.LocalStorageService"
28
+ }
29
+ ],
30
+ "references": []
31
+ }
32
+ ],
33
+ "servicesModule": "./services",
34
+ "i18n": {
35
+ "languages": []
36
+ },
37
+ "ui": {
38
+ "references": []
39
+ },
40
+ "properties": [
41
+ {
42
+ "propertyName": "storageId",
43
+ "defaultValue": null,
44
+ "required": false
45
+ }
46
+ ],
47
+ "packageFormatVersion": "1.0.0"
48
+ }
49
+ }
package/services.d.ts ADDED
@@ -0,0 +1 @@
1
+ export { LocalStorageServiceImpl } from "./LocalStorageServiceImpl";
package/services.js ADDED
@@ -0,0 +1,2 @@
1
+ export { LocalStorageServiceImpl } from './LocalStorageServiceImpl.js';
2
+ //# sourceMappingURL=services.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"services.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}