@intuned/runtime-dev 0.1.0-test.13 → 0.1.0-test.15

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 (97) hide show
  1. package/bin/intuned-api-run +1 -1
  2. package/bin/intuned-auth-session-check +1 -1
  3. package/bin/intuned-auth-session-create +1 -1
  4. package/bin/intuned-auth-session-load +1 -1
  5. package/bin/intuned-auth-session-refresh +1 -1
  6. package/bin/intuned-browser-save-state +1 -1
  7. package/bin/intuned-browser-start +1 -1
  8. package/bin/intuned-build +1 -1
  9. package/bin/intuned-ts-check +1 -1
  10. package/dist/commands/api/run.js +83 -156
  11. package/dist/commands/auth-sessions/load.js +20 -20
  12. package/dist/commands/auth-sessions/run-check.js +39 -45
  13. package/dist/commands/auth-sessions/run-create.js +74 -84
  14. package/dist/commands/browser/save-state.js +7 -12
  15. package/dist/commands/browser/start-browser.js +4 -7
  16. package/dist/commands/build.js +62 -96
  17. package/dist/commands/common/browserUtils.js +30 -41
  18. package/dist/commands/common/getDefaultExportFromFile.d.ts +0 -1
  19. package/dist/commands/common/getDefaultExportFromFile.js +0 -12
  20. package/dist/commands/common/getFirstLineNumber.js +83 -90
  21. package/dist/commands/common/{getFirstLineNumber.test.ts → getFirstLineNumber.test.js} +2 -1
  22. package/dist/commands/common/sendMessageToClient.js +2 -4
  23. package/dist/commands/common/utils/fileUtils.js +16 -16
  24. package/dist/commands/common/utils/settings.js +18 -16
  25. package/dist/commands/common/utils/unixSocket.js +36 -43
  26. package/dist/commands/common/utils/webTemplate.js +19 -25
  27. package/dist/commands/interface/run.js +133 -139
  28. package/dist/commands/ts-check.js +41 -44
  29. package/dist/common/Logger/Logger/index.js +46 -40
  30. package/dist/common/Logger/Logger/types.js +1 -1
  31. package/dist/common/Logger/index.js +46 -40
  32. package/dist/common/Logger/types.js +1 -1
  33. package/dist/common/asyncLocalStorage/index.js +4 -4
  34. package/dist/common/cleanEnvironmentVariables.js +9 -11
  35. package/dist/common/constants.js +1 -1
  36. package/dist/common/contextStorageStateHelpers.js +38 -36
  37. package/dist/common/getPlaywrightConstructs.js +158 -187
  38. package/dist/common/jwtTokenManager.js +61 -74
  39. package/dist/common/runApi/errors.js +121 -130
  40. package/dist/common/runApi/index.js +231 -217
  41. package/dist/common/runApi/types.js +41 -55
  42. package/dist/common/settingsSchema.js +6 -9
  43. package/dist/common/telemetry.js +16 -27
  44. package/dist/index.js +3 -3
  45. package/dist/runtime/RunError.js +10 -10
  46. package/dist/runtime/downloadDirectory.js +10 -10
  47. package/dist/runtime/enums.d.ts +11 -1
  48. package/dist/runtime/enums.js +12 -12
  49. package/dist/runtime/export.d.ts +202 -1
  50. package/dist/runtime/extendPayload.js +12 -12
  51. package/dist/runtime/extendTimeout.js +20 -19
  52. package/dist/runtime/index.js +1 -1
  53. package/dist/runtime/requestMoreInfo.js +14 -14
  54. package/dist/runtime/runInfo.js +12 -11
  55. package/package.json +2 -3
  56. package/dist/commands/api/run.ts +0 -105
  57. package/dist/commands/auth-sessions/load.ts +0 -30
  58. package/dist/commands/auth-sessions/run-check.ts +0 -51
  59. package/dist/commands/auth-sessions/run-create.ts +0 -91
  60. package/dist/commands/browser/save-state.ts +0 -14
  61. package/dist/commands/browser/start-browser.ts +0 -11
  62. package/dist/commands/build.ts +0 -78
  63. package/dist/commands/common/browserUtils.ts +0 -45
  64. package/dist/commands/common/getDefaultExportFromFile.ts +0 -11
  65. package/dist/commands/common/getFirstLineNumber.ts +0 -96
  66. package/dist/commands/common/sendMessageToClient.ts +0 -3
  67. package/dist/commands/common/utils/fileUtils.ts +0 -23
  68. package/dist/commands/common/utils/settings.ts +0 -22
  69. package/dist/commands/common/utils/unixSocket.ts +0 -38
  70. package/dist/commands/common/utils/webTemplate.ts +0 -22
  71. package/dist/commands/interface/run.ts +0 -156
  72. package/dist/commands/ts-check.ts +0 -50
  73. package/dist/common/Logger/Logger/index.ts +0 -53
  74. package/dist/common/Logger/index.ts +0 -53
  75. package/dist/common/asyncLocalStorage/index.ts +0 -9
  76. package/dist/common/cleanEnvironmentVariables.ts +0 -10
  77. package/dist/common/constants.ts +0 -1
  78. package/dist/common/contextStorageStateHelpers.ts +0 -43
  79. package/dist/common/getPlaywrightConstructs.ts +0 -181
  80. package/dist/common/jwtTokenManager.ts +0 -71
  81. package/dist/common/runApi/errors.ts +0 -154
  82. package/dist/common/runApi/index.ts +0 -253
  83. package/dist/common/runApi/types.ts +0 -43
  84. package/dist/common/settingsSchema.ts +0 -9
  85. package/dist/common/telemetry.ts +0 -23
  86. package/dist/index.ts +0 -4
  87. package/dist/runtime/RunError.ts +0 -12
  88. package/dist/runtime/downloadDirectory.ts +0 -13
  89. package/dist/runtime/enums.ts +0 -12
  90. package/dist/runtime/extendPayload.ts +0 -15
  91. package/dist/runtime/extendTimeout.ts +0 -24
  92. package/dist/runtime/index.ts +0 -6
  93. package/dist/runtime/requestMoreInfo.ts +0 -18
  94. package/dist/runtime/runInfo.ts +0 -15
  95. /package/dist/{common/Logger/Logger/types.ts → runtime/enums.d.js} +0 -0
  96. /package/dist/runtime/{executionHelpers.test.ts → executionHelpers.test.js} +0 -0
  97. /package/dist/{common/Logger/types.ts → runtime/export.d.js} +0 -0
