@wordpress/preferences-persistence 2.57.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 (136) hide show
  1. package/README.md +7 -7
  2. package/build/create/debounce-async.cjs +55 -58
  3. package/build/create/debounce-async.cjs.map +1 -7
  4. package/build/create/index.cjs +75 -91
  5. package/build/create/index.cjs.map +1 -7
  6. package/build/get-newest-data.cjs +64 -0
  7. package/build/get-newest-data.cjs.map +1 -0
  8. package/build/index.cjs +52 -53
  9. package/build/index.cjs.map +1 -7
  10. package/build/is-preferences-data.cjs +20 -0
  11. package/build/is-preferences-data.cjs.map +1 -0
  12. package/build/local-storage.cjs +39 -0
  13. package/build/local-storage.cjs.map +1 -0
  14. package/build/migrations/legacy-local-storage-data/convert-edit-post-panels.cjs +49 -38
  15. package/build/migrations/legacy-local-storage-data/convert-edit-post-panels.cjs.map +1 -7
  16. package/build/migrations/legacy-local-storage-data/index.cjs +95 -83
  17. package/build/migrations/legacy-local-storage-data/index.cjs.map +1 -7
  18. package/build/migrations/legacy-local-storage-data/move-feature-preferences.cjs +106 -77
  19. package/build/migrations/legacy-local-storage-data/move-feature-preferences.cjs.map +1 -7
  20. package/build/migrations/legacy-local-storage-data/move-individual-preference.cjs +70 -58
  21. package/build/migrations/legacy-local-storage-data/move-individual-preference.cjs.map +1 -7
  22. package/build/migrations/legacy-local-storage-data/move-interface-enable-items.cjs +93 -75
  23. package/build/migrations/legacy-local-storage-data/move-interface-enable-items.cjs.map +1 -7
  24. package/build/migrations/legacy-local-storage-data/move-third-party-feature-preferences.cjs +77 -65
  25. package/build/migrations/legacy-local-storage-data/move-third-party-feature-preferences.cjs.map +1 -7
  26. package/build/migrations/legacy-local-storage-data/types.cjs +5 -0
  27. package/build/migrations/preferences-package-data/convert-complementary-areas.cjs +19 -35
  28. package/build/migrations/preferences-package-data/convert-complementary-areas.cjs.map +1 -7
  29. package/build/migrations/preferences-package-data/convert-editor-settings.cjs +62 -60
  30. package/build/migrations/preferences-package-data/convert-editor-settings.cjs.map +1 -7
  31. package/build/migrations/preferences-package-data/index.cjs +29 -32
  32. package/build/migrations/preferences-package-data/index.cjs.map +1 -7
  33. package/build/types.cjs +5 -0
  34. package/build-module/create/debounce-async.mjs +51 -39
  35. package/build-module/create/debounce-async.mjs.map +1 -7
  36. package/build-module/create/index.mjs +51 -67
  37. package/build-module/create/index.mjs.map +1 -7
  38. package/build-module/get-newest-data.mjs +36 -0
  39. package/build-module/get-newest-data.mjs.map +1 -0
  40. package/build-module/index.mjs +24 -25
  41. package/build-module/index.mjs.map +1 -7
  42. package/build-module/is-preferences-data.mjs +15 -0
  43. package/build-module/is-preferences-data.mjs.map +1 -0
  44. package/build-module/local-storage.mjs +33 -0
  45. package/build-module/local-storage.mjs.map +1 -0
  46. package/build-module/migrations/legacy-local-storage-data/convert-edit-post-panels.mjs +45 -19
  47. package/build-module/migrations/legacy-local-storage-data/convert-edit-post-panels.mjs.map +1 -7
  48. package/build-module/migrations/legacy-local-storage-data/index.mjs +65 -52
  49. package/build-module/migrations/legacy-local-storage-data/index.mjs.map +1 -7
  50. package/build-module/migrations/legacy-local-storage-data/move-feature-preferences.mjs +102 -58
  51. package/build-module/migrations/legacy-local-storage-data/move-feature-preferences.mjs.map +1 -7
  52. package/build-module/migrations/legacy-local-storage-data/move-individual-preference.mjs +66 -39
  53. package/build-module/migrations/legacy-local-storage-data/move-individual-preference.mjs.map +1 -7
  54. package/build-module/migrations/legacy-local-storage-data/move-interface-enable-items.mjs +89 -56
  55. package/build-module/migrations/legacy-local-storage-data/move-interface-enable-items.mjs.map +1 -7
  56. package/build-module/migrations/legacy-local-storage-data/move-third-party-feature-preferences.mjs +73 -46
  57. package/build-module/migrations/legacy-local-storage-data/move-third-party-feature-preferences.mjs.map +1 -7
  58. package/build-module/migrations/legacy-local-storage-data/types.mjs +0 -0
  59. package/build-module/migrations/preferences-package-data/convert-complementary-areas.mjs +15 -16
  60. package/build-module/migrations/preferences-package-data/convert-complementary-areas.mjs.map +1 -7
  61. package/build-module/migrations/preferences-package-data/convert-editor-settings.mjs +41 -46
  62. package/build-module/migrations/preferences-package-data/convert-editor-settings.mjs.map +1 -7
  63. package/build-module/migrations/preferences-package-data/index.mjs +7 -8
  64. package/build-module/migrations/preferences-package-data/index.mjs.map +1 -7
  65. package/build-module/types.mjs +0 -0
  66. package/build-types/create/debounce-async.d.ts +19 -0
  67. package/build-types/create/debounce-async.d.ts.map +1 -0
  68. package/build-types/create/index.d.ts +20 -0
  69. package/build-types/create/index.d.ts.map +1 -0
  70. package/build-types/get-newest-data.d.ts +11 -0
  71. package/build-types/get-newest-data.d.ts.map +1 -0
  72. package/build-types/index.d.ts +20 -0
  73. package/build-types/index.d.ts.map +1 -0
  74. package/build-types/is-preferences-data.d.ts +11 -0
  75. package/build-types/is-preferences-data.d.ts.map +1 -0
  76. package/build-types/local-storage.d.ts +19 -0
  77. package/build-types/local-storage.d.ts.map +1 -0
  78. package/build-types/migrations/legacy-local-storage-data/convert-edit-post-panels.d.ts +35 -0
  79. package/build-types/migrations/legacy-local-storage-data/convert-edit-post-panels.d.ts.map +1 -0
  80. package/build-types/migrations/legacy-local-storage-data/index.d.ts +22 -0
  81. package/build-types/migrations/legacy-local-storage-data/index.d.ts.map +1 -0
  82. package/build-types/migrations/legacy-local-storage-data/move-feature-preferences.d.ts +60 -0
  83. package/build-types/migrations/legacy-local-storage-data/move-feature-preferences.d.ts.map +1 -0
  84. package/build-types/migrations/legacy-local-storage-data/move-individual-preference.d.ts +42 -0
  85. package/build-types/migrations/legacy-local-storage-data/move-individual-preference.d.ts.map +1 -0
  86. package/build-types/migrations/legacy-local-storage-data/move-interface-enable-items.d.ts +50 -0
  87. package/build-types/migrations/legacy-local-storage-data/move-interface-enable-items.d.ts.map +1 -0
  88. package/build-types/migrations/legacy-local-storage-data/move-third-party-feature-preferences.d.ts +44 -0
  89. package/build-types/migrations/legacy-local-storage-data/move-third-party-feature-preferences.d.ts.map +1 -0
  90. package/build-types/migrations/legacy-local-storage-data/types.d.ts +60 -0
  91. package/build-types/migrations/legacy-local-storage-data/types.d.ts.map +1 -0
  92. package/build-types/migrations/preferences-package-data/convert-complementary-areas.d.ts +5 -0
  93. package/build-types/migrations/preferences-package-data/convert-complementary-areas.d.ts.map +1 -0
  94. package/build-types/migrations/preferences-package-data/convert-editor-settings.d.ts +5 -0
  95. package/build-types/migrations/preferences-package-data/convert-editor-settings.d.ts.map +1 -0
  96. package/build-types/migrations/preferences-package-data/index.d.ts +5 -0
  97. package/build-types/migrations/preferences-package-data/index.d.ts.map +1 -0
  98. package/build-types/types.d.ts +40 -0
  99. package/build-types/types.d.ts.map +1 -0
  100. package/package.json +8 -7
  101. package/src/create/{debounce-async.js → debounce-async.ts} +13 -10
  102. package/src/create/index.ts +95 -0
  103. package/src/create/test/{debounce-async.js → debounce-async.ts} +7 -3
  104. package/src/create/test/{index.jsdom.test.js → index.jsdom.test.ts} +52 -4
  105. package/src/get-newest-data.ts +50 -0
  106. package/src/index.ts +40 -0
  107. package/src/is-preferences-data.ts +15 -0
  108. package/src/local-storage.ts +30 -0
  109. package/src/migrations/legacy-local-storage-data/{convert-edit-post-panels.js → convert-edit-post-panels.ts} +13 -5
  110. package/src/migrations/legacy-local-storage-data/{index.js → index.ts} +22 -15
  111. package/src/migrations/legacy-local-storage-data/{move-feature-preferences.js → move-feature-preferences.ts} +13 -7
  112. package/src/migrations/legacy-local-storage-data/{move-individual-preference.js → move-individual-preference.ts} +15 -12
  113. package/src/migrations/legacy-local-storage-data/{move-interface-enable-items.js → move-interface-enable-items.ts} +6 -2
  114. package/src/migrations/legacy-local-storage-data/{move-third-party-feature-preferences.js → move-third-party-feature-preferences.ts} +8 -4
  115. package/src/migrations/legacy-local-storage-data/test/{index.js → index.ts} +11 -0
  116. package/src/migrations/legacy-local-storage-data/types.ts +66 -0
  117. package/src/migrations/preferences-package-data/convert-complementary-areas.ts +21 -0
  118. package/src/migrations/preferences-package-data/convert-editor-settings.ts +58 -0
  119. package/src/migrations/preferences-package-data/{index.js → index.ts} +4 -1
  120. package/src/migrations/preferences-package-data/test/{convert-complementary-areas.js → convert-complementary-areas.ts} +10 -0
  121. package/src/migrations/preferences-package-data/test/convert-editor-settings.ts +58 -0
  122. package/src/test/index.jsdom.test.ts +97 -0
  123. package/src/test/local-storage.jsdom.test.ts +50 -0
  124. package/src/types.ts +43 -0
  125. package/CHANGELOG.md +0 -228
  126. package/src/create/index.js +0 -105
  127. package/src/index.js +0 -47
  128. package/src/migrations/preferences-package-data/convert-complementary-areas.js +0 -16
  129. package/src/migrations/preferences-package-data/convert-editor-settings.js +0 -48
  130. package/src/migrations/preferences-package-data/test/convert-editor-settings.js +0 -20
  131. /package/src/migrations/legacy-local-storage-data/test/{convert-edit-post-panels.js → convert-edit-post-panels.ts} +0 -0
  132. /package/src/migrations/legacy-local-storage-data/test/{move-feature-preferences.js → move-feature-preferences.ts} +0 -0
  133. /package/src/migrations/legacy-local-storage-data/test/{move-individual-preference.js → move-individual-preference.ts} +0 -0
  134. /package/src/migrations/legacy-local-storage-data/test/{move-interface-enable-items.js → move-interface-enable-items.ts} +0 -0
  135. /package/src/migrations/legacy-local-storage-data/test/{move-third-party-feature-preferences.js → move-third-party-feature-preferences.ts} +0 -0
  136. /package/src/migrations/preferences-package-data/test/{index.js → index.ts} +0 -0
