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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/.babelrc +1 -2
  2. package/dist/commands/api/run.js +170 -105
  3. package/dist/commands/api/run.ts +105 -0
  4. package/dist/commands/auth-sessions/load.js +26 -28
  5. package/dist/commands/auth-sessions/load.ts +30 -0
  6. package/dist/commands/auth-sessions/run-check.js +53 -52
  7. package/dist/commands/auth-sessions/run-check.ts +51 -0
  8. package/dist/commands/auth-sessions/run-create.js +96 -91
  9. package/dist/commands/auth-sessions/run-create.ts +91 -0
  10. package/dist/commands/browser/save-state.js +16 -14
  11. package/dist/commands/browser/save-state.ts +14 -0
  12. package/dist/commands/browser/start-browser.js +11 -11
  13. package/dist/commands/browser/start-browser.ts +11 -0
  14. package/dist/commands/build.js +108 -75
  15. package/dist/commands/build.ts +78 -0
  16. package/dist/commands/common/browserUtils.js +51 -53
  17. package/dist/commands/common/browserUtils.ts +45 -0
  18. package/dist/commands/common/getDefaultExportFromFile.js +12 -17
  19. package/dist/commands/common/getDefaultExportFromFile.ts +11 -0
  20. package/dist/commands/common/getFirstLineNumber.js +93 -93
  21. package/dist/commands/common/{getFirstLineNumber.test.js → getFirstLineNumber.test.ts} +46 -51
  22. package/dist/commands/common/getFirstLineNumber.ts +96 -0
  23. package/dist/commands/common/sendMessageToClient.js +4 -9
  24. package/dist/commands/common/sendMessageToClient.ts +3 -0
  25. package/dist/commands/common/utils/fileUtils.js +22 -32
  26. package/dist/commands/common/utils/fileUtils.ts +23 -0
  27. package/dist/commands/common/utils/settings.js +19 -27
  28. package/dist/commands/common/utils/settings.ts +22 -0
  29. package/dist/commands/common/utils/unixSocket.js +43 -43
  30. package/dist/commands/common/utils/unixSocket.ts +38 -0
  31. package/dist/commands/common/utils/webTemplate.js +27 -29
  32. package/dist/commands/common/utils/webTemplate.ts +22 -0
  33. package/dist/commands/interface/run.js +151 -150
  34. package/dist/commands/interface/run.ts +156 -0
  35. package/dist/commands/ts-check.js +49 -49
  36. package/dist/commands/ts-check.ts +50 -0
  37. package/dist/common/Logger/Logger/index.d.ts +1 -1
  38. package/dist/common/Logger/Logger/index.js +42 -55
  39. package/dist/common/Logger/Logger/index.ts +53 -0
  40. package/dist/common/Logger/Logger/types.js +1 -5
  41. package/dist/common/Logger/Logger/types.ts +1 -0
  42. package/dist/common/Logger/index.d.ts +1 -1
  43. package/dist/common/Logger/index.js +42 -55
  44. package/dist/common/Logger/index.ts +53 -0
  45. package/dist/common/Logger/types.js +1 -5
  46. package/dist/common/Logger/types.ts +1 -0
  47. package/dist/common/asyncLocalStorage/index.js +8 -16
  48. package/dist/common/asyncLocalStorage/index.ts +9 -0
  49. package/dist/common/cleanEnvironmentVariables.js +12 -16
  50. package/dist/common/cleanEnvironmentVariables.ts +10 -0
  51. package/dist/common/constants.js +1 -7
  52. package/dist/common/constants.ts +1 -0
  53. package/dist/common/contextStorageStateHelpers.js +38 -47
  54. package/dist/common/contextStorageStateHelpers.ts +43 -0
  55. package/dist/common/getPlaywrightConstructs.d.ts +1 -1
  56. package/dist/common/getPlaywrightConstructs.js +196 -177
  57. package/dist/common/getPlaywrightConstructs.ts +181 -0
  58. package/dist/common/jwtTokenManager.js +79 -76
  59. package/dist/common/jwtTokenManager.ts +71 -0
  60. package/dist/common/runApi/errors.d.ts +1 -1
  61. package/dist/common/runApi/errors.js +150 -159
  62. package/dist/common/runApi/errors.ts +154 -0
  63. package/dist/common/runApi/index.d.ts +4 -4
  64. package/dist/common/runApi/index.js +220 -269
  65. package/dist/common/runApi/index.ts +253 -0
  66. package/dist/common/runApi/types.d.ts +1 -1
  67. package/dist/common/runApi/types.js +56 -49
  68. package/dist/common/runApi/types.ts +43 -0
  69. package/dist/common/settingsSchema.js +10 -15
  70. package/dist/common/settingsSchema.ts +9 -0
  71. package/dist/common/telemetry.js +30 -28
  72. package/dist/common/telemetry.ts +23 -0
  73. package/dist/index.d.ts +4 -4
  74. package/dist/index.js +4 -69
  75. package/dist/index.ts +4 -0
  76. package/dist/runtime/RunError.d.ts +1 -1
  77. package/dist/runtime/RunError.js +11 -18
  78. package/dist/runtime/RunError.ts +12 -0
  79. package/dist/runtime/downloadDirectory.js +13 -19
  80. package/dist/runtime/downloadDirectory.ts +13 -0
  81. package/dist/runtime/enums.d.ts +1 -11
  82. package/dist/runtime/enums.js +12 -18
  83. package/dist/runtime/enums.ts +12 -0
  84. package/dist/runtime/executionHelpers.test.ts +51 -0
  85. package/dist/runtime/export.d.ts +1 -202
  86. package/dist/runtime/extendPayload.d.ts +1 -1
  87. package/dist/runtime/extendPayload.js +15 -21
  88. package/dist/runtime/extendPayload.ts +15 -0
  89. package/dist/runtime/extendTimeout.js +21 -28
  90. package/dist/runtime/extendTimeout.ts +24 -0
  91. package/dist/runtime/index.d.ts +7 -7
  92. package/dist/runtime/index.js +6 -53
  93. package/dist/runtime/index.ts +6 -0
  94. package/dist/runtime/requestMoreInfo.js +16 -23
  95. package/dist/runtime/requestMoreInfo.ts +18 -0
  96. package/dist/runtime/runInfo.d.ts +1 -1
  97. package/dist/runtime/runInfo.js +14 -21
  98. package/dist/runtime/runInfo.ts +15 -0
  99. package/package.json +3 -2
  100. package/tsconfig.json +1 -1
  101. package/dist/runtime/enums.d.js +0 -5
  102. package/dist/runtime/executionHelpers.test.js +0 -53
  103. package/dist/runtime/export.d.js +0 -5