@@ -1,12 +1,10 @@
1
1
  export function cleanEnvironmentVariables() {
2
- Object.keys(process.env)
3
- .filter((i) => {
4
- if (i.toLocaleLowerCase().startsWith("npm")) {
5
- return true;
6
- }
7
- if (i.toLocaleLowerCase().startsWith("fly") && i !== "FLY_ALLOC_ID") {
8
- return true;
9
- }
10
- })
11
- .forEach((i) => delete process.env[i]);
12
- }
2
+ Object.keys(process.env).filter(i => {
3
+ if (i.toLocaleLowerCase().startsWith("npm")) {
4
+ return true;
5
+ }
6
+ if (i.toLocaleLowerCase().startsWith("fly") && i !== "FLY_ALLOC_ID") {
7
+ return true;
8
+ }
9
+ }).forEach(i => delete process.env[i]);
10
+ }
@@ -1 +1 @@
1
- export const AUTH_SESSIONS_FOLDER_NAME = "auth-sessions";
1
+ export const AUTH_SESSIONS_FOLDER_NAME = "auth-sessions";
@@ -1,41 +1,43 @@
1
1
  function sessionStorageToArray(storage) {
2
- const result = [];
3
- for (const key in storage) {
4
- result.push({ name: key, value: storage[key] });
5
- }
6
- return result;
2
+ const result = [];
3
+ for (const key in storage) {
4
+ result.push({
5
+ name: key,
6
+ value: storage[key]
7
+ });
8
+ }
9
+ return result;
7
10
  }
8
11
  export async function getContextStorageState(context) {
9
- const cookiesAndLocalStorage = await context.storageState();
10
- const pages = context.pages();
11
- const pagesSessions = [];
12
- for (const page of pages) {
13
- try {
14
- const [origin, session] = await page.evaluate(() => [
15
- location.origin,
16
- sessionStorage,
17
- ]);
18
- const transformed = sessionStorageToArray(session);
19
- pagesSessions.push({ origin, sessionStorage: transformed });
20
- }
21
- catch (e) {
22
- // ignore
23
- }
24
- }
25
- return {
26
- ...cookiesAndLocalStorage,
27
- sessionStorage: pagesSessions,
28
- };
12
+ const cookiesAndLocalStorage = await context.storageState();
13
+ const pages = context.pages();
14
+ const pagesSessions = [];
15
+ for (const page of pages) {
16
+ try {
17
+ const [origin, session] = await page.evaluate(() => [location.origin, sessionStorage]);
18
+ const transformed = sessionStorageToArray(session);
19
+ pagesSessions.push({
20
+ origin,
21
+ sessionStorage: transformed
22
+ });
23
+ } catch (e) {}
24
+ }
25
+ return {
26
+ ...cookiesAndLocalStorage,
27
+ sessionStorage: pagesSessions
28
+ };
29
29
  }
