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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/bin/intuned-api-run +1 -1
  2. package/bin/intuned-auth-session-check +1 -1
  3. package/bin/intuned-auth-session-create +1 -1
  4. package/bin/intuned-auth-session-load +1 -1
  5. package/bin/intuned-auth-session-refresh +1 -1
  6. package/bin/intuned-browser-save-state +1 -1
  7. package/bin/intuned-browser-start +1 -1
  8. package/bin/intuned-build +1 -1
  9. package/bin/intuned-ts-check +1 -1
  10. package/dist/commands/api/run.js +83 -156
  11. package/dist/commands/auth-sessions/load.js +20 -20
  12. package/dist/commands/auth-sessions/run-check.js +39 -45
  13. package/dist/commands/auth-sessions/run-create.js +74 -84
  14. package/dist/commands/browser/save-state.js +7 -12
  15. package/dist/commands/browser/start-browser.js +4 -7
  16. package/dist/commands/build.js +62 -96
  17. package/dist/commands/common/browserUtils.js +30 -41
  18. package/dist/commands/common/getDefaultExportFromFile.d.ts +0 -1
  19. package/dist/commands/common/getDefaultExportFromFile.js +0 -12
  20. package/dist/commands/common/getFirstLineNumber.js +83 -90
  21. package/dist/commands/common/{getFirstLineNumber.test.ts → getFirstLineNumber.test.js} +2 -1
  22. package/dist/commands/common/sendMessageToClient.js +2 -4
  23. package/dist/commands/common/utils/fileUtils.js +16 -16
  24. package/dist/commands/common/utils/settings.js +18 -16
  25. package/dist/commands/common/utils/unixSocket.js +36 -43
  26. package/dist/commands/common/utils/webTemplate.js +19 -25
  27. package/dist/commands/interface/run.js +133 -139
  28. package/dist/commands/ts-check.js +41 -44
  29. package/dist/common/Logger/Logger/index.js +46 -40
  30. package/dist/common/Logger/Logger/types.js +1 -1
  31. package/dist/common/Logger/index.js +46 -40
  32. package/dist/common/Logger/types.js +1 -1
  33. package/dist/common/asyncLocalStorage/index.js +4 -4
  34. package/dist/common/cleanEnvironmentVariables.js +9 -11
  35. package/dist/common/constants.js +1 -1
  36. package/dist/common/contextStorageStateHelpers.js +38 -36
  37. package/dist/common/getPlaywrightConstructs.js +158 -187
  38. package/dist/common/jwtTokenManager.js +61 -74
  39. package/dist/common/runApi/errors.js +121 -130
  40. package/dist/common/runApi/index.js +231 -217
  41. package/dist/common/runApi/types.js +41 -55
  42. package/dist/common/settingsSchema.js +6 -9
  43. package/dist/common/telemetry.js +16 -27
  44. package/dist/index.js +3 -3
  45. package/dist/runtime/RunError.js +10 -10
  46. package/dist/runtime/downloadDirectory.js +10 -10
  47. package/dist/runtime/enums.d.ts +11 -1
  48. package/dist/runtime/enums.js +12 -12
  49. package/dist/runtime/export.d.ts +202 -1
  50. package/dist/runtime/extendPayload.js +12 -12
  51. package/dist/runtime/extendTimeout.js +20 -19
  52. package/dist/runtime/index.js +1 -1
  53. package/dist/runtime/requestMoreInfo.js +14 -14
  54. package/dist/runtime/runInfo.js +12 -11
  55. package/package.json +2 -3
  56. package/dist/commands/api/run.ts +0 -105
  57. package/dist/commands/auth-sessions/load.ts +0 -30
  58. package/dist/commands/auth-sessions/run-check.ts +0 -51
  59. package/dist/commands/auth-sessions/run-create.ts +0 -91
  60. package/dist/commands/browser/save-state.ts +0 -14
  61. package/dist/commands/browser/start-browser.ts +0 -11
  62. package/dist/commands/build.ts +0 -78
  63. package/dist/commands/common/browserUtils.ts +0 -45
  64. package/dist/commands/common/getDefaultExportFromFile.ts +0 -11
  65. package/dist/commands/common/getFirstLineNumber.ts +0 -96
  66. package/dist/commands/common/sendMessageToClient.ts +0 -3
  67. package/dist/commands/common/utils/fileUtils.ts +0 -23
  68. package/dist/commands/common/utils/settings.ts +0 -22
  69. package/dist/commands/common/utils/unixSocket.ts +0 -38
  70. package/dist/commands/common/utils/webTemplate.ts +0 -22
  71. package/dist/commands/interface/run.ts +0 -156
  72. package/dist/commands/ts-check.ts +0 -50
  73. package/dist/common/Logger/Logger/index.ts +0 -53
  74. package/dist/common/Logger/index.ts +0 -53
  75. package/dist/common/asyncLocalStorage/index.ts +0 -9
  76. package/dist/common/cleanEnvironmentVariables.ts +0 -10
  77. package/dist/common/constants.ts +0 -1
  78. package/dist/common/contextStorageStateHelpers.ts +0 -43
  79. package/dist/common/getPlaywrightConstructs.ts +0 -181
  80. package/dist/common/jwtTokenManager.ts +0 -71
  81. package/dist/common/runApi/errors.ts +0 -154
  82. package/dist/common/runApi/index.ts +0 -253
  83. package/dist/common/runApi/types.ts +0 -43
  84. package/dist/common/settingsSchema.ts +0 -9
  85. package/dist/common/telemetry.ts +0 -23
  86. package/dist/index.ts +0 -4
  87. package/dist/runtime/RunError.ts +0 -12
  88. package/dist/runtime/downloadDirectory.ts +0 -13
  89. package/dist/runtime/enums.ts +0 -12
  90. package/dist/runtime/extendPayload.ts +0 -15
  91. package/dist/runtime/extendTimeout.ts +0 -24
  92. package/dist/runtime/index.ts +0 -6
  93. package/dist/runtime/requestMoreInfo.ts +0 -18
  94. package/dist/runtime/runInfo.ts +0 -15
  95. /package/dist/{common/Logger/Logger/types.ts → runtime/enums.d.js} +0 -0
  96. /package/dist/runtime/{executionHelpers.test.ts → executionHelpers.test.js} +0 -0
  97. /package/dist/{common/Logger/types.ts → runtime/export.d.js} +0 -0
