@tvlabs/wdio-service 0.1.1 → 0.1.3

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.
Files changed (46) hide show
  1. package/README.md +3 -3
  2. package/{dist → cjs}/channel.d.ts +5 -3
  3. package/cjs/channel.d.ts.map +1 -0
  4. package/cjs/channel.js +184 -0
  5. package/cjs/index.d.ts +5 -0
  6. package/{dist → cjs}/index.d.ts.map +1 -1
  7. package/cjs/index.js +21 -0
  8. package/cjs/logger.d.ts +14 -0
  9. package/cjs/logger.d.ts.map +1 -0
  10. package/cjs/logger.js +57 -0
  11. package/cjs/package.json +1 -0
  12. package/{dist → cjs}/service.d.ts +2 -0
  13. package/cjs/service.d.ts.map +1 -0
  14. package/cjs/service.js +79 -0
  15. package/{dist → cjs}/types.d.ts +1 -0
  16. package/cjs/types.d.ts.map +1 -0
  17. package/cjs/types.js +2 -0
  18. package/esm/channel.d.ts +27 -0
  19. package/esm/channel.d.ts.map +1 -0
  20. package/{dist → esm}/channel.js +27 -24
  21. package/esm/index.d.ts +5 -0
  22. package/esm/index.d.ts.map +1 -0
  23. package/{dist → esm}/index.js +1 -0
  24. package/esm/logger.d.ts +14 -0
  25. package/esm/logger.d.ts.map +1 -0
  26. package/esm/logger.js +53 -0
  27. package/esm/package.json +1 -0
  28. package/esm/service.d.ts +20 -0
  29. package/esm/service.d.ts.map +1 -0
  30. package/{dist → esm}/service.js +9 -5
  31. package/esm/types.d.ts +37 -0
  32. package/esm/types.d.ts.map +1 -0
  33. package/package.json +16 -16
  34. package/src/channel.ts +267 -0
  35. package/{dist/index.d.ts → src/index.ts} +2 -1
  36. package/src/logger.ts +66 -0
  37. package/src/phoenix.d.ts +18 -0
  38. package/src/service.ts +127 -0
  39. package/src/types.ts +46 -0
  40. package/dist/channel.d.ts.map +0 -1
  41. package/dist/logger.d.ts +0 -3
  42. package/dist/logger.d.ts.map +0 -1
  43. package/dist/logger.js +0 -2
  44. package/dist/service.d.ts.map +0 -1
  45. package/dist/types.d.ts.map +0 -1
  46. /package/{dist → esm}/types.js +0 -0