package/README.md CHANGED
@@ -30,7 +30,7 @@ wp.data( 'core/preferences' ).setPersistenceLayer( persistenceLayer );
30
30
 
31
31
  ## Reference
32
32
 
33
- <!-- START TOKEN(Autogenerated Docs|src/index.js) -->
33
+ <!-- START TOKEN(Autogenerated Docs|src/index.ts) -->
34
34
 
35
35
  ### create
36
36
 
@@ -38,16 +38,16 @@ Creates a persistence layer that stores data in WordPress user meta via the REST
38
38
 
39
39
  _Parameters_
40
40
 
41
- - _options_ `Object`:
42
- - _options.preloadedData_ `?Object`: Any persisted preferences data that should be preloaded. When set, the persistence layer will avoid fetching data from the REST API.
43
- - _options.localStorageRestoreKey_ `?string`: The key to use for restoring the localStorage backup, used when the persistence layer calls `localStorage.getItem` or `localStorage.setItem`.
44
- - _options.requestDebounceMS_ `?number`: Debounce requests to the API so that they only occur at minimum every `requestDebounceMS` milliseconds, and don't swamp the server. Defaults to 2500ms.
41
+ - _options_ `[CreateOptions]`:
42
+ - _options.preloadedData_ `[PreferencesData|null]`: Any persisted preferences data that should be preloaded. When set, the persistence layer will avoid fetching data from the REST API.
43
+ - _options.localStorageRestoreKey_ `[string]`: The key to use for restoring the localStorage backup, used when the persistence layer calls `localStorage.getItem` or `localStorage.setItem`.
44
+ - _options.requestDebounceMS_ `[number]`: Debounce requests to the API so that they only occur at minimum every `requestDebounceMS` milliseconds, and don't swamp the server. Defaults to 2500ms.
45
45
 
