@intuned/runtime-dev 1.3.18-interface.2 → 1.3.18-interface.21

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 (225) hide show
  1. package/.babelrc +6 -0
  2. package/.claude/settings.local.json +7 -0
  3. package/InterfaceTemplate/__utils.ts +3 -1
  4. package/dist/commands/api/run.d.ts +6 -0
  5. package/dist/commands/api/run.js +119 -0
  6. package/dist/commands/auth-sessions/load.d.ts +2 -0
  7. package/dist/commands/auth-sessions/load.js +35 -0
  8. package/dist/commands/auth-sessions/run-check.d.ts +2 -0
  9. package/dist/commands/auth-sessions/run-check.js +74 -0
  10. package/dist/commands/auth-sessions/run-create.d.ts +2 -0
  11. package/dist/commands/auth-sessions/run-create.js +78 -0
  12. package/dist/commands/browser/save-state.d.ts +2 -0
  13. package/dist/commands/browser/save-state.js +17 -0
  14. package/dist/commands/browser/start-browser.d.ts +2 -0
  15. package/dist/commands/browser/start-browser.js +14 -0
  16. package/dist/commands/build.d.ts +1 -0
  17. package/dist/commands/build.js +83 -0
  18. package/dist/commands/common/browserUtils.d.ts +14 -0
  19. package/dist/commands/common/browserUtils.js +57 -0
  20. package/dist/commands/common/getFirstLineNumber.d.ts +9 -0
  21. package/dist/commands/common/getFirstLineNumber.js +101 -0
  22. package/dist/commands/common/getFirstLineNumber.test.js +227 -0
  23. package/dist/commands/common/projectExclusions.d.ts +2 -0
  24. package/dist/commands/common/projectExclusions.js +8 -0
  25. package/dist/commands/common/sendMessageToClient.d.ts +1 -0
  26. package/dist/commands/common/sendMessageToClient.js +10 -0
  27. package/dist/commands/common/tsNodeImport.d.ts +2 -0
  28. package/dist/commands/common/tsNodeImport.js +42 -0
  29. package/dist/commands/common/utils/fileUtils.d.ts +6 -0
  30. package/dist/commands/common/utils/fileUtils.js +32 -0
  31. package/dist/commands/common/utils/interfaceClient.d.ts +31 -0
  32. package/dist/commands/common/utils/interfaceClient.js +98 -0
  33. package/dist/commands/common/utils/settings.d.ts +2 -0
  34. package/dist/commands/common/utils/settings.js +31 -0
  35. package/dist/commands/common/utils/template.d.ts +2 -0
  36. package/dist/commands/common/utils/template.js +30 -0
  37. package/dist/commands/get-headless-user-agent.d.ts +1 -0
  38. package/dist/commands/get-headless-user-agent.js +18 -0
  39. package/dist/commands/interface/run.d.ts +1 -0
  40. package/dist/commands/interface/run.js +189 -0
  41. package/dist/commands/intuned-cli/commands/attempt.command.d.ts +1 -0
  42. package/dist/commands/intuned-cli/commands/attempt.command.js +8 -0
  43. package/dist/commands/intuned-cli/commands/attempt_api.command.d.ts +1 -0
  44. package/dist/commands/intuned-cli/commands/attempt_api.command.js +30 -0
  45. package/dist/commands/intuned-cli/commands/attempt_authsession.command.d.ts +1 -0
  46. package/dist/commands/intuned-cli/commands/attempt_authsession.command.js +8 -0
  47. package/dist/commands/intuned-cli/commands/attempt_authsession_check.command.d.ts +1 -0
  48. package/dist/commands/intuned-cli/commands/attempt_authsession_check.command.js +19 -0
  49. package/dist/commands/intuned-cli/commands/attempt_authsession_create.command.d.ts +1 -0
  50. package/dist/commands/intuned-cli/commands/attempt_authsession_create.command.js +24 -0
  51. package/dist/commands/intuned-cli/commands/authsession.command.d.ts +1 -0
  52. package/dist/commands/intuned-cli/commands/authsession.command.js +8 -0
  53. package/dist/commands/intuned-cli/commands/authsession_record.command.d.ts +1 -0
  54. package/dist/commands/intuned-cli/commands/authsession_record.command.js +32 -0
  55. package/dist/commands/intuned-cli/commands/authsession_scaffold.command.d.ts +1 -0
  56. package/dist/commands/intuned-cli/commands/authsession_scaffold.command.js +16 -0
  57. package/dist/commands/intuned-cli/commands/build.command.d.ts +1 -0
  58. package/dist/commands/intuned-cli/commands/build.command.js +12 -0
  59. package/dist/commands/intuned-cli/commands/command.d.ts +2 -0
  60. package/dist/commands/intuned-cli/commands/command.js +9 -0
  61. package/dist/commands/intuned-cli/commands/deploy.command.d.ts +1 -0
  62. package/dist/commands/intuned-cli/commands/deploy.command.js +42 -0
  63. package/dist/commands/intuned-cli/commands/index.d.ts +18 -0
  64. package/dist/commands/intuned-cli/commands/index.js +203 -0
  65. package/dist/commands/intuned-cli/commands/provision.command.d.ts +13 -0
  66. package/dist/commands/intuned-cli/commands/provision.command.js +50 -0
  67. package/dist/commands/intuned-cli/commands/run.command.d.ts +1 -0
  68. package/dist/commands/intuned-cli/commands/run.command.js +8 -0
  69. package/dist/commands/intuned-cli/commands/run_api.command.d.ts +1 -0
  70. package/dist/commands/intuned-cli/commands/run_api.command.js +46 -0
  71. package/dist/commands/intuned-cli/commands/run_authsession.command.d.ts +35 -0
  72. package/dist/commands/intuned-cli/commands/run_authsession.command.js +17 -0
  73. package/dist/commands/intuned-cli/commands/run_authsession_create.command.d.ts +1 -0
  74. package/dist/commands/intuned-cli/commands/run_authsession_create.command.js +35 -0
  75. package/dist/commands/intuned-cli/commands/run_authsession_update.command.d.ts +1 -0
  76. package/dist/commands/intuned-cli/commands/run_authsession_update.command.js +35 -0
  77. package/dist/commands/intuned-cli/commands/run_authsession_validate.command.d.ts +1 -0
  78. package/dist/commands/intuned-cli/commands/run_authsession_validate.command.js +33 -0
  79. package/dist/commands/intuned-cli/commands/types.d.ts +39 -0
  80. package/dist/commands/intuned-cli/commands/types.js +33 -0
  81. package/dist/commands/intuned-cli/constants/index.d.ts +17 -0
  82. package/dist/commands/intuned-cli/constants/index.js +25 -0
  83. package/dist/commands/intuned-cli/controller/__test__/api.test.js +399 -0
  84. package/dist/commands/intuned-cli/controller/__test__/authSession.test.js +1061 -0
  85. package/dist/commands/intuned-cli/controller/api.d.ts +42 -0
  86. package/dist/commands/intuned-cli/controller/api.js +194 -0
  87. package/dist/commands/intuned-cli/controller/authSession.d.ts +209 -0
  88. package/dist/commands/intuned-cli/controller/authSession.js +425 -0
  89. package/dist/commands/intuned-cli/controller/build.d.ts +1 -0
  90. package/dist/commands/intuned-cli/controller/build.js +35 -0
  91. package/dist/commands/intuned-cli/controller/deploy.d.ts +5 -0
  92. package/dist/commands/intuned-cli/controller/deploy.js +317 -0
  93. package/dist/commands/intuned-cli/controller/index.d.ts +1 -0
  94. package/dist/commands/intuned-cli/controller/index.js +45 -0
  95. package/dist/commands/intuned-cli/controller/provision.d.ts +21 -0
  96. package/dist/commands/intuned-cli/controller/provision.js +299 -0
  97. package/dist/commands/intuned-cli/controller/scaffold.d.ts +1 -0
  98. package/dist/commands/intuned-cli/controller/scaffold.js +77 -0
  99. package/dist/commands/intuned-cli/helpers/__test__/browser.test.js +152 -0
  100. package/dist/commands/intuned-cli/helpers/__test__/tracing.test.js +41 -0
  101. package/dist/commands/intuned-cli/helpers/api.d.ts +3 -0
  102. package/dist/commands/intuned-cli/helpers/api.js +16 -0
  103. package/dist/commands/intuned-cli/helpers/auth.d.ts +46 -0
  104. package/dist/commands/intuned-cli/helpers/auth.js +147 -0
  105. package/dist/commands/intuned-cli/helpers/backend.d.ts +8 -0
  106. package/dist/commands/intuned-cli/helpers/backend.js +35 -0
  107. package/dist/commands/intuned-cli/helpers/browser.d.ts +14 -0
  108. package/dist/commands/intuned-cli/helpers/browser.js +93 -0
  109. package/dist/commands/intuned-cli/helpers/context.d.ts +3 -0
  110. package/dist/commands/intuned-cli/helpers/context.js +33 -0
  111. package/dist/commands/intuned-cli/helpers/errors.d.ts +16 -0
  112. package/dist/commands/intuned-cli/helpers/errors.js +44 -0
  113. package/dist/commands/intuned-cli/helpers/index.d.ts +12 -0
  114. package/dist/commands/intuned-cli/helpers/index.js +137 -0
  115. package/dist/commands/intuned-cli/helpers/intunedJson.d.ts +39 -0
  116. package/dist/commands/intuned-cli/helpers/intunedJson.js +20 -0
  117. package/dist/commands/intuned-cli/helpers/prompts.d.ts +3 -0
  118. package/dist/commands/intuned-cli/helpers/prompts.js +71 -0
  119. package/dist/commands/intuned-cli/helpers/proxy.d.ts +5 -0
  120. package/dist/commands/intuned-cli/helpers/proxy.js +23 -0
  121. package/dist/commands/intuned-cli/helpers/terminal.d.ts +5 -0
  122. package/dist/commands/intuned-cli/helpers/terminal.js +13 -0
  123. package/dist/commands/intuned-cli/helpers/timeout.d.ts +1 -0
  124. package/dist/commands/intuned-cli/helpers/timeout.js +23 -0
  125. package/dist/commands/intuned-cli/helpers/traces.d.ts +2 -0
  126. package/dist/commands/intuned-cli/helpers/traces.js +32 -0
  127. package/dist/commands/intuned-cli/helpers/validation.d.ts +2 -0
  128. package/dist/commands/intuned-cli/helpers/validation.js +14 -0
  129. package/dist/commands/intuned-cli/helpers/wrapper.d.ts +2 -0
  130. package/dist/commands/intuned-cli/helpers/wrapper.js +76 -0
  131. package/dist/commands/intuned-cli/index.d.ts +1 -0
  132. package/dist/commands/intuned-cli/index.js +16 -0
  133. package/dist/commands/intuned-cli/main.d.ts +1 -0
  134. package/dist/commands/intuned-cli/main.js +35 -0
  135. package/dist/commands/intuned-cli/types.d.ts +70 -0
  136. package/dist/commands/intuned-cli/types.js +22 -0
  137. package/dist/commands/ts-check.d.ts +2 -0
  138. package/dist/commands/ts-check.js +55 -0
  139. package/dist/common/Logger/Logger/index.d.ts +12 -0
  140. package/dist/common/Logger/Logger/index.js +60 -0
  141. package/dist/common/Logger/Logger/types.d.ts +8 -0
  142. package/dist/common/Logger/Logger/types.js +5 -0
  143. package/dist/common/Logger/index.d.ts +12 -0
  144. package/dist/common/Logger/index.js +60 -0
  145. package/dist/common/Logger/types.d.ts +8 -0
  146. package/dist/common/Logger/types.js +5 -0
  147. package/dist/common/assets/browser_scripts.js +2580 -0
  148. package/dist/common/asyncLocalStorage/index.d.ts +16 -0
  149. package/dist/common/asyncLocalStorage/index.js +17 -0
  150. package/dist/common/backendFunctions/getAuthSessionParameters.d.ts +1 -0
  151. package/dist/common/backendFunctions/getAuthSessionParameters.js +38 -0
  152. package/dist/common/binStartupScript.d.ts +1 -0
  153. package/dist/common/binStartupScript.js +36 -0
  154. package/dist/common/browserTabs.d.ts +72 -0
  155. package/dist/common/browserTabs.js +74 -0
  156. package/dist/common/cleanEnvironmentVariables.d.ts +1 -0
  157. package/dist/common/cleanEnvironmentVariables.js +16 -0
  158. package/dist/common/constants.d.ts +11 -0
  159. package/dist/common/constants.js +17 -0
  160. package/dist/common/contextStorageStateHelpers.d.ts +22 -0
  161. package/dist/common/contextStorageStateHelpers.js +84 -0
  162. package/dist/common/extension/extensionsHelpers.d.ts +11 -0
  163. package/dist/common/extension/extensionsHelpers.js +147 -0
  164. package/dist/common/extension/intunedExtensionServer.d.ts +24 -0
  165. package/dist/common/extension/intunedExtensionServer.js +178 -0
  166. package/dist/common/extension/types.d.ts +219 -0
  167. package/dist/common/extension/types.js +51 -0
  168. package/dist/common/formatZodError.d.ts +2 -0
  169. package/dist/common/formatZodError.js +18 -0
  170. package/dist/common/intunedJson.d.ts +229 -0
  171. package/dist/common/intunedJson.js +132 -0
  172. package/dist/common/jwtTokenManager.d.ts +17 -0
  173. package/dist/common/jwtTokenManager.js +113 -0
  174. package/dist/common/launchBrowser.d.ts +34 -0
  175. package/dist/common/launchBrowser.js +247 -0
  176. package/dist/common/playwrightContext.d.ts +29 -0
  177. package/dist/common/playwrightContext.js +148 -0
  178. package/dist/common/runApi/importUsingImportFunction.d.ts +7 -0
  179. package/dist/common/runApi/importUsingImportFunction.js +46 -0
  180. package/dist/common/runApi/index.d.ts +8 -0
  181. package/dist/common/runApi/index.js +177 -0
  182. package/dist/common/settingsSchema.d.ts +537 -0
  183. package/dist/common/settingsSchema.js +57 -0
  184. package/dist/common/setupContextHook.d.ts +16 -0
  185. package/dist/common/setupContextHook.js +22 -0
  186. package/dist/common/telemetry.d.ts +3 -0
  187. package/dist/common/telemetry.js +31 -0
  188. package/dist/index.d.ts +4 -0
  189. package/dist/index.js +117 -0
  190. package/dist/runtime/RunError.d.ts +5 -0
  191. package/dist/runtime/RunError.js +19 -0
  192. package/dist/runtime/attemptStore.d.ts +2 -0
  193. package/dist/runtime/attemptStore.js +23 -0
  194. package/dist/runtime/captcha.d.ts +15 -0
  195. package/dist/runtime/captcha.js +191 -0
  196. package/dist/runtime/captcha.test.js +821 -0
  197. package/dist/runtime/downloadDirectory.d.ts +1 -0
  198. package/dist/runtime/downloadDirectory.js +19 -0
  199. package/dist/runtime/enums.d.js +5 -0
  200. package/dist/runtime/enums.d.ts +11 -0
  201. package/dist/runtime/enums.js +18 -0
  202. package/dist/runtime/executionHelpers.test.js +52 -0
  203. package/dist/runtime/export.d.js +5 -0
  204. package/dist/runtime/export.d.ts +284 -0
  205. package/dist/runtime/extendPayload.d.ts +2 -0
  206. package/dist/runtime/extendPayload.js +21 -0
  207. package/dist/runtime/extendTimeout.d.ts +1 -0
  208. package/dist/runtime/extendTimeout.js +23 -0
  209. package/dist/runtime/getAiGatewayConfig.d.ts +10 -0
  210. package/dist/runtime/getAiGatewayConfig.js +16 -0
  211. package/dist/runtime/getAuthSessionParameters.d.ts +1 -0
  212. package/dist/runtime/getAuthSessionParameters.js +20 -0
  213. package/dist/runtime/index.d.ts +10 -0
  214. package/dist/runtime/index.js +111 -0
  215. package/dist/runtime/persistentStore.d.ts +2 -0
  216. package/dist/runtime/persistentStore.js +37 -0
  217. package/dist/runtime/persistentStore.test.js +101 -0
  218. package/dist/runtime/runInfo.d.ts +2 -0
  219. package/dist/runtime/runInfo.js +21 -0
  220. package/dist/vendor/runtime-interface.d.ts +1 -0
  221. package/dist/vendor/runtime-interface.js +479 -0
  222. package/package.json +8 -3
  223. package/tsup.config.ts +12 -0
  224. package/WebTemplate.zip +0 -0
  225. package/api/sample.ts +0 -4