@@ -1,91 +0,0 @@
1
- #!/usr/bin/env node
2
- import { Argument, program } from "commander";
3
- import * as fs from "fs-extra";
4
- import { prompt } from "promptly";
5
- import { getFullPathInProject } from "../common/utils/fileUtils";
6
- import { getSettings } from "../common/utils/settings";
7
- import dotenv from "dotenv";
8
- import { AUTH_SESSIONS_FOLDER_NAME } from "../../common/constants";
9
- import { runApiGenerator } from "../../common/runApi";
10
- import { runWithContext } from "../../common/asyncLocalStorage";
11
- import { nanoid } from "nanoid";
12
- import { RunEnvironment } from "../../runtime/enums";
13
- dotenv.config({
14
- path: `.env`
15
- });
16
- program.description("run auth session create").option("--cdpAddress <cdpAddress>", "CDP address", "http://localhost:9222").option("-i, --input [file]", "input json file").option("-j, --json [json]", "input json string").option("--authSessionPath <authSession>", "auth session to use when executing the api").option("--pathToSave <pathToSave>", "path to save the auth session, if not provided, will discard the auth session").allowUnknownOption().addArgument(new Argument("<mode>", "mode of execution").choices(["vanilla", "playwright", "playwright-standalone"]).default("playwright-standalone").argOptional()).action(async (mode, {
17
- cdpAddress,
18
- pathToSave,
19
- input,
20
- json
21
- }) => {
22
- let inputData = null;
23
- if (input) {
24
- inputData = await fs.readJSON(input);
25
- } else if (json) {
26
- inputData = JSON.parse(json);
27
- } else {
28
- inputData = {};
29
- }
30
- const setting = await getSettings();
31
- if (!setting.authSessions.enabled) {
32
- throw new Error("auth sessions feature is not enabled");
33
- }
34
- const createFilePath = getFullPathInProject(AUTH_SESSIONS_FOLDER_NAME, "create.ts");
35
- if (!fs.exists(createFilePath)) {
36
- throw new Error("auth session create file not found");
37
- }
38
- async function runCreate() {
39
- const generator = runApiGenerator({
40
- automationFunction: {
41
- name: "auth-sessions/create",
42
- params: inputData ?? {}
43
- },
44
- runOptions: {
45
- environment: "ide",
46
- mode,
47
- cdpAddress
48
- },
49
- retrieveSession: true
50
- });
51
- let nextGeneratorParam = undefined;
52
- while (true) {
53
- const {
54
- value,
55
- done
56
- } = await generator.next(...(nextGeneratorParam ? [nextGeneratorParam] : []));
57
- if (done) {
58
- if (value.isErr()) {
59
- console.log(value.error);
60
- throw new Error(value.error);
61
- }
62
- const fullState = value.value.session;
63
- if (pathToSave) {
64
- const fullPath = getFullPathInProject(pathToSave);
65
- fs.ensureFileSync(fullPath);
66
- await fs.writeJSON(fullPath, fullState);
67
- }
68
- break;
69
- }
70
- if (value.action === "request_more_info" && value.requestType == "multiple_choice") {
71
- nextGeneratorParam = await prompt(value.messageToUser + `, choices: ${value.choices}`, {
72
- validator: input => {
73
- if (!value.choices.includes(input)) {
74
- throw new Error("Please type on of the allowed choices");
75
- }
76
- return input;
77
- }
78
- });
79
- } else if (value.action === "request_more_info" && value.requestType == "otp") {
80
- nextGeneratorParam = await prompt(value.messageToUser, {});
81
- }
82
- }
83
- }
84
- await runWithContext({
85
- runEnvironment: RunEnvironment.IDE,
86
- extendedPayloads: [],
87
- runId: nanoid()
88
- }, runCreate);
89
- process.exit(0);
90
- });
91
- program.parse(process.argv);
@@ -1,14 +0,0 @@
1
- #!/usr/bin/env node
2
- import { program } from "commander";
3
- import { saveSessionFromOpenedBrowser } from "../common/browserUtils";
4
- import dotenv from "dotenv";
5
- dotenv.config({
6
- path: `.env`
7
- });
8
- program.description("save browser state to file storage.json").option("-p, --path [file]", "path for file", "./localSessions/default.json").allowUnknownOption().action(async ({
9
- path
10
- }) => {
11
- await saveSessionFromOpenedBrowser(path);
12
- process.exit(0);
13
- });
14
- program.parse(process.argv);
@@ -1,11 +0,0 @@
1
- #!/usr/bin/env node
2
- import { program } from "commander";
3
- import { startOrRestartBrowser } from "../common/browserUtils";
4
- import dotenv from "dotenv";
5
- dotenv.config({
6
- path: `.env`
7
- });
8
- program.description("start browser testing purposes").allowUnknownOption().action(async () => {
9
- await startOrRestartBrowser();
10
- });
11
- program.parse(process.argv);
@@ -1,78 +0,0 @@
1
- #!/usr/bin/env node
2
- import { program, Argument } from "commander";
3
- import { rollup } from "rollup";
4
- import typescript from "@rollup/plugin-typescript";
5
- import commonjs from "@rollup/plugin-commonjs";
6
- import { nodeResolve } from "@rollup/plugin-node-resolve";
7
- import dynamicImportVars from "@rollup/plugin-dynamic-import-vars";
8
- import json from "@rollup/plugin-json";
9
- import * as fs from "fs-extra";
10
- import * as path from "path";
11
- import { moveWebTemplateFiles } from "./common/utils/webTemplate.js";
12
- function isThirdPartyWarning(warning) {
13
- if (warning.id && /node_modules/.test(warning.id)) return true;
14
- if (warning.ids && warning.ids.every(id => /node_modules/.test(id))) return true;
15
- return false;
16
- }
17
- import dotenv from "dotenv";
18
- dotenv.config();
19
- program.description("build the intuned server").addArgument(new Argument("<mode>", "mode of execution").choices(["vanilla", "playwright"]).default("playwright").argOptional()).argument("[outfile]", "output bundle", "./output/bundle_v2.js").allowUnknownOption().action(async (mode, outfile) => {
20
- await moveWebTemplateFiles();
21
- const currentTemplateTsConfig = path.resolve(path.dirname(import.meta.url), "..", "..", "template.tsconfig.json");
22
- await fs.copy(currentTemplateTsConfig, "./intuned/WebTemplate/tsconfig.json");
23
- await build(outfile, mode);
24
- });
25
- async function build(outfile, mode) {
26
- let bundle = null;
27
- let buildFailed = false;
28
- try {
29
- bundle = await rollup({
30
- input: `./intuned/WebTemplate/index.${mode}.ts`,
31
- output: {
32
- globals: {
33
- crypto: "crypto"
34
- }
35
- },
36
- plugins: [json(), nodeResolve({
37
- exportConditions: ["node"],
38
- preferBuiltins: true
39
- }), typescript({
40
- tsconfig: "./intuned/WebTemplate/tsconfig.json"
41
- }), commonjs({
42
- include: ["node_modules/**", "intuned/WebTemplate/**", "dist", "../typescript-sdk/**", "../typescript-runtime/**"],
43
- extensions: [".js"],
44
- ignoreGlobal: false,
45
- sourceMap: false,
46
- dynamicRequireTargets: ["api/**/*.js", "auth-sessions/**/*.js"],
47
- requireReturnsDefault: "auto",
48
- transformMixedEsModules: true
49
- }), dynamicImportVars({
50
- include: ["**/*.js", "**/*.ts"],
51
- exclude: ["**/*.d.ts", "**/*.js.map"]
52
- })],
53
- onwarn: (warning, warn) => {
54
- if (isThirdPartyWarning(warning)) return;
55
- warn(warning);
56
- },
57
- external: ["@intuned/playwright", "@intuned/playwright-core", "@intuned/runtime", "jsdom", "canvas", "pdfjs-dist", "pdf-to-png-converter", "crypto", "applicationinsights", "fingerprint-generator", "fingerprint-injector"]
58
- });
59
- console.log(`📦 Building ${outfile}`);
60
- const outfileFolder = path.dirname(outfile);
61
- const assetsDir = path.resolve(path.dirname(import.meta.url), "..", "common", "assets");
62
- await fs.copy(assetsDir, `${outfileFolder}/assets`);
63
- await bundle.write({
64
- format: "cjs",
65
- file: outfile,
66
- inlineDynamicImports: true
67
- });
68
- console.log(`✨ Build succeeded: ${outfile}`);
69
- } catch (error) {
70
- buildFailed = true;
71
- console.error("error", error);
72
- }
73
- if (buildFailed) {
74
- console.error("build failed");
75
- process.exit(1);
76
- }
77
- }
78
- program.parse(process.argv);
@@ -1,45 +0,0 @@
1
- import { spawn } from "child_process";
2
- import * as playwright from "@intuned/playwright-core";
3
- import * as fs from "fs-extra";
4
- import { getFullPathInProject } from "./utils/fileUtils.js";
5
- import { getContextStorageState } from "../../common/contextStorageStateHelpers";
6
- export const REMOTE_DEBUGGING_PORT = 9222;
7
- export const getChromiumLaunchArgs = () => ["--no-sandbox", `--remote-debugging-port=${REMOTE_DEBUGGING_PORT}`, `--user-data-dir=/tmp/${Date.now()}`, "--new-window", "--start-maximized", "--disable-popup-blocking"];
8
- async function getBrowser() {
9
- let playwrightBrowser = null;
10
- try {
11
- playwrightBrowser = await playwright.chromium.connectOverCDP(`http://localhost:${REMOTE_DEBUGGING_PORT}`);
12
- } catch (e) {
13
- throw new Error("Browser is not running");
14
- }
15
- return playwrightBrowser;
16
- }
17
- export async function startOrRestartBrowser() {
18
- const chromiumPath = await playwright.chromium.executablePath();
19
- const chromeInstanceProcess = spawn(chromiumPath, getChromiumLaunchArgs());
20
- chromeInstanceProcess.stdout.on("data", data => {
21
- console.log(`Chrome stdout: ${data}`);
22
- });
23
- chromeInstanceProcess.stderr.on("data", data => {
24
- console.error(`Chrome stderr: ${data}`);
25
- });
26
- }
27
- export async function saveSessionFromOpenedBrowser(path) {
28
- const browser = await getBrowser();
29
- const context = await browser.contexts()[0];
30
- return saveSession(path, context);
31
- }
32
- export async function loadState(path, context) {
33
- const fullPath = getFullPathInProject(path);
34
- if (!(await fs.pathExists(fullPath))) {
35
- throw new Error("session file does not exist");
36
- }
37
- const data = await fs.readJson(fullPath);
38
- await context.addCookies(data.cookies);
39
- }
40
- export async function saveSession(path, context) {
41
- const fullState = await getContextStorageState(context);
42
- const fullPath = getFullPathInProject(path);
43
- fs.ensureFileSync(fullPath);
44
- await fs.writeJSON(fullPath, fullState);
45
- }
@@ -1,11 +0,0 @@
1
- export async function getDefaultExportFromFile(apiFilePath) {
2
- require("ts-node").register({
3
- transpileOnly: true,
4
- compilerOptions: {
5
- lib: ["dom", "es2020"]
6
- }
7
- });
8
- const imported = await import(apiFilePath);
9
- const defaultExport = imported.default;
10
- return defaultExport;
11
- }
@@ -1,96 +0,0 @@
1
- import { ts, Project, ModuleKind, ScriptTarget, Node } from "ts-morph";
2
- import { SourceMapConsumer } from "source-map";
3
- function compileTypeScript(apiFilePath) {
4
- const compilerOptions = {
5
- lib: ["dom", "es2020"],
6
- sourceMap: true,
7
- inlineSourceMap: true,
8
- inlineSources: true,
9
- declaration: false,
10
- noEmit: false,
11
- module: ModuleKind.CommonJS,
12
- target: ScriptTarget.ES2020
13
- };
14
- const project = new Project({
15
- compilerOptions
16
- });
17
- const sourceFile = project.addSourceFileAtPath(apiFilePath);
18
- const outputJS = project.emitToMemory({
19
- targetSourceFile: sourceFile
20
- });
21
- const outputJSText = outputJS.getFiles()[0].text;
22
- return {
23
- sourceFile,
24
- outputJSText
25
- };
26
- }
27
- export function findFirstExecutableLine(sourceFile) {
28
- var _defaultExportSymbol$;
29
- let functionBody;
30
- const defaultExportSymbol = sourceFile.getDefaultExportSymbol();
31
- const defaultExportDeclaration = defaultExportSymbol === null || defaultExportSymbol === void 0 || (_defaultExportSymbol$ = defaultExportSymbol.getDeclarations()) === null || _defaultExportSymbol$ === void 0 ? void 0 : _defaultExportSymbol$[0];
32
- if (defaultExportDeclaration) {
33
- if (defaultExportDeclaration.getKind() === ts.SyntaxKind.FunctionDeclaration) {
34
- functionBody = defaultExportDeclaration.getBody();
35
- } else {
36
- const exportAssignments = sourceFile.getExportAssignments();
37
- for (const exportAssignment of exportAssignments) {
38
- const expression = exportAssignment.getExpression();
39
- if (!expression) continue;
40
- if (expression.getKind() === ts.SyntaxKind.Identifier || expression.getKind() === ts.SyntaxKind.FunctionExpression || expression.getKind() === ts.SyntaxKind.ArrowFunction) {
41
- var _sourceFile$getVariab;
42
- const identifier = expression.getText();
43
- const possiblyExportedFunction = sourceFile.getFunction(identifier) || ((_sourceFile$getVariab = sourceFile.getVariableStatement(identifier)) === null || _sourceFile$getVariab === void 0 ? void 0 : _sourceFile$getVariab.getDescendants().find(node => node.getKind() === ts.SyntaxKind.FunctionExpression || node.getKind() === ts.SyntaxKind.ArrowFunction));
44
- if (possiblyExportedFunction) {
45
- functionBody = possiblyExportedFunction.getBody();
46
- break;
47
- }
48
- }
49
- if (Node.hasBody(expression) && (expression.getKind() === ts.SyntaxKind.FunctionExpression || expression.getKind() === ts.SyntaxKind.ArrowFunction)) {
50
- functionBody = expression.getBody();
51
- break;
52
- }
53
- }
54
- }
55
- }
56
- if (!functionBody || !Node.isStatemented(functionBody)) {
57
- return -1;
58
- }
59
- if (functionBody.getStatements().length === 0) {
60
- return -1;
61
- }
62
- const position = functionBody.getStatements()[0].getStart();
63
- return sourceFile.getLineAndColumnAtPos(position);
64
- }
65
- async function getSourceMap(jsCode) {
66
- const sourceMapBase64 = jsCode.substring(jsCode.lastIndexOf("//# sourceMappingURL=data:application/json;base64,") + "//# sourceMappingURL=data:application/json;base64,".length);
67
- const sourceMapText = Buffer.from(sourceMapBase64, "base64").toString("utf-8");
68
- const sourceMap = JSON.parse(sourceMapText);
69
- return new SourceMapConsumer(sourceMap);
70
- }
71
- async function mapFirstLineNumberBySourceMap(sourceFileName, jsCode, line, column) {
72
- const sourceMap = await getSourceMap(jsCode);
73
- const generatedLineNumber = sourceMap.generatedPositionFor({
74
- source: sourceFileName,
75
- line,
76
- column
77
- }).line;
78
- if (!generatedLineNumber) return -1;
79
- return generatedLineNumber;
80
- }
81
- export default async function getFirstLineNumber(apiFilePath) {
82
- const sourceFileName = apiFilePath.split("/").pop() ?? apiFilePath;
83
- const {
84
- sourceFile,
85
- outputJSText
86
- } = compileTypeScript(apiFilePath);
87
- const result = findFirstExecutableLine(sourceFile);
88
- if (result === -1) return {
89
- sourceFileName,
90
- lineNumber: -1
91
- };
92
- return {
93
- sourceFileName,
94
- lineNumber: await mapFirstLineNumberBySourceMap(sourceFileName, outputJSText, result.line, result.column)
95
- };
96
- }
@@ -1,3 +0,0 @@
1
- export const sendBreakPointOnToClient = (sourceFileName, lineNumber) => {
2
- console.log(`breakpoint on ${sourceFileName}:${lineNumber}`);
3
- };
@@ -1,23 +0,0 @@
1
- import * as path from "path";
2
- import * as fs from "fs-extra";
3
- import dotenv from "dotenv";
4
- dotenv.config();
5
- export function getFullPathInProject(...paths) {
6
- return path.resolve(process.cwd(), process.env.ROOT || "./", ...paths);
7
- }
8
- export async function listProjectFilesAndFolders() {
9
- const projectPath = path.resolve(process.cwd(), process.env.ROOT || "./");
10
- try {
11
- const files = await fs.readdir(projectPath, {
12
- withFileTypes: true
13
- });
14
- return files.map(file => ({
15
- type: file.isDirectory() ? "Folder" : "File",
16
- fullPath: path.join(projectPath, file.name),
17
- name: file.name
18
- }));
19
- } catch (err) {
20
- console.error("Error reading the directory:", err);
21
- throw err;
22
- }
23
- }
@@ -1,22 +0,0 @@
1
- import { getFullPathInProject } from "./fileUtils.js";
2
- import { settingsSchema } from "../../../common/settingsSchema";
3
- import { readJSON } from "fs-extra";
4
- export async function getSettings() {
5
- const settingsFilePath = getFullPathInProject("Intuned.json");
6
- console.log("loading settings");
7
- const settings = await readJSON(settingsFilePath);
8
- if (settings) {
9
- const parsed = settingsSchema.safeParse(settings);
10
- console.log(parsed);
11
- if (parsed.success) {
12
- return parsed.data;
13
- } else {
14
- throw new Error(parsed.error.message);
15
- }
16
- }
17
- return {
18
- authSessions: {
19
- enabled: false
20
- }
21
- };
22
- }
@@ -1,38 +0,0 @@
1
- export class JSONUnixSocket {
2
- static LENGTH_HEADER_LENGTH = 4;
3
- constructor(socket) {
4
- this.socket = socket;
5
- }
6
- sendJSON(data) {
7
- const dataToSend = JSON.stringify(data);
8
- const length = Buffer.byteLength(dataToSend);
9
- const buffer = Buffer.alloc(JSONUnixSocket.LENGTH_HEADER_LENGTH + length);
10
- buffer.writeUInt32BE(length, 0);
11
- buffer.write(dataToSend, JSONUnixSocket.LENGTH_HEADER_LENGTH);
12
- this.socket.write(buffer);
13
- }
14
- async *receiveJSON() {
15
- let buffer = Buffer.alloc(0);
16
- const endPromise = new Promise((resolve, reject) => {
17
- this.socket.once("end", () => {
18
- console.log("end");
19
- resolve();
20
- });
21
- this.socket.once("error", reject);
22
- });
23
- while (true) {
24
- const chunk = await Promise.race([new Promise(resolve => this.socket.once("data", data => resolve(data))), endPromise]);
25
- if (!(chunk instanceof Buffer)) {
26
- break;
27
- }
28
- buffer = Buffer.concat([buffer, chunk]);
29
- const length = buffer.readUInt32BE(0);
30
- if (buffer.length < length + JSONUnixSocket.LENGTH_HEADER_LENGTH) {
31
- continue;
32
- }
33
- const data = buffer.subarray(JSONUnixSocket.LENGTH_HEADER_LENGTH, length + JSONUnixSocket.LENGTH_HEADER_LENGTH);
34
- buffer = buffer.subarray(length + JSONUnixSocket.LENGTH_HEADER_LENGTH);
35
- yield JSON.parse(data.toString());
36
- }
37
- }
38
- }
@@ -1,22 +0,0 @@
1
- import * as fs from "fs-extra";
2
- import * as path from "path";
3
- import { getFullPathInProject, listProjectFilesAndFolders } from "./fileUtils.js";
4
- export const moveWebTemplateFiles = async () => {
5
- await fs.remove("./intuned");
6
- await fs.ensureDir("./intuned");
7
- const currentFileLocation = path.resolve(path.dirname(import.meta.url), "..", "..", "..", "..", "WebTemplate");
8
- await fs.copy(`${currentFileLocation}`, "./intuned/WebTemplate", {
9
- filter: (src, dest) => {
10
- if (src.includes(".d.ts")) {
11
- return false;
12
- }
13
- return true;
14
- }
15
- });
16
- const filesAndFolders = await listProjectFilesAndFolders();
17
- const pathsIgnoreList = [getFullPathInProject("intuned"), getFullPathInProject("node_modules"), getFullPathInProject("package.json"), getFullPathInProject("yarn.lock"), getFullPathInProject(".env")];
18
- const filesToCopy = filesAndFolders.filter(file => !pathsIgnoreList.includes(file.fullPath));
19
- for (const file of filesToCopy) {
20
- await fs.copy(file.fullPath, `./intuned/WebTemplate/${file.name}`);
21
- }
22
- };
@@ -1,156 +0,0 @@
1
- #!/usr/bin/env node
2
- import { program } from "commander";
3
- import dotenv from "dotenv";
4
- import { runWithContext } from "../../common/asyncLocalStorage";
5
- import * as net from "net";
6
- import z from "zod";
7
- import { runApiGenerator, runApiParametersSchema } from "../../common/runApi";
8
- import { RunEnvironment } from "src/runtime/enums";
9
- import { JSONUnixSocket } from "../common/utils/unixSocket";
10
- import { setTimeout } from "timers/promises";
11
- const startRunApiSchema = z.object({
12
- type: z.literal("start"),
13
- parameters: runApiParametersSchema.extend({
14
- retrieveSession: z.boolean(),
15
- context: z.object({
16
- jobId: z.string().optional(),
17
- jobRunId: z.string().optional(),
18
- runId: z.string().optional(),
19
- queueId: z.string().optional()
20
- }).optional()
21
- })
22
- });
23
- const nextRunApiSchema = z.object({
24
- type: z.literal("next"),
25
- parameters: z.object({
26
- value: z.string()
27
- })
28
- });
29
- const abortRunApiSchema = z.object({
30
- type: z.literal("abort"),
31
- parameters: z.object({}).optional()
32
- });
33
- const inputSchema = z.union([startRunApiSchema, nextRunApiSchema, abortRunApiSchema]);
34
- dotenv.config({
35
- path: `.env`
36
- });
37
- program.description("run user automation and communicate using unix socket").argument("<socket-path>", "path to unix socket").action(async socketPath => {
38
- let context;
39
- const throttleTime = 1_000;
40
- let timeoutTimestamp = Date.now();
41
- const client = net.createConnection(socketPath, () => {
42
- console.log("connected to server!");
43
- });
44
- let generator = null;
45
- const abortController = new AbortController();
46
- client.on("end", () => {
47
- console.log("Disconnected from socket");
48
- });
49
- client.on("error", err => {
50
- var _generator;
51
- console.error("Child connection error:", err);
52
- void ((_generator = generator) === null || _generator === void 0 ? void 0 : _generator.throw(err).catch(() => undefined));
53
- });
54
- process.on("SIGINT", () => {
55
- var _generator2;
56
- console.log("Received SIGINT");
57
- void ((_generator2 = generator) === null || _generator2 === void 0 ? void 0 : _generator2.throw(new Error("Interrupted")).catch(() => undefined));
58
- client.end();
59
- process.exit(1);
60
- });
61
- const jsonUnixSocket = new JSONUnixSocket(client);
62
- async function runGeneratorAndSendResult(next) {
63
- if (!generator) return;
64
- const result = await runWithContext(context, () => generator.next(next));
65
- if (result.done) {
66
- const resultToSend = result.value.isOk() ? result.value.value : result.value.error.json;
67
- const success = result.value.isOk();
68
- jsonUnixSocket.sendJSON({
69
- type: "done",
70
- result: resultToSend,
71
- success
72
- });
73
- return true;
74
- } else {
75
- jsonUnixSocket.sendJSON({
76
- type: "yield",
77
- result: result.value
78
- });
79
- return false;
80
- }
81
- }
82
- for await (const data of jsonUnixSocket.receiveJSON()) {
83
- const inputParseResult = inputSchema.safeParse(data);
84
- if (!inputParseResult.success) {
85
- console.error(inputParseResult.error.errors);
86
- jsonUnixSocket.sendJSON({
87
- type: "done",
88
- result: {
89
- error: "InvalidJSON",
90
- message: "Invalid input",
91
- details: {
92
- errors: inputParseResult.error.errors
93
- }
94
- },
95
- success: false
96
- });
97
- break;
98
- }
99
- const input = inputParseResult.data;
100
- if (input.type === "abort") {
101
- abortController.abort();
102
- await setTimeout(10);
103
- jsonUnixSocket.sendJSON({
104
- type: "done",
105
- result: null
106
- });
107
- break;
108
- }
109
- if (input.type === "start") {
110
- const gen = runApiGenerator({
111
- ...input.parameters,
112
- abortSignal: abortController.signal
113
- });
114
- generator = gen;
115
- context = {
116
- extendedPayloads: [],
117
- runEnvironment: input.parameters.runOptions.environment === "deployed" ? RunEnvironment.DEPLOYED : RunEnvironment.IDE,
118
- timeoutInfo: {
119
- extendTimeoutCallback: async () => {
120
- if (Date.now() - timeoutTimestamp < throttleTime) return;
121
- timeoutTimestamp = Date.now();
122
- jsonUnixSocket.sendJSON({
123
- type: "extend"
124
- });
125
- }
126
- },
127
- ...(input.parameters.context ?? {}),
128
- proxy: getProxyUrlFromRunOptions(input.parameters.runOptions)
129
- };
130
- if (await runGeneratorAndSendResult()) {
131
- break;
132
- }
133
- continue;
134
- }
135
- if (input.type === "next") {
136
- if (!generator) {
137
- throw new Error("generator not started");
138
- }
139
- if (await runGeneratorAndSendResult(input.parameters.value)) {
140
- break;
141
- }
142
- continue;
143
- }
144
- }
145
- process.exit(0);
146
- });
147
- program.parse(process.argv);
148
- function getProxyUrlFromRunOptions(runOptions) {
149
- if ((runOptions === null || runOptions === void 0 ? void 0 : runOptions.environment) !== "deployed") return undefined;
150
- const proxy = runOptions.proxy;
151
- if (!proxy) return undefined;
152
- const url = new URL(proxy.server);
153
- url.username = proxy.username;
154
- url.password = proxy.password;
155
- return url.toString();
156
- }
@@ -1,50 +0,0 @@
1
- #!/usr/bin/env node
2
- import * as ts from "typescript";
3
- import { program } from "commander";
4
- import * as fs from "fs-extra";
5
- import * as path from "path";
6
- import { moveWebTemplateFiles } from "./common/utils/webTemplate.js";
7
- program.description("Check TypeScript types in the project").allowUnknownOption().action(async () => {
8
- await moveWebTemplateFiles();
9
- const templateTsConfig = path.resolve(path.dirname(import.meta.url), "..", "..", "template.tsconfig.json");
10
- await fs.copy(templateTsConfig, "./intuned/WebTemplate/tsconfig.json");
11
- checkTypes();
12
- });
13
- function checkTypes() {
14
- const configPath = ts.findConfigFile("./intuned/WebTemplate", ts.sys.fileExists, "tsconfig.json");
15
- if (!configPath) {
16
- console.error("Could not find a valid 'tsconfig.json'.");
17
- process.exit(1);
18
- }
19
- const readConfigResult = ts.readConfigFile(configPath, ts.sys.readFile);
20
- const config = readConfigResult.config;
21
- const parseConfigHost = {
22
- useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames,
23
- readDirectory: ts.sys.readDirectory,
24
- fileExists: ts.sys.fileExists,
25
- readFile: ts.sys.readFile
26
- };
27
- const parsed = ts.parseJsonConfigFileContent(config, parseConfigHost, "./intuned");
28
- const program = ts.createProgram(parsed.fileNames, parsed.options);
29
- const emitResult = program.emit();
30
- const allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
31
- allDiagnostics.forEach(diagnostic => {
32
- if (diagnostic.file) {
33
- const {
34
- line,
35
- character
36
- } = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start);
37
- const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n");
38
- console.log(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`);
39
- } else {
40
- console.log(ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"));
41
- }
42
- });
43
- if (allDiagnostics.length === 0) {
44
- console.log("✨ TypeScript type checking passed without errors.");
45
- } else {
46
- console.error("Errors found during TypeScript type checking.");
47
- process.exit(1);
48
- }
49
- }
50
- program.parse(process.argv);