Skip to content

Spot it. Save it. Free, local-first Chrome extension for images, videos and prompts. Explore 2,000+ curated cases and connect your library to AI Agents via MCP. 提示词导演

保障大资料库导入与文件夹备份的持续可用性

MigenAIafd72d4ccfa3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ef34dd2..2074ead 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,12 @@
# Changelog
+## 1.20.2
+
+- 修复文件夹备份目录选择器丢失用户手势;预检后才创建备份目录,写入和回读验证后再生成完成标记,取消及失败反馈更准确。
+- 资料库导入导出支持 ZIP64 和 GB 级原件,按实际资源能力处理案例和文件数量;保留路径、校验和、容量与事务保护。
+- 大包逐包检查,解压与备份哈希逐段处理;补齐历史图片格式的恢复检查。
+- 发布验证加入原生目录选择器、多 GB ZIP 往返和升级后原始媒体保留检查。
+
## 1.20.1
- 设置首页收紧布局:关联按钮与功能同排、保存改为图标,跨设备同步按需展开;许可与版本详情移到“关于”。
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 7fec7cf..8bef713 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -27,3 +27,7 @@ PromptDirector includes Turndown for local HTML-to-Markdown conversion. It is li
## Mozilla Readability
PromptDirector includes Mozilla Readability for local article extraction. It is licensed under the Apache License 2.0; the complete license is included at `vendor/document-ingestion/readability-LICENSE`.
+
+## @noble/hashes
+
+Incremental SHA-256 for library file integrity verification. MIT licensed. Source: https://github.com/paulmillr/noble-hashes . The pinned version is recorded in package-lock.json; its license is included in vendor/noble-hashes/LICENSE.
diff --git a/blob-digest.js b/blob-digest.js
new file mode 100644
index 0000000..e70345e
--- /dev/null
+++ b/blob-digest.js
@@ -0,0 +1,18 @@
+import { sha256 } from "./vendor/noble-hashes/sha2.js";
+
+export async function sha256Blob(blob) {
+ if (!(blob instanceof Blob)) throw new Error("无法计算无效媒体的内容摘要");
+ const hash = sha256.create();
+ const reader = blob.stream().getReader();
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ hash.update(value);
+ }
+ return [...hash.digest()].map((value) => value.toString(16).padStart(2, "0")).join("");
+ } finally {
+ hash.destroy();
+ reader.releaseLock();
+ }
+}
diff --git a/bounded-media.js b/bounded-media.js
index 971afc3..b6e64f0 100644
--- a/bounded-media.js
+++ b/bounded-media.js
@@ -74,6 +74,46 @@ export function isSupportedDocumentMimeType(value) {
return DOCUMENT_MIME_TYPES.has(cleanMimeType(value));
}
+// Validate an already-local document without copying its entire payload into JS memory.
+export async function verifiedDocumentBlob(blob, expectedMimeType, maxBytes) {
+ if (!blob.size) throw new Error("媒体文件为空");
+ if (blob.size > maxBytes) throw new Error(`媒体文件超过本地容量上限(${maxBytes} bytes)`);
+ // Document signatures use the same 256-byte prefix as detectDocumentMimeType.
+ const prefix = new Uint8Array(await blob.slice(0, 256).arrayBuffer());
+ const detected = detectDocumentMimeType(prefix);
+ const text = ["text/plain", "text/markdown"].includes(cleanMimeType(expectedMimeType));
+ const type = verifiedDocumentMimeType(text ? new Uint8Array() : prefix, detected, blob.type, expectedMimeType);
+ if (text) {
+ const decoder = new TextDecoder("utf-8", { fatal: true });
+ const reader = blob.stream().getReader();
+ let length = 0;
+ let controls = 0;
+ const inspect = (value) => {
+ if (value.includes("\u0000")) throw new Error("来源没有返回有效文档文件");
+ length += value.length;
+ for (const character of value) {
+ const code = character.codePointAt(0);
+ if ((code < 0x20 && ![0x09, 0x0a, 0x0d].includes(code)) || code === 0x7f) controls += 1;
+ }
+ };
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ inspect(decoder.decode(value, { stream: true }));
+ }
+ inspect(decoder.decode());
+ if (controls > Math.max(1, Math.floor(length * 0.01))) throw new Error("来源没有返回有效文档文件");
+ } catch (error) {
+ await reader.cancel().catch(() => undefined);
+ throw new Error("来源没有返回有效文档文件", { cause: error });
+ } finally {
+ reader.releaseLock();
+ }
+ }
+ return blob.slice(0, blob.size, type);
+}
+
export function detectImageDimensions(bytesValue, mimeTypeValue = "") {
const bytes = bytesValue instanceof Uint8Array ? bytesValue : new Uint8Array(bytesValue || []);
const mimeType = cleanMimeType(mimeTypeValue) || detectMediaMimeType(bytes);
diff --git a/docs/DATA_COMPATIBILITY.md b/docs/DATA_COMPATIBILITY.md
index c15728e..0d7c68c 100644
--- a/docs/DATA_COMPATIBILITY.md
+++ b/docs/DATA_COMPATIBILITY.md
@@ -41,7 +41,11 @@ PromptDirector 把正式发布的数据格式视为长期产品契约。应用
## 共享媒体边界与迭代回归
-ZIP 读取、案例导入、临时附件恢复和生成结果恢复按同一媒体类型规则校验大小;格式身份仍由 `asset-formats.js` 统一定义,大小策略来自 `resource-limits.js`。当前分享包总量上限 128 MiB,单张原图 32 MiB、单视频 128 MiB、其他单文件 16 MiB;单文件仍须同时满足包总量限制。导出自检采用接收端的默认规则,不能临时放宽限制后宣布可恢复。超过分享包预算时使用完整资料夹备份,备份根据实际文件集合预检并保留回退能力。
+资料库 ZIP、文件夹备份和恢复按实际文件与目标可用空间处理,支持 ZIP64。资料搬迁使用 `LIBRARY_TRANSFER_LIMITS` 表达浏览器可精确表示的字节和计数范围;网页采集与模型附件使用独立的资源预算。路径安全、文件声明大小、CRC、备份哈希和内容关系仍须完整校验。多 ZIP 逐包检查,原件按流读取;取消检查应停止读取,正式导入失败应保持原资料库并清理本次暂存资源。
+
+备份按钮在有效用户点击链路中立即打开目录选择器,随后检查资料,得到必要确认后才创建备份子目录。写入并回读验证通过后才生成完成标记;未写入完成标记的目录只能尝试救援恢复。
+
+发布包实验室强制包含资料延续性场景:原生目录选择器有效/失效手势对照、GIF/AVIF 原件保留、完整/救援/失败备份、历史格式恢复、多 GB ZIP64 与压缩 ZIP 的实际字节往返以及手动同步。规模场景经默认 UI 导入、导出后由 Python 独立校验。重建夹具、原生 headless 取消、原设备真实事故包和用户安装版验收分别记录证据;最终安装版与真实事故包缺失时不能报告完整验收。
原文件字节与衍生封面分别保存。增加媒体类型或修改大小策略时,同时验证案例、回收站、临时参考、生成结果及附件;至少有一项“导出后走默认导入入口”的回归,不能只用生产者自行放宽参数的读回测试。
diff --git a/image-metadata.js b/image-metadata.js
index e02e1dd..be8f783 100644
--- a/image-metadata.js
+++ b/image-metadata.js
@@ -6,15 +6,28 @@ const JPEG_START_OF_FRAME = new Set([
export async function readImageDimensions(blob) {
if (!(blob instanceof Blob) || !blob.size) throw invalidDimensions();
+ if (blob.type === "image/avif") {
+ if (typeof createImageBitmap !== "function") throw new Error("当前环境无法校验 AVIF 图片");
+ const bitmap = await createImageBitmap(blob);
+ try { return dimensions(bitmap.width, bitmap.height); }
+ finally { bitmap.close(); }
+ }
const bytes = new Uint8Array(await blob.slice(0, HEADER_SCAN_BYTES).arrayBuffer());
try {
+ if (blob.type === "image/gif") return gifDimensions(bytes);
if (blob.type === "image/png") return pngDimensions(bytes);
if (blob.type === "image/jpeg") return jpegDimensions(bytes);
if (blob.type === "image/webp") return webpDimensions(bytes);
} catch {
throw invalidDimensions();
}
- throw new Error("只支持 PNG、JPEG 或 WebP 图片");
+ throw new Error("无法识别支持的图片格式");
+}
+
+function gifDimensions(bytes) {
+ if (bytes.length < 10 || !["GIF87a", "GIF89a"].includes(text(bytes, 0, 6))) throw invalidDimensions();
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ return dimensions(view.getUint16(6, true), view.getUint16(8, true));
}
function pngDimensions(bytes) {
diff --git a/library-export-plan.js b/library-export-plan.js
index bb974b8..81f177f 100644
--- a/library-export-plan.js
+++ b/library-export-plan.js
@@ -1,3 +1,4 @@
+import { sha256Blob } from "./blob-digest.js";
const FOLDER_BACKUP_FORMAT = "prompt-director-folder-backup";
const FOLDER_RESCUE_FORMAT = "prompt-director-folder-rescue";
const BACKUP_MARKER_PATHS = new Set(["complete.json", "rescue.json"]);
@@ -210,11 +211,6 @@ function safePath(value) {
return path;
}
-async function sha256Blob(blob) {
- const digest = await crypto.subtle.digest("SHA-256", await blob.arrayBuffer());
- return [...new Uint8Array(digest)].map((value) => value.toString(16).padStart(2, "0")).join("");
-}
-
function nonNegativeInteger(value) {
const number = Number(value);
return Number.isSafeInteger(number) && number >= 0 ? number : 0;
diff --git a/library-export-zip.js b/library-export-zip.js
index 9d25c6e..1e156ef 100644
--- a/library-export-zip.js
+++ b/library-export-zip.js
@@ -1,5 +1,5 @@
import { parseLibraryPackage } from "./library-package.js";
-import { PORTABLE_LIBRARY_LIMITS } from "./resource-limits.js";
+import { LIBRARY_TRANSFER_LIMITS } from "./resource-limits.js";
import { createZipBlob, readZipBlob } from "./zip.js";
export async function createVerifiedLibraryZip(files, expectedLibraryJson) {
@@ -18,7 +18,7 @@ export async function verifyLibraryZipRoundtrip(archive, expectedLibraryJson) {
}
async function verifyRoundtrip(archive, expectedLibraryJson) {
- const limits = PORTABLE_LIBRARY_LIMITS;
+ const limits = LIBRARY_TRANSFER_LIMITS;
const extracted = await readZipBlob(archive, limits);
const libraryFile = extracted.get("library.json");
if (!(libraryFile instanceof Blob)) throw new Error("导出的 ZIP 缺少 library.json");
diff --git a/library-package.js b/library-package.js
index f5debe5..fa9f199 100644
--- a/library-package.js
+++ b/library-package.js
@@ -12,7 +12,7 @@ import {
import { normalizeComposerSessions, normalizeComposerSettings } from "./composer.js";
import { normalizeCreativeExperimentSettings, normalizeCreativeRuns } from "./creative-runs.js";
import { mergeCreativeSkillsState, normalizeCreativeSkillsState } from "./creative-skills.js";
-import { formatBytes, portableLibraryLimits, portableAssetByteLimit } from "./resource-limits.js";
+import { formatBytes, libraryTransferLimits, portableAssetByteLimit } from "./resource-limits.js";
import { normalizeEntryVisuals } from "./visuals.js";
import { normalizeEntryMedia, removeEntryMedia } from "./media.js";
import { expandLogicalCaseIds, normalizeCompoundCases, removeEntriesFromCompoundCases } from "./compound-cases.js";
@@ -20,7 +20,7 @@ import { prepareLibraryPackageDraft } from "./library-package-migrations.js";
import { remapArticleDocumentAssets } from "./article-document.js";
import { caseSemanticFingerprint } from "./library-semantic-identity.js";
import { normalizeTrashState } from "./trash.js";
-import { boundedMediaBlobFromResponse, isSupportedDocumentMimeType } from "./bounded-media.js";
+import { verifiedDocumentBlob, isSupportedDocumentMimeType } from "./bounded-media.js";
import {
assetFormatForExtension,
fileExtension,
@@ -37,22 +37,18 @@ export function hasLibrarySalvageDiagnostics(diagnosticsValue) {
export async function parseCompleteFolderBackup(value, files = new Map(), limitsValue = {}) {
const preparedFiles = new Map(files);
- const limits = portableLibraryLimits(limitsValue);
+ const limits = libraryTransferLimits(limitsValue);
for (const [path, mimeType] of completeBackupDocumentPaths(value)) {
const blob = preparedFiles.get(path);
if (!(blob instanceof Blob)) continue;
- const verified = await boundedMediaBlobFromResponse(new Response(blob), {
- kind: "document",
- expectedMimeType: mimeType,
- maxBytes: limits.maxFileBytes
- });
+ const verified = await verifiedDocumentBlob(blob, mimeType, limits.maxFileBytes);
preparedFiles.set(path, verified);
}
return parseLibraryPackage(value, preparedFiles, { ...limitsValue, salvageInvalidMedia: false });
}
export function parseLibraryPackage(value, files = new Map(), limitsValue = {}) {
- const limits = portableLibraryLimits(limitsValue);
+ const limits = libraryTransferLimits(limitsValue);
const skipMediaByteValidation = limitsValue?.skipMediaByteValidation === true;
const salvageInvalidMedia = limitsValue?.salvageInvalidMedia === true;
const prepared = prepareLibraryPackageDraft(value);
diff --git a/library.js b/library.js
index ff3fe0e..4aeaad6 100644
--- a/library.js
+++ b/library.js
@@ -32,12 +32,13 @@ import {
} from "./library-export-plan.js";
import { buildLibraryImportReport, importReportDescription } from "./library-import-dialog.js";
import { parseCreativeExperimentPackage } from "./creative-experiment-package.js";
-import { readZipBlob } from "./zip.js";
+import { readZipBlob, openZipBlob } from "./zip.js";
import { analysisDiagnosticSummary } from "./analysis-response.js";
import { ANALYSIS_RETRY_POLICY } from "./analysis-retry-policy.js";
import {
ASSET_IMPORT_FAILURE_CODES,
PORTABLE_LIBRARY_LIMITS,
+ LIBRARY_TRANSFER_LIMITS,
assertImageDimensions,
formatBytes,
importFailureDetails
@@ -3441,7 +3442,12 @@ async function createCompleteFolderBackup() {
if (dataSafetyOperationActive) return showDataSafetyFeedback("当前操作仍在进行,请等待完成", true);
if (typeof window.showDirectoryPicker !== "function") return showDataSafetyFeedback("当前浏览器不支持资料夹备份,请使用最新版 Chrome", true);
setDataSafetyBusy(true);
+ let stage = "picker";
try {
+ const parent = await window.showDirectoryPicker({ mode: "readwrite" });
+ const permission = typeof parent.requestPermission === "function" ? await parent.requestPermission({ mode: "readwrite" }) : "granted";
+ if (permission !== "granted") throw new Error("没有获得所选资料夹的写入权限");
+ stage = "preflight";
const response = await chrome.runtime.sendMessage({ type: "GET_FOLDER_BACKUP_STATE" });
if (!response?.ok) throw new Error(response?.message || "无法读取资料库");
const plannedFiles = new Map();
@@ -3620,13 +3626,13 @@ async function createCompleteFolderBackup() {
const plannedLibrary = JSON.parse(libraryJson);
const initialMediaSizes = [...backupMediaPaths(plannedLibrary)].map((path) => plannedFiles.get(path)?.size ?? 0);
const initialTotalBytes = initialMediaSizes.reduce((sum, size) => sum + size, 0);
- const initialLargestMedia = Math.max(1, ...initialMediaSizes);
+ const initialLargestMedia = initialMediaSizes.reduce((largest, size) => Math.max(largest, size), 1);
const inspectPlannedBackup = (sourceType, sourceReport) => inspectLibraryTransfer({
sourceType,
library: plannedLibrary,
files: plannedFiles,
limits: {
- ...PORTABLE_LIBRARY_LIMITS,
+ ...LIBRARY_TRANSFER_LIMITS,
maxArchiveBytes: Math.max(1, initialTotalBytes),
maxFileBytes: initialLargestMedia,
maxImageBytes: initialLargestMedia,
@@ -3680,7 +3686,7 @@ async function createCompleteFolderBackup() {
const finalMediaSizes = [...backupMediaPaths(finalLibrary)].map((path) => finalFiles.get(path)?.size ?? 0);
byteSize = finalMediaSizes.reduce((sum, size) => sum + size, 0);
mediaCount = finalMediaSizes.length;
- const largestPlannedMedia = Math.max(1, ...finalMediaSizes);
+ const largestPlannedMedia = finalMediaSizes.reduce((largest, size) => Math.max(largest, size), 1);
const plannedTotalBytes = byteSize;
const trashCaseCount = (exportState.trashState?.items ?? []).filter((item) => item.kind === "entry").length;
const trashProjectCount = (exportState.trashState?.items ?? []).filter((item) => item.kind === "collection").length;
@@ -3707,11 +3713,9 @@ async function createCompleteFolderBackup() {
return;
}
}
- const parent = await window.showDirectoryPicker({ mode: "readwrite" });
- const permission = typeof parent.requestPermission === "function" ? await parent.requestPermission({ mode: "readwrite" }) : "granted";
- if (permission !== "granted") throw new Error("没有获得所选资料夹的写入权限");
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
const directoryName = writePlan.mode === "rescue" ? `PromptDirector-Rescue-${stamp}` : `PromptDirector-Backup-${stamp}`;
+ stage = "write";
const directory = await parent.getDirectoryHandle(directoryName, { create: true });
let writtenCount = 0;
for (const [path, blob] of writePlan.files) {
@@ -3732,7 +3736,7 @@ async function createCompleteFolderBackup() {
library: writtenLibrary,
files: writtenFiles,
limits: {
- ...PORTABLE_LIBRARY_LIMITS,
+ ...LIBRARY_TRANSFER_LIMITS,
maxArchiveBytes: Math.max(1, plannedTotalBytes),
maxFileBytes: largestPlannedMedia,
maxImageBytes: largestPlannedMedia,
@@ -3746,7 +3750,16 @@ async function createCompleteFolderBackup() {
const completionLabel = writePlan.mode === "rescue" ? "救援备份已完成" : "完整备份已完成";
showDataSafetyFeedback(`${completionLabel} · ${exportState.entries.length} 个案例 · ${mediaCount} 项媒体 · ${formatBytes(byteSize)}`);
} catch (error) {
- if (error?.name !== "AbortError") showDataSafetyFeedback(`${error.message};未写入完成标记的资料夹不会被当作有效备份`, true);
+ if (error?.name === "AbortError" && stage !== "write") {
+ showDataSafetyFeedback("已取消备份,没有创建任何资料夹");
+ } else if (stage === "picker") {
+ const message = ["NotAllowedError", "SecurityError"].includes(error?.name)
+ ? "目录选择器未在有效用户操作中打开或未获得权限,请重新点击备份按钮并允许访问"
+ : error.message;
+ showDataSafetyFeedback(message, true);
+ } else {
+ showDataSafetyFeedback(`${error.message};未写入完成标记的资料夹不会被认定为完整备份,只能尝试救援恢复`, true);
+ }
} finally {
setDataSafetyBusy(false);
}
@@ -3776,9 +3789,9 @@ async function restoreCompleteFolderBackup() {
)) {
throw new Error("完整备份的媒体数量或大小校验失败,未写入资料库");
}
- const largestMediaBytes = Math.max(1, ...backupMediaSizes);
+ const largestMediaBytes = backupMediaSizes.reduce((largest, size) => Math.max(largest, size), 1);
const restoreLimits = {
- ...PORTABLE_LIBRARY_LIMITS,
+ ...LIBRARY_TRANSFER_LIMITS,
maxArchiveBytes: Math.max(1, totalBytes),
maxFileBytes: largestMediaBytes,
maxImageBytes: largestMediaBytes,
@@ -3995,29 +4008,38 @@ async function openLibraryPackageBatch(packageItems, ordinaryItems = []) {
submitError: "",
plannedBytes: 0,
revision: 0,
- submitting: false
+ submitting: false,
+ controller: new AbortController()
};
pendingLibraryPackageBatch = batch;
setDataSafetyBusy(true, "IMPORT_LIBRARY_PACKAGE_BATCH");
elements.libraryPackageImportDialog.showModal();
renderLibraryPackageBatch();
- await Promise.all(batch.items.map((item) => inspectLibraryPackageBatchItem(batch, item)));
+ for (const item of batch.items) {
+ if (pendingLibraryPackageBatch !== batch) break;
+ await inspectLibraryPackageBatchItem(batch, item);
+ }
if (pendingLibraryPackageBatch === batch) await refreshLibraryPackageBatchPlan(batch);
}
async function inspectLibraryPackageBatchItem(batch, item) {
try {
const file = item.file;
- const limits = { ...PORTABLE_LIBRARY_LIMITS };
- const files = await readZipBlob(file, limits);
+ const limits = { ...LIBRARY_TRANSFER_LIMITS };
+ const reader = await openZipBlob(file, limits);
+ if (!reader.names.includes("library.json")) throw new Error("缺少 library.json");
+ const files = await reader.read(["library.json"], { signal: batch.controller.signal });
const libraryFile = files.get("library.json");
if (!libraryFile) throw new Error("缺少 library.json");
- if (libraryFile.size > PORTABLE_LIBRARY_LIMITS.maxLibraryJsonBytes) {
- throw new Error(`library.json 超过 ${formatBytes(PORTABLE_LIBRARY_LIMITS.maxLibraryJsonBytes)}`);
+ if (libraryFile.size > LIBRARY_TRANSFER_LIMITS.maxLibraryJsonBytes) {
+ throw new Error(`library.json 超过 ${formatBytes(LIBRARY_TRANSFER_LIMITS.maxLibraryJsonBytes)}`);
}
let library;
- try { library = JSON.parse(await libraryFile.text()); }
+ const libraryText = await libraryFile.text();
+ try { library = JSON.parse(libraryText); }
catch { throw new Error("library.json 已损坏"); }
+ const resources = await reader.read(reader.names.filter((name) => name !== "library.json"), { signal: batch.controller.signal });
+ for (const [name, blob] of resources) files.set(name, blob);
const inspection = await inspectLibraryTransfer({
sourceType: LIBRARY_TRANSFER_SOURCES.SHARE_PACKAGE,
library,
@@ -4296,6 +4318,7 @@ function cancelLibraryPackageBatch() {
}
function finishLibraryPackageBatch() {
+ pendingLibraryPackageBatch?.controller.abort();
pendingLibraryPackageBatch = null;
if (elements.libraryPackageImportDialog.open) elements.libraryPackageImportDialog.close();
elements.libraryPackageFile.value = "";
@@ -4562,7 +4585,7 @@ async function validateImportedImageDimensions(images) {
async function validateImportedImage(image) {
const metadata = await readImageDimensions(image);
- assertImageDimensions(metadata.width, metadata.height);
+ assertImageDimensions(metadata.width, metadata.height, LIBRARY_TRANSFER_LIMITS);
}
async function hydrateCardImage(image) {
diff --git a/local-media.js b/local-media.js
index 665a21a..46b7c50 100644
--- a/local-media.js
+++ b/local-media.js
@@ -1,3 +1,5 @@
+import { sha256Blob } from "./blob-digest.js";
+export { sha256Blob } from "./blob-digest.js";
import { readImageDimensions as readStoredImageDimensions } from "./image-metadata.js";
import {
ASSET_IMPORT_FAILURE_CODES,
@@ -181,7 +183,7 @@ async function prepareLocalMediaValue(file, assetId, options) {
}
const readDimensions = typeof options.readImageDimensions === "function"
? options.readImageDimensions
- : readLocalImageDimensions;
+ : readStoredImageDimensions;
const dimensions = await readDimensions(blob);
assertImageDimensions(dimensions.width, dimensions.height, limits);
let poster = null;
@@ -251,12 +253,6 @@ export async function findExactMediaDuplicate(file, entries = [], options = {})
return { contentHash, duplicateAssetId: "" };
}
-export async function sha256Blob(blob) {
- if (!(blob instanceof Blob)) throw new Error("无法计算无效媒体的内容摘要");
- const digest = await crypto.subtle.digest("SHA-256", await blob.arrayBuffer());
- return [...new Uint8Array(digest)].map((value) => value.toString(16).padStart(2, "0")).join("");
-}
-
export async function chunkedBlobFingerprint(blob, options = {}) {
if (!(blob instanceof Blob) || !blob.size) throw new Error("无法计算空媒体的内容指纹");
const chunkBytes = Math.max(1, Number(options.chunkBytes) || MEDIA_FINGERPRINT_CHUNK_BYTES);
@@ -270,15 +266,6 @@ export async function chunkedBlobFingerprint(blob, options = {}) {
return [...new Uint8Array(digest)].map((value) => value.toString(16).padStart(2, "0")).join("");
}
-async function readLocalImageDimensions(blob) {
- if (blob.type !== "image/gif") return readStoredImageDimensions(blob);
- const bytes = new Uint8Array(await blob.slice(0, 10).arrayBuffer());
- if (bytes.length < 10 || !["GIF87a", "GIF89a"].includes(String.fromCharCode(...bytes.slice(0, 6)))) {
- throw new Error("无法读取 GIF 图片尺寸");
- }
- return { width: bytes[6] | (bytes[7] << 8), height: bytes[8] | (bytes[9] << 8) };
-}
-
async function createGifFirstFrame(blob) {
if (typeof createImageBitmap !== "function" || typeof OffscreenCanvas !== "function") {
throw new Error("当前浏览器无法提取 GIF 首帧");
diff --git a/manifest.json b/manifest.json
index 2af62cf..b374a02 100644
--- a/manifest.json
+++ b/manifest.json
@@ -1,7 +1,7 @@
{
"manifest_version": 3,
"name": "__MSG_extensionName__",
- "version": "1.20.1",
+ "version": "1.20.2",
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq2m8W9ACXJTkJqPAd36sPrtzonmHhOYU34uS7c+D7DXX6ggWNMwB4xZapGFJ4ScBQJv71PeG9KfsEnhcXFZ9RoX/X3wY+57evL19hf6woNX1xxhKOe1rtx5QmzWCEYIr99TzW50k/N9U6tS9Ri+2DHKYA85ssXTC8B2yRQ5zUXhsAWZe/HDU18UFuvUKXYt3ZdIUi31c2vIlgFFBfsyKbIUMny9LlxL/smb4vJzU/+A3LwJDjjvOtS/lmQ2vHoQGjHJItO18bYI6h67fIEvmWk+HJKtO08Ca+5RLS8TYhI+K7l7S0RyDVNujyVWtvhAULot1H0BvteYL87fKu3SNywIDAQAB",
"homepage_url": "https://github.com/wchao6891/PromptDirector",
"default_locale": "zh_CN",
diff --git a/package-lock.json b/package-lock.json
index 954faf9..df6ad97 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,16 +1,17 @@
{
"name": "prompt-case-collector",
- "version": "1.20.1",
+ "version": "1.20.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "prompt-case-collector",
- "version": "1.20.1",
+ "version": "1.20.2",
"license": "Apache-2.0",
"dependencies": {
"@jonahschulte/rtf-toolkit": "0.5.0",
"@mozilla/readability": "0.6.0",
+ "@noble/hashes": "2.4.0",
"pdfjs-dist": "6.2.108",
"turndown": "7.2.4"
},
@@ -299,6 +300,18 @@
"url": "https://github.com/sponsors/Brooooooklyn"
}
},
+ "node_modules/@noble/hashes": {
+ "version": "2.4.0",
+ "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz",
+ "integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 20.19.0"
+ },
+ "funding": {
+ "url": "https://paulmillr.com/funding/"
+ }
+ },
"node_modules/@resvg/resvg-js": {
"version": "2.6.2",
"resolved": "https://registry.npmjs.org/@resvg/resvg-js/-/resvg-js-2.6.2.tgz",
diff --git a/package.json b/package.json
index a3d13a2..bf8be1f 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "prompt-case-collector",
- "version": "1.20.1",
+ "version": "1.20.2",
"private": false,
"license": "Apache-2.0",
"repository": "https://github.com/wchao6891/PromptDirector",
@@ -22,20 +22,23 @@
"check:pdfjs": "node tools/pdfjs-runtime.mjs --check",
"check:store": "node tools/build-store-assets.mjs --check && node tools/check-store-readiness.mjs",
"check:compat": "node tools/check-data-compatibility.mjs",
- "package": "npm run build:brand && npm run build:documents && npm run build:icons && node tools/package-extension.mjs",
- "package:release": "npm run build:brand && npm run build:documents && npm run build:icons && node tools/package-extension.mjs --release",
+ "package": "npm run build:brand && npm run build:hash && npm run build:documents && npm run build:icons && node tools/package-extension.mjs",
+ "package:release": "npm run build:brand && npm run build:hash && npm run build:documents && npm run build:icons && node tools/package-extension.mjs --release",
"test:e2e": "python3 test/run_e2e.py",
"test:local-extension": "npm run package && node tools/local-extension-lab.mjs",
"test:live:zhipu": "node tools/zhipu-live-smoke.mjs",
"test:upgrade": "node tools/run-release-upgrade-e2e.mjs",
"test:smart-picker": "python3 test/smart_visual_picker_e2e.py",
- "verify:source": "npm run check:public && npm run check && npm run check:brand && npm run check:documents && npm run check:pdfjs && npm run check:store && npm run check:compat && npm test",
+ "verify:source": "npm run check:public && npm run check && npm run check:hash && npm run check:brand && npm run check:documents && npm run check:pdfjs && npm run check:store && npm run check:compat && npm test",
"verify:release": "npm run verify:source && npm run test:local-extension && npm run package:release && npm run test:upgrade",
- "verify": "npm run verify:release"
+ "verify": "npm run verify:release",
+ "build:hash": "node tools/hash-runtime.mjs",
+ "check:hash": "node tools/hash-runtime.mjs --check"
},
"dependencies": {
"@jonahschulte/rtf-toolkit": "0.5.0",
"@mozilla/readability": "0.6.0",
+ "@noble/hashes": "2.4.0",
"pdfjs-dist": "6.2.108",
"turndown": "7.2.4"
},
diff --git a/resource-limits.js b/resource-limits.js
index e2ff777..63637fc 100644
--- a/resource-limits.js
+++ b/resource-limits.js
@@ -60,6 +60,22 @@ export const PORTABLE_LIBRARY_LIMITS = Object.freeze({
maxVideoBytes: 128 * MEBIBYTE
});
+// Transfer limits describe representable byte/count values, not a library quota.
+// Interactive capture and provider inputs retain their own bounded-media policy.
+export const LIBRARY_TRANSFER_LIMITS = Object.freeze(Object.fromEntries(
+ Object.keys(PORTABLE_LIBRARY_LIMITS).map((key) => [key, Number.MAX_SAFE_INTEGER])
+));
+
+export function libraryTransferLimits(value = {}) {
+ const limits = { ...LIBRARY_TRANSFER_LIMITS, ...value };
+ if (Object.hasOwn(value, "maxFileBytes")) {
+ for (const key of ["maxImageBytes", "maxVideoBytes"]) {
+ if (!Object.hasOwn(value, key)) limits[key] = value.maxFileBytes;
+ }
+ }
+ return portableLibraryLimits(limits);
+}
+
export const SMART_VISUAL_SELECTION_LIMIT = 12;
export const SMART_VISUAL_MINIMUM_EDGE = 64;
export const MEDIA_FINGERPRINT_CHUNK_BYTES = 8 * MEBIBYTE;
diff --git a/store/CHROME_WEB_STORE_SUBMISSION.md b/store/CHROME_WEB_STORE_SUBMISSION.md
index d9620a8..eedfa6c 100644
--- a/store/CHROME_WEB_STORE_SUBMISSION.md
+++ b/store/CHROME_WEB_STORE_SUBMISSION.md
@@ -6,7 +6,7 @@ This file is the source-of-truth worksheet for the current PromptDirector manife
- Chrome Web Store item public key: stored in the source `manifest.json` for local identity verification only; `package:release` removes `key` from the upload manifest.
- Expected extension ID: `iahakaahijddcjjldidbclicedibgpjm`.
-- Current upload artifact: `dist/PromptDirector-1.20.1.zip`. The GitHub `FIXED-ID-DEV` artifact is for local installations only.
+- Current upload artifact: `dist/PromptDirector-1.20.2.zip`. The GitHub `FIXED-ID-DEV` artifact is for local installations only.
- Generate a candidate only with `npm run package:release`; the command verifies the source public key against the expected identity, then removes `key` from the Web Store upload manifest and excludes the local program installer. Record the generated ZIP size and SHA-256 from the final release assets.
## Store listing
diff --git a/test/data-safety-ui.test.js b/test/data-safety-ui.test.js
index 1f3580d..5d27d36 100644
--- a/test/data-safety-ui.test.js
+++ b/test/data-safety-ui.test.js
@@ -119,7 +119,9 @@ test("multi-ZIP import uses one wide preflight with blocking failures and one ba
assert.doesNotMatch(dialog, /library-package-import-remove/);
assert.match(dialog, /class="data-safety-actions import-actions"/);
assert.doesNotMatch(dialog, /type="checkbox"/);
- assert.match(flow, /Promise\.all\(batch\.items\.map/);
+ assert.match(flow, /for \(const item of batch\.items\)/);
+ assert.match(flow, /await inspectLibraryPackageBatchItem\(batch, item\)/);
+ assert.match(flow, /batch\.controller\.signal/);
assert.match(flow, /PREVIEW_LIBRARY_IMPORT_BATCH/);
assert.match(flow, /APPLY_LIBRARY_IMPORT_BATCH/);
assert.match(flow, /assertStorageCapacity\(estimate, batch\.plannedBytes\)/);
diff --git a/test/fixtures/transfer-media/README.md b/test/fixtures/transfer-media/README.md
new file mode 100644
index 0000000..314b10b
--- /dev/null
+++ b/test/fixtures/transfer-media/README.md
@@ -0,0 +1,8 @@
+# Image transfer fixtures
+
+Synthetic single-frame solid-color images generated with FFmpeg. They contain no user material.
+
+- `original.gif`: blue, 2 by 2 pixels.
+- `original.avif`: red, 64 by 64 pixels, encoded with SVT-AV1.
+
+Used to verify native decoding and byte-preserving import and complete folder backup. Regeneration is not required to run the tests.
diff --git a/test/fixtures/transfer-media/original.avif b/test/fixtures/transfer-media/original.avif
new file mode 100644
index 0000000..64b223f
Binary files /dev/null and b/test/fixtures/transfer-media/original.avif differ
diff --git a/test/fixtures/transfer-media/original.gif b/test/fixtures/transfer-media/original.gif
new file mode 100644
index 0000000..f1eda11
Binary files /dev/null and b/test/fixtures/transfer-media/original.gif differ
diff --git a/test/folder_picker_activation_e2e.py b/test/folder_picker_activation_e2e.py
new file mode 100644
index 0000000..c0956c0
--- /dev/null
+++ b/test/folder_picker_activation_e2e.py
@@ -0,0 +1,52 @@
+"""Native Chromium gesture check; headless cancellation is not OS-folder acceptance."""
+from playwright.sync_api import expect
+from e2e_support import extension_session
+
+
+def main() -> None:
+ with extension_session("promptdirector-native-picker-") as session:
+ page = session.open_page("library.html")
+ expect(page.locator("#settings-dialog")).to_be_visible()
+ page.locator('[data-settings-tab="general"]').click()
+ page.evaluate("""() => {
+ const native = window.showDirectoryPicker.bind(window);
+ const send = chrome.runtime.sendMessage.bind(chrome.runtime);
+ const expire = async () => {
+ while (navigator.userActivation.isActive) await new Promise(r => setTimeout(r, 25));
+ };
+ chrome.runtime.sendMessage = async (...args) => {
+ if (args[0]?.type === 'GET_FOLDER_BACKUP_STATE') await expire();
+ return send(...args);
+ };
+ window.__pickerResults = [];
+ window.showDirectoryPicker = async (options) => {
+ const result = {active: navigator.userActivation.isActive};
+ try { return await native(options); }
+ catch (error) { result.error = error.name; throw error; }
+ finally { window.__pickerResults.push(result); }
+ };
+ const control = document.createElement('button');
+ control.id = 'expired-gesture-control';
+ control.textContent = 'Expired gesture control';
+ control.onclick = async () => {
+ await expire();
+ try { await window.showDirectoryPicker({mode: 'read'}); } catch {}
+ finally { console.info('promptdirector:expired-picker-completed'); }
+ };
+ document.querySelector('#settings-dialog').append(control);
+ }""")
+ page.locator("#create-folder-backup").click()
+ expect(page.locator("#data-safety-feedback")).to_contain_text("已取消备份", timeout=15000)
+ results = page.evaluate("window.__pickerResults")
+ assert results == [{"active": True, "error": "AbortError"}], results
+ # Polling page state renews automation user activation; wait for an event instead.
+ with page.expect_console_message(predicate=lambda message: message.text == "promptdirector:expired-picker-completed", timeout=15000):
+ page.locator("#expired-gesture-control").click()
+ results = page.evaluate("window.__pickerResults")
+ assert results[1] == {"active": False, "error": "SecurityError"}, results
+ assert not session.page_errors, session.page_errors
+ print("Native picker: product click passes gesture gate; expired control rejected; headless cancels without writing.")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/test/library-export-zip.test.js b/test/library-export-zip.test.js
index 599d60b..e105f7b 100644
--- a/test/library-export-zip.test.js
+++ b/test/library-export-zip.test.js
@@ -161,10 +161,18 @@ test("self-read keeps a JPEG case while the production parser drops only its bro
assert.equal(parsed.importStats.droppedAiAssignments, 1);
});
-test("export self-read uses recipient limits instead of approving an unimportable attachment", async () => {
- const libraryJson = renderLibraryJson([]);
- await assert.rejects(createVerifiedLibraryZip([
- { name: "library.json", data: libraryJson },
- { name: "attachments/oversize.pdf", data: new Blob([new Uint8Array(PORTABLE_LIBRARY_LIMITS.maxFileBytes + 1)]) }
- ], libraryJson), /导出自检失败.*单个文件超过/);
+test("export self-read accepts original attachments above the capture budget through default import", async () => {
+ const bytes = new Blob([new Uint8Array(PORTABLE_LIBRARY_LIMITS.maxFileBytes + 1)]);
+ const assetPath = "attachments/source/original.psd";
+ const libraryJson = renderLibraryJson([{
+ id: "source", title: "Original source", text: "Keep original bytes",
+ mediaAssets: [{ id: "original", kind: "attachment", storageMode: "managed", mimeType: "image/vnd.adobe.photoshop", sourceFormat: "psd", byteSize: bytes.size, capturedAt: "2026-09-07T00:00:00.000Z", assetPath }],
+ primaryMediaId: "original"
+ }]);
+ const archive = await createVerifiedLibraryZip([
+ { name: "library.json", data: libraryJson }, { name: assetPath, data: bytes }
+ ], libraryJson);
+ const files = await readZipBlob(archive);
+ const parsed = parseLibraryPackage(JSON.parse(await files.get("library.json").text()), files);
+ assert.equal(parsed.assets.get("original").size, bytes.size);
});
diff --git a/test/library-transfer.test.js b/test/library-transfer.test.js
index 112a7a4..d7460c6 100644
--- a/test/library-transfer.test.js
+++ b/test/library-transfer.test.js
@@ -139,7 +139,7 @@ test("complete-backup inspection drops one invalid descriptor and keeps the heal
test("an unexpected strict parser fault is never disguised as rescue content loss", async () => {
const source = portablePackage([portableEntry("case:healthy", "image:healthy")]);
let faultInjected = false;
- const limits = new Proxy({}, {
+ const limits = new Proxy({ maxEntries: 1 }, {
get() {
if (!faultInjected) {
faultInjected = true;
diff --git a/test/library_image_formats_e2e.py b/test/library_image_formats_e2e.py
new file mode 100644
index 0000000..b39eaaa
--- /dev/null
+++ b/test/library_image_formats_e2e.py
@@ -0,0 +1,76 @@
+"""Registered image formats must survive default import and a real filesystem backup."""
+import hashlib
+import json
+import tempfile
+import zipfile
+from pathlib import Path
+from playwright.sync_api import expect
+from e2e_support import base_entry, extension_session
+
+
+def main() -> None:
+ fixtures = Path(__file__).parent / "fixtures" / "transfer-media"
+ with tempfile.TemporaryDirectory(prefix="promptdirector-image-transfer-") as temp, extension_session("promptdirector-image-transfer-") as session:
+ setup = session.open_page("collector.html")
+ schema = setup.evaluate("async () => (await import(chrome.runtime.getURL('taxonomy.js'))).SCHEMA_VERSION")
+ session.seed_storage(setup, {"schemaVersion": schema, "entries": [base_entry("keep", "Keep", "Keep", "content:prompt:text")]})
+ entry = base_entry("formats", "Image formats", "Keep original image formats", "content:prompt:image")
+ entry["mediaAssets"] = []
+ expected = {}
+ for extension in ["gif", "avif"]:
+ data = (fixtures / f"original.{extension}").read_bytes()
+ expected[extension] = hashlib.sha256(data).hexdigest()
+ entry["mediaAssets"].append({
+ "id": extension, "kind": "image", "storageMode": "managed", "sourceFormat": extension,
+ "mimeType": f"image/{extension}", "byteSize": len(data), "assetPath": f"images/formats/original.{extension}",
+ "capturedAt": "2026-09-07T00:00:00.000Z",
+ })
+ entry["primaryMediaId"] = "gif"
+ library = setup.evaluate("async entry => (await import(chrome.runtime.getURL('lib.js'))).renderLibraryJson([entry])", entry)
+ archive_path = Path(temp) / "formats.zip"
+ with zipfile.ZipFile(archive_path, "w") as archive:
+ archive.writestr("library.json", library)
+ for asset in entry["mediaAssets"]:
+ archive.write(fixtures / f"original.{asset['sourceFormat']}", asset["assetPath"])
+ page = session.open_page("library.html", wait_until="networkidle")
+ page.locator("#open-settings").click()
+ page.locator('[data-settings-tab="general"]').click()
+ page.locator("#library-package-file").set_input_files(str(archive_path))
+ expect(page.locator("#library-package-import-confirm")).to_be_enabled()
+ expect(page.locator("#library-package-import-media-count")).to_have_text("2")
+ page.locator("#library-package-import-confirm").click()
+ expect(page.locator("#library-package-import-dialog")).to_be_hidden()
+ page.evaluate("""() => {
+ window.showDirectoryPicker = async () => {
+ if (!navigator.userActivation.isActive) throw new Error('Missing activation');
+ return navigator.storage.getDirectory();
+ };
+ }""")
+ page.locator("#create-folder-backup").click()
+ expect(page.locator("#data-safety-feedback")).to_contain_text("完整备份已完成", timeout=30000)
+ proof = page.evaluate("""async () => {
+ const root = await navigator.storage.getDirectory();
+ const {sha256Blob} = await import(chrome.runtime.getURL('blob-digest.js'));
+ for await (const directory of root.values()) {
+ if (directory.kind !== 'directory' || !directory.name.startsWith('PromptDirector-Backup-')) continue;
+ const marker = JSON.parse(await (await (await directory.getFileHandle('complete.json')).getFile()).text());
+ const library = JSON.parse(await (await (await directory.getFileHandle('library.json')).getFile()).text());
+ const entry = library.entries.find(entry => entry.id === 'formats');
+ const hashes = {};
+ for (const asset of entry.mediaAssets) {
+ const parts = asset.assetPath.split('/');
+ let parent = directory;
+ for (const name of parts.slice(0, -1)) parent = await parent.getDirectoryHandle(name);
+ const blob = await (await parent.getFileHandle(parts.at(-1))).getFile();
+ hashes[asset.sourceFormat] = await sha256Blob(blob);
+ }
+ return {hashes, mediaCount: marker.mediaCount};
+ }
+ }""")
+ assert proof == {"hashes": expected, "mediaCount": 2}, proof
+ assert not session.page_errors, session.page_errors
+ print(json.dumps({"formats": list(expected), "defaultImportAndFilesystemBackup": "passed"}))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/test/library_zip_scale_e2e.py b/test/library_zip_scale_e2e.py
new file mode 100644
index 0000000..771cfe9
--- /dev/null
+++ b/test/library_zip_scale_e2e.py
@@ -0,0 +1,105 @@
+"""Real byte transport beyond ZIP32, using synthetic inert source-file fixtures."""
+import hashlib
+import json
+import tempfile
+import zipfile
+from pathlib import Path
+
+from playwright.sync_api import expect
+from e2e_support import base_entry, extension_session, wait_for_download
+
+
+def write_archive(path: Path, library: str, asset_path: str, size: int, method: int) -> str:
+ digest = hashlib.sha256()
+ block = b"PromptDirector transport fixture\n" * (1024 * 32)
+ with zipfile.ZipFile(path, "w", compression=method, allowZip64=True) as archive:
+ archive.writestr("library.json", library)
+ with archive.open(asset_path, "w", force_zip64=True) as target:
+ remaining = size
+ while remaining:
+ chunk = block[:min(remaining, len(block))]
+ target.write(chunk)
+ digest.update(chunk)
+ remaining -= len(chunk)
+ return digest.hexdigest()
+
+
+def main() -> None:
+ with tempfile.TemporaryDirectory(prefix="promptdirector-zip64-") as temporary, extension_session("promptdirector-zip-scale-") as session:
+ root = Path(temporary)
+ setup = session.open_page("collector.html")
+ sentinel = base_entry("local-sentinel", "Keep local case", "Original local text", "content:prompt:text")
+ schema = setup.evaluate("async () => (await import(chrome.runtime.getURL('taxonomy.js'))).SCHEMA_VERSION")
+ session.seed_storage(setup, {"schemaVersion": schema, "entries": [sentinel]})
+ fixtures = [
+ ("zip64-original", (1 << 32) + 1, zipfile.ZIP_STORED),
+ ("deflated-original", 129 * 1024 * 1024, zipfile.ZIP_DEFLATED),
+ ]
+ sources = []
+ for identity, size, method in fixtures:
+ entry = base_entry(identity, identity, "Synthetic byte transport; not a playable design file", "content:prompt:text")
+ asset_path = f"attachments/{identity}/original.psd"
+ entry["mediaAssets"] = [{
+ "id": identity + "-asset", "kind": "attachment", "storageMode": "managed",
+ "mimeType": "image/vnd.adobe.photoshop", "sourceFormat": "psd", "byteSize": size,
+ "capturedAt": "2026-09-07T00:00:00.000Z", "assetPath": asset_path,
+ }]
+ entry["primaryMediaId"] = identity + "-asset"
+ library_json = setup.evaluate("async entry => (await import(chrome.runtime.getURL('lib.js'))).renderLibraryJson([entry])", entry)
+ path = root / f"{identity}.zip"
+ digest = write_archive(path, library_json, asset_path, size, method)
+ sources.append({"path": path, "id": identity, "size": size, "sha256": digest})
+ print("Generated real ZIP32-boundary and DEFLATE fixtures", flush=True)
+ page = session.open_page("library.html", wait_until="networkidle")
+ page.locator("#open-settings").click()
+ page.locator('[data-settings-tab="general"]').click()
+ page.locator("#library-package-file").set_input_files([str(item["path"]) for item in sources])
+ confirm = page.locator("#library-package-import-confirm")
+ expect(confirm).to_be_enabled(timeout=300000)
+ # Cancellation after actual preflight must leave the existing library untouched.
+ page.locator("#library-package-import-cancel").click()
+ state = page.evaluate("async () => chrome.runtime.sendMessage({type: 'GET_STATE'})")
+ assert [entry["id"] for entry in state["entries"]] == [sentinel["id"]]
+ page.locator("#library-package-file").set_input_files([str(item["path"]) for item in sources])
+ expect(confirm).to_be_enabled(timeout=300000)
+ confirm.click()
+ expect(page.locator("#library-package-import-dialog")).to_be_hidden(timeout=300000)
+ for source in sources:
+ result = page.evaluate("""async id => {
+ const state = await chrome.runtime.sendMessage({type: 'GET_STATE'});
+ const entry = state.entries.find(entry => entry.id === id);
+ const {getMediaBlob} = await import(chrome.runtime.getURL('media-store.js'));
+ const {sha256Blob} = await import(chrome.runtime.getURL('blob-digest.js'));
+ const blob = await getMediaBlob(entry.mediaAssets[0].id);
+ return {size: blob.size, sha256: await sha256Blob(blob)};
+ }""", source["id"])
+ assert result == {"size": source["size"], "sha256": source["sha256"]}, result
+ print("Default multi-package import and stored byte hashes passed", flush=True)
+ page.locator("#settings-close").click()
+ page.locator("#select-cases").click()
+ for source in sources:
+ page.locator(f'.case-card[data-entry-id="{source["id"]}"]').click()
+ page.locator("#share-export").click()
+ page.locator("#share-dialog-export").click()
+ expect(page.locator("#feedback")).to_contain_text("分享包已导出", timeout=300000)
+ download, _ = wait_for_download(page, timeout_seconds=300)
+ # Move this test-created download under the temporary directory for cleanup.
+ exported = root / "roundtrip.zip"
+ download.rename(exported)
+ with zipfile.ZipFile(exported) as archive:
+ library = json.loads(archive.read("library.json"))
+ for source in sources:
+ entry = next(entry for entry in library["entries"] if entry["id"] == source["id"])
+ asset = entry["mediaAssets"][0]
+ assert archive.getinfo(asset["assetPath"]).file_size == source["size"]
+ digest = hashlib.sha256()
+ with archive.open(asset["assetPath"]) as stream:
+ while chunk := stream.read(1024 * 1024):
+ digest.update(chunk)
+ assert digest.hexdigest() == source["sha256"]
+ assert not session.page_errors, session.page_errors
+ print(json.dumps({"status": "passed", "actualBytes": sum(item["size"] for item in sources), "zip64": True, "independentPythonReadback": True}), flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/test/local-extension-lab.test.js b/test/local-extension-lab.test.js
index 941a46e..317de76 100644
--- a/test/local-extension-lab.test.js
+++ b/test/local-extension-lab.test.js
@@ -5,6 +5,7 @@ import {
buildLabReceipt,
hashRuntimeFiles,
parseE2eOutput,
+ REQUIRED_DATA_CONTINUITY_SCRIPTS,
REQUIRED_MODEL_CHAIN_SCRIPTS
} from "../tools/local-extension-lab.mjs";
@@ -29,7 +30,7 @@ test("local extension lab parses every browser scenario instead of stopping at t
});
test("local extension receipt requires model analysis and Composer generation chains", () => {
- const modelChainOutput = REQUIRED_MODEL_CHAIN_SCRIPTS
+ const modelChainOutput = [...REQUIRED_MODEL_CHAIN_SCRIPTS, ...REQUIRED_DATA_CONTINUITY_SCRIPTS]
.map((script) => `[PASS] ${script} (1.0s)`)
.join("\n");
const receipt = buildLabReceipt({
@@ -58,6 +59,7 @@ test("local extension receipt requires model analysis and Composer generation ch
});
assert.equal(receipt.status, "passed");
assert.equal(receipt.checks.modelChainPassed, true);
+ assert.equal(receipt.checks.dataContinuityPassed, true);
assert.equal(receipt.proofBoundary.localPackagedChromeForTesting, true);
assert.equal(receipt.proofBoundary.userInstalledChrome, false);
assert.equal(receipt.proofBoundary.liveProvider, false);
@@ -80,4 +82,6 @@ test("local extension receipt fails when a required model-chain scenario disappe
});
assert.equal(receipt.status, "failed");
assert.ok(receipt.checks.modelChain.missing.includes("composer_video_generation_e2e.py"));
+ assert.equal(receipt.checks.dataContinuityPassed, false);
+ assert.ok(receipt.checks.dataContinuity.missing.includes("library_zip_scale_e2e.py"));
});
diff --git a/test/media-archive-ui.test.js b/test/media-archive-ui.test.js
index ee66607..8134587 100644
--- a/test/media-archive-ui.test.js
+++ b/test/media-archive-ui.test.js
@@ -69,9 +69,9 @@ test("project share preflight uses the same compound-complete member selection a
test("share package import keeps archive and expanded-entry limits independent", () => {
const imported = js.slice(js.indexOf("async function importSharedLibraryPackage"), js.indexOf("function backupMediaPaths"));
- assert.match(imported, /const limits = \{ \.\.\.PORTABLE_LIBRARY_LIMITS \}/);
+ assert.match(imported, /const limits = \{ \.\.\.LIBRARY_TRANSFER_LIMITS \}/);
assert.doesNotMatch(imported, /max(?:Archive|File|Image|Video)Bytes:\s*file\.size/);
- assert.match(imported, /readZipBlob\(file, limits\)/);
+ assert.match(imported, /openZipBlob\(file, limits\)/);
assert.match(imported, /sourceType:\s*LIBRARY_TRANSFER_SOURCES\.SHARE_PACKAGE/);
assert.match(imported, /limits/);
assert.match(imported, /validateImage:\s*validateImportedImage/);
@@ -79,7 +79,7 @@ test("share package import keeps archive and expanded-entry limits independent",
test("folder restore derives its media budget before strict or rescue inspection", () => {
const restore = js.slice(js.indexOf("async function restoreCompleteFolderBackup"), js.indexOf("async function importSharedLibraryPackage"));
- assert.match(restore, /largestMediaBytes = Math\.max\(1, \.\.\.backupMediaSizes\)/);
+ assert.match(restore, /largestMediaBytes = backupMediaSizes\.reduce/);
assert.match(restore, /maxFileBytes: largestMediaBytes/);
assert.match(restore, /maxImageBytes: largestMediaBytes/);
assert.match(restore, /maxVideoBytes: largestMediaBytes/);
diff --git a/test/media-ui.test.js b/test/media-ui.test.js
index 6676ddb..e4abf0e 100644
--- a/test/media-ui.test.js
+++ b/test/media-ui.test.js
@@ -121,11 +121,12 @@ test("fixed-ratio gallery covers crop mismatched source images inside the card",
assert.match(css, /\.case-image-wrap-fixed \.case-shot\s*\{[^}]*height:\s*100%;[^}]*object-fit:\s*cover/);
});
-test("folder backup preflights every resource before choosing a folder and writes its marker last", () => {
+test("folder backup opens the picker before asynchronous preparation and creates files only after approval", () => {
const backup = source.slice(source.indexOf("async function createCompleteFolderBackup"), source.indexOf("async function restoreCompleteFolderBackup"));
const pickerCall = backup.indexOf("const parent = await window.showDirectoryPicker");
- assert.ok(backup.indexOf("GET_FOLDER_BACKUP_STATE") < pickerCall);
- assert.ok(backup.indexOf("inspectLibraryTransfer({") < pickerCall);
+ assert.ok(pickerCall < backup.indexOf("GET_FOLDER_BACKUP_STATE"));
+ assert.ok(pickerCall < backup.indexOf("inspectLibraryTransfer({"));
+ assert.ok(backup.indexOf("confirmAppAction({") < backup.indexOf("parent.getDirectoryHandle"));
assert.match(backup, /plannedFiles\.set\(assetPath, blob\)/);
assert.match(backup, /portableManagedBackupAsset\(asset, blob, assetPath, await sha256Blob\(blob\), portableFormat\)/);
assert.match(backup, /materializeEntry\(item\.snapshot, `trash-entry-/);
diff --git a/test/release_upgrade_e2e.py b/test/release_upgrade_e2e.py
index 97f83ce..fc9984c 100644
--- a/test/release_upgrade_e2e.py
+++ b/test/release_upgrade_e2e.py
@@ -26,7 +26,7 @@ def open_extension(playwright: Playwright, profile: str, extension_dir: Path):
return context, worker.url.split("/")[2]
-def seed_previous_release(playwright: Playwright, profile: str) -> tuple[str, str]:
+def seed_previous_release(playwright: Playwright, profile: str) -> tuple[str, str, list[dict]]:
context, extension_id = open_extension(playwright, profile, PREVIOUS_EXTENSION_DIR)
errors: list[str] = []
try:
@@ -50,6 +50,22 @@ def seed_previous_release(playwright: Playwright, profile: str) -> tuple[str, st
...structuredClone(active), id: 'upgrade:trashed', title: '回收站案例',
customLabels: ['回收站标签']
};
+ const media = await import(chrome.runtime.getURL('media-store.js'));
+ const png = Uint8Array.from(atob('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII='), c => c.charCodeAt(0));
+ const assets = [
+ ['upgrade:image', new Blob([png], {type: 'image/png'})],
+ ['upgrade:trashed-source', new Blob(['original source kept in Trash'], {type: 'image/vnd.adobe.photoshop'})]
+ ];
+ active.mediaAssets = [{id: assets[0][0], kind: 'image', storageMode: 'managed', mimeType: 'image/png', sourceFormat: 'png', width: 1, height: 1, byteSize: assets[0][1].size}];
+ active.primaryMediaId = assets[0][0];
+ trashed.mediaAssets = [{id: assets[1][0], kind: 'attachment', storageMode: 'managed', mimeType: 'image/vnd.adobe.photoshop', sourceFormat: 'psd', byteSize: assets[1][1].size}];
+ trashed.primaryMediaId = assets[1][0];
+ const mediaProof = [];
+ for (const [id, blob] of assets) {
+ await media.saveMediaBlob(id, blob, {checkCapacity: false});
+ const saved = await media.getMediaBlob(id);
+ mediaProof.push({id, bytes: Array.from(new Uint8Array(await saved.arrayBuffer()))});
+ }
await chrome.storage.local.clear();
await chrome.storage.local.set({
schemaVersion: taxonomy.SCHEMA_VERSION,
@@ -80,6 +96,7 @@ def seed_previous_release(playwright: Playwright, profile: str) -> tuple[str, st
});
const state = await chrome.runtime.sendMessage({type: 'GET_STATE'});
return {
+ mediaProof,
version: chrome.runtime.getManifest().version,
activeIds: state.entries.map((entry) => entry.id),
trashIds: state.trashState.items.map((item) => item.targetId),
@@ -91,12 +108,12 @@ def seed_previous_release(playwright: Playwright, profile: str) -> tuple[str, st
assert result["trashIds"] == ["upgrade:trashed"], result
assert result["sessionIds"] == ["upgrade:composer"], result
assert not errors, errors
- return result["version"], extension_id
+ return result["version"], extension_id, result["mediaProof"]
finally:
context.close()
-def verify_current_package(playwright: Playwright, profile: str, previous_version: str, expected_id: str) -> None:
+def verify_current_package(playwright: Playwright, profile: str, previous_version: str, expected_id: str, expected_media: list[dict]) -> None:
context, extension_id = open_extension(playwright, profile, CURRENT_EXTENSION_DIR)
errors: list[str] = []
try:
@@ -107,7 +124,16 @@ def verify_current_package(playwright: Playwright, profile: str, previous_versio
result = page.evaluate(
"""async () => {
const state = await chrome.runtime.sendMessage({type: 'GET_STATE'});
+ const {getMediaBlob} = await import(chrome.runtime.getURL('media-store.js'));
+ const mediaProof = [];
+ for (const entry of [state.entries[0], state.trashState.items[0].snapshot]) {
+ const id = entry.primaryMediaId;
+ if (entry.mediaAssets[0]?.id !== id) throw new Error('Upgrade lost the primary media relationship');
+ const blob = await getMediaBlob(id);
+ mediaProof.push({id, bytes: Array.from(new Uint8Array(await blob.arrayBuffer()))});
+ }
return {
+ mediaProof,
version: chrome.runtime.getManifest().version,
schemaVersion: state.schemaVersion,
active: state.entries.map((entry) => ({
@@ -124,6 +150,7 @@ def verify_current_package(playwright: Playwright, profile: str, previous_versio
};
}"""
)
+ assert result["mediaProof"] == expected_media, result["mediaProof"]
assert version_tuple(result["version"]) >= version_tuple(previous_version), result
assert result["active"] == [{
"id": "upgrade:active", "title": "升级保留的案例",
@@ -151,8 +178,8 @@ def main() -> None:
assert CURRENT_EXTENSION_DIR.joinpath("manifest.json").exists(), CURRENT_EXTENSION_DIR
with tempfile.TemporaryDirectory(prefix="promptdirector-release-profile-") as profile:
with sync_playwright() as playwright:
- previous_version, extension_id = seed_previous_release(playwright, profile)
- verify_current_package(playwright, profile, previous_version, extension_id)
+ previous_version, extension_id, media = seed_previous_release(playwright, profile)
+ verify_current_package(playwright, profile, previous_version, extension_id, media)
print(f"升级资料保持通过:{PREVIOUS_RELEASE_TAG} → 当前最终包")
diff --git a/test/run_e2e.py b/test/run_e2e.py
index fc86c61..f9f51c5 100644
--- a/test/run_e2e.py
+++ b/test/run_e2e.py
@@ -43,6 +43,9 @@ SCRIPTS = [
"composer_temp_references_e2e.py",
"composer_session_layout_e2e.py",
"sharing_and_data_safety_e2e.py",
+ "folder_picker_activation_e2e.py",
+ "library_zip_scale_e2e.py",
+ "library_image_formats_e2e.py",
"manual_sync_e2e.py",
"region_and_smart_picker_e2e.py",
"smart_visual_picker_e2e.py",
diff --git a/test/sharing_and_data_safety_e2e.py b/test/sharing_and_data_safety_e2e.py
index 8762d4f..1563ea0 100644
--- a/test/sharing_and_data_safety_e2e.py
+++ b/test/sharing_and_data_safety_e2e.py
@@ -276,7 +276,10 @@ def main() -> None:
window.__installBackupRoot = () => {
window.__backupRoot = new MemoryDirectoryHandle('chosen-parent');
Object.defineProperty(window, 'showDirectoryPicker', {
- value: async () => window.__backupRoot,
+ value: async () => {
+ if (!navigator.userActivation.isActive) throw new DOMException('Must be handling a user gesture', 'SecurityError');
+ return window.__backupRoot;
+ },
configurable: true
});
};
diff --git a/test/transfer-scale.test.js b/test/transfer-scale.test.js
new file mode 100644
index 0000000..664cdaf
--- /dev/null
+++ b/test/transfer-scale.test.js
@@ -0,0 +1,81 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import { execFileSync } from "node:child_process";
+import { createZipBlob, openZipBlob, readZipBlob } from "../zip.js";
+import { renderLibraryJson } from "../lib.js";
+import { parseLibraryPackage } from "../library-package.js";
+import { sha256Blob } from "../blob-digest.js";
+import { resolveZip64Extra, zipSafeInteger } from "../zip64.js";
+import { verifiedDocumentBlob } from "../bounded-media.js";
+
+test("more than 5000 cases and projects survive default transfer parsing", () => {
+ const entries = Array.from({ length: 5001 }, (_, index) => ({
+ id: `case-${index}`, title: `Case ${index}`, text: `Original ${index}`, savedAt: "2026-09-07T00:00:00.000Z"
+ }));
+ const data = JSON.parse(renderLibraryJson(entries));
+ data.organizerState = { collections: entries.map((entry, index) => ({
+ id: `project-${index}`, name: `Project ${index}`, parentId: null, order: index, entryIds: [entry.id]
+ })) };
+ const parsed = parseLibraryPackage(data);
+ assert.equal(parsed.entries.length, entries.length);
+ assert.equal(parsed.organizerState.collections.length, entries.length);
+ assert.equal(parsed.entries.at(-1).text, entries.at(-1).text);
+ assert.deepEqual(parsed.organizerState.collections.at(-1).entryIds, [entries.at(-1).id]);
+});
+
+test("ZIP64 directory counts roundtrip beyond both the former file quota and ZIP32 count", async () => {
+ const files = Array.from({ length: 65536 }, (_, index) => ({ name: `files/${index}.txt`, data: "" }));
+ const archive = await createZipBlob(files);
+ const reader = await openZipBlob(archive);
+ assert.equal(reader.names.length, files.length);
+ const selected = await reader.read([files[0].name, files.at(-1).name]);
+ assert.equal(selected.size, 2);
+});
+
+test("Python ZIP64 local headers and compressed payloads are readable without relaxed limits", async () => {
+ const bytes = execFileSync("python3", ["-c", `
+import io,sys,zipfile
+b=io.BytesIO()
+with zipfile.ZipFile(b,'w',compression=zipfile.ZIP_DEFLATED) as z:
+ with z.open('attachments/original.psd','w',force_zip64=True) as f: f.write(b'original'*1024)
+sys.stdout.buffer.write(b.getvalue())
+`]);
+ const files = await readZipBlob(new Blob([bytes]));
+ assert.equal(await files.get("attachments/original.psd").text(), "original".repeat(1024));
+});
+
+test("ZIP64 rejects missing sizes and integers that cannot be represented exactly", () => {
+ assert.throws(() => resolveZip64Extra(new Uint8Array(), { size: 0xffffffff }), /缺失/);
+ assert.throws(() => zipSafeInteger(BigInt(Number.MAX_SAFE_INTEGER) + 1n), /可精确处理范围/);
+});
+
+test("canceling ZIP reading stops before materializing assets", async () => {
+ const archive = await createZipBlob([{ name: "library.json", data: "{}" }]);
+ const controller = new AbortController();
+ controller.abort();
+ await assert.rejects(readZipBlob(archive, {}, { signal: controller.signal }), { name: "AbortError" });
+});
+
+test("streaming file hashes preserve standard SHA256 without whole-file arrayBuffer", async () => {
+ const bytes = new Uint8Array(1024 * 1024 + 73).fill(19);
+ const blob = new Blob([bytes]);
+ blob.arrayBuffer = () => { throw new Error("whole-file allocation"); };
+ assert.equal(await sha256Blob(blob), createHash("sha256").update(bytes).digest("hex"));
+ assert.equal(await sha256Blob(new Blob()), createHash("sha256").digest("hex"));
+});
+
+test("local backup document validation streams text and keeps original PDF bytes", async () => {
+ const markdown = new Blob(["跨段文字\n".repeat(30000)], { type: "text/markdown" });
+ markdown.arrayBuffer = () => { throw new Error("whole document allocation"); };
+ const verified = await verifiedDocumentBlob(markdown, "text/markdown", markdown.size);
+ assert.equal(await sha256Blob(verified), await sha256Blob(markdown));
+ const pdf = new Blob(["%PDF-1.7\n", new Uint8Array(1024 * 1024)], { type: "application/pdf" });
+ pdf.arrayBuffer = () => { throw new Error("whole document allocation"); };
+ assert.equal((await verifiedDocumentBlob(pdf, "application/pdf", pdf.size)).size, pdf.size);
+ for (const invalid of [
+ new Blob([markdown, new Uint8Array([0])]),
+ new Blob([markdown, new Uint8Array([0xe4, 0xb8])])
+ ]) await assert.rejects(verifiedDocumentBlob(invalid, "text/markdown", invalid.size), /有效文档/);
+ await assert.rejects(verifiedDocumentBlob(new Blob(["not PDF"]), "application/pdf", 10), /有效文档/);
+});
diff --git a/test/zip.test.js b/test/zip.test.js
index aa9b979..b697e18 100644
--- a/test/zip.test.js
+++ b/test/zip.test.js
@@ -14,7 +14,8 @@ test("ZIP roundtrip preserves original image bytes above the document limit", as
assert.deepEqual(new Uint8Array(await files.get("images/original.png").arrayBuffer()), bytes);
await assert.rejects(() => readZipBlob(archive, { maxImageBytes: bytes.length - 1 }), /单个文件超过/);
const document = await createZipBlob([{ name: "documents/notes.md", data: new Blob([bytes]) }]);
- await assert.rejects(() => readZipBlob(document), /单个文件超过/);
+ assert.equal((await readZipBlob(document)).get("documents/notes.md").size, bytes.length);
+ await assert.rejects(() => readZipBlob(document, { maxFileBytes: bytes.length - 1 }), /单个文件超过/);
});
test("createZipBlob produces a UTF-8 ZIP containing markdown and image paths", async () => {
diff --git a/tools/hash-runtime.mjs b/tools/hash-runtime.mjs
new file mode 100644
index 0000000..6846075
--- /dev/null
+++ b/tools/hash-runtime.mjs
@@ -0,0 +1,16 @@
+import { mkdir, readFile, writeFile } from "node:fs/promises";
+import { fileURLToPath } from "node:url";
+
+const source = new URL("../node_modules/@noble/hashes/", import.meta.url);
+const target = new URL("../vendor/noble-hashes/", import.meta.url);
+const check = process.argv.includes("--check");
+const files = ["sha2.js", "_md.js", "_u64.js", "utils.js", "LICENSE"];
+if (!check) await mkdir(target, { recursive: true });
+for (const name of files) {
+ const bytes = await readFile(new URL(name, source));
+ const path = new URL(name, target);
+ if (check) {
+ if (!bytes.equals(await readFile(path))) throw new Error(`哈希运行时与锁定依赖不一致:${fileURLToPath(path)}`);
+ } else await writeFile(path, bytes);
+}
+process.stdout.write(check ? "哈希运行时与锁定依赖一致\n" : "已同步流式哈希运行时\n");
diff --git a/tools/local-extension-lab.mjs b/tools/local-extension-lab.mjs
index 12d02c1..8671a08 100644
--- a/tools/local-extension-lab.mjs
+++ b/tools/local-extension-lab.mjs
@@ -19,6 +19,15 @@ export const REQUIRED_MODEL_CHAIN_SCRIPTS = [
"composer_video_dialogue_e2e.py"
];
+export const REQUIRED_DATA_CONTINUITY_SCRIPTS = [
+ "sharing_and_data_safety_e2e.py",
+ "historical_zip_salvage_e2e.py",
+ "folder_picker_activation_e2e.py",
+ "library_zip_scale_e2e.py",
+ "library_image_formats_e2e.py",
+ "manual_sync_e2e.py"
+];
+
export function parseE2eOutput(value = "") {
const scripts = [];
for (const match of String(value).matchAll(/^\[(PASS|FAIL)\]\s+([^\s]+)\s+\(([^)]+)\)$/gmu)) {
@@ -71,11 +80,15 @@ export function buildLabReceipt({
const missingModelChainScripts = REQUIRED_MODEL_CHAIN_SCRIPTS.filter((script) => !scriptStatus.has(script));
const failedModelChainScripts = REQUIRED_MODEL_CHAIN_SCRIPTS.filter((script) => scriptStatus.get(script) === "failed");
const modelChainPassed = missingModelChainScripts.length === 0 && failedModelChainScripts.length === 0;
+ const missingDataScripts = REQUIRED_DATA_CONTINUITY_SCRIPTS.filter((script) => !scriptStatus.has(script));
+ const failedDataScripts = REQUIRED_DATA_CONTINUITY_SCRIPTS.filter((script) => scriptStatus.get(script) === "failed");
+ const dataContinuityPassed = missingDataScripts.length === 0 && failedDataScripts.length === 0;
const passed = preflightFactsValid
&& e2e.code === 0
&& e2eSummary.failed === 0
&& e2eSummary.total > 0
- && modelChainPassed;
+ && modelChainPassed
+ && dataContinuityPassed;
return {
schema: "promptdirector-local-extension-lab",
version: 1,
@@ -100,6 +113,12 @@ export function buildLabReceipt({
checks: {
packagedRuntimeLoaded: preflightFactsValid,
fullBrowserSuitePassed: e2e.code === 0 && e2eSummary.failed === 0 && e2eSummary.total > 0,
+ dataContinuityPassed,
+ dataContinuity: {
+ required: REQUIRED_DATA_CONTINUITY_SCRIPTS,
+ missing: missingDataScripts,
+ failed: failedDataScripts
+ },
modelChainPassed,
modelChain: {
required: REQUIRED_MODEL_CHAIN_SCRIPTS,
diff --git a/tools/package-extension.mjs b/tools/package-extension.mjs
index fdbd926..91393db 100644
--- a/tools/package-extension.mjs
+++ b/tools/package-extension.mjs
@@ -44,6 +44,10 @@ for (const path of await runtimeFiles(join(projectRoot, "vendor", "document-inge
files.push(await packageFile(path));
}
+for (const path of await runtimeFiles(join(projectRoot, "vendor", "noble-hashes"))) {
+ files.push(await packageFile(path));
+}
+
for (const locale of await readdir(join(projectRoot, "_locales"), { withFileTypes: true })) {
if (locale.isDirectory()) {
files.push(await packageFile(join(projectRoot, "_locales", locale.name, "messages.json")));
diff --git a/vendor/noble-hashes/LICENSE b/vendor/noble-hashes/LICENSE
new file mode 100644
index 0000000..9297a04
--- /dev/null
+++ b/vendor/noble-hashes/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2022 Paul Miller (https://paulmillr.com)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the “Software”), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
\ No newline at end of file
diff --git a/vendor/noble-hashes/_md.js b/vendor/noble-hashes/_md.js
new file mode 100644
index 0000000..13049ff
--- /dev/null
+++ b/vendor/noble-hashes/_md.js
@@ -0,0 +1,209 @@
+/**
+ * Internal Merkle-Damgard hash utils.
+ * @module
+ */
+import { setU64FromNum } from "./_u64.js";
+import { abytes, aexists, aoutput, createView } from "./utils.js";
+/**
+ * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.
+ * Returns bits from `b` when `a` is set, otherwise from `c`.
+ * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never
+ * set the same bit.
+ * @param a - selector word
+ * @param b - word chosen when selector bit is set
+ * @param c - word chosen when selector bit is clear
+ * @returns Mixed 32-bit word.
+ * @example
+ * Combine three words with the shared 32-bit choice primitive.
+ * ```ts
+ * Chi(0xffffffff, 0x12345678, 0x87654321);
+ * ```
+ */
+export function Chi(a, b, c) {
+ return (a & b) ^ (~a & c);
+}
+/**
+ * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.
+ * Returns bits shared by at least two inputs.
+ * @param a - first input word
+ * @param b - second input word
+ * @param c - third input word
+ * @returns Mixed 32-bit word.
+ * @example
+ * Combine three words with the shared 32-bit majority primitive.
+ * ```ts
+ * Maj(0xffffffff, 0x12345678, 0x87654321);
+ * ```
+ */
+export function Maj(a, b, c) {
+ return (a & b) ^ (a & c) ^ (b & c);
+}
+/**
+ * Merkle-Damgard hash construction base class.
+ * Could be used to create MD5, RIPEMD, SHA1, SHA2.
+ * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit
+ * strings with partial-byte tails.
+ * @param blockLen - internal block size in bytes
+ * @param outputLen - digest size in bytes
+ * @param padOffset - trailing length field size in bytes
+ * @param isLE - whether length and state words are encoded in little-endian
+ * @example
+ * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.
+ * ```ts
+ * import { _SHA1 } from '@noble/hashes/legacy.js';
+ * const hash = new _SHA1();
+ * hash.update(new Uint8Array([97, 98, 99]));
+ * hash.digest();
+ * ```
+ */
+export class HashMD {
+ blockLen;
+ outputLen;
+ canXOF = false;
+ padOffset;
+ isLE;
+ // For partial updates less than block size
+ buffer;
+ view;
+ finished = false;
+ length = 0;
+ pos = 0;
+ destroyed = false;
+ constructor(blockLen, outputLen, padOffset, isLE) {
+ this.blockLen = blockLen;
+ this.outputLen = outputLen;
+ this.padOffset = padOffset;
+ this.isLE = isLE;
+ this.buffer = new Uint8Array(blockLen);
+ this.view = createView(this.buffer);
+ }
+ update(data) {
+ aexists(this);
+ abytes(data);
+ const { view, buffer, blockLen } = this;
+ const len = data.length;
+ let processed = false;
+ for (let pos = 0; pos < len;) {
+ const take = Math.min(blockLen - this.pos, len - pos);
+ // Fast path only when there is no buffered partial block: `take === blockLen` implies
+ // `this.pos === 0`, so we can process full blocks directly from the input view.
+ if (take === blockLen) {
+ const dataView = createView(data);
+ for (; blockLen <= len - pos; pos += blockLen)
+ this.process(dataView, pos);
+ processed = true;
+ continue;
+ }
+ // When the whole input is buffered in one go (common for short messages), passing `data`
+ // directly avoids allocating a subarray view.
+ buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
+ this.pos += take;
+ pos += take;
+ if (this.pos === blockLen) {
+ this.process(view, 0);
+ this.pos = 0;
+ processed = true;
+ }
+ }
+ this.length += data.length;
+ // Shared schedule buffers only pick up input-derived words inside process(); if everything
+ // was buffered without processing, there is nothing to zero.
+ if (processed)
+ this.roundClean();
+ return this;
+ }
+ digestInto(out) {
+ aexists(this);
+ aoutput(out, this);
+ this.finished = true;
+ // Padding
+ // We can avoid allocation of buffer for padding completely if it
+ // was previously not allocated here. But it won't change performance.
+ const { buffer, view, blockLen, isLE } = this;
+ let { pos } = this;
+ // append the bit '1' to the message, then zero-pad the rest of the block
+ buffer[pos++] = 0b10000000;
+ buffer.fill(0, pos);
+ // we have less than padOffset left in buffer, so we cannot put length in
+ // current block, need process it and pad again
+ if (this.padOffset > blockLen - pos) {
+ this.process(view, 0);
+ buffer.fill(0);
+ }
+ // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from
+ // the padding fill above, and JS will overflow before user input can make that half non-zero.
+ // So we only need to write the low 64 bits here (`length * 8` only scales the exponent of an
+ // integer below 2**53, so the split inside the helper stays exact).
+ setU64FromNum(view, blockLen - 8, this.length * 8, isLE);
+ this.process(view, 0);
+ // The final block above is processed outside update(), so the shared message-schedule
+ // buffers (e.g. SHA256_W) would otherwise retain input-derived words after digest().
+ this.roundClean();
+ // digest() passes our own `buffer` as `out`; reuse its cached view instead of allocating one.
+ const oview = out === buffer ? view : createView(out);
+ const len = this.outputLen;
+ // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT
+ const outLen = len / 4;
+ const state = this.get();
+ // Subclass-misconfiguration invariant: outputLen must be 32-bit aligned and fit the state.
+ if (len % 4 || outLen > state.length)
+ throw new Error('invalid outputLen');
+ for (let i = 0; i < outLen; i++)
+ oview.setUint32(4 * i, state[i], isLE);
+ }
+ digest() {
+ const { buffer, outputLen } = this;
+ this.digestInto(buffer);
+ // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return
+ // fresh bytes to the caller.
+ const res = buffer.slice(0, outputLen);
+ this.destroy();
+ return res;
+ }
+ _cloneIntoMeta(to) {
+ const { buffer, length, finished, destroyed, pos } = this;
+ to.destroyed = destroyed;
+ to.finished = finished;
+ to.length = length;
+ to.pos = pos;
+ // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and
+ // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.
+ if (pos)
+ to.buffer.set(buffer); // Avoid a hot modulo guard.
+ return to;
+ }
+ clone() {
+ return this._cloneInto();
+ }
+}
+/**
+ * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
+ * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
+ */
+/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the
+ * square roots of the first eight prime numbers. Exported as a shared table; callers must treat
+ * it as read-only because constructors copy words from it by index. */
+export const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
+]);
+/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must
+ * treat it as read-only because constructors copy words from it by index. */
+export const SHA224_IV = /* @__PURE__ */ Uint32Array.from([
+ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,
+]);
+/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen
+ * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth
+ * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only
+ * because constructors copy halves from it by index. */
+export const SHA384_IV = /* @__PURE__ */ Uint32Array.from([
+ 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,
+ 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,
+]);
+/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen
+ * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first
+ * eight prime numbers. Exported as a shared table; callers must treat it as read-only because
+ * constructors copy halves from it by index. */
+export const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
+ 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,
+ 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,
+]);
diff --git a/vendor/noble-hashes/_u64.js b/vendor/noble-hashes/_u64.js
new file mode 100644
index 0000000..a57c31c
--- /dev/null
+++ b/vendor/noble-hashes/_u64.js
@@ -0,0 +1,77 @@
+const U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();
+const _32n = /* @__PURE__ */ BigInt(32);
+// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high
+// }` to match little-endian word order rather than the property names.
+function fromBig(n, le = false) {
+ if (le)
+ return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
+ return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
+}
+// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array
+// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.
+function split(lst, le = false) {
+ const len = lst.length;
+ let Ah = new Uint32Array(len);
+ let Al = new Uint32Array(len);
+ for (let i = 0; i < len; i++) {
+ const { h, l } = fromBig(lst[i], le);
+ [Ah[i], Al[i]] = [h, l];
+ }
+ return [Ah, Al];
+}
+// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS
+// bitwise results back to uint32 first, and little-endian callers must swap.
+const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
+// Split a JS number into u32 halves without a BigInt allocation. Exact only for integers
+// `0 <= n < 2**53`; callers use it on byte / bit counters, which JS length math caps far below
+// that (an ArrayBuffer cannot exceed 2**53 - 1 bytes).
+const fromNumH = (n) => (n / 2 ** 32) | 0;
+const fromNumL = (n) => n >>> 0;
+// Drop-in replacement for `view.setBigUint64(byteOffset, BigInt(n), isLE)` without the per-call
+// BigInt allocation. Same `n < 2**53` precondition as `fromNumH`/`fromNumL`.
+function setU64FromNum(view, byteOffset, n, isLE) {
+ const h = fromNumH(n);
+ const l = fromNumL(n);
+ view.setUint32(byteOffset, isLE ? l : h, isLE);
+ view.setUint32(byteOffset + 4, isLE ? h : l, isLE);
+}
+// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.
+const shrSH = (h, _l, s) => h >>> s;
+// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.
+const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
+// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.
+const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
+// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.
+const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
+// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.
+const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
+// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.
+const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
+// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.
+const rotr32H = (_h, l) => l;
+// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.
+const rotr32L = (h, _l) => h;
+// 64-bit left rotates (rotl*) are not defined here: sha3.ts, their only consumer, keeps
+// local copies so V8 inlines them into keccakP.
+// Add two split 64-bit words and return the split `{ h, l }` sum.
+// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out
+// of the low sum and instead use division.
+function add(Ah, Al, Bh, Bl) {
+ const l = (Al >>> 0) + (Bl >>> 0);
+ return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
+}
+// Addition with more than 2 elements
+// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.
+const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
+// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.
+const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
+// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.
+const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
+// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.
+const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
+// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.
+const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
+// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.
+const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
+// prettier-ignore
+export { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, fromNumH, fromNumL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, setU64FromNum, shrSH, shrSL, split, toBig };
diff --git a/vendor/noble-hashes/sha2.js b/vendor/noble-hashes/sha2.js
new file mode 100644
index 0000000..020395b
--- /dev/null
+++ b/vendor/noble-hashes/sha2.js
@@ -0,0 +1,446 @@
+/**
+ * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
+ * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
+ * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and
+ * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.
+ * @module
+ */
+import { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from "./_md.js";
+import * as u64 from "./_u64.js";
+import { clean, createHasher, oidNist, rotr } from "./utils.js";
+/**
+ * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits
+ * of the cube roots of the first 64 primes (2..311).
+ */
+// prettier-ignore
+const SHA256_K = /* @__PURE__ */ Uint32Array.from([
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
+]);
+/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */
+const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
+/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */
+class SHA2_32B extends HashMD {
+ // We cannot use array here since array allows indexing by variable
+ // which means optimizer/compiler cannot use registers.
+ // Numeric initializers matter: starting the fields as `undefined` changes
+ // V8's field representation and makes sha256 3x slower (measured).
+ A = 0;
+ B = 0;
+ C = 0;
+ D = 0;
+ E = 0;
+ F = 0;
+ G = 0;
+ H = 0;
+ constructor(outputLen, IV) {
+ super(64, outputLen, 8, false);
+ this.A = IV[0] | 0;
+ this.B = IV[1] | 0;
+ this.C = IV[2] | 0;
+ this.D = IV[3] | 0;
+ this.E = IV[4] | 0;
+ this.F = IV[5] | 0;
+ this.G = IV[6] | 0;
+ this.H = IV[7] | 0;
+ }
+ get() {
+ const { A, B, C, D, E, F, G, H } = this;
+ return [A, B, C, D, E, F, G, H];
+ }
+ // prettier-ignore
+ set(A, B, C, D, E, F, G, H) {
+ this.A = A | 0;
+ this.B = B | 0;
+ this.C = C | 0;
+ this.D = D | 0;
+ this.E = E | 0;
+ this.F = F | 0;
+ this.G = G | 0;
+ this.H = H | 0;
+ }
+ _cloneInto(to) {
+ (to ||= new this.constructor()).set(...this.get());
+ return this._cloneIntoMeta(to);
+ }
+ process(view, offset) {
+ // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
+ for (let i = 0; i < 16; i++, offset += 4)
+ SHA256_W[i] = view.getUint32(offset, false);
+ for (let i = 16; i < 64; i++) {
+ const W15 = SHA256_W[i - 15];
+ const W2 = SHA256_W[i - 2];
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
+ SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
+ }
+ // Compression function main loop, 64 rounds
+ let { A, B, C, D, E, F, G, H } = this;
+ for (let i = 0; i < 64; i++) {
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
+ const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
+ const T2 = (sigma0 + Maj(A, B, C)) | 0;
+ H = G;
+ G = F;
+ F = E;
+ E = (D + T1) | 0;
+ D = C;
+ C = B;
+ B = A;
+ A = (T1 + T2) | 0;
+ }
+ // Add the compressed chunk to the current hash value
+ A = (A + this.A) | 0;
+ B = (B + this.B) | 0;
+ C = (C + this.C) | 0;
+ D = (D + this.D) | 0;
+ E = (E + this.E) | 0;
+ F = (F + this.F) | 0;
+ G = (G + this.G) | 0;
+ H = (H + this.H) | 0;
+ this.set(A, B, C, D, E, F, G, H);
+ }
+ roundClean() {
+ clean(SHA256_W);
+ }
+ destroy() {
+ // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves
+ // update()/digest() callable on reused instances.
+ this.destroyed = true;
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
+ clean(this.buffer);
+ }
+}
+/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */
+export class _SHA256 extends SHA2_32B {
+ constructor() {
+ super(32, SHA256_IV);
+ }
+}
+/** Internal SHA-224 hash class grounded in RFC 6234 §6.2 and §8.5. */
+export class _SHA224 extends SHA2_32B {
+ constructor() {
+ super(28, SHA224_IV);
+ }
+}
+// SHA2-512 is slower than sha256 in js because u64 operations are slow.
+// SHA-384 / SHA-512 round constants from RFC 6234 §5.2:
+// 80 full 64-bit words split into high/low halves.
+// prettier-ignore
+const K512 = /* @__PURE__ */ (() => u64.split([
+ '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
+ '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
+ '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
+ '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
+ '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
+ '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
+ '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
+ '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
+ '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
+ '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
+ '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
+ '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
+ '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
+ '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
+ '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
+ '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
+ '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
+ '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
+ '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
+ '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
+].map(n => BigInt(n))))();
+const SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
+const SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
+// Reusable high-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.
+const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
+// Reusable low-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.
+const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
+/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */
+class SHA2_64B extends HashMD {
+ // We cannot use array here since array allows indexing by variable
+ // which means optimizer/compiler cannot use registers.
+ // h -- high 32 bits, l -- low 32 bits
+ // Numeric initializers matter: starting the fields as `undefined` changes
+ // V8's field representation and slows hashing down (measured on sha256).
+ Ah = 0;
+ Al = 0;
+ Bh = 0;
+ Bl = 0;
+ Ch = 0;
+ Cl = 0;
+ Dh = 0;
+ Dl = 0;
+ Eh = 0;
+ El = 0;
+ Fh = 0;
+ Fl = 0;
+ Gh = 0;
+ Gl = 0;
+ Hh = 0;
+ Hl = 0;
+ constructor(outputLen, IV) {
+ super(128, outputLen, 16, false);
+ this.Ah = IV[0] | 0;
+ this.Al = IV[1] | 0;
+ this.Bh = IV[2] | 0;
+ this.Bl = IV[3] | 0;
+ this.Ch = IV[4] | 0;
+ this.Cl = IV[5] | 0;
+ this.Dh = IV[6] | 0;
+ this.Dl = IV[7] | 0;
+ this.Eh = IV[8] | 0;
+ this.El = IV[9] | 0;
+ this.Fh = IV[10] | 0;
+ this.Fl = IV[11] | 0;
+ this.Gh = IV[12] | 0;
+ this.Gl = IV[13] | 0;
+ this.Hh = IV[14] | 0;
+ this.Hl = IV[15] | 0;
+ }
+ // prettier-ignore
+ get() {
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
+ }
+ // prettier-ignore
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
+ this.Ah = Ah | 0;
+ this.Al = Al | 0;
+ this.Bh = Bh | 0;
+ this.Bl = Bl | 0;
+ this.Ch = Ch | 0;
+ this.Cl = Cl | 0;
+ this.Dh = Dh | 0;
+ this.Dl = Dl | 0;
+ this.Eh = Eh | 0;
+ this.El = El | 0;
+ this.Fh = Fh | 0;
+ this.Fl = Fl | 0;
+ this.Gh = Gh | 0;
+ this.Gl = Gl | 0;
+ this.Hh = Hh | 0;
+ this.Hl = Hl | 0;
+ }
+ _cloneInto(to) {
+ (to ||= new this.constructor()).set(...this.get());
+ return this._cloneIntoMeta(to);
+ }
+ process(view, offset) {
+ // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
+ for (let i = 0; i < 16; i++, offset += 4) {
+ SHA512_W_H[i] = view.getUint32(offset);
+ SHA512_W_L[i] = view.getUint32((offset += 4));
+ }
+ for (let i = 16; i < 80; i++) {
+ // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
+ const W15h = SHA512_W_H[i - 15] | 0;
+ const W15l = SHA512_W_L[i - 15] | 0;
+ const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);
+ const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);
+ // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
+ const W2h = SHA512_W_H[i - 2] | 0;
+ const W2l = SHA512_W_L[i - 2] | 0;
+ const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);
+ const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);
+ // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_W[i - 16];
+ const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
+ const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
+ SHA512_W_H[i] = SUMh | 0;
+ SHA512_W_L[i] = SUMl | 0;
+ }
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
+ // Compression function main loop, 80 rounds
+ for (let i = 0; i < 80; i++) {
+ // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
+ const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);
+ const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);
+ //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
+ const CHIh = (Eh & Fh) ^ (~Eh & Gh);
+ const CHIl = (El & Fl) ^ (~El & Gl);
+ // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
+ // prettier-ignore
+ const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
+ const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
+ const T1l = T1ll | 0;
+ // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
+ const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);
+ const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);
+ const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
+ const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
+ Hh = Gh | 0;
+ Hl = Gl | 0;
+ Gh = Fh | 0;
+ Gl = Fl | 0;
+ Fh = Eh | 0;
+ Fl = El | 0;
+ ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
+ Dh = Ch | 0;
+ Dl = Cl | 0;
+ Ch = Bh | 0;
+ Cl = Bl | 0;
+ Bh = Ah | 0;
+ Bl = Al | 0;
+ const All = u64.add3L(T1l, sigma0l, MAJl);
+ Ah = u64.add3H(All, T1h, sigma0h, MAJh);
+ Al = All | 0;
+ }
+ // Add the compressed chunk to the current hash value
+ ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
+ ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
+ ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
+ ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
+ ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
+ ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
+ ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
+ ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
+ }
+ roundClean() {
+ clean(SHA512_W_H, SHA512_W_L);
+ }
+ destroy() {
+ // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves
+ // update()/digest() callable on reused instances.
+ this.destroyed = true;
+ clean(this.buffer);
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
+ }
+}
+/** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */
+export class _SHA512 extends SHA2_64B {
+ constructor() {
+ super(64, SHA512_IV);
+ }
+}
+/** Internal SHA-384 hash class grounded in RFC 6234 §6.3 and §6.4. */
+export class _SHA384 extends SHA2_64B {
+ constructor() {
+ super(48, SHA384_IV);
+ }
+}
+/**
+ * Truncated SHA512/256 and SHA512/224.
+ * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as "intermediary" IV of SHA512/t.
+ * Then t hashes string to produce result IV.
+ * See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.
+ * These IV literals are checked against that script rather than a dedicated
+ * local RFC section.
+ */
+/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and
+ * stored as sixteen big-endian 32-bit halves. */
+const T224_IV = /* @__PURE__ */ Uint32Array.from([
+ 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,
+ 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,
+]);
+/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and
+ * stored as sixteen big-endian 32-bit halves. */
+const T256_IV = /* @__PURE__ */ Uint32Array.from([
+ 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,
+ 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,
+]);
+/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared
+ * RFC 6234 §6.4 compression engine. */
+export class _SHA512_224 extends SHA2_64B {
+ constructor() {
+ super(28, T224_IV);
+ }
+}
+/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared
+ * RFC 6234 §6.4 compression engine. */
+export class _SHA512_256 extends SHA2_64B {
+ constructor() {
+ super(32, T256_IV);
+ }
+}
+/**
+ * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:
+ *
+ * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.
+ * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
+ * - Each sha256 hash is executing 2^18 bit operations.
+ * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.
+ * @param msg - message bytes to hash
+ * @param opts - Reserved hash options.
+ * @returns Digest bytes.
+ * @example
+ * Hash a message with SHA2-256.
+ * ```ts
+ * sha256(new Uint8Array([97, 98, 99]));
+ * ```
+ */
+export const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(),
+/* @__PURE__ */ oidNist(0x01));
+/**
+ * SHA2-224 hash function from RFC 4634.
+ * @param msg - message bytes to hash
+ * @param opts - Reserved hash options.
+ * @returns Digest bytes.
+ * @example
+ * Hash a message with SHA2-224.
+ * ```ts
+ * sha224(new Uint8Array([97, 98, 99]));
+ * ```
+ */
+export const sha224 = /* @__PURE__ */ createHasher(() => new _SHA224(),
+/* @__PURE__ */ oidNist(0x04));
+/**
+ * SHA2-512 hash function from RFC 4634.
+ * @param msg - message bytes to hash
+ * @param opts - Reserved hash options.
+ * @returns Digest bytes.
+ * @example
+ * Hash a message with SHA2-512.
+ * ```ts
+ * sha512(new Uint8Array([97, 98, 99]));
+ * ```
+ */
+export const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(),
+/* @__PURE__ */ oidNist(0x03));
+/**
+ * SHA2-384 hash function from RFC 4634.
+ * @param msg - message bytes to hash
+ * @param opts - Reserved hash options.
+ * @returns Digest bytes.
+ * @example
+ * Hash a message with SHA2-384.
+ * ```ts
+ * sha384(new Uint8Array([97, 98, 99]));
+ * ```
+ */
+export const sha384 = /* @__PURE__ */ createHasher(() => new _SHA384(),
+/* @__PURE__ */ oidNist(0x02));
+/**
+ * SHA2-512/256 "truncated" hash function, with improved resistance to length extension attacks.
+ * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.
+ * @param msg - message bytes to hash
+ * @param opts - Reserved hash options.
+ * @returns Digest bytes.
+ * @example
+ * Hash a message with SHA2-512/256.
+ * ```ts
+ * sha512_256(new Uint8Array([97, 98, 99]));
+ * ```
+ */
+export const sha512_256 = /* @__PURE__ */ createHasher(() => new _SHA512_256(),
+/* @__PURE__ */ oidNist(0x06));
+/**
+ * SHA2-512/224 "truncated" hash function, with improved resistance to length extension attacks.
+ * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.
+ * @param msg - message bytes to hash
+ * @param opts - Reserved hash options.
+ * @returns Digest bytes.
+ * @example
+ * Hash a message with SHA2-512/224.
+ * ```ts
+ * sha512_224(new Uint8Array([97, 98, 99]));
+ * ```
+ */
+export const sha512_224 = /* @__PURE__ */ createHasher(() => new _SHA512_224(),
+/* @__PURE__ */ oidNist(0x05));
diff --git a/vendor/noble-hashes/utils.js b/vendor/noble-hashes/utils.js
new file mode 100644
index 0000000..8ba8827
--- /dev/null
+++ b/vendor/noble-hashes/utils.js
@@ -0,0 +1,687 @@
+/**
+ * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
+ * @param a - value to test
+ * @returns `true` when the value is a Uint8Array-compatible view.
+ * @example
+ * Check whether a value is a Uint8Array-compatible view.
+ * ```ts
+ * isBytes(new Uint8Array([1, 2, 3]));
+ * ```
+ */
+export function isBytes(a) {
+ // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.
+ // The fallback still requires a real ArrayBuffer view, so plain
+ // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and
+ // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.
+ return (a instanceof Uint8Array ||
+ (ArrayBuffer.isView(a) &&
+ a.constructor.name === 'Uint8Array' &&
+ 'BYTES_PER_ELEMENT' in a &&
+ a.BYTES_PER_ELEMENT === 1));
+}
+// Shared error-message prefix builder. Only called on throw paths, so assert
+// success paths never pay for the string concatenation.
+const atitle = (title) => (title ? `"${title}" ` : '');
+/**
+ * Asserts something is a non-negative integer.
+ * @param n - number to validate
+ * @param title - label included in thrown errors
+ * @returns The validated number.
+ * @throws On wrong argument types. {@link TypeError}
+ * @throws On wrong argument ranges or values. {@link RangeError}
+ * @example
+ * Validate a non-negative integer option.
+ * ```ts
+ * anumber(32, 'length');
+ * ```
+ */
+export function anumber(n, title = '') {
+ if (typeof n !== 'number')
+ throw new TypeError(atitle(title) + 'expected number, got ' + typeof n);
+ if (!Number.isSafeInteger(n) || n < 0)
+ throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n);
+ return n;
+}
+/**
+ * Asserts something is a boolean.
+ * @param value - value to validate
+ * @param title - label included in thrown errors
+ * @returns The validated boolean.
+ * @throws On wrong argument types. {@link TypeError}
+ * @example
+ * Validate a boolean option.
+ * ```ts
+ * abool(true, 'enableXOF');
+ * ```
+ */
+export function abool(value, title = '') {
+ if (typeof value !== 'boolean')
+ throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);
+ return value;
+}
+/**
+ * Asserts something is Uint8Array.
+ * @param value - value to validate
+ * @param length - optional exact length constraint
+ * @param title - label included in thrown errors
+ * @returns The validated byte array.
+ * @throws On wrong argument types. {@link TypeError}
+ * @throws On wrong argument ranges or values. {@link RangeError}
+ * @example
+ * Validate that a value is a byte array.
+ * ```ts
+ * abytes(new Uint8Array([1, 2, 3]));
+ * ```
+ */
+export function abytes(value, length, title = '') {
+ // Success path first: this runs at the start of every update() / digestInto(), and the
+ // common `abytes(data)` form must not pay for length handling it does not use.
+ if (isBytes(value) && (length === undefined || value.length === length))
+ return value;
+ // Error path: recompute freely to build the exact message.
+ if (length !== undefined)
+ anumber(length, 'length');
+ const bytes = isBytes(value);
+ const ofLen = length !== undefined ? ` of length ${length}` : '';
+ const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
+ const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;
+ if (!bytes)
+ throw new TypeError(message);
+ throw new RangeError(message);
+}
+/**
+ * Copies bytes into a fresh Uint8Array.
+ * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.
+ * @param bytes - source bytes to clone
+ * @returns Freshly allocated copy of `bytes`.
+ * @throws On wrong argument types. {@link TypeError}
+ * @example
+ * Clone a byte array before mutating it.
+ * ```ts
+ * const copy = copyBytes(new Uint8Array([1, 2, 3]));
+ * ```
+ */
+export function copyBytes(bytes) {
+ // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict
+ // because callers use it at byte-validation boundaries before mutating the detached copy.
+ return Uint8Array.from(abytes(bytes));
+}
+/**
+ * Asserts something is a wrapped hash constructor.
+ * @param h - hash constructor to validate
+ * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}
+ * @throws On invalid hash metadata ranges or values. {@link RangeError}
+ * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}
+ * @example
+ * Validate a callable hash wrapper.
+ * ```ts
+ * import { ahash } from '@noble/hashes/utils.js';
+ * import { sha256 } from '@noble/hashes/sha2.js';
+ * ahash(sha256);
+ * ```
+ */
+export function ahash(h) {
+ if (typeof h !== 'function' || typeof h.create !== 'function')
+ throw new TypeError('expected hash wrapped by utils.createHasher');
+ anumber(h.outputLen);
+ anumber(h.blockLen);
+ // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass
+ // validation and can produce empty outputs instead of failing fast.
+ if (h.outputLen < 1 || h.blockLen < 1)
+ throw new Error('hash blockLen / outputLen must be >= 1');
+}
+const aobject = (value, label) => {
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
+ throw new TypeError((label === 'object' ? '' : `"${label}" `) + 'expected object, got type=' + typeof value);
+};
+const aopts = (value, label) => {
+ aobject(value, label);
+ const proto = Object.getPrototypeOf(value);
+ if (proto !== Object.prototype && proto !== null)
+ throw new TypeError(`"${label}" expected plain object`);
+ // Object.assign() treats an own "__proto__" source key as a write to the target's legacy
+ // prototype setter. Reject it before merging so inherited option values cannot be injected.
+ if (Object.hasOwn(value, '__proto__'))
+ throw new TypeError(`"${label}.__proto__" is not allowed`);
+};
+/**
+ * Asserts a hash instance has not been destroyed or finished.
+ * @param instance - hash instance to validate
+ * @param checkFinished - whether to reject finalized instances
+ * @throws If the hash instance has already been destroyed or finalized. {@link Error}
+ * @example
+ * Validate that a hash instance is still usable.
+ * ```ts
+ * import { aexists } from '@noble/hashes/utils.js';
+ * import { sha256 } from '@noble/hashes/sha2.js';
+ * const hash = sha256.create();
+ * aexists(hash);
+ * ```
+ */
+export function aexists(instance, checkFinished = true) {
+ // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their
+ // truthiness is checked - re-validating their type per call was pure hot-path overhead.
+ if (instance.destroyed)
+ throw new Error('hash was destroyed');
+ if (checkFinished && instance.finished)
+ throw new Error('digest() was already called');
+}
+/**
+ * Asserts output is a sufficiently-sized byte array.
+ * @param out - destination buffer
+ * @param instance - hash instance providing output length
+ * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.
+ * @throws On wrong argument types. {@link TypeError}
+ * @throws On wrong argument ranges or values. {@link RangeError}
+ * @example
+ * Validate a caller-provided digest buffer.
+ * ```ts
+ * import { aoutput } from '@noble/hashes/utils.js';
+ * import { sha256 } from '@noble/hashes/sha2.js';
+ * const hash = sha256.create();
+ * aoutput(new Uint8Array(hash.outputLen), hash);
+ * ```
+ */
+export function aoutput(out, instance) {
+ abytes(out, undefined, 'output');
+ // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast
+ // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.
+ const min = instance.outputLen;
+ if (!(out.length >= min)) {
+ throw new RangeError('"output" expected length >= ' + min);
+ }
+}
+/**
+ * Casts a typed array view to Uint8Array.
+ * @param arr - source typed array
+ * @returns Uint8Array view over the same buffer.
+ * @example
+ * Reinterpret a typed array as bytes.
+ * ```ts
+ * u8(new Uint32Array([1, 2]));
+ * ```
+ */
+export function u8(arr) {
+ return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
+}
+/**
+ * Casts a typed array view to Uint32Array.
+ * `arr.byteOffset` must already be 4-byte aligned or the platform
+ * Uint32Array constructor will throw.
+ * @param arr - source typed array
+ * @returns Uint32Array view over the same buffer.
+ * @example
+ * Reinterpret a byte array as 32-bit words.
+ * ```ts
+ * u32(new Uint8Array(8));
+ * ```
+ */
+export function u32(arr) {
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
+}
+/**
+ * Zeroizes typed arrays in place. Warning: JS provides no guarantees.
+ * @param arrays - arrays to overwrite with zeros
+ * @example
+ * Zeroize sensitive buffers in place.
+ * ```ts
+ * clean(new Uint8Array([1, 2, 3]));
+ * ```
+ */
+export function clean(...arrays) {
+ for (let i = 0; i < arrays.length; i++) {
+ arrays[i].fill(0);
+ }
+}
+/**
+ * Creates a DataView for byte-level manipulation.
+ * @param arr - source typed array
+ * @returns DataView over the same buffer region.
+ * @example
+ * Create a DataView over an existing buffer.
+ * ```ts
+ * createView(new Uint8Array(4));
+ * ```
+ */
+export function createView(arr) {
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
+}
+/**
+ * Rotate-right operation for uint32 values.
+ * @param word - source word
+ * @param shift - shift amount in bits
+ * @returns Rotated word.
+ * @example
+ * Rotate a 32-bit word to the right.
+ * ```ts
+ * rotr(0x12345678, 8);
+ * ```
+ */
+export function rotr(word, shift) {
+ return (word << (32 - shift)) | (word >>> shift);
+}
+/**
+ * Rotate-left operation for uint32 values.
+ * @param word - source word
+ * @param shift - shift amount in bits
+ * @returns Rotated word.
+ * @example
+ * Rotate a 32-bit word to the left.
+ * ```ts
+ * rotl(0x12345678, 8);
+ * ```
+ */
+export function rotl(word, shift) {
+ return (word << shift) | ((word >>> (32 - shift)) >>> 0);
+}
+/** Whether the current platform is little-endian. */
+export const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
+/**
+ * Byte-swap operation for uint32 values.
+ * @param word - source word
+ * @returns Word with reversed byte order.
+ * @example
+ * Reverse the byte order of a 32-bit word.
+ * ```ts
+ * byteSwap(0x11223344);
+ * ```
+ */
+export function byteSwap(word) {
+ return (((word << 24) & 0xff000000) |
+ ((word << 8) & 0xff0000) |
+ ((word >>> 8) & 0xff00) |
+ ((word >>> 24) & 0xff));
+}
+/**
+ * Conditionally byte-swaps one 32-bit word on big-endian platforms.
+ * @param n - source word
+ * @returns Original or byte-swapped word depending on platform endianness.
+ * @example
+ * Normalize a 32-bit word for host endianness.
+ * ```ts
+ * swap8IfBE(0x11223344);
+ * ```
+ */
+export const swap8IfBE = isLE
+ ? (n) => n
+ : (n) => byteSwap(n) >>> 0;
+/**
+ * Byte-swaps every word of a Uint32Array in place.
+ * @param arr - array to mutate
+ * @returns The same array after mutation; callers pass live state arrays here.
+ * @example
+ * Reverse the byte order of every word in place.
+ * ```ts
+ * byteSwap32(new Uint32Array([0x11223344]));
+ * ```
+ */
+export function byteSwap32(arr) {
+ for (let i = 0; i < arr.length; i++) {
+ arr[i] = byteSwap(arr[i]);
+ }
+ return arr;
+}
+/**
+ * Conditionally byte-swaps a Uint32Array on big-endian platforms.
+ * @param u - array to normalize for host endianness
+ * @returns Original or byte-swapped array depending on platform endianness.
+ * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.
+ * @example
+ * Normalize a word array for host endianness.
+ * ```ts
+ * swap32IfBE(new Uint32Array([0x11223344]));
+ * ```
+ */
+export const swap32IfBE = isLE
+ ? (u) => u
+ : byteSwap32;
+// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
+const hasHexBuiltin = /* @__PURE__ */ (() =>
+// @ts-ignore
+typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
+// Array where index 0xf0 (240) is mapped to string 'f0'
+const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
+/**
+ * Convert byte array to hex string.
+ * Uses the built-in function when available and assumes it matches the tested
+ * fallback semantics.
+ * @param bytes - bytes to encode
+ * @returns Lowercase hexadecimal string.
+ * @throws On wrong argument types. {@link TypeError}
+ * @example
+ * Convert bytes to lowercase hexadecimal.
+ * ```ts
+ * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'
+ * ```
+ */
+export function bytesToHex(bytes) {
+ abytes(bytes);
+ // @ts-ignore
+ if (hasHexBuiltin)
+ return bytes.toHex();
+ // pre-caching improves the speed 6x
+ let hex = '';
+ for (let i = 0; i < bytes.length; i++) {
+ hex += hexes[bytes[i]];
+ }
+ return hex;
+}
+// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined.
+// ASCII codes: '0'..'9' = 48..57, 'A'..'F' = 65..70, 'a'..'f' = 97..102.
+// prettier-ignore
+function asciiToBase16(ch) {
+ return ch >= 48 && ch <= 57 ? ch - 48 // '2' => 50-48
+ : ch >= 65 && ch <= 70 ? ch - (65 - 10) // 'B' => 66-(65-10)
+ : ch >= 97 && ch <= 102 ? ch - (97 - 10) // 'b' => 98-(97-10)
+ : undefined;
+}
+/**
+ * Convert hex string to byte array. Uses built-in function, when available.
+ * @param hex - hexadecimal string to decode
+ * @returns Decoded bytes.
+ * @throws On wrong argument types. {@link TypeError}
+ * @throws On wrong argument ranges or values. {@link RangeError}
+ * @example
+ * Decode lowercase hexadecimal into bytes.
+ * ```ts
+ * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
+ * ```
+ */
+export function hexToBytes(hex) {
+ if (typeof hex !== 'string')
+ throw new TypeError('hex string expected, got ' + typeof hex);
+ if (hasHexBuiltin) {
+ try {
+ return Uint8Array.fromHex(hex);
+ }
+ catch (error) {
+ if (error instanceof SyntaxError)
+ throw new RangeError(error.message);
+ throw error;
+ }
+ }
+ const hl = hex.length;
+ const al = hl / 2;
+ if (hl % 2)
+ throw new RangeError('hex string expected, got unpadded hex of length ' + hl);
+ const array = new Uint8Array(al);
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
+ const n1 = asciiToBase16(hex.charCodeAt(hi)); // parse first char, multiply it by 16
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); // parse second char
+ if (n1 === undefined || n2 === undefined) {
+ const char = hex[hi] + hex[hi + 1];
+ throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi);
+ }
+ array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9
+ }
+ return array;
+}
+/**
+ * Yields to the host task scheduler so timers, I/O, and rendering can make progress.
+ * Uses the Web Scheduling API when available or `setTimeout` as a cross-platform fallback.
+ * Host-task yields are much slower than microtasks (roughly 1ms with the timer fallback), so
+ * async loops should use `asyncTick >= 10` to amortize scheduling overhead to about 10% while
+ * still allowing other event-loop work to proceed.
+ * @param onReject - optional cleanup invoked only if the host yield fails
+ * @example
+ * Yield to the next scheduler tick.
+ * ```ts
+ * await nextTick();
+ * ```
+ */
+export function nextTick(onReject) {
+ const host = globalThis;
+ if (typeof host.scheduler?.yield === 'function') {
+ const promise = host.scheduler.yield();
+ // Keep the original scheduler rejection; this handler exists only for cleanup.
+ if (onReject)
+ promise.catch(onReject);
+ return promise;
+ }
+ return new Promise((resolve) => host.setTimeout(resolve, 0));
+}
+/**
+ * Returns control to the host event loop every `tick` milliseconds to avoid blocking long loops.
+ * @param iters - number of loop iterations to run
+ * @param tick - maximum time slice in milliseconds
+ * @param cb - callback executed on each iteration
+ * @param onReject - optional cleanup invoked only if a host yield fails
+ * @throws On wrong argument types. {@link TypeError}
+ * @throws On wrong argument ranges or values. {@link RangeError}
+ * @example
+ * Run a loop that periodically yields back to the event loop.
+ * ```ts
+ * await asyncLoop(2, 0, () => {});
+ * ```
+ */
+export async function asyncLoop(iters, tick, cb, onReject) {
+ anumber(iters, 'iters');
+ anumber(tick, 'tick');
+ if (typeof cb !== 'function')
+ throw new TypeError('callback must be a function');
+ // Callback is synchronous by contract; asyncLoop only yields between sync work windows.
+ let ts = Date.now();
+ for (let i = 0; i < iters; i++) {
+ cb(i);
+ // Date.now() is not monotonic, so in case if clock goes backwards we return return control too
+ const diff = Date.now() - ts;
+ if (diff >= 0 && diff < tick)
+ continue;
+ await nextTick(onReject);
+ // Track only synchronous work time; scheduler delay after yielding is outside our budget.
+ ts = Date.now();
+ }
+}
+/**
+ * Converts string to bytes using UTF8 encoding.
+ * Built-in doesn't validate input to be string: we do the check.
+ * Non-ASCII details are delegated to the platform `TextEncoder`.
+ * @param str - string to encode
+ * @returns UTF-8 encoded bytes.
+ * @throws On wrong argument types. {@link TypeError}
+ * @example
+ * Encode a string as UTF-8 bytes.
+ * ```ts
+ * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])
+ * ```
+ */
+export function utf8ToBytes(str) {
+ if (typeof str !== 'string')
+ throw new TypeError('string expected');
+ const encoded = new TextEncoder().encode(str);
+ try {
+ // Copy into the current realm for Firefox extension contexts. Callers that own the returned
+ // buffer can then wipe it independently of TextEncoder's temporary result.
+ return new Uint8Array(encoded); // https://bugzil.la/1681809
+ }
+ finally {
+ clean(encoded);
+ }
+}
+/**
+ * Helper for KDFs: consumes Uint8Array or string.
+ * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.
+ * @param data - user-provided KDF input
+ * @param errorTitle - label included in thrown errors
+ * @returns Byte representation of the input.
+ * @throws On wrong argument types. {@link TypeError}
+ * @example
+ * Normalize KDF input to bytes.
+ * ```ts
+ * kdfInputToBytes('password');
+ * ```
+ */
+export function kdfInputToBytes(data, errorTitle = '') {
+ if (typeof data === 'string')
+ return utf8ToBytes(data);
+ return abytes(data, undefined, errorTitle);
+}
+/**
+ * Copies several Uint8Arrays into one.
+ * @param arrays - arrays to concatenate
+ * @returns Concatenated byte array.
+ * @throws On wrong argument types. {@link TypeError}
+ * @example
+ * Concatenate multiple byte arrays.
+ * ```ts
+ * concatBytes(new Uint8Array([1]), new Uint8Array([2]));
+ * ```
+ */
+export function concatBytes(...arrays) {
+ let sum = 0;
+ for (let i = 0; i < arrays.length; i++) {
+ const a = arrays[i];
+ abytes(a);
+ sum += a.length;
+ }
+ const res = new Uint8Array(sum);
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
+ const a = arrays[i];
+ res.set(a, pad);
+ pad += a.length;
+ }
+ return res;
+}
+/**
+ * Validates declared required and optional field types on a plain object.
+ * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct
+ * one-line guards such as `abytes()`, `abool()`, or `anumber()` instead.
+ * @param object - object to validate
+ * @param fields - map of required field names to expected types
+ * @param optFields - map of optional field names to expected types
+ * @param title - label included in thrown errors
+ * @throws On wrong argument types. {@link TypeError}
+ * @example
+ * Validate required and optional option fields.
+ * ```ts
+ * validateObject({ N: 1024, dkLen: 32 }, { N: 'number' }, { dkLen: 'number' });
+ * ```
+ */
+export const validateObject = (object, fields = {}, optFields = {}, title = 'object') => {
+ aobject(object, title);
+ aobject(fields, 'fields');
+ aobject(optFields, 'optFields');
+ function checkField(fieldName, expectedType, isOpt) {
+ const label = title === 'object' ? `param "${String(fieldName)}"` : `"${title}.${String(fieldName)}"`;
+ // Config fields must be explicit own properties. Optional inherited values are rejected too
+ // because callers keep reading the same options object after validation.
+ const val = object[fieldName];
+ // Runtime objects such as Field instances intentionally satisfy required method slots
+ // via their shared prototype.
+ if (!Object.hasOwn(object, fieldName) &&
+ (isOpt ? val !== undefined : expectedType !== 'function')) {
+ throw new TypeError(`${label} is invalid: expected own property`);
+ }
+ if (isOpt && val === undefined)
+ return;
+ const current = typeof val;
+ if (current !== expectedType || val === null)
+ throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);
+ }
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
+ iter(fields, false);
+ iter(optFields, true);
+};
+/**
+ * Merges default options and passed options.
+ * @param defaults - base option object
+ * @param opts - user overrides
+ * @param title - label included in thrown override errors
+ * @returns Fresh merged option object with a null prototype.
+ * @throws On wrong argument types. {@link TypeError}
+ * @example
+ * Merge user overrides onto default options.
+ * ```ts
+ * checkOpts({ dkLen: 32 }, { asyncTick: 10 });
+ * ```
+ */
+export function checkOpts(defaults, opts, title = 'opts') {
+ aopts(defaults, 'defaults');
+ if (opts !== undefined)
+ aopts(opts, title);
+ // Callers read optional fields directly, so omitted values must not fall through to ambient
+ // Object.prototype pollution (for example a forged `dkLen` changing SHAKE's default output).
+ const merged = Object.assign(Object.create(null), defaults, opts);
+ return merged;
+}
+/**
+ * Creates a callable hash function from a stateful class constructor.
+ * @param hashCons - hash constructor or factory
+ * @param info - optional metadata such as DER OID
+ * @returns Frozen callable hash wrapper with `.create()`.
+ * Wrapper construction eagerly calls `hashCons(undefined)` once to read
+ * `outputLen` / `blockLen`, so constructor side effects happen at module
+ * init time.
+ * @throws On wrong argument types. {@link TypeError}
+ * @example
+ * Wrap a stateful hash constructor into a callable helper.
+ * ```ts
+ * import { createHasher } from '@noble/hashes/utils.js';
+ * import { sha256 } from '@noble/hashes/sha2.js';
+ * const wrapped = createHasher(sha256.create, { oid: sha256.oid });
+ * wrapped(new Uint8Array([1]));
+ * ```
+ */
+export function createHasher(hashCons, info = {}) {
+ if (typeof hashCons !== 'function')
+ throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons);
+ info = checkOpts({}, info, 'info');
+ const hashC = (msg, opts) => hashCons(opts)
+ .update(msg)
+ .digest();
+ const tmp = hashCons(undefined);
+ hashC.outputLen = tmp.outputLen;
+ hashC.blockLen = tmp.blockLen;
+ hashC.canXOF = tmp.canXOF;
+ hashC.create = (opts) => hashCons(opts);
+ Object.assign(hashC, info);
+ return Object.freeze(hashC);
+}
+/**
+ * Cryptographically secure PRNG backed by `crypto.getRandomValues`.
+ * @param bytesLength - number of random bytes to generate
+ * @returns Random bytes.
+ * The platform `getRandomValues()` implementation still defines any
+ * single-call length cap, and this helper rejects oversize requests
+ * with a stable library `RangeError` instead of host-specific errors.
+ * @throws On wrong argument types. {@link TypeError}
+ * @throws On wrong argument ranges or values. {@link RangeError}
+ * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}
+ * @example
+ * Generate a fresh random key or nonce.
+ * ```ts
+ * const key = randomBytes(16);
+ * ```
+ */
+export function randomBytes(bytesLength = 32) {
+ // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.
+ anumber(bytesLength, 'bytesLength');
+ const cr = typeof globalThis === 'object' ? globalThis.crypto : null;
+ if (typeof cr?.getRandomValues !== 'function')
+ throw new Error('crypto.getRandomValues must be defined');
+ // Web Cryptography API Level 2 §10.1.1:
+ // if `byteLength > 65536`, throw `QuotaExceededError`.
+ // Keep the guard explicit so callers can see the quota in code
+ // instead of discovering it by reading the spec or host errors.
+ // This wrapper surfaces the same quota as a stable library RangeError.
+ if (bytesLength > 65536)
+ throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
+ return cr.getRandomValues(new Uint8Array(bytesLength));
+}
+/**
+ * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.
+ * @param suffix - final OID byte for the selected hash.
+ * The helper accepts any byte even though only the documented NIST hash
+ * suffixes are meaningful downstream.
+ * @returns Object containing the DER-encoded OID.
+ * @example
+ * Build OID metadata for a NIST hash.
+ * ```ts
+ * oidNist(0x01);
+ * ```
+ */
+export const oidNist = (suffix) => ({
+ // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
+ // Larger suffix values would need base-128 OID encoding and a different length byte.
+ oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),
+});
diff --git a/zip.js b/zip.js
index 1677c96..bdf65a0 100644
--- a/zip.js
+++ b/zip.js
@@ -1,6 +1,8 @@
-import { formatBytes, portableLibraryLimits, portableAssetByteLimit } from "./resource-limits.js";
+import { formatBytes, libraryTransferLimits, portableAssetByteLimit } from "./resource-limits.js";
import { assetFormatForExtension } from "./asset-formats.js";
+import { ZIP32_MAX, ZIP16_MAX, zipSafeInteger, zip64Extra, resolveZip64Extra, readZip64Directory, makeZipEndRecords } from "./zip64.js";
+
const encoder = new TextEncoder();
const UTF8_FLAG = 0x0800;
const DATA_DESCRIPTOR_FLAG = 0x0008;
@@ -8,50 +10,34 @@ const STORE_METHOD = 0;
const DEFLATE_METHOD = 8;
const DOS_DATE = 0x0021;
-export async function createZipBlob(files) {
- if (!Array.isArray(files) || files.length > 0xffff) {
- throw new Error("ZIP 文件数量超出浏览器支持范围");
- }
-
- const records = [];
+export async function createZipBlob(files, options = {}) {
+ if (!Array.isArray(files)) throw new Error("ZIP 文件列表无效");
+ const localParts = [];
+ const centralParts = [];
+ const names = new Set();
let offset = 0;
for (const file of files) {
+ options.signal?.throwIfAborted();
const name = normalizeArchivePath(file?.name);
const nameBytes = encoder.encode(name);
+ if (nameBytes.length > ZIP16_MAX || names.has(name)) throw new Error("ZIP 文件路径过长或重复");
+ names.add(name);
const dataPart = archivePart(file?.data);
- ensureUint32(dataPart.size, "单个文件过大");
- const checksum = await crc32Blob(dataPart);
- const localHeader = makeLocalHeader(nameBytes, dataPart.size, checksum);
- records.push({ nameBytes, dataPart, checksum, offset });
- offset += localHeader.byteLength + nameBytes.byteLength + dataPart.size;
- ensureUint32(offset, "ZIP 文件过大");
- }
-
- const localParts = [];
- const centralParts = [];
- for (const record of records) {
- localParts.push(
- makeLocalHeader(record.nameBytes, record.dataPart.size, record.checksum),
- record.nameBytes,
- record.dataPart
- );
- centralParts.push(
- makeCentralHeader(
- record.nameBytes,
- record.dataPart.size,
- record.checksum,
- record.offset
- ),
- record.nameBytes
- );
+ const size = zipSafeInteger(dataPart.size);
+ const checksum = await crc32Blob(dataPart, options.signal);
+ const localExtra = zip64Extra(size >= ZIP32_MAX ? [size, size] : []);
+ const centralExtra = zip64Extra([
+ ...(size >= ZIP32_MAX ? [size, size] : []),
+ ...(offset >= ZIP32_MAX ? [offset] : [])
+ ]);
+ const local = makeLocalHeader(nameBytes, size, checksum, localExtra.length);
+ const central = makeCentralHeader(nameBytes, size, checksum, offset, centralExtra.length);
+ localParts.push(local, nameBytes, localExtra, dataPart);
+ centralParts.push(central, nameBytes, centralExtra);
+ offset = zipSafeInteger(offset + local.length + nameBytes.length + localExtra.length + size);
}
-
- const centralSize = centralParts.reduce((sum, part) => sum + part.byteLength, 0);
- ensureUint32(centralSize, "ZIP 目录过大");
- return new Blob(
- [...localParts, ...centralParts, makeEndRecord(records.length, centralSize, offset)],
- { type: "application/zip" }
- );
+ const centralSize = zipSafeInteger(centralParts.reduce((sum, part) => sum + part.byteLength, 0));
+ return new Blob([...localParts, ...centralParts, ...makeZipEndRecords(files.length, centralSize, offset)], { type: "application/zip" });
}
export async function readZipBlob(archive, limitsValue = {}, options = {}) {
@@ -60,7 +46,7 @@ export async function readZipBlob(archive, limitsValue = {}, options = {}) {
}
export async function openZipBlob(archive, limitsValue = {}) {
- const limits = portableLibraryLimits(limitsValue);
+ const limits = libraryTransferLimits(limitsValue);
if (!(archive instanceof Blob) || archive.size < 22) throw invalidZip();
if (archive.size > limits.maxArchiveBytes) {
throw new Error(`ZIP 超过 ${formatBytes(limits.maxArchiveBytes)} 上限`);
@@ -74,19 +60,19 @@ export async function openZipBlob(archive, limitsValue = {}) {
const disk = tailView.getUint16(relativeEndOffset + 4, true);
const directoryDisk = tailView.getUint16(relativeEndOffset + 6, true);
const diskCount = tailView.getUint16(relativeEndOffset + 8, true);
- const fileCount = tailView.getUint16(relativeEndOffset + 10, true);
- const directorySize = tailView.getUint32(relativeEndOffset + 12, true);
- const directoryOffset = tailView.getUint32(relativeEndOffset + 16, true);
+ let fileCount = tailView.getUint16(relativeEndOffset + 10, true);
+ let directorySize = tailView.getUint32(relativeEndOffset + 12, true);
+ let directoryOffset = tailView.getUint32(relativeEndOffset + 16, true);
const commentLength = tailView.getUint16(relativeEndOffset + 20, true);
- if (disk || directoryDisk || diskCount !== fileCount || endOffset + 22 + commentLength !== archive.size ||
- fileCount === 0xffff || directorySize === 0xffffffff || directoryOffset === 0xffffffff) {
- throw new Error("暂不支持分卷或 ZIP64 压缩包");
- }
- if (fileCount > limits.maxFileCount) {
- throw new Error(`ZIP 文件数量超过 ${limits.maxFileCount} 个上限`);
+ if (disk || directoryDisk || diskCount !== fileCount) throw new Error("暂不支持分卷 ZIP");
+ if (endOffset + 22 + commentLength !== archive.size) throw invalidZip();
+ let directoryEnd = endOffset;
+ if (fileCount === ZIP16_MAX || directorySize === ZIP32_MAX || directoryOffset === ZIP32_MAX) {
+ ({ fileCount, directorySize, directoryOffset, directoryEnd } = await readZip64Directory(archive, endOffset));
}
- if (directoryOffset + directorySize !== endOffset) throw invalidZip();
- const directoryBytes = await readBlobBytes(archive, directoryOffset, endOffset);
+ if (fileCount > limits.maxFileCount) throw new Error(`ZIP 文件数量超过 ${limits.maxFileCount} 个上限`);
+ if (zipSafeInteger(directoryOffset + directorySize) !== directoryEnd || fileCount > directorySize / 46) throw invalidZip();
+ const directoryBytes = await readBlobBytes(archive, directoryOffset, directoryEnd);
const view = dataView(directoryBytes);
const records = [];
@@ -98,17 +84,22 @@ export async function openZipBlob(archive, limitsValue = {}) {
const flags = view.getUint16(cursor + 8, true);
const method = view.getUint16(cursor + 10, true);
const checksum = view.getUint32(cursor + 16, true);
- const compressedSize = view.getUint32(cursor + 20, true);
- const size = view.getUint32(cursor + 24, true);
+ let compressedSize = view.getUint32(cursor + 20, true);
+ let size = view.getUint32(cursor + 24, true);
const nameLength = view.getUint16(cursor + 28, true);
const extraLength = view.getUint16(cursor + 30, true);
const entryCommentLength = view.getUint16(cursor + 32, true);
- const localOffset = view.getUint32(cursor + 42, true);
+ let localOffset = view.getUint32(cursor + 42, true);
if (flags & 0x0001) throw new Error("不支持加密 ZIP");
if (![STORE_METHOD, DEFLATE_METHOD].includes(method)) throw new Error("ZIP 使用了浏览器不支持的压缩方式");
- if (method === STORE_METHOD && compressedSize !== size) throw invalidZip();
const nameEnd = cursor + 46 + nameLength;
if (nameEnd + extraLength + entryCommentLength > directoryBytes.byteLength) throw invalidZip();
+ let disk = view.getUint16(cursor + 34, true);
+ ({ size, compressedSize, localOffset, disk } = resolveZip64Extra(
+ directoryBytes.subarray(nameEnd, nameEnd + extraLength), { size, compressedSize, localOffset, disk }
+ ));
+ if (disk) throw new Error("暂不支持分卷 ZIP");
+ if (method === STORE_METHOD && compressedSize !== size) throw invalidZip();
if (!(flags & UTF8_FLAG) && directoryBytes.subarray(cursor + 46, nameEnd).some((byte) => byte > 0x7f)) {
throw new Error("ZIP 文件名不是可安全识别的 UTF-8 或 ASCII 编码");
}
@@ -124,13 +115,13 @@ export async function openZipBlob(archive, limitsValue = {}) {
const name = normalizeArchivePath(decodedName);
if (name !== decodedName || names.has(name)) throw new Error("ZIP 内包含不安全或重复的文件路径");
const format = assetFormatForExtension(name.split(".").at(-1));
- const fileLimit = portableAssetByteLimit(format?.kind, limitsValue);
+ const fileLimit = portableAssetByteLimit(format?.kind, { ...limits, ...limitsValue });
if (size > fileLimit) {
throw new Error(`ZIP 单个文件超过 ${formatBytes(fileLimit)} 上限`);
}
if (localOffset + 30 > directoryOffset) throw invalidZip();
- declaredBytes += size;
+ declaredBytes = zipSafeInteger(declaredBytes + size);
if (declaredBytes > limits.maxArchiveBytes) throw new Error("ZIP 解压内容超过安全上限");
names.add(name);
records.push({ name, flags, method, checksum, compressedSize, size, localOffset });
@@ -139,6 +130,7 @@ export async function openZipBlob(archive, limitsValue = {}) {
if (cursor !== directoryBytes.byteLength) throw invalidZip();
return {
names: Object.freeze([...names]),
+ expandedBytes: declaredBytes,
async read(selectedNames = null, options = {}) {
const requested = selectedNames == null
? null
@@ -153,6 +145,7 @@ export async function openZipBlob(archive, limitsValue = {}) {
const files = new Map();
let extractedBytes = 0;
for (let index = 0; index < targets.length; index += 1) {
+ options.signal?.throwIfAborted();
const record = targets[index];
const { dataOffset, dataEnd } = await resolveLocalRecord(archive, record, directoryOffset);
const compressed = archive.slice(dataOffset, dataEnd);
@@ -160,9 +153,9 @@ export async function openZipBlob(archive, limitsValue = {}) {
let actualChecksum;
if (record.method === STORE_METHOD) {
data = compressed.slice(0, compressed.size, mimeTypeForPath(record.name));
- actualChecksum = await crc32Blob(data);
+ actualChecksum = await crc32Blob(data, options.signal);
} else {
- const inflated = await inflateRaw(compressed, record.size, record.name);
+ const inflated = await inflateRaw(compressed, record.size, record.name, options.signal);
data = inflated.blob.slice(0, inflated.blob.size, mimeTypeForPath(record.name));
actualChecksum = inflated.checksum;
}
@@ -187,16 +180,19 @@ async function resolveLocalRecord(archive, record, directoryOffset) {
const localFlags = view.getUint16(6, true);
const localMethod = view.getUint16(8, true);
const localChecksum = view.getUint32(14, true);
- const localCompressedSize = view.getUint32(18, true);
- const localSize = view.getUint32(22, true);
+ let localCompressedSize = view.getUint32(18, true);
+ let localSize = view.getUint32(22, true);
const localNameLength = view.getUint16(26, true);
const localExtraLength = view.getUint16(28, true);
const localNameEnd = record.localOffset + 30 + localNameLength;
const dataOffset = localNameEnd + localExtraLength;
- const dataEnd = dataOffset + record.compressedSize;
+ const dataEnd = zipSafeInteger(dataOffset + record.compressedSize);
if (localNameEnd > directoryOffset || dataEnd > directoryOffset) throw invalidZip();
const localNameBytes = await readBlobBytes(archive, record.localOffset + 30, localNameEnd);
const localName = new TextDecoder("utf-8", { fatal: true }).decode(localNameBytes);
+ ({ size: localSize, compressedSize: localCompressedSize } = resolveZip64Extra(
+ await readBlobBytes(archive, localNameEnd, dataOffset), { size: localSize, compressedSize: localCompressedSize }
+ ));
const descriptor = Boolean(record.flags & DATA_DESCRIPTOR_FLAG);
if (localFlags !== record.flags || localMethod !== record.method || localName !== record.name) throw invalidZip();
if (!descriptor && (localChecksum !== record.checksum || localCompressedSize !== record.compressedSize || localSize !== record.size)) {
@@ -209,39 +205,28 @@ async function resolveLocalRecord(archive, record, directoryOffset) {
return { dataOffset, dataEnd };
}
-async function inflateRaw(compressedBlob, expectedSize, name) {
+async function inflateRaw(compressedBlob, expectedSize, name, signal) {
if (typeof DecompressionStream !== "function") throw new Error("当前浏览器不支持读取压缩 ZIP");
- let reader;
- try {
- const stream = compressedBlob.stream().pipeThrough(new DecompressionStream("deflate-raw"));
- reader = stream.getReader();
- } catch {
- throw new Error(`ZIP 内的文件无法解压:${name}`);
- }
-
- const chunks = [];
let total = 0;
let checksum = 0xffffffff;
try {
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
- total += value.byteLength;
- if (total > expectedSize) {
- await reader.cancel().catch(() => undefined);
- throw new Error(`ZIP 解压内容超过声明大小:${name}`);
- }
- chunks.push(value);
- checksum = crc32Update(checksum, value);
- }
+ // A browser-managed Blob sink avoids retaining all decompressed Uint8Arrays in JS.
+ const checked = compressedBlob.stream().pipeThrough(new DecompressionStream("deflate-raw"))
+ .pipeThrough(new TransformStream({
+ transform(value, controller) {
+ signal?.throwIfAborted();
+ total += value.byteLength;
+ if (total > expectedSize) throw new Error(`ZIP 解压内容超过声明大小:${name}`);
+ checksum = crc32Update(checksum, value);
+ controller.enqueue(value);
+ }
+ }), { signal });
+ const blob = await new Response(checked).blob();
+ return { blob, checksum: (checksum ^ 0xffffffff) >>> 0 };
} catch (error) {
- if (total > expectedSize) throw error;
- throw new Error(`ZIP 内的文件无法解压:${name}`);
- } finally {
- reader.releaseLock();
+ if (signal?.aborted || total > expectedSize) throw error;
+ throw new Error(`ZIP 内的文件无法解压:${name}`, { cause: error });
}
-
- return { blob: new Blob(chunks), checksum: (checksum ^ 0xffffffff) >>> 0 };
}
async function readBlobBytes(blob, start, end) {
@@ -252,11 +237,12 @@ function dataView(bytes) {
return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
}
-async function crc32Blob(blob) {
+async function crc32Blob(blob, signal) {
const reader = blob.stream().getReader();
let checksum = 0xffffffff;
try {
while (true) {
+ signal?.throwIfAborted();
const { done, value } = await reader.read();
if (done) break;
checksum = crc32Update(checksum, value);
@@ -267,48 +253,39 @@ async function crc32Blob(blob) {
return (checksum ^ 0xffffffff) >>> 0;
}
-function makeLocalHeader(name, size, checksum) {
+function makeLocalHeader(name, size, checksum, extraLength) {
const bytes = new Uint8Array(30);
const view = new DataView(bytes.buffer);
view.setUint32(0, 0x04034b50, true);
- view.setUint16(4, 20, true);
+ view.setUint16(4, extraLength ? 45 : 20, true);
view.setUint16(6, UTF8_FLAG, true);
view.setUint16(8, STORE_METHOD, true);
view.setUint16(10, 0, true);
view.setUint16(12, DOS_DATE, true);
view.setUint32(14, checksum, true);
- view.setUint32(18, size, true);
- view.setUint32(22, size, true);
+ view.setUint32(18, Math.min(size, ZIP32_MAX), true);
+ view.setUint32(22, Math.min(size, ZIP32_MAX), true);
view.setUint16(26, name.byteLength, true);
+ view.setUint16(28, extraLength, true);
return bytes;
}
-function makeCentralHeader(name, size, checksum, offset) {
+function makeCentralHeader(name, size, checksum, offset, extraLength) {
const bytes = new Uint8Array(46);
const view = new DataView(bytes.buffer);
view.setUint32(0, 0x02014b50, true);
- view.setUint16(4, 20, true);
- view.setUint16(6, 20, true);
+ view.setUint16(4, extraLength ? 45 : 20, true);
+ view.setUint16(6, extraLength ? 45 : 20, true);
view.setUint16(8, UTF8_FLAG, true);
view.setUint16(10, STORE_METHOD, true);
view.setUint16(12, 0, true);
view.setUint16(14, DOS_DATE, true);
view.setUint32(16, checksum, true);
- view.setUint32(20, size, true);
- view.setUint32(24, size, true);
+ view.setUint32(20, Math.min(size, ZIP32_MAX), true);
+ view.setUint32(24, Math.min(size, ZIP32_MAX), true);
view.setUint16(28, name.byteLength, true);
- view.setUint32(42, offset, true);
- return bytes;
-}
-
-function makeEndRecord(count, centralSize, centralOffset) {
- const bytes = new Uint8Array(22);
- const view = new DataView(bytes.buffer);
- view.setUint32(0, 0x06054b50, true);
- view.setUint16(8, count, true);
- view.setUint16(10, count, true);
- view.setUint32(12, centralSize, true);
- view.setUint32(16, centralOffset, true);
+ view.setUint32(42, Math.min(offset, ZIP32_MAX), true);
+ view.setUint16(30, extraLength, true);
return bytes;
}
@@ -352,12 +329,6 @@ function mimeTypeForPath(path) {
return assetFormatForExtension(extension)?.mimeTypes?.[0] || "application/octet-stream";
}
-function ensureUint32(value, message) {
- if (!Number.isSafeInteger(value) || value < 0 || value > 0xffffffff) {
- throw new Error(message);
- }
-}
-
function crc32Update(initial, bytes) {
let checksum = initial;
for (let index = 0; index < bytes.length; index += 1) {
diff --git a/zip64.js b/zip64.js
new file mode 100644
index 0000000..acc81b6
--- /dev/null
+++ b/zip64.js
@@ -0,0 +1,96 @@
+// PKWARE APPNOTE: ZIP64 extended information and end-of-directory records.
+export const ZIP32_MAX = 0xffffffff;
+export const ZIP16_MAX = 0xffff;
+
+export function zipSafeInteger(value) {
+ const number = Number(value);
+ if (!Number.isSafeInteger(number) || number < 0) throw new Error("ZIP 数值超出可精确处理范围");
+ return number;
+}
+
+export function zip64Extra(values) {
+ if (!values.length) return new Uint8Array();
+ const bytes = new Uint8Array(4 + values.length * 8);
+ const view = new DataView(bytes.buffer);
+ view.setUint16(0, 1, true);
+ view.setUint16(2, values.length * 8, true);
+ values.forEach((value, index) => view.setBigUint64(4 + index * 8, BigInt(zipSafeInteger(value)), true));
+ return bytes;
+}
+
+export function resolveZip64Extra(bytes, fields) {
+ const needed = Object.entries(fields).filter(([key, value]) => value === (key === "disk" ? ZIP16_MAX : ZIP32_MAX));
+ if (!needed.length) return fields;
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ for (let offset = 0; offset + 4 <= bytes.length;) {
+ const id = view.getUint16(offset, true);
+ const length = view.getUint16(offset + 2, true);
+ const end = offset + 4 + length;
+ if (end > bytes.length) throw new Error("ZIP 扩展字段已损坏");
+ if (id === 1) {
+ let cursor = offset + 4;
+ const resolved = { ...fields };
+ for (const [key] of needed) {
+ const width = key === "disk" ? 4 : 8;
+ if (cursor + width > end) throw new Error("ZIP64 扩展字段不完整");
+ resolved[key] = zipSafeInteger(width === 4 ? view.getUint32(cursor, true) : view.getBigUint64(cursor, true));
+ cursor += width;
+ }
+ return resolved;
+ }
+ offset = end;
+ }
+ throw new Error("ZIP64 扩展字段缺失");
+}
+
+export async function readZip64Directory(archive, endOffset) {
+ if (endOffset < 20) throw new Error("ZIP64 目录定位记录缺失");
+ const locator = new DataView(await archive.slice(endOffset - 20, endOffset).arrayBuffer());
+ if (locator.getUint32(0, true) !== 0x07064b50) throw new Error("ZIP64 目录定位记录缺失");
+ if (locator.getUint32(4, true) || locator.getUint32(16, true) !== 1) throw new Error("暂不支持分卷 ZIP");
+ const recordOffset = zipSafeInteger(locator.getBigUint64(8, true));
+ if (recordOffset + 56 > endOffset - 20) throw new Error("ZIP64 目录记录已损坏");
+ const view = new DataView(await archive.slice(recordOffset, recordOffset + 56).arrayBuffer());
+ if (view.getUint32(0, true) !== 0x06064b50 ||
+ recordOffset + 12 + zipSafeInteger(view.getBigUint64(4, true)) !== endOffset - 20) {
+ throw new Error("ZIP64 目录记录已损坏");
+ }
+ const fileCount = zipSafeInteger(view.getBigUint64(32, true));
+ if (view.getUint32(16, true) || view.getUint32(20, true) ||
+ zipSafeInteger(view.getBigUint64(24, true)) !== fileCount) throw new Error("暂不支持分卷 ZIP");
+ return {
+ fileCount,
+ directorySize: zipSafeInteger(view.getBigUint64(40, true)),
+ directoryOffset: zipSafeInteger(view.getBigUint64(48, true)),
+ directoryEnd: recordOffset
+ };
+}
+
+export function makeZipEndRecords(count, size, offset) {
+ [count, size, offset].forEach(zipSafeInteger);
+ const zip64 = count >= ZIP16_MAX || size >= ZIP32_MAX || offset >= ZIP32_MAX;
+ const end = new Uint8Array(22);
+ const view = new DataView(end.buffer);
+ view.setUint32(0, 0x06054b50, true);
+ view.setUint16(8, Math.min(count, ZIP16_MAX), true);
+ view.setUint16(10, Math.min(count, ZIP16_MAX), true);
+ view.setUint32(12, Math.min(size, ZIP32_MAX), true);
+ view.setUint32(16, Math.min(offset, ZIP32_MAX), true);
+ if (!zip64) return [end];
+ const record = new Uint8Array(56);
+ const r = new DataView(record.buffer);
+ r.setUint32(0, 0x06064b50, true);
+ r.setBigUint64(4, 44n, true);
+ r.setUint16(12, 45, true);
+ r.setUint16(14, 45, true);
+ r.setBigUint64(24, BigInt(count), true);
+ r.setBigUint64(32, BigInt(count), true);
+ r.setBigUint64(40, BigInt(size), true);
+ r.setBigUint64(48, BigInt(offset), true);
+ const locator = new Uint8Array(20);
+ const l = new DataView(locator.buffer);
+ l.setUint32(0, 0x07064b50, true);
+ l.setBigUint64(8, BigInt(zipSafeInteger(offset + size)), true);
+ l.setUint32(16, 1, true);
+ return [record, locator, end];
+}