@@ -0,0 +1,247 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.getBrowserExecutablePath = getBrowserExecutablePath;
7
+ exports.getCdpWebSocketUrl = getCdpWebSocketUrl;
8
+ exports.getHeadlessUserAgent = getHeadlessUserAgent;
9
+ exports.getLocalCdpAddress = getLocalCdpAddress;
10
+ exports.launchBrowser = launchBrowser;
11
+ exports.launchChromium = launchChromium;
12
+ var playwright = _interopRequireWildcard(require("playwright"));
13
+ var _fsExtra = _interopRequireWildcard(require("fs-extra"));
14
+ var fs = _fsExtra;
15
+ var _path = require("path");
16
+ var _waitOn = _interopRequireDefault(require("wait-on"));
17
+ var _child_process = require("child_process");
18
+ var _extensionsHelpers = require("./extension/extensionsHelpers");
19
+ var _intunedExtensionServer = require("./extension/intunedExtensionServer");
20
+ var _util = require("util");
21
+ var _neverthrow = require("neverthrow");
22
+ var _zod = require("zod");
23
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
24
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
25
+ const execAsync = (0, _util.promisify)(_child_process.exec);
26
+ async function createUserDirWithPreferences() {
27
+ const playwrightTempDir = await (0, _fsExtra.mkdtemp)("/tmp/pw-");
28
+ const userDir = (0, _path.join)(playwrightTempDir, "userdir");
29
+ const defaultDir = (0, _path.join)(userDir, "Default");
30
+ await (0, _fsExtra.mkdir)(defaultDir, {
31
+ recursive: true
32
+ });
33
+ const preferences = {
34
+ plugins: {
35
+ always_open_pdf_externally: true
36
+ }
37
+ };
38
+ await (0, _fsExtra.writeFile)((0, _path.join)(defaultDir, "Preferences"), JSON.stringify(preferences));
39
+ return userDir;
40
+ }
41
+ async function launchChromium(options) {
42
+ if ("cdpAddress" in options) {
43
+ if (await (0, _extensionsHelpers.isIntunedExtensionEnabled)()) {
44
+ await (0, _intunedExtensionServer.setupIntunedExtensionServer)();
45
+ }
46
+ const browser = await playwright.chromium.connectOverCDP(options.cdpAddress);
47
+ if (browser.contexts().length === 0) {
48
+ throw new Error("No browser contexts found in the connected browser");
49
+ }
50
+ const context = browser.contexts()[0];
51
+ let page = context.pages().at(0) ?? (await context.newPage());
52
+ const targetId = options.cdpTargetId;
53
+ if (targetId) {
54
+ for (const p of context.pages()) {
55
+ let cdp = null;
56
+ try {
57
+ cdp = await context.newCDPSession(p);
58
+ const result = await cdp.send("Target.getTargetInfo");
59
+ if (result.targetInfo.targetId === targetId) {
60
+ page = p;
61
+ break;
62
+ }
63
+ } catch (error) {} finally {
64
+ await cdp?.detach();
65
+ }
66
+ }
67
+ }
68
+ return {
69
+ page,
70
+ context
71
+ };
72
+ }
73
+ const {
74
+ headless,
75
+ appModeInitialUrl,
76
+ cdpPort,
77
+ proxy,
78
+ downloadsPath
79
+ } = options;
80
+ let {
81
+ executablePath
82
+ } = options;
83
+ const defaultArgsToIgnore = ["--disable-extensions", "--disable-component-extensions-with-background-pages", "--disable-background-networking", "--disable-backgrounding-occluded-windows", "--disable-background-timer-throttling"];
84
+ const extraArgs = [];
85
+ const userDataDir = await createUserDirWithPreferences();
86
+ if ((0, _extensionsHelpers.isIntunedExtensionLoaded)()) {
87
+ const extensionsList = (0, _extensionsHelpers.buildExtensionsList)();
88
+ const extensions = extensionsList.join(",");
89
+ extraArgs.push(`--disable-extensions-except=${extensions}`);
90
+ extraArgs.push(`--load-extension=${extensions}`);
91
+ }
92
+ if (await (0, _extensionsHelpers.isIntunedExtensionEnabled)()) {
93
+ await (0, _extensionsHelpers.setupIntunedExtension)();
94
+ if (proxy) {
95
+ extraArgs.push('--proxy-bypass-list="<-loopback>"');
96
+ }
97
+ }
98
+ if (cdpPort) {
99
+ extraArgs.push(`--remote-debugging-port=${cdpPort}`);
100
+ }
101
+ if (headless) {
102
+ defaultArgsToIgnore.push("--headless=old");
103
+ extraArgs.push("--headless=new");
104
+ }
105
+ if (appModeInitialUrl) {
106
+ extraArgs.push(`--app=${appModeInitialUrl}`);
107
+ }
108
+ if (executablePath) {
109
+ executablePath = await fs.realpath(executablePath);
110
+ if (!(await fs.exists(executablePath))) {
111
+ console.log(`Warning: Executable path ${executablePath} does not exist. Falling back to default.`);
112
+ executablePath = undefined;
113
+ }
114
+ }
115
+ const viewport = null;
116
+ const userAgent = process.env.__PLAYWRIGHT_USER_AGENT_OVERRIDE ?? (await getHeadlessUserAgent({
117
+ executablePath
118
+ }));
119
+ const context = await playwright.chromium.launchPersistentContext(userDataDir, {
120
+ userAgent,
121
+ executablePath,
122
+ headless,
123
+ viewport,
124
+ proxy,
125
+ downloadsPath,
126
+ args: extraArgs,
127
+ ignoreDefaultArgs: defaultArgsToIgnore
128
+ });
129
+ context.once("close", async () => {
130
+ try {
131
+ await (0, _fsExtra.rm)(userDataDir, {
132
+ recursive: true,
133
+ force: true,
134
+ retryDelay: 1000,
135
+ maxRetries: 5
136
+ });
137
+ if (await (0, _extensionsHelpers.isIntunedExtensionEnabled)()) {
138
+ await (0, _intunedExtensionServer.cleanIntunedExtensionServer)();
139
+ }
140
+ } catch (error) {
141
+ console.error("Failed to remove user data dir", error);
142
+ }
143
+ });
144
+ if (cdpPort) {
145
+ const createdCdpAddress = getLocalCdpAddress(cdpPort);
146
+ await waitOnCdpAddress(createdCdpAddress);
147
+ }
148
+ const page = context.pages().at(0) ?? (await context.newPage());
149
+ if (await (0, _extensionsHelpers.isIntunedExtensionEnabled)()) {
150
+ await (0, _extensionsHelpers.getIntunedExtensionWorker)(context);
151
+ }
152
+ return {
153
+ page,
154
+ context
155
+ };
156
+ }
157
+ async function getBrowserExecutablePath() {
158
+ const browserType = getBrowserType();
159
+ if (browserType === "brave") {
160
+ return await getBraveExecutablePath();
161
+ }
162
+ }
163
+ async function launchBrowser(options) {
164
+ if ("cdpAddress" in options) {
165
+ return launchChromium(options);
166
+ }
167
+ return launchChromium({
168
+ ...options,
169
+ executablePath: await getBrowserExecutablePath()
170
+ });
171
+ }
172
+ function getBrowserType() {
173
+ if (process.env.BROWSER_TYPE === "brave") {
174
+ return "brave";
175
+ }
176
+ return "chromium";
177
+ }
178
+ async function getBraveExecutablePath() {
179
+ const {
180
+ stdout
181
+ } = await execAsync("which brave-browser-stable");
182
+ const bravePath = stdout.trim();
183
+ if (bravePath.length === 0) {
184
+ throw new Error("Brave browser not found");
185
+ }
186
+ return bravePath;
187
+ }
188
+ function getLocalCdpAddress(port) {
189
+ return `http://localhost:${port}`;
190
+ }
191
+ async function getCdpWebSocketUrl(cdpAddress) {
192
+ let response;
193
+ try {
194
+ response = await fetch(`${cdpAddress}/json/version`);
195
+ } catch (error) {
196
+ return (0, _neverthrow.err)(`Failed to fetch CDP version from ${cdpAddress}: ${error instanceof Error ? error.message : String(error)}`);
197
+ }
198
+ if (!response.ok) {
199
+ return (0, _neverthrow.err)(`Failed to get CDP WebSocket URL from ${cdpAddress}: ${response.status} ${response.statusText}`);
200
+ }
201
+ let data;
202
+ try {
203
+ data = await response.json();
204
+ } catch (error) {
205
+ return (0, _neverthrow.err)(`Invalid CDP version response from ${cdpAddress}: ${error instanceof Error ? error.message : String(error)}`);
206
+ }
207
+ const cdpJsonVersionResponseSchema = _zod.z.object({
208
+ webSocketDebuggerUrl: _zod.z.string().url()
209
+ });
210
+ const parseResult = cdpJsonVersionResponseSchema.safeParse(data);
211
+ if (!parseResult.success) {
212
+ return (0, _neverthrow.err)(`Invalid CDP version response from ${cdpAddress}: ${JSON.stringify(parseResult.error.format())}`);
213
+ }
214
+ return (0, _neverthrow.ok)(parseResult.data.webSocketDebuggerUrl);
215
+ }
216
+ async function waitOnCdpAddress(cdpAddress) {
217
+ const cdpAddressWithoutProtocol = cdpAddress.replace("http://", "").replace("https://", "").replace("localhost", "127.0.0.1");
218
+ await (0, _waitOn.default)({
219
+ resources: [`http-get://${cdpAddressWithoutProtocol}/json/version`],
220
+ delay: 100,
221
+ interval: 100,
222
+ timeout: 5000,
223
+ tcpTimeout: 1000,
224
+ window: 1000
225
+ });
226
+ }
227
+ async function getHeadlessUserAgent({
228
+ executablePath,
229
+ args,
230
+ ignoreDefaultArgs
231
+ }) {
232
+ const browser = await playwright.chromium.launch({
233
+ headless: true,
234
+ executablePath,
235
+ args,
236
+ ignoreDefaultArgs
237
+ });
238
+ const context = await browser.newContext();
239
+ const page = await context.newPage();
240
+ let userAgent = await page.evaluate(() => navigator.userAgent);
241
+ await browser.close();
242
+ if (!userAgent || typeof userAgent !== "string") {
243
+ return undefined;
244
+ }
245
+ userAgent = userAgent.replace("HeadlessChrome", "Chrome");
246
+ return userAgent;
247
+ }
@@ -0,0 +1,29 @@
1
+ import type * as playwright from "playwright";
2
+ import { Err, Ok } from "neverthrow";
3
+ import { type Proxy } from "./launchBrowser";
4
+ import { ImportFunction, RunAutomationError, RunApiSession } from "@intuned/runtime-interface";
5
+ type WithPlaywrightContextParameters = {
6
+ importFunction: ImportFunction;
7
+ apiName: string;
8
+ apiParameters: any;
9
+ } | {
10
+ importFunction?: undefined;
11
+ apiName?: undefined;
12
+ apiParameters?: undefined;
13
+ };
14
+ type WithPlaywrightContextWrappedFunctionReturn<R> = Ok<R, any> | Err<any, RunAutomationError>;
15
+ export type WithPlaywrightContextWrappedFunction<R> = (context: playwright.BrowserContext, page: playwright.Page) => Promise<WithPlaywrightContextWrappedFunctionReturn<R>>;
16
+ export declare function withPlaywrightContext<R>(options: {
17
+ proxy?: Proxy;
18
+ headless: boolean;
19
+ downloadsPath: string;
20
+ } & WithPlaywrightContextParameters, fn: WithPlaywrightContextWrappedFunction<R>): Promise<Ok<R, any> | Err<any, RunAutomationError>>;
21
+ export declare function withPlaywrightContext<R>(options: {
22
+ cdpAddress: string;
23
+ cdpTargetId?: string;
24
+ } & WithPlaywrightContextParameters, fn: WithPlaywrightContextWrappedFunction<R>): Promise<Ok<R, any> | Err<any, RunAutomationError>>;
25
+ export declare function loadSessionToContext({ context, session, }: {
26
+ context: playwright.BrowserContext;
27
+ session: RunApiSession;
28
+ }): Promise<void>;
29
+ export {};
@@ -0,0 +1,148 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.loadSessionToContext = loadSessionToContext;
7
+ exports.withPlaywrightContext = withPlaywrightContext;
8
+ var _contextStorageStateHelpers = require("./contextStorageStateHelpers");
9
+ var fs = _interopRequireWildcard(require("fs-extra"));
10
+ var _fileUtils = require("../commands/common/utils/fileUtils");
11
+ var _neverthrow = require("neverthrow");
12
+ var _setupContextHook = require("./setupContextHook");
13
+ var _portfinder = require("portfinder");
14
+ var _launchBrowser = require("./launchBrowser");
15
+ var _runtimeInterface = require("../vendor/runtime-interface");
16
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
17
+ async function withPlaywrightContext({
18
+ cdpAddress,
19
+ cdpTargetId,
20
+ proxy,
21
+ headless = true,
22
+ downloadsPath,
23
+ importFunction,
24
+ apiName,
25
+ apiParameters
26
+ }, fn) {
27
+ let context;
28
+ let page;
29
+ try {
30
+ const setupContextHookResult = importFunction ? await (0, _setupContextHook.loadSetupContextHook)({
31
+ importFunction
32
+ }) : (0, _neverthrow.ok)(null);
33
+ if (setupContextHookResult.isErr()) {
34
+ return setupContextHookResult;
35
+ }
36
+ const setupContextHook = setupContextHookResult.value;
37
+ if (setupContextHook === null) {
38
+ if (cdpAddress !== undefined) {
39
+ ({
40
+ page,
41
+ context
42
+ } = await (0, _launchBrowser.launchBrowser)({
43
+ cdpAddress,
44
+ cdpTargetId
45
+ }));
46
+ } else {
47
+ ({
48
+ page,
49
+ context
50
+ } = await (0, _launchBrowser.launchBrowser)({
51
+ proxy,
52
+ headless,
53
+ downloadsPath
54
+ }));
55
+ }
56
+ return await fn(context, page);
57
+ }
58
+ let hookCdpUrl = null;
59
+ if (cdpAddress) {
60
+ hookCdpUrl = cdpAddress;
61
+ ({
62
+ context,
63
+ page
64
+ } = await (0, _launchBrowser.launchBrowser)({
65
+ cdpAddress,
66
+ cdpTargetId
67
+ }));
68
+ } else {
69
+ const port = await (0, _portfinder.getPort)({
70
+ port: 9222
71
+ });
72
+ ({
73
+ context,
74
+ page
75
+ } = await (0, _launchBrowser.launchBrowser)({
76
+ proxy,
77
+ headless,
78
+ downloadsPath,
79
+ cdpPort: port
80
+ }));
81
+ hookCdpUrl = (0, _launchBrowser.getLocalCdpAddress)(port);
82
+ }
83
+ let hookResult;
84
+ try {
85
+ const wsUrlResult = await (0, _launchBrowser.getCdpWebSocketUrl)(hookCdpUrl);
86
+ if (wsUrlResult.isOk()) {
87
+ hookCdpUrl = wsUrlResult.value;
88
+ } else {
89
+ throw new Error(wsUrlResult.error);
90
+ }
91
+ hookResult = await setupContextHook({
92
+ apiName: apiName,
93
+ apiParameters: apiParameters,
94
+ cdpUrl: hookCdpUrl
95
+ });
96
+ } catch (error) {
97
+ return (0, _neverthrow.err)(new _runtimeInterface.AutomationError(error));
98
+ }
99
+ if (!hookResult) {
100
+ return await fn(context, page);
101
+ }
102
+ const {
103
+ page: newPage,
104
+ context: newContext,
105
+ cleanup
106
+ } = hookResult;
107
+ let result;
108
+ try {
109
+ result = {
110
+ return: await fn(newContext, newPage ?? page)
111
+ };
112
+ } catch (e) {
113
+ result = {
114
+ throw: e
115
+ };
116
+ }
117
+ try {
118
+ await cleanup?.();
119
+ } catch (e) {
120
+ result = {
121
+ return: (0, _neverthrow.err)(new _runtimeInterface.AutomationError(e))
122
+ };
123
+ }
124
+ if ("throw" in result) {
125
+ throw result.throw;
126
+ }
127
+ return result.return;
128
+ } finally {
129
+ await context?.close();
130
+ }
131
+ }
132
+ async function loadSessionToContext({
133
+ context,
134
+ session
135
+ }) {
136
+ let sessionToLoad;
137
+ if (session.type === "state") {
138
+ const state = session.state;
139
+ if (state === undefined || state === null) {
140
+ return;
141
+ }
142
+ sessionToLoad = state;
143
+ } else {
144
+ const fullPath = (0, _fileUtils.getFullPathInProject)(session.path);
145
+ sessionToLoad = await fs.readJson(fullPath);
146
+ }
147
+ await (0, _contextStorageStateHelpers.setStorageState)(context, sessionToLoad);
148
+ }
@@ -0,0 +1,7 @@
1
+ import { Result } from "neverthrow";
2
+ import { ImportFunction, RunAutomationError } from "@intuned/runtime-interface";
3
+ export declare function importUsingImportFunction<_ReturnType = any>({ path, allowGenerators, importFunction, }: {
4
+ path: string;
5
+ importFunction: ImportFunction;
6
+ allowGenerators?: boolean;
7
+ }): Promise<Result<(..._: any) => Promise<_ReturnType>, RunAutomationError>>;
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.importUsingImportFunction = importUsingImportFunction;
7
+ var _neverthrow = require("neverthrow");
8
+ var _runtimeInterface = require("../../vendor/runtime-interface");
9
+ async function importUsingImportFunction({
10
+ path,
11
+ allowGenerators = true,
12
+ importFunction
13
+ }) {
14
+ try {
15
+ const importedResult = await importFunction(path);
16
+ if (importedResult.isErr()) {
17
+ if (importedResult.error.type === "not_found") {
18
+ return (0, _neverthrow.err)(new _runtimeInterface.ApiNotFoundError(path));
19
+ }
20
+ return (0, _neverthrow.err)(new _runtimeInterface.AutomationError(importedResult.error.error));
21
+ }
22
+ const imported = importedResult.value;
23
+ if (!imported || !imported.default || !imported.default.constructor) {
24
+ return (0, _neverthrow.err)(new _runtimeInterface.InvalidApiError(`${path} does not have a default export`));
25
+ }
26
+ if (imported.default.constructor.name === "AsyncGeneratorFunction") {
27
+ if (!allowGenerators) {
28
+ return (0, _neverthrow.err)(new _runtimeInterface.InvalidApiError(`${path} default export must be an async function`));
29
+ }
30
+ return (0, _neverthrow.ok)(async (...args) => {
31
+ const generator = imported.default(...args);
32
+ const result = await generator.next();
33
+ if (!result.done) {
34
+ throw new Error("Yield is not supported");
35
+ }
36
+ return result.value;
37
+ });
38
+ }
39
+ if (imported.default.constructor.name === "AsyncFunction") {
40
+ return (0, _neverthrow.ok)(imported.default);
41
+ }
42
+ return (0, _neverthrow.err)(new _runtimeInterface.InvalidApiError(`${path} default export must be an async function`));
43
+ } catch (error) {
44
+ return (0, _neverthrow.err)(new _runtimeInterface.AutomationError(error));
45
+ }
46
+ }
@@ -0,0 +1,8 @@
1
+ import { Result } from "neverthrow";
2
+ import type { Page, BrowserContext } from "playwright";
3
+ import { ExtendedRunApiParameters, RunApiResult, RunApiResultWithSessionOk, RunAutomationError } from "@intuned/runtime-interface";
4
+ export declare function runApi<ResultType = any>(input: ExtendedRunApiParameters & {
5
+ retrieveSession: true;
6
+ }): Promise<RunApiResult<ResultType, RunApiResultWithSessionOk<ResultType>>>;
7
+ export declare function runApi<ResultType = any>(input: ExtendedRunApiParameters): Promise<RunApiResult<ResultType>>;
8
+ export declare function checkAuthSessionWithRetries(page: Page, context: BrowserContext, checkFn: (..._: any) => Promise<boolean>, retries?: number): Promise<Result<boolean, RunAutomationError>>;
@@ -0,0 +1,177 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.checkAuthSessionWithRetries = checkAuthSessionWithRetries;
7
+ exports.runApi = runApi;
8
+ var _downloadDirectory = require("../../runtime/downloadDirectory");
9
+ var _asyncLocalStorage = require("../asyncLocalStorage");
10
+ var _fsExtra = _interopRequireWildcard(require("fs-extra"));
11
+ var fs = _fsExtra;
12
+ var _neverthrow = require("neverthrow");
13
+ var _constants = require("../constants");
14
+ var _playwrightContext = require("../playwrightContext");
15
+ var _formatZodError = require("../formatZodError");
16
+ var _cleanEnvironmentVariables = require("../cleanEnvironmentVariables");
17
+ var _importUsingImportFunction = require("./importUsingImportFunction");
18
+ var _runtimeInterface = require("../../vendor/runtime-interface");
19
+ var _contextStorageStateHelpers = require("../contextStorageStateHelpers");
20
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
21
+ function getObjectSizeInBytes(obj) {
22
+ try {
23
+ return new TextEncoder().encode(JSON.stringify(obj)).length;
24
+ } catch (error) {
25
+ return new TextEncoder().encode(String(obj)).length;
26
+ }
27
+ }
28
+ async function runApi({
29
+ abortSignal,
30
+ importFunction,
31
+ retrieveSession = false,
32
+ ...input
33
+ }) {
34
+ let traceStarted = false;
35
+ const inputParseResult = _runtimeInterface.runApiParametersSchema.safeParse(input);
36
+ if (!inputParseResult.success) {
37
+ return (0, _neverthrow.err)(new _runtimeInterface.InternalInvalidInputError("Input validation failed", (0, _formatZodError.formatZodError)(inputParseResult.error)));
38
+ }
39
+ const {
40
+ automationFunction: {
41
+ name,
42
+ params
43
+ },
44
+ runOptions,
45
+ tracing,
46
+ auth
47
+ } = inputParseResult.data;
48
+ const abortSymbol = Symbol("abort");
49
+ const abortPromise = new Promise(resolve => {
50
+ if (!abortSignal) return;
51
+ abortSignal.addEventListener("abort", () => {
52
+ resolve(abortSymbol);
53
+ });
54
+ });
55
+ async function runAutomation() {
56
+ const validatedModuleResult = await (0, _importUsingImportFunction.importUsingImportFunction)({
57
+ path: name,
58
+ importFunction
59
+ });
60
+ if (validatedModuleResult.isErr()) {
61
+ return (0, _neverthrow.err)(validatedModuleResult.error);
62
+ }
63
+ const automationFunction = validatedModuleResult.value;
64
+ if (auth && auth.session.type === "state") {
65
+ const state = auth.session.state;
66
+ if (state === undefined || state === null) {
67
+ return (0, _neverthrow.err)(new _runtimeInterface.AuthRequiredError());
68
+ }
69
+ }
70
+ const playwrightContextParameters = {
71
+ apiName: name,
72
+ apiParameters: params,
73
+ importFunction
74
+ };
75
+ const intunedContext = (0, _asyncLocalStorage.getExecutionContext)();
76
+ const runAutomationWithContext = async (context, page) => {
77
+ async function saveTraceIfNeeded({
78
+ errorMessage
79
+ }) {
80
+ if (!tracing.enabled || !traceStarted) {
81
+ return;
82
+ }
83
+ try {
84
+ await context?.tracing.stop({
85
+ path: tracing.filePath
86
+ });
87
+ } catch (error) {
88
+ console.log(errorMessage, error?.message);
89
+ await (0, _fsExtra.remove)(tracing.filePath);
90
+ }
91
+ }
92
+ if (auth) {
93
+ await (0, _playwrightContext.loadSessionToContext)({
94
+ context,
95
+ session: auth.session
96
+ });
97
+ if (intunedContext && auth.parameters) {
98
+ intunedContext.getAuthSessionParameters = async () => auth.parameters;
99
+ }
100
+ }
101
+ if (tracing.enabled) {
102
+ await context.tracing.start({
103
+ screenshots: true,
104
+ snapshots: true,
105
+ sources: true
106
+ });
107
+ traceStarted = true;
108
+ }
109
+ (0, _cleanEnvironmentVariables.cleanEnvironmentVariables)();
110
+ const automationFunctionParameters = [...(params !== undefined ? [params] : []), page, context];
111
+ try {
112
+ const automationFunctionResult = await Promise.race([automationFunction(...automationFunctionParameters), abortPromise]);
113
+ if (automationFunctionResult === abortSymbol) {
114
+ return (0, _neverthrow.err)(new _runtimeInterface.AbortedError());
115
+ }
116
+ const MAX_RESULT_SIZE_BYTES = 2 * 1024 * 1024;
117
+ const resultSizeInBytes = getObjectSizeInBytes(automationFunctionResult);
118
+ if (resultSizeInBytes > MAX_RESULT_SIZE_BYTES) {
119
+ return (0, _neverthrow.err)(new _runtimeInterface.ResultTooBigError(resultSizeInBytes, MAX_RESULT_SIZE_BYTES));
120
+ }
121
+ if (retrieveSession) {
122
+ return (0, _neverthrow.ok)({
123
+ result: automationFunctionResult,
124
+ extendedPayloads: intunedContext?.extendedPayloads,
125
+ session: await (0, _contextStorageStateHelpers.getStorageState)(context)
126
+ });
127
+ }
128
+ return (0, _neverthrow.ok)({
129
+ result: automationFunctionResult,
130
+ extendedPayloads: intunedContext?.extendedPayloads
131
+ });
132
+ } catch (error) {
133
+ return (0, _neverthrow.err)(new _runtimeInterface.AutomationError(error));
134
+ } finally {
135
+ await saveTraceIfNeeded({
136
+ errorMessage: "failed to save trace"
137
+ });
138
+ }
139
+ };
140
+ if (intunedContext?.store) {
141
+ intunedContext.store = {};
142
+ }
143
+ if (runOptions.environment === "standalone") {
144
+ const downloadsPath = (0, _downloadDirectory.getDownloadDirectoryPath)();
145
+ try {
146
+ return await (0, _playwrightContext.withPlaywrightContext)({
147
+ headless: runOptions.headless,
148
+ proxy: runOptions.proxy,
149
+ downloadsPath,
150
+ ...playwrightContextParameters
151
+ }, runAutomationWithContext);
152
+ } finally {
153
+ await fs.remove(downloadsPath);
154
+ }
155
+ } else {
156
+ return await (0, _playwrightContext.withPlaywrightContext)({
157
+ cdpAddress: runOptions.cdpAddress,
158
+ cdpTargetId: runOptions.cdpTargetId,
159
+ ...playwrightContextParameters
160
+ }, runAutomationWithContext);
161
+ }
162
+ }
163
+ return await runAutomation();
164
+ }
165
+ async function checkAuthSessionWithRetries(page, context, checkFn, retries = 3) {
166
+ if (retries === 0) {
167
+ return (0, _neverthrow.ok)(false);
168
+ }
169
+ let tryNumber = 0;
170
+ console.log("Checking AuthSession with retries", `${_constants.AUTH_SESSIONS_FOLDER_NAME}/check`);
171
+ while (retries > tryNumber) {
172
+ const result = await checkFn(page, context);
173
+ if (result) return (0, _neverthrow.ok)(true);
174
+ tryNumber++;
175
+ }
176
+ return (0, _neverthrow.ok)(false);
177
+ }