@intuned/runtime-dev 0.0.1 → 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 (163) 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 -146
  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/bin/intuned-api-run +2 -0
  23. package/bin/intuned-auth-session-check +2 -0
  24. package/bin/intuned-auth-session-create +2 -0
  25. package/bin/intuned-auth-session-load +2 -0
  26. package/bin/intuned-auth-session-refresh +2 -0
  27. package/bin/intuned-browser-save-state +2 -0
  28. package/bin/intuned-browser-start +2 -0
  29. package/bin/intuned-build +2 -0
  30. package/bin/intuned-ts-check +2 -0
  31. package/dist/commands/api/run.d.ts +6 -0
  32. package/dist/commands/api/run.js +113 -0
  33. package/dist/commands/auth-sessions/load.d.ts +2 -0
  34. package/dist/commands/auth-sessions/load.js +32 -0
  35. package/dist/commands/auth-sessions/run-check.d.ts +2 -0
  36. package/dist/commands/auth-sessions/run-check.js +56 -0
  37. package/dist/commands/auth-sessions/run-create.d.ts +2 -0
  38. package/dist/commands/auth-sessions/run-create.js +96 -0
  39. package/dist/commands/browser/save-state.d.ts +2 -0
  40. package/dist/commands/browser/save-state.js +17 -0
  41. package/dist/commands/browser/start-browser.d.ts +2 -0
  42. package/dist/commands/browser/start-browser.js +14 -0
  43. package/dist/commands/build.d.ts +2 -0
  44. package/dist/commands/build.js +83 -0
  45. package/dist/commands/common/browserUtils.d.ts +14 -0
  46. package/dist/commands/common/browserUtils.js +58 -0
  47. package/dist/commands/common/getDefaultExportFromFile.d.ts +1 -0
  48. package/dist/commands/common/getDefaultExportFromFile.js +19 -0
  49. package/dist/commands/common/getFirstLineNumber.d.ts +9 -0
  50. package/dist/commands/common/getFirstLineNumber.js +103 -0
  51. package/{src/commands/common/getFirstLineNumber.test.ts → dist/commands/common/getFirstLineNumber.test.js} +75 -121
  52. package/dist/commands/common/sendMessageToClient.d.ts +1 -0
  53. package/dist/commands/common/sendMessageToClient.js +10 -0
  54. package/dist/commands/common/utils/fileUtils.d.ts +6 -0
  55. package/dist/commands/common/utils/fileUtils.js +33 -0
  56. package/dist/commands/common/utils/settings.d.ts +2 -0
  57. package/dist/commands/common/utils/settings.js +28 -0
  58. package/dist/commands/common/utils/unixSocket.d.ts +9 -0
  59. package/dist/commands/common/utils/unixSocket.js +45 -0
  60. package/dist/commands/common/utils/webTemplate.d.ts +1 -0
  61. package/dist/commands/common/utils/webTemplate.js +31 -0
  62. package/dist/commands/interface/run.d.ts +2 -0
  63. package/dist/commands/interface/run.js +161 -0
  64. package/dist/commands/ts-check.d.ts +2 -0
  65. package/dist/commands/ts-check.js +54 -0
  66. package/dist/common/Logger/Logger/index.d.ts +12 -0
  67. package/dist/common/Logger/Logger/index.js +60 -0
  68. package/{src/common/Logger/Logger/types.ts → dist/common/Logger/Logger/types.d.ts} +4 -5
  69. package/dist/common/Logger/Logger/types.js +5 -0
  70. package/dist/common/Logger/index.d.ts +12 -0
  71. package/dist/common/Logger/index.js +60 -0
  72. package/{src/common/Logger/types.ts → dist/common/Logger/types.d.ts} +4 -5
  73. package/dist/common/Logger/types.js +5 -0
  74. package/dist/common/asyncLocalStorage/index.d.ts +16 -0
  75. package/dist/common/asyncLocalStorage/index.js +17 -0
  76. package/dist/common/cleanEnvironmentVariables.d.ts +1 -0
  77. package/dist/common/cleanEnvironmentVariables.js +16 -0
  78. package/dist/common/constants.d.ts +1 -0
  79. package/dist/common/constants.js +7 -0
  80. package/dist/common/contextStorageStateHelpers.d.ts +14 -0
  81. package/dist/common/contextStorageStateHelpers.js +50 -0
  82. package/dist/common/getPlaywrightConstructs.d.ts +30 -0
  83. package/dist/common/getPlaywrightConstructs.js +192 -0
  84. package/dist/common/jwtTokenManager.d.ts +16 -0
  85. package/dist/common/jwtTokenManager.js +81 -0
  86. package/dist/common/runApi/errors.d.ts +71 -0
  87. package/dist/common/runApi/errors.js +172 -0
  88. package/dist/common/runApi/index.d.ts +12 -0
  89. package/dist/common/runApi/index.js +288 -0
  90. package/dist/common/runApi/types.d.ts +486 -0
  91. package/dist/common/runApi/types.js +50 -0
  92. package/dist/common/settingsSchema.d.ts +19 -0
  93. package/dist/common/settingsSchema.js +17 -0
  94. package/dist/common/telemetry.d.ts +3 -0
  95. package/dist/common/telemetry.js +32 -0
  96. package/dist/index.d.ts +4 -0
  97. package/dist/index.js +69 -0
  98. package/dist/runtime/RunError.d.ts +5 -0
  99. package/dist/runtime/RunError.js +19 -0
  100. package/dist/runtime/downloadDirectory.d.ts +1 -0
  101. package/dist/runtime/downloadDirectory.js +19 -0
  102. package/dist/runtime/enums.d.js +5 -0
  103. package/dist/runtime/enums.js +18 -0
  104. package/dist/runtime/executionHelpers.test.js +53 -0
  105. package/dist/runtime/export.d.js +5 -0
  106. package/dist/runtime/extendPayload.d.ts +2 -0
  107. package/dist/runtime/extendPayload.js +21 -0
  108. package/dist/runtime/extendTimeout.d.ts +1 -0
  109. package/dist/runtime/extendTimeout.js +30 -0
  110. package/{src/runtime/index.ts → dist/runtime/index.d.ts} +2 -3
  111. package/dist/runtime/index.js +53 -0
  112. package/dist/runtime/requestMoreInfo.d.ts +18 -0
  113. package/dist/runtime/requestMoreInfo.js +25 -0
  114. package/dist/runtime/runInfo.d.ts +2 -0
  115. package/dist/runtime/runInfo.js +21 -0
  116. package/output.txt +39 -0
  117. package/package.json +9 -7
  118. package/testing +0 -0
  119. package/tsconfig.json +2 -1
  120. package/.vite/deps_temp_01af7156/package.json +0 -3
  121. package/.vscode/extensions.json +0 -3
  122. package/.vscode/launch.json +0 -102
  123. package/.vscode/settings.json +0 -12
  124. package/playwright.config.ts +0 -48
  125. package/src/commands/api/run.ts +0 -225
  126. package/src/commands/auth-sessions/load.ts +0 -42
  127. package/src/commands/auth-sessions/run-check.ts +0 -70
  128. package/src/commands/auth-sessions/run-create.ts +0 -124
  129. package/src/commands/browser/save-state.ts +0 -22
  130. package/src/commands/browser/start-browser.ts +0 -17
  131. package/src/commands/build.ts +0 -125
  132. package/src/commands/common/browserUtils.ts +0 -80
  133. package/src/commands/common/getDefaultExportFromFile.ts +0 -13
  134. package/src/commands/common/getFirstLineNumber.ts +0 -146
  135. package/src/commands/common/sendMessageToClient.ts +0 -8
  136. package/src/commands/common/utils/fileUtils.ts +0 -25
  137. package/src/commands/common/utils/settings.ts +0 -23
  138. package/src/commands/common/utils/webTemplate.ts +0 -46
  139. package/src/commands/testing/saveVisibleHtml.ts +0 -29
  140. package/src/commands/ts-check.ts +0 -88
  141. package/src/common/Logger/Logger/index.ts +0 -64
  142. package/src/common/Logger/index.ts +0 -64
  143. package/src/common/asyncLocalStorage/index.ts +0 -29
  144. package/src/common/cleanEnvironmentVariables.ts +0 -13
  145. package/src/common/constants.ts +0 -1
  146. package/src/common/contextStorageStateHelpers.ts +0 -71
  147. package/src/common/getPlaywrightConstructs.ts +0 -283
  148. package/src/common/jwtTokenManager.ts +0 -111
  149. package/src/common/settingsSchema.ts +0 -16
  150. package/src/common/telemetry.ts +0 -49
  151. package/src/index.ts +0 -14
  152. package/src/runtime/RunError.ts +0 -16
  153. package/src/runtime/downloadDirectory.ts +0 -14
  154. package/src/runtime/enums.ts +0 -11
  155. package/src/runtime/executionHelpers.test.ts +0 -70
  156. package/src/runtime/extendPayload.ts +0 -22
  157. package/src/runtime/extendTimeout.ts +0 -32
  158. package/src/runtime/requestMoreInfo.ts +0 -40
  159. package/src/runtime/runInfo.ts +0 -19
  160. package/vite.config.ts +0 -17
  161. /package/{src → dist}/common/assets/browser_scripts.js +0 -0
  162. /package/{src → dist}/runtime/enums.d.ts +0 -0
  163. /package/{src → dist}/runtime/export.d.ts +0 -0
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.backendFunctionsTokenManager = void 0;
7
+ exports.callBackendFunctionWithToken = callBackendFunctionWithToken;
8
+ var _crossFetch = _interopRequireDefault(require("cross-fetch"));
9
+ var jwt = _interopRequireWildcard(require("jsonwebtoken"));
10
+ var _neverthrow = require("neverthrow");
11
+ function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
12
+ function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && 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; }
13
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
14
+ class JwtTokenManager {
15
+ constructor(refreshTokenPath) {
16
+ this.refreshTokenPath = refreshTokenPath;
17
+ this._token = undefined;
18
+ }
19
+ get token() {
20
+ return this._token;
21
+ }
22
+ set token(newToken) {
23
+ if (this._token != newToken) {
24
+ this._token = newToken;
25
+ void this.scheduleTokenRefresh();
26
+ }
27
+ }
28
+ get timeToRefresh() {
29
+ if (!this._token) return;
30
+ const payload = jwt.decode(this._token);
31
+ if (!payload || typeof payload == "string") return;
32
+ const expiry = payload.expiry;
33
+ if (!expiry || typeof expiry !== "number") return;
34
+ const timeWindow = 60 * 1000;
35
+ const timeToRefresh = expiry - Date.now() - timeWindow;
36
+ return Math.max(timeToRefresh, timeWindow);
37
+ }
38
+ async scheduleTokenRefresh() {
39
+ var _process$env$RUN_ENVI;
40
+ if (((_process$env$RUN_ENVI = process.env.RUN_ENVIRONMENT) === null || _process$env$RUN_ENVI === void 0 ? void 0 : _process$env$RUN_ENVI.toLowerCase()) !== "authoring") return;
41
+ const timeToRefresh = this.timeToRefresh;
42
+ if (timeToRefresh === undefined) return;
43
+ if (this.tokenRefreshTimeout) clearTimeout(this.tokenRefreshTimeout);
44
+ this.tokenRefreshTimeout = setTimeout(async () => {
45
+ const result = await this.refreshToken();
46
+ if (result && result.isErr()) {
47
+ console.error(`[Internal Error] ${result.error}`);
48
+ return;
49
+ }
50
+ await this.scheduleTokenRefresh();
51
+ }, timeToRefresh);
52
+ }
53
+ async refreshToken() {
54
+ var _process$env$RUN_ENVI2;
55
+ if (((_process$env$RUN_ENVI2 = process.env.RUN_ENVIRONMENT) === null || _process$env$RUN_ENVI2 === void 0 ? void 0 : _process$env$RUN_ENVI2.toLowerCase()) !== "authoring") return;
56
+ const res = await this.fetchWithToken(this.refreshTokenPath, {
57
+ method: "GET"
58
+ });
59
+ if (res.status === 401) {
60
+ return (0, _neverthrow.err)("Unauthorized");
61
+ }
62
+ const jsonResult = await _neverthrow.ResultAsync.fromPromise(res.json(), () => "not json");
63
+ if (jsonResult.isErr()) return;
64
+ const newToken = jsonResult.value.token;
65
+ if (newToken) this._token = newToken;
66
+ }
67
+ fetchWithToken(...[input, init]) {
68
+ const headers = new Headers(init === null || init === void 0 ? void 0 : init.headers);
69
+ headers.set("Authorization", `Bearer ${this.token}`);
70
+ return (0, _crossFetch.default)(input, {
71
+ ...init,
72
+ headers
73
+ });
74
+ }
75
+ }
76
+ const backendFunctionsPath = `${process.env.FUNCTIONS_DOMAIN}/api/${process.env.INTUNED_WORKSPACE_ID}/functions/${process.env.INTUNED_INTEGRATION_ID}`;
77
+ const backendFunctionsTokenManager = exports.backendFunctionsTokenManager = new JwtTokenManager(`${backendFunctionsPath}/refreshBackendFunctionsToken`);
78
+ backendFunctionsTokenManager.token = process.env.INTUNED_AUTHORING_SESSION_BACKEND_FUNCTIONS_TOKEN;
79
+ function callBackendFunctionWithToken(path, init) {
80
+ return backendFunctionsTokenManager.fetchWithToken(`${backendFunctionsPath}/${path}`, init);
81
+ }
@@ -0,0 +1,71 @@
1
+ import { RunAutomationResponse } from "./types";
2
+ import { RunErrorOptions } from "src/runtime/export";
3
+ export declare const apiNotFoundErrorCode = "APINotFoundError";
4
+ export declare const invalidApiErrorCode = "InvalidAPIError";
5
+ export declare const invalidCheckErrorCode = "InvalidCheckError";
6
+ export declare const abortedErrorCode = "AbortedError";
7
+ export declare const authRequiredErrorCode = "AuthRequiredError";
8
+ export declare const authCheckNotFoundErrorCode = "AuthCheckNotFoundError";
9
+ export declare const authCheckFailedErrorCode = "AuthCheckFailedError";
10
+ export declare const maxLevelsExceededErrorCode = "MaxLevelsExceededError";
11
+ export declare const automationError = "AutomationError";
12
+ export declare const runAutomationErrorCodes: readonly ["APINotFoundError", "InvalidAPIError", "InvalidCheckError", "AbortedError", "AuthRequiredError", "AuthCheckNotFoundError", "AuthCheckFailedError", "MaxLevelsExceededError", "AutomationError"];
13
+ export type RunAutomationErrorCode = (typeof runAutomationErrorCodes)[number];
14
+ export declare abstract class RunAutomationError<T = any> {
15
+ code: RunAutomationErrorCode;
16
+ statusCode: number;
17
+ wrapped: boolean;
18
+ message: string;
19
+ cause?: RunAutomationError;
20
+ details?: T;
21
+ get apiResponse(): RunAutomationResponse;
22
+ get json(): {
23
+ code: "APINotFoundError" | "InvalidAPIError" | "InvalidCheckError" | "AbortedError" | "AuthRequiredError" | "AuthCheckNotFoundError" | "AuthCheckFailedError" | "MaxLevelsExceededError" | "AutomationError";
24
+ details: T | undefined;
25
+ cause: any;
26
+ };
27
+ }
28
+ export declare class ApiNotFoundError extends RunAutomationError {
29
+ constructor(apiName: string);
30
+ }
31
+ export declare class InvalidApiError extends RunAutomationError {
32
+ constructor(message: string);
33
+ }
34
+ export declare class InvalidCheckError extends RunAutomationError {
35
+ constructor(message: string, cause?: RunAutomationError);
36
+ }
37
+ export declare class AbortedError extends RunAutomationError {
38
+ constructor();
39
+ }
40
+ export declare class AuthRequiredError extends RunAutomationError {
41
+ constructor();
42
+ }
43
+ export declare class AuthCheckNotFoundError extends RunAutomationError {
44
+ constructor();
45
+ }
46
+ export declare class AuthCheckFailedError extends RunAutomationError {
47
+ constructor();
48
+ get apiResponse(): {
49
+ status: number;
50
+ body: {
51
+ status: number;
52
+ error: string;
53
+ message: string;
54
+ };
55
+ };
56
+ }
57
+ export declare class MaxLevelsExceededError extends RunAutomationError<{
58
+ levels: number;
59
+ }> {
60
+ constructor(levels: number);
61
+ }
62
+ export declare class AutomationError extends RunAutomationError<{
63
+ name?: string;
64
+ message?: string;
65
+ statusCode?: number;
66
+ errorCode?: string;
67
+ options?: RunErrorOptions;
68
+ }> {
69
+ error: any;
70
+ constructor(error: any);
71
+ }
@@ -0,0 +1,172 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.runAutomationErrorCodes = exports.maxLevelsExceededErrorCode = exports.invalidCheckErrorCode = exports.invalidApiErrorCode = exports.automationError = exports.authRequiredErrorCode = exports.authCheckNotFoundErrorCode = exports.authCheckFailedErrorCode = exports.apiNotFoundErrorCode = exports.abortedErrorCode = exports.RunAutomationError = exports.MaxLevelsExceededError = exports.InvalidCheckError = exports.InvalidApiError = exports.AutomationError = exports.AuthRequiredError = exports.AuthCheckNotFoundError = exports.AuthCheckFailedError = exports.ApiNotFoundError = exports.AbortedError = void 0;
7
+ var _runtime = require("../../runtime");
8
+ var playwright = _interopRequireWildcard(require("@intuned/playwright-core"));
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; }
11
+ const apiNotFoundErrorCode = exports.apiNotFoundErrorCode = "APINotFoundError";
12
+ const invalidApiErrorCode = exports.invalidApiErrorCode = "InvalidAPIError";
13
+ const invalidCheckErrorCode = exports.invalidCheckErrorCode = "InvalidCheckError";
14
+ const abortedErrorCode = exports.abortedErrorCode = "AbortedError";
15
+ const authRequiredErrorCode = exports.authRequiredErrorCode = "AuthRequiredError";
16
+ const authCheckNotFoundErrorCode = exports.authCheckNotFoundErrorCode = "AuthCheckNotFoundError";
17
+ const authCheckFailedErrorCode = exports.authCheckFailedErrorCode = "AuthCheckFailedError";
18
+ const maxLevelsExceededErrorCode = exports.maxLevelsExceededErrorCode = "MaxLevelsExceededError";
19
+ const automationError = exports.automationError = "AutomationError";
20
+ const runAutomationErrorCodes = exports.runAutomationErrorCodes = [apiNotFoundErrorCode, invalidApiErrorCode, invalidCheckErrorCode, abortedErrorCode, authRequiredErrorCode, authCheckNotFoundErrorCode, authCheckFailedErrorCode, maxLevelsExceededErrorCode, automationError];
21
+ class RunAutomationError {
22
+ wrapped = false;
23
+ get apiResponse() {
24
+ if (this.wrapped) {
25
+ return {
26
+ status: 200,
27
+ body: {
28
+ status: this.statusCode,
29
+ error: this.code,
30
+ message: this.message
31
+ }
32
+ };
33
+ }
34
+ return {
35
+ status: this.statusCode,
36
+ body: {
37
+ error: this.code,
38
+ message: this.message
39
+ }
40
+ };
41
+ }
42
+ get json() {
43
+ var _this$cause;
44
+ return {
45
+ code: this.code,
46
+ details: this.details,
47
+ cause: (_this$cause = this.cause) === null || _this$cause === void 0 ? void 0 : _this$cause.json
48
+ };
49
+ }
50
+ }
51
+ exports.RunAutomationError = RunAutomationError;
52
+ class ApiNotFoundError extends RunAutomationError {
53
+ constructor(apiName) {
54
+ super();
55
+ this.code = apiNotFoundErrorCode;
56
+ this.statusCode = 404;
57
+ this.message = `API ${apiName} not found`;
58
+ }
59
+ }
60
+ exports.ApiNotFoundError = ApiNotFoundError;
61
+ class InvalidApiError extends RunAutomationError {
62
+ constructor(message) {
63
+ super();
64
+ this.code = invalidApiErrorCode;
65
+ this.statusCode = 400;
66
+ this.message = `API is invalid: ${message}`;
67
+ }
68
+ }
69
+ exports.InvalidApiError = InvalidApiError;
70
+ class InvalidCheckError extends RunAutomationError {
71
+ constructor(message, cause) {
72
+ super();
73
+ this.code = invalidCheckErrorCode;
74
+ this.statusCode = 400;
75
+ this.message = message;
76
+ this.cause = cause;
77
+ }
78
+ }
79
+ exports.InvalidCheckError = InvalidCheckError;
80
+ class AbortedError extends RunAutomationError {
81
+ constructor() {
82
+ super();
83
+ this.code = abortedErrorCode;
84
+ this.statusCode = 200;
85
+ this.message = "Operation was aborted";
86
+ }
87
+ }
88
+ exports.AbortedError = AbortedError;
89
+ class AuthRequiredError extends RunAutomationError {
90
+ constructor() {
91
+ super();
92
+ this.code = authRequiredErrorCode;
93
+ this.statusCode = 401;
94
+ this.message = "Authentication is required";
95
+ }
96
+ }
97
+ exports.AuthRequiredError = AuthRequiredError;
98
+ class AuthCheckNotFoundError extends RunAutomationError {
99
+ constructor() {
100
+ super();
101
+ this.code = authCheckNotFoundErrorCode;
102
+ this.statusCode = 404;
103
+ this.message = "Auth check not found";
104
+ }
105
+ }
106
+ exports.AuthCheckNotFoundError = AuthCheckNotFoundError;
107
+ class AuthCheckFailedError extends RunAutomationError {
108
+ constructor() {
109
+ super();
110
+ this.code = authCheckFailedErrorCode;
111
+ this.statusCode = 401;
112
+ this.message = "auth session check failed";
113
+ }
114
+ get apiResponse() {
115
+ return {
116
+ status: 200,
117
+ body: {
118
+ status: this.statusCode,
119
+ error: "AUTH_SESSION_CHECK_FAILED",
120
+ message: this.message
121
+ }
122
+ };
123
+ }
124
+ }
125
+ exports.AuthCheckFailedError = AuthCheckFailedError;
126
+ class MaxLevelsExceededError extends RunAutomationError {
127
+ constructor(levels) {
128
+ super();
129
+ this.code = maxLevelsExceededErrorCode;
130
+ this.statusCode = 400;
131
+ this.message = `Max levels exceeded. Only ${levels} levels are supported`;
132
+ this.details = {
133
+ levels
134
+ };
135
+ }
136
+ }
137
+ exports.MaxLevelsExceededError = MaxLevelsExceededError;
138
+ class AutomationError extends RunAutomationError {
139
+ constructor(error) {
140
+ super();
141
+ this.error = error;
142
+ this.code = automationError;
143
+ if (error instanceof playwright.errors.TimeoutError) {
144
+ this.statusCode = 500;
145
+ this.message = `[${error.name}] ${error.message}`;
146
+ this.details = {
147
+ name: error.name,
148
+ message: error.message
149
+ };
150
+ return;
151
+ }
152
+ if (error instanceof _runtime.RunError) {
153
+ this.wrapped = true;
154
+ this.statusCode = error.options.status_code ?? 500;
155
+ this.message = `[${error.options.error_code ?? error.name}] ${error.message}`;
156
+ this.details = {
157
+ name: error.name,
158
+ statusCode: error.options.status_code,
159
+ errorCode: error.options.error_code,
160
+ message: error.message,
161
+ options: error.options
162
+ };
163
+ }
164
+ this.statusCode = 500;
165
+ this.message = `[${(error === null || error === void 0 ? void 0 : error.name) ?? error}] ${error === null || error === void 0 ? void 0 : error.message}`;
166
+ this.details = {
167
+ name: error === null || error === void 0 ? void 0 : error.name,
168
+ message: error === null || error === void 0 ? void 0 : error.message
169
+ };
170
+ }
171
+ }
172
+ exports.AutomationError = AutomationError;
@@ -0,0 +1,12 @@
1
+ import { Result } from "neverthrow";
2
+ import { RunAutomationError } from "./errors";
3
+ import { Page, BrowserContext } from "@intuned/playwright-core";
4
+ import { ExtendedRunApiParameters, RunApiResult, RunApiResultWithSessionOk } from "./types";
5
+ export * from "./types";
6
+ export * from "./errors";
7
+ export declare function runApiGenerator<ResultType = any, _YieldType = any, _NextType = any>(params: ExtendedRunApiParameters & {
8
+ retrieveSession: true;
9
+ }): AsyncGenerator<_YieldType, RunApiResult<ResultType, RunApiResultWithSessionOk>, _NextType>;
10
+ export declare function runApiGenerator<ResultType = any, _YieldType = any, _NextType = any>(params: ExtendedRunApiParameters): AsyncGenerator<_YieldType, RunApiResult<ResultType>, _NextType>;
11
+ export declare function runApi<ResultType = any>(params: ExtendedRunApiParameters): Promise<RunApiResult<ResultType>>;
12
+ export declare function checkAuthSessionWithRetries(page: Page, context: BrowserContext, retries?: number): Promise<Result<boolean, RunAutomationError>>;
@@ -0,0 +1,288 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ var _exportNames = {
7
+ runApiGenerator: true,
8
+ runApi: true,
9
+ checkAuthSessionWithRetries: true
10
+ };
11
+ exports.checkAuthSessionWithRetries = checkAuthSessionWithRetries;
12
+ exports.runApi = runApi;
13
+ exports.runApiGenerator = runApiGenerator;
14
+ var _downloadDirectory = require("../../runtime/downloadDirectory");
15
+ var _asyncLocalStorage = require("../asyncLocalStorage");
16
+ var _fsExtra = _interopRequireWildcard(require("fs-extra"));
17
+ var fs = _fsExtra;
18
+ var _jwtTokenManager = require("../jwtTokenManager");
19
+ var _contextStorageStateHelpers = require("../contextStorageStateHelpers");
20
+ var _neverthrow = require("neverthrow");
21
+ var _errors = require("./errors");
22
+ Object.keys(_errors).forEach(function (key) {
23
+ if (key === "default" || key === "__esModule") return;
24
+ if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
25
+ if (key in exports && exports[key] === _errors[key]) return;
26
+ Object.defineProperty(exports, key, {
27
+ enumerable: true,
28
+ get: function () {
29
+ return _errors[key];
30
+ }
31
+ });
32
+ });
33
+ var _constants = require("../constants");
34
+ var _getPlaywrightConstructs = require("../getPlaywrightConstructs");
35
+ var _types = require("./types");
36
+ Object.keys(_types).forEach(function (key) {
37
+ if (key === "default" || key === "__esModule") return;
38
+ if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
39
+ if (key in exports && exports[key] === _types[key]) return;
40
+ Object.defineProperty(exports, key, {
41
+ enumerable: true,
42
+ get: function () {
43
+ return _types[key];
44
+ }
45
+ });
46
+ });
47
+ 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); }
48
+ 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; }
49
+ async function* runApiGenerator({
50
+ retrieveSession = false,
51
+ abortSignal,
52
+ ...input
53
+ }) {
54
+ let traceStarted = false;
55
+ const {
56
+ automationFunction,
57
+ runOptions,
58
+ tracing,
59
+ auth,
60
+ functionsToken
61
+ } = _types.runApiParametersSchema.parse(input);
62
+ _jwtTokenManager.backendFunctionsTokenManager.token = functionsToken;
63
+ const downloadsPath = (0, _downloadDirectory.getDownloadDirectoryPath)();
64
+ let page;
65
+ let context;
66
+ if (runOptions.environment === "deployed") {
67
+ const {
68
+ headless,
69
+ proxy
70
+ } = runOptions;
71
+ ({
72
+ page,
73
+ context
74
+ } = await (0, _getPlaywrightConstructs.getProductionPlaywrightConstructs)({
75
+ headless,
76
+ proxy,
77
+ downloadsPath,
78
+ storageState: auth === null || auth === void 0 ? void 0 : auth.session
79
+ }));
80
+ } else {
81
+ const {
82
+ mode,
83
+ cdpAddress
84
+ } = runOptions;
85
+ ({
86
+ page,
87
+ context
88
+ } = await (0, _getPlaywrightConstructs.getPlaywrightConstructsForMode)(mode, cdpAddress, auth === null || auth === void 0 ? void 0 : auth.session));
89
+ }
90
+ const executionContext = (0, _asyncLocalStorage.getExecutionContext)();
91
+ if (!executionContext) {
92
+ throw "";
93
+ }
94
+ async function saveTraceIfNeeded({
95
+ errorMessage
96
+ }) {
97
+ if (!tracing.enabled || !traceStarted) {
98
+ return;
99
+ }
100
+ try {
101
+ await context.tracing.stop({
102
+ path: tracing.filePath
103
+ });
104
+ } catch (error) {
105
+ console.log(errorMessage, error === null || error === void 0 ? void 0 : error.message);
106
+ await (0, _fsExtra.remove)(tracing.filePath);
107
+ }
108
+ }
109
+ if (tracing.enabled) {
110
+ await context.tracing.start({
111
+ screenshots: true,
112
+ snapshots: true,
113
+ sources: true
114
+ });
115
+ traceStarted = true;
116
+ }
117
+ const abortSymbol = Symbol("abort");
118
+ const abortPromise = new Promise(resolve => {
119
+ if (!abortSignal) return;
120
+ abortSignal.addEventListener("abort", () => {
121
+ resolve(abortSymbol);
122
+ });
123
+ });
124
+ if (auth && auth.session.type === "state") {
125
+ await (0, _contextStorageStateHelpers.setContextStorageState)(context, auth.session.state);
126
+ }
127
+ async function* runAutomation() {
128
+ var _getExecutionContext;
129
+ if (auth !== null && auth !== void 0 && auth.runCheck) {
130
+ if (!auth.session) {
131
+ return (0, _neverthrow.err)({
132
+ code: "AuthRequiredError"
133
+ });
134
+ }
135
+ console.log("Running auth check");
136
+ const authCheckResult = await checkAuthSessionWithRetries(page, context, 2);
137
+ if (authCheckResult.isErr()) {
138
+ const error = authCheckResult.error;
139
+ if (["APINotFoundError", "InvalidAPIError"].includes(error.code)) {
140
+ return (0, _neverthrow.err)(new _errors.InvalidCheckError(`Auth session check function failed`, error));
141
+ }
142
+ return authCheckResult;
143
+ }
144
+ if (!authCheckResult.value) {
145
+ return (0, _neverthrow.err)({
146
+ code: "AuthCheckFailedError"
147
+ });
148
+ }
149
+ }
150
+ console.log("Running function", automationFunction.name);
151
+ const args = [...(automationFunction.params ? [automationFunction.params] : []), page, context];
152
+ const importResult = await importFunction(automationFunction.name);
153
+ if (importResult.isErr()) {
154
+ return importResult;
155
+ }
156
+ let result;
157
+ if (importResult.value.type === "async-generator") {
158
+ const generator = importResult.value.generator(...args);
159
+ let next = undefined;
160
+ while (true) {
161
+ const generatorResult = await generator.next(...(next ? [next] : []));
162
+ if (!generatorResult.done) {
163
+ next = yield generatorResult.value;
164
+ continue;
165
+ }
166
+ result = generatorResult.value;
167
+ break;
168
+ }
169
+ } else {
170
+ result = await importResult.value.func(...args);
171
+ }
172
+ return (0, _neverthrow.ok)({
173
+ result,
174
+ extendedPayloads: (_getExecutionContext = (0, _asyncLocalStorage.getExecutionContext)()) === null || _getExecutionContext === void 0 ? void 0 : _getExecutionContext.extendedPayloads,
175
+ session: retrieveSession ? await (0, _contextStorageStateHelpers.getContextStorageState)(context) : undefined
176
+ });
177
+ }
178
+ try {
179
+ const generator = runAutomation();
180
+ let next = undefined;
181
+ while (true) {
182
+ const result = await Promise.race([generator.next(await next), abortPromise]);
183
+ if (result === abortSymbol) {
184
+ return (0, _neverthrow.err)(new _errors.AbortedError());
185
+ }
186
+ if (!result.done) {
187
+ next = yield result.value;
188
+ continue;
189
+ }
190
+ return result.value;
191
+ }
192
+ } catch (error) {
193
+ console.log("run errored", error);
194
+ return (0, _neverthrow.err)(new _errors.AutomationError(error));
195
+ } finally {
196
+ await saveTraceIfNeeded({
197
+ errorMessage: "failed to save trace"
198
+ });
199
+ await context.close();
200
+ await fs.remove(downloadsPath);
201
+ }
202
+ }
203
+ async function runApi(params) {
204
+ const generator = runApiGenerator(params);
205
+ const {
206
+ value,
207
+ done
208
+ } = await generator.next();
209
+ if (done) {
210
+ return value;
211
+ }
212
+ return (0, _neverthrow.err)(new _errors.InvalidApiError("Expected API to be async function, got async generator"));
213
+ }
214
+ async function checkAuthSessionWithRetries(page, context, retries = 3) {
215
+ if (retries === 0) {
216
+ return (0, _neverthrow.ok)(false);
217
+ }
218
+ let tryNumber = 0;
219
+ console.log("Checking auth session with retries", `${_constants.AUTH_SESSIONS_FOLDER_NAME}/check`);
220
+ const importResult = await importFunction(`${_constants.AUTH_SESSIONS_FOLDER_NAME}/check`);
221
+ if (importResult.isErr()) {
222
+ return (0, _neverthrow.err)(importResult.error);
223
+ }
224
+ if (importResult.value.type !== "async") {
225
+ return (0, _neverthrow.err)(new _errors.InvalidCheckError("Check function is not an async function"));
226
+ }
227
+ const check = importResult.value.func;
228
+ while (retries > tryNumber) {
229
+ const result = await check(page, context);
230
+ if (result) return (0, _neverthrow.ok)(true);
231
+ tryNumber++;
232
+ }
233
+ return (0, _neverthrow.ok)(false);
234
+ }
235
+ async function importFunction(path) {
236
+ const functionNameParts = path.split("/");
237
+ const functionNameDepth = functionNameParts.length;
238
+ try {
239
+ let imported = undefined;
240
+ switch (functionNameDepth) {
241
+ case 1:
242
+ imported = await (specifier => new Promise(r => r(specifier)).then(s => _interopRequireWildcard(require(s))))(`${functionNameParts[0]}.ts`);
243
+ break;
244
+ case 2:
245
+ imported = await (specifier => new Promise(r => r(specifier)).then(s => _interopRequireWildcard(require(s))))(`${functionNameParts[0]}/${functionNameParts[1]}.ts`);
246
+ break;
247
+ case 3:
248
+ imported = await (specifier => new Promise(r => r(specifier)).then(s => _interopRequireWildcard(require(s))))(`${functionNameParts[0]}/${functionNameParts[1]}/${functionNameParts[2]}.ts`);
249
+ break;
250
+ case 4:
251
+ imported = await (specifier => new Promise(r => r(specifier)).then(s => _interopRequireWildcard(require(s))))(`${functionNameParts[0]}/${functionNameParts[1]}/${functionNameParts[2]}/${functionNameParts[3]}.ts`);
252
+ break;
253
+ case 5:
254
+ imported = await (specifier => new Promise(r => r(specifier)).then(s => _interopRequireWildcard(require(s))))(`${functionNameParts[0]}/${functionNameParts[1]}/${functionNameParts[2]}/${functionNameParts[3]}/${functionNameParts[4]}.ts`);
255
+ break;
256
+ case 6:
257
+ imported = await (specifier => new Promise(r => r(specifier)).then(s => _interopRequireWildcard(require(s))))(`${functionNameParts[0]}/${functionNameParts[1]}/${functionNameParts[2]}/${functionNameParts[3]}/${functionNameParts[4]}/${functionNameParts[5]}.ts`);
258
+ break;
259
+ default:
260
+ return (0, _neverthrow.err)(new _errors.MaxLevelsExceededError(5));
261
+ }
262
+ if (!imported || !imported.default || !imported.default.constructor) {
263
+ return (0, _neverthrow.err)(new _errors.InvalidApiError("API file path does not have a default export"));
264
+ }
265
+ if (imported.default.constructor.name === "AsyncGeneratorFunction") {
266
+ return (0, _neverthrow.ok)({
267
+ type: "async-generator",
268
+ generator: imported.default
269
+ });
270
+ }
271
+ if (imported.default.constructor.name === "AsyncFunction") {
272
+ return (0, _neverthrow.ok)({
273
+ type: "async",
274
+ func: imported.default
275
+ });
276
+ }
277
+ return (0, _neverthrow.err)(new _errors.InvalidApiError("API file path does not have a default async function/generator export"));
278
+ } catch (error) {
279
+ if (error.message.includes("Unknown variable dynamic import")) {
280
+ return (0, _neverthrow.err)(new _errors.ApiNotFoundError(path));
281
+ }
282
+ if ((error === null || error === void 0 ? void 0 : error.code) === "ERR_MODULE_NOT_FOUND") {
283
+ console.log("API not found", error);
284
+ return (0, _neverthrow.err)(new _errors.ApiNotFoundError(path));
285
+ }
286
+ throw error;
287
+ }
288
+ }