@@ -0,0 +1,78 @@
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(__dirname, "..", "..", "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(__dirname, "..", "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,58 +1,56 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.getChromiumLaunchArgs = exports.REMOTE_DEBUGGING_PORT = void 0;
7
- exports.loadState = loadState;
8
- exports.saveSession = saveSession;
9
- exports.saveSessionFromOpenedBrowser = saveSessionFromOpenedBrowser;
10
- exports.startOrRestartBrowser = startOrRestartBrowser;
11
- var _child_process = require("child_process");
12
- var playwright = _interopRequireWildcard(require("@intuned/playwright-core"));
13
- var fs = _interopRequireWildcard(require("fs-extra"));
14
- var _fileUtils = require("./utils/fileUtils");
15
- var _contextStorageStateHelpers = require("../../common/contextStorageStateHelpers");
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); }
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; }
18
- const REMOTE_DEBUGGING_PORT = exports.REMOTE_DEBUGGING_PORT = 9222;
19
- const getChromiumLaunchArgs = () => ["--no-sandbox", `--remote-debugging-port=${REMOTE_DEBUGGING_PORT}`, `--user-data-dir=/tmp/${Date.now()}`, "--new-window", "--start-maximized", "--disable-popup-blocking"];
20
- exports.getChromiumLaunchArgs = getChromiumLaunchArgs;
1
+ // this file is to make testing easier only.
2
+ import { spawn } from "child_process";
3
+ import * as playwright from "@intuned/playwright-core";
4
+ import * as fs from "fs-extra";
5
+ import { getFullPathInProject } from "./utils/fileUtils.js";
6
+ import { getContextStorageState } from "../../common/contextStorageStateHelpers";
7
+ export const REMOTE_DEBUGGING_PORT = 9222;
8
+ export const getChromiumLaunchArgs = () => [
9
+ "--no-sandbox",
10
+ `--remote-debugging-port=${REMOTE_DEBUGGING_PORT}`,
11
+ `--user-data-dir=/tmp/${Date.now()}`,
12
+ "--new-window",
13
+ "--start-maximized",
14
+ "--disable-popup-blocking",
15
+ ];
16
+ // this is needed cause we need to keep the same browser instance alive between start recording and stop recording calls.
21
17
  async function getBrowser() {
22
- let playwrightBrowser = null;
23
- try {
24
- playwrightBrowser = await playwright.chromium.connectOverCDP(`http://localhost:${REMOTE_DEBUGGING_PORT}`);
25
- } catch (e) {
26
- throw new Error("Browser is not running");
27
- }
28
- return playwrightBrowser;
18
+ let playwrightBrowser = null;
19
+ try {
20
+ playwrightBrowser = await playwright.chromium.connectOverCDP(`http://localhost:${REMOTE_DEBUGGING_PORT}`);
21
+ }
22
+ catch (e) {
23
+ throw new Error("Browser is not running");
24
+ }
25
+ return playwrightBrowser;
29
26
  }
