@synlexa/studio 0.0.0-stage → 0.4.3

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 (46) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +72 -0
  3. package/README.md +70 -2
  4. package/assets/icon-256.png +0 -0
  5. package/assets/icon.icns +0 -0
  6. package/assets/icon.ico +0 -0
  7. package/assets/icon.png +0 -0
  8. package/bin/synlexa-studio.mjs +244 -0
  9. package/package.json +38 -4
  10. package/scripts/desktop-shortcut.mjs +413 -0
  11. package/scripts/postinstall.mjs +184 -0
  12. package/wasm/synlexa_bio_core.wasm +0 -0
  13. package/web-dist/assets/MolStarViewport-BYVdqMR8.css +1 -0
  14. package/web-dist/assets/MolStarViewport-C2s337aX.js +8197 -0
  15. package/web-dist/assets/bioCore.worker-BGMOX1WA.js +1 -0
  16. package/web-dist/assets/index-DR8pRGGj.css +1 -0
  17. package/web-dist/assets/index-U3MvggqW.js +845 -0
  18. package/web-dist/assets/node.browser-Bv5igiSk.js +1 -0
  19. package/web-dist/assets/node.browser-h9BcAsHn.js +1 -0
  20. package/web-dist/assets/rdkit.worker-BvevbBxc.js +19 -0
  21. package/web-dist/favicon_io/android-chrome-192x192.png +0 -0
  22. package/web-dist/favicon_io/android-chrome-512x512.png +0 -0
  23. package/web-dist/favicon_io/apple-touch-icon.png +0 -0
  24. package/web-dist/favicon_io/favicon-16x16.png +0 -0
  25. package/web-dist/favicon_io/favicon-32x32.png +0 -0
  26. package/web-dist/favicon_io/favicon.ico +0 -0
  27. package/web-dist/favicon_io/site.webmanifest +1 -0
  28. package/web-dist/fixtures/1A3N.cif +8411 -0
  29. package/web-dist/fixtures/1LZ1.cif +2950 -0
  30. package/web-dist/fixtures/1UBQ.cif +2237 -0
  31. package/web-dist/fixtures/3HS4.cif +7817 -0
  32. package/web-dist/fixtures/3HS4.pdb +5385 -0
  33. package/web-dist/fixtures/AF-P00918-F1-model_v6.cif +3372 -0
  34. package/web-dist/fixtures/AF-P00918-F1-model_v6.pdb +2141 -0
  35. package/web-dist/fixtures/AF-P00918-F1-predicted_aligned_error_v6.json +1 -0
  36. package/web-dist/fixtures/AF-P0CG48-F1-model_v6.cif +8128 -0
  37. package/web-dist/fixtures/AF-P61626-F1-model_v6.cif +2075 -0
  38. package/web-dist/fixtures/AF-P68871-F1-model_v6.cif +2029 -0
  39. package/web-dist/fixtures/fixtures-manifest.json +198 -0
  40. package/web-dist/fixtures/pubchem-panel.json +84 -0
  41. package/web-dist/index.html +19 -0
  42. package/web-dist/synlexa-logo.png +0 -0
  43. package/web-dist/synlexa-s-icon.svg +12 -0
  44. package/web-dist/synlexa-wordmark.png +0 -0
  45. package/web-dist/wasm/rdkit/RDKit_minimal.wasm +0 -0
  46. package/web-dist/wasm/synlexa_bio_core.wasm +0 -0
