@intuned/runtime 1.0.5

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 (110) hide show
  1. package/.babelrc +21 -0
  2. package/.eslintignore +10 -0
  3. package/.eslintrc.js +39 -0
  4. package/CHANGELOG.md +7 -0
  5. package/InterfaceTemplate/index.playwright.ts +5 -0
  6. package/InterfaceTemplate/utils.ts +39 -0
  7. package/bin/intuned-api-run +2 -0
  8. package/bin/intuned-auth-session-check +2 -0
  9. package/bin/intuned-auth-session-create +2 -0
  10. package/bin/intuned-auth-session-load +2 -0
  11. package/bin/intuned-auth-session-refresh +2 -0
  12. package/bin/intuned-browser-save-state +2 -0
  13. package/bin/intuned-browser-start +2 -0
  14. package/bin/intuned-build +2 -0
  15. package/bin/intuned-ts-check +2 -0
  16. package/dist/commands/api/run.d.ts +6 -0
  17. package/dist/commands/api/run.js +115 -0
  18. package/dist/commands/auth-sessions/load.d.ts +2 -0
  19. package/dist/commands/auth-sessions/load.js +32 -0
  20. package/dist/commands/auth-sessions/run-check.d.ts +2 -0
  21. package/dist/commands/auth-sessions/run-check.js +62 -0
  22. package/dist/commands/auth-sessions/run-create.d.ts +2 -0
  23. package/dist/commands/auth-sessions/run-create.js +101 -0
  24. package/dist/commands/browser/save-state.d.ts +2 -0
  25. package/dist/commands/browser/save-state.js +17 -0
  26. package/dist/commands/browser/start-browser.d.ts +2 -0
  27. package/dist/commands/browser/start-browser.js +14 -0
  28. package/dist/commands/build.d.ts +1 -0
  29. package/dist/commands/build.js +84 -0
  30. package/dist/commands/common/browserUtils.d.ts +14 -0
  31. package/dist/commands/common/browserUtils.js +58 -0
  32. package/dist/commands/common/getFirstLineNumber.d.ts +9 -0
  33. package/dist/commands/common/getFirstLineNumber.js +103 -0
  34. package/dist/commands/common/getFirstLineNumber.test.js +228 -0
  35. package/dist/commands/common/sendMessageToClient.d.ts +1 -0
  36. package/dist/commands/common/sendMessageToClient.js +10 -0
  37. package/dist/commands/common/tsNodeImport.d.ts +1 -0
  38. package/dist/commands/common/tsNodeImport.js +20 -0
  39. package/dist/commands/common/utils/fileUtils.d.ts +6 -0
  40. package/dist/commands/common/utils/fileUtils.js +33 -0
  41. package/dist/commands/common/utils/settings.d.ts +2 -0
  42. package/dist/commands/common/utils/settings.js +28 -0
  43. package/dist/commands/common/utils/template.d.ts +2 -0
  44. package/dist/commands/common/utils/template.js +31 -0
  45. package/dist/commands/common/utils/unixSocket.d.ts +9 -0
  46. package/dist/commands/common/utils/unixSocket.js +44 -0
  47. package/dist/commands/interface/run.d.ts +1 -0
  48. package/dist/commands/interface/run.js +214 -0
  49. package/dist/commands/ts-check.d.ts +2 -0
  50. package/dist/commands/ts-check.js +56 -0
  51. package/dist/common/Logger/Logger/index.d.ts +12 -0
  52. package/dist/common/Logger/Logger/index.js +60 -0
  53. package/dist/common/Logger/Logger/types.d.ts +8 -0
  54. package/dist/common/Logger/Logger/types.js +5 -0
  55. package/dist/common/Logger/index.d.ts +12 -0
  56. package/dist/common/Logger/index.js +60 -0
  57. package/dist/common/Logger/types.d.ts +8 -0
  58. package/dist/common/Logger/types.js +5 -0
  59. package/dist/common/assets/browser_scripts.js +2214 -0
  60. package/dist/common/asyncLocalStorage/index.d.ts +16 -0
  61. package/dist/common/asyncLocalStorage/index.js +17 -0
  62. package/dist/common/cleanEnvironmentVariables.d.ts +1 -0
  63. package/dist/common/cleanEnvironmentVariables.js +16 -0
  64. package/dist/common/constants.d.ts +1 -0
  65. package/dist/common/constants.js +7 -0
  66. package/dist/common/contextStorageStateHelpers.d.ts +21 -0
  67. package/dist/common/contextStorageStateHelpers.js +81 -0
  68. package/dist/common/formatZodError.d.ts +2 -0
  69. package/dist/common/formatZodError.js +18 -0
  70. package/dist/common/getPlaywrightConstructs.d.ts +30 -0
  71. package/dist/common/getPlaywrightConstructs.js +196 -0
  72. package/dist/common/jwtTokenManager.d.ts +16 -0
  73. package/dist/common/jwtTokenManager.js +81 -0
  74. package/dist/common/runApi/errors.d.ts +65 -0
  75. package/dist/common/runApi/errors.js +156 -0
  76. package/dist/common/runApi/index.d.ts +12 -0
  77. package/dist/common/runApi/index.js +265 -0
  78. package/dist/common/runApi/types.d.ts +702 -0
  79. package/dist/common/runApi/types.js +74 -0
  80. package/dist/common/settingsSchema.d.ts +19 -0
  81. package/dist/common/settingsSchema.js +17 -0
  82. package/dist/common/telemetry.d.ts +3 -0
  83. package/dist/common/telemetry.js +32 -0
  84. package/dist/index.d.ts +4 -0
  85. package/dist/index.js +69 -0
  86. package/dist/runtime/RunError.d.ts +5 -0
  87. package/dist/runtime/RunError.js +19 -0
  88. package/dist/runtime/downloadDirectory.d.ts +1 -0
  89. package/dist/runtime/downloadDirectory.js +19 -0
  90. package/dist/runtime/enums.d.js +5 -0
  91. package/dist/runtime/enums.d.ts +11 -0
  92. package/dist/runtime/enums.js +18 -0
  93. package/dist/runtime/executionHelpers.test.js +53 -0
  94. package/dist/runtime/export.d.js +5 -0
  95. package/dist/runtime/export.d.ts +202 -0
  96. package/dist/runtime/extendPayload.d.ts +2 -0
  97. package/dist/runtime/extendPayload.js +21 -0
  98. package/dist/runtime/extendTimeout.d.ts +1 -0
  99. package/dist/runtime/extendTimeout.js +30 -0
  100. package/dist/runtime/index.d.ts +7 -0
  101. package/dist/runtime/index.js +53 -0
  102. package/dist/runtime/requestMoreInfo.d.ts +18 -0
  103. package/dist/runtime/requestMoreInfo.js +25 -0
  104. package/dist/runtime/runInfo.d.ts +2 -0
  105. package/dist/runtime/runInfo.js +21 -0
  106. package/package.json +136 -0
  107. package/template.tsconfig.json +14 -0
  108. package/tsconfig.eslint.json +5 -0
  109. package/tsconfig.json +24 -0
  110. package/typedoc.json +49 -0
