zero-query 1.0.9 → 1.1.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,489 @@
1
+ /**
2
+ * Dev server unit tests.
3
+ *
4
+ * Validates the SSEPool class, createServer() factory, middleware wiring,
5
+ * SSE endpoint, keep-alive timeouts, SPA fallback, auto-resolve, and
6
+ * all recent additions (helmet, compress, cors, retry/pad).
7
+ */
8
+
9
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
10
+ import fs from 'fs';
11
+ import path from 'path';
12
+ import os from 'os';
13
+
14
+
15
+ // ---------------------------------------------------------------------------
16
+ // SSEPool tests (pure logic, no server needed)
17
+ // ---------------------------------------------------------------------------
18
+
19
+ describe('SSEPool', () => {
20
+ let SSEPool;
21
+
22
+ beforeEach(async () => {
23
+ vi.resetModules();
24
+ ({ SSEPool } = await import('../cli/commands/dev/server.js'));
25
+ });
26
+
27
+ it('exports SSEPool class', () => {
28
+ expect(SSEPool).toBeTypeOf('function');
29
+ });
30
+
31
+ it('starts with zero clients', () => {
32
+ const pool = new SSEPool();
33
+ expect(pool.size).toBe(0);
34
+ });
35
+
36
+ it('add() stores a client and size reflects count', () => {
37
+ const pool = new SSEPool();
38
+ const sse = { on: vi.fn(), event: vi.fn(), close: vi.fn() };
39
+ pool.add(sse);
40
+ expect(pool.size).toBe(1);
41
+ expect(sse.on).toHaveBeenCalledWith('close', expect.any(Function));
42
+ });
43
+
44
+ it('add() registers close listener that removes client', () => {
45
+ const pool = new SSEPool();
46
+ let closeCb;
47
+ const sse = { on: vi.fn((evt, cb) => { closeCb = cb; }), event: vi.fn(), close: vi.fn() };
48
+ pool.add(sse);
49
+ expect(pool.size).toBe(1);
50
+ closeCb(); // simulate close
51
+ expect(pool.size).toBe(0);
52
+ });
53
+
54
+ it('broadcast() sends event to all clients', () => {
55
+ const pool = new SSEPool();
56
+ const sse1 = { on: vi.fn(), event: vi.fn(), close: vi.fn() };
57
+ const sse2 = { on: vi.fn(), event: vi.fn(), close: vi.fn() };
58
+ pool.add(sse1);
59
+ pool.add(sse2);
60
+ pool.broadcast('reload', 'app.js');
61
+ expect(sse1.event).toHaveBeenCalledWith('reload', 'app.js');
62
+ expect(sse2.event).toHaveBeenCalledWith('reload', 'app.js');
63
+ });
64
+
65
+ it('broadcast() uses empty string when data is falsy', () => {
66
+ const pool = new SSEPool();
67
+ const sse = { on: vi.fn(), event: vi.fn(), close: vi.fn() };
68
+ pool.add(sse);
69
+ pool.broadcast('ping');
70
+ expect(sse.event).toHaveBeenCalledWith('ping', '');
71
+ });
72
+
73
+ it('broadcast() removes clients that throw', () => {
74
+ const pool = new SSEPool();
75
+ const bad = { on: vi.fn(), event: vi.fn(() => { throw new Error('gone'); }), close: vi.fn() };
76
+ const good = { on: vi.fn(), event: vi.fn(), close: vi.fn() };
77
+ pool.add(bad);
78
+ pool.add(good);
79
+ pool.broadcast('reload', '');
80
+ expect(pool.size).toBe(1); // bad removed
81
+ expect(good.event).toHaveBeenCalled();
82
+ });
83
+
84
+ it('closeAll() closes every client and empties the pool', () => {
85
+ const pool = new SSEPool();
86
+ const sse1 = { on: vi.fn(), event: vi.fn(), close: vi.fn() };
87
+ const sse2 = { on: vi.fn(), event: vi.fn(), close: vi.fn() };
88
+ pool.add(sse1);
89
+ pool.add(sse2);
90
+ pool.closeAll();
91
+ expect(pool.size).toBe(0);
92
+ expect(sse1.close).toHaveBeenCalled();
93
+ expect(sse2.close).toHaveBeenCalled();
94
+ });
95
+
96
+ it('closeAll() ignores errors from close()', () => {
97
+ const pool = new SSEPool();
98
+ const sse = { on: vi.fn(), event: vi.fn(), close: vi.fn(() => { throw new Error('boom'); }) };
99
+ pool.add(sse);
100
+ expect(() => pool.closeAll()).not.toThrow();
101
+ expect(pool.size).toBe(0);
102
+ });
103
+
104
+ it('multiple add/remove cycles work correctly', () => {
105
+ const pool = new SSEPool();
106
+ const closers = [];
107
+ for (let i = 0; i < 5; i++) {
108
+ const sse = { on: vi.fn((_, cb) => closers.push(cb)), event: vi.fn(), close: vi.fn() };
109
+ pool.add(sse);
110
+ }
111
+ expect(pool.size).toBe(5);
112
+ closers[0]();
113
+ closers[2]();
114
+ closers[4]();
115
+ expect(pool.size).toBe(2);
116
+ pool.closeAll();
117
+ expect(pool.size).toBe(0);
118
+ });
119
+ });
120
+
121
+
122
+ // ---------------------------------------------------------------------------
123
+ // createServer tests (requires zero-http — integration)
124
+ // ---------------------------------------------------------------------------
125
+
126
+ describe('createServer', () => {
127
+ let createServer, createServerFn;
128
+ let tmpRoot;
129
+
130
+ beforeEach(async () => {
131
+ vi.resetModules();
132
+ const mod = await import('../cli/commands/dev/server.js');
133
+ createServerFn = mod.createServer;
134
+
135
+ tmpRoot = path.join(os.tmpdir(), 'zq-dev-test-' + Date.now() + '-' + Math.random().toString(36).slice(2, 8));
136
+ fs.mkdirSync(tmpRoot, { recursive: true });
137
+ fs.writeFileSync(path.join(tmpRoot, 'index.html'), '<!DOCTYPE html><html><head></head><body><p>Hello</p></body></html>');
138
+ fs.writeFileSync(path.join(tmpRoot, 'style.css'), 'body { margin: 0; }');
139
+ fs.writeFileSync(path.join(tmpRoot, 'app.js'), 'console.log("ok");');
140
+ });
141
+
142
+ afterEach(() => {
143
+ if (tmpRoot && fs.existsSync(tmpRoot)) {
144
+ fs.rmSync(tmpRoot, { recursive: true, force: true });
145
+ }
146
+ });
147
+
148
+ // Check if zero-http is available before running integration tests
149
+ let zeroHttpAvailable = false;
150
+ try { require('zero-http'); zeroHttpAvailable = true; } catch {}
151
+
152
+ it('createServer is exported as a function', () => {
153
+ expect(createServerFn).toBeTypeOf('function');
154
+ });
155
+
156
+ it.skipIf(!zeroHttpAvailable)('returns app, pool, and listen', async () => {
157
+ const result = await createServerFn({ root: tmpRoot, htmlEntry: 'index.html', port: 0, noIntercept: true });
158
+ expect(result).toBeDefined();
159
+ expect(result.app).toBeDefined();
160
+ expect(result.pool).toBeDefined();
161
+ expect(result.listen).toBeTypeOf('function');
162
+ });
163
+
164
+ it.skipIf(!zeroHttpAvailable)('pool is an SSEPool instance with size/broadcast/closeAll', async () => {
165
+ const { pool } = await createServerFn({ root: tmpRoot, htmlEntry: 'index.html', port: 0, noIntercept: true });
166
+ expect(pool.size).toBe(0);
167
+ expect(pool.broadcast).toBeTypeOf('function');
168
+ expect(pool.closeAll).toBeTypeOf('function');
169
+ expect(pool.add).toBeTypeOf('function');
170
+ });
171
+
172
+ it.skipIf(!zeroHttpAvailable)('listen() starts the server and returns the server object', async () => {
173
+ const { listen } = await createServerFn({ root: tmpRoot, htmlEntry: 'index.html', port: 0, noIntercept: true });
174
+ const server = listen(() => {});
175
+ expect(server).toBeDefined();
176
+ expect(server.keepAliveTimeout).toBe(65000);
177
+ expect(server.headersTimeout).toBe(66000);
178
+ server.close();
179
+ });
180
+
181
+ it.skipIf(!zeroHttpAvailable)('app has registered routes for SSE and devtools', async () => {
182
+ const { app } = await createServerFn({ root: tmpRoot, htmlEntry: 'index.html', port: 0, noIntercept: true });
183
+ // The app should be a valid zero-http app with the ability to handle routes
184
+ expect(app).toBeDefined();
185
+ expect(app.listen).toBeTypeOf('function');
186
+ });
187
+ });
188
+
189
+
190
+ // ---------------------------------------------------------------------------
191
+ // Server middleware & route integration (real HTTP requests)
192
+ // ---------------------------------------------------------------------------
193
+
194
+ describe('Dev server HTTP integration', () => {
195
+ let createServerFn;
196
+ let tmpRoot, server, port;
197
+
198
+ let zeroHttpAvailable = false;
199
+ try { require('zero-http'); zeroHttpAvailable = true; } catch {}
200
+
201
+ beforeEach(async () => {
202
+ vi.resetModules();
203
+ const mod = await import('../cli/commands/dev/server.js');
204
+ createServerFn = mod.createServer;
205
+
206
+ tmpRoot = path.join(os.tmpdir(), 'zq-dev-http-' + Date.now() + '-' + Math.random().toString(36).slice(2, 8));
207
+ fs.mkdirSync(tmpRoot, { recursive: true });
208
+ fs.writeFileSync(path.join(tmpRoot, 'index.html'),
209
+ '<!DOCTYPE html><html><head></head><body><p>Hello</p></body></html>');
210
+ fs.writeFileSync(path.join(tmpRoot, 'style.css'), 'body { margin: 0; }');
211
+ fs.writeFileSync(path.join(tmpRoot, 'app.js'), 'console.log("ok");');
212
+ });
213
+
214
+ afterEach(() => {
215
+ if (server) { try { server.close(); } catch {} }
216
+ if (tmpRoot && fs.existsSync(tmpRoot)) {
217
+ fs.rmSync(tmpRoot, { recursive: true, force: true });
218
+ }
219
+ });
220
+
221
+ async function boot() {
222
+ const result = await createServerFn({ root: tmpRoot, htmlEntry: 'index.html', port: 0, noIntercept: true });
223
+ return new Promise((resolve) => {
224
+ server = result.listen(() => {
225
+ port = server.address().port;
226
+ resolve(result);
227
+ });
228
+ });
229
+ }
230
+
231
+ it.skipIf(!zeroHttpAvailable)('serves static CSS files', async () => {
232
+ await boot();
233
+ const res = await fetch(`http://127.0.0.1:${port}/style.css`);
234
+ expect(res.status).toBe(200);
235
+ const text = await res.text();
236
+ expect(text).toContain('margin: 0');
237
+ });
238
+
239
+ it.skipIf(!zeroHttpAvailable)('serves static JS files', async () => {
240
+ await boot();
241
+ const res = await fetch(`http://127.0.0.1:${port}/app.js`);
242
+ expect(res.status).toBe(200);
243
+ const text = await res.text();
244
+ expect(text).toContain('console.log');
245
+ });
246
+
247
+ it.skipIf(!zeroHttpAvailable)('SPA fallback injects overlay script into HTML', async () => {
248
+ await boot();
249
+ const res = await fetch(`http://127.0.0.1:${port}/`);
250
+ expect(res.status).toBe(200);
251
+ const text = await res.text();
252
+ // Original content preserved
253
+ expect(text).toContain('<p>Hello</p>');
254
+ // Overlay script injected before </body>
255
+ expect(text).toContain('__zq_error_overlay');
256
+ });
257
+
258
+ it.skipIf(!zeroHttpAvailable)('SPA fallback works for non-existent routes', async () => {
259
+ await boot();
260
+ const res = await fetch(`http://127.0.0.1:${port}/about`);
261
+ expect(res.status).toBe(200);
262
+ const text = await res.text();
263
+ expect(text).toContain('<p>Hello</p>');
264
+ });
265
+
266
+ it.skipIf(!zeroHttpAvailable)('returns 404 for missing non-HTML file extensions', async () => {
267
+ await boot();
268
+ const res = await fetch(`http://127.0.0.1:${port}/missing.png`);
269
+ expect(res.status).toBe(404);
270
+ });
271
+
272
+ it.skipIf(!zeroHttpAvailable)('devtools endpoint returns HTML', async () => {
273
+ await boot();
274
+ const res = await fetch(`http://127.0.0.1:${port}/_devtools`);
275
+ expect(res.status).toBe(200);
276
+ const ct = res.headers.get('content-type');
277
+ expect(ct).toContain('text/html');
278
+ const text = await res.text();
279
+ expect(text).toContain('<!DOCTYPE html');
280
+ });
281
+
282
+ // --- Helmet (security headers) ---
283
+
284
+ it.skipIf(!zeroHttpAvailable)('helmet sets Content-Security-Policy header', async () => {
285
+ await boot();
286
+ const res = await fetch(`http://127.0.0.1:${port}/`);
287
+ const csp = res.headers.get('content-security-policy');
288
+ expect(csp).toBeDefined();
289
+ expect(csp).toContain("'self'");
290
+ expect(csp).toContain("'unsafe-inline'");
291
+ expect(csp).toContain("'unsafe-eval'");
292
+ });
293
+
294
+ it.skipIf(!zeroHttpAvailable)('helmet sets X-Content-Type-Options header', async () => {
295
+ await boot();
296
+ const res = await fetch(`http://127.0.0.1:${port}/`);
297
+ const xcto = res.headers.get('x-content-type-options');
298
+ expect(xcto).toBe('nosniff');
299
+ });
300
+
301
+ it.skipIf(!zeroHttpAvailable)('helmet does NOT set Strict-Transport-Security (dev)', async () => {
302
+ await boot();
303
+ const res = await fetch(`http://127.0.0.1:${port}/`);
304
+ const hsts = res.headers.get('strict-transport-security');
305
+ expect(hsts).toBeNull();
306
+ });
307
+
308
+ it.skipIf(!zeroHttpAvailable)('helmet does NOT set X-Frame-Options (dev allows framing)', async () => {
309
+ await boot();
310
+ const res = await fetch(`http://127.0.0.1:${port}/`);
311
+ const xfo = res.headers.get('x-frame-options');
312
+ expect(xfo).toBeNull();
313
+ });
314
+
315
+ // --- CORS ---
316
+
317
+ it.skipIf(!zeroHttpAvailable)('CORS allows cross-origin requests', async () => {
318
+ await boot();
319
+ const res = await fetch(`http://127.0.0.1:${port}/style.css`, {
320
+ headers: { 'Origin': 'http://localhost:8080' },
321
+ });
322
+ const acao = res.headers.get('access-control-allow-origin');
323
+ expect(acao).toBeDefined();
324
+ });
325
+
326
+ // --- SSE endpoint ---
327
+
328
+ it.skipIf(!zeroHttpAvailable)('SSE endpoint responds with event stream', async () => {
329
+ const { pool } = await boot();
330
+ const controller = new AbortController();
331
+ const res = await fetch(`http://127.0.0.1:${port}/__zq_reload`, {
332
+ signal: controller.signal,
333
+ headers: { 'Accept': 'text/event-stream' },
334
+ });
335
+ expect(res.status).toBe(200);
336
+ const ct = res.headers.get('content-type');
337
+ expect(ct).toContain('text/event-stream');
338
+ // The pool should have one client now
339
+ expect(pool.size).toBe(1);
340
+ controller.abort();
341
+ // Give the abort a moment to process
342
+ await new Promise(r => setTimeout(r, 50));
343
+ });
344
+
345
+ // --- Compression ---
346
+
347
+ it.skipIf(!zeroHttpAvailable)('compress middleware sets content-encoding for large responses', async () => {
348
+ // Create a file larger than 1024 bytes (the threshold)
349
+ const largeContent = 'body { ' + 'color: red; '.repeat(200) + '}';
350
+ fs.writeFileSync(path.join(tmpRoot, 'large.css'), largeContent);
351
+ await boot();
352
+ const res = await fetch(`http://127.0.0.1:${port}/large.css`, {
353
+ headers: { 'Accept-Encoding': 'gzip, deflate, br' },
354
+ });
355
+ expect(res.status).toBe(200);
356
+ // The response should be compressed — check encoding header
357
+ const enc = res.headers.get('content-encoding');
358
+ // Accept either br, gzip, or deflate depending on what zero-http negotiates
359
+ expect(['br', 'gzip', 'deflate']).toContain(enc);
360
+ });
361
+
362
+ it.skipIf(!zeroHttpAvailable)('compress middleware is active on static files', async () => {
363
+ await boot();
364
+ const res = await fetch(`http://127.0.0.1:${port}/style.css`, {
365
+ headers: { 'Accept-Encoding': 'gzip, deflate, br' },
366
+ });
367
+ expect(res.status).toBe(200);
368
+ // Compression is applied — exact encoding depends on zero-http negotiation
369
+ const text = await res.text();
370
+ expect(text).toContain('margin: 0');
371
+ });
372
+
373
+ // --- Keep-alive ---
374
+
375
+ it.skipIf(!zeroHttpAvailable)('server has correct keep-alive and headers timeouts', async () => {
376
+ await boot();
377
+ expect(server.keepAliveTimeout).toBe(65000);
378
+ expect(server.headersTimeout).toBe(66000);
379
+ });
380
+
381
+ // --- Missing htmlEntry ---
382
+
383
+ it.skipIf(!zeroHttpAvailable)('returns 404 when htmlEntry is missing', async () => {
384
+ // Remove the index.html to simulate a missing entry
385
+ fs.unlinkSync(path.join(tmpRoot, 'index.html'));
386
+ await boot();
387
+ const res = await fetch(`http://127.0.0.1:${port}/`);
388
+ expect(res.status).toBe(404);
389
+ const text = await res.text();
390
+ expect(text).toContain('index.html not found');
391
+ });
392
+
393
+ // --- HTML without </body> ---
394
+
395
+ it.skipIf(!zeroHttpAvailable)('injects overlay even when </body> tag is missing', async () => {
396
+ fs.writeFileSync(path.join(tmpRoot, 'index.html'), '<html><head></head><p>No body tag</p></html>');
397
+ await boot();
398
+ const res = await fetch(`http://127.0.0.1:${port}/`);
399
+ const text = await res.text();
400
+ expect(text).toContain('No body tag');
401
+ expect(text).toContain('__zq_error_overlay');
402
+ });
403
+ });
404
+
405
+
406
+ // ---------------------------------------------------------------------------
407
+ // Watcher helpers (pure functions)
408
+ // ---------------------------------------------------------------------------
409
+
410
+ describe('Watcher helpers', () => {
411
+ it('validator module exports validateJS function', async () => {
412
+ vi.resetModules();
413
+ const mod = await import('../cli/commands/dev/validator.js');
414
+ expect(mod.validateJS).toBeTypeOf('function');
415
+ });
416
+
417
+ it('validateJS returns null for valid JS', async () => {
418
+ vi.resetModules();
419
+ const { validateJS } = await import('../cli/commands/dev/validator.js');
420
+ const tmpFile = path.join(os.tmpdir(), 'zq-valid-' + Date.now() + '.js');
421
+ fs.writeFileSync(tmpFile, 'const x = 1;\nfunction foo() { return x; }');
422
+ const result = validateJS(tmpFile, 'test.js');
423
+ expect(result).toBeNull();
424
+ fs.unlinkSync(tmpFile);
425
+ });
426
+
427
+ it('validateJS returns error object for invalid JS', async () => {
428
+ vi.resetModules();
429
+ const { validateJS } = await import('../cli/commands/dev/validator.js');
430
+ const tmpFile = path.join(os.tmpdir(), 'zq-invalid-' + Date.now() + '.js');
431
+ fs.writeFileSync(tmpFile, 'const x = {;\n');
432
+ const result = validateJS(tmpFile, 'test.js');
433
+ expect(result).not.toBeNull();
434
+ expect(result.file).toBe('test.js');
435
+ fs.unlinkSync(tmpFile);
436
+ });
437
+
438
+ it('overlay module exports a string', async () => {
439
+ vi.resetModules();
440
+ const mod = await import('../cli/commands/dev/overlay.js');
441
+ const overlay = mod.default || mod;
442
+ expect(typeof overlay).toBe('string');
443
+ expect(overlay.length).toBeGreaterThan(100);
444
+ });
445
+
446
+ it('devtools module exports HTML string', async () => {
447
+ vi.resetModules();
448
+ const mod = await import('../cli/commands/dev/devtools/index.js');
449
+ const html = mod.default || mod;
450
+ expect(typeof html).toBe('string');
451
+ expect(html).toContain('<!DOCTYPE html');
452
+ });
453
+
454
+ it('logger exports printBanner, logCSS, logReload, logError', async () => {
455
+ vi.resetModules();
456
+ const mod = await import('../cli/commands/dev/logger.js');
457
+ expect(mod.printBanner).toBeTypeOf('function');
458
+ expect(mod.logCSS).toBeTypeOf('function');
459
+ expect(mod.logReload).toBeTypeOf('function');
460
+ expect(mod.logError).toBeTypeOf('function');
461
+ });
462
+ });
463
+
464
+
465
+ // ---------------------------------------------------------------------------
466
+ // promptInstall (unit - does not call real readline in test)
467
+ // ---------------------------------------------------------------------------
468
+
469
+ describe('Server module exports', () => {
470
+ it('exports createServer and SSEPool', async () => {
471
+ vi.resetModules();
472
+ const mod = await import('../cli/commands/dev/server.js');
473
+ expect(mod.createServer).toBeTypeOf('function');
474
+ expect(mod.SSEPool).toBeTypeOf('function');
475
+ });
476
+
477
+ it('dev/index.js exports devServer function', async () => {
478
+ vi.resetModules();
479
+ const mod = await import('../cli/commands/dev/index.js');
480
+ const fn = mod.default || mod;
481
+ expect(fn).toBeTypeOf('function');
482
+ });
483
+
484
+ it('watcher exports startWatcher', async () => {
485
+ vi.resetModules();
486
+ const mod = await import('../cli/commands/dev/watcher.js');
487
+ expect(mod.startWatcher).toBeTypeOf('function');
488
+ });
489
+ });