@mytools-all/mytools-ctool 0.1.0 → 0.1.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/README.md CHANGED
@@ -1,21 +1,25 @@
1
- # Ctool
2
-
3
- Ctool
4
-
5
- 版本:0.1.0;适用于 MyTools,不能作为独立网页调用宿主能力。
6
-
7
- ## 安装
8
-
9
- 在 MyTools 插件管理的 npm 安装入口输入 `@mytools-all/mytools-ctool@0.1.0`。也可以下载本仓库,在开发者页面选择“安装本地目录”。
10
-
11
- ## 开发
12
-
13
- 直接编辑本目录的 HTML、JavaScript 和样式,无需依赖宿主源码或其他插件仓库。修改后重新安装本地目录。运行 `npm test` 检查包内契约和逻辑。插件 API 规范见 [mytools](https://github.com/mytools-all/mytools/tree/main/docs)。
14
-
15
- ## 权限
16
-
17
- 声明的宿主能力:clipboard.write。目录和危险操作仍需用户授权。
18
-
19
- ## 许可
20
-
21
- 项目代码使用 MIT;随附的第三方代码遵循各自随附的许可证。
1
+ # Ctool
2
+
3
+ Ctool
4
+
5
+ 版本:0.1.0;适用于 MyTools,不能作为独立网页调用宿主能力。
6
+
7
+ ## 安装
8
+
9
+ 在 MyTools 插件管理的 npm 安装入口输入 `@mytools-all/mytools-ctool@0.1.0`。也可以下载本仓库,在开发者页面选择“安装本地目录”。
10
+
11
+ ## 开发
12
+
13
+ 直接编辑本目录的 HTML、JavaScript 和样式,无需依赖宿主源码或其他插件仓库。修改后重新安装本地目录。运行 `npm test` 检查包内契约和逻辑。插件 API 规范见 [mytools](https://github.com/mytools-all/mytools/tree/main/docs)。
14
+
15
+ ## 权限
16
+
17
+ 声明的宿主能力:clipboard.write。目录和危险操作仍需用户授权。
18
+
19
+ ## 许可
20
+
21
+ 项目代码使用 MIT;随附的第三方代码遵循各自随附的许可证。
22
+
23
+ ## MyTools 兼容范围
24
+
25
+ 版本 0.1.1 声明支持 MyTools >=0.2.0 <0.3.0(0.2.x 稳定版),插件 API 为 v1。主程序超出范围时应更新插件或使用受支持的主程序版本。旧版主程序可能不识别此声明,请先升级到提供兼容检查的 MyTools。
package/app.mjs CHANGED
@@ -1,222 +1,222 @@
1
- import { $, $$, action, copy, status, escapeHtml } from "./common.mjs";
2
- import md5 from "./md5.mjs";
3
- import { load as yamlLoad, dump as yamlDump } from "./yaml.mjs";
4
- const definitions = [
5
- ["base64", "Base64 编解码", ["编码", "解码"]],
6
- ["url", "URL 编解码", ["编码", "解码"]],
7
- ["hash", "哈希 / 摘要", ["MD5", "SHA-1", "SHA-256", "SHA-512"]],
8
- ["time", "时间戳转换", ["时间戳 → 日期", "日期 → 时间戳"]],
9
- ["regex", "正则测试", ["匹配"]],
10
- ["json", "JSON 工具", ["格式化", "压缩", "转义", "反转义"]],
11
- ["yaml", "JSON ↔ YAML", ["JSON → YAML", "YAML → JSON"]],
12
- ["urlparse", "URL 解析", ["解析"]],
13
- ["radix", "进制转换", ["10 → 2", "10 → 16", "16 → 10", "2 → 10"]],
14
- ["uuid", "UUID 生成", ["生成"]],
15
- ["text", "文本处理", ["去重行", "排序行", "大写", "小写", "统计"]],
16
- ];
17
- let current = definitions[0],
18
- revision = 0;
19
- function menu() {
20
- const q = $("#tool-search").value.toLowerCase();
21
- $("#tools").innerHTML = definitions
22
- .filter((d) => d[1].toLowerCase().includes(q))
23
- .map(
24
- (d) =>
25
- '<button class="' +
26
- (d === current ? "active" : "") +
27
- '" data-id="' +
28
- d[0] +
29
- '">' +
30
- d[1] +
31
- "</button>",
32
- )
33
- .join("");
34
- $$("#tools button").forEach((b) => (b.onclick = () => select(b.dataset.id)));
35
- }
36
- function select(id) {
37
- current = definitions.find((d) => d[0] === id);
38
- menu();
39
- $("#title").textContent = current[1];
40
- $("#operation").innerHTML = current[2]
41
- .map((x, i) => '<option value="' + i + '">' + escapeHtml(x) + "</option>")
42
- .join("");
43
- $("#extra").innerHTML =
44
- id === "regex"
45
- ? '<div class="row"><input id="pattern" placeholder="正则表达式" value="\\w+" style="flex:1"><input id="flags" placeholder="标志" value="g" style="width:65px"></div>'
46
- : id === "time"
47
- ? '<label>时间戳单位 <select id="unit"><option value="seconds">秒</option><option value="milliseconds">毫秒</option></select></label>'
48
- : "";
49
- $("#output").value = "";
50
- status("输入后点击执行 · Ctrl+Enter");
51
- }
52
- async function run() {
53
- const rev = ++revision;
54
- const text = $("#input").value,
55
- op = Number($("#operation").value);
56
- let output = "";
57
- switch (current[0]) {
58
- case "base64":
59
- output = op
60
- ? new TextDecoder("utf-8", { fatal: true }).decode(
61
- Uint8Array.from(atob(text.replace(/\s/g, "")), (c) =>
62
- c.charCodeAt(0),
63
- ),
64
- )
65
- : btoa(
66
- Array.from(new TextEncoder().encode(text), (b) =>
67
- String.fromCharCode(b),
68
- ).join(""),
69
- );
70
- break;
71
- case "url":
72
- output = op ? decodeURIComponent(text) : encodeURIComponent(text);
73
- break;
74
- case "hash":
75
- output = op
76
- ? [
77
- ...new Uint8Array(
78
- await crypto.subtle.digest(
79
- current[2][op],
80
- new TextEncoder().encode(text),
81
- ),
82
- ),
83
- ]
84
- .map((b) => b.toString(16).padStart(2, "0"))
85
- .join("")
86
- : md5(text);
87
- break;
88
- case "time": {
89
- let d;
90
- if (op === 0) {
91
- if (!/^\d+$/.test(text.trim())) throw Error("请输入数字时间戳");
92
- d = new Date(
93
- Number(text) * ($("#unit").value === "seconds" ? 1000 : 1),
94
- );
95
- } else d = new Date(text);
96
- if (Number.isNaN(d.getTime())) throw Error("日期无效");
97
- output = op
98
- ? String(
99
- $("#unit").value === "seconds"
100
- ? Math.floor(d.getTime() / 1000)
101
- : d.getTime(),
102
- )
103
- : "本地时间:" + d.toLocaleString() + "\nUTC:" + d.toISOString();
104
- break;
105
- }
106
- case "regex": {
107
- if (text.length > 200000) throw Error("正则测试输入不能超过 200 KB");
108
- output = await new Promise((resolve, reject) => {
109
- const worker = new Worker(
110
- new URL("./regex-worker.mjs", import.meta.url),
111
- { type: "module" },
112
- );
113
- const timer = setTimeout(() => {
114
- worker.terminate();
115
- reject(Error("正则运行超过 1 秒,已停止"));
116
- }, 1000);
117
- worker.onmessage = (e) => {
118
- clearTimeout(timer);
119
- worker.terminate();
120
- e.data.error ? reject(Error(e.data.error)) : resolve(e.data.result);
121
- };
122
- worker.onerror = () => {
123
- clearTimeout(timer);
124
- worker.terminate();
125
- reject(Error("正则测试失败"));
126
- };
127
- worker.postMessage({
128
- text,
129
- pattern: $("#pattern").value,
130
- flags: $("#flags").value,
131
- });
132
- });
133
- break;
134
- }
135
- case "json":
136
- output =
137
- op === 0
138
- ? JSON.stringify(JSON.parse(text), null, 2)
139
- : op === 1
140
- ? JSON.stringify(JSON.parse(text))
141
- : op === 2
142
- ? JSON.stringify(text)
143
- : JSON.parse(text);
144
- break;
145
- case "yaml":
146
- output = op
147
- ? JSON.stringify(yamlLoad(text), null, 2)
148
- : yamlDump(JSON.parse(text));
149
- break;
150
- case "urlparse": {
151
- const u = new URL(text);
152
- output = JSON.stringify(
153
- {
154
- protocol: u.protocol,
155
- host: u.host,
156
- hostname: u.hostname,
157
- port: u.port,
158
- pathname: u.pathname,
159
- hash: u.hash,
160
- query: [...u.searchParams],
161
- },
162
- null,
163
- 2,
164
- );
165
- break;
166
- }
167
- case "radix": {
168
- const n = BigInt(
169
- op === 2
170
- ? "0x" + text.replace(/^0x/i, "")
171
- : op === 3
172
- ? "0b" + text.replace(/^0b/i, "")
173
- : text,
174
- );
175
- output = n.toString(op === 0 ? 2 : op === 1 ? 16 : 10);
176
- break;
177
- }
178
- case "uuid":
179
- output = crypto.randomUUID();
180
- break;
181
- case "text": {
182
- const lines = text.split("\n");
183
- output =
184
- op === 0
185
- ? [...new Set(lines)].join("\n")
186
- : op === 1
187
- ? lines.sort((a, b) => a.localeCompare(b, "zh-CN")).join("\n")
188
- : op === 2
189
- ? text.toUpperCase()
190
- : op === 3
191
- ? text.toLowerCase()
192
- : JSON.stringify(
193
- {
194
- 字符数: [...text].length,
195
- 字节数: new TextEncoder().encode(text).length,
196
- 行数: lines.length,
197
- },
198
- null,
199
- 2,
200
- );
201
- break;
202
- }
203
- }
204
- if (rev === revision) {
205
- $("#output").value =
206
- typeof output === "string" ? output : JSON.stringify(output, null, 2);
207
- status("执行完成");
208
- }
209
- }
210
- $("#run").onclick = action(run);
211
- $("#copy").onclick = action(() => copy($("#output").value));
212
- $("#swap").onclick = () => {
213
- $("#input").value = $("#output").value;
214
- };
215
- $("#tool-search").oninput = menu;
216
- document.onkeydown = (e) => {
217
- if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
218
- e.preventDefault();
219
- $("#run").click();
220
- }
221
- };
222
- select("base64");
1
+ import { $, $$, action, copy, status, escapeHtml } from "./common.mjs";
2
+ import md5 from "./md5.mjs";
3
+ import { load as yamlLoad, dump as yamlDump } from "./yaml.mjs";
4
+ const definitions = [
5
+ ["base64", "Base64 编解码", ["编码", "解码"]],
6
+ ["url", "URL 编解码", ["编码", "解码"]],
7
+ ["hash", "哈希 / 摘要", ["MD5", "SHA-1", "SHA-256", "SHA-512"]],
8
+ ["time", "时间戳转换", ["时间戳 → 日期", "日期 → 时间戳"]],
9
+ ["regex", "正则测试", ["匹配"]],
10
+ ["json", "JSON 工具", ["格式化", "压缩", "转义", "反转义"]],
11
+ ["yaml", "JSON ↔ YAML", ["JSON → YAML", "YAML → JSON"]],
12
+ ["urlparse", "URL 解析", ["解析"]],
13
+ ["radix", "进制转换", ["10 → 2", "10 → 16", "16 → 10", "2 → 10"]],
14
+ ["uuid", "UUID 生成", ["生成"]],
15
+ ["text", "文本处理", ["去重行", "排序行", "大写", "小写", "统计"]],
16
+ ];
17
+ let current = definitions[0],
18
+ revision = 0;
19
+ function menu() {
20
+ const q = $("#tool-search").value.toLowerCase();
21
+ $("#tools").innerHTML = definitions
22
+ .filter((d) => d[1].toLowerCase().includes(q))
23
+ .map(
24
+ (d) =>
25
+ '<button class="' +
26
+ (d === current ? "active" : "") +
27
+ '" data-id="' +
28
+ d[0] +
29
+ '">' +
30
+ d[1] +
31
+ "</button>",
32
+ )
33
+ .join("");
34
+ $$("#tools button").forEach((b) => (b.onclick = () => select(b.dataset.id)));
35
+ }
36
+ function select(id) {
37
+ current = definitions.find((d) => d[0] === id);
38
+ menu();
39
+ $("#title").textContent = current[1];
40
+ $("#operation").innerHTML = current[2]
41
+ .map((x, i) => '<option value="' + i + '">' + escapeHtml(x) + "</option>")
42
+ .join("");
43
+ $("#extra").innerHTML =
44
+ id === "regex"
45
+ ? '<div class="row"><input id="pattern" placeholder="正则表达式" value="\\w+" style="flex:1"><input id="flags" placeholder="标志" value="g" style="width:65px"></div>'
46
+ : id === "time"
47
+ ? '<label>时间戳单位 <select id="unit"><option value="seconds">秒</option><option value="milliseconds">毫秒</option></select></label>'
48
+ : "";
49
+ $("#output").value = "";
50
+ status("输入后点击执行 · Ctrl+Enter");
51
+ }
52
+ async function run() {
53
+ const rev = ++revision;
54
+ const text = $("#input").value,
55
+ op = Number($("#operation").value);
56
+ let output = "";
57
+ switch (current[0]) {
58
+ case "base64":
59
+ output = op
60
+ ? new TextDecoder("utf-8", { fatal: true }).decode(
61
+ Uint8Array.from(atob(text.replace(/\s/g, "")), (c) =>
62
+ c.charCodeAt(0),
63
+ ),
64
+ )
65
+ : btoa(
66
+ Array.from(new TextEncoder().encode(text), (b) =>
67
+ String.fromCharCode(b),
68
+ ).join(""),
69
+ );
70
+ break;
71
+ case "url":
72
+ output = op ? decodeURIComponent(text) : encodeURIComponent(text);
73
+ break;
74
+ case "hash":
75
+ output = op
76
+ ? [
77
+ ...new Uint8Array(
78
+ await crypto.subtle.digest(
79
+ current[2][op],
80
+ new TextEncoder().encode(text),
81
+ ),
82
+ ),
83
+ ]
84
+ .map((b) => b.toString(16).padStart(2, "0"))
85
+ .join("")
86
+ : md5(text);
87
+ break;
88
+ case "time": {
89
+ let d;
90
+ if (op === 0) {
91
+ if (!/^\d+$/.test(text.trim())) throw Error("请输入数字时间戳");
92
+ d = new Date(
93
+ Number(text) * ($("#unit").value === "seconds" ? 1000 : 1),
94
+ );
95
+ } else d = new Date(text);
96
+ if (Number.isNaN(d.getTime())) throw Error("日期无效");
97
+ output = op
98
+ ? String(
99
+ $("#unit").value === "seconds"
100
+ ? Math.floor(d.getTime() / 1000)
101
+ : d.getTime(),
102
+ )
103
+ : "本地时间:" + d.toLocaleString() + "\nUTC:" + d.toISOString();
104
+ break;
105
+ }
106
+ case "regex": {
107
+ if (text.length > 200000) throw Error("正则测试输入不能超过 200 KB");
108
+ output = await new Promise((resolve, reject) => {
109
+ const worker = new Worker(
110
+ new URL("./regex-worker.mjs", import.meta.url),
111
+ { type: "module" },
112
+ );
113
+ const timer = setTimeout(() => {
114
+ worker.terminate();
115
+ reject(Error("正则运行超过 1 秒,已停止"));
116
+ }, 1000);
117
+ worker.onmessage = (e) => {
118
+ clearTimeout(timer);
119
+ worker.terminate();
120
+ e.data.error ? reject(Error(e.data.error)) : resolve(e.data.result);
121
+ };
122
+ worker.onerror = () => {
123
+ clearTimeout(timer);
124
+ worker.terminate();
125
+ reject(Error("正则测试失败"));
126
+ };
127
+ worker.postMessage({
128
+ text,
129
+ pattern: $("#pattern").value,
130
+ flags: $("#flags").value,
131
+ });
132
+ });
133
+ break;
134
+ }
135
+ case "json":
136
+ output =
137
+ op === 0
138
+ ? JSON.stringify(JSON.parse(text), null, 2)
139
+ : op === 1
140
+ ? JSON.stringify(JSON.parse(text))
141
+ : op === 2
142
+ ? JSON.stringify(text)
143
+ : JSON.parse(text);
144
+ break;
145
+ case "yaml":
146
+ output = op
147
+ ? JSON.stringify(yamlLoad(text), null, 2)
148
+ : yamlDump(JSON.parse(text));
149
+ break;
150
+ case "urlparse": {
151
+ const u = new URL(text);
152
+ output = JSON.stringify(
153
+ {
154
+ protocol: u.protocol,
155
+ host: u.host,
156
+ hostname: u.hostname,
157
+ port: u.port,
158
+ pathname: u.pathname,
159
+ hash: u.hash,
160
+ query: [...u.searchParams],
161
+ },
162
+ null,
163
+ 2,
164
+ );
165
+ break;
166
+ }
167
+ case "radix": {
168
+ const n = BigInt(
169
+ op === 2
170
+ ? "0x" + text.replace(/^0x/i, "")
171
+ : op === 3
172
+ ? "0b" + text.replace(/^0b/i, "")
173
+ : text,
174
+ );
175
+ output = n.toString(op === 0 ? 2 : op === 1 ? 16 : 10);
176
+ break;
177
+ }
178
+ case "uuid":
179
+ output = crypto.randomUUID();
180
+ break;
181
+ case "text": {
182
+ const lines = text.split("\n");
183
+ output =
184
+ op === 0
185
+ ? [...new Set(lines)].join("\n")
186
+ : op === 1
187
+ ? lines.sort((a, b) => a.localeCompare(b, "zh-CN")).join("\n")
188
+ : op === 2
189
+ ? text.toUpperCase()
190
+ : op === 3
191
+ ? text.toLowerCase()
192
+ : JSON.stringify(
193
+ {
194
+ 字符数: [...text].length,
195
+ 字节数: new TextEncoder().encode(text).length,
196
+ 行数: lines.length,
197
+ },
198
+ null,
199
+ 2,
200
+ );
201
+ break;
202
+ }
203
+ }
204
+ if (rev === revision) {
205
+ $("#output").value =
206
+ typeof output === "string" ? output : JSON.stringify(output, null, 2);
207
+ status("执行完成");
208
+ }
209
+ }
210
+ $("#run").onclick = action(run);
211
+ $("#copy").onclick = action(() => copy($("#output").value));
212
+ $("#swap").onclick = () => {
213
+ $("#input").value = $("#output").value;
214
+ };
215
+ $("#tool-search").oninput = menu;
216
+ document.onkeydown = (e) => {
217
+ if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
218
+ e.preventDefault();
219
+ $("#run").click();
220
+ }
221
+ };
222
+ select("base64");
package/common.mjs CHANGED
@@ -1,69 +1,69 @@
1
- export const $ = (selector) => document.querySelector(selector);
2
- export const $$ = (selector) => [...document.querySelectorAll(selector)];
3
- export function status(text, error = false) {
4
- const el = $("#status");
5
- if (el) {
6
- el.textContent = text;
7
- el.dataset.error = String(error);
8
- }
9
- }
10
- export function action(fn) {
11
- return async (...args) => {
12
- try {
13
- return await fn(...args);
14
- } catch (e) {
15
- status(e.message || String(e), true);
16
- }
17
- };
18
- }
19
- export async function call(id, args = {}) {
20
- if (!window.mytools) throw Error("请从 MyTools 打开此工具");
21
- return window.mytools.call(id, args);
22
- }
23
- export const copy = async (text) => {
24
- await call("clipboard.write", { text: String(text) });
25
- status("已复制到剪贴板");
26
- };
27
- export function ready(fn) {
28
- if (window.mytools) window.mytools.onPluginReady(action(fn));
29
- else status("预览模式:系统能力需从 MyTools 使用");
30
- }
31
- export const escapeHtml = (text) =>
32
- String(text).replace(
33
- /[&<>"']/g,
34
- (c) =>
35
- ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[
36
- c
37
- ],
38
- );
39
- export function download(name, text, type = "text/plain") {
40
- const url = URL.createObjectURL(new Blob([text], { type }));
41
- const a = document.createElement("a");
42
- a.href = url;
43
- a.download = name;
44
- a.click();
45
- setTimeout(() => URL.revokeObjectURL(url), 1000);
46
- }
47
- export function debounce(fn, ms = 200) {
48
- let timer;
49
- return (...args) => {
50
- clearTimeout(timer);
51
- timer = setTimeout(() => fn(...args), ms);
52
- };
53
- }
54
- export const formatBytes = (n) =>
55
- n < 1024
56
- ? n + " B"
57
- : n < 1048576
58
- ? (n / 1024).toFixed(1) + " KB"
59
- : (n / 1048576).toFixed(1) + " MB";
60
- const savedTheme = localStorage.getItem("tool-theme");
61
- document.documentElement.dataset.theme =
62
- savedTheme ||
63
- (matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
64
- $("#theme")?.addEventListener("click", () => {
65
- const theme =
66
- document.documentElement.dataset.theme === "dark" ? "light" : "dark";
67
- document.documentElement.dataset.theme = theme;
68
- localStorage.setItem("tool-theme", theme);
69
- });
1
+ export const $ = (selector) => document.querySelector(selector);
2
+ export const $$ = (selector) => [...document.querySelectorAll(selector)];
3
+ export function status(text, error = false) {
4
+ const el = $("#status");
5
+ if (el) {
6
+ el.textContent = text;
7
+ el.dataset.error = String(error);
8
+ }
9
+ }
10
+ export function action(fn) {
11
+ return async (...args) => {
12
+ try {
13
+ return await fn(...args);
14
+ } catch (e) {
15
+ status(e.message || String(e), true);
16
+ }
17
+ };
18
+ }
19
+ export async function call(id, args = {}) {
20
+ if (!window.mytools) throw Error("请从 MyTools 打开此工具");
21
+ return window.mytools.call(id, args);
22
+ }
23
+ export const copy = async (text) => {
24
+ await call("clipboard.write", { text: String(text) });
25
+ status("已复制到剪贴板");
26
+ };
27
+ export function ready(fn) {
28
+ if (window.mytools) window.mytools.onPluginReady(action(fn));
29
+ else status("预览模式:系统能力需从 MyTools 使用");
30
+ }
31
+ export const escapeHtml = (text) =>
32
+ String(text).replace(
33
+ /[&<>"']/g,
34
+ (c) =>
35
+ ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[
36
+ c
37
+ ],
38
+ );
39
+ export function download(name, text, type = "text/plain") {
40
+ const url = URL.createObjectURL(new Blob([text], { type }));
41
+ const a = document.createElement("a");
42
+ a.href = url;
43
+ a.download = name;
44
+ a.click();
45
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
46
+ }
47
+ export function debounce(fn, ms = 200) {
48
+ let timer;
49
+ return (...args) => {
50
+ clearTimeout(timer);
51
+ timer = setTimeout(() => fn(...args), ms);
52
+ };
53
+ }
54
+ export const formatBytes = (n) =>
55
+ n < 1024
56
+ ? n + " B"
57
+ : n < 1048576
58
+ ? (n / 1024).toFixed(1) + " KB"
59
+ : (n / 1048576).toFixed(1) + " MB";
60
+ const savedTheme = localStorage.getItem("tool-theme");
61
+ document.documentElement.dataset.theme =
62
+ savedTheme ||
63
+ (matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
64
+ $("#theme")?.addEventListener("click", () => {
65
+ const theme =
66
+ document.documentElement.dataset.theme === "dark" ? "light" : "dark";
67
+ document.documentElement.dataset.theme = theme;
68
+ localStorage.setItem("tool-theme", theme);
69
+ });