30
30
  export async function setContextStorageState(context, storage) {
31
- await context.intunedSetStorageState(storage);
32
- const sessionStorage = storage.sessionStorage;
33
- await context.addInitScript((storage) => {
34
- for (const { origin, sessionStorage } of storage) {
35
- if (window.location.origin === origin) {
36
- for (const item of sessionStorage)
37
- window.sessionStorage.setItem(item.name, item.value);
38
- }
39
- }
40
- }, sessionStorage);
41
- }
31
+ await context.intunedSetStorageState(storage);
32
+ const sessionStorage = storage.sessionStorage;
33
+ await context.addInitScript(storage => {
34
+ for (const {
35
+ origin,
36
+ sessionStorage
37
+ } of storage) {
38
+ if (window.location.origin === origin) {
39
+ for (const item of sessionStorage) window.sessionStorage.setItem(item.name, item.value);
40
+ }
41
+ }
42
+ }, sessionStorage);
43
+ }
@@ -1,211 +1,182 @@
1
1
  import * as playwright from "@intuned/playwright-core";
2
2
  import { existsSync, mkdir, mkdtemp, rm, writeFile, readFile } from "fs-extra";
3
- import { setContextStorageState, } from "./contextStorageStateHelpers.js";
3
+ import { setContextStorageState } from "./contextStorageStateHelpers.js";
4
4
  import { join } from "path";
5
5
  import path from "path";
6
6
  import * as fs from "fs-extra";
7
7
  import { getFullPathInProject } from "../commands/common/utils/fileUtils";
8
8
  import waitOn from "wait-on";
9
9
  import { getDownloadDirectoryPath } from "../runtime";
