@zseven-w/qoder-openpencil 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.
Files changed (63) hide show
  1. package/INSTALL.md +77 -0
  2. package/LICENSE +21 -0
  3. package/NOTICE +10 -0
  4. package/README.md +46 -2
  5. package/README.zh.md +38 -0
  6. package/THIRD_PARTY_NOTICES.md +69 -0
  7. package/bin/qoder-openpencil.mjs +90 -0
  8. package/package.json +71 -4
  9. package/platforms.json +65 -0
  10. package/plugins/openpencil/.mcp.json +10 -0
  11. package/plugins/openpencil/.qoder-plugin/plugin.json +19 -0
  12. package/plugins/openpencil/CONNECTORS.md +9 -0
  13. package/plugins/openpencil/LICENSE +21 -0
  14. package/plugins/openpencil/NOTICE +10 -0
  15. package/plugins/openpencil/assets/icon.png +0 -0
  16. package/plugins/openpencil/assets/logo.png +0 -0
  17. package/plugins/openpencil/mcp.json +11 -0
  18. package/plugins/openpencil/plugin.json +19 -0
  19. package/plugins/openpencil/scripts/browser-launch.mjs +37 -0
  20. package/plugins/openpencil/scripts/canvas-codegen.mjs +141 -0
  21. package/plugins/openpencil/scripts/canvas-controller.mjs +293 -0
  22. package/plugins/openpencil/scripts/canvas-images.mjs +93 -0
  23. package/plugins/openpencil/scripts/canvas-panel.mjs +82 -0
  24. package/plugins/openpencil/scripts/canvas-selection.mjs +61 -0
  25. package/plugins/openpencil/scripts/document-format.mjs +48 -0
  26. package/plugins/openpencil/scripts/editor-runtime.mjs +453 -0
  27. package/plugins/openpencil/scripts/editor-session.mjs +230 -0
  28. package/plugins/openpencil/scripts/launch-mcp +22 -0
  29. package/plugins/openpencil/scripts/launch-mcp.cmd +21 -0
  30. package/plugins/openpencil/scripts/mcp-bridge.mjs +70 -0
  31. package/plugins/openpencil/scripts/runtime-install.mjs +128 -0
  32. package/plugins/openpencil/scripts/transport.mjs +138 -0
  33. package/plugins/openpencil/skills/openpencil-design/SKILL.md +125 -0
  34. package/plugins/openpencil/skills/openpencil-design/references/codegen.md +34 -0
  35. package/plugins/openpencil/skills/openpencil-design/references/images.md +54 -0
  36. package/plugins/openpencil/skills/openpencil-design/references/node-schema.md +208 -0
  37. package/plugins/openpencil/skills/openpencil-setup/SKILL.md +59 -0
  38. package/plugins/openpencil/ui/app.html +226 -0
  39. package/plugins/openpencil/ui/codegen.js +80 -0
  40. package/plugins/openpencil/ui/panel.css +311 -0
  41. package/plugins/openpencil/ui/panel.html +11 -0
  42. package/plugins/openpencil/ui/panel.js +219 -0
  43. package/plugins/openpencil/ui/selection.js +19 -0
  44. package/scripts/build-editor-runtime.mjs +35 -0
  45. package/scripts/canvas.mjs +75 -0
  46. package/scripts/check-package.mjs +81 -0
  47. package/scripts/check-release-version.mjs +53 -0
  48. package/scripts/collab-bootstrap-config.mjs +66 -0
  49. package/scripts/configure-runtime.mjs +15 -0
  50. package/scripts/host-config.mjs +352 -0
  51. package/scripts/managed-handshake.mjs +23 -0
  52. package/scripts/node-registration.mjs +17 -0
  53. package/scripts/pack-package.mjs +41 -0
  54. package/scripts/pack-plugin.mjs +166 -0
  55. package/scripts/platforms.mjs +84 -0
  56. package/scripts/plugin-host-check.mjs +174 -0
  57. package/scripts/publish-release.mjs +294 -0
  58. package/scripts/registry-convergence.mjs +40 -0
  59. package/scripts/setup.mjs +147 -0
  60. package/scripts/stage-editor-runtime.mjs +189 -0
  61. package/scripts/sync-platform-versions.mjs +63 -0
  62. package/scripts/verify-platform-packages.mjs +270 -0
  63. package/scripts/verify-selective-install.mjs +219 -0
