@snap/valdi 1.2.0 → 1.2.1

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.
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.syncDirectoryContents = syncDirectoryContents;
4
+ const tslib_1 = require("tslib");
5
+ const node_fs_1 = tslib_1.__importDefault(require("node:fs"));
6
+ const node_path_1 = tslib_1.__importDefault(require("node:path"));
7
+ let temporaryFileCounter = 0;
8
+ function isPathInside(parentPath, childPath) {
9
+ const relativePath = node_path_1.default.relative(parentPath, childPath);
10
+ return (relativePath === '' ||
11
+ (!relativePath.startsWith(`..${node_path_1.default.sep}`) && relativePath !== '..' && !node_path_1.default.isAbsolute(relativePath)));
12
+ }
13
+ async function countFiles(directoryPath) {
14
+ const entries = await node_fs_1.default.promises.readdir(directoryPath, { withFileTypes: true });
15
+ let count = 0;
16
+ for (const entry of entries) {
17
+ const entryPath = node_path_1.default.join(directoryPath, entry.name);
18
+ count += entry.isDirectory() ? await countFiles(entryPath) : 1;
19
+ }
20
+ return count;
21
+ }
22
+ async function makeTreeWritable(entryPath) {
23
+ const stats = await node_fs_1.default.promises.lstat(entryPath);
24
+ if (stats.isDirectory()) {
25
+ await node_fs_1.default.promises.chmod(entryPath, (stats.mode & 0o777) | 0o700);
26
+ const entries = await node_fs_1.default.promises.readdir(entryPath);
27
+ for (const entry of entries) {
28
+ await makeTreeWritable(node_path_1.default.join(entryPath, entry));
29
+ }
30
+ }
31
+ else if (stats.isFile()) {
32
+ await node_fs_1.default.promises.chmod(entryPath, (stats.mode & 0o777) | 0o600);
33
+ }
34
+ }
35
+ async function removeTree(entryPath) {
36
+ await makeTreeWritable(entryPath);
37
+ await node_fs_1.default.promises.rm(entryPath, { force: true, recursive: true });
38
+ }
39
+ async function filesHaveEqualContents(sourcePath, destinationPath) {
40
+ const [sourceStats, destinationStats] = await Promise.all([
41
+ node_fs_1.default.promises.stat(sourcePath),
42
+ node_fs_1.default.promises.stat(destinationPath),
43
+ ]);
44
+ if (sourceStats.size !== destinationStats.size) {
45
+ return false;
46
+ }
47
+ const [sourceContents, destinationContents] = await Promise.all([
48
+ node_fs_1.default.promises.readFile(sourcePath),
49
+ node_fs_1.default.promises.readFile(destinationPath),
50
+ ]);
51
+ return sourceContents.equals(destinationContents);
52
+ }
53
+ async function replaceFile(sourcePath, destinationPath, sourceMode) {
54
+ const temporaryPath = `${destinationPath}.valdi-export-${process.pid}-${temporaryFileCounter++}`;
55
+ try {
56
+ await node_fs_1.default.promises.copyFile(sourcePath, temporaryPath);
57
+ await node_fs_1.default.promises.chmod(temporaryPath, sourceMode);
58
+ await node_fs_1.default.promises.rename(temporaryPath, destinationPath);
59
+ }
60
+ finally {
61
+ await node_fs_1.default.promises.rm(temporaryPath, { force: true });
62
+ }
63
+ }
64
+ async function syncFile(sourcePath, destinationPath, destinationEntry, result) {
65
+ const sourceStats = await node_fs_1.default.promises.stat(sourcePath);
66
+ const sourceMode = sourceStats.mode & 0o777;
67
+ if (destinationEntry?.isFile() && (await filesHaveEqualContents(sourcePath, destinationPath))) {
68
+ result.unchanged += 1;
69
+ return;
70
+ }
71
+ if (destinationEntry?.isDirectory()) {
72
+ const removedFileCount = await countFiles(destinationPath);
73
+ result.removed += removedFileCount;
74
+ await removeTree(destinationPath);
75
+ }
76
+ else if (destinationEntry?.isSymbolicLink()) {
77
+ result.removed += 1;
78
+ await node_fs_1.default.promises.rm(destinationPath);
79
+ }
80
+ await replaceFile(sourcePath, destinationPath, sourceMode);
81
+ if (destinationEntry) {
82
+ result.updated += 1;
83
+ }
84
+ else {
85
+ result.added += 1;
86
+ }
87
+ }
88
+ async function syncDirectory(sourceDirectory, destinationDirectory, result) {
89
+ if (node_fs_1.default.existsSync(destinationDirectory)) {
90
+ const destinationStats = await node_fs_1.default.promises.lstat(destinationDirectory);
91
+ if (destinationStats.isDirectory()) {
92
+ const destinationMode = destinationStats.mode & 0o777;
93
+ const writableDestinationMode = destinationMode | 0o700;
94
+ if (destinationMode !== writableDestinationMode) {
95
+ await node_fs_1.default.promises.chmod(destinationDirectory, writableDestinationMode);
96
+ }
97
+ }
98
+ else {
99
+ result.removed += 1;
100
+ await removeTree(destinationDirectory);
101
+ await node_fs_1.default.promises.mkdir(destinationDirectory, { recursive: true });
102
+ }
103
+ }
104
+ else {
105
+ await node_fs_1.default.promises.mkdir(destinationDirectory, { recursive: true });
106
+ }
107
+ const [sourceEntries, destinationEntries] = await Promise.all([
108
+ node_fs_1.default.promises.readdir(sourceDirectory, { withFileTypes: true }),
109
+ node_fs_1.default.promises.readdir(destinationDirectory, { withFileTypes: true }),
110
+ ]);
111
+ const remainingDestinationEntries = new Map(destinationEntries.map(entry => [entry.name, entry]));
112
+ await Promise.all(sourceEntries.map(async (sourceEntry) => {
113
+ const sourcePath = node_path_1.default.join(sourceDirectory, sourceEntry.name);
114
+ const destinationPath = node_path_1.default.join(destinationDirectory, sourceEntry.name);
115
+ const destinationEntry = remainingDestinationEntries.get(sourceEntry.name);
116
+ remainingDestinationEntries.delete(sourceEntry.name);
117
+ if (sourceEntry.isDirectory()) {
118
+ await syncDirectory(sourcePath, destinationPath, result);
119
+ }
120
+ else if (sourceEntry.isFile() || sourceEntry.isSymbolicLink()) {
121
+ await syncFile(sourcePath, destinationPath, destinationEntry, result);
122
+ }
123
+ else {
124
+ throw new Error(`Unsupported entry in exported web package: ${sourcePath}`);
125
+ }
126
+ }));
127
+ await Promise.all(Array.from(remainingDestinationEntries.values(), async (destinationEntry) => {
128
+ const destinationPath = node_path_1.default.join(destinationDirectory, destinationEntry.name);
129
+ const removedFileCount = destinationEntry.isDirectory() ? await countFiles(destinationPath) : 1;
130
+ result.removed += removedFileCount;
131
+ await removeTree(destinationPath);
132
+ }));
133
+ }
134
+ async function syncDirectoryContents(sourceDirectory, destinationDirectory) {
135
+ const resolvedSourceDirectory = node_path_1.default.resolve(sourceDirectory);
136
+ const resolvedDestinationDirectory = node_path_1.default.resolve(destinationDirectory);
137
+ if (isPathInside(resolvedSourceDirectory, resolvedDestinationDirectory) ||
138
+ isPathInside(resolvedDestinationDirectory, resolvedSourceDirectory)) {
139
+ throw new Error('Source and destination directories must not overlap');
140
+ }
141
+ const sourceStats = await node_fs_1.default.promises.stat(resolvedSourceDirectory);
142
+ if (!sourceStats.isDirectory()) {
143
+ throw new Error(`Directory export source is not a directory: ${resolvedSourceDirectory}`);
144
+ }
145
+ const result = {
146
+ added: 0,
147
+ updated: 0,
148
+ removed: 0,
149
+ unchanged: 0,
150
+ };
151
+ await syncDirectory(resolvedSourceDirectory, resolvedDestinationDirectory, result);
152
+ return result;
153
+ }
@@ -11,7 +11,7 @@ function parseGitHubRepoSlug(repoUrl) {
11
11
  }
