@intuned/runtime-dev 0.0.1-testing.0 → 0.1.0-test.0

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 (50) hide show
  1. package/InterfaceTemplate/index.ts +1 -0
  2. package/Intuned.json +5 -0
  3. package/WebTemplate/api.ts +92 -90
  4. package/WebTemplate/controllers/authSessions/check.ts +23 -29
  5. package/WebTemplate/controllers/authSessions/create.ts +46 -71
  6. package/WebTemplate/controllers/authSessions/index.ts +4 -4
  7. package/WebTemplate/controllers/authSessions/killOperation.ts +1 -1
  8. package/WebTemplate/controllers/authSessions/resumeOperation.ts +28 -52
  9. package/WebTemplate/controllers/authSessions/store.ts +11 -6
  10. package/WebTemplate/controllers/runApi/helpers.ts +47 -144
  11. package/WebTemplate/index.playwright.ts +42 -32
  12. package/WebTemplate/index.vanilla.ts +2 -20
  13. package/WebTemplate/jobs.ts +2 -13
  14. package/WebTemplate/utils.ts +1 -85
  15. package/WebTemplate.zip +0 -0
  16. package/api/authed.ts +12 -0
  17. package/api/test.ts +3 -0
  18. package/api/test2.ts +25 -0
  19. package/auth-sessions/check.ts +9 -0
  20. package/auth-sessions/create.ts +32 -0
  21. package/authSessions +1 -0
  22. package/dist/commands/api/run.d.ts +1 -1
  23. package/dist/commands/api/run.js +28 -50
  24. package/dist/commands/auth-sessions/load.js +7 -1
  25. package/dist/commands/auth-sessions/run-check.js +23 -9
  26. package/dist/commands/auth-sessions/run-create.js +51 -30
  27. package/dist/commands/build.js +5 -2
  28. package/dist/commands/common/utils/settings.js +5 -5
  29. package/dist/commands/common/utils/unixSocket.d.ts +9 -0
  30. package/dist/commands/common/utils/unixSocket.js +45 -0
  31. package/dist/commands/interface/run.d.ts +2 -0
  32. package/dist/commands/interface/run.js +161 -0
  33. package/dist/common/asyncLocalStorage/index.d.ts +1 -1
  34. package/dist/common/contextStorageStateHelpers.d.ts +1 -2
  35. package/dist/common/contextStorageStateHelpers.js +9 -7
  36. package/dist/common/getPlaywrightConstructs.d.ts +7 -5
  37. package/dist/common/getPlaywrightConstructs.js +28 -11
  38. package/dist/common/runApi/errors.d.ts +71 -0
  39. package/dist/common/runApi/errors.js +172 -0
  40. package/dist/common/runApi/index.d.ts +12 -0
  41. package/dist/common/runApi/index.js +288 -0
  42. package/dist/common/runApi/types.d.ts +486 -0
  43. package/dist/common/runApi/types.js +50 -0
  44. package/dist/runtime/extendTimeout.js +10 -6
  45. package/dist/runtime/index.d.ts +1 -0
  46. package/dist/runtime/requestMoreInfo.d.ts +1 -0
  47. package/output.txt +39 -0
  48. package/package.json +7 -5
  49. package/testing +0 -0
  50. package/tsconfig.json +2 -1
@@ -7,11 +7,7 @@ Object.defineProperty(exports, "__esModule", {
7
7
  exports.executeCLI = executeCLI;
8
8
  var _commander = require("commander");
9
9
  var fs = _interopRequireWildcard(require("fs-extra"));
10
- var _getDefaultExportFromFile = require("../common/getDefaultExportFromFile");
11
- var _fileUtils = require("../common/utils/fileUtils");
12
10
  var _settings = require("../common/utils/settings");
13
- var _getFirstLineNumber = _interopRequireDefault(require("../common/getFirstLineNumber"));
14
- var _sendMessageToClient = require("../common/sendMessageToClient");
15
11
  var _dotenv = _interopRequireDefault(require("dotenv"));
16
12
  var _asyncLocalStorage = require("../../common/asyncLocalStorage");
17
13
  var _enums = require("../../runtime/enums");
@@ -19,8 +15,7 @@ var _cleanEnvironmentVariables = require("../../common/cleanEnvironmentVariables
19
15
  var _Logger = require("../../common/Logger");
20
16
  var _nanoid = require("nanoid");
21
17
  var _chalk = _interopRequireDefault(require("chalk"));
22
- var _runtime = require("../../runtime");
23
- var _getPlaywrightConstructs = require("../../common/getPlaywrightConstructs");
18
+ var _runApi = require("../../common/runApi");
24
19
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
25
20
  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); }
26
21
  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; }
