@fast-china/utils 2.1.7 → 2.1.9
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 +40 -15
- package/README.md +42 -122
- package/README.zh.md +42 -122
- package/dist/async/index.mjs +2 -2
- package/dist/async/index.mjs.map +1 -1
- package/dist/env/index.mjs +4 -4
- package/dist/env/index.mjs.map +1 -1
- package/dist/function/index.mjs +18 -14
- package/dist/function/index.mjs.map +1 -1
- package/dist/index.d.mts +15 -14
- package/dist/index.global.min.js +2 -2
- package/dist/index.global.min.js.map +1 -1
- 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/number/index.mjs +1 -1
- package/dist/number/index.mjs.map +1 -1
- package/dist/object/index.mjs +26 -14
- package/dist/object/index.mjs.map +1 -1
- package/dist/storage/index.mjs +5 -5
- 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/now.mjs +2 -2
- package/dist/vue/now.mjs.map +1 -1
- package/package.json +3 -3
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,M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C;CAC1B,OAAO,OAAO,SAAS,QAAQ;EAC9B,MAAM,YAAY,SAAS,OAAO;EAElC,MAAM,UAAU,IAAI,YAAY,KAAK,IAAI,WAAW,2BAA2B,CAAC;EAChF,iBAAiB,OAAO;EACxB,KAAK,MAAM,UAAU,SAAS;GAC7B,IAAI,UAAU,iBAAiB;GAC/B,MAAM,YAAY,WAAW,SAAS,WAAW;GACjD,IAAI,cAAc,KAAA,GAAW;GAC7B,OAAO,KAAK,SAAS;GACrB,IAAI,OAAO,WAAW,QAAQ;EAC/B;CACD;CACA,OAAO,OAAO,KAAK,EAAE;AACtB;;;;;;;;AASA,SAAgB,iBAAyB;CACxC,MAAM,SAAS,eAAe;CAC9B,IAAI,OAAO,QAAQ,eAAe,YAAY,OAAO,OAAO,WAAW;CACvE,MAAM,wBAAQ,IAAI,WAAW,EAAE;CAC/B,iBAAiB,KAAK;CACtB,OAAO,sBAAsB,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,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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AM,SAAS,eAAe;CAC9B,IAAI,OAAO,QAAQ,eAAe,YAAY,OAAO,OAAO,WAAW;CACvE,MAAM,wBAAQ,IAAI,WAAW,EAAE;CAC/B,iBAAiB,KAAK;CACtB,OAAO,sBAAsB,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"}
|
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.9",
|
|
4
4
|
"description": "Typed utilities for modern browsers, WebViews, Vue 3, and uni-app applications.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"keywords": [
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
"utils"
|
|
11
11
|
],
|
|
12
12
|
"license": "Apache-2.0",
|
|
13
|
-
"homepage": "
|
|
13
|
+
"homepage": "http://fastdotnet.com",
|
|
14
14
|
"bugs": {
|
|
15
15
|
"url": "https://gitee.com/FastDotnet/fast.utils/issues"
|
|
16
16
|
},
|
|
@@ -56,7 +56,7 @@
|
|
|
56
56
|
"format:check": "prettier --check .",
|
|
57
57
|
"test": "pnpm run build && pnpm run test:types && pnpm run test:runtime && pnpm run test:package",
|
|
58
58
|
"test:types": "tsc --noEmit --project tests/tsconfig.json",
|
|
59
|
-
"test:runtime": "node --import tsx --test tests/async.test.ts tests/core.test.ts tests/storage-crypto.test.ts tests/storage-default.test.ts tests/storage-uni.test.ts tests/vue.test.ts",
|
|
59
|
+
"test:runtime": "node --import tsx --test tests/async.test.ts tests/core.test.ts tests/storage-crypto.test.ts tests/storage-default.test.ts tests/storage-uni.test.ts tests/vue.test.ts tests/number.test.ts tests/object-contract.test.ts tests/tool-ignores.test.mjs",
|
|
60
60
|
"test:package": "node --test tests/package.test.mjs && publint --strict --pack npm",
|
|
61
61
|
"check": "pnpm run typecheck && pnpm run lint && pnpm run test && pnpm run format:check",
|
|
62
62
|
"prepack": "pnpm run check"
|