46
46
  _Returns_
47
47
 
48
- - `Object`: A persistence layer for WordPress user meta.
48
+ - `PersistenceLayer`: A persistence layer for WordPress user meta.
49
49
 
50
- <!-- END TOKEN(Autogenerated Docs|src/index.js) -->
50
+ <!-- END TOKEN(Autogenerated Docs|src/index.ts) -->
51
51
 
52
52
  ## Contributing to this package
53
53
 
@@ -1,61 +1,58 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __hasOwnProp = Object.prototype.hasOwnProperty;
5
- var __export = (target, all) => {
6
- for (var name in all)
7
- __defProp(target, name, { get: all[name], enumerable: true });
8
- };
9
- var __copyProps = (to, from, except, desc) => {
10
- if (from && typeof from === "object" || typeof from === "function") {
11
- for (let key of __getOwnPropNames(from))
12
- if (!__hasOwnProp.call(to, key) && key !== except)
13
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
- }
15
- return to;
16
- };
17
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
-
19
- // packages/preferences-persistence/src/create/debounce-async.js
20
- var debounce_async_exports = {};
21
- __export(debounce_async_exports, {
22
- default: () => debounceAsync
1
+ "use strict";
2
+ Object.defineProperties(exports, {
3
+ __esModule: { value: true },
4
+ [Symbol.toStringTag]: { value: "Module" }
23
5
  });
24
- module.exports = __toCommonJS(debounce_async_exports);
6
+ // packages/preferences-persistence/src/create/debounce-async.ts
7
+ /**
8
+ * Performs a leading edge debounce of async functions.
9
+ *
10
+ * If three functions are throttled at the same time:
11
+ * - The first happens immediately.
12
+ * - The second is never called.
13
+ * - The third happens `delayMS` milliseconds after the first has resolved.
14
+ *
15
+ * This is distinct from `{ debounce } from @wordpress/compose` in that it
16
+ * waits for promise resolution.
17
+ *
18
+ * @param func A function that returns a promise.
19
+ * @param delayMS A delay in milliseconds.
20
+ *
21
+ * @return A function that debounce whatever function is passed
22
+ * to it.
23
+ */
25
24
  function debounceAsync(func, delayMS) {
26
- let timeoutId;
27
- let activePromise;
28
- return async function debounced(...args) {
29
- if (!activePromise && !timeoutId) {
30
- return new Promise((resolve, reject) => {
31
- activePromise = func(...args).then((...thenArgs) => {
32
- resolve(...thenArgs);
33
- }).catch((error) => {
34
- reject(error);
35
- }).finally(() => {
36
- activePromise = null;
37
- });
38
- });
39
- }
40
- if (activePromise) {
41
- await activePromise;
42
- }
43
- if (timeoutId) {
44
- clearTimeout(timeoutId);
45
- timeoutId = null;
46
- }
47
- return new Promise((resolve, reject) => {
48
- timeoutId = setTimeout(() => {
49
- activePromise = func(...args).then((...thenArgs) => {
50
- resolve(...thenArgs);
51
- }).catch((error) => {
52
- reject(error);
53
- }).finally(() => {
54
- activePromise = null;
55
- timeoutId = null;
56
- });
57
- }, delayMS);
58
- });
59
- };
25
+ let timeoutId;
26
+ let activePromise;
27
+ return async function debounced(...args) {
28
+ if (!activePromise && !timeoutId) return new Promise((resolve, reject) => {
29
+ activePromise = func(...args).then((...thenArgs) => {
30
+ resolve(...thenArgs);
31
+ }).catch((error) => {
32
+ reject(error);
33
+ }).finally(() => {
34
+ activePromise = null;
35
+ });
36
+ });
37
+ if (activePromise) await activePromise;
38
+ if (timeoutId) {
39
+ clearTimeout(timeoutId);
40
+ timeoutId = null;
41
+ }
42
+ return new Promise((resolve, reject) => {
43
+ timeoutId = setTimeout(() => {
44
+ activePromise = func(...args).then((...thenArgs) => {
45
+ resolve(...thenArgs);
46
+ }).catch((error) => {
47
+ reject(error);
48
+ }).finally(() => {
49
+ activePromise = null;
50
+ timeoutId = null;
51
+ });
52
+ }, delayMS);
53
+ });
54
+ };
60
55
  }
61
- //# sourceMappingURL=debounce-async.cjs.map
56
+ exports.default = debounceAsync;
57
+
58
+ //# sourceMappingURL=debounce-async.cjs.map
@@ -1,7 +1 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/create/debounce-async.js"],
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 {Function} func A function that returns a promise.\n * @param {number} delayMS A delay in milliseconds.\n *\n * @return {Function} A function that debounce whatever function is passed\n * to it.\n */\nexport default function debounceAsync( func, delayMS ) {\n\tlet timeoutId;\n\tlet activePromise;\n\n\treturn async function debounced( ...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( ( 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( ( 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": ";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAiBe,SAAR,cAAgC,MAAM,SAAU;AACtD,MAAI;AACJ,MAAI;AAEJ,SAAO,eAAe,aAAc,MAAO;AAG1C,QAAK,CAAE,iBAAiB,CAAE,WAAY;AACrC,aAAO,IAAI,QAAS,CAAE,SAAS,WAAY;AAE1C,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,QAAS,CAAE,SAAS,WAAY;AAE1C,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.cjs","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,100 +1,84 @@
1
+ "use strict";
2
+ Object.defineProperties(exports, {
3
+ __esModule: { value: true },
4
+ [Symbol.toStringTag]: { value: "Module" }
5
+ });
6
+ // \0rolldown/runtime.js
1
7
  var __create = Object.create;
2
8
  var __defProp = Object.defineProperty;
3
9
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
10
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
11
  var __getProtoOf = Object.getPrototypeOf;
6
12
  var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
13
  var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
14
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
15
+ key = keys[i];
16
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
17
+ get: ((k) => from[k]).bind(null, key),
18
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
19
+ });
20
+ }
21
+ return to;
18
22
  };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
- // If the importer is in node compatibility mode or this is not an ESM
21
- // file that has been converted to a CommonJS file using a Babel-
22
- // compatible transform (i.e. "__esModule" has not been set), then set
23
- // "default" to the CommonJS "module.exports" for node compatibility.
24
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
- mod
26
- ));
27
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
-
29
- // packages/preferences-persistence/src/create/index.js
30
- var create_exports = {};
31
- __export(create_exports, {
32
- default: () => create
33
- });
34
- module.exports = __toCommonJS(create_exports);
35
- var import_api_fetch = __toESM(require("@wordpress/api-fetch"));
36
- var import_debounce_async = __toESM(require("./debounce-async.cjs"));
37
- var EMPTY_OBJECT = {};
38
- var localStorage = window.localStorage;
39
- function create({
40
- preloadedData,
41
- localStorageRestoreKey = "WP_PREFERENCES_RESTORE_DATA",
42
- requestDebounceMS = 2500
43
- } = {}) {
44
- let cache = preloadedData;
45
- const debouncedApiFetch = (0, import_debounce_async.default)(import_api_fetch.default, requestDebounceMS);
46
- async function get() {
47
- if (cache) {
48
- return cache;
49
- }
50
- const user = await (0, import_api_fetch.default)({
51
- path: "/wp/v2/users/me?context=edit"
52
- });
53
- const serverData = user?.meta?.persisted_preferences;
54
- const localData = JSON.parse(
55
- localStorage.getItem(localStorageRestoreKey)
56
- );
57
- const serverTimestamp = Date.parse(serverData?._modified) || 0;
58
- const localTimestamp = Date.parse(localData?._modified) || 0;
59
- if (serverData && serverTimestamp >= localTimestamp) {
60
- cache = serverData;
61
- } else if (localData) {
62
- cache = localData;
63
- } else {
64
- cache = EMPTY_OBJECT;
65
- }
66
- return cache;
67
- }
68
- function set(newData) {
69
- const dataWithTimestamp = {
70
- ...newData,
71
- _modified: (/* @__PURE__ */ new Date()).toISOString()
72
- };
73
- cache = dataWithTimestamp;
74
- localStorage.setItem(
75
- localStorageRestoreKey,
76
- JSON.stringify(dataWithTimestamp)
77
- );
78
- debouncedApiFetch({
79
- path: "/wp/v2/users/me",
80
- method: "PUT",
81
- // `keepalive` will still send the request in the background,
82
- // even when a browser unload event might interrupt it.
83
- // This should hopefully make things more resilient.
84
- // This does have a size limit of 64kb, but the data is usually
85
- // much less.
86
- keepalive: true,
87
- data: {
88
- meta: {
89
- persisted_preferences: dataWithTimestamp
90
- }
91
- }
92
- }).catch(() => {
93
- });
94
- }
95
- return {
96
- get,
97
- set
98
- };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
24
+ value: mod,
25
+ enumerable: true
26
+ }) : target, mod));
27
+ let _wordpress_api_fetch = require("@wordpress/api-fetch");
28
+ _wordpress_api_fetch = __toESM(_wordpress_api_fetch);
29
+ let __debounce_async_ts = require("./debounce-async.cjs");
30
+ __debounce_async_ts = __toESM(__debounce_async_ts);
31
+ let ___get_newest_data_ts = require("../get-newest-data.cjs");
32
+ ___get_newest_data_ts = __toESM(___get_newest_data_ts);
33
+ let ___is_preferences_data_ts = require("../is-preferences-data.cjs");
34
+ ___is_preferences_data_ts = __toESM(___is_preferences_data_ts);
35
+ let ___local_storage_ts = require("../local-storage.cjs");
36
+ // packages/preferences-persistence/src/create/index.ts
37
+ /**
38
+ * Creates a persistence layer that stores data in WordPress user meta via the
39
+ * REST API.
40
+ *
41
+ * @param {CreateOptions} [options]
42
+ * @param {PreferencesData|null} [options.preloadedData] Any persisted preferences data that should be preloaded.
43
+ * When set, the persistence layer will avoid fetching data
44
+ * from the REST API.
45
+ * @param {string} [options.localStorageRestoreKey] The key to use for restoring the localStorage backup, used
46
+ * when the persistence layer calls `localStorage.getItem` or
47
+ * `localStorage.setItem`.
48
+ * @param {number} [options.requestDebounceMS] Debounce requests to the API so that they only occur at
49
+ * minimum every `requestDebounceMS` milliseconds, and don't
50
+ * swamp the server. Defaults to 2500ms.
51
+ *
52
+ * @return A persistence layer for WordPress user meta.
53
+ */
54
+ function create({ preloadedData, localStorageRestoreKey = "WP_PREFERENCES_RESTORE_DATA", requestDebounceMS = 2500 } = {}) {
55
+ let cache = (0, ___is_preferences_data_ts.default)(preloadedData) ? preloadedData : void 0;
56
+ const debouncedApiFetch = (0, __debounce_async_ts.default)(_wordpress_api_fetch.default, requestDebounceMS);
57
+ async function get() {
58
+ if (cache) return cache;
59
+ const user = await (0, _wordpress_api_fetch.default)({ path: "/wp/v2/users/me?context=edit" });
60
+ cache = (0, ___get_newest_data_ts.default)(user?.meta?.persisted_preferences, localStorageRestoreKey) ?? {};
61
+ return cache;
62
+ }
63
+ function set(newData) {
64
+ const dataWithTimestamp = {
65
+ ...newData,
66
+ _modified: (/* @__PURE__ */ new Date()).toISOString()
67
+ };
68
+ cache = dataWithTimestamp;
69
+ (0, ___local_storage_ts.writeStoredJSON)(localStorageRestoreKey, dataWithTimestamp);
70
+ debouncedApiFetch({
71
+ path: "/wp/v2/users/me",
72
+ method: "PUT",
73
+ keepalive: true,
74
+ data: { meta: { persisted_preferences: dataWithTimestamp } }
75
+ }).catch(() => {});
76
+ }
77
+ return {
78
+ get,
79
+ set
80
+ };
99
81
  }