@@ -28,9 +23,7 @@ _dotenv.default.config({
28
23
  path: `.env`
29
24
  });
30
25
  async function executeCLI(apiName, mode, inputData, options) {
31
- var _getExecutionContext;
32
26
  (0, _cleanEnvironmentVariables.cleanEnvironmentVariables)();
33
- const apiFilePath = (0, _fileUtils.getFullPathInProject)("api", `${apiName}.ts`);
34
27
  let authSessionPathToUse = null;
35
28
  const settings = await (0, _settings.getSettings)();
36
29
  if (settings.authSessions.enabled) {
@@ -43,49 +36,35 @@ async function executeCLI(apiName, mode, inputData, options) {
43
36
  throw new Error("Auth session is not enabled but auth session provided. To use auth session please enable it in Intuned.json");
44
37
  }
45
38
  }
46
- const defaultExport = await (0, _getDefaultExportFromFile.getDefaultExportFromFile)(apiFilePath);
47
- const isDebug = process.execArgv.some(arg => arg.includes("--inspect"));
48
- if (isDebug) {
49
- const {
50
- sourceFileName,
51
- lineNumber
52
- } = await (0, _getFirstLineNumber.default)(apiFilePath);
53
- (0, _sendMessageToClient.sendBreakPointOnToClient)(sourceFileName, lineNumber);
54
- }
55
- if (mode === "vanilla") {
56
- const result = await defaultExport(inputData);
57
- return result;
58
- }
59
- const {
60
- page,
61
- context
62
- } = await (0, _getPlaywrightConstructs.getPlaywrightConstructsForMode)(mode, options.cdpAddress, authSessionPathToUse ? authSessionPathToUse : undefined);
63
- let isPageStable = false;
64
- let retry = 0;
65
- while (!isPageStable && retry < 10) {
66
- try {
67
- await page.locator("html").all();
68
- isPageStable = true;
69
- break;
70
- } catch (error) {
71
- var _error$message;
72
- if (error !== null && error !== void 0 && (_error$message = error.message) !== null && _error$message !== void 0 && _error$message.includes("Execution context was destroyed")) {
73
- await new Promise(resolve => setTimeout(resolve, 200));
74
- } else {
75
- throw error;
76
- }
39
+ const runApiResult = await (0, _runApi.runApi)({
40
+ automationFunction: {
41
+ name: `api/${apiName}`,
42
+ params: inputData ?? {}
43
+ },
44
+ auth: authSessionPathToUse ? {
45
+ session: {
46
+ type: "file",
47
+ path: authSessionPathToUse
48
+ },
49
+ runCheck: false
50
+ } : undefined,
51
+ runOptions: {
52
+ environment: "ide",
53
+ cdpAddress: options.cdpAddress,
54
+ mode
77
55
  }
78
- retry++;
79
- }
80
- if (!isPageStable) {
81
- throw new Error("The page is not stable, try to run again.");
82
- }
83
- const result = await defaultExport(inputData, page, context);
84
- const downloadsPath = (0, _runtime.getDownloadDirectoryPath)();
85
- await fs.remove(downloadsPath);
86
- if (mode == "playwright") {
87
- await context.close();
56
+ });
57
+ if (runApiResult.isErr()) {
58
+ if (runApiResult.error instanceof _runApi.AutomationError) {
59
+ throw runApiResult.error.error;
60
+ }
61
+ console.error("An error occurred while running the API", runApiResult.error);
62
+ return;
88
63
  }
64
+ const {
65
+ result,
66
+ extendedPayloads: payloadToAppend
67
+ } = runApiResult.value;
89
68
  const isResponseObject = typeof result === "object" && result !== null;
90
69
  const hasMoreThank5Keys = isResponseObject && Object.keys(result).length > 5;
91
70
  const hasNestedObjects = isResponseObject && Object.values(result).some(value => typeof value === "object");
@@ -101,7 +80,6 @@ async function executeCLI(apiName, mode, inputData, options) {
101
80
  } else {
102
81
  console.log("result:", result);
103
82
  }
104
- const payloadToAppend = (_getExecutionContext = (0, _asyncLocalStorage.getExecutionContext)()) === null || _getExecutionContext === void 0 ? void 0 : _getExecutionContext.extendedPayloads;
105
83
  const hasPayloadToAppend = payloadToAppend && payloadToAppend.length > 0;
106
84
  if (hasPayloadToAppend && options.outputFileId) {
107
85
  _Logger.logger.info(_chalk.default.underline.bgBlue.white(`Click to Open: payloads to append (Run: ${options.outputFileId})`));
@@ -20,7 +20,13 @@ _commander.program.description("load auth session to browser").option("--cdpAddr
20
20
  const {
21
21
  context
22
22
  } = await (0, _getPlaywrightConstructs.getRemotePlaywrightContext)(cdpAddress);
23
- await (0, _getPlaywrightConstructs.loadAuthSessionToContext)(context, authSessionPath);
23
+ await (0, _getPlaywrightConstructs.loadSessionToContext)({
24
+ context,
25
+ session: {
26
+ type: "file",
27
+ path: authSessionPath
28
+ }
29
+ });
24
30
  process.exit(0);
25
31
  });
26
32
  _commander.program.parse(process.argv);
@@ -2,13 +2,12 @@
2
2
  "use strict";
3
3
 
4
4
  var _commander = require("commander");
5
- var _getDefaultExportFromFile = require("../common/getDefaultExportFromFile");
6
5
  var fs = _interopRequireWildcard(require("fs-extra"));
7
6
  var _fileUtils = require("../common/utils/fileUtils");
8
7
  var _settings = require("../common/utils/settings");
9
8
  var _dotenv = _interopRequireDefault(require("dotenv"));
10
9
  var _constants = require("../../common/constants");
11
- var _getPlaywrightConstructs = require("../../common/getPlaywrightConstructs");
10
+ var _runApi = require("../../common/runApi");
12
11
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13
12
  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); }
14
13
  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; }
