@nwutils/packager 0.4.0 → 0.6.0

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.
package/src/index.js CHANGED
@@ -1,33 +1,40 @@
1
1
  import appImage from "./appImage.js";
2
+ import nsis from "./nsis.js";
2
3
 
3
4
  /**
4
5
  * Supported packaged output formats.
5
6
  *
6
7
  * `AppImage`, `deb` and `rpm` package a Linux build. `MSIX` and `NSIS`
7
- * package a Windows build. Only `"AppImage"` is implemented today - the
8
- * others are reserved so this option doesn't need to change shape once they
9
- * land.
8
+ * package a Windows build. `"AppImage"` and `"nsis"` are implemented today -
9
+ * the others are reserved so this option doesn't need to change shape once
10
+ * they land.
10
11
  * @typedef {"AppImage" | "deb" | "rpm" | "msix" | "nsis" | "dmg"} PackageFormat
11
12
  */
12
13
 
14
+ /**
15
+ * Where releases are published, for packagers that support self updating.
16
+ * @typedef {import("./appImage.js").PublishOptions} PublishOptions
17
+ */
18
+
13
19
  /**
14
20
  * Package a built NW.js application.
15
21
  * @async
16
22
  * @function
17
- * @param {{format: PackageFormat} & Record<string, any>} options `format`, plus the options the matching packager (eg. `appImage`) expects.
23
+ * @param {{format: PackageFormat} & Record<string, any>} options `format`, plus the options the matching packager (eg. `appImage` or `nsis`) expects.
18
24
  * @returns {Promise<string>} Path to the resulting packaged artifact.
19
25
  */