@@ -0,0 +1,14 @@
1
+ import type { LogLevel } from './types.js';
2
+ export declare class Logger {
3
+ private name;
4
+ private logLevel;
5
+ constructor(name: string, logLevel?: LogLevel);
6
+ private shouldLog;
7
+ private formatMessage;
8
+ debug(...args: unknown[]): void;
9
+ info(...args: unknown[]): void;
10
+ warn(...args: unknown[]): void;
11
+ error(...args: unknown[]): void;
12
+ trace(...args: unknown[]): void;
13
+ }
14
+ //# sourceMappingURL=logger.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAc3C,qBAAa,MAAM;IAEf,OAAO,CAAC,IAAI;IACZ,OAAO,CAAC,QAAQ;gBADR,IAAI,EAAE,MAAM,EACZ,QAAQ,GAAE,QAAiB;IAGrC,OAAO,CAAC,SAAS;IAOjB,OAAO,CAAC,aAAa;IASrB,KAAK,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI;IAM/B,IAAI,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI;IAM9B,IAAI,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI;IAM9B,KAAK,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI;IAM/B,KAAK,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI;CAKhC"}
package/esm/logger.js ADDED
@@ -0,0 +1,53 @@
1
+ const LOG_LEVELS = {
2
+ error: 0,
3
+ warn: 1,
4
+ info: 2,
5
+ debug: 3,
6
+ trace: 4,
7
+ silent: 5,
8
+ };
9
+ export class Logger {
10
+ name;
11
+ logLevel;
12
+ constructor(name, logLevel = 'info') {
13
+ this.name = name;
14
+ this.logLevel = logLevel;
15
+ }
16
+ shouldLog(level) {
17
+ if (this.logLevel === 'silent') {
18
+ return false;
19
+ }
20
+ return LOG_LEVELS[level] <= LOG_LEVELS[this.logLevel];
21
+ }
22
+ formatMessage(level, ...args) {
23
+ const timestamp = new Date().toISOString();
24
+ return `${timestamp} ${level.toUpperCase()} ${this.name}: ${args
25
+ .map((arg) => typeof arg === 'object' ? JSON.stringify(arg) : String(arg))
26
+ .join(' ')}`;
27
+ }
28
+ debug(...args) {
29
+ if (this.shouldLog('debug')) {
30
+ console.log(this.formatMessage('debug', ...args));
31
+ }
32
+ }
33
+ info(...args) {
34
+ if (this.shouldLog('info')) {
35
+ console.log(this.formatMessage('info', ...args));
36
+ }
37
+ }
38
+ warn(...args) {
39
+ if (this.shouldLog('warn')) {
40
+ console.warn(this.formatMessage('warn', ...args));
41
+ }
42
+ }
43
+ error(...args) {
44
+ if (this.shouldLog('error')) {
45
+ console.error(this.formatMessage('error', ...args));
46
+ }
47
+ }
48
+ trace(...args) {
49
+ if (this.shouldLog('trace')) {
50
+ console.trace(this.formatMessage('trace', ...args));
51
+ }
52
+ }
53
+ }
@@ -0,0 +1 @@
1
+ {"type": "module"}
@@ -0,0 +1,20 @@
1
+ import type { Services, Capabilities, Options } from '@wdio/types';
2
+ import type { TVLabsCapabilities, TVLabsServiceOptions } from './types.js';
3
+ export default class TVLabsService implements Services.ServiceInstance {
4
+ private _options;
5
+ private _capabilities;
6
+ private _config;
7
+ private log;
8
+ constructor(_options: TVLabsServiceOptions, _capabilities: Capabilities.ResolvedTestrunnerCapabilities, _config: Options.WebdriverIO);
9
+ onPrepare(_config: Options.Testrunner, param: Capabilities.TestrunnerCapabilities): void;
10
+ beforeSession(_config: Omit<Options.Testrunner, 'capabilities'>, capabilities: TVLabsCapabilities, _specs: string[], _cid: string): Promise<void>;
11
+ private setupRequestId;
12
+ private setRequestHeader;
13
+ private endpoint;
14
+ private retries;
15
+ private apiKey;
16
+ private logLevel;
17
+ private attachRequestId;
18
+ private reconnectRetries;
19
+ }
20
+ //# sourceMappingURL=service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../src/service.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,QAAQ,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACnE,OAAO,KAAK,EACV,kBAAkB,EAClB,oBAAoB,EAErB,MAAM,YAAY,CAAC;AAEpB,MAAM,CAAC,OAAO,OAAO,aAAc,YAAW,QAAQ,CAAC,eAAe;IAIlE,OAAO,CAAC,QAAQ;IAChB,OAAO,CAAC,aAAa;IACrB,OAAO,CAAC,OAAO;IALjB,OAAO,CAAC,GAAG,CAAS;gBAGV,QAAQ,EAAE,oBAAoB,EAC9B,aAAa,EAAE,YAAY,CAAC,8BAA8B,EAC1D,OAAO,EAAE,OAAO,CAAC,WAAW;IAQtC,SAAS,CACP,OAAO,EAAE,OAAO,CAAC,UAAU,EAC3B,KAAK,EAAE,YAAY,CAAC,sBAAsB;IAStC,aAAa,CACjB,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,cAAc,CAAC,EACjD,YAAY,EAAE,kBAAkB,EAChC,MAAM,EAAE,MAAM,EAAE,EAChB,IAAI,EAAE,MAAM;IAmBd,OAAO,CAAC,cAAc;IA0BtB,OAAO,CAAC,gBAAgB;IAgBxB,OAAO,CAAC,QAAQ;IAIhB,OAAO,CAAC,OAAO;IAIf,OAAO,CAAC,MAAM;IAId,OAAO,CAAC,QAAQ;IAIhB,OAAO,CAAC,eAAe;IAIvB,OAAO,CAAC,gBAAgB;CAGzB"}
@@ -1,16 +1,17 @@
1
1
  import { SevereServiceError } from 'webdriverio';
