@fast-china/utils 2.1.6 → 2.1.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/README.md +4 -2
- package/README.zh.md +4 -2
- package/THIRD_PARTY_LICENSES.md +26 -0
- package/dist/crypto/index.mjs +2240 -33
- package/dist/crypto/index.mjs.map +1 -1
- package/dist/dom/index.mjs +2 -0
- package/dist/env/index.mjs +4 -4
- package/dist/env/index.mjs.map +1 -1
- package/dist/index.d.mts +1918 -32
- package/dist/index.global.min.js +2 -2
- package/dist/index.global.min.js.map +1 -1
- package/dist/index.mjs +2 -0
- package/dist/internal/runtime.mjs +21 -1
- package/dist/internal/runtime.mjs.map +1 -1
- package/dist/logger/index.mjs +2 -2
- package/dist/logger/index.mjs.map +1 -1
- package/dist/storage/index.mjs +2 -2
- package/dist/storage/index.mjs.map +1 -1
- package/dist/string/index.mjs +2 -2
- package/dist/string/index.mjs.map +1 -1
- package/dist/vue/index.mjs +15 -0
- package/dist/vue/now.mjs +2 -2
- package/dist/vue/now.mjs.map +1 -1
- package/package.json +4 -6
- package/dist/array/index.d.mts +0 -94
- package/dist/async/index.d.mts +0 -145
- package/dist/base64/index.d.mts +0 -106
- package/dist/color/index.d.mts +0 -89
- package/dist/crypto/index.d.mts +0 -327
- package/dist/date/index.d.mts +0 -190
- package/dist/dom/style.d.mts +0 -29
- package/dist/env/index.d.mts +0 -62
- package/dist/function/index.d.mts +0 -13
- package/dist/identity/index.d.mts +0 -77
- package/dist/internal/text.d.mts +0 -15
- package/dist/logger/index.d.mts +0 -90
- package/dist/number/index.d.mts +0 -89
- package/dist/object/index.d.mts +0 -114
- package/dist/storage/index.d.mts +0 -115
- package/dist/string/index.d.mts +0 -141
- package/dist/vue/breakpoints.d.mts +0 -21
- package/dist/vue/element-size.d.mts +0 -25
- package/dist/vue/emits.d.mts +0 -23
- package/dist/vue/event-listener.d.mts +0 -16
- package/dist/vue/expose.d.mts +0 -11
- package/dist/vue/func.d.mts +0 -13
- package/dist/vue/index.d.mts +0 -15
- package/dist/vue/install.d.mts +0 -50
- package/dist/vue/now.d.mts +0 -13
- package/dist/vue/props.d.mts +0 -22
- package/dist/vue/render.d.mts +0 -11
- package/dist/vue/resize-observer.d.mts +0 -15
- package/dist/vue/slots.d.mts +0 -18
- package/dist/vue/window-size.d.mts +0 -16
- package/dist/vue/with.d.mts +0 -11
- package/docs/API.md +0 -155
- package/docs/API.zh-CN.md +0 -154
- package/docs/DEVELOPMENT_RELEASE.zh-CN.md +0 -65
- package/docs/RUNTIME_CONTRACT.md +0 -44
package/dist/index.mjs
CHANGED
|
@@ -6,6 +6,7 @@ import { contrastRatio, formatHexColor, mixHexColorWithBlack, mixHexColorWithWhi
|
|
|
6
6
|
import { AESDecrypt, AESDecryptAuthenticated, AESDecryptWithPassword, AESEncrypt, AESEncryptAuthenticated, AESEncryptWithPassword, DeriveECDHKeySHA256, DeriveECDHSecret, ECDSASign, ECDSAVerify, FixedTimeEquals, GenerateECDHKeyPair, GenerateECDSAKeyPair, GenerateRSAKeyPair, GenerateRandomBytes, HKDFSHA256, HMACSHA256Encrypt, HMACSHA384Encrypt, HMACSHA512Encrypt, HashPasswordPBKDF2SHA256, MD5Encrypt, PBKDF2SHA256, RSADecryptOAEP, RSAEncryptOAEP, RSASignPSS, RSAVerifyPSS, SHA1Encrypt, SHA256Bytes, SHA256Encrypt, SHA384Bytes, SHA384Encrypt, SHA512Bytes, SHA512Encrypt, VerifyPasswordPBKDF2SHA256 } from "./crypto/index.mjs";
|
|
7
7
|
import { addDays, addMonths, addYears, createDateRangeShortcuts, createDateShortcuts, createOneMonthRangeFromToday, endOfDay, formatChineseRelativeTime, formatRelativeTime, getLocalDayBounds, getLocalTimeGreeting, getStartOfToday, isDateAfterNow, isFuture, isSameDay, isValidDate, isWithinInterval, startOfDay, toDate } from "./date/index.mjs";
|
|
8
8
|
import { addCssUnit, serializeStyle } from "./dom/style.mjs";
|
|
9
|
+
import "./dom/index.mjs";
|
|
9
10
|
import { detectRuntime, hasWebCrypto, isBrowser, isMobileUserAgent, isNode, isTabletUserAgent, isUniApp, isWebWorker } from "./env/index.mjs";
|
|
10
11
|
import { once } from "./function/index.mjs";
|
|
11
12
|
import { Local, Session, base64StorageCodec, configureStorage, isStorageConfigured } from "./storage/index.mjs";
|
|
@@ -27,4 +28,5 @@ import { useRender } from "./vue/render.mjs";
|
|
|
27
28
|
import { makeSlots } from "./vue/slots.mjs";
|
|
28
29
|
import { useWindowSize } from "./vue/window-size.mjs";
|
|
29
30
|
import { withDefineType } from "./vue/with.mjs";
|
|
31
|
+
import "./vue/index.mjs";
|
|
30
32
|
export { AESDecrypt, AESDecryptAuthenticated, AESDecryptWithPassword, AESEncrypt, AESEncryptAuthenticated, AESEncryptWithPassword, DeriveECDHKeySHA256, DeriveECDHSecret, ECDSASign, ECDSAVerify, FixedTimeEquals, GenerateECDHKeyPair, GenerateECDSAKeyPair, GenerateRSAKeyPair, GenerateRandomBytes, HKDFSHA256, HMACSHA256Encrypt, HMACSHA384Encrypt, HMACSHA512Encrypt, HashPasswordPBKDF2SHA256, Local, MD5Encrypt, PBKDF2SHA256, RSADecryptOAEP, RSAEncryptOAEP, RSASignPSS, RSAVerifyPSS, SHA1Encrypt, SHA256Bytes, SHA256Encrypt, SHA384Bytes, SHA384Encrypt, SHA512Bytes, SHA512Encrypt, Session, VerifyPasswordPBKDF2SHA256, addCssUnit, addDays, addMonths, addYears, allEqualBy, average, base64StorageCodec, callOptionalFunction, camelCase, chunk, clamp, cloneDeep, configureInstallationIdentity, configureLogger, configureStorage, contrastRatio, copy, createDateRangeShortcuts, createDateShortcuts, createLogger, createOneMonthRangeFromToday, debounce, decodeBase64, decodeBase64Bytes, decodeBase64Url, decodeBase64UrlBytes, decodeLatin1Base64, decodeSecureBase64, decodeURIComponentRepeatedly, definePropType, detectRuntime, difference, encodeBase64, encodeBase64Bytes, encodeBase64Url, encodeBase64UrlBytes, encodeLatin1Base64, encodeSecureBase64, endOfDay, escapeHtml, formatBytes, formatChineseRelativeTime, formatHexColor, formatRelativeTime, generateUuidV4, getLocalDayBounds, getLocalTimeGreeting, getOrCreateInstallationId, getStartOfToday, groupBy, hasDuplicatesBy, hasOwn, hasWebCrypto, inRange, installationIdentity, intersection, isBrowser, isDateAfterNow, isEqual, isFuture, isMobileUserAgent, isNode, isPlainObject, isSameDay, isStorageConfigured, isTabletUserAgent, isUniApp, isUuidV4, isValidDate, isValidJson, isWebWorker, isWithinInterval, kebabCase, lerp, logger, lowerFirst, makeSlots, mapConcurrent, mapValues, mixHexColorWithBlack, mixHexColorWithWhite, mixHexColors, normalizeWhitespace, omit, omitBy, once, parseHexColor, parseQueryString, partition, pascalCase, pick, pickBy, pickHigherContrastColor, randomInt, randomString, relativeLuminance, removeNullishValues, retry, roundTo, serializeStyle, shallowEqual, sleep, splitWords, startOfDay, sum, symmetricDifference, throttle, toDate, toQueryString, truncateGraphemes, unique, uniqueBy, upperFirst, useBreakpoints, useElementSize, useEmits, useEventListener, useExpose, useNow, useProps, useRender, useResizeObserver, useWindowSize, withDefineType, withInstall, withInstallDirective, withNoopInstall, withTimeout };
|
|
@@ -6,7 +6,27 @@
|
|
|
6
6
|
* 和 uni-app 中运行。这里只放宽能力是否存在,不改变标准 API 的属性与方法类型。
|
|
7
7
|
*/
|
|
8
8
|
const runtimeGlobals = globalThis;
|
|
9
|
+
/**
|
|
10
|
+
* 延迟读取 HTML5+ 注入的 `plus` 运行时对象。
|
|
11
|
+
*
|
|
12
|
+
* @remarks HTML5+ 与 uni-app App 运行时不保证把 `plus` 标识符挂载到 `globalThis`。
|
|
13
|
+
* 自由标识符不存在时,再回退到全局属性以兼容传统 WebView 与测试环境。
|
|
14
|
+
* @returns 当前 HTML5+ 运行时对象;非 App-Plus 环境返回 `undefined`。
|
|
15
|
+
*/
|
|
16
|
+
function getRuntimePlus() {
|
|
17
|
+
return typeof plus === "undefined" ? runtimeGlobals.plus : plus;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* 延迟读取 uni-app 注入的 `uni` 运行时对象。
|
|
21
|
+
*
|
|
22
|
+
* @remarks uni-app 不保证把 `uni` 标识符挂载到 `globalThis`。自由标识符不存在时,
|
|
23
|
+
* 再回退到全局属性,以兼容浏览器式宿主与测试环境。
|
|
24
|
+
* @returns 当前 uni-app 运行时对象;非 uni-app 环境返回 `undefined`。
|
|
25
|
+
*/
|
|
26
|
+
function getRuntimeUni() {
|
|
27
|
+
return typeof uni === "undefined" ? runtimeGlobals.uni : uni;
|
|
28
|
+
}
|
|
9
29
|
//#endregion
|
|
10
|
-
export { runtimeGlobals };
|
|
30
|
+
export { getRuntimePlus, getRuntimeUni, runtimeGlobals };
|
|
11
31
|
|
|
12
32
|
//# sourceMappingURL=runtime.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.mjs","names":[],"sources":["../../src/internal/runtime.ts"],"sourcesContent":["/** Web、Node、WebView 与 uni-app 宿主可能按需提供的运行时全局能力。 */\ninterface RuntimeGlobals {\n\treadonly Intl?: {\n\t\treadonly Segmenter?: typeof Intl.Segmenter;\n\t};\n\treadonly crypto?: Omit<Partial<Crypto>, \"subtle\"> & {\n\t\treadonly subtle?: Partial<SubtleCrypto>;\n\t};\n\treadonly document?: Partial<Document>;\n\treadonly importScripts?: unknown;\n\treadonly isSecureContext?: boolean;\n\treadonly localStorage?: Storage;\n\treadonly navigator?: Partial<Navigator>;\n\treadonly plus?: unknown;\n\treadonly process?: unknown;\n\treadonly ResizeObserver?: typeof ResizeObserver;\n\treadonly sessionStorage?: Storage;\n\treadonly uni?: unknown;\n\treadonly window?: Window;\n}\n\n/**\n * 以可选能力视图读取全局对象。\n *\n * @remarks TypeScript 的 DOM 声明假定浏览器全局始终存在,但本包也会在 Node、WebView\n * 和 uni-app 中运行。这里只放宽能力是否存在,不改变标准 API 的属性与方法类型。\n */\nexport const runtimeGlobals = globalThis as RuntimeGlobals;\n"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"runtime.mjs","names":[],"sources":["../../src/internal/runtime.ts"],"sourcesContent":["/** Web、Node、WebView 与 uni-app 宿主可能按需提供的运行时全局能力。 */\ninterface RuntimeGlobals {\n\treadonly Intl?: {\n\t\treadonly Segmenter?: typeof Intl.Segmenter;\n\t};\n\treadonly crypto?: Omit<Partial<Crypto>, \"subtle\"> & {\n\t\treadonly subtle?: Partial<SubtleCrypto>;\n\t};\n\treadonly document?: Partial<Document>;\n\treadonly importScripts?: unknown;\n\treadonly isSecureContext?: boolean;\n\treadonly localStorage?: Storage;\n\treadonly navigator?: Partial<Navigator>;\n\treadonly plus?: unknown;\n\treadonly process?: unknown;\n\treadonly ResizeObserver?: typeof ResizeObserver;\n\treadonly sessionStorage?: Storage;\n\treadonly uni?: unknown;\n\treadonly window?: Window;\n}\n\ndeclare const plus: unknown;\ndeclare const uni: unknown;\n\n/**\n * 以可选能力视图读取全局对象。\n *\n * @remarks TypeScript 的 DOM 声明假定浏览器全局始终存在,但本包也会在 Node、WebView\n * 和 uni-app 中运行。这里只放宽能力是否存在,不改变标准 API 的属性与方法类型。\n */\nexport const runtimeGlobals = globalThis as RuntimeGlobals;\n\n/**\n * 延迟读取 HTML5+ 注入的 `plus` 运行时对象。\n *\n * @remarks HTML5+ 与 uni-app App 运行时不保证把 `plus` 标识符挂载到 `globalThis`。\n * 自由标识符不存在时,再回退到全局属性以兼容传统 WebView 与测试环境。\n * @returns 当前 HTML5+ 运行时对象;非 App-Plus 环境返回 `undefined`。\n */\nexport function getRuntimePlus(): unknown {\n\treturn typeof plus === \"undefined\" ? runtimeGlobals.plus : plus;\n}\n\n/**\n * 延迟读取 uni-app 注入的 `uni` 运行时对象。\n *\n * @remarks uni-app 不保证把 `uni` 标识符挂载到 `globalThis`。自由标识符不存在时,\n * 再回退到全局属性,以兼容浏览器式宿主与测试环境。\n * @returns 当前 uni-app 运行时对象;非 uni-app 环境返回 `undefined`。\n */\nexport function getRuntimeUni(): unknown {\n\treturn typeof uni === \"undefined\" ? runtimeGlobals.uni : uni;\n}\n"],"mappings":";;;;;;;AA8BA,MAAa,iBAAiB;;;;;;;;AAS9B,SAAgB,iBAA0B;CACzC,OAAO,OAAO,SAAS,cAAc,eAAe,OAAO;AAC5D;;;;;;;;AASA,SAAgB,gBAAyB;CACxC,OAAO,OAAO,QAAQ,cAAc,eAAe,MAAM;AAC1D"}
|
package/dist/logger/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { getRuntimePlus, getRuntimeUni } from "../internal/runtime.mjs";
|
|
2
2
|
//#region src/logger/index.ts
|
|
3
3
|
const levelPriority = {
|
|
4
4
|
debug: 10,
|
|
@@ -19,7 +19,7 @@ const isLogLevel = (value) => typeof value === "string" && Object.hasOwn(levelPr
|
|
|
19
19
|
* @returns 全局 `uni` 与 `plus` 同时存在时返回 `true`。
|
|
20
20
|
*/
|
|
21
21
|
const isUniAppPlus = () => {
|
|
22
|
-
return
|
|
22
|
+
return getRuntimeUni() !== void 0 && getRuntimePlus() !== void 0;
|
|
23
23
|
};
|
|
24
24
|
/**
|
|
25
25
|
* 把日志附加值转换为适合 HBuilderX 单行输出的文本。
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/logger/index.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/logger/index.ts"],"sourcesContent":["import { getRuntimePlus, getRuntimeUni } from \"../internal/runtime\";\n\n/** 日志严重级别,按从低到高排列。 */\nexport type LogLevel = \"debug\" | \"log\" | \"warn\" | \"error\";\n\n/** 日志输出目标需要实现的最小控制台接口。 */\nexport interface LoggerSink {\n\t/**\n\t * 接收通过级别过滤后的调试参数。\n\t * @param data - 已格式化的品牌、作用域、消息以及保持原始类型的附加值。\n\t */\n\tdebug: (...data: unknown[]) => void;\n\t/**\n\t * 接收通过级别过滤后的普通日志参数;对应 Logger 的 `log` 级别。\n\t * @param data - 已格式化的品牌、作用域、消息以及保持原始类型的附加值。\n\t */\n\tlog: (...data: unknown[]) => void;\n\t/**\n\t * 接收通过级别过滤后的警告参数。\n\t * @param data - 已格式化的品牌、作用域、消息以及保持原始类型的附加值。\n\t */\n\twarn: (...data: unknown[]) => void;\n\t/**\n\t * 接收通过级别过滤后的错误参数。\n\t * @param data - 已格式化的品牌、作用域、消息以及保持原始类型的附加值。\n\t */\n\terror: (...data: unknown[]) => void;\n}\n\n/** {@link createLogger} 的不可变配置。 */\nexport interface LoggerOptions {\n\t/** 最低输出级别,默认 `debug`;低于该优先级的消息不会传给 Sink。 */\n\tlevel?: LogLevel;\n\t/** 日志品牌前缀,默认 `Fast`;必须是无外围空白的非空字符串。 */\n\tprefix?: string;\n\t/** 可注入输出目标,默认当前运行时的 `console`;Logger 不会修改该对象。 */\n\tsink?: LoggerSink;\n\t/** uni-app App-Plus/HBuilderX 中把附加参数逐条转成单行文本输出,默认 `false`;其他平台忽略。 */\n\tuniAppPlusSplit?: boolean;\n}\n\n/** 配置隔离的轻量日志器。 */\nexport interface Logger {\n\t/**\n\t * 输出指定作用域的调试信息或数据。\n\t * @param scope - 模块、组件或业务来源名称。\n\t * @param content - 可选的消息与附加值;非字符串值保持原始类型。\n\t * @throws `TypeError` 或 `RangeError` 当作用域不是无外围空白的非空字符串。\n\t */\n\tdebug: (scope: string, ...content: unknown[]) => void;\n\t/**\n\t * 输出指定作用域的普通信息或数据。\n\t * @param scope - 模块、组件或业务来源名称。\n\t * @param content - 可选的消息与附加值;非字符串值保持原始类型。\n\t * @throws `TypeError` 或 `RangeError` 当作用域不是无外围空白的非空字符串。\n\t */\n\tlog: (scope: string, ...content: unknown[]) => void;\n\t/**\n\t * 输出指定作用域的警告信息或数据。\n\t * @param scope - 模块、组件或业务来源名称。\n\t * @param content - 可选的消息与附加值;非字符串值保持原始类型。\n\t * @throws `TypeError` 或 `RangeError` 当作用域不是无外围空白的非空字符串。\n\t */\n\twarn: (scope: string, ...content: unknown[]) => void;\n\t/**\n\t * 输出指定作用域的错误信息或数据。\n\t * @param scope - 模块、组件或业务来源名称。\n\t * @param content - 可选的消息与附加值;非字符串值保持原始类型。\n\t * @throws `TypeError` 或 `RangeError` 当作用域不是无外围空白的非空字符串。\n\t */\n\terror: (scope: string, ...content: unknown[]) => void;\n}\n\nconst levelPriority: Readonly<Record<LogLevel, number>> = {\n\tdebug: 10,\n\tlog: 20,\n\twarn: 30,\n\terror: 40,\n};\n\n/**\n * 判断未知值是否为受支持日志级别。\n *\n * @param value - 待检查配置值。\n * @returns 值是 `debug`、`log`、`warn` 或 `error` 时返回 `true`。\n */\nconst isLogLevel = (value: unknown): value is LogLevel => typeof value === \"string\" && Object.hasOwn(levelPriority, value);\n\n/**\n * 检测 uni-app App-Plus 日志环境。\n *\n * @returns 全局 `uni` 与 `plus` 同时存在时返回 `true`。\n */\nconst isUniAppPlus = (): boolean => {\n\treturn getRuntimeUni() !== undefined && getRuntimePlus() !== undefined;\n};\n\n/**\n * 把日志附加值转换为适合 HBuilderX 单行输出的文本。\n *\n * @remarks 循环引用会替换为 `[Circular]`,BigInt 保留 `n` 后缀,Error 优先输出堆栈。\n * @param value - 任意日志附加值。\n * @returns 不会因 JSON 序列化失败而中断日志调用的文本。\n */\nconst formatSplitValue = (value: unknown): string => {\n\tif (typeof value === \"string\") return value;\n\tif (typeof value === \"bigint\") return `${value.toString()}n`;\n\tif (value instanceof Error) return value.stack ?? `${value.name}: ${value.message}`;\n\tconst visited = new WeakSet();\n\ttry {\n\t\tconst serialized = JSON.stringify(\n\t\t\tvalue,\n\t\t\t(_key, item: unknown) => {\n\t\t\t\tif (typeof item === \"bigint\") return `${item.toString()}n`;\n\t\t\t\tif (typeof item !== \"object\" || item === null) return item;\n\t\t\t\tif (visited.has(item)) return \"[Circular]\";\n\t\t\t\tvisited.add(item);\n\t\t\t\treturn item;\n\t\t\t},\n\t\t\t2\n\t\t);\n\t\treturn typeof serialized === \"string\" ? serialized : String(value);\n\t} catch {\n\t\treturn String(value);\n\t}\n};\n\nconst defaultConsoleSink: LoggerSink = {\n\tdebug: (...data) => {\n\t\t// eslint-disable-next-line no-console\n\t\tif (typeof console.debug === \"function\") console.debug(...data);\n\t\t// eslint-disable-next-line no-console\n\t\telse console.log(...data);\n\t},\n\tlog: (...data) => {\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.log(...data);\n\t},\n\twarn: (...data) => {\n\t\tconsole.warn(...data);\n\t},\n\terror: (...data) => {\n\t\tconsole.error(...data);\n\t},\n};\n\n/**\n * 创建独立日志器。\n *\n * @remarks 本库其他模块不会自动记录、吞掉或转换异常。日志内容可能进入持久化平台,\n * 调用方不得传入密码、令牌、密钥或完整个人数据。\n * @param options - 级别、前缀、输出目标和 uni-app App-Plus 拆分选项。\n * @returns 不会修改全局控制台或其他日志器配置的新实例。\n * @throws `RangeError` 当级别未知,或前缀、作用域不是有效的非空字符串。\n */\nexport function createLogger(options: LoggerOptions = {}): Logger {\n\tconst level: unknown = options.level ?? \"debug\";\n\tconst prefix: unknown = options.prefix ?? \"Fast\";\n\tconst sink = options.sink ?? defaultConsoleSink;\n\tif (!isLogLevel(level)) throw new RangeError(`未知的日志级别:${String(level)}。`);\n\tif (typeof prefix !== \"string\" || prefix.length === 0) {\n\t\tthrow new RangeError(\"日志前缀必须是非空字符串。\");\n\t}\n\tconst uniAppPlusSplit = options.uniAppPlusSplit ?? false;\n\n\t/**\n\t * 应用级别过滤、标题格式和平台输出策略。\n\t *\n\t * @param messageLevel - 本条消息的严重级别。\n\t * @param scope - 模块、组件或业务来源名称。\n\t * @param content - 可选的消息与保持原始类型的附加值。\n\t * @throws `RangeError` 当作用域不是非空字符串或包含外围空白。\n\t */\n\tconst write = (messageLevel: LogLevel, scope: string, content: readonly unknown[]) => {\n\t\tif (typeof scope !== \"string\") throw new TypeError(\"日志作用域必须是字符串。\");\n\t\tif (scope.length === 0 || scope.trim() !== scope) {\n\t\t\tthrow new RangeError(\"日志作用域必须是无外围空白的非空字符串。\");\n\t\t}\n\t\tif (levelPriority[messageLevel] < levelPriority[level]) return;\n\t\tconst heading = `[${prefix}:${scope}]`;\n\t\tconst sinkMethod = messageLevel;\n\t\tif (uniAppPlusSplit && isUniAppPlus()) {\n\t\t\tconst [first, ...remaining] = content;\n\t\t\tif (typeof first === \"string\") {\n\t\t\t\tsink[sinkMethod](`${heading} ${first}`);\n\t\t\t\tfor (const item of remaining) sink[sinkMethod](formatSplitValue(item));\n\t\t\t} else {\n\t\t\t\tsink[sinkMethod](heading);\n\t\t\t\tfor (const item of content) sink[sinkMethod](formatSplitValue(item));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tsink[sinkMethod](heading, ...content);\n\t};\n\n\treturn {\n\t\tdebug: (scope, ...content) => {\n\t\t\twrite(\"debug\", scope, content);\n\t\t},\n\t\tlog: (scope, ...content) => {\n\t\t\twrite(\"log\", scope, content);\n\t\t},\n\t\twarn: (scope, ...content) => {\n\t\t\twrite(\"warn\", scope, content);\n\t\t},\n\t\terror: (scope, ...content) => {\n\t\t\twrite(\"error\", scope, content);\n\t\t},\n\t};\n}\n\nlet activeDefaultLogger = createLogger();\n\n/**\n * 替换默认 {@link logger} 的完整配置。\n *\n * @remarks 已创建的独立 Logger 不受影响;默认 Logger 对象引用保持稳定,并立即转发到新配置。\n * 省略选项会恢复 `createLogger()` 的全部默认值。\n * @param options - 默认 Logger 使用的级别、前缀、输出目标和 uni-app App-Plus 拆分选项。\n */\nexport function configureLogger(options: LoggerOptions = {}): void {\n\tactiveDefaultLogger = createLogger(options);\n}\n\n/** 默认使用 `Fast` 前缀和 `debug` 级别、可通过 {@link configureLogger} 配置的便捷日志器。 */\nexport const logger: Logger = {\n\tdebug: (scope, ...content) => {\n\t\tactiveDefaultLogger.debug(scope, ...content);\n\t},\n\tlog: (scope, ...content) => {\n\t\tactiveDefaultLogger.log(scope, ...content);\n\t},\n\twarn: (scope, ...content) => {\n\t\tactiveDefaultLogger.war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,MAAM,QAAQ,OAAO,OAAO;EAC7B;EACA,QAAQ,OAAO,GAAG,YAAY;GAC7B,MAAM,SAAS,OAAO,OAAO;EAC9B;CACD;AACD;AAEA,IAAI,sBAAsB,aAAa;;;;;;;;AASvC,SAAgB,gBAAgB,UAAyB,CAAC,GAAS;CAClE,sBAAsB,aAAa,OAAO;AAC3C;;AAGA,MAAa,SAAiB;CAC7B,QAAQ,OAAO,GAAG,YAAY;EAC7B,oBAAoB,MAAM,OAAO,GAAG,OAAO;CAC5C;CACA,MAAM,OAAO,GAAG,YAAY;EAC3B,oBAAoB,IAAI,OAAO,GAAG,OAAO;CAC1C;CACA,OAAO,OAAO,GAAG,YAAY;EAC5B,oBAAoB,KAAK,OAAO,GAAG,OAAO;CAC3C;CACA,QAAQ,OAAO,GAAG,YAAY;EAC7B,oBAAoB,MAAM,OAAO,GAAG,OAAO;CAC5C;AACD"}
|
package/dist/storage/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { runtimeGlobals } from "../internal/runtime.mjs";
|
|
1
|
+
import { getRuntimeUni, runtimeGlobals } from "../internal/runtime.mjs";
|
|
2
2
|
import { decodeSecureBase64, encodeSecureBase64 } from "../base64/index.mjs";
|
|
3
3
|
//#region src/storage/index.ts
|
|
4
4
|
/**
|
|
@@ -8,7 +8,7 @@ import { decodeSecureBase64, encodeSecureBase64 } from "../base64/index.mjs";
|
|
|
8
8
|
* @throws `TypeError` 当全局 `uni` 存在但缺少本库需要的同步 Storage 方法。
|
|
9
9
|
*/
|
|
10
10
|
const getGlobalUniStorage = () => {
|
|
11
|
-
const value =
|
|
11
|
+
const value = getRuntimeUni();
|
|
12
12
|
if (value === void 0) return void 0;
|
|
13
13
|
if (typeof value !== "object" && typeof value !== "function" || value === null) throw new TypeError("全局 uni 对象未提供同步 Storage API。");
|
|
14
14
|
const storage = value;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/storage/index.ts"],"sourcesContent":["import { decodeSecureBase64, encodeSecureBase64 } from \"../base64/index\";\nimport { runtimeGlobals } from \"../internal/runtime\";\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/** 启用 Base64 可逆混淆;不提供加密、完整性或认证,不能与 `codec` 同时使用。 */\n\tcrypto?: boolean;\n\t/** 返回 Unix 毫秒时间戳的时钟;默认使用 `Date.now`,主要用于 TTL 测试与受控时间源。 */\n\tnow?: () => number;\n\t/** 所有物理键使用的非空命名空间前缀; */\n\tprefix?: string;\n}\n\n/** 单次 Storage 读取配置。 */\nexport interface StorageReadOptions {\n\t/**\n\t * 仅覆盖本次读取使用的 Codec;`true` 使用 Base64 混淆,`false` 使用 JSON,省略时使用全局配置。\n\t * 必须与写入该条目时使用的单次设置一致。\n\t */\n\tcrypto?: boolean;\n}\n\n/** 单次 Storage 写入配置。 */\nexport interface StorageWriteOptions extends StorageReadOptions {\n\t/** 从写入时刻开始的有效毫秒数;必须是大于 0 的有限数,省略时永久有效。 */\n\tttlMs?: number;\n}\n\n/** `Local` 与 `Session` 的统一操作接口。 */\nexport interface StorageArea {\n\t/** 当前全局 Storage 配置的物理键前缀;首次读取会激活默认配置。 */\n\treadonly prefix: string;\n\t/**\n\t * 删除当前命名空间内的全部键,不影响同一后端中的其他应用键。\n\t * @throws `Error` 当当前平台后端不可用。\n\t */\n\tclear: () => void;\n\t/**\n\t * 获取并解码业务值;已过期记录会在读取时删除。\n\t * @param key - 不含全局前缀的非空业务键。\n\t * @param options - 可选的单次 Base64 混淆开关;必须与写入时一致。\n\t * @returns 解码后的值;未传泛型时静态类型默认为 `string`,键缺失或过期时返回 `undefined`。\n\t * @throws 当键非法、包络损坏、Codec 解码失败或后端不可用时抛出错误。\n\t */\n\tget: <Value = string>(key: string, options?: StorageReadOptions) => 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 与 Base64 混淆开关。\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/**\n * 读取并校验当前运行时的全局 uni-app 同步 Storage。\n *\n * @returns 检测到 uni-app 时返回同步 Storage;普通浏览器环境返回 `undefined`。\n * @throws `TypeError` 当全局 `uni` 存在但缺少本库需要的同步 Storage 方法。\n */\nconst getGlobalUniStorage = (): UniStorageLike | undefined => {\n\tconst value = runtimeGlobals.uni;\n\tif (value === undefined) return undefined;\n\tif ((typeof value !== \"object\" && typeof value !== \"function\") || value === null) {\n\t\tthrow new TypeError(\"全局 uni 对象未提供同步 Storage API。\");\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(\"全局 uni 对象未提供同步 Storage API。\");\n\t}\n\treturn storage as UniStorageLike;\n};\n\n/** 默认 JSON Codec;显式拒绝会被 JSON.stringify 静默丢弃的顶层值。 */\nconst jsonCodec: StorageCodec = {\n\tdecode: (value) => JSON.parse(value) as unknown,\n\tencode: (value) => {\n\t\tconst encoded = JSON.stringify(value);\n\t\tif (typeof encoded !== \"string\") throw new TypeError(\"存储值无法序列化为 JSON。\");\n\t\treturn encoded;\n\t},\n};\n\n/** Base64 混淆 Codec;只隐藏明文外观,不提供加密、完整性或认证。 */\nexport const base64StorageCodec: StorageCodec = {\n\tdecode: (value) => JSON.parse(decodeSecureBase64(value)) as unknown,\n\tencode: (value) => {\n\t\tconst encoded = JSON.stringify(value);\n\t\tif (typeof encoded !== \"string\") throw new TypeError(\"存储值无法序列化为 JSON。\");\n\t\treturn encodeSecureBase64(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 键必须是非空字符串。\");\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\" ? runtimeGlobals.localStorage : runtimeGlobals.sessionStorage;\n\tif (storage === undefined) throw new Error(`当前运行环境不支持 ${kind}Storage。`);\n\treturn {\n\t\tgetItem: (key) => storage.getItem(key),\n\t\tkeys: () => {\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) => {\n\t\t\tstorage.removeItem(key);\n\t\t},\n\t\tsetItem: (key, value) => {\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) => {\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: () => [...storage.getStorageInfoSync().keys],\n\tremoveItem: (key) => {\n\t\tstorage.removeStorageSync(key);\n\t},\n\tsetItem: (key, value) => {\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 条目“${key}”不是字符串。`);\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(\"不支持该存储包络。\");\n\t\t}\n\t\treturn { data: parsed[\"data\"], expiresAt: parsed[\"expiresAt\"], version: 3 };\n\t} catch (cause) {\n\t\tthrow new TypeError(`Storage 条目“${key}”已损坏或不受支持。`, { 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) => `${prefix}${key}`;\n\t/**\n\t * 解析本次读写实际使用的 Codec。\n\t *\n\t * @param crypto - 单次 Base64 混淆开关;省略时沿用 Area 全局 Codec。\n\t * @returns 本次操作使用的全局、JSON 或 Base64 Codec。\n\t * @throws `TypeError` 当 JavaScript 调用方传入非布尔值。\n\t */\n\tconst resolveOperationCodec = (crypto: boolean | undefined) => {\n\t\tif (crypto === undefined) return codec;\n\t\tif (typeof crypto !== \"boolean\") throw new TypeError(\"Storage 单次 `crypto` 选项必须是布尔值。\");\n\t\treturn crypto ? base64StorageCodec : jsonCodec;\n\t};\n\t/**\n\t * 枚举当前命名空间中的业务键。\n\t *\n\t * @param backend - 本次操作使用的后端。\n\t * @returns 已移除物理前缀、去重并排序的业务键。\n\t * @throws `TypeError` 当后端返回非字符串键。\n\t */\n\tconst listBusinessKeys = (backend: StorageBackend) => {\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 后端返回的键必须是字符串。\");\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 时钟必须返回有限时间戳。\");\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() {\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, options: StorageReadOptions = {}): 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 resolveOperationCodec(options.crypto).decode(envelope.data) as Value;\n\t\t\t} catch (cause) {\n\t\t\t\tthrow new TypeError(`无法解码 Storage 条目“${toStorageKey(key)}”。`, { cause });\n\t\t\t}\n\t\t},\n\t\thas: (key) => readStoredEnvelope(backendFactory(), key) !== undefined,\n\t\tkeys: () => listBusinessKeys(backendFactory()),\n\t\tpruneExpired() {\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) {\n\t\t\tassertKey(key);\n\t\t\tbackendFactory().removeItem(toStorageKey(key));\n\t\t},\n\t\tremoveByPrefix(keyPrefix: string) {\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 = {}) {\n\t\t\tassertKey(key);\n\t\t\tif (value === undefined) throw new TypeError(\"不能存储顶层 `undefined`,请改为移除对应的键。\");\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` 必须是大于 0 的有限数。\");\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 过期时间超出支持的时间戳范围。\");\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 = resolveOperationCodec(options.crypto).encode(value);\n\t\t\t\tif (typeof data !== \"string\") throw new TypeError(\"Storage Codec 必须返回字符串。\");\n\t\t\t} catch (cause) {\n\t\t\t\tthrow new TypeError(\"无法编码存储值。\", { 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 显式配置或首次 Storage 操作创建的默认配置。\n */\nconst requireStorageConfiguration = (): ActiveStorageConfiguration => {\n\tif (activeConfiguration === undefined) configureStorage();\n\tif (activeConfiguration === undefined) throw new Error(\"无法初始化 Storage 配置。\");\n\treturn activeConfiguration;\n};\n\n/**\n * 创建稳定的公开 Storage 门面。\n *\n * @param select - 从激活配置选择 Local 或 Session 的函数。\n * @param name - 用于不可用错误的公开门面名称。\n * @returns 可安全导入、并在首次调用时解析默认或显式配置的稳定对象。\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 = () => {\n\t\tconst area = select(requireStorageConfiguration());\n\t\tif (area === undefined) throw new Error(`uni-app 中不支持 ${name}。`);\n\t\treturn area;\n\t};\n\treturn {\n\t\tget prefix() {\n\t\t\treturn getArea().prefix;\n\t\t},\n\t\tclear: () => {\n\t\t\tgetArea().clear();\n\t\t},\n\t\tget: <Value>(key: string, options?: StorageReadOptions): Value | undefined => getArea().get<Value>(key, options),\n\t\thas: (key) => getArea().has(key),\n\t\tkeys: () => getArea().keys(),\n\t\tpruneExpired: () => getArea().pruneExpired(),\n\t\tremove: (key) => {\n\t\t\tgetArea().remove(key);\n\t\t},\n\t\tremoveByPrefix: (keyPrefix) => {\n\t\t\tgetArea().removeByPrefix(keyPrefix);\n\t\t},\n\t\tset: <Value>(key: string, value: Value, options?: StorageWriteOptions) => {\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 * 在首次 Storage 操作前可选配置 `Local` 与 `Session`。\n *\n * @remarks 不调用时在首次操作上使用 `fast__`、JSON Codec 与 `Date.now`。首次激活后只允许以完全相同的值和引用重复调用。若检测到\n * 全局 `uni`,则自动使用其同步 Storage 且只启用 `Local`,否则使用浏览器 `localStorage` 与 `sessionStorage`。\n * `crypto: true` 仅恢复旧版 Base64 混淆行为,不能保护敏感数据。\n * @param options - 可选的全局键前缀、Codec、旧版混淆选项与时钟。\n * @throws 配置非法、重复配置冲突或目标平台 Storage 不可用时抛出错误。\n */\nexport function configureStorage(options: StorageConfiguration = {}): void {\n\tconst prefix = options.prefix ?? \"fast__\";\n\tif (typeof prefix !== \"string\" || prefix.length === 0) {\n\t\tthrow new TypeError(\"Storage 前缀必须是非空字符串。\");\n\t}\n\tif (options.codec !== undefined && options.crypto === true) {\n\t\tthrow new TypeError(\"Storage 的 Codec 和加密选项不能同时使用。\");\n\t}\n\tconst codec = options.codec ?? (options.crypto === true ? base64StorageCodec : jsonCodec);\n\tconst now = options.now ?? Date.now;\n\tif (activeConfiguration !== undefined) {\n\t\t// 相同配置允许多个入口模块幂等调用;任何引用或值变化都视为冲突。\n\t\tif (activeConfiguration.prefix === prefix && activeConfiguration.codec === codec && activeConfiguration.now === now) {\n\t\t\treturn;\n\t\t}\n\t\tthrow new Error(\"Storage 已使用其他选项完成配置。\");\n\t}\n\tconst uni = getGlobalUniStorage();\n\tconst localBackend = uni === undefined ? () => createWebStorageBackend(\"local\") : () => createUniStorageBackend(uni);\n\tconst local = createStorageArea(localBackend, prefix, codec, now);\n\tconst configuration: ActiveStorageConfiguration = { codec, local, now, prefix };\n\tif (uni === undefined) {\n\t\tconfiguration.session = createStorageArea(() => createWebStorageBackend(\"session\"), prefix, codec, now);\n\t}\n\tactiveConfiguration = configuration;\n}\n\n/** 返回全局 Storage 是否已经由应用入口配置。 */\nexport function isStorageConfigured(): boolean {\n\treturn activeConfiguration !== undefined;\n}\n"],"mappings":";;;;;;;;;AAgLA,MAAM,4BAAwD;CAC7D,MAAM,QAAQ,eAAe;CAC7B,IAAI,UAAU,KAAA,GAAW,OAAO,KAAA;CAChC,IAAK,OAAO,UAAU,YAAY,OAAO,UAAU,cAAe,UAAU,MAC3E,MAAM,IAAI,UAAU,6BAA6B;CAElD,MAAM,UAAU;CAChB,IACC,OAAO,QAAQ,mBAAmB,cAClC,OAAO,QAAQ,uBAAuB,cACtC,OAAO,QAA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;CAE1C,IAAI,QAAQ,UAAU,KAAA,KAAa,QAAQ,WAAW,MACrD,MAAM,IAAI,UAAU,8BAA8B;CAEnD,MAAM,QAAQ,QAAQ,UAAU,QAAQ,WAAW,OAAO,qBAAqB;CAC/E,MAAM,MAAM,QAAQ,OAAO,KAAK;CAChC,IAAI,wBAAwB,KAAA,GAAW;EAEtC,IAAI,oBAAoB,WAAW,UAAU,oBAAoB,UAAU,SAAS,oBAAoB,QAAQ,KAC/G;EAED,MAAM,IAAI,MAAM,sBAAsB;CACvC;CACA,MAAM,MAAM,oBAAoB;CAGhC,MAAM,gBAA4C;EAAE;EAAO,OAD7C,kBADO,QAAQ,KAAA,UAAkB,wBAAwB,OAAO,UAAU,wBAAwB,GAAG,GACrE,QAAQ,OAAO,GACE;EAAG;EAAK;CAAO;CAC9E,IAAI,QAAQ,KAAA,GACX,cAAc,UAAU,wBAAwB,wBAAwB,SAAS,GAAG,QAAQ,OAAO,GAAG;CAEvG,sBAAsB;AACvB;;AAGA,SAAgB,sBAA+B;CAC9C,OAAO,wBAAwB,KAAA;AAChC"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/storage/index.ts"],"sourcesContent":["import { decodeSecureBase64, encodeSecureBase64 } from \"../base64/index\";\nimport { getRuntimeUni, runtimeGlobals } from \"../internal/runtime\";\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/** 启用 Base64 可逆混淆;不提供加密、完整性或认证,不能与 `codec` 同时使用。 */\n\tcrypto?: boolean;\n\t/** 返回 Unix 毫秒时间戳的时钟;默认使用 `Date.now`,主要用于 TTL 测试与受控时间源。 */\n\tnow?: () => number;\n\t/** 所有物理键使用的非空命名空间前缀; */\n\tprefix?: string;\n}\n\n/** 单次 Storage 读取配置。 */\nexport interface StorageReadOptions {\n\t/**\n\t * 仅覆盖本次读取使用的 Codec;`true` 使用 Base64 混淆,`false` 使用 JSON,省略时使用全局配置。\n\t * 必须与写入该条目时使用的单次设置一致。\n\t */\n\tcrypto?: boolean;\n}\n\n/** 单次 Storage 写入配置。 */\nexport interface StorageWriteOptions extends StorageReadOptions {\n\t/** 从写入时刻开始的有效毫秒数;必须是大于 0 的有限数,省略时永久有效。 */\n\tttlMs?: number;\n}\n\n/** `Local` 与 `Session` 的统一操作接口。 */\nexport interface StorageArea {\n\t/** 当前全局 Storage 配置的物理键前缀;首次读取会激活默认配置。 */\n\treadonly prefix: string;\n\t/**\n\t * 删除当前命名空间内的全部键,不影响同一后端中的其他应用键。\n\t * @throws `Error` 当当前平台后端不可用。\n\t */\n\tclear: () => void;\n\t/**\n\t * 获取并解码业务值;已过期记录会在读取时删除。\n\t * @param key - 不含全局前缀的非空业务键。\n\t * @param options - 可选的单次 Base64 混淆开关;必须与写入时一致。\n\t * @returns 解码后的值;未传泛型时静态类型默认为 `string`,键缺失或过期时返回 `undefined`。\n\t * @throws 当键非法、包络损坏、Codec 解码失败或后端不可用时抛出错误。\n\t */\n\tget: <Value = string>(key: string, options?: StorageReadOptions) => 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 与 Base64 混淆开关。\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/**\n * 读取并校验当前运行时的全局 uni-app 同步 Storage。\n *\n * @returns 检测到 uni-app 时返回同步 Storage;普通浏览器环境返回 `undefined`。\n * @throws `TypeError` 当全局 `uni` 存在但缺少本库需要的同步 Storage 方法。\n */\nconst getGlobalUniStorage = (): UniStorageLike | undefined => {\n\tconst value = getRuntimeUni();\n\tif (value === undefined) return undefined;\n\tif ((typeof value !== \"object\" && typeof value !== \"function\") || value === null) {\n\t\tthrow new TypeError(\"全局 uni 对象未提供同步 Storage API。\");\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(\"全局 uni 对象未提供同步 Storage API。\");\n\t}\n\treturn storage as UniStorageLike;\n};\n\n/** 默认 JSON Codec;显式拒绝会被 JSON.stringify 静默丢弃的顶层值。 */\nconst jsonCodec: StorageCodec = {\n\tdecode: (value) => JSON.parse(value) as unknown,\n\tencode: (value) => {\n\t\tconst encoded = JSON.stringify(value);\n\t\tif (typeof encoded !== \"string\") throw new TypeError(\"存储值无法序列化为 JSON。\");\n\t\treturn encoded;\n\t},\n};\n\n/** Base64 混淆 Codec;只隐藏明文外观,不提供加密、完整性或认证。 */\nexport const base64StorageCodec: StorageCodec = {\n\tdecode: (value) => JSON.parse(decodeSecureBase64(value)) as unknown,\n\tencode: (value) => {\n\t\tconst encoded = JSON.stringify(value);\n\t\tif (typeof encoded !== \"string\") throw new TypeError(\"存储值无法序列化为 JSON。\");\n\t\treturn encodeSecureBase64(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 键必须是非空字符串。\");\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\" ? runtimeGlobals.localStorage : runtimeGlobals.sessionStorage;\n\tif (storage === undefined) throw new Error(`当前运行环境不支持 ${kind}Storage。`);\n\treturn {\n\t\tgetItem: (key) => storage.getItem(key),\n\t\tkeys: () => {\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) => {\n\t\t\tstorage.removeItem(key);\n\t\t},\n\t\tsetItem: (key, value) => {\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) => {\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: () => [...storage.getStorageInfoSync().keys],\n\tremoveItem: (key) => {\n\t\tstorage.removeStorageSync(key);\n\t},\n\tsetItem: (key, value) => {\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 条目“${key}”不是字符串。`);\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(\"不支持该存储包络。\");\n\t\t}\n\t\treturn { data: parsed[\"data\"], expiresAt: parsed[\"expiresAt\"], version: 3 };\n\t} catch (cause) {\n\t\tthrow new TypeError(`Storage 条目“${key}”已损坏或不受支持。`, { 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) => `${prefix}${key}`;\n\t/**\n\t * 解析本次读写实际使用的 Codec。\n\t *\n\t * @param crypto - 单次 Base64 混淆开关;省略时沿用 Area 全局 Codec。\n\t * @returns 本次操作使用的全局、JSON 或 Base64 Codec。\n\t * @throws `TypeError` 当 JavaScript 调用方传入非布尔值。\n\t */\n\tconst resolveOperationCodec = (crypto: boolean | undefined) => {\n\t\tif (crypto === undefined) return codec;\n\t\tif (typeof crypto !== \"boolean\") throw new TypeError(\"Storage 单次 `crypto` 选项必须是布尔值。\");\n\t\treturn crypto ? base64StorageCodec : jsonCodec;\n\t};\n\t/**\n\t * 枚举当前命名空间中的业务键。\n\t *\n\t * @param backend - 本次操作使用的后端。\n\t * @returns 已移除物理前缀、去重并排序的业务键。\n\t * @throws `TypeError` 当后端返回非字符串键。\n\t */\n\tconst listBusinessKeys = (backend: StorageBackend) => {\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 后端返回的键必须是字符串。\");\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 时钟必须返回有限时间戳。\");\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() {\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, options: StorageReadOptions = {}): 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 resolveOperationCodec(options.crypto).decode(envelope.data) as Value;\n\t\t\t} catch (cause) {\n\t\t\t\tthrow new TypeError(`无法解码 Storage 条目“${toStorageKey(key)}”。`, { cause });\n\t\t\t}\n\t\t},\n\t\thas: (key) => readStoredEnvelope(backendFactory(), key) !== undefined,\n\t\tkeys: () => listBusinessKeys(backendFactory()),\n\t\tpruneExpired() {\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) {\n\t\t\tassertKey(key);\n\t\t\tbackendFactory().removeItem(toStorageKey(key));\n\t\t},\n\t\tremoveByPrefix(keyPrefix: string) {\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 = {}) {\n\t\t\tassertKey(key);\n\t\t\tif (value === undefined) throw new TypeError(\"不能存储顶层 `undefined`,请改为移除对应的键。\");\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` 必须是大于 0 的有限数。\");\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 过期时间超出支持的时间戳范围。\");\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 = resolveOperationCodec(options.crypto).encode(value);\n\t\t\t\tif (typeof data !== \"string\") throw new TypeError(\"Storage Codec 必须返回字符串。\");\n\t\t\t} catch (cause) {\n\t\t\t\tthrow new TypeError(\"无法编码存储值。\", { 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 显式配置或首次 Storage 操作创建的默认配置。\n */\nconst requireStorageConfiguration = (): ActiveStorageConfiguration => {\n\tif (activeConfiguration === undefined) configureStorage();\n\tif (activeConfiguration === undefined) throw new Error(\"无法初始化 Storage 配置。\");\n\treturn activeConfiguration;\n};\n\n/**\n * 创建稳定的公开 Storage 门面。\n *\n * @param select - 从激活配置选择 Local 或 Session 的函数。\n * @param name - 用于不可用错误的公开门面名称。\n * @returns 可安全导入、并在首次调用时解析默认或显式配置的稳定对象。\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 = () => {\n\t\tconst area = select(requireStorageConfiguration());\n\t\tif (area === undefined) throw new Error(`uni-app 中不支持 ${name}。`);\n\t\treturn area;\n\t};\n\treturn {\n\t\tget prefix() {\n\t\t\treturn getArea().prefix;\n\t\t},\n\t\tclear: () => {\n\t\t\tgetArea().clear();\n\t\t},\n\t\tget: <Value>(key: string, options?: StorageReadOptions): Value | undefined => getArea().get<Value>(key, options),\n\t\thas: (key) => getArea().has(key),\n\t\tkeys: () => getArea().keys(),\n\t\tpruneExpired: () => getArea().pruneExpired(),\n\t\tremove: (key) => {\n\t\t\tgetArea().remove(key);\n\t\t},\n\t\tremoveByPrefix: (keyPrefix) => {\n\t\t\tgetArea().removeByPrefix(keyPrefix);\n\t\t},\n\t\tset: <Value>(key: string, value: Value, options?: StorageWriteOptions) => {\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 * 在首次 Storage 操作前可选配置 `Local` 与 `Session`。\n *\n * @remarks 不调用时在首次操作上使用 `fast__`、JSON Codec 与 `Date.now`。首次激活后只允许以完全相同的值和引用重复调用。若检测到\n * 全局 `uni`,则自动使用其同步 Storage 且只启用 `Local`,否则使用浏览器 `localStorage` 与 `sessionStorage`。\n * `crypto: true` 仅恢复旧版 Base64 混淆行为,不能保护敏感数据。\n * @param options - 可选的全局键前缀、Codec、旧版混淆选项与时钟。\n * @throws 配置非法、重复配置冲突或目标平台 Storage 不可用时抛出错误。\n */\nexport function configureStorage(options: StorageConfiguration = {}): void {\n\tconst prefix = options.prefix ?? \"fast__\";\n\tif (typeof prefix !== \"string\" || prefix.length === 0) {\n\t\tthrow new TypeError(\"Storage 前缀必须是非空字符串。\");\n\t}\n\tif (options.codec !== undefined && options.crypto === true) {\n\t\tthrow new TypeError(\"Storage 的 Codec 和加密选项不能同时使用。\");\n\t}\n\tconst codec = options.codec ?? (options.crypto === true ? base64StorageCodec : jsonCodec);\n\tconst now = options.now ?? Date.now;\n\tif (activeConfiguration !== undefined) {\n\t\t// 相同配置允许多个入口模块幂等调用;任何引用或值变化都视为冲突。\n\t\tif (activeConfiguration.prefix === prefix && activeConfiguration.codec === codec && activeConfiguration.now === now) {\n\t\t\treturn;\n\t\t}\n\t\tthrow new Error(\"Storage 已使用其他选项完成配置。\");\n\t}\n\tconst uni = getGlobalUniStorage();\n\tconst localBackend = uni === undefined ? () => createWebStorageBackend(\"local\") : () => createUniStorageBackend(uni);\n\tconst local = createStorageArea(localBackend, prefix, codec, now);\n\tconst configuration: ActiveStorageConfiguration = { codec, local, now, prefix };\n\tif (uni === undefined) {\n\t\tconfiguration.session = createStorageArea(() => createWebStorageBackend(\"session\"), prefix, codec, now);\n\t}\n\tactiveConfiguration = configuration;\n}\n\n/** 返回全局 Storage 是否已经由应用入口配置。 */\nexport function isStorageConfigured(): boolean {\n\treturn activeConfiguration !== undefined;\n}\n"],"mappings":";;;;;;;;;AAgLA,MAAM,4BAAwD;CAC7D,MAAM,QAAQ,cAAc;CAC5B,IAAI,UAAU,KAAA,GAAW,OAAO,KAAA;CAChC,IAAK,OAAO,UAAU,YAAY,OAAO,UAAU,cAAe,UAAU,MAC3E,MAAM,IAAI,UAAU,6BAA6B;CAElD,MAAM,UAAU;CAChB,IACC,OAAO,QAAQ,mBAAmB,cAClC,OAAO,QAAQ,uBAAuB,cACtC,OAAO,QAAQ,sBAAsB,cACrC,OAAO,QAAQ,mBAAmB,YAElC,MAAM,IAAI,UAAU,6BAA6B;CAElD,OAAO;AACR;;AAGA,MAAM,YAA0B;CAC/B,SAAS,UAAU,KAAK,MAAM,KAAK;CACnC,SAAS,UAAU;EAClB,MAAM,UAAU,KAAK,UAAU,KAAK;EACpC,IAAI,OAAO,YAAY,UAAU,MAAM,IAAI,UAAU,iBAAiB;EACtE,OAAO;CACR;AACD;;AAGA,MAAa,qBAAmC;CAC/C,SAAS,UAAU,KAAK,MAAM,mBAAmB,KAAK,CAAC;CACvD,SAAS,UAAU;EAClB,MAAM,UAAU,KAAK,UAAU,KAAK;EACpC,IAAI,OAAO,YAAY,UAAU,MAAM,IAAI,UAAU,iBAAiB;EACtE,OAAO,mBAAmB,OAAO;CAClC;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CAAO;CAC9E,IAAI,QAAQ,KAAA,GACX,cAAc,UAAU,wBAAwB,wBAAwB,SAAS,GAAG,QAAQ,OAAO,GAAG;CAEvG,sBAAsB;AACvB;;AAGA,SAAgB,sBAA+B;CAC9C,OAAO,wBAAwB,KAAA;AAChC"}
|
package/dist/string/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { runtimeGlobals } from "../internal/runtime.mjs";
|
|
1
|
+
import { getRuntimeUni, runtimeGlobals } from "../internal/runtime.mjs";
|
|
2
2
|
//#region src/string/index.ts
|
|
3
3
|
const defaultRandomAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
|
4
4
|
const defaultStringLocale = "en-US";
|
|
@@ -201,7 +201,7 @@ function truncateGraphemes(value, maxLength, suffix = "…", locale) {
|
|
|
201
201
|
* @throws `Error` 当运行时没有可用的剪贴板能力或复制失败。
|
|
202
202
|
*/
|
|
203
203
|
async function copy(value) {
|
|
204
|
-
const uni =
|
|
204
|
+
const uni = getRuntimeUni();
|
|
205
205
|
if (uni !== void 0) {
|
|
206
206
|
if (typeof uni !== "object" && typeof uni !== "function" || uni === null) throw new TypeError("全局 uni 对象未提供 `setClipboardData`。");
|
|
207
207
|
const clipboard = uni;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/string/index.ts"],"sourcesContent":["import { runtimeGlobals } from \"../internal/runtime\";\n\nconst defaultRandomAlphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\nconst defaultStringLocale = \"en-US\";\nconst maximumRandomStringLength = 1_000_000;\nconst maximumRandomValuesPerBatch = 16_384;\nconst uint32Range = 0x1_0000_0000;\nconst uuidV4Pattern = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;\n\n/** 查询字符串解析结果;重复键保留为数组,不存在的键读取为 `undefined`。 */\nexport type ParsedQueryParameters = Record<string, string | string[] | undefined>;\n\n/** 大小写与字素分割可接受的显式语言;省略时固定使用 `en-US` 以保持输出稳定。 */\nexport type StringLocale = string | readonly string[] | undefined;\n\n/** uni-app 文本复制所需的最小运行时能力。 */\ninterface UniClipboard {\n\tsetClipboardData: (options: { data: string; fail: (error: unknown) => void; success: () => void }) => void;\n}\n\n/** 使用 Web Crypto 填充随机值,能力缺失时回退到 `Math.random()`。 */\nconst fillRandomValues = (values: Uint8Array<ArrayBuffer> | Uint32Array<ArrayBuffer>): void => {\n\tconst crypto = runtimeGlobals.crypto;\n\tif (typeof crypto?.getRandomValues === \"function\") {\n\t\tcrypto.getRandomValues(values);\n\t\treturn;\n\t}\n\tconst range = values.BYTES_PER_ELEMENT === Uint8Array.BYTES_PER_ELEMENT ? 0x100 : uint32Range;\n\tfor (let index = 0; index < values.length; index += 1) values[index] = Math.floor(Math.random() * range);\n};\n\n/**\n * 从随机字节创建 UUID v4。\n *\n * @param bytes - 长度至少为 16 的随机字节;Version 与 Variant 位会被原地修改。\n * @returns 小写、带连字符的 RFC 4122 UUID v4。\n */\nconst createUuidV4FromBytes = (bytes: Uint8Array): string => {\n\tbytes[6] = ((bytes[6] ?? 0) & 15) | 64;\n\tbytes[8] = ((bytes[8] ?? 0) & 63) | 128;\n\tconst hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\treturn `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n};\n\n/**\n * 按用户可见字素切分文本。\n *\n * @param value - 待切分字符串。\n * @param locale - Segmenter 使用的显式语言;省略时使用固定默认值。\n * @returns 保留组合 Emoji、变音符号和连接序列的字素数组。\n * @throws `Error` 当平台缺少 `Intl.Segmenter`。\n */\nconst splitGraphemes = (value: string, locale: StringLocale): string[] => {\n\tconst Segmenter = runtimeGlobals.Intl?.Segmenter;\n\tif (typeof Segmenter !== \"function\") {\n\t\tthrow new Error(\"当前运行环境不支持 Intl.Segmenter。\");\n\t}\n\tconst segmenter = new Segmenter(locale ?? defaultStringLocale, { granularity: \"grapheme\" });\n\treturn Array.from(segmenter.segment(value), ({ segment }) => segment);\n};\n\n/**\n * 重复执行 URI 组件解码,直到值稳定或达到深度上限。\n *\n * @param value - 不包含 URI 路径语义的编码组件。\n * @param maxDepth - 最大解码次数,默认 `10`。\n * @returns 解码稳定或达到上限后的组件文本。\n * @throws `URIError` 当任一层包含非法百分号序列;深度非法时抛出 `RangeError`。\n */\nexport function decodeURIComponentRepeatedly(value: string, maxDepth = 10): string {\n\tif (!Number.isSafeInteger(maxDepth) || maxDepth < 0) throw new RangeError(\"`maxDepth` 必须是非负安全整数。\");\n\tlet decoded = value;\n\tfor (let index = 0; index < maxDepth; index += 1) {\n\t\tconst next = decodeURIComponent(decoded);\n\t\tif (next === decoded) break;\n\t\tdecoded = next;\n\t}\n\treturn decoded;\n}\n\n/**\n * 解析带 `://` 的绝对 URL、`?query` 或纯查询字符串。\n *\n * @remarks 纯查询字符串值中的未编码 `?` 会作为值内容保留;片段标识及其后内容被忽略。\n * @param input - 完整 URL、带前导问号或不带前导问号的查询文本。\n * @returns 重复键对应字符串数组,空值保留为空字符串。\n */\nexport function parseQueryString(input: string): ParsedQueryParameters {\n\tconst fragmentStart = input.indexOf(\"#\");\n\tconst withoutFragment = fragmentStart < 0 ? input : input.slice(0, fragmentStart);\n\tconst isAbsoluteUrl = /^[a-z][a-z\\d+.-]*:\\/\\//iu.test(withoutFragment);\n\tconst queryStart = withoutFragment.indexOf(\"?\");\n\tif (isAbsoluteUrl && queryStart < 0) return {};\n\tconst query = isAbsoluteUrl ? withoutFragment.slice(queryStart + 1) : withoutFragment.replace(/^\\?/u, \"\");\n\tconst result: ParsedQueryParameters = {};\n\tfor (const [key, value] of new URLSearchParams(query)) {\n\t\tconst existing = Object.hasOwn(result, key) ? result[key] : undefined;\n\t\tif (existing === undefined) {\n\t\t\t// defineProperty 让 `__proto__` 成为普通自有键,不触发 Object.prototype Setter。\n\t\t\tObject.defineProperty(result, key, { configurable: true, enumerable: true, value, writable: true });\n\t\t} else if (Array.isArray(existing)) {\n\t\t\texisting.push(value);\n\t\t} else {\n\t\t\tObject.defineProperty(result, key, { configurable: true, enumerable: true, value: [existing, value], writable: true });\n\t\t}\n\t}\n\treturn result;\n}\n\n/**\n * 判断文本是否为任意合法 JSON 值,包括标量与 `null`。\n *\n * @param value - 待解析文本;纯空白不视为 JSON。\n * @returns `JSON.parse` 能完整解析时返回 `true`。\n */\nexport function isValidJson(value: string): boolean {\n\tif (value.trim().length === 0) return false;\n\ttry {\n\t\tJSON.parse(value);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * 按大小写边界、连字符、下划线与空白切分单词。\n *\n * @example `XMLHttp_request` 返回 `[\"XML\", \"Http\", \"request\"]`。\n * @param value - 待拆分文本。\n * @returns 删除空项、保持输入顺序的单词数组。\n */\nexport function splitWords(value: string): string[] {\n\treturn value\n\t\t.trim()\n\t\t.replace(/(\\p{Ll}|\\p{N})(\\p{Lu})/gu, \"$1 $2\")\n\t\t.replace(/(\\p{Lu})(\\p{Lu}\\p{Ll})/gu, \"$1 $2\")\n\t\t.split(/[\\s_-]+/u)\n\t\t.filter((part) => part.length > 0);\n}\n\n/**\n * 将首个 Unicode 码点转为大写。\n *\n * @param value - 输入文本;空字符串保持为空。\n * @param locale - 显式语言,默认固定为 `en-US`。\n * @returns 首个 Unicode 码点转换后的文本。\n */\nexport function upperFirst(value: string, locale?: StringLocale): string {\n\tconst characters = Array.from(value);\n\tconst first = characters.shift();\n\treturn first === undefined ? \"\" : first.toLocaleUpperCase(locale ?? defaultStringLocale) + characters.join(\"\");\n}\n\n/**\n * 将首个 Unicode 码点转为小写。\n *\n * @param value - 输入文本;空字符串保持为空。\n * @param locale - 显式语言,默认固定为 `en-US`。\n * @returns 首个 Unicode 码点转换后的文本。\n */\nexport function lowerFirst(value: string, locale?: StringLocale): string {\n\tconst characters = Array.from(value);\n\tconst first = characters.shift();\n\treturn first === undefined ? \"\" : first.toLocaleLowerCase(locale ?? defaultStringLocale) + characters.join(\"\");\n}\n\n/**\n * 将文本转换为 camelCase。\n *\n * @param value - 由大小写、连字符、下划线或空白分隔的文本。\n * @param locale - 大小写转换使用的语言,默认固定为 `en-US`。\n * @returns camelCase 文本。\n */\nexport function camelCase(value: string, locale?: StringLocale): string {\n\treturn splitWords(value)\n\t\t.map((part, index) => {\n\t\t\tconst normalized = part.toLocaleLowerCase(locale ?? defaultStringLocale);\n\t\t\treturn index === 0 ? normalized : upperFirst(normalized, locale);\n\t\t})\n\t\t.join(\"\");\n}\n\n/**\n * 将文本转换为 PascalCase。\n *\n * @param value - 参数语义与 {@link camelCase} 一致。\n * @param locale - 大小写转换使用的显式语言。\n * @returns PascalCase 文本。\n */\nexport function pascalCase(value: string, locale?: StringLocale): string {\n\treturn upperFirst(camelCase(value, locale), locale);\n}\n\n/**\n * 将文本转换为 kebab-case。\n *\n * @param value - 参数语义与 {@link camelCase} 一致。\n * @param locale - 大小写转换使用的显式语言。\n * @returns kebab-case 文本。\n */\nexport function kebabCase(value: string, locale?: StringLocale): string {\n\treturn splitWords(value)\n\t\t.map((part) => part.toLocaleLowerCase(locale ?? defaultStringLocale))\n\t\t.join(\"-\");\n}\n\n/**\n * 按 Unicode 字素簇截断文本,避免拆开 emoji、组合音标或代理对。\n *\n * @param value - 输入文本。\n * @param maxLength - 保留的最大字素簇数量。\n * @param suffix - 被截断时追加的文本,默认单字符省略号 `…`;不计入上限。\n * @param locale - 字素分割语言,默认固定为 `en-US`。\n * @returns 未超限时返回原字符串,否则返回截断内容与后缀。\n * @throws `RangeError` 当 `maxLength` 不是非负安全整数或 Locale 无效;缺少\n * `Intl.Segmenter` 时抛出 `Error`。\n */\nexport function truncateGraphemes(value: string, maxLength: number, suffix = \"…\", locale?: StringLocale): string {\n\tif (!Number.isSafeInteger(maxLength) || maxLength < 0) throw new RangeError(\"`maxLength` 必须是非负安全整数。\");\n\tconst segments = splitGraphemes(value, locale);\n\treturn segments.length > maxLength ? segments.slice(0, maxLength).join(\"\") + suffix : value;\n}\n\n/**\n * 把文本复制到系统剪贴板。\n *\n * @remarks uni-app 使用 `setClipboardData`;浏览器优先使用 Clipboard API,并在该 API 不可用时\n * 回退到 `document.execCommand(\"copy\")`。平台拒绝访问剪贴板时不会静默忽略错误。\n * @param value - 要复制的文本。\n * @returns 复制完成后兑现的 Promise。\n * @throws `Error` 当运行时没有可用的剪贴板能力或复制失败。\n */\nexport async function copy(value: string): Promise<void> {\n\tconst uni = runtimeGlobals.uni;\n\tif (uni !== undefined) {\n\t\tif ((typeof uni !== \"object\" && typeof uni !== \"function\") || uni === null) {\n\t\t\tthrow new TypeError(\"全局 uni 对象未提供 `setClipboardData`。\");\n\t\t}\n\t\tconst clipboard = uni as Partial<UniClipboard>;\n\t\tconst setClipboardData = clipboard.setClipboardData?.bind(clipboard);\n\t\tif (setClipboardData === undefined) throw new TypeError(\"全局 uni 对象未提供 `setClipboardData`。\");\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tsetClipboardData({\n\t\t\t\tdata: value,\n\t\t\t\tfail: (error: unknown) => {\n\t\t\t\t\treject(error instanceof Error ? error : new Error(\"文本复制到剪贴板失败。\", { cause: error }));\n\t\t\t\t},\n\t\t\t\tsuccess: resolve,\n\t\t\t});\n\t\t});\n\t\treturn;\n\t}\n\n\tconst browserClipboard = runtimeGlobals.navigator?.clipboard;\n\tif (runtimeGlobals.isSecureContext === true && typeof browserClipboard?.writeText === \"function\") {\n\t\tawait browserClipboard.writeText(value);\n\t\treturn;\n\t}\n\n\tconst document = runtimeGlobals.document;\n\t// eslint-disable-next-line @typescript-eslint/no-deprecated -- 兼容不支持 Clipboard API 的旧 WebView。\n\tif (typeof document?.createElement !== \"function\" || document.body == null || typeof document.execCommand !== \"function\") {\n\t\tthrow new Error(\"当前运行环境不支持访问剪贴板。\");\n\t}\n\tconst textarea = document.createElement(\"textarea\");\n\ttextarea.value = value;\n\ttextarea.style.left = \"-999999px\";\n\ttextarea.style.opacity = \"0\";\n\ttextarea.style.position = \"fixed\";\n\ttextarea.style.top = \"-999999px\";\n\tdocument.body.appendChild(textarea);\n\tlet copied: boolean;\n\ttry {\n\t\ttextarea.focus();\n\t\ttextarea.select();\n\t\t// eslint-disable-next-line @typescript-eslint/no-deprecated -- 兼容不支持 Clipboard API 的旧 WebView。\n\t\tcopied = document.execCommand(\"copy\");\n\t} finally {\n\t\ttextarea.remove();\n\t}\n\tif (!copied) throw new Error(\"文本复制到剪贴板失败。\");\n}\n\n/**\n * 生成随机字符串。\n *\n * @remarks 优先使用 Web Crypto;平台缺少安全随机能力时回退到 `Math.random()`。\n * @param length - 字符数量,必须是 0 至 1,000,000 的安全整数。\n * @param alphabet - 不得为空、包含重复字符或超过 2^32 个 Unicode 码点。\n * @returns 由 `alphabet` 中 Unicode 码点组成的随机文本。\n * @throws `RangeError` 当长度或字母表非法。\n */\nexport function randomString(length: number, alphabet: string = defaultRandomAlphabet): string {\n\tif (!Number.isSafeInteger(length) || length < 0 || length > maximumRandomStringLength) {\n\t\tthrow new RangeError(`\\`length\\` 必须是 0 到 ${maximumRandomStringLength} 之间的安全整数。`);\n\t}\n\tconst characters = Array.from(alphabet);\n\tif (characters.length === 0) throw new RangeError(\"`alphabet` 不能为空。\");\n\tif (new Set(characters).size !== characters.length) throw new RangeError(\"`alphabet` 不能包含重复字符。\");\n\tif (characters.length > 0x1_0000_0000) throw new RangeError(\"`alphabet` 不能包含超过 2^32 个字符。\");\n\tif (length === 0) return \"\";\n\n\t// 丢弃不能平均映射到字母表的尾部区间,避免 `%` 造成前部字符概率偏高。\n\tconst acceptanceLimit = Math.floor(uint32Range / characters.length) * characters.length;\n\tconst result: string[] = [];\n\twhile (result.length < length) {\n\t\tconst remaining = length - result.length;\n\t\t// 分批填充可控制临时内存,并避开 Web Crypto 单次随机数组大小限制。\n\t\tconst samples = new Uint32Array(Math.min(remaining, maximumRandomValuesPerBatch));\n\t\tfillRandomValues(samples);\n\t\tfor (const sample of samples) {\n\t\t\tif (sample >= acceptanceLimit) continue;\n\t\t\tconst character = characters[sample % characters.length];\n\t\t\tif (character === undefined) continue;\n\t\t\tresult.push(character);\n\t\t\tif (result.length === length) break;\n\t\t}\n\t}\n\treturn result.join(\"\");\n}\n\n/**\n * 生成 RFC 4122 version 4 UUID。\n *\n * @remarks 优先使用 Web Crypto;平台缺少安全随机能力时回退到 `Math.random()`。\n * 该 UUID 适合普通唯一标识,不应作为安全令牌或秘密。\n * @returns 小写、带连字符的 UUID v4。\n */\nexport function generateUuidV4(): string {\n\tconst crypto = runtimeGlobals.crypto;\n\tif (typeof crypto?.randomUUID === \"function\") return crypto.randomUUID();\n\tconst bytes = new Uint8Array(16);\n\tfillRandomValues(bytes);\n\treturn createUuidV4FromBytes(bytes);\n}\n\n/**\n * 判断字符串是否为 RFC 4122 version 4 UUID。\n *\n * @param value - 待验证文本;十六进制字母大小写均可。\n * @returns 版本位与 Variant 位均正确时返回 `true`。\n */\nexport function isUuidV4(value: string): boolean {\n\treturn uuidV4Pattern.test(value);\n}\n\n/**\n * 转义 HTML 文本上下文中的五个特殊字符。\n *\n * @remarks 这不是 HTML 清洗器,不能让不可信文本安全进入 URL、CSS、脚本或属性名上下文。\n * @param value - 将作为 HTML 文本节点内容的字符串。\n * @returns 转义 `&`、`<`、`>`、双引号与单引号后的文本。\n */\nexport function escapeHtml(value: string): string {\n\treturn value.replace(/[&<>\"']/gu, (character) => {\n\t\tswitch (character) {\n\t\t\tcase \"&\":\n\t\t\t\treturn \"&\";\n\t\t\tcase \"<\":\n\t\t\t\treturn \"<\";\n\t\t\tcase \">\":\n\t\t\t\treturn \">\";\n\t\t\tcase '\"':\n\t\t\t\treturn \""\";\n\t\t\tdefault:\n\t\t\t\treturn \"'\";\n\t\t}\n\t});\n}\n\n/**\n * 把连续 Unicode 空白折叠为单个空格并删除两端空白。\n *\n * @param value - 输入文本。\n * @returns 规范化后的文本;全空白输入返回空字符串。\n */\nexport function normalizeWhitespace(value: string): string {\n\treturn value.trim().replace(/\\s+/gu, \" \");\n}\n"],"mappings":";;AAEA,MAAM,wBAAwB;AAC9B,MAAM,sBAAsB;AAC5B,MAAM,4BAA4B;AAClC,MAAM,8BAA8B;AACpC,MAAM,cAAc;AACpB,MAAM,gBAAgB;;AActB,MAAM,oBAAoB,WAAqE;CAC9F,MAAM,SAAS,eAAe;CAC9B,IAAI,OAAO,QAAQ,oBAAoB,YAAY;EAClD,OAAO,gBAAgB,MAAM;EAC7B;CACD;CACA,MAAM,QAAQ,OAAO,sBAAsB,WAAW,oBAAoB,MAAQ;CAClF,KAAK,IAAI,QAAQ,GAAG,QAAQ,OAAO,QAAQ,SAAS,GAAG,OAAO,SAAS,KAAK,MAAM,KAAK,OAAO,IAAI,KAAK;AACxG;;;;;;;AAQA,MAAM,yBAAyB,UAA8B;CAC5D,MAAM,MAAO,MAAM,MAAM,KAAK,KAAM;CACpC,MAAM,MAAO,MAAM,MAAM,KAAK,KAAM;CACpC,MAAM,MAAM,MAAM,KAAK,QAAQ,SAAS,KAAK,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE;CACnF,OAAO,GAAG,IAAI,MAAM,GAAG,CAAC,EAAE,GAAG,IAAI,MAAM,GAAG,EAAE,EAAE,GAAG,IAAI,MAAM,IAAI,EAAE,EAAE,GAAG,IAAI,MAAM,IAAI,EAAE,EAAE,GAAG,IAAI,MAAM,EAAE;AACxG;;;;;;;;;AAUA,MAAM,kBAAkB,OAAe,WAAmC;CACzE,MAAM,YAAY,eAAe,MAAM;CACvC,IAAI,OAAO,cAAc,YACxB,MAAM,IAAI,MAAM,2BAA2B;CAE5C,MAAM,YAAY,IAAI,UAAU,UAAU,qBAAqB,EAAE,aAAa,WAAW,CAAC;CAC1F,OAAO,MAAM,KAAK,UAAU,QA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sB,KAAK;AACnC;;;;;;;AAQA,SAAgB,SAAS,OAAwB;CAChD,OAAO,cAAc,KAAK,KAAK;AAChC;;;;;;;;AASA,SAAgB,WAAW,OAAuB;CACjD,OAAO,MAAM,QAAQ,cAAc,cAAc;EAChD,QAAQ,WAAR;GACC,KAAK,KACJ,OAAO;GACR,KAAK,KACJ,OAAO;GACR,KAAK,KACJ,OAAO;GACR,KAAK,MACJ,OAAO;GACR,SACC,OAAO;EACT;CACD,CAAC;AACF;;;;;;;AAQA,SAAgB,oBAAoB,OAAuB;CAC1D,OAAO,MAAM,KAAK,CAAC,CAAC,QAAQ,SAAS,GAAG;AACzC"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/string/index.ts"],"sourcesContent":["import { getRuntimeUni, runtimeGlobals } from \"../internal/runtime\";\n\nconst defaultRandomAlphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\nconst defaultStringLocale = \"en-US\";\nconst maximumRandomStringLength = 1_000_000;\nconst maximumRandomValuesPerBatch = 16_384;\nconst uint32Range = 0x1_0000_0000;\nconst uuidV4Pattern = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;\n\n/** 查询字符串解析结果;重复键保留为数组,不存在的键读取为 `undefined`。 */\nexport type ParsedQueryParameters = Record<string, string | string[] | undefined>;\n\n/** 大小写与字素分割可接受的显式语言;省略时固定使用 `en-US` 以保持输出稳定。 */\nexport type StringLocale = string | readonly string[] | undefined;\n\n/** uni-app 文本复制所需的最小运行时能力。 */\ninterface UniClipboard {\n\tsetClipboardData: (options: { data: string; fail: (error: unknown) => void; success: () => void }) => void;\n}\n\n/** 使用 Web Crypto 填充随机值,能力缺失时回退到 `Math.random()`。 */\nconst fillRandomValues = (values: Uint8Array<ArrayBuffer> | Uint32Array<ArrayBuffer>): void => {\n\tconst crypto = runtimeGlobals.crypto;\n\tif (typeof crypto?.getRandomValues === \"function\") {\n\t\tcrypto.getRandomValues(values);\n\t\treturn;\n\t}\n\tconst range = values.BYTES_PER_ELEMENT === Uint8Array.BYTES_PER_ELEMENT ? 0x100 : uint32Range;\n\tfor (let index = 0; index < values.length; index += 1) values[index] = Math.floor(Math.random() * range);\n};\n\n/**\n * 从随机字节创建 UUID v4。\n *\n * @param bytes - 长度至少为 16 的随机字节;Version 与 Variant 位会被原地修改。\n * @returns 小写、带连字符的 RFC 4122 UUID v4。\n */\nconst createUuidV4FromBytes = (bytes: Uint8Array): string => {\n\tbytes[6] = ((bytes[6] ?? 0) & 15) | 64;\n\tbytes[8] = ((bytes[8] ?? 0) & 63) | 128;\n\tconst hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\treturn `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n};\n\n/**\n * 按用户可见字素切分文本。\n *\n * @param value - 待切分字符串。\n * @param locale - Segmenter 使用的显式语言;省略时使用固定默认值。\n * @returns 保留组合 Emoji、变音符号和连接序列的字素数组。\n * @throws `Error` 当平台缺少 `Intl.Segmenter`。\n */\nconst splitGraphemes = (value: string, locale: StringLocale): string[] => {\n\tconst Segmenter = runtimeGlobals.Intl?.Segmenter;\n\tif (typeof Segmenter !== \"function\") {\n\t\tthrow new Error(\"当前运行环境不支持 Intl.Segmenter。\");\n\t}\n\tconst segmenter = new Segmenter(locale ?? defaultStringLocale, { granularity: \"grapheme\" });\n\treturn Array.from(segmenter.segment(value), ({ segment }) => segment);\n};\n\n/**\n * 重复执行 URI 组件解码,直到值稳定或达到深度上限。\n *\n * @param value - 不包含 URI 路径语义的编码组件。\n * @param maxDepth - 最大解码次数,默认 `10`。\n * @returns 解码稳定或达到上限后的组件文本。\n * @throws `URIError` 当任一层包含非法百分号序列;深度非法时抛出 `RangeError`。\n */\nexport function decodeURIComponentRepeatedly(value: string, maxDepth = 10): string {\n\tif (!Number.isSafeInteger(maxDepth) || maxDepth < 0) throw new RangeError(\"`maxDepth` 必须是非负安全整数。\");\n\tlet decoded = value;\n\tfor (let index = 0; index < maxDepth; index += 1) {\n\t\tconst next = decodeURIComponent(decoded);\n\t\tif (next === decoded) break;\n\t\tdecoded = next;\n\t}\n\treturn decoded;\n}\n\n/**\n * 解析带 `://` 的绝对 URL、`?query` 或纯查询字符串。\n *\n * @remarks 纯查询字符串值中的未编码 `?` 会作为值内容保留;片段标识及其后内容被忽略。\n * @param input - 完整 URL、带前导问号或不带前导问号的查询文本。\n * @returns 重复键对应字符串数组,空值保留为空字符串。\n */\nexport function parseQueryString(input: string): ParsedQueryParameters {\n\tconst fragmentStart = input.indexOf(\"#\");\n\tconst withoutFragment = fragmentStart < 0 ? input : input.slice(0, fragmentStart);\n\tconst isAbsoluteUrl = /^[a-z][a-z\\d+.-]*:\\/\\//iu.test(withoutFragment);\n\tconst queryStart = withoutFragment.indexOf(\"?\");\n\tif (isAbsoluteUrl && queryStart < 0) return {};\n\tconst query = isAbsoluteUrl ? withoutFragment.slice(queryStart + 1) : withoutFragment.replace(/^\\?/u, \"\");\n\tconst result: ParsedQueryParameters = {};\n\tfor (const [key, value] of new URLSearchParams(query)) {\n\t\tconst existing = Object.hasOwn(result, key) ? result[key] : undefined;\n\t\tif (existing === undefined) {\n\t\t\t// defineProperty 让 `__proto__` 成为普通自有键,不触发 Object.prototype Setter。\n\t\t\tObject.defineProperty(result, key, { configurable: true, enumerable: true, value, writable: true });\n\t\t} else if (Array.isArray(existing)) {\n\t\t\texisting.push(value);\n\t\t} else {\n\t\t\tObject.defineProperty(result, key, { configurable: true, enumerable: true, value: [existing, value], writable: true });\n\t\t}\n\t}\n\treturn result;\n}\n\n/**\n * 判断文本是否为任意合法 JSON 值,包括标量与 `null`。\n *\n * @param value - 待解析文本;纯空白不视为 JSON。\n * @returns `JSON.parse` 能完整解析时返回 `true`。\n */\nexport function isValidJson(value: string): boolean {\n\tif (value.trim().length === 0) return false;\n\ttry {\n\t\tJSON.parse(value);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * 按大小写边界、连字符、下划线与空白切分单词。\n *\n * @example `XMLHttp_request` 返回 `[\"XML\", \"Http\", \"request\"]`。\n * @param value - 待拆分文本。\n * @returns 删除空项、保持输入顺序的单词数组。\n */\nexport function splitWords(value: string): string[] {\n\treturn value\n\t\t.trim()\n\t\t.replace(/(\\p{Ll}|\\p{N})(\\p{Lu})/gu, \"$1 $2\")\n\t\t.replace(/(\\p{Lu})(\\p{Lu}\\p{Ll})/gu, \"$1 $2\")\n\t\t.split(/[\\s_-]+/u)\n\t\t.filter((part) => part.length > 0);\n}\n\n/**\n * 将首个 Unicode 码点转为大写。\n *\n * @param value - 输入文本;空字符串保持为空。\n * @param locale - 显式语言,默认固定为 `en-US`。\n * @returns 首个 Unicode 码点转换后的文本。\n */\nexport function upperFirst(value: string, locale?: StringLocale): string {\n\tconst characters = Array.from(value);\n\tconst first = characters.shift();\n\treturn first === undefined ? \"\" : first.toLocaleUpperCase(locale ?? defaultStringLocale) + characters.join(\"\");\n}\n\n/**\n * 将首个 Unicode 码点转为小写。\n *\n * @param value - 输入文本;空字符串保持为空。\n * @param locale - 显式语言,默认固定为 `en-US`。\n * @returns 首个 Unicode 码点转换后的文本。\n */\nexport function lowerFirst(value: string, locale?: StringLocale): string {\n\tconst characters = Array.from(value);\n\tconst first = characters.shift();\n\treturn first === undefined ? \"\" : first.toLocaleLowerCase(locale ?? defaultStringLocale) + characters.join(\"\");\n}\n\n/**\n * 将文本转换为 camelCase。\n *\n * @param value - 由大小写、连字符、下划线或空白分隔的文本。\n * @param locale - 大小写转换使用的语言,默认固定为 `en-US`。\n * @returns camelCase 文本。\n */\nexport function camelCase(value: string, locale?: StringLocale): string {\n\treturn splitWords(value)\n\t\t.map((part, index) => {\n\t\t\tconst normalized = part.toLocaleLowerCase(locale ?? defaultStringLocale);\n\t\t\treturn index === 0 ? normalized : upperFirst(normalized, locale);\n\t\t})\n\t\t.join(\"\");\n}\n\n/**\n * 将文本转换为 PascalCase。\n *\n * @param value - 参数语义与 {@link camelCase} 一致。\n * @param locale - 大小写转换使用的显式语言。\n * @returns PascalCase 文本。\n */\nexport function pascalCase(value: string, locale?: StringLocale): string {\n\treturn upperFirst(camelCase(value, locale), locale);\n}\n\n/**\n * 将文本转换为 kebab-case。\n *\n * @param value - 参数语义与 {@link camelCase} 一致。\n * @param locale - 大小写转换使用的显式语言。\n * @returns kebab-case 文本。\n */\nexport function kebabCase(value: string, locale?: StringLocale): string {\n\treturn splitWords(value)\n\t\t.map((part) => part.toLocaleLowerCase(locale ?? defaultStringLocale))\n\t\t.join(\"-\");\n}\n\n/**\n * 按 Unicode 字素簇截断文本,避免拆开 emoji、组合音标或代理对。\n *\n * @param value - 输入文本。\n * @param maxLength - 保留的最大字素簇数量。\n * @param suffix - 被截断时追加的文本,默认单字符省略号 `…`;不计入上限。\n * @param locale - 字素分割语言,默认固定为 `en-US`。\n * @returns 未超限时返回原字符串,否则返回截断内容与后缀。\n * @throws `RangeError` 当 `maxLength` 不是非负安全整数或 Locale 无效;缺少\n * `Intl.Segmenter` 时抛出 `Error`。\n */\nexport function truncateGraphemes(value: string, maxLength: number, suffix = \"…\", locale?: StringLocale): string {\n\tif (!Number.isSafeInteger(maxLength) || maxLength < 0) throw new RangeError(\"`maxLength` 必须是非负安全整数。\");\n\tconst segments = splitGraphemes(value, locale);\n\treturn segments.length > maxLength ? segments.slice(0, maxLength).join(\"\") + suffix : value;\n}\n\n/**\n * 把文本复制到系统剪贴板。\n *\n * @remarks uni-app 使用 `setClipboardData`;浏览器优先使用 Clipboard API,并在该 API 不可用时\n * 回退到 `document.execCommand(\"copy\")`。平台拒绝访问剪贴板时不会静默忽略错误。\n * @param value - 要复制的文本。\n * @returns 复制完成后兑现的 Promise。\n * @throws `Error` 当运行时没有可用的剪贴板能力或复制失败。\n */\nexport async function copy(value: string): Promise<void> {\n\tconst uni = getRuntimeUni();\n\tif (uni !== undefined) {\n\t\tif ((typeof uni !== \"object\" && typeof uni !== \"function\") || uni === null) {\n\t\t\tthrow new TypeError(\"全局 uni 对象未提供 `setClipboardData`。\");\n\t\t}\n\t\tconst clipboard = uni as Partial<UniClipboard>;\n\t\tconst setClipboardData = clipboard.setClipboardData?.bind(clipboard);\n\t\tif (setClipboardData === undefined) throw new TypeError(\"全局 uni 对象未提供 `setClipboardData`。\");\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tsetClipboardData({\n\t\t\t\tdata: value,\n\t\t\t\tfail: (error: unknown) => {\n\t\t\t\t\treject(error instanceof Error ? error : new Error(\"文本复制到剪贴板失败。\", { cause: error }));\n\t\t\t\t},\n\t\t\t\tsuccess: resolve,\n\t\t\t});\n\t\t});\n\t\treturn;\n\t}\n\n\tconst browserClipboard = runtimeGlobals.navigator?.clipboard;\n\tif (runtimeGlobals.isSecureContext === true && typeof browserClipboard?.writeText === \"function\") {\n\t\tawait browserClipboard.writeText(value);\n\t\treturn;\n\t}\n\n\tconst document = runtimeGlobals.document;\n\t// eslint-disable-next-line @typescript-eslint/no-deprecated -- 兼容不支持 Clipboard API 的旧 WebView。\n\tif (typeof document?.createElement !== \"function\" || document.body == null || typeof document.execCommand !== \"function\") {\n\t\tthrow new Error(\"当前运行环境不支持访问剪贴板。\");\n\t}\n\tconst textarea = document.createElement(\"textarea\");\n\ttextarea.value = value;\n\ttextarea.style.left = \"-999999px\";\n\ttextarea.style.opacity = \"0\";\n\ttextarea.style.position = \"fixed\";\n\ttextarea.style.top = \"-999999px\";\n\tdocument.body.appendChild(textarea);\n\tlet copied: boolean;\n\ttry {\n\t\ttextarea.focus();\n\t\ttextarea.select();\n\t\t// eslint-disable-next-line @typescript-eslint/no-deprecated -- 兼容不支持 Clipboard API 的旧 WebView。\n\t\tcopied = document.execCommand(\"copy\");\n\t} finally {\n\t\ttextarea.remove();\n\t}\n\tif (!copied) throw new Error(\"文本复制到剪贴板失败。\");\n}\n\n/**\n * 生成随机字符串。\n *\n * @remarks 优先使用 Web Crypto;平台缺少安全随机能力时回退到 `Math.random()`。\n * @param length - 字符数量,必须是 0 至 1,000,000 的安全整数。\n * @param alphabet - 不得为空、包含重复字符或超过 2^32 个 Unicode 码点。\n * @returns 由 `alphabet` 中 Unicode 码点组成的随机文本。\n * @throws `RangeError` 当长度或字母表非法。\n */\nexport function randomString(length: number, alphabet: string = defaultRandomAlphabet): string {\n\tif (!Number.isSafeInteger(length) || length < 0 || length > maximumRandomStringLength) {\n\t\tthrow new RangeError(`\\`length\\` 必须是 0 到 ${maximumRandomStringLength} 之间的安全整数。`);\n\t}\n\tconst characters = Array.from(alphabet);\n\tif (characters.length === 0) throw new RangeError(\"`alphabet` 不能为空。\");\n\tif (new Set(characters).size !== characters.length) throw new RangeError(\"`alphabet` 不能包含重复字符。\");\n\tif (characters.length > 0x1_0000_0000) throw new RangeError(\"`alphabet` 不能包含超过 2^32 个字符。\");\n\tif (length === 0) return \"\";\n\n\t// 丢弃不能平均映射到字母表的尾部区间,避免 `%` 造成前部字符概率偏高。\n\tconst acceptanceLimit = Math.floor(uint32Range / characters.length) * characters.length;\n\tconst result: string[] = [];\n\twhile (result.length < length) {\n\t\tconst remaining = length - result.length;\n\t\t// 分批填充可控制临时内存,并避开 Web Crypto 单次随机数组大小限制。\n\t\tconst samples = new Uint32Array(Math.min(remaining, maximumRandomValuesPerBatch));\n\t\tfillRandomValues(samples);\n\t\tfor (const sample of samples) {\n\t\t\tif (sample >= acceptanceLimit) continue;\n\t\t\tconst character = characters[sample % characters.length];\n\t\t\tif (character === undefined) continue;\n\t\t\tresult.push(character);\n\t\t\tif (result.length === length) break;\n\t\t}\n\t}\n\treturn result.join(\"\");\n}\n\n/**\n * 生成 RFC 4122 version 4 UUID。\n *\n * @remarks 优先使用 Web Crypto;平台缺少安全随机能力时回退到 `Math.random()`。\n * 该 UUID 适合普通唯一标识,不应作为安全令牌或秘密。\n * @returns 小写、带连字符的 UUID v4。\n */\nexport function generateUuidV4(): string {\n\tconst crypto = runtimeGlobals.crypto;\n\tif (typeof crypto?.randomUUID === \"function\") return crypto.randomUUID();\n\tconst bytes = new Uint8Array(16);\n\tfillRandomValues(bytes);\n\treturn createUuidV4FromBytes(bytes);\n}\n\n/**\n * 判断字符串是否为 RFC 4122 version 4 UUID。\n *\n * @param value - 待验证文本;十六进制字母大小写均可。\n * @returns 版本位与 Variant 位均正确时返回 `true`。\n */\nexport function isUuidV4(value: string): boolean {\n\treturn uuidV4Pattern.test(value);\n}\n\n/**\n * 转义 HTML 文本上下文中的五个特殊字符。\n *\n * @remarks 这不是 HTML 清洗器,不能让不可信文本安全进入 URL、CSS、脚本或属性名上下文。\n * @param value - 将作为 HTML 文本节点内容的字符串。\n * @returns 转义 `&`、`<`、`>`、双引号与单引号后的文本。\n */\nexport function escapeHtml(value: string): string {\n\treturn value.replace(/[&<>\"']/gu, (character) => {\n\t\tswitch (character) {\n\t\t\tcase \"&\":\n\t\t\t\treturn \"&\";\n\t\t\tcase \"<\":\n\t\t\t\treturn \"<\";\n\t\t\tcase \">\":\n\t\t\t\treturn \">\";\n\t\t\tcase '\"':\n\t\t\t\treturn \""\";\n\t\t\tdefault:\n\t\t\t\treturn \"'\";\n\t\t}\n\t});\n}\n\n/**\n * 把连续 Unicode 空白折叠为单个空格并删除两端空白。\n *\n * @param value - 输入文本。\n * @returns 规范化后的文本;全空白输入返回空字符串。\n */\nexport function normalizeWhitespace(value: string): string {\n\treturn value.trim().replace(/\\s+/gu, \" \");\n}\n"],"mappings":";;AAEA,MAAM,wBAAwB;AAC9B,MAAM,sBAAsB;AAC5B,MAAM,4BAA4B;AAClC,MAAM,8BAA8B;AACpC,MAAM,cAAc;AACpB,MAAM,gBAAgB;;AActB,MAAM,oBAAoB,WAAqE;CAC9F,MAAM,SAAS,eAAe;CAC9B,IAAI,OAAO,QAAQ,oBAAoB,YAAY;EAClD,OAAO,gBAAgB,MAAM;EAC7B;CACD;CACA,MAAM,QAAQ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,0 +1,15 @@
|
|
|
1
|
+
import { useEventListener } from "./event-listener.mjs";
|
|
2
|
+
import { useBreakpoints } from "./breakpoints.mjs";
|
|
3
|
+
import { useResizeObserver } from "./resize-observer.mjs";
|
|
4
|
+
import { useElementSize } from "./element-size.mjs";
|
|
5
|
+
import { useEmits } from "./emits.mjs";
|
|
6
|
+
import { useExpose } from "./expose.mjs";
|
|
7
|
+
import { callOptionalFunction } from "./func.mjs";
|
|
8
|
+
import { withInstall, withInstallDirective, withNoopInstall } from "./install.mjs";
|
|
9
|
+
import { useNow } from "./now.mjs";
|
|
10
|
+
import { definePropType, useProps } from "./props.mjs";
|
|
11
|
+
import { useRender } from "./render.mjs";
|
|
12
|
+
import { makeSlots } from "./slots.mjs";
|
|
13
|
+
import { useWindowSize } from "./window-size.mjs";
|
|
14
|
+
import { withDefineType } from "./with.mjs";
|
|
15
|
+
export { callOptionalFunction, definePropType, makeSlots, useBreakpoints, useElementSize, useEmits, useEventListener, useExpose, useNow, useProps, useRender, useResizeObserver, useWindowSize, withDefineType, withInstall, withInstallDirective, withNoopInstall };
|
package/dist/vue/now.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { runtimeGlobals } from "../internal/runtime.mjs";
|
|
1
|
+
import { getRuntimeUni, runtimeGlobals } from "../internal/runtime.mjs";
|
|
2
2
|
import { getCurrentScope, onScopeDispose, readonly, shallowRef } from "vue";
|
|
3
3
|
//#region src/vue/now.ts
|
|
4
4
|
/**
|
|
@@ -12,7 +12,7 @@ import { getCurrentScope, onScopeDispose, readonly, shallowRef } from "vue";
|
|
|
12
12
|
function useNow(intervalMilliseconds = 1e3) {
|
|
13
13
|
if (!Number.isInteger(intervalMilliseconds) || intervalMilliseconds < 0 || intervalMilliseconds > 2147483647) throw new RangeError("`intervalMilliseconds` 必须是 0 至 2,147,483,647 的整数。");
|
|
14
14
|
const now = shallowRef(/* @__PURE__ */ new Date());
|
|
15
|
-
if (runtimeGlobals.window !== void 0 ||
|
|
15
|
+
if (runtimeGlobals.window !== void 0 || getRuntimeUni() !== void 0) {
|
|
16
16
|
if (getCurrentScope() === void 0) throw new Error("`useNow` 必须在 Vue 响应式作用域内调用。");
|
|
17
17
|
const timer = setInterval(() => {
|
|
18
18
|
now.value = /* @__PURE__ */ new Date();
|
package/dist/vue/now.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"now.mjs","names":[],"sources":["../../src/vue/now.ts"],"sourcesContent":["import { getCurrentScope, onScopeDispose, readonly, shallowRef } from \"vue\";\nimport { runtimeGlobals } from \"../internal/runtime\";\nimport type { ShallowRef } from \"vue\";\n\n/**\n * 按固定间隔提供响应式当前时间。\n *\n * @param intervalMilliseconds - 更新时间间隔,默认 `1000` 毫秒。\n * @returns 当前 Date 的只读 ShallowRef;SSR 环境只返回调用时的时间。\n * @throws `Error` 当浏览器或 uni-app 环境中不存在可用于自动清理的 Vue 响应式作用域。\n * @throws `RangeError` 当间隔不是平台计时器支持的非负有限整数。\n */\nexport function useNow(intervalMilliseconds = 1000): Readonly<ShallowRef<Date>> {\n\tif (!Number.isInteger(intervalMilliseconds) || intervalMilliseconds < 0 || intervalMilliseconds > 2_147_483_647) {\n\t\tthrow new RangeError(\"`intervalMilliseconds` 必须是 0 至 2,147,483,647 的整数。\");\n\t}\n\tconst now = shallowRef(new Date());\n\tif (runtimeGlobals.window !== undefined ||
|
|
1
|
+
{"version":3,"file":"now.mjs","names":[],"sources":["../../src/vue/now.ts"],"sourcesContent":["import { getCurrentScope, onScopeDispose, readonly, shallowRef } from \"vue\";\nimport { getRuntimeUni, runtimeGlobals } from \"../internal/runtime\";\nimport type { ShallowRef } from \"vue\";\n\n/**\n * 按固定间隔提供响应式当前时间。\n *\n * @param intervalMilliseconds - 更新时间间隔,默认 `1000` 毫秒。\n * @returns 当前 Date 的只读 ShallowRef;SSR 环境只返回调用时的时间。\n * @throws `Error` 当浏览器或 uni-app 环境中不存在可用于自动清理的 Vue 响应式作用域。\n * @throws `RangeError` 当间隔不是平台计时器支持的非负有限整数。\n */\nexport function useNow(intervalMilliseconds = 1000): Readonly<ShallowRef<Date>> {\n\tif (!Number.isInteger(intervalMilliseconds) || intervalMilliseconds < 0 || intervalMilliseconds > 2_147_483_647) {\n\t\tthrow new RangeError(\"`intervalMilliseconds` 必须是 0 至 2,147,483,647 的整数。\");\n\t}\n\tconst now = shallowRef(new Date());\n\tif (runtimeGlobals.window !== undefined || getRuntimeUni() !== undefined) {\n\t\tif (getCurrentScope() === undefined) throw new Error(\"`useNow` 必须在 Vue 响应式作用域内调用。\");\n\t\tconst timer = setInterval(() => {\n\t\t\tnow.value = new Date();\n\t\t}, intervalMilliseconds);\n\t\tonScopeDispose(() => {\n\t\t\tclearInterval(timer);\n\t\t});\n\t}\n\treturn readonly(now);\n}\n"],"mappings":";;;;;;;;;;;AAYA,SAAgB,OAAO,uBAAuB,KAAkC;CAC/E,IAAI,CAAC,OAAO,UAAU,oBAAoB,KAAK,uBAAuB,KAAK,uBAAuB,YACjG,MAAM,IAAI,WAAW,mDAAmD;CAEzE,MAAM,MAAM,2BAAW,IAAI,KAAK,CAAC;CACjC,IAAI,eAAe,WAAW,KAAA,KAAa,cAAc,MAAM,KAAA,GAAW;EACzE,IAAI,gBAAgB,MAAM,KAAA,GAAW,MAAM,IAAI,MAAM,6BAA6B;EAClF,MAAM,QAAQ,kBAAkB;GAC/B,IAAI,wBAAQ,IAAI,KAAK;EACtB,GAAG,oBAAoB;EACvB,qBAAqB;GACpB,cAAc,KAAK;EACpB,CAAC;CACF;CACA,OAAO,SAAS,GAAG;AACpB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fast-china/utils",
|
|
3
|
-
"version": "2.1.
|
|
3
|
+
"version": "2.1.8",
|
|
4
4
|
"description": "Typed utilities for modern browsers, WebViews, Vue 3, and uni-app applications.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"keywords": [
|
|
@@ -27,8 +27,8 @@
|
|
|
27
27
|
"README.md",
|
|
28
28
|
"README.zh.md",
|
|
29
29
|
"SECURITY.md",
|
|
30
|
-
"
|
|
31
|
-
"
|
|
30
|
+
"THIRD_PARTY_LICENSES.md",
|
|
31
|
+
"dist"
|
|
32
32
|
],
|
|
33
33
|
"main": "./dist/index.mjs",
|
|
34
34
|
"module": "./dist/index.mjs",
|
|
@@ -64,14 +64,12 @@
|
|
|
64
64
|
"peerDependencies": {
|
|
65
65
|
"vue": "^3.5.11"
|
|
66
66
|
},
|
|
67
|
-
"dependencies": {
|
|
68
|
-
"crypto-js": "^4.2.0"
|
|
69
|
-
},
|
|
70
67
|
"devDependencies": {
|
|
71
68
|
"@eslint/js": "^10.0.1",
|
|
72
69
|
"@eslint/markdown": "^8.0.3",
|
|
73
70
|
"@types/crypto-js": "^4.2.2",
|
|
74
71
|
"@types/node": "^24.13.4",
|
|
72
|
+
"crypto-js": "^4.2.0",
|
|
75
73
|
"eslint": "^10.10.0",
|
|
76
74
|
"eslint-config-flat-gitignore": "^2.4.0",
|
|
77
75
|
"eslint-config-prettier": "^10.1.8",
|
package/dist/array/index.d.mts
DELETED
|
@@ -1,94 +0,0 @@
|
|
|
1
|
-
//#region src/array/index.d.ts
|
|
2
|
-
/** 从数组项中提取可比较键的函数。 */
|
|
3
|
-
export type KeySelector<Item, Key> = (item: Item, index: number) => Key;
|
|
4
|
-
/**
|
|
5
|
-
* 将只读数组按固定大小分组。
|
|
6
|
-
*
|
|
7
|
-
* @typeParam Item - 数组项类型。
|
|
8
|
-
* @param items - 不会被修改的输入数组。
|
|
9
|
-
* @param size - 每组最多包含的项目数,必须是正安全整数。
|
|
10
|
-
* @returns 新建的二维数组;最后一组可能小于 `size`。
|
|
11
|
-
* @throws `RangeError` 当 `size` 不是正安全整数。
|
|
12
|
-
*/
|
|
13
|
-
export declare function chunk<Item>(items: readonly Item[], size: number): Item[][];
|
|
14
|
-
/**
|
|
15
|
-
* 删除数组中的 `null` 与 `undefined`,保留 `false`、`0` 和空字符串。
|
|
16
|
-
*
|
|
17
|
-
* @param items - 可包含空值的只读数组。
|
|
18
|
-
* @returns 保持原顺序的新数组。
|
|
19
|
-
*/
|
|
20
|
-
export declare function removeNullishValues<Item>(items: readonly (Item | null | undefined)[]): Item[];
|
|
21
|
-
/**
|
|
22
|
-
* 使用 JavaScript `Set` 的 SameValueZero 语义去重。
|
|
23
|
-
*
|
|
24
|
-
* @param items - 不会被修改的输入数组。
|
|
25
|
-
* @returns 保留每个值首次出现顺序的新数组;稀疏数组空位被忽略。
|
|
26
|
-
*/
|
|
27
|
-
export declare function unique<Item>(items: readonly Item[]): Item[];
|
|
28
|
-
/**
|
|
29
|
-
* 按选择器返回的键去重。
|
|
30
|
-
*
|
|
31
|
-
* @param items - 不会被修改的输入数组。
|
|
32
|
-
* @param selectKey - 接收项目与索引并返回去重键的函数。
|
|
33
|
-
* @returns 保留每个键首次出现项目的新数组;稀疏数组空位被忽略。
|
|
34
|
-
*/
|
|
35
|
-
export declare function uniqueBy<Item, Key>(items: readonly Item[], selectKey: KeySelector<Item, Key>): Item[];
|
|
36
|
-
/**
|
|
37
|
-
* 按选择器结果分组。
|
|
38
|
-
*
|
|
39
|
-
* @param items - 不会被修改的输入数组。
|
|
40
|
-
* @param selectKey - 返回任意 `Map` 键的函数。
|
|
41
|
-
* @returns 按键首次出现顺序排列的 `Map`;每个分组保持输入顺序,稀疏空位被忽略。
|
|
42
|
-
*/
|
|
43
|
-
export declare function groupBy<Item, Key>(items: readonly Item[], selectKey: KeySelector<Item, Key>): Map<Key, Item[]>;
|
|
44
|
-
/**
|
|
45
|
-
* 按谓词把数组拆分为匹配项和非匹配项。
|
|
46
|
-
*
|
|
47
|
-
* @param items - 不会被修改的输入数组。
|
|
48
|
-
* @param predicate - 接收项目与索引的判断函数。
|
|
49
|
-
* @returns 二元组:第一项匹配谓词,第二项不匹配;两组都保持原顺序并忽略稀疏空位。
|
|
50
|
-
*/
|
|
51
|
-
export declare function partition<Item>(items: readonly Item[], predicate: (item: Item, index: number) => boolean): [matched: Item[], unmatched: Item[]];
|
|
52
|
-
/**
|
|
53
|
-
* 返回只出现在左侧数组中的不同值。
|
|
54
|
-
*
|
|
55
|
-
* @param left - 主输入数组。
|
|
56
|
-
* @param right - 需要排除的值。
|
|
57
|
-
* @returns 保留左侧首次出现顺序的去重结果;两侧稀疏空位都被忽略。
|
|
58
|
-
*/
|
|
59
|
-
export declare function difference<Item>(left: readonly Item[], right: readonly Item[]): Item[];
|
|
60
|
-
/**
|
|
61
|
-
* 返回两个数组共有的不同值。
|
|
62
|
-
*
|
|
63
|
-
* @param left - 决定结果顺序的数组。
|
|
64
|
-
* @param right - 用于成员判断的数组。
|
|
65
|
-
* @returns 保留左侧首次出现顺序的去重结果;两侧稀疏空位都被忽略。
|
|
66
|
-
*/
|
|
67
|
-
export declare function intersection<Item>(left: readonly Item[], right: readonly Item[]): Item[];
|
|
68
|
-
/**
|
|
69
|
-
* 返回只存在于其中一个数组的不同值。
|
|
70
|
-
*
|
|
71
|
-
* @param left - 决定左侧结果顺序的数组。
|
|
72
|
-
* @param right - 决定右侧结果顺序的数组。
|
|
73
|
-
* @returns 先按左侧、再按右侧首次出现顺序排列的对称差集;使用 SameValueZero 比较并忽略稀疏空位。
|
|
74
|
-
*/
|
|
75
|
-
export declare function symmetricDifference<Item>(left: readonly Item[], right: readonly Item[]): Item[];
|
|
76
|
-
/**
|
|
77
|
-
* 判断选择器产生的键是否重复。
|
|
78
|
-
*
|
|
79
|
-
* @param items - 不会被修改的输入数组。
|
|
80
|
-
* @param selectKey - 返回比较键的函数;键使用 SameValueZero 语义比较。
|
|
81
|
-
* @returns 存在至少一个重复键时返回 `true`。
|
|
82
|
-
*/
|
|
83
|
-
export declare function hasDuplicatesBy<Item, Key>(items: readonly Item[], selectKey: KeySelector<Item, Key>): boolean;
|
|
84
|
-
/**
|
|
85
|
-
* 判断所有项目是否具有相同的选择器结果。
|
|
86
|
-
*
|
|
87
|
-
* @remarks 空数组、只有稀疏空位的数组和单项数组按数学惯例返回 `true`;空位不会调用选择器。
|
|
88
|
-
* @param items - 不会被修改的输入数组。
|
|
89
|
-
* @param selectKey - 返回比较键的函数。
|
|
90
|
-
* @returns 所有键都满足 SameValueZero 相等时返回 `true`。
|
|
91
|
-
*/
|
|
92
|
-
export declare function allEqualBy<Item, Key>(items: readonly Item[], selectKey: KeySelector<Item, Key>): boolean;
|
|
93
|
-
//#endregion
|
|
94
|
-
//# sourceMappingURL=index.d.mts.map
|