# LoopCode command-line installer for Windows. # # irm https://loopcode.heksync.in/cli.ps1 | iex # # Installs the `loopcode` command for the current user - no administrator rights, nothing else to # install first - then signs you in. # %USERPROFILE%\.loopcode\app\\ the CLI (one JavaScript file) # %USERPROFILE%\.loopcode\runtime\ Node.js for LoopCode alone, when yours is missing or too old # %USERPROFILE%\.loopcode\bin\loopcode.cmd the command, a small launcher, added to your PATH # Your conversations and sign-in live in %USERPROFILE%\.loopcode\cli and are never touched here. # # Options (set before running): # $env:LOOPCODE_NO_MODIFY_PATH = "1" don't add the command's folder to your PATH # $env:LOOPCODE_NO_LOGIN = "1" don't start sign-in at the end # $env:LOOPCODE_NODE = "bundled" use LoopCode's own Node.js even when yours is new enough # $env:LOOPCODE_NODE_MIRROR = "" fetch Node.js from a mirror of https://nodejs.org/dist # Uninstall: # $env:LOOPCODE_UNINSTALL = "1"; irm https://loopcode.heksync.in/cli.ps1 | iex # # Everything happens inside Install-LoopCode, called on the last line, so a download cut off # halfway cannot run half an installer. This file is plain ASCII on purpose: Windows PowerShell # 5.1 misreads anything else when it downloads a script. function Install-LoopCode { [CmdletBinding()] param([switch]$Uninstall) $ErrorActionPreference = 'Stop' # The progress bar makes Invoke-WebRequest many times slower on Windows PowerShell 5.1. $ProgressPreference = 'SilentlyContinue' $RequiredNode = [version]'22.18.0' $Site = if ($env:LOOPCODE_INSTALL_SITE) { $env:LOOPCODE_INSTALL_SITE.TrimEnd('/') } else { 'https://loopcode.heksync.in' } $Root = Join-Path $env:USERPROFILE '.loopcode' $AppRoot = Join-Path $Root 'app' $BinDir = Join-Path $Root 'bin' $Launcher = Join-Path $BinDir 'loopcode.cmd' $Runtime = Join-Path $Root 'runtime' # The Node.js line LoopCode brings along: the newest 24.x, so its security fixes come with every install. $NodeDist = $(if ($env:LOOPCODE_NODE_MIRROR) { $env:LOOPCODE_NODE_MIRROR.TrimEnd('/') } else { 'https://nodejs.org/dist' }) + '/latest-v24.x' $Marker = 'rem loopcode-launcher' function Say([string]$Text = '') { Write-Host $Text } function Step([string]$Text) { Write-Host " $Text" -ForegroundColor DarkGray } function Fail([string]$Text) { Write-Host '' Write-Host " $Text" -ForegroundColor Red Write-Host '' throw 'LoopCode was not installed.' } # Node.js for LoopCode alone: the official build for this machine from nodejs.org, checked against # the checksums published beside it, tried before it replaces anything, kept in .loopcode\runtime. # It is never put on your PATH, so it cannot get in the way of a Node.js you install yourself. function Install-Runtime([string]$Tmp, [string]$Tar) { $arch = $null $machine = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE } if ($machine -eq 'AMD64') { $arch = 'x64' } elseif ($machine -eq 'ARM64') { $arch = 'arm64' } if (-not $arch) { Fail "LoopCode can't bring Node.js for this processor ($machine). Install Node.js $RequiredNode or newer (winget install OpenJS.NodeJS.LTS), then run this again." } try { $sums = (Invoke-WebRequest -Uri "$NodeDist/SHASUMS256.txt" -UseBasicParsing -TimeoutSec 60).Content } catch { Fail "Could not reach nodejs.org for Node.js. Check your connection, or install Node.js $RequiredNode or newer yourself (winget install OpenJS.NodeJS.LTS) and run this again." } if ($sums -is [byte[]]) { $sums = [Text.Encoding]::UTF8.GetString($sums) } $line = $sums -split "`n" | Where-Object { $_ -match "\s+node-v[0-9.]+-win-$arch\.zip\s*$" } | Select-Object -First 1 if (-not $line) { Fail "nodejs.org has no Node.js build for win-$arch. Install Node.js $RequiredNode or newer yourself, then run this again." } $parts = $line.Trim() -split '\s+' $expected = $parts[0].ToLowerInvariant() $file = $parts[1] $runtimeVersion = $file -replace '^node-v([0-9.]+)-.*$', '$1' $exe = Join-Path $Runtime 'node.exe' if (Test-Path $exe) { $have = (& $exe -p 'process.versions.node' 2>$null | Out-String).Trim() if ($have -eq $runtimeVersion) { Step "Node.js $runtimeVersion (LoopCode's own)"; return $exe } } Step "downloading Node.js $runtimeVersion for LoopCode (it stays in $Runtime)" $zip = Join-Path $Tmp $file try { Invoke-WebRequest -Uri "$NodeDist/$file" -OutFile $zip -UseBasicParsing -TimeoutSec 900 } catch { Fail 'The Node.js download failed. Please try again.' } $actual = (Get-FileHash -Path $zip -Algorithm SHA256).Hash.ToLowerInvariant() if ($actual -ne $expected) { Fail "The Node.js download did not match nodejs.org's checksum, so nothing was installed. Please try again." } $unzipDir = Join-Path $Tmp 'node' New-Item -ItemType Directory -Path $unzipDir | Out-Null # Windows' tar reads zip archives too, many times faster than Expand-Archive. & $Tar -xf $zip -C $unzipDir if ($LASTEXITCODE -ne 0) { Fail 'Node.js could not be unpacked. Please try again.' } $unpacked = Join-Path $unzipDir ($file -replace '\.zip$', '') $ran = (& (Join-Path $unpacked 'node.exe') -p 'process.versions.node' 2>$null | Out-String).Trim() if ($ran -ne $runtimeVersion) { Fail "Node.js did not start on this machine, so nothing was changed. Install Node.js $RequiredNode or newer yourself (winget install OpenJS.NodeJS.LTS), then run this again." } # LoopCode needs node.exe alone: npm and the rest stay behind (Node's LICENSE comes along). Get-ChildItem $unpacked -Force | Where-Object { $_.Name -ne 'node.exe' -and $_.Name -ne 'LICENSE' } | Remove-Item -Recurse -Force if (Test-Path $Runtime) { try { Remove-Item $Runtime -Recurse -Force } catch { Fail "Close any running loopcode first: its Node.js in $Runtime is in use. Then run this again." } } # On a first install .loopcode does not exist yet, and Move-Item will not create it. New-Item -ItemType Directory -Path $Root -Force | Out-Null Move-Item -Path $unpacked -Destination $Runtime Step "Node.js $runtimeVersion checked and installed for LoopCode" return (Join-Path $Runtime 'node.exe') } # The user PATH as stored, with %VARIABLES% left unexpanded, so rewriting it loses nothing. function Get-UserPath { $key = Get-Item -Path 'HKCU:\Environment' return [string]$key.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) } function Set-UserPath([string]$Value) { Set-ItemProperty -Path 'HKCU:\Environment' -Name 'Path' -Value $Value -Type ExpandString # Tell Explorer, so terminals opened from now on see the change without signing out. try { if (-not ('LoopCode.NativeMethods' -as [type])) { Add-Type -Namespace LoopCode -Name NativeMethods -MemberDefinition @' [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint fuFlags, uint uTimeout, out UIntPtr lpdwResult); '@ } $result = [UIntPtr]::Zero [void][LoopCode.NativeMethods]::SendMessageTimeout([IntPtr]0xffff, 0x1A, [UIntPtr]::Zero, 'Environment', 2, 5000, [ref]$result) } catch { } } function Test-OnPath([string]$Entries, [string]$Dir) { foreach ($entry in ($Entries -split ';')) { if ($entry -and ([Environment]::ExpandEnvironmentVariables($entry).TrimEnd('\') -ieq $Dir.TrimEnd('\'))) { return $true } } return $false } if ($Uninstall) { Say '' if ((Test-Path $Launcher) -and (Select-String -Path $Launcher -Pattern $Marker -SimpleMatch -Quiet)) { Remove-Item $Launcher -Force Step "removed $Launcher" } if (Test-Path $AppRoot) { Remove-Item $AppRoot -Recurse -Force; Step "removed $AppRoot" } if (Test-Path $Runtime) { Remove-Item $Runtime -Recurse -Force; Step "removed $Runtime" } if ((Test-Path $BinDir) -and -not (Get-ChildItem $BinDir -Force)) { Remove-Item $BinDir -Force } $userPath = Get-UserPath if (Test-OnPath $userPath $BinDir) { $kept = ($userPath -split ';' | Where-Object { $_ -and ([Environment]::ExpandEnvironmentVariables($_).TrimEnd('\') -ine $BinDir.TrimEnd('\')) }) -join ';' Set-UserPath $kept Step "removed $BinDir from your PATH" } Say " LoopCode's command-line tool is uninstalled." Say " Your conversations and sign-in are still in $Root\cli; delete that folder to remove them too." Say '' return } Say '' Write-Host ' LoopCode' -NoNewline Write-Host ' - command-line installer' -ForegroundColor DarkGray Say '' # HTTPS only. Plain HTTP is allowed for localhost alone, so the installer can be tested end to end. if ($Site -notmatch '^https://' -and $Site -notmatch '^http://(localhost|127\.0\.0\.1)(:\d+)?$') { Fail "Refusing to download over an insecure connection: $Site" } # Windows PowerShell 5.1 may not offer TLS 1.2 by default. try { [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 } catch { } # Node.js runs the CLI. Yours is used when it is new enough; otherwise LoopCode brings its own # (Install-Runtime, below), once the download folder exists. $nodeExe = $null $node = Get-Command node -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 if ($node -and $env:LOOPCODE_NODE -ne 'bundled') { $nodeText = (& $node.Source -p 'process.versions.node' 2>$null | Out-String).Trim() $nodeVersion = $null if ([version]::TryParse($nodeText, [ref]$nodeVersion) -and $nodeVersion -ge $RequiredNode) { $nodeExe = $node.Source; Step "Node.js $nodeText" } else { Step "Node.js $nodeText is older than LoopCode needs ($RequiredNode); LoopCode will bring its own and leave yours alone" } } # Windows' own tar (Windows 10 1803 and later). Not whatever tar is first on the PATH: the one # that comes with Git reads "C:\..." as a remote host. $tar = Join-Path $env:SystemRoot 'System32\tar.exe' if (-not (Test-Path $tar)) { Fail 'This installer needs Windows 10 (version 1803) or newer, which includes tar.exe.' } $tmp = Join-Path ([IO.Path]::GetTempPath()) ('loopcode-' + [Guid]::NewGuid().ToString('N')) New-Item -ItemType Directory -Path $tmp | Out-Null try { if (-not $nodeExe) { $nodeExe = Install-Runtime $tmp $tar } # Which build is current. The site answers with key=value lines. try { $manifest = (Invoke-WebRequest -Uri "$Site/api/loopcode/cli?mirror=1" -UseBasicParsing -TimeoutSec 30).Content } catch { Fail "Could not reach $Site. Check your connection and try again." } if ($manifest -is [byte[]]) { $manifest = [Text.Encoding]::UTF8.GetString($manifest) } $fields = @{} foreach ($line in ($manifest -split "`n")) { $pair = $line.Trim() -split '=', 2 if ($pair.Count -eq 2) { $fields[$pair[0]] = $pair[1] } } $version = $fields['version'] $url = $fields['url'] $sumUrl = $fields['sha256_url'] if (-not $version -or -not $url) { $reason = $fields['error'] if ($reason) { Fail "No command-line build is available right now ($reason). Please try again later." } Fail 'No command-line build is available right now. Please try again later.' } if ($version -notmatch '^[0-9]+(\.[0-9]+)*$') { Fail "The release server gave an unexpected version: $version" } if ($Site -match '^https://' -and ($url -notmatch '^https://' -or ($sumUrl -and $sumUrl -notmatch '^https://'))) { Fail 'The release server pointed at an insecure download, so nothing was installed.' } $target = Join-Path $AppRoot $version $current = Join-Path $AppRoot 'current' $installed = (Test-Path (Join-Path $target 'loopcode.mjs')) -and (Test-Path $current) -and ((Get-Content $current -ErrorAction SilentlyContinue | Select-Object -First 1) -eq $version) -and (Test-Path $Launcher) if ($installed) { Step "LoopCode $version is already installed; refreshing the command" } else { Step "downloading LoopCode $version" $archive = Join-Path $tmp 'loopcode.tar.gz' try { Invoke-WebRequest -Uri $url -OutFile $archive -UseBasicParsing -TimeoutSec 300 } catch { Fail 'The download failed. Please try again.' } if ($sumUrl) { try { $sumText = (Invoke-WebRequest -Uri $sumUrl -UseBasicParsing -TimeoutSec 60).Content } catch { Fail 'Could not fetch the checksum. Please try again.' } if ($sumText -is [byte[]]) { $sumText = [Text.Encoding]::UTF8.GetString($sumText) } $expected = ($sumText.Trim() -split '\s+')[0].ToLowerInvariant() $actual = (Get-FileHash -Path $archive -Algorithm SHA256).Hash.ToLowerInvariant() if ($expected -ne $actual) { Fail 'The download did not match its checksum, so nothing was installed. Please try again.' } Step 'checksum verified' } $extract = Join-Path $tmp 'extract' New-Item -ItemType Directory -Path $extract | Out-Null & $tar -xzf $archive -C $extract if ($LASTEXITCODE -ne 0) { Fail 'The download could not be unpacked. Please try again.' } $bundle = Join-Path $extract 'loopcode\loopcode.mjs' if (-not (Test-Path $bundle)) { Fail 'The download was not a LoopCode build.' } # Make sure it runs here before it replaces anything. $ran = (& $nodeExe $bundle --version 2>$null | Out-String).Trim() if ($ran -ne $version) { Fail 'The downloaded build did not start on this machine, so nothing was changed. Please write to team@heksync.in.' } Step 'verified it runs' New-Item -ItemType Directory -Path $AppRoot -Force | Out-Null if (Test-Path $target) { Remove-Item $target -Recurse -Force } Move-Item -Path (Join-Path $extract 'loopcode') -Destination $target Set-Content -Path $current -Value $version -Encoding ASCII # Tidy up older versions. One still running keeps its folder until next time. Get-ChildItem $AppRoot -Directory | Where-Object { $_.Name -ne $version } | ForEach-Object { Remove-Item $_.FullName -Recurse -Force -ErrorAction SilentlyContinue } } # The command itself. A file we didn't write is left alone. New-Item -ItemType Directory -Path $BinDir -Force | Out-Null if ((Test-Path $Launcher) -and -not (Select-String -Path $Launcher -Pattern $Marker -SimpleMatch -Quiet)) { Fail "$Launcher already exists and wasn't installed by LoopCode. Move it aside and run this again." } # Through %USERPROFILE%, not the literal path: the launcher is ASCII, and a user folder may not be. # It follows `current`, so loopcode can update itself without rewriting this file (the updater's # windowsLauncher() is only for launchers that named a version, from installs that had Node). # LoopCode's own Node.js when the installer brought one, otherwise yours. $launcherText = @( '@echo off', $Marker, 'setlocal', 'set /p v=<"%USERPROFILE%\.loopcode\app\current"', 'set "n=%USERPROFILE%\.loopcode\runtime\node.exe"', 'if exist "%n%" goto run', 'set "n=node"', 'where node >nul 2>nul', "if errorlevel 1 (echo loopcode: Node.js is missing. Run the installer again and it will bring its own: irm $Site/cli.ps1 ^| iex 1>&2 & exit /b 127)", ':run', '"%n%" "%USERPROFILE%\.loopcode\app\%v%\loopcode.mjs" %*' ) -join "`r`n" Set-Content -Path $Launcher -Value $launcherText -Encoding ASCII Step "installed $Launcher" # Make sure new terminals can find it, and this one too. $onPath = Test-OnPath $env:Path $BinDir $userPath = Get-UserPath if (-not (Test-OnPath $userPath $BinDir)) { if ($env:LOOPCODE_NO_MODIFY_PATH -eq '1') { Say '' Write-Host " $BinDir is not on your PATH. Add it to use the loopcode command." -ForegroundColor Yellow } else { if ($userPath) { Set-UserPath ($userPath.TrimEnd(';') + ';' + $BinDir) } else { Set-UserPath $BinDir } Step "added $BinDir to your PATH" } } if (-not $onPath -and $env:LOOPCODE_NO_MODIFY_PATH -ne '1') { $env:Path = $env:Path.TrimEnd(';') + ';' + $BinDir } Say '' Write-Host " LoopCode $version is installed." -ForegroundColor Green # First install: sign in now, while you're here. $account = Join-Path $Root 'cli\account.json' $hasAccount = (Test-Path $account) -and ((Get-Item $account).Length -gt 0) if ($env:LOOPCODE_NO_LOGIN -ne '1' -and -not $hasAccount -and [Environment]::UserInteractive -and -not [Console]::IsInputRedirected) { Say '' Say " Let's sign you in - your browser will open to approve this terminal." & $Launcher login if ($LASTEXITCODE -ne 0) { Write-Host ' You can sign in any time with: loopcode login' -ForegroundColor DarkGray } } Say '' Write-Host ' Open a project folder and run ' -NoNewline Write-Host 'loopcode' -NoNewline -ForegroundColor White Write-Host ' to start. Other terminals that were already open need restarting first.' Write-Host ' Update any time by running this installer again. Help: loopcode --help - team@heksync.in' -ForegroundColor DarkGray Say '' } finally { Remove-Item $tmp -Recurse -Force -ErrorAction SilentlyContinue } } Install-LoopCode -Uninstall:($env:LOOPCODE_UNINSTALL -eq '1')