2
- import crypto from 'crypto';
3
- import chalk from 'chalk';
2
+ import * as crypto from 'crypto';
4
3
  import { TVLabsChannel } from './channel.js';
5
- import { log } from './logger.js';
4
+ import { Logger } from './logger.js';
6
5
  export default class TVLabsService {
7
6
  _options;
8
7
  _capabilities;
9
8
  _config;
9
+ log;
10
10
  constructor(_options, _capabilities, _config) {
11
11
  this._options = _options;
12
12
  this._capabilities = _capabilities;
13
13
  this._config = _config;
14
+ this.log = new Logger('@tvlabs/wdio-server', this._config.logLevel);
14
15
  if (this.attachRequestId()) {
15
16
  this.setupRequestId();
16
17
  }
@@ -21,7 +22,7 @@ export default class TVLabsService {
21
22
  }
22
23
  }
23
24
  async beforeSession(_config, capabilities, _specs, _cid) {
24
- const channel = new TVLabsChannel(this.endpoint(), this.reconnectRetries(), this.apiKey());
25
+ const channel = new TVLabsChannel(this.endpoint(), this.reconnectRetries(), this.apiKey(), this.logLevel());
25
26
  await channel.connect();
26
27
  capabilities['tvlabs:session_id'] = await channel.newSession(capabilities, this.retries());
27
28
  await channel.disconnect();
@@ -37,7 +38,7 @@ export default class TVLabsService {
37
38
  originalRequestOptions.headers = {};
38
39
  }
39
40
  this.setRequestHeader(originalRequestOptions.headers, 'x-request-id', requestId);
40
- log.info(chalk.blue('ATTACHED REQUEST ID'), requestId);
41
+ this.log.info('ATTACHED REQUEST ID', requestId);
41
42
  return originalRequestOptions;
42
43
  };
43
44
  }
@@ -63,6 +64,9 @@ export default class TVLabsService {
63
64
  apiKey() {
64
65
  return this._options.apiKey;
65
66
  }
67
+ logLevel() {
68
+ return this._config.logLevel ?? 'info';
69
+ }
66
70
  attachRequestId() {
67
71
  return this._options.attachRequestId ?? true;
68
72
  }
package/esm/types.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ import type { Capabilities } from '@wdio/types';
2
+ export type LogLevel = 'error' | 'warn' | 'info' | 'debug' | 'trace' | 'silent';
3
+ export type TVLabsServiceOptions = {
4
+ apiKey: string;
5
+ endpoint?: string;
6
+ retries?: number;
7
+ reconnectRetries?: number;
8
+ attachRequestId?: boolean;
9
+ };
10
+ export type TVLabsCapabilities = Capabilities.RequestedStandaloneCapabilities & {
11
+ 'tvlabs:session_id'?: string;
12
+ 'tvlabs:build'?: string;
13
+ 'tvlabs:constraints'?: {
14
+ platform_key?: string;
15
+ device_type?: string;
16
+ make?: string;
17
+ model?: string;
18
+ year?: string;
19
+ minimum_chromedriver_major_version?: number;
20
+ supports_chromedriver?: boolean;
21
+ };
22
+ 'tvlabs:match_timeout'?: number;
23
+ 'tvlabs:device_timeout'?: number;
24
+ };
25
+ export type TVLabsSessionRequestEventHandler = (response: TVLabsSessionRequestUpdate) => void;
26
+ export type TVLabsSessionRequestUpdate = {
27
+ request_id: string;
28
+ session_id: string;
29
+ reason: string;
30
+ };
31
+ export type TVLabsSessionRequestResponse = {
32
+ request_id: string;
33
+ };
34
+ export type TVLabsSessionChannelParams = {
35
+ api_key: string;
36
+ };
37
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD,MAAM,MAAM,QAAQ,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,OAAO,GAAG,QAAQ,CAAC;AAEhF,MAAM,MAAM,oBAAoB,GAAG;IACjC,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAC5B,YAAY,CAAC,+BAA+B,GAAG;IAC7C,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,oBAAoB,CAAC,EAAE;QACrB,YAAY,CAAC,EAAE,MAAM,CAAC;QACtB,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,kCAAkC,CAAC,EAAE,MAAM,CAAC;QAC5C,qBAAqB,CAAC,EAAE,OAAO,CAAC;KACjC,CAAC;IACF,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,uBAAuB,CAAC,EAAE,MAAM,CAAC;CAClC,CAAC;AAEJ,MAAM,MAAM,gCAAgC,GAAG,CAC7C,QAAQ,EAAE,0BAA0B,KACjC,IAAI,CAAC;AAEV,MAAM,MAAM,0BAA0B,GAAG;IACvC,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF,MAAM,MAAM,4BAA4B,GAAG;IACzC,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,MAAM,MAAM,0BAA0B,GAAG;IACvC,OAAO,EAAE,MAAM,CAAC;CACjB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tvlabs/wdio-service",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "WebdriverIO service that provides a better integration into TV Labs",
5
5
  "author": "Regan Karlewicz <regan@tvlabs.ai>",
6
6
  "license": "Apache-2.0",
@@ -22,47 +22,47 @@
22
22
  "url": "https://github.com/tv-labs/wdio-tvlabs-service/issues"
23
23
  },
