@midscene/core 0.9.1 → 0.9.2-beta-20250114083542.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.
@@ -1,8 +1,9 @@
1
- import { g as AIUsageInfo } from './types-05c1f241.js';
1
+ import { g as AIUsageInfo, y as PlanningAction } from './types-c4bec333.js';
2
2
  import { ChatCompletionMessageParam } from 'openai/resources';
3
3
  export { ChatCompletionMessageParam } from 'openai/resources';
4
- import { A as AIActionType } from './automation-81d96430.js';
5
- export { f as AiAssert, e as AiExtractElementInfo, b as AiInspectElement, c as callAiFn, d as describeUserPage, p as plan, t as transformElementPositionToId } from './automation-81d96430.js';
4
+ import { A as AIActionType } from './automation-d7e10a4e.js';
5
+ export { f as AiAssert, e as AiExtractElementInfo, b as AiInspectElement, c as callAiFn, d as describeUserPage, p as plan, t as transformElementPositionToId } from './automation-d7e10a4e.js';
6
+ import '@midscene/shared/constants';
6
7
 
7
8
  declare function callToGetJSONObject<T>(messages: ChatCompletionMessageParam[], AIActionTypeValue: AIActionType): Promise<{
8
9
  content: T;
@@ -11,4 +12,59 @@ declare function callToGetJSONObject<T>(messages: ChatCompletionMessageParam[],
11
12
 
12
13
  declare function systemPromptToFindElement(): string;
13
14
 
14
- export { callToGetJSONObject, systemPromptToFindElement };
15
+ type ActionType = 'click' | 'type' | 'hotkey' | 'finished' | 'scroll' | 'wait';
16
+ declare function vlmPlanning(options: {
17
+ userInstruction: string;
18
+ conversationHistory: ChatCompletionMessageParam[];
19
+ size: {
20
+ width: number;
21
+ height: number;
22
+ };
23
+ }): Promise<{
24
+ actions: PlanningAction<any>[];
25
+ realActions: Array<Action>;
26
+ action_summary: string;
27
+ }>;
28
+ interface BaseAction {
29
+ action_type: ActionType;
30
+ action_inputs: Record<string, any>;
31
+ reflection: string | null;
32
+ thought: string | null;
33
+ }
34
+ interface ClickAction extends BaseAction {
35
+ action_type: 'click';
36
+ action_inputs: {
37
+ start_box: string;
38
+ };
39
+ }
40
+ interface WaitAction extends BaseAction {
41
+ action_type: 'wait';
42
+ action_inputs: {
43
+ time: string;
44
+ };
45
+ }
46
+ interface TypeAction extends BaseAction {
47
+ action_type: 'type';
48
+ action_inputs: {
49
+ content: string;
50
+ };
51
+ }
52
+ interface HotkeyAction extends BaseAction {
53
+ action_type: 'hotkey';
54
+ action_inputs: {
55
+ key: string;
56
+ };
57
+ }
58
+ interface ScrollAction extends BaseAction {
59
+ action_type: 'scroll';
60
+ action_inputs: {
61
+ direction: 'up' | 'down';
62
+ };
63
+ }
64
+ interface FinishedAction extends BaseAction {
65
+ action_type: 'finished';
66
+ action_inputs: Record<string, never>;
67
+ }
68
+ type Action = ClickAction | TypeAction | HotkeyAction | ScrollAction | FinishedAction | WaitAction;
69
+
70
+ export { callToGetJSONObject, systemPromptToFindElement, vlmPlanning };
@@ -1,4 +1,4 @@
1
- import { g as AIUsageInfo, B as BaseElement, U as UIContext, l as AIElementResponse, A as AISingleElementResponse, u as ElementById, m as AISectionParseResponse, n as AIAssertionResponse, z as PlanningAIResponse } from './types-05c1f241.js';
1
+ import { g as AIUsageInfo, B as BaseElement, U as UIContext, l as AIElementResponse, A as AISingleElementResponse, j as AISingleElementResponseByPosition, u as ElementById, m as AISectionParseResponse, n as AIAssertionResponse, z as PlanningAIResponse } from './types-c4bec333.js';
2
2
  import { ChatCompletionSystemMessageParam, ChatCompletionUserMessageParam } from 'openai/resources';
3
3
 
4
4
  type AIArgs = [
@@ -29,6 +29,10 @@ declare function describeUserPage<ElementType extends BaseElement = BaseElement>
29
29
  width: number;
30
30
  height: number;
31
31
  }): BaseElement | undefined;
32
+ insertElementByPosition(position: {
33
+ x: number;
34
+ y: number;
35
+ }): ElementType;
32
36
  size: {
33
37
  width: number;
34
38
  height: number;
@@ -61,7 +65,7 @@ declare function AiInspectElement<ElementType extends BaseElement = BaseElement>
61
65
  multi: boolean;
62
66
  targetElementDescription: string;
63
67
  callAI?: typeof callAiFn<AIElementResponse | [number, number]>;
64
- quickAnswer?: AISingleElementResponse;
68
+ quickAnswer?: Partial<AISingleElementResponse | AISingleElementResponseByPosition>;
65
69
  }): Promise<{
66
70
  parseResult: AIElementResponse;
67
71
  rawResponse: any;
@@ -10,6 +10,7 @@ declare const OPENAI_BASE_URL = "OPENAI_BASE_URL";
10
10
  declare const OPENAI_MAX_TOKENS = "OPENAI_MAX_TOKENS";
11
11
  declare const MIDSCENE_MODEL_TEXT_ONLY = "MIDSCENE_MODEL_TEXT_ONLY";
12
12
  declare const MIDSCENE_CACHE = "MIDSCENE_CACHE";
13
+ declare const MIDSCENE_USE_VLM_UI_TARS = "MIDSCENE_USE_VLM_UI_TARS";
13
14
  declare const MATCH_BY_POSITION = "MATCH_BY_POSITION";
14
15
  declare const MIDSCENE_API_TYPE = "MIDSCENE-API-TYPE";
15
16
  declare const MIDSCENE_REPORT_TAG_NAME = "MIDSCENE_REPORT_TAG_NAME";
@@ -43,6 +44,7 @@ declare const allConfigFromEnv: () => {
43
44
  MIDSCENE_AZURE_OPENAI_SCOPE: string | undefined;
44
45
  MIDSCENE_AZURE_OPENAI_INIT_CONFIG_JSON: string | undefined;
45
46
  MIDSCENE_USE_ANTHROPIC_SDK: string | undefined;
47
+ MIDSCENE_USE_VLM_UI_TARS: string | undefined;
46
48
  ANTHROPIC_API_KEY: string | undefined;
47
49
  AZURE_OPENAI_ENDPOINT: string | undefined;
48
50
  AZURE_OPENAI_KEY: string | undefined;
@@ -72,6 +74,7 @@ declare const allAIConfig: () => {
72
74
  MIDSCENE_AZURE_OPENAI_SCOPE: string | undefined;
73
75
  MIDSCENE_AZURE_OPENAI_INIT_CONFIG_JSON: string | undefined;
74
76
  MIDSCENE_USE_ANTHROPIC_SDK: string | undefined;
77
+ MIDSCENE_USE_VLM_UI_TARS: string | undefined;
75
78
  ANTHROPIC_API_KEY: string | undefined;
76
79
  AZURE_OPENAI_ENDPOINT: string | undefined;
77
80
  AZURE_OPENAI_KEY: string | undefined;
@@ -80,4 +83,4 @@ declare const allAIConfig: () => {
80
83
  };
81
84
  declare const overrideAIConfig: (newConfig: ReturnType<typeof allConfigFromEnv>, extendMode?: boolean) => void;
82
85
 
83
- export { ANTHROPIC_API_KEY, AZURE_OPENAI_API_VERSION, AZURE_OPENAI_DEPLOYMENT, AZURE_OPENAI_ENDPOINT, AZURE_OPENAI_KEY, MATCH_BY_POSITION, MIDSCENE_API_TYPE, MIDSCENE_AZURE_OPENAI_INIT_CONFIG_JSON, MIDSCENE_AZURE_OPENAI_SCOPE, MIDSCENE_CACHE, MIDSCENE_DANGEROUSLY_PRINT_ALL_CONFIG, MIDSCENE_DEBUG_AI_PROFILE, MIDSCENE_DEBUG_MODE, MIDSCENE_LANGSMITH_DEBUG, MIDSCENE_MODEL_NAME, MIDSCENE_MODEL_TEXT_ONLY, MIDSCENE_OPENAI_INIT_CONFIG_JSON, MIDSCENE_OPENAI_SOCKS_PROXY, MIDSCENE_REPORT_TAG_NAME, MIDSCENE_USE_ANTHROPIC_SDK, MIDSCENE_USE_AZURE_OPENAI, OPENAI_API_KEY, OPENAI_BASE_URL, OPENAI_MAX_TOKENS, OPENAI_USE_AZURE, allAIConfig, getAIConfig, getAIConfigInJson, overrideAIConfig };
86
+ export { ANTHROPIC_API_KEY, AZURE_OPENAI_API_VERSION, AZURE_OPENAI_DEPLOYMENT, AZURE_OPENAI_ENDPOINT, AZURE_OPENAI_KEY, MATCH_BY_POSITION, MIDSCENE_API_TYPE, MIDSCENE_AZURE_OPENAI_INIT_CONFIG_JSON, MIDSCENE_AZURE_OPENAI_SCOPE, MIDSCENE_CACHE, MIDSCENE_DANGEROUSLY_PRINT_ALL_CONFIG, MIDSCENE_DEBUG_AI_PROFILE, MIDSCENE_DEBUG_MODE, MIDSCENE_LANGSMITH_DEBUG, MIDSCENE_MODEL_NAME, MIDSCENE_MODEL_TEXT_ONLY, MIDSCENE_OPENAI_INIT_CONFIG_JSON, MIDSCENE_OPENAI_SOCKS_PROXY, MIDSCENE_REPORT_TAG_NAME, MIDSCENE_USE_ANTHROPIC_SDK, MIDSCENE_USE_AZURE_OPENAI, MIDSCENE_USE_VLM_UI_TARS, OPENAI_API_KEY, OPENAI_BASE_URL, OPENAI_MAX_TOKENS, OPENAI_USE_AZURE, allAIConfig, getAIConfig, getAIConfigInJson, overrideAIConfig };
@@ -1,9 +1,9 @@
1
- import { E as ExecutionTask, a as ExecutionTaskProgressOptions, b as ExecutionTaskApply, c as ExecutionDump, B as BaseElement, U as UIContext, I as InsightAction, D as DumpSubscriber, d as InsightOptions, e as InsightTaskInfo, A as AISingleElementResponse, f as InsightAssertionResponse } from './types-05c1f241.js';
2
- export { n as AIAssertionResponse, k as AIElementIdResponse, l as AIElementResponse, h as AIResponseFormat, m as AISectionParseResponse, i as AISingleElementResponseById, j as AISingleElementResponseByPosition, g as AIUsageInfo, w as AgentAssertOpt, v as AgentWaitForOpt, X as BaseAgentParserOpt, C as CallAIFn, W as Color, q as DumpMeta, u as ElementById, o as EnsureObject, _ as ExecutionRecorderItem, ag as ExecutionTaskAction, af as ExecutionTaskActionApply, ae as ExecutionTaskInsightAssertion, ad as ExecutionTaskInsightAssertionApply, ac as ExecutionTaskInsightAssertionParam, a5 as ExecutionTaskInsightDumpLog, a7 as ExecutionTaskInsightLocate, a6 as ExecutionTaskInsightLocateApply, a4 as ExecutionTaskInsightLocateOutput, a3 as ExecutionTaskInsightLocateParam, ab as ExecutionTaskInsightQuery, aa as ExecutionTaskInsightQueryApply, a9 as ExecutionTaskInsightQueryOutput, a8 as ExecutionTaskInsightQueryParam, ai as ExecutionTaskPlanning, ah as ExecutionTaskPlanningApply, a2 as ExecutionTaskReturn, $ as ExecutionTaskType, a0 as ExecutorContext, aj as GroupedActionDump, s as InsightDump, p as InsightExtractParam, L as LiteUISection, O as OnTaskStartTip, t as PartialInsightDumpFromSDK, z as PlanningAIResponse, y as PlanningAction, N as PlanningActionParamAssert, T as PlanningActionParamError, J as PlanningActionParamHover, K as PlanningActionParamInputOrKeyPress, G as PlanningActionParamPlan, M as PlanningActionParamScroll, Q as PlanningActionParamSleep, H as PlanningActionParamTap, V as PlanningActionParamWaitFor, F as PlanningFurtherPlan, x as PlanningLocateParam, Z as PlaywrightParserOpt, P as Point, Y as PuppeteerParserOpt, R as Rect, r as ReportDumpWithAttributes, S as Size, a1 as TaskCacheInfo } from './types-05c1f241.js';
3
- export { allAIConfig, getAIConfig, overrideAIConfig } from './env.js';
4
- import { c as callAiFn, r as retrieveElement, a as retrieveSection } from './automation-81d96430.js';
5
- export { p as plan, t as transformElementPositionToId } from './automation-81d96430.js';
1
+ import { E as ExecutionTask, a as ExecutionTaskProgressOptions, b as ExecutionTaskApply, c as ExecutionDump, B as BaseElement, U as UIContext, I as InsightAction, D as DumpSubscriber, d as InsightOptions, e as InsightTaskInfo, f as InsightAssertionResponse, A as AISingleElementResponse } from './types-c4bec333.js';
2
+ export { n as AIAssertionResponse, k as AIElementIdResponse, l as AIElementResponse, h as AIResponseFormat, m as AISectionParseResponse, i as AISingleElementResponseById, j as AISingleElementResponseByPosition, g as AIUsageInfo, w as AgentAssertOpt, v as AgentWaitForOpt, X as BaseAgentParserOpt, C as CallAIFn, W as Color, q as DumpMeta, u as ElementById, o as EnsureObject, _ as ExecutionRecorderItem, ag as ExecutionTaskAction, af as ExecutionTaskActionApply, ae as ExecutionTaskInsightAssertion, ad as ExecutionTaskInsightAssertionApply, ac as ExecutionTaskInsightAssertionParam, a5 as ExecutionTaskInsightDumpLog, a7 as ExecutionTaskInsightLocate, a6 as ExecutionTaskInsightLocateApply, a4 as ExecutionTaskInsightLocateOutput, a3 as ExecutionTaskInsightLocateParam, ab as ExecutionTaskInsightQuery, aa as ExecutionTaskInsightQueryApply, a9 as ExecutionTaskInsightQueryOutput, a8 as ExecutionTaskInsightQueryParam, ai as ExecutionTaskPlanning, ah as ExecutionTaskPlanningApply, a2 as ExecutionTaskReturn, $ as ExecutionTaskType, a0 as ExecutorContext, aj as GroupedActionDump, s as InsightDump, p as InsightExtractParam, L as LiteUISection, O as OnTaskStartTip, t as PartialInsightDumpFromSDK, z as PlanningAIResponse, y as PlanningAction, N as PlanningActionParamAssert, T as PlanningActionParamError, J as PlanningActionParamHover, K as PlanningActionParamInputOrKeyPress, G as PlanningActionParamPlan, M as PlanningActionParamScroll, Q as PlanningActionParamSleep, H as PlanningActionParamTap, V as PlanningActionParamWaitFor, F as PlanningFurtherPlan, x as PlanningLocateParam, Z as PlaywrightParserOpt, P as Point, Y as PuppeteerParserOpt, R as Rect, r as ReportDumpWithAttributes, S as Size, a1 as TaskCacheInfo } from './types-c4bec333.js';
3
+ import { c as callAiFn, r as retrieveElement, a as retrieveSection } from './automation-d7e10a4e.js';
4
+ export { p as plan, t as transformElementPositionToId } from './automation-d7e10a4e.js';
6
5
  export { getLogDirByType, getVersion, setLogDir } from './utils.js';
6
+ import '@midscene/shared/constants';
7
7
  import 'openai/resources';
8
8
 
9
9
  interface MidsceneYamlScript {
@@ -97,6 +97,11 @@ declare class Executor {
97
97
  dump(): ExecutionDump;
98
98
  }
99
99
 
100
+ interface LocateOpts {
101
+ multi?: boolean;
102
+ callAI?: typeof callAiFn<AIElementResponse>;
103
+ quickAnswer?: Partial<AISingleElementResponse>;
104
+ }
100
105
  declare class Insight<ElementType extends BaseElement = BaseElement, ContextType extends UIContext<ElementType> = UIContext<ElementType>> {
101
106
  contextRetrieverFn: (action: InsightAction) => Promise<ContextType> | ContextType;
102
107
  aiVendorFn: (...args: Array<any>) => Promise<any>;
@@ -104,10 +109,7 @@ declare class Insight<ElementType extends BaseElement = BaseElement, ContextType
104
109
  generateElement: InsightOptions['generateElement'];
105
110
  taskInfo?: Omit<InsightTaskInfo, 'durationMs'>;
106
111
  constructor(context: ContextType | ((action: InsightAction) => Promise<ContextType> | ContextType), opt?: InsightOptions);
107
- locate(queryPrompt: string, opt?: {
108
- callAI?: typeof callAiFn<AIElementResponse>;
109
- quickAnswer?: AISingleElementResponse | null;
110
- }): Promise<ElementType | null>;
112
+ locate(queryPrompt: string, opt?: LocateOpts): Promise<ElementType | null>;
111
113
  locate(queryPrompt: string, opt: {
112
114
  multi: true;
113
115
  }): Promise<ElementType[]>;
@@ -1,3 +1,4 @@
1
+ import { NodeType } from '@midscene/shared/constants';
1
2
  import { ChatCompletionMessageParam } from 'openai/resources';
2
3
 
3
4
  interface Point {
@@ -12,13 +13,6 @@ interface Size {
12
13
  type Rect = Point & Size & {
13
14
  zoom?: number;
14
15
  };
15
- declare enum NodeType {
16
- CONTAINER = "CONTAINER Node",
17
- FORM_ITEM = "FORM_ITEM Node",
18
- BUTTON = "BUTTON Node",
19
- IMG = "IMG Node",
20
- TEXT = "TEXT Node"
21
- }
22
16
  declare abstract class BaseElement {
23
17
  abstract id: string;
24
18
  abstract attributes: {
@@ -122,7 +116,7 @@ interface InsightDump extends DumpMeta {
122
116
  sections?: Record<string, string>;
123
117
  assertion?: string;
124
118
  };
125
- quickAnswer?: AISingleElementResponse | null;
119
+ quickAnswer?: Partial<AISingleElementResponse> | null;
126
120
  matchedSection: [];
127
121
  matchedElement: BaseElement[];
128
122
  data: any;
@@ -166,14 +160,14 @@ interface PlanningLocateParam {
166
160
  }
167
161
  interface PlanningAction<ParamType = any> {
168
162
  thought?: string;
169
- type: 'Locate' | 'Tap' | 'Hover' | 'Input' | 'KeyboardPress' | 'Scroll' | 'Error' | 'FalsyConditionStatement' | 'Assert' | 'AssertWithoutThrow' | 'Sleep';
163
+ type: 'Locate' | 'Tap' | 'Hover' | 'Input' | 'KeyboardPress' | 'Scroll' | 'Error' | 'FalsyConditionStatement' | 'Assert' | 'AssertWithoutThrow' | 'Sleep' | 'Finished';
170
164
  param: ParamType;
171
165
  locate: PlanningLocateParam | null;
172
166
  }
173
167
  interface PlanningAIResponse {
174
168
  actions: PlanningAction[];
175
169
  taskWillBeAccomplished: boolean;
176
- furtherPlan: PlanningFurtherPlan | null;
170
+ furtherPlan?: PlanningFurtherPlan | null;
177
171
  error?: string;
178
172
  }
179
173
  interface PlanningFurtherPlan {
@@ -258,6 +252,7 @@ type ExecutionTask<E extends ExecutionTaskApply<any, any, any> = ExecutionTaskAp
258
252
  start: number;
259
253
  end?: number;
260
254
  cost?: number;
255
+ aiCost?: number;
261
256
  };
262
257
  };
263
258
  interface ExecutionDump extends DumpMeta {
@@ -1,4 +1,5 @@
1
- import { r as ReportDumpWithAttributes, R as Rect } from './types-05c1f241.js';
1
+ import { r as ReportDumpWithAttributes, R as Rect } from './types-c4bec333.js';
2
+ import '@midscene/shared/constants';
2
3
  import 'openai/resources';
3
4
 
4
5
  declare const insightDumpFileExt = "insight-dump.json";
package/dist/lib/utils.js CHANGED
@@ -1,370 +1,40 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/utils.ts
31
- var utils_exports = {};
32
- __export(utils_exports, {
33
- getLogDir: () => getLogDir,
34
- getLogDirByType: () => getLogDirByType,
35
- getTmpDir: () => getTmpDir,
36
- getTmpFile: () => getTmpFile,
37
- getVersion: () => getVersion,
38
- groupedActionDumpFileExt: () => groupedActionDumpFileExt,
39
- insightDumpFileExt: () => insightDumpFileExt,
40
- overlapped: () => overlapped,
41
- replaceStringWithFirstAppearance: () => replaceStringWithFirstAppearance,
42
- replacerForPageObject: () => replacerForPageObject,
43
- reportHTMLContent: () => reportHTMLContent,
44
- setLogDir: () => setLogDir,
45
- sleep: () => sleep,
46
- stringifyDumpData: () => stringifyDumpData,
47
- uploadTestInfoToServer: () => uploadTestInfoToServer,
48
- writeDumpReport: () => writeDumpReport,
49
- writeLogFile: () => writeLogFile
50
- });
51
- module.exports = __toCommonJS(utils_exports);
52
- var import_node_assert = __toESM(require("assert"));
53
- var import_node_child_process = require("child_process");
54
- var import_node_fs = require("fs");
55
- var import_node_os = require("os");
56
- var import_node_path = require("path");
57
- var import_fs = require("@midscene/shared/fs");
58
- var import_utils = require("@midscene/shared/utils");
59
-
60
- // src/env.ts
61
- var MIDSCENE_OPENAI_INIT_CONFIG_JSON = "MIDSCENE_OPENAI_INIT_CONFIG_JSON";
62
- var MIDSCENE_MODEL_NAME = "MIDSCENE_MODEL_NAME";
63
- var MIDSCENE_LANGSMITH_DEBUG = "MIDSCENE_LANGSMITH_DEBUG";
64
- var MIDSCENE_DEBUG_AI_PROFILE = "MIDSCENE_DEBUG_AI_PROFILE";
65
- var MIDSCENE_DANGEROUSLY_PRINT_ALL_CONFIG = "MIDSCENE_DANGEROUSLY_PRINT_ALL_CONFIG";
66
- var MIDSCENE_DEBUG_MODE = "MIDSCENE_DEBUG_MODE";
67
- var MIDSCENE_OPENAI_SOCKS_PROXY = "MIDSCENE_OPENAI_SOCKS_PROXY";
68
- var OPENAI_API_KEY = "OPENAI_API_KEY";
69
- var OPENAI_BASE_URL = "OPENAI_BASE_URL";
70
- var OPENAI_MAX_TOKENS = "OPENAI_MAX_TOKENS";
71
- var MIDSCENE_MODEL_TEXT_ONLY = "MIDSCENE_MODEL_TEXT_ONLY";
72
- var MIDSCENE_CACHE = "MIDSCENE_CACHE";
73
- var MATCH_BY_POSITION = "MATCH_BY_POSITION";
74
- var MIDSCENE_REPORT_TAG_NAME = "MIDSCENE_REPORT_TAG_NAME";
75
- var MIDSCENE_USE_AZURE_OPENAI = "MIDSCENE_USE_AZURE_OPENAI";
76
- var MIDSCENE_AZURE_OPENAI_SCOPE = "MIDSCENE_AZURE_OPENAI_SCOPE";
77
- var MIDSCENE_AZURE_OPENAI_INIT_CONFIG_JSON = "MIDSCENE_AZURE_OPENAI_INIT_CONFIG_JSON";
78
- var AZURE_OPENAI_ENDPOINT = "AZURE_OPENAI_ENDPOINT";
79
- var AZURE_OPENAI_KEY = "AZURE_OPENAI_KEY";
80
- var AZURE_OPENAI_API_VERSION = "AZURE_OPENAI_API_VERSION";
81
- var AZURE_OPENAI_DEPLOYMENT = "AZURE_OPENAI_DEPLOYMENT";
82
- var MIDSCENE_USE_ANTHROPIC_SDK = "MIDSCENE_USE_ANTHROPIC_SDK";
83
- var ANTHROPIC_API_KEY = "ANTHROPIC_API_KEY";
84
- var OPENAI_USE_AZURE = "OPENAI_USE_AZURE";
85
- var allConfigFromEnv = () => {
86
- return {
87
- [MIDSCENE_OPENAI_INIT_CONFIG_JSON]: process.env[MIDSCENE_OPENAI_INIT_CONFIG_JSON] || void 0,
88
- [MIDSCENE_MODEL_NAME]: process.env[MIDSCENE_MODEL_NAME] || void 0,
89
- [MIDSCENE_DEBUG_MODE]: process.env[MIDSCENE_DEBUG_MODE] || void 0,
90
- [MIDSCENE_LANGSMITH_DEBUG]: process.env[MIDSCENE_LANGSMITH_DEBUG] || void 0,
91
- [MIDSCENE_DEBUG_AI_PROFILE]: process.env[MIDSCENE_DEBUG_AI_PROFILE] || void 0,
92
- [MIDSCENE_DANGEROUSLY_PRINT_ALL_CONFIG]: process.env[MIDSCENE_DANGEROUSLY_PRINT_ALL_CONFIG] || void 0,
93
- [OPENAI_API_KEY]: process.env[OPENAI_API_KEY] || void 0,
94
- [OPENAI_BASE_URL]: process.env[OPENAI_BASE_URL] || void 0,
95
- [MIDSCENE_MODEL_TEXT_ONLY]: process.env[MIDSCENE_MODEL_TEXT_ONLY] || void 0,
96
- [OPENAI_MAX_TOKENS]: process.env[OPENAI_MAX_TOKENS] || void 0,
97
- [OPENAI_USE_AZURE]: process.env[OPENAI_USE_AZURE] || void 0,
98
- [MIDSCENE_CACHE]: process.env[MIDSCENE_CACHE] || void 0,
99
- [MATCH_BY_POSITION]: process.env[MATCH_BY_POSITION] || void 0,
100
- [MIDSCENE_REPORT_TAG_NAME]: process.env[MIDSCENE_REPORT_TAG_NAME] || void 0,
101
- [MIDSCENE_OPENAI_SOCKS_PROXY]: process.env[MIDSCENE_OPENAI_SOCKS_PROXY] || void 0,
102
- [MIDSCENE_USE_AZURE_OPENAI]: process.env[MIDSCENE_USE_AZURE_OPENAI] || void 0,
103
- [MIDSCENE_AZURE_OPENAI_SCOPE]: process.env[MIDSCENE_AZURE_OPENAI_SCOPE] || void 0,
104
- [MIDSCENE_AZURE_OPENAI_INIT_CONFIG_JSON]: process.env[MIDSCENE_AZURE_OPENAI_INIT_CONFIG_JSON] || void 0,
105
- [MIDSCENE_USE_ANTHROPIC_SDK]: process.env[MIDSCENE_USE_ANTHROPIC_SDK] || void 0,
106
- [ANTHROPIC_API_KEY]: process.env[ANTHROPIC_API_KEY] || void 0,
107
- [AZURE_OPENAI_ENDPOINT]: process.env[AZURE_OPENAI_ENDPOINT] || void 0,
108
- [AZURE_OPENAI_KEY]: process.env[AZURE_OPENAI_KEY] || void 0,
109
- [AZURE_OPENAI_API_VERSION]: process.env[AZURE_OPENAI_API_VERSION] || void 0,
110
- [AZURE_OPENAI_DEPLOYMENT]: process.env[AZURE_OPENAI_DEPLOYMENT] || void 0
111
- };
112
- };
113
- var userConfig = {};
114
- var getAIConfig = (configKey) => {
115
- if (typeof userConfig[configKey] !== "undefined") {
116
- return userConfig[configKey];
117
- }
118
- return allConfigFromEnv()[configKey];
119
- };
120
- var getAIConfigInJson = (configKey) => {
121
- const config = getAIConfig(configKey);
122
- try {
123
- return config ? JSON.parse(config) : void 0;
124
- } catch (error) {
125
- throw new Error(
126
- `Failed to parse json config: ${configKey}. ${error.message}`,
127
- {
128
- cause: error
129
- }
130
- );
131
- }
132
- };
133
-
134
- // src/utils.ts
135
- var logDir = (0, import_node_path.join)(process.cwd(), "./midscene_run/");
136
- var logEnvReady = false;
137
- var insightDumpFileExt = "insight-dump.json";
138
- var groupedActionDumpFileExt = "web-dump.json";
139
- function getLogDir() {
140
- return logDir;
141
- }
142
- function setLogDir(dir) {
143
- logDir = dir;
144
- }
145
- function getLogDirByType(type) {
146
- const dir = (0, import_node_path.join)(getLogDir(), type);
147
- if (!(0, import_node_fs.existsSync)(dir)) {
148
- (0, import_node_fs.mkdirSync)(dir, { recursive: true });
149
- }
150
- return dir;
151
- }
152
- var reportTpl = null;
153
- function getReportTpl() {
154
- if (import_utils.ifInBrowser) {
155
- if (!reportTpl && window.get_midscene_report_tpl) {
156
- reportTpl = window.get_midscene_report_tpl();
157
- }
158
- (0, import_node_assert.default)(
159
- reportTpl,
160
- "reportTpl should be set before writing report in browser"
161
- );
162
- return reportTpl;
163
- }
164
- if (!reportTpl) {
165
- let reportPath = (0, import_node_path.join)(__dirname, "../../report/index.html");
166
- if (!(0, import_node_fs.existsSync)(reportPath)) {
167
- reportPath = (0, import_node_path.join)(__dirname, "../report/index.html");
168
- }
169
- reportTpl = (0, import_node_fs.readFileSync)(reportPath, "utf-8");
170
- }
171
- return reportTpl;
172
- }
173
- function replaceStringWithFirstAppearance(str, target, replacement) {
174
- const index = str.indexOf(target);
175
- return str.slice(0, index) + replacement + str.slice(index + target.length);
176
- }
177
- function reportHTMLContent(dumpData) {
178
- const tpl = getReportTpl();
179
- let reportContent;
180
- if (Array.isArray(dumpData) && dumpData.length === 0 || typeof dumpData === "undefined") {
181
- reportContent = replaceStringWithFirstAppearance(
182
- tpl,
183
- "{{dump}}",
184
- `<script type="midscene_web_dump" type="application/json"></script>`
185
- );
186
- } else if (typeof dumpData === "string") {
187
- reportContent = replaceStringWithFirstAppearance(
188
- tpl,
189
- "{{dump}}",
190
- `<script type="midscene_web_dump" type="application/json">${dumpData}</script>`
191
- );
192
- } else {
193
- const dumps = dumpData.map(({ dumpString, attributes }) => {
194
- const attributesArr = Object.keys(attributes || {}).map((key) => {
195
- return `${key}="${encodeURIComponent(attributes[key])}"`;
196
- });
197
- return `<script type="midscene_web_dump" type="application/json" ${attributesArr.join(
198
- " "
199
- )}
200
- >${dumpString}
201
- </script>`;
202
- });
203
- reportContent = replaceStringWithFirstAppearance(
204
- tpl,
205
- "{{dump}}",
206
- dumps.join("\n")
207
- );
208
- }
209
- return reportContent;
210
- }
211
- function writeDumpReport(fileName, dumpData) {
212
- if (import_utils.ifInBrowser) {
213
- console.log("will not write report in browser");
214
- return null;
215
- }
216
- const midscenePkgInfo = (0, import_fs.getRunningPkgInfo)(__dirname);
217
- if (!midscenePkgInfo) {
218
- console.warn("midscenePkgInfo not found, will not write report");
219
- return null;
220
- }
221
- const reportPath = (0, import_node_path.join)(getLogDirByType("report"), `${fileName}.html`);
222
- const reportContent = reportHTMLContent(dumpData);
223
- (0, import_node_fs.writeFileSync)(reportPath, reportContent);
224
- return reportPath;
225
- }
226
- function writeLogFile(opts) {
227
- if (import_utils.ifInBrowser) {
228
- return "/mock/report.html";
229
- }
230
- const { fileName, fileExt, fileContent, type = "dump" } = opts;
231
- const targetDir = getLogDirByType(type);
232
- if (!logEnvReady) {
233
- (0, import_node_assert.default)(targetDir, "logDir should be set before writing dump file");
234
- const gitIgnorePath = (0, import_node_path.join)(targetDir, "../../.gitignore");
235
- let gitIgnoreContent = "";
236
- if ((0, import_node_fs.existsSync)(gitIgnorePath)) {
237
- gitIgnoreContent = (0, import_node_fs.readFileSync)(gitIgnorePath, "utf-8");
238
- }
239
- const logDirName = (0, import_node_path.basename)(logDir);
240
- if (!gitIgnoreContent.includes(`${logDirName}/`)) {
241
- (0, import_node_fs.writeFileSync)(
242
- gitIgnorePath,
243
- `${gitIgnoreContent}
244
- # Midscene.js dump files
245
- ${logDirName}/report
246
- ${logDirName}/dump
247
- ${logDirName}/tmp
248
- `,
249
- "utf-8"
250
- );
251
- }
252
- logEnvReady = true;
253
- }
254
- const filePath = (0, import_node_path.join)(targetDir, `${fileName}.${fileExt}`);
255
- const outputResourceDir = (0, import_node_path.dirname)(filePath);
256
- if (!(0, import_node_fs.existsSync)(outputResourceDir)) {
257
- (0, import_node_fs.mkdirSync)(outputResourceDir, { recursive: true });
258
- }
259
- (0, import_node_fs.writeFileSync)(filePath, fileContent);
260
- if (opts == null ? void 0 : opts.generateReport) {
261
- return writeDumpReport(fileName, fileContent);
262
- }
263
- return filePath;
264
- }
265
- function getTmpDir() {
266
- if (import_utils.ifInBrowser) {
267
- return null;
268
- }
269
- const runningPkgInfo = (0, import_fs.getRunningPkgInfo)();
270
- if (!runningPkgInfo) {
271
- return null;
272
- }
273
- const { name } = runningPkgInfo;
274
- const path = (0, import_node_path.join)((0, import_node_os.tmpdir)(), name);
275
- (0, import_node_fs.mkdirSync)(path, { recursive: true });
276
- return path;
277
- }
278
- function getTmpFile(fileExtWithoutDot) {
279
- if (import_utils.ifInBrowser) {
280
- return null;
281
- }
282
- const tmpDir = getTmpDir();
283
- const filename = `${(0, import_utils.uuid)()}.${fileExtWithoutDot}`;
284
- return (0, import_node_path.join)(tmpDir, filename);
285
- }
286
- function overlapped(container, target) {
287
- return container.left < target.left + target.width && container.left + container.width > target.left && container.top < target.top + target.height && container.top + container.height > target.top;
288
- }
289
- async function sleep(ms) {
290
- return new Promise((resolve) => setTimeout(resolve, ms));
291
- }
292
- function replacerForPageObject(key, value) {
293
- var _a, _b;
294
- if (value && ((_a = value.constructor) == null ? void 0 : _a.name) === "Page") {
295
- return "[Page object]";
296
- }
297
- if (value && ((_b = value.constructor) == null ? void 0 : _b.name) === "Browser") {
298
- return "[Browser object]";
299
- }
300
- return value;
301
- }
302
- function stringifyDumpData(data, indents) {
303
- return JSON.stringify(data, replacerForPageObject, indents);
304
- }
305
- function getVersion() {
306
- return "0.9.1";
307
- }
308
- function debugLog(...message) {
309
- const debugMode = getAIConfig(MIDSCENE_DEBUG_MODE);
310
- if (debugMode) {
311
- console.log("[Midscene]", ...message);
312
- }
313
- }
314
- var lastReportedRepoUrl = "";
315
- function uploadTestInfoToServer({ testUrl }) {
316
- let repoUrl = "";
317
- let userEmail = "";
318
- const extraConfig = getAIConfigInJson(MIDSCENE_OPENAI_INIT_CONFIG_JSON);
319
- const serverUrl = extraConfig == null ? void 0 : extraConfig.REPORT_SERVER_URL;
320
- try {
321
- repoUrl = (0, import_node_child_process.execSync)("git config --get remote.origin.url").toString().trim();
322
- userEmail = (0, import_node_child_process.execSync)("git config --get user.email").toString().trim();
323
- } catch (error) {
324
- debugLog("Failed to get git info:", error);
325
- }
326
- if (serverUrl && (repoUrl && repoUrl !== lastReportedRepoUrl || !repoUrl && testUrl)) {
327
- debugLog("Uploading test info to server", {
328
- serverUrl,
329
- repoUrl,
330
- testUrl,
331
- userEmail
332
- });
333
- fetch(serverUrl, {
334
- method: "POST",
335
- headers: {
336
- "Content-Type": "application/json"
337
- },
338
- body: JSON.stringify({
339
- repo_url: repoUrl,
340
- test_url: testUrl,
341
- user_email: userEmail
342
- })
343
- }).then((response) => response.json()).then((data) => {
344
- debugLog("Successfully uploaded test info to server:", data);
345
- }).catch(
346
- (error) => debugLog("Failed to upload test info to server:", error)
347
- );
348
- lastReportedRepoUrl = repoUrl;
349
- }
350
- }
351
- // Annotate the CommonJS export names for ESM import in node:
352
- 0 && (module.exports = {
353
- getLogDir,
354
- getLogDirByType,
355
- getTmpDir,
356
- getTmpFile,
357
- getVersion,
358
- groupedActionDumpFileExt,
359
- insightDumpFileExt,
360
- overlapped,
361
- replaceStringWithFirstAppearance,
362
- replacerForPageObject,
363
- reportHTMLContent,
364
- setLogDir,
365
- sleep,
366
- stringifyDumpData,
367
- uploadTestInfoToServer,
368
- writeDumpReport,
369
- writeLogFile
370
- });
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+ var _chunkZRCWDGK2js = require('./chunk-ZRCWDGK2.js');
20
+ require('./chunk-SCNIHQKF.js');
21
+ require('./chunk-G7A32JAG.js');
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+
37
+
38
+
39
+
40
+ exports.getLogDir = _chunkZRCWDGK2js.getLogDir; exports.getLogDirByType = _chunkZRCWDGK2js.getLogDirByType; exports.getTmpDir = _chunkZRCWDGK2js.getTmpDir; exports.getTmpFile = _chunkZRCWDGK2js.getTmpFile; exports.getVersion = _chunkZRCWDGK2js.getVersion; exports.groupedActionDumpFileExt = _chunkZRCWDGK2js.groupedActionDumpFileExt; exports.insightDumpFileExt = _chunkZRCWDGK2js.insightDumpFileExt; exports.overlapped = _chunkZRCWDGK2js.overlapped; exports.replaceStringWithFirstAppearance = _chunkZRCWDGK2js.replaceStringWithFirstAppearance; exports.replacerForPageObject = _chunkZRCWDGK2js.replacerForPageObject; exports.reportHTMLContent = _chunkZRCWDGK2js.reportHTMLContent; exports.setLogDir = _chunkZRCWDGK2js.setLogDir; exports.sleep = _chunkZRCWDGK2js.sleep; exports.stringifyDumpData = _chunkZRCWDGK2js.stringifyDumpData; exports.uploadTestInfoToServer = _chunkZRCWDGK2js.uploadTestInfoToServer; exports.writeDumpReport = _chunkZRCWDGK2js.writeDumpReport; exports.writeLogFile = _chunkZRCWDGK2js.writeLogFile;