100
- //# sourceMappingURL=index.cjs.map
82
+ exports.default = create;
83
+
84
+ //# sourceMappingURL=index.cjs.map
@@ -1,7 +1 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/create/index.js"],
4
- "sourcesContent": ["import apiFetch from '@wordpress/api-fetch';\nimport debounceAsync from './debounce-async';\n\nconst EMPTY_OBJECT = {};\nconst localStorage = window.localStorage;\n\n/**\n * Creates a persistence layer that stores data in WordPress user meta via the\n * REST API.\n *\n * @param {Object} options\n * @param {?Object} 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 {Object} A persistence layer for WordPress user meta.\n */\nexport default function create( {\n\tpreloadedData,\n\tlocalStorageRestoreKey = 'WP_PREFERENCES_RESTORE_DATA',\n\trequestDebounceMS = 2500,\n} = {} ) {\n\tlet cache = preloadedData;\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\tpath: '/wp/v2/users/me?context=edit',\n\t\t} );\n\n\t\tconst serverData = user?.meta?.persisted_preferences;\n\t\tconst localData = JSON.parse(\n\t\t\tlocalStorage.getItem( localStorageRestoreKey )\n\t\t);\n\n\t\t// Date parse returns NaN for invalid input. Coerce anything invalid\n\t\t// into a conveniently comparable zero.\n\t\tconst serverTimestamp = Date.parse( serverData?._modified ) || 0;\n\t\tconst localTimestamp = Date.parse( localData?._modified ) || 0;\n\n\t\t// Prefer server data if it exists and is more recent.\n\t\t// Otherwise fallback to localStorage data.\n\t\tif ( serverData && serverTimestamp >= localTimestamp ) {\n\t\t\tcache = serverData;\n\t\t} else if ( localData ) {\n\t\t\tcache = localData;\n\t\t} else {\n\t\t\tcache = EMPTY_OBJECT;\n\t\t}\n\n\t\treturn cache;\n\t}\n\n\tfunction set( newData ) {\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\tlocalStorage.setItem(\n\t\t\tlocalStorageRestoreKey,\n\t\t\tJSON.stringify( dataWithTimestamp )\n\t\t);\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;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAqB;AACrB,4BAA0B;AAE1B,IAAM,eAAe,CAAC;AACtB,IAAM,eAAe,OAAO;AAmBb,SAAR,OAAyB;AAAA,EAC/B;AAAA,EACA,yBAAyB;AAAA,EACzB,oBAAoB;AACrB,IAAI,CAAC,GAAI;AACR,MAAI,QAAQ;AACZ,QAAM,wBAAoB,sBAAAA,SAAe,iBAAAC,SAAU,iBAAkB;AAErE,iBAAe,MAAM;AACpB,QAAK,OAAQ;AACZ,aAAO;AAAA,IACR;AAEA,UAAM,OAAO,UAAM,iBAAAA,SAAU;AAAA,MAC5B,MAAM;AAAA,IACP,CAAE;AAEF,UAAM,aAAa,MAAM,MAAM;AAC/B,UAAM,YAAY,KAAK;AAAA,MACtB,aAAa,QAAS,sBAAuB;AAAA,IAC9C;AAIA,UAAM,kBAAkB,KAAK,MAAO,YAAY,SAAU,KAAK;AAC/D,UAAM,iBAAiB,KAAK,MAAO,WAAW,SAAU,KAAK;AAI7D,QAAK,cAAc,mBAAmB,gBAAiB;AACtD,cAAQ;AAAA,IACT,WAAY,WAAY;AACvB,cAAQ;AAAA,IACT,OAAO;AACN,cAAQ;AAAA,IACT;AAEA,WAAO;AAAA,EACR;AAEA,WAAS,IAAK,SAAU;AACvB,UAAM,oBAAoB;AAAA,MACzB,GAAG;AAAA,MACH,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,IACnC;AACA,YAAQ;AAKR,iBAAa;AAAA,MACZ;AAAA,MACA,KAAK,UAAW,iBAAkB;AAAA,IACnC;AAOA,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": ["debounceAsync", "apiFetch"]
7
- }
1
+ {"version":3,"file":"index.cjs","names":["isPreferencesData","debounceAsync","apiFetch","getNewestData"],"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,SAAA,GAAQA,0BAAAA,QAAAA,CAAmB,aAAc,IAAI,gBAAgB,KAAA;CACjE,MAAM,qBAAA,GAAoBC,oBAAAA,QAAAA,CAAeC,qBAAAA,SAAU,iBAAkB;CAErE,eAAe,MAAM;EACpB,IAAK,OACJ,OAAO;EAGR,MAAM,OAAO,OAAA,GAAMA,qBAAAA,QAAAA,CAEd,EACJ,MAAM,+BACP,CAAE;EAEF,SAAA,GACCC,sBAAAA,QAAAA,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,CAAA,GAAA,oBAAA,gBAAA,CAAiB,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"}
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ Object.defineProperties(exports, {
3
+ __esModule: { value: true },
4
+ [Symbol.toStringTag]: { value: "Module" }
5
+ });
6
+ // \0rolldown/runtime.js
7
+ var __create = Object.create;
8
+ var __defProp = Object.defineProperty;
9
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
10
+ var __getOwnPropNames = Object.getOwnPropertyNames;
11
+ var __getProtoOf = Object.getPrototypeOf;
12
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
15
+ key = keys[i];
16
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
17
+ get: ((k) => from[k]).bind(null, key),
18
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
19
+ });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
24
+ value: mod,
25
+ enumerable: true
26
+ }) : target, mod));
27
+ let __is_preferences_data_ts = require("./is-preferences-data.cjs");
28
+ __is_preferences_data_ts = __toESM(__is_preferences_data_ts);
29
+ let __local_storage_ts = require("./local-storage.cjs");
30
+ let __migrations_preferences_package_data_index_ts = require("./migrations/preferences-package-data/index.cjs");
31
+ __migrations_preferences_package_data_index_ts = __toESM(__migrations_preferences_package_data_index_ts);
32
+ // packages/preferences-persistence/src/get-newest-data.ts
33
+ /**
34
+ * Picks the most recently modified preferences from the server data and the
35
+ * local storage backup, ignoring either when it is not a preferences object.
36
+ *
37
+ * @param serverData Preferences data from the server.
38
+ * @param localStorageRestoreKey The key of the local storage backup.
39
+ *
40
+ * @return The newest preferences data, or `null` when neither is valid.
41
+ */
42
+ function pickNewestData(serverData, localStorageRestoreKey) {
43
+ const storedData = (0, __local_storage_ts.readStoredJSON)(localStorageRestoreKey);
44
+ const localData = (0, __is_preferences_data_ts.default)(storedData) ? storedData : null;
45
+ if (!(0, __is_preferences_data_ts.default)(serverData)) return localData;
46
+ const serverModified = Date.parse(serverData._modified ?? "") || 0;
47
+ const localModified = Date.parse(localData?._modified ?? "") || 0;
48
+ return localData && localModified > serverModified ? localData : serverData;
49
+ }
50
+ /**
51
+ * Gets the newest persisted preferences, migrated to the current format.
52
+ *
53
+ * @param serverData Preferences data from the server.
54
+ * @param localStorageRestoreKey The key of the local storage backup.
55
+ *
56
+ * @return The migrated preferences, or `undefined` when there are none.
57
+ */
58
+ function getNewestData(serverData, localStorageRestoreKey) {
59
+ const newestData = pickNewestData(serverData, localStorageRestoreKey);
60
+ return newestData ? (0, __migrations_preferences_package_data_index_ts.default)(newestData) : void 0;
61
+ }
62
+ exports.default = getNewestData;
63
+
64
+ //# sourceMappingURL=get-newest-data.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"get-newest-data.cjs","names":["readStoredJSON","isPreferencesData","convertPreferencesPackageData"],"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,cAAA,GAAaA,mBAAAA,eAAAA,CAAgB,sBAAuB;CAC1D,MAAM,aAAA,GAAYC,yBAAAA,QAAAA,CAAmB,UAAW,IAAI,aAAa;CACjE,IAAK,EAAA,GAAEA,yBAAAA,QAAAA,CAAmB,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,cAAA,GACJC,+CAAAA,QAAAA,CAA+B,UAAgC,IAC/D,KAAA;AACJ"}
package/build/index.cjs CHANGED
@@ -1,64 +1,63 @@
1
+ "use strict";
2
+ Object.defineProperties(exports, {
3
+ __esModule: { value: true },
4
+ [Symbol.toStringTag]: { value: "Module" }
5
+ });
6
+ // \0rolldown/runtime.js
1
7
  var __create = Object.create;
