@intuned/runtime-dev 0.1.0-test.10 → 0.1.0-test.12

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 (103) hide show
  1. package/.babelrc +1 -2
  2. package/dist/commands/api/run.js +170 -105
  3. package/dist/commands/api/run.ts +105 -0
  4. package/dist/commands/auth-sessions/load.js +26 -28
  5. package/dist/commands/auth-sessions/load.ts +30 -0
  6. package/dist/commands/auth-sessions/run-check.js +53 -52
  7. package/dist/commands/auth-sessions/run-check.ts +51 -0
  8. package/dist/commands/auth-sessions/run-create.js +96 -91
  9. package/dist/commands/auth-sessions/run-create.ts +91 -0
  10. package/dist/commands/browser/save-state.js +16 -14
  11. package/dist/commands/browser/save-state.ts +14 -0
  12. package/dist/commands/browser/start-browser.js +11 -11
  13. package/dist/commands/browser/start-browser.ts +11 -0
  14. package/dist/commands/build.js +108 -75
  15. package/dist/commands/build.ts +78 -0
  16. package/dist/commands/common/browserUtils.js +51 -53
  17. package/dist/commands/common/browserUtils.ts +45 -0
  18. package/dist/commands/common/getDefaultExportFromFile.js +12 -17
  19. package/dist/commands/common/getDefaultExportFromFile.ts +11 -0
  20. package/dist/commands/common/getFirstLineNumber.js +93 -93
  21. package/dist/commands/common/{getFirstLineNumber.test.js → getFirstLineNumber.test.ts} +46 -51
  22. package/dist/commands/common/getFirstLineNumber.ts +96 -0
  23. package/dist/commands/common/sendMessageToClient.js +4 -9
  24. package/dist/commands/common/sendMessageToClient.ts +3 -0
  25. package/dist/commands/common/utils/fileUtils.js +22 -32
  26. package/dist/commands/common/utils/fileUtils.ts +23 -0
  27. package/dist/commands/common/utils/settings.js +19 -27
  28. package/dist/commands/common/utils/settings.ts +22 -0
  29. package/dist/commands/common/utils/unixSocket.js +43 -43
  30. package/dist/commands/common/utils/unixSocket.ts +38 -0
  31. package/dist/commands/common/utils/webTemplate.js +27 -29
  32. package/dist/commands/common/utils/webTemplate.ts +22 -0
  33. package/dist/commands/interface/run.js +151 -150
  34. package/dist/commands/interface/run.ts +156 -0
  35. package/dist/commands/ts-check.js +49 -49
  36. package/dist/commands/ts-check.ts +50 -0
  37. package/dist/common/Logger/Logger/index.d.ts +1 -1
  38. package/dist/common/Logger/Logger/index.js +42 -55
  39. package/dist/common/Logger/Logger/index.ts +53 -0
  40. package/dist/common/Logger/Logger/types.js +1 -5
  41. package/dist/common/Logger/Logger/types.ts +1 -0
  42. package/dist/common/Logger/index.d.ts +1 -1
  43. package/dist/common/Logger/index.js +42 -55
  44. package/dist/common/Logger/index.ts +53 -0
  45. package/dist/common/Logger/types.js +1 -5
  46. package/dist/common/Logger/types.ts +1 -0
  47. package/dist/common/asyncLocalStorage/index.js +8 -16
  48. package/dist/common/asyncLocalStorage/index.ts +9 -0
  49. package/dist/common/cleanEnvironmentVariables.js +12 -16
  50. package/dist/common/cleanEnvironmentVariables.ts +10 -0
  51. package/dist/common/constants.js +1 -7
  52. package/dist/common/constants.ts +1 -0
  53. package/dist/common/contextStorageStateHelpers.js +38 -47
  54. package/dist/common/contextStorageStateHelpers.ts +43 -0
  55. package/dist/common/getPlaywrightConstructs.d.ts +1 -1
  56. package/dist/common/getPlaywrightConstructs.js +196 -177
  57. package/dist/common/getPlaywrightConstructs.ts +181 -0
  58. package/dist/common/jwtTokenManager.js +79 -76
  59. package/dist/common/jwtTokenManager.ts +71 -0
  60. package/dist/common/runApi/errors.d.ts +1 -1
  61. package/dist/common/runApi/errors.js +150 -159
  62. package/dist/common/runApi/errors.ts +154 -0
  63. package/dist/common/runApi/index.d.ts +4 -4
  64. package/dist/common/runApi/index.js +220 -269
  65. package/dist/common/runApi/index.ts +253 -0
  66. package/dist/common/runApi/types.d.ts +1 -1
  67. package/dist/common/runApi/types.js +56 -49
  68. package/dist/common/runApi/types.ts +43 -0
  69. package/dist/common/settingsSchema.js +10 -15
  70. package/dist/common/settingsSchema.ts +9 -0
  71. package/dist/common/telemetry.js +30 -28
  72. package/dist/common/telemetry.ts +23 -0
  73. package/dist/index.d.ts +4 -4
  74. package/dist/index.js +4 -69
  75. package/dist/index.ts +4 -0
  76. package/dist/runtime/RunError.d.ts +1 -1
  77. package/dist/runtime/RunError.js +11 -18
  78. package/dist/runtime/RunError.ts +12 -0
  79. package/dist/runtime/downloadDirectory.js +13 -19
  80. package/dist/runtime/downloadDirectory.ts +13 -0
  81. package/dist/runtime/enums.d.ts +1 -11
  82. package/dist/runtime/enums.js +12 -18
  83. package/dist/runtime/enums.ts +12 -0
  84. package/dist/runtime/executionHelpers.test.ts +51 -0
  85. package/dist/runtime/export.d.ts +1 -202
  86. package/dist/runtime/extendPayload.d.ts +1 -1
  87. package/dist/runtime/extendPayload.js +15 -21
  88. package/dist/runtime/extendPayload.ts +15 -0
  89. package/dist/runtime/extendTimeout.js +21 -28
  90. package/dist/runtime/extendTimeout.ts +24 -0
  91. package/dist/runtime/index.d.ts +7 -7
  92. package/dist/runtime/index.js +6 -53
  93. package/dist/runtime/index.ts +6 -0
  94. package/dist/runtime/requestMoreInfo.js +16 -23
  95. package/dist/runtime/requestMoreInfo.ts +18 -0
  96. package/dist/runtime/runInfo.d.ts +1 -1
  97. package/dist/runtime/runInfo.js +14 -21
  98. package/dist/runtime/runInfo.ts +15 -0
  99. package/package.json +3 -2
  100. package/tsconfig.json +1 -1
  101. package/dist/runtime/enums.d.js +0 -5
  102. package/dist/runtime/executionHelpers.test.js +0 -53
  103. package/dist/runtime/export.d.js +0 -5
