@wordpress/preferences-persistence 3.0.0 → 3.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.
Files changed (82) hide show
  1. package/build/create/debounce-async.cjs +54 -58
  2. package/build/create/debounce-async.cjs.map +1 -7
  3. package/build/create/index.cjs +73 -79
  4. package/build/create/index.cjs.map +1 -7
  5. package/build/get-newest-data.cjs +50 -39
  6. package/build/get-newest-data.cjs.map +1 -7
  7. package/build/index.cjs +50 -43
  8. package/build/index.cjs.map +1 -7
  9. package/build/is-preferences-data.cjs +16 -25
  10. package/build/is-preferences-data.cjs.map +1 -7
  11. package/build/local-storage.cjs +33 -40
  12. package/build/local-storage.cjs.map +1 -7
  13. package/build/migrations/legacy-local-storage-data/convert-edit-post-panels.cjs +48 -38
  14. package/build/migrations/legacy-local-storage-data/convert-edit-post-panels.cjs.map +1 -7
  15. package/build/migrations/legacy-local-storage-data/index.cjs +93 -83
  16. package/build/migrations/legacy-local-storage-data/index.cjs.map +1 -7
  17. package/build/migrations/legacy-local-storage-data/move-feature-preferences.cjs +105 -77
  18. package/build/migrations/legacy-local-storage-data/move-feature-preferences.cjs.map +1 -7
  19. package/build/migrations/legacy-local-storage-data/move-individual-preference.cjs +69 -58
  20. package/build/migrations/legacy-local-storage-data/move-individual-preference.cjs.map +1 -7
  21. package/build/migrations/legacy-local-storage-data/move-interface-enable-items.cjs +92 -75
  22. package/build/migrations/legacy-local-storage-data/move-interface-enable-items.cjs.map +1 -7
  23. package/build/migrations/legacy-local-storage-data/move-third-party-feature-preferences.cjs +76 -65
  24. package/build/migrations/legacy-local-storage-data/move-third-party-feature-preferences.cjs.map +1 -7
  25. package/build/migrations/legacy-local-storage-data/types.cjs +4 -18
  26. package/build/migrations/preferences-package-data/convert-complementary-areas.cjs +18 -38
  27. package/build/migrations/preferences-package-data/convert-complementary-areas.cjs.map +1 -7
  28. package/build/migrations/preferences-package-data/convert-editor-settings.cjs +58 -72
  29. package/build/migrations/preferences-package-data/convert-editor-settings.cjs.map +1 -7
  30. package/build/migrations/preferences-package-data/index.cjs +27 -31
  31. package/build/migrations/preferences-package-data/index.cjs.map +1 -7
  32. package/build/types.cjs +4 -18
  33. package/build-module/create/debounce-async.mjs +50 -38
  34. package/build-module/create/debounce-async.mjs.map +1 -7
  35. package/build-module/create/index.mjs +48 -53
  36. package/build-module/create/index.mjs.map +1 -7
  37. package/build-module/get-newest-data.mjs +29 -15
  38. package/build-module/get-newest-data.mjs.map +1 -7
  39. package/build-module/index.mjs +23 -15
  40. package/build-module/index.mjs.map +1 -7
  41. package/build-module/is-preferences-data.mjs +12 -5
  42. package/build-module/is-preferences-data.mjs.map +1 -7
  43. package/build-module/local-storage.mjs +28 -15
  44. package/build-module/local-storage.mjs.map +1 -7
  45. package/build-module/migrations/legacy-local-storage-data/convert-edit-post-panels.mjs +44 -18
  46. package/build-module/migrations/legacy-local-storage-data/convert-edit-post-panels.mjs.map +1 -7
  47. package/build-module/migrations/legacy-local-storage-data/index.mjs +63 -51
  48. package/build-module/migrations/legacy-local-storage-data/index.mjs.map +1 -7
  49. package/build-module/migrations/legacy-local-storage-data/move-feature-preferences.mjs +101 -57
  50. package/build-module/migrations/legacy-local-storage-data/move-feature-preferences.mjs.map +1 -7
  51. package/build-module/migrations/legacy-local-storage-data/move-individual-preference.mjs +65 -38
  52. package/build-module/migrations/legacy-local-storage-data/move-individual-preference.mjs.map +1 -7
  53. package/build-module/migrations/legacy-local-storage-data/move-interface-enable-items.mjs +88 -55
  54. package/build-module/migrations/legacy-local-storage-data/move-interface-enable-items.mjs.map +1 -7
  55. package/build-module/migrations/legacy-local-storage-data/move-third-party-feature-preferences.mjs +72 -45
  56. package/build-module/migrations/legacy-local-storage-data/move-third-party-feature-preferences.mjs.map +1 -7
  57. package/build-module/migrations/legacy-local-storage-data/types.mjs +0 -1
  58. package/build-module/migrations/preferences-package-data/convert-complementary-areas.mjs +14 -18
  59. package/build-module/migrations/preferences-package-data/convert-complementary-areas.mjs.map +1 -7
  60. package/build-module/migrations/preferences-package-data/convert-editor-settings.mjs +40 -50
  61. package/build-module/migrations/preferences-package-data/convert-editor-settings.mjs.map +1 -7
  62. package/build-module/migrations/preferences-package-data/index.mjs +7 -8
  63. package/build-module/migrations/preferences-package-data/index.mjs.map +1 -7
  64. package/build-module/types.mjs +0 -1
  65. package/package.json +5 -4
  66. package/src/create/test/{debounce-async.js → debounce-async.ts} +7 -3
  67. package/src/create/test/{index.jsdom.test.js → index.jsdom.test.ts} +8 -5
  68. package/src/migrations/legacy-local-storage-data/test/{index.js → index.ts} +6 -1
  69. package/src/migrations/preferences-package-data/test/{convert-editor-settings.js → convert-editor-settings.ts} +3 -0
  70. package/src/test/{index.jsdom.test.js → index.jsdom.test.ts} +6 -4
  71. package/build/migrations/legacy-local-storage-data/types.cjs.map +0 -7
  72. package/build/types.cjs.map +0 -7
  73. package/build-module/migrations/legacy-local-storage-data/types.mjs.map +0 -7
  74. package/build-module/types.mjs.map +0 -7
  75. /package/src/migrations/legacy-local-storage-data/test/{convert-edit-post-panels.js → convert-edit-post-panels.ts} +0 -0
  76. /package/src/migrations/legacy-local-storage-data/test/{move-feature-preferences.js → move-feature-preferences.ts} +0 -0
  77. /package/src/migrations/legacy-local-storage-data/test/{move-individual-preference.js → move-individual-preference.ts} +0 -0
  78. /package/src/migrations/legacy-local-storage-data/test/{move-interface-enable-items.js → move-interface-enable-items.ts} +0 -0
  79. /package/src/migrations/legacy-local-storage-data/test/{move-third-party-feature-preferences.js → move-third-party-feature-preferences.ts} +0 -0
  80. /package/src/migrations/preferences-package-data/test/{convert-complementary-areas.js → convert-complementary-areas.ts} +0 -0
  81. /package/src/migrations/preferences-package-data/test/{index.js → index.ts} +0 -0
  82. /package/src/test/{local-storage.jsdom.test.js → local-storage.jsdom.test.ts} +0 -0