24
24
  "scripts": {
25
- "build": "tsc -p src",
25
+ "build": "npm run build:cjs && npm run build:esm",
26
+ "build:cjs": "tsc -p src --module commonjs --moduleResolution node --outDir cjs && echo '{\"type\": \"commonjs\"}' > cjs/package.json",
27
+ "build:esm": "tsc -p src --outDir esm && echo '{\"type\": \"module\"}' > esm/package.json",
26
28
  "start": "ts-node src/index.ts",
27
29
  "dev": "ts-node --transpile-only src/index.ts",
28
- "clean": "rm -rf dist",
30
+ "clean": "rm -rf cjs && rm -rf esm",
29
31
  "format": "prettier --write .",
30
32
  "format:check": "prettier --check .",
31
33
  "lint": "eslint",
32
- "test": "vitest --config vitest.config.ts --coverage"
34
+ "test": "vitest --config vitest.config.ts --coverage",
35
+ "publish:dry": "npm publish --access public --provenance --dry-run"
33
36
  },
34
37
  "type": "module",
35
- "types": "./dist/index.d.ts",
38
+ "types": "./esm/index.d.ts",
36
39
  "exports": {
37
- ".": {
38
- "types": "./dist/index.d.ts",
39
- "import": "./dist/index.js"
40
- }
40
+ "require": "./cjs/index.js",
41
+ "import": "./esm/index.js"
41
42
  },
43
+ "main": "cjs/index.js",
42
44
  "typeScriptVersion": "5.8.2",
43
45
  "devDependencies": {
44
46
  "@eslint/js": "^9.22.0",
45
47
  "@types/node": "^22.13.10",
46
48
  "@types/phoenix": "^1.6.6",
47
49
  "@types/ws": "^8.18.0",
48
- "@typescript-eslint/eslint-plugin": "^8.27.0",
49
- "@typescript-eslint/parser": "^8.27.0",
50
+ "@typescript-eslint/eslint-plugin": "^8.36.0",
51
+ "@typescript-eslint/parser": "^8.36.0",
50
52
  "@vitest/coverage-v8": "^3.0.9",
51
53
  "@wdio/globals": "^9.12.1",
52
- "@wdio/logger": "^9.4.4",
53
54
  "@wdio/types": "^9.10.1",
54
- "eslint": "^9.22.0",
55
+ "eslint": "^9.30.1",
55
56
  "globals": "^16.0.0",
56
57
  "jiti": "^2.4.2",
57
58
  "prettier": "^3.5.3",
58
59
  "typescript": "^5.8.2",
59
- "typescript-eslint": "^8.27.0",
60
+ "typescript-eslint": "^8.36.0",
60
61
  "vitest": "^3.0.9",
61
62
  "webdriverio": "^9.12.1"
62
63
  },
63
64
  "dependencies": {
64
- "chalk": "^5.1.2",
65
65
  "phoenix": "^1.7.20",
66
- "ws": "^8.18.1"
66
+ "ws": "^8.18.3"
67
67
  }
68
68
  }
