@fast-china/utils 1.0.38 → 2.0.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 (286) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/CONTRIBUTING.md +87 -0
  3. package/README.md +111 -50
  4. package/README.zh.md +111 -50
  5. package/SECURITY.md +46 -0
  6. package/dist/array/index.d.mts +87 -0
  7. package/dist/array/index.d.mts.map +1 -0
  8. package/dist/array/index.mjs +161 -0
  9. package/dist/array/index.mjs.map +1 -0
  10. package/dist/async/index.d.mts +146 -0
  11. package/dist/async/index.d.mts.map +1 -0
  12. package/dist/async/index.mjs +336 -0
  13. package/dist/async/index.mjs.map +1 -0
  14. package/dist/base64/index.d.mts +105 -0
  15. package/dist/base64/index.d.mts.map +1 -0
  16. package/dist/base64/index.mjs +427 -0
  17. package/dist/base64/index.mjs.map +1 -0
  18. package/dist/color/index.d.mts +90 -0
  19. package/dist/color/index.d.mts.map +1 -0
  20. package/dist/color/index.mjs +178 -0
  21. package/dist/color/index.mjs.map +1 -0
  22. package/dist/crypto/index.d.mts +157 -0
  23. package/dist/crypto/index.d.mts.map +1 -0
  24. package/dist/crypto/index.mjs +541 -0
  25. package/dist/crypto/index.mjs.map +1 -0
  26. package/dist/date/index.d.mts +191 -0
  27. package/dist/date/index.d.mts.map +1 -0
  28. package/dist/date/index.mjs +383 -0
  29. package/dist/date/index.mjs.map +1 -0
  30. package/dist/dom/style.d.mts +30 -0
  31. package/dist/dom/style.d.mts.map +1 -0
  32. package/dist/dom/style.mjs +74 -0
  33. package/dist/dom/style.mjs.map +1 -0
  34. package/dist/env/index.d.mts +63 -0
  35. package/dist/env/index.d.mts.map +1 -0
  36. package/dist/env/index.mjs +97 -0
  37. package/dist/env/index.mjs.map +1 -0
  38. package/dist/identity/index.d.mts +78 -0
  39. package/dist/identity/index.d.mts.map +1 -0
  40. package/dist/identity/index.mjs +87 -0
  41. package/dist/identity/index.mjs.map +1 -0
  42. package/dist/index.d.mts +24 -0
  43. package/dist/index.mjs +23 -0
  44. package/dist/internal/text.mjs +36 -0
  45. package/dist/internal/text.mjs.map +1 -0
  46. package/dist/logger/index.d.mts +87 -0
  47. package/dist/logger/index.d.mts.map +1 -0
  48. package/dist/logger/index.mjs +124 -0
  49. package/dist/logger/index.mjs.map +1 -0
  50. package/dist/number/index.d.mts +89 -0
  51. package/dist/number/index.d.mts.map +1 -0
  52. package/dist/number/index.mjs +215 -0
  53. package/dist/number/index.mjs.map +1 -0
  54. package/dist/object/index.d.mts +76 -0
  55. package/dist/object/index.d.mts.map +1 -0
  56. package/dist/object/index.mjs +134 -0
  57. package/dist/object/index.mjs.map +1 -0
  58. package/dist/storage/index.d.mts +104 -0
  59. package/dist/storage/index.d.mts.map +1 -0
  60. package/dist/storage/index.mjs +324 -0
  61. package/dist/storage/index.mjs.map +1 -0
  62. package/dist/string/index.d.mts +130 -0
  63. package/dist/string/index.d.mts.map +1 -0
  64. package/dist/string/index.mjs +275 -0
  65. package/dist/string/index.mjs.map +1 -0
  66. package/dist/vue/emits.d.mts +24 -0
  67. package/dist/vue/emits.d.mts.map +1 -0
  68. package/dist/vue/emits.mjs +47 -0
  69. package/dist/vue/emits.mjs.map +1 -0
  70. package/dist/vue/expose.d.mts +12 -0
  71. package/dist/vue/expose.d.mts.map +1 -0
  72. package/dist/vue/expose.mjs +16 -0
  73. package/dist/vue/expose.mjs.map +1 -0
  74. package/dist/vue/func.d.mts +14 -0
  75. package/dist/vue/func.d.mts.map +1 -0
  76. package/dist/vue/func.mjs +16 -0
  77. package/dist/vue/func.mjs.map +1 -0
  78. package/dist/vue/index.d.mts +9 -0
  79. package/dist/vue/install.d.mts +69 -0
  80. package/dist/vue/install.d.mts.map +1 -0
  81. package/dist/vue/install.mjs +123 -0
  82. package/dist/vue/install.mjs.map +1 -0
  83. package/dist/vue/props.d.mts +23 -0
  84. package/dist/vue/props.d.mts.map +1 -0
  85. package/dist/vue/props.mjs +41 -0
  86. package/dist/vue/props.mjs.map +1 -0
  87. package/dist/vue/render.d.mts +13 -0
  88. package/dist/vue/render.d.mts.map +1 -0
  89. package/dist/vue/render.mjs +23 -0
  90. package/dist/vue/render.mjs.map +1 -0
  91. package/dist/vue/slots.d.mts +19 -0
  92. package/dist/vue/slots.d.mts.map +1 -0
  93. package/dist/vue/slots.mjs +13 -0
  94. package/dist/vue/slots.mjs.map +1 -0
  95. package/dist/vue/with.d.mts +12 -0
  96. package/dist/vue/with.d.mts.map +1 -0
  97. package/dist/vue/with.mjs +15 -0
  98. package/dist/vue/with.mjs.map +1 -0
  99. package/docs/API.md +96 -0
  100. package/docs/API.zh-CN.md +96 -0
  101. package/docs/DEVELOPMENT_RELEASE.zh-CN.md +65 -0
  102. package/docs/RUNTIME_CONTRACT.md +37 -0
  103. package/package.json +65 -73
  104. package/src/array/index.ts +173 -0
  105. package/src/async/index.ts +475 -0
  106. package/src/base64/index.ts +374 -0
  107. package/src/color/index.ts +208 -0
  108. package/src/crypto/index.ts +670 -0
  109. package/src/date/index.ts +451 -0
  110. package/src/dom/index.ts +6 -0
  111. package/src/dom/style.ts +92 -0
  112. package/src/env/index.ts +169 -0
  113. package/src/identity/index.ts +144 -0
  114. package/src/index.ts +20 -0
  115. package/src/internal/text.ts +46 -0
  116. package/src/logger/index.ts +219 -0
  117. package/src/number/index.ts +235 -0
  118. package/src/object/index.ts +160 -0
  119. package/src/storage/index.ts +524 -0
  120. package/src/string/index.ts +328 -0
  121. package/src/vue/emits.ts +71 -0
  122. package/src/vue/expose.ts +11 -0
  123. package/src/vue/func.ts +17 -0
  124. package/src/vue/index.ts +13 -0
  125. package/src/vue/install.ts +185 -0
  126. package/src/vue/props.ts +39 -0
  127. package/src/vue/render.ts +41 -0
  128. package/src/vue/slots.ts +23 -0
  129. package/src/vue/with.ts +10 -0
  130. package/Fast.png +0 -0
  131. package/dist/index.global.js +0 -14500
  132. package/dist/index.global.js.map +0 -1
  133. package/dist/index.global.min.js +0 -2
  134. package/dist/index.global.min.js.map +0 -1
  135. package/es/array/index.d.ts +0 -19
  136. package/es/array/index.mjs +0 -2
  137. package/es/array/index.mjs.map +0 -1
  138. package/es/base64/index.d.ts +0 -21
  139. package/es/base64/index.mjs +0 -2
  140. package/es/base64/index.mjs.map +0 -1
  141. package/es/click/index.d.ts +0 -33
  142. package/es/click/index.mjs +0 -2
  143. package/es/click/index.mjs.map +0 -1
  144. package/es/color/index.d.ts +0 -33
  145. package/es/color/index.mjs +0 -2
  146. package/es/color/index.mjs.map +0 -1
  147. package/es/console/index.d.ts +0 -31
  148. package/es/console/index.mjs +0 -2
  149. package/es/console/index.mjs.map +0 -1
  150. package/es/crypto/index.d.ts +0 -46
  151. package/es/crypto/index.mjs +0 -2
  152. package/es/crypto/index.mjs.map +0 -1
  153. package/es/date/index.d.ts +0 -44
  154. package/es/date/index.mjs +0 -2
  155. package/es/date/index.mjs.map +0 -1
  156. package/es/dom/index.d.ts +0 -1
  157. package/es/dom/index.mjs +0 -2
  158. package/es/dom/index.mjs.map +0 -1
  159. package/es/dom/style.d.ts +0 -12
  160. package/es/dom/style.mjs +0 -2
  161. package/es/dom/style.mjs.map +0 -1
  162. package/es/env/index.d.ts +0 -25
  163. package/es/env/index.mjs +0 -2
  164. package/es/env/index.mjs.map +0 -1
  165. package/es/error/index.d.ts +0 -3
  166. package/es/error/index.mjs +0 -2
  167. package/es/error/index.mjs.map +0 -1
  168. package/es/identity/index.d.ts +0 -14
  169. package/es/identity/index.mjs +0 -2
  170. package/es/identity/index.mjs.map +0 -1
  171. package/es/index.d.ts +0 -15
  172. package/es/index.es.d.ts +0 -2
  173. package/es/index.mjs +0 -2
  174. package/es/index.mjs.map +0 -1
  175. package/es/object/index.d.ts +0 -13
  176. package/es/object/index.mjs +0 -2
  177. package/es/object/index.mjs.map +0 -1
  178. package/es/storage/index.d.ts +0 -96
  179. package/es/storage/index.mjs +0 -2
  180. package/es/storage/index.mjs.map +0 -1
  181. package/es/string/index.d.ts +0 -114
  182. package/es/string/index.mjs +0 -2
  183. package/es/string/index.mjs.map +0 -1
  184. package/es/vue/emits.d.ts +0 -8
  185. package/es/vue/emits.mjs +0 -2
  186. package/es/vue/emits.mjs.map +0 -1
  187. package/es/vue/expose.d.ts +0 -4
  188. package/es/vue/expose.mjs +0 -2
  189. package/es/vue/expose.mjs.map +0 -1
  190. package/es/vue/func.d.ts +0 -6
  191. package/es/vue/func.mjs +0 -2
  192. package/es/vue/func.mjs.map +0 -1
  193. package/es/vue/index.d.ts +0 -8
  194. package/es/vue/index.mjs +0 -2
  195. package/es/vue/index.mjs.map +0 -1
  196. package/es/vue/install.d.ts +0 -5
  197. package/es/vue/install.mjs +0 -2
  198. package/es/vue/install.mjs.map +0 -1
  199. package/es/vue/props.d.ts +0 -9
  200. package/es/vue/props.mjs +0 -2
  201. package/es/vue/props.mjs.map +0 -1
  202. package/es/vue/slots.d.ts +0 -11
  203. package/es/vue/slots.mjs +0 -2
  204. package/es/vue/slots.mjs.map +0 -1
  205. package/es/vue/useRender.d.ts +0 -6
  206. package/es/vue/useRender.mjs +0 -2
  207. package/es/vue/useRender.mjs.map +0 -1
  208. package/es/vue/with.d.ts +0 -5
  209. package/es/vue/with.mjs +0 -2
  210. package/es/vue/with.mjs.map +0 -1
  211. package/lib/array/index.d.ts +0 -19
  212. package/lib/array/index.js +0 -2
  213. package/lib/array/index.js.map +0 -1
  214. package/lib/base64/index.d.ts +0 -21
  215. package/lib/base64/index.js +0 -2
  216. package/lib/base64/index.js.map +0 -1
  217. package/lib/click/index.d.ts +0 -33
  218. package/lib/click/index.js +0 -2
  219. package/lib/click/index.js.map +0 -1
  220. package/lib/color/index.d.ts +0 -33
  221. package/lib/color/index.js +0 -2
  222. package/lib/color/index.js.map +0 -1
  223. package/lib/console/index.d.ts +0 -31
  224. package/lib/console/index.js +0 -2
  225. package/lib/console/index.js.map +0 -1
  226. package/lib/crypto/index.d.ts +0 -46
  227. package/lib/crypto/index.js +0 -2
  228. package/lib/crypto/index.js.map +0 -1
  229. package/lib/date/index.d.ts +0 -44
  230. package/lib/date/index.js +0 -2
  231. package/lib/date/index.js.map +0 -1
  232. package/lib/dom/index.d.ts +0 -1
  233. package/lib/dom/index.js +0 -2
  234. package/lib/dom/index.js.map +0 -1
  235. package/lib/dom/style.d.ts +0 -12
  236. package/lib/dom/style.js +0 -2
  237. package/lib/dom/style.js.map +0 -1
  238. package/lib/env/index.d.ts +0 -25
  239. package/lib/env/index.js +0 -2
  240. package/lib/env/index.js.map +0 -1
  241. package/lib/error/index.d.ts +0 -3
  242. package/lib/error/index.js +0 -2
  243. package/lib/error/index.js.map +0 -1
  244. package/lib/identity/index.d.ts +0 -14
  245. package/lib/identity/index.js +0 -2
  246. package/lib/identity/index.js.map +0 -1
  247. package/lib/index.d.ts +0 -15
  248. package/lib/index.es.d.ts +0 -2
  249. package/lib/index.js +0 -2
  250. package/lib/index.js.map +0 -1
  251. package/lib/object/index.d.ts +0 -13
  252. package/lib/object/index.js +0 -2
  253. package/lib/object/index.js.map +0 -1
  254. package/lib/storage/index.d.ts +0 -96
  255. package/lib/storage/index.js +0 -2
  256. package/lib/storage/index.js.map +0 -1
  257. package/lib/string/index.d.ts +0 -114
  258. package/lib/string/index.js +0 -2
  259. package/lib/string/index.js.map +0 -1
  260. package/lib/vue/emits.d.ts +0 -8
  261. package/lib/vue/emits.js +0 -2
  262. package/lib/vue/emits.js.map +0 -1
  263. package/lib/vue/expose.d.ts +0 -4
  264. package/lib/vue/expose.js +0 -2
  265. package/lib/vue/expose.js.map +0 -1
  266. package/lib/vue/func.d.ts +0 -6
  267. package/lib/vue/func.js +0 -2
  268. package/lib/vue/func.js.map +0 -1
  269. package/lib/vue/index.d.ts +0 -8
  270. package/lib/vue/index.js +0 -2
  271. package/lib/vue/index.js.map +0 -1
  272. package/lib/vue/install.d.ts +0 -5
  273. package/lib/vue/install.js +0 -2
  274. package/lib/vue/install.js.map +0 -1
  275. package/lib/vue/props.d.ts +0 -9
  276. package/lib/vue/props.js +0 -2
  277. package/lib/vue/props.js.map +0 -1
  278. package/lib/vue/slots.d.ts +0 -11
  279. package/lib/vue/slots.js +0 -2
  280. package/lib/vue/slots.js.map +0 -1
  281. package/lib/vue/useRender.d.ts +0 -6
  282. package/lib/vue/useRender.js +0 -2
  283. package/lib/vue/useRender.js.map +0 -1
  284. package/lib/vue/with.d.ts +0 -5
  285. package/lib/vue/with.js +0 -2
  286. package/lib/vue/with.js.map +0 -1