@@ -0,0 +1,219 @@
1
+ const el = id => document.getElementById(id);
2
+ const frame = el('editor');
3
+ let ready = false, saving = false, dirty = false, source = grant.source;
4
+ let generation = 0, revision = 0, savedVersion = null, checkpointTimer;
5
+ let refreshingCanvas = false;
6
+ let connectionInterrupted = false;
7
+ const errors = new Map();
8
+ const snapshots = new Map();
9
+ const systemTheme = window.matchMedia?.('(prefers-color-scheme: dark)');
10
+ const validTheme = value => value === 'light' || value === 'dark';
11
+ const seedTheme = new URLSearchParams(window.location.hash.slice(1)).get('theme');
12
+ const browserLaunchId = new URLSearchParams(window.location.hash.slice(1)).get('launch');
13
+ let launchAcknowledged = false;
14
+ let parentTheme = validTheme(seedTheme) ? seedTheme : undefined;
15
+ let colorScheme, parentOrigin, editorInitialized = false;
16
+
17
+ function renderError() {
18
+ // Background connection failures must not hide a failed save or sync conflict.
19
+ const visible = [...errors.entries()].filter(([, error]) => !error.dismissed);
20
+ const current = (visible.findLast(([kind]) => kind !== 'connection') || visible.at(-1))?.[1];
21
+ el('error-message').textContent = current?.message || '';
22
+ el('error').hidden = !current;
23
+ }
24
+ function fail(error, kind = 'operation') {
25
+ const message = error.message || String(error), previous = errors.get(kind);
26
+ errors.set(kind, { message, dismissed: previous?.message === message && previous.dismissed });
27
+ renderError();
28
+ }
29
+ function clearError(kind) { errors.delete(kind); renderError(); }
30
+ function status(text) { el('status').textContent = text; }
31
+ function restoreStatus() {
32
+ status(errors.has('sync') ? '同步冲突' : errors.has('save') ? '保存未完成' : connectionInterrupted ? '画布连接中断' : dirty ? '未保存' : '画布已连接');
33
+ }
34
+ function send(value) { frame.contentWindow?.postMessage(JSON.stringify(value), grant.editorOrigin); }
35
+ function sendTheme() { if (editorInitialized) send({ type: 'op-bridge/theme', colorScheme }); }
36
+ function applyTheme() {
37
+ const nextTheme = parentTheme || (systemTheme?.matches ? 'dark' : 'light');
38
+ if (colorScheme === nextTheme) return;
39
+ colorScheme = nextTheme;
40
+ document.documentElement.dataset.theme = colorScheme;
41
+ document.documentElement.style.colorScheme = colorScheme;
42
+ sendTheme();
43
+ }
44
+ function notifyParentReady() {
45
+ if (window.parent !== window) {
46
+ window.parent.postMessage({ type: 'openpencil-canvas/ready' }, parentOrigin && parentOrigin !== 'null' ? parentOrigin : '*');
47
+ }
48
+ }
49
+ function initialize() {
50
+ send({ type: 'op-bridge/init', token: grant.token });
51
+ editorInitialized = true;
52
+ sendTheme();
53
+ }
54
+ systemTheme?.addEventListener('change', applyTheme);
55
+ applyTheme();
56
+
57
+ async function rpc(name, args = {}) {
58
+ const response = await fetch(grant.rpcPath, {
59
+ method: 'POST',
60
+ headers: { 'Content-Type': 'application/json' },
61
+ body: JSON.stringify({ name, arguments: args }),
62
+ signal: AbortSignal.timeout(15_000),
63
+ });
64
+ const value = await response.json();
65
+ if (!response.ok || value.error || value.isError) {
66
+ throw Object.assign(new Error(value.error || value.content?.[0]?.text || '画布操作失败'), { code: value.code || value.structuredContent?.code });
67
+ }
68
+ return value.structuredContent;
69
+ }
70
+ function updateSource() {
71
+ el('document-label').textContent = source || '未命名设计 · 独立文档';
72
+ el('document-label').title = source || '';
73
+ }
74
+ function flush() {
75
+ const requestId = crypto.randomUUID();
76
+ return new Promise((resolve, reject) => {
77
+ const timer = setTimeout(() => { snapshots.delete(requestId); reject(new Error('画布同步超时。请检查内容后重新保存,操作不会自动重试。')); }, 15_000);
78
+ snapshots.set(requestId, { resolve, reject, timer });
79
+ send({ type: 'op-bridge/snapshot', purpose: 'save', requestId });
80
+ });
81
+ }
82
+ async function save(path = source) {
83
+ if (!ready || saving) return;
84
+ if (!path) { el('save-dialog').showModal(); el('file-path').focus(); return; }
85
+ saving = true;
86
+ el('save').disabled = el('save-as').disabled = true;
87
+ status('正在保存…');
88
+ clearError('save');
89
+ try {
90
+ const snapshot = await flush();
91
+ const result = await rpc('canvas_save', { filePath: path, docJson: snapshot.docJson });
92
+ source = result.filePath;
93
+ savedVersion = result.version;
94
+ // A later edit must stay dirty even when an earlier Save completes.
95
+ if (generation === snapshot.generation && revision === snapshot.revision) dirty = false;
96
+ send({ type: 'op-bridge/save-committed', generation: snapshot.generation, revision: snapshot.revision });
97
+ clearError('sync');
98
+ updateSource();
99
+ status(dirty ? '有新的未保存修改' : '已保存');
100
+ } catch (error) {
101
+ fail(error, 'save');
102
+ status('保存未完成');
103
+ } finally {
104
+ saving = false;
105
+ el('save').disabled = el('save-as').disabled = !ready;
106
+ }
107
+ }
108
+ function checkpointSoon() {
109
+ if (checkpointTimer) return;
110
+ checkpointTimer = setTimeout(() => {
111
+ checkpointTimer = undefined;
112
+ if (!saving && ready) rpc('canvas_checkpoint').then(() => clearError('checkpoint')).catch(error => fail(error, 'checkpoint'));
113
+ }, 1000);
114
+ }
115
+ window.addEventListener('message', event => {
116
+ if (window.parent !== window && event.source === window.parent && event.data?.type === 'openpencil-canvas/theme') {
117
+ if (parentOrigin !== undefined && event.origin !== parentOrigin) return;
118
+ if (validTheme(event.data.colorScheme)) {
119
+ parentOrigin = event.origin;
120
+ parentTheme = event.data.colorScheme;
121
+ applyTheme();
122
+ }
123
+ return;
124
+ }
125
+ if (event.source !== frame.contentWindow || event.origin !== grant.editorOrigin || typeof event.data !== 'string') return;
126
+ let value;
127
+ try { value = JSON.parse(event.data); } catch { return; }
128
+ if (value.type === 'op-bridge/listening') initialize();
129
+ if (value.type === 'op-bridge/ready') {
130
+ if (!Number.isSafeInteger(value.generation) || !Number.isSafeInteger(value.revision)) return;
131
+ ready = true;
132
+ generation = value.generation;
133
+ revision = value.revision;
134
+ el('loading').hidden = true;
135
+ el('save').disabled = el('save-as').disabled = false;
136
+ connectionInterrupted = false;
137
+ clearError('connection');
138
+ restoreStatus();
139
+ sendTheme();
140
+ notifyParentReady();
141
+ if (!launchAcknowledged && /^[A-Za-z0-9_-]{22}$/.test(browserLaunchId || '')) {
142
+ launchAcknowledged = true;
143
+ void rpc('canvas_launch_ready', { launchId: browserLaunchId }).catch(() => {});
144
+ }
145
+ }
146
+ if (value.type === 'op-bridge/dirty-changed') {
147
+ if (!Number.isSafeInteger(value.generation) || !Number.isSafeInteger(value.revision)) return;
148
+ generation = value.generation;
149
+ revision = value.revision;
150
+ dirty = Boolean(value.dirty) || dirty;
151
+ if (!saving && dirty) restoreStatus();
152
+ checkpointSoon();
153
+ }
154
+ if (value.type === 'op-bridge/sync-conflict') {
155
+ dirty = true;
156
+ status('同步冲突');
157
+ fail(new Error('设计在同步过程中发生变化。请在编辑器中处理冲突,再保存。'), 'sync');
158
+ }
159
+ if (value.type === 'op-bridge/snapshot-result' || value.type === 'op-bridge/snapshot-conflict') {
160
+ const pending = snapshots.get(value.requestId);
161
+ if (!pending) return;
162
+ clearTimeout(pending.timer);
163
+ snapshots.delete(value.requestId);
164
+ if (value.type === 'op-bridge/snapshot-conflict') pending.reject(new Error('设计已发生变化,保存已停止。请同步后重试。'));
165
+ else pending.resolve(value);
166
+ }
167
+ if (value.type === 'op-shell/save') void save();
168
+ });
169
+ frame.addEventListener('load', initialize);
170
+ frame.src = `${grant.editorOrigin}/?embed=vscode&chat=host&locale=zh-CN&theme=${colorScheme}`;
171
+ notifyParentReady();
172
+ updateSource();
173
+ const startup = setInterval(() => { if (ready) clearInterval(startup); else initialize(); }, 1000);
174
+ setTimeout(() => {
175
+ if (!ready) {
176
+ clearInterval(startup);
177
+ connectionInterrupted = true;
178
+ fail(new Error('编辑器尚未连接。请检查运行包、页面加载或连接器状态后重新打开画布。'), 'connection');
179
+ }
180
+ }, 30_000);
181
+ el('error-dismiss').onclick = () => { for (const error of errors.values()) error.dismissed = true; renderError(); };
182
+ el('save').onclick = () => void save();
183
+ el('save-as').onclick = () => { el('file-path').value = source || ''; el('save-dialog').showModal(); };
184
+ el('cancel').onclick = () => el('save-dialog').close();
185
+ el('save-form').onsubmit = event => {
186
+ event.preventDefault();
187
+ const path = el('file-path').value.trim();
188
+ if (path) { el('save-dialog').close(); void save(path); }
189
+ };
190
+ window.addEventListener('keydown', event => { if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 's') { event.preventDefault(); void save(); } });
191
+ window.addEventListener('beforeunload', event => { if (dirty) { event.preventDefault(); event.returnValue = ''; } });
192
+
193
+ async function refreshCanvas() {
194
+ if (!ready || saving || refreshingCanvas || document.hidden) return;
195
+ refreshingCanvas = true;
196
+ try {
197
+ const result = await rpc('canvas_status');
198
+ source = result.filePath || source;
199
+ updateSource();
200
+ renderSelection(result.selection);
201
+ clearError('selection');
202
+ clearError('connection');
203
+ if (connectionInterrupted) { connectionInterrupted = false; restoreStatus(); }
204
+ if (savedVersion === null) savedVersion = result.version;
205
+ else if (result.version !== savedVersion) { dirty = true; restoreStatus(); checkpointSoon(); }
206
+ if (window.parent !== window) {
207
+ window.parent.postMessage({ type: 'openpencil-canvas/context', filePath: source, selection: result.selection }, parentOrigin && parentOrigin !== 'null' ? parentOrigin : '*');
208
+ }
209
+ } catch (error) {
210
+ selectionReadFailed(error);
211
+ if (!isSelectionReadError(error)) { connectionInterrupted = true; fail(error, 'connection'); restoreStatus(); }
212
+ if (window.parent !== window) {
213
+ window.parent.postMessage({ type: 'openpencil-canvas/context', filePath: source, selection: null }, parentOrigin && parentOrigin !== 'null' ? parentOrigin : '*');
214
+ }
215
+ } finally {
216
+ refreshingCanvas = false;
217
+ }
218
+ }
219
+ setInterval(refreshCanvas, 750);
@@ -0,0 +1,19 @@
1
+ function isSelectionReadError(error) {
2
+ return (typeof error.code === 'string' && error.code.startsWith('SELECTION_'))
3
+ || error.message === '选区或页面正在切换,请确认选中的元素后重试。';
4
+ }
5
+
6
+ function selectionReadFailed(error) {
7
+ renderSelection(null);
8
+ el('selection-label').textContent = isSelectionReadError(error)
9
+ ? error.code === 'SELECTION_STALE' ? '请重新选择元素' : '正在同步选区…'
10
+ : '选区暂不可用';
11
+ }
12
+
13
+ function renderSelection(value) {
14
+ const selection = value?.count > 0 && Array.isArray(value.nodeIds) && value.count === value.nodeIds.length ? value : null;
15
+ const names = selection?.nodes?.map(node => node.name || node.id).join('、') || '';
16
+ const text = selection ? `已选 ${selection.count} 个元素${names ? ` · ${names}` : ''}` : '未选中元素';
17
+ el('selection-label').textContent = text;
18
+ el('selection-label').title = text;
19
+ }
@@ -0,0 +1,35 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { join } from 'node:path';
3
+ import { collabBootstrapEnvNames, validatedCollabBootstrapUrls } from './collab-bootstrap-config.mjs';
4
+ import { argumentValue, openPencilRoot } from './platforms.mjs';
5
+
6
+ const target = argumentValue('--target');
7
+ const bootstrap = validatedCollabBootstrapUrls();
8
+ const args = [
9
+ 'build',
10
+ '--manifest-path',
11
+ join(openPencilRoot, 'Cargo.toml'),
12
+ '--locked',
13
+ '--release',
14
+ '-p',
15
+ 'op-host-web-server',
16
+ ];
17
+ if (target !== undefined) args.push('--target', target);
18
+
19
+ const result = spawnSync(process.platform === 'win32' ? 'cargo.exe' : 'cargo', args, {
20
+ cwd: openPencilRoot,
21
+ env: {
22
+ ...process.env,
23
+ [collabBootstrapEnvNames[0]]: bootstrap.cn,
24
+ [collabBootstrapEnvNames[1]]: bootstrap.global,
25
+ },
26
+ stdio: 'inherit',
27
+ });
28
+ if (result.error !== undefined) throw result.error;
29
+ if (result.status !== 0) {
30
+ throw new Error(`op-host-web-server release build exited with status ${result.status ?? 'unknown'}`);
31
+ }
32
+
33
+ process.stdout.write(
34
+ `built collaboration-enabled op-host-web-server${target === undefined ? '' : ` for ${target}`}\n`,
35
+ );
@@ -0,0 +1,75 @@
1
+ import { createInterface } from 'node:readline';
2
+ import { resolve, join } from 'node:path';
3
+ import { writeFile } from 'node:fs/promises';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { CanvasController } from '../plugins/openpencil/scripts/canvas-controller.mjs';
6
+
7
+ export async function runCanvas(args = process.argv.slice(2)) {
8
+ if (args.length && (args.length !== 2 || args[0] !== '--file')) {
9
+ throw new Error('Usage: qoder-openpencil canvas [--file /absolute/design.op]');
10
+ }
11
+ const controller = new CanvasController();
12
+ const tty = process.stdin.isTTY && typeof process.stdin.setRawMode === 'function';
13
+ const previousRawMode = process.stdin.isRaw;
14
+ if (tty) process.stdin.setRawMode(true);
15
+ const input = createInterface({ input: process.stdin, terminal: false });
16
+ let stopping = false;
17
+ const shutdown = () => { stopping = true; input.close(); };
18
+ const interrupt = chunk => { if (chunk.includes(3) || chunk.includes(4)) shutdown(); };
19
+ if (tty) process.stdin.on('data', interrupt);
20
+ process.once('SIGINT', shutdown);
21
+ process.once('SIGTERM', shutdown);
22
+ try {
23
+ const opened = await controller.open(args.length ? { filePath: resolve(args[1]) } : {});
24
+ console.log(JSON.stringify({
25
+ ready: true,
26
+ ...opened.structuredContent,
27
+ input: 'One JSON object per line: {"name":"get_editor_state","arguments":{}}. Send {"quit":true} to close. Never retry a failed write automatically.',
28
+ }));
29
+ let id = 0;
30
+ for await (const line of input) {
31
+ if (stopping) break;
32
+ if (!line.trim()) continue;
33
+ try {
34
+ const request = JSON.parse(line);
35
+ if (request.quit === true) break;
36
+ const message = request.method
37
+ ? { ...request, jsonrpc: '2.0', id: ++id }
38
+ : { jsonrpc: '2.0', id: ++id, method: 'tools/call', params: { name: request.name, arguments: request.arguments || {} } };
39
+ const reply = await controller.enqueue(() => controller.dispatch(message));
40
+ const imagePaths = new Map();
41
+ for (const [index, item] of (reply?.result?.content || []).entries()) {
42
+ const extension = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp' }[item.mimeType];
43
+ if (item.type !== 'image' || !extension || typeof item.data !== 'string') continue;
44
+ const path = join(controller.session.dir, `preview-${id}-${index}.${extension}`);
45
+ await writeFile(path, Buffer.from(item.data, 'base64'), { flag: 'wx', mode: 0o600 });
46
+ imagePaths.set(item.data, path);
47
+ reply.result.content[index] = { type: 'text', text: JSON.stringify({ imagePath: path, mimeType: item.mimeType }) };
48
+ }
49
+ for (const item of reply?.result?.content || []) {
50
+ if (item.type !== 'text') continue;
51
+ try {
52
+ const value = JSON.parse(item.text);
53
+ if (imagePaths.has(value.image_base64)) {
54
+ value.imagePath = imagePaths.get(value.image_base64);
55
+ delete value.image_base64;
56
+ item.text = JSON.stringify(value);
57
+ }
58
+ } catch { /* Preserve native non-JSON text. */ }
59
+ }
60
+ console.log(JSON.stringify(reply));
61
+ } catch (error) {
62
+ console.log(JSON.stringify({ error: error.message }));
63
+ }
64
+ }
65
+ } finally {
66
+ input.close();
67
+ process.stdin.off('data', interrupt);
68
+ if (tty) { process.stdin.setRawMode(Boolean(previousRawMode)); process.stdin.pause(); }
69
+ await controller.close();
70
+ }
71
+ }
72
+
73
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
74
+ await runCanvas(process.argv.slice(2));
75
+ }
@@ -0,0 +1,81 @@
1
+ import assert from 'node:assert/strict';
2
+ import { readFile, readdir, stat } from 'node:fs/promises';
3
+ import { resolve, relative, join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { parseEditorRuntimeCatalog } from '../plugins/openpencil/scripts/editor-runtime.mjs';
6
+
7
+ const root = fileURLToPath(new URL('../', import.meta.url));
8
+ const json = async (path) => JSON.parse(await readFile(path, 'utf8'));
9
+
10
+ const pkg = await json(join(root, 'package.json'));
11
+ const catalog = parseEditorRuntimeCatalog(await json(join(root, 'platforms.json')));
12
+ assert.equal(catalog.platforms.length, 6, 'Publish runtime packages for all six platforms');
13
+ const expectedOptionals = Object.fromEntries(catalog.platforms.map(platform => [platform.packageName, pkg.version]));
14
+ assert.deepEqual(pkg.optionalDependencies, expectedOptionals);
15
+ for (const platform of catalog.platforms) {
16
+ const platformPkg = await json(join(root, 'npm', platform.id, 'package.json'));
17
+ assert.equal(platformPkg.name, platform.packageName);
18
+ assert.equal(platformPkg.version, pkg.version);
19
+ }
20
+
21
+ const pluginRoot = resolve(root, 'plugins/openpencil');
22
+ for (const manifestRel of ['plugin.json', '.qoder-plugin/plugin.json']) {
23
+ const manifest = await json(join(pluginRoot, manifestRel));
24
+ assert.equal(manifest.name, 'openpencil');
25
+ assert.equal(manifest.version, pkg.version);
26
+ }
27
+
28
+ for (const assetRel of ['./assets/icon.png', './assets/logo.png']) {
29
+ const target = resolve(pluginRoot, assetRel);
30
+ const bytes = await readFile(target);
31
+ assert.ok(bytes.length >= 24 && bytes.length <= 5 * 1024 * 1024, `Invalid ${assetRel} size`);
32
+ assert.equal(bytes.subarray(0, 8).toString('hex'), '89504e470d0a1a0a', `Invalid ${assetRel} PNG`);
33
+ const width = bytes.readUInt32BE(16);
34
+ const height = bytes.readUInt32BE(20);
35
+ assert.ok(width === height && width >= 48 && width <= 4096, `Invalid ${assetRel} dimensions`);
36
+ }
37
+
38
+ const dotMcp = await json(join(pluginRoot, '.mcp.json'));
39
+ assert.equal(dotMcp.mcpServers.openpencil.type, 'stdio');
40
+ assert.equal(dotMcp.mcpServers.openpencil.command, '${QODER_PLUGIN_ROOT}/scripts/launch-mcp');
41
+ assert.equal(dotMcp.mcpServers.openpencil.cwd, '${QODER_PLUGIN_ROOT}');
42
+
43
+ const stdMcp = await json(join(pluginRoot, 'mcp.json'));
44
+ assert.equal(stdMcp.mcpServers.openpencil.type, 'stdio');
45
+ assert.equal(stdMcp.mcpServers.openpencil.command, './scripts/launch-mcp');
46
+
47
+ for (const path of ['LICENSE', 'NOTICE', 'CONNECTORS.md', 'scripts/launch-mcp', 'scripts/launch-mcp.cmd', 'scripts/mcp-bridge.mjs']) {
48
+ assert.ok((await stat(join(pluginRoot, path))).isFile(), `Missing ${path}`);
49
+ }
50
+ if (process.platform !== 'win32') {
51
+ assert.ok((await stat(join(pluginRoot, 'scripts/launch-mcp'))).mode & 0o111, 'launch-mcp must be executable');
52
+ assert.ok((await stat(join(root, 'bin/qoder-openpencil.mjs'))).mode & 0o111, 'CLI bin must be executable');
53
+ }
54
+ for (const asset of ['app.html', 'panel.html', 'panel.css', 'panel.js', 'selection.js', 'codegen.js']) {
55
+ assert.ok((await stat(join(pluginRoot, 'ui', asset))).isFile(), `Missing canvas asset: ${asset}`);
56
+ }
57
+
58
+ async function scan(dir) {
59
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
60
+ const path = join(dir, entry.name);
61
+ if (entry.isDirectory()) {
62
+ await scan(path);
63
+ } else {
64
+ if (entry.name.endsWith('.png')) continue;
65
+ const body = (await readFile(path, 'utf8')).replace(/\r\n/g, '\n');
66
+ assert.ok(!/\/Users\/[A-Za-z0-9_.-]+\//.test(body), `Machine path in ${path}`);
67
+ assert.ok(body.split('\n').length <= 800, `File exceeds 800 lines: ${path}`);
68
+ if (entry.name === 'SKILL.md') {
69
+ assert.match(body, /^---\nname: [a-z0-9-]+\ndescription: .+\n---/);
70
+ for (const [, link] of body.matchAll(/\]\(([^)]+)\)/g)) {
71
+ if (/^https?:/.test(link)) continue;
72
+ const target = resolve(dir, link);
73
+ assert.ok(!relative(pluginRoot, target).startsWith('..'), `Escaping reference ${link}`);
74
+ assert.ok((await stat(target)).isFile(), `Missing reference ${link}`);
75
+ }
76
+ }
77
+ }
78
+ }
79
+ }
80
+ await scan(pluginRoot);
81
+ console.log('Qoder plugin identity, six-platform npm catalog, MCP paths, skill references, portability and license: OK');
@@ -0,0 +1,53 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { openPencil, openPencilRoot, platforms, projectRoot } from './platforms.mjs';
5
+
6
+ const requested = process.argv[2]?.replace(/^(?:qoder-)?v/u, '');
7
+ if (requested === undefined) throw new Error('usage: node scripts/check-release-version.mjs <version>');
8
+ if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u.test(requested)) {
9
+ throw new Error(`invalid release version ${JSON.stringify(requested)}`);
10
+ }
11
+
12
+ const root = JSON.parse(await readFile(join(projectRoot, 'package.json'), 'utf8'));
13
+ if (root.version !== requested) throw new Error(`tag version ${requested} does not match package.json ${root.version}`);
14
+ const expectedOptionals = Object.fromEntries(platforms.map(platform => [platform.packageName, requested]));
15
+ if (JSON.stringify(root.optionalDependencies) !== JSON.stringify(expectedOptionals)) {
16
+ throw new Error('root optionalDependencies are not the exact synchronized six-platform set');
17
+ }
18
+ for (const platform of platforms) {
19
+ const manifest = JSON.parse(await readFile(join(projectRoot, 'npm', platform.id, 'package.json'), 'utf8'));
20
+ if (manifest.version !== requested) throw new Error(`${platform.packageName} is not synchronized to ${requested}`);
21
+ }
22
+ for (const pluginRel of ['plugin.json', '.qoder-plugin/plugin.json']) {
23
+ const pluginManifest = JSON.parse(await readFile(join(projectRoot, 'plugins', 'openpencil', pluginRel), 'utf8'));
24
+ if (pluginManifest.version !== requested) {
25
+ throw new Error(`plugins/openpencil/${pluginRel} is ${pluginManifest.version}, expected ${requested}`);
26
+ }
27
+ }
28
+
29
+ const controllerText = await readFile(join(projectRoot, 'plugins', 'openpencil', 'scripts', 'canvas-controller.mjs'), 'utf8');
30
+ if (!controllerText.includes(`'ui://openpencil/canvas/v${requested}.html'`)) {
31
+ throw new Error(`canvas-controller.mjs CANVAS_URI does not match ${requested}`);
32
+ }
33
+ if (!controllerText.includes(`serverInfo: { name: 'qoder-openpencil', version: '${requested}' }`)) {
34
+ throw new Error(`canvas-controller.mjs serverInfo.version does not match ${requested}`);
35
+ }
36
+ const appHtmlText = await readFile(join(projectRoot, 'plugins', 'openpencil', 'ui', 'app.html'), 'utf8');
37
+ if (!appHtmlText.includes(`appInfo: { name: 'OpenPencil Canvas', version: '${requested}' }`)) {
38
+ throw new Error(`plugins/openpencil/ui/app.html appInfo.version does not match ${requested}`);
39
+ }
40
+
41
+ const cargo = await readFile(join(openPencilRoot, 'Cargo.toml'), 'utf8');
42
+ const cargoVersion = /^\[workspace\.package\][\s\S]*?^version = "([^"]+)"/mu.exec(cargo)?.[1];
43
+ if (cargoVersion !== openPencil.version) {
44
+ throw new Error(`platforms.json pins OpenPencil ${openPencil.version}, Cargo.toml reports ${cargoVersion ?? 'nothing'}`);
45
+ }
46
+ git(['-C', openPencilRoot, 'merge-base', '--is-ancestor', openPencil.revision, 'HEAD']);
47
+ process.stdout.write(requested + '\n');
48
+
49
+ function git(args) {
50
+ const result = spawnSync('git', args, { cwd: projectRoot, encoding: 'utf8' });
51
+ if (result.status !== 0) throw new Error(`git ${args.join(' ')} failed:\n${result.stderr || result.stdout}`);
52
+ return result.stdout;
53
+ }
@@ -0,0 +1,66 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { join } from 'node:path';
3
+ import { openPencilRoot, projectRoot } from './platforms.mjs';
4
+
5
+ export const collabBootstrapEnvNames = Object.freeze([
6
+ 'OPENPENCIL_BUILD_COLLAB_BOOTSTRAP_URL_CN',
7
+ 'OPENPENCIL_BUILD_COLLAB_BOOTSTRAP_URL_GLOBAL',
8
+ ]);
9
+
10
+ export function withoutCollabBootstrapBuildEnv(env = process.env) {
11
+ const sanitized = { ...env };
12
+ for (const name of collabBootstrapEnvNames) delete sanitized[name];
13
+ return sanitized;
14
+ }
15
+
16
+ const validator = join(
17
+ openPencilRoot,
18
+ 'tools',
19
+ 'check-collab-bootstrap-urls.py',
20
+ );
21
+
22
+ /**
23
+ * Read and validate both production relay bootstrap URLs without putting their
24
+ * values on a command line. OpenPencil deliberately keeps these endpoints out
25
+ * of the open-source binary; every published native package must inject both.
26
+ */
27
+ export function validatedCollabBootstrapUrls(env = process.env) {
28
+ const values = collabBootstrapEnvNames.map(name => {
29
+ const value = env[name];
30
+ if (typeof value !== 'string' || value.length === 0) {
31
+ throw new Error(`${name} is required for a collaboration-enabled editor runtime`);
32
+ }
33
+ return value;
34
+ });
35
+
36
+ const payload = Buffer.from(`${values[0]}\0${values[1]}\0`, 'utf8');
37
+ const candidates = process.platform === 'win32'
38
+ ? [['python', []], ['py', ['-3']], ['python3', []]]
39
+ : [['python3', []], ['python', []]];
40
+
41
+ for (const [command, prefix] of candidates) {
42
+ const result = spawnSync(command, [...prefix, validator], {
43
+ cwd: projectRoot,
44
+ env: withoutCollabBootstrapBuildEnv(process.env),
45
+ input: payload,
46
+ encoding: 'utf8',
47
+ maxBuffer: 64 * 1024,
48
+ });
49
+ if (result.error?.code === 'ENOENT') continue;
50
+ if (result.error !== undefined) {
51
+ throw new Error(`could not run the OpenPencil relay bootstrap validator with ${command}`, {
52
+ cause: result.error,
53
+ });
54
+ }
55
+ if (result.status !== 0) {
56
+ const detail = result.stderr.trim() || 'OpenPencil relay bootstrap validation failed';
57
+ throw new Error(detail);
58
+ }
59
+ return Object.freeze({
60
+ cn: values[0],
61
+ global: values[1],
62
+ });
63
+ }
64
+
65
+ throw new Error('Python 3 is required to validate the production collaboration bootstrap URLs');
66
+ }
@@ -0,0 +1,15 @@
1
+ import { resolve } from 'node:path';
2
+ import { configureRuntime } from '../plugins/openpencil/scripts/runtime-install.mjs';
3
+
4
+ const raw = process.argv[2];
5
+ if (!raw || process.argv.length !== 3) {
6
+ console.error('Usage: npm run configure-runtime -- /absolute/runtime/root');
7
+ process.exit(1);
8
+ }
9
+ try {
10
+ const runtime = await configureRuntime(resolve(raw), undefined, { source: 'custom' });
11
+ console.log(`Verified and configured Rust OpenPencil ${runtime.version} (${process.platform}-${process.arch}).`);
12
+ } catch (error) {
13
+ console.error(`Failed to configure OpenPencil runtime: ${error.message}`);
14
+ process.exit(1);
15
+ }