package/src/channel.ts ADDED
@@ -0,0 +1,267 @@
1
+ import { WebSocket } from 'ws';
2
+ import { Socket, type Channel } from 'phoenix';
3
+ import { SevereServiceError } from 'webdriverio';
4
+ import { Logger } from './logger.js';
5
+
6
+ import type {
7
+ TVLabsCapabilities,
8
+ TVLabsSessionChannelParams,
9
+ TVLabsSessionRequestEventHandler,
10
+ TVLabsSessionRequestResponse,
11
+ LogLevel,
12
+ } from './types.js';
13
+ import type { PhoenixChannelJoinResponse } from './phoenix.js';
14
+
15
+ export class TVLabsChannel {
16
+ private socket: Socket;
17
+ private lobbyTopic: Channel;
18
+ private requestTopic?: Channel;
19
+ private log: Logger;
20
+
21
+ private readonly events = {
22
+ SESSION_READY: 'session:ready',
23
+ SESSION_FAILED: 'session:failed',
24
+ REQUEST_CANCELED: 'request:canceled',
25
+ REQUEST_FAILED: 'request:failed',
26
+ REQUEST_FILLED: 'request:filled',
27
+ REQUEST_MATCHING: 'request:matching',
28
+ } as const;
29
+
30
+ constructor(
31
+ private endpoint: string,
32
+ private maxReconnectRetries: number,
33
+ private key: string,
34
+ private logLevel: LogLevel,
35
+ ) {
36
+ this.log = new Logger('@tvlabs/wdio-channel', this.logLevel);
37
+ this.socket = new Socket(this.endpoint, {
38
+ transport: WebSocket,
39
+ params: this.params(),
40
+ reconnectAfterMs: this.reconnectAfterMs.bind(this),
41
+ });
42
+
43
+ this.socket.onError((...args) =>
44
+ TVLabsChannel.logSocketError(this.log, ...args),
45
+ );
46
+
47
+ this.lobbyTopic = this.socket.channel('requests:lobby');
48
+ }
49
+
50
+ async disconnect(): Promise<void> {
51
+ return new Promise((res, _rej) => {
52
+ this.lobbyTopic.leave();
53
+ this.requestTopic?.leave();
54
+ this.socket.disconnect(() => res());
55
+ });
56
+ }
57
+
58
+ async connect(): Promise<void> {
59
+ try {
60
+ this.log.debug('Connecting to TV Labs...');
61
+
62
+ this.socket.connect();
63
+
64
+ await this.join(this.lobbyTopic);
65
+
66
+ this.log.debug('Connected to TV Labs!');
67
+ } catch (error) {
68
+ this.log.error('Error connecting to TV Labs:', error);
69
+ throw new SevereServiceError(
70
+ 'Could not connect to TV Labs, please check your connection.',
71
+ );
72
+ }
73
+ }
74
+
75
+ async newSession(
76
+ capabilities: TVLabsCapabilities,
77
+ maxRetries: number,
78
+ retry = 0,
79
+ ): Promise<string> {
80
+ try {
81
+ const requestId = await this.requestSession(capabilities);
82
+ const sessionId = await this.observeRequest(requestId);
83
+
84
+ return sessionId;
85
+ } catch {
86
+ return this.handleRetry(capabilities, maxRetries, retry);
87
+ }
88
+ }
89
+
90
+ private async handleRetry(
91
+ capabilities: TVLabsCapabilities,
92
+ maxRetries: number,
93
+ retry: number,
94
+ ): Promise<string> {
95
+ if (retry < maxRetries) {
96
+ this.log.warn(
97
+ `Could not create a session, retrying (${retry + 1}/${maxRetries})`,
98
+ );
99
+
100
+ return this.newSession(capabilities, maxRetries, retry + 1);
101
+ } else {
102
+ throw new SevereServiceError(
103
+ `Could not create a session after ${maxRetries} attempts.`,
104
+ );
105
+ }
106
+ }
107
+
108
+ private async observeRequest(requestId: string): Promise<string> {
109
+ const cleanup = () => this.unobserveRequest();
110
+
111
+ return new Promise<string>((res, rej) => {
112
+ this.requestTopic = this.socket.channel(`requests:${requestId}`);
113
+
114
+ const eventHandlers: Record<string, TVLabsSessionRequestEventHandler> = {
115
+ // Information events
116
+ [this.events.REQUEST_MATCHING]: ({ request_id }) => {
117
+ this.log.info(`Session request ${request_id} matching...`);
118
+ },
119
+ [this.events.REQUEST_FILLED]: ({ session_id, request_id }) => {
120
+ this.log.info(
121
+ `Session request ${request_id} filled: ${this.tvlabsSessionLink(session_id)}`,
122
+ );
123
+
124
+ this.log.info('Waiting for device to be ready...');
125
+ },
126
+
127
+ // Failure events
128
+ [this.events.SESSION_FAILED]: ({ session_id, reason }) => {
129
+ this.log.error(`Session ${session_id} failed, reason: ${reason}`);
130
+ rej(reason);
131
+ },
132
+ [this.events.REQUEST_CANCELED]: ({ request_id, reason }) => {
133
+ this.log.info(
134
+ `Session request ${request_id} canceled, reason: ${reason}`,
135
+ );
136
+ rej(reason);
137
+ },
138
+ [this.events.REQUEST_FAILED]: ({ request_id, reason }) => {
139
+ this.log.info(
140
+ `Session request ${request_id} failed, reason: ${reason}`,
141
+ );
142
+ rej(reason);
143
+ },
144
+
145
+ // Ready event
146
+ [this.events.SESSION_READY]: ({ session_id }) => {
147
+ this.log.info(`Session ${session_id} ready!`);
148
+ res(session_id);
149
+ },
150
+ };
151
+
152
+ Object.entries(eventHandlers).forEach(([event, handler]) => {
153
+ this.requestTopic?.on(event, handler);
154
+ });
155
+
156
+ this.join(this.requestTopic).catch((err) => {
157
+ rej(err);
158
+ });
159
+ }).finally(cleanup);
160
+ }
161
+
162
+ private unobserveRequest() {
163
+ Object.values(this.events).forEach((event) => {
164
+ this.requestTopic?.off(event);
165
+ });
166
+
167
+ this.requestTopic?.leave();
168
+
169
+ this.requestTopic = undefined;
170
+ }
171
+
172
+ private async requestSession(
173
+ capabilities: TVLabsCapabilities,
174
+ ): Promise<string> {
175
+ this.log.info('Requesting TV Labs session');
176
+
177
+ try {
178
+ const response = await this.push<TVLabsSessionRequestResponse>(
179
+ this.lobbyTopic,
180
+ 'requests:create',
181
+ { capabilities },
182
+ );
183
+
184
+ this.log.info(
185
+ `Received session request ID: ${response.request_id}. Waiting for a match...`,
186
+ );
187
+
188
+ return response.request_id;
189
+ } catch (error) {
190
+ this.log.error('Error requesting session:', error);
191
+ throw error;
192
+ }
193
+ }
194
+
195
+ private async join(topic: Channel): Promise<void> {
196
+ return new Promise((res, rej) => {
197
+ topic
198
+ .join()
199
+ .receive('ok', (_resp: PhoenixChannelJoinResponse) => {
200
+ res();
201
+ })
202
+ .receive('error', ({ response }: PhoenixChannelJoinResponse) => {
203
+ rej('Failed to join topic: ' + response);
204
+ })
205
+ .receive('timeout', () => {
206
+ rej('timeout');
207
+ });
208
+ });
209
+ }
210
+
211
+ private async push<T>(
212
+ topic: Channel,
213
+ event: string,
214
+ payload: object,
215
+ ): Promise<T> {
216
+ return new Promise((res, rej) => {
217
+ topic
218
+ .push(event, payload)
219
+ .receive('ok', (msg: T) => {
220
+ res(msg);
221
+ })
222
+ .receive('error', (reason: string) => {
223
+ rej(reason);
224
+ })
225
+ .receive('timeout', () => {
226
+ rej('timeout');
227
+ });
228
+ });
229
+ }
230
+
231
+ private params(): TVLabsSessionChannelParams {
232
+ return {
233
+ api_key: this.key,
234
+ };
235
+ }
236
+
237
+ private reconnectAfterMs(tries: number) {
238
+ if (tries > this.maxReconnectRetries) {
239
+ throw new SevereServiceError(
240
+ 'Could not connect to TV Labs, please check your connection.',
241
+ );
242
+ }
243
+
244
+ const wait = [0, 1000, 3000, 5000][tries] || 10000;
245
+
246
+ this.log.info(
247
+ `[${tries}/${this.maxReconnectRetries}] Waiting ${wait}ms before re-attempting to connect...`,
248
+ );
249
+
250
+ return wait;
251
+ }
252
+
253
+ private tvlabsSessionLink(sessionId: string) {
254
+ return `https://tvlabs.ai/app/sessions/${sessionId}`;
255
+ }
256
+
257
+ private static logSocketError(
258
+ log: Logger,
259
+ event: ErrorEvent,
260
+ _transport: new (endpoint: string) => object,
261
+ _establishedConnections: number,
262
+ ) {
263
+ const error = event.error;
264
+
265
+ log.error('Socket error:', error || event);
266
+ }
267
+ }
@@ -1,4 +1,5 @@
1
1
  import TVLabsService from './service.js';