@@ -0,0 +1,413 @@
1
+ import { createRequire } from 'node:module';
2
+ import {
3
+ accessSync,
4
+ chmodSync,
5
+ constants,
6
+ cpSync,
7
+ existsSync,
8
+ lstatSync,
9
+ mkdirSync,
10
+ readFileSync,
11
+ rmSync,
12
+ symlinkSync,
13
+ writeFileSync,
14
+ } from 'node:fs';
15
+ import { spawnSync } from 'node:child_process';
16
+ import { homedir, userInfo } from 'node:os';
17
+ import { dirname, join, resolve } from 'node:path';
18
+ import { fileURLToPath } from 'node:url';
19
+
20
+ const __dirname = dirname(fileURLToPath(import.meta.url));
21
+ export const PKG_ROOT = resolve(__dirname, '..');
22
+
23
+ export const PLATFORM_MAP = {
24
+ 'darwin-arm64': '@synlexa/studio-darwin-arm64',
25
+ 'darwin-x64': '@synlexa/studio-darwin-x64',
26
+ 'linux-x64': '@synlexa/studio-linux-x64-gnu',
27
+ 'linux-arm64': '@synlexa/studio-linux-arm64-gnu',
28
+ 'win32-x64': '@synlexa/studio-win32-x64-msvc',
29
+ 'win32-arm64': '@synlexa/studio-win32-arm64-msvc',
30
+ };
31
+
32
+ const require = createRequire(import.meta.url);
33
+
34
+ export function readPackageMeta() {
35
+ return JSON.parse(readFileSync(join(PKG_ROOT, 'package.json'), 'utf8'));
36
+ }
37
+
38
+ export function findNativeBinary(name, pkgRoot = PKG_ROOT) {
39
+ const pkgName = PLATFORM_MAP[`${process.platform}-${process.arch}`];
40
+ const ext = process.platform === 'win32' ? '.exe' : '';
41
+ const names =
42
+ process.platform === 'win32' && name === 'synlexa-studio-desktop-native'
43
+ ? ['synlexa-studio-desktop-native.exe', 'synlexa-studio.exe']
44
+ : [`${name}${ext}`];
45
+
46
+ if (pkgName) {
47
+ try {
48
+ const pkgJsonPath = require.resolve(`${pkgName}/package.json`);
49
+ for (const binName of names) {
50
+ const candidate = join(dirname(pkgJsonPath), 'bin', binName);
51
+ if (existsSync(candidate)) return candidate;
52
+ }
53
+ } catch {
54
+ // Optional native package not installed; try local/home runtime fallbacks
55
+ }
56
+ }
57
+ for (const binName of names) {
58
+ const localCandidate = join(pkgRoot, 'bin', binName);
59
+ if (existsSync(localCandidate)) return localCandidate;
60
+ }
61
+
62
+ const home = process.env.HOME || process.env.USERPROFILE || '';
63
+ const runtimeDir = process.env.SYNLEXA_INSTALL_DIR || (home ? join(home, '.synlexa-studio', 'runtime') : '');
64
+ if (runtimeDir) {
65
+ for (const binName of names) {
66
+ const homeCandidate = join(runtimeDir, 'bin', binName);
67
+ if (existsSync(homeCandidate)) return homeCandidate;
68
+ }
69
+ }
70
+ return null;
71
+ }
72
+
73
+ function isWritableDir(dir) {
74
+ try {
75
+ accessSync(dir, constants.W_OK);
76
+ return true;
77
+ } catch {
78
+ return false;
79
+ }
80
+ }
81
+
82
+ function escapeShDoubleQuoted(value) {
83
+ return value.replace(/(["\\$`])/g, '\\$1');
84
+ }
85
+
86
+ function quoteDesktopExecArg(value) {
87
+ if (/^[A-Za-z0-9_./:-]+$/.test(value)) return value;
88
+ return `"${value.replace(/(["\\$`])/g, '\\$1')}"`;
89
+ }
90
+
91
+ function buildInfoPlist(version, executableName) {
92
+ return `<?xml version="1.0" encoding="UTF-8"?>
93
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
94
+ <plist version="1.0">
95
+ <dict>
96
+ <key>CFBundleName</key><string>Synlexa Studio</string>
97
+ <key>CFBundleDisplayName</key><string>Synlexa Studio</string>
98
+ <key>CFBundleIdentifier</key><string>com.synlexa.studio</string>
99
+ <key>CFBundleVersion</key><string>${version}</string>
100
+ <key>CFBundleShortVersionString</key><string>${version}</string>
101
+ <key>CFBundlePackageType</key><string>APPL</string>
102
+ <key>CFBundleExecutable</key><string>${executableName}</string>
103
+ <key>CFBundleIconFile</key><string>icon.icns</string>
104
+ <key>NSHighResolutionCapable</key><true/>
105
+ <key>LSMinimumSystemVersion</key><string>11.0</string>
106
+ <key>CFBundleURLTypes</key>
107
+ <array>
108
+ <dict>
109
+ <key>CFBundleURLName</key><string>com.synlexa.studio.auth</string>
110
+ <key>CFBundleURLSchemes</key><array><string>synlexa-studio</string></array>
111
+ </dict>
112
+ </array>
113
+ </dict>
114
+ </plist>
115
+ `;
116
+ }
117
+
118
+ function installMacosDesktopShortcut({ version, nativeHost, nativeCli, distDir, cliEntry, nodeExe }) {
119
+ const home = process.env.HOME || homedir();
120
+ let realHome = home;
121
+ try {
122
+ realHome = userInfo().homedir || home;
123
+ } catch {
124
+ // fallback if passwd entry unavailable
125
+ }
126
+ const useSystemApps = !process.env.SYNLEXA_APP_DIR && home === realHome && isWritableDir('/Applications');
127
+ const appParent = process.env.SYNLEXA_APP_DIR || (useSystemApps ? '/Applications' : join(home, 'Applications'));
128
+ mkdirSync(appParent, { recursive: true });
129
+
130
+ const appBundle = join(appParent, 'Synlexa Studio.app');
131
+ const contentsDir = join(appBundle, 'Contents');
132
+ const macosDir = join(contentsDir, 'MacOS');
133
+ const resourcesDir = join(contentsDir, 'Resources');
134
+
135
+ rmSync(appBundle, { recursive: true, force: true });
136
+ mkdirSync(macosDir, { recursive: true });
137
+ mkdirSync(resourcesDir, { recursive: true });
138
+
139
+ const iconSrc = join(PKG_ROOT, 'assets', 'icon.icns');
140
+ if (existsSync(iconSrc)) {
141
+ cpSync(iconSrc, join(resourcesDir, 'icon.icns'));
142
+ }
143
+
144
+ let executableName = 'synlexa-studio-launcher';
145
+ if (nativeHost && existsSync(distDir)) {
146
+ executableName = 'synlexa-studio-desktop-native';
147
+ const destHost = join(macosDir, executableName);
148
+ cpSync(nativeHost, destHost);
149
+ chmodSync(destHost, 0o755);
150
+ if (nativeCli && existsSync(nativeCli)) {
151
+ const destCli = join(macosDir, 'studio-cli');
152
+ cpSync(nativeCli, destCli);
153
+ chmodSync(destCli, 0o755);
154
+ }
155
+ cpSync(distDir, join(resourcesDir, 'web-dist'), { recursive: true });
156
+ } else {
157
+ const launcherPath = join(macosDir, executableName);
158
+ const script = `#!/usr/bin/env sh
159
+ set -eu
160
+ PORT="\${SYNLEXA_PORT:-4179}"
161
+ URL="http://127.0.0.1:\${PORT}/"
162
+ NODE_BIN="${escapeShDoubleQuoted(nodeExe)}"
163
+ CLI_BIN="${escapeShDoubleQuoted(cliEntry)}"
164
+ LOG_FILE="\${HOME:-/tmp}/.synlexa-studio/launcher.log"
165
+ mkdir -p "$(dirname "$LOG_FILE")"
166
+ if ! curl -fsS --max-time 1 "$URL" >/dev/null 2>&1; then
167
+ nohup "$NODE_BIN" "$CLI_BIN" launch --port "$PORT" --no-open >"$LOG_FILE" 2>&1 &
168
+ for _ in 1 2 3 4 5 6 7 8 9 10; do
169
+ if curl -fsS --max-time 1 "$URL" >/dev/null 2>&1; then
170
+ break
171
+ fi
172
+ sleep 0.2
173
+ done
174
+ fi
175
+ if [ -x "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" ]; then
176
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --app="$URL" >/dev/null 2>&1 &
177
+ else
178
+ open "$URL"
179
+ fi
180
+ `;
181
+ writeFileSync(launcherPath, script, 'utf8');
182
+ chmodSync(launcherPath, 0o755);
183
+ }
184
+
185
+ writeFileSync(join(contentsDir, 'Info.plist'), buildInfoPlist(version, executableName), 'utf8');
186
+
187
+ spawnSync('xattr', ['-cr', appBundle], { stdio: 'ignore' });
188
+ spawnSync('codesign', ['--force', '--deep', '--sign', '-', appBundle], { stdio: 'ignore' });
189
+ spawnSync(
190
+ '/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister',
191
+ ['-f', appBundle],
192
+ { stdio: 'ignore' },
193
+ );
194
+
195
+ const created = [appBundle];
196
+ const desktopDir = process.env.SYNLEXA_DESKTOP_DIR || join(home, 'Desktop');
197
+ if (existsSync(desktopDir) && isWritableDir(desktopDir)) {
198
+ const desktopLink = join(desktopDir, 'Synlexa Studio.app');
199
+ let canWriteLink = true;
200
+ try {
201
+ const st = lstatSync(desktopLink);
202
+ if (st.isSymbolicLink() || st.isFile()) {
203
+ rmSync(desktopLink, { force: true });
204
+ } else {
205
+ canWriteLink = false;
206
+ }
207
+ } catch {
208
+ // Does not exist yet
209
+ }
210
+ if (canWriteLink) {
211
+ symlinkSync(appBundle, desktopLink);
212
+ created.push(desktopLink);
213
+ }
214
+ }
215
+ return created;
216
+ }
217
+
218
+ function resolveLinuxDesktopDir(home) {
219
+ if (process.env.SYNLEXA_DESKTOP_DIR) return process.env.SYNLEXA_DESKTOP_DIR;
220
+ const xdg = spawnSync('xdg-user-dir', ['DESKTOP'], { encoding: 'utf8' });
221
+ if (xdg.status === 0 && xdg.stdout) {
222
+ const candidate = xdg.stdout.trim();
223
+ if (candidate && candidate !== home && existsSync(candidate)) {
224
+ return candidate;
225
+ }
226
+ }
227
+ return join(home, 'Desktop');
228
+ }
229
+
230
+ function installLinuxDesktopShortcut({ nativeHost, distDir, cliEntry, nodeExe }) {
231
+ const home = process.env.HOME || homedir();
232
+ const xdgDataHome = process.env.XDG_DATA_HOME || join(home, '.local', 'share');
233
+ const appsDir = join(xdgDataHome, 'applications');
234
+ const icons256Dir = join(xdgDataHome, 'icons', 'hicolor', '256x256', 'apps');
235
+ const icons1024Dir = join(xdgDataHome, 'icons', 'hicolor', '1024x1024', 'apps');
236
+
237
+ mkdirSync(appsDir, { recursive: true });
238
+ mkdirSync(icons256Dir, { recursive: true });
239
+ mkdirSync(icons1024Dir, { recursive: true });
240
+
241
+ const icon1024Src = join(PKG_ROOT, 'assets', 'icon.png');
242
+ const icon256Src = join(PKG_ROOT, 'assets', 'icon-256.png');
243
+ const installedIcon1024 = join(icons1024Dir, 'synlexa-studio.png');
244
+ const installedIcon256 = join(icons256Dir, 'synlexa-studio.png');
245
+
246
+ if (existsSync(icon1024Src)) cpSync(icon1024Src, installedIcon1024);
247
+ if (existsSync(icon256Src)) {
248
+ cpSync(icon256Src, installedIcon256);
249
+ } else if (existsSync(icon1024Src)) {
250
+ cpSync(icon1024Src, installedIcon256);
251
+ }
252
+
253
+ const iconField = existsSync(installedIcon1024) ? installedIcon1024 : 'synlexa-studio';
254
+ const execLine =
255
+ nativeHost && existsSync(distDir)
256
+ ? `${quoteDesktopExecArg(nativeHost)} --dist ${quoteDesktopExecArg(distDir)}`
257
+ : `${quoteDesktopExecArg(nodeExe)} ${quoteDesktopExecArg(cliEntry)} launch`;
258
+
259
+ const desktopEntry = `[Desktop Entry]
260
+ Version=1.0
261
+ Type=Application
262
+ Name=Synlexa Studio
263
+ GenericName=Computational Biology Workbench
264
+ Comment=Deterministic Structural Biology & Cheminformatics Workbench (Research-Use-Only)
265
+ Exec=${execLine}
266
+ Icon=${iconField}
267
+ Categories=Science;Education;Development;
268
+ Keywords=Synlexa;Bioinformatics;Protein;MolStar;SMILES;CRISPR;MCP;
269
+ Terminal=false
270
+ StartupNotify=true
271
+ `;
272
+
273
+ const created = [];
274
+ const appDesktopFile = join(appsDir, 'synlexa-studio.desktop');
275
+ writeFileSync(appDesktopFile, desktopEntry, 'utf8');
276
+ chmodSync(appDesktopFile, 0o755);
277
+ created.push(appDesktopFile);
278
+
279
+ const desktopDir = resolveLinuxDesktopDir(home);
280
+ if (existsSync(desktopDir) && isWritableDir(desktopDir)) {
281
+ const desktopFile = join(desktopDir, 'synlexa-studio.desktop');
282
+ writeFileSync(desktopFile, desktopEntry, 'utf8');
283
+ chmodSync(desktopFile, 0o755);
284
+ spawnSync('gio', ['set', desktopFile, 'metadata::trusted', 'true'], { stdio: 'ignore' });
285
+ created.push(desktopFile);
286
+ }
287
+
288
+ spawnSync('update-desktop-database', [appsDir], { stdio: 'ignore' });
289
+ return created;
290
+ }
291
+
292
+ function installWindowsDesktopShortcut({ nativeHost, distDir, cliEntry, nodeExe }) {
293
+ const home = process.env.USERPROFILE || process.env.HOME || homedir();
294
+ const iconIco = join(PKG_ROOT, 'assets', 'icon.ico');
295
+ const targetPath = nativeHost && existsSync(distDir) ? nativeHost : nodeExe;
296
+ const targetArgs =
297
+ nativeHost && existsSync(distDir) ? `--dist "${distDir}"` : `"${cliEntry}" launch`;
298
+
299
+ const psScript = `
300
+ $ErrorActionPreference = 'Stop'
301
+ $WshShell = New-Object -ComObject WScript.Shell
302
+ $Targets = @()
303
+ $DesktopDir = if ($env:SYNLEXA_DESKTOP_DIR) { $env:SYNLEXA_DESKTOP_DIR } else { [Environment]::GetFolderPath('Desktop') }
304
+ $ProgramsDir = if ($env:SYNLEXA_PROGRAMS_DIR) { $env:SYNLEXA_PROGRAMS_DIR } else { [Environment]::GetFolderPath('Programs') }
305
+ if ($DesktopDir -and (Test-Path $DesktopDir)) { $Targets += (Join-Path $DesktopDir 'Synlexa Studio.lnk') }
306
+ if ($ProgramsDir) {
307
+ New-Item -ItemType Directory -Force -Path $ProgramsDir | Out-Null
308
+ $Targets += (Join-Path $ProgramsDir 'Synlexa Studio.lnk')
309
+ }
310
+ foreach ($LnkPath in $Targets) {
311
+ $Sc = $WshShell.CreateShortcut($LnkPath)
312
+ $Sc.TargetPath = $env:SYNLEXA_SC_TARGET
313
+ $Sc.Arguments = $env:SYNLEXA_SC_ARGS
314
+ $Sc.WorkingDirectory = $env:SYNLEXA_SC_WORKDIR
315
+ $Sc.Description = 'Synlexa Studio — Deterministic Structural Biology & Cheminformatics Workbench (RUO)'
316
+ $Sc.WindowStyle = 7
317
+ if ($env:SYNLEXA_SC_ICON -and (Test-Path $env:SYNLEXA_SC_ICON)) {
318
+ $Sc.IconLocation = "$($env:SYNLEXA_SC_ICON),0"
319
+ }
320
+ $Sc.Save()
321
+ Write-Output $LnkPath
322
+ }
323
+ `;
324
+
325
+ const res = spawnSync(
326
+ 'powershell.exe',
327
+ ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', psScript],
328
+ {
329
+ encoding: 'utf8',
330
+ env: {
331
+ ...process.env,
332
+ SYNLEXA_SC_TARGET: targetPath,
333
+ SYNLEXA_SC_ARGS: targetArgs,
334
+ SYNLEXA_SC_ICON: existsSync(iconIco) ? iconIco : '',
335
+ SYNLEXA_SC_WORKDIR: home,
336
+ },
337
+ },
338
+ );
339
+ if (res.status !== 0) {
340
+ throw new Error(res.stderr || 'Failed to create Windows desktop shortcut');
341
+ }
342
+ return (res.stdout || '')
343
+ .split(/\r?\n/)
344
+ .map((s) => s.trim())
345
+ .filter(Boolean);
346
+ }
347
+
348
+ /**
349
+ * Installs a clickable Synlexa Studio icon onto the user's Desktop and OS app launcher.
350
+ */
351
+ export function installDesktopShortcut({ platform = process.platform } = {}) {
352
+ const meta = readPackageMeta();
353
+ const version = meta.version || '0.4.1';
354
+ const nativeHost = findNativeBinary('synlexa-studio-desktop-native');
355
+ const nativeCli = findNativeBinary('studio-cli');
356
+ const distDir = join(PKG_ROOT, 'web-dist');
357
+ const cliEntry = join(PKG_ROOT, 'bin', 'synlexa-studio.mjs');
358
+ const nodeExe = process.execPath;
359
+
360
+ const opts = { version, nativeHost, nativeCli, distDir, cliEntry, nodeExe };
361
+ if (platform === 'darwin') return installMacosDesktopShortcut(opts);
362
+ if (platform === 'linux') return installLinuxDesktopShortcut(opts);
363
+ if (platform === 'win32') return installWindowsDesktopShortcut(opts);
364
+ return [];
365
+ }
366
+
367
+ /**
368
+ * Removes Synlexa Studio Desktop / Applications shortcuts created by npm install.
369
+ */
370
+ export function uninstallDesktopShortcut({ platform = process.platform } = {}) {
371
+ const removed = [];
372
+ const home = process.env.HOME || process.env.USERPROFILE || homedir();
373
+ const candidates = [];
374
+
375
+ if (platform === 'darwin') {
376
+ const desktopDir = process.env.SYNLEXA_DESKTOP_DIR || join(home, 'Desktop');
377
+ const desktopLink = join(desktopDir, 'Synlexa Studio.app');
378
+ try {
379
+ if (lstatSync(desktopLink).isSymbolicLink()) candidates.push(desktopLink);
380
+ } catch {
381
+ // ignore
382
+ }
383
+ const appDir = process.env.SYNLEXA_APP_DIR;
384
+ if (appDir) candidates.push(join(appDir, 'Synlexa Studio.app'));
385
+ candidates.push(join(home, 'Applications', 'Synlexa Studio.app'));
386
+ let realHome = home;
387
+ try {
388
+ realHome = userInfo().homedir || home;
389
+ } catch {
390
+ // ignore
391
+ }
392
+ if (home === realHome && isWritableDir('/Applications')) candidates.push('/Applications/Synlexa Studio.app');
393
+ } else if (platform === 'linux') {
394
+ const xdgDataHome = process.env.XDG_DATA_HOME || join(home, '.local', 'share');
395
+ candidates.push(join(xdgDataHome, 'applications', 'synlexa-studio.desktop'));
396
+ candidates.push(join(resolveLinuxDesktopDir(home), 'synlexa-studio.desktop'));
397
+ } else if (platform === 'win32') {
398
+ const desktopDir = process.env.SYNLEXA_DESKTOP_DIR || join(home, 'Desktop');
399
+ const programsDir =
400
+ process.env.SYNLEXA_PROGRAMS_DIR ||
401
+ join(process.env.APPDATA || join(home, 'AppData', 'Roaming'), 'Microsoft', 'Windows', 'Start Menu', 'Programs');
402
+ candidates.push(join(desktopDir, 'Synlexa Studio.lnk'));
403
+ candidates.push(join(programsDir, 'Synlexa Studio.lnk'));
404
+ }
405
+
406
+ for (const target of candidates) {
407
+ if (existsSync(target)) {
408
+ rmSync(target, { recursive: true, force: true });
409
+ removed.push(target);
410
+ }
411
+ }
412
+ return removed;
413
+ }
@@ -0,0 +1,184 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { spawnSync } from 'node:child_process';
3
+ import {
4
+ chmodSync,
5
+ existsSync,
6
+ mkdirSync,
7
+ mkdtempSync,
8
+ readdirSync,
9
+ readFileSync,
10
+ rmSync,
11
+ writeFileSync,
12
+ } from 'node:fs';
13
+ import { homedir, tmpdir } from 'node:os';
14
+ import { join } from 'node:path';
15
+ import { findNativeBinary, installDesktopShortcut, PKG_ROOT, readPackageMeta } from './desktop-shortcut.mjs';
16
+
17
+ const hasWasm = existsSync(join(PKG_ROOT, 'wasm', 'synlexa_bio_core.wasm'));
18
+ if (!hasWasm) {
19
+ console.log('[synlexa-studio] Installed launcher (native runtime or Wasm core will be resolved at runtime).');
20
+ }
21
+
22
+ function getRuntimeArchiveName(version) {
23
+ const key = `${process.platform}-${process.arch}`;
24
+ if (process.platform === 'darwin') return `synlexa-studio-v${version}-universal-apple-darwin.tar.gz`;
25
+ if (key === 'linux-x64') return `synlexa-studio-v${version}-x86_64-unknown-linux-gnu.tar.gz`;
26
+ if (key === 'linux-arm64') return `synlexa-studio-v${version}-aarch64-unknown-linux-gnu.tar.gz`;
27
+ if (key === 'win32-x64') return `Synlexa-Studio-v${version}-windows-x64.zip`;
28
+ if (key === 'win32-arm64') return `Synlexa-Studio-v${version}-windows-arm64.zip`;
29
+ return null;
30
+ }
31
+
32
+ async function fetchWithTimeout(url, timeoutMs) {
33
+ const controller = new AbortController();
34
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
35
+ try {
36
+ const res = await fetch(url, { signal: controller.signal, redirect: 'follow' });
37
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
38
+ return new Uint8Array(await res.arrayBuffer());
39
+ } finally {
40
+ clearTimeout(timer);
41
+ }
42
+ }
43
+
44
+ async function fetchFirstAvailable(urls, timeoutMs) {
45
+ let lastErr = null;
46
+ for (const url of urls) {
47
+ try {
48
+ return await fetchWithTimeout(url, timeoutMs);
49
+ } catch (err) {
50
+ lastErr = err;
51
+ }
52
+ }
53
+ throw lastErr || new Error('Download failed');
54
+ }
55
+
56
+ async function ensureVerifiedNativeRuntime(version) {
57
+ const archiveName = getRuntimeArchiveName(version);
58
+ if (!archiveName) return false;
59
+
60
+ const home = process.env.HOME || process.env.USERPROFILE || homedir();
61
+ const installDir = process.env.SYNLEXA_INSTALL_DIR || join(home, '.synlexa-studio', 'runtime');
62
+ const versionStampPath = join(installDir, '.version');
63
+ const existingHost = findNativeBinary('synlexa-studio-desktop-native');
64
+
65
+ if (existingHost && existsSync(versionStampPath) && readFileSync(versionStampPath, 'utf8').trim() === version) {
66
+ return true;
67
+ }
68
+
69
+ const primaryBase =
70
+ process.env.SYNLEXA_RELEASES_BASE || `https://github.com/Synlexa/synlexa-studio/releases/download/v${version}`;
71
+ const mirrorBase = 'https://studio.synlexa.com/releases';
72
+
73
+ const sumsBytes = await fetchFirstAvailable(
74
+ [`${primaryBase}/SHA256SUMS.txt`, `${mirrorBase}/SHA256SUMS.txt`],
75
+ 15000,
76
+ );
77
+ const sumsText = Buffer.from(sumsBytes).toString('utf8');
78
+ let expectedSha = null;
79
+ for (const line of sumsText.split(/\r?\n/)) {
80
+ const m = line.trim().match(/^([0-9a-fA-F]{64})\s+\*?(.+)$/);
81
+ if (m && m[2].trim() === archiveName) {
82
+ expectedSha = m[1].toLowerCase();
83
+ break;
84
+ }
85
+ }
86
+ if (!expectedSha) {
87
+ throw new Error(`Checksum for ${archiveName} not found in SHA256SUMS.txt`);
88
+ }
89
+
90
+ const archiveBytes = await fetchFirstAvailable(
91
+ [`${primaryBase}/${archiveName}`, `${mirrorBase}/${archiveName}`],
92
+ 60000,
93
+ );
94
+ const actualSha = createHash('sha256').update(archiveBytes).digest('hex').toLowerCase();
95
+ if (actualSha !== expectedSha) {
96
+ throw new Error(`SHA-256 verification failed for ${archiveName}`);
97
+ }
98
+
99
+ const tmpDir = mkdtempSync(join(tmpdir(), 'synlexa-runtime-'));
100
+ try {
101
+ const archivePath = join(tmpDir, archiveName);
102
+ writeFileSync(archivePath, archiveBytes);
103
+
104
+ rmSync(join(installDir, 'bin'), { recursive: true, force: true });
105
+ rmSync(join(installDir, 'web-dist'), { recursive: true, force: true });
106
+ mkdirSync(installDir, { recursive: true });
107
+
108
+ if (archiveName.endsWith('.zip')) {
109
+ const res = spawnSync(
110
+ 'powershell.exe',
111
+ [
112
+ '-NoProfile',
113
+ '-NonInteractive',
114
+ '-ExecutionPolicy',
115
+ 'Bypass',
116
+ '-Command',
117
+ 'Unblock-File -Path $env:SYNLEXA_ARCHIVE -ErrorAction SilentlyContinue; Expand-Archive -Path $env:SYNLEXA_ARCHIVE -DestinationPath $env:SYNLEXA_DEST -Force; Get-ChildItem -Path (Join-Path $env:SYNLEXA_DEST "bin") -Filter "*.exe" -ErrorAction SilentlyContinue | Unblock-File -ErrorAction SilentlyContinue',
118
+ ],
119
+ {
120
+ stdio: 'pipe',
121
+ env: { ...process.env, SYNLEXA_ARCHIVE: archivePath, SYNLEXA_DEST: installDir },
122
+ },
123
+ );
124
+ if (res.status !== 0) {
125
+ throw new Error(res.stderr?.toString() || 'Failed to extract Windows runtime archive');
126
+ }
127
+ } else {
128
+ const res = spawnSync('tar', ['-xzf', archivePath, '-C', installDir], { stdio: 'pipe' });
129
+ if (res.status !== 0) {
130
+ throw new Error(res.stderr?.toString() || 'Failed to extract runtime archive');
131
+ }
132
+ const binDir = join(installDir, 'bin');
133
+ if (existsSync(binDir)) {
134
+ for (const item of readdirSync(binDir)) {
135
+ chmodSync(join(binDir, item), 0o755);
136
+ }
137
+ }
138
+ if (process.platform === 'darwin') {
139
+ spawnSync('xattr', ['-cr', installDir], { stdio: 'ignore' });
140
+ if (existsSync(binDir)) {
141
+ for (const item of readdirSync(binDir)) {
142
+ spawnSync('codesign', ['--force', '--sign', '-', join(binDir, item)], { stdio: 'ignore' });
143
+ }
144
+ }
145
+ }
146
+ }
147
+
148
+ writeFileSync(versionStampPath, `${version}\n`, 'utf8');
149
+ return true;
150
+ } finally {
151
+ rmSync(tmpDir, { recursive: true, force: true });
152
+ }
153
+ }
154
+
155
+ const isCi = process.env.CI === 'true' || process.env.GITHUB_ACTIONS === 'true';
156
+ const optOut = process.env.SYNLEXA_NO_DESKTOP_ICON === '1';
157
+ const isGlobalInstall = process.env.npm_config_global === 'true' || process.env.SYNLEXA_DESKTOP_ICON === '1';
158
+
159
+ if (!isCi && !optOut && isGlobalInstall) {
160
+ const meta = readPackageMeta();
161
+ const version = meta.version || '0.4.3';
162
+
163
+ if (process.env.SYNLEXA_SKIP_RUNTIME_DOWNLOAD !== '1') {
164
+ try {
165
+ const ok = await ensureVerifiedNativeRuntime(version);
166
+ if (ok) {
167
+ console.log(`[synlexa-studio] Verified native desktop runtime v${version}.`);
168
+ }
169
+ } catch (err) {
170
+ const msg = err instanceof Error ? err.message : String(err);
171
+ console.warn(`[synlexa-studio] Native runtime download skipped (${msg}); using bundled Wasm/Web runtime.`);
172
+ }
173
+ }
174
+
175
+ try {
176
+ const installed = installDesktopShortcut();
177
+ if (installed.length > 0) {
178
+ console.log(`[synlexa-studio] Added Synlexa Studio launcher icon: ${installed.join(', ')}`);
179
+ }
180
+ } catch (err) {
181
+ const msg = err instanceof Error ? err.message : String(err);
182
+ console.warn(`[synlexa-studio] Desktop shortcut setup skipped (${msg}). Run "synlexa-studio install-desktop" later to create it.`);
183
+ }
184
+ }
Binary file