'use strict'; const fs=require('node:fs'),path=require('node:path'),{execFileSync}=require('node:child_process'),{SupervisorStore}=require('./supervisor-store.cjs'); function powershell(script,data){ const source=fs.readFileSync(path.join(__dirname,'windows-shortcut.cs'),'utf8'); const prefix="$ErrorActionPreference=\"Stop\"; [Console]::InputEncoding=New-Object System.Text.UTF8Encoding; [Console]::OutputEncoding=New-Object System.Text.UTF8Encoding; Add-Type -TypeDefinition @'\n"+source+"\n'@\n"; return execFileSync('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-Command',prefix+script],{input:JSON.stringify(data),encoding:'utf8',windowsHide:true,timeout:15000,stdio:['pipe','pipe','pipe']}).trim(); } function locations({stateDir,startupDir}){ if(process.platform!=='win32')throw Error('登录自启动仅支持 Windows。'); const root=path.resolve(startupDir||path.join(process.env.APPDATA,'Microsoft','Windows','Start Menu','Programs','Startup')); return {linkPath:path.join(root,'OrderNotificationAutomation.lnk'),launcherPath:path.join(path.resolve(stateDir),'supervisor','logon-launch.vbs'),wscript:path.join(process.env.SystemRoot,'System32','wscript.exe')}; } function readShortcut(file){const raw=powershell('$d=[Console]::In.ReadToEnd()|ConvertFrom-Json; $s=[OrderShortcut]::Read($d.file); @{target=$s[0];args=$s[1]}|ConvertTo-Json -Compress',{file});return JSON.parse(raw);} function ownedShortcut(paths){if(!fs.existsSync(paths.linkPath))return true;const old=readShortcut(paths.linkPath);return path.resolve(old.target).toLowerCase()===path.resolve(paths.wscript).toLowerCase()&&old.args==='//B "'+paths.launcherPath+'"';} function removeFile(file){try{fs.unlinkSync(file);}catch(e){if(e.code!=='ENOENT')throw e;}if(fs.existsSync(file))throw Error('无法确认自启动文件已移除。');} function writeShortcut({paths,projectRoot}){powershell('$d=[Console]::In.ReadToEnd()|ConvertFrom-Json; [OrderShortcut]::Save($d.link,$d.target,$d.args,$d.cwd)',{link:paths.linkPath,target:paths.wscript,args:'//B "'+paths.launcherPath+'"',cwd:path.resolve(projectRoot)});} function installAutostart({stateDir,projectRoot=path.resolve(__dirname,'..'),nodePath=process.execPath,startupDir,shortcutWriter=writeShortcut}={}){ const paths=locations({stateDir,startupDir}),store=new SupervisorStore(stateDir); try{ if(!ownedShortcut(paths))throw Error('同名启动快捷方式属于其他程序,未覆盖。'); const cli=path.join(path.resolve(projectRoot),'scripts','service.cjs');fs.accessSync(nodePath);fs.accessSync(cli); const command='"'+nodePath+'" "'+cli+'" run'; const source='Set shell = CreateObject("WScript.Shell")\r\nshell.Run "'+command.replace(/"/g,'""')+'", 0, False\r\n'; fs.writeFileSync(paths.launcherPath,Buffer.concat([Buffer.from([0xff,0xfe]),Buffer.from(source,'utf16le')]),{mode:0o600}); fs.mkdirSync(path.dirname(paths.linkPath),{recursive:true}); shortcutWriter({paths,projectRoot}); if(!fs.existsSync(paths.linkPath)||!ownedShortcut(paths))throw Error('启动快捷方式验证失败。'); const record={enabled:true,method:'current_user_logon',installedAt:new Date().toISOString(),...paths};store.set('autostart',record);store.event('autostart_installed');return record; }finally{store.close();} } function uninstallAutostart({stateDir,startupDir}={}){ const paths=locations({stateDir,startupDir}),store=new SupervisorStore(stateDir); try{if(!ownedShortcut(paths))throw Error('启动快捷方式已被更改,未删除。');removeFile(paths.linkPath);removeFile(paths.launcherPath);store.set('autostart',{enabled:false,method:'current_user_logon',removedAt:new Date().toISOString()});store.event('autostart_removed');return {enabled:false};}finally{store.close();} } module.exports={installAutostart,uninstallAutostart,readShortcut};