2
8
  var __defProp = Object.defineProperty;
3
9
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
10
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
11
  var __getProtoOf = Object.getPrototypeOf;
6
12
  var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
13
  var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
14
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
15
+ key = keys[i];
16
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
17
+ get: ((k) => from[k]).bind(null, key),
18
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
19
+ });
20
+ }
21
+ return to;
18
22
  };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
- // If the importer is in node compatibility mode or this is not an ESM
21
- // file that has been converted to a CommonJS file using a Babel-
22
- // compatible transform (i.e. "__esModule" has not been set), then set
23
- // "default" to the CommonJS "module.exports" for node compatibility.
24
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
- mod
26
- ));
27
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
-
29
- // packages/preferences-persistence/src/index.js
30
- var index_exports = {};
31
- __export(index_exports, {
32
- __unstableCreatePersistenceLayer: () => __unstableCreatePersistenceLayer,
33
- create: () => import_create.default
34
- });
35
- module.exports = __toCommonJS(index_exports);
36
- var import_create = __toESM(require("./create/index.cjs"));
37
- var import_legacy_local_storage_data = __toESM(require("./migrations/legacy-local-storage-data/index.cjs"));
38
- var import_preferences_package_data = __toESM(require("./migrations/preferences-package-data/index.cjs"));
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
24
+ value: mod,
25
+ enumerable: true
26
+ }) : target, mod));
27
+ let __create_index_ts = require("./create/index.cjs");
28
+ __create_index_ts = __toESM(__create_index_ts);
29
+ let __migrations_legacy_local_storage_data_index_ts = require("./migrations/legacy-local-storage-data/index.cjs");
30
+ __migrations_legacy_local_storage_data_index_ts = __toESM(__migrations_legacy_local_storage_data_index_ts);
31
+ let __get_newest_data_ts = require("./get-newest-data.cjs");
32
+ __get_newest_data_ts = __toESM(__get_newest_data_ts);
33
+ // packages/preferences-persistence/src/index.ts
34
+ /**
35
+ * Creates the persistence layer with preloaded data.
36
+ *
37
+ * It prioritizes any data from the server, but falls back first to localStorage
38
+ * restore data, and then to any legacy data.
39
+ *
40
+ * This function is used internally by WordPress in an inline script, so
41
+ * prefixed with `__unstable`.
42
+ *
43
+ * @param serverData Preferences data preloaded from the server.
44
+ * @param userId The user id.
45
+ *
46
+ * @return The persistence layer initialized with the preloaded data.
47
+ */
39
48
  function __unstableCreatePersistenceLayer(serverData, userId) {
40
- const localStorageRestoreKey = `WP_PREFERENCES_USER_${userId}`;
41
- const localData = JSON.parse(
42
- window.localStorage.getItem(localStorageRestoreKey)
43
- );
44
- const serverModified = Date.parse(serverData && serverData._modified) || 0;
45
- const localModified = Date.parse(localData && localData._modified) || 0;
46
- let preloadedData;
47
- if (serverData && serverModified >= localModified) {
48
- preloadedData = (0, import_preferences_package_data.default)(serverData);
49
- } else if (localData) {
50
- preloadedData = (0, import_preferences_package_data.default)(localData);
51
- } else {
52
- preloadedData = (0, import_legacy_local_storage_data.default)(userId);
53
- }
54
- return (0, import_create.default)({
55
- preloadedData,
56
- localStorageRestoreKey
57
- });
49
+ const localStorageRestoreKey = `WP_PREFERENCES_USER_${userId}`;
50
+ return (0, __create_index_ts.default)({
51
+ preloadedData: (0, __get_newest_data_ts.default)(serverData, localStorageRestoreKey) ?? (0, __migrations_legacy_local_storage_data_index_ts.default)(userId) ?? {},
52
+ localStorageRestoreKey
53
+ });
58
54
  }
