Repository navigation
Expand file tree
/
Copy pathbuild.ps1
More file actions
226 lines (197 loc) Β· 12.1 KB
/
Copy pathbuild.ps1
File metadata and controls
226 lines (197 loc) Β· 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# ============================================================
# This file is part of DataLaVistaβ’
# build.ps1: DataLaVistaβ’ build script (Windows PowerShell).
# Author(s): Gabriel Mongefranco; Jeremy Gluskin; Shelley Boa.
# Created: 2026-03-24
# Last Modified: 2026-10-26
# Summary: Generates datalavista.js, DataLaVista.html, DataLaVista-nojs.html.
# Notes: See README file for documentation and full license information.
# Website: https://github.com/DepressionCenter/datalavista
#
# Copyright (c) 2026 The Regents of the University of Michigan
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <https://www.gnu.org/licenses/>.
# ================================================================
$ErrorActionPreference = 'Stop'
$SRC = 'src'
# Read license template and substitute {GIT_HASH} placeholder if present
$SourceHash = (& git rev-parse --short HEAD 2>$null)
if (-not $SourceHash) { $SourceHash = 'unknown' }
$LicenseText = [System.IO.File]::ReadAllText("$SRC\license-template.txt", [System.Text.Encoding]::UTF8).TrimEnd()
$LicenseText = $LicenseText.Replace('{GIT_HASH}', $SourceHash)
# Collect JS source files in sort order
$JsFiles = Get-ChildItem "$SRC\[0-9][0-9]-*.js" | Sort-Object Name
# ββ Helper: get or download esbuild ββββββββββββββββββββββββββββββββββββββββββ
$EsBuildVersion = '0.28.0'
$EsBuildCache = "$env:LOCALAPPDATA\datalavista-build\esbuild.exe"
function Get-EsBuild {
if (Get-Command esbuild -ErrorAction SilentlyContinue) { return 'esbuild' }
if (Test-Path $EsBuildCache) { return $EsBuildCache }
Write-Host " Downloading esbuild v$EsBuildVersion..." -ForegroundColor Cyan
New-Item -ItemType Directory -Force -Path (Split-Path $EsBuildCache) | Out-Null
$tgz = "$env:TEMP\esbuild.tgz"
$url = "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-$EsBuildVersion.tgz"
Invoke-WebRequest $url -OutFile $tgz
$extractDir = "$env:TEMP\esbuild-extract"
New-Item -ItemType Directory -Force -Path $extractDir | Out-Null
tar -xzf $tgz -C $extractDir
$bin = Get-ChildItem $extractDir -Filter 'esbuild.exe' -Recurse | Select-Object -First 1
Copy-Item $bin.FullName $EsBuildCache
Remove-Item $tgz, $extractDir -Recurse -Force
return $EsBuildCache
}
$EsBuild = Get-EsBuild
# ββ Helper: strip first /* */ block comment from a JS string βββββββββββββββββ
function Strip-LicenseJs {
param([string]$Text)
return [regex]::Replace($Text, '(?s)^\s*/\*.*?\*/[ \t]*(\r?\n)?', '')
}
# ββ Helper: strip first <!-- --> block comment from an HTML string ββββββββββββ
function Strip-LicenseHtml {
param([string]$Text)
return [regex]::Replace($Text, '(?s)^\s*<!--.*?-->[ \t]*(\r?\n)?', '')
}
# ββ Strip license from HTML template once; reuse the clean copy βββββββββββββββ
$RawHtml = [System.IO.File]::ReadAllText("$SRC\00-full-page.html", [System.Text.Encoding]::UTF8)
$CleanTemplate = Strip-LicenseHtml $RawHtml
$HtmlLicenseComment = "<!--`n$LicenseText`n-->`n"
# ββ Extract body content for _DLV_SHELL_HTML βββββββββββββββββββββββββββββββββ
# Extract inner body content (between <body> and </body>), strip the scripts placeholder block.
$bodyMatch = [regex]::Match($RawHtml, '(?s)<body>(.*)</body>')
$bodyRaw = $bodyMatch.Groups[1].Value
$bodyContent = [regex]::Replace($bodyRaw, '(?s)\s*<!-- DATALAVISTA_SCRIPTS_PLACEHOLDER_OPEN -->.*?<!-- DATALAVISTA_SCRIPTS_PLACEHOLDER_CLOSE -->', '')
$ShellHtmlJson = $bodyContent | ConvertTo-Json -Compress
$ShellHtmlVar = 'var _DLV_SHELL_HTML = ' + $ShellHtmlJson + ';'
# ββ Extract CSS head content for _DLV_HEAD_CSS βββββββββββββββββββββββββββββββ
# Collect <link rel="stylesheet"> tags and the <style>...</style> block from the source head.
$linkTagMatches = [regex]::Matches($RawHtml, '<link[^>]+rel=["\x27]stylesheet["\x27][^>]*/>')
$styleContent = [regex]::Match($RawHtml, '(?s)<style>(.*?)</style>').Groups[1].Value
$headCssHtml = ($linkTagMatches | ForEach-Object { $_.Value }) -join "`n"
$headCssHtml += "`n<style id=`"dlv-styles`">$styleContent</style>"
$DlvHeadCssJson = $headCssHtml | ConvertTo-Json -Compress
$DlvHeadCssVar = 'var _DLV_HEAD_CSS = ' + $DlvHeadCssJson + ';'
# ββ Extract <head>...</head> for the minimal shell output βββββββββββββββββββββ
# Strip the CSS (link tags + style block) so the shell head only has CDN scripts.
$headEnd = $CleanTemplate.IndexOf('</head>') + '</head>'.Length
$HeadSection = $CleanTemplate.Substring(0, $headEnd)
$HeadSection = [regex]::Replace($HeadSection, '\s*<link[^>]+rel=["\x27]stylesheet["\x27][^>]*/>', '')
$HeadSection = [regex]::Replace($HeadSection, '(?s)\s*<!--[^-]*Custom styles[^-]*-->\s*<style>.*?</style>', '')
# ββ 1. Build datalavista.js ββββββββββββββββββββββββββββββββββββββββββββββββββ
Write-Host 'Building datalavista.js...'
$bodySb = [System.Text.StringBuilder]::new()
$null = $bodySb.AppendLine('(() => {')
$null = $bodySb.AppendLine(" 'use strict';")
foreach ($f in $JsFiles) {
$null = $bodySb.AppendLine('')
$null = $bodySb.AppendLine(" /* === $($f.Name) === */")
$rawJs = [System.IO.File]::ReadAllText($f.FullName, [System.Text.Encoding]::UTF8)
$null = $bodySb.Append((Strip-LicenseJs $rawJs))
$null = $bodySb.AppendLine('')
}
$null = $bodySb.AppendLine('')
$null = $bodySb.AppendLine('})();')
$bodyPath = "$env:TEMP\dlv_js_body.js"
$minifiedPath = "$env:TEMP\dlv_js_minified.js"
[System.IO.File]::WriteAllText($bodyPath, $bodySb.ToString(), [System.Text.Encoding]::UTF8)
& $EsBuild $bodyPath --bundle=false --platform=browser --minify-whitespace --minify-syntax --log-level=error "--outfile=$minifiedPath"
$minifiedBody = [System.IO.File]::ReadAllText($minifiedPath, [System.Text.Encoding]::UTF8)
$finalJs = "/* ============================================================`n$LicenseText`n================================================================ */`n`n" + $ShellHtmlVar + "`n" + $DlvHeadCssVar + "`n`n" + $minifiedBody
[System.IO.File]::WriteAllText('datalavista.js', $finalJs, [System.Text.Encoding]::UTF8)
$lineCount = (Get-Content 'datalavista.js').Count
Write-Host " -> datalavista.js ($lineCount lines)"
# ββ 2. Build DataLaVista-nojs.html βββββββββββββββββββββββββββββββββββββββββ
Write-Host 'Building DataLaVista-nojs.html...'
$noJsShell = "<!DOCTYPE html>`n" + $HeadSection + "`n<body>`n <div id=`"dlv-root`"></div>`n <script src=`"datalavista.js`"></script>`n</body>`n</html>"
[System.IO.File]::WriteAllText('DataLaVista-nojs.html', ($HtmlLicenseComment + $noJsShell), [System.Text.Encoding]::UTF8)
Write-Host ' -> DataLaVista-nojs.html'
# ββ 3. Build DataLaVista.html (inline) ββββββββββββββββββββββββββββββββββββββ
Write-Host 'Building DataLaVista.html (inline)...'
$inlineShell = "<!DOCTYPE html>`n" + $HeadSection + "`n<body>`n <div id=`"dlv-root`"></div>`n <script>`n" + $ShellHtmlVar + "`n" + $DlvHeadCssVar + "`n" + $minifiedBody.TrimEnd() + "`n </script>`n</body>`n</html>"
[System.IO.File]::WriteAllText('DataLaVista.html', ($HtmlLicenseComment + $inlineShell), [System.Text.Encoding]::UTF8)
Write-Host ' -> DataLaVista.html'
# ββ 4. Check the outputs that run the application βββββββββββββββββββββββββββββ
# Without these values the application cannot draw its interface inside dlv-root.
foreach ($output in @('datalavista.js', 'DataLaVista.html')) {
$outputText = [System.IO.File]::ReadAllText($output, [System.Text.Encoding]::UTF8)
foreach ($definition in @('_DLV_SHELL_HTML', '_DLV_HEAD_CSS')) {
if (-not $outputText.Contains("var $definition = ")) {
Write-Error "Build failed: $output is missing $definition, so the page would show nothing."
exit 1
}
}
}
Write-Host ''
Write-Host ("Build completed at {0:yyyy-MM-dd hh:mm:ss tt}." -f (Get-Date))
# Simple web server for testing; pass --start to start the server or --stop to stop it
if ($args -contains '--stop') {
$Port = 8080
Write-Host "Stopping server on port $Port..." -ForegroundColor Yellow
# Finds the specific process using the port and kills it
$process = Get-NetTCPConnection -LocalPort $Port -ErrorAction SilentlyContinue | Select-Object -ExpandProperty OwningProcess -Unique
if ($process -and $process -gt 4) {
Stop-Process -Id $process -Force
Write-Host "Server stopped successfully." -ForegroundColor Green
} elseif ($process -and $process -le 4) {
Invoke-WebRequest -Uri "http://localhost:$Port/shutdown" -UseBasicParsing -ErrorAction SilentlyContinue
Write-Host "Server stopped successfully." -ForegroundColor Green
} else {
Write-Host "No server found running on port $Port." -ForegroundColor Gray
}
}
elseif ($args -contains '--start') {
$Port = 8080
$RootPath = $PSScriptRoot
# 1. Clean up any existing server first
Get-NetTCPConnection -LocalPort $Port -ErrorAction SilentlyContinue |
Select-Object -ExpandProperty OwningProcess -Unique |
Stop-Process -Force -ErrorAction SilentlyContinue
# 2. Server Logic
$ServerBlock = "
`$listener = New-Object System.Net.HttpListener
`$listener.Prefixes.Add('http://localhost:$Port/')
try {
`$listener.Start()
while (`$listener.IsListening) {
`$context = `$listener.GetContext()
`$path = `$context.Request.Url.LocalPath.TrimStart('/')
# --- SHUTDOWN HANDLING ---
if (`$path -eq 'shutdown') {
`$context.Response.StatusCode = 200
`$context.Response.Close() # Send response first
`$listener.Stop() # Then stop
break # Exit loop
}
if ([string]::IsNullOrWhiteSpace(`$path)) { `$path = 'DataLaVista.html' }
`$fullPath = Join-Path '$RootPath' `$path
if (Test-Path `$fullPath -PathType Leaf) {
`$ext = [System.IO.Path]::GetExtension(`$fullPath).ToLower()
if (`$ext -eq '.html') { `$context.Response.ContentType = 'text/html' }
elseif (`$ext -eq '.js') { `$context.Response.ContentType = 'application/javascript' }
elseif (`$ext -eq '.css') { `$context.Response.ContentType = 'text/css' }
`$bytes = [System.IO.File]::ReadAllBytes(`$fullPath)
`$context.Response.ContentLength64 = `$bytes.Length
`$context.Response.OutputStream.Write(`$bytes, 0, `$bytes.Length)
} else {
`$context.Response.StatusCode = 404
}
`$context.Response.Close()
}
} finally { `$listener.Stop() }
"
# 3. Launch background process
Start-Process powershell -ArgumentList "-NoProfile", "-Command", $ServerBlock -WindowStyle Hidden
Start-Sleep -Seconds 1
Start-Process "http://localhost:$Port/DataLaVista.html"
# 4. Print helpful instructions
Write-Host "--------------------------------------------------------" -ForegroundColor Gray
Write-Host "Server is running at http://localhost:$Port" -ForegroundColor Green
Write-Host "To stop the server, run: .\build.ps1 --stop" -ForegroundColor Cyan
}