@@ -1,7 +1 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/create/debounce-async.ts"],
4
- "sourcesContent": ["/**\n * Performs a leading edge debounce of async functions.\n *\n * If three functions are throttled at the same time:\n * - The first happens immediately.\n * - The second is never called.\n * - The third happens `delayMS` milliseconds after the first has resolved.\n *\n * This is distinct from `{ debounce } from @wordpress/compose` in that it\n * waits for promise resolution.\n *\n * @param func A function that returns a promise.\n * @param delayMS A delay in milliseconds.\n *\n * @return A function that debounce whatever function is passed\n * to it.\n */\nexport default function debounceAsync< Args extends unknown[], Result >(\n\tfunc: ( ...args: Args ) => Promise< Result >,\n\tdelayMS: number\n): ( ...args: Args ) => Promise< Result > {\n\tlet timeoutId: ReturnType< typeof setTimeout > | null | undefined;\n\tlet activePromise: Promise< void > | null | undefined;\n\n\treturn async function debounced( ...args: Args ) {\n\t\t// This is a leading edge debounce. If there's no promise or timeout\n\t\t// in progress, call the debounced function immediately.\n\t\tif ( ! activePromise && ! timeoutId ) {\n\t\t\treturn new Promise< Result >( ( resolve, reject ) => {\n\t\t\t\t// Keep a reference to the promise.\n\t\t\t\tactivePromise = func( ...args )\n\t\t\t\t\t.then( ( ...thenArgs ) => {\n\t\t\t\t\t\tresolve( ...thenArgs );\n\t\t\t\t\t} )\n\t\t\t\t\t.catch( ( error ) => {\n\t\t\t\t\t\treject( error );\n\t\t\t\t\t} )\n\t\t\t\t\t.finally( () => {\n\t\t\t\t\t\t// As soon this promise is complete, clear the way for the\n\t\t\t\t\t\t// next one to happen immediately.\n\t\t\t\t\t\tactivePromise = null;\n\t\t\t\t\t} );\n\t\t\t} );\n\t\t}\n\n\t\tif ( activePromise ) {\n\t\t\t// Let any active promises finish before queuing the next request.\n\t\t\tawait activePromise;\n\t\t}\n\n\t\t// Clear any active timeouts, abandoning any requests that have\n\t\t// been queued but not been made.\n\t\tif ( timeoutId ) {\n\t\t\tclearTimeout( timeoutId );\n\t\t\ttimeoutId = null;\n\t\t}\n\n\t\t// Trigger any trailing edge calls to the function.\n\t\treturn new Promise< Result >( ( resolve, reject ) => {\n\t\t\t// Schedule the next request but with a delay.\n\t\t\ttimeoutId = setTimeout( () => {\n\t\t\t\tactivePromise = func( ...args )\n\t\t\t\t\t.then( ( ...thenArgs ) => {\n\t\t\t\t\t\tresolve( ...thenArgs );\n\t\t\t\t\t} )\n\t\t\t\t\t.catch( ( error ) => {\n\t\t\t\t\t\treject( error );\n\t\t\t\t\t} )\n\t\t\t\t\t.finally( () => {\n\t\t\t\t\t\t// As soon this promise is complete, clear the way for the\n\t\t\t\t\t\t// next one to happen immediately.\n\t\t\t\t\t\tactivePromise = null;\n\t\t\t\t\t\ttimeoutId = null;\n\t\t\t\t\t} );\n\t\t\t}, delayMS );\n\t\t} );\n\t};\n}\n"],
5
- "mappings": ";AAiBe,SAAR,cACN,MACA,SACyC;AACzC,MAAI;AACJ,MAAI;AAEJ,SAAO,eAAe,aAAc,MAAa;AAGhD,QAAK,CAAE,iBAAiB,CAAE,WAAY;AACrC,aAAO,IAAI,QAAmB,CAAE,SAAS,WAAY;AAEpD,wBAAgB,KAAM,GAAG,IAAK,EAC5B,KAAM,IAAK,aAAc;AACzB,kBAAS,GAAG,QAAS;AAAA,QACtB,CAAE,EACD,MAAO,CAAE,UAAW;AACpB,iBAAQ,KAAM;AAAA,QACf,CAAE,EACD,QAAS,MAAM;AAGf,0BAAgB;AAAA,QACjB,CAAE;AAAA,MACJ,CAAE;AAAA,IACH;AAEA,QAAK,eAAgB;AAEpB,YAAM;AAAA,IACP;AAIA,QAAK,WAAY;AAChB,mBAAc,SAAU;AACxB,kBAAY;AAAA,IACb;AAGA,WAAO,IAAI,QAAmB,CAAE,SAAS,WAAY;AAEpD,kBAAY,WAAY,MAAM;AAC7B,wBAAgB,KAAM,GAAG,IAAK,EAC5B,KAAM,IAAK,aAAc;AACzB,kBAAS,GAAG,QAAS;AAAA,QACtB,CAAE,EACD,MAAO,CAAE,UAAW;AACpB,iBAAQ,KAAM;AAAA,QACf,CAAE,EACD,QAAS,MAAM;AAGf,0BAAgB;AAChB,sBAAY;AAAA,QACb,CAAE;AAAA,MACJ,GAAG,OAAQ;AAAA,IACZ,CAAE;AAAA,EACH;AACD;",
6
- "names": []
7
- }
1
+ {"version":3,"file":"debounce-async.mjs","names":[],"sources":["../../src/create/debounce-async.ts"],"sourcesContent":["/**\n * Performs a leading edge debounce of async functions.\n *\n * If three functions are throttled at the same time:\n * - The first happens immediately.\n * - The second is never called.\n * - The third happens `delayMS` milliseconds after the first has resolved.\n *\n * This is distinct from `{ debounce } from @wordpress/compose` in that it\n * waits for promise resolution.\n *\n * @param func A function that returns a promise.\n * @param delayMS A delay in milliseconds.\n *\n * @return A function that debounce whatever function is passed\n * to it.\n */\nexport default function debounceAsync< Args extends unknown[], Result >(\n\tfunc: ( ...args: Args ) => Promise< Result >,\n\tdelayMS: number\n): ( ...args: Args ) => Promise< Result > {\n\tlet timeoutId: ReturnType< typeof setTimeout > | null | undefined;\n\tlet activePromise: Promise< void > | null | undefined;\n\n\treturn async function debounced( ...args: Args ) {\n\t\t// This is a leading edge debounce. If there's no promise or timeout\n\t\t// in progress, call the debounced function immediately.\n\t\tif ( ! activePromise && ! timeoutId ) {\n\t\t\treturn new Promise< Result >( ( resolve, reject ) => {\n\t\t\t\t// Keep a reference to the promise.\n\t\t\t\tactivePromise = func( ...args )\n\t\t\t\t\t.then( ( ...thenArgs ) => {\n\t\t\t\t\t\tresolve( ...thenArgs );\n\t\t\t\t\t} )\n\t\t\t\t\t.catch( ( error ) => {\n\t\t\t\t\t\treject( error );\n\t\t\t\t\t} )\n\t\t\t\t\t.finally( () => {\n\t\t\t\t\t\t// As soon this promise is complete, clear the way for the\n\t\t\t\t\t\t// next one to happen immediately.\n\t\t\t\t\t\tactivePromise = null;\n\t\t\t\t\t} );\n\t\t\t} );\n\t\t}\n\n\t\tif ( activePromise ) {\n\t\t\t// Let any active promises finish before queuing the next request.\n\t\t\tawait activePromise;\n\t\t}\n\n\t\t// Clear any active timeouts, abandoning any requests that have\n\t\t// been queued but not been made.\n\t\tif ( timeoutId ) {\n\t\t\tclearTimeout( timeoutId );\n\t\t\ttimeoutId = null;\n\t\t}\n\n\t\t// Trigger any trailing edge calls to the function.\n\t\treturn new Promise< Result >( ( resolve, reject ) => {\n\t\t\t// Schedule the next request but with a delay.\n\t\t\ttimeoutId = setTimeout( () => {\n\t\t\t\tactivePromise = func( ...args )\n\t\t\t\t\t.then( ( ...thenArgs ) => {\n\t\t\t\t\t\tresolve( ...thenArgs );\n\t\t\t\t\t} )\n\t\t\t\t\t.catch( ( error ) => {\n\t\t\t\t\t\treject( error );\n\t\t\t\t\t} )\n\t\t\t\t\t.finally( () => {\n\t\t\t\t\t\t// As soon this promise is complete, clear the way for the\n\t\t\t\t\t\t// next one to happen immediately.\n\t\t\t\t\t\tactivePromise = null;\n\t\t\t\t\t\ttimeoutId = null;\n\t\t\t\t\t} );\n\t\t\t}, delayMS );\n\t\t} );\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiBA,SAAwB,cACvB,MACA,SACyC;CACzC,IAAI;CACJ,IAAI;CAEJ,OAAO,eAAe,UAAW,GAAG,MAAa;EAGhD,IAAK,CAAE,iBAAiB,CAAE,WACzB,OAAO,IAAI,SAAqB,SAAS,WAAY;GAEpD,gBAAgB,KAAM,GAAG,IAAK,CAAC,CAC7B,MAAQ,GAAG,aAAc;IACzB,QAAS,GAAG,QAAS;GACtB,CAAE,CAAC,CACF,OAAS,UAAW;IACpB,OAAQ,KAAM;GACf,CAAE,CAAC,CACF,cAAe;IAGf,gBAAgB;GACjB,CAAE;EACJ,CAAE;EAGH,IAAK,eAEJ,MAAM;EAKP,IAAK,WAAY;GAChB,aAAc,SAAU;GACxB,YAAY;EACb;EAGA,OAAO,IAAI,SAAqB,SAAS,WAAY;GAEpD,YAAY,iBAAkB;IAC7B,gBAAgB,KAAM,GAAG,IAAK,CAAC,CAC7B,MAAQ,GAAG,aAAc;KACzB,QAAS,GAAG,QAAS;IACtB,CAAE,CAAC,CACF,OAAS,UAAW;KACpB,OAAQ,KAAM;IACf,CAAE,CAAC,CACF,cAAe;KAGf,gBAAgB;KAChB,YAAY;IACb,CAAE;GACJ,GAAG,OAAQ;EACZ,CAAE;CACH;AACD"}
@@ -1,59 +1,54 @@
1
- // packages/preferences-persistence/src/create/index.ts
2
1
  import apiFetch from "@wordpress/api-fetch";
3
2
  import debounceAsync from "./debounce-async.mjs";
4
3
  import getNewestData from "../get-newest-data.mjs";
5
4
  import isPreferencesData from "../is-preferences-data.mjs";
6
5
  import { writeStoredJSON } from "../local-storage.mjs";
7
- function create({
8
- preloadedData,
9
- localStorageRestoreKey = "WP_PREFERENCES_RESTORE_DATA",
10
- requestDebounceMS = 2500
11
- } = {}) {
12
- let cache = isPreferencesData(preloadedData) ? preloadedData : void 0;
13
- const debouncedApiFetch = debounceAsync(apiFetch, requestDebounceMS);
14
- async function get() {
15
- if (cache) {
16
- return cache;
17
- }
18
- const user = await apiFetch({
19
- path: "/wp/v2/users/me?context=edit"
20
- });
21
- cache = getNewestData(
22
- user?.meta?.persisted_preferences,
23
- localStorageRestoreKey
24
- ) ?? {};
25
- return cache;
26
- }
27
- function set(newData) {
28
- const dataWithTimestamp = {
29
- ...newData,
30
- _modified: (/* @__PURE__ */ new Date()).toISOString()
31
- };
32
- cache = dataWithTimestamp;
33
- writeStoredJSON(localStorageRestoreKey, dataWithTimestamp);
34
- debouncedApiFetch({
35
- path: "/wp/v2/users/me",
36
- method: "PUT",
37
- // `keepalive` will still send the request in the background,
38
- // even when a browser unload event might interrupt it.
39
- // This should hopefully make things more resilient.
40
- // This does have a size limit of 64kb, but the data is usually
41
- // much less.
42
- keepalive: true,
43
- data: {
44
- meta: {
45
- persisted_preferences: dataWithTimestamp
46
- }
47
- }
48
- }).catch(() => {
49
- });
50
- }
51
- return {
52
- get,
53
- set
54
- };
6
+ // packages/preferences-persistence/src/create/index.ts
7
+ /**
8
+ * Creates a persistence layer that stores data in WordPress user meta via the
9
+ * REST API.
10
+ *
11
+ * @param {CreateOptions} [options]
12
+ * @param {PreferencesData|null} [options.preloadedData] Any persisted preferences data that should be preloaded.
13
+ * When set, the persistence layer will avoid fetching data
14
+ * from the REST API.
15
+ * @param {string} [options.localStorageRestoreKey] The key to use for restoring the localStorage backup, used
16
+ * when the persistence layer calls `localStorage.getItem` or
17
+ * `localStorage.setItem`.
18
+ * @param {number} [options.requestDebounceMS] Debounce requests to the API so that they only occur at
19
+ * minimum every `requestDebounceMS` milliseconds, and don't
20
+ * swamp the server. Defaults to 2500ms.
21
+ *
22
+ * @return A persistence layer for WordPress user meta.
23
+ */
24
+ function create({ preloadedData, localStorageRestoreKey = "WP_PREFERENCES_RESTORE_DATA", requestDebounceMS = 2500 } = {}) {
25
+ let cache = isPreferencesData(preloadedData) ? preloadedData : void 0;
26
+ const debouncedApiFetch = debounceAsync(apiFetch, requestDebounceMS);
27
+ async function get() {
28
+ if (cache) return cache;
29
+ const user = await apiFetch({ path: "/wp/v2/users/me?context=edit" });
30
+ cache = getNewestData(user?.meta?.persisted_preferences, localStorageRestoreKey) ?? {};
31
+ return cache;
32
+ }
33
+ function set(newData) {
34
+ const dataWithTimestamp = {
35
+ ...newData,
36
+ _modified: (/* @__PURE__ */ new Date()).toISOString()
37
+ };
38
+ cache = dataWithTimestamp;
39
+ writeStoredJSON(localStorageRestoreKey, dataWithTimestamp);
40
+ debouncedApiFetch({
41
+ path: "/wp/v2/users/me",
42
+ method: "PUT",
43
+ keepalive: true,
44
+ data: { meta: { persisted_preferences: dataWithTimestamp } }
45
+ }).catch(() => {});
46
+ }
47
+ return {
48
+ get,
49
+ set
50
+ };
55
51
  }
56
- export {
57
- create as default
58
- };
59
- //# sourceMappingURL=index.mjs.map
52
+ export { create as default };
53
+
54
+ //# sourceMappingURL=index.mjs.map
@@ -1,7 +1 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/create/index.ts"],
4
- "sourcesContent": ["import apiFetch from '@wordpress/api-fetch';\nimport debounceAsync from './debounce-async';\nimport getNewestData from '../get-newest-data';\nimport isPreferencesData from '../is-preferences-data';\nimport { writeStoredJSON } from '../local-storage';\nimport type {\n\tCreateOptions,\n\tPersistenceLayer,\n\tPreferencesData,\n} from '../types';\n\n/**\n * Creates a persistence layer that stores data in WordPress user meta via the\n * REST API.\n *\n * @param {CreateOptions} [options]\n * @param {PreferencesData|null} [options.preloadedData] Any persisted preferences data that should be preloaded.\n * When set, the persistence layer will avoid fetching data\n * from the REST API.\n * @param {string} [options.localStorageRestoreKey] The key to use for restoring the localStorage backup, used\n * when the persistence layer calls `localStorage.getItem` or\n * `localStorage.setItem`.\n * @param {number} [options.requestDebounceMS] Debounce requests to the API so that they only occur at\n * minimum every `requestDebounceMS` milliseconds, and don't\n * swamp the server. Defaults to 2500ms.\n *\n * @return A persistence layer for WordPress user meta.\n */\nexport default function create( {\n\tpreloadedData,\n\tlocalStorageRestoreKey = 'WP_PREFERENCES_RESTORE_DATA',\n\trequestDebounceMS = 2500,\n}: CreateOptions = {} ): PersistenceLayer {\n\tlet cache = isPreferencesData( preloadedData ) ? preloadedData : undefined;\n\tconst debouncedApiFetch = debounceAsync( apiFetch, requestDebounceMS );\n\n\tasync function get() {\n\t\tif ( cache ) {\n\t\t\treturn cache;\n\t\t}\n\n\t\tconst user = await apiFetch< {\n\t\t\tmeta?: { persisted_preferences?: unknown };\n\t\t} >( {\n\t\t\tpath: '/wp/v2/users/me?context=edit',\n\t\t} );\n\n\t\tcache =\n\t\t\tgetNewestData(\n\t\t\t\tuser?.meta?.persisted_preferences,\n\t\t\t\tlocalStorageRestoreKey\n\t\t\t) ?? {};\n\n\t\treturn cache;\n\t}\n\n\tfunction set( newData: PreferencesData ) {\n\t\tconst dataWithTimestamp = {\n\t\t\t...newData,\n\t\t\t_modified: new Date().toISOString(),\n\t\t};\n\t\tcache = dataWithTimestamp;\n\n\t\t// Store data in local storage as a fallback. If for some reason the\n\t\t// api request does not complete or becomes unavailable, this data\n\t\t// can be used to restore preferences.\n\t\twriteStoredJSON( localStorageRestoreKey, dataWithTimestamp );\n\n\t\t// The user meta endpoint seems susceptible to errors when consecutive\n\t\t// requests are made in quick succession. Ensure there's a gap between\n\t\t// any consecutive requests.\n\t\t//\n\t\t// Catch and do nothing with errors from the REST API.\n\t\tdebouncedApiFetch( {\n\t\t\tpath: '/wp/v2/users/me',\n\t\t\tmethod: 'PUT',\n\t\t\t// `keepalive` will still send the request in the background,\n\t\t\t// even when a browser unload event might interrupt it.\n\t\t\t// This should hopefully make things more resilient.\n\t\t\t// This does have a size limit of 64kb, but the data is usually\n\t\t\t// much less.\n\t\t\tkeepalive: true,\n\t\t\tdata: {\n\t\t\t\tmeta: {\n\t\t\t\t\tpersisted_preferences: dataWithTimestamp,\n\t\t\t\t},\n\t\t\t},\n\t\t} ).catch( () => {} );\n\t}\n\n\treturn {\n\t\tget,\n\t\tset,\n\t};\n}\n"],
5
- "mappings": ";AAAA,OAAO,cAAc;AACrB,OAAO,mBAAmB;AAC1B,OAAO,mBAAmB;AAC1B,OAAO,uBAAuB;AAC9B,SAAS,uBAAuB;AAwBjB,SAAR,OAAyB;AAAA,EAC/B;AAAA,EACA,yBAAyB;AAAA,EACzB,oBAAoB;AACrB,IAAmB,CAAC,GAAsB;AACzC,MAAI,QAAQ,kBAAmB,aAAc,IAAI,gBAAgB;AACjE,QAAM,oBAAoB,cAAe,UAAU,iBAAkB;AAErE,iBAAe,MAAM;AACpB,QAAK,OAAQ;AACZ,aAAO;AAAA,IACR;AAEA,UAAM,OAAO,MAAM,SAEd;AAAA,MACJ,MAAM;AAAA,IACP,CAAE;AAEF,YACC;AAAA,MACC,MAAM,MAAM;AAAA,MACZ;AAAA,IACD,KAAK,CAAC;AAEP,WAAO;AAAA,EACR;AAEA,WAAS,IAAK,SAA2B;AACxC,UAAM,oBAAoB;AAAA,MACzB,GAAG;AAAA,MACH,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,IACnC;AACA,YAAQ;AAKR,oBAAiB,wBAAwB,iBAAkB;AAO3D,sBAAmB;AAAA,MAClB,MAAM;AAAA,MACN,QAAQ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAMR,WAAW;AAAA,MACX,MAAM;AAAA,QACL,MAAM;AAAA,UACL,uBAAuB;AAAA,QACxB;AAAA,MACD;AAAA,IACD,CAAE,EAAE,MAAO,MAAM;AAAA,IAAC,CAAE;AAAA,EACrB;AAEA,SAAO;AAAA,IACN;AAAA,IACA;AAAA,EACD;AACD;",
6
- "names": []
7
- }
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/create/index.ts"],"sourcesContent":["import apiFetch from '@wordpress/api-fetch';\nimport debounceAsync from './debounce-async';\nimport getNewestData from '../get-newest-data';\nimport isPreferencesData from '../is-preferences-data';\nimport { writeStoredJSON } from '../local-storage';\nimport type {\n\tCreateOptions,\n\tPersistenceLayer,\n\tPreferencesData,\n} from '../types';\n\n/**\n * Creates a persistence layer that stores data in WordPress user meta via the\n * REST API.\n *\n * @param {CreateOptions} [options]\n * @param {PreferencesData|null} [options.preloadedData] Any persisted preferences data that should be preloaded.\n * When set, the persistence layer will avoid fetching data\n * from the REST API.\n * @param {string} [options.localStorageRestoreKey] The key to use for restoring the localStorage backup, used\n * when the persistence layer calls `localStorage.getItem` or\n * `localStorage.setItem`.\n * @param {number} [options.requestDebounceMS] Debounce requests to the API so that they only occur at\n * minimum every `requestDebounceMS` milliseconds, and don't\n * swamp the server. Defaults to 2500ms.\n *\n * @return A persistence layer for WordPress user meta.\n */\nexport default function create( {\n\tpreloadedData,\n\tlocalStorageRestoreKey = 'WP_PREFERENCES_RESTORE_DATA',\n\trequestDebounceMS = 2500,\n}: CreateOptions = {} ): PersistenceLayer {\n\tlet cache = isPreferencesData( preloadedData ) ? preloadedData : undefined;\n\tconst debouncedApiFetch = debounceAsync( apiFetch, requestDebounceMS );\n\n\tasync function get() {\n\t\tif ( cache ) {\n\t\t\treturn cache;\n\t\t}\n\n\t\tconst user = await apiFetch< {\n\t\t\tmeta?: { persisted_preferences?: unknown };\n\t\t} >( {\n\t\t\tpath: '/wp/v2/users/me?context=edit',\n\t\t} );\n\n\t\tcache =\n\t\t\tgetNewestData(\n\t\t\t\tuser?.meta?.persisted_preferences,\n\t\t\t\tlocalStorageRestoreKey\n\t\t\t) ?? {};\n\n\t\treturn cache;\n\t}\n\n\tfunction set( newData: PreferencesData ) {\n\t\tconst dataWithTimestamp = {\n\t\t\t...newData,\n\t\t\t_modified: new Date().toISOString(),\n\t\t};\n\t\tcache = dataWithTimestamp;\n\n\t\t// Store data in local storage as a fallback. If for some reason the\n\t\t// api request does not complete or becomes unavailable, this data\n\t\t// can be used to restore preferences.\n\t\twriteStoredJSON( localStorageRestoreKey, dataWithTimestamp );\n\n\t\t// The user meta endpoint seems susceptible to errors when consecutive\n\t\t// requests are made in quick succession. Ensure there's a gap between\n\t\t// any consecutive requests.\n\t\t//\n\t\t// Catch and do nothing with errors from the REST API.\n\t\tdebouncedApiFetch( {\n\t\t\tpath: '/wp/v2/users/me',\n\t\t\tmethod: 'PUT',\n\t\t\t// `keepalive` will still send the request in the background,\n\t\t\t// even when a browser unload event might interrupt it.\n\t\t\t// This should hopefully make things more resilient.\n\t\t\t// This does have a size limit of 64kb, but the data is usually\n\t\t\t// much less.\n\t\t\tkeepalive: true,\n\t\t\tdata: {\n\t\t\t\tmeta: {\n\t\t\t\t\tpersisted_preferences: dataWithTimestamp,\n\t\t\t\t},\n\t\t\t},\n\t\t} ).catch( () => {} );\n\t}\n\n\treturn {\n\t\tget,\n\t\tset,\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAwB,OAAQ,EAC/B,eACA,yBAAyB,+BACzB,oBAAoB,SACF,CAAC,GAAsB;CACzC,IAAI,QAAQ,kBAAmB,aAAc,IAAI,gBAAgB,KAAA;CACjE,MAAM,oBAAoB,cAAe,UAAU,iBAAkB;CAErE,eAAe,MAAM;EACpB,IAAK,OACJ,OAAO;EAGR,MAAM,OAAO,MAAM,SAEd,EACJ,MAAM,+BACP,CAAE;EAEF,QACC,cACC,MAAM,MAAM,uBACZ,sBACD,KAAK,CAAC;EAEP,OAAO;CACR;CAEA,SAAS,IAAK,SAA2B;EACxC,MAAM,oBAAoB;GACzB,GAAG;GACH,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;EACnC;EACA,QAAQ;EAKR,gBAAiB,wBAAwB,iBAAkB;EAO3D,kBAAmB;GAClB,MAAM;GACN,QAAQ;GAMR,WAAW;GACX,MAAM,EACL,MAAM,EACL,uBAAuB,kBACxB,EACD;EACD,CAAE,CAAC,CAAC,YAAa,CAAC,CAAE;CACrB;CAEA,OAAO;EACN;EACA;CACD;AACD"}
@@ -1,22 +1,36 @@
1
- // packages/preferences-persistence/src/get-newest-data.ts
2
1
  import isPreferencesData from "./is-preferences-data.mjs";
3
2
  import { readStoredJSON } from "./local-storage.mjs";
4
3
  import convertPreferencesPackageData from "./migrations/preferences-package-data/index.mjs";
4
+ // packages/preferences-persistence/src/get-newest-data.ts
5
+ /**
6
+ * Picks the most recently modified preferences from the server data and the
7
+ * local storage backup, ignoring either when it is not a preferences object.
8
+ *
9
+ * @param serverData Preferences data from the server.
10
+ * @param localStorageRestoreKey The key of the local storage backup.
11
+ *
12
+ * @return The newest preferences data, or `null` when neither is valid.
13
+ */
5
14
  function pickNewestData(serverData, localStorageRestoreKey) {
6
- const storedData = readStoredJSON(localStorageRestoreKey);
7
- const localData = isPreferencesData(storedData) ? storedData : null;
8
- if (!isPreferencesData(serverData)) {
9
- return localData;
10
- }
11
- const serverModified = Date.parse(serverData._modified ?? "") || 0;
12
- const localModified = Date.parse(localData?._modified ?? "") || 0;
13
- return localData && localModified > serverModified ? localData : serverData;
15
+ const storedData = readStoredJSON(localStorageRestoreKey);
16
+ const localData = isPreferencesData(storedData) ? storedData : null;
17
+ if (!isPreferencesData(serverData)) return localData;
18
+ const serverModified = Date.parse(serverData._modified ?? "") || 0;
19
+ const localModified = Date.parse(localData?._modified ?? "") || 0;
20
+ return localData && localModified > serverModified ? localData : serverData;
14
21
  }
22
+ /**
23
+ * Gets the newest persisted preferences, migrated to the current format.
24
+ *
25
+ * @param serverData Preferences data from the server.
26
+ * @param localStorageRestoreKey The key of the local storage backup.
27
+ *
28
+ * @return The migrated preferences, or `undefined` when there are none.
29
+ */
15
30
  function getNewestData(serverData, localStorageRestoreKey) {
16
- const newestData = pickNewestData(serverData, localStorageRestoreKey);
17
- return newestData ? convertPreferencesPackageData(newestData) : void 0;
31
+ const newestData = pickNewestData(serverData, localStorageRestoreKey);
32
+ return newestData ? convertPreferencesPackageData(newestData) : void 0;
18
33
  }
19
- export {
20
- getNewestData as default
21
- };
22
- //# sourceMappingURL=get-newest-data.mjs.map
34
+ export { getNewestData as default };
35
+
36
+ //# sourceMappingURL=get-newest-data.mjs.map
@@ -1,7 +1 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/get-newest-data.ts"],
4
- "sourcesContent": ["import isPreferencesData from './is-preferences-data';\nimport { readStoredJSON } from './local-storage';\nimport convertPreferencesPackageData from './migrations/preferences-package-data';\nimport type { PreferencesData, ScopedPreferences } from './types';\n\n/**\n * Picks the most recently modified preferences from the server data and the\n * local storage backup, ignoring either when it is not a preferences object.\n *\n * @param serverData Preferences data from the server.\n * @param localStorageRestoreKey The key of the local storage backup.\n *\n * @return The newest preferences data, or `null` when neither is valid.\n */\nfunction pickNewestData(\n\tserverData: unknown,\n\tlocalStorageRestoreKey: string\n): PreferencesData | null {\n\tconst storedData = readStoredJSON( localStorageRestoreKey );\n\tconst localData = isPreferencesData( storedData ) ? storedData : null;\n\tif ( ! isPreferencesData( serverData ) ) {\n\t\treturn localData;\n\t}\n\n\t// Date parse returns NaN for invalid input. Coerce anything invalid\n\t// into a conveniently comparable zero.\n\tconst serverModified = Date.parse( serverData._modified ?? '' ) || 0;\n\tconst localModified = Date.parse( localData?._modified ?? '' ) || 0;\n\n\t// Prefer server data when it is at least as recent.\n\treturn localData && localModified > serverModified ? localData : serverData;\n}\n\n/**\n * Gets the newest persisted preferences, migrated to the current format.\n *\n * @param serverData Preferences data from the server.\n * @param localStorageRestoreKey The key of the local storage backup.\n *\n * @return The migrated preferences, or `undefined` when there are none.\n */\nexport default function getNewestData(\n\tserverData: unknown,\n\tlocalStorageRestoreKey: string\n): ScopedPreferences | undefined {\n\tconst newestData = pickNewestData( serverData, localStorageRestoreKey );\n\treturn newestData\n\t\t? convertPreferencesPackageData( newestData as ScopedPreferences )\n\t\t: undefined;\n}\n"],
5
- "mappings": ";AAAA,OAAO,uBAAuB;AAC9B,SAAS,sBAAsB;AAC/B,OAAO,mCAAmC;AAY1C,SAAS,eACR,YACA,wBACyB;AACzB,QAAM,aAAa,eAAgB,sBAAuB;AAC1D,QAAM,YAAY,kBAAmB,UAAW,IAAI,aAAa;AACjE,MAAK,CAAE,kBAAmB,UAAW,GAAI;AACxC,WAAO;AAAA,EACR;AAIA,QAAM,iBAAiB,KAAK,MAAO,WAAW,aAAa,EAAG,KAAK;AACnE,QAAM,gBAAgB,KAAK,MAAO,WAAW,aAAa,EAAG,KAAK;AAGlE,SAAO,aAAa,gBAAgB,iBAAiB,YAAY;AAClE;AAUe,SAAR,cACN,YACA,wBACgC;AAChC,QAAM,aAAa,eAAgB,YAAY,sBAAuB;AACtE,SAAO,aACJ,8BAA+B,UAAgC,IAC/D;AACJ;",
6
- "names": []
7
- }
1
+ {"version":3,"file":"get-newest-data.mjs","names":[],"sources":["../src/get-newest-data.ts"],"sourcesContent":["import isPreferencesData from './is-preferences-data';\nimport { readStoredJSON } from './local-storage';\nimport convertPreferencesPackageData from './migrations/preferences-package-data';\nimport type { PreferencesData, ScopedPreferences } from './types';\n\n/**\n * Picks the most recently modified preferences from the server data and the\n * local storage backup, ignoring either when it is not a preferences object.\n *\n * @param serverData Preferences data from the server.\n * @param localStorageRestoreKey The key of the local storage backup.\n *\n * @return The newest preferences data, or `null` when neither is valid.\n */\nfunction pickNewestData(\n\tserverData: unknown,\n\tlocalStorageRestoreKey: string\n): PreferencesData | null {\n\tconst storedData = readStoredJSON( localStorageRestoreKey );\n\tconst localData = isPreferencesData( storedData ) ? storedData : null;\n\tif ( ! isPreferencesData( serverData ) ) {\n\t\treturn localData;\n\t}\n\n\t// Date parse returns NaN for invalid input. Coerce anything invalid\n\t// into a conveniently comparable zero.\n\tconst serverModified = Date.parse( serverData._modified ?? '' ) || 0;\n\tconst localModified = Date.parse( localData?._modified ?? '' ) || 0;\n\n\t// Prefer server data when it is at least as recent.\n\treturn localData && localModified > serverModified ? localData : serverData;\n}\n\n/**\n * Gets the newest persisted preferences, migrated to the current format.\n *\n * @param serverData Preferences data from the server.\n * @param localStorageRestoreKey The key of the local storage backup.\n *\n * @return The migrated preferences, or `undefined` when there are none.\n */\nexport default function getNewestData(\n\tserverData: unknown,\n\tlocalStorageRestoreKey: string\n): ScopedPreferences | undefined {\n\tconst newestData = pickNewestData( serverData, localStorageRestoreKey );\n\treturn newestData\n\t\t? convertPreferencesPackageData( newestData as ScopedPreferences )\n\t\t: undefined;\n}\n"],"mappings":";;;;;;;;;;;;;AAcA,SAAS,eACR,YACA,wBACyB;CACzB,MAAM,aAAa,eAAgB,sBAAuB;CAC1D,MAAM,YAAY,kBAAmB,UAAW,IAAI,aAAa;CACjE,IAAK,CAAE,kBAAmB,UAAW,GACpC,OAAO;CAKR,MAAM,iBAAiB,KAAK,MAAO,WAAW,aAAa,EAAG,KAAK;CACnE,MAAM,gBAAgB,KAAK,MAAO,WAAW,aAAa,EAAG,KAAK;CAGlE,OAAO,aAAa,gBAAgB,iBAAiB,YAAY;AAClE;;;;;;;;;AAUA,SAAwB,cACvB,YACA,wBACgC;CAChC,MAAM,aAAa,eAAgB,YAAY,sBAAuB;CACtE,OAAO,aACJ,8BAA+B,UAAgC,IAC/D,KAAA;AACJ"}
@@ -1,20 +1,28 @@
1
- // packages/preferences-persistence/src/index.ts
2
1
  import create from "./create/index.mjs";
3
2
  import convertLegacyLocalStorageData from "./migrations/legacy-local-storage-data/index.mjs";
4
3
  import getNewestData from "./get-newest-data.mjs";
4
+ // packages/preferences-persistence/src/index.ts
5
+ /**
6
+ * Creates the persistence layer with preloaded data.
7
+ *
8
+ * It prioritizes any data from the server, but falls back first to localStorage
9
+ * restore data, and then to any legacy data.
10
+ *
11
+ * This function is used internally by WordPress in an inline script, so
12
+ * prefixed with `__unstable`.
13
+ *
14
+ * @param serverData Preferences data preloaded from the server.
15
+ * @param userId The user id.
16
+ *
17
+ * @return The persistence layer initialized with the preloaded data.
18
+ */
5
19
  function __unstableCreatePersistenceLayer(serverData, userId) {
6
- const localStorageRestoreKey = `WP_PREFERENCES_USER_${userId}`;
7
- return create({
8
- /*
9
- * Fall back to data in the legacy format from the old persistence system.
10
- * The server data is already preloaded, so fetching it again is redundant.
11
- */
12
- preloadedData: getNewestData(serverData, localStorageRestoreKey) ?? convertLegacyLocalStorageData(userId) ?? {},
13
- localStorageRestoreKey
14
- });
20
+ const localStorageRestoreKey = `WP_PREFERENCES_USER_${userId}`;
21
+ return create({
22
+ preloadedData: getNewestData(serverData, localStorageRestoreKey) ?? convertLegacyLocalStorageData(userId) ?? {},
23
+ localStorageRestoreKey
24
+ });
15
25
  }
16
- export {
17
- __unstableCreatePersistenceLayer,
18
- create
19
- };
20
- //# sourceMappingURL=index.mjs.map
26
+ export { __unstableCreatePersistenceLayer, create };
27
+
28
+ //# sourceMappingURL=index.mjs.map
@@ -1,7 +1 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/index.ts"],
4
- "sourcesContent": ["import create from './create';\nimport convertLegacyLocalStorageData from './migrations/legacy-local-storage-data';\nimport getNewestData from './get-newest-data';\nimport type { PersistenceLayer } from './types';\n\nexport { create };\n\nexport type * from './types';\n\n/**\n * Creates the persistence layer with preloaded data.\n *\n * It prioritizes any data from the server, but falls back first to localStorage\n * restore data, and then to any legacy data.\n *\n * This function is used internally by WordPress in an inline script, so\n * prefixed with `__unstable`.\n *\n * @param serverData Preferences data preloaded from the server.\n * @param userId The user id.\n *\n * @return The persistence layer initialized with the preloaded data.\n */\nexport function __unstableCreatePersistenceLayer(\n\tserverData: unknown,\n\tuserId: string | number\n): PersistenceLayer {\n\tconst localStorageRestoreKey = `WP_PREFERENCES_USER_${ userId }`;\n\treturn create( {\n\t\t/*\n\t\t * Fall back to data in the legacy format from the old persistence system.\n\t\t * The server data is already preloaded, so fetching it again is redundant.\n\t\t */\n\t\tpreloadedData:\n\t\t\tgetNewestData( serverData, localStorageRestoreKey ) ??\n\t\t\tconvertLegacyLocalStorageData( userId ) ??\n\t\t\t{},\n\t\tlocalStorageRestoreKey,\n\t} );\n}\n"],
5
- "mappings": ";AAAA,OAAO,YAAY;AACnB,OAAO,mCAAmC;AAC1C,OAAO,mBAAmB;AAqBnB,SAAS,iCACf,YACA,QACmB;AACnB,QAAM,yBAAyB,uBAAwB,MAAO;AAC9D,SAAO,OAAQ;AAAA;AAAA;AAAA;AAAA;AAAA,IAKd,eACC,cAAe,YAAY,sBAAuB,KAClD,8BAA+B,MAAO,KACtC,CAAC;AAAA,IACF;AAAA,EACD,CAAE;AACH;",
6
- "names": []
7
- }
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["import create from './create';\nimport convertLegacyLocalStorageData from './migrations/legacy-local-storage-data';\nimport getNewestData from './get-newest-data';\nimport type { PersistenceLayer } from './types';\n\nexport { create };\n\nexport type * from './types';\n\n/**\n * Creates the persistence layer with preloaded data.\n *\n * It prioritizes any data from the server, but falls back first to localStorage\n * restore data, and then to any legacy data.\n *\n * This function is used internally by WordPress in an inline script, so\n * prefixed with `__unstable`.\n *\n * @param serverData Preferences data preloaded from the server.\n * @param userId The user id.\n *\n * @return The persistence layer initialized with the preloaded data.\n */\nexport function __unstableCreatePersistenceLayer(\n\tserverData: unknown,\n\tuserId: string | number\n): PersistenceLayer {\n\tconst localStorageRestoreKey = `WP_PREFERENCES_USER_${ userId }`;\n\treturn create( {\n\t\t/*\n\t\t * Fall back to data in the legacy format from the old persistence system.\n\t\t * The server data is already preloaded, so fetching it again is redundant.\n\t\t */\n\t\tpreloadedData:\n\t\t\tgetNewestData( serverData, localStorageRestoreKey ) ??\n\t\t\tconvertLegacyLocalStorageData( userId ) ??\n\t\t\t{},\n\t\tlocalStorageRestoreKey,\n\t} );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAuBA,SAAgB,iCACf,YACA,QACmB;CACnB,MAAM,yBAAyB,uBAAwB;CACvD,OAAO,OAAQ;EAKd,eACC,cAAe,YAAY,sBAAuB,KAClD,8BAA+B,MAAO,KACtC,CAAC;EACF;CACD,CAAE;AACH"}
@@ -1,8 +1,15 @@
1
1
  // packages/preferences-persistence/src/is-preferences-data.ts
2
+ /**
3
+ * Checks whether persisted data is a preferences object. Empty user meta
4
+ * reaches the client as `[]` or `''`, which must not be used as preferences.
5
+ *
6
+ * @param data The persisted data.
7
+ *
8
+ * @return Whether the data is a preferences object.
9
+ */
2
10
  function isPreferencesData(data) {
3
- return !!data && typeof data === "object" && !Array.isArray(data);
11
+ return !!data && typeof data === "object" && !Array.isArray(data);
4
12
  }
5
- export {
6
- isPreferencesData as default
7
- };
8
- //# sourceMappingURL=is-preferences-data.mjs.map
13
+ export { isPreferencesData as default };
14
+
15
+ //# sourceMappingURL=is-preferences-data.mjs.map
@@ -1,7 +1 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/is-preferences-data.ts"],
4
- "sourcesContent": ["import type { PreferencesData } from './types';\n\n/**\n * Checks whether persisted data is a preferences object. Empty user meta\n * reaches the client as `[]` or `''`, which must not be used as preferences.\n *\n * @param data The persisted data.\n *\n * @return Whether the data is a preferences object.\n */\nexport default function isPreferencesData(\n\tdata: unknown\n): data is PreferencesData {\n\treturn !! data && typeof data === 'object' && ! Array.isArray( data );\n}\n"],
5
- "mappings": ";AAUe,SAAR,kBACN,MAC0B;AAC1B,SAAO,CAAC,CAAE,QAAQ,OAAO,SAAS,YAAY,CAAE,MAAM,QAAS,IAAK;AACrE;",
6
- "names": []
7
- }
1
+ {"version":3,"file":"is-preferences-data.mjs","names":[],"sources":["../src/is-preferences-data.ts"],"sourcesContent":["import type { PreferencesData } from './types';\n\n/**\n * Checks whether persisted data is a preferences object. Empty user meta\n * reaches the client as `[]` or `''`, which must not be used as preferences.\n *\n * @param data The persisted data.\n *\n * @return Whether the data is a preferences object.\n */\nexport default function isPreferencesData(\n\tdata: unknown\n): data is PreferencesData {\n\treturn !! data && typeof data === 'object' && ! Array.isArray( data );\n}\n"],"mappings":";;;;;;;;;AAUA,SAAwB,kBACvB,MAC0B;CAC1B,OAAO,CAAC,CAAE,QAAQ,OAAO,SAAS,YAAY,CAAE,MAAM,QAAS,IAAK;AACrE"}
@@ -1,20 +1,33 @@
1
1
  // packages/preferences-persistence/src/local-storage.ts