2
+
3
+ export { TVLabsService };
2
4
  export default TVLabsService;
3
5
  export * from './types.js';
4
- //# sourceMappingURL=index.d.ts.map
package/src/logger.ts ADDED
@@ -0,0 +1,66 @@
1
+ import type { LogLevel } from './types.js';
2
+
3
+ // TODO: Replace this with @wdio/logger
4
+ // It is currently not compatible with CJS
5
+
6
+ const LOG_LEVELS: Record<LogLevel, number> = {
7
+ error: 0,
8
+ warn: 1,
9
+ info: 2,
10
+ debug: 3,
11
+ trace: 4,
12
+ silent: 5,
13
+ };
14
+
15
+ export class Logger {
16
+ constructor(
17
+ private name: string,
18
+ private logLevel: LogLevel = 'info',
19
+ ) {}
20
+
21
+ private shouldLog(level: LogLevel): boolean {
22
+ if (this.logLevel === 'silent') {
23
+ return false;
24
+ }
25
+ return LOG_LEVELS[level] <= LOG_LEVELS[this.logLevel];
26
+ }
27
+
28
+ private formatMessage(level: LogLevel, ...args: unknown[]): string {
29
+ const timestamp = new Date().toISOString();
30
+ return `${timestamp} ${level.toUpperCase()} ${this.name}: ${args
31
+ .map((arg) =>
32
+ typeof arg === 'object' ? JSON.stringify(arg) : String(arg),
33
+ )
34
+ .join(' ')}`;
35
+ }
36
+
37
+ debug(...args: unknown[]): void {
38
+ if (this.shouldLog('debug')) {
39
+ console.log(this.formatMessage('debug', ...args));
40
+ }
41
+ }
42
+
43
+ info(...args: unknown[]): void {
44
+ if (this.shouldLog('info')) {
45
+ console.log(this.formatMessage('info', ...args));
46
+ }
47
+ }
48
+
49
+ warn(...args: unknown[]): void {
50
+ if (this.shouldLog('warn')) {
51
+ console.warn(this.formatMessage('warn', ...args));
52
+ }
53
+ }
54
+
55
+ error(...args: unknown[]): void {
56
+ if (this.shouldLog('error')) {
57
+ console.error(this.formatMessage('error', ...args));
58
+ }
59
+ }
60
+
61
+ trace(...args: unknown[]): void {
62
+ if (this.shouldLog('trace')) {
63
+ console.trace(this.formatMessage('trace', ...args));
64
+ }
65
+ }
66
+ }
@@ -0,0 +1,18 @@
1
+ import type { Socket as PhoenixSocket, MessageRef } from 'phoenix';
2
+
3
+ declare module 'phoenix' {
4
+ interface Socket extends PhoenixSocket {
5
+ onError(
6
+ callback: (
7
+ error: ErrorEvent,
8
+ transport: new (endpoint: string) => object,
9
+ establishedConnections: number,
10
+ ) => void | Promise<void>,
11
+ ): MessageRef;
12
+ }
13
+ }
14
+
15
+ export type PhoenixChannelJoinResponse = {
16
+ status?: string;
17
+ response?: unknown;
18
+ };