20
26
  async function packager({ format, ...options }) {
21
27
  switch (format) {
22
28
  case "AppImage":
23
29
  return appImage(/** @type {any} */ (options));
30
+ case "nsis":
31
+ return nsis(/** @type {any} */ (options));
24
32
  case "deb":
25
33
  case "rpm":
26
34
  case "msix":
27
- case "nsis":
28
35
  case "dmg":
29
36
  throw new Error(
30
- `options.format ${JSON.stringify(format)} is not implemented yet. Currently only "AppImage" is supported.`,
37
+ `options.format ${JSON.stringify(format)} is not implemented yet. Currently only "AppImage" and "nsis" are supported.`,
31
38
  );
32
39
  default:
33
40
  throw new Error(
package/src/nsis.js ADDED
@@ -0,0 +1,563 @@
1
+ import child_process from "node:child_process";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import process from "node:process";
6
+
7
+ import util from "./util.js";
8
+
9
+ /**
10
+ * @typedef {object} NsisOptions
11
+ * @property {string} appDir Path to a built NW.js Windows application, ie. the `outDir` produced by `@nwutils/builder` for `platform: "win"`.
12
+ * @property {string} appName Name of the application. Must match the `app.name` value used to build `appDir` - the executable is expected at `<appDir>/<appName>.exe`. Must be a valid Windows file name.
13
+ * @property {string} version Version of the application, eg. `"1.2.0"`. Shown in Windows' installed apps list, and converted to `X.X.X.X` for the installer's own version resource.
14
+ * @property {"ia32" | "x64" | "arm64"} [arch] Architecture `appDir` was built for. Defaults to the host architecture. The installer refuses to run on Windows machines that can't run that architecture.
15
+ * @property {string} [outDir] Directory the resulting `<appName>-<arch>-Setup.exe` file is written to. Defaults to the parent directory of `appDir`.
16
+ * @property {string} [icon] Path to a `.ico` icon for the installer and uninstaller. Defaults to NSIS' own icon.
17
+ * @property {string} [appId] Name of the registry key the installation is recorded under. Defaults to `appName`. Keep it the same across releases, so installing a new version replaces the previous one.
18
+ * @property {string} [publisher] Publisher shown in Windows' installed apps list.
19
+ * @property {string} [copyright] Copyright notice written into the installer's version information.
20
+ * @property {string} [license] Path to a `.txt` or `.rtf` license file. When set, the installer shows it on a page the user has to accept.
21
+ * @property {boolean} [desktopShortcut=true] If true, create a desktop shortcut.
22
+ * @property {boolean} [startMenuShortcut=true] If true, create a Start Menu shortcut.
23
+ * @property {string} [makensisPath="makensis"] Path to the NSIS compiler. Defaults to `makensis` on the `PATH`.
24
+ */
25
+
26
+ /**
27
+ * The files and directories of a built application, relative to its root.
28
+ * @typedef {object} AppFiles
29
+ * @property {string[]} files Relative file paths, using the host's path separator.
30
+ * @property {string[]} dirs Relative directory paths, parents before children.
31
+ * @property {number} size Total size of `files` in bytes.
32
+ */
33
+
34
+ /**
35
+ * Map nw-builder's architecture identifiers to the `x64.nsh` and `WinVer.nsh`
36
+ * checks for whether the Windows machine running the installer can run that
37
+ * architecture. Each inner list is one way to pass, and all of its checks
38
+ * must pass. x64 builds run natively on x64 and, emulated, on ARM64 - but
39
+ * only from Windows 11, as ARM64 Windows 10 only emulates ia32. Every Windows
40
+ * machine runs ia32 builds.
41
+ * @type {Record<"ia32" | "x64" | "arm64", string[][]>}
42
+ */
43
+ const ARCH_CHECK_KV = {
44
+ ia32: [],
45
+ x64: [["${IsNativeAMD64}"], ["${IsNativeARM64}", "${AtLeastWin11}"]],
46
+ arm64: [["${IsNativeARM64}"]],
47
+ };
48
+
49
+ /**
50
+ * Package a built NW.js Windows application as an NSIS installer.
51
+ *
52
+ * The installer installs for the current user only, into
53
+ * `%LOCALAPPDATA%\Programs\<appName>`, so it never asks for administrator
54
+ * rights. It registers an uninstaller in Windows' installed apps list, and
55
+ * installing a new version first uninstalls the previous one. Both wait for
56
+ * the application to be closed before touching its files.
57
+ *
58
+ * This composes with `@nwutils/builder`: run it against the `outDir` (and
59
+ * `app.name`) that `@nwutils/builder` produced for `platform: "win"`.
60
+ * `makensis` runs on Linux and macOS too, so the installer can be built on
61
+ * any host.
62
+ * @async
63
+ * @function
64
+ * @param {NsisOptions} options
65
+ * @returns {Promise<string>} Path to the resulting installer `.exe` file.
66
+ */
67
+ async function nsis({
68
+ appDir,
69
+ appName,
70
+ version,
71
+ arch,
72
+ outDir,
73
+ icon,
74
+ appId,
75
+ publisher,
76
+ copyright = "",
77
+ license,
78
+ desktopShortcut = true,
79
+ startMenuShortcut = true,
80
+ makensisPath = "makensis",
81
+ }) {
82
+ if (typeof appDir !== "string" || appDir === "") {
83
+ throw new Error(
84
+ `Expected "options.appDir" to be a non-empty string. Received: ${JSON.stringify(appDir)}`,
85
+ );
86
+ }
87
+
88
+ if ((await util.fileExists(appDir)) === false) {
89
+ throw new Error(`"options.appDir" does not exist: ${appDir}`);
90
+ }
91
+
92
+ /*
93
+ * `appName` names files inside `appDir`, `outDir` and the install
94
+ * directory, and is written into the installer script.
95
+ */
96
+ if (
97
+ typeof appName !== "string" ||
98
+ util.isWindowsFileName(appName) === false
99
+ ) {
100
+ throw new Error(
101
+ `Expected "options.appName" to be a valid Windows file name. Received: ${JSON.stringify(appName)}`,
102
+ );
103
+ }
104
+
105
+ if (typeof version !== "string" || version === "") {
106
+ throw new Error(
107
+ `Expected "options.version" to be a non-empty string. Received: ${JSON.stringify(version)}`,
108
+ );
109
+ }
110
+ const fileVersion = util.windowsVersion(version);
111
+
112
+ const resolvedArch =
113
+ /** @type {"ia32" | "x64" | "arm64" | undefined} */ (arch) ??
114
+ /** @type {"ia32" | "x64" | "arm64"} */ (
115
+ /** @type {unknown} */ (process.arch)
116
+ );
117
+ /* `Object.hasOwn` so inherited keys such as "constructor" aren't mistaken for architectures. */
118
+ if (Object.hasOwn(ARCH_CHECK_KV, resolvedArch) === false) {
119
+ throw new Error(
120
+ `Expected "options.arch" to be "ia32", "x64" or "arm64". Received: ${JSON.stringify(arch)}`,
121
+ );
122
+ }
123
+
124
+ const resolvedAppId = appId ?? appName;
125
+ /* The installation is recorded under a registry key named after `appId`, and `\` separates registry keys. */
126
+ if (
127
+ typeof resolvedAppId !== "string" ||
128
+ resolvedAppId === "" ||
129
+ resolvedAppId.includes("\\") ||
130
+ [...resolvedAppId].some((character) => {
131
+ const code = character.charCodeAt(0);
132
+ return code < 0x20 || code === 0x7f;
133
+ })
134
+ ) {
135
+ throw new Error(
136
+ `Expected "options.appId" to be a non-empty string without "\\" or control characters. Received: ${JSON.stringify(appId)}`,
137
+ );
138
+ }
139
+
140
+ if (
141
+ publisher !== undefined &&
142
+ (typeof publisher !== "string" || publisher === "")
143
+ ) {
144
+ throw new Error(
145
+ `Expected "options.publisher" to be a non-empty string. Received: ${JSON.stringify(publisher)}`,
146
+ );
147
+ }
148
+
149
+ if (typeof copyright !== "string") {
150
+ throw new Error(
151
+ `Expected "options.copyright" to be a string. Received: ${JSON.stringify(copyright)}`,
152
+ );
153
+ }
154
+
155
+ for (const [key, value] of Object.entries({
156
+ desktopShortcut,
157
+ startMenuShortcut,
158
+ })) {
159
+ if (typeof value !== "boolean") {
160
+ throw new Error(
161
+ `Expected "options.${key}" to be a boolean. Received: ${JSON.stringify(value)}`,
162
+ );
163
+ }
164
+ }
165
+
166
+ if (typeof makensisPath !== "string" || makensisPath === "") {
167
+ throw new Error(
168
+ `Expected "options.makensisPath" to be a non-empty string. Received: ${JSON.stringify(makensisPath)}`,
169
+ );
170
+ }
171
+
172
+ const resolvedIconPath =
173
+ icon === undefined
174
+ ? undefined
175
+ : await resolveInputFile("icon", icon, [".ico"]);
176
+ const resolvedLicensePath =
177
+ license === undefined
178
+ ? undefined
179
+ : await resolveInputFile("license", license, [".txt", ".rtf"]);
180
+
181
+ const resolvedAppDir = path.resolve(appDir);
182
+ const executablePath = path.resolve(resolvedAppDir, `${appName}.exe`);
183
+ if ((await util.fileExists(executablePath)) === false) {
184
+ throw new Error(
185
+ `Expected the NW.js executable to exist at ${executablePath}. Does "options.appName" match the "app.name" used to build "options.appDir" for "platform: \\"win\\""?`,
186
+ );
187
+ }
188
+
189
+ const resolvedOutDir = path.resolve(outDir ?? path.dirname(resolvedAppDir));
190
+ await fs.promises.mkdir(resolvedOutDir, { recursive: true });
191
+ const installerPath = path.resolve(
192
+ resolvedOutDir,
193
+ `${appName}-${resolvedArch}-Setup.exe`,
194
+ );
195
+
196
+ const script = nsisScript({
197
+ appDir: resolvedAppDir,
198
+ appFiles: await listAppFiles(resolvedAppDir),
199
+ appName,
200
+ appId: resolvedAppId,
201
+ version,
202
+ fileVersion,
203
+ arch: resolvedArch,
204
+ installerPath,
205
+ iconPath: resolvedIconPath,
206
+ licensePath: resolvedLicensePath,
207
+ publisher,
208
+ copyright,
209
+ desktopShortcut,
210
+ startMenuShortcut,
211
+ });
212
+
213
+ const scriptDir = await fs.promises.mkdtemp(
214
+ path.join(os.tmpdir(), "nwutils-packager-nsis-"),
215
+ );
216
+
217
+ try {
218
+ const scriptPath = path.resolve(scriptDir, "installer.nsi");
219
+ await fs.promises.writeFile(scriptPath, script, "utf-8");
220
+
221
+ try {
222
+ child_process.execFileSync(
223
+ makensisPath,
224
+ ["-INPUTCHARSET", "UTF8", "-V2", scriptPath],
225
+ { stdio: "inherit" },
226
+ );
227
+ } catch (error) {
228
+ if (/** @type {NodeJS.ErrnoException} */ (error).code === "ENOENT") {
229
+ throw new Error(
230
+ `Could not find the NSIS compiler at ${JSON.stringify(makensisPath)}. Install NSIS (eg. "apt install nsis", "brew install makensis" or "choco install nsis"), or pass its path as "options.makensisPath".`,
231
+ { cause: error },
232
+ );
233
+ }
234
+ throw error;
235
+ }
236
+
237
+ return installerPath;
238
+ } finally {
239
+ await fs.promises.rm(scriptDir, { recursive: true, force: true });
240
+ }
241
+ }
242
+
243
+ /**
244
+ * Resolve an input file option, and throw unless it exists and has one of
245
+ * `extensions`.
246
+ * @async
247
+ * @function
248
+ * @param {string} key Option name, for error messages.
249
+ * @param {unknown} value Option value.
250
+ * @param {string[]} extensions Accepted lowercase extensions, eg. `[".ico"]`.
251
+ * @returns {Promise<string>} Absolute path to the file.
252
+ */
253
+ async function resolveInputFile(key, value, extensions) {
254
+ if (typeof value !== "string" || value === "") {
255
+ throw new Error(
256
+ `Expected "options.${key}" to be a non-empty string. Received: ${JSON.stringify(value)}`,
257
+ );
258
+ }
259
+ const resolvedPath = path.resolve(value);
260
+ if (extensions.includes(path.extname(resolvedPath).toLowerCase()) === false) {
261
+ throw new Error(
262
+ `Expected "options.${key}" to be a ${extensions.join(" or ")} file. Received: ${resolvedPath}`,
263
+ );
264
+ }
265
+ if ((await util.fileExists(resolvedPath)) === false) {
266
+ throw new Error(`"options.${key}" does not exist: ${resolvedPath}`);
267
+ }
268
+ return resolvedPath;
269
+ }
270
+
271
+ /**
272
+ * List the files and directories under `appDir`. Symbolic links are followed,
273
+ * since NSIS copies what they point at.
274
+ * @async
275
+ * @function
276
+ * @param {string} appDir Absolute path to the built application.
277
+ * @returns {Promise<AppFiles>}
278
+ */
279
+ async function listAppFiles(appDir) {
280
+ /** @type {AppFiles} */
281
+ const appFiles = { files: [], dirs: [], size: 0 };
282
+
283
+ /**
284
+ * @param {string} relativeDir
285
+ * @returns {Promise<void>}
286
+ */
287
+ async function walk(relativeDir) {
288
+ const entries = await fs.promises.readdir(path.join(appDir, relativeDir));
289
+ for (const entry of entries.sort()) {
290
+ const relativePath = path.join(relativeDir, entry);
291
+ const stats = await fs.promises.stat(path.join(appDir, relativePath));
292
+ if (stats.isDirectory()) {
293
+ appFiles.dirs.push(relativePath);
294
+ await walk(relativePath);
295
+ } else {
296
+ appFiles.files.push(relativePath);
297
+ appFiles.size += stats.size;
298
+ }
299
+ }
300
+ }
301
+
302
+ await walk("");
303
+ return appFiles;
304
+ }
305
+
306
+ /**
307
+ * Generate the NSIS script for an installer.
308
+ *
309
+ * Every file is listed explicitly rather than copied with `File /r`, so the
310
+ * uninstaller deletes exactly the files that were installed. The user can
311
+ * choose any install directory - including one such as `C:\` that holds
312
+ * other files - so the uninstaller never deletes directories recursively.
313
+ * @param {object} options
314
+ * @param {string} options.appDir Absolute path to the built application.
315
+ * @param {AppFiles} options.appFiles Files and directories under `appDir`.
316
+ * @param {string} options.appName
317
+ * @param {string} options.appId
318
+ * @param {string} options.version
319
+ * @param {string} options.fileVersion `version` in `X.X.X.X` form.
320
+ * @param {"ia32" | "x64" | "arm64"} options.arch
321
+ * @param {string} options.installerPath Absolute path the installer is written to.
322
+ * @param {string} [options.iconPath] Absolute path to a `.ico` file.
323
+ * @param {string} [options.licensePath] Absolute path to a `.txt` or `.rtf` file.
324
+ * @param {string} [options.publisher]
325
+ * @param {string} options.copyright
326
+ * @param {boolean} options.desktopShortcut
327
+ * @param {boolean} options.startMenuShortcut
328
+ * @returns {string}
329
+ */
330
+ function nsisScript({
331
+ appDir,
332
+ appFiles,
333
+ appName,
334
+ appId,
335
+ version,
336
+ fileVersion,
337
+ arch,
338
+ installerPath,
339
+ iconPath,
340
+ licensePath,
341
+ publisher,
342
+ copyright,
343
+ desktopShortcut,
344
+ startMenuShortcut,
345
+ }) {
346
+ const e = util.nsisEscape;
347
+ const p = util.nsisPath;
348
+ /* Paths inside the install directory always use `\`, whichever host builds the installer. */
349
+ const installed = (/** @type {string} */ relativePath) =>
350
+ `"$INSTDIR\\${e(relativePath.split(path.sep).join("\\"))}"`;
351
+ const uninstallKey = `"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\${e(appId)}"`;
352
+ const exe = installed(`${appName}.exe`);
353
+ const archChecks = ARCH_CHECK_KV[arch];
354
+
355
+ /** @type {string[]} */
356
+ const lines = [
357
+ "Unicode true",
358
+ "ManifestDPIAware true",
359
+ "RequestExecutionLevel user",
360
+ "SetCompressor /SOLID lzma",
361
+ "",
362
+ '!include "MUI2.nsh"',
363
+ '!include "LogicLib.nsh"',
364
+ '!include "x64.nsh"',
365
+ '!include "WinVer.nsh"',
366
+ "",
367
+ `Name "${e(appName)}"`,
368
+ `OutFile "${p(installerPath)}"`,
369
+ `InstallDir "$LOCALAPPDATA\\Programs\\${e(appName)}"`,
370
+ `InstallDirRegKey HKCU ${uninstallKey} "InstallLocation"`,
371
+ "",
372
+ ];
373
+
374
+ if (iconPath !== undefined) {
375
+ lines.push(
376
+ `!define MUI_ICON "${p(iconPath)}"`,
377
+ `!define MUI_UNICON "${p(iconPath)}"`,
378
+ );
379
+ }
380
+ lines.push(
381
+ "!define MUI_ABORTWARNING",
382
+ `!define MUI_FINISHPAGE_RUN ${exe}`,
383
+ "",
384
+ "!insertmacro MUI_PAGE_WELCOME",
385
+ );
386
+ if (licensePath !== undefined) {
387
+ lines.push(`!insertmacro MUI_PAGE_LICENSE "${p(licensePath)}"`);
388
+ }
389
+ lines.push(
390
+ "!insertmacro MUI_PAGE_DIRECTORY",
391
+ "!insertmacro MUI_PAGE_INSTFILES",
392
+ "!insertmacro MUI_PAGE_FINISH",
393
+ "!insertmacro MUI_UNPAGE_CONFIRM",
394
+ "!insertmacro MUI_UNPAGE_INSTFILES",
395
+ '!insertmacro MUI_LANGUAGE "English"',
396
+ "",
397
+ `VIProductVersion "${fileVersion}"`,
398
+ `VIFileVersion "${fileVersion}"`,
399
+ `VIAddVersionKey "ProductName" "${e(appName)}"`,
400
+ `VIAddVersionKey "ProductVersion" "${e(version)}"`,
401
+ `VIAddVersionKey "FileVersion" "${e(version)}"`,
402
+ `VIAddVersionKey "FileDescription" "${e(appName)} Setup"`,
403
+ `VIAddVersionKey "LegalCopyright" "${e(copyright)}"`,
404
+ );
405
+ if (publisher !== undefined) {
406
+ lines.push(`VIAddVersionKey "CompanyName" "${e(publisher)}"`);
407
+ }
408
+ lines.push("", "Function .onInit", " SetShellVarContext current");
409
+ if (archChecks.length > 0) {
410
+ /* Passing branches are left empty: only the final `${Else}` does anything. */
411
+ lines.push(
412
+ ...archChecks.flatMap((checks, index) =>
413
+ checks.map(
414
+ (check, checkIndex) =>
415
+ ` \${${checkIndex > 0 ? "AndIf" : index === 0 ? "If" : "ElseIf"}} ${check}`,
416
+ ),
417
+ ),
418
+ " ${Else}",
419
+ ` MessageBox MB_ICONSTOP "This installer is for ${arch} Windows, which this computer can't run." /SD IDOK`,
420
+ " Abort",
421
+ " ${EndIf}",
422
+ );
423
+ }
424
+ lines.push(
425
+ "FunctionEnd",
426
+ "",
427
+ 'Section "Install"',
428
+ ` ReadRegStr $0 HKCU ${uninstallKey} "InstallLocation"`,
429
+ ' ${If} $0 != ""',
430
+ ...waitForAppToClose(`"$0\\${e(appName)}.exe"`, appName, " "),
431
+ " ${EndIf}",
432
+ ...waitForAppToClose(exe, appName, " "),
433
+ /*
434
+ * Uninstall the previous version first, so files it had that this
435
+ * version doesn't are removed. `_?=` runs its uninstaller in place and
436
+ * waits for it, which leaves the uninstaller itself behind.
437
+ */
438
+ ' ${If} $0 != ""',
439
+ ' ${AndIf} ${FileExists} "$0\\Uninstall.exe"',
440
+ " ClearErrors",
441
+ ` ExecWait '"$0\\Uninstall.exe" /S _?=$0' $1`,
442
+ " ${If} ${Errors}",
443
+ " ${OrIf} $1 != 0",
444
+ ` MessageBox MB_ICONSTOP "The previous version of ${e(appName)} couldn't be uninstalled." /SD IDOK`,
445
+ " Abort",
446
+ " ${EndIf}",
447
+ ' Delete "$0\\Uninstall.exe"',
448
+ ' RMDir "$0"',
449
+ " ${EndIf}",
450
+ "",
451
+ ' SetOutPath "$INSTDIR"',
452
+ );
453
+
454
+ /* Group files by directory: `File` writes into the current `SetOutPath`. */
455
+ /** @type {Map<string, string[]>} */
456
+ const filesByDir = new Map([["", []]]);
457
+ for (const dir of appFiles.dirs) {
458
+ filesByDir.set(dir, []);
459
+ }
460
+ for (const file of appFiles.files) {
461
+ /** @type {string[]} */ (
462
+ filesByDir.get(path.dirname(file).replace(/^\.$/, ""))
463
+ ).push(file);
464
+ }
465
+ for (const [dir, files] of filesByDir) {
466
+ if (dir !== "") {
467
+ lines.push(` SetOutPath ${installed(dir)}`);
468
+ }
469
+ for (const file of files) {
470
+ lines.push(` File "${p(path.join(appDir, file))}"`);
471
+ }
472
+ }
473
+
474
+ lines.push(
475
+ ' SetOutPath "$INSTDIR"',
476
+ ' WriteUninstaller "$INSTDIR\\Uninstall.exe"',
477
+ "",
478
+ );
479
+ if (startMenuShortcut) {
480
+ lines.push(` CreateShortcut "$SMPROGRAMS\\${e(appName)}.lnk" ${exe}`);
481
+ }
482
+ if (desktopShortcut) {
483
+ lines.push(` CreateShortcut "$DESKTOP\\${e(appName)}.lnk" ${exe}`);
484
+ }
485
+ lines.push(
486
+ "",
487
+ ` WriteRegStr HKCU ${uninstallKey} "DisplayName" "${e(appName)}"`,
488
+ ` WriteRegStr HKCU ${uninstallKey} "DisplayVersion" "${e(version)}"`,
489
+ ` WriteRegStr HKCU ${uninstallKey} "DisplayIcon" ${exe}`,
490
+ ` WriteRegStr HKCU ${uninstallKey} "InstallLocation" "$INSTDIR"`,
491
+ ` WriteRegStr HKCU ${uninstallKey} "UninstallString" '"$INSTDIR\\Uninstall.exe"'`,
492
+ ` WriteRegStr HKCU ${uninstallKey} "QuietUninstallString" '"$INSTDIR\\Uninstall.exe" /S'`,
493
+ ` WriteRegDWORD HKCU ${uninstallKey} "EstimatedSize" ${Math.ceil(appFiles.size / 1024)}`,
494
+ ` WriteRegDWORD HKCU ${uninstallKey} "NoModify" 1`,
495
+ ` WriteRegDWORD HKCU ${uninstallKey} "NoRepair" 1`,
496
+ );
497
+ if (publisher !== undefined) {
498
+ lines.push(
499
+ ` WriteRegStr HKCU ${uninstallKey} "Publisher" "${e(publisher)}"`,
500
+ );
501
+ }
502
+ lines.push(
503
+ "SectionEnd",
504
+ "",
505
+ "Function un.onInit",
506
+ " SetShellVarContext current",
507
+ "FunctionEnd",
508
+ "",
509
+ 'Section "Uninstall"',
510
+ ...waitForAppToClose(exe, appName, " "),
511
+ );
512
+ for (const file of appFiles.files) {
513
+ lines.push(` Delete ${installed(file)}`);
514
+ }
515
+ /* Children before parents, and `RMDir` without `/r` only removes empty directories. */
516
+ for (const dir of [...appFiles.dirs].reverse()) {
517
+ lines.push(` RMDir ${installed(dir)}`);
518
+ }
519
+ lines.push(
520
+ ' Delete "$INSTDIR\\Uninstall.exe"',
521
+ ' RMDir "$INSTDIR"',
522
+ ` Delete "$SMPROGRAMS\\${e(appName)}.lnk"`,
523
+ ` Delete "$DESKTOP\\${e(appName)}.lnk"`,
524
+ ` DeleteRegKey HKCU ${uninstallKey}`,
525
+ "SectionEnd",
526
+ "",
527
+ );
528
+
529
+ return lines.join("\n");
530
+ }
531
+
532
+ /**
533
+ * Generate NSIS lines that wait until the application isn't running, asking
534
+ * the user to close it, so its files can be replaced or deleted. Windows
535
+ * refuses to open a running executable for writing, which is how a running
536
+ * copy is detected. Cancelling - which silent mode does straight away -
537
+ * aborts the installer or uninstaller. Uses `$2`.
538
+ * @param {string} exePath Quoted NSIS string with the executable's path, eg. `"$INSTDIR\Demo.exe"`.
539
+ * @param {string} appName Application name, shown in the prompt.
540
+ * @param {string} indent Indentation of the generated lines.
541
+ * @returns {string[]}
542
+ */
543
+ function waitForAppToClose(exePath, appName, indent) {
544
+ return [
545
+ "${Do}",
546
+ ` \${IfNot} \${FileExists} ${exePath}`,
547
+ " ${Break}",
548
+ " ${EndIf}",
549
+ " ClearErrors",
550
+ ` FileOpen $2 ${exePath} a`,
551
+ " ${IfNot} ${Errors}",
552
+ " FileClose $2",
553
+ " ${Break}",
554
+ " ${EndIf}",
555
+ ` \${If} \${Cmd} \`MessageBox MB_RETRYCANCEL|MB_ICONEXCLAMATION "Close ${util.nsisEscape(appName)}, then select Retry." /SD IDCANCEL IDCANCEL\``,
556
+ " Abort",
557
+ " ${EndIf}",
558
+ "${Loop}",
559
+ ].map((line) => `${indent}${line}`);
560
+ }
561
+
562
+ export default nsis;
563
+ export { listAppFiles, nsisScript };