2
+ /**
3
+ * Reads and parses a JSON value from local storage.
4
+ *
5
+ * @param key The local storage key.
6
+ *
7
+ * @return The parsed value, or `null` when the value is missing or invalid,
8
+ * or local storage is unavailable.
9
+ */
2
10
  function readStoredJSON(key) {
3
- try {
4
- const value = window.localStorage.getItem(key);
5
- return value === null ? null : JSON.parse(value);
6
- } catch {
7
- return null;
8
- }
11
+ try {
12
+ const value = window.localStorage.getItem(key);
13
+ return value === null ? null : JSON.parse(value);
14
+ } catch {
15
+ return null;
16
+ }
9
17
  }
18
+ /**
19
+ * Stores a value in local storage as JSON.
20
+ *
21
+ * Failures, such as blocked storage or an exceeded quota, are ignored.
22
+ *
23
+ * @param key The local storage key.
24
+ * @param value The value to store.
25
+ */
10
26
  function writeStoredJSON(key, value) {
11
- try {
12
- window.localStorage.setItem(key, JSON.stringify(value));
13
- } catch {
14
- }
27
+ try {
28
+ window.localStorage.setItem(key, JSON.stringify(value));
29
+ } catch {}
15
30
  }
16
- export {
17
- readStoredJSON,
18
- writeStoredJSON
19
- };
20
- //# sourceMappingURL=local-storage.mjs.map
31
+ export { readStoredJSON, writeStoredJSON };
32
+
33
+ //# sourceMappingURL=local-storage.mjs.map
@@ -1,7 +1 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/local-storage.ts"],
4
- "sourcesContent": ["/**\n * Reads and parses a JSON value from local storage.\n *\n * @param key The local storage key.\n *\n * @return The parsed value, or `null` when the value is missing or invalid,\n * or local storage is unavailable.\n */\nexport function readStoredJSON( key: string ): unknown {\n\ttry {\n\t\tconst value = window.localStorage.getItem( key );\n\t\treturn value === null ? null : JSON.parse( value );\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Stores a value in local storage as JSON.\n *\n * Failures, such as blocked storage or an exceeded quota, are ignored.\n *\n * @param key The local storage key.\n * @param value The value to store.\n */\nexport function writeStoredJSON( key: string, value: unknown ) {\n\ttry {\n\t\twindow.localStorage.setItem( key, JSON.stringify( value ) );\n\t} catch {}\n}\n"],
5
- "mappings": ";AAQO,SAAS,eAAgB,KAAuB;AACtD,MAAI;AACH,UAAM,QAAQ,OAAO,aAAa,QAAS,GAAI;AAC/C,WAAO,UAAU,OAAO,OAAO,KAAK,MAAO,KAAM;AAAA,EAClD,QAAQ;AACP,WAAO;AAAA,EACR;AACD;AAUO,SAAS,gBAAiB,KAAa,OAAiB;AAC9D,MAAI;AACH,WAAO,aAAa,QAAS,KAAK,KAAK,UAAW,KAAM,CAAE;AAAA,EAC3D,QAAQ;AAAA,EAAC;AACV;",
6
- "names": []
7
- }
1
+ {"version":3,"file":"local-storage.mjs","names":[],"sources":["../src/local-storage.ts"],"sourcesContent":["/**\n * Reads and parses a JSON value from local storage.\n *\n * @param key The local storage key.\n *\n * @return The parsed value, or `null` when the value is missing or invalid,\n * or local storage is unavailable.\n */\nexport function readStoredJSON( key: string ): unknown {\n\ttry {\n\t\tconst value = window.localStorage.getItem( key );\n\t\treturn value === null ? null : JSON.parse( value );\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Stores a value in local storage as JSON.\n *\n * Failures, such as blocked storage or an exceeded quota, are ignored.\n *\n * @param key The local storage key.\n * @param value The value to store.\n */\nexport function writeStoredJSON( key: string, value: unknown ) {\n\ttry {\n\t\twindow.localStorage.setItem( key, JSON.stringify( value ) );\n\t} catch {}\n}\n"],"mappings":";;;;;;;;;AAQA,SAAgB,eAAgB,KAAuB;CACtD,IAAI;EACH,MAAM,QAAQ,OAAO,aAAa,QAAS,GAAI;EAC/C,OAAO,UAAU,OAAO,OAAO,KAAK,MAAO,KAAM;CAClD,QAAQ;EACP,OAAO;CACR;AACD;;;;;;;;;AAUA,SAAgB,gBAAiB,KAAa,OAAiB;CAC9D,IAAI;EACH,OAAO,aAAa,QAAS,KAAK,KAAK,UAAW,KAAM,CAAE;CAC3D,QAAQ,CAAC;AACV"}
@@ -1,21 +1,47 @@
1
1
  // packages/preferences-persistence/src/migrations/legacy-local-storage-data/convert-edit-post-panels.ts