12
12
  return `${match[1]}/${match[2]}`;
13
13
  }
14
- const LATEST_RELEASE_HINT = 'Use --valdiVersion=latest to retry, or --valdiVersion=<tag> (e.g. main or v1.0.0) to pin a version.';
14
+ const LATEST_RELEASE_HINT = 'Use --valdiVersion=latest to retry, or --valdiVersion=<tag> (e.g. main or beta-0.2.0) to pin a version.';
15
15
  async function getLatestReleaseTag(repoUrl) {
16
16
  const slug = parseGitHubRepoSlug(repoUrl);
17
17
  let response;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.waitForShutdownSignal = waitForShutdownSignal;
4
+ function waitForShutdownSignal() {
5
+ return new Promise(resolve => {
6
+ const resolveOnce = () => {
7
+ process.off('SIGINT', resolveOnce);
8
+ process.off('SIGTERM', resolveOnce);
9
+ resolve();
10
+ };
11
+ process.once('SIGINT', resolveOnce);
12
+ process.once('SIGTERM', resolveOnce);
13
+ });
14
+ }
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.startWebApplicationSession = startWebApplicationSession;
4
+ const tslib_1 = require("tslib");
5
+ const node_fs_1 = tslib_1.__importDefault(require("node:fs"));
6
+ const node_path_1 = tslib_1.__importDefault(require("node:path"));
7
+ const webServerUtils_1 = require("./webServerUtils");
8
+ const zipUtils_1 = require("./zipUtils");
9
+ async function extractWebSite(archivePath, sitesDir, generation) {
10
+ const siteDir = node_path_1.default.join(sitesDir, String(generation));
11
+ node_fs_1.default.mkdirSync(siteDir);
12
+ try {
13
+ await (0, zipUtils_1.decompressTo)(archivePath, siteDir);
14
+ return siteDir;
15
+ }
16
+ catch (error) {
17
+ node_fs_1.default.rmSync(siteDir, { force: true, recursive: true });
18
+ throw error;
19
+ }
20
+ }
21
+ async function startWebApplicationSession(options) {
22
+ const sitesDir = node_path_1.default.join(options.workingDir, 'sites');
23
+ node_fs_1.default.mkdirSync(sitesDir);
24
+ let generation = 1;
25
+ let activeSiteDir = await extractWebSite(options.archivePath, sitesDir, generation);
26
+ const staleSiteDirs = [];
27
+ const server = await (0, webServerUtils_1.startStaticWebServer)(activeSiteDir, {
28
+ host: options.host,
29
+ liveReload: options.liveReload ?? false,
30
+ port: options.port,
31
+ });
32
+ let publicationQueue = Promise.resolve();
33
+ const publish = async () => {
34
+ const nextSiteDir = await extractWebSite(options.archivePath, sitesDir, ++generation);
35
+ const previousSiteDir = activeSiteDir;
36
+ activeSiteDir = nextSiteDir;
37
+ server.setRootDir(nextSiteDir);
38
+ server.reload();
39
+ staleSiteDirs.push(previousSiteDir);
40
+ while (staleSiteDirs.length > 1) {
41
+ const staleSiteDir = staleSiteDirs.shift();
42
+ if (staleSiteDir) {
43
+ node_fs_1.default.rmSync(staleSiteDir, { force: true, recursive: true });
44
+ }
45
+ }
46
+ };
47
+ return {
48
+ url: server.url,
49
+ close: async () => {
50
+ await publicationQueue.catch(() => { });
51
+ await server.close();
52
+ },
53
+ publish: () => {
54
+ publicationQueue = publicationQueue.then(publish, publish);
55
+ return publicationQueue;
56
+ },
57
+ };
58
+ }
@@ -0,0 +1,212 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.inferWebHotReloadTarget = inferWebHotReloadTarget;
4
+ exports.registerWebHotReloadSession = registerWebHotReloadSession;
5
+ exports.findWebHotReloadSessions = findWebHotReloadSessions;
6
+ exports.publishWebHotReloadSession = publishWebHotReloadSession;
7
+ const tslib_1 = require("tslib");
8
+ const node_crypto_1 = tslib_1.__importDefault(require("node:crypto"));
9
+ const node_fs_1 = tslib_1.__importDefault(require("node:fs"));
10
+ const node_http_1 = tslib_1.__importDefault(require("node:http"));
11
+ const node_os_1 = tslib_1.__importDefault(require("node:os"));
12
+ const node_path_1 = tslib_1.__importDefault(require("node:path"));
13
+ const SESSION_VERSION = 1;
14
+ const PUBLISH_PATH = '/publish';
15
+ function defaultRegistryDir() {
16
+ const userId = typeof process.getuid === 'function' ? String(process.getuid()) : node_os_1.default.userInfo().username;
17
+ return node_path_1.default.join(node_os_1.default.tmpdir(), `valdi-web-sessions-${userId}`);
18
+ }
19
+ function ensureRegistryDir(registryDir) {
20
+ node_fs_1.default.mkdirSync(registryDir, { mode: 0o700, recursive: true });
21
+ const stat = node_fs_1.default.lstatSync(registryDir);
22
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
23
+ throw new Error(`Web hot reload registry is not a directory: ${registryDir}`);
24
+ }
25
+ if (typeof process.getuid === 'function' && stat.uid !== process.getuid()) {
26
+ throw new Error(`Web hot reload registry is not owned by the current user: ${registryDir}`);
27
+ }
28
+ try {
29
+ node_fs_1.default.chmodSync(registryDir, 0o700);
30
+ }
31
+ catch {
32
+ }
33
+ }
34
+ function sessionFilePath(registryDir, id) {
35
+ return node_path_1.default.join(registryDir, `${id}.json`);
36
+ }
37
+ function isProcessRunning(pid) {
38
+ try {
39
+ process.kill(pid, 0);
40
+ return true;
41
+ }
42
+ catch (error) {
43
+ return error.code === 'EPERM';
44
+ }
45
+ }
46
+ function isSessionDescriptor(value) {
47
+ if (typeof value !== 'object' || value === null) {
48
+ return false;
49
+ }
50
+ const descriptor = value;
51
+ return (descriptor.version === SESSION_VERSION &&
52
+ typeof descriptor.id === 'string' &&
53
+ Number.isInteger(descriptor.pid) &&
54
+ typeof descriptor.pid === 'number' &&
55
+ descriptor.pid > 0 &&
56
+ typeof descriptor.workspaceRoot === 'string' &&
57
+ typeof descriptor.applicationTarget === 'string' &&
58
+ typeof descriptor.hotreloadTarget === 'string' &&
59
+ typeof descriptor.bazelArgs === 'string' &&
60
+ typeof descriptor.publishUrl === 'string' &&
61
+ typeof descriptor.token === 'string' &&
62
+ typeof descriptor.startedAt === 'string');
63
+ }
64
+ function closeServer(server, sockets) {
65
+ return new Promise((resolve, reject) => {
66
+ server.close(error => {
67
+ if (error) {
68
+ reject(error);
69
+ }
70
+ else {
71
+ resolve();
72
+ }
73
+ });
74
+ for (const socket of sockets) {
75
+ socket.destroy();
76
+ }
77
+ });
78
+ }
79
+ function inferWebHotReloadTarget(applicationTarget) {
80
+ const separatorIndex = applicationTarget.lastIndexOf(':');
81
+ const targetNameStart = separatorIndex === -1 ? applicationTarget.lastIndexOf('/') + 1 : separatorIndex + 1;
82
+ const targetName = applicationTarget.slice(targetNameStart);
83
+ if (!targetName.endsWith('_web')) {
84
+ return undefined;
85
+ }
86
+ return `${applicationTarget.slice(0, targetNameStart)}${targetName.slice(0, -'_web'.length)}_hotreload`;
87
+ }
88
+ async function registerWebHotReloadSession(options) {
89
+ const registryDir = options.registryDir ?? defaultRegistryDir();
90
+ ensureRegistryDir(registryDir);
91
+ const token = node_crypto_1.default.randomBytes(32).toString('hex');
92
+ let publishQueue = Promise.resolve();
93
+ const server = node_http_1.default.createServer((request, response) => {
94
+ const requestUrl = new URL(request.url ?? '/', 'http://127.0.0.1');
95
+ if (request.method !== 'POST' || requestUrl.pathname !== PUBLISH_PATH) {
96
+ response.writeHead(404).end('not found');
97
+ return;
98
+ }
99
+ if (request.headers.authorization !== `Bearer ${token}`) {
100
+ response.writeHead(401).end('unauthorized');
101
+ return;
102
+ }
103
+ publishQueue = publishQueue.then(options.onPublish, options.onPublish);
104
+ void publishQueue.then(() => response.writeHead(204).end(), () => response.writeHead(500).end('publication failed'));
105
+ });
106
+ const sockets = new Set();
107
+ server.on('connection', socket => {
108
+ sockets.add(socket);
109
+ socket.once('close', () => sockets.delete(socket));
110
+ });
111
+ const port = await new Promise((resolve, reject) => {
112
+ server.once('error', reject);
113
+ server.listen(0, '127.0.0.1', () => {
114
+ server.off('error', reject);
115
+ const address = server.address();
116
+ if (address === null || typeof address === 'string') {
117
+ reject(new Error('Could not resolve the web hot reload control port'));
118
+ return;
119
+ }
120
+ resolve(address.port);
121
+ });
122
+ });
123
+ const descriptor = {
124
+ applicationTarget: options.applicationTarget,
125
+ bazelArgs: options.bazelArgs,
126
+ hotreloadTarget: options.hotreloadTarget,
127
+ id: node_crypto_1.default.randomUUID(),
128
+ pid: process.pid,
129
+ publishUrl: `http://127.0.0.1:${port}${PUBLISH_PATH}`,
130
+ startedAt: new Date().toISOString(),
131
+ token,
132
+ version: SESSION_VERSION,
133
+ workspaceRoot: node_fs_1.default.realpathSync(options.workspaceRoot),
134
+ };
135
+ const descriptorPath = sessionFilePath(registryDir, descriptor.id);
136
+ const temporaryPath = `${descriptorPath}.${process.pid}.tmp`;
137
+ try {
138
+ node_fs_1.default.writeFileSync(temporaryPath, JSON.stringify(descriptor), { flag: 'wx', mode: 0o600 });
139
+ node_fs_1.default.renameSync(temporaryPath, descriptorPath);
140
+ }
141
+ catch (error) {
142
+ node_fs_1.default.rmSync(temporaryPath, { force: true });
143
+ await closeServer(server, sockets);
144
+ throw error;
145
+ }
146
+ return {
147
+ descriptor,
148
+ close: async () => {
149
+ node_fs_1.default.rmSync(descriptorPath, { force: true });
150
+ await publishQueue.catch(() => { });
151
+ await closeServer(server, sockets);
152
+ },
153
+ };
154
+ }
155
+ function findWebHotReloadSessions(workspaceRoot, hotreloadTarget, registryDir = defaultRegistryDir()) {
156
+ if (!node_fs_1.default.existsSync(registryDir)) {
157
+ return [];
158
+ }
159
+ const realWorkspaceRoot = node_fs_1.default.realpathSync(workspaceRoot);
160
+ const sessions = [];
161
+ for (const entry of node_fs_1.default.readdirSync(registryDir, { withFileTypes: true })) {
162
+ if (!entry.isFile() || !entry.name.endsWith('.json')) {
163
+ continue;
164
+ }
165
+ const descriptorPath = node_path_1.default.join(registryDir, entry.name);
166
+ let descriptor;
167
+ try {
168
+ const parsed = JSON.parse(node_fs_1.default.readFileSync(descriptorPath, 'utf8'));
169
+ if (!isSessionDescriptor(parsed)) {
170
+ continue;
171
+ }
172
+ descriptor = parsed;
173
+ }
174
+ catch {
175
+ continue;
176
+ }
177
+ if (!isProcessRunning(descriptor.pid)) {
178
+ node_fs_1.default.rmSync(descriptorPath, { force: true });
179
+ continue;
180
+ }
181
+ if (descriptor.workspaceRoot === realWorkspaceRoot &&
182
+ (hotreloadTarget === undefined || descriptor.hotreloadTarget === hotreloadTarget)) {
183
+ sessions.push(descriptor);
184
+ }
185
+ }
186
+ return sessions.sort((left, right) => left.startedAt.localeCompare(right.startedAt));
187
+ }
188
+ function publishWebHotReloadSession(session) {
189
+ const publishUrl = new URL(session.publishUrl);
190
+ if (publishUrl.protocol !== 'http:' || publishUrl.hostname !== '127.0.0.1' || publishUrl.pathname !== PUBLISH_PATH) {
191
+ return Promise.reject(new Error(`Refusing non-loopback web hot reload endpoint: ${session.publishUrl}`));
192
+ }
193
+ return new Promise((resolve, reject) => {
194
+ const request = node_http_1.default.request(publishUrl, {
195
+ headers: { authorization: `Bearer ${session.token}` },
196
+ method: 'POST',
197
+ }, response => {
198
+ response.resume();
199
+ response.once('end', () => {
200
+ if (response.statusCode === 204) {
201
+ resolve();
202
+ }
203
+ else {
204
+ reject(new Error(`Web hot reload publication failed with HTTP ${String(response.statusCode)}`));
205
+ }
206
+ });
207
+ });
208
+ request.setTimeout(60_000, () => request.destroy(new Error('Web hot reload publication timed out')));
209
+ request.once('error', reject);
210
+ request.end();
211
+ });
212
+ }
@@ -0,0 +1,195 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WEB_LIVE_RELOAD_PATH = void 0;
4
+ exports.startStaticWebServer = startStaticWebServer;
5
+ exports.openUrlInDefaultBrowser = openUrlInDefaultBrowser;
6
+ const tslib_1 = require("tslib");
7
+ const child_process_1 = require("child_process");
8
+ const fs_1 = tslib_1.__importDefault(require("fs"));
9
+ const http_1 = tslib_1.__importDefault(require("http"));
10
+ const path_1 = tslib_1.__importDefault(require("path"));
11
+ exports.WEB_LIVE_RELOAD_PATH = '/__valdi_livereload';
12
+ const LIVE_RELOAD_SCRIPT = `<script>
13
+ (() => {
14
+ const events = new EventSource('${exports.WEB_LIVE_RELOAD_PATH}');
15
+ events.addEventListener('reload', () => window.location.reload());
16
+ })();
17
+ </script>`;
18
+ function contentType(filePath) {
19
+ if (filePath.endsWith('.html')) {
20
+ return 'text/html; charset=utf-8';
21
+ }
22
+ if (filePath.endsWith('.js')) {
23
+ return 'text/javascript; charset=utf-8';
24
+ }
25
+ if (filePath.endsWith('.json')) {
26
+ return 'application/json; charset=utf-8';
27
+ }
28
+ if (filePath.endsWith('.png')) {
29
+ return 'image/png';
30
+ }
31
+ if (filePath.endsWith('.jpg') || filePath.endsWith('.jpeg')) {
32
+ return 'image/jpeg';
33
+ }
34
+ if (filePath.endsWith('.svg')) {
35
+ return 'image/svg+xml';
36
+ }
37
+ if (filePath.endsWith('.webp')) {
38
+ return 'image/webp';
39
+ }
40
+ return 'application/octet-stream';
41
+ }
42
+ function sendText(response, statusCode, body) {
43
+ response.writeHead(statusCode, { 'content-type': 'text/plain; charset=utf-8' });
44
+ response.end(body);
45
+ }
46
+ function injectHtml(html, injectedHtml) {
47
+ const headEnd = html.lastIndexOf('</head>');
48
+ if (headEnd !== -1) {
49
+ return `${html.slice(0, headEnd)}${injectedHtml}\n${html.slice(headEnd)}`;
50
+ }
51
+ return `${injectedHtml}\n${html}`;
52
+ }
53
+ function serveFile(rootDir, request, response, injectedHtml, liveReload) {
54
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
55
+ sendText(response, 405, 'method not allowed');
56
+ return;
57
+ }
58
+ const requestUrl = new URL(request.url ?? '/', `http://${request.headers.host ?? 'localhost'}`);
59
+ const decodedPath = decodeURIComponent(requestUrl.pathname === '/' ? '/index.html' : requestUrl.pathname);
60
+ if (decodedPath.split('/').includes('..')) {
61
+ sendText(response, 403, 'forbidden');
62
+ return;
63
+ }
64
+ const root = path_1.default.resolve(rootDir);
65
+ const relativePath = decodedPath.startsWith('/') ? decodedPath.slice(1) : decodedPath;
66
+ let filePath = path_1.default.resolve(root, relativePath);
67
+ if (!(filePath === root || filePath.startsWith(`${root}${path_1.default.sep}`))) {
68
+ sendText(response, 403, 'forbidden');
69
+ return;
70
+ }
71
+ if (fs_1.default.existsSync(filePath) && fs_1.default.statSync(filePath).isDirectory()) {
72
+ filePath = path_1.default.join(filePath, 'index.html');
73
+ }
74
+ if (!fs_1.default.existsSync(filePath) || !fs_1.default.statSync(filePath).isFile()) {
75
+ sendText(response, 404, 'not found');
76
+ return;
77
+ }
78
+ response.writeHead(200, {
79
+ 'cache-control': liveReload || injectedHtml !== '' ? 'no-store' : 'no-cache',
80
+ 'content-type': contentType(filePath),
81
+ });
82
+ if (request.method === 'HEAD') {
83
+ response.end();
84
+ return;
85
+ }
86
+ if (injectedHtml !== '' && filePath.endsWith('.html')) {
87
+ response.end(injectHtml(fs_1.default.readFileSync(filePath, 'utf8'), injectedHtml));
88
+ return;
89
+ }
90
+ fs_1.default.createReadStream(filePath).pipe(response);
91
+ }
92
+ function serveLiveReload(request, response, clients) {
93
+ if (request.method !== 'GET') {
94
+ sendText(response, 405, 'method not allowed');
95
+ return;
96
+ }
97
+ response.writeHead(200, {
98
+ 'cache-control': 'no-cache, no-transform',
99
+ connection: 'keep-alive',
100
+ 'content-type': 'text/event-stream',
101
+ });
102
+ response.write('retry: 1000\n\n');
103
+ clients.add(response);
104
+ request.once('close', () => {
105
+ clients.delete(response);
106
+ });
107
+ }
108
+ function listen(server, host, port) {
109
+ return new Promise((resolve, reject) => {
110
+ const onError = (error) => {
111
+ reject(error);
112
+ };
113
+ server.once('error', onError);
114
+ server.listen(port, host, () => {
115
+ server.off('error', onError);
116
+ const address = server.address();
117
+ if (address === null || typeof address === 'string') {
118
+ reject(new Error(`Could not resolve listening port for ${host}:${port}`));
119
+ return;
120
+ }
121
+ resolve(address.port);
122
+ });
123
+ });
124
+ }
125
+ function trackConnections(server) {
126
+ const sockets = new Set();
127
+ server.on('connection', socket => {
128
+ sockets.add(socket);
129
+ socket.on('close', () => {
130
+ sockets.delete(socket);
131
+ });
132
+ });
133
+ return sockets;
134
+ }
135
+ function close(server, sockets) {
136
+ return new Promise((resolve, reject) => {
137
+ server.close(error => {
138
+ if (error) {
139
+ reject(error);
140
+ }
141
+ else {
142
+ resolve();
143
+ }
144
+ });
145
+ for (const socket of sockets) {
146
+ socket.destroy();
147
+ }
148
+ });
149
+ }
150
+ async function startStaticWebServer(rootDir, options) {
151
+ let activeRootDir = path_1.default.resolve(rootDir);
152
+ const liveReloadClients = new Set();
153
+ const injectedHtml = options.liveReload ? LIVE_RELOAD_SCRIPT : '';
154
+ const server = http_1.default.createServer((request, response) => {
155
+ const requestUrl = new URL(request.url ?? '/', `http://${request.headers.host ?? 'localhost'}`);
156
+ if (options.liveReload && requestUrl.pathname === exports.WEB_LIVE_RELOAD_PATH) {
157
+ serveLiveReload(request, response, liveReloadClients);
158
+ return;
159
+ }
160
+ serveFile(activeRootDir, request, response, injectedHtml, options.liveReload ?? false);
161
+ });
162
+ const sockets = trackConnections(server);
163
+ const actualPort = await listen(server, options.host, options.port);
164
+ return {
165
+ url: `http://${options.host}:${actualPort}/index.html`,
166
+ close: async () => {
167
+ for (const client of liveReloadClients) {
168
+ client.end();
169
+ }
170
+ liveReloadClients.clear();
171
+ await close(server, sockets);
172
+ },
173
+ reload: () => {
174
+ for (const client of liveReloadClients) {
175
+ client.write('event: reload\ndata: {}\n\n');
176
+ }
177
+ },
178
+ setRootDir: nextRootDir => {
179
+ activeRootDir = path_1.default.resolve(nextRootDir);
180
+ },
181
+ };
182
+ }
183
+ function openUrlInDefaultBrowser(url) {
184
+ const platform = process.platform;
185
+ const command = platform === 'darwin' ? 'open' : platform === 'win32' ? 'cmd' : 'xdg-open';
186
+ const args = platform === 'win32' ? ['/c', 'start', '', url] : [url];
187
+ const child = (0, child_process_1.spawn)(command, args, {
188
+ detached: true,
189
+ stdio: 'ignore',
190
+ });
191
+ child.on('error', error => {
192
+ console.warn(`Could not open browser: ${error.message}`);
193
+ });
194
+ child.unref();
195
+ }
@@ -1,16 +1,34 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.decompressTo = decompressTo;
4
+ exports.compressDirectoryContentsTo = compressDirectoryContentsTo;
4
5
  const tslib_1 = require("tslib");
