dsh-paste-image 0.0.0-stage → 0.2.1

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 ADDED
@@ -0,0 +1,54 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.2.1] - 2026-11-18
10
+
11
+ ### Fixed
12
+
13
+ - The release checklist in `docs/releasing.md` reported the 0.2.0 test count; it now matches the suite (16 tests).
14
+
15
+ ## [0.2.0] - 2026-11-18
16
+
17
+ ### Added
18
+
19
+ - Full BMP/DIB coverage in `decodeBmp()`: 1/4/8/16/24/32-bit pixels, `BI_RLE8`/`BI_RLE4`, `BI_BITFIELDS`/`BI_ALPHABITFIELDS`, `BITMAPCOREHEADER`, `BITMAPV2/V3/V4/V5HEADER`, OS/2 v2 headers and headerless DIBs (the `CF_DIB` shape).
20
+ - Embedded JPEG/PNG payloads (`BI_JPEG`/`BI_PNG`) are unwrapped and handed to the browser decoder.
21
+ - SVG pastes are rasterised through an `<img>` element; `viewBox` provides the size when `width`/`height` are missing.
22
+ - ICO/CUR fall back to the largest PNG-compressed directory entry when the browser cannot decode the icon.
23
+ - Magic-byte detection for AVIF, HEIC/HEIF, ICO/CUR, SVG and headerless DIBs.
24
+ - MIME alias table so `image/jpg`, `image/x-png`, `image/x-bmp`, `image/x-xpixmap`, `image/svg+xml` and friends are treated as the canonical type.
25
+ - `MAX_PIXELS` guard (64 Mi px) before a BMP/XPM canvas is allocated.
26
+ - `docs/formats.md`: the decision pipeline, the full format matrix, the BMP variant grid and the checklist for adding a format.
27
+ - `docs/releasing.md`: version policy, release checklist, npm publish steps and marketplace sync.
28
+ - Open-source scaffolding: `.github/CODEOWNERS`, issue-template contact links, README badges, and a Community section linking contributing, conduct, security, changelog and releases.
29
+
30
+ ### Changed
31
+
32
+ - A native image with an empty declared type is re-wrapped with the sniffed type instead of being passed through and rejected by the host.
33
+ - Row stride, palette entries, bit masks and alpha handling in the BMP decoder are shared by every pixel depth instead of being hard-coded for 24/32-bit.
34
+ - BMP files using `BI_CMYK` compression (11/12/13) are rejected with `bmp: unsupported compression` instead of being decoded as RGB.
35
+
36
+ ### Fixed
37
+
38
+ - 32-bit BMPs whose encoder leaves the alpha channel at zero no longer export as a fully transparent PNG.
39
+ - Palette BMP entries are loaded with the correct entry size (3 bytes for the OS/2 core header, 4 otherwise), and a zero alpha byte in a palette entry no longer makes that colour transparent.
40
+ - `cordis.patch.yml` is now part of the published `files` list. GitHub (and future npm) installs used to omit the loader patch, so the bundle entry never mounted; CI checks the tarball for the file.
41
+
42
+ ## [0.1.0] - 2026-11-15
43
+
44
+ ### Added
45
+
46
+ - Capture-phase `paste` and `drop` interception in the DSH renderer.
47
+ - Magic-byte detection for PNG, JPEG, GIF, WebP, BMP, TIFF and XPM, independent of the declared MIME type.
48
+ - Native pass-through for PNG, JPEG, WebP and GIF when the declared type agrees with the bytes.
49
+ - XPM3 text decoder (`decodeXpm`) and a 24/32-bit uncompressed BMP fallback decoder (`decodeBmp`).
50
+ - Canvas re-encoding to PNG with a 4096 px longest-side cap and `.png` file naming.
51
+ - Synthetic `drop` rerouting to `[data-composer-card]`, guarded by `__dshPasteImageRerouted`.
52
+ - `__ModuleLoader__` module registration with a `ctx.effect` lifecycle hook.
53
+ - Node test suite covering sniffing, candidate detection, BMP decoding, format-lie conversion and native pass-through.
54
+ - MIT license.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 pengtang1024
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,127 @@
1
- # Temporary Holding Version
1
+ # dsh-paste-image
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![CI](https://github.com/pengtang1024/dsh-paste-image/actions/workflows/ci.yml/badge.svg)](https://github.com/pengtang1024/dsh-paste-image/actions/workflows/ci.yml)
4
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
5
+ [![Node](https://img.shields.io/badge/node-%3E%3D20-brightgreen.svg)](package.json)
6
+
7
+ Paste or drop almost any image into DeepSeek Harness — even when the clipboard says `image/xpm` or lies about the MIME type.
8
+
9
+ ## Why this exists
10
+
11
+ The DSH desktop client (Electron/Chromium) accepts exactly four attachment types: `image/png`, `image/jpeg`, `image/webp` and `image/gif`. Anything else gives you the red rejection:
12
+
13
+ > 仅支持 PNG、JPG、WebP、GIF
14
+
15
+ That whitelist breaks two things that happen all the time on Linux:
16
+
17
+ - **Screenshots declared as XPM.** Some screenshot tools, notably on Ubuntu/Wayland, put the image on the clipboard with the type `image/xpm`. The pixels are fine; the label is not on the whitelist, so the paste is rejected.
18
+ - **BMP bytes wearing a PNG label.** Some applications hand over a BMP (or TIFF) payload while declaring `image/png`. The declared type passes the whitelist check, the decoder later fails, and you get the same red error.
19
+
20
+ `dsh-paste-image` handles both cases inside the renderer: it looks at the actual bytes, decodes what the clipboard really contains, re-encodes it as PNG, and hands the result back to the normal attachment channel.
21
+
22
+ ## How it works
23
+
24
+ 1. **Capture.** `install()` registers `paste` and `drop` listeners on `document` in the capture phase, so the plugin sees the event before the composer does.
25
+ 2. **Sniff.** `handle()` reads the `File` objects from `clipboardData` or `dataTransfer`, and `sniff()` identifies the real format from magic bytes — not from the declared MIME type.
26
+ 3. **Re-encode.** `normalize()` lets native files through untouched. Everything else is decoded (dedicated XPM, BMP/DIB and SVG paths, the browser's own codec for the rest), drawn onto a canvas capped at 4096 px on the longest side, and exported as `image/png` with a `.png` file name.
27
+ 4. **Reroute.** `handle()` dispatches a synthetic `drop` event carrying the new `File` at `[data-composer-card]`, which is the same path a real drag-and-drop takes. A `__dshPasteImageRerouted` marker stops the plugin from intercepting its own event.
28
+
29
+ All of this is client-side. There is no host process, no clipboard polling and no network request.
30
+
31
+ ## Supported formats
32
+
33
+ This table is the short version. The [format support reference](docs/formats.md) explains the decision pipeline, the full BMP variant grid, and what is intentionally out of scope.
34
+
35
+ | Format | Typical declared type | What happens |
36
+ | ---------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
37
+ | PNG | `image/png` | Passed through unchanged |
38
+ | JPEG / JFIF | `image/jpeg` | Passed through unchanged |
39
+ | WebP | `image/webp` | Passed through unchanged |
40
+ | GIF | `image/gif` | Passed through unchanged |
41
+ | XPM (XPM3 text) | `image/xpm` | Decoded by `decodeXpm()`, re-encoded as PNG |
42
+ | BMP / DIB | `image/bmp` | Browser decode first, `decodeBmp()` fallback: 1/4/8/16/24/32-bit, RLE4/RLE8, BITFIELDS, OS/2 headers and headerless DIBs |
43
+ | SVG | `image/svg+xml` | Rasterised through an `<img>` element, re-encoded as PNG |
44
+ | ICO / CUR | `image/x-icon` | Browser decode first, then falls back to the largest PNG-compressed entry |
45
+ | TIFF | `image/tiff` | Detected by magic bytes; decoded only if the browser ships a TIFF codec (Chromium does not), otherwise the original is passed through |
46
+ | AVIF | `image/avif` | Decoded by Chromium, re-encoded as PNG |
47
+ | HEIC / HEIF, other `image/*` | `image/...` | Detected by magic bytes; decoded only when the browser has the codec (Chromium does not decode HEIC), otherwise passed through |
48
+
49
+ Pass-through only happens when the magic bytes match one of the four native types **and** the declared type agrees. A file whose bytes are JPEG but which claims `image/png` is re-encoded as a real PNG, so the declared type can no longer lie. A native file with no declared type at all is re-wrapped with the sniffed type instead of being re-encoded, and common alias spellings (`image/jpg`, `image/x-png`, `image/x-bmp`, `image/x-xpixmap`, `image/svg+xml`, …) count as agreement.
50
+
51
+ A file is considered at all when its MIME type starts with `image/` or its name ends in `.png`, `.jpg`, `.jpeg`, `.jfif`, `.gif`, `.webp`, `.bmp`, `.dib`, `.tif`, `.tiff`, `.xpm`, `.avif`, `.ico`, `.cur`, `.svg`, `.heic` or `.heif`. Non-image files in the same paste are forwarded untouched.
52
+
53
+ ## Install
54
+
55
+ Not published to npm. Install from GitHub:
56
+
57
+ ```bash
58
+ dsh plugin --profile <profile> add github:pengtang1024/dsh-paste-image
59
+ ```
60
+
61
+ For local development, point the profile at your checkout:
62
+
63
+ ```bash
64
+ dsh plugin --profile <profile> add file:/absolute/path/to/dsh-paste-image
65
+ ```
66
+
67
+ Replace `<profile>` with the profile your app runs. **Reload the page after installing** (`Ctrl+R`, or `Cmd+R` on macOS). The client module is only injected when the renderer loads, so a freshly installed plugin intercepts nothing until you reload.
68
+
69
+ ## Verify it works
70
+
71
+ Run the repository checks:
72
+
73
+ ```bash
74
+ cd dsh-paste-image
75
+ npm test
76
+ npm run check
77
+ ```
78
+
79
+ `npm test` runs the Node test suite (16 tests at 0.2.1) covering magic-byte sniffing, candidate detection, every BMP variant, the BMP-labelled-PNG conversion, headerless DIBs and native pass-through. `npm run check` syntax-checks `client.js` and `lib/index.js`.
80
+
81
+ Then check the real flow:
82
+
83
+ 1. Reload the DSH window.
84
+ 2. Take a screenshot with your usual tool and paste it into the composer, or drop an image file onto it.
85
+ 3. The attachment appears. Open DevTools (`Ctrl+Shift+I`) → Console, switch the level to **Verbose**, and look for a line like:
86
+
87
+ ```text
88
+ [dsh-paste-image] image/xpm -> image/png 1440x900
89
+ ```
90
+
91
+ If conversion fails, the plugin keeps the original file and logs `keep original (...)` instead.
92
+
93
+ ## Limitations
94
+
95
+ - **XPM:** XPM3 text format only. The parser reads the `c` colour key; other keys such as `m`, `g` and `s` are ignored. Colours are resolved by the browser's CSS parser, so palette names that are not valid CSS colours, such as the multi-word `light gray`, fall back to opaque black.
96
+ - **BMP:** 1/4/8/16/24/32-bit, `BI_RGB`, `BI_RLE8`, `BI_RLE4`, `BI_BITFIELDS` and `BI_ALPHABITFIELDS`, with core, extended, V4/V5 or OS/2 headers — plus headerless DIBs. 2-bit and 64-bit-per-pixel variants are not supported. For 32-bit files without a declared alpha mask, an all-zero alpha channel is treated as opaque instead of producing a fully transparent PNG.
97
+ - **Other codecs:** SVG is rasterised in-house; ICO/CUR fall back to PNG-compressed entries; AVIF relies on the browser decoder. TIFF and HEIC are detected but Chromium ships no codec for them, so the original is passed through and the host rejects it as before. No third-party decoder is bundled.
98
+ - **Size:** converted images are scaled down to at most 4096 px on the longest side. Native files passed through untouched are not resized.
99
+ - **File count:** one paste or drop may contain at most 8 files. Larger batches are left entirely to the native path.
100
+ - **Flattening:** a converted image becomes a single PNG frame. Animation, EXIF metadata and embedded colour profiles are not preserved.
101
+ - **Scope:** only the `paste` and `drop` paths are covered. The file picker and other insertion paths keep their native behaviour.
102
+
103
+ ## Security and privacy
104
+
105
+ - Everything runs in the renderer. The plugin makes no network requests, uploads nothing and stores nothing.
106
+ - There is no background process, no clipboard polling and no change to DSH host code.
107
+ - Image bytes are read only from the paste or drop event, decoded locally, and handed back to the same window.
108
+ - The decoders are small, but they do process untrusted input. If you find a crash or a parsing bug, see [SECURITY.md](SECURITY.md).
109
+
110
+ ## Documentation
111
+
112
+ - [How it works](docs/how-it-works.md) — event flow, decoder internals and a function-by-function code map.
113
+ - [Format support](docs/formats.md) — decision pipeline, format matrix, BMP variants and the checklist for adding a format.
114
+ - [Troubleshooting](docs/troubleshooting.md) — common failures and how to read the logs.
115
+ - [Releasing](docs/releasing.md) — version policy and the maintainer release checklist.
116
+
117
+ ## Community
118
+
119
+ - [Contributing](CONTRIBUTING.md) — setup, tests, style and what a format contribution needs.
120
+ - [Code of Conduct](CODE_OF_CONDUCT.md) — Contributor Covenant 2.1.
121
+ - [Security policy](SECURITY.md) — private reporting, scope and supported versions.
122
+ - [Changelog](CHANGELOG.md) and [releases](https://github.com/pengtang1024/dsh-paste-image/releases) — what changed and why.
123
+ - [Issues](https://github.com/pengtang1024/dsh-paste-image/issues) — bug reports and format requests.
124
+
125
+ ## License
126
+
127
+ MIT © 2026 pengtang1024. See [LICENSE](LICENSE).
package/README.zh.md ADDED
@@ -0,0 +1,127 @@
1
+ # dsh-paste-image
2
+
3
+ [![CI](https://github.com/pengtang1024/dsh-paste-image/actions/workflows/ci.yml/badge.svg)](https://github.com/pengtang1024/dsh-paste-image/actions/workflows/ci.yml)
4
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
5
+ [![Node](https://img.shields.io/badge/node-%3E%3D20-brightgreen.svg)](package.json)
6
+
7
+ 把几乎任何图片粘进或拖进 DeepSeek Harness —— 哪怕剪贴板声称它是 `image/xpm`,或者干脆把 MIME 类型写错了。
8
+
9
+ ## 为什么需要它
10
+
11
+ DSH 桌面客户端(Electron/Chromium)的附件通道只接受四种类型:`image/png`、`image/jpeg`、`image/webp`、`image/gif`。其它类型一律报红:
12
+
13
+ > 仅支持 PNG、JPG、WebP、GIF
14
+
15
+ 这份白名单会打断两种在 Linux 上很常见的场景:
16
+
17
+ - **截图被声明成 XPM。** 部分截图工具(尤其是 Ubuntu/Wayland 上)会把图片以 `image/xpm` 类型放进剪贴板。像素本身没问题,但这个类型不在白名单里,粘贴直接被拒。
18
+ - **BMP 字节披着 PNG 的皮。** 有些应用交上来的是 BMP(或 TIFF)数据,却声明成 `image/png`。声明类型过了白名单检查,后面解码失败,还是同一个红字。
19
+
20
+ `dsh-paste-image` 在渲染进程里把这两类问题一起解决:看真实字节、解出剪贴板里真正的内容、重编码成 PNG,再交回原生附件通道。
21
+
22
+ ## 工作原理
23
+
24
+ 1. **捕获。** `install()` 在 `document` 上以捕获阶段挂 `paste` 和 `drop` 监听,确保先于输入框自己的处理逻辑看到事件。
25
+ 2. **嗅探。** `handle()` 从 `clipboardData` 或 `dataTransfer` 取出 `File`,`sniff()` 按魔数判断真实格式 —— 不看声明的 MIME 类型。
26
+ 3. **重编码。** `normalize()` 对四种原生格式原样放行;其余先解码(XPM、BMP/DIB、SVG 走自带路径,其它交给浏览器),画到画布上(最长边超过 4096 会被缩放),再导出为 `image/png`,文件名改成 `.png`。
27
+ 4. **回投。** `handle()` 在 `[data-composer-card]` 上派发一个携带新 `File` 的合成 `drop` 事件,和真实拖拽走同一条路径;`__dshPasteImageRerouted` 标记防止插件截获自己的事件。
28
+
29
+ 全部逻辑都在客户端。没有宿主进程、不轮询剪贴板、不发网络请求。
30
+
31
+ ## 支持的格式
32
+
33
+ 下表是简版;完整决策流程、BMP 变体网格以及明确不做的格式,见[格式支持参考](docs/formats.md)。
34
+
35
+ | 格式 | 常见声明类型 | 处理方式 |
36
+ | ------------------------ | --------------- | --------------------------------------------------------------------------------------------------------- |
37
+ | PNG | `image/png` | 原样放行,不改写 |
38
+ | JPEG / JFIF | `image/jpeg` | 原样放行,不改写 |
39
+ | WebP | `image/webp` | 原样放行,不改写 |
40
+ | GIF | `image/gif` | 原样放行,不改写 |
41
+ | XPM(XPM3 文本) | `image/xpm` | 由 `decodeXpm()` 解码,重编码为 PNG |
42
+ | BMP / DIB | `image/bmp` | 先交给浏览器解码,失败则用 `decodeBmp()` 兜底:1/4/8/16/24/32 位、RLE4/RLE8、BITFIELDS、OS/2 头与无头 DIB |
43
+ | SVG | `image/svg+xml` | 通过 `<img>` 元素光栅化,重编码为 PNG |
44
+ | ICO / CUR | `image/x-icon` | 先交给浏览器解码,失败则取最大的 PNG 压缩条目 |
45
+ | TIFF | `image/tiff` | 能按魔数识别;仅当浏览器自带 TIFF 解码器时才解码(Chromium 没有),否则原样放行 |
46
+ | AVIF | `image/avif` | Chromium 能解码,重编码为 PNG |
47
+ | HEIC / HEIF 等 `image/*` | `image/...` | 能按魔数识别;浏览器有对应解码器才解码(Chromium 不解 HEIC),否则原样放行 |
48
+
49
+ 只有在「魔数属于四种原生格式」**且**「声明类型与之一致」时才原样放行。字节是 JPEG 却声称 `image/png` 的文件会被重编码成真正的 PNG,声明类型从此骗不了人。声明类型为空的原生文件会按嗅探结果重新包一层 `File`(不重编码);`image/jpg`、`image/x-png`、`image/x-bmp`、`image/x-xpixmap`、`image/svg+xml` 等常见别名视为一致。
50
+
51
+ 一个文件会被纳入处理,条件是 MIME 类型以 `image/` 开头,或文件名以 `.png`、`.jpg`、`.jpeg`、`.jfif`、`.gif`、`.webp`、`.bmp`、`.dib`、`.tif`、`.tiff`、`.xpm`、`.avif`、`.ico`、`.cur`、`.svg`、`.heic`、`.heif` 结尾。同一次粘贴里的非图片文件会原样转发。
52
+
53
+ ## 安装
54
+
55
+ 未发布到 npm,从 GitHub 安装:
56
+
57
+ ```bash
58
+ dsh plugin --profile <profile> add github:pengtang1024/dsh-paste-image
59
+ ```
60
+
61
+ 本地开发时指向你的工作副本:
62
+
63
+ ```bash
64
+ dsh plugin --profile <profile> add file:/absolute/path/to/dsh-paste-image
65
+ ```
66
+
67
+ 把 `<profile>` 换成应用实际使用的 profile。**装完必须重载页面**(`Ctrl+R`,macOS 上是 `Cmd+R`):客户端模块只在渲染进程加载时注入,没重载之前插件不会拦截任何东西。
68
+
69
+ ## 验证
70
+
71
+ 先跑仓库自带检查:
72
+
73
+ ```bash
74
+ cd dsh-paste-image
75
+ npm test
76
+ npm run check
77
+ ```
78
+
79
+ `npm test` 跑 Node 测试(0.2.1 为 16 个用例):魔数嗅探、候选判定、各个 BMP 变体、BMP 冒充 PNG 的转码、无头 DIB、原生 PNG 放行。`npm run check` 对 `client.js` 和 `lib/index.js` 做语法检查。
80
+
81
+ 再验证真实链路:
82
+
83
+ 1. 重载 DSH 窗口。
84
+ 2. 用平时的截图工具截图后粘进输入框,或把图片文件拖进去。
85
+ 3. 附件正常出现。打开开发者工具(`Ctrl+Shift+I`)→ Console,把日志级别切到 **Verbose**,应能看到:
86
+
87
+ ```text
88
+ [dsh-paste-image] image/xpm -> image/png 1440x900
89
+ ```
90
+
91
+ 如果转码失败,插件会保留原文件并打印 `keep original (...)`。
92
+
93
+ ## 限制
94
+
95
+ - **XPM:** 只支持 XPM3 文本格式。解析器只读 `c` 颜色键,`m`、`g`、`s` 等键会被忽略;颜色交给浏览器的 CSS 解析器,调色板里带空格的名字(如 `light gray`)不是合法 CSS,会退化为不透明黑色。
96
+ - **BMP:** 支持 1/4/8/16/24/32 位、`BI_RGB`/`BI_RLE8`/`BI_RLE4`/`BI_BITFIELDS`/`BI_ALPHABITFIELDS`、core/扩展头/V4/V5/OS/2 头,以及无文件头的 DIB。2 位和 64 位像素格式不支持。32 位图若没有声明 alpha 掩码,且整幅图 alpha 全为 0,会按不透明处理,不再导出全透明 PNG。
97
+ - **其它编解码器:** SVG 由插件自己光栅化;ICO/CUR 会回退到 PNG 压缩条目;AVIF 依赖浏览器解码器。TIFF 和 HEIC 能被识别,但 Chromium 没有对应解码器,会原样放行、宿主仍然拒绝。插件不捆绑任何第三方解码库。
98
+ - **尺寸:** 转码后的图片最长边会被缩到不超过 4096 px;原生放行的文件不做任何缩放。
99
+ - **数量:** 一次粘贴或拖入最多 8 个文件,超过就整批交回原生路径。
100
+ - **扁平化:** 转码结果是一帧 PNG,动画、EXIF 元数据和内嵌色彩配置都不会保留。
101
+ - **范围:** 只覆盖 `paste` 与 `drop`;文件选择器等其它入口保持原生行为。
102
+
103
+ ## 安全与隐私
104
+
105
+ - 全部逻辑运行在渲染进程,不发网络请求、不上传、不落盘。
106
+ - 没有后台进程、不轮询剪贴板、不修改 DSH 宿主代码。
107
+ - 图片字节只从 paste 或 drop 事件读取,本地解码后交回同一窗口。
108
+ - 解码器很小,但确实在渲染进程里处理不可信输入。发现崩溃或解析问题请见 [SECURITY.md](SECURITY.md)。
109
+
110
+ ## 文档
111
+
112
+ - [实现原理](docs/how-it-works.md) —— 事件流、解码器内部实现、逐函数代码地图。
113
+ - [格式支持](docs/formats.md) —— 决策流程、格式矩阵、BMP 变体与新增格式清单。
114
+ - [常见问题](docs/troubleshooting.md) —— 典型故障与日志查看方法。
115
+ - [发版流程](docs/releasing.md) —— 版本策略与维护者发布清单。
116
+
117
+ ## 社区
118
+
119
+ - [贡献指南](CONTRIBUTING.md) —— 开发环境、测试、代码风格与格式贡献要求。
120
+ - [行为准则](CODE_OF_CONDUCT.md) —— Contributor Covenant 2.1。
121
+ - [安全策略](SECURITY.md) —— 私下报告、影响范围与支持版本。
122
+ - [更新日志](CHANGELOG.md) 与[发布记录](https://github.com/pengtang1024/dsh-paste-image/releases) —— 改了什么、为什么改。
123
+ - [Issues](https://github.com/pengtang1024/dsh-paste-image/issues) —— 缺陷报告与格式需求。
124
+
125
+ ## 许可证
126
+
127
+ MIT © 2026 pengtang1024,见 [LICENSE](LICENSE)。
package/client.js ADDED
@@ -0,0 +1,717 @@
1
+ ;(function () {
2
+ 'use strict'
3
+
4
+ var NATIVE_TYPES = ['image/png', 'image/jpeg', 'image/webp', 'image/gif']
5
+ var NATIVE_SET = new Set(NATIVE_TYPES)
6
+ var NATIVE_EXT = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp', 'image/gif': 'gif' }
7
+ var MIME_ALIAS = {
8
+ 'image/jpg': 'image/jpeg',
9
+ 'image/pjpeg': 'image/jpeg',
10
+ 'image/x-png': 'image/png',
11
+ 'image/x-bmp': 'image/bmp',
12
+ 'image/x-ms-bmp': 'image/bmp',
13
+ 'image/x-win-bitmap': 'image/bmp',
14
+ 'image/vnd.microsoft.icon': 'image/x-icon',
15
+ 'image/x-xpixmap': 'image/xpm',
16
+ 'image/x-xpm': 'image/xpm',
17
+ 'image/svg+xml': 'image/svg',
18
+ }
19
+ var IMAGE_EXT = /\.(png|jpe?g|jfif|gif|webp|bmp|dib|tiff?|xpm|avif|ico|cur|svg|heic|heif)$/i
20
+ var MAX_SIDE = 4096
21
+ var MAX_FILES = 8
22
+ var MAX_PIXELS = 64 * 1024 * 1024
23
+ var REROUTED = '__dshPasteImageRerouted'
24
+ var BMP_HEADERS = { 12: true, 40: true, 52: true, 56: true, 64: true, 108: true, 124: true }
25
+ var HEIC_BRANDS = { heic: true, heix: true, heis: true, heim: true, hevc: true, hevx: true, mif1: true, msf1: true }
26
+ var BMP_BPPS = { 1: true, 4: true, 8: true, 16: true, 24: true, 32: true }
27
+ var BMP_COMPRESSION = { 0: true, 1: true, 2: true, 3: true, 4: true, 5: true, 6: true }
28
+
29
+ function ascii(bytes, start, len) {
30
+ var out = ''
31
+ for (var i = start; i < start + len && i < bytes.length; i++) out += String.fromCharCode(bytes[i])
32
+ return out
33
+ }
34
+
35
+ function unit32(bytes, offset) {
36
+ return (bytes[offset] | (bytes[offset + 1] << 8) | (bytes[offset + 2] << 16) | (bytes[offset + 3] << 24)) >>> 0
37
+ }
38
+
39
+ function aliasMime(type) {
40
+ return MIME_ALIAS[type] || type
41
+ }
42
+
43
+ // 无文件头的 DIB(BITMAPINFOHEADER 起步,Windows CF_DIB 形状)。
44
+ function dibHeaderSize(bytes) {
45
+ if (bytes.length < 16) return 0
46
+ var size = unit32(bytes, 0)
47
+ if (!BMP_HEADERS[size]) return 0
48
+ if (size === 12) {
49
+ var width = bytes[4] | (bytes[5] << 8)
50
+ var height = bytes[6] | (bytes[7] << 8)
51
+ var planes = bytes[8] | (bytes[9] << 8)
52
+ var bpp = bytes[10] | (bytes[11] << 8)
53
+ return width > 0 && height > 0 && planes === 1 && (bpp === 1 || bpp === 4 || bpp === 8 || bpp === 24) ? size : 0
54
+ }
55
+ if (bytes.length < 20) return 0
56
+ var w = unit32(bytes, 4) | 0
57
+ var h = unit32(bytes, 8) | 0
58
+ var pl = bytes[12] | (bytes[13] << 8)
59
+ var bits = bytes[14] | (bytes[15] << 8)
60
+ var compression = unit32(bytes, 16)
61
+ if (!(w > 0) || h === 0 || pl !== 1 || !BMP_BPPS[bits]) return 0
62
+ if (compression !== 0 && compression !== 1 && compression !== 2 && compression !== 3 && compression !== 6) return 0
63
+ return w * Math.abs(h) > MAX_PIXELS ? 0 : size
64
+ }
65
+
66
+ function looksLikeSvg(bytes) {
67
+ var head = new TextDecoder('utf-8', { fatal: false }).decode(bytes.subarray(0, Math.min(bytes.length, 1024)))
68
+ head = head.replace(/^\uFEFF/, '').replace(/^\s+/, '')
69
+ if (head.charAt(0) !== '<') return false
70
+ return /<svg[\s>]/i.test(head)
71
+ }
72
+
73
+ function sniff(bytes) {
74
+ if (
75
+ bytes.length >= 8 &&
76
+ bytes[0] === 0x89 &&
77
+ bytes[1] === 0x50 &&
78
+ bytes[2] === 0x4e &&
79
+ bytes[3] === 0x47 &&
80
+ bytes[4] === 0x0d &&
81
+ bytes[5] === 0x0a &&
82
+ bytes[6] === 0x1a &&
83
+ bytes[7] === 0x0a
84
+ )
85
+ return 'image/png'
86
+ if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg'
87
+ if (bytes.length >= 6 && ascii(bytes, 0, 3) === 'GIF') return 'image/gif'
88
+ if (bytes.length >= 12 && ascii(bytes, 0, 4) === 'RIFF' && ascii(bytes, 8, 4) === 'WEBP') return 'image/webp'
89
+ if (bytes.length >= 2 && bytes[0] === 0x42 && bytes[1] === 0x4d) return 'image/bmp'
90
+ if (
91
+ bytes.length >= 4 &&
92
+ ((bytes[0] === 0x49 && bytes[1] === 0x49 && bytes[2] === 0x2a && bytes[3] === 0) ||
93
+ (bytes[0] === 0x4d && bytes[1] === 0x4d && bytes[2] === 0 && bytes[3] === 0x2a))
94
+ )
95
+ return 'image/tiff'
96
+ if (bytes.length >= 9 && ascii(bytes, 0, 9).toLowerCase() === '/* xpm */') return 'image/xpm'
97
+ if (bytes.length >= 12 && ascii(bytes, 4, 4) === 'ftyp') {
98
+ var brand = ascii(bytes, 8, 4).toLowerCase()
99
+ if (brand === 'avif' || brand === 'avis') return 'image/avif'
100
+ if (HEIC_BRANDS[brand]) return 'image/heic'
101
+ }
102
+ if (bytes.length >= 4 && bytes[0] === 0 && bytes[1] === 0 && (bytes[2] === 1 || bytes[2] === 2) && bytes[3] === 0)
103
+ return 'image/x-icon'
104
+ if (looksLikeSvg(bytes)) return 'image/svg'
105
+ if (dibHeaderSize(bytes)) return 'image/bmp'
106
+ return null
107
+ }
108
+
109
+ // ---------- XPM ----------
110
+
111
+ function xpmStrings(text) {
112
+ var out = []
113
+ var re = /"((?:[^"\\]|\\.)*)"/g
114
+ var m
115
+ while ((m = re.exec(text)) !== null) {
116
+ out.push(m[1].replace(/\\"/g, '"').replace(/\\\\/g, '\\').replace(/\\n/g, '\n').replace(/\\t/g, '\t'))
117
+ }
118
+ return out
119
+ }
120
+
121
+ // 用 canvas 把任意 CSS 颜色解析成 RGBA,顺带支持命名色与 4/8/12 位十六进制。
122
+ function resolveColor(color) {
123
+ if (!color || color === 'None') return [0, 0, 0, 0]
124
+ var c = document.createElement('canvas')
125
+ c.width = 1
126
+ c.height = 1
127
+ var ctx = c.getContext('2d')
128
+ ctx.clearRect(0, 0, 1, 1)
129
+ ctx.fillStyle = '#000000'
130
+ ctx.fillStyle = color
131
+ var filled = ctx.fillStyle
132
+ if (
133
+ typeof filled === 'string' &&
134
+ filled === '#000000' &&
135
+ color.toLowerCase() !== '#000000' &&
136
+ color.toLowerCase() !== 'black'
137
+ ) {
138
+ return null
139
+ }
140
+ ctx.fillRect(0, 0, 1, 1)
141
+ var d = ctx.getImageData(0, 0, 1, 1).data
142
+ return [d[0], d[1], d[2], d[3]]
143
+ }
144
+
145
+ function decodeXpm(text) {
146
+ var strings = xpmStrings(text.replace(/^\uFEFF/, ''))
147
+ if (strings.length < 2) throw new Error('xpm: no strings')
148
+ var head = strings[0].trim().split(/\s+/).map(Number)
149
+ var width = head[0]
150
+ var height = head[1]
151
+ var colors = head[2]
152
+ var cpp = head[3] || 1
153
+ if (!(width > 0 && height > 0 && colors > 0)) throw new Error('xpm: bad header ' + strings[0])
154
+ if (width * height > MAX_PIXELS) throw new Error('xpm: too large')
155
+
156
+ var palette = new Map()
157
+ for (var i = 1; i <= colors; i++) {
158
+ var line = strings[i] || ''
159
+ var key = line.slice(0, cpp)
160
+ var rest = line.slice(cpp)
161
+ var m = /\bc\s+([^\s]+(?:\s+[^\s]+)?)/.exec(rest)
162
+ var raw = m ? m[1].trim() : '#000000'
163
+ palette.set(key, resolveColor(raw) || [0, 0, 0, 255])
164
+ }
165
+
166
+ var canvas = document.createElement('canvas')
167
+ canvas.width = width
168
+ canvas.height = height
169
+ var ctx = canvas.getContext('2d')
170
+ var image = ctx.createImageData(width, height)
171
+ var data = image.data
172
+ for (var y = 0; y < height; y++) {
173
+ var row = strings[1 + colors + y] || ''
174
+ for (var x = 0; x < width; x++) {
175
+ var k = row.slice(x * cpp, (x + 1) * cpp)
176
+ var rgba = palette.get(k) || [0, 0, 0, 0]
177
+ var o = (y * width + x) * 4
178
+ data[o] = rgba[0]
179
+ data[o + 1] = rgba[1]
180
+ data[o + 2] = rgba[2]
181
+ data[o + 3] = rgba[3]
182
+ }
183
+ }
184
+ ctx.putImageData(image, 0, 0)
185
+ return canvas
186
+ }
187
+
188
+ // ---------- BMP / DIB ----------
189
+
190
+ function parseBmp(bytes) {
191
+ var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
192
+ var file = bytes.length >= 18 && dv.getUint16(0, true) === 0x4d42
193
+ var p = file ? 14 : 0
194
+ if (bytes.length < p + 16) throw new Error('bmp: truncated header')
195
+ var headerSize = dv.getUint32(p, true)
196
+ if (!BMP_HEADERS[headerSize]) throw new Error('bmp: unsupported header ' + headerSize)
197
+ var info = {
198
+ headerSize: headerSize,
199
+ width: 0,
200
+ height: 0,
201
+ bpp: 0,
202
+ compression: 0,
203
+ clrUsed: 0,
204
+ imageSize: 0,
205
+ paletteStride: headerSize === 12 ? 3 : 4,
206
+ paletteOffset: p + headerSize,
207
+ masks: null,
208
+ offset: 0,
209
+ }
210
+ if (headerSize === 12) {
211
+ info.width = dv.getUint16(p + 4, true)
212
+ info.height = dv.getInt16(p + 6, true)
213
+ info.bpp = dv.getUint16(p + 10, true)
214
+ if (info.bpp !== 1 && info.bpp !== 4 && info.bpp !== 8 && info.bpp !== 24)
215
+ throw new Error('bmp: core header bpp ' + info.bpp)
216
+ } else {
217
+ info.width = dv.getInt32(p + 4, true)
218
+ info.height = dv.getInt32(p + 8, true)
219
+ info.bpp = dv.getUint16(p + 14, true)
220
+ info.compression = dv.getUint32(p + 16, true)
221
+ info.imageSize = dv.getUint32(p + 20, true)
222
+ info.clrUsed = dv.getUint32(p + 32, true)
223
+ // BI_CMYK and friends (11/12/13) are not decoded; refuse instead of guessing channel order.
224
+ if (!BMP_COMPRESSION[info.compression]) throw new Error('bmp: unsupported compression ' + info.compression)
225
+ }
226
+ if (!(info.width > 0) || info.height === 0) throw new Error('bmp: bad dimensions')
227
+ if (info.width * Math.abs(info.height) > MAX_PIXELS) throw new Error('bmp: too large')
228
+ if (!BMP_BPPS[info.bpp]) throw new Error('bmp: unsupported bpp ' + info.bpp)
229
+
230
+ var maskBytes = 0
231
+ if (info.compression === 3 || info.compression === 6) {
232
+ var mo = p + 40
233
+ if (mo + 12 > bytes.length) throw new Error('bmp: truncated masks')
234
+ info.masks = [dv.getUint32(mo, true), dv.getUint32(mo + 4, true), dv.getUint32(mo + 8, true)]
235
+ if (info.compression === 6 && mo + 16 <= bytes.length) info.masks.push(dv.getUint32(mo + 12, true))
236
+ if (headerSize === 40) maskBytes = info.compression === 6 ? 16 : 12
237
+ }
238
+
239
+ if (file) {
240
+ info.offset = dv.getUint32(10, true)
241
+ } else {
242
+ var paletteBytes = info.bpp <= 8 ? (info.clrUsed || 1 << info.bpp) * info.paletteStride : 0
243
+ info.offset = p + headerSize + maskBytes + paletteBytes
244
+ }
245
+ if (info.offset > bytes.length) throw new Error('bmp: bad pixel offset')
246
+ return info
247
+ }
248
+
249
+ function maskChannel(mask) {
250
+ if (!mask) return null
251
+ var m = mask >>> 0
252
+ var shift = 0
253
+ while (shift < 32 && ((m >>> shift) & 1) === 0) shift++
254
+ if (shift === 32) return null
255
+ return { shift: shift, max: m >>> shift, mask: m }
256
+ }
257
+
258
+ function maskValue(value, channel) {
259
+ if (!channel) return 0
260
+ var v = (value & channel.mask) >>> channel.shift
261
+ return channel.max === 255 ? v : Math.round((v * 255) / channel.max)
262
+ }
263
+
264
+ function bmpPalette(bytes, info) {
265
+ var palette = new Uint8Array(256 * 4)
266
+ for (var a = 0; a < 256; a++) palette[a * 4 + 3] = 255
267
+ var count = Math.min(info.bpp <= 8 ? info.clrUsed || 1 << info.bpp : 0, 256)
268
+ for (var i = 0; i < count; i++) {
269
+ var po = info.paletteOffset + i * info.paletteStride
270
+ if (po + 3 > bytes.length) break
271
+ palette[i * 4] = bytes[po + 2]
272
+ palette[i * 4 + 1] = bytes[po + 1]
273
+ palette[i * 4 + 2] = bytes[po]
274
+ if (info.paletteStride === 4 && bytes[po + 3]) palette[i * 4 + 3] = bytes[po + 3]
275
+ }
276
+ return palette
277
+ }
278
+
279
+ function putIndexed(data, width, x, y, index, palette) {
280
+ var o = (y * width + x) * 4
281
+ data[o] = palette[index * 4]
282
+ data[o + 1] = palette[index * 4 + 1]
283
+ data[o + 2] = palette[index * 4 + 2]
284
+ data[o + 3] = palette[index * 4 + 3]
285
+ }
286
+
287
+ function decodeRleBmp(bytes, info, data, width, height, topDown, palette) {
288
+ var rle4 = info.compression === 2
289
+ var x = 0
290
+ var y = 0
291
+ var i = info.offset
292
+ while (i + 1 < bytes.length) {
293
+ var count = bytes[i++]
294
+ var value = bytes[i++]
295
+ if (count > 0) {
296
+ for (var k = 0; k < count; k++) {
297
+ if (x < width && y < height) {
298
+ var idx = rle4 ? (k % 2 === 0 ? value >> 4 : value & 0x0f) : value
299
+ putIndexed(data, width, x, topDown ? y : height - 1 - y, idx, palette)
300
+ }
301
+ x++
302
+ }
303
+ } else if (value === 0) {
304
+ x = 0
305
+ y++
306
+ if (y >= height) break
307
+ } else if (value === 1) {
308
+ break
309
+ } else if (value === 2) {
310
+ if (i + 1 >= bytes.length) break
311
+ x += bytes[i++]
312
+ y += bytes[i++]
313
+ if (y >= height) break
314
+ } else {
315
+ var n = value
316
+ var used = 0
317
+ if (rle4) {
318
+ var pairs = (n + 1) >> 1
319
+ for (var j = 0; j < pairs && i < bytes.length; j++) {
320
+ var b = bytes[i++]
321
+ used++
322
+ if (x < width && y < height) {
323
+ putIndexed(data, width, x, topDown ? y : height - 1 - y, b >> 4, palette)
324
+ }
325
+ x++
326
+ if (j * 2 + 1 < n) {
327
+ if (x < width && y < height) {
328
+ putIndexed(data, width, x, topDown ? y : height - 1 - y, b & 0x0f, palette)
329
+ }
330
+ x++
331
+ }
332
+ }
333
+ } else {
334
+ for (var m = 0; m < n && i < bytes.length; m++) {
335
+ var v = bytes[i++]
336
+ used++
337
+ if (x < width && y < height) {
338
+ putIndexed(data, width, x, topDown ? y : height - 1 - y, v, palette)
339
+ }
340
+ x++
341
+ }
342
+ }
343
+ if (used & 1) i++
344
+ }
345
+ if (y >= height) break
346
+ }
347
+ }
348
+
349
+ function decodeBmp(bytes) {
350
+ var info = parseBmp(bytes)
351
+ var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
352
+ var width = info.width
353
+ var topDown = info.height < 0
354
+ var height = topDown ? -info.height : info.height
355
+ var bpp = info.bpp
356
+ if (info.compression === 4 || info.compression === 5) throw new Error('bmp: embedded payload')
357
+
358
+ var canvas = document.createElement('canvas')
359
+ canvas.width = width
360
+ canvas.height = height
361
+ var ctx = canvas.getContext('2d')
362
+ var image = ctx.createImageData(width, height)
363
+ var data = image.data
364
+
365
+ if (info.compression === 1 || info.compression === 2) {
366
+ decodeRleBmp(bytes, info, data, width, height, topDown, bmpPalette(bytes, info))
367
+ } else if (bpp <= 8) {
368
+ var palette = bmpPalette(bytes, info)
369
+ var stride = ((bpp * width + 31) >> 5) << 2
370
+ for (var y = 0; y < height; y++) {
371
+ var srcRow = info.offset + (topDown ? y : height - 1 - y) * stride
372
+ if (srcRow + stride > bytes.length) throw new Error('bmp: truncated pixels')
373
+ for (var x = 0; x < width; x++) {
374
+ var idx
375
+ if (bpp === 8) idx = bytes[srcRow + x]
376
+ else if (bpp === 4) idx = (bytes[srcRow + (x >> 1)] >> (x & 1 ? 0 : 4)) & 0x0f
377
+ else idx = (bytes[srcRow + (x >> 3)] >> (7 - (x & 7))) & 1
378
+ putIndexed(data, width, x, y, idx, palette)
379
+ }
380
+ }
381
+ } else if (bpp === 16) {
382
+ var masks16 = info.masks && info.masks[0] | info.masks[1] | info.masks[2] ? info.masks : [0x7c00, 0x03e0, 0x001f]
383
+ var rc = maskChannel(masks16[0])
384
+ var gc = maskChannel(masks16[1])
385
+ var bc = maskChannel(masks16[2])
386
+ var stride16 = ((16 * width + 31) >> 5) << 2
387
+ for (var y16 = 0; y16 < height; y16++) {
388
+ var row16 = info.offset + (topDown ? y16 : height - 1 - y16) * stride16
389
+ if (row16 + stride16 > bytes.length) throw new Error('bmp: truncated pixels')
390
+ for (var x16 = 0; x16 < width; x16++) {
391
+ var v16 = dv.getUint16(row16 + x16 * 2, true)
392
+ var o16 = (y16 * width + x16) * 4
393
+ data[o16] = maskValue(v16, rc)
394
+ data[o16 + 1] = maskValue(v16, gc)
395
+ data[o16 + 2] = maskValue(v16, bc)
396
+ data[o16 + 3] = 255
397
+ }
398
+ }
399
+ } else if (bpp === 24) {
400
+ var stride24 = ((24 * width + 31) >> 5) << 2
401
+ for (var y24 = 0; y24 < height; y24++) {
402
+ var row24 = info.offset + (topDown ? y24 : height - 1 - y24) * stride24
403
+ if (row24 + stride24 > bytes.length) throw new Error('bmp: truncated pixels')
404
+ for (var x24 = 0; x24 < width; x24++) {
405
+ var s24 = row24 + x24 * 3
406
+ var o24 = (y24 * width + x24) * 4
407
+ data[o24] = bytes[s24 + 2]
408
+ data[o24 + 1] = bytes[s24 + 1]
409
+ data[o24 + 2] = bytes[s24]
410
+ data[o24 + 3] = 255
411
+ }
412
+ }
413
+ } else {
414
+ var masks32 = info.masks && info.masks[0] | info.masks[1] | info.masks[2] ? info.masks : null
415
+ var r32 = masks32 ? maskChannel(masks32[0]) : null
416
+ var g32 = masks32 ? maskChannel(masks32[1]) : null
417
+ var b32 = masks32 ? maskChannel(masks32[2]) : null
418
+ var a32 = masks32 && masks32[3] ? maskChannel(masks32[3]) : null
419
+ var anyAlpha = false
420
+ for (var y32 = 0; y32 < height; y32++) {
421
+ var row32 = info.offset + (topDown ? y32 : height - 1 - y32) * width * 4
422
+ if (row32 + width * 4 > bytes.length) throw new Error('bmp: truncated pixels')
423
+ for (var x32 = 0; x32 < width; x32++) {
424
+ var s32 = row32 + x32 * 4
425
+ var o32 = (y32 * width + x32) * 4
426
+ if (masks32) {
427
+ var v32 = dv.getUint32(s32, true)
428
+ data[o32] = maskValue(v32, r32)
429
+ data[o32 + 1] = maskValue(v32, g32)
430
+ data[o32 + 2] = maskValue(v32, b32)
431
+ data[o32 + 3] = a32 ? maskValue(v32, a32) : 255
432
+ } else {
433
+ var a = bytes[s32 + 3]
434
+ data[o32] = bytes[s32 + 2]
435
+ data[o32 + 1] = bytes[s32 + 1]
436
+ data[o32 + 2] = bytes[s32]
437
+ data[o32 + 3] = a
438
+ if (a) anyAlpha = true
439
+ }
440
+ }
441
+ }
442
+ // 很多编码器把 32 位 BMP 的 alpha 全留成 0;整幅图都没有非零 alpha 时按不透明处理,
443
+ // 否则粘贴出来的 PNG 会整张透明。
444
+ if (!masks32 && !anyAlpha) for (var q = 3; q < data.length; q += 4) data[q] = 255
445
+ }
446
+ ctx.putImageData(image, 0, 0)
447
+ return canvas
448
+ }
449
+
450
+ function bmpEmbedded(bytes) {
451
+ var info
452
+ try {
453
+ info = parseBmp(bytes)
454
+ } catch (error) {
455
+ return null
456
+ }
457
+ if (info.compression !== 4 && info.compression !== 5) return null
458
+ var start = info.offset
459
+ var length = info.imageSize || bytes.length - start
460
+ if (start + length > bytes.length) length = bytes.length - start
461
+ var payload = bytes.subarray(start, start + length)
462
+ var kind = sniff(payload)
463
+ return kind === 'image/png' || kind === 'image/jpeg' ? { type: kind, data: payload } : null
464
+ }
465
+
466
+ // ---------- SVG / ICO ----------
467
+
468
+ function svgSize(text) {
469
+ var w = /<svg[^>]*\bwidth\s*=\s*["']\s*([\d.]+)/i.exec(text)
470
+ var h = /<svg[^>]*\bheight\s*=\s*["']\s*([\d.]+)/i.exec(text)
471
+ var box = /viewBox\s*=\s*["']\s*[-\d.]+[\s,]+[-\d.]+[\s,]+([\d.]+)[\s,]+([\d.]+)/i.exec(text)
472
+ return {
473
+ width: w ? Number(w[1]) : box ? Number(box[1]) : 0,
474
+ height: h ? Number(h[1]) : box ? Number(box[2]) : 0,
475
+ }
476
+ }
477
+
478
+ function loadSvg(bytes) {
479
+ return new Promise(function (resolve, reject) {
480
+ if (typeof Image === 'undefined') throw new Error('svg: no Image')
481
+ var text = new TextDecoder('utf-8', { fatal: false }).decode(bytes)
482
+ var url = URL.createObjectURL(new Blob([text], { type: 'image/svg+xml' }))
483
+ var size = svgSize(text)
484
+ var img = new Image()
485
+ var finish = function (fn, value) {
486
+ URL.revokeObjectURL(url)
487
+ fn(value)
488
+ }
489
+ img.onload = function () {
490
+ finish(resolve, {
491
+ image: img,
492
+ width: img.naturalWidth || size.width || 300,
493
+ height: img.naturalHeight || size.height || 150,
494
+ })
495
+ }
496
+ img.onerror = function () {
497
+ finish(reject, new Error('svg: decode failed'))
498
+ }
499
+ img.src = url
500
+ })
501
+ }
502
+
503
+ function icoPngEntry(bytes) {
504
+ if (bytes.length < 6) return null
505
+ var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
506
+ if (dv.getUint16(0, true) !== 0 || dv.getUint16(2, true) !== 1) return null
507
+ var count = dv.getUint16(4, true)
508
+ var best = null
509
+ var bestArea = -1
510
+ for (var i = 0; i < count; i++) {
511
+ var e = 6 + i * 16
512
+ if (e + 16 > bytes.length) break
513
+ var w = bytes[e] || 256
514
+ var h = bytes[e + 1] || 256
515
+ var size = dv.getUint32(e + 8, true)
516
+ var off = dv.getUint32(e + 12, true)
517
+ if (!size || off + 8 > bytes.length || off + size > bytes.length) continue
518
+ if (sniff(bytes.subarray(off, off + 8)) !== 'image/png') continue
519
+ if (w * h > bestArea) {
520
+ bestArea = w * h
521
+ best = bytes.subarray(off, off + size)
522
+ }
523
+ }
524
+ return best
525
+ }
526
+
527
+ // ---------- 规范化 ----------
528
+
529
+ function canvasOf(source, width, height) {
530
+ var w = width || source.width || source.naturalWidth || 1
531
+ var h = height || source.height || source.naturalHeight || 1
532
+ var scale = Math.min(1, MAX_SIDE / Math.max(w, h))
533
+ var canvas = document.createElement('canvas')
534
+ canvas.width = Math.max(1, Math.round(w * scale))
535
+ canvas.height = Math.max(1, Math.round(h * scale))
536
+ canvas.getContext('2d').drawImage(source, 0, 0, canvas.width, canvas.height)
537
+ return canvas
538
+ }
539
+
540
+ function toPngBlob(canvas) {
541
+ return new Promise(function (resolve, reject) {
542
+ canvas.toBlob(function (blob) {
543
+ blob ? resolve(blob) : reject(new Error('canvas.toBlob failed'))
544
+ }, 'image/png')
545
+ })
546
+ }
547
+
548
+ async function toCanvas(file, bytes, kind) {
549
+ if (kind === 'image/xpm') {
550
+ return canvasOf(decodeXpm(new TextDecoder('utf-8', { fatal: false }).decode(bytes)))
551
+ }
552
+ if (kind === 'image/svg') {
553
+ var svg = await loadSvg(bytes)
554
+ return canvasOf(svg.image, svg.width, svg.height)
555
+ }
556
+ var type = kind || aliasMime((file.type || '').toLowerCase()) || 'application/octet-stream'
557
+ try {
558
+ var bitmap = await createImageBitmap(new Blob([bytes], { type: type }))
559
+ return canvasOf(bitmap)
560
+ } catch (error) {
561
+ if (kind === 'image/bmp') {
562
+ var embedded = bmpEmbedded(bytes)
563
+ if (embedded) {
564
+ var inner = await createImageBitmap(new Blob([embedded.data], { type: embedded.type }))
565
+ return canvasOf(inner)
566
+ }
567
+ return canvasOf(decodeBmp(bytes))
568
+ }
569
+ if (kind === 'image/x-icon') {
570
+ var png = icoPngEntry(bytes)
571
+ if (!png) throw error
572
+ var icon = await createImageBitmap(new Blob([png], { type: 'image/png' }))
573
+ return canvasOf(icon)
574
+ }
575
+ throw error
576
+ }
577
+ }
578
+
579
+ function fileName(file, ext) {
580
+ var base = (file.name || 'image').replace(/\.[^.]+$/, '')
581
+ return base + '.' + ext
582
+ }
583
+
584
+ async function normalize(file) {
585
+ var bytes = new Uint8Array(await file.arrayBuffer())
586
+ var kind = sniff(bytes)
587
+ var declared = aliasMime((file.type || '').toLowerCase())
588
+ if (kind && NATIVE_SET.has(kind)) {
589
+ if (declared === kind) return null
590
+ if (!declared) {
591
+ return {
592
+ file: new File([bytes], fileName(file, NATIVE_EXT[kind]), { type: kind }),
593
+ from: '(no type)',
594
+ to: kind,
595
+ width: 0,
596
+ height: 0,
597
+ }
598
+ }
599
+ }
600
+ var canvas = await toCanvas(file, bytes, kind)
601
+ var blob = await toPngBlob(canvas)
602
+ return {
603
+ file: new File([blob], fileName(file, 'png'), { type: 'image/png' }),
604
+ from: declared || '(no type)',
605
+ to: 'image/png',
606
+ width: canvas.width,
607
+ height: canvas.height,
608
+ }
609
+ }
610
+
611
+ // ---------- 事件桥 ----------
612
+
613
+ function isImageCandidate(file) {
614
+ if (!file) return false
615
+ var type = (file.type || '').toLowerCase()
616
+ if (type.indexOf('image/') === 0) return true
617
+ return IMAGE_EXT.test(file.name || '')
618
+ }
619
+
620
+ function composer() {
621
+ return document.querySelector('[data-composer-card]') || document.body
622
+ }
623
+
624
+ function reroute(files) {
625
+ var dt = new DataTransfer()
626
+ files.forEach(function (file) {
627
+ dt.items.add(file)
628
+ })
629
+ var event = new DragEvent('drop', { bubbles: true, cancelable: true, composed: true, dataTransfer: dt })
630
+ Object.defineProperty(event, REROUTED, { value: true })
631
+ composer().dispatchEvent(event)
632
+ }
633
+
634
+ async function handle(event, data) {
635
+ if (!data || event[REROUTED]) return
636
+ var files = Array.prototype.slice.call(data.files || [])
637
+ if (files.length === 0 || files.length > MAX_FILES) return
638
+ if (!files.some(isImageCandidate)) return
639
+ event.preventDefault()
640
+ event.stopPropagation()
641
+ var out = []
642
+ for (var i = 0; i < files.length; i++) {
643
+ var file = files[i]
644
+ if (!isImageCandidate(file)) {
645
+ out.push(file)
646
+ continue
647
+ }
648
+ try {
649
+ var converted = await normalize(file)
650
+ out.push(converted ? converted.file : file)
651
+ if (converted)
652
+ console.debug(
653
+ '[dsh-paste-image] ' +
654
+ converted.from +
655
+ ' -> ' +
656
+ converted.to +
657
+ (converted.width ? ' ' + converted.width + 'x' + converted.height : ''),
658
+ )
659
+ } catch (error) {
660
+ out.push(file)
661
+ console.debug(
662
+ '[dsh-paste-image] keep original (' +
663
+ (file.type || 'no type') +
664
+ '): ' +
665
+ (error && error.message ? error.message : String(error)),
666
+ )
667
+ }
668
+ }
669
+ reroute(out)
670
+ }
671
+
672
+ function install() {
673
+ document.addEventListener(
674
+ 'paste',
675
+ function (event) {
676
+ void handle(event, event.clipboardData)
677
+ },
678
+ true,
679
+ )
680
+ document.addEventListener(
681
+ 'drop',
682
+ function (event) {
683
+ void handle(event, event.dataTransfer)
684
+ },
685
+ true,
686
+ )
687
+ return function () {}
688
+ }
689
+
690
+ var api = {
691
+ sniff: sniff,
692
+ decodeXpm: decodeXpm,
693
+ decodeBmp: decodeBmp,
694
+ normalize: normalize,
695
+ isImageCandidate: isImageCandidate,
696
+ install: install,
697
+ }
698
+
699
+ if (typeof window !== 'undefined' && window.__ModuleLoader__ && typeof window.__ModuleLoader__.load === 'function') {
700
+ window.__ModuleLoader__.load({
701
+ id: 'dsh-paste-image',
702
+ factory: function () {
703
+ return {
704
+ apply: function (ctx) {
705
+ if (ctx && typeof ctx.effect === 'function') {
706
+ ctx.effect(install, 'paste-image')
707
+ return
708
+ }
709
+ install()
710
+ },
711
+ }
712
+ },
713
+ })
714
+ }
715
+
716
+ if (typeof module !== 'undefined' && module.exports) module.exports = api
717
+ })()
@@ -0,0 +1,5 @@
1
+ # Mount the plugin on the Host side; the actual work happens in the renderer.
2
+ - insert:
3
+ - id: paste-image
4
+ name: dsh-paste-image
5
+ config: {}
package/lib/index.js ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Host half of dsh-paste-image.
3
+ *
4
+ * The plugin works entirely inside the browser renderer: it intercepts pasted and
5
+ * dropped images, decodes the ones the Host refuses (BMP / XPM / TIFF / lying
6
+ * MIME types), re-encodes them as PNG and hands them back through a synthetic
7
+ * drop event. Nothing runs on the Host, so there is no polling and no child
8
+ * process.
9
+ */
10
+ export function apply() {}
package/package.json CHANGED
@@ -1,6 +1,68 @@
1
1
  {
2
2
  "name": "dsh-paste-image",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.1",
4
+ "description": "Paste any image into DeepSeek Harness: converts XPM/BMP/DIB/SVG/TIFF/etc. and MIME-lying images to real PNG in the renderer.",
5
+ "keywords": [
6
+ "dsh",
7
+ "dsh-plugin",
8
+ "deepseek-harness",
9
+ "clipboard",
10
+ "paste",
11
+ "image",
12
+ "xpm",
13
+ "bmp",
14
+ "dib",
15
+ "svg",
16
+ "png",
17
+ "wayland"
18
+ ],
19
+ "private": false,
20
+ "type": "module",
21
+ "main": "./lib/index.js",
22
+ "exports": {
23
+ ".": "./lib/index.js",
24
+ "./client": "./client.js",
25
+ "./package.json": "./package.json"
26
+ },
27
+ "files": [
28
+ "client.js",
29
+ "lib",
30
+ "cordis.patch.yml",
31
+ "README.md",
32
+ "README.zh.md",
33
+ "LICENSE",
34
+ "CHANGELOG.md"
35
+ ],
36
+ "dsh": {
37
+ "bundle": {
38
+ "patch": "./cordis.patch.yml"
39
+ },
40
+ "client": {
41
+ "platform": "web",
42
+ "inject": []
43
+ }
44
+ },
45
+ "scripts": {
46
+ "test": "node --test tests/*.test.mjs",
47
+ "check": "node --check client.js && node --check lib/index.js",
48
+ "format": "npx --yes prettier@3 --write .",
49
+ "format:check": "npx --yes prettier@3 --check .",
50
+ "prepublishOnly": "npm test && npm run check"
51
+ },
52
+ "publishConfig": {
53
+ "access": "public"
54
+ },
55
+ "repository": {
56
+ "type": "git",
57
+ "url": "git+https://github.com/pengtang1024/dsh-paste-image.git"
58
+ },
59
+ "bugs": {
60
+ "url": "https://github.com/pengtang1024/dsh-paste-image/issues"
61
+ },
62
+ "homepage": "https://github.com/pengtang1024/dsh-paste-image#readme",
63
+ "author": "pengtang1024",
64
+ "engines": {
65
+ "node": ">=20"
66
+ },
67
+ "license": "MIT"
68
+ }