30
- async function startOrRestartBrowser() {
31
- const chromiumPath = await playwright.chromium.executablePath();
32
- const chromeInstanceProcess = (0, _child_process.spawn)(chromiumPath, getChromiumLaunchArgs());
33
- chromeInstanceProcess.stdout.on("data", data => {
34
- console.log(`Chrome stdout: ${data}`);
35
- });
36
- chromeInstanceProcess.stderr.on("data", data => {
37
- console.error(`Chrome stderr: ${data}`);
38
- });
27
+ export async function startOrRestartBrowser() {
28
+ const chromiumPath = await playwright.chromium.executablePath();
29
+ const chromeInstanceProcess = spawn(chromiumPath, getChromiumLaunchArgs());
30
+ chromeInstanceProcess.stdout.on("data", (data) => {
31
+ console.log(`Chrome stdout: ${data}`);
32
+ });
33
+ chromeInstanceProcess.stderr.on("data", (data) => {
34
+ console.error(`Chrome stderr: ${data}`);
35
+ });
39
36
  }
40
- async function saveSessionFromOpenedBrowser(path) {
41
- const browser = await getBrowser();
42
- const context = await browser.contexts()[0];
43
- return saveSession(path, context);
37
+ export async function saveSessionFromOpenedBrowser(path) {
38
+ const browser = await getBrowser();
39
+ const context = await browser.contexts()[0];
40
+ return saveSession(path, context);
44
41
  }
45
- async function loadState(path, context) {
46
- const fullPath = (0, _fileUtils.getFullPathInProject)(path);
47
- if (!(await fs.pathExists(fullPath))) {
48
- throw new Error("session file does not exist");
49
- }
50
- const data = await fs.readJson(fullPath);
51
- await context.addCookies(data.cookies);
42
+ export async function loadState(path, context) {
43
+ const fullPath = getFullPathInProject(path);
44
+ if (!(await fs.pathExists(fullPath))) {
45
+ throw new Error("session file does not exist");
46
+ }
47
+ const data = await fs.readJson(fullPath);
48
+ await context.addCookies(data.cookies);
49
+ // ToDo: logic to load storage without using the page.
50
+ }
51
+ export async function saveSession(path, context) {
52
+ const fullState = await getContextStorageState(context);
53
+ const fullPath = getFullPathInProject(path);
54
+ fs.ensureFileSync(fullPath);
55
+ await fs.writeJSON(fullPath, fullState);
52
56
  }
53
- async function saveSession(path, context) {
54
- const fullState = await (0, _contextStorageStateHelpers.getContextStorageState)(context);
55
- const fullPath = (0, _fileUtils.getFullPathInProject)(path);
56
- fs.ensureFileSync(fullPath);
57
- await fs.writeJSON(fullPath, fullState);
58
- }
@@ -0,0 +1,45 @@
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,17 +1,12 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.getDefaultExportFromFile = getDefaultExportFromFile;
7
- async function getDefaultExportFromFile(apiFilePath) {
8
- require("ts-node").register({
9
- transpileOnly: true,
10
- compilerOptions: {
11
- lib: ["dom", "es2020"]
12
- }
13
- });
14
- const imported = await Promise.resolve(require(apiFilePath));
15
- const defaultExport = imported.default;
16
- return defaultExport;
17
- }
1
+ export async function getDefaultExportFromFile(apiFilePath) {
2
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
3
+ require("ts-node").register({
4
+ transpileOnly: true,
5
+ compilerOptions: {
6
+ lib: ["dom", "es2020"],
7
+ },
8
+ });
9
+ const imported = await import(apiFilePath);
10
+ const defaultExport = imported.default;
11
+ return defaultExport;
12
+ }
@@ -0,0 +1,11 @@
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,103 +1,103 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = getFirstLineNumber;
7
- exports.findFirstExecutableLine = findFirstExecutableLine;
8
- var _tsMorph = require("ts-morph");
9
- var _sourceMap = require("source-map");
1
+ import { ts, Project, ModuleKind, ScriptTarget, Node, } from "ts-morph";
2
+ import { SourceMapConsumer } from "source-map";
10
3
  function compileTypeScript(apiFilePath) {
11
- const compilerOptions = {
12
- lib: ["dom", "es2020"],
13
- sourceMap: true,
14
- inlineSourceMap: true,
15
- inlineSources: true,
16
- declaration: false,
17
- noEmit: false,
18
- module: _tsMorph.ModuleKind.CommonJS,
19
- target: _tsMorph.ScriptTarget.ES2020
20
- };
21
- const project = new _tsMorph.Project({
22
- compilerOptions
23
- });
24
- const sourceFile = project.addSourceFileAtPath(apiFilePath);
25
- const outputJS = project.emitToMemory({
26
- targetSourceFile: sourceFile
27
- });
28
- const outputJSText = outputJS.getFiles()[0].text;
29
- return {
30
- sourceFile,
31
- outputJSText
32
- };
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({ targetSourceFile: sourceFile });
19
+ const outputJSText = outputJS.getFiles()[0].text;
20
+ return { sourceFile, outputJSText };
33
21
  }
34
- function findFirstExecutableLine(sourceFile) {
35
- var _defaultExportSymbol$;
36
- let functionBody;
37
- const defaultExportSymbol = sourceFile.getDefaultExportSymbol();
38
- const defaultExportDeclaration = defaultExportSymbol === null || defaultExportSymbol === void 0 || (_defaultExportSymbol$ = defaultExportSymbol.getDeclarations()) === null || _defaultExportSymbol$ === void 0 ? void 0 : _defaultExportSymbol$[0];
39
- if (defaultExportDeclaration) {
40
- if (defaultExportDeclaration.getKind() === _tsMorph.ts.SyntaxKind.FunctionDeclaration) {
41
- functionBody = defaultExportDeclaration.getBody();
42
- } else {
43
- const exportAssignments = sourceFile.getExportAssignments();
44
- for (const exportAssignment of exportAssignments) {
45
- const expression = exportAssignment.getExpression();
46
- if (!expression) continue;
47
- if (expression.getKind() === _tsMorph.ts.SyntaxKind.Identifier || expression.getKind() === _tsMorph.ts.SyntaxKind.FunctionExpression || expression.getKind() === _tsMorph.ts.SyntaxKind.ArrowFunction) {
48
- var _sourceFile$getVariab;
49
- const identifier = expression.getText();
50
- const possiblyExportedFunction = sourceFile.getFunction(identifier) || ((_sourceFile$getVariab = sourceFile.getVariableStatement(identifier)) === null || _sourceFile$getVariab === void 0 ? void 0 : _sourceFile$getVariab.getDescendants().find(node => node.getKind() === _tsMorph.ts.SyntaxKind.FunctionExpression || node.getKind() === _tsMorph.ts.SyntaxKind.ArrowFunction));
51
- if (possiblyExportedFunction) {
52
- functionBody = possiblyExportedFunction.getBody();
53
- break;
54
- }
22
+ export function findFirstExecutableLine(sourceFile) {
23
+ let functionBody;
24
+ // Directly find the default exported function's body
25
+ const defaultExportSymbol = sourceFile.getDefaultExportSymbol();
26
+ const defaultExportDeclaration = defaultExportSymbol?.getDeclarations()?.[0];
27
+ if (defaultExportDeclaration) {
28
+ // Check if the default export is a function
29
+ if (defaultExportDeclaration.getKind() === ts.SyntaxKind.FunctionDeclaration) {
30
+ functionBody = defaultExportDeclaration.getBody();
55
31
  }
56
- if (_tsMorph.Node.hasBody(expression) && (expression.getKind() === _tsMorph.ts.SyntaxKind.FunctionExpression || expression.getKind() === _tsMorph.ts.SyntaxKind.ArrowFunction)) {
57
- functionBody = expression.getBody();
58
- break;
32
+ else {
33
+ // Handle ExportAssignment specifically for cases like `export default identifier;`
34
+ const exportAssignments = sourceFile.getExportAssignments();
35
+ for (const exportAssignment of exportAssignments) {
36
+ const expression = exportAssignment.getExpression();
37
+ if (!expression)
38
+ continue;
39
+ if (expression.getKind() === ts.SyntaxKind.Identifier ||
40
+ expression.getKind() === ts.SyntaxKind.FunctionExpression ||
41
+ expression.getKind() === ts.SyntaxKind.ArrowFunction) {
42
+ const identifier = expression.getText();
43
+ const possiblyExportedFunction = sourceFile.getFunction(identifier) ||
44
+ sourceFile
45
+ .getVariableStatement(identifier)
46
+ ?.getDescendants()
47
+ .find((node) => node.getKind() === ts.SyntaxKind.FunctionExpression ||
48
+ node.getKind() === ts.SyntaxKind.ArrowFunction);
49
+ if (possiblyExportedFunction) {
50
+ functionBody = possiblyExportedFunction.getBody();
51
+ break;
52
+ }
53
+ }
54
+ if (Node.hasBody(expression) &&
55
+ (expression.getKind() === ts.SyntaxKind.FunctionExpression ||
56
+ expression.getKind() === ts.SyntaxKind.ArrowFunction)) {
57
+ // As these are anonymous, we directly access their body
58
+ functionBody = expression.getBody();
59
+ break;
60
+ }
61
+ }
59
62
  }
60
- }
61
63
  }
62
- }
63
- if (!functionBody || !_tsMorph.Node.isStatemented(functionBody)) {
64
- return -1;
65
- }
66
- if (functionBody.getStatements().length === 0) {
67
- return -1;
68
- }
69
- const position = functionBody.getStatements()[0].getStart();
70
- return sourceFile.getLineAndColumnAtPos(position);
64
+ if (!functionBody || !Node.isStatemented(functionBody)) {
65
+ return -1;
66
+ }
67
+ if (functionBody.getStatements().length === 0) {
68
+ return -1;
69
+ }
70
+ const position = functionBody.getStatements()[0].getStart();
71
+ return sourceFile.getLineAndColumnAtPos(position);
71
72
  }
72
73
  async function getSourceMap(jsCode) {
73
- const sourceMapBase64 = jsCode.substring(jsCode.lastIndexOf("//# sourceMappingURL=data:application/json;base64,") + "//# sourceMappingURL=data:application/json;base64,".length);
74
- const sourceMapText = Buffer.from(sourceMapBase64, "base64").toString("utf-8");
75
- const sourceMap = JSON.parse(sourceMapText);
76
- return new _sourceMap.SourceMapConsumer(sourceMap);
74
+ const sourceMapBase64 = jsCode.substring(jsCode.lastIndexOf("//# sourceMappingURL=data:application/json;base64,") +
75
+ "//# sourceMappingURL=data:application/json;base64,".length);
76
+ const sourceMapText = Buffer.from(sourceMapBase64, "base64").toString("utf-8");
77
+ const sourceMap = JSON.parse(sourceMapText);
78
+ return new SourceMapConsumer(sourceMap);
77
79
  }
78
80
  async function mapFirstLineNumberBySourceMap(sourceFileName, jsCode, line, column) {
79
- const sourceMap = await getSourceMap(jsCode);
80
- const generatedLineNumber = sourceMap.generatedPositionFor({
81
- source: sourceFileName,
82
- line,
83
- column
84
- }).line;
85
- if (!generatedLineNumber) return -1;
86
- return generatedLineNumber;
81
+ const sourceMap = await getSourceMap(jsCode);
82
+ const generatedLineNumber = sourceMap.generatedPositionFor({
83
+ source: sourceFileName,
84
+ line,
85
+ column,
86
+ }).line;
87
+ if (!generatedLineNumber)
88
+ return -1;
89
+ return generatedLineNumber;
90
+ }
91
+ export default async function getFirstLineNumber(apiFilePath) {
92
+ const sourceFileName = apiFilePath.split("/").pop() ?? apiFilePath;
93
+ // Compile TypeScript to JavaScript and get the Typescript AST
94
+ const { sourceFile, outputJSText } = compileTypeScript(apiFilePath);
95
+ // Find the first line of code in the default export ts code
96
+ const result = findFirstExecutableLine(sourceFile);
97
+ if (result === -1)
98
+ return { sourceFileName, lineNumber: -1 };
99
+ return {
100
+ sourceFileName,
101
+ lineNumber: await mapFirstLineNumberBySourceMap(sourceFileName, outputJSText, result.line, result.column),
102
+ };
87
103
  }
88
- async function getFirstLineNumber(apiFilePath) {
89
- const sourceFileName = apiFilePath.split("/").pop() ?? apiFilePath;
90
- const {
91
- sourceFile,
92
- outputJSText
93
- } = compileTypeScript(apiFilePath);
94
- const result = findFirstExecutableLine(sourceFile);
95
- if (result === -1) return {
96
- sourceFileName,
97
- lineNumber: -1
98
- };
99
- return {
100
- sourceFileName,
101
- lineNumber: await mapFirstLineNumberBySourceMap(sourceFileName, outputJSText, result.line, result.column)
102
- };
103
- }