6
+ const node_child_process_1 = require("node:child_process");
7
+ const fs = tslib_1.__importStar(require("node:fs"));
5
8
  const node_path_1 = tslib_1.__importDefault(require("node:path"));
6
- const extract_zip_1 = tslib_1.__importDefault(require("extract-zip"));
9
+ const node_util_1 = require("node:util");
10
+ const execFileAsync = (0, node_util_1.promisify)(node_child_process_1.execFile);
7
11
  async function decompressTo(inputFilePath, outputFilePath) {
8
12
  const archive = node_path_1.default.resolve(inputFilePath);
9
13
  const destination = node_path_1.default.resolve(outputFilePath);
10
14
  try {
11
- await (0, extract_zip_1.default)(archive, { dir: destination });
15
+ await execFileAsync('unzip', ['-DD', '-q', '-o', archive, '-d', destination]);
12
16
  }
13
17
  catch (error) {
14
18
  throw new Error(`Failed to extract “${archive}” → “${destination}”: ${error.message}`);
15
19
  }
16
20
  }
21
+ async function compressDirectoryContentsTo(inputDirectoryPath, outputFilePath) {
22
+ const sourceDirectory = node_path_1.default.resolve(inputDirectoryPath);
23
+ const archive = node_path_1.default.resolve(outputFilePath);
24
+ const stat = await fs.promises.stat(sourceDirectory);
25
+ if (!stat.isDirectory()) {
26
+ throw new Error(`Expected ${sourceDirectory} to be a directory`);
27
+ }
28
+ try {
29
+ await execFileAsync('zip', ['-q', '-r', archive, '.'], { cwd: sourceDirectory });
30
+ }
31
+ catch (error) {
32
+ throw new Error(`Failed to archive ${sourceDirectory} into ${archive}: ${error.message}`);
33
+ }
34
+ }