@breinzhang/mivark 0.0.0-stage → 0.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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,21 @@
1
- # Temporary Holding Version
1
+ # mivark(npm CLI)
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
+ 启动预编译 Mivark 桌面应用的命令行工具。**不包含 Rust 编译,不做任何网络下载**;应用二进制由同版本的 npm 平台包(`@breinzhang/mivark-<platform>-<arch>`)提供。
4
+
5
+ ## 用法
6
+
7
+ ```bash
8
+ npm install -g @breinzhang/mivark
9
+ mivark --version
10
+ mivark /path/to/README.md
11
+ ```
12
+
13
+ - `--version` / `--help` 不启动 GUI。
14
+ - 文件参数会启动(或聚焦已运行的)Mivark 并打开对应文件。
15
+ - macOS 首次运行校验 ZIP SHA-256,解包到 `~/Library/Application Support/Mivark/npm/<version>-<arch>-<payload-sha>/Mivark.app`;每次启动复验缓存内容和 `codesign --verify --deep --strict`,损坏时从本地包重建。无需联网。
16
+ - 并发首次启动通过目录锁串行处理;暂存目录与缓存同盘,验证完成才切换目录,失败尝试恢复旧缓存。
17
+ - 锁等待超时会报告具体路径。只有确认其他启动器均已退出后,才删除该锁目录重试;旧版缓存不会自动删除。
18
+ - 不再支持 `MIVARK_SKIP_CODESIGN_CHECK`。启动器会校验本地应用包完整性与 `codesign` 签名(支持 ad-hoc 签名或 Developer ID 签名)。
19
+ - macOS 等待 `open` 返回,失败以非零退出码报告。Windows 等待进程创建成功后分离;这不代表 GUI/WebView2 已就绪。
20
+ - 支持 `--ignore-scripts` 安装;`--omit=optional` 可能导致平台包缺失,CLI 会给出修复指引。
21
+ - 相对路径按调用目录解析;以 `-` 开头的文件名放在 `--` 后;未知选项报错,不静默忽略。
@@ -0,0 +1,52 @@
1
+ micromark-util-edit-map 1.0.0 (Mivark performance patch)
2
+ ========================================================
3
+
4
+ (The MIT License)
5
+
6
+ Copyright (c) Titus Wormer <tituswormer@gmail.com>
7
+
8
+ Permission is hereby granted, free of charge, to any person obtaining
9
+ a copy of this software and associated documentation files (the
10
+ 'Software'), to deal in the Software without restriction, including
11
+ without limitation the rights to use, copy, modify, merge, publish,
12
+ distribute, sublicense, and/or sell copies of the Software, and to
13
+ permit persons to whom the Software is furnished to do so, subject to
14
+ the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be
17
+ included in all copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
20
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
22
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
23
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
24
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
25
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26
+
27
+
28
+ @milkdown/transformer 7.23.0 (Mivark performance patch)
29
+ =======================================================
30
+
31
+ The MIT License (MIT)
32
+
33
+ Copyright (c) 2020-present Mirone
34
+
35
+ Permission is hereby granted, free of charge, to any person obtaining a copy
36
+ of this software and associated documentation files (the "Software"), to deal
37
+ in the Software without restriction, including without limitation the rights
38
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
39
+ copies of the Software, and to permit persons to whom the Software is
40
+ furnished to do so, subject to the following conditions:
41
+
42
+ The above copyright notice and this permission notice shall be included in all
43
+ copies or substantial portions of the Software.
44
+
45
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
46
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
47
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
48
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
49
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
50
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
51
+ SOFTWARE.
52
+
package/bin/mivark.mjs ADDED
@@ -0,0 +1,152 @@
1
+ #!/usr/bin/env node
2
+ // Mivark CLI launcher responsibilities:
3
+ // --version / --help without starting the GUI
4
+ // platform resolution → optional platform package → payload verification
5
+ // macOS: unpack .app.zip into a versioned cache, codesign check, `open -a`
6
+ // Windows: spawn the precompiled Mivark.exe directly
7
+ // The CLI NEVER downloads anything from the network.
8
+ import { createRequire } from 'node:module';
9
+ import { existsSync, readFileSync } from 'node:fs';
10
+ import { homedir } from 'node:os';
11
+ import path from 'node:path';
12
+ import process from 'node:process';
13
+ import { launchDetached, prepareMacCache, runChecked, sha256File } from './runtime.mjs';
14
+
15
+ const {
16
+ name: cliName,
17
+ version: CLI_VERSION,
18
+ optionalDependencies,
19
+ } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
20
+
21
+ const fail = (msg, code = 1) => {
22
+ console.error(`mivark: ${msg}`);
23
+ process.exit(code);
24
+ };
25
+
26
+ const args = process.argv.slice(2);
27
+ const flagArgs = args.slice(0, args.indexOf('--') < 0 ? args.length : args.indexOf('--'));
28
+
29
+ if (flagArgs.includes('--help') || flagArgs.includes('-h')) {
30
+ console.log(`mivark ${CLI_VERSION} — Mivark 桌面应用启动器
31
+
32
+ 用法:
33
+ mivark [--version] [--help]
34
+ mivark <文件路径...> 启动/聚焦 Mivark 并打开文件(支持 .md/.json/图片)
35
+
36
+ 说明:
37
+ - npm 包只负责启动预编译的桌面程序;不包含也不执行 Rust 编译。
38
+ - 首次运行会把平台包内的应用解包到本地缓存目录(macOS),之后离线可用。
39
+ - 支持 --ignore-scripts 安装;不要使用 --omit=optional,否则可能缺少平台包。`);
40
+ process.exit(0);
41
+ }
42
+
43
+ if (flagArgs.includes('--version') || flagArgs.includes('-V')) {
44
+ // Keep --version offline and cheap: report the CLI version; the desktop
45
+ // bundle version is verified at launch time against the payload manifest.
46
+ console.log(`mivark ${CLI_VERSION}`);
47
+ process.exit(0);
48
+ }
49
+
50
+ // ---------- platform resolution ----------
51
+ const platform = process.platform; // darwin | win32 | ...
52
+ const arch = process.arch; // arm64 | x64
53
+ const key = `${platform}-${arch}`;
54
+ const pkgName = Object.keys(optionalDependencies).find((name) => name.endsWith(`/mivark-${key}`));
55
+ if (!pkgName) {
56
+ fail(`不支持的平台 ${key}。支持: darwin-arm64, darwin-x64, win32-x64。`, 1);
57
+ }
58
+
59
+ // Resolve the platform package robustly: normal install layout first
60
+ // (relative to this file), then the invoking cwd (covers file:/symlinked
61
+ // development installs where import.meta.url is realpath'ed away).
62
+ const resolvers = [
63
+ createRequire(import.meta.url),
64
+ createRequire(path.join(process.cwd(), 'noop.js')),
65
+ ];
66
+ let payloadDir;
67
+ let resolveErr;
68
+ try {
69
+ let resolved;
70
+ for (const req of resolvers) {
71
+ try {
72
+ resolved = req.resolve(`${pkgName}/package.json`);
73
+ break;
74
+ } catch (e) {
75
+ resolveErr = e;
76
+ }
77
+ }
78
+ if (!resolved) throw resolveErr ?? new Error('MODULE_NOT_FOUND');
79
+ payloadDir = path.join(path.dirname(resolved), 'payload');
80
+ } catch (err) {
81
+ fail(
82
+ `缺少平台包 ${pkgName}(错误: ${err instanceof Error ? (err.code ?? err.message) : String(err)})。
83
+ 修复方式:
84
+ npm install -g ${cliName}@${CLI_VERSION}
85
+ # 或显式安装平台包: npm install -g ${pkgName}@${CLI_VERSION}
86
+ # 注意: 不要使用 --omit=optional 安装。`,
87
+ 1,
88
+ );
89
+ }
90
+
91
+ const manifestPath = path.join(payloadDir, 'manifest.json');
92
+ if (!existsSync(manifestPath)) {
93
+ fail(`平台包不完整: 未找到 ${manifestPath}。请重新安装 ${pkgName}。`, 1);
94
+ }
95
+ let manifest;
96
+ try {
97
+ manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
98
+ } catch {
99
+ fail(`平台包 manifest.json 损坏。请重新安装 ${pkgName}。`, 1);
100
+ }
101
+
102
+ if (manifest.version !== CLI_VERSION) {
103
+ fail(
104
+ `版本不一致: CLI ${CLI_VERSION} vs 平台包 ${pkgName} ${manifest.version}。请统一重装两个包。`,
105
+ 1,
106
+ );
107
+ }
108
+ if (manifest.platform !== platform || manifest.arch !== arch) {
109
+ fail(`平台包架构不匹配: 期望 ${key},实际 ${manifest.platform}-${manifest.arch}。`, 1);
110
+ }
111
+
112
+ async function verifyArtifact(file, expectedSha) {
113
+ const actual = await sha256File(file);
114
+ if (actual !== expectedSha) {
115
+ fail(
116
+ `完整性校验失败: ${path.basename(file)}\n 期望 SHA-256: ${expectedSha}\n 实际 SHA-256: ${actual}\n请重新安装 ${pkgName};不要绕过校验。`,
117
+ 1,
118
+ );
119
+ }
120
+ }
121
+
122
+ // Reject unknown options; `--` permits filenames beginning with a dash.
123
+ const separator = args.indexOf('--');
124
+ const options = separator < 0 ? args : args.slice(0, separator);
125
+ if (options.some((arg) => arg.startsWith('-')))
126
+ fail('未知选项。使用 --help 查看用法;以 - 开头的路径请放在 -- 后。');
127
+ const fileArgs = (separator < 0 ? args : [...options, ...args.slice(separator + 1)]).map((file) =>
128
+ path.resolve(file),
129
+ );
130
+ const expectedArtifact = platform === 'darwin' ? 'Mivark.app.zip' : 'Mivark.exe';
131
+ if (manifest.artifact !== expectedArtifact || !/^[a-f0-9]{64}$/.test(manifest.sha256)) {
132
+ fail('平台包 manifest 的 artifact 或 SHA-256 无效,请重新安装。');
133
+ }
134
+
135
+ try {
136
+ if (platform === 'darwin') {
137
+ const appPath = await prepareMacCache({
138
+ zipPath: path.join(payloadDir, expectedArtifact),
139
+ cacheBase: path.join(homedir(), 'Library', 'Application Support', 'Mivark', 'npm'),
140
+ manifest,
141
+ });
142
+ // Wait for LaunchServices acceptance, not for the long-lived GUI to exit.
143
+ runChecked('open', ['-a', appPath, ...(fileArgs.length ? ['--args', ...fileArgs] : [])]);
144
+ } else {
145
+ const exePath = path.join(payloadDir, expectedArtifact);
146
+ await verifyArtifact(exePath, manifest.sha256);
147
+ // Success means OS process creation, not GUI readiness/WebView2 availability.
148
+ await launchDetached(exePath, fileArgs);
149
+ }
150
+ } catch (error) {
151
+ fail(error instanceof Error ? error.message : String(error));
152
+ }
@@ -0,0 +1,151 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { spawn, spawnSync } from 'node:child_process';
3
+ import { createReadStream } from 'node:fs';
4
+ import {
5
+ lstat,
6
+ mkdir,
7
+ mkdtemp,
8
+ readFile,
9
+ readdir,
10
+ readlink,
11
+ rename,
12
+ rm,
13
+ writeFile,
14
+ } from 'node:fs/promises';
15
+ import path from 'node:path';
16
+ import { setTimeout as delay } from 'node:timers/promises';
17
+
18
+ export async function sha256File(file) {
19
+ const hash = createHash('sha256');
20
+ for await (const chunk of createReadStream(file)) hash.update(chunk);
21
+ return hash.digest('hex');
22
+ }
23
+
24
+ // Include names, modes and symlink targets, without following bundle symlinks.
25
+ export async function bundleDigest(root) {
26
+ const hash = createHash('sha256');
27
+ async function visit(relative) {
28
+ const file = path.join(root, relative);
29
+ const stat = await lstat(file);
30
+ hash.update(JSON.stringify([relative, stat.mode]));
31
+ if (stat.isSymbolicLink()) hash.update(JSON.stringify(await readlink(file)));
32
+ else if (stat.isDirectory()) {
33
+ for (const name of (await readdir(file)).sort()) await visit(path.join(relative, name));
34
+ } else if (stat.isFile()) hash.update(await sha256File(file));
35
+ else throw new Error('应用缓存包含不支持的文件类型。');
36
+ }
37
+ if (!(await lstat(root)).isDirectory()) throw new Error('应用缓存不是目录。');
38
+ await visit('');
39
+ return hash.digest('hex');
40
+ }
41
+
42
+ export function runChecked(command, args) {
43
+ const result = spawnSync(command, args, { encoding: 'utf8', timeout: 120_000 });
44
+ if (result.error || result.status !== 0) {
45
+ throw new Error(
46
+ `${command} 失败: ${result.error?.message ?? result.stderr?.trim() ?? result.status}`,
47
+ );
48
+ }
49
+ }
50
+
51
+ export async function withCacheLock(lock, action, timeoutMs = 30_000) {
52
+ const start = Date.now();
53
+ for (;;) {
54
+ try {
55
+ await mkdir(lock);
56
+ break;
57
+ } catch (error) {
58
+ if (error.code !== 'EEXIST') throw error;
59
+ if (Date.now() - start >= timeoutMs) {
60
+ throw new Error(
61
+ `等待缓存锁超时: ${lock}。确认其他 mivark 启动器已退出后,删除此锁目录再重试。`,
62
+ );
63
+ }
64
+ await delay(100);
65
+ }
66
+ }
67
+ try {
68
+ await writeFile(
69
+ path.join(lock, 'owner.json'),
70
+ JSON.stringify({ pid: process.pid, at: Date.now() }),
71
+ );
72
+ return await action();
73
+ } finally {
74
+ await rm(lock, { recursive: true, force: true });
75
+ }
76
+ }
77
+
78
+ export async function prepareMacCache({
79
+ zipPath,
80
+ cacheBase,
81
+ manifest,
82
+ run = runChecked,
83
+ renameCache = rename,
84
+ }) {
85
+ if (!/^[a-f0-9]{64}$/.test(manifest.sha256)) throw new Error('无效的 payload SHA-256。');
86
+ if ((await sha256File(zipPath)) !== manifest.sha256)
87
+ throw new Error('平台包完整性校验失败,请重新安装。');
88
+ // Content identity prevents same-version builds from reusing stale applications.
89
+ const cacheRoot = path.join(cacheBase, `${manifest.version}-${manifest.arch}-${manifest.sha256}`);
90
+ await mkdir(cacheBase, { recursive: true });
91
+ return withCacheLock(`${cacheRoot}.lock`, async () => {
92
+ const app = path.join(cacheRoot, 'Mivark.app');
93
+ try {
94
+ const stamp = JSON.parse(await readFile(path.join(cacheRoot, '.unpacked-ok'), 'utf8'));
95
+ if (stamp.sha256 === manifest.sha256 && stamp.digest === (await bundleDigest(app))) {
96
+ run('codesign', ['--verify', '--deep', '--strict', app]);
97
+ return app;
98
+ }
99
+ } catch {
100
+ // Rebuild damaged/old caches exclusively from the verified local payload.
101
+ }
102
+ const stage = await mkdtemp(path.join(cacheBase, '.mivark-stage-'));
103
+ let backup;
104
+ let cleanupBackup = false;
105
+ try {
106
+ run('ditto', ['-x', '-k', zipPath, stage]);
107
+ const extracted = path.join(stage, 'Mivark.app');
108
+ run('codesign', ['--verify', '--deep', '--strict', extracted]);
109
+ const digest = await bundleDigest(extracted);
110
+ await writeFile(
111
+ path.join(stage, '.unpacked-ok'),
112
+ JSON.stringify({ sha256: manifest.sha256, digest }),
113
+ );
114
+ // Stage on the same filesystem. Keep the previous cache until promotion succeeds.
115
+ try {
116
+ await lstat(cacheRoot);
117
+ backup = await mkdtemp(path.join(cacheBase, '.mivark-old-'));
118
+ await renameCache(cacheRoot, path.join(backup, 'cache'));
119
+ } catch (error) {
120
+ if (error.code !== 'ENOENT') throw error;
121
+ }
122
+ try {
123
+ await renameCache(stage, cacheRoot);
124
+ } catch (error) {
125
+ if (backup) await renameCache(path.join(backup, 'cache'), cacheRoot);
126
+ cleanupBackup = true;
127
+ throw error;
128
+ }
129
+ cleanupBackup = true;
130
+ return app;
131
+ } finally {
132
+ await rm(stage, { recursive: true, force: true });
133
+ if (backup && cleanupBackup) await rm(backup, { recursive: true, force: true });
134
+ }
135
+ });
136
+ }
137
+
138
+ export async function launchDetached(executable, args, spawnProcess = spawn) {
139
+ await new Promise((resolve, reject) => {
140
+ const child = spawnProcess(executable, args, {
141
+ detached: true,
142
+ stdio: 'ignore',
143
+ windowsHide: true,
144
+ });
145
+ child.once('error', reject);
146
+ child.once('spawn', () => {
147
+ child.unref();
148
+ resolve();
149
+ });
150
+ });
151
+ }
package/package.json CHANGED
@@ -1,6 +1,27 @@
1
1
  {
2
2
  "name": "@breinzhang/mivark",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Mivark desktop launcher — starts the precompiled Mivark.app / Mivark.exe",
5
+ "bin": {
6
+ "mivark": "bin/mivark.mjs"
7
+ },
8
+ "type": "module",
9
+ "engines": {
10
+ "node": ">=20"
11
+ },
12
+ "optionalDependencies": {
13
+ "@breinzhang/mivark-darwin-arm64": "0.1.0",
14
+ "@breinzhang/mivark-darwin-x64": "0.1.0",
15
+ "@breinzhang/mivark-win32-x64": "0.1.0"
16
+ },
17
+ "files": [
18
+ "bin/",
19
+ "README.md",
20
+ "THIRD_PARTY_NOTICES.txt"
21
+ ],
22
+ "license": "Apache-2.0",
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/breinzhang/mivark.git"
26
+ }
27
+ }