2
+ /**
3
+ * Convert the post editor's panels state from:
4
+ * ```
5
+ * {
6
+ * panels: {
7
+ * tags: {
8
+ * enabled: true,
9
+ * opened: true,
10
+ * },
11
+ * permalinks: {
12
+ * enabled: false,
13
+ * opened: false,
14
+ * },
15
+ * },
16
+ * }
17
+ * ```
18
+ *
19
+ * to a new, more concise data structure:
20
+ * {
21
+ * inactivePanels: [
22
+ * 'permalinks',
23
+ * ],
24
+ * openPanels: [
25
+ * 'tags',
26
+ * ],
27
+ * }
28
+ *
29
+ * @param preferences A preferences object.
30
+ *
31
+ * @return The converted data.
32
+ */
2
33
  function convertEditPostPanels(preferences) {
3
- const panels = preferences?.panels ?? {};
4
- return Object.keys(panels).reduce(
5
- (convertedData, panelName) => {
6
- const panel = panels[panelName];
7
- if (panel?.enabled === false) {
8
- convertedData.inactivePanels.push(panelName);
9
- }
10
- if (panel?.opened === true) {
11
- convertedData.openPanels.push(panelName);
12
- }
13
- return convertedData;
14
- },
15
- { inactivePanels: [], openPanels: [] }
16
- );
34
+ const panels = preferences?.panels ?? {};
35
+ return Object.keys(panels).reduce((convertedData, panelName) => {
36
+ const panel = panels[panelName];
37
+ if (panel?.enabled === false) convertedData.inactivePanels.push(panelName);
38
+ if (panel?.opened === true) convertedData.openPanels.push(panelName);
39
+ return convertedData;
40
+ }, {
41
+ inactivePanels: [],
42
+ openPanels: []
43
+ });
17
44
  }