@@ -0,0 +1,16 @@
1
+ /// <reference types="node" />
2
+ import { AsyncLocalStorage } from "async_hooks";
3
+ import { Payload, RunInfo } from "../../runtime/export";
4
+ export declare const asyncLocalStorage: AsyncLocalStorage<InternalRunInfo>;
5
+ export declare function runWithContext<R, TArgs extends any[]>(contextData: InternalRunInfo, callback: (...args: TArgs) => R, ...args: TArgs): R;
6
+ interface TimeoutInfo {
7
+ extendTimeoutCallback?: () => Promise<void>;
8
+ timeoutDuration?: number;
9
+ timeoutTimestamp?: number;
10
+ }
11
+ export interface InternalRunInfo extends RunInfo {
12
+ extendedPayloads: Payload[];
13
+ timeoutInfo?: TimeoutInfo;
14
+ }
15
+ export declare function getExecutionContext(): InternalRunInfo | undefined;
16
+ export {};
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.asyncLocalStorage = void 0;
7
+ exports.getExecutionContext = getExecutionContext;
8
+ exports.runWithContext = runWithContext;
9
+ var _async_hooks = require("async_hooks");
10
+ const asyncLocalStorage = exports.asyncLocalStorage = new _async_hooks.AsyncLocalStorage();
11
+ function runWithContext(contextData, callback, ...args) {
12
+ return asyncLocalStorage.run(contextData, callback, ...args);
13
+ }
14
+ function getExecutionContext() {
15
+ const contextData = asyncLocalStorage.getStore();
16
+ return contextData;
17
+ }
@@ -0,0 +1 @@
1
+ export declare function cleanEnvironmentVariables(): void;
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.cleanEnvironmentVariables = cleanEnvironmentVariables;
7
+ function cleanEnvironmentVariables() {
8
+ Object.keys(process.env).filter(i => {
9
+ if (i.toLocaleLowerCase().startsWith("npm")) {
10
+ return true;
11
+ }
12
+ if (i.toLocaleLowerCase().startsWith("fly") && i !== "FLY_ALLOC_ID") {
13
+ return true;
14
+ }
15
+ }).forEach(i => delete process.env[i]);
16
+ }
@@ -0,0 +1 @@
1
+ export declare const AUTH_SESSIONS_FOLDER_NAME = "auth-sessions";
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.AUTH_SESSIONS_FOLDER_NAME = void 0;
7
+ const AUTH_SESSIONS_FOLDER_NAME = exports.AUTH_SESSIONS_FOLDER_NAME = "auth-sessions";
@@ -0,0 +1,21 @@
1
+ import * as playwright from "playwright-core";
2
+ interface StorageEntry {
3
+ name: string;
4
+ value: string;
5
+ }
6
+ interface LocalStorageState {
7
+ origin: string;
8
+ localStorage: StorageEntry[];
9
+ }
10
+ interface SessionStorageState {
11
+ origin: string;
12
+ sessionStorage: StorageEntry[];
13
+ }
14
+ export interface StorageState {
15
+ cookies?: playwright.Cookie[] | null;
16
+ origins?: LocalStorageState[] | null;
17
+ sessionStorage?: SessionStorageState[] | null;
18
+ }
19
+ export declare function setStorageState(context: playwright.BrowserContext, state: StorageState): Promise<void>;
20
+ export declare function getStorageState(context: playwright.BrowserContext): Promise<StorageState>;
21
+ export {};
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.getStorageState = getStorageState;
7
+ exports.setStorageState = setStorageState;
8
+ async function setStorageState(context, state) {
9
+ if ("cookies" in state && state.cookies) {
10
+ await context.addCookies(state.cookies);
11
+ }
12
+ const page = await context.newPage();
13
+ if ("origins" in state && state.origins) {
14
+ for (const originData of state.origins || []) {
15
+ const origin = originData.origin;
16
+ await page.route(`${origin}/*`, route => route.fulfill({
17
+ body: "<html><head><title>Set Storage</title></head><body><h1>Set Storage</h1></body></html>",
18
+ contentType: "text/html",
19
+ status: 200
20
+ }));
21
+ try {
22
+ await page.goto(origin);
23
+ for (const item of originData.localStorage) {
24
+ await page.evaluate(([key, value]) => {
25
+ window.localStorage.setItem(key, value);
26
+ }, [item.name, item.value]);
27
+ }
28
+ } finally {
29
+ await page.unroute(`${origin}/*`);
30
+ }
31
+ }
32
+ }
33
+ if ("sessionStorage" in state && state.sessionStorage) {
34
+ await context.addInitScript(storage => {
35
+ for (const {
36
+ origin,
37
+ sessionStorage
38
+ } of storage) {
39
+ if (window.location.origin === origin) {
40
+ for (const item of sessionStorage) {
41
+ const value = window.sessionStorage.getItem(item.name);
42
+ if (!value) {
43
+ window.sessionStorage.setItem(item.name, item.value);
44
+ }
45
+ }
46
+ }
47
+ }
48
+ }, state.sessionStorage);
49
+ }
50
+ await page.close();
51
+ }
52
+ async function getStorageState(context) {
53
+ const result = {};
54
+ const storageState = await context.storageState();
55
+ result.cookies = storageState.cookies;
56
+ result.origins = storageState.origins;
57
+ const sessionDataList = [];
58
+ const pages = await context.pages();
59
+ for (const page of pages) {
60
+ if (page.isClosed()) continue;
61
+ try {
62
+ const sessionData = await page.evaluate(() => {
63
+ const items = {
64
+ ...window.sessionStorage
65
+ };
66
+ return {
67
+ origin: window.location.origin,
68
+ sessionStorage: Object.entries(items).map(([name, value]) => ({
69
+ name,
70
+ value
71
+ }))
72
+ };
73
+ });
74
+ sessionDataList.push(sessionData);
75
+ } catch (error) {
76
+ console.error("Error getting sessionStorage:", error);
77
+ }
78
+ }
79
+ result["sessionStorage"] = sessionDataList;
80
+ return result;
81
+ }
@@ -0,0 +1,2 @@
1
+ import { ZodError } from "zod";
2
+ export declare function formatZodError(zodError: ZodError): string[];
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.formatZodError = formatZodError;
7
+ function formatZodError(zodError) {
8
+ const formattedErrors = zodError.errors.map(error => {
9
+ const path = error.path.map(segment => {
10
+ return typeof segment === "number" ? `[${segment}]` : segment;
11
+ }).join(".");
12
+ if (path) {
13
+ return `${path} is invalid - ${error.message}`;
14
+ }
15
+ return error.message;
16
+ });
17
+ return formattedErrors;
18
+ }
@@ -0,0 +1,30 @@
1
+ import * as playwright from "playwright-core";
2
+ import type { RunApiSession } from "./runApi";
3
+ interface Proxy {
4
+ server: string;
5
+ username: string;
6
+ password: string;
7
+ }
8
+ interface GetPlaywrightConstructsOptions {
9
+ proxy?: Proxy;
10
+ headless?: boolean;
11
+ storageState?: RunApiSession;
12
+ downloadsPath: string;
13
+ }
14
+ export declare function getProductionPlaywrightConstructs({ proxy, headless, storageState, downloadsPath, }: GetPlaywrightConstructsOptions): Promise<{
15
+ page: playwright.Page;
16
+ context: playwright.BrowserContext;
17
+ }>;
18
+ export declare function getPlaywrightConstructsForMode(mode: "vanilla" | "playwright" | "playwright-standalone" | "playwright-headless", cdpAddress: string | undefined, authSession?: RunApiSession): Promise<{
19
+ page: playwright.Page;
20
+ context: playwright.BrowserContext;
21
+ }>;
22
+ export declare function loadSessionToContext({ context, session, }: {
23
+ context: playwright.BrowserContext;
24
+ session: RunApiSession;
25
+ }): Promise<void>;
26
+ export declare function getRemotePlaywrightContext(cdpAddress: string): Promise<{
27
+ browser: playwright.Browser;
28
+ context: playwright.BrowserContext;
29
+ }>;
30
+ export {};
@@ -0,0 +1,196 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.getPlaywrightConstructsForMode = getPlaywrightConstructsForMode;
7
+ exports.getProductionPlaywrightConstructs = getProductionPlaywrightConstructs;
8
+ exports.getRemotePlaywrightContext = getRemotePlaywrightContext;
9
+ exports.loadSessionToContext = loadSessionToContext;
10
+ var playwright = _interopRequireWildcard(require("playwright-core"));
11
+ var _fsExtra = _interopRequireWildcard(require("fs-extra"));
12
+ var fs = _fsExtra;
13
+ var _contextStorageStateHelpers = require("./contextStorageStateHelpers");
14
+ var _path = _interopRequireWildcard(require("path"));
15
+ var _fileUtils = require("../commands/common/utils/fileUtils");
16
+ var _waitOn = _interopRequireDefault(require("wait-on"));
17
+ var _runtime = require("../runtime");
18
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
19
+ function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
20
+ function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
21
+ async function createUserDirWithPreferences() {
22
+ const playwrightTempDir = await (0, _fsExtra.mkdtemp)("/tmp/pw-");
23
+ const userDir = (0, _path.join)(playwrightTempDir, "userdir");
24
+ const defaultDir = (0, _path.join)(userDir, "Default");
25
+ await (0, _fsExtra.mkdir)(defaultDir, {
26
+ recursive: true
27
+ });
28
+ const preferences = {
29
+ plugins: {
30
+ always_open_pdf_externally: true
31
+ }
32
+ };
33
+ await (0, _fsExtra.writeFile)((0, _path.join)(defaultDir, "Preferences"), JSON.stringify(preferences));
34
+ return userDir;
35
+ }
36
+ async function getProductionPlaywrightConstructs({
37
+ proxy,
38
+ headless = true,
39
+ storageState,
40
+ downloadsPath
41
+ }) {
42
+ const extraArgs = ["--no-first-run", "--disable-sync", "--disable-translate", "--disable-features=TranslateUI", "--disable-features=NetworkService", "--lang=en"];
43
+ if (headless) {
44
+ extraArgs.push("--headless=new");
45
+ }
46
+ const executablePath = playwright.chromium.executablePath();
47
+ const chromium127Path = executablePath.replace("chromium-1117", "chromium-1124");
48
+ const isChrome127There = await (0, _fsExtra.exists)(chromium127Path);
49
+ const userAgent = `Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${isChrome127There ? 127 : 125}.0.0.0 Safari/537.36`;
50
+ const userDataDir = await createUserDirWithPreferences();
51
+ const context = await playwright.chromium.launchPersistentContext(userDataDir, {
52
+ headless,
53
+ ignoreDefaultArgs: [...getChromiumLaunchArgsToIgnore(), "--headless"],
54
+ proxy,
55
+ executablePath: isChrome127There ? chromium127Path : executablePath,
56
+ args: extraArgs,
57
+ downloadsPath,
58
+ userAgent
59
+ });
60
+ context.once("close", async () => {
61
+ try {
62
+ await (0, _fsExtra.rm)(userDataDir, {
63
+ recursive: true,
64
+ force: true,
65
+ retryDelay: 1000,
66
+ maxRetries: 5
67
+ });
68
+ } catch (error) {
69
+ console.error("Failed to remove user data dir", error);
70
+ }
71
+ });
72
+ if (storageState) {
73
+ await loadSessionToContext({
74
+ context,
75
+ session: storageState
76
+ });
77
+ }
78
+ const assetsFile = _path.default.join(__dirname, "./assets/browser_scripts.js");
79
+ await context.addInitScript({
80
+ path: assetsFile
81
+ });
82
+ let page = context.pages().at(0);
83
+ if (page) {
84
+ const scriptString = await (0, _fsExtra.readFile)(assetsFile, "utf8");
85
+ await page.evaluate(scriptString);
86
+ } else {
87
+ page = await context.newPage();
88
+ }
89
+ return {
90
+ page,
91
+ context
92
+ };
93
+ }
94
+ const getChromiumLaunchArgsToIgnore = () => ["--disable-field-trial-config", "--disable-background-networking", "--enable-features=NetworkService,NetworkServiceInProcess", "--disable-background-timer-throttling", "--disable-backgrounding-occluded-windows", "--disable-back-forward-cache", "--disable-breakpad", "--disable-client-side-phishing-detection", "--disable-component-extensions-with-background-pages", "--disable-component-update", "--no-default-browser-check", "--disable-default-apps", "--disable-dev-shm-usage", "--disable-extensions", "--disable-features=ImprovedCookieControls,LazyFrameLoading,GlobalMediaControls,DestroyProfileOnBrowserClose,MediaRouter,DialMediaRouteProvider,AcceptCHFrame,AutoExpandDetailsElement,CertificateTransparencyComponentUpdater,AvoidUnnecessaryBeforeUnloadCheckSync,Translate,TranslateUI", "--allow-pre-commit-input", "--disable-hang-monitor", "--disable-ipc-flooding-protection", "--disable-prompt-on-repost", "--disable-renderer-backgrounding", "--force-color-profile=srgb", "--metrics-recording-only", "--no-first-run", "--enable-automation", "--password-store=basic", "--use-mock-keychain", "--no-service-autorun", "--export-tagged-pdf", "--enable-use-zoom-for-dsf=false"];
95
+ async function getPlaywrightConstructsForMode(mode, cdpAddress, authSession) {
96
+ if (mode == "playwright-standalone") {
97
+ if (!cdpAddress) {
98
+ throw new Error("cdpAddress is required");
99
+ }
100
+ const {
101
+ context
102
+ } = await getRemotePlaywrightContext(cdpAddress);
103
+ if (!context) {
104
+ throw new Error("no context found");
105
+ }
106
+ const assetsFile = _path.default.join(__dirname, "./assets/browser_scripts.js");
107
+ await context.addInitScript({
108
+ path: assetsFile
109
+ });
110
+ const pages = await context.pages();
111
+ let page = null;
112
+ if (pages.length > 0) {
113
+ page = pages[0];
114
+ const scriptString = await fs.readFile(assetsFile, "utf8");
115
+ await page.evaluate(scriptString);
116
+ } else {
117
+ page = await context.newPage();
118
+ }
119
+ if (authSession) {
120
+ await loadSessionToContext({
121
+ context,
122
+ session: authSession
123
+ });
124
+ }
125
+ return {
126
+ page,
127
+ context
128
+ };
129
+ }
130
+ const downloadsPath = (0, _runtime.getDownloadDirectoryPath)();
131
+ if (mode === "playwright" || mode === "playwright-headless") {
132
+ const productionConstructs = await getProductionPlaywrightConstructs({
133
+ headless: mode === "playwright-headless",
134
+ downloadsPath
135
+ });
136
+ if (authSession) {
137
+ await loadSessionToContext({
138
+ context: productionConstructs.context,
139
+ session: authSession
140
+ });
141
+ }
142
+ return {
143
+ ...productionConstructs
144
+ };
145
+ }
146
+ throw "invalid mode";
147
+ }
148
+ async function loadSessionToContext({
149
+ context,
150
+ session
151
+ }) {
152
+ let sessionToLoad;
153
+ if (session.type === "state") {
154
+ const state = session.state;
155
+ if (state === undefined || state === null) {
156
+ return;
157
+ }
158
+ sessionToLoad = state;
159
+ } else {
160
+ const fullPath = (0, _fileUtils.getFullPathInProject)(session.path);
161
+ sessionToLoad = await fs.readJson(fullPath);
162
+ }
163
+ await (0, _contextStorageStateHelpers.setStorageState)(context, sessionToLoad);
164
+ }
165
+ async function getRemotePlaywrightContext(cdpAddress) {
166
+ const playwright = await Promise.resolve().then(() => _interopRequireWildcard(require("playwright-core")));
167
+ let browser = null;
168
+ if (!cdpAddress) {
169
+ throw new Error("cdpAddress is required");
170
+ }
171
+ const cdpAddressWithoutProtocol = cdpAddress.replace("http://", "").replace("https://", "").replace("localhost", "127.0.0.1");
172
+ try {
173
+ await (0, _waitOn.default)({
174
+ resources: [`http-get://${cdpAddressWithoutProtocol}/json/version`],
175
+ delay: 100,
176
+ interval: 100,
177
+ timeout: 5000,
178
+ tcpTimeout: 1000,
179
+ window: 1000
180
+ });
181
+ } catch (error) {
182
+ console.error("Failed to connect to the browser");
183
+ process.exit(128 + 9);
184
+ }
185
+ try {
186
+ browser = await playwright.chromium.connectOverCDP(cdpAddress);
187
+ } catch (e) {
188
+ console.log(e);
189
+ throw new Error("failed to connect to the browser");
190
+ }
191
+ const context = browser.contexts()[0];
192
+ return {
193
+ browser,
194
+ context
195
+ };
196
+ }
@@ -0,0 +1,16 @@
1
+ import fetch from "cross-fetch";
2
+ declare class JwtTokenManager {
3
+ private _token;
4
+ private tokenRefreshTimeout;
5
+ private refreshTokenPath;
6
+ constructor(refreshTokenPath: string);
7
+ get token(): string | undefined;
8
+ set token(newToken: string | undefined);
9
+ private get timeToRefresh();
10
+ private scheduleTokenRefresh;
11
+ private refreshToken;
12
+ fetchWithToken(...[input, init]: Parameters<typeof fetch>): Promise<Response>;
13
+ }
14
+ export declare const backendFunctionsTokenManager: JwtTokenManager;
15
+ export declare function callBackendFunctionWithToken(path: string, init?: Parameters<typeof fetch>[1]): Promise<Response>;
16
+ export {};
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.backendFunctionsTokenManager = void 0;
7
+ exports.callBackendFunctionWithToken = callBackendFunctionWithToken;
8
+ var _crossFetch = _interopRequireDefault(require("cross-fetch"));
9
+ var jwt = _interopRequireWildcard(require("jsonwebtoken"));
10
+ var _neverthrow = require("neverthrow");
11
+ function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
12
+ function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
13
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
14
+ class JwtTokenManager {
15
+ constructor(refreshTokenPath) {
16
+ this.refreshTokenPath = refreshTokenPath;
17
+ this._token = undefined;
18
+ }
19
+ get token() {
20
+ return this._token;
21
+ }
22
+ set token(newToken) {
23
+ if (this._token != newToken) {
24
+ this._token = newToken;
25
+ void this.scheduleTokenRefresh();
26
+ }
27
+ }
28
+ get timeToRefresh() {
29
+ if (!this._token) return;
30
+ const payload = jwt.decode(this._token);
31
+ if (!payload || typeof payload == "string") return;
32
+ const expiry = payload.expiry;
33
+ if (!expiry || typeof expiry !== "number") return;
34
+ const timeWindow = 60 * 1000;
35
+ const timeToRefresh = expiry - Date.now() - timeWindow;
36
+ return Math.max(timeToRefresh, timeWindow);
37
+ }
38
+ async scheduleTokenRefresh() {
39
+ var _process$env$RUN_ENVI;
40
+ if (((_process$env$RUN_ENVI = process.env.RUN_ENVIRONMENT) === null || _process$env$RUN_ENVI === void 0 ? void 0 : _process$env$RUN_ENVI.toLowerCase()) !== "authoring") return;
41
+ const timeToRefresh = this.timeToRefresh;
42
+ if (timeToRefresh === undefined) return;
43
+ if (this.tokenRefreshTimeout) clearTimeout(this.tokenRefreshTimeout);
44
+ this.tokenRefreshTimeout = setTimeout(async () => {
45
+ const result = await this.refreshToken();
46
+ if (result && result.isErr()) {
47
+ console.error(`[Internal Error] ${result.error}`);
48
+ return;
49
+ }
50
+ await this.scheduleTokenRefresh();
51
+ }, timeToRefresh);
52
+ }
53
+ async refreshToken() {
54
+ var _process$env$RUN_ENVI2;
55
+ if (((_process$env$RUN_ENVI2 = process.env.RUN_ENVIRONMENT) === null || _process$env$RUN_ENVI2 === void 0 ? void 0 : _process$env$RUN_ENVI2.toLowerCase()) !== "authoring") return;
56
+ const res = await this.fetchWithToken(this.refreshTokenPath, {
57
+ method: "GET"
58
+ });
59
+ if (res.status === 401) {
60
+ return (0, _neverthrow.err)("Unauthorized");
61
+ }
62
+ const jsonResult = await _neverthrow.ResultAsync.fromPromise(res.json(), () => "not json");
63
+ if (jsonResult.isErr()) return;
64
+ const newToken = jsonResult.value.token;
65
+ if (newToken) this._token = newToken;
66
+ }
67
+ fetchWithToken(...[input, init]) {
68
+ const headers = new Headers(init === null || init === void 0 ? void 0 : init.headers);
69
+ headers.set("Authorization", `Bearer ${this.token}`);
70
+ return (0, _crossFetch.default)(input, {
71
+ ...init,
72
+ headers
73
+ });
74
+ }
75
+ }
76
+ const backendFunctionsPath = `${process.env.FUNCTIONS_DOMAIN}/api/${process.env.INTUNED_WORKSPACE_ID}/functions/${process.env.INTUNED_INTEGRATION_ID}`;
77
+ const backendFunctionsTokenManager = exports.backendFunctionsTokenManager = new JwtTokenManager(`${backendFunctionsPath}/refreshBackendFunctionsToken`);
78
+ backendFunctionsTokenManager.token = process.env.INTUNED_AUTHORING_SESSION_BACKEND_FUNCTIONS_TOKEN;
79
+ function callBackendFunctionWithToken(path, init) {
80
+ return backendFunctionsTokenManager.fetchWithToken(`${backendFunctionsPath}/${path}`, init);
81
+ }
@@ -0,0 +1,65 @@
1
+ import { RunErrorOptions } from "../../runtime/export";
2
+ export declare const apiNotFoundErrorCode = "APINotFoundError";
3
+ export declare const invalidApiErrorCode = "InvalidAPIError";
4
+ export declare const invalidCheckErrorCode = "InvalidCheckError";
5
+ export declare const abortedErrorCode = "AbortedError";
6
+ export declare const authRequiredErrorCode = "AuthRequiredError";
7
+ export declare const authCheckNotFoundErrorCode = "AuthCheckNotFoundError";
8
+ export declare const authCheckFailedErrorCode = "AuthCheckFailedError";
9
+ export declare const maxLevelsExceededErrorCode = "MaxLevelsExceededError";
10
+ export declare const automationError = "AutomationError";
11
+ export declare const internalInvalidInputErrorCode = "InternalInvalidInputError";
12
+ export declare const runAutomationErrorCodes: readonly ["APINotFoundError", "InvalidAPIError", "InvalidCheckError", "AbortedError", "AuthRequiredError", "AuthCheckNotFoundError", "AuthCheckFailedError", "MaxLevelsExceededError", "AutomationError", "InternalInvalidInputError"];
13
+ export type RunAutomationErrorCode = (typeof runAutomationErrorCodes)[number];
14
+ export declare abstract class RunAutomationError<T = any> {
15
+ code: RunAutomationErrorCode;
16
+ statusCode: number;
17
+ wrapped: boolean;
18
+ message: string;
19
+ cause?: RunAutomationError;
20
+ details?: T;
21
+ get json(): {
22
+ code: "APINotFoundError" | "InvalidAPIError" | "InvalidCheckError" | "AbortedError" | "AuthRequiredError" | "AuthCheckNotFoundError" | "AuthCheckFailedError" | "MaxLevelsExceededError" | "AutomationError" | "InternalInvalidInputError";
23
+ details: T | undefined;
24
+ cause: any;
25
+ };
26
+ }
27
+ export declare class ApiNotFoundError extends RunAutomationError {
28
+ constructor(apiName: string);
29
+ }
30
+ export declare class InvalidApiError extends RunAutomationError {
31
+ constructor(message: string);
32
+ }
33
+ export declare class InvalidCheckError extends RunAutomationError {
34
+ constructor(message: string, cause?: RunAutomationError);
35
+ }
36
+ export declare class AbortedError extends RunAutomationError {
37
+ constructor();
38
+ }
39
+ export declare class AuthRequiredError extends RunAutomationError {
40
+ constructor();
41
+ }
42
+ export declare class AuthCheckNotFoundError extends RunAutomationError {
43
+ constructor();
44
+ }
45
+ export declare class AuthCheckFailedError extends RunAutomationError {
46
+ constructor();
47
+ }
48
+ export declare class MaxLevelsExceededError extends RunAutomationError<{
49
+ levels: number;
50
+ }> {
51
+ constructor(levels: number);
52
+ }
53
+ export declare class AutomationError extends RunAutomationError<{
54
+ name?: string;
55
+ message?: string;
56
+ statusCode?: number;
57
+ errorCode?: string;
58
+ options?: RunErrorOptions;
59
+ }> {
60
+ error: any;
61
+ constructor(error: any);
62
+ }
63
+ export declare class InternalInvalidInputError extends RunAutomationError {
64
+ constructor(message: string, details?: any);
65
+ }