-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathcommon.ts
536 lines (502 loc) · 15.9 KB
/
common.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
/*---------------------------------------------------------------------------------------------
* BrightScript Engine (https://github.com/lvcabral/brs-engine)
*
* Copyright (c) 2019-2025 Marcelo Lv Cabral. All Rights Reserved.
*
* Licensed under the MIT License. See LICENSE in the repository root for license information.
*--------------------------------------------------------------------------------------------*/
/* Device Simulation Information Interface
*
* This interface is used to simulate a Roku device environment in the engine.
* It feeds the interpreter with several device features like registry, fonts,
* audio codecs, video formats, and other device information provided by `roDeviceInfo`.
*
* Roku documentation: https://developer.roku.com/docs/references/brightscript/interfaces/ifdeviceinfo.md
*/
export interface DeviceInfo {
[key: string]: any;
developerId: string;
friendlyName: string;
deviceModel: string;
firmwareVersion: string;
clientId: string;
RIDA: string;
countryCode: string;
timeZone: string;
locale: "en_US" | "de_DE" | "es_MX" | "fr_CA" | "pt_BR";
captionLanguage: string;
clockFormat: string;
displayMode: "480p" | "720p" | "1080p";
captionsMode: "Off" | "On" | "Instant replay" | "When mute";
defaultFont: string;
fontPath: string;
fonts?: Map<string, any>;
maxSimulStreams: 1 | 2 | 3;
remoteControls: RemoteControl[];
customFeatures: string[];
connectionInfo: ConnectionInfo;
localIps: string[];
startTime: number;
audioVolume: number;
maxFps: number;
registry?: Map<string, string>;
audioCodecs?: string[];
videoFormats?: Map<string, string[]>;
appList?: AppData[];
entryPoint?: boolean;
stopOnCrash?: boolean;
platform?: Platform;
}
// Default Device Information
export const platform = getPlatform();
export const defaultDeviceInfo: DeviceInfo = {
developerId: "34c6fceca75e456f25e7e99531e2425c6c1de443", // As in Roku devices, segregates Registry data (can't have a dot)
friendlyName: "BrightScript Engine Library",
deviceModel: "8000X", // Roku TV (Midland)
firmwareVersion: "48F.04E12221A", // v14.0
clientId: "6c5bf3a5-b2a5-4918-824d-7691d5c85364",
RIDA: "f51ac698-bc60-4409-aae3-8fc3abc025c4", // Unique identifier for advertisement tracking
countryCode: "US", // App Store Country
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
locale: "en_US", // Used if app supports localization
captionLanguage: "eng",
clockFormat: "12h",
displayMode: "720p",
captionsMode: "Off",
defaultFont: "Asap",
fontPath: "../fonts/",
fonts: new Map(),
maxSimulStreams: 2,
remoteControls: [],
customFeatures: [],
connectionInfo: {
type: "WiredConnection",
name: "eth1",
gateway: "127.0.0.1",
ip: "127.0.0.1",
dns: ["8.8.8.8", "8.8.4.4"],
quality: "Excellent",
},
localIps: ["eth1,127.0.0.1"], // In a Browser is not possible to get a real IP, populate it on NodeJS or Electron.
startTime: Date.now(),
audioVolume: 40,
registry: new Map(),
maxFps: 60,
platform: platform,
};
/* Execution Payload Interface
*
* This interface is used to provide information to the interpreter about the
* device and app that will be executed. It contains the DeviceInfo object,
* the app manifest, source code, deep link, encryption password, paths,
* some execution flags and file system paths.
*
*/
export type AppPayload = {
device: DeviceInfo;
launchTime: number;
manifest: Map<string, string>;
deepLink: Map<string, string>;
paths: PkgFilePath[];
source: string[];
pkgZip?: ArrayBuffer;
extZip?: ArrayBuffer;
password?: string;
root?: string;
ext?: string;
};
export function isAppPayload(value: any): value is AppPayload {
return (
value &&
typeof value.device === "object" &&
typeof value.launchTime === "number" &&
value.manifest instanceof Map &&
value.deepLink instanceof Map &&
Array.isArray(value.paths) &&
Array.isArray(value.source) &&
(value.pkgZip instanceof ArrayBuffer || value.pkgZip === undefined) &&
(value.extZip instanceof ArrayBuffer || value.extZip === undefined) &&
(typeof value.password === "string" || value.password === undefined) &&
(typeof value.root === "string" || value.root === undefined) &&
(typeof value.ext === "string" || value.ext === undefined)
);
}
/* Package File Path Interface
*
* This interface is used to provide information about the paths to the
* source code and pcode files that are available in the app package.
* It is sent to the interpreter via `ExecPayload.paths`.
*
*/
export type PkgFilePath = {
id: number;
url: string;
type: "source" | "pcode";
};
/* App Exit Reason Enumerator
*
* This enumerator is used to provide information about the reason
* why the app was terminated.
*
* Roku documentation: https://developer.roku.com/docs/developer-program/getting-started/architecture/dev-environment.md#lastexitorterminationreason-parameter
*/
export enum AppExitReason {
UNKNOWN = "EXIT_UNKNOWN",
CRASHED = "EXIT_BRIGHTSCRIPT_CRASH",
UNKFUNC = "EXIT_BRIGHTSCRIPT_UNK_FUNC",
FINISHED = "EXIT_USER_NAV",
SETTINGS = "EXIT_SETTINGS_UPDATE",
POWER = "EXIT_POWER_MODE",
PACKAGED = "EXIT_PACKAGER_DONE",
INVALID = "EXIT_INVALID_PCODE",
PASSWORD = "EXIT_MISSING_PASSWORD",
UNPACK = "EXIT_UNPACK_FAILED",
}
/* App Data Interface
*
* This interface is used to provide information about the apps that are
* available in the device and status of the app that is currently running.
*
*/
export type AppData = {
id: string;
title: string;
subtitle?: string;
version: string;
path?: string;
icon?: string;
password?: string;
exitReason?: AppExitReason;
exitTime?: number;
params?: Map<string, string>;
running?: boolean;
};
// Function to check if a value is an AppData object
export function isAppData(value: any): value is AppData {
return (
value &&
typeof value.id === "string" &&
typeof value.title === "string" &&
typeof value.version === "string" &&
(typeof value.path === "string" || value.path === undefined) &&
(typeof value.icon === "string" || value.icon === undefined) &&
(typeof value.password === "string" || value.password === undefined) &&
(typeof value.exitReason === "string" || value.exitReason === undefined) &&
(typeof value.exitTime === "number" || value.exitTime === undefined) &&
(value.params instanceof Map || value.params === undefined) &&
(typeof value.running === "boolean" || value.running === undefined)
);
}
/**
* NDK Start Interface
*/
export type NDKStart = {
app: "roku_browser" | "SDKLauncher";
params: string[];
env: string[];
};
// Function to check if a value is an NDKStart object
export function isNDKStart(value: any): value is NDKStart {
return (
value &&
typeof value.app === "string" &&
["roku_browser", "SDKLauncher"].includes(value.app) &&
Array.isArray(value.params) &&
Array.isArray(value.env)
);
}
/* Remote Control Interface
*
* This interface is used to provide information about the remote controls
* that are available in the device.
*
*/
export type RemoteControl = {
model: number;
features: string[];
};
/* Platform Interface
*
* This interface is used to provide information about the environment
* where the engine is running.
*
*/
export type Platform = {
inBrowser: boolean;
inChromium: boolean;
inFirefox: boolean;
inSafari: boolean;
inElectron: boolean;
inAndroid: boolean;
inIOS: boolean;
inMacOS: boolean;
inWindows: boolean;
inLinux: boolean;
inChromeOS: boolean;
};
// Function to check if a value is a Platform object
export function isPlatform(value: any): value is Platform {
return (
value &&
typeof value.inBrowser === "boolean" &&
typeof value.inChromium === "boolean" &&
typeof value.inFirefox === "boolean" &&
typeof value.inSafari === "boolean" &&
typeof value.inElectron === "boolean" &&
typeof value.inAndroid === "boolean" &&
typeof value.inIOS === "boolean" &&
typeof value.inMacOS === "boolean" &&
typeof value.inWindows === "boolean" &&
typeof value.inLinux === "boolean" &&
typeof value.inChromeOS === "boolean"
);
}
/* Connection Information Interface
*
* This interface is used to provide information about the connection
* that is available in the device.
*
*/
export type ConnectionInfo = {
type: "WiFiConnection" | "WiredConnection" | "";
name: string;
ip: string;
gateway: string;
quality: "Excellent" | "Good" | "Fair" | "Poor";
dns?: string[];
protocol?: string;
ssid?: string;
};
// Shared array data types enumerator
export enum DataType {
DBG, // Debug Command
BUF, // Buffer flag
VDO, // Video State
VDX, // Video Index
VSE, // Video Selected
VLP, // Video Load Progress
VPS, // Video Position
VDR, // Video Duration
SND, // Sound State
IDX, // Sound Index
WAV, // Wave Audio
WAV1, // Reserved for second stream
WAV2, // Reserved for third stream
MUHS, // Memory Used Heap Size
MHSL, // Memory Heap Size Limit
MBWD, // Measured Bandwidth
CEC, // Consumer Electronics Control
HDMI, // HDMI Status
// Key Buffer starts here: KeyBufferSize * KeyArraySpots
RID, // Remote Id
KEY, // Key Code
MOD, // Key State (down/up)
}
// Debug constants
export const dataBufferIndex = 33;
export const dataBufferSize = 1024;
// Key Buffer Constants
export const keyBufferSize = 5; // Max is 5, if needs more space increase `dataBufferIndex`
export const keyArraySpots = 3;
// Remote control type
export enum RemoteType {
IR = 10, // Infra Red (default)
WD = 20, // Wifi Direct (keyboard simulation)
BT = 30, // Bluetooth (gamepad simulation)
SIM = 40, // Simulated
ECP = 50, // External Control Protocol
RMOB = 60, // Roku Mobile App (ECP2)
}
// Other RBI valid remote codes:
// CEC - Consumer Electronics Control
// MHL - Mobile High-Definition Link
// FP - Front Panel (for on-device controls)
// Debug prompt
export const debugPrompt = "Brightscript Debugger> ";
// Debug commands enumerator
export enum DebugCommand {
BSCS,
BT,
CLASSES,
CONT,
EXIT,
EXPR,
HELP,
LAST,
LIST,
NEXT,
STATS,
STEP,
THREAD,
THREADS,
VAR,
BREAK,
PAUSE,
}
// Media events enumerator
export enum MediaEvent {
SELECTED,
FULL,
PARTIAL,
PAUSED,
RESUMED,
FAILED,
LOADING,
START_STREAM,
START_PLAY,
POSITION,
}
// Buffer Data Types enumerator
export enum BufferType {
DEBUG_EXPR,
AUDIO_TRACKS,
SYS_LOG,
INPUT,
}
// Default Roku Sounds
export const DefaultSounds = ["select", "navsingle", "navmulti", "deadend"];
// Media Files Extensions
export const AudioExt = new Set<string>([
"wav",
"mp2",
"mp3",
"m4a",
"aac",
"ogg",
"oga",
"ac3",
"wma",
"flac",
]);
export const VideoExt = new Set<string>(["mp4", "m4v", "mkv", "mov"]);
// Check the platform where the library is running
export function getPlatform(): Platform {
let inBrowser = false;
let inChromium = false;
let inFirefox = false;
let inSafari = false;
let inElectron = false;
let inAndroid = false;
let inChromeOS = false;
let inIOS = false;
let inMacOS = false;
let inLinux = false;
let inWindows = false;
if (typeof window !== "undefined") {
inBrowser = true;
inChromium =
("chrome" in window || (window.Intl && "v8BreakIterator" in Intl)) && "CSS" in window;
}
if (typeof navigator !== "undefined" && typeof navigator.userAgent === "string") {
let ua = navigator.userAgent;
// Check Browsers
if (ua.indexOf("Electron") >= 0) {
inElectron = true;
inChromium = true;
} else if (/Firefox\D+(\d+)/.test(ua)) {
inFirefox = true;
} else if (/^((?!chrome|android).)*safari/i.test(ua)) {
inSafari = true;
}
// Check OS
if (/Android/.test(ua)) {
inAndroid = true;
} else if (/CrOS/.test(ua)) {
inChromeOS = true;
} else if (/iP[ao]d|iPhone/i.test(ua)) {
inIOS = true;
} else if (/Mac OS/.test(ua) && !/like Mac OS/.test(ua)) {
inMacOS = true;
} else if (/Linux/.test(ua)) {
inLinux = true;
} else if (/Windows/.test(ua)) {
inWindows = true;
}
} else if (process.platform === "android") {
inAndroid = true;
} else if (process.platform === "darwin") {
inMacOS = true;
} else if (process.platform === "linux") {
inLinux = true;
} else if (process.platform === "win32") {
inWindows = true;
}
return {
inBrowser: inBrowser,
inChromium: inChromium,
inFirefox: inFirefox,
inSafari: inSafari,
inElectron: inElectron,
inAndroid: inAndroid,
inChromeOS: inChromeOS,
inIOS: inIOS,
inLinux: inLinux,
inMacOS: inMacOS,
inWindows: inWindows,
};
}
// Function to parse the Manifest file into a Map
export function parseManifest(contents: string) {
let keyValuePairs = contents
// for each line
.split("\n")
// remove leading/trailing whitespace
.map((line) => line.trim())
// separate keys and values
.map((line, index) => {
// skip empty lines and comments
if (line === "" || line.startsWith("#")) {
return ["", ""];
}
let equals = line.indexOf("=");
if (equals === -1) {
const pos = `${index + 1},0-${line.length}`;
console.warn(
`manifest(${pos}): Missing "=". Manifest entries must have this format: key=value`
);
}
return [line.slice(0, equals), line.slice(equals + 1)];
})
// keep only non-empty keys and values
.filter(([key, value]) => key && value)
// remove leading/trailing whitespace from keys and values
.map(([key, value]) => [key.trim(), value.trim()])
// convert value to boolean, integer, or leave as string
.map(([key, value]): [string, string] => {
return [key, value];
});
return new Map<string, string>(keyValuePairs);
}
// Function to return the Exit Reason from the enumerator based on a string
export function getExitReason(value: string): AppExitReason {
if (Object.values(AppExitReason).includes(value as any)) {
return value as AppExitReason;
} else {
return AppExitReason.UNKNOWN;
}
}
// Function to convert a number to a hexadecimal string
export function numberToHex(value: number, pad: string = ""): string {
return (value >>> 0).toString(16).padStart(8, pad);
}
// This function takes a text file content as a string and returns an array of lines
export function parseTextFile(content?: string): string[] {
let lines: string[] = [];
if (content) {
lines = content.trimEnd().split("\n");
}
return lines;
}
// Function to convert the firmware string to a Map with Roku OS version parts
export function getRokuOSVersion(firmware: string) {
const osVersion: Map<string, string> = new Map();
if (firmware.length > 0) {
const versions = "0123456789ACDEFGHJKLMNPRSTUVWXY";
osVersion.set("major", versions.indexOf(firmware.charAt(2)).toString());
osVersion.set("minor", firmware.slice(4, 5));
osVersion.set("revision", firmware.slice(7, 8));
osVersion.set("build", firmware.slice(8, 12));
osVersion.set("plid", firmware.slice(0, 2));
}
return osVersion;
}