@@ -1,192 +1,211 @@
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("@intuned/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(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
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 && Object.prototype.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; }
1
+ import * as playwright from "@intuned/playwright-core";
2
+ import { existsSync, mkdir, mkdtemp, rm, writeFile, readFile } from "fs-extra";
3
+ import { setContextStorageState, } from "./contextStorageStateHelpers.js";
4
+ import { join } from "path";
5
+ import path from "path";
6
+ import * as fs from "fs-extra";
7
+ import { getFullPathInProject } from "../commands/common/utils/fileUtils";
8
+ import waitOn from "wait-on";
9
+ import { getDownloadDirectoryPath } from "../runtime";
21
10
  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 = (0, _fsExtra.existsSync)(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, {
11
+ const playwrightTempDir = await mkdtemp("/tmp/pw-");
12
+ const userDir = join(playwrightTempDir, "userdir");
13
+ const defaultDir = join(userDir, "Default");
14
+ await mkdir(defaultDir, {
63
15
  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
16
  });
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
- };
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;
93
24
  }
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");
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");
99
36
  }
100
- const {
101
- context
102
- } = await getRemotePlaywrightContext(cdpAddress);
103
- if (!context) {
104
- throw new Error("no context found");
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 });
105
67
  }
106
- const assetsFile = _path.default.join(__dirname, "./assets/browser_scripts.js");
68
+ const assetsFile = path.join(__dirname, "./assets/browser_scripts.js");
107
69
  await context.addInitScript({
108
- path: assetsFile
70
+ path: assetsFile,
109
71
  });
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();
72
+ let page = context.pages().at(0);
73
+ if (page) {
74
+ const scriptString = await readFile(assetsFile, "utf8");
75
+ await page.evaluate(scriptString);
118
76
  }