@@ -23,16 +22,31 @@ _commander.program.description("run auth session check").option("--cdpAddress <c
23
22
  if (!setting.authSessions.enabled) {
24
23
  throw new Error("auth session is not enabled");
25
24
  }
26
- const checkFilePath = (0, _fileUtils.getFullPathInProject)(_constants.AUTH_SESSIONS_FOLDER_NAME, "check.ts");
25
+ const checkFilePath = (0, _fileUtils.getFullPathInProject)(_constants.AUTH_SESSIONS_FOLDER_NAME, "check");
27
26
  if (!fs.exists(checkFilePath)) {
28
27
  throw new Error("auth session check file not found");
29
28
  }
30
- const defaultExport = await (0, _getDefaultExportFromFile.getDefaultExportFromFile)(checkFilePath);
31
- const {
32
- page,
33
- context
34
- } = await (0, _getPlaywrightConstructs.getPlaywrightConstructsForMode)(mode, cdpAddress, authSessionPath);
35
- const result = await defaultExport(page, context);
29
+ const runApiResult = await (0, _runApi.runApi)({
30
+ automationFunction: {
31
+ name: `${_constants.AUTH_SESSIONS_FOLDER_NAME}/check`
32
+ },
33
+ runOptions: {
34
+ environment: "ide",
35
+ mode,
36
+ cdpAddress
37
+ },
38
+ auth: {
39
+ session: {
40
+ type: "file",
41
+ path: authSessionPath
42
+ },
43
+ runCheck: false
44
+ }
45
+ });
46
+ if (runApiResult.isErr()) {
47
+ throw new Error(runApiResult.error);
48
+ }
49
+ const result = runApiResult.value.result;
36
50
  console.log("check result", result);
37
51
  if (!result) {
38
52
  throw new Error("auth session check failed");
@@ -2,15 +2,16 @@
2
2
  "use strict";
3
3
 
4
4
  var _commander = require("commander");
5
- var _getDefaultExportFromFile = require("../common/getDefaultExportFromFile");
6
5
  var fs = _interopRequireWildcard(require("fs-extra"));
7
- var _browserUtils = require("../common/browserUtils");
8
6
  var _promptly = require("promptly");
9
7
  var _fileUtils = require("../common/utils/fileUtils");
10
8
  var _settings = require("../common/utils/settings");
11
9
  var _dotenv = _interopRequireDefault(require("dotenv"));
12
10
  var _constants = require("../../common/constants");
13
- var _getPlaywrightConstructs = require("../../common/getPlaywrightConstructs");
11
+ var _runApi = require("../../common/runApi");
12
+ var _asyncLocalStorage = require("../../common/asyncLocalStorage");
13
+ var _nanoid = require("nanoid");
14
+ var _enums = require("../../runtime/enums");
14
15
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
15
16
  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); }