@@ -0,0 +1,134 @@
1
+ //#region src/object/index.ts
2
+ /**
3
+ * 判断 Query Value 是否为重复参数数组。
4
+ *
5
+ * @param value - 单值或数组形式的 Query Value。
6
+ * @returns 是只读原始值数组时返回 `true`。
7
+ */
8
+ const isQueryPrimitiveArray = (value) => Array.isArray(value);
9
+ /**
10
+ * 安全写入结果对象的自有可枚举属性。
11
+ *
12
+ * @remarks 使用 `defineProperty` 避免 `__proto__` 触发 Setter,并显式拒绝三个原型污染键。
13
+ * @param target - 要写入的结果对象。
14
+ * @param key - 自有属性键。
15
+ * @param value - 属性值。
16
+ * @throws `TypeError` 当键为 `__proto__`、`prototype` 或 `constructor`。
17
+ */
18
+ const defineEnumerableProperty = (target, key, value) => {
19
+ Object.defineProperty(target, key, {
20
+ configurable: true,
21
+ enumerable: true,
22
+ value,
23
+ writable: true
24
+ });
25
+ };
26
+ /**
27
+ * 判断值是否是普通对象。
28
+ *
29
+ * @param value - 任意待检查值。
30
+ * @returns 原型为 `Object.prototype` 或 `null` 时返回 `true`。
31
+ */
32
+ function isPlainObject(value) {
33
+ if (typeof value !== "object" || value === null) return false;
34
+ const prototype = Object.getPrototypeOf(value);
35
+ return prototype === null || prototype === Object.prototype;
36
+ }
37
+ /**
38
+ * 安全判断对象是否拥有自己的属性。
39
+ *
40
+ * @remarks 不调用可能被对象覆盖的 `hasOwnProperty`。
41
+ * @param value - 待检查对象。
42
+ * @param key - 字符串、数字或 Symbol 属性键。
43
+ * @returns 属性为对象自有属性时返回 `true`,并收窄键类型。
44
+ */
45
+ function hasOwn(value, key) {
46
+ return Object.hasOwn(value, key);
47
+ }
48
+ /**
49
+ * 从对象中选择指定自有可枚举属性。
50
+ *
51
+ * @param source - 不会被修改的源对象。
52
+ * @param keys - 需要保留的键;不存在的键被忽略。
53
+ * @returns 新对象,保持 `keys` 的遍历顺序。
54
+ */
55
+ function pick(source, keys) {
56
+ const result = {};
57
+ for (const key of keys) if (Object.prototype.propertyIsEnumerable.call(source, key)) defineEnumerableProperty(result, key, source[key]);
58
+ return result;
59
+ }
60
+ /**
61
+ * 浅复制对象并删除指定属性。
62
+ *
63
+ * @param source - 不会被修改的源对象。
64
+ * @param keys - 需要排除的键。
65
+ * @returns 包含其余自有可枚举字符串与 Symbol 属性的新对象。
66
+ */
67
+ function omit(source, keys) {
68
+ const result = { ...source };
69
+ for (const key of keys) Reflect.deleteProperty(result, key);
70
+ return result;
71
+ }
72
+ /**
73
+ * 映射对象的自有可枚举属性值。
74
+ *
75
+ * @param source - 不会被修改的源对象。
76
+ * @param mapper - 接收值、键和源对象的映射函数。
77
+ * @returns 保留原键的新对象。
78
+ */
79
+ function mapValues(source, mapper) {
80
+ const result = {};
81
+ for (const key of Reflect.ownKeys(source)) if (Object.prototype.propertyIsEnumerable.call(source, key)) defineEnumerableProperty(result, key, mapper(source[key], key, source));
82
+ return result;
83
+ }
84
+ /**
85
+ * 对自有可枚举属性执行 SameValue 浅比较。
86
+ *
87
+ * @remarks 嵌套对象只比较引用;`NaN` 相等,`0` 与 `-0` 不相等。
88
+ * @param left - 第一对象。
89
+ * @param right - 第二对象。
90
+ * @returns 自有可枚举键集合与对应值均满足 SameValue 时返回 `true`。
91
+ */
92
+ function shallowEqual(left, right) {
93
+ if (Object.is(left, right)) return true;
94
+ const leftKeys = Reflect.ownKeys(left).filter((key) => Object.prototype.propertyIsEnumerable.call(left, key));
95
+ const rightKeys = Reflect.ownKeys(right).filter((key) => Object.prototype.propertyIsEnumerable.call(right, key));
96
+ if (leftKeys.length !== rightKeys.length) return false;
97
+ return leftKeys.every((key) => Object.hasOwn(right, key) && Object.is(Reflect.get(left, key), Reflect.get(right, key)));
98
+ }
99
+ /**
100
+ * 把 Query 原始值规范化为文本。
101
+ *
102
+ * @param value - 已排除空值的字符串、数字、布尔值或 BigInt。
103
+ * @returns 与 URLSearchParams 兼容的文本值。
104
+ * @throws `RangeError` 当数字不是有限值。
105
+ */
106
+ const serializeQueryValue = (value) => {
107
+ if (typeof value === "number" && !Number.isFinite(value)) throw new RangeError("Query parameter numbers must be finite.");
108
+ return String(value);
109
+ };
110
+ /**
111
+ * 将对象序列化为标准 URL 查询字符串。
112
+ *
113
+ * @remarks `null` 与 `undefined` 被跳过;数组使用重复键;返回值不会修改输入。
114
+ * @param value - 查询参数对象。
115
+ * @param options - 排序、空格和问号前缀选项。
116
+ * @returns URL 编码后的查询字符串;没有参数时始终返回空字符串。
117
+ * @throws `RangeError` 当参数包含 `NaN` 或无穷数字。
118
+ */
119
+ function toQueryString(value, options = {}) {
120
+ const entries = Object.entries(value);
121
+ if (options.sort) entries.sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
122
+ const parameters = new URLSearchParams();
123
+ for (const [key, rawValue] of entries) {
124
+ const values = isQueryPrimitiveArray(rawValue) ? rawValue : [rawValue];
125
+ for (const item of values) if (item !== null && item !== void 0) parameters.append(key, serializeQueryValue(item));
126
+ }
127
+ let result = parameters.toString();
128
+ if (options.space === "percent") result = result.replace(/\+/gu, "%20");
129
+ return result && options.prefixQuestionMark ? `?${result}` : result;
130
+ }
131
+ //#endregion
132
+ export { hasOwn, isPlainObject, mapValues, omit, pick, shallowEqual, toQueryString };
133
+
134
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/object/index.ts"],"sourcesContent":["/** URL 查询参数支持的单值类型。 */\nexport type QueryPrimitive = bigint | boolean | number | string | null | undefined;\n\n/** URL 查询参数值;数组使用重复键表示。 */\nexport type QueryValue = QueryPrimitive | readonly QueryPrimitive[];\n\n/**\n * 判断 Query Value 是否为重复参数数组。\n *\n * @param value - 单值或数组形式的 Query Value。\n * @returns 是只读原始值数组时返回 `true`。\n */\nconst isQueryPrimitiveArray = (value: QueryValue): value is readonly QueryPrimitive[] => Array.isArray(value);\n\n/** {@link toQueryString} 的序列化选项。 */\nexport interface QueryStringOptions {\n\t/** 返回非空结果时是否添加 `?`;默认 `false`。 */\n\tprefixQuestionMark?: boolean;\n\t/** 是否按键的 UTF-16 码元顺序稳定排序;默认保留对象枚举顺序。 */\n\tsort?: boolean;\n\t/** 空格编码方式;默认遵循表单编码并输出 `+`。 */\n\tspace?: \"percent\" | \"plus\";\n}\n\n/**\n * 安全写入结果对象的自有可枚举属性。\n *\n * @remarks 使用 `defineProperty` 避免 `__proto__` 触发 Setter,并显式拒绝三个原型污染键。\n * @param target - 要写入的结果对象。\n * @param key - 自有属性键。\n * @param value - 属性值。\n * @throws `TypeError` 当键为 `__proto__`、`prototype` 或 `constructor`。\n */\nconst defineEnumerableProperty = (target: object, key: PropertyKey, value: unknown): void => {\n\tObject.defineProperty(target, key, { configurable: true, enumerable: true, value, writable: true });\n};\n\n/**\n * 判断值是否是普通对象。\n *\n * @param value - 任意待检查值。\n * @returns 原型为 `Object.prototype` 或 `null` 时返回 `true`。\n */\nexport function isPlainObject(value: unknown): value is Record<PropertyKey, unknown> {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst prototype = Object.getPrototypeOf(value) as object | null;\n\treturn prototype === null || prototype === Object.prototype;\n}\n\n/**\n * 安全判断对象是否拥有自己的属性。\n *\n * @remarks 不调用可能被对象覆盖的 `hasOwnProperty`。\n * @param value - 待检查对象。\n * @param key - 字符串、数字或 Symbol 属性键。\n * @returns 属性为对象自有属性时返回 `true`,并收窄键类型。\n */\nexport function hasOwn<ObjectType extends object, Key extends PropertyKey>(value: ObjectType, key: Key): key is Key & keyof ObjectType {\n\treturn Object.hasOwn(value, key);\n}\n\n/**\n * 从对象中选择指定自有可枚举属性。\n *\n * @param source - 不会被修改的源对象。\n * @param keys - 需要保留的键;不存在的键被忽略。\n * @returns 新对象,保持 `keys` 的遍历顺序。\n */\nexport function pick<Source extends object, Keys extends readonly (keyof Source)[]>(source: Source, keys: Keys): Pick<Source, Keys[number]> {\n\tconst result = {} as Pick<Source, Keys[number]>;\n\tfor (const key of keys) {\n\t\tif (Object.prototype.propertyIsEnumerable.call(source, key)) defineEnumerableProperty(result, key, source[key]);\n\t}\n\treturn result;\n}\n\n/**\n * 浅复制对象并删除指定属性。\n *\n * @param source - 不会被修改的源对象。\n * @param keys - 需要排除的键。\n * @returns 包含其余自有可枚举字符串与 Symbol 属性的新对象。\n */\nexport function omit<Source extends object, Keys extends readonly (keyof Source)[]>(source: Source, keys: Keys): Omit<Source, Keys[number]> {\n\tconst result = { ...source };\n\tfor (const key of keys) Reflect.deleteProperty(result, key);\n\treturn result;\n}\n\n/**\n * 映射对象的自有可枚举属性值。\n *\n * @param source - 不会被修改的源对象。\n * @param mapper - 接收值、键和源对象的映射函数。\n * @returns 保留原键的新对象。\n */\nexport function mapValues<Source extends object, Result>(\n\tsource: Source,\n\tmapper: (value: Source[keyof Source], key: keyof Source, source: Source) => Result\n): { [Key in keyof Source]: Result } {\n\tconst result = {} as { [Key in keyof Source]: Result };\n\tfor (const key of Reflect.ownKeys(source) as (keyof Source)[]) {\n\t\tif (Object.prototype.propertyIsEnumerable.call(source, key)) defineEnumerableProperty(result, key, mapper(source[key], key, source));\n\t}\n\treturn result;\n}\n\n/**\n * 对自有可枚举属性执行 SameValue 浅比较。\n *\n * @remarks 嵌套对象只比较引用;`NaN` 相等,`0` 与 `-0` 不相等。\n * @param left - 第一对象。\n * @param right - 第二对象。\n * @returns 自有可枚举键集合与对应值均满足 SameValue 时返回 `true`。\n */\nexport function shallowEqual(left: object, right: object): boolean {\n\tif (Object.is(left, right)) return true;\n\tconst leftKeys = Reflect.ownKeys(left).filter((key) => Object.prototype.propertyIsEnumerable.call(left, key));\n\tconst rightKeys = Reflect.ownKeys(right).filter((key) => Object.prototype.propertyIsEnumerable.call(right, key));\n\tif (leftKeys.length !== rightKeys.length) return false;\n\treturn leftKeys.every((key) => Object.hasOwn(right, key) && Object.is(Reflect.get(left, key), Reflect.get(right, key)));\n}\n\n/**\n * 把 Query 原始值规范化为文本。\n *\n * @param value - 已排除空值的字符串、数字、布尔值或 BigInt。\n * @returns 与 URLSearchParams 兼容的文本值。\n * @throws `RangeError` 当数字不是有限值。\n */\nconst serializeQueryValue = (value: Exclude<QueryPrimitive, null | undefined>): string => {\n\tif (typeof value === \"number\" && !Number.isFinite(value)) {\n\t\tthrow new RangeError(\"Query parameter numbers must be finite.\");\n\t}\n\treturn String(value);\n};\n\n/**\n * 将对象序列化为标准 URL 查询字符串。\n *\n * @remarks `null` 与 `undefined` 被跳过;数组使用重复键;返回值不会修改输入。\n * @param value - 查询参数对象。\n * @param options - 排序、空格和问号前缀选项。\n * @returns URL 编码后的查询字符串;没有参数时始终返回空字符串。\n * @throws `RangeError` 当参数包含 `NaN` 或无穷数字。\n */\nexport function toQueryString(value: Readonly<Record<string, QueryValue>>, options: QueryStringOptions = {}): string {\n\tconst entries = Object.entries(value);\n\tif (options.sort) entries.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));\n\tconst parameters = new URLSearchParams();\n\tfor (const [key, rawValue] of entries) {\n\t\tconst values = isQueryPrimitiveArray(rawValue) ? rawValue : [rawValue];\n\t\tfor (const item of values) {\n\t\t\tif (item !== null && item !== undefined) parameters.append(key, serializeQueryValue(item));\n\t\t}\n\t}\n\tlet result = parameters.toString();\n\tif (options.space === \"percent\") result = result.replace(/\\+/gu, \"%20\");\n\treturn result && options.prefixQuestionMark ? `?${result}` : result;\n}\n"],"mappings":";;;;;;;AAYA,MAAM,yBAAyB,UAA0D,MAAM,QAAQ,KAAK;;;;;;;;;;AAqB5G,MAAM,4BAA4B,QAAgB,KAAkB,UAAyB;CAC5F,OAAO,eAAe,QAAQ,KAAK;EAAE,cAAc;EAAM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Q,OAAO;CACjD,OAAO,SAAS,OAAO,QAAQ,OAAO,OAAO,OAAO,GAAG,KAAK,OAAO,GAAG,QAAQ,IAAI,MAAM,GAAG,GAAG,QAAQ,IAAI,OAAO,GAAG,CAAC,CAAC;AACvH;;;;;;;;AASA,MAAM,uBAAuB,UAA6D;CACzF,IAAI,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,GACtD,MAAM,IAAI,WAAW,yCAAyC;CAE/D,OAAO,OAAO,KAAK;AACpB;;;;;;;;;;AAWA,SAAgB,cAAc,OAA6C,UAA8B,CAAC,GAAW;CACpH,MAAM,UAAU,OAAO,QAAQ,KAAK;CACpC,IAAI,QAAQ,MAAM,QAAQ,MAAM,CAAC,OAAO,CAAC,WAAY,OAAO,QAAQ,KAAK,OAAO,QAAQ,IAAI,CAAE;CAC9F,MAAM,aAAa,IAAI,gBAAgB;CACvC,KAAK,MAAM,CAAC,KAAK,aAAa,SAAS;EACtC,MAAM,SAAS,sBAAsB,QAAQ,IAAI,WAAW,CAAC,QAAQ;EACrE,KAAK,MAAM,QAAQ,QAClB,IAAI,SAAS,QAAQ,SAAS,KAAA,GAAW,WAAW,OAAO,KAAK,oBAAoB,IAAI,CAAC;CAE3F;CACA,IAAI,SAAS,WAAW,SAAS;CACjC,IAAI,QAAQ,UAAU,WAAW,SAAS,OAAO,QAAQ,QAAQ,KAAK;CACtE,OAAO,UAAU,QAAQ,qBAAqB,IAAI,WAAW;AAC9D"}
@@ -0,0 +1,104 @@
1
+ //#region src/storage/index.d.ts
2
+ /** Storage 业务值编码器。 */
3
+ interface StorageCodec {
4
+ /**
5
+ * 把已编码文本恢复为业务值。
6
+ * @param value - 由同一 Codec 的 `encode` 生成并持久化的文本。
7
+ * @returns 解码后的业务值。
8
+ * @throws 当文本损坏、格式不受支持或无法反序列化时应抛出错误。
9
+ */
10
+ decode: (value: string) => unknown;
11
+ /**
12
+ * 把业务值编码为可持久化字符串。
13
+ * @param value - 调用方传入的业务值。
14
+ * @returns 可由同一 Codec 的 `decode` 无损恢复的文本。
15
+ * @throws 当值不受支持或无法序列化时应抛出错误。
16
+ */
17
+ encode: (value: unknown) => string;
18
+ }
19
+ /** 程序入口调用 {@link configureStorage} 时使用的全局配置。 */
20
+ interface StorageConfiguration {
21
+ /** 自定义值编码器;默认使用严格 JSON Codec,同一应用生命周期内必须保持同一引用。 */
22
+ codec?: StorageCodec;
23
+ /** 返回 Unix 毫秒时间戳的时钟;默认使用 `Date.now`,主要用于 TTL 测试与受控时间源。 */
24
+ now?: () => number;
25
+ /** 所有物理键使用的非空命名空间前缀;`clear` 与 `keys` 不会越过该范围。 */
26
+ prefix: string;
27
+ }
28
+ /** 单次 Storage 写入配置。 */
29
+ interface StorageWriteOptions {
30
+ /** 从写入时刻开始的有效毫秒数;必须是大于 0 的有限数,省略时永久有效。 */
31
+ ttlMs?: number;
32
+ }
33
+ /** `Local` 与 `Session` 的统一操作接口。 */
34
+ interface StorageArea {
35
+ /** 当前全局 Storage 配置的物理键前缀;读取它会要求 Storage 已经完成配置。 */
36
+ readonly prefix: string;
37
+ /**
38
+ * 删除当前命名空间内的全部键,不影响同一后端中的其他应用键。
39
+ * @throws `Error` 当 Storage 尚未配置或后端不可用。
40
+ */
41
+ clear: () => void;
42
+ /**
43
+ * 获取并解码业务值;已过期记录会在读取时删除。
44
+ * @param key - 不含全局前缀的非空业务键。
45
+ * @returns 解码后的值;键缺失或过期时返回 `undefined`。
46
+ * @throws 当键非法、包络损坏、Codec 解码失败或后端不可用时抛出错误。
47
+ */
48
+ get: <Value = unknown>(key: string) => Value | undefined;
49
+ /**
50
+ * 判断一个可成功读取且未过期的业务键是否存在。
51
+ * @param key - 不含全局前缀的非空业务键。
52
+ * @returns 键存在且包络有效时返回 `true`。
53
+ */
54
+ has: (key: string) => boolean;
55
+ /**
56
+ * 返回当前命名空间内的业务键快照。
57
+ * @returns 已移除全局前缀并按字典序排列的新数组;不会自动清理过期项。
58
+ */
59
+ keys: () => string[];
60
+ /**
61
+ * 扫描当前命名空间并删除全部过期记录。
62
+ * @returns 本次实际删除的记录数量。
63
+ * @throws 当发现损坏包络或后端不可用时抛出错误。
64
+ */
65
+ pruneExpired: () => number;
66
+ /**
67
+ * 删除单个业务键;键不存在时保持幂等。
68
+ * @param key - 不含全局前缀的非空业务键。
69
+ */
70
+ remove: (key: string) => void;
71
+ /**
72
+ * 删除业务键以指定文本开头的全部条目,范围仍受全局命名空间限制。
73
+ * @param keyPrefix - 不含全局前缀的非空业务键前缀。
74
+ */
75
+ removeByPrefix: (keyPrefix: string) => void;
76
+ /**
77
+ * 编码并写入业务值,可附加惰性清理的 TTL。
78
+ * @param key - 不含全局前缀的非空业务键。
79
+ * @param value - 必须受当前 Codec 支持的业务值。
80
+ * @param options - 可选的单次写入 TTL。
81
+ * @throws 当键、TTL、业务值或后端写入无效时抛出错误。
82
+ */
83
+ set: <Value>(key: string, value: Value, options?: StorageWriteOptions) => void;
84
+ }
85
+ /** Base64 混淆 Codec;只隐藏明文外观,不提供加密、完整性或认证。 */
86
+ declare const base64StorageCodec: StorageCodec;
87
+ /** 浏览器 localStorage 或自动检测的 uni-app Storage 全局业务入口。 */
88
+ declare const Local: StorageArea;
89
+ /** 浏览器 sessionStorage 的全局业务入口;uni-app 不提供会话存储。 */
90
+ declare const Session: StorageArea;
91
+ /**
92
+ * 在应用入口一次性配置 `Local` 与 `Session`。
93
+ *
94
+ * @remarks 首次配置后只允许以完全相同的值和引用重复调用。模块导入不会访问平台对象;调用本函数时若检测到
95
+ * 全局 `uni`,则自动使用其同步 Storage 且只启用 `Local`,否则使用浏览器 `localStorage` 与 `sessionStorage`。
96
+ * @param options - 全局键前缀、Codec 与时钟。
97
+ * @throws 配置非法、重复配置冲突或目标平台 Storage 不可用时抛出错误。
98
+ */
99
+ declare function configureStorage(options: StorageConfiguration): void;
100
+ /** 返回全局 Storage 是否已经由应用入口配置。 */
101
+ declare function isStorageConfigured(): boolean;
102
+ //#endregion
103
+ export { Local, Session, StorageArea, StorageCodec, StorageConfiguration, StorageWriteOptions, base64StorageCodec, configureStorage, isStorageConfigured };
104
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/storage/index.ts"],"mappings":";;UAmCiB;;;;;;;EAOhB,SAAS;;;;;;;EAOT,SAAS;;;UAIO;;EAEhB,QAAQ;;EAER;;EAEA;;;UAIgB;;EAEhB;;;UAIgB;;WAEP;;;;;EAKT;;;;;;;EAOA,MAAM,iBAAiB,gBAAgB;;;;;;EAMvC,MAAM;;;;;EAKN;;;;;;EAMA;;;;;EAKA,SAAS;;;;;EAKT,iBAAiB;;;;;;;;EAQjB,MAAM,OAAO,aAAa,OAAO,OAAO,UAAU;;;cAsFtC,oBAAoB;;cAuRpB,OAAO;;cAGP,SAAS;;;;;;;;;iBAUN,iBAAiB,SAAS;;iBAyB1B"}
@@ -0,0 +1,324 @@
1
+ import { decodeBase64, encodeBase64 } from "../base64/index.mjs";
2
+ //#region src/storage/index.ts
3
+ const runtimeStorageGlobals = globalThis;
4
+ /**
5
+ * 读取并校验当前运行时的全局 uni-app 同步 Storage。
6
+ *
7
+ * @returns 检测到 uni-app 时返回同步 Storage;普通浏览器环境返回 `undefined`。
8
+ * @throws `TypeError` 当全局 `uni` 存在但缺少本库需要的同步 Storage 方法。
9
+ */
10
+ const getGlobalUniStorage = () => {
11
+ const value = runtimeStorageGlobals.uni;
12
+ if (value === void 0) return void 0;
13
+ if (typeof value !== "object" && typeof value !== "function" || value === null) throw new TypeError("The global uni object does not provide synchronous Storage APIs.");
14
+ const storage = value;
15
+ if (typeof storage.getStorageSync !== "function" || typeof storage.getStorageInfoSync !== "function" || typeof storage.removeStorageSync !== "function" || typeof storage.setStorageSync !== "function") throw new TypeError("The global uni object does not provide synchronous Storage APIs.");
16
+ return storage;
17
+ };
18
+ /** 默认 JSON Codec;显式拒绝会被 JSON.stringify 静默丢弃的顶层值。 */
19
+ const jsonCodec = {
20
+ decode: (value) => JSON.parse(value),
21
+ encode: (value) => {
22
+ const encoded = JSON.stringify(value);
23
+ if (typeof encoded !== "string") throw new TypeError("The storage value is not JSON-serializable.");
24
+ return encoded;
25
+ }
26
+ };
27
+ /** Base64 混淆 Codec;只隐藏明文外观,不提供加密、完整性或认证。 */
28
+ const base64StorageCodec = {
29
+ decode: (value) => JSON.parse(decodeBase64(value)),
30
+ encode: (value) => {
31
+ const encoded = JSON.stringify(value);
32
+ if (typeof encoded !== "string") throw new TypeError("The storage value is not JSON-serializable.");
33
+ return encodeBase64(encoded);
34
+ }
35
+ };
36
+ /** 页面级唯一配置;只允许幂等重复配置,避免模块加载顺序改变行为。 */
37
+ let activeConfiguration;
38
+ /**
39
+ * 判断未知值是否为非数组对象记录。
40
+ *
41
+ * @param value - JSON.parse 返回的未知值。
42
+ * @returns 值为非空、非数组对象时返回 `true`。
43
+ */
44
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
45
+ /**
46
+ * 校验 Storage 业务键。
47
+ *
48
+ * @param key - 不含全局 Prefix 的业务键或业务键前缀。
49
+ * @throws `TypeError` 当值不是非空字符串。
50
+ */
51
+ const assertKey = (key) => {
52
+ if (typeof key !== "string" || key.length === 0) throw new TypeError("Storage keys must be non-empty strings.");
53
+ };
54
+ /**
55
+ * 创建浏览器 Storage 后端。
56
+ *
57
+ * @remarks 平台对象在调用阶段读取,因此导入模块不会访问浏览器全局对象。
58
+ * @param kind - 选择 `localStorage` 或 `sessionStorage`。
59
+ * @returns 统一的内部同步后端。
60
+ * @throws `Error` 当所选 Storage 在当前环境不可用。
61
+ */
62
+ const createWebStorageBackend = (kind) => {
63
+ const storage = kind === "local" ? runtimeStorageGlobals.localStorage : runtimeStorageGlobals.sessionStorage;
64
+ if (storage === void 0) throw new Error(`${kind}Storage is unavailable in the current runtime.`);
65
+ return {
66
+ getItem: (key) => storage.getItem(key),
67
+ keys: () => {
68
+ const keys = [];
69
+ for (let index = 0; index < storage.length; index += 1) {
70
+ const key = storage.key(index);
71
+ if (key !== null) keys.push(key);
72
+ }
73
+ return keys;
74
+ },
75
+ removeItem: (key) => {
76
+ storage.removeItem(key);
77
+ },
78
+ setItem: (key, value) => {
79
+ storage.setItem(key, value);
80
+ }
81
+ };
82
+ };
83
+ /**
84
+ * 把 uni-app 同步 Storage 适配为内部后端。
85
+ *
86
+ * @remarks uni-app 以空字符串同时表示“键缺失”和“真实空值”,因此空字符串需要结合键清单消除歧义。
87
+ * @param storage - 已从全局 `uni` 读取并校验的同步 API。
88
+ * @returns 统一的内部同步后端。
89
+ */
90
+ const createUniStorageBackend = (storage) => ({
91
+ getItem: (key) => {
92
+ const value = storage.getStorageSync(key);
93
+ if (value !== "") return value;
94
+ return storage.getStorageInfoSync().keys.includes(key) ? value : void 0;
95
+ },
96
+ keys: () => [...storage.getStorageInfoSync().keys],
97
+ removeItem: (key) => {
98
+ storage.removeStorageSync(key);
99
+ },
100
+ setItem: (key, value) => {
101
+ storage.setStorageSync(key, value);
102
+ }
103
+ });
104
+ /**
105
+ * 解析并校验版本化 Storage 包络。
106
+ *
107
+ * @param rawValue - 后端返回的原始值。
108
+ * @param key - 用于错误定位的完整物理键。
109
+ * @returns 当前 v3 包络。
110
+ * @throws `TypeError` 当原始值不是字符串、JSON 损坏、版本不支持或字段类型非法。
111
+ */
112
+ const parseStoredEnvelope = (rawValue, key) => {
113
+ if (typeof rawValue !== "string") throw new TypeError(`Storage entry "${key}" is not a string.`);
114
+ try {
115
+ const parsed = JSON.parse(rawValue);
116
+ if (!isRecord(parsed) || parsed["version"] !== 3 || typeof parsed["data"] !== "string" || !(parsed["expiresAt"] === null || typeof parsed["expiresAt"] === "number" && Number.isFinite(parsed["expiresAt"]))) throw new TypeError("Unsupported storage envelope.");
117
+ return {
118
+ data: parsed["data"],
119
+ expiresAt: parsed["expiresAt"],
120
+ version: 3
121
+ };
122
+ } catch (cause) {
123
+ throw new TypeError(`Storage entry "${key}" is corrupted or unsupported.`, { cause });
124
+ }
125
+ };
126
+ /**
127
+ * 创建绑定命名空间、Codec 与时钟的 Storage Area。
128
+ *
129
+ * @param backendFactory - 每次操作时解析平台后端的工厂,保证导入安全并反映平台可用性。
130
+ * @param prefix - 已校验的全局物理键前缀。
131
+ * @param codec - 业务值与包络文本之间的 Codec。
132
+ * @param now - TTL 计算使用的可注入时钟。
133
+ * @returns 完整的命名空间 Storage 操作集合。
134
+ */
135
+ const createStorageArea = (backendFactory, prefix, codec, now) => {
136
+ /**
137
+ * 拼接物理键。
138
+ *
139
+ * @param key - 已校验业务键。
140
+ * @returns 带当前命名空间前缀的物理键。
141
+ */
142
+ const toStorageKey = (key) => `${prefix}${key}`;
143
+ /**
144
+ * 枚举当前命名空间中的业务键。
145
+ *
146
+ * @param backend - 本次操作使用的后端。
147
+ * @returns 已移除物理前缀、去重并排序的业务键。
148
+ * @throws `TypeError` 当后端返回非字符串键。
149
+ */
150
+ const listBusinessKeys = (backend) => {
151
+ const keys = backend.keys();
152
+ if (!Array.isArray(keys) || !keys.every((key) => typeof key === "string")) throw new TypeError("Storage backend keys must be strings.");
153
+ return [...new Set(keys.filter((key) => key.startsWith(prefix)).map((key) => key.slice(prefix.length)))].sort();
154
+ };
155
+ /**
156
+ * 读取并处理单个包络。
157
+ *
158
+ * @param backend - 本次操作使用的后端。
159
+ * @param key - 业务键。
160
+ * @returns 未过期包络;键缺失或已经过期时返回 `undefined`。
161
+ * @throws `TypeError` 当键或包络非法。
162
+ * @throws `RangeError` 当注入时钟返回非有限时间戳。
163
+ */
164
+ const readStoredEnvelope = (backend, key) => {
165
+ assertKey(key);
166
+ const storageKey = toStorageKey(key);
167
+ const rawValue = backend.getItem(storageKey);
168
+ if (rawValue === null || rawValue === void 0) return void 0;
169
+ const envelope = parseStoredEnvelope(rawValue, storageKey);
170
+ if (envelope.expiresAt === null) return envelope;
171
+ const timestamp = now();
172
+ if (!Number.isFinite(timestamp)) throw new RangeError("Storage clock must return a finite timestamp.");
173
+ if (timestamp < envelope.expiresAt) return envelope;
174
+ backend.removeItem(storageKey);
175
+ };
176
+ return {
177
+ prefix,
178
+ clear() {
179
+ const backend = backendFactory();
180
+ for (const key of listBusinessKeys(backend)) backend.removeItem(toStorageKey(key));
181
+ },
182
+ get(key) {
183
+ const envelope = readStoredEnvelope(backendFactory(), key);
184
+ if (envelope === void 0) return void 0;
185
+ try {
186
+ return codec.decode(envelope.data);
187
+ } catch (cause) {
188
+ throw new TypeError(`Storage entry "${toStorageKey(key)}" could not be decoded.`, { cause });
189
+ }
190
+ },
191
+ has: (key) => readStoredEnvelope(backendFactory(), key) !== void 0,
192
+ keys: () => listBusinessKeys(backendFactory()),
193
+ pruneExpired() {
194
+ const backend = backendFactory();
195
+ let removed = 0;
196
+ for (const key of listBusinessKeys(backend)) {
197
+ const before = backend.getItem(toStorageKey(key));
198
+ if (before !== null && before !== void 0 && readStoredEnvelope(backend, key) === void 0) removed += 1;
199
+ }
200
+ return removed;
201
+ },
202
+ remove(key) {
203
+ assertKey(key);
204
+ backendFactory().removeItem(toStorageKey(key));
205
+ },
206
+ removeByPrefix(keyPrefix) {
207
+ assertKey(keyPrefix);
208
+ const backend = backendFactory();
209
+ for (const key of listBusinessKeys(backend)) if (key.startsWith(keyPrefix)) backend.removeItem(toStorageKey(key));
210
+ },
211
+ set(key, value, options = {}) {
212
+ assertKey(key);
213
+ if (value === void 0) throw new TypeError("Top-level undefined cannot be stored; remove the key instead.");
214
+ let expiresAt = null;
215
+ if (options.ttlMs !== void 0) {
216
+ if (!Number.isFinite(options.ttlMs) || options.ttlMs <= 0) throw new RangeError("ttlMs must be a positive finite number.");
217
+ const timestamp = now();
218
+ if (!Number.isFinite(timestamp) || !Number.isFinite(timestamp + options.ttlMs)) throw new RangeError("Storage expiry exceeds the supported timestamp range.");
219
+ expiresAt = timestamp + options.ttlMs;
220
+ }
221
+ let data;
222
+ try {
223
+ data = codec.encode(value);
224
+ if (typeof data !== "string") throw new TypeError("Storage codecs must return strings.");
225
+ } catch (cause) {
226
+ throw new TypeError("The storage value could not be encoded.", { cause });
227
+ }
228
+ backendFactory().setItem(toStorageKey(key), JSON.stringify({
229
+ data,
230
+ expiresAt,
231
+ version: 3
232
+ }));
233
+ }
234
+ };
235
+ };
236
+ /**
237
+ * 获取已激活的全局 Storage 配置。
238
+ *
239
+ * @returns 首次 `configureStorage` 创建的内部配置。
240
+ * @throws `Error` 当应用入口尚未配置 Storage。
241
+ */
242
+ const requireStorageConfiguration = () => {
243
+ if (activeConfiguration === void 0) throw new Error("Storage is not configured. Call configureStorage() once from the application entry.");
244
+ return activeConfiguration;
245
+ };
246
+ /**
247
+ * 创建稳定的公开 Storage 门面。
248
+ *
249
+ * @param select - 从激活配置选择 Local 或 Session 的函数。
250
+ * @param name - 用于不可用错误的公开门面名称。
251
+ * @returns 可在配置前导入、但只在调用时解析实际 Area 的稳定对象。
252
+ */
253
+ const createStorageAreaProxy = (select, name) => {
254
+ /**
255
+ * 解析当前实际 Area。
256
+ *
257
+ * @returns 配置中的 Local 或 Session Area。
258
+ * @throws `Error` 当尚未配置,或 uni-app 模式请求 Session。
259
+ */
260
+ const getArea = () => {
261
+ const area = select(requireStorageConfiguration());
262
+ if (area === void 0) throw new Error(`${name} is unavailable in uni-app.`);
263
+ return area;
264
+ };
265
+ return {
266
+ get prefix() {
267
+ return getArea().prefix;
268
+ },
269
+ clear: () => {
270
+ getArea().clear();
271
+ },
272
+ get: (key) => getArea().get(key),
273
+ has: (key) => getArea().has(key),
274
+ keys: () => getArea().keys(),
275
+ pruneExpired: () => getArea().pruneExpired(),
276
+ remove: (key) => {
277
+ getArea().remove(key);
278
+ },
279
+ removeByPrefix: (keyPrefix) => {
280
+ getArea().removeByPrefix(keyPrefix);
281
+ },
282
+ set: (key, value, options) => {
283
+ getArea().set(key, value, options);
284
+ }
285
+ };
286
+ };
287
+ /** 浏览器 localStorage 或自动检测的 uni-app Storage 全局业务入口。 */
288
+ const Local = createStorageAreaProxy((configuration) => configuration.local, "Local");
289
+ /** 浏览器 sessionStorage 的全局业务入口;uni-app 不提供会话存储。 */
290
+ const Session = createStorageAreaProxy((configuration) => configuration.session, "Session");
291
+ /**
292
+ * 在应用入口一次性配置 `Local` 与 `Session`。
293
+ *
294
+ * @remarks 首次配置后只允许以完全相同的值和引用重复调用。模块导入不会访问平台对象;调用本函数时若检测到
295
+ * 全局 `uni`,则自动使用其同步 Storage 且只启用 `Local`,否则使用浏览器 `localStorage` 与 `sessionStorage`。
296
+ * @param options - 全局键前缀、Codec 与时钟。
297
+ * @throws 配置非法、重复配置冲突或目标平台 Storage 不可用时抛出错误。
298
+ */
299
+ function configureStorage(options) {
300
+ if (typeof options.prefix !== "string" || options.prefix.length === 0) throw new TypeError("Storage prefix must be a non-empty string.");
301
+ const codec = options.codec ?? jsonCodec;
302
+ const now = options.now ?? Date.now;
303
+ if (activeConfiguration !== void 0) {
304
+ if (activeConfiguration.prefix === options.prefix && activeConfiguration.codec === codec && activeConfiguration.now === now) return;
305
+ throw new Error("Storage has already been configured with different options.");
306
+ }
307
+ const uni = getGlobalUniStorage();
308
+ const configuration = {
309
+ codec,
310
+ local: createStorageArea(uni === void 0 ? () => createWebStorageBackend("local") : () => createUniStorageBackend(uni), options.prefix, codec, now),
311
+ now,
312
+ prefix: options.prefix
313
+ };
314
+ if (uni === void 0) configuration.session = createStorageArea(() => createWebStorageBackend("session"), options.prefix, codec, now);
315
+ activeConfiguration = configuration;
316
+ }
317
+ /** 返回全局 Storage 是否已经由应用入口配置。 */
318
+ function isStorageConfigured() {
319
+ return activeConfiguration !== void 0;
320
+ }
321
+ //#endregion
322
+ export { Local, Session, base64StorageCodec, configureStorage, isStorageConfigured };
323
+
324
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/storage/index.ts"],"sourcesContent":["import { decodeBase64, encodeBase64 } from \"../base64/index.js\";\n\n/** uni-app 同步存储信息中本库实际读取的字段。 */\ninterface UniStorageInfo {\n\t/** 当前平台可见的物理键快照。 */\n\tkeys: readonly string[];\n}\n\n/** 全局 `uni` 必须提供的同步存储 API 最小结构。 */\ninterface UniStorageLike {\n\t/**\n\t * 同步读取一个物理键的原始值。\n\t * @param key - 已包含全局命名空间前缀的物理键。\n\t * @returns 平台保存的值;键缺失时应返回 `undefined`、`null` 或空字符串。\n\t */\n\tgetStorageSync: (key: string) => unknown;\n\t/**\n\t * 同步读取平台当前可见的全部物理键。\n\t * @returns 至少包含只读 `keys` 数组的快照对象。\n\t */\n\tgetStorageInfoSync: () => UniStorageInfo;\n\t/**\n\t * 同步删除一个物理键;键不存在时应保持幂等。\n\t * @param key - 已包含全局命名空间前缀的物理键。\n\t */\n\tremoveStorageSync: (key: string) => void;\n\t/**\n\t * 同步写入已经序列化的包络文本。\n\t * @param key - 已包含全局命名空间前缀的物理键。\n\t * @param value - JSON 包络字符串,不是未经编码的业务值。\n\t */\n\tsetStorageSync: (key: string, value: string) => void;\n}\n\n/** Storage 业务值编码器。 */\nexport interface StorageCodec {\n\t/**\n\t * 把已编码文本恢复为业务值。\n\t * @param value - 由同一 Codec 的 `encode` 生成并持久化的文本。\n\t * @returns 解码后的业务值。\n\t * @throws 当文本损坏、格式不受支持或无法反序列化时应抛出错误。\n\t */\n\tdecode: (value: string) => unknown;\n\t/**\n\t * 把业务值编码为可持久化字符串。\n\t * @param value - 调用方传入的业务值。\n\t * @returns 可由同一 Codec 的 `decode` 无损恢复的文本。\n\t * @throws 当值不受支持或无法序列化时应抛出错误。\n\t */\n\tencode: (value: unknown) => string;\n}\n\n/** 程序入口调用 {@link configureStorage} 时使用的全局配置。 */\nexport interface StorageConfiguration {\n\t/** 自定义值编码器;默认使用严格 JSON Codec,同一应用生命周期内必须保持同一引用。 */\n\tcodec?: StorageCodec;\n\t/** 返回 Unix 毫秒时间戳的时钟;默认使用 `Date.now`,主要用于 TTL 测试与受控时间源。 */\n\tnow?: () => number;\n\t/** 所有物理键使用的非空命名空间前缀;`clear` 与 `keys` 不会越过该范围。 */\n\tprefix: string;\n}\n\n/** 单次 Storage 写入配置。 */\nexport interface StorageWriteOptions {\n\t/** 从写入时刻开始的有效毫秒数;必须是大于 0 的有限数,省略时永久有效。 */\n\tttlMs?: number;\n}\n\n/** `Local` 与 `Session` 的统一操作接口。 */\nexport interface StorageArea {\n\t/** 当前全局 Storage 配置的物理键前缀;读取它会要求 Storage 已经完成配置。 */\n\treadonly prefix: string;\n\t/**\n\t * 删除当前命名空间内的全部键,不影响同一后端中的其他应用键。\n\t * @throws `Error` 当 Storage 尚未配置或后端不可用。\n\t */\n\tclear: () => void;\n\t/**\n\t * 获取并解码业务值;已过期记录会在读取时删除。\n\t * @param key - 不含全局前缀的非空业务键。\n\t * @returns 解码后的值;键缺失或过期时返回 `undefined`。\n\t * @throws 当键非法、包络损坏、Codec 解码失败或后端不可用时抛出错误。\n\t */\n\tget: <Value = unknown>(key: string) => Value | undefined;\n\t/**\n\t * 判断一个可成功读取且未过期的业务键是否存在。\n\t * @param key - 不含全局前缀的非空业务键。\n\t * @returns 键存在且包络有效时返回 `true`。\n\t */\n\thas: (key: string) => boolean;\n\t/**\n\t * 返回当前命名空间内的业务键快照。\n\t * @returns 已移除全局前缀并按字典序排列的新数组;不会自动清理过期项。\n\t */\n\tkeys: () => string[];\n\t/**\n\t * 扫描当前命名空间并删除全部过期记录。\n\t * @returns 本次实际删除的记录数量。\n\t * @throws 当发现损坏包络或后端不可用时抛出错误。\n\t */\n\tpruneExpired: () => number;\n\t/**\n\t * 删除单个业务键;键不存在时保持幂等。\n\t * @param key - 不含全局前缀的非空业务键。\n\t */\n\tremove: (key: string) => void;\n\t/**\n\t * 删除业务键以指定文本开头的全部条目,范围仍受全局命名空间限制。\n\t * @param keyPrefix - 不含全局前缀的非空业务键前缀。\n\t */\n\tremoveByPrefix: (keyPrefix: string) => void;\n\t/**\n\t * 编码并写入业务值,可附加惰性清理的 TTL。\n\t * @param key - 不含全局前缀的非空业务键。\n\t * @param value - 必须受当前 Codec 支持的业务值。\n\t * @param options - 可选的单次写入 TTL。\n\t * @throws 当键、TTL、业务值或后端写入无效时抛出错误。\n\t */\n\tset: <Value>(key: string, value: Value, options?: StorageWriteOptions) => void;\n}\n\n/** 浏览器 Storage 与 uni-app Storage 适配后的最小内部协议。 */\ninterface StorageBackend {\n\t/** 读取物理键原始值;缺失约定由上层统一规范为 `undefined`。 */\n\tgetItem: (key: string) => unknown;\n\t/** 枚举后端可见的全部物理键;返回值必须是不会随枚举过程变化的快照。 */\n\tkeys: () => readonly string[];\n\t/** 删除单个物理键;实现必须允许重复删除。 */\n\tremoveItem: (key: string) => void;\n\t/** 写入已经序列化的包络文本;配额和平台错误保持原样传播。 */\n\tsetItem: (key: string, value: string) => void;\n}\n\n/** 物理存储中的版本化包络;业务值始终先经 Codec 转为文本。 */\ninterface StoredEnvelope {\n\t/** Codec 编码后的业务文本;只有在包络结构校验通过后才能交给 Codec。 */\n\tdata: string;\n\t/** Unix 毫秒绝对过期时间戳;`null` 表示永久有效。 */\n\texpiresAt: number | null;\n\t/** 当前持久化协议版本;读取其他版本必须明确失败,不能猜测迁移。 */\n\tversion: 3;\n}\n\n/** 首次配置后冻结使用的解析结果和两个稳定门面。 */\ninterface ActiveStorageConfiguration {\n\t/** 首次配置后锁定的业务值 Codec 引用。 */\n\tcodec: StorageCodec;\n\t/** 已绑定 Local 后端、命名空间、Codec 与时钟的实际 Area。 */\n\tlocal: StorageArea;\n\t/** 首次配置后锁定的 TTL 时钟引用。 */\n\tnow: () => number;\n\t/** 所有 Area 共享的物理键命名空间前缀。 */\n\tprefix: string;\n\t/** 仅浏览器模式存在的 Session Area;uni-app 模式必须保持缺失。 */\n\tsession?: StorageArea;\n}\n\n/** 浏览器 Storage 在调用阶段延迟读取的平台全局对象最小视图。 */\ninterface RuntimeStorageGlobals {\n\t/** 可选 localStorage;缺失时 `Local` 操作明确失败。 */\n\tlocalStorage?: Storage;\n\t/** 可选 sessionStorage;缺失时 `Session` 操作明确失败。 */\n\tsessionStorage?: Storage;\n\t/** uni-app 运行时暴露的全局对象;只在调用 `configureStorage` 时读取和校验。 */\n\tuni?: unknown;\n}\n\nconst runtimeStorageGlobals = globalThis as unknown as RuntimeStorageGlobals;\n\n/**\n * 读取并校验当前运行时的全局 uni-app 同步 Storage。\n *\n * @returns 检测到 uni-app 时返回同步 Storage;普通浏览器环境返回 `undefined`。\n * @throws `TypeError` 当全局 `uni` 存在但缺少本库需要的同步 Storage 方法。\n */\nconst getGlobalUniStorage = (): UniStorageLike | undefined => {\n\tconst value = runtimeStorageGlobals.uni;\n\tif (value === undefined) return undefined;\n\tif ((typeof value !== \"object\" && typeof value !== \"function\") || value === null) {\n\t\tthrow new TypeError(\"The global uni object does not provide synchronous Storage APIs.\");\n\t}\n\tconst storage = value as Partial<UniStorageLike>;\n\tif (\n\t\ttypeof storage.getStorageSync !== \"function\" ||\n\t\ttypeof storage.getStorageInfoSync !== \"function\" ||\n\t\ttypeof storage.removeStorageSync !== \"function\" ||\n\t\ttypeof storage.setStorageSync !== \"function\"\n\t) {\n\t\tthrow new TypeError(\"The global uni object does not provide synchronous Storage APIs.\");\n\t}\n\treturn storage as UniStorageLike;\n};\n\n/** 默认 JSON Codec;显式拒绝会被 JSON.stringify 静默丢弃的顶层值。 */\nconst jsonCodec: StorageCodec = {\n\tdecode: (value): unknown => JSON.parse(value) as unknown,\n\tencode: (value): string => {\n\t\tconst encoded: unknown = JSON.stringify(value);\n\t\tif (typeof encoded !== \"string\") throw new TypeError(\"The storage value is not JSON-serializable.\");\n\t\treturn encoded;\n\t},\n};\n\n/** Base64 混淆 Codec;只隐藏明文外观,不提供加密、完整性或认证。 */\nexport const base64StorageCodec: StorageCodec = {\n\tdecode: (value): unknown => JSON.parse(decodeBase64(value)) as unknown,\n\tencode: (value): string => {\n\t\tconst encoded: unknown = JSON.stringify(value);\n\t\tif (typeof encoded !== \"string\") throw new TypeError(\"The storage value is not JSON-serializable.\");\n\t\treturn encodeBase64(encoded);\n\t},\n};\n\n/** 页面级唯一配置;只允许幂等重复配置,避免模块加载顺序改变行为。 */\nlet activeConfiguration: ActiveStorageConfiguration | undefined;\n\n/**\n * 判断未知值是否为非数组对象记录。\n *\n * @param value - JSON.parse 返回的未知值。\n * @returns 值为非空、非数组对象时返回 `true`。\n */\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * 校验 Storage 业务键。\n *\n * @param key - 不含全局 Prefix 的业务键或业务键前缀。\n * @throws `TypeError` 当值不是非空字符串。\n */\nconst assertKey = (key: string): void => {\n\tif (typeof key !== \"string\" || key.length === 0) throw new TypeError(\"Storage keys must be non-empty strings.\");\n};\n\n/**\n * 创建浏览器 Storage 后端。\n *\n * @remarks 平台对象在调用阶段读取,因此导入模块不会访问浏览器全局对象。\n * @param kind - 选择 `localStorage` 或 `sessionStorage`。\n * @returns 统一的内部同步后端。\n * @throws `Error` 当所选 Storage 在当前环境不可用。\n */\nconst createWebStorageBackend = (kind: \"local\" | \"session\"): StorageBackend => {\n\tconst storage = kind === \"local\" ? runtimeStorageGlobals.localStorage : runtimeStorageGlobals.sessionStorage;\n\tif (storage === undefined) throw new Error(`${kind}Storage is unavailable in the current runtime.`);\n\treturn {\n\t\tgetItem: (key): string | null => storage.getItem(key),\n\t\tkeys: (): string[] => {\n\t\t\tconst keys: string[] = [];\n\t\t\tfor (let index = 0; index < storage.length; index += 1) {\n\t\t\t\tconst key = storage.key(index);\n\t\t\t\tif (key !== null) keys.push(key);\n\t\t\t}\n\t\t\treturn keys;\n\t\t},\n\t\tremoveItem: (key): void => {\n\t\t\tstorage.removeItem(key);\n\t\t},\n\t\tsetItem: (key, value): void => {\n\t\t\tstorage.setItem(key, value);\n\t\t},\n\t};\n};\n\n/**\n * 把 uni-app 同步 Storage 适配为内部后端。\n *\n * @remarks uni-app 以空字符串同时表示“键缺失”和“真实空值”,因此空字符串需要结合键清单消除歧义。\n * @param storage - 已从全局 `uni` 读取并校验的同步 API。\n * @returns 统一的内部同步后端。\n */\nconst createUniStorageBackend = (storage: UniStorageLike): StorageBackend => ({\n\tgetItem: (key): unknown => {\n\t\tconst value = storage.getStorageSync(key);\n\t\tif (value !== \"\") return value;\n\t\treturn storage.getStorageInfoSync().keys.includes(key) ? value : undefined;\n\t},\n\tkeys: (): readonly string[] => [...storage.getStorageInfoSync().keys],\n\tremoveItem: (key): void => {\n\t\tstorage.removeStorageSync(key);\n\t},\n\tsetItem: (key, value): void => {\n\t\tstorage.setStorageSync(key, value);\n\t},\n});\n\n/**\n * 解析并校验版本化 Storage 包络。\n *\n * @param rawValue - 后端返回的原始值。\n * @param key - 用于错误定位的完整物理键。\n * @returns 当前 v3 包络。\n * @throws `TypeError` 当原始值不是字符串、JSON 损坏、版本不支持或字段类型非法。\n */\nconst parseStoredEnvelope = (rawValue: unknown, key: string): StoredEnvelope => {\n\tif (typeof rawValue !== \"string\") throw new TypeError(`Storage entry \"${key}\" is not a string.`);\n\ttry {\n\t\tconst parsed = JSON.parse(rawValue) as unknown;\n\t\tif (\n\t\t\t!isRecord(parsed) ||\n\t\t\tparsed[\"version\"] !== 3 ||\n\t\t\ttypeof parsed[\"data\"] !== \"string\" ||\n\t\t\t!(parsed[\"expiresAt\"] === null || (typeof parsed[\"expiresAt\"] === \"number\" && Number.isFinite(parsed[\"expiresAt\"])))\n\t\t) {\n\t\t\tthrow new TypeError(\"Unsupported storage envelope.\");\n\t\t}\n\t\treturn { data: parsed[\"data\"], expiresAt: parsed[\"expiresAt\"], version: 3 };\n\t} catch (cause) {\n\t\tthrow new TypeError(`Storage entry \"${key}\" is corrupted or unsupported.`, { cause });\n\t}\n};\n\n/**\n * 创建绑定命名空间、Codec 与时钟的 Storage Area。\n *\n * @param backendFactory - 每次操作时解析平台后端的工厂,保证导入安全并反映平台可用性。\n * @param prefix - 已校验的全局物理键前缀。\n * @param codec - 业务值与包络文本之间的 Codec。\n * @param now - TTL 计算使用的可注入时钟。\n * @returns 完整的命名空间 Storage 操作集合。\n */\nconst createStorageArea = (backendFactory: () => StorageBackend, prefix: string, codec: StorageCodec, now: () => number): StorageArea => {\n\t/**\n\t * 拼接物理键。\n\t *\n\t * @param key - 已校验业务键。\n\t * @returns 带当前命名空间前缀的物理键。\n\t */\n\tconst toStorageKey = (key: string): string => `${prefix}${key}`;\n\t/**\n\t * 枚举当前命名空间中的业务键。\n\t *\n\t * @param backend - 本次操作使用的后端。\n\t * @returns 已移除物理前缀、去重并排序的业务键。\n\t * @throws `TypeError` 当后端返回非字符串键。\n\t */\n\tconst listBusinessKeys = (backend: StorageBackend): string[] => {\n\t\tconst keys = backend.keys();\n\t\tif (!Array.isArray(keys) || !keys.every((key) => typeof key === \"string\")) {\n\t\t\tthrow new TypeError(\"Storage backend keys must be strings.\");\n\t\t}\n\t\treturn [...new Set(keys.filter((key) => key.startsWith(prefix)).map((key) => key.slice(prefix.length)))].sort();\n\t};\n\t/**\n\t * 读取并处理单个包络。\n\t *\n\t * @param backend - 本次操作使用的后端。\n\t * @param key - 业务键。\n\t * @returns 未过期包络;键缺失或已经过期时返回 `undefined`。\n\t * @throws `TypeError` 当键或包络非法。\n\t * @throws `RangeError` 当注入时钟返回非有限时间戳。\n\t */\n\tconst readStoredEnvelope = (backend: StorageBackend, key: string): StoredEnvelope | undefined => {\n\t\tassertKey(key);\n\t\tconst storageKey = toStorageKey(key);\n\t\tconst rawValue = backend.getItem(storageKey);\n\t\tif (rawValue === null || rawValue === undefined) return undefined;\n\t\tconst envelope = parseStoredEnvelope(rawValue, storageKey);\n\t\tif (envelope.expiresAt === null) return envelope;\n\t\tconst timestamp = now();\n\t\tif (!Number.isFinite(timestamp)) throw new RangeError(\"Storage clock must return a finite timestamp.\");\n\t\tif (timestamp < envelope.expiresAt) return envelope;\n\t\t// 过期项在读取时立即删除,后续 has/keys/pruneExpired 观察到一致状态。\n\t\tbackend.removeItem(storageKey);\n\t\treturn undefined;\n\t};\n\n\treturn {\n\t\tprefix,\n\t\tclear(): void {\n\t\t\tconst backend = backendFactory();\n\t\t\tfor (const key of listBusinessKeys(backend)) backend.removeItem(toStorageKey(key));\n\t\t},\n\t\tget<Value>(key: string): Value | undefined {\n\t\t\tconst envelope = readStoredEnvelope(backendFactory(), key);\n\t\t\tif (envelope === undefined) return undefined;\n\t\t\ttry {\n\t\t\t\treturn codec.decode(envelope.data) as Value;\n\t\t\t} catch (cause) {\n\t\t\t\tthrow new TypeError(`Storage entry \"${toStorageKey(key)}\" could not be decoded.`, { cause });\n\t\t\t}\n\t\t},\n\t\thas: (key): boolean => readStoredEnvelope(backendFactory(), key) !== undefined,\n\t\tkeys: (): string[] => listBusinessKeys(backendFactory()),\n\t\tpruneExpired(): number {\n\t\t\tconst backend = backendFactory();\n\t\t\tlet removed = 0;\n\t\t\tfor (const key of listBusinessKeys(backend)) {\n\t\t\t\t// read 同时处理删除;先读取一次用于区分“原本缺失”和“本轮因过期删除”。\n\t\t\t\tconst before = backend.getItem(toStorageKey(key));\n\t\t\t\tif (before !== null && before !== undefined && readStoredEnvelope(backend, key) === undefined) removed += 1;\n\t\t\t}\n\t\t\treturn removed;\n\t\t},\n\t\tremove(key: string): void {\n\t\t\tassertKey(key);\n\t\t\tbackendFactory().removeItem(toStorageKey(key));\n\t\t},\n\t\tremoveByPrefix(keyPrefix: string): void {\n\t\t\tassertKey(keyPrefix);\n\t\t\tconst backend = backendFactory();\n\t\t\tfor (const key of listBusinessKeys(backend)) if (key.startsWith(keyPrefix)) backend.removeItem(toStorageKey(key));\n\t\t},\n\t\tset<Value>(key: string, value: Value, options: StorageWriteOptions = {}): void {\n\t\t\tassertKey(key);\n\t\t\tif (value === undefined) throw new TypeError(\"Top-level undefined cannot be stored; remove the key instead.\");\n\t\t\tlet expiresAt: number | null = null;\n\t\t\tif (options.ttlMs !== undefined) {\n\t\t\t\tif (!Number.isFinite(options.ttlMs) || options.ttlMs <= 0) throw new RangeError(\"ttlMs must be a positive finite number.\");\n\t\t\t\tconst timestamp = now();\n\t\t\t\tif (!Number.isFinite(timestamp) || !Number.isFinite(timestamp + options.ttlMs)) {\n\t\t\t\t\tthrow new RangeError(\"Storage expiry exceeds the supported timestamp range.\");\n\t\t\t\t}\n\t\t\t\texpiresAt = timestamp + options.ttlMs;\n\t\t\t}\n\t\t\tlet data: string;\n\t\t\ttry {\n\t\t\t\tdata = codec.encode(value);\n\t\t\t\tif (typeof data !== \"string\") throw new TypeError(\"Storage codecs must return strings.\");\n\t\t\t} catch (cause) {\n\t\t\t\tthrow new TypeError(\"The storage value could not be encoded.\", { cause });\n\t\t\t}\n\t\t\tbackendFactory().setItem(toStorageKey(key), JSON.stringify({ data, expiresAt, version: 3 } satisfies StoredEnvelope));\n\t\t},\n\t};\n};\n\n/**\n * 获取已激活的全局 Storage 配置。\n *\n * @returns 首次 `configureStorage` 创建的内部配置。\n * @throws `Error` 当应用入口尚未配置 Storage。\n */\nconst requireStorageConfiguration = (): ActiveStorageConfiguration => {\n\tif (activeConfiguration === undefined) {\n\t\tthrow new Error(\"Storage is not configured. Call configureStorage() once from the application entry.\");\n\t}\n\treturn activeConfiguration;\n};\n\n/**\n * 创建稳定的公开 Storage 门面。\n *\n * @param select - 从激活配置选择 Local 或 Session 的函数。\n * @param name - 用于不可用错误的公开门面名称。\n * @returns 可在配置前导入、但只在调用时解析实际 Area 的稳定对象。\n */\nconst createStorageAreaProxy = (select: (configuration: ActiveStorageConfiguration) => StorageArea | undefined, name: string): StorageArea => {\n\t/**\n\t * 解析当前实际 Area。\n\t *\n\t * @returns 配置中的 Local 或 Session Area。\n\t * @throws `Error` 当尚未配置,或 uni-app 模式请求 Session。\n\t */\n\tconst getArea = (): StorageArea => {\n\t\tconst area = select(requireStorageConfiguration());\n\t\tif (area === undefined) throw new Error(`${name} is unavailable in uni-app.`);\n\t\treturn area;\n\t};\n\treturn {\n\t\tget prefix(): string {\n\t\t\treturn getArea().prefix;\n\t\t},\n\t\tclear: (): void => {\n\t\t\tgetArea().clear();\n\t\t},\n\t\tget: <Value>(key: string): Value | undefined => getArea().get<Value>(key),\n\t\thas: (key): boolean => getArea().has(key),\n\t\tkeys: (): string[] => getArea().keys(),\n\t\tpruneExpired: (): number => getArea().pruneExpired(),\n\t\tremove: (key): void => {\n\t\t\tgetArea().remove(key);\n\t\t},\n\t\tremoveByPrefix: (keyPrefix): void => {\n\t\t\tgetArea().removeByPrefix(keyPrefix);\n\t\t},\n\t\tset: <Value>(key: string, value: Value, options?: StorageWriteOptions): void => {\n\t\t\tgetArea().set(key, value, options);\n\t\t},\n\t};\n};\n\n/** 浏览器 localStorage 或自动检测的 uni-app Storage 全局业务入口。 */\nexport const Local: StorageArea = createStorageAreaProxy((configuration) => configuration.local, \"Local\");\n\n/** 浏览器 sessionStorage 的全局业务入口;uni-app 不提供会话存储。 */\nexport const Session: StorageArea = createStorageAreaProxy((configuration) => configuration.session, \"Session\");\n\n/**\n * 在应用入口一次性配置 `Local` 与 `Session`。\n *\n * @remarks 首次配置后只允许以完全相同的值和引用重复调用。模块导入不会访问平台对象;调用本函数时若检测到\n * 全局 `uni`,则自动使用其同步 Storage 且只启用 `Local`,否则使用浏览器 `localStorage` 与 `sessionStorage`。\n * @param options - 全局键前缀、Codec 与时钟。\n * @throws 配置非法、重复配置冲突或目标平台 Storage 不可用时抛出错误。\n */\nexport function configureStorage(options: StorageConfiguration): void {\n\tif (typeof options.prefix !== \"string\" || options.prefix.length === 0) {\n\t\tthrow new TypeError(\"Storage prefix must be a non-empty string.\");\n\t}\n\tconst codec = options.codec ?? jsonCodec;\n\tconst now = options.now ?? Date.now;\n\tif (activeConfiguration !== undefined) {\n\t\t// 相同配置允许多个入口模块幂等调用;任何引用或值变化都视为冲突。\n\t\tif (activeConfiguration.prefix === options.prefix && activeConfiguration.codec === codec && activeConfiguration.now === now) {\n\t\t\treturn;\n\t\t}\n\t\tthrow new Error(\"Storage has already been configured with different options.\");\n\t}\n\tconst uni = getGlobalUniStorage();\n\tconst localBackend =\n\t\tuni === undefined ? (): StorageBackend => createWebStorageBackend(\"local\") : (): StorageBackend => createUniStorageBackend(uni);\n\tconst local = createStorageArea(localBackend, options.prefix, codec, now);\n\tconst configuration: ActiveStorageConfiguration = { codec, local, now, prefix: options.prefix };\n\tif (uni === undefined) {\n\t\tconfiguration.session = createStorageArea(() => createWebStorageBackend(\"session\"), options.prefix, codec, now);\n\t}\n\tactiveConfiguration = configuration;\n}\n\n/** 返回全局 Storage 是否已经由应用入口配置。 */\nexport function isStorageConfigured(): boolean {\n\treturn activeConfiguration !== undefined;\n}\n"],"mappings":";;AAuKA,MAAM,wBAAwB;;;;;;;AAQ9B,MAAM,4BAAwD;CAC7D,MAAM,QAAQ,sBAAsB;CACpC,IAAI,UAAU,KAAA,GAAW,OAAO,KAAA;CAChC,IAAK,OAAO,UAAU,YAAY,OAAO,UAAU,cAAe,UAAU,MAC3E,MAAM,IAAI,UAAU,kEAAkE;CAEvF,MAAM,UAAU;CAChB,IACC,OAAO,QAAQ,mBAAmB,cAClC,OAAO,QAAQ,uBAAuB,cACtC,OAAO,QAAQ,sBAAsB,cACrC,OAAO,QAAQ,mBAAmB,YAElC,MAAM,IAAI,UAAU,kEAAkE;CAEvF,OAAO;AACR;;AAGA,MAAM,YAA0B;CAC/B,SAAS,UAAmB,KAAK,MAAM,KAAK;CAC5C,SAAS,UAAkB;EAC1B,MAAM,UAAmB,KAAK,UAAU,KAAK;EAC7C,IAAI,OAAO,YAAY,UAAU,MAAM,IAAI,UAAU,6CAA6C;EAClG,OAAO;CACR;AACD;;AAGA,MAAa,qBAAmC;CAC/C,SAAS,UAAmB,KAAK,MAAM,aAAa,KAAK,CAAC;CAC1D,SAAS,UAAkB;EAC1B,MAAM,UAAmB,KAAK,UAAU,KAAK;EAC7C,IAAI,OAAO,YAAY,UAAU,MAAM,IAAI,UAAU,6CAA6C;EAClG,OAAO,aAAa,OAAO;CAC5B;AACD;;AAGA,IAAI;;;;;;;AAQJ,MAAM,YAAY,UAAqD,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;;;;;;;AAQ1I,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