18
- export {
19
- convertEditPostPanels as default
20
- };
21
- //# sourceMappingURL=convert-edit-post-panels.mjs.map
45
+ export { convertEditPostPanels as default };
46
+
47
+ //# sourceMappingURL=convert-edit-post-panels.mjs.map
@@ -1,7 +1 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../src/migrations/legacy-local-storage-data/convert-edit-post-panels.ts"],
4
- "sourcesContent": ["import type { ScopePreferences } from '../../types';\nimport type { EditPostPanels, LegacyEditPostPanel } from './types';\n\n/**\n * Convert the post editor's panels state from:\n * ```\n * {\n * panels: {\n * tags: {\n * enabled: true,\n * opened: true,\n * },\n * permalinks: {\n * enabled: false,\n * opened: false,\n * },\n * },\n * }\n * ```\n *\n * to a new, more concise data structure:\n * {\n * inactivePanels: [\n * 'permalinks',\n * ],\n * openPanels: [\n * 'tags',\n * ],\n * }\n *\n * @param preferences A preferences object.\n *\n * @return The converted data.\n */\nexport default function convertEditPostPanels(\n\tpreferences: ScopePreferences\n): EditPostPanels {\n\tconst panels = ( preferences?.panels ?? {} ) as Record<\n\t\tstring,\n\t\tLegacyEditPostPanel | undefined\n\t>;\n\treturn Object.keys( panels ).reduce< EditPostPanels >(\n\t\t( convertedData, panelName ) => {\n\t\t\tconst panel = panels[ panelName ];\n\n\t\t\tif ( panel?.enabled === false ) {\n\t\t\t\tconvertedData.inactivePanels.push( panelName );\n\t\t\t}\n\n\t\t\tif ( panel?.opened === true ) {\n\t\t\t\tconvertedData.openPanels.push( panelName );\n\t\t\t}\n\n\t\t\treturn convertedData;\n\t\t},\n\t\t{ inactivePanels: [], openPanels: [] }\n\t);\n}\n"],
5
- "mappings": ";AAkCe,SAAR,sBACN,aACiB;AACjB,QAAM,SAAW,aAAa,UAAU,CAAC;AAIzC,SAAO,OAAO,KAAM,MAAO,EAAE;AAAA,IAC5B,CAAE,eAAe,cAAe;AAC/B,YAAM,QAAQ,OAAQ,SAAU;AAEhC,UAAK,OAAO,YAAY,OAAQ;AAC/B,sBAAc,eAAe,KAAM,SAAU;AAAA,MAC9C;AAEA,UAAK,OAAO,WAAW,MAAO;AAC7B,sBAAc,WAAW,KAAM,SAAU;AAAA,MAC1C;AAEA,aAAO;AAAA,IACR;AAAA,IACA,EAAE,gBAAgB,CAAC,GAAG,YAAY,CAAC,EAAE;AAAA,EACtC;AACD;",
6
- "names": []
7
- }
1
+ {"version":3,"file":"convert-edit-post-panels.mjs","names":[],"sources":["../../../src/migrations/legacy-local-storage-data/convert-edit-post-panels.ts"],"sourcesContent":["import type { ScopePreferences } from '../../types';\nimport type { EditPostPanels, LegacyEditPostPanel } from './types';\n\n/**\n * Convert the post editor's panels state from:\n * ```\n * {\n * panels: {\n * tags: {\n * enabled: true,\n * opened: true,\n * },\n * permalinks: {\n * enabled: false,\n * opened: false,\n * },\n * },\n * }\n * ```\n *\n * to a new, more concise data structure:\n * {\n * inactivePanels: [\n * 'permalinks',\n * ],\n * openPanels: [\n * 'tags',\n * ],\n * }\n *\n * @param preferences A preferences object.\n *\n * @return The converted data.\n */\nexport default function convertEditPostPanels(\n\tpreferences: ScopePreferences\n): EditPostPanels {\n\tconst panels = ( preferences?.panels ?? {} ) as Record<\n\t\tstring,\n\t\tLegacyEditPostPanel | undefined\n\t>;\n\treturn Object.keys( panels ).reduce< EditPostPanels >(\n\t\t( convertedData, panelName ) => {\n\t\t\tconst panel = panels[ panelName ];\n\n\t\t\tif ( panel?.enabled === false ) {\n\t\t\t\tconvertedData.inactivePanels.push( panelName );\n\t\t\t}\n\n\t\t\tif ( panel?.opened === true ) {\n\t\t\t\tconvertedData.openPanels.push( panelName );\n\t\t\t}\n\n\t\t\treturn convertedData;\n\t\t},\n\t\t{ inactivePanels: [], openPanels: [] }\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,SAAwB,sBACvB,aACiB;CACjB,MAAM,SAAW,aAAa,UAAU,CAAC;CAIzC,OAAO,OAAO,KAAM,MAAO,CAAC,CAAC,QAC1B,eAAe,cAAe;EAC/B,MAAM,QAAQ,OAAQ;EAEtB,IAAK,OAAO,YAAY,OACvB,cAAc,eAAe,KAAM,SAAU;EAG9C,IAAK,OAAO,WAAW,MACtB,cAAc,WAAW,KAAM,SAAU;EAG1C,OAAO;CACR,GACA;EAAE,gBAAgB,CAAC;EAAG,YAAY,CAAC;CAAE,CACtC;AACD"}
@@ -1,4 +1,3 @@
1
- // packages/preferences-persistence/src/migrations/legacy-local-storage-data/index.ts
2
1
  import moveFeaturePreferences from "./move-feature-preferences.mjs";
3
2
  import moveThirdPartyFeaturePreferences from "./move-third-party-feature-preferences.mjs";
4
3
  import moveIndividualPreference from "./move-individual-preference.mjs";
@@ -6,59 +5,72 @@ import moveInterfaceEnableItems from "./move-interface-enable-items.mjs";
6
5
  import convertEditPostPanels from "./convert-edit-post-panels.mjs";
7
6
  import isPreferencesData from "../../is-preferences-data.mjs";
8
7
  import { readStoredJSON } from "../../local-storage.mjs";
8
+ // packages/preferences-persistence/src/migrations/legacy-local-storage-data/index.ts
9
+ /**
10
+ * Gets the legacy local storage data for a given user.
11
+ *
12
+ * @param userId The user id.
13
+ *
14
+ * @return The local storage data.
15
+ */
9
16
  function getLegacyData(userId) {
10
- return readStoredJSON(`WP_DATA_USER_${userId}`);
17
+ return readStoredJSON(`WP_DATA_USER_${userId}`);
11
18
  }
19
+ /**
20
+ * Converts data from the old `@wordpress/data` package format.
21
+ *
22
+ * @param data The legacy data in its original format.
23
+ *
24
+ * @return The converted data or `undefined` if there was
25
+ * nothing to convert.
26
+ */
12
27
  function convertLegacyData(data) {
13
- if (!data) {
14
- return;
15
- }
16
- data = moveFeaturePreferences(data, "core/edit-widgets");
17
- data = moveFeaturePreferences(data, "core/customize-widgets");
18
- data = moveFeaturePreferences(data, "core/edit-post");
19
- data = moveFeaturePreferences(data, "core/edit-site");
20
- data = moveThirdPartyFeaturePreferences(data);
21
- data = moveInterfaceEnableItems(data);
22
- data = moveIndividualPreference(
23
- data,
24
- { from: "core/edit-post", to: "core/edit-post" },
25
- "hiddenBlockTypes"
26
- );
27
- data = moveIndividualPreference(
28
- data,
29
- { from: "core/edit-post", to: "core/edit-post" },
30
- "editorMode"
31
- );
32
- data = moveIndividualPreference(
33
- data,
34
- { from: "core/edit-post", to: "core/edit-post" },
35
- "panels",
36
- convertEditPostPanels
37
- );
38
- data = moveIndividualPreference(
39
- data,
40
- { from: "core/editor", to: "core" },
41
- "isPublishSidebarEnabled"
42
- );
43
- data = moveIndividualPreference(
44
- data,
45
- { from: "core/edit-post", to: "core" },
46
- "isPublishSidebarEnabled"
47
- );
48
- data = moveIndividualPreference(
49
- data,
50
- { from: "core/edit-site", to: "core/edit-site" },
51
- "editorMode"
52
- );
53
- const preferences = data?.["core/preferences"]?.preferences;
54
- return isPreferencesData(preferences) ? preferences : void 0;
28
+ if (!data) return;
29
+ data = moveFeaturePreferences(data, "core/edit-widgets");
30
+ data = moveFeaturePreferences(data, "core/customize-widgets");
31
+ data = moveFeaturePreferences(data, "core/edit-post");
32
+ data = moveFeaturePreferences(data, "core/edit-site");
33
+ data = moveThirdPartyFeaturePreferences(data);
34
+ data = moveInterfaceEnableItems(data);
35
+ data = moveIndividualPreference(data, {
36
+ from: "core/edit-post",
37
+ to: "core/edit-post"
38
+ }, "hiddenBlockTypes");
39
+ data = moveIndividualPreference(data, {
40
+ from: "core/edit-post",
41
+ to: "core/edit-post"
42
+ }, "editorMode");
43
+ data = moveIndividualPreference(data, {
44
+ from: "core/edit-post",
45
+ to: "core/edit-post"
46
+ }, "panels", convertEditPostPanels);
47
+ data = moveIndividualPreference(data, {
48
+ from: "core/editor",
49
+ to: "core"
50
+ }, "isPublishSidebarEnabled");
51
+ data = moveIndividualPreference(data, {
52
+ from: "core/edit-post",
53
+ to: "core"
54
+ }, "isPublishSidebarEnabled");
55
+ data = moveIndividualPreference(data, {
56
+ from: "core/edit-site",
57
+ to: "core/edit-site"
58
+ }, "editorMode");
59
+ const preferences = data?.["core/preferences"]?.preferences;
60
+ return isPreferencesData(preferences) ? preferences : void 0;
55
61
  }
62
+ /**
63
+ * Gets the legacy local storage data for the given user and returns the
64
+ * data converted to the new format.
65
+ *
66
+ * @param userId The user id.
67
+ *
68
+ * @return The converted data or undefined if no local
69
+ * storage data could be found.
70
+ */
56
71
  function convertLegacyLocalStorageData(userId) {
57
- const data = getLegacyData(userId);
58
- return convertLegacyData(data);
72
+ return convertLegacyData(getLegacyData(userId));
59
73
  }
60
- export {
61
- convertLegacyData,
62
- convertLegacyLocalStorageData as default
63
- };
64
- //# sourceMappingURL=index.mjs.map
74
+ export { convertLegacyData, convertLegacyLocalStorageData as default };
75
+
76
+ //# sourceMappingURL=index.mjs.map