@pwaos.net/runtime-client-api 0.0.0-stage → 0.2.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/test/test.cjs ADDED
@@ -0,0 +1,747 @@
1
+ /**
2
+ * PwaOS Node.js Addon - Test Suite
3
+ *
4
+ * Two layers:
5
+ * 1. Surface tests - always run when the addon is built. Exercise
6
+ * exported constants, class methods, and the wrapper. No runtime
7
+ * server required.
8
+ * 2. Integration tests - mirror the chromium-pwaos addon flow:
9
+ * setRuntimeExecutablePath -> init -> createInstance -> pollEvent
10
+ * loop until instanceStatusWorking -> createPwa -> exercise App
11
+ * methods -> pollEvent until appStatusStopping -> teardown.
12
+ * Skipped unless PWAOS_RUNTIME_PATH is set (or run via
13
+ * `npm run test:integration`).
14
+ */
15
+
16
+ const assert = require('assert');
17
+
18
+ // ---------------------------------------------------------------------------
19
+ // Direct-run mode: `node test/test.js [options] [url]` runs the standalone
20
+ // CLI demo (open a URL in the runtime browser) instead of the mocha suite.
21
+ // Run under mocha (npm test) for the test suite below.
22
+ // ---------------------------------------------------------------------------
23
+
24
+ const PLATFORM = process.platform === 'win32' ? 'win' : process.platform;
25
+
26
+ const DEFAULTS = {
27
+ addon: require('path').join(
28
+ __dirname, '..', 'build', 'Release', 'pwaos_addon.node'),
29
+ runtime: require('path').join(
30
+ __dirname, '..', '..', 'runtime-linux-x64', 'runtime'),
31
+ url: 'https://www.pwaos.net',
32
+ };
33
+
34
+ const isUrlLike = (s) => /^[a-z][a-z0-9+.-]*:\/\//i.test(s) || /^about:/i.test(s);
35
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
36
+ const log = (msg) => console.log(`[pwaos] ${msg}`);
37
+ const err = (msg) => console.error(`[pwaos] ❌ ${msg}`);
38
+
39
+ function printUsage() {
40
+ console.log(`
41
+ Usage:
42
+ mocha test/test.js # run the test suite (or: npm test)
43
+ node test/test.js [options] [url]
44
+
45
+ Options (demo mode):
46
+ -a, --addon <path> Path to pwaos_addon.node
47
+ (env PWAOS_ADDON_PATH, default "${DEFAULTS.addon}")
48
+ -r, --runtime <path> Path to runtime directory
49
+ (env PWAOS_RUNTIME_EXEC, default "${DEFAULTS.runtime}")
50
+ -u, --url <url> URL to open (env PWAOS_URL)
51
+ -h, --help Show this help
52
+
53
+ Examples:
54
+ npm test
55
+ node test/test.js https://example.com
56
+ node test/test.js -a ./build/Release/pwaos_addon.node -u https://example.com
57
+ `);
58
+ }
59
+
60
+ function parseArgs(argv) {
61
+ const opts = { addon: null, runtime: null, url: null };
62
+ const positional = [];
63
+
64
+ for (let i = 0; i < argv.length; i++) {
65
+ const a = argv[i];
66
+ switch (a) {
67
+ case '-a': case '--addon': opts.addon = argv[++i]; break;
68
+ case '-r': case '--runtime': opts.runtime = argv[++i]; break;
69
+ case '-u': case '--url': opts.url = argv[++i]; break;
70
+ case '-h': case '--help': printUsage(); process.exit(0);
71
+ default: positional.push(a);
72
+ }
73
+ }
74
+
75
+ // Positional args: URL first, then addon / runtime in order.
76
+ for (const p of positional) {
77
+ if (isUrlLike(p)) { if (!opts.url) opts.url = p; }
78
+ else if (!opts.addon) { opts.addon = p; }
79
+ else if (!opts.runtime) { opts.runtime = p; }
80
+ }
81
+
82
+ // Environment variables and defaults.
83
+ opts.addon = opts.addon || process.env.PWAOS_ADDON_PATH || DEFAULTS.addon;
84
+ opts.runtime = opts.runtime || process.env.PWAOS_RUNTIME_EXEC || DEFAULTS.runtime;
85
+ opts.url = opts.url || process.env.PWAOS_URL || DEFAULTS.url;
86
+
87
+ return opts;
88
+ }
89
+
90
+ // The CLI demo: load the addon, init the runtime, open the URL in a
91
+ // browser-type PWA window, pump events until the app stops, shut down.
92
+ async function runDemo() {
93
+ const path = require('path');
94
+ const fs = require('fs');
95
+ const opts = parseArgs(process.argv.slice(2));
96
+
97
+ const addonAbsolute = path.resolve(__dirname, opts.addon);
98
+ const runtimeAbsolute = path.resolve(__dirname, opts.runtime);
99
+
100
+ if (!fs.existsSync(addonAbsolute)) {
101
+ err(`Addon file not found: ${addonAbsolute}`);
102
+ process.exit(1);
103
+ }
104
+ if (!fs.existsSync(runtimeAbsolute)) {
105
+ err(`Runtime directory not found: ${runtimeAbsolute}`);
106
+ process.exit(1);
107
+ }
108
+
109
+ log(`Addon : ${addonAbsolute}`);
110
+ log(`Runtime : ${runtimeAbsolute}`);
111
+ log(`URL : ${opts.url}`);
112
+
113
+ let pwaos;
114
+ try {
115
+ pwaos = require(addonAbsolute);
116
+ } catch (e) {
117
+ err(`Failed to load addon: ${e.message}`);
118
+ process.exit(1);
119
+ }
120
+
121
+ let currentInstance = null;
122
+ let currentApp = null;
123
+ let shuttingDown = false;
124
+
125
+ function shutdown(code = 0) {
126
+ if (shuttingDown) return;
127
+ shuttingDown = true;
128
+ try {
129
+ if (currentApp && currentInstance) {
130
+ currentApp.setCallback(null, null);
131
+ currentInstance.destroyPwa(currentApp);
132
+ }
133
+ currentApp = null;
134
+ if (currentInstance) {
135
+ pwaos.destroyInstance(currentInstance);
136
+ }
137
+ currentInstance = null;
138
+ pwaos.shutDown();
139
+ } catch (e) {
140
+ err(`Error during shutdown: ${e && e.stack ? e.stack : e}`);
141
+ }
142
+ log('Shutdown complete.');
143
+ process.exit(code);
144
+ }
145
+
146
+ process.on('SIGINT', () => { log('SIGINT received.'); shutdown(0); });
147
+ process.on('SIGTERM', () => { log('SIGTERM received.'); shutdown(0); });
148
+
149
+ pwaos.setRuntimeExecutablePath(runtimeAbsolute);
150
+
151
+ try {
152
+ pwaos.init().then(function (result) {
153
+ log(`pwaos_init succeeded. result code = ${result}`);
154
+
155
+ const createInfo = {
156
+ type: pwaos.PWAOS_TYPE_INSTANCE_CREATE_INFO,
157
+ runtimeType: pwaos.runtimeTypePwa,
158
+ serverUrl: 'http://localhost',
159
+ dataPath: '', // empty = default data path
160
+ };
161
+ currentInstance = pwaos.createInstance(createInfo);
162
+
163
+ let bQuit = false;
164
+ // The demo runs until the app stops on its own or the user quits
165
+ // (SIGINT). The timeout is a headless safety net, not an error.
166
+ const demoTimeoutMs = parseInt(process.env.PWAOS_DEMO_TIMEOUT_MS, 10) || 120_000;
167
+ const deadline = Date.now() + demoTimeoutMs;
168
+ (async function pump() {
169
+ while (!bQuit) {
170
+ const ev = currentInstance.pollEvent();
171
+ if (!ev) {
172
+ await sleep(100); // yield the event loop, avoid busy-wait
173
+ if (Date.now() > deadline) {
174
+ log(`demo timeout (${demoTimeoutMs}ms) reached - shutting down`);
175
+ shutdown(0);
176
+ return;
177
+ }
178
+ continue;
179
+ }
180
+
181
+ log(`event: type=${ev.type} status=${ev.status}`);
182
+
183
+ if (ev.type === pwaos.PWAOS_TYPE_EVENT_DATA_INSTANCE_STATUS_CHANGED) {
184
+ if (ev.status === pwaos.Instance.instanceStatusWorking) {
185
+ log(`properties: ${JSON.stringify(currentInstance.getProperties())}`);
186
+ const createPwaInfo = {
187
+ type: pwaos.PWAOS_TYPE_PWA_CREATE_INFO,
188
+ appType: pwaos.App.appTypeBrowser,
189
+ appUrl: opts.url, // the URL from the command line
190
+ width: 800,
191
+ height: 600,
192
+ };
193
+ currentApp = currentInstance.createPwa(createPwaInfo);
194
+ }
195
+ } else if (ev.type === pwaos.PWAOS_TYPE_EVENT_DATA_APP_STATUS_CHANGED) {
196
+ if (ev.status === pwaos.App.appStatusStopping) {
197
+ bQuit = true;
198
+ }
199
+ }
200
+ }
201
+ shutdown(0);
202
+ })();
203
+ });
204
+ } catch (e) {
205
+ err(`pwaos_init failed: ${e && e.stack ? e.stack : e}`);
206
+ shutdown(1);
207
+ }
208
+ }
209
+
210
+ // Mode switch:
211
+ // - mocha (npx mocha test/test.cjs): describe/it globals exist -> the
212
+ // suite below runs (17 tests).
213
+ // - `node --test test/test.cjs`: NODE_TEST_CONTEXT is set but describe/it
214
+ // are undefined at load time -> describe/it/before/after/afterEach are
215
+ // bridged from node:test so the SAME suite registers under both
216
+ // runners (this.timeout is guarded - node:test has no timeout API).
217
+ // - direct `node test/test.cjs [url]`: plain script -> the CLI demo runs.
218
+ // CommonJS files are function-wrapped, so a top-level return legally stops
219
+ // evaluation in demo mode.
220
+ const argv1 = process.argv[1] || '';
221
+ const mochaGlobals = typeof describe === 'function' && typeof it === 'function';
222
+ const nodeTestRunner = process.env.NODE_TEST_CONTEXT !== undefined;
223
+ if (!mochaGlobals && !nodeTestRunner) {
224
+ runDemo(); // wires its own exit paths
225
+ return;
226
+ }
227
+
228
+ if (nodeTestRunner && !mochaGlobals) {
229
+ // `node --test` path: wrap the same checks with node:test's API. The
230
+ // integration flow needs the runtime session; it is guarded the same
231
+ // way as the mocha suite below (skipped when no runtime resolved).
232
+ const {
233
+ describe: ndescribe, it: nit,
234
+ before: nbefore, after: nafter, afterEach: nafterEach,
235
+ } = require('node:test');
236
+ global.describe = ndescribe;
237
+ global.it = nit;
238
+ global.before = nbefore;
239
+ global.after = nafter;
240
+ global.afterEach = nafterEach;
241
+ }
242
+
243
+ let addon;
244
+ let addonBuilt = false;
245
+
246
+ // The package entry point (../runtime.cjs) is REQUIRED here - not the raw
247
+ // addon binary - because it performs the setup contract: dynamic-library
248
+ // search path, addon load, and pwaos_setRuntimeExecutablePath at require
249
+ // time. Its export surface IS the addon (module.exports = addon).
250
+ try {
251
+ addon = require('../runtime.cjs');
252
+ // The setup contract: loading the package must have bound a runtime
253
+ // directory via pwaos_setRuntimeExecutablePath.
254
+ assert.strictEqual(typeof addon.setRuntimeExecutablePath, 'function');
255
+ addonBuilt = true;
256
+ } catch (e) {
257
+ // Addon not built or setup failed - tests will be skipped
258
+ }
259
+
260
+ if (!addonBuilt) {
261
+ console.log('⚠️ Addon not built - tests will be skipped');
262
+ console.log(' Run "npm run build" to enable tests\n');
263
+ } else {
264
+ console.log('✓ Package loaded (module.exports = addon) - running tests\n');
265
+ }
266
+
267
+ // ---------------------------------------------------------------------------
268
+ // 1. Surface tests (no runtime required)
269
+ // ---------------------------------------------------------------------------
270
+
271
+ describe('PwaOS Addon - surface', function() {
272
+ before(function() {
273
+ if (!addonBuilt) this.skip();
274
+ });
275
+
276
+ describe('Constants', function() {
277
+ it('should export runtime types', function() {
278
+ assert.strictEqual(addon.runtimeTypeUnknown, 0);
279
+ assert.strictEqual(addon.runtimeTypePwa, 1);
280
+ });
281
+
282
+ it('should export instance statuses on Instance class', function() {
283
+ assert.strictEqual(addon.Instance.instanceStatusUnavailable, -1);
284
+ assert.strictEqual(addon.Instance.instanceStatusAvailable, 0);
285
+ assert.strictEqual(addon.Instance.instanceStatusWorking, 2);
286
+ });
287
+
288
+ it('should export app types on App class', function() {
289
+ assert.strictEqual(addon.App.appTypeUnknown, 0);
290
+ assert.strictEqual(addon.App.appTypePwa, 1);
291
+ assert.strictEqual(addon.App.appTypeBrowser, 2);
292
+ assert.strictEqual(addon.App.appTypeConsole, 3);
293
+ assert.strictEqual(addon.App.appTypeDesktop, 4);
294
+ });
295
+
296
+ it('should export app statuses on App class', function() {
297
+ assert.strictEqual(addon.App.appStatusInVisible, 0);
298
+ assert.strictEqual(addon.App.appStatusStopping, 1);
299
+ assert.strictEqual(addon.App.appStatusReady, 2);
300
+ assert.strictEqual(addon.App.appStatusSynchronized, 3);
301
+ assert.strictEqual(addon.App.appStatusVisible, 4);
302
+ assert.strictEqual(addon.App.appStatusFocused, 5);
303
+ assert.strictEqual(addon.App.appStatusUnFocused, 6);
304
+ });
305
+
306
+ it('should export result codes', function() {
307
+ assert.strictEqual(addon.PWAOS_RESULT_SUCCESS, 0);
308
+ assert.strictEqual(addon.PWAOS_RESULT_PENDING, 1);
309
+ });
310
+
311
+ it('should export structure types', function() {
312
+ assert.strictEqual(addon.PWAOS_TYPE_UNKNOWN, 0);
313
+ assert.strictEqual(addon.PWAOS_TYPE_INITIALIZE_INFO, 1);
314
+ assert.strictEqual(addon.PWAOS_TYPE_INSTANCE_CREATE_INFO, 2);
315
+ assert.strictEqual(addon.PWAOS_TYPE_INSTANCE_GET_PROPERTIES, 3);
316
+ assert.strictEqual(addon.PWAOS_TYPE_PWA_CREATE_INFO, 4);
317
+ });
318
+
319
+ it('should export event-data structure types', function() {
320
+ assert.ok('PWAOS_TYPE_EVENT_DATA_INSTANCE_STATUS_CHANGED' in addon);
321
+ assert.ok('PWAOS_TYPE_EVENT_DATA_APP_STATUS_CHANGED' in addon);
322
+ assert.ok('PWAOS_TYPE_ASYNC_CALLBACK_INFO' in addon);
323
+ });
324
+ });
325
+
326
+ describe('Native API', function() {
327
+ it('resultToString(0) returns "RESULT_SUCCESS"', function() {
328
+ assert.strictEqual(addon.resultToString(0), 'RESULT_SUCCESS');
329
+ });
330
+
331
+ it('resultToString returns string for error code', function() {
332
+ const s = addon.resultToString(-1);
333
+ assert.strictEqual(typeof s, 'string');
334
+ assert.ok(s.length > 0);
335
+ });
336
+
337
+ it('setRuntimeExecutablePath accepts a path and returns int', function() {
338
+ const r = addon.setRuntimeExecutablePath(require('os').tmpdir());
339
+ assert.strictEqual(typeof r, 'number');
340
+ });
341
+ });
342
+
343
+ describe('Package setup contract', function() {
344
+ it('module.exports IS the addon (no extra surface)', function() {
345
+ const native = require('../build/Release/pwaos_addon.node');
346
+ assert.strictEqual(require('../runtime.cjs'), native);
347
+ // Spot-check the native classes are reachable through the export.
348
+ assert.strictEqual(typeof addon.Instance, 'function');
349
+ assert.strictEqual(typeof addon.App, 'function');
350
+ });
351
+
352
+ it('loading the package set the runtime executable path', function() {
353
+ // runtime.cjs eagerly calls pwaos_setRuntimeExecutablePath with the
354
+ // resolved runtime dir; the SDK tooling convention exposes it as
355
+ // PWAOS_RUNTIME_PATH. Integration tests use the same value.
356
+ const rt = process.env.PWAOS_RUNTIME_PATH;
357
+ assert.ok(rt && rt.length > 0,
358
+ 'PWAOS_RUNTIME_PATH not set by loading the package');
359
+ const {
360
+ resolveRuntimePath,
361
+ } = require('../scripts/runtime-resolver.cjs');
362
+ assert.strictEqual(rt, resolveRuntimePath());
363
+ });
364
+
365
+ it('dynamic-library search path includes the platform lib dir', function() {
366
+ const path = require('path');
367
+ const { getPlatformPackageName } =
368
+ require('../scripts/runtime-resolver.cjs');
369
+ const pkgJson = require.resolve(`${getPlatformPackageName()}/package.json`);
370
+ const libDir = process.platform === 'win32'
371
+ ? path.join(path.dirname(pkgJson), 'lib', 'win')
372
+ : path.join(path.dirname(pkgJson), 'lib', process.platform);
373
+ if (process.platform === 'win32') {
374
+ assert.ok(process.env.PATH.includes(libDir),
375
+ `PATH missing ${libDir}`);
376
+ } else {
377
+ assert.ok((process.env.LD_LIBRARY_PATH || '').includes(libDir),
378
+ `LD_LIBRARY_PATH missing ${libDir}`);
379
+ }
380
+ });
381
+ });
382
+
383
+ describe('Class introspection', function() {
384
+ it('Instance class has expected methods', function() {
385
+ const expected = [
386
+ 'createPwa',
387
+ 'destroyPwa',
388
+ 'createObjectInterface',
389
+ 'destroyObjectInterface',
390
+ 'getProperties',
391
+ 'pollEvent',
392
+ 'setCallback',
393
+ ];
394
+ for (const name of expected) {
395
+ assert.strictEqual(
396
+ typeof addon.Instance.prototype[name],
397
+ 'function',
398
+ `Instance.${name} missing`
399
+ );
400
+ }
401
+ });
402
+
403
+ it('App class has expected methods', function() {
404
+ const expected = [
405
+ 'addJavascriptInterface',
406
+ 'createProjector',
407
+ 'destroyProjector',
408
+ 'getBounds',
409
+ 'executeJavaScript',
410
+ 'getDensity',
411
+ 'getDevToolsUri',
412
+ 'getUserAgent',
413
+ 'handleClick',
414
+ 'handlePointerInput',
415
+ 'removeJavascriptInterface',
416
+ 'setBounds',
417
+ 'setCallback',
418
+ 'setDensity',
419
+ 'setFPS',
420
+ 'setUserAgent',
421
+ ];
422
+ for (const name of expected) {
423
+ assert.strictEqual(
424
+ typeof addon.App.prototype[name],
425
+ 'function',
426
+ `App.${name} missing`
427
+ );
428
+ }
429
+ });
430
+ });
431
+ });
432
+
433
+ // ---------------------------------------------------------------------------
434
+ // 2. Integration tests (require a real pwaos_server runtime)
435
+ //
436
+ // The pwaos runtime enforces process-wide singletons:
437
+ // - ONE instance per process (its IPC channel is named after the pid, so a
438
+ // second createInstance hangs 30s and fails),
439
+ // - init() is one-shot: after shutDown() the runtime cannot re-init in the
440
+ // same process (later calls segfault inside the runtime).
441
+ // Therefore all integration coverage lives in a SINGLE lifecycle test that
442
+ // follows the chromium-pwaos addon flow: setRuntimeExecutablePath -> init ->
443
+ // createInstance -> pollEvent until instanceStatusWorking -> createPwa ->
444
+ // exercise App methods -> pollEvent until appStatusStopping -> teardown.
445
+ // ---------------------------------------------------------------------------
446
+
447
+ const RUNTIME_PATH = process.env.PWAOS_RUNTIME_PATH ||
448
+ require('../scripts/resolve-sdk.cjs').resolve().runtimeDir;
449
+ const POLL_INTERVAL_MS = 100;
450
+ const POLL_TIMEOUT_MS = 30_000;
451
+
452
+ function pollUntil(fn, timeoutMs) {
453
+ return new Promise((resolve, reject) => {
454
+ const start = Date.now();
455
+ const tick = () => {
456
+ let result;
457
+ try {
458
+ result = fn();
459
+ } catch (e) {
460
+ return reject(e);
461
+ }
462
+ if (result.done) return resolve(result.value);
463
+ if (Date.now() - start > timeoutMs) {
464
+ return reject(new Error('pollUntil timed out'));
465
+ }
466
+ setTimeout(tick, POLL_INTERVAL_MS);
467
+ };
468
+ tick();
469
+ });
470
+ }
471
+
472
+ const describeOrSkipIntegration = (addonBuilt && RUNTIME_PATH) ? describe : describe.skip;
473
+
474
+ (describeOrSkipIntegration === describe.skip ? describe.skip : describe)(
475
+ 'PwaOS Addon - integration',
476
+ function() {
477
+ let instance = null;
478
+ let app = null;
479
+ let lifecycleFailed = false;
480
+
481
+ before(function() {
482
+ if (!addonBuilt || !RUNTIME_PATH) this.skip();
483
+ // mocha-specific timeout API; node:test's SuiteContext has no
484
+ // this.timeout - guard so the same file runs under both runners.
485
+ if (typeof this.timeout === 'function') this.timeout(60_000);
486
+ });
487
+
488
+ // The runtime enforces ONE instance per process and init() is
489
+ // one-shot, so the whole describe shares a single runtime session:
490
+ // app/instance are created by the lifecycle test and torn down only
491
+ // in after() - NOT per-test (afterEach destroys would make the
492
+ // follow-up session tests skip and leak the runtime).
493
+ afterEach(function() {
494
+ // Same broken-runtime hazard as after(): native destroy calls can
495
+ // segfault once the runtime has failed, hiding the test's error.
496
+ if (lifecycleFailed) {
497
+ app = null;
498
+ instance = null;
499
+ }
500
+ });
501
+
502
+ after(function() {
503
+ // Tear down the shared session (see afterEach note).
504
+ if (!lifecycleFailed && app) {
505
+ try { app.setCallback(null, null); } catch (_) {}
506
+ try { addon.destroyPwa(app); } catch (_) {}
507
+ app = null;
508
+ }
509
+ if (!lifecycleFailed && instance) {
510
+ try { addon.destroyInstance(instance); } catch (_) {}
511
+ instance = null;
512
+ }
513
+ // If the lifecycle test failed, the runtime is in a broken state
514
+ // and shutDown() can segfault inside the native library - that
515
+ // would swallow the failure details mocha is about to print.
516
+ // Skip the native shutdown on failure; process exit reaps it.
517
+ if (lifecycleFailed) return;
518
+ try { addon.shutDown(); } catch (_) {}
519
+ });
520
+
521
+ // Print a failing step's reason immediately (with the native result
522
+ // code decoded via resultToString and the test.js file:line that made
523
+ // the failing call) BEFORE any teardown runs - the runtime library can
524
+ // segfault during teardown after a failed step, which would otherwise
525
+ // swallow the error message.
526
+ const TEST_FILE = __filename;
527
+ function firstTestFrame(err) {
528
+ // First stack frame inside THIS test file, formatted file:line:col.
529
+ const esc = TEST_FILE.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
530
+ const re = new RegExp(esc + ':(\\d+):(\\d+)');
531
+ const m = (err.stack || '').match(re);
532
+ if (m) return `${TEST_FILE}:${m[1]}:${m[2]}`;
533
+ return null;
534
+ }
535
+ async function step(name, fn) {
536
+ try {
537
+ return await fn();
538
+ } catch (e) {
539
+ lifecycleFailed = true;
540
+ const code = typeof e.pwaosResult === 'number'
541
+ ? ` (pwaosResult ${e.pwaosResult} = ${addon.resultToString(e.pwaosResult)})`
542
+ : '';
543
+ const at = firstTestFrame(e) || firstTestFrame(new Error());
544
+ console.error(`\n ✗ lifecycle step '${name}' failed:${code}` +
545
+ (at ? `\n at ${at}` : '') +
546
+ `\n ${e.message}\n`);
547
+ throw e;
548
+ }
549
+ }
550
+
551
+ it('runs the full instance+pwa lifecycle in a single runtime session',
552
+ async function() {
553
+ if (typeof this.timeout === 'function') this.timeout(60_000);
554
+
555
+ await step('setRuntimeExecutablePath', async () => {
556
+ const pathResult = addon.setRuntimeExecutablePath(RUNTIME_PATH);
557
+ assert.strictEqual(typeof pathResult, 'number',
558
+ `setRuntimeExecutablePath returned ${addon.resultToString(pathResult)}`);
559
+ });
560
+
561
+ await step('init', async () => {
562
+ const initResult = await addon.init();
563
+ assert.strictEqual(typeof initResult, 'number',
564
+ `init returned ${addon.resultToString(initResult)}`);
565
+ });
566
+
567
+ instance = await step('createInstance', async () => {
568
+ const createInfo = {
569
+ type: addon.PWAOS_TYPE_INSTANCE_CREATE_INFO,
570
+ runtimeType: addon.runtimeTypePwa,
571
+ serverUrl: 'http://localhost',
572
+ dataPath: '',
573
+ };
574
+ const inst = addon.createInstance(createInfo);
575
+ assert.ok(inst, 'createInstance should return an Instance');
576
+ return inst;
577
+ });
578
+
579
+ await step('poll instance status', () => pollUntil(() => {
580
+ const ev = instance.pollEvent();
581
+ if (!ev) return { done: false };
582
+ if (ev.type === addon.PWAOS_TYPE_EVENT_DATA_INSTANCE_STATUS_CHANGED
583
+ && ev.status === addon.Instance.instanceStatusWorking) {
584
+ return { done: true, value: ev };
585
+ }
586
+ return { done: false };
587
+ }, POLL_TIMEOUT_MS));
588
+
589
+ const props = await step('getProperties', async () => {
590
+ const p = instance.getProperties();
591
+ assert.ok(p, 'getProperties should return a value');
592
+ assert.strictEqual(typeof p.runtimeVersion, 'string',
593
+ `runtimeVersion should be a string, got ${JSON.stringify(p)}`);
594
+ return p;
595
+ });
596
+ console.log(` runtime version: ${props.runtimeVersion}`);
597
+
598
+ app = await step('createPwa', async () => {
599
+ const createPwaInfo = {
600
+ type: addon.PWAOS_TYPE_PWA_CREATE_INFO,
601
+ appType: addon.App.appTypeConsole,
602
+ appUrl: 'https://example.com',
603
+ width: 800,
604
+ height: 600,
605
+ };
606
+ const a = instance.createPwa(createPwaInfo);
607
+ assert.ok(a, 'createPwa should return an App');
608
+ return a;
609
+ });
610
+
611
+ // This runtime build may never emit appStatusReady: 0.2.a.2
612
+ // jumps straight to appStatusSynchronized. Accept any status
613
+ // >= appStatusSynchronized (enum is monotonic); appStatusReady
614
+ // alone also passes for older runtimes that emit it.
615
+ await step('poll app status', () => pollUntil(() => {
616
+ const ev = instance.pollEvent();
617
+ if (!ev) return { done: false };
618
+ if (ev.type === addon.PWAOS_TYPE_EVENT_DATA_APP_STATUS_CHANGED
619
+ && ev.status >= addon.App.appStatusSynchronized) {
620
+ return { done: true, value: ev };
621
+ }
622
+ return { done: false };
623
+ }, POLL_TIMEOUT_MS));
624
+ await new Promise(r => setTimeout(r, 500));
625
+
626
+ await step('getDensity', async () => {
627
+ const density = app.getDensity();
628
+ assert.strictEqual(typeof density, 'number');
629
+ });
630
+
631
+ await step('getBounds', async () => {
632
+ const bounds = app.getBounds();
633
+ assert.ok(bounds);
634
+ assert.strictEqual(typeof bounds.width, 'number');
635
+ assert.strictEqual(typeof bounds.height, 'number');
636
+ });
637
+
638
+ await step('setFPS', async () => {
639
+ const fpsResult = app.setFPS(60);
640
+ assert.strictEqual(fpsResult, addon.PWAOS_RESULT_SUCCESS,
641
+ `setFPS returned ${addon.resultToString(fpsResult)}`);
642
+ });
643
+
644
+ await step('executeJavaScript', async () => {
645
+ const jsResult = app.executeJavaScript('1+1');
646
+ assert.strictEqual(jsResult, addon.PWAOS_RESULT_SUCCESS,
647
+ `executeJavaScript returned ${addon.resultToString(jsResult)}`);
648
+ });
649
+
650
+ await step('setBounds', async () => {
651
+ const setBoundsResult = app.setBounds({
652
+ type: addon.PWAOS_TYPE_WINDOW_BOUNDS_INFO,
653
+ x: 0, y: 0, width: 400, height: 300,
654
+ });
655
+ assert.strictEqual(setBoundsResult, addon.PWAOS_RESULT_SUCCESS,
656
+ `setBounds returned ${addon.resultToString(setBoundsResult)}`);
657
+ });
658
+
659
+ // Known runtime limitation: UA access returns ERROR_INTERNAL on
660
+ // this build. Assert call completion (a number) without crashing;
661
+ // never assert success.
662
+ await step('setUserAgent', async () => {
663
+ const ua = 'PwaOSAddonTest/0.1.0';
664
+ const uaResult = app.setUserAgent(ua);
665
+ assert.strictEqual(typeof uaResult, 'number',
666
+ `setUserAgent returned ${addon.resultToString(uaResult)}`);
667
+ });
668
+ });
669
+
670
+ // Verifies the runtime actually WORKS end-to-end: the spawned
671
+ // pwaos_server loads a real web page served by this test, executes its
672
+ // JavaScript, and that script fetches a URL back to the test's HTTP
673
+ // server. Reaching the beacon proves the whole chain - renderer up,
674
+ // page loaded, JS executed, network stack live - not just that the
675
+ // API calls return SUCCESS.
676
+ it('runtime loads a real page and its JS calls back over the network',
677
+ async function() {
678
+ if (typeof this.timeout === 'function') this.timeout(30_000);
679
+ if (!addonBuilt || !RUNTIME_PATH) this.skip();
680
+ if (!app) this.skip(); // lifecycle test failed - session unusable
681
+
682
+ const hits = [];
683
+ const server = require('http').createServer((req, res) => {
684
+ hits.push(req.url);
685
+ if (req.url.startsWith('/beacon')) {
686
+ res.writeHead(204);
687
+ return res.end();
688
+ }
689
+ res.writeHead(200, { 'Content-Type': 'text/html' });
690
+ res.end('<!doctype html><html><head><title>pwaos-e2e</title>' +
691
+ '</head><body><script>' +
692
+ 'fetch("/beacon?from=page").catch(function(){});' +
693
+ '</script></body></html>');
694
+ });
695
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
696
+ const port = server.address().port;
697
+ // A NEW app in the SAME session (one instance per process, but
698
+ // many PWA apps are allowed): appTypePwa so the renderer
699
+ // actually loads and runs the page's JavaScript. The lifecycle
700
+ // test's appTypeConsole app does not execute page JS.
701
+ let e2eApp = null;
702
+ try {
703
+ e2eApp = await step('createPwa(e2e page)', async () => {
704
+ const a = instance.createPwa({
705
+ type: addon.PWAOS_TYPE_PWA_CREATE_INFO,
706
+ appType: addon.App.appTypePwa,
707
+ appUrl: `http://127.0.0.1:${port}/`,
708
+ width: 800,
709
+ height: 600,
710
+ });
711
+ assert.ok(a, 'createPwa should return an App');
712
+ return a;
713
+ });
714
+
715
+ await step('beacon round-trip', () => pollUntil(() => {
716
+ if (hits.some((h) => h.startsWith('/beacon'))) {
717
+ return { done: true, value: hits };
718
+ }
719
+ return { done: false };
720
+ }, 15_000));
721
+
722
+ await step('page hit recorded', async () => {
723
+ assert.ok(hits.some((h) => h.startsWith('/beacon')),
724
+ `page JS never reached the test server; requests seen: ` +
725
+ `${hits.join(', ') || '(none)'}`);
726
+ console.log(` e2e requests: ${hits.join(', ')}`);
727
+ });
728
+ } finally {
729
+ if (e2eApp && !lifecycleFailed) {
730
+ try { e2eApp.setCallback(null, null); } catch (_) {}
731
+ try { instance.destroyPwa(e2eApp); } catch (_) {}
732
+ }
733
+ server.close();
734
+ }
735
+ });
736
+
737
+ }
738
+ );
739
+
740
+ // Summary
741
+ if (!addonBuilt) {
742
+ console.log('\n⚠️ NOTE: To run surface tests, build the addon first:');
743
+ console.log(' npm run build\n');
744
+ } else if (!RUNTIME_PATH) {
745
+ console.log('ℹ️ Integration tests skipped (set PWAOS_RUNTIME_PATH to enable).');
746
+ console.log(' Example: PWAOS_RUNTIME_PATH=/path/to/runtime npm run test:integration\n');
747
+ }