10
+ import { fileURLToPath } from "url";
10
11
  async function createUserDirWithPreferences() {
11
- const playwrightTempDir = await mkdtemp("/tmp/pw-");
12
- const userDir = join(playwrightTempDir, "userdir");
13
- const defaultDir = join(userDir, "Default");
14
- await mkdir(defaultDir, {
12
+ const playwrightTempDir = await mkdtemp("/tmp/pw-");
13
+ const userDir = join(playwrightTempDir, "userdir");
14
+ const defaultDir = join(userDir, "Default");
15
+ await mkdir(defaultDir, {
16
+ recursive: true
17
+ });
18
+ const preferences = {
19
+ plugins: {
20
+ always_open_pdf_externally: true
21
+ }
22
+ };
23
+ await writeFile(join(defaultDir, "Preferences"), JSON.stringify(preferences));
24
+ return userDir;
25
+ }
26
+ export async function getProductionPlaywrightConstructs({
27
+ proxy,
28
+ headless = true,
29
+ storageState,
30
+ downloadsPath
31
+ }) {
32
+ const extraArgs = ["--no-first-run", "--disable-sync", "--disable-translate", "--disable-features=TranslateUI", "--disable-features=NetworkService", "--lang=en"];
33
+ if (headless) {
34
+ extraArgs.push("--headless=new");
35
+ }
36
+ const executablePath = playwright.chromium.executablePath();
37
+ const chromium127Path = executablePath.replace("chromium-1117", "chromium-1124");
38
+ const isChrome127There = existsSync(chromium127Path);
39
+ 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`;
40
+ const userDataDir = await createUserDirWithPreferences();
41
+ const context = await playwright.chromium.launchPersistentContext(userDataDir, {
42
+ headless,
43
+ ignoreDefaultArgs: [...getChromiumLaunchArgsToIgnore(), "--headless"],
44
+ proxy,
45
+ executablePath: isChrome127There ? chromium127Path : executablePath,
46
+ args: extraArgs,
47
+ downloadsPath,
48
+ userAgent
49
+ });
50
+ context.once("close", async () => {
51
+ try {
52
+ await rm(userDataDir, {
15
53
  recursive: true,
54
+ force: true,
55
+ retryDelay: 1000,
56
+ maxRetries: 5
57
+ });
58
+ } catch (error) {
59
+ console.error("Failed to remove user data dir", error);
60
+ }
61
+ });
62
+ if (storageState) {
63
+ await loadSessionToContext({
64
+ context,
65
+ session: storageState
16
66
  });
17
- const preferences = {
18
- plugins: {
19
- always_open_pdf_externally: true,
20
- },
21
- };
22
- await writeFile(join(defaultDir, "Preferences"), JSON.stringify(preferences));
23
- return userDir;
67
+ }
68
+ const assetsFile = path.join(path.dirname(fileURLToPath(import.meta.url)), "./assets/browser_scripts.js");
69
+ await context.addInitScript({
70
+ path: assetsFile
71
+ });
72
+ let page = context.pages().at(0);
73
+ if (page) {
74
+ const scriptString = await readFile(assetsFile, "utf8");
75
+ await page.evaluate(scriptString);
76
+ } else {
77
+ page = await context.newPage();
78
+ }
79
+ return {
80
+ page,
81
+ context
82
+ };
24
83
  }
25
- export async function getProductionPlaywrightConstructs({ proxy, headless = true, storageState, downloadsPath, }) {
26
- const extraArgs = [
27
- "--no-first-run",
28
- "--disable-sync",
29
- "--disable-translate",
30
- "--disable-features=TranslateUI",
31
- "--disable-features=NetworkService",
32
- "--lang=en",
33
- ];
34
- if (headless) {
35
- extraArgs.push("--headless=new");
84
+ 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"];
85
+ export async function getPlaywrightConstructsForMode(mode, cdpAddress, authSession) {
86
+ if (mode == "playwright-standalone") {
87
+ if (!cdpAddress) {
88
+ throw new Error("cdpAddress is required");
36
89
  }
37
- const executablePath = playwright.chromium.executablePath();
38
- // use chromium 127 instead of 125, this depends on the docker image playwright version.
39
- const chromium127Path = executablePath.replace("chromium-1117", "chromium-1124");
40
- const isChrome127There = existsSync(chromium127Path);
41
- 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`;
42
- const userDataDir = await createUserDirWithPreferences();
43
- const context = await playwright.chromium.launchPersistentContext(userDataDir, {
44
- headless,
45
- ignoreDefaultArgs: [...getChromiumLaunchArgsToIgnore(), "--headless"],
46
- proxy,
47
- executablePath: isChrome127There ? chromium127Path : executablePath,
48
- args: extraArgs,
49
- downloadsPath,
50
- userAgent,
51
- });
52
- context.once("close", async () => {
53
- try {
54
- await rm(userDataDir, {
55
- recursive: true,
56
- force: true,
57
- retryDelay: 1000,
58
- maxRetries: 5,
59
- });
60
- }
61
- catch (error) {
62
- console.error("Failed to remove user data dir", error);
63
- }
64
- });
65
- if (storageState) {
66
- await loadSessionToContext({ context, session: storageState });
90
+ const {
91
+ context
92
+ } = await getRemotePlaywrightContext(cdpAddress);
93
+ if (!context) {
94
+ throw new Error("no context found");
67
95
  }
68
- const assetsFile = path.join(path.dirname(import.meta.url), "./assets/browser_scripts.js");
96
+ const assetsFile = path.join(path.dirname(fileURLToPath(import.meta.url)), "./assets/browser_scripts.js");
69
97
  await context.addInitScript({
70
- path: assetsFile,
98
+ path: assetsFile
71
99
  });
72
- let page = context.pages().at(0);
73
- if (page) {
74
- const scriptString = await readFile(assetsFile, "utf8");
75
- await page.evaluate(scriptString);
100
+ const pages = await context.pages();
101
+ let page = null;
102
+ if (pages.length > 0) {
103
+ page = pages[0];
104
+ const scriptString = await fs.readFile(assetsFile, "utf8");
105
+ await page.evaluate(scriptString);
106
+ } else {
107
+ page = await context.newPage();
76
108
  }
77
- else {
78
- page = await context.newPage();
109
+ if (authSession) {
110
+ await loadSessionToContext({
111
+ context,
112
+ session: authSession
113
+ });
79
114
  }
80
115
  return {
81
- page,
82
- context,
116
+ page,
117
+ context
83
118
  };
84
- }
85
- const getChromiumLaunchArgsToIgnore = () => [
86
- "--disable-field-trial-config",
87
- "--disable-background-networking",
88
- "--enable-features=NetworkService,NetworkServiceInProcess",
89
- "--disable-background-timer-throttling",
90
- "--disable-backgrounding-occluded-windows",
91
- "--disable-back-forward-cache",
92
- "--disable-breakpad",
93
- "--disable-client-side-phishing-detection",
94
- "--disable-component-extensions-with-background-pages",
95
- "--disable-component-update",
96
- "--no-default-browser-check",
97
- "--disable-default-apps",
98
- "--disable-dev-shm-usage",
99
- "--disable-extensions",
100
- "--disable-features=ImprovedCookieControls,LazyFrameLoading,GlobalMediaControls,DestroyProfileOnBrowserClose,MediaRouter,DialMediaRouteProvider,AcceptCHFrame,AutoExpandDetailsElement,CertificateTransparencyComponentUpdater,AvoidUnnecessaryBeforeUnloadCheckSync,Translate,TranslateUI",
101
- "--allow-pre-commit-input",
102
- "--disable-hang-monitor",
103
- "--disable-ipc-flooding-protection",
104
- "--disable-prompt-on-repost",
105
- "--disable-renderer-backgrounding",
106
- "--force-color-profile=srgb",
107
- "--metrics-recording-only",
108
- "--no-first-run",
109
- "--enable-automation",
110
- "--password-store=basic",
111
- "--use-mock-keychain",
112
- "--no-service-autorun",
113
- "--export-tagged-pdf",
114
- "--enable-use-zoom-for-dsf=false",
115
- ];
116
- export async function getPlaywrightConstructsForMode(mode, cdpAddress, authSession) {
117
- if (mode == "playwright-standalone") {
118
- if (!cdpAddress) {
119
- throw new Error("cdpAddress is required");
120
- }
121
- const { context } = await getRemotePlaywrightContext(cdpAddress);
122
- if (!context) {
123
- throw new Error("no context found");
124
- }
125
- const assetsFile = path.join(path.dirname(import.meta.url), "./assets/browser_scripts.js");
126
- await context.addInitScript({
127
- path: assetsFile,
128
- });
129
- const pages = await context.pages();
130
- let page = null;
131
- if (pages.length > 0) {
132
- page = pages[0];
133
- const scriptString = await fs.readFile(assetsFile, "utf8");
134
- await page.evaluate(scriptString);
135
- }
136
- else {
137
- page = await context.newPage();
138
- }
139
- if (authSession) {
140
- await loadSessionToContext({ context, session: authSession });
141
- }
142
- return {
143
- page,
144
- context,
145
- };
146
- }
147
- const downloadsPath = getDownloadDirectoryPath();
148
- if (mode === "playwright" || mode === "playwright-headless") {
149
- const productionConstructs = await getProductionPlaywrightConstructs({
150
- headless: mode === "playwright-headless",
151
- downloadsPath,
152
- });
153
- if (authSession) {
154
- await loadSessionToContext({
155
- context: productionConstructs.context,
156
- session: authSession,
157
- });
158
- }
159
- return {
160
- ...productionConstructs,
161
- };
119
+ }
120
+ const downloadsPath = getDownloadDirectoryPath();
121
+ if (mode === "playwright" || mode === "playwright-headless") {
122
+ const productionConstructs = await getProductionPlaywrightConstructs({
123
+ headless: mode === "playwright-headless",
124
+ downloadsPath
125
+ });
126
+ if (authSession) {
127
+ await loadSessionToContext({
128
+ context: productionConstructs.context,
129
+ session: authSession
130
+ });
162
131
  }
163
- throw "invalid mode";
132
+ return {
133
+ ...productionConstructs
134
+ };
135
+ }
136
+ throw "invalid mode";
164
137
  }
165
- export async function loadSessionToContext({ context, session, }) {
166
- let sessionToLoad;
167
- if (session.type === "state") {
168
- sessionToLoad = session.state;
169
- }
170
- else {
171
- const fullPath = getFullPathInProject(session.path);
172
- sessionToLoad = await fs.readJson(fullPath);
173
- }
174
- await setContextStorageState(context, sessionToLoad);
138
+ export async function loadSessionToContext({
139
+ context,
140
+ session
141
+ }) {
142
+ let sessionToLoad;
143
+ if (session.type === "state") {
144
+ sessionToLoad = session.state;
145
+ } else {
146
+ const fullPath = getFullPathInProject(session.path);
147
+ sessionToLoad = await fs.readJson(fullPath);
148
+ }
149
+ await setContextStorageState(context, sessionToLoad);
175
150
  }
176
151
  export async function getRemotePlaywrightContext(cdpAddress) {
177
- const playwright = await import("@intuned/playwright-core");
178
- let browser = null;
179
- if (!cdpAddress) {
180
- throw new Error("cdpAddress is required");
181
- }
182
- const cdpAddressWithoutProtocol = cdpAddress
183
- .replace("http://", "")
184
- .replace("https://", "")
185
- .replace("localhost", "127.0.0.1");
186
- try {
187
- await waitOn({
188
- resources: [`http-get://${cdpAddressWithoutProtocol}/json/version`],
189
- delay: 100,
190
- interval: 100,
191
- timeout: 5000,
192
- tcpTimeout: 1000,
193
- window: 1000,
194
- });
195
- }
196
- catch (error) {
197
- console.error("Failed to connect to the browser");
198
- // 128 is the exit code for SIGINT https://tldp.org/LDP/abs/html/exitcodes.html
199
- // 9 is the SIGKILL signal
200
- process.exit(128 + 9);
201
- }
202
- try {
203
- browser = await playwright.chromium.connectOverCDP(cdpAddress);
204
- }
205
- catch (e) {
206
- console.log(e);
207
- throw new Error("failed to connect to the browser");
208
- }
209
- const context = browser.contexts()[0];
210
- return { browser, context };
211
- }
152
+ const playwright = await import("@intuned/playwright-core");
153
+ let browser = null;
154
+ if (!cdpAddress) {
155
+ throw new Error("cdpAddress is required");
156
+ }
157
+ const cdpAddressWithoutProtocol = cdpAddress.replace("http://", "").replace("https://", "").replace("localhost", "127.0.0.1");
158
+ try {
159
+ await waitOn({
160
+ resources: [`http-get://${cdpAddressWithoutProtocol}/json/version`],
161
+ delay: 100,
162
+ interval: 100,
163
+ timeout: 5000,
164
+ tcpTimeout: 1000,
165
+ window: 1000
166
+ });
167
+ } catch (error) {
168
+ console.error("Failed to connect to the browser");
169
+ process.exit(128 + 9);
170
+ }
171
+ try {
172
+ browser = await playwright.chromium.connectOverCDP(cdpAddress);
173
+ } catch (e) {
174
+ console.log(e);
175
+ throw new Error("failed to connect to the browser");
176
+ }
177
+ const context = browser.contexts()[0];
178
+ return {
179
+ browser,
180
+ context
181
+ };
182
+ }
@@ -1,84 +1,71 @@
1
1
  import fetch from "cross-fetch";
2
2
  import * as jwt from "jsonwebtoken";
3
3
  import { err, ResultAsync } from "neverthrow";
4
- // Manages JWT token with renewal
5
4
  class JwtTokenManager {
6
- constructor(refreshTokenPath) {
7
- this.refreshTokenPath = refreshTokenPath;
8
- this._token = undefined;
5
+ constructor(refreshTokenPath) {
6
+ this.refreshTokenPath = refreshTokenPath;
7
+ this._token = undefined;
8
+ }
9
+ get token() {
10
+ return this._token;
11
+ }
12
+ set token(newToken) {
13
+ if (this._token != newToken) {
14
+ this._token = newToken;
15
+ void this.scheduleTokenRefresh();
9
16
  }
10
- get token() {
11
- return this._token;
12
- }
13
- // When the token is set, the schedule for renewal is issued automatically
14
- // This is currently being set it two places:
15
- // 1. Whenever the runner starts, initializes it from the environment variable (set whenever the api is run from the authoring IDE)
16
- // 2. Whenever a published api is called to run (/api/run/*), it is set to the token received in the run request.
17
- set token(newToken) {
18
- if (this._token != newToken) {
19
- this._token = newToken;
20
- void this.scheduleTokenRefresh();
21
- }
22
- }
23
- get timeToRefresh() {
24
- if (!this._token)
25
- return;
26
- const payload = jwt.decode(this._token);
27
- if (!payload || typeof payload == "string")
28
- return;
29
- const expiry = payload.expiry;
30
- if (!expiry || typeof expiry !== "number")
31
- return;
32
- const timeWindow = 60 * 1000; // 1 minute
33
- const timeToRefresh = expiry - Date.now() - timeWindow;
34
- return Math.max(timeToRefresh, timeWindow);
35
- }
36
- async scheduleTokenRefresh() {
37
- if (process.env.RUN_ENVIRONMENT?.toLowerCase() !== "authoring")
38
- return;
39
- const timeToRefresh = this.timeToRefresh;
40
- if (timeToRefresh === undefined)
41
- return;
42
- if (this.tokenRefreshTimeout)
43
- 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
- if (process.env.RUN_ENVIRONMENT?.toLowerCase() !== "authoring")
55
- return;
56
- const res = await this.fetchWithToken(this.refreshTokenPath, {
57
- method: "GET",
58
- });
59
- if (res.status === 401) {
60
- return err("Unauthorized");
61
- }
62
- const jsonResult = await ResultAsync.fromPromise(res.json(), () => "not json");
63
- if (jsonResult.isErr())
64
- return;
65
- const newToken = jsonResult.value.token;
66
- if (newToken)
67
- this._token = newToken;
68
- }
69
- fetchWithToken(...[input, init]) {
70
- const headers = new Headers(init?.headers);
71
- headers.set("Authorization", `Bearer ${this.token}`);
72
- return fetch(input, {
73
- ...init,
74
- headers,
75
- });
17
+ }
18
+ get timeToRefresh() {
19
+ if (!this._token) return;
20
+ const payload = jwt.decode(this._token);
21
+ if (!payload || typeof payload == "string") return;
22
+ const expiry = payload.expiry;
23
+ if (!expiry || typeof expiry !== "number") return;
24
+ const timeWindow = 60 * 1000;
25
+ const timeToRefresh = expiry - Date.now() - timeWindow;
26
+ return Math.max(timeToRefresh, timeWindow);
27
+ }
28
+ async scheduleTokenRefresh() {
29
+ var _process$env$RUN_ENVI;
30
+ 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;
31
+ const timeToRefresh = this.timeToRefresh;
32
+ if (timeToRefresh === undefined) return;
33
+ if (this.tokenRefreshTimeout) clearTimeout(this.tokenRefreshTimeout);
34
+ this.tokenRefreshTimeout = setTimeout(async () => {
35
+ const result = await this.refreshToken();
36
+ if (result && result.isErr()) {
37
+ console.error(`[Internal Error] ${result.error}`);
38
+ return;
39
+ }
40
+ await this.scheduleTokenRefresh();
41
+ }, timeToRefresh);
42
+ }
43
+ async refreshToken() {
44
+ var _process$env$RUN_ENVI2;
45
+ 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;
46
+ const res = await this.fetchWithToken(this.refreshTokenPath, {
47
+ method: "GET"
48
+ });
49
+ if (res.status === 401) {
50
+ return err("Unauthorized");
76
51
  }
52
+ const jsonResult = await ResultAsync.fromPromise(res.json(), () => "not json");
53
+ if (jsonResult.isErr()) return;
54
+ const newToken = jsonResult.value.token;
55
+ if (newToken) this._token = newToken;
56
+ }
57
+ fetchWithToken(...[input, init]) {
58
+ const headers = new Headers(init === null || init === void 0 ? void 0 : init.headers);
59
+ headers.set("Authorization", `Bearer ${this.token}`);
60
+ return fetch(input, {
61
+ ...init,
62
+ headers
63
+ });
64
+ }
77
65
  }
78
66
  const backendFunctionsPath = `${process.env.FUNCTIONS_DOMAIN}/api/${process.env.INTUNED_WORKSPACE_ID}/functions/${process.env.INTUNED_INTEGRATION_ID}`;
79
67
  export const backendFunctionsTokenManager = new JwtTokenManager(`${backendFunctionsPath}/refreshBackendFunctionsToken`);
80
- backendFunctionsTokenManager.token =
81
- process.env.INTUNED_AUTHORING_SESSION_BACKEND_FUNCTIONS_TOKEN;
68
+ backendFunctionsTokenManager.token = process.env.INTUNED_AUTHORING_SESSION_BACKEND_FUNCTIONS_TOKEN;
82
69
  export function callBackendFunctionWithToken(path, init) {
83
- return backendFunctionsTokenManager.fetchWithToken(`${backendFunctionsPath}/${path}`, init);
84
- }
70
+ return backendFunctionsTokenManager.fetchWithToken(`${backendFunctionsPath}/${path}`, init);
71
+ }