@fgv/ts-res-browser-cli 5.0.0-2

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/README.md ADDED
@@ -0,0 +1,131 @@
1
+ # @fgv/ts-res-browser-cli
2
+
3
+ Command-line interface to launch ts-res-browser with specified resources and configuration.
4
+
5
+ ## Features
6
+
7
+ - **ZIP Archive Creation**: Automatically creates ZIP archives containing resources and configuration for easy browser loading
8
+ - **Development Server Integration**: Can automatically start and manage the ts-res-browser development server
9
+ - **Flexible Resource Input**: Supports both individual files and entire directory trees
10
+ - **Configuration Management**: Works with predefined configurations or custom configuration files
11
+ - **Context Filtering**: Apply context filters and qualifier settings via command line
12
+ - **Interactive Mode**: Launch with sample data for exploration
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ npm install -g @fgv/ts-res-browser-cli
18
+ ```
19
+
20
+ ## Usage
21
+
22
+ ### Basic Usage
23
+
24
+ ```bash
25
+ # Launch browser with resources from a directory
26
+ ts-res-browser-cli browse --input ./resources --config default
27
+
28
+ # Launch with a specific configuration file
29
+ ts-res-browser-cli browse --input ./my-resources --config ./config.json
30
+
31
+ # Create ZIP and launch without opening browser automatically
32
+ ts-res-browser-cli browse --input ./resources --config extended-example --no-open
33
+ ```
34
+
35
+ ### ZIP Workflow
36
+
37
+ The CLI automatically creates ZIP archives containing your resources and configuration:
38
+
39
+ 1. **ZIP Creation**: Resources and configuration are bundled into a timestamped ZIP file in your Downloads folder
40
+ 2. **Manifest Generation**: Each ZIP includes a manifest with metadata about the bundled content
41
+ 3. **Browser Integration**: The browser can directly load and process these ZIP archives
42
+
43
+ ```bash
44
+ # Creates: ~/Downloads/ts-res-bundle-[timestamp].zip
45
+ ts-res-browser-cli browse --input ./resources --config my-config
46
+ ```
47
+
48
+ ### Development Server
49
+
50
+ ```bash
51
+ # Automatically start development server locally
52
+ ts-res-browser-cli browse --input ./resources --dev
53
+
54
+ # Use existing server at custom URL
55
+ ts-res-browser-cli browse --input ./resources --url http://localhost:3001
56
+ ```
57
+
58
+ ### Advanced Options
59
+
60
+ ```bash
61
+ # Apply context filtering
62
+ ts-res-browser-cli browse \
63
+ --input ./resources \
64
+ --context-filter "language=en-US|territory=US" \
65
+ --reduce-qualifiers
66
+
67
+ # Interactive mode with sample data
68
+ ts-res-browser-cli browse --interactive
69
+
70
+ # Verbose output
71
+ ts-res-browser-cli browse --input ./resources --verbose
72
+ ```
73
+
74
+ ## Command Reference
75
+
76
+ ### `browse` Command
77
+
78
+ Launch ts-res-browser with specified resources and configuration.
79
+
80
+ **Options:**
81
+ - `-i, --input <path>`: Input file or directory path
82
+ - `--config <name|path>`: Predefined configuration name or file path
83
+ - `-c, --context <json>`: Context filter (JSON string)
84
+ - `--context-filter <token>`: Context filter (pipe-separated)
85
+ - `--qualifier-defaults <token>`: Qualifier defaults (pipe-separated)
86
+ - `--resource-types <types>`: Resource type filter (comma-separated)
87
+ - `--max-distance <number>`: Maximum distance for language matching
88
+ - `--reduce-qualifiers`: Remove perfectly matching qualifier conditions
89
+ - `-p, --port <number>`: Port for local browser instance
90
+ - `--url <url>`: URL of remote browser instance
91
+ - `--no-open`: Do not open browser automatically
92
+ - `--interactive`: Launch in interactive mode with sample data
93
+ - `--dev`: Automatically start development server locally
94
+ - `-v, --verbose`: Verbose output
95
+ - `-q, --quiet`: Quiet output
96
+
97
+ ### `config` Command
98
+
99
+ Manage system configurations (future enhancement).
100
+
101
+ ## ZIP Archive Format
102
+
103
+ Created ZIP archives contain:
104
+
105
+ ```
106
+ ts-res-bundle-[timestamp].zip
107
+ ├── manifest.json # Archive metadata
108
+ ├── input/ # Resource files (preserving structure)
109
+ │ ├── file1.json
110
+ │ └── subdirectory/
111
+ │ └── file2.json
112
+ └── config.json # Configuration (if provided)
113
+ ```
114
+
115
+ The manifest includes:
116
+ - Timestamp of archive creation
117
+ - Input file/directory metadata
118
+ - Configuration file metadata
119
+ - Original paths for reference
120
+
121
+ ## Integration with ts-res-browser
122
+
123
+ The browser application includes a dedicated ZIP Loader tool that can:
124
+ - Directly load ZIP archives created by this CLI
125
+ - Parse manifests and apply configurations automatically
126
+ - Process resources through the standard ts-res pipeline
127
+ - Provide seamless transition from CLI to browser workflow
128
+
129
+ ## License
130
+
131
+ MIT
@@ -0,0 +1,40 @@
1
+ #!/usr/bin/env node
2
+
3
+ /*
4
+ * Copyright (c) 2025 Erik Fortune
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ const { TsResBrowserCliApp } = require('../lib/cli');
26
+
27
+ async function main() {
28
+ try {
29
+ const app = new TsResBrowserCliApp();
30
+ await app.run(process.argv);
31
+ } catch (error) {
32
+ console.error('Fatal error:', error.message);
33
+ process.exit(1);
34
+ }
35
+ }
36
+
37
+ main().catch((error) => {
38
+ console.error('Unhandled error:', error);
39
+ process.exit(1);
40
+ });
@@ -0,0 +1,16 @@
1
+ // The "rig.json" file directs tools to look for their config files in an external package.
2
+ // Documentation for this system: https://www.npmjs.com/package/@rushstack/rig-package
3
+ {
4
+ "$schema": "https://developer.microsoft.com/json-schemas/rig-package/rig.schema.json",
5
+ /**
6
+ * (Required) The name of the rig package to inherit from.
7
+ * It should be an NPM package name with the "-rig" suffix.
8
+ */
9
+ "rigPackageName": "@rushstack/heft-node-rig",
10
+ /**
11
+ * (Optional) Selects a config profile from the rig package. The name must consist of
12
+ * lowercase alphanumeric words separated by hyphens, for example "sample-profile".
13
+ * If omitted, then the "default" profile will be used."
14
+ */
15
+ "rigProfile": "default"
16
+ }
@@ -0,0 +1,53 @@
1
+ import { Result } from '@fgv/ts-utils';
2
+ import { IBrowseOptions } from './options';
3
+ /**
4
+ * Manages launching the browser application with specified options
5
+ */
6
+ export declare class BrowserLauncher {
7
+ private _devServer?;
8
+ /**
9
+ * Launches the browser with the specified options
10
+ */
11
+ launch(options: IBrowseOptions): Promise<Result<void>>;
12
+ /**
13
+ * Opens the browser to the specified URL
14
+ */
15
+ private _openBrowser;
16
+ /**
17
+ * Builds the URL with query parameters based on options
18
+ */
19
+ private _buildUrl;
20
+ /**
21
+ * Starts the development server for ts-res-browser
22
+ */
23
+ private _startDevServer;
24
+ /**
25
+ * Waits for the development server to be ready by checking HTTP availability
26
+ */
27
+ private _waitForServerReady;
28
+ /**
29
+ * Checks if the server is responding
30
+ */
31
+ private _checkServerHealth;
32
+ /**
33
+ * Stops the development server
34
+ */
35
+ private _stopDevServer;
36
+ /**
37
+ * Sleep for the specified number of milliseconds
38
+ */
39
+ private _sleep;
40
+ /**
41
+ * Determines if a ZIP archive should be created based on the options
42
+ */
43
+ private _shouldCreateZip;
44
+ /**
45
+ * Creates a ZIP archive containing the input and config files
46
+ */
47
+ private _createZipArchive;
48
+ /**
49
+ * Graceful shutdown - stops development server if running
50
+ */
51
+ shutdown(): void;
52
+ }
53
+ //# sourceMappingURL=browserLauncher.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browserLauncher.d.ts","sourceRoot":"","sources":["../src/browserLauncher.ts"],"names":[],"mappings":"AAyBA,OAAO,EAAE,MAAM,EAAiB,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAI3C;;GAEG;AACH,qBAAa,eAAe;IAC1B,OAAO,CAAC,UAAU,CAAC,CAAe;IAClC;;OAEG;IACU,MAAM,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAoGnE;;OAEG;YACW,YAAY;IAkB1B;;OAEG;IACH,OAAO,CAAC,SAAS;IAqDjB;;OAEG;YACW,eAAe;IAuC7B;;OAEG;YACW,mBAAmB;IA4BjC;;OAEG;YACW,kBAAkB;IAiBhC;;OAEG;IACH,OAAO,CAAC,cAAc;IAWtB;;OAEG;IACH,OAAO,CAAC,MAAM;IAId;;OAEG;IACH,OAAO,CAAC,gBAAgB;IAWxB;;OAEG;YACW,iBAAiB;IAa/B;;OAEG;IACI,QAAQ,IAAI,IAAI;CAGxB"}
@@ -0,0 +1,347 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright (c) 2025 Erik Fortune
4
+ *
5
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ * of this software and associated documentation files (the "Software"), to deal
7
+ * in the Software without restriction, including without limitation the rights
8
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ * copies of the Software, and to permit persons to whom the Software is
10
+ * furnished to do so, subject to the following conditions:
11
+ *
12
+ * The above copyright notice and this permission notice shall be included in all
13
+ * copies or substantial portions of the Software.
14
+ *
15
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ * SOFTWARE.
22
+ */
23
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
24
+ if (k2 === undefined) k2 = k;
25
+ var desc = Object.getOwnPropertyDescriptor(m, k);
26
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
27
+ desc = { enumerable: true, get: function() { return m[k]; } };
28
+ }
29
+ Object.defineProperty(o, k2, desc);
30
+ }) : (function(o, m, k, k2) {
31
+ if (k2 === undefined) k2 = k;
32
+ o[k2] = m[k];
33
+ }));
34
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
35
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
36
+ }) : function(o, v) {
37
+ o["default"] = v;
38
+ });
39
+ var __importStar = (this && this.__importStar) || (function () {
40
+ var ownKeys = function(o) {
41
+ ownKeys = Object.getOwnPropertyNames || function (o) {
42
+ var ar = [];
43
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
44
+ return ar;
45
+ };
46
+ return ownKeys(o);
47
+ };
48
+ return function (mod) {
49
+ if (mod && mod.__esModule) return mod;
50
+ var result = {};
51
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
52
+ __setModuleDefault(result, mod);
53
+ return result;
54
+ };
55
+ })();
56
+ Object.defineProperty(exports, "__esModule", { value: true });
57
+ exports.BrowserLauncher = void 0;
58
+ const child_process_1 = require("child_process");
59
+ const path = __importStar(require("path"));
60
+ const http = __importStar(require("http"));
61
+ const ts_utils_1 = require("@fgv/ts-utils");
62
+ const zipArchiver_1 = require("./zipArchiver");
63
+ /**
64
+ * Manages launching the browser application with specified options
65
+ */
66
+ class BrowserLauncher {
67
+ /**
68
+ * Launches the browser with the specified options
69
+ */
70
+ async launch(options) {
71
+ try {
72
+ // Check if we need to create a ZIP archive for file-based inputs
73
+ let zipCreated = false;
74
+ let finalOptions = Object.assign({}, options);
75
+ if (this._shouldCreateZip(options)) {
76
+ if (!options.quiet) {
77
+ console.log('Creating ZIP archive for file-based resources...');
78
+ }
79
+ const zipResult = await this._createZipArchive(options);
80
+ if (zipResult.isFailure()) {
81
+ return (0, ts_utils_1.fail)(`Failed to create ZIP archive: ${zipResult.message}`);
82
+ }
83
+ if (!options.quiet) {
84
+ console.log(`ZIP archive created: ${zipResult.value.zipPath}`);
85
+ }
86
+ // Modify options to use ZIP loading instead of file paths
87
+ const zipFileName = path.basename(zipResult.value.zipPath);
88
+ finalOptions = Object.assign(Object.assign({}, options), { input: undefined, config: undefined,
89
+ // Add ZIP loading parameters
90
+ loadZip: true, zipFile: zipFileName, zipPath: zipResult.value.zipPath });
91
+ zipCreated = true;
92
+ }
93
+ // Start development server if requested
94
+ if (finalOptions.dev && !finalOptions.url) {
95
+ if (!finalOptions.quiet) {
96
+ console.log('Starting TS-RES Browser development server...');
97
+ }
98
+ const serverResult = await this._startDevServer(finalOptions);
99
+ if (serverResult.isFailure()) {
100
+ return serverResult;
101
+ }
102
+ // Wait for server to be ready
103
+ const port = options.port || 3000;
104
+ const readyResult = await this._waitForServerReady(port, options.verbose || false);
105
+ if (readyResult.isFailure()) {
106
+ this._stopDevServer();
107
+ return readyResult;
108
+ }
109
+ if (!options.quiet) {
110
+ console.log(`Development server started on port ${port}`);
111
+ }
112
+ }
113
+ // Build URL with parameters
114
+ const url = this._buildUrl(finalOptions);
115
+ if (!finalOptions.quiet) {
116
+ console.log('Opening TS-RES Browser...');
117
+ if (zipCreated) {
118
+ console.log('ZIP archive created - browser will load from Downloads folder');
119
+ }
120
+ else {
121
+ if (finalOptions.input) {
122
+ console.log(`Resource file: ${finalOptions.input}`);
123
+ }
124
+ if (finalOptions.config) {
125
+ console.log(`Configuration: ${finalOptions.config}`);
126
+ }
127
+ }
128
+ if (finalOptions.contextFilter) {
129
+ console.log(`Context filter: ${finalOptions.contextFilter}`);
130
+ }
131
+ console.log(`URL: ${url}`);
132
+ }
133
+ // Open browser if requested (default to true)
134
+ const shouldOpen = finalOptions.open !== false;
135
+ if (shouldOpen) {
136
+ const openResult = await this._openBrowser(url, finalOptions.verbose || false);
137
+ if (openResult.isFailure()) {
138
+ return (0, ts_utils_1.fail)(`Could not open browser: ${openResult.message}`);
139
+ }
140
+ if (!finalOptions.quiet) {
141
+ console.log('Browser opened successfully');
142
+ }
143
+ }
144
+ else {
145
+ console.log(`Browser URL: ${url}`);
146
+ }
147
+ return (0, ts_utils_1.succeed)(undefined);
148
+ }
149
+ catch (error) {
150
+ return (0, ts_utils_1.fail)(`Failed to launch browser: ${error}`);
151
+ }
152
+ }
153
+ /**
154
+ * Opens the browser to the specified URL
155
+ */
156
+ async _openBrowser(url, verbose) {
157
+ return new Promise((resolve) => {
158
+ const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start ""' : 'xdg-open';
159
+ (0, child_process_1.exec)(`${command} "${url}"`, (error) => {
160
+ if (error) {
161
+ resolve((0, ts_utils_1.fail)(`Failed to open browser: ${error.message}`));
162
+ }
163
+ else {
164
+ if (verbose) {
165
+ console.log(`Opened browser to: ${url}`);
166
+ }
167
+ resolve((0, ts_utils_1.succeed)(undefined));
168
+ }
169
+ });
170
+ });
171
+ }
172
+ /**
173
+ * Builds the URL with query parameters based on options
174
+ */
175
+ _buildUrl(options) {
176
+ // Use provided URL or default to localhost
177
+ const baseUrl = options.url || `http://localhost:${options.port || 3000}`;
178
+ const params = new URLSearchParams();
179
+ if (options.input) {
180
+ params.set('input', options.input);
181
+ }
182
+ if (options.config) {
183
+ params.set('config', options.config);
184
+ }
185
+ if (options.contextFilter) {
186
+ params.set('contextFilter', options.contextFilter);
187
+ }
188
+ if (options.qualifierDefaults) {
189
+ params.set('qualifierDefaults', options.qualifierDefaults);
190
+ }
191
+ if (options.resourceTypes) {
192
+ params.set('resourceTypes', options.resourceTypes);
193
+ }
194
+ if (options.maxDistance !== undefined) {
195
+ params.set('maxDistance', options.maxDistance.toString());
196
+ }
197
+ if (options.reduceQualifiers) {
198
+ params.set('reduceQualifiers', 'true');
199
+ }
200
+ if (options.interactive) {
201
+ params.set('interactive', 'true');
202
+ }
203
+ if (options.loadZip) {
204
+ params.set('loadZip', 'true');
205
+ }
206
+ if (options.zipFile) {
207
+ params.set('zipFile', options.zipFile);
208
+ }
209
+ if (options.zipPath) {
210
+ params.set('zipPath', options.zipPath);
211
+ }
212
+ const queryString = params.toString();
213
+ return queryString ? `${baseUrl}?${queryString}` : baseUrl;
214
+ }
215
+ /**
216
+ * Starts the development server for ts-res-browser
217
+ */
218
+ async _startDevServer(options) {
219
+ try {
220
+ // Find the ts-res-browser project directory
221
+ // Assume we're running from tools/ts-res-browser-cli, so go up and over to tools/ts-res-browser
222
+ const browserProjectPath = path.resolve(__dirname, '../../ts-res-browser');
223
+ if (options.verbose) {
224
+ console.log(`Looking for ts-res-browser at: ${browserProjectPath}`);
225
+ }
226
+ const port = options.port || 3000;
227
+ const env = Object.assign(Object.assign({}, process.env), { PORT: port.toString() });
228
+ this._devServer = (0, child_process_1.spawn)('rushx', ['dev'], {
229
+ cwd: browserProjectPath,
230
+ env,
231
+ stdio: options.verbose ? 'inherit' : ['ignore', 'pipe', 'pipe']
232
+ });
233
+ this._devServer.on('error', (error) => {
234
+ return (0, ts_utils_1.fail)(`Failed to start development server: ${error}`);
235
+ });
236
+ // Give the server a moment to start
237
+ await this._sleep(3000);
238
+ if (this._devServer && !this._devServer.killed) {
239
+ if (options.verbose) {
240
+ console.log('Development server process started successfully');
241
+ }
242
+ return (0, ts_utils_1.succeed)(undefined);
243
+ }
244
+ else {
245
+ return (0, ts_utils_1.fail)('Development server process failed to start');
246
+ }
247
+ }
248
+ catch (error) {
249
+ return (0, ts_utils_1.fail)(`Failed to start development server: ${error}`);
250
+ }
251
+ }
252
+ /**
253
+ * Waits for the development server to be ready by checking HTTP availability
254
+ */
255
+ async _waitForServerReady(port, verbose, maxAttempts = 60) {
256
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
257
+ try {
258
+ const isReady = await this._checkServerHealth(port);
259
+ if (isReady) {
260
+ if (verbose) {
261
+ console.log(`Server is ready at http://localhost:${port}`);
262
+ }
263
+ return (0, ts_utils_1.succeed)(undefined);
264
+ }
265
+ }
266
+ catch (error) {
267
+ // Server not ready yet, continue waiting
268
+ }
269
+ if (verbose && attempt % 10 === 0) {
270
+ console.log(`Waiting for server to be ready... (attempt ${attempt}/${maxAttempts})`);
271
+ }
272
+ await this._sleep(1000);
273
+ }
274
+ return (0, ts_utils_1.fail)(`Server did not become ready after ${maxAttempts} attempts`);
275
+ }
276
+ /**
277
+ * Checks if the server is responding
278
+ */
279
+ async _checkServerHealth(port) {
280
+ return new Promise((resolve) => {
281
+ const request = http.get(`http://localhost:${port}`, (res) => {
282
+ resolve(res.statusCode !== undefined && res.statusCode >= 200 && res.statusCode < 400);
283
+ });
284
+ request.on('error', () => {
285
+ resolve(false);
286
+ });
287
+ request.setTimeout(3000, () => {
288
+ request.destroy();
289
+ resolve(false);
290
+ });
291
+ });
292
+ }
293
+ /**
294
+ * Stops the development server
295
+ */
296
+ _stopDevServer() {
297
+ if (this._devServer && !this._devServer.killed) {
298
+ this._devServer.kill('SIGTERM');
299
+ setTimeout(() => {
300
+ if (this._devServer && !this._devServer.killed) {
301
+ this._devServer.kill('SIGKILL');
302
+ }
303
+ }, 5000);
304
+ }
305
+ }
306
+ /**
307
+ * Sleep for the specified number of milliseconds
308
+ */
309
+ _sleep(ms) {
310
+ return new Promise((resolve) => setTimeout(resolve, ms));
311
+ }
312
+ /**
313
+ * Determines if a ZIP archive should be created based on the options
314
+ */
315
+ _shouldCreateZip(options) {
316
+ // Create ZIP if input or config are file paths (not predefined names)
317
+ const hasFilePath = (path) => {
318
+ if (!path)
319
+ return false;
320
+ // Check if it's a file path (contains directory separators or file extensions)
321
+ return path.includes('/') || path.includes('\\') || (path.includes('.') && !path.startsWith('.'));
322
+ };
323
+ return hasFilePath(options.input) || hasFilePath(options.config);
324
+ }
325
+ /**
326
+ * Creates a ZIP archive containing the input and config files
327
+ */
328
+ async _createZipArchive(options) {
329
+ try {
330
+ return await zipArchiver_1.zipArchiver.createArchive({
331
+ input: options.input,
332
+ config: options.config
333
+ });
334
+ }
335
+ catch (error) {
336
+ return (0, ts_utils_1.fail)(`Failed to create ZIP archive: ${error instanceof Error ? error.message : String(error)}`);
337
+ }
338
+ }
339
+ /**
340
+ * Graceful shutdown - stops development server if running
341
+ */
342
+ shutdown() {
343
+ this._stopDevServer();
344
+ }
345
+ }
346
+ exports.BrowserLauncher = BrowserLauncher;
347
+ //# sourceMappingURL=browserLauncher.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browserLauncher.js","sourceRoot":"","sources":["../src/browserLauncher.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,iDAA0D;AAC1D,2CAA6B;AAC7B,2CAA6B;AAC7B,4CAAsD;AAEtD,+CAA4C;AAG5C;;GAEG;AACH,MAAa,eAAe;IAE1B;;OAEG;IACI,KAAK,CAAC,MAAM,CAAC,OAAuB;QACzC,IAAI,CAAC;YACH,iEAAiE;YACjE,IAAI,UAAU,GAAG,KAAK,CAAC;YACvB,IAAI,YAAY,qBAAQ,OAAO,CAAE,CAAC;YAElC,IAAI,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC,EAAE,CAAC;gBACnC,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;oBACnB,OAAO,CAAC,GAAG,CAAC,kDAAkD,CAAC,CAAC;gBAClE,CAAC;gBAED,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC,C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AAC,KAAK,CAAC,EAAE,CAAC,CAAC;QACzG,CAAC;IACH,CAAC;IAED;;OAEG;IACI,QAAQ;QACb,IAAI,CAAC,cAAc,EAAE,CAAC;IACxB,CAAC;CACF;AA5UD,0CA4UC","sourcesContent":["/*\n * Copyright (c) 2025 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { exec, spawn, ChildProcess } from 'child_process';\nimport * as path from 'path';\nimport * as http from 'http';\nimport { Result, succeed, fail } from '@fgv/ts-utils';\nimport { IBrowseOptions } from './options';\nimport { zipArchiver } from './zipArchiver';\nimport * as fs from 'fs';\n\n/**\n * Manages launching the browser application with specified options\n */\nexport class BrowserLauncher {\n private _devServer?: ChildProcess;\n /**\n * Launches the browser with the specified options\n */\n public async launch(options: IBrowseOptions): Promise<Result<void>> {\n try {\n // Check if we need to create a ZIP archive for file-based inputs\n let zipCreated = false;\n let finalOptions = { ...options };\n\n if (this._shouldCreateZip(options)) {\n if (!options.quiet) {\n console.log('Creating ZIP archive for file-based resources...');\n }\n\n const zipResult = await this._createZipArchive(options);\n if (zipResult.isFailure()) {\n return fail(`Failed to create ZIP archive: ${zipResult.message}`);\n }\n\n if (!options.quiet) {\n console.log(`ZIP archive created: ${zipResult.value.zipPath}`);\n }\n\n // Modify options to use ZIP loading instead of file paths\n const zipFileName = path.basename(zipResult.value.zipPath);\n finalOptions = {\n ...options,\n input: undefined,\n config: undefined,\n // Add ZIP loading parameters\n loadZip: true,\n zipFile: zipFileName,\n zipPath: zipResult.value.zipPath\n };\n zipCreated = true;\n }\n\n // Start development server if requested\n if (finalOptions.dev && !finalOptions.url) {\n if (!finalOptions.quiet) {\n console.log('Starting TS-RES Browser development server...');\n }\n\n const serverResult = await this._startDevServer(finalOptions);\n if (serverResult.isFailure()) {\n return serverResult;\n }\n\n // Wait for server to be ready\n const port = options.port || 3000;\n const readyResult = await this._waitForServerReady(port, options.verbose || false);\n if (readyResult.isFailure()) {\n this._stopDevServer();\n return readyResult;\n }\n\n if (!options.quiet) {\n console.log(`Development server started on port ${port}`);\n }\n }\n\n // Build URL with parameters\n const url = this._buildUrl(finalOptions);\n\n if (!finalOptions.quiet) {\n console.log('Opening TS-RES Browser...');\n if (zipCreated) {\n console.log('ZIP archive created - browser will load from Downloads folder');\n } else {\n if (finalOptions.input) {\n console.log(`Resource file: ${finalOptions.input}`);\n }\n if (finalOptions.config) {\n console.log(`Configuration: ${finalOptions.config}`);\n }\n }\n if (finalOptions.contextFilter) {\n console.log(`Context filter: ${finalOptions.contextFilter}`);\n }\n console.log(`URL: ${url}`);\n }\n\n // Open browser if requested (default to true)\n const shouldOpen = finalOptions.open !== false;\n if (shouldOpen) {\n const openResult = await this._openBrowser(url, finalOptions.verbose || false);\n if (openResult.isFailure()) {\n return fail(`Could not open browser: ${openResult.message}`);\n }\n\n if (!finalOptions.quiet) {\n console.log('Browser opened successfully');\n }\n } else {\n console.log(`Browser URL: ${url}`);\n }\n\n return succeed(undefined);\n } catch (error) {\n return fail(`Failed to launch browser: ${error}`);\n }\n }\n\n /**\n * Opens the browser to the specified URL\n */\n private async _openBrowser(url: string, verbose: boolean): Promise<Result<void>> {\n return new Promise((resolve) => {\n const command =\n process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start \"\"' : 'xdg-open';\n\n exec(`${command} \"${url}\"`, (error) => {\n if (error) {\n resolve(fail(`Failed to open browser: ${error.message}`));\n } else {\n if (verbose) {\n console.log(`Opened browser to: ${url}`);\n }\n resolve(succeed(undefined));\n }\n });\n });\n }\n\n /**\n * Builds the URL with query parameters based on options\n */\n private _buildUrl(options: IBrowseOptions): string {\n // Use provided URL or default to localhost\n const baseUrl = options.url || `http://localhost:${options.port || 3000}`;\n const params = new URLSearchParams();\n\n if (options.input) {\n params.set('input', options.input);\n }\n\n if (options.config) {\n params.set('config', options.config);\n }\n\n if (options.contextFilter) {\n params.set('contextFilter', options.contextFilter);\n }\n\n if (options.qualifierDefaults) {\n params.set('qualifierDefaults', options.qualifierDefaults);\n }\n\n if (options.resourceTypes) {\n params.set('resourceTypes', options.resourceTypes);\n }\n\n if (options.maxDistance !== undefined) {\n params.set('maxDistance', options.maxDistance.toString());\n }\n\n if (options.reduceQualifiers) {\n params.set('reduceQualifiers', 'true');\n }\n\n if (options.interactive) {\n params.set('interactive', 'true');\n }\n\n if (options.loadZip) {\n params.set('loadZip', 'true');\n }\n\n if (options.zipFile) {\n params.set('zipFile', options.zipFile);\n }\n\n if (options.zipPath) {\n params.set('zipPath', options.zipPath);\n }\n\n const queryString = params.toString();\n return queryString ? `${baseUrl}?${queryString}` : baseUrl;\n }\n\n /**\n * Starts the development server for ts-res-browser\n */\n private async _startDevServer(options: IBrowseOptions): Promise<Result<void>> {\n try {\n // Find the ts-res-browser project directory\n // Assume we're running from tools/ts-res-browser-cli, so go up and over to tools/ts-res-browser\n const browserProjectPath = path.resolve(__dirname, '../../ts-res-browser');\n\n if (options.verbose) {\n console.log(`Looking for ts-res-browser at: ${browserProjectPath}`);\n }\n\n const port = options.port || 3000;\n const env = { ...process.env, PORT: port.toString() };\n\n this._devServer = spawn('rushx', ['dev'], {\n cwd: browserProjectPath,\n env,\n stdio: options.verbose ? 'inherit' : ['ignore', 'pipe', 'pipe']\n });\n\n this._devServer.on('error', (error) => {\n return fail(`Failed to start development server: ${error}`);\n });\n\n // Give the server a moment to start\n await this._sleep(3000);\n\n if (this._devServer && !this._devServer.killed) {\n if (options.verbose) {\n console.log('Development server process started successfully');\n }\n return succeed(undefined);\n } else {\n return fail('Development server process failed to start');\n }\n } catch (error) {\n return fail(`Failed to start development server: ${error}`);\n }\n }\n\n /**\n * Waits for the development server to be ready by checking HTTP availability\n */\n private async _waitForServerReady(\n port: number,\n verbose: boolean,\n maxAttempts: number = 60\n ): Promise<Result<void>> {\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n const isReady = await this._checkServerHealth(port);\n if (isReady) {\n if (verbose) {\n console.log(`Server is ready at http://localhost:${port}`);\n }\n return succeed(undefined);\n }\n } catch (error) {\n // Server not ready yet, continue waiting\n }\n\n if (verbose && attempt % 10 === 0) {\n console.log(`Waiting for server to be ready... (attempt ${attempt}/${maxAttempts})`);\n }\n\n await this._sleep(1000);\n }\n\n return fail(`Server did not become ready after ${maxAttempts} attempts`);\n }\n\n /**\n * Checks if the server is responding\n */\n private async _checkServerHealth(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const request = http.get(`http://localhost:${port}`, (res) => {\n resolve(res.statusCode !== undefined && res.statusCode >= 200 && res.statusCode < 400);\n });\n\n request.on('error', () => {\n resolve(false);\n });\n\n request.setTimeout(3000, () => {\n request.destroy();\n resolve(false);\n });\n });\n }\n\n /**\n * Stops the development server\n */\n private _stopDevServer(): void {\n if (this._devServer && !this._devServer.killed) {\n this._devServer.kill('SIGTERM');\n setTimeout(() => {\n if (this._devServer && !this._devServer.killed) {\n this._devServer.kill('SIGKILL');\n }\n }, 5000);\n }\n }\n\n /**\n * Sleep for the specified number of milliseconds\n */\n private _sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n /**\n * Determines if a ZIP archive should be created based on the options\n */\n private _shouldCreateZip(options: IBrowseOptions): boolean {\n // Create ZIP if input or config are file paths (not predefined names)\n const hasFilePath = (path: string | undefined): boolean => {\n if (!path) return false;\n // Check if it's a file path (contains directory separators or file extensions)\n return path.includes('/') || path.includes('\\\\') || (path.includes('.') && !path.startsWith('.'));\n };\n\n return hasFilePath(options.input) || hasFilePath(options.config);\n }\n\n /**\n * Creates a ZIP archive containing the input and config files\n */\n private async _createZipArchive(\n options: IBrowseOptions\n ): Promise<Result<{ zipPath: string; manifest: any }>> {\n try {\n return await zipArchiver.createArchive({\n input: options.input,\n config: options.config\n });\n } catch (error) {\n return fail(`Failed to create ZIP archive: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n /**\n * Graceful shutdown - stops development server if running\n */\n public shutdown(): void {\n this._stopDevServer();\n }\n}\n"]}
package/lib/cli.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Main CLI class for ts-res-browser-cli
3
+ */
4
+ export declare class TsResBrowserCliApp {
5
+ private readonly _program;
6
+ private readonly _launcher;
7
+ constructor();
8
+ /**
9
+ * Runs the CLI with the provided arguments
10
+ */
11
+ run(argv: string[]): Promise<void>;
12
+ /**
13
+ * Sets up the CLI commands and options
14
+ */
15
+ private _setupCommands;
16
+ /**
17
+ * Check if any meaningful options were provided
18
+ */
19
+ private _hasOptions;
20
+ /**
21
+ * Handles the browse command
22
+ */
23
+ private _handleBrowseCommand;
24
+ /**
25
+ * Handles the config command (similar to ts-res-cli)
26
+ */
27
+ private _handleConfigCommand;
28
+ /**
29
+ * Parses and validates browse options
30
+ */
31
+ private _parseBrowseOptions;
32
+ /**
33
+ * Sets up graceful shutdown handling
34
+ */
35
+ private _setupGracefulShutdown;
36
+ }
37
+ //# sourceMappingURL=cli.d.ts.map