dsh-builtin-browser 1.0.3 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -1
- package/README.en.md +89 -0
- package/browser-extension/constants.mjs +20 -0
- package/browser-extension/controller.mjs +293 -0
- package/browser-extension/locales.mjs +15 -0
- package/browser-extension/manifest.json +12 -0
- package/browser-extension/options.html +14 -0
- package/browser-extension/options.mjs +9 -0
- package/browser-extension/permission-guard.mjs +13 -0
- package/browser-extension/worker.mjs +74 -0
- package/desktop-bridge/desktop-identity.json +10 -2
- package/desktop-bridge/install.mjs +28 -2
- package/docs/issue-replies-2026-11-28.md +141 -0
- package/dsh-host-patch/apply.mjs +1 -1
- package/dsh-host-patch/rc3.json +4 -4
- package/dsh-host-patch/rc5.json +4 -4
- package/dsh-host-patch/v023-alpha2.json +2 -2
- package/lib/browser-electron/bridge-status.js +24 -1
- package/lib/browser-electron/desktop-identity.js +47 -8
- package/lib/client.js +2 -1
- package/native-host/install.mjs +5 -0
- package/package.json +20 -2
- package/scripts/build-client.mjs +305 -0
- package/scripts/build.mjs +69 -0
- package/scripts/bundle-host.mjs +28 -0
- package/scripts/fix-exports.mjs +40 -0
- package/scripts/install-electron.mjs +101 -0
- package/scripts/pack.mjs +99 -0
- package/scripts/publish-manifest.mjs +56 -0
- package/scripts/verify-exports.mjs +58 -0
- package/scripts/verify-preview-sdk.mjs +93 -0
- package/skills/dsh-builtin-browser/SKILL.md +98 -0
- package/skills/dsh-builtin-browser/references/batch.md +68 -0
- package/skills/dsh-builtin-browser/references/deliver.md +31 -0
- package/skills/dsh-builtin-browser/references/locate.md +11 -0
- package/skills/dsh-builtin-browser/references/recover.md +11 -0
- package/skills/dsh-builtin-browser/references/verify.md +13 -0
- package/skills/dsh-debug-host/SKILL.md +56 -0
- package/skills/dsh-debug-self/SKILL.md +50 -0
- package/src/bridge-compatibility.ts +39 -0
- package/src/browser/anti-bot.ts +251 -0
- package/src/browser/deep-dom.ts +40 -0
- package/src/browser/handles.ts +89 -0
- package/src/browser/runtime.ts +578 -0
- package/src/browser/takeover-target.ts +45 -0
- package/src/browser/types.ts +870 -0
- package/src/browser-electron/authenticated-route.ts +109 -0
- package/src/browser-electron/automatic-maintenance.ts +736 -0
- package/src/browser-electron/bridge-auto.ts +159 -0
- package/src/browser-electron/bridge-connection.ts +386 -0
- package/src/browser-electron/bridge-endpoint.ts +129 -0
- package/src/browser-electron/bridge-install.ts +290 -0
- package/src/browser-electron/bridge-maintenance.ts +189 -0
- package/src/browser-electron/bridge-status.ts +412 -0
- package/src/browser-electron/desktop-bridge-host.ts +253 -0
- package/src/browser-electron/desktop-identity.ts +400 -0
- package/src/browser-electron/desktop-shell.ts +100 -0
- package/src/browser-electron/document-readiness.ts +45 -0
- package/src/browser-electron/electron-provision.ts +347 -0
- package/src/browser-electron/entry.ts +1378 -0
- package/src/browser-electron/ephemeral-profile.ts +189 -0
- package/src/browser-electron/extension-browser.ts +230 -0
- package/src/browser-electron/extension-setup.ts +67 -0
- package/src/browser-electron/file-write.ts +31 -0
- package/src/browser-electron/foreground-watch.ts +142 -0
- package/src/browser-electron/guest-cookie-jar.ts +177 -0
- package/src/browser-electron/guest-cookie-store.ts +59 -0
- package/src/browser-electron/guest-css-runtime.ts +76 -0
- package/src/browser-electron/guest-css.ts +68 -0
- package/src/browser-electron/guest-route.ts +716 -0
- package/src/browser-electron/guest-runtime.ts +408 -0
- package/src/browser-electron/guest-storage-runtime.ts +54 -0
- package/src/browser-electron/guest-storage.ts +120 -0
- package/src/browser-electron/history-store.ts +224 -0
- package/src/browser-electron/host-main.ts +1385 -0
- package/src/browser-electron/host-patch-maintenance.ts +121 -0
- package/src/browser-electron/http-body.ts +65 -0
- package/src/browser-electron/json-reply.ts +47 -0
- package/src/browser-electron/maintenance-broker.ts +166 -0
- package/src/browser-electron/maintenance-lifecycle.ts +91 -0
- package/src/browser-electron/maintenance-route.ts +68 -0
- package/src/browser-electron/missing-system-browser.ts +114 -0
- package/src/browser-electron/open-slot.ts +49 -0
- package/src/browser-electron/paths.ts +25 -0
- package/src/browser-electron/preferred-browser.ts +130 -0
- package/src/browser-electron/preview-route.ts +215 -0
- package/src/browser-electron/process-ownership.ts +174 -0
- package/src/browser-electron/process.ts +23 -0
- package/src/browser-electron/profile-checkpoint.ts +187 -0
- package/src/browser-electron/profile-command.ts +47 -0
- package/src/browser-electron/profile-extension.ts +129 -0
- package/src/browser-electron/profile-lease.ts +211 -0
- package/src/browser-electron/profile-residue.ts +49 -0
- package/src/browser-electron/provider-core.ts +1107 -0
- package/src/browser-electron/provider-interaction.ts +1034 -0
- package/src/browser-electron/provider-media.ts +589 -0
- package/src/browser-electron/provider-navigation.ts +323 -0
- package/src/browser-electron/provider-observation.ts +664 -0
- package/src/browser-electron/provider-tabs.ts +372 -0
- package/src/browser-electron/provider.ts +666 -0
- package/src/browser-electron/reference-route.ts +598 -0
- package/src/browser-electron/remote-host.ts +1538 -0
- package/src/browser-electron/rpc-input.ts +13 -0
- package/src/browser-electron/rpc-ops.ts +41 -0
- package/src/browser-electron/runtime-diagnostics.ts +38 -0
- package/src/browser-electron/runtime-route.ts +105 -0
- package/src/browser-electron/runtime-status.ts +309 -0
- package/src/browser-electron/settings-route.ts +64 -0
- package/src/browser-electron/settings-store.ts +593 -0
- package/src/browser-electron/shortcuts-route.ts +112 -0
- package/src/browser-electron/sidebar-only-host.ts +300 -0
- package/src/browser-electron/startpage-shortcuts.ts +213 -0
- package/src/browser-electron/system-browser.ts +1850 -0
- package/src/browser-electron/tauri-host.ts +194 -0
- package/src/browser-electron/timing.ts +16 -0
- package/src/browser-electron/virtual-cursor.ts +162 -0
- package/src/browser-electron/windows-system.ts +24 -0
- package/src/browser-reference/delivery.ts +384 -0
- package/src/browser-reference/entry.ts +631 -0
- package/src/browser-reference/export.ts +339 -0
- package/src/browser-reference/import.ts +303 -0
- package/src/browser-reference/page-script.ts +1537 -0
- package/src/browser-reference/service.ts +1346 -0
- package/src/browser-reference/store.ts +172 -0
- package/src/browser-reference/text-quote.ts +219 -0
- package/src/browser-reference/types.ts +195 -0
- package/src/browser-reference/visible.ts +367 -0
- package/src/browser-reference/web-sources.ts +106 -0
- package/src/client/apply-guard.ts +22 -0
- package/src/client/browser/BrowserController.ts +693 -0
- package/src/client/browser/BrowserFrame.ts +78 -0
- package/src/client/browser/BrowserNavigation.ts +169 -0
- package/src/client/browser/BrowserPage.ts +23 -0
- package/src/client/browser/BrowserPersistence.ts +44 -0
- package/src/client/browser/IframeImpl.ts +182 -0
- package/src/client/browser/child-tabs.ts +14 -0
- package/src/client/browser/frame-history.ts +125 -0
- package/src/client/browser/frame-state.ts +27 -0
- package/src/client/browser/iframe-reference.ts +67 -0
- package/src/client/browser/initialization.ts +262 -0
- package/src/client/browser/omnibox.ts +243 -0
- package/src/client/browser/store.ts +38 -0
- package/src/client/browser/takeover-channel.ts +72 -0
- package/src/client/browser/url.ts +46 -0
- package/src/client/browser/web-reference-source.ts +56 -0
- package/src/client/css-modules.d.ts +4 -0
- package/src/client/definition.tsx +36 -0
- package/src/client/electron/ElectronWebViewImpl.ts +371 -0
- package/src/client/electron/ElectronWebviewPresentation.ts +140 -0
- package/src/client/electron/NativeChildPresentation.ts +53 -0
- package/src/client/electron/NativeViewPage.ts +265 -0
- package/src/client/electron/pages.ts +23 -0
- package/src/client/electron/reference-overlay.ts +53 -0
- package/src/client/electron/workspace.ts +33 -0
- package/src/client/index.ts +333 -0
- package/src/client/locales.ts +860 -0
- package/src/client/pages.ts +28 -0
- package/src/client/reference/client/BrowserRefLink.tsx +142 -0
- package/src/client/reference/client/draft-reference.ts +167 -0
- package/src/client/reference/client/index.ts +7 -0
- package/src/client/reference/client/ordered-submission.ts +108 -0
- package/src/client/reference/client/pending-delivery.ts +216 -0
- package/src/client/reference/client/plugin.ts +208 -0
- package/src/client/reference/client/production/ReferenceCapsules.tsx +345 -0
- package/src/client/reference/client/production/ReferenceDock.module.css +193 -0
- package/src/client/reference/client/production/ReferenceDock.tsx +6 -0
- package/src/client/reference/client/production/ReferenceFeedback.tsx +15 -0
- package/src/client/reference/client/production/ReferenceMath.tsx +44 -0
- package/src/client/reference/client/production/ReferenceText.tsx +36 -0
- package/src/client/reference/client/production/assembly.ts +447 -0
- package/src/client/reference/client/production/asset-store.ts +144 -0
- package/src/client/reference/client/production/availability.ts +72 -0
- package/src/client/reference/client/production/bytes.ts +36 -0
- package/src/client/reference/client/production/composer-attachments.ts +44 -0
- package/src/client/reference/client/production/delivery-client.ts +211 -0
- package/src/client/reference/client/production/draft-adapter.ts +512 -0
- package/src/client/reference/client/production/http-transport.ts +212 -0
- package/src/client/reference/client/production/production-submission.ts +70 -0
- package/src/client/reference/client/production/protocol.ts +234 -0
- package/src/client/reference/client/production/reference-card.ts +240 -0
- package/src/client/reference/client/production/reference-labels.ts +29 -0
- package/src/client/reference/client/production/reply-link-bridge.ts +222 -0
- package/src/client/reference/client/production/reveal.ts +215 -0
- package/src/client/reference/client/production/runtime.ts +1056 -0
- package/src/client/reference/client/production/snapshot-adapter.ts +154 -0
- package/src/client/reference/client/production/source-marker.ts +99 -0
- package/src/client/reference/client/production/source-opener.ts +55 -0
- package/src/client/reference/client/production/styles.ts +104 -0
- package/src/client/reference/client/production/user-text-rule.ts +67 -0
- package/src/client/reference/client/reveal.ts +109 -0
- package/src/client/reference/client/scheme.ts +114 -0
- package/src/client/reference/client/session-schedule.ts +36 -0
- package/src/client/reference/client/types.ts +168 -0
- package/src/client/reference/css-modules.d.ts +4 -0
- package/src/client/reference/index.ts +11 -0
- package/src/client/reference-capture-owner.ts +162 -0
- package/src/client/reference-intents.ts +36 -0
- package/src/client/settings/index.ts +42 -0
- package/src/client/settings/mount-guard.ts +31 -0
- package/src/client/settings/panel.ts +2773 -0
- package/src/client/shortcut-open.ts +30 -0
- package/src/client/startpage/binding.ts +99 -0
- package/src/client/startpage/controller.ts +300 -0
- package/src/client/startpage/model.ts +279 -0
- package/src/client/view/Browser.module.css +751 -0
- package/src/client/view/BrowserBody.tsx +315 -0
- package/src/client/view/BrowserPresentation.ts +9 -0
- package/src/client/view/BrowserTitle.tsx +17 -0
- package/src/client/view/IframePresentation.ts +365 -0
- package/src/client/view/StartPage.tsx +598 -0
- package/src/client/view/TakeoverBanner.tsx +21 -0
- package/src/compat/host-features.ts +92 -0
- package/src/index.ts +110 -0
- package/src/reference-owner.ts +5 -0
- package/src/reference-page.ts +9 -0
- package/src/reference-source.ts +3 -0
- package/src/reference-text.ts +219 -0
- package/src/startpage-settings.ts +103 -0
- package/src/startpage.ts +71 -0
- package/src/takeover-protocol.ts +28 -0
- package/src/tool-browser/block-recovery.ts +85 -0
- package/src/tool-browser/code-tool.ts +555 -0
- package/src/tool-browser/code-worker.ts +725 -0
- package/src/tool-browser/element-fields.ts +167 -0
- package/src/tool-browser/errors.ts +40 -0
- package/src/tool-browser/index.ts +265 -0
- package/src/tool-browser/page-probe.ts +675 -0
- package/src/tool-browser/panel-page.ts +126 -0
- package/src/tool-browser/probe-client.ts +183 -0
- package/src/tool-browser/screenshot-annotations.ts +131 -0
- package/src/tool-browser/screenshot-image.ts +49 -0
- package/src/tool-browser/state.ts +375 -0
- package/src/tool-browser/takeover.ts +199 -0
- package/src/tool-browser/tools-debug.ts +806 -0
- package/src/tool-browser/tools-interaction.ts +956 -0
- package/src/tool-browser/tools-navigation.ts +786 -0
- package/src/tool-browser/tools-observation.ts +474 -0
- package/src/tool-browser/tools-reference.ts +294 -0
- package/src/types/electron-shim.d.ts +144 -0
- package/src/types.ts +85 -0
- package/src/web-guest.ts +35 -0
- package/tools/accept-desktop.mjs +148 -0
- package/dist/client.d.cts +0 -516
- package/dist/client.d.mts +0 -516
- package/dist/index.cjs +0 -92
- package/dist/index.d.mts +0 -2960
- package/dist/index.mjs +0 -24
- package/dsh-builtin-browser-1.0.3-publish.tgz +0 -0
- package/dsh-builtin-browser-1.0.3.tgz +0 -0
- package/dsh-host-patch/sources/main/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
- package/dsh-host-patch/sources/main/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
- package/dsh-host-patch/sources/manifest.json +0 -218
- package/dsh-host-patch/sources/rc3/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
- package/dsh-host-patch/sources/rc3/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0001-feat-sidebar-right-add-session-rendering-holds.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0002-feat-desktop-load-trusted-profile-main-extensions.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0003-feat-desktop-report-resolved-and-running-main-extens.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0004-feat-desktop-compose-admitted-native-sidebar-views.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0005-fix-client-admit-coded-browser-errors-in-native-comp.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0006-fix-desktop-acknowledge-native-same-document-navigat.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0007-fix-desktop-restore-auth-in-the-native-lease-partiti.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0008-feat-desktop-adopt-native-children-in-admitted-sideb.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0009-fix-desktop-publish-complete-native-child-close-reco.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0010-fix-desktop-bundle-structured-errors-in-sandboxed-pr.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0011-feat-desktop-offer-persistent-Sidebar-sessions-per-D.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0012-feat-desktop-retain-sidebar-session-cookies-across-r.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0013-fix-desktop-honor-sidebar-session-cookie-sidecar-con.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0014-fix-desktop-retry-cookie-protection-without-failing-.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0015-fix-desktop-preserve-host-only-cookie-identity-in-se.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0016-fix-desktop-restore-session-cookies-before-checkpoin.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0017-fix-desktop-restore-sidebar-cookies-once-before-gues.patch.gz +0 -0
- package/dsh-host-patch/sources/rc5/0018-fix-sidebar-right-follow-animated-native-slot-placem.patch.gz +0 -0
- package/dsh-host-patch/sources/series.json +0 -260
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reference-library export encoders: JSONL records, readable Markdown, and a
|
|
3
|
+
* stored ZIP carrying the actual image bytes.
|
|
4
|
+
*
|
|
5
|
+
* Nothing here reads a page or a browser. The service hands over immutable
|
|
6
|
+
* records and already-validated asset bytes, so an export cannot claim content
|
|
7
|
+
* the store does not hold. A reference is written as one JSON object per line;
|
|
8
|
+
* the ZIP adds a manifest that binds each `assetKey` to its file, MIME type and
|
|
9
|
+
* source address so a receiver can rebuild the ordered parts.
|
|
10
|
+
* @module dsh-browser/browser-reference/export
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type {
|
|
14
|
+
BrowserReference,
|
|
15
|
+
BrowserReferencePart,
|
|
16
|
+
ImageReferencePart,
|
|
17
|
+
TableReferencePart,
|
|
18
|
+
} from './types.ts'
|
|
19
|
+
|
|
20
|
+
/** Output shapes the local library can produce without a conversation host. */
|
|
21
|
+
export type ReferenceExportFormat = 'jsonl' | 'markdown' | 'zip' | 'markdown-zip'
|
|
22
|
+
|
|
23
|
+
/** One validated asset ready to be written. */
|
|
24
|
+
export interface ExportAsset {
|
|
25
|
+
readonly assetKey: string
|
|
26
|
+
readonly mime: string
|
|
27
|
+
readonly bytes: Buffer
|
|
28
|
+
readonly sourceUrl?: string
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Everything one export needs. */
|
|
32
|
+
export interface ReferenceExportInput {
|
|
33
|
+
readonly references: readonly BrowserReference[]
|
|
34
|
+
readonly assets: readonly ExportAsset[]
|
|
35
|
+
readonly exportedAt: string
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** One file in the resource package. */
|
|
39
|
+
export interface ZipEntry {
|
|
40
|
+
readonly name: string
|
|
41
|
+
readonly data: Buffer | string
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const MIME_EXTENSIONS: Readonly<Record<string, string>> = {
|
|
45
|
+
'image/png': 'png',
|
|
46
|
+
'image/jpeg': 'jpg',
|
|
47
|
+
'image/gif': 'gif',
|
|
48
|
+
'image/webp': 'webp',
|
|
49
|
+
'image/avif': 'avif',
|
|
50
|
+
'image/bmp': 'bmp',
|
|
51
|
+
'image/svg+xml': 'svg',
|
|
52
|
+
'image/x-icon': 'ico',
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** @returns one file name for an asset, keeping the extension derived from validated bytes. */
|
|
56
|
+
export function assetFileName(assetKey: string, mime: string): string {
|
|
57
|
+
return `${assetKey}.${MIME_EXTENSIONS[mime.toLowerCase()] ?? 'bin'}`
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Unique asset keys used by these references, in first-use order.
|
|
62
|
+
* @param references - stored records.
|
|
63
|
+
* @returns keys from image parts and table-cell images.
|
|
64
|
+
*/
|
|
65
|
+
export function collectAssetKeys(references: readonly BrowserReference[]): string[] {
|
|
66
|
+
const seen = new Set<string>()
|
|
67
|
+
for (const reference of references) {
|
|
68
|
+
for (const part of reference.parts) {
|
|
69
|
+
if (part.type === 'image') seen.add(part.assetKey)
|
|
70
|
+
else if (part.type === 'table') {
|
|
71
|
+
for (const cell of part.table.cells) {
|
|
72
|
+
for (const run of cell.inlineContent ?? []) {
|
|
73
|
+
if (run.type === 'image') seen.add(run.assetKey)
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return [...seen]
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** @returns one JSON object per line, oldest first. Binary assets stay in their files. */
|
|
83
|
+
export function referencesJsonl(references: readonly BrowserReference[]): string {
|
|
84
|
+
return references.map(reference => JSON.stringify(reference)).join('\n') + (references.length === 0 ? '' : '\n')
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Render a readable export. Resource packages link images by relative path;
|
|
89
|
+
* a single file names the source address instead of embedding remote images.
|
|
90
|
+
*/
|
|
91
|
+
export function referencesMarkdown(input: ReferenceExportInput, resources: boolean): string {
|
|
92
|
+
const files = new Map(input.assets.map(asset => [asset.assetKey, asset]))
|
|
93
|
+
const sections: string[] = ['# Browser references', '']
|
|
94
|
+
for (const reference of input.references) {
|
|
95
|
+
sections.push(`## ${singleLine(reference.source.title) || reference.source.pageUrl || reference.referenceId}`)
|
|
96
|
+
sections.push('')
|
|
97
|
+
sections.push(`- Reference: \`dsh-browser-ref:${reference.referenceId}\``)
|
|
98
|
+
if (reference.source.pageUrl !== '') sections.push(`- Source: ${reference.source.pageUrl}`)
|
|
99
|
+
sections.push(`- Captured: ${reference.source.capturedAt}`)
|
|
100
|
+
sections.push(`- Carrier: ${reference.source.carrier}`)
|
|
101
|
+
sections.push('')
|
|
102
|
+
let counter = 0
|
|
103
|
+
for (const part of reference.parts) {
|
|
104
|
+
counter += 1
|
|
105
|
+
sections.push(...partMarkdown(part, counter, files, resources))
|
|
106
|
+
sections.push('')
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return sections.join('\n').replace(/\n{3,}/gu, '\n\n')
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Build the resource package.
|
|
114
|
+
* @returns ZIP bytes plus the manifest that names each asset.
|
|
115
|
+
*/
|
|
116
|
+
export function referenceZip(input: ReferenceExportInput): Buffer {
|
|
117
|
+
const fileNames = new Map(input.assets.map(asset => [asset.assetKey, assetFileName(asset.assetKey, asset.mime)]))
|
|
118
|
+
const manifest = {
|
|
119
|
+
kind: 'dsh-browser-reference-export',
|
|
120
|
+
version: 1,
|
|
121
|
+
exportedAt: input.exportedAt,
|
|
122
|
+
references: input.references.map(reference => ({
|
|
123
|
+
referenceId: reference.referenceId,
|
|
124
|
+
manifestHash: reference.manifestHash,
|
|
125
|
+
pageUrl: reference.source.pageUrl,
|
|
126
|
+
title: reference.source.title,
|
|
127
|
+
capturedAt: reference.source.capturedAt,
|
|
128
|
+
owner: reference.owner,
|
|
129
|
+
assets: collectAssetKeys([reference]).flatMap(key => {
|
|
130
|
+
const asset = input.assets.find(candidate => candidate.assetKey === key)
|
|
131
|
+
return asset === undefined ? [] : [{
|
|
132
|
+
assetKey: key,
|
|
133
|
+
file: `assets/${fileNames.get(key) ?? assetFileName(key, asset.mime)}`,
|
|
134
|
+
mime: asset.mime,
|
|
135
|
+
bytes: asset.bytes.length,
|
|
136
|
+
...asset.sourceUrl === undefined ? {} : { sourceUrl: asset.sourceUrl },
|
|
137
|
+
}]
|
|
138
|
+
}),
|
|
139
|
+
})),
|
|
140
|
+
assets: input.assets.map(asset => ({
|
|
141
|
+
assetKey: asset.assetKey,
|
|
142
|
+
file: `assets/${fileNames.get(asset.assetKey) ?? assetFileName(asset.assetKey, asset.mime)}`,
|
|
143
|
+
mime: asset.mime,
|
|
144
|
+
bytes: asset.bytes.length,
|
|
145
|
+
...asset.sourceUrl === undefined ? {} : { sourceUrl: asset.sourceUrl },
|
|
146
|
+
})),
|
|
147
|
+
}
|
|
148
|
+
const entries: ZipEntry[] = [
|
|
149
|
+
{ name: 'references.jsonl', data: referencesJsonl(input.references) },
|
|
150
|
+
{ name: 'manifest.json', data: JSON.stringify(manifest, null, 2) + '\n' },
|
|
151
|
+
{ name: 'references.md', data: referencesMarkdown(input, true) },
|
|
152
|
+
]
|
|
153
|
+
for (const asset of input.assets) {
|
|
154
|
+
entries.push({ name: `assets/${fileNames.get(asset.assetKey)!}`, data: asset.bytes })
|
|
155
|
+
}
|
|
156
|
+
return createZip(entries)
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Encode an export in the requested shape.
|
|
161
|
+
* @returns a file name, content type, and body.
|
|
162
|
+
*/
|
|
163
|
+
export function encodeReferenceExport(input: ReferenceExportInput, format: ReferenceExportFormat):
|
|
164
|
+
{ readonly fileName: string; readonly mime: string; readonly body: Buffer } {
|
|
165
|
+
const stamp = input.exportedAt.replace(/[:.]/gu, '-')
|
|
166
|
+
if (format === 'jsonl') {
|
|
167
|
+
return { fileName: `browser-references-${stamp}.jsonl`, mime: 'application/x-ndjson; charset=utf-8',
|
|
168
|
+
body: Buffer.from(referencesJsonl(input.references), 'utf8') }
|
|
169
|
+
}
|
|
170
|
+
if (format === 'markdown') {
|
|
171
|
+
return { fileName: `browser-references-${stamp}.md`, mime: 'text/markdown; charset=utf-8',
|
|
172
|
+
body: Buffer.from(referencesMarkdown(input, false), 'utf8') }
|
|
173
|
+
}
|
|
174
|
+
if (format === 'markdown-zip') {
|
|
175
|
+
const zip = createZip([
|
|
176
|
+
{ name: 'references.md', data: referencesMarkdown(input, true) },
|
|
177
|
+
{ name: 'references.jsonl', data: referencesJsonl(input.references) },
|
|
178
|
+
...input.assets.map(asset => ({ name: `assets/${assetFileName(asset.assetKey, asset.mime)}`, data: asset.bytes })),
|
|
179
|
+
])
|
|
180
|
+
return { fileName: `browser-references-${stamp}-markdown.zip`, mime: 'application/zip', body: zip }
|
|
181
|
+
}
|
|
182
|
+
return { fileName: `browser-references-${stamp}.zip`, mime: 'application/zip', body: referenceZip(input) }
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function partMarkdown(part: BrowserReferencePart, index: number, files: ReadonlyMap<string, ExportAsset>,
|
|
186
|
+
resources: boolean): string[] {
|
|
187
|
+
if (part.type === 'text') {
|
|
188
|
+
return [`### Part ${String(index)} · text`, '', quote(part.text)]
|
|
189
|
+
}
|
|
190
|
+
if (part.type === 'image') return imageMarkdown(part, index, files, resources)
|
|
191
|
+
return tableMarkdown(part, index)
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function imageMarkdown(part: ImageReferencePart, index: number, files: ReadonlyMap<string, ExportAsset>,
|
|
195
|
+
resources: boolean): string[] {
|
|
196
|
+
const asset = files.get(part.assetKey)
|
|
197
|
+
const alt = singleLine(part.alt ?? '') || singleLine(part.caption ?? '') || 'Image'
|
|
198
|
+
const source = part.anchor.currentSrc ?? part.anchor.src ?? asset?.sourceUrl
|
|
199
|
+
if (resources && asset !== undefined) {
|
|
200
|
+
const lines = [`### Part ${String(index)} · image`, '', `})`]
|
|
201
|
+
if (source !== undefined && source !== '') lines.push('', `<${source}>`)
|
|
202
|
+
return lines
|
|
203
|
+
}
|
|
204
|
+
const lines = [`### Part ${String(index)} · image`, '', `Image: ${alt}`]
|
|
205
|
+
if (source !== undefined && source !== '') lines.push('', `Source: <${source}>`)
|
|
206
|
+
return lines
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function tableMarkdown(part: TableReferencePart, index: number): string[] {
|
|
210
|
+
const { table } = part
|
|
211
|
+
const rows = Math.min(Math.max(table.rowCount, 0), 1000)
|
|
212
|
+
const columns = Math.min(Math.max(table.columnCount, 0), 200)
|
|
213
|
+
const grid: string[][] = Array.from({ length: rows }, () => Array.from({ length: columns }, () => ''))
|
|
214
|
+
const merges: string[] = []
|
|
215
|
+
for (const cell of table.cells) {
|
|
216
|
+
if (cell.row >= rows || cell.column >= columns) continue
|
|
217
|
+
grid[cell.row]![cell.column] = singleLine(cell.text)
|
|
218
|
+
if (cell.rowSpan > 1 || cell.columnSpan > 1) {
|
|
219
|
+
merges.push(`(${String(cell.row + 1)},${String(cell.column + 1)}) spans ${String(cell.rowSpan)}×${String(cell.columnSpan)}`)
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
const lines = [`### Part ${String(index)} · table`, '']
|
|
223
|
+
if (table.caption !== undefined && table.caption !== '') lines.push(`Caption: ${singleLine(table.caption)}`, '')
|
|
224
|
+
if (rows > 0 && columns > 0) {
|
|
225
|
+
lines.push(`| ${grid[0]!.map(escapeCell).join(' | ')} |`)
|
|
226
|
+
lines.push(`| ${Array.from({ length: columns }, () => '---').join(' | ')} |`)
|
|
227
|
+
for (let row = 1; row < rows; row += 1) {
|
|
228
|
+
lines.push(`| ${grid[row]!.map(escapeCell).join(' | ')} |`)
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
lines.push('')
|
|
232
|
+
lines.push(`Completeness: ${table.completeness}; rows ${String(rows)}; columns ${String(columns)}`)
|
|
233
|
+
if (merges.length > 0) lines.push('', ...merges.map(note => `- ${note}`))
|
|
234
|
+
return lines
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function quote(text: string): string {
|
|
238
|
+
return text.split(/\r?\n/u).map(line => `> ${line}`).join('\n')
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function escapeMarkdown(text: string): string {
|
|
242
|
+
return text.replace(/[[\]\\]/gu, match => `\\${match}`)
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function escapeCell(text: string): string {
|
|
246
|
+
return text.replace(/\|/gu, '\\|').replace(/\r?\n/gu, ' ')
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function singleLine(text: string): string {
|
|
250
|
+
return text.replace(/\s+/gu, ' ').trim()
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const CRC_TABLE = (() => {
|
|
254
|
+
const table = new Uint32Array(256)
|
|
255
|
+
for (let index = 0; index < 256; index += 1) {
|
|
256
|
+
let value = index
|
|
257
|
+
for (let bit = 0; bit < 8; bit += 1) value = (value & 1) === 1 ? 0xEDB88320 ^ (value >>> 1) : value >>> 1
|
|
258
|
+
table[index] = value >>> 0
|
|
259
|
+
}
|
|
260
|
+
return table
|
|
261
|
+
})()
|
|
262
|
+
|
|
263
|
+
export function crc32(data: Buffer): number {
|
|
264
|
+
let crc = 0xFFFFFFFF
|
|
265
|
+
for (const byte of data) crc = CRC_TABLE[(crc ^ byte) & 0xFF]! ^ (crc >>> 8)
|
|
266
|
+
return (crc ^ 0xFFFFFFFF) >>> 0
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function dosTimestamp(date: Date): { readonly time: number; readonly date: number } {
|
|
270
|
+
const year = Math.max(1980, date.getFullYear())
|
|
271
|
+
return {
|
|
272
|
+
time: (date.getHours() << 11) | (date.getMinutes() << 5) | Math.floor(date.getSeconds() / 2),
|
|
273
|
+
date: ((year - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate(),
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Write a ZIP using the stored method. The export has no server-side
|
|
279
|
+
* compressor dependency, and PNG bytes do not compress further anyway.
|
|
280
|
+
* @param entries - names and already-validated bytes.
|
|
281
|
+
* @returns ZIP bytes.
|
|
282
|
+
*/
|
|
283
|
+
export function createZip(entries: readonly ZipEntry[]): Buffer {
|
|
284
|
+
const stamp = dosTimestamp(new Date())
|
|
285
|
+
const locals: Buffer[] = []
|
|
286
|
+
const centrals: Buffer[] = []
|
|
287
|
+
let offset = 0
|
|
288
|
+
for (const entry of entries) {
|
|
289
|
+
const name = Buffer.from(entry.name, 'utf8')
|
|
290
|
+
const data = Buffer.isBuffer(entry.data) ? entry.data : Buffer.from(entry.data, 'utf8')
|
|
291
|
+
if (data.length > 0xFFFFFFFF) throw new Error('zip entry exceeds the 4 GiB stored limit')
|
|
292
|
+
const crc = crc32(data)
|
|
293
|
+
const local = Buffer.alloc(30)
|
|
294
|
+
local.writeUInt32LE(0x04034B50, 0)
|
|
295
|
+
local.writeUInt16LE(20, 4)
|
|
296
|
+
local.writeUInt16LE(0x0800, 6)
|
|
297
|
+
local.writeUInt16LE(0, 8)
|
|
298
|
+
local.writeUInt16LE(stamp.time, 10)
|
|
299
|
+
local.writeUInt16LE(stamp.date, 12)
|
|
300
|
+
local.writeUInt32LE(crc, 14)
|
|
301
|
+
local.writeUInt32LE(data.length, 18)
|
|
302
|
+
local.writeUInt32LE(data.length, 22)
|
|
303
|
+
local.writeUInt16LE(name.length, 26)
|
|
304
|
+
local.writeUInt16LE(0, 28)
|
|
305
|
+
locals.push(local, name, data)
|
|
306
|
+
|
|
307
|
+
const central = Buffer.alloc(46)
|
|
308
|
+
central.writeUInt32LE(0x02014B50, 0)
|
|
309
|
+
central.writeUInt16LE(20, 4)
|
|
310
|
+
central.writeUInt16LE(20, 6)
|
|
311
|
+
central.writeUInt16LE(0x0800, 8)
|
|
312
|
+
central.writeUInt16LE(0, 10)
|
|
313
|
+
central.writeUInt16LE(stamp.time, 12)
|
|
314
|
+
central.writeUInt16LE(stamp.date, 14)
|
|
315
|
+
central.writeUInt32LE(crc, 16)
|
|
316
|
+
central.writeUInt32LE(data.length, 20)
|
|
317
|
+
central.writeUInt32LE(data.length, 24)
|
|
318
|
+
central.writeUInt16LE(name.length, 28)
|
|
319
|
+
central.writeUInt16LE(0, 30)
|
|
320
|
+
central.writeUInt16LE(0, 32)
|
|
321
|
+
central.writeUInt16LE(0, 34)
|
|
322
|
+
central.writeUInt16LE(0, 36)
|
|
323
|
+
central.writeUInt32LE(0, 38)
|
|
324
|
+
central.writeUInt32LE(offset, 42)
|
|
325
|
+
centrals.push(central, name)
|
|
326
|
+
offset += local.length + name.length + data.length
|
|
327
|
+
}
|
|
328
|
+
const centralBuffer = Buffer.concat(centrals)
|
|
329
|
+
const end = Buffer.alloc(22)
|
|
330
|
+
end.writeUInt32LE(0x06054B50, 0)
|
|
331
|
+
end.writeUInt16LE(0, 4)
|
|
332
|
+
end.writeUInt16LE(0, 6)
|
|
333
|
+
end.writeUInt16LE(entries.length, 8)
|
|
334
|
+
end.writeUInt16LE(entries.length, 10)
|
|
335
|
+
end.writeUInt32LE(centralBuffer.length, 12)
|
|
336
|
+
end.writeUInt32LE(offset, 16)
|
|
337
|
+
end.writeUInt16LE(0, 20)
|
|
338
|
+
return Buffer.concat([...locals, centralBuffer, end])
|
|
339
|
+
}
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Import the plugin's own `format=zip` export back into the local reference library.
|
|
3
|
+
*
|
|
4
|
+
* The archive is untrusted input. No name in it becomes a filesystem path, no hash in it is
|
|
5
|
+
* trusted without being recomputed from the bytes, and no reference is stored unless its
|
|
6
|
+
* canonical manifestHash matches and every asset it names was verified inside this archive.
|
|
7
|
+
* Only stored (method 0) entries with a matching CRC32 are accepted: the exporter never writes
|
|
8
|
+
* compressed entries, and accepting deflate here would add a decompression bomb surface for no
|
|
9
|
+
* benefit. Bare JSONL, Markdown and the documentation-only `markdown-zip` packages are refused —
|
|
10
|
+
* they carry no manifest to check the assets against.
|
|
11
|
+
*
|
|
12
|
+
* This is the plugin-local import half of design §16. It does NOT restore DSH conversation
|
|
13
|
+
* messages, queues or attachment registrations, and it does not claim that a session fork is
|
|
14
|
+
* complete: the host still owns `ctx.sessions.fork`.
|
|
15
|
+
* @module dsh-browser/browser-reference/import
|
|
16
|
+
*/
|
|
17
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
18
|
+
import { existsSync, mkdirSync, renameSync, writeFileSync } from 'node:fs'
|
|
19
|
+
import { dirname, join } from 'node:path'
|
|
20
|
+
import { collectAssetKeys, crc32 } from './export.ts'
|
|
21
|
+
import { sniffImageMime } from './service.ts'
|
|
22
|
+
import { isReference, manifestHashOf, ReferenceStore, referenceStorePath } from './store.ts'
|
|
23
|
+
import type { BrowserReference } from './types.ts'
|
|
24
|
+
|
|
25
|
+
/** Bounds that keep a hostile archive from exhausting memory or the disk. */
|
|
26
|
+
const MAX_ENTRIES = 5_000
|
|
27
|
+
const MAX_TOTAL_BYTES = 200 * 1024 * 1024
|
|
28
|
+
const MAX_ENTRY_BYTES = 20 * 1024 * 1024
|
|
29
|
+
const ASSET_KEY = /^[0-9a-f]{64}$/
|
|
30
|
+
const ASSET_FILE = /^[0-9a-f]{64}\.[a-z0-9]+$/
|
|
31
|
+
const HTTP_URL = /^https?:\/\/\S+$/i
|
|
32
|
+
|
|
33
|
+
interface BundleAsset {
|
|
34
|
+
readonly mime: string
|
|
35
|
+
readonly bytes: Buffer
|
|
36
|
+
readonly sourceUrl?: string
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
interface DecodedBundle {
|
|
40
|
+
readonly references: readonly BrowserReference[]
|
|
41
|
+
readonly assets: ReadonlyMap<string, BundleAsset>
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface ImportResult {
|
|
45
|
+
readonly references: number
|
|
46
|
+
readonly added: number
|
|
47
|
+
readonly duplicates: number
|
|
48
|
+
readonly assets: number
|
|
49
|
+
readonly assetsWritten: number
|
|
50
|
+
/** Per-reference reasons; one bad record never discards the rest of a valid package. */
|
|
51
|
+
readonly rejected: readonly string[]
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface ImportOptions {
|
|
55
|
+
readonly store?: ReferenceStore
|
|
56
|
+
readonly assetDir?: string
|
|
57
|
+
readonly now?: () => Date
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
61
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function safeEntryName(name: string): boolean {
|
|
65
|
+
if (name === '' || name.startsWith('/') || name.includes('\\') || name.includes('\0')) return false
|
|
66
|
+
const parts = name.split('/')
|
|
67
|
+
if (parts.length > 2 || parts.some(part => part === '' || part === '.' || part === '..')) return false
|
|
68
|
+
if (parts.length === 1) {
|
|
69
|
+
return name === 'references.jsonl' || name === 'manifest.json' || name === 'references.md'
|
|
70
|
+
}
|
|
71
|
+
return parts[0] === 'assets' && ASSET_FILE.test(parts[1] ?? '')
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Read a stored-only ZIP without trusting local-header sizes over the central directory.
|
|
76
|
+
* @param zip - the archive bytes.
|
|
77
|
+
* @returns entry name to verified bytes.
|
|
78
|
+
*/
|
|
79
|
+
export function parseStoredZip(zip: Buffer): Map<string, Buffer> {
|
|
80
|
+
if (zip.length < 22) throw new Error('not a zip archive: too short')
|
|
81
|
+
let end = -1
|
|
82
|
+
const floor = Math.max(0, zip.length - 65_557)
|
|
83
|
+
for (let at = zip.length - 22; at >= floor; at -= 1) {
|
|
84
|
+
if (zip.readUInt32LE(at) === 0x06054B50) { end = at; break }
|
|
85
|
+
}
|
|
86
|
+
if (end < 0) throw new Error('not a zip archive: end of central directory not found')
|
|
87
|
+
const count = zip.readUInt16LE(end + 10)
|
|
88
|
+
const centralSize = zip.readUInt32LE(end + 12)
|
|
89
|
+
const centralOffset = zip.readUInt32LE(end + 16)
|
|
90
|
+
if (count > MAX_ENTRIES) throw new Error('the zip has too many entries')
|
|
91
|
+
if (centralOffset + centralSize > zip.length) throw new Error('the zip central directory is out of bounds')
|
|
92
|
+
|
|
93
|
+
const files = new Map<string, Buffer>()
|
|
94
|
+
let cursor = centralOffset
|
|
95
|
+
let total = 0
|
|
96
|
+
for (let index = 0; index < count; index += 1) {
|
|
97
|
+
if (cursor + 46 > zip.length || zip.readUInt32LE(cursor) !== 0x02014B50) {
|
|
98
|
+
throw new Error('the zip central directory is damaged')
|
|
99
|
+
}
|
|
100
|
+
const method = zip.readUInt16LE(cursor + 10)
|
|
101
|
+
const crc = zip.readUInt32LE(cursor + 16)
|
|
102
|
+
const compressed = zip.readUInt32LE(cursor + 20)
|
|
103
|
+
const size = zip.readUInt32LE(cursor + 24)
|
|
104
|
+
const nameLength = zip.readUInt16LE(cursor + 28)
|
|
105
|
+
const extraLength = zip.readUInt16LE(cursor + 30)
|
|
106
|
+
const commentLength = zip.readUInt16LE(cursor + 32)
|
|
107
|
+
const localOffset = zip.readUInt32LE(cursor + 42)
|
|
108
|
+
if (cursor + 46 + nameLength + extraLength + commentLength > zip.length) {
|
|
109
|
+
throw new Error('the zip central directory is damaged')
|
|
110
|
+
}
|
|
111
|
+
const name = zip.toString('utf8', cursor + 46, cursor + 46 + nameLength)
|
|
112
|
+
cursor += 46 + nameLength + extraLength + commentLength
|
|
113
|
+
if (!safeEntryName(name)) throw new Error(`the zip contains an unsafe entry name: ${JSON.stringify(name)}`)
|
|
114
|
+
if (files.has(name)) throw new Error(`the zip contains a duplicate entry: ${JSON.stringify(name)}`)
|
|
115
|
+
if (method !== 0 || compressed !== size) throw new Error(`the zip entry ${JSON.stringify(name)} is not stored uncompressed`)
|
|
116
|
+
if (size > MAX_ENTRY_BYTES) throw new Error('a zip entry exceeds the import size limit')
|
|
117
|
+
total += size
|
|
118
|
+
if (total > MAX_TOTAL_BYTES) throw new Error('the zip exceeds the total import size limit')
|
|
119
|
+
if (localOffset + 30 > zip.length || zip.readUInt32LE(localOffset) !== 0x04034B50) {
|
|
120
|
+
throw new Error(`the zip entry ${JSON.stringify(name)} has no valid local header`)
|
|
121
|
+
}
|
|
122
|
+
const localNameLength = zip.readUInt16LE(localOffset + 26)
|
|
123
|
+
const localExtraLength = zip.readUInt16LE(localOffset + 28)
|
|
124
|
+
const dataStart = localOffset + 30 + localNameLength + localExtraLength
|
|
125
|
+
if (dataStart + size > zip.length) throw new Error(`the zip entry ${JSON.stringify(name)} is truncated`)
|
|
126
|
+
const bytes = Buffer.from(zip.subarray(dataStart, dataStart + size))
|
|
127
|
+
if (crc32(bytes) !== crc) throw new Error(`the zip entry ${JSON.stringify(name)} failed its CRC32`)
|
|
128
|
+
files.set(name, bytes)
|
|
129
|
+
}
|
|
130
|
+
return files
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Validate a decoded package: manifest shape, asset content hashes and reference hashes.
|
|
135
|
+
* @param files - the verified ZIP entries.
|
|
136
|
+
* @returns references and content-addressed assets ready to materialise.
|
|
137
|
+
*/
|
|
138
|
+
export function decodeReferenceBundle(files: ReadonlyMap<string, Buffer>): DecodedBundle {
|
|
139
|
+
const manifestText = files.get('manifest.json')
|
|
140
|
+
if (manifestText === undefined) {
|
|
141
|
+
throw new Error('the package has no manifest.json; import a format=zip export, not markdown-zip or raw JSONL')
|
|
142
|
+
}
|
|
143
|
+
let parsed: unknown
|
|
144
|
+
try { parsed = JSON.parse(manifestText.toString('utf8')) } catch {
|
|
145
|
+
throw new Error('the package manifest is not valid JSON')
|
|
146
|
+
}
|
|
147
|
+
if (!isRecord(parsed) || parsed.kind !== 'dsh-browser-reference-export' || parsed.version !== 1) {
|
|
148
|
+
throw new Error('the package manifest is not a version 1 browser-reference export')
|
|
149
|
+
}
|
|
150
|
+
const rows: readonly unknown[] = Array.isArray(parsed.assets) ? parsed.assets : []
|
|
151
|
+
const assets = new Map<string, BundleAsset>()
|
|
152
|
+
for (const row of rows) {
|
|
153
|
+
if (!isRecord(row)) throw new Error('the package manifest has a malformed asset row')
|
|
154
|
+
const assetKey = row.assetKey
|
|
155
|
+
const file = row.file
|
|
156
|
+
if (typeof assetKey !== 'string' || !ASSET_KEY.test(assetKey)) throw new Error('an asset key is not a SHA-256 hex digest')
|
|
157
|
+
if (typeof file !== 'string' || !file.startsWith('assets/') || !safeEntryName(file)) {
|
|
158
|
+
throw new Error('an asset file name is not inside the package assets directory')
|
|
159
|
+
}
|
|
160
|
+
const bytes = files.get(file)
|
|
161
|
+
if (bytes === undefined) throw new Error(`the package is missing ${JSON.stringify(file)}`)
|
|
162
|
+
if (row.bytes !== bytes.length) throw new Error(`the manifest byte count for ${assetKey} does not match the bytes`)
|
|
163
|
+
if (createHash('sha256').update(bytes).digest('hex') !== assetKey) {
|
|
164
|
+
throw new Error(`the bytes of ${assetKey} do not match their content hash`)
|
|
165
|
+
}
|
|
166
|
+
const mime = sniffImageMime(bytes)
|
|
167
|
+
if (mime === undefined) throw new Error(`the bytes of ${assetKey} are not a recognised image`)
|
|
168
|
+
const sourceUrl = row.sourceUrl
|
|
169
|
+
if (sourceUrl !== undefined && (typeof sourceUrl !== 'string' || !HTTP_URL.test(sourceUrl))) {
|
|
170
|
+
throw new Error(`the manifest source URL for ${assetKey} is not an HTTP(S) URL`)
|
|
171
|
+
}
|
|
172
|
+
assets.set(assetKey, {
|
|
173
|
+
mime, bytes,
|
|
174
|
+
...typeof sourceUrl === 'string' ? { sourceUrl } : {},
|
|
175
|
+
})
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const jsonl = files.get('references.jsonl')
|
|
179
|
+
if (jsonl === undefined) throw new Error('the package has no references.jsonl')
|
|
180
|
+
const references: BrowserReference[] = []
|
|
181
|
+
for (const line of jsonl.toString('utf8').split('\n')) {
|
|
182
|
+
if (line.trim() === '') continue
|
|
183
|
+
let value: unknown
|
|
184
|
+
try { value = JSON.parse(line) } catch { throw new Error('references.jsonl has a malformed line') }
|
|
185
|
+
if (!isReference(value)) throw new Error('references.jsonl contains a record that is not a browser reference')
|
|
186
|
+
if (manifestHashOf(value) !== value.manifestHash) throw new Error(`reference ${value.referenceId} has a mismatched manifestHash`)
|
|
187
|
+
for (const key of collectAssetKeys([value])) {
|
|
188
|
+
if (!assets.has(key)) throw new Error(`reference ${value.referenceId} names an asset absent from the package`)
|
|
189
|
+
}
|
|
190
|
+
references.push(value)
|
|
191
|
+
}
|
|
192
|
+
return { references, assets }
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Materialise assets and append references to the local library.
|
|
197
|
+
* @param zip - the export package bytes.
|
|
198
|
+
* @param options - test seams for the store, asset directory and clock.
|
|
199
|
+
* @returns counts, including per-record rejections.
|
|
200
|
+
*/
|
|
201
|
+
export function importReferenceBundle(zip: Buffer, options: ImportOptions = {}): ImportResult {
|
|
202
|
+
const { references, assets } = decodeReferenceBundle(parseStoredZip(zip))
|
|
203
|
+
const store = options.store ?? new ReferenceStore()
|
|
204
|
+
const assetDir = options.assetDir ?? join(dirname(referenceStorePath()), 'reference-assets')
|
|
205
|
+
const now = options.now ?? (() => new Date())
|
|
206
|
+
let assetsWritten = 0
|
|
207
|
+
if (assets.size > 0) {
|
|
208
|
+
mkdirSync(assetDir, { recursive: true })
|
|
209
|
+
for (const [assetKey, asset] of assets) {
|
|
210
|
+
const file = join(assetDir, `${assetKey}.bin`)
|
|
211
|
+
if (!existsSync(file)) {
|
|
212
|
+
const temp = `${file}.${process.pid}-${randomUUID()}.tmp`
|
|
213
|
+
writeFileSync(temp, asset.bytes)
|
|
214
|
+
renameSync(temp, file)
|
|
215
|
+
assetsWritten += 1
|
|
216
|
+
}
|
|
217
|
+
const metaFile = join(assetDir, `${assetKey}.json`)
|
|
218
|
+
if (!existsSync(metaFile)) {
|
|
219
|
+
writeFileSync(metaFile, JSON.stringify({
|
|
220
|
+
assetKey,
|
|
221
|
+
mime: asset.mime,
|
|
222
|
+
bytes: asset.bytes.length,
|
|
223
|
+
...asset.sourceUrl === undefined ? {} : { sourceUrl: asset.sourceUrl },
|
|
224
|
+
representation: 'source-image',
|
|
225
|
+
savedAt: now().toISOString(),
|
|
226
|
+
}))
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
const rejected: string[] = []
|
|
231
|
+
let added = 0
|
|
232
|
+
let duplicates = 0
|
|
233
|
+
for (const reference of references) {
|
|
234
|
+
try {
|
|
235
|
+
if (store.append(reference) === 'added') added += 1
|
|
236
|
+
else duplicates += 1
|
|
237
|
+
} catch (error) {
|
|
238
|
+
rejected.push(`${reference.referenceId}: ${String(error)}`)
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return {
|
|
242
|
+
references: references.length, added, duplicates,
|
|
243
|
+
assets: assets.size, assetsWritten, rejected,
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export interface ForkRegistration {
|
|
248
|
+
readonly created: number
|
|
249
|
+
readonly duplicates: number
|
|
250
|
+
/** Reference ids skipped because at least one bound asset is no longer on disk. */
|
|
251
|
+
readonly missingAssets: readonly string[]
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Register a session fork's references in the plugin library.
|
|
256
|
+
*
|
|
257
|
+
* Assets are content-addressed and shared, never copied: a fork is legal only when every
|
|
258
|
+
* asset the source references still exists. Reference ids are derived deterministically from
|
|
259
|
+
* the target session and the original id, so replaying the same fork is idempotent. This is
|
|
260
|
+
* the plugin's asset-registration half; the host still owns the actual `ctx.sessions.fork`.
|
|
261
|
+
* @param sourceSessionId - the conversation being forked.
|
|
262
|
+
* @param targetSessionId - the new conversation.
|
|
263
|
+
* @param options - test seams for the store and asset directory.
|
|
264
|
+
* @returns the registration counts.
|
|
265
|
+
*/
|
|
266
|
+
export function registerForkedReferences(
|
|
267
|
+
sourceSessionId: string,
|
|
268
|
+
targetSessionId: string,
|
|
269
|
+
options: ImportOptions = {},
|
|
270
|
+
): ForkRegistration {
|
|
271
|
+
const store = options.store ?? new ReferenceStore()
|
|
272
|
+
const assetDir = options.assetDir ?? join(dirname(referenceStorePath()), 'reference-assets')
|
|
273
|
+
const missingAssets: string[] = []
|
|
274
|
+
let created = 0
|
|
275
|
+
let duplicates = 0
|
|
276
|
+
for (const original of store.list({ sessionId: sourceSessionId })) {
|
|
277
|
+
const keys = collectAssetKeys([original])
|
|
278
|
+
if (keys.some(key => !existsSync(join(assetDir, `${key}.bin`)))) {
|
|
279
|
+
missingAssets.push(original.referenceId)
|
|
280
|
+
continue
|
|
281
|
+
}
|
|
282
|
+
const referenceId = createHash('sha256').update(`fork:${targetSessionId}:${original.referenceId}`).digest('hex')
|
|
283
|
+
const draft: Omit<BrowserReference, 'manifestHash'> = {
|
|
284
|
+
version: 1,
|
|
285
|
+
provider: 'dsh-browser',
|
|
286
|
+
referenceId,
|
|
287
|
+
owner: { sessionId: targetSessionId, ...original.owner.browserSessionId === undefined ? {} : { browserSessionId: original.owner.browserSessionId } },
|
|
288
|
+
provenance: original.provenance,
|
|
289
|
+
source: original.source,
|
|
290
|
+
parts: original.parts,
|
|
291
|
+
}
|
|
292
|
+
const reference: BrowserReference = { ...draft, manifestHash: manifestHashOf(draft) }
|
|
293
|
+
try {
|
|
294
|
+
if (store.append(reference) === 'added') created += 1
|
|
295
|
+
else duplicates += 1
|
|
296
|
+
} catch {
|
|
297
|
+
// A pre-existing id with different content means the fork was already registered with a
|
|
298
|
+
// different source snapshot; leave the original untouched rather than mutate an immutable record.
|
|
299
|
+
missingAssets.push(original.referenceId)
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
return { created, duplicates, missingAssets }
|
|
303
|
+
}
|