@synlexa/studio 0.0.0-stage → 0.4.4

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 +73 -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 +245 -0
  9. package/package.json +38 -4
  10. package/scripts/desktop-shortcut.mjs +610 -0
  11. package/scripts/postinstall.mjs +13 -0
  12. package/wasm/synlexa_bio_core.wasm +0 -0
  13. package/web-dist/assets/MolStarViewport-BEGb0UZJ.js +8197 -0
  14. package/web-dist/assets/MolStarViewport-BYVdqMR8.css +1 -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-OgQ3RYDT.js +845 -0
  18. package/web-dist/assets/node.browser-BFtyutLR.js +1 -0
  19. package/web-dist/assets/node.browser-BoI8HeAS.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,610 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { createRequire } from 'node:module';
3
+ import {
4
+ accessSync,
5
+ chmodSync,
6
+ constants,
7
+ cpSync,
8
+ existsSync,
9
+ lstatSync,
10
+ mkdirSync,
11
+ mkdtempSync,
12
+ readdirSync,
13
+ readFileSync,
14
+ rmSync,
15
+ symlinkSync,
16
+ writeFileSync,
17
+ } from 'node:fs';
18
+ import { spawnSync } from 'node:child_process';
19
+ import { homedir, tmpdir, userInfo } from 'node:os';
20
+ import { dirname, join, resolve } from 'node:path';
21
+ import { fileURLToPath } from 'node:url';
22
+
23
+ const __dirname = dirname(fileURLToPath(import.meta.url));
24
+ export const PKG_ROOT = resolve(__dirname, '..');
25
+
26
+ export const PLATFORM_MAP = {
27
+ 'darwin-arm64': '@synlexa/studio-darwin-arm64',
28
+ 'darwin-x64': '@synlexa/studio-darwin-x64',
29
+ 'linux-x64': '@synlexa/studio-linux-x64-gnu',
30
+ 'linux-arm64': '@synlexa/studio-linux-arm64-gnu',
31
+ 'win32-x64': '@synlexa/studio-win32-x64-msvc',
32
+ 'win32-arm64': '@synlexa/studio-win32-arm64-msvc',
33
+ };
34
+
35
+ const require = createRequire(import.meta.url);
36
+
37
+ export function readPackageMeta() {
38
+ return JSON.parse(readFileSync(join(PKG_ROOT, 'package.json'), 'utf8'));
39
+ }
40
+
41
+ export function findNativeBinary(name, pkgRoot = PKG_ROOT) {
42
+ const pkgName = PLATFORM_MAP[`${process.platform}-${process.arch}`];
43
+ const ext = process.platform === 'win32' ? '.exe' : '';
44
+ const names =
45
+ process.platform === 'win32' && name === 'synlexa-studio-desktop-native'
46
+ ? ['synlexa-studio-desktop-native.exe', 'synlexa-studio.exe']
47
+ : [`${name}${ext}`];
48
+
49
+ if (pkgName) {
50
+ try {
51
+ const pkgJsonPath = require.resolve(`${pkgName}/package.json`);
52
+ for (const binName of names) {
53
+ const candidate = join(dirname(pkgJsonPath), 'bin', binName);
54
+ if (existsSync(candidate)) return candidate;
55
+ }
56
+ } catch {
57
+ // Optional native package not installed; try local/home runtime fallbacks
58
+ }
59
+ }
60
+ for (const binName of names) {
61
+ const localCandidate = join(pkgRoot, 'bin', binName);
62
+ if (existsSync(localCandidate)) return localCandidate;
63
+ }
64
+
65
+ const home = process.env.HOME || process.env.USERPROFILE || '';
66
+ const runtimeDir = process.env.SYNLEXA_INSTALL_DIR || (home ? join(home, '.synlexa-studio', 'runtime') : '');
67
+ if (runtimeDir) {
68
+ for (const binName of names) {
69
+ const homeCandidate = join(runtimeDir, 'bin', binName);
70
+ if (existsSync(homeCandidate)) return homeCandidate;
71
+ }
72
+ }
73
+ return null;
74
+ }
75
+
76
+ function isWritableDir(dir) {
77
+ try {
78
+ accessSync(dir, constants.W_OK);
79
+ return true;
80
+ } catch {
81
+ return false;
82
+ }
83
+ }
84
+
85
+ function escapeShDoubleQuoted(value) {
86
+ return value.replace(/(["\\$`])/g, '\\$1');
87
+ }
88
+
89
+ function quoteDesktopExecArg(value) {
90
+ if (/^[A-Za-z0-9_./:-]+$/.test(value)) return value;
91
+ return `"${value.replace(/(["\\$`])/g, '\\$1')}"`;
92
+ }
93
+
94
+ function buildInfoPlist(version, executableName) {
95
+ return `<?xml version="1.0" encoding="UTF-8"?>
96
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
97
+ <plist version="1.0">
98
+ <dict>
99
+ <key>CFBundleName</key><string>Synlexa Studio</string>
100
+ <key>CFBundleDisplayName</key><string>Synlexa Studio</string>
101
+ <key>CFBundleIdentifier</key><string>com.synlexa.studio</string>
102
+ <key>CFBundleVersion</key><string>${version}</string>
103
+ <key>CFBundleShortVersionString</key><string>${version}</string>
104
+ <key>CFBundlePackageType</key><string>APPL</string>
105
+ <key>CFBundleExecutable</key><string>${executableName}</string>
106
+ <key>CFBundleIconFile</key><string>icon.icns</string>
107
+ <key>NSHighResolutionCapable</key><true/>
108
+ <key>LSMinimumSystemVersion</key><string>11.0</string>
109
+ <key>CFBundleURLTypes</key>
110
+ <array>
111
+ <dict>
112
+ <key>CFBundleURLName</key><string>com.synlexa.studio.auth</string>
113
+ <key>CFBundleURLSchemes</key><array><string>synlexa-studio</string></array>
114
+ </dict>
115
+ </array>
116
+ </dict>
117
+ </plist>
118
+ `;
119
+ }
120
+
121
+ function installMacosDesktopShortcut({ version, nativeHost, nativeCli, distDir, cliEntry, nodeExe }) {
122
+ const home = process.env.HOME || homedir();
123
+ let realHome = home;
124
+ try {
125
+ realHome = userInfo().homedir || home;
126
+ } catch {
127
+ // fallback if passwd entry unavailable
128
+ }
129
+ const useSystemApps = !process.env.SYNLEXA_APP_DIR && home === realHome && isWritableDir('/Applications');
130
+ const appParent = process.env.SYNLEXA_APP_DIR || (useSystemApps ? '/Applications' : join(home, 'Applications'));
131
+ mkdirSync(appParent, { recursive: true });
132
+
133
+ const appBundle = join(appParent, 'Synlexa Studio.app');
134
+ const contentsDir = join(appBundle, 'Contents');
135
+ const macosDir = join(contentsDir, 'MacOS');
136
+ const resourcesDir = join(contentsDir, 'Resources');
137
+
138
+ rmSync(appBundle, { recursive: true, force: true });
139
+ mkdirSync(macosDir, { recursive: true });
140
+ mkdirSync(resourcesDir, { recursive: true });
141
+
142
+ const iconSrc = join(PKG_ROOT, 'assets', 'icon.icns');
143
+ if (existsSync(iconSrc)) {
144
+ cpSync(iconSrc, join(resourcesDir, 'icon.icns'));
145
+ }
146
+
147
+ let executableName = 'synlexa-studio-launcher';
148
+ if (nativeHost && existsSync(distDir)) {
149
+ executableName = 'synlexa-studio-desktop-native';
150
+ const destHost = join(macosDir, executableName);
151
+ cpSync(nativeHost, destHost);
152
+ chmodSync(destHost, 0o755);
153
+ if (nativeCli && existsSync(nativeCli)) {
154
+ const destCli = join(macosDir, 'studio-cli');
155
+ cpSync(nativeCli, destCli);
156
+ chmodSync(destCli, 0o755);
157
+ }
158
+ cpSync(distDir, join(resourcesDir, 'web-dist'), { recursive: true });
159
+ } else {
160
+ const launcherPath = join(macosDir, executableName);
161
+ const script = `#!/usr/bin/env sh
162
+ set -eu
163
+ PORT="\${SYNLEXA_PORT:-4179}"
164
+ URL="http://127.0.0.1:\${PORT}/"
165
+ NODE_BIN="${escapeShDoubleQuoted(nodeExe)}"
166
+ CLI_BIN="${escapeShDoubleQuoted(cliEntry)}"
167
+ LOG_FILE="\${HOME:-/tmp}/.synlexa-studio/launcher.log"
168
+ mkdir -p "$(dirname "$LOG_FILE")"
169
+ if ! curl -fsS --max-time 1 "$URL" >/dev/null 2>&1; then
170
+ nohup "$NODE_BIN" "$CLI_BIN" launch --port "$PORT" --no-open >"$LOG_FILE" 2>&1 &
171
+ for _ in 1 2 3 4 5 6 7 8 9 10; do
172
+ if curl -fsS --max-time 1 "$URL" >/dev/null 2>&1; then
173
+ break
174
+ fi
175
+ sleep 0.2
176
+ done
177
+ fi
178
+ if [ -x "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" ]; then
179
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --app="$URL" >/dev/null 2>&1 &
180
+ else
181
+ open "$URL"
182
+ fi
183
+ `;
184
+ writeFileSync(launcherPath, script, 'utf8');
185
+ chmodSync(launcherPath, 0o755);
186
+ }
187
+
188
+ writeFileSync(join(contentsDir, 'Info.plist'), buildInfoPlist(version, executableName), 'utf8');
189
+
190
+ spawnSync('xattr', ['-cr', appBundle], { stdio: 'ignore' });
191
+ spawnSync('codesign', ['--force', '--deep', '--sign', '-', appBundle], { stdio: 'ignore' });
192
+ spawnSync(
193
+ '/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister',
194
+ ['-f', appBundle],
195
+ { stdio: 'ignore' },
196
+ );
197
+
198
+ const created = [appBundle];
199
+ const desktopDir = process.env.SYNLEXA_DESKTOP_DIR || join(home, 'Desktop');
200
+ if (existsSync(desktopDir) && isWritableDir(desktopDir)) {
201
+ const desktopLink = join(desktopDir, 'Synlexa Studio.app');
202
+ let canWriteLink = true;
203
+ try {
204
+ const st = lstatSync(desktopLink);
205
+ if (st.isSymbolicLink() || st.isFile()) {
206
+ rmSync(desktopLink, { force: true });
207
+ } else {
208
+ canWriteLink = false;
209
+ }
210
+ } catch {
211
+ // Does not exist yet
212
+ }
213
+ if (canWriteLink) {
214
+ symlinkSync(appBundle, desktopLink);
215
+ created.push(desktopLink);
216
+ }
217
+ }
218
+ return created;
219
+ }
220
+
221
+ function resolveLinuxDesktopDir(home) {
222
+ if (process.env.SYNLEXA_DESKTOP_DIR) return process.env.SYNLEXA_DESKTOP_DIR;
223
+ const xdg = spawnSync('xdg-user-dir', ['DESKTOP'], { encoding: 'utf8' });
224
+ if (xdg.status === 0 && xdg.stdout) {
225
+ const candidate = xdg.stdout.trim();
226
+ if (candidate && candidate !== home && existsSync(candidate)) {
227
+ return candidate;
228
+ }
229
+ }
230
+ return join(home, 'Desktop');
231
+ }
232
+
233
+ function installLinuxDesktopShortcut({ nativeHost, distDir, cliEntry, nodeExe }) {
234
+ const home = process.env.HOME || homedir();
235
+ const xdgDataHome = process.env.XDG_DATA_HOME || join(home, '.local', 'share');
236
+ const appsDir = join(xdgDataHome, 'applications');
237
+ const icons256Dir = join(xdgDataHome, 'icons', 'hicolor', '256x256', 'apps');
238
+ const icons1024Dir = join(xdgDataHome, 'icons', 'hicolor', '1024x1024', 'apps');
239
+
240
+ mkdirSync(appsDir, { recursive: true });
241
+ mkdirSync(icons256Dir, { recursive: true });
242
+ mkdirSync(icons1024Dir, { recursive: true });
243
+
244
+ const icon1024Src = join(PKG_ROOT, 'assets', 'icon.png');
245
+ const icon256Src = join(PKG_ROOT, 'assets', 'icon-256.png');
246
+ const installedIcon1024 = join(icons1024Dir, 'synlexa-studio.png');
247
+ const installedIcon256 = join(icons256Dir, 'synlexa-studio.png');
248
+
249
+ if (existsSync(icon1024Src)) cpSync(icon1024Src, installedIcon1024);
250
+ if (existsSync(icon256Src)) {
251
+ cpSync(icon256Src, installedIcon256);
252
+ } else if (existsSync(icon1024Src)) {
253
+ cpSync(icon1024Src, installedIcon256);
254
+ }
255
+
256
+ const iconField = existsSync(installedIcon1024) ? installedIcon1024 : 'synlexa-studio';
257
+ const execLine =
258
+ nativeHost && existsSync(distDir)
259
+ ? `${quoteDesktopExecArg(nativeHost)} --dist ${quoteDesktopExecArg(distDir)}`
260
+ : `${quoteDesktopExecArg(nodeExe)} ${quoteDesktopExecArg(cliEntry)} launch`;
261
+
262
+ const desktopEntry = `[Desktop Entry]
263
+ Version=1.0
264
+ Type=Application
265
+ Name=Synlexa Studio
266
+ GenericName=Computational Biology Workbench
267
+ Comment=Deterministic Structural Biology & Cheminformatics Workbench (Research-Use-Only)
268
+ Exec=${execLine}
269
+ Icon=${iconField}
270
+ Categories=Science;Education;Development;
271
+ Keywords=Synlexa;Bioinformatics;Protein;MolStar;SMILES;CRISPR;MCP;
272
+ Terminal=false
273
+ StartupNotify=true
274
+ `;
275
+
276
+ const created = [];
277
+ const appDesktopFile = join(appsDir, 'synlexa-studio.desktop');
278
+ writeFileSync(appDesktopFile, desktopEntry, 'utf8');
279
+ chmodSync(appDesktopFile, 0o755);
280
+ created.push(appDesktopFile);
281
+
282
+ const desktopDir = resolveLinuxDesktopDir(home);
283
+ if (existsSync(desktopDir) && isWritableDir(desktopDir)) {
284
+ const desktopFile = join(desktopDir, 'synlexa-studio.desktop');
285
+ writeFileSync(desktopFile, desktopEntry, 'utf8');
286
+ chmodSync(desktopFile, 0o755);
287
+ spawnSync('gio', ['set', desktopFile, 'metadata::trusted', 'true'], { stdio: 'ignore' });
288
+ created.push(desktopFile);
289
+ }
290
+
291
+ spawnSync('update-desktop-database', [appsDir], { stdio: 'ignore' });
292
+ return created;
293
+ }
294
+
295
+ function installWindowsDesktopShortcut({ nativeHost, distDir, cliEntry, nodeExe }) {
296
+ const home = process.env.USERPROFILE || process.env.HOME || homedir();
297
+ const iconIco = join(PKG_ROOT, 'assets', 'icon.ico');
298
+ const targetPath = nativeHost && existsSync(distDir) ? nativeHost : nodeExe;
299
+ const targetArgs =
300
+ nativeHost && existsSync(distDir) ? `--dist "${distDir}"` : `"${cliEntry}" launch`;
301
+
302
+ const psScript = `
303
+ $ErrorActionPreference = 'Stop'
304
+ $WshShell = New-Object -ComObject WScript.Shell
305
+ $Targets = @()
306
+ $DesktopDir = if ($env:SYNLEXA_DESKTOP_DIR) { $env:SYNLEXA_DESKTOP_DIR } else { [Environment]::GetFolderPath('Desktop') }
307
+ $ProgramsDir = if ($env:SYNLEXA_PROGRAMS_DIR) { $env:SYNLEXA_PROGRAMS_DIR } else { [Environment]::GetFolderPath('Programs') }
308
+ if ($DesktopDir -and (Test-Path $DesktopDir)) { $Targets += (Join-Path $DesktopDir 'Synlexa Studio.lnk') }
309
+ if ($ProgramsDir) {
310
+ New-Item -ItemType Directory -Force -Path $ProgramsDir | Out-Null
311
+ $Targets += (Join-Path $ProgramsDir 'Synlexa Studio.lnk')
312
+ }
313
+ foreach ($LnkPath in $Targets) {
314
+ $Sc = $WshShell.CreateShortcut($LnkPath)
315
+ $Sc.TargetPath = $env:SYNLEXA_SC_TARGET
316
+ $Sc.Arguments = $env:SYNLEXA_SC_ARGS
317
+ $Sc.WorkingDirectory = $env:SYNLEXA_SC_WORKDIR
318
+ $Sc.Description = 'Synlexa Studio — Deterministic Structural Biology & Cheminformatics Workbench (RUO)'
319
+ $Sc.WindowStyle = 7
320
+ if ($env:SYNLEXA_SC_ICON -and (Test-Path $env:SYNLEXA_SC_ICON)) {
321
+ $Sc.IconLocation = "$($env:SYNLEXA_SC_ICON),0"
322
+ }
323
+ $Sc.Save()
324
+ Write-Output $LnkPath
325
+ }
326
+ `;
327
+
328
+ const res = spawnSync(
329
+ 'powershell.exe',
330
+ ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', psScript],
331
+ {
332
+ encoding: 'utf8',
333
+ env: {
334
+ ...process.env,
335
+ SYNLEXA_SC_TARGET: targetPath,
336
+ SYNLEXA_SC_ARGS: targetArgs,
337
+ SYNLEXA_SC_ICON: existsSync(iconIco) ? iconIco : '',
338
+ SYNLEXA_SC_WORKDIR: home,
339
+ },
340
+ },
341
+ );
342
+ if (res.status !== 0) {
343
+ throw new Error(res.stderr || 'Failed to create Windows desktop shortcut');
344
+ }
345
+ return (res.stdout || '')
346
+ .split(/\r?\n/)
347
+ .map((s) => s.trim())
348
+ .filter(Boolean);
349
+ }
350
+
351
+ /**
352
+ * Installs a clickable Synlexa Studio icon onto the user's Desktop and OS app launcher.
353
+ */
354
+ export function installDesktopShortcut({ platform = process.platform } = {}) {
355
+ const meta = readPackageMeta();
356
+ const version = meta.version || '0.4.1';
357
+ const nativeHost = findNativeBinary('synlexa-studio-desktop-native');
358
+ const nativeCli = findNativeBinary('studio-cli');
359
+ const distDir = join(PKG_ROOT, 'web-dist');
360
+ const cliEntry = join(PKG_ROOT, 'bin', 'synlexa-studio.mjs');
361
+ const nodeExe = process.execPath;
362
+
363
+ const opts = { version, nativeHost, nativeCli, distDir, cliEntry, nodeExe };
364
+ if (platform === 'darwin') return installMacosDesktopShortcut(opts);
365
+ if (platform === 'linux') return installLinuxDesktopShortcut(opts);
366
+ if (platform === 'win32') return installWindowsDesktopShortcut(opts);
367
+ return [];
368
+ }
369
+
370
+ /**
371
+ * Removes Synlexa Studio Desktop / Applications shortcuts created by npm install.
372
+ */
373
+ export function uninstallDesktopShortcut({ platform = process.platform } = {}) {
374
+ const removed = [];
375
+ const home = process.env.HOME || process.env.USERPROFILE || homedir();
376
+ const candidates = [];
377
+
378
+ if (platform === 'darwin') {
379
+ const desktopDir = process.env.SYNLEXA_DESKTOP_DIR || join(home, 'Desktop');
380
+ const desktopLink = join(desktopDir, 'Synlexa Studio.app');
381
+ try {
382
+ if (lstatSync(desktopLink).isSymbolicLink()) candidates.push(desktopLink);
383
+ } catch {
384
+ // ignore
385
+ }
386
+ const appDir = process.env.SYNLEXA_APP_DIR;
387
+ if (appDir) candidates.push(join(appDir, 'Synlexa Studio.app'));
388
+ candidates.push(join(home, 'Applications', 'Synlexa Studio.app'));
389
+ let realHome = home;
390
+ try {
391
+ realHome = userInfo().homedir || home;
392
+ } catch {
393
+ // ignore
394
+ }
395
+ if (home === realHome && isWritableDir('/Applications')) candidates.push('/Applications/Synlexa Studio.app');
396
+ } else if (platform === 'linux') {
397
+ const xdgDataHome = process.env.XDG_DATA_HOME || join(home, '.local', 'share');
398
+ candidates.push(join(xdgDataHome, 'applications', 'synlexa-studio.desktop'));
399
+ candidates.push(join(resolveLinuxDesktopDir(home), 'synlexa-studio.desktop'));
400
+ } else if (platform === 'win32') {
401
+ const desktopDir = process.env.SYNLEXA_DESKTOP_DIR || join(home, 'Desktop');
402
+ const programsDir =
403
+ process.env.SYNLEXA_PROGRAMS_DIR ||
404
+ join(process.env.APPDATA || join(home, 'AppData', 'Roaming'), 'Microsoft', 'Windows', 'Start Menu', 'Programs');
405
+ candidates.push(join(desktopDir, 'Synlexa Studio.lnk'));
406
+ candidates.push(join(programsDir, 'Synlexa Studio.lnk'));
407
+ }
408
+
409
+ for (const target of candidates) {
410
+ if (existsSync(target)) {
411
+ rmSync(target, { recursive: true, force: true });
412
+ removed.push(target);
413
+ }
414
+ }
415
+ const stateDir = join(home, '.synlexa-studio');
416
+ if (existsSync(stateDir)) {
417
+ for (const entry of readdirSync(stateDir)) {
418
+ if (entry.startsWith('.desktop-setup-v')) {
419
+ rmSync(join(stateDir, entry), { force: true });
420
+ }
421
+ }
422
+ }
423
+ return removed;
424
+ }
425
+
426
+ function getRuntimeArchiveName(version) {
427
+ const key = `${process.platform}-${process.arch}`;
428
+ if (process.platform === 'darwin') return `synlexa-studio-v${version}-universal-apple-darwin.tar.gz`;
429
+ if (key === 'linux-x64') return `synlexa-studio-v${version}-x86_64-unknown-linux-gnu.tar.gz`;
430
+ if (key === 'linux-arm64') return `synlexa-studio-v${version}-aarch64-unknown-linux-gnu.tar.gz`;
431
+ if (key === 'win32-x64') return `Synlexa-Studio-v${version}-windows-x64.zip`;
432
+ if (key === 'win32-arm64') return `Synlexa-Studio-v${version}-windows-arm64.zip`;
433
+ return null;
434
+ }
435
+
436
+ async function fetchWithTimeout(url, timeoutMs) {
437
+ const controller = new AbortController();
438
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
439
+ try {
440
+ const res = await fetch(url, { signal: controller.signal, redirect: 'follow' });
441
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
442
+ return new Uint8Array(await res.arrayBuffer());
443
+ } finally {
444
+ clearTimeout(timer);
445
+ }
446
+ }
447
+
448
+ async function fetchFirstAvailable(urls, timeoutMs) {
449
+ let lastErr = null;
450
+ for (const url of urls) {
451
+ try {
452
+ return await fetchWithTimeout(url, timeoutMs);
453
+ } catch (err) {
454
+ lastErr = err;
455
+ }
456
+ }
457
+ throw lastErr || new Error('Download failed');
458
+ }
459
+
460
+ /**
461
+ * Downloads and SHA-256 verifies the native desktop runtime archive into ~/.synlexa-studio/runtime.
462
+ */
463
+ export async function ensureVerifiedNativeRuntime(version) {
464
+ const archiveName = getRuntimeArchiveName(version);
465
+ if (!archiveName) return false;
466
+
467
+ const home = process.env.HOME || process.env.USERPROFILE || homedir();
468
+ const installDir = process.env.SYNLEXA_INSTALL_DIR || join(home, '.synlexa-studio', 'runtime');
469
+ const versionStampPath = join(installDir, '.version');
470
+ const existingHost = findNativeBinary('synlexa-studio-desktop-native');
471
+
472
+ if (existingHost && existsSync(versionStampPath) && readFileSync(versionStampPath, 'utf8').trim() === version) {
473
+ return true;
474
+ }
475
+
476
+ const primaryBase =
477
+ process.env.SYNLEXA_RELEASES_BASE || `https://github.com/Synlexa/synlexa-studio/releases/download/v${version}`;
478
+ const mirrorBase = 'https://studio.synlexa.com/releases';
479
+
480
+ const sumsBytes = await fetchFirstAvailable(
481
+ [`${primaryBase}/SHA256SUMS.txt`, `${mirrorBase}/SHA256SUMS.txt`],
482
+ 15000,
483
+ );
484
+ const sumsText = Buffer.from(sumsBytes).toString('utf8');
485
+ let expectedSha = null;
486
+ for (const line of sumsText.split(/\r?\n/)) {
487
+ const m = line.trim().match(/^([0-9a-fA-F]{64})\s+\*?(.+)$/);
488
+ if (m && m[2].trim() === archiveName) {
489
+ expectedSha = m[1].toLowerCase();
490
+ break;
491
+ }
492
+ }
493
+ if (!expectedSha) {
494
+ throw new Error(`Checksum for ${archiveName} not found in SHA256SUMS.txt`);
495
+ }
496
+
497
+ const archiveBytes = await fetchFirstAvailable(
498
+ [`${primaryBase}/${archiveName}`, `${mirrorBase}/${archiveName}`],
499
+ 60000,
500
+ );
501
+ const actualSha = createHash('sha256').update(archiveBytes).digest('hex').toLowerCase();
502
+ if (actualSha !== expectedSha) {
503
+ throw new Error(`SHA-256 verification failed for ${archiveName}`);
504
+ }
505
+
506
+ const tmpDir = mkdtempSync(join(tmpdir(), 'synlexa-runtime-'));
507
+ try {
508
+ const archivePath = join(tmpDir, archiveName);
509
+ writeFileSync(archivePath, archiveBytes);
510
+
511
+ rmSync(join(installDir, 'bin'), { recursive: true, force: true });
512
+ rmSync(join(installDir, 'web-dist'), { recursive: true, force: true });
513
+ mkdirSync(installDir, { recursive: true });
514
+
515
+ if (archiveName.endsWith('.zip')) {
516
+ const res = spawnSync(
517
+ 'powershell.exe',
518
+ [
519
+ '-NoProfile',
520
+ '-NonInteractive',
521
+ '-ExecutionPolicy',
522
+ 'Bypass',
523
+ '-Command',
524
+ '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',
525
+ ],
526
+ {
527
+ stdio: 'pipe',
528
+ env: { ...process.env, SYNLEXA_ARCHIVE: archivePath, SYNLEXA_DEST: installDir },
529
+ },
530
+ );
531
+ if (res.status !== 0) {
532
+ throw new Error(res.stderr?.toString() || 'Failed to extract Windows runtime archive');
533
+ }
534
+ } else {
535
+ const res = spawnSync('tar', ['-xzf', archivePath, '-C', installDir], { stdio: 'pipe' });
536
+ if (res.status !== 0) {
537
+ throw new Error(res.stderr?.toString() || 'Failed to extract runtime archive');
538
+ }
539
+ const binDir = join(installDir, 'bin');
540
+ if (existsSync(binDir)) {
541
+ for (const item of readdirSync(binDir)) {
542
+ chmodSync(join(binDir, item), 0o755);
543
+ }
544
+ }
545
+ if (process.platform === 'darwin') {
546
+ spawnSync('xattr', ['-cr', installDir], { stdio: 'ignore' });
547
+ if (existsSync(binDir)) {
548
+ for (const item of readdirSync(binDir)) {
549
+ spawnSync('codesign', ['--force', '--sign', '-', join(binDir, item)], { stdio: 'ignore' });
550
+ }
551
+ }
552
+ }
553
+ }
554
+
555
+ writeFileSync(versionStampPath, `${version}\n`, 'utf8');
556
+ return true;
557
+ } finally {
558
+ rmSync(tmpDir, { recursive: true, force: true });
559
+ }
560
+ }
561
+
562
+ /**
563
+ * Ensures the native runtime and Desktop/launcher shortcut are provisioned once per version.
564
+ * Covers both npm postinstall and npm v12+ first-launch execution (when allowScripts defaults off).
565
+ */
566
+ export async function ensureStudioDesktopSetup({ force = false, quiet = false } = {}) {
567
+ const isCi = process.env.CI === 'true' || process.env.GITHUB_ACTIONS === 'true';
568
+ const optOut = process.env.SYNLEXA_NO_DESKTOP_ICON === '1';
569
+ if (isCi || optOut) return [];
570
+
571
+ const meta = readPackageMeta();
572
+ const version = meta.version || '0.4.3';
573
+ const home = process.env.HOME || process.env.USERPROFILE || homedir();
574
+ const stateDir = join(home, '.synlexa-studio');
575
+ const markerPath = join(stateDir, `.desktop-setup-v${version}`);
576
+
577
+ if (!force && existsSync(markerPath)) {
578
+ return [];
579
+ }
580
+
581
+ if (process.env.SYNLEXA_SKIP_RUNTIME_DOWNLOAD !== '1') {
582
+ try {
583
+ const ok = await ensureVerifiedNativeRuntime(version);
584
+ if (ok && !quiet) {
585
+ console.log(`[synlexa-studio] Verified native desktop runtime v${version}.`);
586
+ }
587
+ } catch (err) {
588
+ if (!quiet) {
589
+ const msg = err instanceof Error ? err.message : String(err);
590
+ console.warn(`[synlexa-studio] Native runtime download skipped (${msg}); using bundled Wasm/Web runtime.`);
591
+ }
592
+ }
593
+ }
594
+
595
+ let installed = [];
596
+ try {
597
+ installed = installDesktopShortcut();
598
+ if (installed.length > 0 && !quiet) {
599
+ console.log(`[synlexa-studio] Added Synlexa Studio launcher icon: ${installed.join(', ')}`);
600
+ }
601
+ mkdirSync(stateDir, { recursive: true });
602
+ writeFileSync(markerPath, `${new Date().toISOString()}\n`, 'utf8');
603
+ } catch (err) {
604
+ if (!quiet) {
605
+ const msg = err instanceof Error ? err.message : String(err);
606
+ console.warn(`[synlexa-studio] Desktop shortcut setup skipped (${msg}). Run "synlexa-studio install-desktop" later to create it.`);
607
+ }
608
+ }
609
+ return installed;
610
+ }
@@ -0,0 +1,13 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { ensureStudioDesktopSetup, PKG_ROOT } from './desktop-shortcut.mjs';
4
+
5
+ const hasWasm = existsSync(join(PKG_ROOT, 'wasm', 'synlexa_bio_core.wasm'));
6
+ if (!hasWasm) {
7
+ console.log('[synlexa-studio] Installed launcher (native runtime or Wasm core will be resolved at runtime).');
8
+ }
9
+
10
+ const isGlobalInstall = process.env.npm_config_global === 'true' || process.env.SYNLEXA_DESKTOP_ICON === '1';
11
+ if (isGlobalInstall) {
12
+ await ensureStudioDesktopSetup({ force: true });
13
+ }
Binary file