iconpeek 1.0.3 → 1.1.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/server.js CHANGED
@@ -1,521 +1,667 @@
1
- #!/usr/bin/env node
2
-
3
- const http = require('http');
4
- const fs = require('fs');
5
- const path = require('path');
6
- const { exec } = require('child_process');
7
-
8
- const DEFAULT_PORT = 4200;
9
- const PLACEHOLDER_ICON = path.join(__dirname, 'assets', 'placeholder-icon.png');
10
- const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
11
-
12
- const sseClients = [];
13
- const activeWatchers = new Map();
14
- let notifyDebounceTimeout = null;
15
-
16
- function notifyClients() {
17
- clearTimeout(notifyDebounceTimeout);
18
- notifyDebounceTimeout = setTimeout(() => {
19
- for (const client of sseClients) {
20
- client.write('data: reload\n\n');
21
- }
22
- }, 100);
23
- }
24
-
25
- function updateWatchers(projectRoot) {
26
- const state = buildState(projectRoot);
27
- const filesToWatch = [
28
- path.join(__dirname, 'style.css'),
29
- path.join(__dirname, 'index.html')
30
- ];
31
-
32
- if (state.configPath) filesToWatch.push(state.configPath);
33
- if (state.assets.icon.path && !state.assets.icon.placeholder) filesToWatch.push(state.assets.icon.path);
34
- if (state.assets.iosIcon.path && !state.assets.iosIcon.placeholder) filesToWatch.push(state.assets.iosIcon.path);
35
- if (state.assets.splash.path && !state.assets.splash.placeholder) filesToWatch.push(state.assets.splash.path);
36
- if (state.assets.splashDark.path && !state.assets.splashDark.placeholder) filesToWatch.push(state.assets.splashDark.path);
37
-
38
- // Clean up old watchers
39
- for (const [filePath, watcher] of activeWatchers.entries()) {
40
- if (!filesToWatch.includes(filePath)) {
41
- watcher.close();
42
- activeWatchers.delete(filePath);
43
- }
44
- }
45
-
46
- // Add new watchers
47
- for (const filePath of filesToWatch) {
48
- if (!activeWatchers.has(filePath)) {
49
- try {
50
- if (fs.existsSync(filePath)) {
51
- const watcher = fs.watch(filePath, () => {
52
- notifyClients();
53
- // Re-evaluate files in case config path or assets changed
54
- updateWatchers(projectRoot);
55
- });
56
- activeWatchers.set(filePath, watcher);
57
- }
58
- } catch (e) {
59
- // File may be missing or locked
60
- }
61
- }
62
- }
63
- }
64
-
65
-
66
- function parseArgs(argv) {
67
- const options = {
68
- projectRoot: process.cwd(),
69
- port: DEFAULT_PORT,
70
- open: true,
71
- };
72
-
73
- for (let index = 0; index < argv.length; index += 1) {
74
- const arg = argv[index];
75
- if (arg === '--project') {
76
- const value = argv[index + 1];
77
- if (!value) {
78
- throw new Error('Missing value for --project');
79
- }
80
- options.projectRoot = path.resolve(value);
81
- index += 1;
82
- continue;
83
- }
84
-
85
- if (arg === '--port') {
86
- const value = argv[index + 1];
87
- const parsed = value && /^\d+$/.test(value) ? Number(value) : NaN;
88
- if (!value || Number.isNaN(parsed) || parsed < 1 || parsed > 65535) {
89
- throw new Error('Missing or invalid value for --port (expected 1-65535)');
90
- }
91
- options.port = parsed;
92
- index += 1;
93
- continue;
94
- }
95
-
96
- if (arg === '--no-open') {
97
- options.open = false;
98
- continue;
99
- }
100
-
101
- if (arg === '--help' || arg === '-h') {
102
- printHelp();
103
- process.exit(0);
104
- }
105
-
106
- throw new Error(`Unknown argument: ${arg}`);
107
- }
108
-
109
- return options;
110
- }
111
-
112
- function printHelp() {
113
- process.stdout.write(
114
- [
115
- 'iconpeek',
116
- '',
117
- 'Usage:',
118
- ' npx iconpeek',
119
- ' npx iconpeek --project /path/to/expo/app',
120
- ' npx iconpeek --port 5000',
121
- ' npx iconpeek --no-open',
122
- '',
123
- 'Flags:',
124
- ' --project <path> Expo project root (default: current working directory)',
125
- ' --port <number> Starting port (default: 4200)',
126
- ' --no-open Do not open a browser window',
127
- '',
128
- ].join('\n')
129
- );
130
- }
131
-
132
- function ensurePlaceholderAsset() {
133
- if (fs.existsSync(PLACEHOLDER_ICON)) {
134
- return;
135
- }
136
-
137
- fs.mkdirSync(path.dirname(PLACEHO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7CsAAAj0VAA4BQCAGp6dyU4AACDQ0wHgFAAA5joyi50AAECgQwHgFAAA5jg6gw+fAIgAABjrjNnrKwAACHRKADgFAIAxzpq5p50AiAAAuNaZs/bUrwBEAABc4+wZ63cAACDQ6QHgFAAAznXFbL3kBEAEAMA5rpqpl30FIAIA4JgrZ6nfAQCAQJcGgFMAAHjO1TP08hMAEQAA+4yYnUO+AhABAPCYUTNz2O8AiAAA+NjIWTn0lwBFAADcN3pGDv8rABEAAK/NmI1T/gxQBADAN7Nm4rR/D4AIACDdzFk49V8EJAIASDV7Bk7/NwHOXgAAGK3C7JseANtWYyEAYIQqM69EAGxbnQUBgKtUmnVlAmDbai0MAJyp2owrFQDbVm+BAOCoirOt3AXd+vLl1z9mXwMAPKvi4H9R7gTgVuWFA4CPVJ9hpQNg2+ovIAC81WF2lb/AW74SAKCyDoP/RfkTgFudFhaALN1mVKsA2LZ+CwzA+jrOpnYXfMtXAgDM1HHwv2h3AnCr88ID0Fv3GdT64m85DQBghO6D/8USN3FLCABwhVUG/4ulbuaWEADgDKsN/hetfwfgI6s+MADGWXmWLHtjt5wGALDHyoP/xfI3+JYYAOCehKF/K+pmbwkBALYtb/C/iLzpW0IAIFPq4H8RffNviQGAtaUP/VsW4g4hALAWg/97FuQBggCgFwP/cxZoJzEAUJOhv4/FOkgQAMxh4B9j8S4gCgDOZdifz4IOJg4A7jPkx/o/rsTlUKe3I3IAAAAASUVORK5CYII=';
140
- fs.writeFileSync(PLACEHOLDER_ICON, Buffer.from(placeholderBase64, 'base64'));
141
- }
142
-
143
- function parseConfigFile(filePath) {
144
- if (!fs.existsSync(filePath)) {
145
- return null;
146
- }
147
-
148
- try {
149
- const raw = fs.readFileSync(filePath, 'utf8');
150
- return JSON.parse(raw);
151
- } catch (error) {
152
- return {
153
- __error: `Failed to parse ${path.basename(filePath)}: ${error.message}`,
154
- };
155
- }
156
- }
157
-
158
- function parseJsConfigFile(filePath) {
159
- if (!fs.existsSync(filePath)) {
160
- return null;
161
- }
162
-
163
- try {
164
- delete require.cache[require.resolve(filePath)];
165
- const loaded = require(filePath);
166
- const config = loaded && loaded.default ? loaded.default : loaded;
167
- if (typeof config === 'function') {
168
- return config({ config: {} });
169
- }
170
- return config;
171
- } catch (error) {
172
- // Node 20.19+/22.12+ ship require(esm) unflagged, so "export default" in
173
- // app.config.js works natively there and this branch won't be hit. On
174
- // older Node (down to this package's declared >=14 floor), require()
175
- // still throws ERR_REQUIRE_ESM on ESM syntax, so give a specific,
176
- // actionable message instead of a generic parse failure.
177
- const looksLikeEsm =
178
- error.code === 'ERR_REQUIRE_ESM' ||
179
- (error instanceof SyntaxError && /export|import/.test(error.message));
180
-
181
- const message = looksLikeEsm
182
- ? `Failed to load ${path.basename(filePath)}: it uses ES module syntax (import/export). ` +
183
- `This Node.js version (${process.version}) can't require() that. Either upgrade to ` +
184
- `Node 20.19+/22.12+ (which support this natively), convert the file to ` +
185
- `"module.exports = ({ config }) => ({ ...config })", or use app.json / app.config.json instead.`
186
- : `Failed to load ${path.basename(filePath)}: ${error.message}`;
187
-
188
- return { __error: message };
189
- }
190
- }
191
- function detectConfig(projectRoot) {
192
- const jsonCandidates = ['app.json', 'app.config.json'];
193
-
194
- for (const name of jsonCandidates) {
195
- const filePath = path.join(projectRoot, name);
196
- const parsed = parseConfigFile(filePath);
197
- if (parsed) {
198
- return {
199
- configPath: filePath,
200
- configName: name,
201
- raw: parsed,
202
- };
203
- }
204
- }
205
-
206
- const jsConfigPath = path.join(projectRoot, 'app.config.js');
207
- const parsedJsConfig = parseJsConfigFile(jsConfigPath);
208
- if (parsedJsConfig) {
209
- return {
210
- configPath: jsConfigPath,
211
- configName: 'app.config.js',
212
- raw: parsedJsConfig,
213
- };
214
- }
215
-
216
- return {
217
- configPath: null,
218
- configName: null,
219
- raw: null,
220
- };
221
- }
222
- function normalizeHexColor(value, fallback) {
223
- if (typeof value !== 'string') {
224
- return fallback;
225
- }
226
-
227
- const trimmed = value.trim();
228
- if (/^#[0-9a-fA-F]{6}$/.test(trimmed)) {
229
- return trimmed.toUpperCase();
230
- }
231
- if (/^#[0-9a-fA-F]{3}$/.test(trimmed)) {
232
- return `#${trimmed[1]}${trimmed[1]}${trimmed[2]}${trimmed[2]}${trimmed[3]}${trimmed[3]}`.toUpperCase();
233
- }
234
- // Expo allows 8-digit #RRGGBBAA colors. CSS background-color in this preview
235
- // doesn't need the alpha channel, so keep the RGB and drop AA rather than
236
- // silently discarding the whole value to the fallback.
237
- if (/^#[0-9a-fA-F]{8}$/.test(trimmed)) {
238
- return trimmed.slice(0, 7).toUpperCase();
239
- }
240
- return fallback;
241
- }
242
-
243
- function safeProjectAsset(projectRoot, relativePath) {
244
- if (typeof relativePath !== 'string' || !relativePath.trim()) {
245
- return null;
246
- }
247
-
248
- const resolvedRoot = path.resolve(projectRoot);
249
- const resolvedPath = path.resolve(resolvedRoot, relativePath);
250
- const relativeFromRoot = path.relative(resolvedRoot, resolvedPath);
251
-
252
- // Reject anything that escapes the project root (e.g. "../../etc/foo.png")
253
- // so a hostile or malformed app.json can't be used to read arbitrary files.
254
- if (relativeFromRoot.startsWith('..') || path.isAbsolute(relativeFromRoot)) {
255
- return null;
256
- }
257
-
258
- return resolvedPath;
259
- }
260
-
261
- function resolveAsset(projectRoot, relativePath) {
262
- const absolutePath = safeProjectAsset(projectRoot, relativePath);
263
- if (!absolutePath) {
264
- return {
265
- path: PLACEHOLDER_ICON,
266
- relative: 'assets/placeholder-icon.png',
267
- placeholder: true,
268
- missing: false,
269
- };
270
- }
271
-
272
- try {
273
- if (fs.existsSync(absolutePath) && fs.statSync(absolutePath).isFile()) {
274
- return {
275
- path: absolutePath,
276
- relative: path.relative(projectRoot, absolutePath).replace(/\\/g, '/'),
277
- placeholder: false,
278
- missing: false,
279
- };
280
- }
281
- } catch (error) {
282
- return {
283
- path: PLACEHOLDER_ICON,
284
- relative: 'assets/placeholder-icon.png',
285
- placeholder: true,
286
- missing: true,
287
- error: error.message,
288
- };
289
- }
290
-
291
- return {
292
- path: PLACEHOLDER_ICON,
293
- relative: 'assets/placeholder-icon.png',
294
- placeholder: true,
295
- missing: true,
296
- };
297
- }
298
-
299
- function buildState(projectRoot) {
300
- ensurePlaceholderAsset();
301
- const detected = detectConfig(projectRoot);
302
- const rawConfig = detected.raw && !detected.raw.__error ? detected.raw : {};
303
- const expo = rawConfig.expo || {};
304
- const android = expo.android || {};
305
- const adaptiveIcon = android.adaptiveIcon || {};
306
- const splash = expo.splash || {};
307
- const splashDark = splash.dark || {};
308
-
309
- const iconAsset = resolveAsset(projectRoot, adaptiveIcon.foregroundImage || expo.icon);
310
- const iosIconAsset = resolveAsset(projectRoot, expo.icon);
311
- const splashAsset = resolveAsset(projectRoot, splash.image);
312
- const splashDarkAsset = resolveAsset(projectRoot, splashDark.image || splash.image);
313
-
314
- const warningMessages = [];
315
- if (!detected.configPath) {
316
- warningMessages.push('No app.json, app.config.json, or app.config.js found. Showing placeholder assets and default colors.');
317
- }
318
- if (detected.raw && detected.raw.__error) {
319
- warningMessages.push(detected.raw.__error);
320
- }
321
- if (iconAsset.missing) {
322
- warningMessages.push('Android foreground icon was missing. Using the bundled placeholder.');
323
- }
324
- if (iosIconAsset.missing) {
325
- warningMessages.push('Expo icon was missing. Using the bundled placeholder for iOS.');
326
- }
327
- if (splashAsset.missing) {
328
- warningMessages.push('Splash image was missing. Using the bundled placeholder.');
329
- }
330
-
331
- return {
332
- projectRoot,
333
- configName: detected.configName,
334
- configPath: detected.configPath,
335
- warnings: warningMessages,
336
- assets: {
337
- icon: iconAsset,
338
- iosIcon: iosIconAsset,
339
- splash: splashAsset,
340
- splashDark: splashDarkAsset,
341
- },
342
- expo: {
343
- name: typeof expo.name === 'string' && expo.name.trim() ? expo.name.trim() : 'Your App',
344
- icon: expo.icon || null,
345
- androidForegroundImage: adaptiveIcon.foregroundImage || null,
346
- adaptiveBackgroundColor: normalizeHexColor(adaptiveIcon.backgroundColor, '#FFFFFF'),
347
- splashImage: splash.image || null,
348
- splashImageWidth: typeof splash.imageWidth === 'number' ? splash.imageWidth : null,
349
- splashBackgroundColor: normalizeHexColor(splash.backgroundColor, '#FFFFFF'),
350
- splashDarkBackgroundColor: normalizeHexColor(splashDark.backgroundColor, '#121212'),
351
- splashDarkImage: splashDark.image || null,
352
- },
353
- };
354
- }
355
-
356
- function escapeHtml(value) {
357
- return String(value)
358
- .replace(/&/g, '&amp;')
359
- .replace(/</g, '&lt;')
360
- .replace(/>/g, '&gt;')
361
- .replace(/"/g, '&quot;')
362
- .replace(/'/g, '&#39;');
363
- }
364
-
365
- function createHtml(state) {
366
- const payload = JSON.stringify({
367
- warnings: state.warnings,
368
- projectRoot: state.projectRoot,
369
- configName: state.configName,
370
- assets: {
371
- iconPath: state.assets.icon.relative,
372
- iosIconPath: state.assets.iosIcon.relative,
373
- splashPath: state.assets.splash.relative,
374
- splashDarkPath: state.assets.splashDark.relative,
375
- },
376
- expo: state.expo,
377
- }).replace(/</g, '\\u003c');
378
-
379
- const htmlTemplate = fs.readFileSync(path.join(__dirname, 'index.html'), 'utf8');
380
- const styles = fs.readFileSync(path.join(__dirname, 'style.css'), 'utf8');
381
-
382
- return htmlTemplate
383
- .replace('<style id="main-styles"></style>', `<style>\n${styles}\n </style>`)
384
- .replace('{{PROJECT_ROOT}}', escapeHtml(state.projectRoot))
385
- .replace('{{CONFIG_NAME}}', escapeHtml(state.configName || 'Not found'))
386
- .replace(/\{\{EXPO_NAME\}\}/g, escapeHtml(state.expo.name))
387
- .replace('let STATE = {};', `let STATE = ${payload};`);
388
- }
389
-
390
- function openBrowser(url) {
391
- const command =
392
- process.platform === 'darwin'
393
- ? `open "${url}"`
394
- : process.platform === 'win32'
395
- ? `start "" "${url}"`
396
- : `xdg-open "${url}"`;
397
-
398
- exec(command, (error) => {
399
- if (error) {
400
- process.stdout.write(`Open manually: ${url}\n`);
401
- }
402
- });
403
- }
404
-
405
- function servePng(res, filePath) {
406
- fs.readFile(filePath, (error, data) => {
407
- if (error || !data || data.length < PNG_SIGNATURE.length || !data.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)) {
408
- res.writeHead(404, {
409
- 'Content-Type': 'text/plain; charset=utf-8',
410
- 'Cache-Control': 'no-store',
411
- });
412
- res.end('Not Found');
413
- return;
414
- }
415
-
416
- res.writeHead(200, {
417
- 'Content-Type': 'image/png',
418
- 'Cache-Control': 'no-store',
419
- });
420
- res.end(data);
421
- });
422
- }
423
-
424
- function createServer(options) {
425
- return http.createServer((req, res) => {
426
- const requestUrl = new URL(req.url, 'http://localhost');
427
- const state = buildState(options.projectRoot);
428
-
429
- if (requestUrl.pathname === '/') {
430
- const html = createHtml(state);
431
- res.writeHead(200, {
432
- 'Content-Type': 'text/html; charset=utf-8',
433
- 'Cache-Control': 'no-store',
434
- });
435
- res.end(html);
436
- return;
437
- }
438
-
439
- if (requestUrl.pathname === '/events') {
440
- res.writeHead(200, {
441
- 'Content-Type': 'text/event-stream',
442
- 'Cache-Control': 'no-cache',
443
- 'Connection': 'keep-alive',
444
- });
445
- res.write('\n');
446
- sseClients.push(res);
447
-
448
- req.on('close', () => {
449
- const index = sseClients.indexOf(res);
450
- if (index !== -1) {
451
- sseClients.splice(index, 1);
452
- }
453
- });
454
- return;
455
- }
456
-
457
- if (requestUrl.pathname === '/assets/icon') {
458
- servePng(res, state.assets.icon.path);
459
- return;
460
- }
461
-
462
- if (requestUrl.pathname === '/assets/ios-icon') {
463
- servePng(res, state.assets.iosIcon.path);
464
- return;
465
- }
466
-
467
- if (requestUrl.pathname === '/assets/splash') {
468
- servePng(res, state.assets.splash.path);
469
- return;
470
- }
471
-
472
- if (requestUrl.pathname === '/assets/splash-dark') {
473
- servePng(res, state.assets.splashDark.path);
474
- return;
475
- }
476
-
477
- res.writeHead(404, {
478
- 'Content-Type': 'text/plain; charset=utf-8',
479
- 'Cache-Control': 'no-store',
480
- });
481
- res.end('Not Found');
482
- });
483
- }
484
-
485
- function startServer(options) {
486
- const server = createServer(options);
487
- let currentPort = options.port;
488
- let browserOpened = false;
489
-
490
- server.on('error', (error) => {
491
- if (error && error.code === 'EADDRINUSE') {
492
- currentPort += 1;
493
- server.listen(currentPort);
494
- return;
495
- }
496
-
497
- process.stderr.write(`${error.message}\n`);
498
- process.exit(1);
499
- });
500
-
501
- server.on('listening', () => {
502
- const url = `http://localhost:${currentPort}`;
503
- process.stdout.write(`iconpeek running at ${url}\n`);
504
- updateWatchers(options.projectRoot);
505
- if (options.open && !browserOpened) {
506
- browserOpened = true;
507
- openBrowser(url);
508
- }
509
- });
510
-
511
- server.listen(currentPort);
512
- }
513
-
514
- try {
515
- const options = parseArgs(process.argv.slice(2));
516
- startServer(options);
517
- } catch (error) {
518
- process.stderr.write(`${error.message}\n\n`);
519
- printHelp();
520
- process.exit(1);
1
+ #!/usr/bin/env node
2
+
3
+ const http = require('http');
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const { exec } = require('child_process');
7
+
8
+ const DEFAULT_PORT = 4200;
9
+ const PLACEHOLDER_ICON = path.join(__dirname, 'assets', 'placeholder-icon.png');
10
+ const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
11
+
12
+ const sseClients = [];
13
+ const activeWatchers = new Map();
14
+ let notifyDebounceTimeout = null;
15
+
16
+ function notifyClients() {
17
+ clearTimeout(notifyDebounceTimeout);
18
+ notifyDebounceTimeout = setTimeout(() => {
19
+ for (const client of sseClients) {
20
+ client.write('data: reload\n\n');
21
+ }
22
+ }, 100);
23
+ }
24
+
25
+ function updateWatchers(projectRoot) {
26
+ const state = buildState(projectRoot);
27
+ const filesToWatch = [
28
+ path.join(__dirname, 'style.css'),
29
+ path.join(__dirname, 'index.html')
30
+ ];
31
+
32
+ if (state.configPath) filesToWatch.push(state.configPath);
33
+ if (state.assets.icon.path && !state.assets.icon.placeholder) filesToWatch.push(state.assets.icon.path);
34
+ if (state.assets.iosIcon.path && !state.assets.iosIcon.placeholder) filesToWatch.push(state.assets.iosIcon.path);
35
+ if (state.assets.splash.path && !state.assets.splash.placeholder) filesToWatch.push(state.assets.splash.path);
36
+ if (state.assets.splashDark.path && !state.assets.splashDark.placeholder) filesToWatch.push(state.assets.splashDark.path);
37
+
38
+ // Clean up old watchers
39
+ for (const [filePath, watcher] of activeWatchers.entries()) {
40
+ if (!filesToWatch.includes(filePath)) {
41
+ watcher.close();
42
+ activeWatchers.delete(filePath);
43
+ }
44
+ }
45
+
46
+ // Add new watchers
47
+ for (const filePath of filesToWatch) {
48
+ if (!activeWatchers.has(filePath)) {
49
+ try {
50
+ if (fs.existsSync(filePath)) {
51
+ const watcher = fs.watch(filePath, () => {
52
+ notifyClients();
53
+ // Re-evaluate files in case config path or assets changed
54
+ updateWatchers(projectRoot);
55
+ });
56
+ activeWatchers.set(filePath, watcher);
57
+ }
58
+ } catch (e) {
59
+ // File may be missing or locked
60
+ }
61
+ }
62
+ }
63
+ }
64
+
65
+
66
+ function parseArgs(argv) {
67
+ const options = {
68
+ projectRoot: process.cwd(),
69
+ port: DEFAULT_PORT,
70
+ open: true,
71
+ };
72
+
73
+ for (let index = 0; index < argv.length; index += 1) {
74
+ const arg = argv[index];
75
+ if (arg === '--project') {
76
+ const value = argv[index + 1];
77
+ if (!value) {
78
+ throw new Error('Missing value for --project');
79
+ }
80
+ options.projectRoot = path.resolve(value);
81
+ index += 1;
82
+ continue;
83
+ }
84
+
85
+ if (arg === '--port') {
86
+ const value = argv[index + 1];
87
+ const parsed = value && /^\d+$/.test(value) ? Number(value) : NaN;
88
+ if (!value || Number.isNaN(parsed) || parsed < 1 || parsed > 65535) {
89
+ throw new Error('Missing or invalid value for --port (expected 1-65535)');
90
+ }
91
+ options.port = parsed;
92
+ index += 1;
93
+ continue;
94
+ }
95
+
96
+ if (arg === '--no-open') {
97
+ options.open = false;
98
+ continue;
99
+ }
100
+
101
+ if (arg === '--help' || arg === '-h') {
102
+ printHelp();
103
+ process.exit(0);
104
+ }
105
+
106
+ throw new Error(`Unknown argument: ${arg}`);
107
+ }
108
+
109
+ return options;
110
+ }
111
+
112
+ function printHelp() {
113
+ process.stdout.write(
114
+ [
115
+ 'iconpeek',
116
+ '',
117
+ 'Usage:',
118
+ ' npx iconpeek',
119
+ ' npx iconpeek --project /path/to/expo/app',
120
+ ' npx iconpeek --port 5000',
121
+ ' npx iconpeek --no-open',
122
+ '',
123
+ 'Flags:',
124
+ ' --project <path> Expo project root (default: current working directory)',
125
+ ' --port <number> Starting port (default: 4200)',
126
+ ' --no-open Do not open a browser window',
127
+ '',
128
+ ].join('\n')
129
+ );
130
+ }
131
+
132
+ function ensurePlaceholderAsset() {
133
+ if (fs.existsSync(PLACEHOLDER_ICON)) {
134
+ return;
135
+ }
136
+
137
+ fs.mkdirSync(path.dirname(PLACEHOLDER_ICON), { recursive: true });
138
+ const placeholderBase64 =
139
+ 'iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAYAAAD0eNT6AAARwElEQVR4nO3dQXLkxrWGUUghr8PrUnjgNfRIEVqAIzTqNXjg0Lq8Dg/0Bv0oFdlFslAAMu/N/5yxbQEJIu9XWaT8w8ZQX778+sfsawCo6OvXf/0w+xqSWOwLGPIA5xIH57OgBxn2AHOIgmMs3k4GPkBNgmAfi/UAQx+gFzHwOQt0h4EPsBZB8D0LcsPgB1ibEPhL/EIY+gCZ0mMg9uYNfgC2LTcE4m7a4AfgnrQQiLhZQx+APRJiYOkbNPgBOGLlEPhx9gVcxfAH4KiVZ8lyZbPywwJgntVOA5a5GYMfgBFWCYH2N2HwAzBD9xBo/TsAhj8As3SfQS3rpfuiA7CWjqcB7U4ADH8Aquk4m1oFQMcFBiBDtxnV4sii26ICkK3DVwLlTwAMfwC66TC7SgdAhwUEgHuqz7CSRxTVFw0A9qj4lUC5EwDDH4DVVJxtpQKg4gIBwBmqzbgyAVBtYQDgbJVmXYkAqLQgAHClKjNvegBUWQgAGKXC7JsaABUWAABmmD0DpwXA7BsHgNlmzsIpAWD4A8A3s2bi8AAw/AHgtRmzcWgAGP4AcN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aUP/VsW4g4hALAWg/97FuQBggCgFwP/cxZoJzEAUJOhv4/FOkgQAMxh4B9j8S4gCgDOZdifz4IOJg4A7jPkx/o/rsTlUKe3I3IAAAAASUVORK5CYII=';
140
+ fs.writeFileSync(PLACEHOLDER_ICON, Buffer.from(placeholderBase64, 'base64'));
141
+ }
142
+
143
+ function parseConfigFile(filePath) {
144
+ if (!fs.existsSync(filePath)) {
145
+ return null;
146
+ }
147
+
148
+ try {
149
+ const raw = fs.readFileSync(filePath, 'utf8');
150
+ return JSON.parse(raw);
151
+ } catch (error) {
152
+ return {
153
+ __error: `Failed to parse ${path.basename(filePath)}: ${error.message}`,
154
+ };
155
+ }
156
+ }
157
+
158
+ function parseJsConfigFile(filePath, baseConfig = {}) {
159
+ if (!fs.existsSync(filePath)) {
160
+ return null;
161
+ }
162
+
163
+ try {
164
+ delete require.cache[require.resolve(filePath)];
165
+ const loaded = require(filePath);
166
+ const config = loaded && loaded.default ? loaded.default : loaded;
167
+ if (typeof config === 'function') {
168
+ return config({ config: baseConfig });
169
+ }
170
+ return config;
171
+ } catch (error) {
172
+ // Node 20.19+/22.12+ ship require(esm) unflagged, so "export default" in
173
+ // app.config.js works natively there and this branch won't be hit. On
174
+ // older Node (down to this package's declared >=14 floor), require()
175
+ // still throws ERR_REQUIRE_ESM on ESM syntax, so give a specific,
176
+ // actionable message instead of a generic parse failure.
177
+ const looksLikeEsm =
178
+ error.code === 'ERR_REQUIRE_ESM' ||
179
+ (error instanceof SyntaxError && /export|import/.test(error.message));
180
+
181
+ const message = looksLikeEsm
182
+ ? `Failed to load ${path.basename(filePath)}: it uses ES module syntax (import/export). ` +
183
+ `This Node.js version (${process.version}) can't require() that. Either upgrade to ` +
184
+ `Node 20.19+/22.12+ (which support this natively), convert the file to ` +
185
+ `"module.exports = ({ config }) => ({ ...config })", or use app.json / app.config.json instead.`
186
+ : `Failed to load ${path.basename(filePath)}: ${error.message}`;
187
+
188
+ return { __error: message };
189
+ }
190
+ }
191
+ function detectConfig(projectRoot) {
192
+ const jsonCandidates = ['app.json', 'app.config.json'];
193
+ let baseJsonParsed = null;
194
+ let baseJsonPath = null;
195
+ let baseJsonName = null;
196
+
197
+ for (const name of jsonCandidates) {
198
+ const filePath = path.join(projectRoot, name);
199
+ const parsed = parseConfigFile(filePath);
200
+ if (parsed) {
201
+ baseJsonParsed = parsed;
202
+ baseJsonPath = filePath;
203
+ baseJsonName = name;
204
+ break;
205
+ }
206
+ }
207
+
208
+ // If app.config.js exists, it takes precedence in Expo projects (dynamic config)
209
+ const jsConfigPath = path.join(projectRoot, 'app.config.js');
210
+ if (fs.existsSync(jsConfigPath)) {
211
+ const baseConfig = baseJsonParsed && baseJsonParsed.expo ? baseJsonParsed.expo : (baseJsonParsed || {});
212
+ const parsedJsConfig = parseJsConfigFile(jsConfigPath, baseConfig);
213
+ if (parsedJsConfig) {
214
+ return {
215
+ configPath: jsConfigPath,
216
+ configName: 'app.config.js',
217
+ raw: parsedJsConfig,
218
+ };
219
+ }
220
+ }
221
+
222
+ if (baseJsonParsed) {
223
+ return {
224
+ configPath: baseJsonPath,
225
+ configName: baseJsonName,
226
+ raw: baseJsonParsed,
227
+ };
228
+ }
229
+
230
+ return {
231
+ configPath: null,
232
+ configName: null,
233
+ raw: null,
234
+ };
235
+ }
236
+ function normalizeHexColor(value, fallback) {
237
+ if (typeof value !== 'string') {
238
+ return fallback;
239
+ }
240
+
241
+ const trimmed = value.trim();
242
+ if (/^#[0-9a-fA-F]{6}$/.test(trimmed)) {
243
+ return trimmed.toUpperCase();
244
+ }
245
+ if (/^#[0-9a-fA-F]{3}$/.test(trimmed)) {
246
+ return `#${trimmed[1]}${trimmed[1]}${trimmed[2]}${trimmed[2]}${trimmed[3]}${trimmed[3]}`.toUpperCase();
247
+ }
248
+ // Expo allows 8-digit #RRGGBBAA colors. CSS background-color in this preview
249
+ // doesn't need the alpha channel, so keep the RGB and drop AA rather than
250
+ // silently discarding the whole value to the fallback.
251
+ if (/^#[0-9a-fA-F]{8}$/.test(trimmed)) {
252
+ return trimmed.slice(0, 7).toUpperCase();
253
+ }
254
+ return fallback;
255
+ }
256
+
257
+ function safeProjectAsset(projectRoot, relativePath) {
258
+ if (typeof relativePath !== 'string' || !relativePath.trim()) {
259
+ return null;
260
+ }
261
+
262
+ const resolvedRoot = path.resolve(projectRoot);
263
+ const resolvedPath = path.resolve(resolvedRoot, relativePath);
264
+ const relativeFromRoot = path.relative(resolvedRoot, resolvedPath);
265
+
266
+ // Reject anything that escapes the project root (e.g. "../../etc/foo.png")
267
+ // so a hostile or malformed app.json can't be used to read arbitrary files.
268
+ if (relativeFromRoot.startsWith('..') || path.isAbsolute(relativeFromRoot)) {
269
+ return null;
270
+ }
271
+
272
+ return resolvedPath;
273
+ }
274
+
275
+ function resolveAsset(projectRoot, relativePath) {
276
+ const absolutePath = safeProjectAsset(projectRoot, relativePath);
277
+ if (!absolutePath) {
278
+ return {
279
+ path: PLACEHOLDER_ICON,
280
+ relative: 'assets/placeholder-icon.png',
281
+ placeholder: true,
282
+ missing: false,
283
+ };
284
+ }
285
+
286
+ try {
287
+ if (fs.existsSync(absolutePath) && fs.statSync(absolutePath).isFile()) {
288
+ return {
289
+ path: absolutePath,
290
+ relative: path.relative(projectRoot, absolutePath).replace(/\\/g, '/'),
291
+ placeholder: false,
292
+ missing: false,
293
+ };
294
+ }
295
+ } catch (error) {
296
+ return {
297
+ path: PLACEHOLDER_ICON,
298
+ relative: 'assets/placeholder-icon.png',
299
+ placeholder: true,
300
+ missing: true,
301
+ error: error.message,
302
+ };
303
+ }
304
+
305
+ return {
306
+ path: PLACEHOLDER_ICON,
307
+ relative: 'assets/placeholder-icon.png',
308
+ placeholder: true,
309
+ missing: true,
310
+ };
311
+ }
312
+
313
+ function findFallbackAsset(projectRoot, candidates) {
314
+ for (const rel of candidates) {
315
+ const resolved = safeProjectAsset(projectRoot, rel);
316
+ if (resolved && fs.existsSync(resolved) && fs.statSync(resolved).isFile()) {
317
+ return {
318
+ path: resolved,
319
+ relative: path.relative(projectRoot, resolved).replace(/\\/g, '/'),
320
+ placeholder: false,
321
+ missing: false,
322
+ };
323
+ }
324
+ }
325
+ return null;
326
+ }
327
+
328
+ function buildState(projectRoot) {
329
+ ensurePlaceholderAsset();
330
+ const detected = detectConfig(projectRoot);
331
+ const rawConfig = detected.raw && !detected.raw.__error ? detected.raw : {};
332
+ const expo = (rawConfig && rawConfig.expo) || rawConfig || {};
333
+ const android = expo.android || {};
334
+ const adaptiveIcon = android.adaptiveIcon || {};
335
+ let splashPluginConfig = {};
336
+ if (Array.isArray(expo.plugins)) {
337
+ for (const plugin of expo.plugins) {
338
+ if (Array.isArray(plugin) && plugin[0] === 'expo-splash-screen' && typeof plugin[1] === 'object') {
339
+ splashPluginConfig = plugin[1];
340
+ break;
341
+ }
342
+ }
343
+ }
344
+ const splash = { ...splashPluginConfig, ...(expo.splash || {}) };
345
+ const splashDark = splash.dark || {};
346
+
347
+ let iconAsset = resolveAsset(projectRoot, adaptiveIcon.foregroundImage || expo.icon);
348
+ let iosIconAsset = resolveAsset(projectRoot, expo.icon);
349
+ let splashAsset = resolveAsset(projectRoot, splash.image);
350
+ let splashDarkAsset = resolveAsset(projectRoot, splashDark.image || splash.image);
351
+
352
+ let usedFallback = false;
353
+ if (iconAsset.placeholder) {
354
+ const fallback = findFallbackAsset(projectRoot, [
355
+ 'icon_output/android/mipmap-xxxhdpi/ic_launcher_foreground.png',
356
+ 'android/mipmap-xxxhdpi/ic_launcher_foreground.png',
357
+ 'icon_output/android/mipmap-xxhdpi/ic_launcher_foreground.png',
358
+ 'android/mipmap-xxhdpi/ic_launcher_foreground.png',
359
+ 'icon_output/android/play-store/play_store_icon.png',
360
+ 'android/play-store/play_store_icon.png',
361
+ 'assets/adaptive-icon.png',
362
+ 'assets/iconpeek.png',
363
+ 'assets/icon.png',
364
+ 'adaptive-icon.png',
365
+ 'iconpeek.png',
366
+ 'icon.png',
367
+ ]);
368
+ if (fallback) {
369
+ iconAsset = fallback;
370
+ usedFallback = true;
371
+ }
372
+ }
373
+
374
+ if (iosIconAsset.placeholder) {
375
+ const fallback = findFallbackAsset(projectRoot, [
376
+ 'icon_output/ios/AppIcon.appiconset/icon_ios-marketing_1024x1024@1x.png',
377
+ 'ios/AppIcon.appiconset/icon_ios-marketing_1024x1024@1x.png',
378
+ 'icon_output/android/play-store/play_store_icon.png',
379
+ 'android/play-store/play_store_icon.png',
380
+ 'assets/iconpeek.png',
381
+ 'assets/icon.png',
382
+ 'iconpeek.png',
383
+ 'icon.png',
384
+ ]);
385
+ if (fallback) {
386
+ iosIconAsset = fallback;
387
+ usedFallback = true;
388
+ }
389
+ }
390
+
391
+ if (splashAsset.placeholder) {
392
+ const fallback = findFallbackAsset(projectRoot, [
393
+ 'assets/splash.png',
394
+ 'assets/splash-icon.png',
395
+ 'assets/iconpeek.png',
396
+ 'splash.png',
397
+ 'icon_output/android/play-store/play_store_icon.png',
398
+ 'android/play-store/play_store_icon.png',
399
+ ]);
400
+ if (fallback) {
401
+ splashAsset = fallback;
402
+ usedFallback = true;
403
+ }
404
+ }
405
+
406
+ if (splashDarkAsset.placeholder) {
407
+ const fallback = findFallbackAsset(projectRoot, [
408
+ 'assets/splash-dark.png',
409
+ 'splash-dark.png',
410
+ 'assets/splash.png',
411
+ 'assets/iconpeek.png',
412
+ ]);
413
+ if (fallback) {
414
+ splashDarkAsset = fallback;
415
+ usedFallback = true;
416
+ }
417
+ }
418
+
419
+ const warningMessages = [];
420
+ if (!detected.configPath) {
421
+ if (usedFallback) {
422
+ warningMessages.push('No app.json, app.config.json, or app.config.js found. Using assets found in icon_output / assets.');
423
+ } else {
424
+ warningMessages.push('No app.json, app.config.json, or app.config.js found. Showing placeholder assets and default colors.');
425
+ }
426
+ }
427
+ if (detected.raw && detected.raw.__error) {
428
+ warningMessages.push(detected.raw.__error);
429
+ }
430
+ if (iconAsset.missing) {
431
+ warningMessages.push('Android foreground icon was missing. Using the bundled placeholder.');
432
+ }
433
+ if (iosIconAsset.missing) {
434
+ warningMessages.push('Expo icon was missing. Using the bundled placeholder for iOS.');
435
+ }
436
+ if (splashAsset.missing) {
437
+ warningMessages.push('Splash image was missing. Using the bundled placeholder.');
438
+ }
439
+
440
+ return {
441
+ projectRoot,
442
+ configName: detected.configName,
443
+ configPath: detected.configPath,
444
+ warnings: warningMessages,
445
+ assets: {
446
+ icon: iconAsset,
447
+ iosIcon: iosIconAsset,
448
+ splash: splashAsset,
449
+ splashDark: splashDarkAsset,
450
+ },
451
+ expo: {
452
+ name: typeof expo.name === 'string' && expo.name.trim() ? expo.name.trim() : 'Your App',
453
+ icon: expo.icon || null,
454
+ androidForegroundImage: adaptiveIcon.foregroundImage || null,
455
+ adaptiveBackgroundColor: normalizeHexColor(adaptiveIcon.backgroundColor, '#FFFFFF'),
456
+ splashImage: splash.image || null,
457
+ splashImageWidth: typeof splash.imageWidth === 'number' ? splash.imageWidth : null,
458
+ splashBackgroundColor: normalizeHexColor(splash.backgroundColor, '#FFFFFF'),
459
+ splashDarkBackgroundColor: normalizeHexColor(splashDark.backgroundColor, '#121212'),
460
+ splashDarkImage: splashDark.image || null,
461
+ },
462
+ };
463
+ }
464
+
465
+ function escapeHtml(value) {
466
+ return String(value)
467
+ .replace(/&/g, '&amp;')
468
+ .replace(/</g, '&lt;')
469
+ .replace(/>/g, '&gt;')
470
+ .replace(/"/g, '&quot;')
471
+ .replace(/'/g, '&#39;');
472
+ }
473
+
474
+ function createHtml(state) {
475
+ const payload = JSON.stringify({
476
+ warnings: state.warnings,
477
+ projectRoot: state.projectRoot,
478
+ configName: state.configName,
479
+ assets: {
480
+ iconPath: state.assets.icon.relative,
481
+ iosIconPath: state.assets.iosIcon.relative,
482
+ splashPath: state.assets.splash.relative,
483
+ splashDarkPath: state.assets.splashDark.relative,
484
+ },
485
+ expo: state.expo,
486
+ }).replace(/</g, '\\u003c');
487
+
488
+ const htmlTemplate = fs.readFileSync(path.join(__dirname, 'index.html'), 'utf8');
489
+ const styles = fs.readFileSync(path.join(__dirname, 'style.css'), 'utf8');
490
+
491
+ return htmlTemplate
492
+ .replace('<style id="main-styles"></style>', `<style>\n${styles}\n </style>`)
493
+ .replace('{{PROJECT_ROOT}}', escapeHtml(state.projectRoot))
494
+ .replace('{{CONFIG_NAME}}', escapeHtml(state.configName || 'Not found'))
495
+ .replace(/\{\{EXPO_NAME\}\}/g, escapeHtml(state.expo.name))
496
+ .replace('let STATE = {};', `let STATE = ${payload};`);
497
+ }
498
+
499
+ function openBrowser(url) {
500
+ const command =
501
+ process.platform === 'darwin'
502
+ ? `open "${url}"`
503
+ : process.platform === 'win32'
504
+ ? `start "" "${url}"`
505
+ : `xdg-open "${url}"`;
506
+
507
+ exec(command, (error) => {
508
+ if (error) {
509
+ process.stdout.write(`Open manually: ${url}\n`);
510
+ }
511
+ });
512
+ }
513
+
514
+ function servePng(res, filePath) {
515
+ fs.readFile(filePath, (error, data) => {
516
+ if (error || !data || data.length < PNG_SIGNATURE.length || !data.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)) {
517
+ res.writeHead(404, {
518
+ 'Content-Type': 'text/plain; charset=utf-8',
519
+ 'Cache-Control': 'no-store',
520
+ });
521
+ res.end('Not Found');
522
+ return;
523
+ }
524
+
525
+ res.writeHead(200, {
526
+ 'Content-Type': 'image/png',
527
+ 'Cache-Control': 'no-store',
528
+ });
529
+ res.end(data);
530
+ });
531
+ }
532
+
533
+ function createServer(options) {
534
+ return http.createServer((req, res) => {
535
+ const requestUrl = new URL(req.url, 'http://localhost');
536
+ const state = buildState(options.projectRoot);
537
+
538
+ if (requestUrl.pathname === '/') {
539
+ const html = createHtml(state);
540
+ res.writeHead(200, {
541
+ 'Content-Type': 'text/html; charset=utf-8',
542
+ 'Cache-Control': 'no-store',
543
+ });
544
+ res.end(html);
545
+ return;
546
+ }
547
+
548
+ if (requestUrl.pathname === '/events') {
549
+ res.writeHead(200, {
550
+ 'Content-Type': 'text/event-stream',
551
+ 'Cache-Control': 'no-cache',
552
+ 'Connection': 'keep-alive',
553
+ });
554
+ res.write('\n');
555
+ sseClients.push(res);
556
+
557
+ req.on('close', () => {
558
+ const index = sseClients.indexOf(res);
559
+ if (index !== -1) {
560
+ sseClients.splice(index, 1);
561
+ }
562
+ });
563
+ return;
564
+ }
565
+
566
+ if (requestUrl.pathname === '/bundle.js') {
567
+ const bundlePath = path.join(__dirname, 'dist', 'bundle.js');
568
+ if (fs.existsSync(bundlePath)) {
569
+ res.writeHead(200, {
570
+ 'Content-Type': 'application/javascript; charset=utf-8',
571
+ 'Cache-Control': 'no-store',
572
+ });
573
+ fs.createReadStream(bundlePath).pipe(res);
574
+ return;
575
+ }
576
+ }
577
+
578
+ if (requestUrl.pathname === '/assets/iconpeek.png' || requestUrl.pathname === '/favicon.ico') {
579
+ const filePath = path.join(__dirname, 'assets', 'iconpeek.png');
580
+ if (fs.existsSync(filePath)) {
581
+ res.writeHead(200, {
582
+ 'Content-Type': 'image/png',
583
+ 'Cache-Control': 'public, max-age=86400',
584
+ });
585
+ fs.createReadStream(filePath).pipe(res);
586
+ return;
587
+ }
588
+ }
589
+
590
+ if (requestUrl.pathname.startsWith('/assets/mockups/')) {
591
+ const fileName = path.basename(requestUrl.pathname);
592
+ const filePath = path.join(__dirname, 'assets', 'mockups', fileName);
593
+ if (fs.existsSync(filePath)) {
594
+ res.writeHead(200, {
595
+ 'Content-Type': 'image/webp',
596
+ 'Cache-Control': 'public, max-age=86400',
597
+ });
598
+ fs.createReadStream(filePath).pipe(res);
599
+ return;
600
+ }
601
+ }
602
+
603
+ if (requestUrl.pathname === '/assets/icon') {
604
+ servePng(res, state.assets.icon.path);
605
+ return;
606
+ }
607
+
608
+ if (requestUrl.pathname === '/assets/ios-icon') {
609
+ servePng(res, state.assets.iosIcon.path);
610
+ return;
611
+ }
612
+
613
+ if (requestUrl.pathname === '/assets/splash') {
614
+ servePng(res, state.assets.splash.path);
615
+ return;
616
+ }
617
+
618
+ if (requestUrl.pathname === '/assets/splash-dark') {
619
+ servePng(res, state.assets.splashDark.path);
620
+ return;
621
+ }
622
+
623
+ res.writeHead(404, {
624
+ 'Content-Type': 'text/plain; charset=utf-8',
625
+ 'Cache-Control': 'no-store',
626
+ });
627
+ res.end('Not Found');
628
+ });
629
+ }
630
+
631
+ function startServer(options) {
632
+ const server = createServer(options);
633
+ let currentPort = options.port;
634
+ let browserOpened = false;
635
+
636
+ server.on('error', (error) => {
637
+ if (error && error.code === 'EADDRINUSE') {
638
+ currentPort += 1;
639
+ server.listen(currentPort);
640
+ return;
641
+ }
642
+
643
+ process.stderr.write(`${error.message}\n`);
644
+ process.exit(1);
645
+ });
646
+
647
+ server.on('listening', () => {
648
+ const url = `http://localhost:${currentPort}`;
649
+ process.stdout.write(`iconpeek running at ${url}\n`);
650
+ updateWatchers(options.projectRoot);
651
+ if (options.open && !browserOpened) {
652
+ browserOpened = true;
653
+ openBrowser(url);
654
+ }
655
+ });
656
+
657
+ server.listen(currentPort);
658
+ }
659
+
660
+ try {
661
+ const options = parseArgs(process.argv.slice(2));
662
+ startServer(options);
663
+ } catch (error) {
664
+ process.stderr.write(`${error.message}\n\n`);
665
+ printHelp();
666
+ process.exit(1);
521
667
  }