59
- // Annotate the CommonJS export names for ESM import in node:
60
- 0 && (module.exports = {
61
- __unstableCreatePersistenceLayer,
62
- create
55
+ exports.__unstableCreatePersistenceLayer = __unstableCreatePersistenceLayer;
56
+ Object.defineProperty(exports, "create", {
57
+ enumerable: true,
58
+ get: function() {
59
+ return __create_index_ts.default;
60
+ }
63
61
  });
64
- //# sourceMappingURL=index.cjs.map
62
+
63
+ //# sourceMappingURL=index.cjs.map
@@ -1,7 +1 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/index.js"],
4
- "sourcesContent": ["import create from './create';\nimport convertLegacyLocalStorageData from './migrations/legacy-local-storage-data';\nimport convertPreferencesPackageData from './migrations/preferences-package-data';\n\nexport { create };\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 {Object} serverData Preferences data preloaded from the server.\n * @param {string} userId The user id.\n *\n * @return {Object} The persistence layer initialized with the preloaded data.\n */\nexport function __unstableCreatePersistenceLayer( serverData, userId ) {\n\tconst localStorageRestoreKey = `WP_PREFERENCES_USER_${ userId }`;\n\tconst localData = JSON.parse(\n\t\twindow.localStorage.getItem( localStorageRestoreKey )\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 =\n\t\tDate.parse( serverData && serverData._modified ) || 0;\n\tconst localModified = Date.parse( localData && localData._modified ) || 0;\n\n\tlet preloadedData;\n\tif ( serverData && serverModified >= localModified ) {\n\t\tpreloadedData = convertPreferencesPackageData( serverData );\n\t} else if ( localData ) {\n\t\tpreloadedData = convertPreferencesPackageData( localData );\n\t} else {\n\t\t// Check if there is data in the legacy format from the old persistence system.\n\t\tpreloadedData = convertLegacyLocalStorageData( userId );\n\t}\n\n\treturn create( {\n\t\tpreloadedData,\n\t\tlocalStorageRestoreKey,\n\t} );\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA,8BAAAA;AAAA;AAAA;AAAA,oBAAmB;AACnB,uCAA0C;AAC1C,sCAA0C;AAkBnC,SAAS,iCAAkC,YAAY,QAAS;AACtE,QAAM,yBAAyB,uBAAwB,MAAO;AAC9D,QAAM,YAAY,KAAK;AAAA,IACtB,OAAO,aAAa,QAAS,sBAAuB;AAAA,EACrD;AAIA,QAAM,iBACL,KAAK,MAAO,cAAc,WAAW,SAAU,KAAK;AACrD,QAAM,gBAAgB,KAAK,MAAO,aAAa,UAAU,SAAU,KAAK;AAExE,MAAI;AACJ,MAAK,cAAc,kBAAkB,eAAgB;AACpD,wBAAgB,gCAAAC,SAA+B,UAAW;AAAA,EAC3D,WAAY,WAAY;AACvB,wBAAgB,gCAAAA,SAA+B,SAAU;AAAA,EAC1D,OAAO;AAEN,wBAAgB,iCAAAC,SAA+B,MAAO;AAAA,EACvD;AAEA,aAAO,cAAAC,SAAQ;AAAA,IACd;AAAA,IACA;AAAA,EACD,CAAE;AACH;",
6
- "names": ["create", "convertPreferencesPackageData", "convertLegacyLocalStorageData", "create"]
7
- }
1
+ {"version":3,"file":"index.cjs","names":["create","getNewestData","convertLegacyLocalStorageData"],"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,QAAA,GAAOA,kBAAAA,QAAAA,CAAQ;EAKd,gBAAA,GACCC,qBAAAA,QAAAA,CAAe,YAAY,sBAAuB,MAAA,GAClDC,gDAAAA,QAAAA,CAA+B,MAAO,KACtC,CAAC;EACF;CACD,CAAE;AACH"}
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperties(exports, {
3
+ __esModule: { value: true },
4
+ [Symbol.toStringTag]: { value: "Module" }
5
+ });
6
+ // packages/preferences-persistence/src/is-preferences-data.ts
7
+ /**
8
+ * Checks whether persisted data is a preferences object. Empty user meta
9
+ * reaches the client as `[]` or `''`, which must not be used as preferences.
10
+ *
11
+ * @param data The persisted data.
12
+ *
13
+ * @return Whether the data is a preferences object.
14
+ */
15
+ function isPreferencesData(data) {
16
+ return !!data && typeof data === "object" && !Array.isArray(data);
17
+ }
18
+ exports.default = isPreferencesData;
19
+
20
+ //# sourceMappingURL=is-preferences-data.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"is-preferences-data.cjs","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"}