119
- if (authSession) {
120
- await loadSessionToContext({
121
- context,
122
- session: authSession
123
- });
77
+ else {
78
+ page = await context.newPage();
124
79
  }
125
80
  return {
126
- page,
127
- context
81
+ page,
82
+ context,
128
83
  };
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
- });
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(__dirname, "./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
+ };
141
146
  }
142
- return {
143
- ...productionConstructs
144
- };
145
- }
146
- throw "invalid mode";
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
+ };
162
+ }
163
+ throw "invalid mode";
147
164
  }
148
- async function loadSessionToContext({
149
- context,
150
- session
151
- }) {
152
- let sessionToLoad;
153
- if (session.type === "state") {
154
- sessionToLoad = session.state;
155
- } else {
156
- const fullPath = (0, _fileUtils.getFullPathInProject)(session.path);
157
- sessionToLoad = await fs.readJson(fullPath);
158
- }
159
- await (0, _contextStorageStateHelpers.setContextStorageState)(context, sessionToLoad);
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);
175
+ }
176
+ 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 };
160
211
  }
161
- async function getRemotePlaywrightContext(cdpAddress) {
162
- const playwright = await Promise.resolve(require("@intuned/playwright-core"));
163
- let browser = null;
164
- if (!cdpAddress) {
165
- throw new Error("cdpAddress is required");
166
- }
167
- const cdpAddressWithoutProtocol = cdpAddress.replace("http://", "").replace("https://", "").replace("localhost", "127.0.0.1");
168
- try {
169
- await (0, _waitOn.default)({
170
- resources: [`http-get://${cdpAddressWithoutProtocol}/json/version`],
171
- delay: 100,
172
- interval: 100,
173
- timeout: 5000,
174
- tcpTimeout: 1000,
175
- window: 1000
176
- });
177
- } catch (error) {
178
- console.error("Failed to connect to the browser");
179
- process.exit(128 + 9);
180
- }
181
- try {
182
- browser = await playwright.chromium.connectOverCDP(cdpAddress);
183
- } catch (e) {
184
- console.log(e);
185
- throw new Error("failed to connect to the browser");
186
- }
187
- const context = browser.contexts()[0];
188
- return {
189
- browser,
190
- context
191
- };
192
- }
@@ -0,0 +1,181 @@
1
+ import * as playwright from "@intuned/playwright-core";
2
+ import { existsSync, mkdir, mkdtemp, rm, writeFile, readFile } from "fs-extra";
3
+ import { setContextStorageState } from "./contextStorageStateHelpers.js";
4
+ import { join } from "path";
5
+ import path from "path";
6
+ import * as fs from "fs-extra";
7
+ import { getFullPathInProject } from "../commands/common/utils/fileUtils";
8
+ import waitOn from "wait-on";
9
+ import { getDownloadDirectoryPath } from "../runtime";
10
+ 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, {
15
+ recursive: true
16
+ });
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;
24
+ }
25
+ export async function getProductionPlaywrightConstructs({
26
+ proxy,
27
+ headless = true,
28
+ storageState,
29
+ downloadsPath
30
+ }) {
31
+ const extraArgs = ["--no-first-run", "--disable-sync", "--disable-translate", "--disable-features=TranslateUI", "--disable-features=NetworkService", "--lang=en"];
32
+ if (headless) {
33
+ extraArgs.push("--headless=new");
34
+ }
35
+ const executablePath = playwright.chromium.executablePath();
36
+ const chromium127Path = executablePath.replace("chromium-1117", "chromium-1124");
37
+ const isChrome127There = existsSync(chromium127Path);
38
+ 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`;
39
+ const userDataDir = await createUserDirWithPreferences();
40
+ const context = await playwright.chromium.launchPersistentContext(userDataDir, {
41
+ headless,
42
+ ignoreDefaultArgs: [...getChromiumLaunchArgsToIgnore(), "--headless"],
43
+ proxy,
44
+ executablePath: isChrome127There ? chromium127Path : executablePath,
45
+ args: extraArgs,
46
+ downloadsPath,
47
+ userAgent
48
+ });
49
+ context.once("close", async () => {
50
+ try {
51
+ await rm(userDataDir, {
52
+ recursive: true,
53
+ force: true,
54
+ retryDelay: 1000,
55
+ maxRetries: 5
56
+ });
57
+ } catch (error) {
58
+ console.error("Failed to remove user data dir", error);
59
+ }
60
+ });
61
+ if (storageState) {
62
+ await loadSessionToContext({
63
+ context,
64
+ session: storageState
65
+ });
66
+ }
67
+ const assetsFile = path.join(__dirname, "./assets/browser_scripts.js");
68
+ await context.addInitScript({
69
+ path: assetsFile
70
+ });
71
+ let page = context.pages().at(0);
72
+ if (page) {
73
+ const scriptString = await readFile(assetsFile, "utf8");
74
+ await page.evaluate(scriptString);
75
+ } else {
76
+ page = await context.newPage();
77
+ }
78
+ return {
79
+ page,
80
+ context
81
+ };
82
+ }
83
+ 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"];
84
+ export async function getPlaywrightConstructsForMode(mode, cdpAddress, authSession) {
85
+ if (mode == "playwright-standalone") {
86
+ if (!cdpAddress) {
87
+ throw new Error("cdpAddress is required");
88
+ }
89
+ const {
90
+ context
91
+ } = await getRemotePlaywrightContext(cdpAddress);
92
+ if (!context) {
93
+ throw new Error("no context found");
94
+ }
95
+ const assetsFile = path.join(__dirname, "./assets/browser_scripts.js");
96
+ await context.addInitScript({
97
+ path: assetsFile
98
+ });
99
+ const pages = await context.pages();
100
+ let page = null;
101
+ if (pages.length > 0) {
102
+ page = pages[0];
103
+ const scriptString = await fs.readFile(assetsFile, "utf8");
104
+ await page.evaluate(scriptString);
105
+ } else {
106
+ page = await context.newPage();
107
+ }
108
+ if (authSession) {
109
+ await loadSessionToContext({
110
+ context,
111
+ session: authSession
112
+ });
113
+ }
114
+ return {
115
+ page,
116
+ context
117
+ };
118
+ }
119
+ const downloadsPath = getDownloadDirectoryPath();
120
+ if (mode === "playwright" || mode === "playwright-headless") {
121
+ const productionConstructs = await getProductionPlaywrightConstructs({
122
+ headless: mode === "playwright-headless",
123
+ downloadsPath
124
+ });
125
+ if (authSession) {
126
+ await loadSessionToContext({
127
+ context: productionConstructs.context,
128
+ session: authSession
129
+ });
130
+ }
131
+ return {
132
+ ...productionConstructs
133
+ };
134
+ }
135
+ throw "invalid mode";
136
+ }
137
+ export async function loadSessionToContext({
138
+ context,
139
+ session
140
+ }) {
141
+ let sessionToLoad;
142
+ if (session.type === "state") {
143
+ sessionToLoad = session.state;
144
+ } else {
145
+ const fullPath = getFullPathInProject(session.path);
146
+ sessionToLoad = await fs.readJson(fullPath);
147
+ }
148
+ await setContextStorageState(context, sessionToLoad);
149
+ }
150
+ export async function getRemotePlaywrightContext(cdpAddress) {
151
+ const playwright = await import("@intuned/playwright-core");
152
+ let browser = null;
153
+ if (!cdpAddress) {
154
+ throw new Error("cdpAddress is required");
155
+ }
156
+ const cdpAddressWithoutProtocol = cdpAddress.replace("http://", "").replace("https://", "").replace("localhost", "127.0.0.1");
157
+ try {
158
+ await waitOn({
159
+ resources: [`http-get://${cdpAddressWithoutProtocol}/json/version`],
160
+ delay: 100,
161
+ interval: 100,
162
+ timeout: 5000,
163
+ tcpTimeout: 1000,
164
+ window: 1000
165
+ });
166
+ } catch (error) {
167
+ console.error("Failed to connect to the browser");
168
+ process.exit(128 + 9);
169
+ }
170
+ try {
171
+ browser = await playwright.chromium.connectOverCDP(cdpAddress);
172
+ } catch (e) {
173
+ console.log(e);
174
+ throw new Error("failed to connect to the browser");
175
+ }
176
+ const context = browser.contexts()[0];
177
+ return {
178
+ browser,
179
+ context
180
+ };
181
+ }