16
17
  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; }
@@ -39,37 +40,57 @@ _commander.program.description("run auth session create").option("--cdpAddress <
39
40
  if (!fs.exists(createFilePath)) {
40
41
  throw new Error("auth session create file not found");
41
42
  }
42
- const defaultExport = await (0, _getDefaultExportFromFile.getDefaultExportFromFile)(createFilePath);
43
- const {
44
- page,
45
- context
46
- } = await (0, _getPlaywrightConstructs.getPlaywrightConstructsForMode)(mode, cdpAddress);
47
- const generator = await defaultExport(inputData, page, context, false);
48
- let nextGeneratorParam = undefined;
49
- while (true) {
50
- const {
51
- value,
52
- done
53
- } = await generator.next(nextGeneratorParam);
54
- if (done) {
55
- if (pathToSave) {
56
- await (0, _browserUtils.saveSession)(pathToSave, context);
43
+ async function runCreate() {
44
+ const generator = (0, _runApi.runApiGenerator)({
45
+ automationFunction: {
46
+ name: "auth-sessions/create",
47
+ params: inputData ?? {}
48
+ },
49
+ runOptions: {
50
+ environment: "ide",
51
+ mode,
52
+ cdpAddress
53
+ },
54
+ retrieveSession: true
55
+ });
56
+ let nextGeneratorParam = undefined;
57
+ while (true) {
58
+ const {
59
+ value,
60
+ done
61
+ } = await generator.next(...(nextGeneratorParam ? [nextGeneratorParam] : []));
62
+ if (done) {
63
+ if (value.isErr()) {
64
+ console.log(value.error);
65
+ throw new Error(value.error);
66
+ }
67
+ const fullState = value.value.session;
68
+ if (pathToSave) {
69
+ const fullPath = (0, _fileUtils.getFullPathInProject)(pathToSave);
70
+ fs.ensureFileSync(fullPath);
71
+ await fs.writeJSON(fullPath, fullState);
72
+ }
73
+ break;
57
74
  }
58
- break;
59
- }
60
- if (value.action === "request_more_info" && value.requestType == "multiple_choice") {
61
- nextGeneratorParam = await (0, _promptly.prompt)(value.messageToUser + `, choices: ${value.choices}`, {
62
- validator: input => {
63
- if (!value.choices.includes(input)) {
64
- throw new Error("Please type on of the allowed choices");
75
+ if (value.action === "request_more_info" && value.requestType == "multiple_choice") {
76
+ nextGeneratorParam = await (0, _promptly.prompt)(value.messageToUser + `, choices: ${value.choices}`, {
77
+ validator: input => {
78
+ if (!value.choices.includes(input)) {
79
+ throw new Error("Please type on of the allowed choices");
80
+ }
81
+ return input;
65
82
  }
66
- return input;
67
- }
68
- });
69
- } else if (value.action === "request_more_info" && value.requestType == "otp") {
70
- nextGeneratorParam = await (0, _promptly.prompt)(value.messageToUser, {});
83
+ });
84
+ } else if (value.action === "request_more_info" && value.requestType == "otp") {
85
+ nextGeneratorParam = await (0, _promptly.prompt)(value.messageToUser, {});
86
+ }
71
87
  }
72
88
  }
89
+ await (0, _asyncLocalStorage.runWithContext)({
90
+ runEnvironment: _enums.RunEnvironment.IDE,
91
+ extendedPayloads: [],
92
+ runId: (0, _nanoid.nanoid)()
93
+ }, runCreate);
73
94
  process.exit(0);
74
95
  });
75
96
  _commander.program.parse(process.argv);
@@ -44,10 +44,13 @@ async function build(outfile, mode) {
44
44
  }), (0, _pluginTypescript.default)({
45
45
  tsconfig: "./intuned/WebTemplate/tsconfig.json"
46
46
  }), (0, _pluginCommonjs.default)({
47
- include: ["node_modules/**", "intuned/WebTemplate/**", "dist", "../typescript-sdk/**", "../typescript-runtime/**"],
47
+ include: [path.resolve("/Users/omarhurani/Documents/GitHub/WebApp/apps/typescript-runtime"), "node_modules/**", "intuned/WebTemplate/**", "dist", "../typescript-sdk/**", "../typescript-runtime/**"],
48
48
  extensions: [".js"],
49
49
  ignoreGlobal: false,
50
- sourceMap: false
50
+ sourceMap: false,
51
+ transformMixedEsModules: true,
52
+ ignoreTryCatch: true,
53
+ requireReturnsDefault: "auto"
51
54
  }), (0, _pluginDynamicImportVars.default)({
52
55
  include: ["**/*.js", "**/*.ts"],
53
56
  exclude: ["**/*.d.ts", "**/*.js.map"]
@@ -6,14 +6,14 @@ Object.defineProperty(exports, "__esModule", {
6
6
  exports.getSettings = getSettings;
7
7
  var _fileUtils = require("./fileUtils");
8
8
  var _settingsSchema = require("../../../common/settingsSchema");
9
- 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); }
10
- 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; }
9
+ var _fsExtra = require("fs-extra");
11
10
  async function getSettings() {
12
11
  const settingsFilePath = (0, _fileUtils.getFullPathInProject)("Intuned.json");
13
12
  console.log("loading settings");
14
- const settings = await (specifier => new Promise(r => r(`${specifier}`)).then(s => _interopRequireWildcard(require(s))))(settingsFilePath);
15
- if (settings.default) {
16
- const parsed = _settingsSchema.settingsSchema.safeParse(settings.default);
13
+ const settings = await (0, _fsExtra.readJSON)(settingsFilePath);
14
+ if (settings) {
15
+ const parsed = _settingsSchema.settingsSchema.safeParse(settings);
16
+ console.log(parsed);
17
17
  if (parsed.success) {
18
18
  return parsed.data;
19
19
  } else {
@@ -0,0 +1,9 @@
1
+ /// <reference types="node" />
2
+ import * as net from "net";
3
+ export declare class JSONUnixSocket {
4
+ private readonly socket;
5
+ static readonly LENGTH_HEADER_LENGTH = 4;
6
+ constructor(socket: net.Socket);
7
+ sendJSON(data: any): void;
8
+ receiveJSON(): AsyncGenerator<any, void, unknown>;
9
+ }
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.JSONUnixSocket = void 0;
7
+ class JSONUnixSocket {
8
+ static LENGTH_HEADER_LENGTH = 4;
9
+ constructor(socket) {
10
+ this.socket = socket;
11
+ }
12
+ sendJSON(data) {
13
+ const dataToSend = JSON.stringify(data);
14
+ const length = Buffer.byteLength(dataToSend);
15
+ const buffer = Buffer.alloc(JSONUnixSocket.LENGTH_HEADER_LENGTH + length);
16
+ buffer.writeUInt32BE(length, 0);
17
+ buffer.write(dataToSend, JSONUnixSocket.LENGTH_HEADER_LENGTH);
18
+ this.socket.write(buffer);
19
+ }
20
+ async *receiveJSON() {
21
+ let buffer = Buffer.alloc(0);
22
+ const endPromise = new Promise((resolve, reject) => {
23
+ this.socket.once("end", () => {
24
+ console.log("end");
25
+ resolve();
26
+ });
27
+ this.socket.once("error", reject);
28
+ });
29
+ while (true) {
30
+ const chunk = await Promise.race([new Promise(resolve => this.socket.once("data", data => resolve(data))), endPromise]);
31
+ if (!(chunk instanceof Buffer)) {
32
+ break;
33
+ }
34
+ buffer = Buffer.concat([buffer, chunk]);
35
+ const length = buffer.readUInt32BE(0);
36
+ if (buffer.length < length + JSONUnixSocket.LENGTH_HEADER_LENGTH) {
37
+ continue;
38
+ }
39
+ const data = buffer.subarray(JSONUnixSocket.LENGTH_HEADER_LENGTH, length + JSONUnixSocket.LENGTH_HEADER_LENGTH);
40
+ buffer = buffer.subarray(length + JSONUnixSocket.LENGTH_HEADER_LENGTH);
41
+ yield JSON.parse(data.toString());
42
+ }
43
+ }
44
+ }
45
+ exports.JSONUnixSocket = JSONUnixSocket;
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,161 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ var _commander = require("commander");
5
+ var _dotenv = _interopRequireDefault(require("dotenv"));
6
+ var _asyncLocalStorage = require("../../common/asyncLocalStorage");
7
+ var net = _interopRequireWildcard(require("net"));
8
+ var _zod = _interopRequireDefault(require("zod"));
9
+ var _runApi = require("../../common/runApi");
10
+ var _enums = require("src/runtime/enums");
11
+ var _unixSocket = require("../common/utils/unixSocket");
12
+ var _promises = require("timers/promises");
13
+ 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); }
14
+ 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; }
15
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
16
+ const startRunApiSchema = _zod.default.object({
17
+ type: _zod.default.literal("start"),
18
+ parameters: _runApi.runApiParametersSchema.extend({
19
+ retrieveSession: _zod.default.boolean(),
20
+ context: _zod.default.object({
21
+ jobId: _zod.default.string().optional(),
22
+ jobRunId: _zod.default.string().optional(),
23
+ runId: _zod.default.string().optional(),
24
+ queueId: _zod.default.string().optional()
25
+ }).optional()
26
+ })
27
+ });
28
+ const nextRunApiSchema = _zod.default.object({
29
+ type: _zod.default.literal("next"),
30
+ parameters: _zod.default.object({
31
+ value: _zod.default.string()
32
+ })
33
+ });
34
+ const abortRunApiSchema = _zod.default.object({
35
+ type: _zod.default.literal("abort"),
36
+ parameters: _zod.default.object({}).optional()
37
+ });
38
+ const inputSchema = _zod.default.union([startRunApiSchema, nextRunApiSchema, abortRunApiSchema]);
39
+ _dotenv.default.config({
40
+ path: `.env`
41
+ });
42
+ _commander.program.description("run user automation and communicate using unix socket").argument("<socket-path>", "path to unix socket").action(async socketPath => {
43
+ let context;
44
+ const throttleTime = 1_000;
45
+ let timeoutTimestamp = Date.now();
46
+ const client = net.createConnection(socketPath, () => {
47
+ console.log("connected to server!");
48
+ });
49
+ let generator = null;
50
+ const abortController = new AbortController();
51
+ client.on("end", () => {
52
+ console.log("Disconnected from socket");
53
+ });
54
+ client.on("error", err => {
55
+ var _generator;
56
+ console.error("Child connection error:", err);
57
+ void ((_generator = generator) === null || _generator === void 0 ? void 0 : _generator.throw(err).catch(() => undefined));
58
+ });
59
+ process.on("SIGINT", () => {
60
+ var _generator2;
61
+ console.log("Received SIGINT");
62
+ void ((_generator2 = generator) === null || _generator2 === void 0 ? void 0 : _generator2.throw(new Error("Interrupted")).catch(() => undefined));
63
+ client.end();
64
+ process.exit(1);
65
+ });
66
+ const jsonUnixSocket = new _unixSocket.JSONUnixSocket(client);
67
+ async function runGeneratorAndSendResult(next) {
68
+ if (!generator) return;
69
+ const result = await (0, _asyncLocalStorage.runWithContext)(context, () => generator.next(next));
70
+ if (result.done) {
71
+ const resultToSend = result.value.isOk() ? result.value.value : result.value.error.json;
72
+ const success = result.value.isOk();
73
+ jsonUnixSocket.sendJSON({
74
+ type: "done",
75
+ result: resultToSend,
76
+ success
77
+ });
78
+ return true;
79
+ } else {
80
+ jsonUnixSocket.sendJSON({
81
+ type: "yield",
82
+ result: result.value
83
+ });
84
+ return false;
85
+ }
86
+ }
87
+ for await (const data of jsonUnixSocket.receiveJSON()) {
88
+ const inputParseResult = inputSchema.safeParse(data);
89
+ if (!inputParseResult.success) {
90
+ console.error(inputParseResult.error.errors);
91
+ jsonUnixSocket.sendJSON({
92
+ type: "done",
93
+ result: {
94
+ error: "InvalidJSON",
95
+ message: "Invalid input",
96
+ details: {
97
+ errors: inputParseResult.error.errors
98
+ }
99
+ },
100
+ success: false
101
+ });
102
+ break;
103
+ }
104
+ const input = inputParseResult.data;
105
+ if (input.type === "abort") {
106
+ abortController.abort();
107
+ await (0, _promises.setTimeout)(10);
108
+ jsonUnixSocket.sendJSON({
109
+ type: "done",
110
+ result: null
111
+ });
112
+ break;
113
+ }
114
+ if (input.type === "start") {
115
+ const gen = (0, _runApi.runApiGenerator)({
116
+ ...input.parameters,
117
+ abortSignal: abortController.signal
118
+ });
119
+ generator = gen;
120
+ context = {
121
+ extendedPayloads: [],
122
+ runEnvironment: input.parameters.runOptions.environment === "deployed" ? _enums.RunEnvironment.DEPLOYED : _enums.RunEnvironment.IDE,
123
+ timeoutInfo: {
124
+ extendTimeoutCallback: async () => {
125
+ if (Date.now() - timeoutTimestamp < throttleTime) return;
126
+ timeoutTimestamp = Date.now();
127
+ jsonUnixSocket.sendJSON({
128
+ type: "extend"
129
+ });
130
+ }
131
+ },
132
+ ...(input.parameters.context ?? {}),
133
+ proxy: getProxyUrlFromRunOptions(input.parameters.runOptions)
134
+ };
135
+ if (await runGeneratorAndSendResult()) {
136
+ break;
137
+ }
138
+ continue;
139
+ }
140
+ if (input.type === "next") {
141
+ if (!generator) {
142
+ throw new Error("generator not started");
143
+ }
144
+ if (await runGeneratorAndSendResult(input.parameters.value)) {
145
+ break;
146
+ }
147
+ continue;
148
+ }
149
+ }
150
+ process.exit(0);
151
+ });
152
+ _commander.program.parse(process.argv);
153
+ function getProxyUrlFromRunOptions(runOptions) {
154
+ if ((runOptions === null || runOptions === void 0 ? void 0 : runOptions.environment) !== "deployed") return undefined;
155
+ const proxy = runOptions.proxy;
156
+ if (!proxy) return undefined;
157
+ const url = new URL(proxy.server);
158
+ url.username = proxy.username;
159
+ url.password = proxy.password;
160
+ return url.toString();
161
+ }
@@ -8,7 +8,7 @@ interface TimeoutInfo {
8
8
  timeoutDuration?: number;
9
9
  timeoutTimestamp?: number;
10
10
  }
11
- interface InternalRunInfo extends RunInfo {
11
+ export interface InternalRunInfo extends RunInfo {
12
12
  extendedPayloads: Payload[];
13
13
  timeoutInfo?: TimeoutInfo;
14
14
  }
@@ -1,6 +1,6 @@
1
1
  import { BrowserContext } from "@intuned/playwright";
2
2
  import * as playwright from "@intuned/playwright-core";
3
- interface OriginSessionStorage {
3
+ export interface OriginSessionStorage {
4
4
  origin: string;
5
5
  sessionStorage: Array<{
6
6
  name: string;
@@ -12,4 +12,3 @@ export type IntunedStorageState = Exclude<playwright.BrowserContextOptions["stor
12
12
  };
13
13
  export declare function getContextStorageState(context: BrowserContext): Promise<IntunedStorageState>;
14
14
  export declare function setContextStorageState(context: BrowserContext, storage: IntunedStorageState): Promise<void>;
15
- export {};
@@ -17,15 +17,17 @@ function sessionStorageToArray(storage) {
17
17
  }
18
18
  async function getContextStorageState(context) {
19
19
  const cookiesAndLocalStorage = await context.storageState();
20
- const pages = await context.pages();
20
+ const pages = context.pages();
21
21
  const pagesSessions = [];
22
22
  for (const page of pages) {
23
- const [origin, session] = await page.evaluate(() => [location.origin, sessionStorage]);
24
- const transformed = sessionStorageToArray(session);
25
- pagesSessions.push({
26
- origin,
27
- sessionStorage: transformed
28
- });
23
+ try {
24
+ const [origin, session] = await page.evaluate(() => [location.origin, sessionStorage]);
25
+ const transformed = sessionStorageToArray(session);
26
+ pagesSessions.push({
27
+ origin,
28
+ sessionStorage: transformed
29
+ });
30
+ } catch (e) {}
29
31
  }
30
32
  return {
31
33
  ...cookiesAndLocalStorage,
@@ -1,5 +1,5 @@
1
1
  import * as playwright from "@intuned/playwright-core";
2
- import { IntunedStorageState } from "./contextStorageStateHelpers";
2
+ import type { RunApiSession } from "./runApi";
3
3
  interface Proxy {
4
4
  server: string;
5
5
  username: string;
@@ -8,19 +8,21 @@ interface Proxy {
8
8
  interface GetPlaywrightConstructsOptions {
9
9
  proxy?: Proxy;
10
10
  headless?: boolean;
11
- storageState?: IntunedStorageState;
11
+ storageState?: RunApiSession;
12
12
  downloadsPath: string;
13
- userDataDir?: string;
14
13
  }
15
14
  export declare function getProductionPlaywrightConstructs({ proxy, headless, storageState, downloadsPath, }: GetPlaywrightConstructsOptions): Promise<{
16
15
  page: playwright.Page;
17
16
  context: playwright.BrowserContext;
18
17
  }>;
19
- export declare function getPlaywrightConstructsForMode(mode: "vanilla" | "playwright" | "playwright-standalone" | "playwright-headless", cdpAddress: string | undefined, authSessionPath?: string): Promise<{
18
+ export declare function getPlaywrightConstructsForMode(mode: "vanilla" | "playwright" | "playwright-standalone" | "playwright-headless", cdpAddress: string | undefined, authSession?: RunApiSession): Promise<{
20
19
  page: playwright.Page;
21
20
  context: playwright.BrowserContext;
22
21
  }>;
23
- export declare function loadAuthSessionToContext(context: playwright.BrowserContext, authSessionPath: string): Promise<void>;
22
+ export declare function loadSessionToContext({ context, session, }: {
23
+ context: playwright.BrowserContext;
24
+ session: RunApiSession;
25
+ }): Promise<void>;
24
26
  export declare function getRemotePlaywrightContext(cdpAddress: string): Promise<{
25
27
  browser: playwright.Browser;
26
28
  context: playwright.BrowserContext;